local-operator-ui 0.36.4 → 0.36.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/out/main/index.js +438 -143
  2. package/out/preload/index.js +120 -0
  3. package/out/renderer/assets/{_basePickBy-DQ6BzkJm.js → _basePickBy-CxqDmmHv.js} +1 -1
  4. package/out/renderer/assets/{_baseUniq-D4Pzw8OZ.js → _baseUniq-DZ5q-4MO.js} +1 -1
  5. package/out/renderer/assets/{agent-details-page-vUtr6XRL.js → agent-details-page-BBaVqJ-k.js} +2 -2
  6. package/out/renderer/assets/{agent-hub-page-DLfJB8ns.js → agent-hub-page-TSnDpkEN.js} +2 -7
  7. package/out/renderer/assets/{agents-page-B-PHMFxF.js → agents-page-BpAcSHU9.js} +3 -3
  8. package/out/renderer/assets/{arc-BvXLfjiv.js → arc-Cj5oOdNk.js} +1 -1
  9. package/out/renderer/assets/{architectureDiagram-IEHRJDOE-DGO7ixLg.js → architectureDiagram-IEHRJDOE-BLG-Rki4.js} +1 -1
  10. package/out/renderer/assets/{arrow-up-D8Tgt51O.js → arrow-up-B9XooY3R.js} +1 -1
  11. package/out/renderer/assets/{blockDiagram-JOT3LUYC-Bpj3zFYQ.js → blockDiagram-JOT3LUYC-DJkmqNYL.js} +1 -1
  12. package/out/renderer/assets/{book-open-DeWHPw1t.js → book-open-CSxa_YmK.js} +1 -1
  13. package/out/renderer/assets/browser-page-C9MH7MXX.js +1 -0
  14. package/out/renderer/assets/{browser-webauthn-prompt-CLrsocAn.js → browser-webauthn-prompt-CuaS1ZyY.js} +1 -1
  15. package/out/renderer/assets/building-2-BgiPDMo-.js +6 -0
  16. package/out/renderer/assets/{c4Diagram-VJAJSXHY-tA5p19nS.js → c4Diagram-VJAJSXHY-sgmFcnZ9.js} +1 -1
  17. package/out/renderer/assets/channel-Ccp6y6yN.js +1 -0
  18. package/out/renderer/assets/{chunk-4BMEZGHF-CAtpoCnM.js → chunk-4BMEZGHF-BBWXJqFy.js} +1 -1
  19. package/out/renderer/assets/{chunk-A2AXSNBT-CYHy7Mvk.js → chunk-A2AXSNBT-q8UkjaB1.js} +1 -1
  20. package/out/renderer/assets/{chunk-AEK57VVT-B2bXanTe.js → chunk-AEK57VVT-qKzkVDpt.js} +1 -1
  21. package/out/renderer/assets/{chunk-D6G4REZN-DfhdrNKB.js → chunk-D6G4REZN-Cnve3iPN.js} +1 -1
  22. package/out/renderer/assets/{chunk-RZ5BOZE2-BNdcLGHR.js → chunk-RZ5BOZE2-CXlNa1ns.js} +1 -1
  23. package/out/renderer/assets/{chunk-XZIHB7SX-Caa_mRlB.js → chunk-XZIHB7SX-CH_n0WpC.js} +1 -1
  24. package/out/renderer/assets/classDiagram-GIVACNV2-DWJzEShu.js +1 -0
  25. package/out/renderer/assets/classDiagram-v2-COTLJTTW-DWJzEShu.js +1 -0
  26. package/out/renderer/assets/clone-PErpKu4z.js +1 -0
  27. package/out/renderer/assets/{console-mirror-BnHVC7eO.js → console-mirror-Cb5yLix0.js} +1 -1
  28. package/out/renderer/assets/{consoleCapture-BxykZlLx.js → consoleCapture-DTUn8btA.js} +1 -1
  29. package/out/renderer/assets/{conversation-input-sync-CJiOSzCX.js → conversation-input-sync-BWiC2ZNQ.js} +6 -6
  30. package/out/renderer/assets/{dagre-OKDRZEBW-pq4RiyaY.js → dagre-OKDRZEBW-CcLBj9dR.js} +1 -1
  31. package/out/renderer/assets/{diagram-SSKATNLV-DnlzCGD2.js → diagram-SSKATNLV-BnBuzUHq.js} +1 -1
  32. package/out/renderer/assets/{diagram-VNBRO52H-DbJ2RTVe.js → diagram-VNBRO52H-B4nIkHdB.js} +1 -1
  33. package/out/renderer/assets/{erDiagram-Q7BY3M3F-C56WVcbc.js → erDiagram-Q7BY3M3F-D5sW3c1J.js} +1 -1
  34. package/out/renderer/assets/{error-boundary-Tv9TlaZ8.js → error-boundary-DxVWsYpy.js} +2 -2
  35. package/out/renderer/assets/{flowDiagram-4HSFHLVR-CL1GRaaq.js → flowDiagram-4HSFHLVR-q9AjGiBl.js} +1 -1
  36. package/out/renderer/assets/{ganttDiagram-APWFNJXF-CES2U6dP.js → ganttDiagram-APWFNJXF-y0u1sOsY.js} +4 -4
  37. package/out/renderer/assets/{gitGraphDiagram-7IBYFJ6S-CRyPEqXz.js → gitGraphDiagram-7IBYFJ6S-Av-mS9kO.js} +1 -1
  38. package/out/renderer/assets/{graph-Dtsej9jG.js → graph-D0BldG7q.js} +1 -1
  39. package/out/renderer/assets/hash-yZIrwUE4.js +6 -0
  40. package/out/renderer/assets/{index-BsV4LVu3.js → index-C6Pn32aB.js} +1 -1
  41. package/out/renderer/assets/index-CjToIHDL.js +57 -0
  42. package/out/renderer/assets/index-Ctcid6gL.css +1 -0
  43. package/out/renderer/assets/{index-DAoplO_Z.js → index-FVvzpk9i.js} +1 -1
  44. package/out/renderer/assets/{index-D0l2JJ6w.js → index-lLn4-su7.js} +208 -208
  45. package/out/renderer/assets/{infoDiagram-PH2N3AL5-BwRaN2ZH.js → infoDiagram-PH2N3AL5-CLYc4y61.js} +1 -1
  46. package/out/renderer/assets/{installer-DjflOef5.js → installer-D3I6JJnd.js} +1 -1
  47. package/out/renderer/assets/{journeyDiagram-U35MCT3I-CwrSuzth.js → journeyDiagram-U35MCT3I-o0YPT9KT.js} +1 -1
  48. package/out/renderer/assets/{kanban-definition-NDS4AKOZ-CjW130n-.js → kanban-definition-NDS4AKOZ-B1WRSBgd.js} +1 -1
  49. package/out/renderer/assets/{layout-DnBx2qbk.js → layout-6qCmOzEc.js} +1 -1
  50. package/out/renderer/assets/{legacy-agents-page-BiAHAYWZ.js → legacy-agents-page-DlYBCvv7.js} +6 -6
  51. package/out/renderer/assets/library-page-CjhrFVEo.js +157 -0
  52. package/out/renderer/assets/{mermaid.core-BHqZ2SZO.js → mermaid.core-DePJ3QoR.js} +5 -5
  53. package/out/renderer/assets/mesh-page-BSJFgFCr.js +1 -0
  54. package/out/renderer/assets/{mindmap-definition-ALO5MXBD-Ca2VY79V.js → mindmap-definition-ALO5MXBD-BgpnkVkf.js} +1 -1
  55. package/out/renderer/assets/{mini-Dd3N58po.js → mini-Csq--Wlq.js} +1 -1
  56. package/out/renderer/assets/{notebook-pen-CcH01r1l.js → notebook-pen-Bt8ewXE9.js} +1 -1
  57. package/out/renderer/assets/{org-access-WIuI99P6.js → org-access-BzNFiBDx.js} +1 -1
  58. package/out/renderer/assets/{org-surface-gate-BsP8aWCi.js → org-surface-gate-CIJNYTYB.js} +1 -1
  59. package/out/renderer/assets/{page-header-ggruiR-O.js → page-header-DM0jhCF2.js} +1 -1
  60. package/out/renderer/assets/{pieDiagram-IB7DONF6-C7lP9J7V.js → pieDiagram-IB7DONF6-WDOJ33Hk.js} +1 -1
  61. package/out/renderer/assets/{projects-page-BIRVv4yi.js → projects-page-CcNU6_X8.js} +6 -6
  62. package/out/renderer/assets/publication-validation-BcIDRO_Q.js +1 -0
  63. package/out/renderer/assets/{quadrantDiagram-7GDLP6J5-CPMEK8EO.js → quadrantDiagram-7GDLP6J5-qxT7WPZD.js} +1 -1
  64. package/out/renderer/assets/{radar-MK3ICKWK-sbfBaJo0.js → radar-MK3ICKWK-xGtvrCw2.js} +1 -1
  65. package/out/renderer/assets/{radient-auth-buttons-C0ljZy4O.js → radient-auth-buttons-D9Y-bems.js} +1 -1
  66. package/out/renderer/assets/{requirementDiagram-KVF5MWMF-S2rhrmTH.js → requirementDiagram-KVF5MWMF-CX_IrGLA.js} +1 -1
  67. package/out/renderer/assets/{sankeyDiagram-QLVOVGJD-sNpc3Wfn.js → sankeyDiagram-QLVOVGJD-DV1ZdXxS.js} +1 -1
  68. package/out/renderer/assets/{schedules-page-DbZSRb3g.js → schedules-page-Ce0-woL0.js} +1 -1
  69. package/out/renderer/assets/{sequenceDiagram-X6HHIX6F-Cv-47OeQ.js → sequenceDiagram-X6HHIX6F-DKqwb67S.js} +1 -1
  70. package/out/renderer/assets/{settings-page-DH9sXfEW.js → settings-page-JTZ4QBJW.js} +8 -8
  71. package/out/renderer/assets/smartart-BNasG3UO.js +1 -0
  72. package/out/renderer/assets/{stateDiagram-DGXRK772-DIBWf8qm.js → stateDiagram-DGXRK772-B7kjPArX.js} +1 -1
  73. package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-BAZmozFm.js +1 -0
  74. package/out/renderer/assets/{tags-input-chips-B4_gHGYO.js → tags-input-chips-Cv0lsEDt.js} +1 -1
  75. package/out/renderer/assets/team-bridge-page-XaIwS8Qz.js +1 -0
  76. package/out/renderer/assets/{timeline-definition-BDJGKUSR-CE8q2f33.js → timeline-definition-BDJGKUSR-84zVvGlx.js} +1 -1
  77. package/out/renderer/assets/ui-preferences-store-D0NZNchc.js +1 -0
  78. package/out/renderer/assets/{use-download-agent-mutation-LdjExo2g.js → use-download-agent-mutation-DeuSzNhw.js} +4 -4
  79. package/out/renderer/assets/{use-memberships-query-DcD9UeVY.js → use-memberships-query-yUmGp-Y1.js} +1 -1
  80. package/out/renderer/assets/{use-session-snapshot-Cqye2iDz.js → use-session-snapshot-D70s2vL7.js} +1 -1
  81. package/out/renderer/assets/{xychartDiagram-VJFVF3MP-DlbgdRgT.js → xychartDiagram-VJFVF3MP-BhpruKGF.js} +1 -1
  82. package/out/renderer/console-capture.html +5 -5
  83. package/out/renderer/index.html +7 -7
  84. package/out/renderer/installer.html +4 -4
  85. package/out/renderer/mini.html +7 -7
  86. package/package.json +2 -2
  87. package/out/renderer/assets/browser-page-DAQis2Rt.js +0 -1
  88. package/out/renderer/assets/channel-CG3c-hsB.js +0 -1
  89. package/out/renderer/assets/classDiagram-GIVACNV2-BGWu-T14.js +0 -1
  90. package/out/renderer/assets/classDiagram-v2-COTLJTTW-BGWu-T14.js +0 -1
  91. package/out/renderer/assets/clone-UwOnPjS7.js +0 -1
  92. package/out/renderer/assets/index-hX_aZwq0.js +0 -57
  93. package/out/renderer/assets/index-vPvXCaIy.css +0 -1
  94. package/out/renderer/assets/library-page-BGmng_P-.js +0 -162
  95. package/out/renderer/assets/mesh-page-1yPLxWRO.js +0 -1
  96. package/out/renderer/assets/publication-validation-C73bqNja.js +0 -1
  97. package/out/renderer/assets/smartart-C2eRO4WK.js +0 -1
  98. package/out/renderer/assets/stateDiagram-v2-YXO3MK2T-DBPLNjJl.js +0 -1
  99. package/out/renderer/assets/ui-preferences-store-C6eXGzFs.js +0 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-BsV4LVu3.js","./index-hX_aZwq0.js","./index-vPvXCaIy.css","./ui-preferences-store-C6eXGzFs.js","./error-boundary-Tv9TlaZ8.js","./index-DAoplO_Z.js","./pug-DukmZTjD.js","./javascript-qCveANmP.js","./mermaid.core-BHqZ2SZO.js","./katex-BCx1q_2Y.css"])))=>i.map(i=>d[i]);
2
- import{r as $,b as ee,j as h,i as mRe,c as q,g as er,t as J,B as Bse,k as ov,L as qd,d as dA,C as Ob,h as yn,e as Wq}from"./index-hX_aZwq0.js";import{aR as xp,aS as FQ,aT as Hse,aU as Kse,aV as y$,B as lf,aW as gRe,aX as BQ,aY as $Re,L as Jse,aZ as fA,a_ as yRe,C as hA,a$ as vRe,b0 as bRe,e as ta,g as lc,R as Rm,F as ele,E as pA,b1 as zu,b2 as wRe,u as Jn,b3 as SRe,b4 as xRe,b5 as QRe,b6 as kRe,b7 as UN,b8 as PRe,ay as _Re,aG as TRe,b9 as RRe,aM as XRe,ba as ERe,bb as qRe,aA as WN,aB as jRe,bc as HQ,bd as Qp,be as CRe,bf as NN,bg as ARe,bh as zRe,bi as tle,bj as YN,M as nle,bk as rle,bl as URe,bm as WRe,bn as NRe,bo as YRe,aO as mA,bp as GRe,D as IRe,s as GN,bq as W_,z as ZRe,br as DRe,y as ile,bs as Nq}from"./ui-preferences-store-C6eXGzFs.js";import{ag as MRe,c as Ie,a as Xe,as as gA,D as $A,b as yA,d as VRe,e as vA,g as LRe,m as Yt,y as oS,z as ale,T as cf,B as Md,h as xu,X as ea,u as br,ah as Yq,a9 as FRe,aa as BRe,aH as HRe,A as Ll,S as Go,q as ole,r as bA,s as wA,t as SA,x as jl,n as E0,o as q0,aG as xA,p as kp,aK as KRe,a1 as JRe,a2 as eXe,a3 as tXe,a8 as nXe,a0 as KQ,N as rXe,Y as iXe,Z as aXe,_ as oXe,I as ao,F as sle,G as lle,H as cle,J as ule,K as Gq,M as sXe,f as Iq,L as Ole,C as lXe,l as _o,P as cXe,Q as uXe,R as IN,U as ZN,V as OXe,W as DN,at as dXe,aL as fXe,i as hXe,v as N_,w as MN,E as VN}from"./error-boundary-Tv9TlaZ8.js";const pXe="superseded_completion_token",mXe="store_busy",gXe="session_is_remote",$Xe="owner_build_behind";function yXe(e,t,n){if(!e||typeof e!="object")return!1;const r=e;return r.unseen===!1&&r.conversation_id===`session/${t}`&&r.completion_token===n}function jd(e,t,n){return!t||t.conversation_id!==`session/${n}`||!Array.isArray(t.revision)||t.revision.length!==2||!t.revision.every(r=>Number.isSafeInteger(r)&&r>=0)||e?.conversation_id===t.conversation_id&&(t.revision[0]<e.revision[0]||t.revision[1]<e.revision[1])?e:t.supported===void 0&&e?.supported!==void 0?{...t,supported:e.supported}:t}function dle(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.round(t*1e3):null}const fle=e=>typeof e?.goal_status=="string",hle=e=>(e?.goal??"").trim().length>0;function vXe(e,t,n){return n.session_id!==t||n.payload.frontend.snapshot.session_id!==t||!e?!1:e.epoch===n.epoch&&n.seq>e.seq}const j0={notPaired:"This backend was not started with desktop controls.",serverDown:"The Local Operator server is not answering.",frameBudget:"The event stream exceeded its frame budget.",ended:"The event stream ended."},LN={statement:"Lost the connection to this conversation — reconnect to keep reading.",action:"reconnect"},bXe={statement:"The Local Operator server is not running — reconnect once it is back, or restart the app if it stays down.",action:"reconnect"},wXe={statement:"This app is not paired with the Local Operator server, so this conversation cannot be read yet.",action:null},SXe={statement:"Could not load this conversation's history — reconnect to try again.",action:"reconnect"},xXe={statement:"This conversation's updates were too large to display — reconnect to try again.",action:"reconnect"};function FN(e){return e?e===j0.notPaired?wXe:e===j0.serverDown?bXe:e===j0.frameBudget?xXe:LN:LN}async function QA(e){if(window.api?.desktop)try{return await QXe(window.api.desktop.request(e),e)}catch(n){throw n instanceof Ut?n:XXe(n)?new ou(Hse,Kse):new Ut(null,"Desktop controls could not reach the backend process.",n)}let t;try{t=await fetch("/__desktop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(n){throw new Ut(null,"Desktop controls could not reach the backend process.",n)}if(!t.ok)throw new Ut(t.status,"Desktop controls need a compatible backend connection.");return t.json()}function QXe(e,t){const n=fA(t);let r;return Promise.race([e,new Promise((i,a)=>{r=setTimeout(()=>{const o=yRe(t.op,n);a(new Ut(null,o.message,void 0,o.code))},n)})]).finally(()=>clearTimeout(r))}const ple="This server did not answer the request for its desktop controls.";class Ut extends Error{status;cause;code;retryAfterMs;detail;constructor(t,n,r,i,a,o){super(n),this.name="DesktopControlError",this.status=t,this.cause=r,this.code=i,this.retryAfterMs=a,this.detail=o}}class ou extends Error{code;constructor(t,n){super(t),this.name="UserFacingError",this.code=n}}function Io(e,t){return e instanceof Ut||e instanceof ou?xp(e.code)?FQ[e.code]:e.message:t}function kXe(e,t,n,r){return typeof r=="string"?r:n===y$.noCredential?lf.noCredential:n===y$.transportFailed?lf.transportFailed:gRe(BQ(e).path,t)}async function Re(e){const t=await QA(e),n=t.body;if(t.status<200||t.status>=300){const r=typeof n?.detail=="string"?n.detail:typeof n?.detail?.text=="string"?n.detail.text:typeof n?.detail?.message=="string"?n.detail.message:null;throw new Ut(t.status,r??ple,void 0,kXe(e,t.status,r,typeof n?.detail=="object"?n.detail?.code:void 0),typeof n?.detail=="object"&&typeof n.detail?.retry_after_ms=="number"&&Number.isFinite(n.detail.retry_after_ms)?n.detail.retry_after_ms:void 0,typeof n?.detail=="object"?n.detail:void 0)}return e.op==="sessions.list"&&PXe(n?.result),n?.result}function PXe(e){if(typeof e!="object"||e===null)return;const t=$Re(e.delegated_cleanup_notice);t&&Jse.getState().receive(t)}async function _Xe(){try{await Re({op:"delegated_cleanup_notice.ack"})}catch{}}async function dln(){Jse.getState().dismiss(),await _Xe()}function mle(e){return e instanceof Ut&&e.code===hA}function TXe(e){if(!(e instanceof Ut))return!1;const t=e.detail?.cause;return typeof t=="string"&&t.length>0?t===$Xe:e.code===gXe}function RXe(e){return e instanceof ou&&e.code===Kse}function XXe(e){return e instanceof Error&&e.message.includes(Hse)}async function jn(e){const t=await QA(e);return new Response(t.status===204?null:JSON.stringify(t.body),{status:t.status,headers:{"Content-Type":"application/json"}})}async function EXe(e,t=!1){if(window.api?.desktop)return window.api.desktop.openAuthorization(e,t);const n=await Re({op:"auth.status",id:e});if(!n.auth_url)throw new Error("This sign-in is no longer waiting for a browser.");const r=new URL(n.auth_url);if(r.username||r.password||r.protocol!=="https:"&&!(r.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(r.hostname)))throw new Error("The provider returned an invalid sign-in address.");window.open(r.href,"_blank","noopener,noreferrer")}function qXe(e,t){const n=window.api?.desktop?.stream;if(n){const a=n.subscribe(e,t);return()=>a.dispose()}const r=new URLSearchParams({session:e.sessionId});e.epoch&&r.set("epoch",e.epoch),e.afterSeq!==void 0&&r.set("after_seq",String(e.afterSeq)),r.set("frontend_replace","1"),e.openFrame===!0&&r.set("open_frame","1"),e.journalOrder===!0&&(r.set("journal_order","1"),e.peerJournalSource===!0&&r.set("peer_journal_source","1"),vRe(r,"/__desktop/stream",e.orderIds??[]));const i=new EventSource(`/__desktop/stream?${r}`);return i.onmessage=a=>{t({kind:"data",data:a.data})},i.onerror=()=>{i.readyState===EventSource.CLOSED&&(t({kind:"error",detail:j0.ended}),i.close())},()=>{i.close(),t({kind:"end"})}}async function su(e,t){const n=window.api?.desktop?.media;if(n)return n(e,t);const r=await fetch("/__desktop/media",{method:"POST",headers:{"x-desktop-media":JSON.stringify(e),"Content-Type":"application/octet-stream"},body:t?new Blob([t]):void 0}),i=r.headers.get("content-type")??"";if(!r.ok){let a="The media request failed.",o;if(i.includes("application/json"))try{const l=(await r.json())?.detail;if(typeof l=="string")a=l;else if(typeof l=="object"&&l!==null){const c=l;typeof c.text=="string"&&c.text.trim()?a=c.text:typeof c.message=="string"&&c.message.trim()&&(a=c.message),typeof c.code=="string"&&(o=c.code)}}catch{}return{status:r.status,kind:"error",detail:a,code:o!==void 0&&xp(o)?o:a===y$.noCredential?lf.noCredential:void 0}}return i.includes("application/json")?{status:r.status,kind:"json",body:await r.json()}:{status:r.status,kind:"bytes",mimeType:i||"application/octet-stream",data:new Uint8Array(await r.arrayBuffer())}}function v$(e){return e.kind==="error"?xp(e.code)?new ou(FQ[e.code],e.code):new Error(e.detail):new Error("The media request returned an unexpected response.")}const Zq=e=>({revision:es(e),demand:e.orderDemand}),Vd=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Pp(e,t,n,r,i,a={}){let o=e;const s=t.journal_generation;if(t.reconcile===!0){const d=typeof s=="string"&&s.length>0?s:void 0;return o.orderNeedsReconcile&&o.orderWantedGeneration===d?o.journalMode?o:{...o,journalMode:!0}:{...o,journalMode:!0,orderNeedsReconcile:!0,orderWantedGeneration:d,orderDemand:d!==void 0?{generation:d}:{}}}if(typeof s!="string"||s.length===0)return t.journal_order_state&&t.journal_order_state!=="unsupported"&&!o.journalMode?{...o,journalMode:!0}:o;if(r&&t.journal_order_state==="ready"&&i&&o.orderNeedsReconcile&&o.orderDemand===i.demand&&(o={...o,orderNeedsReconcile:!1,orderWantedGeneration:void 0,orderDemand:void 0}),s!==o.journalGeneration&&!r)return o.orderNeedsReconcile&&o.orderWantedGeneration===s?o:{...o,orderNeedsReconcile:!0,orderWantedGeneration:s,orderDemand:{generation:s}};let l=o.journalMode?o:{...o,journalMode:!0};if(s!==o.journalGeneration&&(l={...o,journalMode:!0,journalGeneration:s,orderRevision:(o.orderRevision??0)+1,journalPositions:new Map,orderNeedsReconcile:o.orderNeedsReconcile,orderWantedGeneration:o.orderWantedGeneration,orderDemand:o.orderDemand},a.peer===!0)){const d=(o.orderRevision??0)+1,f=new Map;for(const p of o.records){const m=p.sourceEntryId??(p.kind==="tool"||p.kind==="supplement"?null:p.id);typeof m=="string"&&m.length>0&&m.length<=128&&f.set(m,d)}l={...l,...f.size>0?{journalBodyOwed:f}:{},journalSourceVoid:void 0}}let c=l.journalPositions??new Map;const u=c,O=(d,f,p)=>{if(!Vd(p))return;const m=c.get(d);m&&m.seq>=p||(c===u&&(c=new Map(c)),c.set(d,{entryId:f,seq:p}))};for(const[d,f]of Object.entries(t.journal_ordinals??{}))O(d,d,f);for(const d of n)typeof d.id=="string"&&(O(d.id,d.id,d.journal_seq),d.role==="tool"&&typeof d.tool_call_id=="string"&&O(`tool:${d.tool_call_id}`,d.id,d.journal_seq),typeof d.anchor=="string"&&O(`supplement:${d.anchor}`,d.id,d.journal_seq));return c!==u&&(l={...l,journalPositions:c}),l}function kA(e,t){if(!e.journalMode||typeof t.id!="string"||!Array.isArray(t.tool_calls))return e;let n=e.journalCallOwners??new Map,r=e.journalCallSlots??new Map;const i=n,a=r;return t.tool_calls.forEach((o,s)=>{!o||typeof o.id!="string"||(n.get(o.id)!==t.id&&(n===i&&(n=new Map(n)),n.set(o.id,t.id)),r.get(o.id)!==s&&(r===a&&(r=new Map(r)),r.set(o.id,s)))}),n===i&&r===a?e:{...e,journalCallOwners:n,journalCallSlots:r}}function gle(e,t){const n=new Set(e.map(a=>a.id));let r=!1,i;for(let a=0;a<e.length;a++){const o=e[a];if(o.kind==="user"&&o.provisional===!0){i=o;continue}!t(o)&&i&&(o.sourceAdmissionAnchor===void 0||!n.has(o.sourceAdmissionAnchor))&&(e[a]={...o,sourceAdmissionAnchor:i.id},r=!0),i=e[a]}return r}function $le(e,t,n,r,i){const a=[],o=new Set;let s=e,l;for(;s!==void 0;){if(i.has(s.id)){l=i.get(s.id);break}if(n(s)){l=r(s);break}if(s.kind==="user"&&s.provisional===!0||o.has(s.id))break;o.add(s.id),a.push(s.id),s=s.sourceAdmissionAnchor?t.get(s.sourceAdmissionAnchor):void 0}for(const c of a)i.set(c,l);return l}function yle(e,t){const n=new Map;return r=>{if(!r)return;const i=t(r);if(i===void 0)return;const a=[],o=new Set;let s=r,l=!0;for(;s;){if(n.has(s.id)){l=n.get(s.id)===!0;break}if(o.has(s.id)||t(s)===void 0){l=!1;break}o.add(s.id),a.push(s.id),s=s.sourceAdmissionAnchor===void 0?void 0:e.get(s.sourceAdmissionAnchor)}for(const c of a)n.set(c,l);return l?i:void 0}}function sS(e,t){const n=e.journalCallOwners,r=e.journalCallSlots;if(!n||!r)return t;const i=new Map;t.forEach((o,s)=>{if(o.kind!=="tool")return;const l=n.get(o.toolCallId);if(l===void 0||!r.has(o.toolCallId))return;const c=i.get(l);c?c.push(s):i.set(l,[s])});let a=t;for(const o of i.values()){if(o.length<2)continue;const s=o.map(l=>t[l]).sort((l,c)=>(r.get(l.toolCallId)??0)-(r.get(c.toolCallId)??0));s.every((l,c)=>l===t[o[c]])||(a===t&&(a=t.slice()),o.forEach((l,c)=>{a[l]=s[c]}))}return a}function vle(e,t){if(!e.journalMode)return t;if(e.journalPeerSource===!0)return jXe(e,t);const n=e.journalGeneration,r=e.journalPositions;let i=!1;const a=t.map(f=>{let m=[r?.get(f.sourceEntryId??f.id),r?.get(f.id)].filter(v=>v!==void 0).sort((v,S)=>S.seq-v.seq)[0];if(f.journalGeneration===n&&Vd(f.journalSeq)&&(!m||f.journalSeq>m.seq)&&(m={entryId:f.sourceEntryId??f.id,seq:f.journalSeq}),!m||!n||!(f.kind==="user"&&(f.provisional===!0||f.local===!0))&&f.sourceEntryId===m.entryId&&f.journalSeq===m.seq&&f.journalGeneration===n)return f;i=!0;let y={...f,sourceEntryId:m.entryId,journalSeq:m.seq,journalGeneration:n};if(y.kind==="user"){const{provisional:v,local:S,...Q}=y;y=Q}return y});gle(a,f=>f.journalGeneration===n&&Vd(f.journalSeq))&&(i=!0);const s=new Map,l=new Map(a.map(f=>[f.id,f])),c=yle(l,f=>f!==void 0&&f.journalGeneration===n&&Vd(f.journalSeq)?f.journalSeq:void 0),u=f=>c(f)!==void 0,O=(f,p)=>{const m=c(f);if(f.kind==="user"&&f.provisional===!0&&m===void 0)return[1,0,0,0,p];const g=f.kind==="supplement"?f.anchor:f.kind==="tool"?e.journalCallOwners?.get(f.toolCallId)??e.argsByCall.get(f.toolCallId)?.anchorId:void 0,y=typeof g=="string"?c(l.get(g)):void 0,v=m===void 0?$le(f,l,u,c,s):void 0,S=y??m??v;return S===void 0?[1,0,0,0,p]:[0,S,y!==void 0?1:m!==void 0?0:2,m??Number.MAX_SAFE_INTEGER,p]},d=a.map((f,p)=>({record:f,index:p,rank:O(f,p)}));return d.sort((f,p)=>{for(let m=0;m<f.rank.length;m++){const g=f.rank[m]-p.rank[m];if(g)return g}return 0}),!i&&d.every((f,p)=>f.index===p)?sS(e,t):sS(e,d.map(f=>f.record))}function jXe(e,t){const n=e.journalGeneration,r=e.journalPositions,i=new Map;for(const m of t){let y=[r?.get(m.sourceEntryId??m.id),r?.get(m.id)].filter(v=>v!==void 0).sort((v,S)=>S.seq-v.seq)[0];m.journalGeneration===n&&Vd(m.journalSeq)&&(!y||m.journalSeq>y.seq)&&(y={entryId:m.sourceEntryId??m.id,seq:m.journalSeq}),y&&i.set(m.id,y)}const a=m=>m===void 0?void 0:i.get(m.id)??r?.get(m.sourceEntryId??m.id)??r?.get(m.id);let o=!1;const s=t.slice();gle(s,m=>m.journalGeneration===n&&Vd(m.journalSeq))&&(o=!0);const c=new Map,u=new Map(s.map(m=>[m.id,m])),O=yle(u,m=>a(m)?.seq),d=m=>O(m)!==void 0,f=(m,g)=>{const y=O(m);if(m.kind==="user"&&m.provisional===!0&&y===void 0)return[1,0,0,0,g];const v=m.kind==="supplement"?m.anchor:m.kind==="tool"?e.journalCallOwners?.get(m.toolCallId)??e.argsByCall.get(m.toolCallId)?.anchorId:void 0,S=typeof v=="string"?O(u.get(v)):void 0,Q=y===void 0?$le(m,u,d,O,c):void 0,b=S??y??Q;return b===void 0?[1,0,0,0,g]:[0,b,S!==void 0?1:y!==void 0?0:2,y??Number.MAX_SAFE_INTEGER,g]},p=s.map((m,g)=>({record:m,index:g,rank:f(m,g)}));return p.sort((m,g)=>{for(let y=0;y<m.rank.length;y++){const v=m.rank[y]-g.rank[y];if(v)return v}return 0}),!o&&p.every((m,g)=>m.index===g)?sS(e,t):sS(e,p.map(m=>m.record))}function kl(e){const t=e.records.filter(i=>i.kind==="user"&&i.provisional===!0),n=e.records.filter(i=>i.journalGeneration!==e.journalGeneration||!Vd(i.journalSeq)),r=[...t,...n].map(i=>i.sourceEntryId??(i.kind==="tool"||i.kind==="supplement"?null:i.id));if(r.push(...PA(e)),e.journalPositions?.has(e.oldestId??"")||r.push(e.oldestId),e.journalSourceVoid?.size)for(let i=r.length-1;i>=0;i--){const a=r[i];typeof a=="string"&&e.journalSourceVoid.has(a)&&r.splice(i,1)}return[...new Set(r.filter(i=>typeof i=="string"&&i.length>0&&i.length<=128))]}function PA(e){if(e.journalPeerSource!==!0||!e.journalBodyOwed)return[];const t=new Set;for(const r of e.records){const i=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof i=="string"&&i.length>0&&i.length<=128&&t.add(i)}const n=[];for(const r of e.journalBodyOwed.keys())r.length<1||r.length>128||t.has(r)&&(e.journalSourceVoid?.has(r)||n.push(r));return n}function ble(e,t){const n=e.journalPositions;return kl(e).filter(r=>!n?.has(r)&&!t?.has(r))}const es=e=>e.orderRevision??0;async function CXe(e){const t=new Map,n=s=>{let l=t.get(s);return l||(l=new Set,t.set(s,l)),l},r=(s,l)=>l==="payload"?PA(s):l==="lookup"?ble(s):kl(s);let i=e.getTranscript().journalGeneration,a=0,o=0;for(;;){if(!e.isCurrent())return{kind:"stale"};const s=e.getTranscript(),l=Zq(s),c=l.revision,u=e.sweep?.(s,n);if(u?.kind==="none")return{kind:"complete",transcript:s};const O=u?.kind??"authority",d=bRe(r(s,O).filter(g=>!n(O).has(g)),u?.path??e.lookupPath,u?.query??new URLSearchParams({journal_order:"1"})),f=await e.read(d,O);if(!e.isCurrent()||es(e.getTranscript())!==c)return{kind:"stale"};if(e.commit(f,c,l),!e.isCurrent())return{kind:"stale"};const p=e.getTranscript(),m=e.page(f);if(m.journal_order_state==="ready"&&m.journal_generation===p.journalGeneration){m.journal_generation!==i&&(t.clear(),i=m.journal_generation);for(const v of d)n(O).add(v);if(p.orderNeedsReconcile){if(p.orderDemand===l.demand||a===1)return{kind:"waiting"};a++,t.clear();continue}if(O==="payload"){const v=(m.source_retry_ids??[]).filter(S=>typeof S=="string"&&S.length>0&&S.length<=128);if(v.length>0&&d.length>1&&o===0){o++;for(const S of v)n("payload").delete(S);continue}}const g=e.sweep?.(p,n);if(g?.kind==="none")return{kind:"complete",transcript:p};const y=g?.kind??"authority";if(r(p,y).some(v=>!n(y).has(v)))continue;return{kind:"complete",transcript:p}}if(!p.orderNeedsReconcile||p.orderDemand===l.demand||a===1)return{kind:"waiting"};a++,t.clear()}}function Vs(e){const t=e.payload,n=t?.tool_call_id;if(t?.role==="tool"&&typeof n=="string"&&n)return`tool:${n}`;const i=(t?.details??{}).anchor;return t?.custom_type==="completion_attention"&&typeof i=="string"&&i?i:e.id}function Y_(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.trunc(e))}function BN(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:e}function fln(e){if(!e||e.runs_state!=="ready")return null;const t=e.runs;if(!t||t.length===0)return null;const n=new Map;for(const a of t){if(!a.settled||typeof a.run_key!="string"||a.run_key.length===0)continue;const o=Y_(a.action_count);if(o===null)continue;const s={actions:o,workedSeconds:BN(a.worked_seconds),failed:Y_(a.failed_count)??0,complete:a.complete!==!1,openingUserId:typeof a.opening_user_id=="string"&&a.opening_user_id.length>0?a.opening_user_id:null,closingAnswerId:typeof a.closing_answer_id=="string"&&a.closing_answer_id.length>0?a.closing_answer_id:null,crossSessionActions:Y_(a.cross_session_action_count),crossSessionWorkedSeconds:BN(a.cross_session_worked_seconds)};n.set(a.run_key,s),s.openingUserId!==null&&n.set(s.openingUserId,s),s.closingAnswerId!==null&&n.set(s.closingAnswerId,s)}if(n.size===0)return null;const r=new Set;for(const a of e.entries)r.add(Vs(a));const i=e.entries[e.entries.length-1];return{runs:n,page:{ids:r,newestKey:i?Vs(i):null}}}function AXe(e){if(!e||e.runs_state!=="ready"||e.head_cut===!0)return null;const t=e.runs,n=e.entries[0];if(!n||!t||t.length===0||!t.find(a=>a.opening_user_id===n.id))return null;const i=Math.round((n.ts??0)*1e3);return i>0?{id:n.id,tsMs:i}:null}function zXe(e,t,n){const r=AXe(e),i=e?.entries;if(r===null||!i||i.length===0)return!1;const a=Math.round((i[i.length-1].ts??0)*1e3);if(!(a>r.tsMs))return!1;for(const[o,s]of t)if(!n.has(o)&&(s===null||!(s>r.tsMs)||!(s<a)))return!1;return!0}const _A=new Set,ba="\\t\\n\\v\\f\\r\\u001C-\\u001F \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000",Zo=new RegExp(`[${ba}]`),JQ=new RegExp(`[${ba}]+`),UXe=new RegExp(`[${ba}]+`,"g"),WXe=new RegExp(`^[${ba}]+|[${ba}]+$`,"g"),NXe=new RegExp(`^[${ba}]+`),YXe=new RegExp(`[^${ba}]`);function on(e){return e.replace(WXe,"")}function lu(e){return e.replace(NXe,"")}function GXe(e,t){return t===0||Zo.test(e[t-1])}function wle(e){const t=[];for(let n=0;n<e.length;n++)e[n]==="/"&&GXe(e,n)&&t.push(n);return t}function ek(e,t){let n=t===null||t>e.length?e.length:t;n<0&&(n=0);const r=e.lastIndexOf(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-C6Pn32aB.js","./index-CjToIHDL.js","./index-Ctcid6gL.css","./ui-preferences-store-D0NZNchc.js","./error-boundary-DxVWsYpy.js","./index-FVvzpk9i.js","./pug-DukmZTjD.js","./javascript-qCveANmP.js","./mermaid.core-DePJ3QoR.js","./katex-BCx1q_2Y.css"])))=>i.map(i=>d[i]);
2
+ import{r as $,b as ee,j as h,i as mRe,c as q,g as er,t as J,B as Bse,k as ov,L as qd,d as dA,C as Ob,h as yn,e as Wq}from"./index-CjToIHDL.js";import{aS as xp,aT as FQ,aU as Hse,aV as Kse,aW as y$,B as lf,aX as gRe,aY as BQ,aZ as $Re,L as Jse,a_ as fA,a$ as yRe,C as hA,b0 as vRe,b1 as bRe,e as ta,g as lc,R as Rm,F as ele,E as pA,aM as zu,b2 as wRe,u as Jn,b3 as SRe,b4 as xRe,b5 as QRe,b6 as kRe,b7 as UN,b8 as PRe,ay as _Re,aG as TRe,b9 as RRe,aN as XRe,ba as ERe,bb as qRe,aA as WN,aB as jRe,bc as HQ,bd as Qp,be as CRe,bf as NN,bg as ARe,bh as zRe,bi as tle,bj as YN,M as nle,bk as rle,bl as URe,bm as WRe,bn as NRe,bo as YRe,aP as mA,bp as GRe,D as IRe,s as GN,bq as W_,z as ZRe,br as DRe,y as ile,bs as Nq}from"./ui-preferences-store-D0NZNchc.js";import{ai as MRe,c as Ie,a as Xe,au as gA,D as $A,b as yA,d as VRe,e as vA,g as LRe,y as Yt,j as oS,J as ale,T as cf,B as Md,s as xu,X as ea,u as br,aj as Yq,ad as FRe,ae as BRe,aI as HRe,A as Ll,S as Go,H as ole,h as bA,i as wA,k as SA,q as jl,z as E0,E as q0,aH as xA,F as kp,aL as KRe,a5 as JRe,a6 as eXe,a7 as tXe,ac as nXe,a4 as KQ,R as rXe,a0 as iXe,a1 as aXe,a2 as oXe,I as ao,K as sle,M as lle,N as cle,O as ule,P as Gq,Q as sXe,f as Iq,L as Ole,C as lXe,x as _o,V as cXe,W as uXe,Y as IN,Z as ZN,_ as OXe,$ as DN,av as dXe,aM as fXe,t as hXe,l as N_,p as MN,G as VN}from"./error-boundary-DxVWsYpy.js";const pXe="superseded_completion_token",mXe="store_busy",gXe="session_is_remote",$Xe="owner_build_behind";function yXe(e,t,n){if(!e||typeof e!="object")return!1;const r=e;return r.unseen===!1&&r.conversation_id===`session/${t}`&&r.completion_token===n}function jd(e,t,n){return!t||t.conversation_id!==`session/${n}`||!Array.isArray(t.revision)||t.revision.length!==2||!t.revision.every(r=>Number.isSafeInteger(r)&&r>=0)||e?.conversation_id===t.conversation_id&&(t.revision[0]<e.revision[0]||t.revision[1]<e.revision[1])?e:t.supported===void 0&&e?.supported!==void 0?{...t,supported:e.supported}:t}function dle(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.round(t*1e3):null}const fle=e=>typeof e?.goal_status=="string",hle=e=>(e?.goal??"").trim().length>0;function vXe(e,t,n){return n.session_id!==t||n.payload.frontend.snapshot.session_id!==t||!e?!1:e.epoch===n.epoch&&n.seq>e.seq}const j0={notPaired:"This backend was not started with desktop controls.",serverDown:"The Local Operator server is not answering.",frameBudget:"The event stream exceeded its frame budget.",ended:"The event stream ended."},LN={statement:"Lost the connection to this conversation — reconnect to keep reading.",action:"reconnect"},bXe={statement:"The Local Operator server is not running — reconnect once it is back, or restart the app if it stays down.",action:"reconnect"},wXe={statement:"This app is not paired with the Local Operator server, so this conversation cannot be read yet.",action:null},SXe={statement:"Could not load this conversation's history — reconnect to try again.",action:"reconnect"},xXe={statement:"This conversation's updates were too large to display — reconnect to try again.",action:"reconnect"};function FN(e){return e?e===j0.notPaired?wXe:e===j0.serverDown?bXe:e===j0.frameBudget?xXe:LN:LN}async function QA(e){if(window.api?.desktop)try{return await QXe(window.api.desktop.request(e),e)}catch(n){throw n instanceof Ut?n:XXe(n)?new ou(Hse,Kse):new Ut(null,"Desktop controls could not reach the backend process.",n)}let t;try{t=await fetch("/__desktop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}catch(n){throw new Ut(null,"Desktop controls could not reach the backend process.",n)}if(!t.ok)throw new Ut(t.status,"Desktop controls need a compatible backend connection.");return t.json()}function QXe(e,t){const n=fA(t);let r;return Promise.race([e,new Promise((i,a)=>{r=setTimeout(()=>{const o=yRe(t.op,n);a(new Ut(null,o.message,void 0,o.code))},n)})]).finally(()=>clearTimeout(r))}const ple="This server did not answer the request for its desktop controls.";class Ut extends Error{status;cause;code;retryAfterMs;detail;constructor(t,n,r,i,a,o){super(n),this.name="DesktopControlError",this.status=t,this.cause=r,this.code=i,this.retryAfterMs=a,this.detail=o}}class ou extends Error{code;constructor(t,n){super(t),this.name="UserFacingError",this.code=n}}function Io(e,t){return e instanceof Ut||e instanceof ou?xp(e.code)?FQ[e.code]:e.message:t}function kXe(e,t,n,r){return typeof r=="string"?r:n===y$.noCredential?lf.noCredential:n===y$.transportFailed?lf.transportFailed:gRe(BQ(e).path,t)}async function Re(e){const t=await QA(e),n=t.body;if(t.status<200||t.status>=300){const r=typeof n?.detail=="string"?n.detail:typeof n?.detail?.text=="string"?n.detail.text:typeof n?.detail?.message=="string"?n.detail.message:null;throw new Ut(t.status,r??ple,void 0,kXe(e,t.status,r,typeof n?.detail=="object"?n.detail?.code:void 0),typeof n?.detail=="object"&&typeof n.detail?.retry_after_ms=="number"&&Number.isFinite(n.detail.retry_after_ms)?n.detail.retry_after_ms:void 0,typeof n?.detail=="object"?n.detail:void 0)}return e.op==="sessions.list"&&PXe(n?.result),n?.result}function PXe(e){if(typeof e!="object"||e===null)return;const t=$Re(e.delegated_cleanup_notice);t&&Jse.getState().receive(t)}async function _Xe(){try{await Re({op:"delegated_cleanup_notice.ack"})}catch{}}async function dln(){Jse.getState().dismiss(),await _Xe()}function mle(e){return e instanceof Ut&&e.code===hA}function TXe(e){if(!(e instanceof Ut))return!1;const t=e.detail?.cause;return typeof t=="string"&&t.length>0?t===$Xe:e.code===gXe}function RXe(e){return e instanceof ou&&e.code===Kse}function XXe(e){return e instanceof Error&&e.message.includes(Hse)}async function jn(e){const t=await QA(e);return new Response(t.status===204?null:JSON.stringify(t.body),{status:t.status,headers:{"Content-Type":"application/json"}})}async function EXe(e,t=!1){if(window.api?.desktop)return window.api.desktop.openAuthorization(e,t);const n=await Re({op:"auth.status",id:e});if(!n.auth_url)throw new Error("This sign-in is no longer waiting for a browser.");const r=new URL(n.auth_url);if(r.username||r.password||r.protocol!=="https:"&&!(r.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(r.hostname)))throw new Error("The provider returned an invalid sign-in address.");window.open(r.href,"_blank","noopener,noreferrer")}function qXe(e,t){const n=window.api?.desktop?.stream;if(n){const a=n.subscribe(e,t);return()=>a.dispose()}const r=new URLSearchParams({session:e.sessionId});e.epoch&&r.set("epoch",e.epoch),e.afterSeq!==void 0&&r.set("after_seq",String(e.afterSeq)),r.set("frontend_replace","1"),e.openFrame===!0&&r.set("open_frame","1"),e.journalOrder===!0&&(r.set("journal_order","1"),e.peerJournalSource===!0&&r.set("peer_journal_source","1"),vRe(r,"/__desktop/stream",e.orderIds??[]));const i=new EventSource(`/__desktop/stream?${r}`);return i.onmessage=a=>{t({kind:"data",data:a.data})},i.onerror=()=>{i.readyState===EventSource.CLOSED&&(t({kind:"error",detail:j0.ended}),i.close())},()=>{i.close(),t({kind:"end"})}}async function su(e,t){const n=window.api?.desktop?.media;if(n)return n(e,t);const r=await fetch("/__desktop/media",{method:"POST",headers:{"x-desktop-media":JSON.stringify(e),"Content-Type":"application/octet-stream"},body:t?new Blob([t]):void 0}),i=r.headers.get("content-type")??"";if(!r.ok){let a="The media request failed.",o;if(i.includes("application/json"))try{const l=(await r.json())?.detail;if(typeof l=="string")a=l;else if(typeof l=="object"&&l!==null){const c=l;typeof c.text=="string"&&c.text.trim()?a=c.text:typeof c.message=="string"&&c.message.trim()&&(a=c.message),typeof c.code=="string"&&(o=c.code)}}catch{}return{status:r.status,kind:"error",detail:a,code:o!==void 0&&xp(o)?o:a===y$.noCredential?lf.noCredential:void 0}}return i.includes("application/json")?{status:r.status,kind:"json",body:await r.json()}:{status:r.status,kind:"bytes",mimeType:i||"application/octet-stream",data:new Uint8Array(await r.arrayBuffer())}}function v$(e){return e.kind==="error"?xp(e.code)?new ou(FQ[e.code],e.code):new Error(e.detail):new Error("The media request returned an unexpected response.")}const Zq=e=>({revision:es(e),demand:e.orderDemand}),Vd=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0;function Pp(e,t,n,r,i,a={}){let o=e;const s=t.journal_generation;if(t.reconcile===!0){const d=typeof s=="string"&&s.length>0?s:void 0;return o.orderNeedsReconcile&&o.orderWantedGeneration===d?o.journalMode?o:{...o,journalMode:!0}:{...o,journalMode:!0,orderNeedsReconcile:!0,orderWantedGeneration:d,orderDemand:d!==void 0?{generation:d}:{}}}if(typeof s!="string"||s.length===0)return t.journal_order_state&&t.journal_order_state!=="unsupported"&&!o.journalMode?{...o,journalMode:!0}:o;if(r&&t.journal_order_state==="ready"&&i&&o.orderNeedsReconcile&&o.orderDemand===i.demand&&(o={...o,orderNeedsReconcile:!1,orderWantedGeneration:void 0,orderDemand:void 0}),s!==o.journalGeneration&&!r)return o.orderNeedsReconcile&&o.orderWantedGeneration===s?o:{...o,orderNeedsReconcile:!0,orderWantedGeneration:s,orderDemand:{generation:s}};let l=o.journalMode?o:{...o,journalMode:!0};if(s!==o.journalGeneration&&(l={...o,journalMode:!0,journalGeneration:s,orderRevision:(o.orderRevision??0)+1,journalPositions:new Map,orderNeedsReconcile:o.orderNeedsReconcile,orderWantedGeneration:o.orderWantedGeneration,orderDemand:o.orderDemand},a.peer===!0)){const d=(o.orderRevision??0)+1,f=new Map;for(const p of o.records){const m=p.sourceEntryId??(p.kind==="tool"||p.kind==="supplement"?null:p.id);typeof m=="string"&&m.length>0&&m.length<=128&&f.set(m,d)}l={...l,...f.size>0?{journalBodyOwed:f}:{},journalSourceVoid:void 0}}let c=l.journalPositions??new Map;const u=c,O=(d,f,p)=>{if(!Vd(p))return;const m=c.get(d);m&&m.seq>=p||(c===u&&(c=new Map(c)),c.set(d,{entryId:f,seq:p}))};for(const[d,f]of Object.entries(t.journal_ordinals??{}))O(d,d,f);for(const d of n)typeof d.id=="string"&&(O(d.id,d.id,d.journal_seq),d.role==="tool"&&typeof d.tool_call_id=="string"&&O(`tool:${d.tool_call_id}`,d.id,d.journal_seq),typeof d.anchor=="string"&&O(`supplement:${d.anchor}`,d.id,d.journal_seq));return c!==u&&(l={...l,journalPositions:c}),l}function kA(e,t){if(!e.journalMode||typeof t.id!="string"||!Array.isArray(t.tool_calls))return e;let n=e.journalCallOwners??new Map,r=e.journalCallSlots??new Map;const i=n,a=r;return t.tool_calls.forEach((o,s)=>{!o||typeof o.id!="string"||(n.get(o.id)!==t.id&&(n===i&&(n=new Map(n)),n.set(o.id,t.id)),r.get(o.id)!==s&&(r===a&&(r=new Map(r)),r.set(o.id,s)))}),n===i&&r===a?e:{...e,journalCallOwners:n,journalCallSlots:r}}function gle(e,t){const n=new Set(e.map(a=>a.id));let r=!1,i;for(let a=0;a<e.length;a++){const o=e[a];if(o.kind==="user"&&o.provisional===!0){i=o;continue}!t(o)&&i&&(o.sourceAdmissionAnchor===void 0||!n.has(o.sourceAdmissionAnchor))&&(e[a]={...o,sourceAdmissionAnchor:i.id},r=!0),i=e[a]}return r}function $le(e,t,n,r,i){const a=[],o=new Set;let s=e,l;for(;s!==void 0;){if(i.has(s.id)){l=i.get(s.id);break}if(n(s)){l=r(s);break}if(s.kind==="user"&&s.provisional===!0||o.has(s.id))break;o.add(s.id),a.push(s.id),s=s.sourceAdmissionAnchor?t.get(s.sourceAdmissionAnchor):void 0}for(const c of a)i.set(c,l);return l}function yle(e,t){const n=new Map;return r=>{if(!r)return;const i=t(r);if(i===void 0)return;const a=[],o=new Set;let s=r,l=!0;for(;s;){if(n.has(s.id)){l=n.get(s.id)===!0;break}if(o.has(s.id)||t(s)===void 0){l=!1;break}o.add(s.id),a.push(s.id),s=s.sourceAdmissionAnchor===void 0?void 0:e.get(s.sourceAdmissionAnchor)}for(const c of a)n.set(c,l);return l?i:void 0}}function sS(e,t){const n=e.journalCallOwners,r=e.journalCallSlots;if(!n||!r)return t;const i=new Map;t.forEach((o,s)=>{if(o.kind!=="tool")return;const l=n.get(o.toolCallId);if(l===void 0||!r.has(o.toolCallId))return;const c=i.get(l);c?c.push(s):i.set(l,[s])});let a=t;for(const o of i.values()){if(o.length<2)continue;const s=o.map(l=>t[l]).sort((l,c)=>(r.get(l.toolCallId)??0)-(r.get(c.toolCallId)??0));s.every((l,c)=>l===t[o[c]])||(a===t&&(a=t.slice()),o.forEach((l,c)=>{a[l]=s[c]}))}return a}function vle(e,t){if(!e.journalMode)return t;if(e.journalPeerSource===!0)return jXe(e,t);const n=e.journalGeneration,r=e.journalPositions;let i=!1;const a=t.map(f=>{let m=[r?.get(f.sourceEntryId??f.id),r?.get(f.id)].filter(v=>v!==void 0).sort((v,S)=>S.seq-v.seq)[0];if(f.journalGeneration===n&&Vd(f.journalSeq)&&(!m||f.journalSeq>m.seq)&&(m={entryId:f.sourceEntryId??f.id,seq:f.journalSeq}),!m||!n||!(f.kind==="user"&&(f.provisional===!0||f.local===!0))&&f.sourceEntryId===m.entryId&&f.journalSeq===m.seq&&f.journalGeneration===n)return f;i=!0;let y={...f,sourceEntryId:m.entryId,journalSeq:m.seq,journalGeneration:n};if(y.kind==="user"){const{provisional:v,local:S,...Q}=y;y=Q}return y});gle(a,f=>f.journalGeneration===n&&Vd(f.journalSeq))&&(i=!0);const s=new Map,l=new Map(a.map(f=>[f.id,f])),c=yle(l,f=>f!==void 0&&f.journalGeneration===n&&Vd(f.journalSeq)?f.journalSeq:void 0),u=f=>c(f)!==void 0,O=(f,p)=>{const m=c(f);if(f.kind==="user"&&f.provisional===!0&&m===void 0)return[1,0,0,0,p];const g=f.kind==="supplement"?f.anchor:f.kind==="tool"?e.journalCallOwners?.get(f.toolCallId)??e.argsByCall.get(f.toolCallId)?.anchorId:void 0,y=typeof g=="string"?c(l.get(g)):void 0,v=m===void 0?$le(f,l,u,c,s):void 0,S=y??m??v;return S===void 0?[1,0,0,0,p]:[0,S,y!==void 0?1:m!==void 0?0:2,m??Number.MAX_SAFE_INTEGER,p]},d=a.map((f,p)=>({record:f,index:p,rank:O(f,p)}));return d.sort((f,p)=>{for(let m=0;m<f.rank.length;m++){const g=f.rank[m]-p.rank[m];if(g)return g}return 0}),!i&&d.every((f,p)=>f.index===p)?sS(e,t):sS(e,d.map(f=>f.record))}function jXe(e,t){const n=e.journalGeneration,r=e.journalPositions,i=new Map;for(const m of t){let y=[r?.get(m.sourceEntryId??m.id),r?.get(m.id)].filter(v=>v!==void 0).sort((v,S)=>S.seq-v.seq)[0];m.journalGeneration===n&&Vd(m.journalSeq)&&(!y||m.journalSeq>y.seq)&&(y={entryId:m.sourceEntryId??m.id,seq:m.journalSeq}),y&&i.set(m.id,y)}const a=m=>m===void 0?void 0:i.get(m.id)??r?.get(m.sourceEntryId??m.id)??r?.get(m.id);let o=!1;const s=t.slice();gle(s,m=>m.journalGeneration===n&&Vd(m.journalSeq))&&(o=!0);const c=new Map,u=new Map(s.map(m=>[m.id,m])),O=yle(u,m=>a(m)?.seq),d=m=>O(m)!==void 0,f=(m,g)=>{const y=O(m);if(m.kind==="user"&&m.provisional===!0&&y===void 0)return[1,0,0,0,g];const v=m.kind==="supplement"?m.anchor:m.kind==="tool"?e.journalCallOwners?.get(m.toolCallId)??e.argsByCall.get(m.toolCallId)?.anchorId:void 0,S=typeof v=="string"?O(u.get(v)):void 0,Q=y===void 0?$le(m,u,d,O,c):void 0,b=S??y??Q;return b===void 0?[1,0,0,0,g]:[0,b,S!==void 0?1:y!==void 0?0:2,y??Number.MAX_SAFE_INTEGER,g]},p=s.map((m,g)=>({record:m,index:g,rank:f(m,g)}));return p.sort((m,g)=>{for(let y=0;y<m.rank.length;y++){const v=m.rank[y]-g.rank[y];if(v)return v}return 0}),!o&&p.every((m,g)=>m.index===g)?sS(e,t):sS(e,p.map(m=>m.record))}function kl(e){const t=e.records.filter(i=>i.kind==="user"&&i.provisional===!0),n=e.records.filter(i=>i.journalGeneration!==e.journalGeneration||!Vd(i.journalSeq)),r=[...t,...n].map(i=>i.sourceEntryId??(i.kind==="tool"||i.kind==="supplement"?null:i.id));if(r.push(...PA(e)),e.journalPositions?.has(e.oldestId??"")||r.push(e.oldestId),e.journalSourceVoid?.size)for(let i=r.length-1;i>=0;i--){const a=r[i];typeof a=="string"&&e.journalSourceVoid.has(a)&&r.splice(i,1)}return[...new Set(r.filter(i=>typeof i=="string"&&i.length>0&&i.length<=128))]}function PA(e){if(e.journalPeerSource!==!0||!e.journalBodyOwed)return[];const t=new Set;for(const r of e.records){const i=r.sourceEntryId??(r.kind==="tool"||r.kind==="supplement"?null:r.id);typeof i=="string"&&i.length>0&&i.length<=128&&t.add(i)}const n=[];for(const r of e.journalBodyOwed.keys())r.length<1||r.length>128||t.has(r)&&(e.journalSourceVoid?.has(r)||n.push(r));return n}function ble(e,t){const n=e.journalPositions;return kl(e).filter(r=>!n?.has(r)&&!t?.has(r))}const es=e=>e.orderRevision??0;async function CXe(e){const t=new Map,n=s=>{let l=t.get(s);return l||(l=new Set,t.set(s,l)),l},r=(s,l)=>l==="payload"?PA(s):l==="lookup"?ble(s):kl(s);let i=e.getTranscript().journalGeneration,a=0,o=0;for(;;){if(!e.isCurrent())return{kind:"stale"};const s=e.getTranscript(),l=Zq(s),c=l.revision,u=e.sweep?.(s,n);if(u?.kind==="none")return{kind:"complete",transcript:s};const O=u?.kind??"authority",d=bRe(r(s,O).filter(g=>!n(O).has(g)),u?.path??e.lookupPath,u?.query??new URLSearchParams({journal_order:"1"})),f=await e.read(d,O);if(!e.isCurrent()||es(e.getTranscript())!==c)return{kind:"stale"};if(e.commit(f,c,l),!e.isCurrent())return{kind:"stale"};const p=e.getTranscript(),m=e.page(f);if(m.journal_order_state==="ready"&&m.journal_generation===p.journalGeneration){m.journal_generation!==i&&(t.clear(),i=m.journal_generation);for(const v of d)n(O).add(v);if(p.orderNeedsReconcile){if(p.orderDemand===l.demand||a===1)return{kind:"waiting"};a++,t.clear();continue}if(O==="payload"){const v=(m.source_retry_ids??[]).filter(S=>typeof S=="string"&&S.length>0&&S.length<=128);if(v.length>0&&d.length>1&&o===0){o++;for(const S of v)n("payload").delete(S);continue}}const g=e.sweep?.(p,n);if(g?.kind==="none")return{kind:"complete",transcript:p};const y=g?.kind??"authority";if(r(p,y).some(v=>!n(y).has(v)))continue;return{kind:"complete",transcript:p}}if(!p.orderNeedsReconcile||p.orderDemand===l.demand||a===1)return{kind:"waiting"};a++,t.clear()}}function Vs(e){const t=e.payload,n=t?.tool_call_id;if(t?.role==="tool"&&typeof n=="string"&&n)return`tool:${n}`;const i=(t?.details??{}).anchor;return t?.custom_type==="completion_attention"&&typeof i=="string"&&i?i:e.id}function Y_(e){return typeof e!="number"||!Number.isFinite(e)?null:Math.max(0,Math.trunc(e))}function BN(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:e}function fln(e){if(!e||e.runs_state!=="ready")return null;const t=e.runs;if(!t||t.length===0)return null;const n=new Map;for(const a of t){if(!a.settled||typeof a.run_key!="string"||a.run_key.length===0)continue;const o=Y_(a.action_count);if(o===null)continue;const s={actions:o,workedSeconds:BN(a.worked_seconds),failed:Y_(a.failed_count)??0,complete:a.complete!==!1,openingUserId:typeof a.opening_user_id=="string"&&a.opening_user_id.length>0?a.opening_user_id:null,closingAnswerId:typeof a.closing_answer_id=="string"&&a.closing_answer_id.length>0?a.closing_answer_id:null,crossSessionActions:Y_(a.cross_session_action_count),crossSessionWorkedSeconds:BN(a.cross_session_worked_seconds)};n.set(a.run_key,s),s.openingUserId!==null&&n.set(s.openingUserId,s),s.closingAnswerId!==null&&n.set(s.closingAnswerId,s)}if(n.size===0)return null;const r=new Set;for(const a of e.entries)r.add(Vs(a));const i=e.entries[e.entries.length-1];return{runs:n,page:{ids:r,newestKey:i?Vs(i):null}}}function AXe(e){if(!e||e.runs_state!=="ready"||e.head_cut===!0)return null;const t=e.runs,n=e.entries[0];if(!n||!t||t.length===0||!t.find(a=>a.opening_user_id===n.id))return null;const i=Math.round((n.ts??0)*1e3);return i>0?{id:n.id,tsMs:i}:null}function zXe(e,t,n){const r=AXe(e),i=e?.entries;if(r===null||!i||i.length===0)return!1;const a=Math.round((i[i.length-1].ts??0)*1e3);if(!(a>r.tsMs))return!1;for(const[o,s]of t)if(!n.has(o)&&(s===null||!(s>r.tsMs)||!(s<a)))return!1;return!0}const _A=new Set,ba="\\t\\n\\v\\f\\r\\u001C-\\u001F \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000",Zo=new RegExp(`[${ba}]`),JQ=new RegExp(`[${ba}]+`),UXe=new RegExp(`[${ba}]+`,"g"),WXe=new RegExp(`^[${ba}]+|[${ba}]+$`,"g"),NXe=new RegExp(`^[${ba}]+`),YXe=new RegExp(`[^${ba}]`);function on(e){return e.replace(WXe,"")}function lu(e){return e.replace(NXe,"")}function GXe(e,t){return t===0||Zo.test(e[t-1])}function wle(e){const t=[];for(let n=0;n<e.length;n++)e[n]==="/"&&GXe(e,n)&&t.push(n);return t}function ek(e,t){let n=t===null||t>e.length?e.length:t;n<0&&(n=0);const r=e.lastIndexOf(`
3
3
  `,n-1)+1,i=e.indexOf(`
4
4
  `,n),a=i===-1?e.length:i;let o=e.slice(r,a);return o.endsWith("\r")&&(o=o.slice(0,-1)),{line:o,lineStart:r,column:n-r}}function IXe(e,t){if(t.size===0)return null;for(const n of wle(e)){const r=e.slice(n+1),i=r.indexOf(" ");if(i!==-1&&t.has(r.slice(0,i).toLowerCase()))return n}return null}function TA(e,t,n){const r=IXe(e,n);let i=null;for(const a of wle(e)){if(a===r)return t>a?a:i;a<=t&&(i=a)}return i}function sv(e,t=null,n=_A){const{line:r,lineStart:i,column:a}=ek(e,t),o=TA(r,a,n);if(o===null)return null;let s=o+1;for(;s<r.length&&!Zo.test(r[s]);)s++;return a>s?null:{start:i+o,query:r.slice(o+1,s),end:i+s}}function b$(e,t=null,n=_A){const{line:r,lineStart:i,column:a}=ek(e,t),o=TA(r,a,n);return o===null?null:{start:i+o,end:i+r.length}}function tk(e,t,n=null,r=_A){const{line:i,lineStart:a,column:o}=ek(e,n),s=r.size>0?r:new Set(t.map(f=>f.toLowerCase())),l=TA(i,o,s);if(l===null)return null;const c=i.slice(l+1),u=c.indexOf(" ");if(u===-1)return null;const O=c.slice(0,u);if(!t.some(f=>f.toLowerCase()===O.toLowerCase()))return null;const d=l+1+O.length;return o<=d?null:{value:c.slice(u+1),start:a+d+1,end:a+i.length,tokenStart:a+l}}function Dq(e,t){return on(e.slice(0,t))===""}function ZXe(e,t,n,r){const i=tk(e,r,t,n);if(i!==null&&Dq(e,i.tokenStart))return"argument";const a=sv(e,t,n);return a!==null&&Dq(e,a.start)?"command":null}function vO(e,t,n,r){let i=t,a=n;const o=s=>s>=0&&s<e.length&&`
5
5
  `.includes(e[s]);return r===""?i>0&&o(i-1)?i-=1:o(a)&&(a+=1):i===0&&o(a)&&(a+=1),{text:`${e.slice(0,i)}${r}${e.slice(a)}`,caret:i+r.length}}const DXe=/^\$([A-Za-z0-9][A-Za-z0-9._-]*)/,MXe=/<skill name="([^"]*)" invocation="([^"]*)">/;function HN(e,t){const n=lu(e),r=DXe.exec(n);if(!r)return null;const i=r[1];let a=t.includes(i)?i:void 0;if(a===void 0){const s=i.toLowerCase();a=t.find(l=>l.toLowerCase()===s)}if(a===void 0)return null;const o=on(n.slice(r[0].length));return{name:a,request:o,token:r[0],typed:on(n)}}function VXe(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\n/g,"&#10;")}function LXe(e){return e.replace(/&#10;/g,`
@@ -513,7 +513,7 @@ ${t}`)}throw new Error(`Failed to load configuration: ${e instanceof Error?e.mes
513
513
  `);return n.length<=t?{lines:n,hidden:0}:{lines:n.slice(0,t),hidden:n.length-t}}const gWe=["connected","connecting","cold"],$We={"auth-required":"Manage this server's credentials in Settings"},d0={grant:"Grant account access",key:"Enter API key",reconnect:"Reconnect",reload:"Reload"};function yWe(e,t={},n=[]){const r=SWe(n);return Hd(e).map(i=>{const a=rn(i.name);if(!a)return null;const o=rn(i.status)||"cold",s=!gWe.includes(o),l=rn(i.transport)||null,c=typeof i.transport_oauth_supported=="boolean"?i.transport_oauth_supported:null,u=(Array.isArray(i.secret_refs)?i.secret_refs:[]).map(O=>rn(O&&typeof O=="object"&&"id"in O?O.id:null)).filter((O,d,f)=>O&&f.indexOf(O)===d);return{name:a,status:o,problem:s,toolCount:o==="connected"?xi(i.tool_count):null,keyNames:u,transport:l,oauthSupported:c,grant:r.get(a)&&(s||r.get(a)?.status==="running")?r.get(a):null,scope:rn(i.owned_scope)||xWe(i.source)||null,remedy:s?bWe({status:o,transport:l,oauthSupported:c,keyNames:u}):null,errorText:s&&rn(t[a])||null}}).filter(i=>i!==null).sort((i,a)=>i.name.localeCompare(a.name))}const vWe=/[\\/]/,bWe=e=>["disconnected","auth-required"].includes(e.status)&&e.keyNames.length>0&&(e.oauthSupported===!1||e.transport==="stdio")?{kind:"key"}:e.status==="disconnected"?{kind:"reconnect"}:e.status!=="auth-required"?null:e.transport==="stdio"||e.oauthSupported===!1?e.keyNames.length>0?{kind:"key"}:{kind:"words",label:$We["auth-required"]}:{kind:"grant"},wWe=["running","complete","failed","cancelled"],SWe=e=>{const t=new Map;for(const r of Hd(e)){const i=rn(r.name),a=rn(r.id),o=rn(r.status);if(!i||!a||!wWe.includes(o))continue;const s=xi(r.created_at)??0,l=t.get(i);l&&l.createdAt>s||t.set(i,{id:a,action:rn(r.action)||"reauth",status:o,credentialRemoved:r.credential_removed===!0,createdAt:s})}const n=new Map;for(const[r,{createdAt:i,...a}]of t)a.status!=="complete"&&n.set(r,a);return n},Qj=e=>Hd(e).some(t=>rn(t.status)==="running"),xWe=e=>{const t=rn(e);if(!t)return"";const n=t.split(vWe);return n[n.length-1]??""};function QWe(e){return e.length>0&&e.every(t=>t.status==="cold")}function Tcn(e){const t={};for(const n of Hd(e)){const r=rn(n.name),i=rn(n.error);r&&i&&(t[r]=i)}return t}function Rcn(e,t){if(QWe(e))return kWe;const n=e.filter(o=>o.status==="connected").length,r=e.filter(o=>o.problem).length,i=`${n} of ${e.length} connected`;if(r===0)return i;const a=`${i} · ${AWe(r)}`;return t!==void 0&&a.length>t?i:a}const kWe="No session is running — server status cannot be checked.";function PWe(e){return e.filter(t=>t.problem).map(t=>t.name)}function Xcn(e,t=WO){const n=PWe(e),r=new Set(n.filter(a=>t.has(a))),i=bOe(r,n);return i.size===t.size&&[...i].every(a=>t.has(a))?t:i}function _We(e,t=WO){return e.filter(n=>n.problem&&!t.has(n.name)).map(n=>n.name)}function Ecn(e,t=WO){return _We(e,t).length>0}const wOe=(e,t)=>{if(e.length===0)return"";if(t===void 0)return e.join(m5);let n=e.slice(0,1);for(const r of e.slice(1)){if([...n,r].join(m5).length>t)break;n=[...n,r]}return n.join(m5)},SOe=32,xOe=66,QOe=6,TWe=4,qcn=e=>(Number.isFinite(e)&&e>0?e:xz)-SOe-xOe>=TWe*QOe,xz=420,jcn=e=>{const t=Number.isFinite(e)&&e>0?e:xz;return Math.max(1,Math.floor((t-SOe-xOe)/QOe))};function Ccn(e,t){const n=[];for(const r of["running","queued","failed","interrupted","paused","cancelled","done","gone","unknown"]){const i=e.filter(o=>o.status===r);if(i.length===0)continue;const a=new Map;for(const o of i)a.set(o.stateWord,(a.get(o.stateWord)??0)+1);for(const[o,s]of a)n.push(`${s} ${o}`)}return wOe(n,t)}function Acn(e,t){if(!e)return"";const n=[`${RWe(e)} of ${e.totalTodos} closed`,...e.droppedTodos>0?[`${e.droppedTodos} dropped`]:[]];return wOe(n,t)}function RWe(e){return e.doneTodos+e.droppedTodos}const AG=e=>e.settledSeconds??e.startSeconds,XWe=(e,t)=>{const n=AG(e),r=AG(t);return n!==null&&r!==null?n===r?0:r-n:n===null&&r===null?0:n===null?1:-1},zG=(e,t)=>EG[e.status]-EG[t.status]||XWe(e,t);function EWe(e,t=OOe){const n=[...e].sort(zG);if(n.length<=t)return{rows:n,hidden:0};const r=n.slice(0,t);for(const i of n.slice(t)){if(i.status!=="failed")continue;let a=-1;for(let o=r.length-1;o>=0;o--)if(r[o].status!=="failed"){a=o;break}if(a===-1)break;r[a]=i}return r.sort(zG),{rows:r,hidden:n.length-r.length}}function qWe(e,t=OOe){return EWe([...e],t)}function jWe(e){return qWe(e).rows.filter(t=>t.status==="failed").map(t=>t.id)}function zcn(e){return jWe(e?.subagents??[])}function Ucn(e){const t=e.reduce((c,u)=>c+u.items.length,0);if(t<=qG)return{phases:e.map(c=>({...c,hidden:0})),hidden:0};const n=c=>wz.includes(c.status),r=e.reduce((c,u)=>c+u.items.filter(O=>!n(O)).length,0),i=t-r,a=Math.max(0,qG-i),o=Math.max(0,r-a);let s=0;const l=e.map(c=>{const u=[];let O=0;for(const d of c.items){if(n(d)){u.push(d);continue}s++<o?O+=1:u.push(d)}return{...c,items:u,hidden:O}});return{phases:l,hidden:l.reduce((c,u)=>c+u.hidden,0)}}const $k=(e,t)=>e===1?`1 ${t}`:`${e} ${t}s`,kOe=e=>uOe[e],POe=e=>e.markCount===e.count?kOe(e.mark):"open",_Oe=e=>e.markCount===e.count?"":`, ${e.markCount} ${kOe(e.mark)}`,Qz=e=>`${$k(e.count,"subagent")} ${POe(e)}`,kz=e=>`${$k(e.count,"job")} ${POe(e)}`,Pz=e=>e.openTodos>0?e.openTodos===1?"1 to-do open":`${e.openTodos} to-dos open`:e.droppedTodos>0?"All to-dos closed":"All to-dos resolved",CWe=e=>`${$k(e,"subagent")} failed`,TOe=e=>e===1?"needs":"need",AWe=e=>`${e} ${TOe(e)} attention`,zWe=e=>`${$k(e,"MCP server")} ${TOe(e)} attention`;function Wcn(e,t=WO,n={}){const r=n.cap??null,i=`${n.open?DUe:ZUe}${r===null?"":` (${r})`}`;if(!e)return i;const a=[],o=[],s=vOe(e,t).length;s>0&&a.push(CWe(s)),(n.mcpProblems??0)>0&&a.push(zWe(n.mcpProblems??0));const l=xS(e.subagents);l&&o.push(Qz(l));const c=xS(e.jobs);c&&o.push(kz(c)),e.openTodos>0&&o.push(Pz(e));const u=[...a,...o];if(u.length===0)return i;if(n.maxChars!==void 0){const O=a.length>0?a:o.slice(0,1),d=a.length>0?o:o.slice(1);let f=[...O];for(const p of d){if((i+Wa+[...f,p].join(g5)).length>n.maxChars)break;f=[...f,p]}return i+Wa+f.join(g5)}return i+Wa+u.join(g5)}function UWe(e){return e.stateWord}const Ncn=e=>e.childCount>0?`${e.childCount} child${e.childCount===1?"":"ren"}`:null,WWe=54,NWe=48,YWe=12,GWe=172,IWe=92,Ycn=e=>(Number.isFinite(e)&&e>0?e:xz)-NWe-GWe-YWe-WWe>=IWe,Gcn=e=>e.childSessionId!==null;function Icn(e,t){return e.filter(n=>n.parentJobId===t.id)}const ROe='textarea[aria-label="Message"]';let W0=null;function ZWe(e,t){return W0={give:e,field:t},()=>{W0?.give===e&&(W0=null)}}function DWe(){return W0?.field()??null}function _z(){W0?.give()}const MWe="data-canvas-shortcuts",VWe=`[${MWe}]`,LWe=e=>XOe(e,VWe),FWe='[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]',X$=e=>XOe(e,FWe);function XOe(e,t){const n=e;return typeof n?.closest=="function"?n.closest(t)!==null:!1}const Zcn=e=>{if(!(e.metaKey||e.ctrlKey))return null;const t=e.key.toLowerCase();return t==="o"?"open-file":t==="n"&&LWe(e.target)?"new-file":null},BWe=e=>e==="open"||e==="answered"||e==="declined"||e==="timed_out"||e==="late"||e==="dismissed"||e==="expired",EOe=e=>{const t=e?.asks;return Array.isArray(t)?t:null},HWe=e=>e!=null&&(Array.isArray(e.asks)||e.asks_open!=null),Dcn=e=>ONe(e)?null:e?.pending_gate??null,mv=e=>!e.truncated&&e.open<=e.waiting+e.movedOn,Mcn=e=>mv(e)?e.rows.filter(t=>t.canAnswer).length:e.open,UG=(e,t)=>{const n=Tz(e),r=rNe(e,t);return r===null?n:`${n} · ${r}`},Tz=e=>mv(e)?e.waiting>0?e.waiting===1?"1 question waiting":`${e.waiting} questions waiting`:e.delivering>0?e.delivering===1?"1 answer not yet delivered — you can still change it":`${e.delivering} answers not yet delivered — you can still change them`:e.movedOn>0?e.movedOn===1?"1 question timed out":`${e.movedOn} questions timed out`:"All asks settled":`${e.open} outstanding`,kj=e=>e==="fleet"?"All conversations":"This conversation",KWe="Reading the asks…",JWe="Asks unavailable",eNe="This runtime doesn't support queued asks.",tNe=e=>e.unread?"":e.published?mv(e)&&e.waiting===0&&e.delivering===0?"All asks settled":Tz(e):JWe,nNe=(e,t)=>{const n=tNe(t);return n===""?kj(e):`${kj(e)} · ${n}`},Vcn=e=>{const t=e.open?"Close":"Open",n=e.cap===null||e.cap===void 0?"":` (${e.cap})`,r=kj(e.scope);return e.count>0?`${t} asks${n} — ${r}, ${e.count} waiting`:`${t} asks${n} — ${r}`},qOe=e=>!mv(e)||e.waiting===0?null:e.soonestExpiryMs,jOe=(e,t)=>{const n=qOe(e);return n===null?null:YOe(n,t)},COe=e=>e.waiting>1?"soonest ask":"",rNe=(e,t)=>{const n=jOe(e,t);if(n===null)return null;const r=COe(e);return r===""?n:`${r} ${n}`},iNe=(e,t)=>{const n=qOe(e);return n===null?null:SNe(n,t)},aNe=(e,t)=>mv(e)&&(e.waiting>0||e.delivering>0)&&e.movedOn>0?`${UG(e,t)} · ${e.movedOn} timed out`:UG(e,t),oNe=(e,t,n)=>{const r=e.urgent?" · Urgent":"";return`${t?"Collapse":"Expand"} this conversation's asks${Wa}${aNe(e,n)}${r}`},Lcn=e=>{const t=e.head;if(t===null||!t.canAnswer)return!1;const n=t.ask.questions;return n.length>0&&n.every(r=>r.secret===!0)},sNe=e=>{const t=e.questions,n=t.length===1&&t[0].secret===!0;return{key:`${e.ask_id}:${n?t[0].id:"*"}`,questionId:n?t[0].id:null}},Fcn=async(e,t,n,r)=>{if(e===null)return"stale";const i=sNe(e.ask);if(i.key!==t)return"stale";if(i.questionId===null)return"multi";const a=await r(e.ask.ask_id,{[i.questionId]:[n.trim()]});return a===void 0?"unavailable":a.status==="sent"?"sent":a.status==="refused"||a.status==="failed"?"refused":a.status},lNe="[data-lo-ask-surfaces]",AOe="[data-lo-ask-item-toggle]",cNe='[data-tour-tag="ask-pane-trigger"]',uNe=e=>{const t=e;return typeof t?.closest!="function"?!0:t.closest(lNe)!==null||t.closest(AOe)!==null||t.closest(ROe)!==null},Bcn=e=>e.key!=="Escape"||e.isComposing===!0||e.defaultPrevented===!0||X$(e.target)?!1:uNe(e.target),ONe=e=>EOe(e)!==null&&e?.pending_gate?.kind==="ask",dNe=e=>e.questions.map(t=>({id:t.id,question:t.question,answers:(e.answers?.[t.id]??[]).slice()})),fNe=e=>!Number.isFinite(e)||e<=0?"a while":e<60?`${Math.trunc(e)}s`:e<3600?`${Math.trunc(e/60)}m`:e<86400?`${Math.trunc(e/3600)}h`:`${Math.trunc(e/86400)}d`,hNe=e=>e.status==="declined"?`Ask ${e.askId} declined — the agent was told`:e.status==="late"?`Answered late — the agent was told (ask ${e.askId})`:`Answered — delivering (ask ${e.askId})`,pNe=e=>`Timed out after ${fNe(e.waitedS)} — the agent goes ahead without your answer (ask ${e.askId})`,mNe="You can change this until the agent is handed your answer.",gNe=new Set(["open","timed_out"]),zOe=e=>{const t=BWe(e.status)?e.status:"unknown",n=gNe.has(t),r=t==="timed_out";return{ask:e,status:t,open:n,waiting:t==="open",movedOn:r,lapsed:r,canAnswer:t==="open",canDecline:t==="open",delivering:(t==="answered"||t==="late")&&e.delivered!==!0}},yk=(e,t)=>{const n=EOe(e),r=HWe(e),i=e==null;if(n===null)return{asks:null,published:r,unread:i,rows:[],open:typeof e?.asks_open=="number"?e.asks_open:0,waiting:0,movedOn:0,total:0,truncated:e?.asks_truncated===!0,urgent:!1,delivering:0,soonestExpiryMs:null,head:null};const a=n.map(zOe).sort($Ne),o=a.filter(O=>O.open).length,s=a.filter(O=>O.waiting).length,l=a.filter(O=>O.movedOn).length,c=a.filter(O=>O.delivering&&t?.[O.ask.ask_id]?.refusedByOwner!==!0).length,u=a.filter(O=>O.waiting).map(O=>Number(O.ask.expires_at??0)).filter(O=>Number.isFinite(O)&&O>0);return{asks:n,published:r,unread:i,rows:a,open:typeof e?.asks_open=="number"?e.asks_open:o,waiting:s,movedOn:l,delivering:c,total:a.length,truncated:e?.asks_truncated===!0,urgent:a.some(O=>O.waiting&&O.ask.urgent===!0),soonestExpiryMs:u.length>0?Math.min(...u):null,head:a.find(O=>O.canAnswer)??null}},$Ne=(e,t)=>e.open!==t.open?e.open?-1:1:UOe(e,t),UOe=(e,t)=>{const n=Number(e.ask.created_at??0),r=Number(t.ask.created_at??0);return n!==r?n-r:e.ask.ask_id.localeCompare(t.ask.ask_id)},WOe={open:"Queued — the agent is continuing",answered:"Answered — delivering",timed_out:"Timed out — the agent goes ahead without your answer",late:"Answered late — the agent was told",declined:"Declined — the agent was told",dismissed:"Dismissed — no reply was sent",expired:"Expired — this ask is too old to answer; ask the agent again",unknown:"Waiting on an answer"},yNe="Answered late — not yet delivered",vNe=e=>{const t=WOe[e],n=t.indexOf(" — ");return n===-1?t:t.slice(0,n)},WG=(e,t=new Set)=>{const n=r=>r.canAnswer||r.delivering||r.lapsed&&t.has(r.ask.ask_id);return{pending:e.filter(n),settled:e.filter(r=>!n(r)).sort((r,i)=>UOe(i,r))}},bNe=(e,t)=>{const n=zOe(e);if(n.status==="late"&&n.delivering)return yNe;const r=WOe[n.status];if(n.status!=="open")return r;const i=wNe(e,t);return i===null?r:`${r}; ${i}`},wNe=(e,t)=>YOe(Number(e.expires_at??0),t),NOe=(e,t)=>{if(!Number.isFinite(e)||e<=0)return null;const n=e-t;if(n<=0)return{long:"expiring now",short:"now"};const r=Math.floor(n/6e4);if(r<1){const o=`${Math.floor(n/1e3)}s`;return{long:`expires in ${o}`,short:o}}if(r<60)return{long:`expires in ${r}m`,short:`${r}m`};const i=Math.floor(r/60);if(i<24)return{long:`expires in ${i}h`,short:`${i}h`};const a=Math.floor(i/24);return{long:`expires in ${a}d`,short:`${a}d`}},YOe=(e,t)=>NOe(e,t)?.long??null,SNe=(e,t)=>NOe(e,t)?.short??null,GOe={},xNe={},QNe=()=>{},Rz=(e,t)=>e[t]??[],IOe=e=>e==="",gv=e=>e.trim().length>0,kNe="<not provided>",ZOe=(e,t)=>{if(t===void 0)return!0;const n=t[e.id];if(!Array.isArray(n))return!1;const r=n.filter(gv);return r.length===0||r[0]===kNe},PNe="Leave empty to skip; what you type is never shown",_Ne="Required: type it again; it is never shown",TNe="Your answer (never shown again)",Xz=(e,t)=>gv(t[e.id]??""),DOe=(e,t)=>!e.secret||t===void 0||Xz(e,t),RNe=(e,t,n)=>ZOe(t,n)?e.questions.some(r=>r.id!==t.id&&DOe(r))?PNe:TNe:_Ne,Pj=(e,t,n={},r)=>{if(e.secret)return Xz(e,n)||ZOe(e,r);const i=Rz(t,e.id);return i.some(gv)&&!i.some(IOe)},XNe=(e,t,n={},r)=>e.questions.every(i=>Pj(i,t,n,r))&&e.questions.some(i=>DOe(i,n)),_j=32768,ENe=(e,t)=>e.filter(n=>gv(n)&&!t.includes(n)),qNe=(e,t)=>{const n=ENe(e,t);return{open:n.length>0||e.some(IOe),text:n.join(`
514
514
  `)}},jNe=(e,t,n)=>{const r=e.filter(o=>t.includes(o)),i=n.open?n.text.trim():"";if(i===""||!t.includes(i))return r;const a=r.lastIndexOf(i);return r.filter((o,s)=>s!==a)},NG=(e,t,n)=>{if(!n.open)return t?[...e]:[];const r=n.text.trim();return t?[...e,r]:[r]},bb=(e,t,n={},r)=>{if(!XNe(e,t,n,r))return null;const i={};for(const a of e.questions)i[a.id]=a.secret?Xz(a,n)?[(n[a.id]??"").trim()]:[]:[...new Set(Rz(t,a.id).filter(gv))];return i},CNe=e=>{const t={};for(const n of e.questions){if(n.secret)continue;const r=e.answers?.[n.id];Array.isArray(r)&&r.length>0&&(t[n.id]=[...r])}return t},Tj="That question was already settled, so your answer was not sent.",ANe="This ask is too old to answer — ask the agent again.",MOe=e=>{const t=typeof e?.status=="number"?e.status:null,n=typeof e?.code=="string"?e.code:"";return t===410||n==="expired"?ANe:t===409?Tj:null},zNe=e=>{const t=typeof e=="object"&&e!==null?e.detail:void 0,n=e instanceof Error?e.message:"";return t!==void 0||e instanceof Ut&&n!==""&&n!==ple},UNe=e=>{if(zNe(e))return Io(e,Tj);const t=MOe(e);return t!==null?t:Io(e,e instanceof Error&&e.message?e.message:Tj)},WNe=e=>MOe(e)!==null,Hcn=e=>e===1?"1 ask":`${e} asks`,VOe=["desktop","asks"],YG=1e4;function NNe(e){const t=Array.isArray(e)?e:e?.asks??[];if(!Array.isArray(t))return[];const n=[];for(const r of t){if(r===null||typeof r!="object")continue;const i=r;if(typeof i.ask_id!="string"||i.ask_id.length===0)continue;const a=i.session_id;typeof a!="string"||a.length===0||n.push(i)}return n}const LOe=e=>yk({asks:[...e]}).rows.filter(t=>t.canAnswer).length;function Kcn(e){const t=new Map;for(const n of yk({asks:[...e]}).rows){if(!n.canAnswer)continue;const r=n.ask.session_id;typeof r!="string"||r.length===0||t.set(r,(t.get(r)??0)+1)}return t}const YNe=Object.freeze({asks:null,asks_open:null,asks_truncated:!1});function GNe(e,t){return e!==null?INe(e):t?YNe:null}function INe(e){return{asks:[...e],asks_open:LOe(e),asks_truncated:!1}}function ZNe(e,t){const n=typeof e.session_id=="string"?e.session_id:"",r=t===void 0?null:t(n);if(typeof r=="string"&&r.trim().length>0)return r.trim();const a=(typeof e.cwd=="string"?e.cwd:"").replace(/[/\\]+$/,"");if(a.length>0){const o=a.split(/[/\\]/),s=o[o.length-1];if(s&&s.length>0)return s}return n.length===0?null:`conversation ${n.slice(-4)}`}function DNe(e,t){const n=e.map(a=>({ask:a,label:ZNe(a,t)})),r=new Map;for(const a of n){if(a.label===null)continue;const o=a.ask.session_id,s=a.label.toLocaleLowerCase(),l=r.get(s)??new Set;typeof o=="string"&&o.length>0&&l.add(o),r.set(s,l)}const i=new Map;for(const a of n){if(a.label===null)continue;const o=a.ask.session_id,s=(r.get(a.label.toLocaleLowerCase())?.size??0)>1&&typeof o=="string"&&o.length>0;i.set(a.ask.ask_id,s?`${a.label} · ${o.slice(-4)}`:a.label)}return i}function v5(e,t){const n=e.find(i=>i.ask_id===t);if(!n)return null;const r=n.session_id;return typeof r=="string"&&r.length>0?r:null}function MNe(e,t){return e!==null?"live":t instanceof Ut&&t.status===404?"absent":"unknown"}function VNe(){const{client:e,provided:t}=oo(),n=jt({enabled:t,queryKey:VOe,queryFn:async()=>NNe(await Re({op:"asks.list"})),staleTime:YG,refetchOnMount:!1,retry:Ua,refetchInterval:YG},e),r=n.data??null,i=MNe(r,n.error);return{rows:r,outstanding:r===null?0:LOe(r),capability:i,frontend:GNe(r,i==="absent"),rowFor:a=>r===null?null:r.find(o=>o.ask_id===a)??null}}const LNe=16,FNe=64,Rj=e=>e==="right"||e==="bottom"?1:-1,BNe=(e,t,n)=>Math.max(t,Math.min(n,e)),f0=(e,t,n,r,i)=>BNe(e+t*Rj(n),r,i),HNe=e=>e==="top"||e==="bottom",KNe=(e,{shiftKey:t,value:n,min:r,max:i,side:a,homeEnd:o="axis"})=>{const s=t?FNe:LNe,l=Rj(a)===1?r:i,c=Rj(a)===1?i:r,u=o==="value"?r:l,O=o==="value"?i:c;if(HNe(a)){if(e==="ArrowDown")return f0(n,s,a,r,i);if(e==="ArrowUp")return f0(n,-s,a,r,i)}else{if(e==="ArrowRight")return f0(n,s,a,r,i);if(e==="ArrowLeft")return f0(n,-s,a,r,i)}if(e==="Home")return u;if(e==="End")return O;if(e==="Enter")return null};var b5={exports:{}},w5,GG;function JNe(){if(GG)return w5;GG=1;var e="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED";return w5=e,w5}var S5,IG;function eYe(){if(IG)return S5;IG=1;var e=JNe();function t(){}function n(){}return n.resetWarningCache=t,S5=function(){function r(o,s,l,c,u,O){if(O!==e){var d=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw d.name="Invariant Violation",d}}r.isRequired=r;function i(){return r}var a={array:r,bigint:r,bool:r,func:r,number:r,object:r,string:r,symbol:r,any:r,arrayOf:i,element:r,elementType:r,instanceOf:i,node:r,objectOf:i,oneOf:i,oneOfType:i,shape:i,exact:i,checkPropTypes:n,resetWarningCache:t};return a.PropTypes=a,a},S5}var ZG;function tYe(){return ZG||(ZG=1,b5.exports=eYe()()),b5.exports}var nYe=tYe();const Mn=er(nYe),Jcn=(e,t,n)=>t===null||t===n||e!==null&&t===e,eun=e=>e.viewMoved?e.caretUntouched?"composer":"leave":e.capturedUsable?"captured":e.caretUntouched?"trigger":"leave",rYe=()=>{const e=DWe();return!e||e.disabled?!1:(_z(),document.activeElement===e)},iYe=3e4,FOe=(e,t)=>{const[n,r]=$.useState(()=>t??Date.now());return $.useEffect(()=>{if(t!==void 0||!e)return;r(Date.now());const i=window.setInterval(()=>r(Date.now()),iYe);return()=>window.clearInterval(i)},[e,t]),t??n},BOe="data-text-surface",x5=Object.freeze({[BOe]:"true"}),Ez=e=>{const t=$.useCallback(r=>{const i=window.matchMedia(e);return i.addEventListener("change",r),()=>i.removeEventListener("change",r)},[e]),n=$.useCallback(()=>window.matchMedia(e).matches,[e]);return $.useSyncExternalStore(t,n,()=>!1)},HOe="ml-5",KOe="self-start mt-0.5",DG="flex min-h-6 w-full items-center gap-1.5 py-0.5 text-left",$a=({summary:e,children:t,defaultOpen:n=!1,animate:r=!1,open:i,chevron:a="leading",className:o,triggerClassName:s,triggerData:l,chevronClassName:c,summaryAlign:u="center",rowClassName:O,disabled:d=!1,triggerLabel:f,triggerTooltip:p,tooltipClassName:m,trailing:g,onOpenChange:y})=>{const[v,S]=$.useState(n),Q=i!==void 0,b=Q?i:v,w=z=>{Q||S(z),y?.(z)},x=$.useId(),k=$.useRef(null),T=q("shrink-0",u==="firstLine"&&KOe),_=u==="firstLine"?"items-start":null,E=$.useRef(!1),R=$.useRef(!1),j=$.useRef(null),C=z=>{for(let M=z instanceof Element?z:null;M&&M!==k.current;M=M.parentElement)if(M.hasAttribute(BOe))return!0;return!1},W=z=>{if(E.current=C(z.target),R.current=!!window.getSelection()?.toString(),z.detail<=1){j.current=null;return}E.current&&j.current!==null&&(w(j.current),j.current=null)},G=z=>{const M=z.detail===0,te=R.current||!!window.getSelection()?.toString();!M&&E.current&&(te||z.detail>1)||(j.current=b,w(!b))},N=z=>{if(z.key!=="Escape")return;const M=window.getSelection();!M||M.isCollapsed||k.current?.contains(M.anchorNode)&&M.removeAllRanges()};if(d)return h.jsx("div",{...l,className:o,children:h.jsxs("div",{className:q(DG,_,"text-ink-dim",O),children:[a==="leading"&&h.jsx("span",{className:q("size-3.5",T),"aria-hidden":!0}),h.jsx("span",{className:"min-w-0 flex-1",children:e})]})});const Z=b?h.jsx(oS,{className:"size-3.5","aria-hidden":!0}):h.jsx(ale,{className:"size-3.5","aria-hidden":!0}),F=h.jsx(Yt,{content:p,side:"top",className:m,children:h.jsxs("button",{type:"button",...l,"aria-expanded":b,"aria-controls":t!=null?x:void 0,"aria-label":f,ref:k,onMouseDown:W,onClick:G,onKeyDown:N,className:q(DG,_,"cursor-pointer select-none","text-ink-dim transition-colors duration-fast ease-out-quart hover:text-ink-muted",O,s),children:[a==="leading"&&h.jsx("span",{className:q("flex text-ink-disabled",T,c),children:Z}),h.jsx("span",{className:"min-w-0 flex-1",children:e}),a==="trailing"&&h.jsx("span",{className:q("flex text-ink-disabled",T,c),children:Z})]})});return h.jsxs("div",{className:o,children:[g?h.jsxs("div",{className:q("group flex items-center"),children:[F,g]}):F,r&&t!=null?h.jsx(aYe,{id:x,open:b,indent:a==="leading",children:t}):b&&t!=null?h.jsx("div",{id:x,className:q("mt-1 flex flex-col gap-2 pb-1",a==="leading"&&HOe),children:t}):null]})},aYe=({id:e,open:t,indent:n,children:r})=>{const i=Ez("(prefers-reduced-motion: reduce)"),[a,o]=$.useState(t),[s,l]=$.useState(t);return $.useLayoutEffect(()=>{if(!t||i){l(t);return}o(!0);let c=requestAnimationFrame(()=>{c=requestAnimationFrame(()=>l(!0))});return()=>cancelAnimationFrame(c)},[t,i]),$.useEffect(()=>{if(t||!a)return;if(i){o(!1);return}const c=setTimeout(()=>o(!1),240);return()=>clearTimeout(c)},[t,a,i]),h.jsx("div",{id:e,"data-disclosure-body":"animated","aria-hidden":!t,...t?{}:{inert:""},className:q("grid overflow-hidden transition-[grid-template-rows,opacity] duration-base ease-out-quart motion-reduce:transition-none",s?"grid-rows-[1fr] opacity-100":"grid-rows-[0fr] opacity-0"),onTransitionEnd:c=>{!t&&c.target===c.currentTarget&&c.propertyName==="grid-template-rows"&&o(!1)},children:h.jsx("div",{className:q("min-h-0 overflow-hidden"),children:(t||a&&!i)&&h.jsx("div",{className:q("flex flex-col gap-2 pt-1 pb-1",n&&HOe),children:r})})})};function oYe(e,t){return typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<t?e:null}function sYe({className:e}){return h.jsxs("span",{className:q("inline-flex shrink-0 items-baseline gap-0.5 font-medium text-ink-muted text-meta",e),children:[h.jsx("span",{"aria-hidden":"true",children:"▸"}),"Recommended"]})}const MG="Files and images can't be attached to an answer yet. Type your answer here, or send the file in the chat.",lYe=`Answers stop at ${_j.toLocaleString("en-US")} characters; anything past that is not kept.`,JOe=e=>t=>{t.key!=="Enter"||t.shiftKey||t.nativeEvent.isComposing||(t.preventDefault(),!t.repeat&&e())},VG=({value:e,onChange:t,onEnter:n,disabled:r,ariaLabel:i,placeholder:a,questionId:o,fieldRef:s})=>{const[l,c]=$.useState(null);return h.jsxs("div",{className:"flex flex-col gap-1",children:[h.jsx(cf,{ref:s,"data-ask-other":o,value:e,disabled:r,"aria-label":i,placeholder:a,autoComplete:"off",maxLength:_j,onChange:u=>{c(null),t(u.target.value)},onKeyDown:JOe(n),onPaste:u=>{const O=u.clipboardData;if(!O)return;const d=Array.from(O.files??[]);if(!(d.length>0||Array.from(O.items??[]).some(y=>y.kind==="file")))return;const p=O.getData("text/plain"),m=d.map(y=>y.name),g=m.length>0&&p.split(`
515
515
  `).every(y=>m.includes(y.trim()));p.trim()!==""&&!g||(u.preventDefault(),c(MG))},onDragOver:u=>{u.dataTransfer?.types.includes("Files")&&(u.preventDefault(),u.dataTransfer.dropEffect="none")},onDrop:u=>{u.dataTransfer?.files?.length&&(u.preventDefault(),c(MG))},className:q("field-sizing-content max-h-40 min-h-14 rounded-md px-2 py-1.5 text-sm")}),l===null&&e.length<_j?null:h.jsx("output",{className:"block text-ink-muted text-xs",children:l??lYe})]})},cYe=e=>e==="answered"?"success":e==="late"?"warning":"neutral",uYe=e=>{switch(e){case"answered":case"late":return{Icon:xu,className:"text-success"};case"timed_out":return{Icon:fk,className:"text-ink-muted"};case"declined":case"dismissed":case"expired":return{Icon:ea,className:"text-ink-muted"};default:return{Icon:dk,className:"text-accent"}}},LG=({chosen:e,multi:t})=>h.jsx("span",{"aria-hidden":"true",className:q("mt-1 h-3 w-3 shrink-0 border",t?"rounded-[2px]":"rounded-full",e?"border-accent bg-accent":"border-control")}),FG="button[data-ask-option]:not([disabled]), input[data-ask-secret]:not([disabled]), textarea[data-ask-other]:not([disabled])",Q5="Type your answer",QS=e=>{if(e==null||(e.focus(),e.tagName!=="TEXTAREA"))return;const t=e,n=t.value.length;t.setSelectionRange(n,n)},OYe=({question:e,selected:t,secret:n,secretPlaceholder:r,disabled:i,onCell:a,onSecret:o,onAdvance:s,focusOtherRef:l})=>{const c=e.options??[],u=e.multi===!0,O=oYe(e.recommended,c.length),d=c.map(v=>v.label),[f,p]=$.useState(()=>qNe(t,d)),m=jNe(t,d,f),g=$.useRef(null);$.useLayoutEffect(()=>{l.current===e.id&&(l.current=null,QS(g.current))},[f.open]);const y=v=>{p(v),a(NG(m,u,v))};return h.jsxs("div",{className:"flex flex-col gap-1.5","data-lo-ask-question":e.id,children:[h.jsx("p",{className:"text-ink text-sm",children:e.question}),e.secret?h.jsx("input",{"data-ask-secret":e.id,type:"password",autoComplete:"off",autoCorrect:"off",spellCheck:!1,disabled:i,value:n,onChange:v=>o(v.target.value),onKeyDown:JOe(()=>s(e.id)),placeholder:r,"aria-label":`Your answer to: ${e.question}`,className:"w-full rounded-md border border-control bg-surface px-2 py-1.5 text-ink text-sm placeholder:text-ink-dim disabled:placeholder:text-ink-disabled"}):c.length>0?h.jsxs("div",{className:"flex flex-col",role:u?"group":"radiogroup",children:[c.map((v,S)=>{const Q=m.includes(v.label),b=O===S;return h.jsxs("button",{type:"button","data-ask-option":v.label,disabled:i,"aria-pressed":u?Q:void 0,"aria-checked":u?void 0:Q,role:u?"checkbox":"radio",onClick:()=>{if(!u){f.open&&p({...f,open:!1}),a([v.label]);return}a(NG(Q?m.filter(w=>w!==v.label):[...m,v.label],!0,f))},className:q("flex w-full items-baseline gap-2 rounded-sm px-2 py-1 text-left",Q?"bg-sunken":"hover:bg-sunken",i?"text-ink-dim":"text-ink"),children:[h.jsx(LG,{chosen:Q,multi:u}),h.jsxs("span",{className:"min-w-0 flex-1",children:[h.jsxs("span",{className:"flex items-baseline gap-x-2",children:[h.jsx("span",{className:q("min-w-0",b&&"font-semibold"),children:v.label}),b?h.jsx(sYe,{}):null]}),v.description?h.jsx("span",{className:"block text-ink-muted text-xs",children:v.description}):null]})]},v.label)}),h.jsxs("button",{type:"button","data-ask-option-other":"",disabled:i,"aria-pressed":u?f.open:void 0,"aria-checked":u?void 0:f.open,role:u?"checkbox":"radio",onClick:()=>{if(u&&f.open){y({...f,open:!1});return}l.current=e.id,f.open?QS(g.current):y({...f,open:!0})},className:q("flex w-full items-baseline gap-2 rounded-sm px-2 py-1 text-left",f.open?"bg-sunken":"hover:bg-sunken",i?"text-ink-dim":"text-ink"),children:[h.jsx(LG,{chosen:f.open,multi:u}),h.jsxs("span",{className:"min-w-0 flex-1",children:[h.jsx("span",{children:"Other"})," ",f.open?null:h.jsx("span",{className:"ml-1.5 text-ink-muted text-xs",children:Q5})]})]}),f.open?h.jsx("div",{className:"pt-1 pr-1 pb-1 pl-7",children:h.jsx(VG,{questionId:e.id,fieldRef:g,value:f.text,disabled:i,ariaLabel:`Your answer to: ${e.question}`,placeholder:Q5,onChange:v=>y({open:!0,text:v}),onEnter:()=>s(e.id)})}):null]}):h.jsx(VG,{questionId:e.id,fieldRef:g,value:f.text,disabled:i,ariaLabel:`Your answer to: ${e.question}`,placeholder:Q5,onChange:v=>y({open:!0,text:v}),onEnter:()=>s(e.id)})]})},dYe=({presentation:e,nowMs:t,answering:n,outcome:r,draft:i,onDraftChange:a,onAnswer:o,onDecline:s,onRevise:l,conversationOf:c})=>{const{ask:u,status:O,waiting:d,canAnswer:f,canDecline:p,delivering:m}=e,g=c===void 0?null:c(e),y=$.useMemo(()=>ne=>a(u.ask_id,ne(i)),[u.ask_id,i,a]),[v,S]=$.useState({}),Q=n||!!r?.sending,b=Q||!f,w=$.useMemo(()=>bb(u,i,v)!==null,[u,i,v]),x=uYe(O),k=x.Icon,T=u.urgent===!0&&d,[_,E]=$.useState(!1),[R,j]=$.useState(GOe),C=r?.refusedByOwner===!0,W=m&&!C;$.useEffect(()=>{r?.changed===!0&&E(!1)},[r?.changed]);const G=$.useMemo(()=>u.answers??{},[u.answers]),N=$.useMemo(()=>bb(u,R,v,G)!==null,[u,R,v,G]),Z=$.useRef(null),F=$.useRef(!1);$.useLayoutEffect(()=>{if(!F.current)return;F.current=!1;const ne=Z.current,le=ne?.querySelector("textarea[data-ask-other]:not([disabled])");QS(le??ne?.querySelector(FG))},[_]);const z=_&&W,M=z?R:i,te=z?G:void 0,U=z?ne=>j(ne):y,H=z?Q:b,D=()=>{const ne=bb(u,i,v);ne!==null&&o(u,ne)},V=()=>{if(l===void 0)return;const ne=bb(u,R,v,G);ne!==null&&l(u,ne)},se=ne=>{const le=u.questions.findIndex(Oe=>Oe.id===ne);if(!(le<0||H)&&Pj(u.questions[le],M,v,te)){if(z){N&&l!==void 0?V():B(le);return}w?D():B(le)}},B=ne=>{const le=u.questions.length;for(let Oe=1;Oe<le;Oe++){const Qe=u.questions[(ne+Oe)%le];if(Pj(Qe,M,v,te))continue;const we=[...Z.current?.querySelectorAll("[data-lo-ask-question]")??[]].find(He=>He.dataset.loAskQuestion===Qe.id);QS(we?.querySelector(FG));return}},K=$.useRef(null);return h.jsxs("div",{ref:Z,"data-lo-ask-row":u.ask_id,"data-lo-ask-status":O,"data-glass-block":"",className:"flex flex-col gap-2 rounded-md border border-hairline bg-surface p-3",children:[g===null?null:h.jsx("span",{"data-lo-ask-conversation":"",className:"truncate text-ink-dim text-meta",children:g}),h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx(k,{"aria-hidden":"true",className:q("shrink-0",T?"text-warning":x.className),size:16}),h.jsxs("span",{className:"min-w-0 flex-1 text-ink text-xs",children:[T?h.jsx("span",{className:"sr-only",children:"Urgent. "}):null,bNe(u,t)]}),h.jsx("span",{className:"shrink-0 text-ink text-xs",title:u.ask_id,children:" "})]}),!f&&!z?h.jsx("div",{className:"flex flex-col gap-1.5",children:dNe(u).map(ne=>{const le=u.questions.find(we=>we.id===ne.id),Oe=(le?.options??[]).map(we=>we.label),Qe=le?.secret!==!0&&Oe.length>0;return h.jsxs("div",{className:"flex flex-col gap-0.5",children:[h.jsx("span",{className:"text-ink-muted text-xs",children:ne.question}),ne.answers.length>0?ne.answers.map((we,He)=>h.jsxs("span",{className:"whitespace-pre-wrap break-words text-ink text-sm",children:[we,Qe&&!Oe.includes(we)?h.jsxs("span",{className:"text-ink-muted text-xs",children:[h.jsx("span",{"aria-hidden":"true",children:" · "}),"Other"]}):null]},`${He}:${we}`)):h.jsx("span",{className:"text-ink text-sm",children:"No answer given"})]},ne.id)})}):null,f||z?u.questions.map(ne=>h.jsx(OYe,{question:ne,selected:Rz(M,ne.id),secret:v[ne.id]??"",secretPlaceholder:RNe(u,ne,te),disabled:H,onCell:le=>U(Oe=>({...Oe,[ne.id]:le})),onSecret:le=>S(Oe=>({...Oe,[ne.id]:le})),onAdvance:se,focusOtherRef:K},ne.id)):null,r?.refused?h.jsx("output",{className:"block text-body-sm text-danger",children:r.refused}):null,r?.changed===!0?h.jsxs("p",{className:"flex items-start gap-1.5 text-xs",children:[h.jsx(xu,{"aria-hidden":"true",size:14,className:"mt-0.5 shrink-0 text-success"}),h.jsx("span",{className:"text-ink",children:"Changed — the agent has not been handed it yet."})]}):null,f||p?h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("button",{type:"button",disabled:b||!w,onClick:D,className:q("rounded-md px-3 py-1.5 text-sm",b||!w?"border border-hairline bg-surface text-ink-dim":"border border-transparent bg-accent text-on-accent hover:bg-accent-hover"),children:"Send answer"}),p?h.jsx("button",{type:"button",disabled:Q,onClick:()=>s(u),className:"rounded-md border border-transparent px-3 py-1.5 text-ink-muted text-sm hover:bg-sunken hover:text-ink",children:"Decline"}):null]}):null,W&&l!==void 0?h.jsx("div",{className:"flex flex-col gap-1.5",children:z?h.jsxs(h.Fragment,{children:[h.jsx("p",{className:"text-ink-dim text-meta",children:mNe}),h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("button",{type:"button",disabled:Q||!N,onClick:V,className:q("rounded-md px-3 py-1.5 text-sm",Q||!N?"border border-hairline bg-surface text-ink-dim":"border border-transparent bg-accent text-on-accent hover:bg-accent-hover"),children:"Update answer"}),h.jsx("button",{type:"button",disabled:Q,onClick:()=>E(!1),className:"rounded-md border border-transparent px-3 py-1.5 text-ink-muted text-sm hover:bg-sunken hover:text-ink",children:"Cancel"})]})]}):h.jsx("button",{type:"button",disabled:Q,onClick:()=>{j(CNe(u)),F.current=!0,E(!0)},className:"self-start rounded-md border border-control px-3 py-1.5 text-ink text-sm hover:bg-sunken",children:"Change answer"})}):null]})},BG="rounded-md border border-hairline",fYe=8e3,hYe=({view:e,onAnswer:t,onDecline:n,onRevise:r,answering:i=!1,outcomes:a,nowMs:o,drafts:s,onDraftChange:l,conversationOf:c,className:u})=>{if(!e.published)return null;const{pending:O,settled:d}=WG(e.rows),[f,p]=$.useState("all"),m=f!=="settled",g=f!=="outstanding",y=$.useRef(new Set);for(const H of e.rows)H.canAnswer&&y.current.add(H.ask.ask_id);const v=$.useRef(new Map),[,S]=$.useState(0),Q=()=>{y.current=new Set(e.rows.filter(H=>H.canAnswer).map(H=>H.ask.ask_id)),G(H=>({...H,text:""})),S(H=>H+1)},b=WG(e.rows,y.current),w=new Set(b.pending.filter(H=>H.lapsed).map(H=>H.ask.ask_id)),x=$.useRef(null),k=$.useRef(new Set),T=typeof document>"u"?null:document.activeElement,_=T!==null&&x.current?.contains(T)?T.closest("[data-lo-ask-row], [data-lo-ask-held]"):null,E=_?.getAttribute("data-lo-ask-held")??_?.getAttribute("data-lo-ask-row")??null,[R,j]=$.useState({seq:0,text:""}),C=$.useRef(s),[W,G]=$.useState({seq:0,text:"",from:null}),N=W.text,Z=$.useRef(null),F=$.useRef(0);$.useEffect(()=>{if(R.text==="")return;const H=setTimeout(()=>j(D=>({seq:D.seq,text:""})),fYe);return()=>clearTimeout(H)},[R]),$.useLayoutEffect(()=>{if(W.seq!==F.current){F.current=W.seq;const le=document.activeElement;(le===null||le===document.body||!le.isConnected||W.from!==null&&le.closest("[data-lo-ask-row]")?.getAttribute("data-lo-ask-row")===W.from)&&Z.current!==null&&Z.current.focus({preventScroll:!0})}const H=[...w].filter(le=>!k.current.has(le)),D=k.current;k.current=w;const V=new Map([...x.current?.querySelectorAll("[data-lo-ask-row]")??[]].map(le=>[le.getAttribute("data-lo-ask-row"),le]));for(const le of e.rows){if(!le.canAnswer)continue;const Oe=V.get(le.ask.ask_id)?.getBoundingClientRect().height??0;Oe>0&&v.current.set(le.ask.ask_id,Oe)}const se=H.filter(le=>Object.values(C.current[le]??s[le]??{}).some(Oe=>Oe.some(Qe=>Qe.trim()!==""))).length;C.current=s,se>0&&j(le=>({seq:le.seq+1,text:se===1?"That question timed out; your answer was not sent.":`${se} questions timed out; your answers were not sent.`}));const B=E;if(B===null||!w.has(B)||D.has(B))return;const K=document.activeElement;if(K!==null&&K!==document.body&&K.isConnected)return;if(f==="outstanding"){G(le=>({seq:le.seq+1,text:H.length===1?"Question timed out":`${H.length} questions timed out`,from:B}));return}[...x.current?.querySelectorAll("[data-lo-ask-held]")??[]].find(le=>le.getAttribute("data-lo-ask-held")===B)?.querySelector("button[aria-expanded]")?.focus({preventScroll:!0})});const z=H=>h.jsx(dYe,{presentation:H,nowMs:o,answering:i,outcome:a?.[H.ask.ask_id],draft:s[H.ask.ask_id]??GOe,onDraftChange:l,onAnswer:t,onDecline:n,onRevise:r,conversationOf:c},H.ask.ask_id),M=(H,{held:D=!1}={})=>{const V=vNe(H.status),se=H.ask.questions[0]?.question??"No question text",B=a?.[H.ask.ask_id]?.refused??null;return h.jsx($a,{triggerClassName:q("text-ink hover:bg-row-hover hover:text-ink",D&&"rounded-t-[9px]"),chevronClassName:"text-ink-dim",rowClassName:"min-h-7 py-1",triggerLabel:`${V} - ${se}`,summary:h.jsxs("span",{className:"flex min-w-0 flex-col gap-0.5",children:[h.jsxs("span",{className:"flex min-w-0 items-start gap-1.5",children:[h.jsx(Md,{variant:cYe(H.status),shape:"pill",className:"mt-px shrink-0",children:V}),h.jsx("span",{className:"min-w-0 whitespace-normal break-words text-ink text-meta",children:se})]}),B===null?null:h.jsx("span",{className:"min-w-0 text-danger text-meta",children:B})]}),children:h.jsx("div",{className:"pt-1.5",children:z(H)})},H.ask.ask_id)},te=h.jsx("fieldset",{"data-lo-ask-filter":f,"aria-label":"Filter asks",className:"m-0 flex items-center gap-1 border-0 p-0 px-1",children:[["all","All",e.rows.length],["outstanding","Pending",O.length],["settled","Settled",d.length]].map(([H,D,V])=>h.jsx("button",{type:"button","aria-pressed":f===H,onClick:()=>{Q(),p(H)},className:q("rounded-md px-2 py-0.5 text-meta transition-colors duration-fast ease-out-quart",f===H?"bg-sunken text-ink":"text-ink-muted hover:bg-row-hover hover:text-ink"),children:`${D} · ${V}`},H))}),U=e.rows.length===0?e.open>0?"The details for these asks could not be loaded.":"No asks outstanding. The agent is not waiting on anything.":f==="outstanding"&&O.length===0?"No asks are pending. They have all settled — see Settled.":f==="settled"&&d.length===0?"No asks have settled yet. They are all still pending.":null;return h.jsxs("div",{ref:x,"data-lo-ask-panel":"open",className:q("flex w-full flex-col gap-2",u),children:[e.rows.length>0?te:null,h.jsx("div",{"data-lo-ask-lapse-note":"","aria-live":"polite",className:"sr-only",children:R.text===""?null:h.jsx("span",{children:R.text},R.seq)}),U===null?null:h.jsx("p",{"data-lo-ask-empty":"",className:"px-3 py-2 text-ink-muted text-body",children:U}),f==="outstanding"&&N!==""?h.jsx("div",{ref:Z,"data-lo-ask-lapse-landing":"",tabIndex:-1,className:"sr-only",onKeyDown:H=>{H.target===H.currentTarget&&H.key===" "&&H.preventDefault()},onBlur:()=>G(H=>({...H,text:""})),children:N}):null,m?b.pending.map(H=>{const D=H.ask.ask_id;if(!w.has(D))return z(H);const V=v.current.get(D),se=V===void 0?void 0:{minHeight:`${V}px`};return f==="outstanding"?h.jsx("div",{"data-lo-ask-spacer":D,"aria-hidden":"true",className:BG,style:se},D):h.jsx("div",{"data-lo-ask-held":D,className:BG,style:se,children:M(H,{held:!0})},D)}):null,g&&(m?b.settled:d).length>0?h.jsxs("div",{"data-lo-ask-settled":"",className:"flex flex-col gap-1 pb-1",children:[m&&b.pending.length>0?h.jsx("p",{className:"px-3 pt-1 text-ink-dim text-meta",children:"Settled"}):null,(m?b.settled:d).map(H=>M(H))]}):null]})},HG='a[href]:not([aria-disabled="true"]), button:not([disabled]):not([aria-disabled="true"]), [tabindex]:not([tabindex="-1"]):not([aria-disabled="true"]), input:not([disabled]):not([aria-disabled="true"]), select:not([disabled]):not([aria-disabled="true"]), textarea:not([disabled]):not([aria-disabled="true"])',pYe="[data-lo-ask-panel]",mYe="[data-lo-ask-row], [data-lo-ask-settled]",kS="[data-conversation-actions]",KG=e=>e.matches(kS)?e:document.querySelector(kS),gYe=e=>e===document.body||e.matches(kS),$Ye=8,yYe=({frontend:e,scope:t,onClose:n,onAnswer:r,onDecline:i,onRevise:a,answering:o=!1,outcomes:s,drafts:l,onDraftChange:c,conversationOf:u,nowMs:O})=>{const d=yk(e,s),f=FOe(d.open>0,O),p=$.useRef(null),m=d.unread,g=Jn(C=>C.askOpenIntent),y=Jn(C=>C.clearAskOpenIntent),v=$.useRef(!1),S=$.useRef(null),Q=$.useRef(!1);$.useEffect(()=>{if(Q.current)return;if(d.rows.length>0||d.open>0){S.current=!0;return}if(m)return;const C=S.current===!0;if(S.current=!1,C){Q.current=!0,n();return}v.current||(Q.current=!0,n())},[d.rows.length,d.open,m,n]);const b=$.useRef(!1),w=$.useRef(!1),x=$.useRef({attempts:0,handler:null,menu:null,menuGone:!1,beat:null,beatMaySettle:!1,observer:null}),k=$.useRef(!1),T=$.useRef(null),_=$.useCallback(()=>{const C=x.current;C.handler!==null&&(document.removeEventListener("focusin",C.handler,!0),C.handler=null),C.beat!==null&&(clearTimeout(C.beat),C.beat=null),C.observer?.disconnect(),C.observer=null},[]),E=$.useCallback(()=>{const C=x.current;if(C.handler!==null||k.current)return;C.attempts=0,C.menu=document.querySelector('[role="menu"]'),C.menuGone=C.menu===null||!C.menu.isConnected;const W=()=>{k.current=!0,_()},G=()=>C.menu===null||!C.menu.isConnected,N=F=>{C.beat!==null&&clearTimeout(C.beat),C.beatMaySettle=F,C.beat=setTimeout(()=>{if(C.beat=null,!k.current&&G()&&p.current?.contains(document.activeElement)){if(!C.beatMaySettle){N(!0);return}W()}},0)};if(C.menu!==null&&!C.menuGone&&typeof MutationObserver<"u"){const F=new MutationObserver(()=>{k.current||C.menu!==null&&!C.menu.isConnected&&(C.menuGone=!0,F.disconnect(),C.observer=null,N(!1))});F.observe(document.body,{childList:!0,subtree:!0}),C.observer=F}const Z=F=>{const z=F.target;if(z!==null){if(p.current?.contains(z)){N(!1);return}if(z.matches(kS)){if(C.attempts>=$Ye){W();return}C.attempts+=1;const M=T.current;(M?.isConnected?M:p.current)?.focus();return}z.closest('[role="menu"]')!==null||z.closest("[data-radix-popper-content-wrapper]")!==null||z.closest("[data-radix-focus-guard]")!==null||W()}};C.handler=Z,document.addEventListener("focusin",Z,!0)},[_]),R=$.useRef(!1),j=$.useRef(null);return $.useLayoutEffect(()=>{if(b.current&&w.current&&E(),R.current)return;const C=document.activeElement;if(C===null||typeof C.matches!="function")return;const W=C.matches(AOe)||C.matches(cNe)?C:null;g?.scope===t&&(y(t),b.current=!0,w.current=g.via==="menu",w.current&&(j.current=KG(C),E()));const G=W===null&&b.current;(W!==null||G)&&(v.current=!0);const N=p.current;if(N===null||(W!==null||G)&&m||(R.current=!0,W===null&&!G)||(W!==null&&(j.current=W),w.current&&(j.current??=KG(C)),W===null&&!gYe(C)))return;const Z=N.querySelector(pYe),F=Z?.querySelector(mYe),z=F?.querySelector(HG)??F??Z?.querySelector(HG)??N;T.current=z,z.focus()}),$.useEffect(()=>()=>{_(),y(t),queueMicrotask(()=>{const C=document.activeElement;if(C!==null&&C!==document.body)return;const W=j.current;if(W!==null){W.isConnected&&W.focus();return}rYe()})},[y,_,t]),h.jsxs("section",{ref:p,"aria-label":t==="fleet"?"All asks":"This conversation's asks","data-lo-ask-surfaces":"","data-glass-region":"pane","data-ask-drawer":t,tabIndex:-1,className:q("flex h-full flex-col bg-elevated"),onKeyDown:C=>{C.key==="Escape"&&(C.preventDefault(),n())},children:[h.jsxs("div",{className:q("flex h-10 shrink-0 items-center justify-between gap-2 px-2","[padding-inline-end:max(0.5rem,var(--chrome-inset-end-pane,var(--chrome-inset-end)))]"),children:[h.jsx("span",{className:"truncate text-ink-muted text-xs","data-ask-scope":"",children:nNe(t,d)}),h.jsx(Yt,{content:"Close asks",children:h.jsx(Xe,{variant:"ghost",size:"icon-sm","aria-label":"Close asks",onClick:()=>n({dismissSlot:!0}),"data-tour-tag":"close-asks-button",children:h.jsx(p9e,{"aria-hidden":"true"})})})]}),h.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-y-auto px-3 py-2",children:d.published?h.jsx(hYe,{view:d,nowMs:f,answering:o,outcomes:s,drafts:l??xNe,onDraftChange:c??QNe,onAnswer:(C,W)=>r?.(C.ask_id,W),onDecline:C=>i?.(C.ask_id),onRevise:a===void 0?void 0:(C,W)=>a(C.ask_id,W),conversationOf:u}):h.jsx("p",{className:"text-ink-muted text-body",children:m?KWe:eNe})})]})},vYe={},bYe=({onClose:e})=>{const{rows:t,frontend:n}=VNe(),{client:r}=oo(),i=$.useRef(SUe()).current,[a,o]=$.useState(vYe),[s,l]=$.useState({}),[c,u]=$.useState(!1),O=ar(w=>w.sessions),d=$.useMemo(()=>{const w=new Map;for(const x of O){const k=x.title;typeof k=="string"&&k.trim().length>0&&w.set(x.session_id,k)}return w},[O]),f=$.useMemo(()=>DNe(t??[],w=>d.get(w)),[t,d]),p=$.useCallback(w=>f.get(w.ask.ask_id)??null,[f]),m=$.useCallback(()=>{r.invalidateQueries({queryKey:VOe})},[r]);$.useEffect(()=>{const w=x=>{x.key!=="Escape"||x.isComposing===!0||x.defaultPrevented!==!0&&(X$(x.target)||(x.preventDefault(),e()))};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[e]);const g=$.useCallback((w,x)=>{const k=f.get(x);Of(k?`${w} ${k}`:w)},[f]),y=$.useCallback((w,x,k,T=!1)=>{const _=x.status==="failed"?{refused:UNe(x.error),refusedByOwner:WNe(x.error)}:{refused:null};l(E=>({...E,[w]:{sending:!1,..._,...T?{changed:!0}:{}}})),x.status==="sent"&&(g(k,w),m())},[g,m]),v=$.useCallback((w,x)=>{const k=v5(t??[],w);!k||i.held||(u(!0),l(T=>({...T,[w]:{sending:!0,refused:null}})),(async()=>{let T;try{T=await UUe({taskId:w,answers:x,sessionId:k,lock:i},_=>Re(_))}finally{u(!1)}y(w,T,"Answer sent to")})())},[i,t,y]),S=$.useCallback((w,x)=>{const k=v5(t??[],w);!k||i.held||(u(!0),l(T=>({...T,[w]:{sending:!0,refused:null}})),(async()=>{let T;try{T=await WUe({taskId:w,answers:x,sessionId:k,lock:i},_=>Re(_))}finally{u(!1)}y(w,T,"Answer changed for",!0)})())},[i,t,y]),Q=$.useCallback(w=>{const x=v5(t??[],w);!x||i.held||(u(!0),l(k=>({...k,[w]:{sending:!0,refused:null}})),(async()=>{let k;try{k=await NUe({taskId:w,sessionId:x,lock:i},T=>Re(T))}finally{u(!1)}y(w,k,"Declined the ask in")})())},[i,t,y]),b=$.useCallback((w,x)=>{o(k=>({...k,[w]:x}))},[]);return h.jsx(yYe,{frontend:n,scope:"fleet",onClose:e,onAnswer:v,onDecline:Q,onRevise:S,answering:c,outcomes:s,drafts:a,onDraftChange:b,conversationOf:p})},wYe=48*60*60*1e3;var Zc=(e=>(e.UI="ui",e.BACKEND="backend",e))(Zc||{});const tun=ta()(lc((e,t)=>({uiDeferredVersion:null,uiDeferredAt:null,backendDeferredVersion:null,backendDeferredAt:null,hydrated:!1,deferUpdate:(n,r)=>{e(n==="ui"?{uiDeferredVersion:r,uiDeferredAt:Date.now()}:{backendDeferredVersion:r,backendDeferredAt:Date.now()})},shouldShowUpdate:(n,r)=>{const{uiDeferredVersion:i,uiDeferredAt:a,backendDeferredVersion:o,backendDeferredAt:s}=t();let l,c;return n==="ui"?(l=i,c=a):(l=o,c=s),!l||!c||l!==r?!0:Date.now()-c>wYe},clearDeferredUpdate:n=>{if(n==="ui")e({uiDeferredVersion:null,uiDeferredAt:null});else if(n==="backend")e({backendDeferredVersion:null,backendDeferredAt:null});else throw new Error(`Invalid update type: ${n}`)}}),{name:"deferred-updates-storage",onRehydrateStorage:()=>e=>{e&&typeof e=="object"&&"setState"in e&&typeof e.setState=="function"&&e.setState({hydrated:!0})}})),SYe=["patch","minor","major"],JG="patch",xYe=/^v?(\d+)\.(\d+)\.(\d+)/,eI=e=>{if(typeof e!="string")return null;const t=xYe.exec(e.trim());return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null},QYe=(e,t)=>e[0]!==t[0]?e[0]>t[0]:e[1]!==t[1]?e[1]>t[1]:e[2]>t[2],kYe=(e,t)=>e[0]===0&&t[0]===0?e[1]!==t[1]:e[0]!==t[0],PYe=(e,t)=>e[0]!==t[0]||e[1]!==t[1],_Ye=(e,t,n)=>{const r=eI(t),i=eI(n);return!r||!i||!QYe(i,r)?!1:e==="major"?kYe(r,i):e==="minor"?PYe(r,i):!0},TYe=e=>typeof e=="string"&&SYe.includes(e),RYe=[Zc.UI,Zc.BACKEND],Fo=e=>({[Zc.UI]:e(Zc.UI),[Zc.BACKEND]:e(Zc.BACKEND)}),XYe=(e,t)=>{const n=e.offers[t];return!n||e.detailOpen[t]?!1:_Ye(e.followed[t],e.running[t],n.version)},nd=ta()(lc((e,t)=>({followed:Fo(()=>JG),running:Fo(()=>null),offers:Fo(()=>null),detailOpen:Fo(()=>!1),noticeOpen:!1,inflight:Fo(()=>!1),downloadPercent:Fo(()=>null),setFollowedSegment:(n,r)=>e(i=>({followed:{...i.followed,[n]:r}})),followedSegment:n=>t().followed[n],noteRunningVersion:(n,r)=>e(i=>({running:{...i.running,[n]:r}})),noteQuietOffer:(n,r)=>e(i=>({offers:{...i.offers,[n]:r}})),clearQuietOffer:n=>e(r=>{const i={...r.offers,[n]:null};return{offers:i,noticeOpen:Object.values(i).some(a=>a!==null)&&r.noticeOpen}}),openNotice:()=>e({noticeOpen:!0}),dismissNotice:()=>e({noticeOpen:!1}),noteInFlight:(n,r)=>e(i=>({inflight:{...i.inflight,[n]:r}})),noteDownloadPercent:(n,r)=>e(i=>({downloadPercent:{...i.downloadPercent,[n]:r}})),clearSurface:n=>e(r=>{const i={...r.offers,[n]:null};return{offers:i,detailOpen:{...r.detailOpen,[n]:!1},noticeOpen:Object.values(i).some(a=>a!==null)&&r.noticeOpen}}),openDetail:n=>e(()=>({detailOpen:Fo(r=>r===n)})),closeDetail:n=>e(r=>({detailOpen:{...r.detailOpen,[n]:!1}})),resetNotices:()=>e({offers:Fo(()=>null),detailOpen:Fo(()=>!1),noticeOpen:!1,inflight:Fo(()=>!1),downloadPercent:Fo(()=>null)})}),{name:"update-notice-storage",storage:SRe(()=>{if(typeof localStorage>"u"||localStorage===null)throw new Error("no localStorage in this environment");return localStorage}),partialize:e=>({followed:e.followed}),merge:(e,t)=>{const n=e??{},r=Fo(i=>{const a=n.followed?.[i];return TYe(a)?a:JG});return{...t,followed:r}}})),ede={get[Zc.UI](){return J("ui.common.updates.update_quiet_indicator.application_update")},get[Zc.BACKEND](){return J("ui.common.updates.update_quiet_indicator.server_update")}},EYe=e=>`${ede[e.type]} ${e.version}`,nun=e=>ede[e],tI=e=>`${EYe(e)} available`,qYe=({offers:e,onOpen:t,onDismiss:n,className:r})=>{br();const i=e.length===0;return h.jsxs("output",{"data-update-indicator":"","data-glass-region":"sidebar","data-update-indicator-count":e.length,onKeyDown:a=>{a.key==="Escape"&&(a.stopPropagation(),n())},className:i?void 0:q("flex h-7 shrink-0 items-center gap-1 border-t border-hairline bg-surface px-2",r),children:[e.map((a,o)=>h.jsxs($.Fragment,{children:[o>0&&h.jsx("span",{className:"sr-only",children:", "}),h.jsxs("button",{type:"button","data-update-indicator-open":a.type,"aria-label":`${tI(a)}. Open release details.`,className:q("flex h-6 items-center gap-1.5 rounded-md px-1.5 text-meta text-accent","hover:bg-row-hover","focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-0!"),onClick:()=>t(a.type),children:[h.jsx(LAe,{className:"size-3.5 shrink-0","aria-hidden":"true"}),h.jsx("span",{className:"whitespace-nowrap",children:tI(a)})]},a.type)]},a.type)),!i&&h.jsx("button",{type:"button","data-update-indicator-dismiss":"","aria-label":J("ui.common.updates.update_quiet_indicator.dismiss_update_notice"),onClick:n,className:q("flex h-6 items-center rounded-md px-1.5 text-ink-muted","hover:bg-row-hover hover:text-ink","focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-0!"),children:h.jsx(ea,{className:"size-3.5 shrink-0","aria-hidden":"true"})})]})},jYe=()=>{document.querySelector("[data-update-foot-icon]")?.focus()},CYe=()=>{const e=nd(u=>u.followed),t=nd(u=>u.running),n=nd(u=>u.offers),r=nd(u=>u.detailOpen),i=nd(u=>u.openDetail),a=nd(u=>u.noticeOpen),o=nd(u=>u.dismissNotice),s=$.useCallback(()=>{o(),jYe()},[o]);$.useLayoutEffect(()=>{a&&document.querySelector("[data-update-indicator] button")?.focus()},[a]);const l=$.useMemo(()=>{const u={followed:e,running:t,offers:n,detailOpen:r};return RYe.filter(O=>XYe(u,O)).map(O=>({type:O,version:n[O]?.version??""}))},[e,t,n,r]),c=$.useCallback(u=>i(u),[i]);return h.jsx(qYe,{offers:a?l:[],onOpen:c,onDismiss:s})},tde=$.createContext(null),run=({children:e})=>{const t=$.useContext(tde);return t?Yq.createPortal(e,t):null},nde=$.forwardRef(({width:e,minWidth:t=0,tourTag:n,children:r,...i},a)=>h.jsx("div",{ref:a,style:{minWidth:t,width:e},"data-tour-tag":n,className:q("relative h-full overflow-hidden transition-[width] duration-base ease-out-quart"),...i,children:r}));nde.displayName="PaneSlot";const AYe=200;let nO=null;const zYe=e=>{nO||(nO=document.createElement("div"),Object.assign(nO.style,{position:"fixed",top:"0",left:"0",width:"100vw",height:"100vh",zIndex:"9999"}),document.body.appendChild(nO)),nO.style.cursor=e},UYe=()=>{nO&&(document.body.removeChild(nO),nO=null)},nI=({sidebarWidth:e,onSidebarWidthChange:t,minWidth:n=180,maxWidth:r=600,orientation:i="vertical",side:a="right",onDoubleClick:o,label:s,homeEnd:l="axis"})=>{const c=i==="horizontal",[u,O]=$.useState(!1),[d,f]=$.useState(!1),p=$.useRef(!1),m=$.useRef(null);$.useEffect(()=>()=>{m.current&&clearTimeout(m.current)},[]);const g=S=>{const Q=KNe(S.key,{shiftKey:S.shiftKey,value:e,min:n,max:r,side:a,homeEnd:l});if(Q!==void 0&&!(Q===null&&!o)){if(S.preventDefault(),S.stopPropagation(),Q===null){o?.();return}t(Q)}},y=S=>{S.preventDefault(),p.current=!0,f(!0);const Q=S.clientX,b=S.clientY,w=e;document.body.style.userSelect="none",zYe(c?"row-resize":"col-resize");const x=T=>{if(!p.current)return;const _=c?T.clientY-b:T.clientX-Q;t(f0(w,_,a,n,r))},k=()=>{p.current&&(p.current=!1,f(!1),O(!1),document.body.style.userSelect="",UYe(),window.removeEventListener("mousemove",x),window.removeEventListener("mouseup",k),window.removeEventListener("blur",k),document.documentElement.removeEventListener("mouseleave",k))};window.addEventListener("mousemove",x),window.addEventListener("mouseup",k),window.addEventListener("blur",k),document.documentElement.addEventListener("mouseleave",k)},v=u||d;return h.jsxs("div",{className:q("relative z-10 shrink-0",c?"h-0 w-full":"h-full w-0"),children:[h.jsx("div",{"aria-hidden":"true",className:q("pointer-events-none absolute z-12",c?"left-0 h-0.5 w-full":"top-0 h-full w-0.5","transition-[opacity,background-color] duration-fast ease-out-quart",c?a==="top"?"top-0":"bottom-0":a==="left"?"left-0":"right-0",d?"bg-accent":"bg-control",v?"opacity-100":"opacity-0")}),h.jsx("div",{role:"separator","aria-label":s,"aria-orientation":c?"horizontal":"vertical","aria-valuenow":Math.round(e),"aria-valuemin":n,"aria-valuemax":r,tabIndex:0,className:q("absolute z-11 touch-none",c?"left-0 h-2.5 w-full cursor-row-resize":"top-0 h-full w-3 cursor-col-resize",c?a==="top"?"-top-[5px]":"-bottom-[5px]":a==="left"?"-left-1.5":"-right-1.5"),onMouseEnter:()=>{m.current&&clearTimeout(m.current),m.current=setTimeout(()=>O(!0),AYe)},onMouseLeave:()=>{m.current&&clearTimeout(m.current),p.current||O(!1)},onFocus:()=>O(!0),onBlur:()=>{p.current||O(!1)},onKeyDown:g,onMouseDown:y,onDoubleClick:o})]})};function WYe(e){const[t,n]=$.useState({width:0,left:0});return $.useLayoutEffect(()=>{const r=e.current;if(!r)return;const i=()=>{const o=r.getBoundingClientRect();n({width:o.width,left:o.left})};i();const a=new ResizeObserver(i);return a.observe(r),()=>a.disconnect()},[e]),t}const NYe="data-sidebar-sheet",rde="data-lane-leading-column",ide=$.createContext(null),iun=e=>{const t=$.useContext(ide);return $.useCallback(n=>{n&&t&&n.setAttribute(rde,e),t?.(n)},[t,e])},YYe=e=>e.getAttribute(rde)==="elevated"?"elevated":"surface";function GYe(e,t,n){const[r,i]=$.useState(null);return $.useLayoutEffect(()=>{const a=e.current;if(!a||!t){i(null);return}const o=()=>{const l={edge:Math.round((t.getBoundingClientRect().right-a.getBoundingClientRect().left)*100)/100,ground:YYe(t)};i(c=>c!==null&&c.edge===l.edge&&c.ground===l.ground?c:l)},s=new ResizeObserver(o);return s.observe(t),o(),()=>s.disconnect()},[t,e,n]),r}const Xj=$.createContext(null),aun=()=>{const e=$.useContext(Xj);if(!e)throw new Error("useSidebarFrame: the sidebar must be rendered inside ChatLayout (app.tsx)");return e},oun=({sidebar:e,content:t})=>{const n=Jn(te=>te.chatSidebarWidth),r=Jn(te=>te.setChatSidebarWidth),i=Jn(te=>te.restoreDefaultChatSidebarWidth),a=Jn(te=>te.isSidebarCollapsed),o=Jn(te=>te.toggleSidebar),[s,l]=$.useState(()=>typeof window>"u"?1380:window.innerWidth),[c,u]=$.useState(!1),O=$.useRef(null),[d,f]=$.useState(null);$.useEffect(()=>{const te=()=>l(window.innerWidth);return window.addEventListener("resize",te),()=>window.removeEventListener("resize",te)},[]);const p=Jn(te=>te.isAskDrawerOpen),m=Jn(te=>te.askDrawerScope),g=Jn(te=>te.setAskDrawerOpen),y=Jn(te=>te.setRightSlotWidth),v=Jn(te=>te.restoreDefaultRightSlotWidth),S=p&&m==="fleet",Q=Jn(xRe),w=Jn(te=>te.rightSlotRoute.mounted)?RRe:0,[x,k]=$.useState(null),T=QRe(s,a,c,n,Q,w);$.useEffect(()=>{c&&!T.sheetOpen&&u(!1)},[c,T.sheetOpen]);const _=$.useCallback(te=>{if(!kRe(te))return;const U=te.target;!(typeof U?.closest=="function"&&U.closest(`[${NYe}]`))&&X$(te.target)||(te.preventDefault(),s>=UN?o():u(D=>!D))},[o,s]);$.useEffect(()=>(document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)),[_]);const E=$.useCallback(te=>{const U=fUe(te);if(U===null||X$(te.target))return;const H=pUe(document,nOe(document.activeElement),U);H!==null&&(te.preventDefault(),mUe(document,H))},[]);$.useEffect(()=>(document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)),[E]);const R=T.mode==="docked"?T.width:PRe,j=$.useRef(null),C=WYe(j),W=Jn(te=>_Re(C.width,te)),G=TRe(C.width||Number.MAX_SAFE_INTEGER)==="docked",N=C.width>0?C.left+C.width-W:0,Z=C.width>0?C.left+C.width:0,F=GYe(O,d,R),z=Math.max(R,F?.edge??0),M=F?.ground??"surface";return h.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",style:{"--panel-rail-w":`${w}px`,"--chrome-inset-end-pane":`max(0px, calc(var(--chrome-inset-end) - ${w}px))`},children:[h.jsx("div",{ref:O,"data-titlebar-lane":"","data-titlebar-drag":"","data-slot-edge":N,className:"h-8 shrink-0",style:{background:M==="surface"?`linear-gradient(to right, var(--lo-surface) ${z}px, var(--lo-canvas) ${z}px, var(--lo-canvas) ${N}px, var(--lo-elevated) ${N}px, var(--lo-elevated) ${Z}px, var(--lo-surface) ${Z}px)`:`linear-gradient(to right, var(--lo-surface) ${R}px, var(--lo-${M}) ${R}px, var(--lo-${M}) ${z}px, var(--lo-canvas) ${z}px, var(--lo-canvas) ${N}px, var(--lo-elevated) ${N}px, var(--lo-elevated) ${Z}px, var(--lo-surface) ${Z}px)`}}),h.jsxs("div",{className:"flex min-h-0 flex-1 overflow-hidden",children:[h.jsx("div",{className:"h-full shrink-0",style:{width:R},children:h.jsx(Xj.Provider,{value:{expanded:T.mode==="docked",mode:T.mode==="docked"?"docked":"strip",onCollapse:s>=UN?o:()=>u(!0)},children:T.sheetOpen?h.jsx(IYe,{}):e})}),T.resizable&&h.jsx(nI,{sidebarWidth:T.width,onSidebarWidthChange:r,minWidth:qRe,maxWidth:ERe,onDoubleClick:i,label:`Resize the sidebar (${XRe(ZYe())})`}),h.jsx("div",{ref:j,className:"flex h-full min-w-0 grow flex-col overflow-hidden",children:h.jsx(ide.Provider,{value:f,children:h.jsx(tde.Provider,{value:x,children:h.jsxs("div",{className:"flex h-full min-h-0 w-full overflow-hidden",children:[t,S&&h.jsxs(h.Fragment,{children:[G&&h.jsx(nI,{sidebarWidth:W,onSidebarWidthChange:y,minWidth:WN,maxWidth:Math.max(WN,jRe(C.width)),side:"left",onDoubleClick:v,label:"Resize asks. Double-click resets the shared pane width."}),h.jsx(nde,{width:W,tourTag:"ask-fleet-slot","data-ask-mode":G?"docked":"overlay",children:h.jsx(bYe,{onClose:te=>g(!1,"fleet",te)})})]})]})})})}),h.jsx("div",{ref:k,"data-panel-rail-host":"","data-glass-region":"sidebar",className:"h-full shrink-0 bg-surface",style:{width:w}})]}),h.jsx(CYe,{}),h.jsx(FRe,{open:T.sheetOpen,onOpenChange:te=>{te||u(!1)},children:h.jsxs(BRe,{side:"left","data-sidebar-sheet":"",showClose:!1,className:q("w-[260px] max-w-none gap-0 border-0 bg-surface p-0","pt-[var(--chrome-strip-h)]"),"aria-describedby":void 0,children:[h.jsx(HRe,{className:"sr-only",children:"Chats and destinations"}),h.jsx(Xj.Provider,{value:{expanded:!0,mode:"overlay",onCollapse:()=>u(!1)},children:e})]})})]})},IYe=()=>h.jsx("div",{"aria-hidden":"true","data-glass-region":"sidebar",className:"h-full bg-surface"}),ZYe=()=>typeof navigator<"u"&&navigator.platform.toUpperCase().indexOf("MAC")>=0,DYe=({open:e,onClose:t,autoHideDuration:n,variant:r="info",role:i,action:a,children:o})=>{if(br(),$.useEffect(()=>{if(!e||n===void 0)return;const l=window.setTimeout(t,n);return()=>window.clearTimeout(l)},[e,n,t]),!e)return null;const s=i??(r==="danger"||r==="warning"?"alert":"status");return h.jsxs("div",{className:"fixed right-4 bottom-4 z-50 w-100 max-w-[calc(100vw-2rem)]",children:[h.jsxs(Ll,{variant:r,role:s,className:"relative pr-10 shadow-overlay",children:[o,a?h.jsx("div",{className:"flex justify-end gap-2 pt-1",children:a}):null]}),h.jsx(Xe,{variant:"ghost",size:"icon-sm",onClick:t,"aria-label":J("ui.common.connection.floating_alert.dismiss"),className:"absolute top-1.5 right-1.5",children:h.jsx(ea,{})})]})};DYe.displayName="FloatingAlert";function k5(e){return e>=9995e5?`${(e/1e9).toFixed(1)} GB`:e>=999500?`${(e/1e6).toFixed(1)} MB`:`${Math.round(e/1e3)} KB`}const qz="000000000000",jz="00000000-0000-0000-0000-000000000000";function Ej(e,t){const n=BQ({op:"sessions.message",sessionId:qz,requestId:jz,text:e,images:t,mode:"prompt"});return new TextEncoder().encode(JSON.stringify(n.body)).length}function E$(e,t){const n=k5(e);if(n!==k5(t))return[n,k5(t)];const r=n.endsWith("MB"),i=r?1e6:1e3,a=r?"MB":"KB";for(const o of[2,3]){const s=(e/i).toFixed(o),l=(t/i).toFixed(o);if(s!==l)return[`${s} ${a}`,`${l} ${a}`]}return[`${e.toLocaleString()} bytes`,`${t.toLocaleString()} bytes`]}function sun(e,t,n=HQ){if(t.length>Qp)return`This command is ${t.length.toLocaleString()} characters, more than the ${Qp.toLocaleString()} one command can carry. Shorten it, or put the text in a message instead.`;const r=BQ({op:"sessions.command",sessionId:qz,requestId:jz,command:e,args:t}),i=new TextEncoder().encode(JSON.stringify(r.body)).length;if(i<=n)return null;const[a,o]=E$(i,n);return`This command is ${a}, more than the ${o} one command can carry. Shorten it, or put the text in a message instead.`}function lun(e,t=CRe){if(e.length>NN)return`This system prompt is ${e.length.toLocaleString()} characters, more than the ${NN.toLocaleString()} one agent can carry. Shorten it.`;const n=new TextEncoder().encode(JSON.stringify({system_prompt:e})).length;if(n<=t)return null;const[r,i]=E$(n,t);return`This system prompt is ${r}, more than the ${i} one agent can carry. Shorten it.`}function MYe(e,t=HQ){if(e.length>Qp)return`This first message is ${e.length.toLocaleString()} characters, more than the ${Qp.toLocaleString()} one message can carry. Shorten it, or send it in the new conversation instead.`;const n=BQ({op:"sessions.fork",sessionId:qz,requestId:jz,message:e,boundary:"next_safe"}),r=new TextEncoder().encode(JSON.stringify(n.body)).length;if(r<=t)return null;const[i,a]=E$(r,t);return`This first message is ${i}, more than the ${a} one message can carry. Shorten it, or send it in the new conversation instead.`}function cun(e,t,n=HQ){if(e.length>Qp)return`This message is ${e.length.toLocaleString()} characters, more than the ${Qp.toLocaleString()} one message can carry. Split it across two messages.`;const r=Ej(e,t);if(r<=n)return null;const i=Ej(e,[]),a=r-i;if(t.length&&a>=i){const[l,c]=E$(a,n);return`These images total ${l}, more than the ${c} one message can carry. Remove an image, or send them in a second message.`}const[o,s]=E$(i,n);return`This message is ${o} of text, more than the ${s} one message can carry. Split it across two messages.`}const ri={settings:["desktop","settings"],capabilities:["desktop","capabilities"],providers:["desktop","auth","providers"],commands:["desktop","commands"],accounts:["desktop","auth","accounts"],catalogue:["desktop","models"],credentials:e=>["desktop","credentials",e]},VYe=3e4,LYe=15e3;function FYe(e){return e?.desktop_available===!0}function Ri(){const{client:e,provided:t}=oo();return jt({enabled:t,queryKey:ri.capabilities,queryFn:async()=>{try{return await Re({op:"capabilities"})}catch(n){throw n instanceof Error?n:new Error(String(n))}},staleTime:6e4,retry:!1,refetchInterval:n=>FYe(n.state.data)?VYe:LYe,refetchIntervalInBackground:!0},e)}function ade(e,t,n=1){return e?e.desktop_available?(e.features?.[t]??0)>=n?"enabled":"below-version":"unpaired":"unknown"}function oi(e,t,n=1){return ade(e,t,n)==="enabled"}function Cz(e){return jt({queryKey:ri.providers,queryFn:()=>Re({op:"providers.list"}).then(t=>t.providers),enabled:e,staleTime:3e4,retry:Ua})}var BYe=(e=>(e.CONNECT_PROVIDER="connect_provider",e.DEFAULT_MODEL="default_model",e.EXTRAS="extras",e))(BYe||{});const uun=ta()(lc((e,t)=>({isModalComplete:!1,isTourComplete:!1,currentStep:"connect_provider",isModalActive:!1,completeModalOnboarding:()=>{e({isModalComplete:!0,isModalActive:!1,isTourComplete:!0})},completeTourOnboarding:()=>{e({isTourComplete:!0})},setCurrentStep:n=>{e({currentStep:n})},activateModalOnboarding:()=>{e({isModalActive:!0})},deactivateModalOnboarding:()=>{e({isModalActive:!1})},resetOnboarding:()=>{e({isModalComplete:!1,isTourComplete:!1,currentStep:"connect_provider",isModalActive:!1})}}),{name:"onboarding-storage",partialize:e=>({isModalComplete:e.isModalComplete,isTourComplete:e.isTourComplete,currentStep:e.currentStep}),merge:(e,t)=>{const{isModalActive:n,...r}=e??{};return{...t,...r}},onRehydrateStorage:()=>(e,t)=>{t?console.error("Failed to rehydrate onboarding store:",t):e&&JSON.parse(localStorage.getItem("onboarding-storage")||"{}")?.state?.isComplete===!0&&!e.isModalComplete&&(console.log("Migrating old 'isComplete:true' state to 'isModalComplete:true'"),e.isModalComplete=!0)}}));function qj(e){return e.some(t=>!t.local&&!t.credential_optional&&(t.configured||t.has_credential))}function Oun(e){return e.onboardingComplete?"returning":e.census.status==="loading"||e.census.status==="failed"?"pending":e.census.status==="ready"?qj(e.census.providers)?"returning":"first_time":e.legacy.status!=="ready"?"pending":e.legacy.keys.length===0?"first_time":"returning"}const HYe=(e,t)=>e===t?!0:!e||!t?!e&&!t:e.length!==t.length?!1:e.every((n,r)=>n===t[r]),rI=(e,t)=>{const n=e.timestamp instanceof Date?e.timestamp.getTime():new Date(e.timestamp).getTime(),r=t.timestamp instanceof Date?t.timestamp.getTime():new Date(t.timestamp).getTime();return e.id===t.id&&e.role===t.role&&n===r&&e.message===t.message&&e.code===t.code&&e.stdout===t.stdout&&e.stderr===t.stderr&&e.logging===t.logging&&e.formatted_print===t.formatted_print&&e.status===t.status&&e.task_classification===t.task_classification&&e.action===t.action&&e.execution_type===t.execution_type&&e.is_streamable===t.is_streamable&&e.is_complete===t.is_complete&&e.conversation_id===t.conversation_id&&e.content===t.content&&e.file_path===t.file_path&&e.replacements===t.replacements&&e.agent===t.agent&&e.learnings===t.learnings&&e.thinking===t.thinking&&HYe(e.files,t.files)},ts=e=>e.timestamp instanceof Date?e.timestamp.getTime():new Date(e.timestamp).getTime(),iI=e=>{for(let t=1;t<e.length;t+=1)if(ts(e[t-1])>ts(e[t]))return!1;return!0},dun=ta((e,t)=>({messagesByConversation:{},paginationByConversation:{},lastUpdated:Date.now(),addMessages:(n,r,i=!1)=>{e(a=>{const o=a.messagesByConversation[n]||[],s=new Set(o.map(d=>d.id)),l=r.filter(d=>!s.has(d.id));if(l.length===0)return a;const c=iI(l)?l:[...l].sort((d,f)=>ts(d)-ts(f));let u=i?[...c,...o]:[...o,...c];return o.length===0||(i?ts(c[c.length-1])<=ts(o[0]):ts(c[0])>=ts(o[o.length-1]))||(u=[...u].sort((d,f)=>ts(d)-ts(f))),{messagesByConversation:{...a.messagesByConversation,[n]:u},lastUpdated:Date.now()}})},setMessages:(n,r)=>{e(i=>{const a=iI(r)?r:[...r].sort((s,l)=>ts(s)-ts(l)),o=i.messagesByConversation[n]||[];if(o.length===a.length){let s=!1;for(let l=0;l<o.length;l+=1)if(!rI(o[l],a[l])){s=!0;break}if(!s)return i}return{messagesByConversation:{...i.messagesByConversation,[n]:a},lastUpdated:Date.now()}})},addMessage:(n,r)=>{e(i=>{const a=i.messagesByConversation[n]||[];return a.some(o=>o.id===r.id)?i:{messagesByConversation:{...i.messagesByConversation,[n]:[...a,r]},lastUpdated:Date.now()}})},updateMessage:(n,r)=>{let i=!1;return e(a=>{const s=(a.messagesByConversation[n]||[]).map(l=>l.id===r.id?rI(l,r)?l:(i=!0,r):l);return i?{messagesByConversation:{...a.messagesByConversation,[n]:s},lastUpdated:Date.now()}:a}),i},clearConversation:n=>{e(r=>{const{[n]:i,...a}=r.messagesByConversation,{[n]:o,...s}=r.paginationByConversation;return{messagesByConversation:a,paginationByConversation:s,lastUpdated:Date.now()}})},getMessages:n=>t().messagesByConversation[n]||[],updatePagination:(n,r,i,a)=>{e(o=>{const s=o.paginationByConversation[n]||{currentPage:1,totalPages:1,hasMore:!1};return s.currentPage===r&&s.totalPages===i&&s.hasMore===a?o:{paginationByConversation:{...o.paginationByConversation,[n]:{...s,currentPage:r,totalPages:i,hasMore:a}},lastUpdated:Date.now()}})},getPagination:n=>t().paginationByConversation[n]||{currentPage:1,totalPages:1,hasMore:!1},updateScrollPosition:(n,r)=>{e(i=>{const a=i.paginationByConversation[n]||{currentPage:1,totalPages:1,hasMore:!1};return a.scrollPosition===r?i:{paginationByConversation:{...i.paginationByConversation,[n]:{...a,scrollPosition:r}}}})},getScrollPosition:n=>t().paginationByConversation[n]?.scrollPosition})),fun=ta((e,t)=>({historyByConversation:{},setCurrentMessage:(n,r)=>{e(i=>{const a=i.historyByConversation[n]||{currentMessage:"",currentSequenceId:null};return{historyByConversation:{...i.historyByConversation,[n]:{...a,currentMessage:r}}}})},getCurrentMessage:n=>t().historyByConversation[n]?.currentMessage||"",setCurrentSequenceId:(n,r)=>{e(i=>{const a=i.historyByConversation[n]||{currentMessage:"",currentSequenceId:null};return{historyByConversation:{...i.historyByConversation,[n]:{...a,currentSequenceId:r}}}})},getCurrentSequenceId:n=>t().historyByConversation[n]?.currentSequenceId||null,resetHistory:n=>{e(r=>{const i=r.historyByConversation[n];return i?{historyByConversation:{...r.historyByConversation,[n]:{...i,currentSequenceId:null}}}:r})},clearConversationHistory:n=>{e(r=>{const{[n]:i,...a}=r.historyByConversation;return{historyByConversation:a}})}}));function KYe(e){return e.serverOnline?e.capabilitiesState==="pending"?"checking":e.capabilitiesState==="error"||e.accountUnavailable?"could-not-check":e.accountRead==="checking"?"checking":e.accountRead==="signed-out"||e.accountRead==="refused"?"sign-in":"could-not-check":"offline"}const JYe={recording:{checking:"Checking your Radient sign-in…","sign-in":"Sign in to Radient in Settings to enable recording","could-not-check":"Your Radient sign-in could not be checked, so recording is unavailable for now",offline:"Recording is unavailable while Local Operator is offline"},"speaking-aloud":{checking:"Checking your Radient sign-in…","sign-in":"Sign in to Radient in Settings to enable speaking aloud","could-not-check":"Your Radient sign-in could not be checked, so speaking aloud is unavailable for now",offline:"Speaking aloud is unavailable while Local Operator is offline"}};function ode(e,t){return JYe[e][t]}const eGe={checking:"Checking whether this machine can speak aloud…","sign-in":"Nothing can speak aloud yet: run /login radient to sign in, or store a provider key in the Model providers section","could-not-check":"Nothing can speak aloud yet. A Radient sign-in or a stored provider key is what changes that",offline:"Local Operator is offline, so nothing can speak aloud right now"};function hun(e){return eGe[e]}const tGe={name:"User",email:"user@example.com"},sde=ta()(lc(e=>({profile:tGe,isSigningOut:!1,updateName:t=>{e(n=>({profile:{...n.profile,name:t}}))},updateEmail:t=>{e(n=>({profile:{...n.profile,email:t}}))},updateProfile:t=>{e(n=>({profile:{...n.profile,...t}}))},setIsSigningOut:t=>{e({isSigningOut:t})},clearProfile:()=>{e({profile:{name:"",email:""}})}}),{name:"user-profile-storage"}));function nGe(e){return{operation:e.operation,...e.tenantId?{tenant_id:e.tenantId}:{},...e.accountId?{account_id:e.accountId}:{},...e.agentId?{agent_id:e.agentId}:{},...e.commentId?{comment_id:e.commentId}:{},...e.teamId?{team_id:e.teamId}:{},...e.skillId?{skill_id:e.skillId}:{},...e.query?{query:e.query}:{},...e.payload?{payload:e.payload}:{},...e.requestId?{request_id:e.requestId}:{},...e.confirmed?{confirmed:!0}:{}}}async function rGe(e){return(await Re({op:"radient.request",control:nGe(e)})).data}async function Az(e){const t=await rGe(e);return t&&typeof t=="object"&&"result"in t?t.result:t}const Kd={all:["radient-user"],user:()=>[...Kd.all,"user"]};function pun(e){return e==="refused"||e==="unavailable"||e==="unknown"}const iGe="radient_no_credential",aGe="radient_credential_refused",oGe="radient_upstream_failed";function jj(e){if(e instanceof Ut){if(e.code===iGe)return"signed-out";if(e.code===aGe)return"refused";if(e.code===oGe)return"unavailable";if(e.status===409&&/sign in to radient/i.test(e.message))return"signed-out"}return"unknown"}function aI(e){return jj(e)==="signed-out"}const zz=JSON.stringify(Kd.user()),Uz=new Map,Cj=new Set;function lde(){for(const e of Cj)e()}function Aj(){return Uz.get(zz)??null}function sGe(e){return Cj.add(e),()=>{Cj.delete(e)}}function lGe(e){Aj()!==e&&(Uz.set(zz,e),lde())}let zj=0;function $1(){zj+=1,Uz.delete(zz)&&lde()}async function cGe(e){$1(),await e.cancelQueries({queryKey:Kd.all}),await e.invalidateQueries({queryKey:Kd.all})}const cde=({retryOnMount:e=!0,staleTime:t=30*1e3}={})=>{const n=cc(),{setIsSigningOut:r}=sde(),i=Ri(),a=oi(i.data,"radient"),o=jt({queryKey:Kd.user(),queryFn:async()=>{const m=zj;try{const g=await Az({operation:"account"});return $1(),g}catch(g){if(aI(g))return $1(),null;throw m===zj&&lGe(jj(g)),g}},enabled:a,staleTime:t,refetchOnWindowFocus:!0,retry:(m,g)=>!aI(g)&&m<2,retryOnMount:e}),s=!!o.data&&!o.isLoading,l=s,c=$.useSyncExternalStore(sGe,Aj,Aj),u=!!o.data,O=u?null:o.error?jj(o.error):c,d=O&&O!=="signed-out"?O:u?"ready":o.isLoading?"checking":"signed-out",f=pj({onMutate:()=>{r(!0)},mutationFn:async()=>{const g=(await Re({op:"accounts.list"})).accounts.filter(y=>y.provider==="radient");for(const y of g)await Re({op:"accounts.remove",accountId:y.id,confirmed:!0});return!0},onSuccess:()=>{n.removeQueries({queryKey:Kd.all}),$1(),n.invalidateQueries({queryKey:ri.accounts}),Of("Successfully signed out"),r(!1)},onError:m=>{const g=m instanceof Error?m.message:String(m);mi(`Failed to sign out: ${g}`),r(!1)}}),p=pj({mutationFn:async()=>(await n.invalidateQueries({queryKey:Kd.all}),!0)});return{user:o.data??void 0,isLoading:o.isLoading,isRefetching:o.isRefetching,isFetching:o.isFetching,isRefreshing:p.isPending,accountRead:d,error:o.error,hasLocalSession:l,isAuthenticated:s,unavailable:i.isSuccess&&!a,signOut:f.mutate,refreshUser:p.mutate,userQuery:o}},uGe=()=>{const e=sde(),{user:t,isLoading:n,isFetching:r,accountRead:i,error:a,isAuthenticated:o,hasLocalSession:s,unavailable:l,signOut:c,refreshUser:u}=cde();let O;return n?O=s?"restoring":"loading":o?O="authenticated":O="unauthenticated",$.useEffect(()=>{if(!o||!t?.account)return;const{account:d}=t;if(!d.name&&!d.email)return;const{name:f,email:p}=e.profile;(d.name&&d.name!==f||d.email&&d.email!==p)&&e.updateProfile({name:d.name||f,email:d.email||p})},[o,t,e]),{authStatus:O,isAuthenticated:o,hasLocalSession:s,isLoading:n,isFetching:r,accountRead:i,error:a,user:o&&t?.account?{name:t.account.name,email:t.account.email,radientUser:t}:null,unavailable:l,refreshUser:u,signOut:c,updateProfile:e.updateProfile,updateName:e.updateName,updateEmail:e.updateEmail}},OGe=["credentials"],dGe=()=>{const{shouldEnableQuery:e,getConnectivityError:t}=yz(),n=t();return $.useEffect(()=>{n&&console.error("Credentials connectivity error:",n.message)},[n]),jt({enabled:e({bypassInternetCheck:!0}),queryKey:OGe,queryFn:async()=>{const i=await hv(Nf.baseUrl).credentials.listCredentials();if(i.status>=400)throw new Error(i.message||"Failed to fetch credentials");return i.result},refetchOnWindowFocus:!1,staleTime:5e3})},fGe=()=>{const{data:e,isError:t,isPending:n,fetchStatus:r,refetch:i}=dGe(),{isAuthenticated:a,accountRead:o,unavailable:s}=uGe(),{isServerOnline:l}=yz(),c=Ri(),u=c.isPending?"pending":c.isError?"error":"answered",O=!!e?.keys?.includes("RADIENT_API_KEY"),d=a,f=t||n&&r==="idle",p=$.useRef(a);$.useEffect(()=>{p.current!==a&&(p.current=a,i())},[a,i]);const m=l&&(d||O&&!f),g=KYe({serverOnline:l,accountRead:o,accountUnavailable:s,capabilitiesState:u});return $.useMemo(()=>({hasRadientApiKey:O,hasRadientSession:d,isUnavailable:f,canUseRadientSpeech:m,speechBlock:g}),[O,d,f,m,g])};let P5=null;function hGe(){if(!P5){const e=window.api?.getHomeDirectory;P5=typeof e=="function"?e.call(window.api).catch(()=>null):Promise.resolve(null)}return P5}function pGe(){const[e,t]=$.useState(null);return $.useEffect(()=>{let n=!0;return hGe().then(r=>{n&&t(r)}),()=>{n=!1}},[]),e}const mGe=15*60*1e3,gGe=ta()(lc((e,t)=>({providers:[],models:[],isLoading:!1,error:null,lastFetched:null,isInitialized:!1,fetchModels:async(n,r=!1)=>{const{lastFetched:i,isInitialized:a}=t(),o=Date.now();if(!(!r&&a&&i&&o-i<mGe)){e({isLoading:!0,error:null});try{const s=hv(n),c=(await s.models.listProviders()).result?.providers||[],O=(await s.models.listModels("","recommended","descending")).result?.models||[];e({providers:c,models:O,isLoading:!1,lastFetched:o,isInitialized:!0})}catch(s){console.error("Failed to fetch models:",s),e({isLoading:!1,error:s instanceof Error?s.message:String(s)})}}},getModelsForProvider:n=>t().models.filter(r=>r.provider===n),reset:()=>{e({providers:[],models:[],isLoading:!1,error:null,lastFetched:null,isInitialized:!1})}}),{name:"local-operator-models",partialize:e=>({providers:e.providers,models:e.models,lastFetched:e.lastFetched,isInitialized:e.isInitialized})})),$Ge=({autoFetch:e=!0}={})=>{const t=Nf.baseUrl,n=$.useRef(null),{shouldEnableQuery:r,getConnectivityError:i,hasConnectivityIssue:a}=yz(),{providers:o,models:s,isLoading:l,error:c,lastFetched:u,isInitialized:O,fetchModels:d,getModelsForProvider:f}=gGe(),p=$.useRef(!0),m=$.useRef(!1),g=$.useRef(null);$.useEffect(()=>(n.current&&(clearInterval(n.current),n.current=null),g.current&&(clearTimeout(g.current),g.current=null),e&&r({bypassInternetCheck:!0})?(p.current?(p.current=!1,g.current=window.setTimeout(()=>{!m.current&&r({bypassInternetCheck:!0})&&(d(t),m.current=!0),g.current=null},1e3)):m.current||(d(t),m.current=!0),n.current=window.setInterval(()=>{r({bypassInternetCheck:!0})&&d(t)},15*60*1e3),()=>{n.current&&(clearInterval(n.current),n.current=null),g.current&&(clearTimeout(g.current),g.current=null)}):()=>{g.current&&(clearTimeout(g.current),g.current=null)}),[e,t,d,r]),$.useEffect(()=>{!a&&e&&O&&d(t)},[a,e,O,t,d]);const y=$.useCallback(async()=>{if(r({bypassInternetCheck:!0}))await d(t,!0);else{const S=i();if(S)throw S}},[t,d,r,i]);return{providers:o,models:s,isLoading:l,error:c,lastFetched:u,isInitialized:O,getModelsForProvider:f,getModelById:S=>s.find(Q=>Q.id===S),refreshModels:y}},yGe=()=>{const{isLoading:e,error:t,refreshModels:n}=$Ge({autoFetch:!1}),r=$.useRef(!1);return $.useEffect(()=>{r.current||(r.current=!0)},[]),{isLoading:e,error:t,refreshModels:n}},vGe=(e,t,n)=>n&&e!==t,Wz=e=>typeof e=="object"&&e!==null;function ude(e,t){e.offRecord.then(t,()=>{})}const bGe=e=>e!==!1&&!Wz(e),wGe=(e,t)=>e===t?"":e,SGe=(e,t)=>e===""||e===t,xGe=e=>e==="",oI=(e,t)=>e?/\s$/.test(e)||/^\s/.test(t)?e+t:`${e} ${t}`:t,Ys={unavailable:"This conversation is gone",busy:"Agent is busy",answer:"Type your own answer…",secretAnswer:"Answer the secret request in the asks panel",aside:"Ask off the record — Esc closes the aside",sending:"Sending your message",stopping:"Stopping the turn",recording:"Recording",waiting:"Steer the agent. Enter sends now · Esc stops",noProvider:"Connect a provider to start chatting",idle:"Ask anything. @ adds files, / runs commands"},QGe=e=>e.unavailable?Ys.unavailable:e.secretAnswer?Ys.secretAnswer:e.hostLine&&(e.inputDisabled||e.sendingUnsettled||e.awaitingReply)?e.hostLine:e.inputDisabled?Ys.busy:e.awaitingAnswer?Ys.answer:e.asideAttached?Ys.aside:e.stopping?Ys.stopping:e.sendingUnsettled?Ys.sending:e.awaitingReply?Ys.waiting:e.noProvider?Ys.noProvider:e.idle??Ys.idle,kGe=[],PGe=[],_Ge=e=>{const t=an.getState().inputByConversation[e];return{replies:t?.replies??kGe,attachments:t?.attachments??PGe}},TGe=(e,t)=>{const n=an.getState();for(const r of t.replies)n.removeReply(e,r.id);for(const r of t.attachments)n.removeAttachment(e,r.id)},RGe=()=>0,XGe=({conversationId:e,onSubmit:t,scrollToBottom:n,draftHeld:r=!1,draftUnredacted:i=RGe,transcriptless:a=!1})=>{const o=an(B=>B.getCurrentInput),s=an(B=>B.setCurrentInput),l=an(B=>B.addSubmittedMessage),c=an(B=>B.getSubmittedMessages),u=an(B=>B.getCurrentHistoryIndex),O=an(B=>B.setCurrentHistoryIndex),d=an(B=>B.resetCurrentHistoryIndex),f=an(B=>B.beginInFlight),p=an(B=>B.adoptReturnedText),[m,g]=$.useState(an.persist?.hasHydrated?.()??!1),y=$.useRef(void 0),v=$.useRef(void 0),[S,Q]=$.useState("");$.useEffect(()=>{const B=an.persist;let K,ne;return B&&typeof B.onHydrate=="function"&&typeof B.onFinishHydration=="function"?(K=B.onHydrate(()=>g(!1)),ne=B.onFinishHydration(()=>g(!0)),g(B.hasHydrated())):g(!0),()=>{K?.(),ne?.()}},[]);const b=$.useRef(null),w=$.useRef(""),x=an(B=>e?B.inputByConversation[e]?.currentInput??"":""),k=$.useRef(""),T=e?c(e):[],_=e?u(e):null;$.useEffect(()=>{if(vGe(v.current,e,m))if(v.current=e,e){const B=o(e);_!==null&&T.length>0?Q(T[_]||""):Q(B),y.current=e,w.current=""}else Q(""),y.current=void 0,w.current=""},[e,m,o,_,T]),$.useEffect(()=>{m&&e&&y.current!==e&&s(e,S)},[e,S,s,m]),$.useEffect(()=>{!m||!e||x!==k.current&&(k.current=x,x&&!S&&Q(x))},[x,m,e,S]);const E=an(B=>e?B.inputByConversation[e]?.pendingText:void 0),R=an(B=>e?B.inputByConversation[e]?.textRevision??0:0),j=an(B=>e?B.inputByConversation[e]?.currentInput:void 0),C=$.useRef(null);$.useEffect(()=>{if(!m||!e||y.current!==e)return;const B=C.current;C.current=R;const K=B===null;if(E!==void 0){if(r)return;const le=p(e);if(le===null)return;k.current=le,Q(le);return}if(K||R===B||r)return;const ne=j??"";ne!==S&&(k.current=ne,Q(ne))},[R,j,E,m,e,r,S,p]);const W=$.useCallback(B=>{if(Q(B),e){if(r)return;k.current=B,s(e,B,i(B)),d(e)}},[e,s,d,r,i]),G=$.useRef(!1),N=$.useRef(""),Z=$.useRef(!1),F=$.useCallback(B=>{if(!(!e||!B)){if(r){Q(K=>oI(K,B));return}W(oI(o(e),B))}},[e,r,o,W]),z=$.useCallback(B=>{if(B){if(Z.current){N.current+=B;return}F(B)}},[F]),[M,te]=$.useState(!1),U=$.useCallback(async()=>{const B=e?_Ge(e):void 0;if(!e||!S.trim()&&(B?.attachments.length??0)===0)return;const K=G.current;G.current=!0,K||(te(!0),Z.current=!0);const ne=S;let le=!1,Oe=!1,Qe;const we=(Ne=!1)=>{if(le&&!Ne)return;le=!0;const Ke=N.current;if(Ke&&(N.current=""),Z.current=!1,!a&&y.current!==e){Ke&&F(Ke);return}Q(Le=>wGe(Le,ne)),e&&f(e,{text:ne,attachments:Oe?[]:B?.attachments??[],replies:Oe?[]:B?.replies??[],volatileText:r},Ne),Ke&&F(Ke)},He=()=>{e&&!SGe(o(e),ne)||(k.current="",s(e,""),d(e),w.current="")};try{if(Qe=await t?.(ne,()=>we(!0)),Qe===!1){Z.current=!1;const Ne=N.current;Ne&&(N.current="",F(Ne));return}}finally{K||(G.current=!1,te(!1))}Wz(Qe)&&(Oe=!0,e&&B&&ude(Qe,()=>TGe(e,B))),we(),bGe(Qe)&&l(e,ne),He(),n&&requestAnimationFrame(()=>{n()})},[S,e,t,l,s,d,n,f,r,F,o,a]),H=$.useCallback(()=>{const B=b.current;if(!B)return{line:0,totalLines:1};const K=B.value,ne=B.selectionStart,Oe=(K.substring(0,ne).match(/\n/g)||[]).length+1,Qe=(K.match(/\n/g)||[]).length+1;return{line:Oe,totalLines:Qe}},[]),D=$.useCallback(()=>H().line===1,[H]),V=$.useCallback(()=>{const{line:B,totalLines:K}=H();return B===K},[H]),se=$.useCallback(B=>{if(e){if(B.key==="Enter"&&!B.shiftKey){B.preventDefault(),U();return}if(T.length){if(B.key==="ArrowUp"){if(_===null){if(!xGe(S))return}else if(!D())return;if(B.preventDefault(),_===null)w.current=S,O(e,T.length-1),Q(T[T.length-1]||"");else if(_>0){const K=_-1;O(e,K),Q(T[K]||"")}setTimeout(()=>{if(b.current){const K=b.current.value.length;b.current.selectionStart=K,b.current.selectionEnd=K}},0)}if(B.key==="ArrowDown"&&V()){if(_===null)return;if(B.preventDefault(),_!==null){if(_<T.length-1){const K=_+1;O(e,K),Q(T[K]||"")}else d(e),Q(w.current),w.current="";setTimeout(()=>{if(b.current){const K=b.current.value.length;b.current.selectionStart=K,b.current.selectionEnd=K}},0)}}}}},[U,D,V,_,S,T,e,O,d]);return{inputValue:S,setInputValue:W,handleKeyDown:se,handleSubmit:U,textareaRef:b,appendTranscriptText:z,sendInFlight:M}},q$=e=>e.replace(/\\/g,"/"),mun=()=>window.location.hash?q$(window.location.hash.substring(1)):q$(window.location.pathname),EGe=(e,t)=>{if(t!==null&&(e===t||e.startsWith(`${t}/`)||e.startsWith(`${t}\\`))){const r=e.substring(t.length);return r.startsWith("/")||r.startsWith("\\")||r===""?`~${r.replace(/\\/g,"/")}`:`~/${r.replace(/\\/g,"/")}`}return e==="~"?"~":e.replace(/\\/g,"/")},gun=(e,t)=>{if(e.length<=t)return e;const n=e.split("/"),r=n[n.length-1]??"";if(r.length+1>=t)return`…${r.slice(-39)}`;const i=n[0]==="~"||n[0]==="",a=i?n.slice(0,2):n.slice(0,1),o=n.slice(a.length),s=p=>{const m=t-p.length-(p?3:2);let g=[];for(let y=o.length-1;y>=0;y-=1){const v=[o[y],...g];if(v.join("/").length>m)break;g=v}return g},l=(p,m)=>p?`${p}/…/${m.join("/")}`:`…/${m.join("/")}`,c=a.join("/"),u=s(c);if(u.length>0)return u.length===o.length?e:l(c,u);const O=i?n[0]:"",d=s(O);if(d.length>0)return l(O,d);const f=t-(O?`${O}/…/`.length:2);return f>0?l(O,[r.slice(-f)]):"…"},$un=(e,t)=>q$(e).includes(t),qGe=$.memo(()=>(yGe(),null));qGe.displayName="ModelsInitializer";const jGe={"--normal-bg":"var(--color-elevated)","--normal-text":"var(--color-ink)","--normal-border":"var(--color-control)","--border-radius":"var(--radius-md)","--gray12":"var(--color-ink)","--gray4":"var(--color-control)","--gray2":"var(--color-accent-wash)","--gray5":"var(--color-control)",background:"var(--color-elevated)",color:"var(--color-ink)",border:"1px solid var(--color-control)",boxShadow:"var(--shadow-overlay)",fontSize:"var(--text-meta)",padding:"12px 16px","--toast-close-button-start":"auto","--toast-close-button-end":"0px","--toast-close-button-transform":"translate(35%, -35%)"},yun=({duration:e})=>h.jsx(Q7e,{duration:e,position:"bottom-right",toastOptions:{style:jGe,closeButton:!0}});var mg={},mh={},wb={},rd={},id={},_5={},sI;function Ode(){return sI||(sI=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Doctype=e.CDATA=e.Tag=e.Style=e.Script=e.Comment=e.Directive=e.Text=e.Root=e.isTag=e.ElementType=void 0;var t;(function(r){r.Root="root",r.Text="text",r.Directive="directive",r.Comment="comment",r.Script="script",r.Style="style",r.Tag="tag",r.CDATA="cdata",r.Doctype="doctype"})(t=e.ElementType||(e.ElementType={}));function n(r){return r.type===t.Tag||r.type===t.Script||r.type===t.Style}e.isTag=n,e.Root=t.Root,e.Text=t.Text,e.Directive=t.Directive,e.Comment=t.Comment,e.Script=t.Script,e.Style=t.Style,e.Tag=t.Tag,e.CDATA=t.CDATA,e.Doctype=t.Doctype}(_5)),_5}var Ht={},lI;function cI(){if(lI)return Ht;lI=1;var e=Ht&&Ht.__extends||function(){var b=function(w,x){return b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(k,T){k.__proto__=T}||function(k,T){for(var _ in T)Object.prototype.hasOwnProperty.call(T,_)&&(k[_]=T[_])},b(w,x)};return function(w,x){if(typeof x!="function"&&x!==null)throw new TypeError("Class extends value "+String(x)+" is not a constructor or null");b(w,x);function k(){this.constructor=w}w.prototype=x===null?Object.create(x):(k.prototype=x.prototype,new k)}}(),t=Ht&&Ht.__assign||function(){return t=Object.assign||function(b){for(var w,x=1,k=arguments.length;x<k;x++){w=arguments[x];for(var T in w)Object.prototype.hasOwnProperty.call(w,T)&&(b[T]=w[T])}return b},t.apply(this,arguments)};Object.defineProperty(Ht,"__esModule",{value:!0}),Ht.cloneNode=Ht.hasChildren=Ht.isDocument=Ht.isDirective=Ht.isComment=Ht.isText=Ht.isCDATA=Ht.isTag=Ht.Element=Ht.Document=Ht.CDATA=Ht.NodeWithChildren=Ht.ProcessingInstruction=Ht.Comment=Ht.Text=Ht.DataNode=Ht.Node=void 0;var n=Ode(),r=function(){function b(){this.parent=null,this.prev=null,this.next=null,this.startIndex=null,this.endIndex=null}return Object.defineProperty(b.prototype,"parentNode",{get:function(){return this.parent},set:function(w){this.parent=w},enumerable:!1,configurable:!0}),Object.defineProperty(b.prototype,"previousSibling",{get:function(){return this.prev},set:function(w){this.prev=w},enumerable:!1,configurable:!0}),Object.defineProperty(b.prototype,"nextSibling",{get:function(){return this.next},set:function(w){this.next=w},enumerable:!1,configurable:!0}),b.prototype.cloneNode=function(w){return w===void 0&&(w=!1),S(this,w)},b}();Ht.Node=r;var i=function(b){e(w,b);function w(x){var k=b.call(this)||this;return k.data=x,k}return Object.defineProperty(w.prototype,"nodeValue",{get:function(){return this.data},set:function(x){this.data=x},enumerable:!1,configurable:!0}),w}(r);Ht.DataNode=i;var a=function(b){e(w,b);function w(){var x=b!==null&&b.apply(this,arguments)||this;return x.type=n.ElementType.Text,x}return Object.defineProperty(w.prototype,"nodeType",{get:function(){return 3},enumerable:!1,configurable:!0}),w}(i);Ht.Text=a;var o=function(b){e(w,b);function w(){var x=b!==null&&b.apply(this,arguments)||this;return x.type=n.ElementType.Comment,x}return Object.defineProperty(w.prototype,"nodeType",{get:function(){return 8},enumerable:!1,configurable:!0}),w}(i);Ht.Comment=o;var s=function(b){e(w,b);function w(x,k){var T=b.call(this,k)||this;return T.name=x,T.type=n.ElementType.Directive,T}return Object.defineProperty(w.prototype,"nodeType",{get:function(){return 1},enumerable:!1,configurable:!0}),w}(i);Ht.ProcessingInstruction=s;var l=function(b){e(w,b);function w(x){var k=b.call(this)||this;return k.children=x,k}return Object.defineProperty(w.prototype,"firstChild",{get:function(){var x;return(x=this.children[0])!==null&&x!==void 0?x:null},enumerable:!1,configurable:!0}),Object.defineProperty(w.prototype,"lastChild",{get:function(){return this.children.length>0?this.children[this.children.length-1]:null},enumerable:!1,configurable:!0}),Object.defineProperty(w.prototype,"childNodes",{get:function(){return this.children},set:function(x){this.children=x},enumerable:!1,configurable:!0}),w}(r);Ht.NodeWithChildren=l;var c=function(b){e(w,b);function w(){var x=b!==null&&b.apply(this,arguments)||this;return x.type=n.ElementType.CDATA,x}return Object.defineProperty(w.prototype,"nodeType",{get:function(){return 4},enumerable:!1,configurable:!0}),w}(l);Ht.CDATA=c;var u=function(b){e(w,b);function w(){var x=b!==null&&b.apply(this,arguments)||this;return x.type=n.ElementType.Root,x}return Object.defineProperty(w.prototype,"nodeType",{get:function(){return 9},enumerable:!1,configurable:!0}),w}(l);Ht.Document=u;var O=function(b){e(w,b);function w(x,k,T,_){T===void 0&&(T=[]),_===void 0&&(_=x==="script"?n.ElementType.Script:x==="style"?n.ElementType.Style:n.ElementType.Tag);var E=b.call(this,T)||this;return E.name=x,E.attribs=k,E.type=_,E}return Object.defineProperty(w.prototype,"nodeType",{get:function(){return 1},enumerable:!1,configurable:!0}),Object.defineProperty(w.prototype,"tagName",{get:function(){return this.name},set:function(x){this.name=x},enumerable:!1,configurable:!0}),Object.defineProperty(w.prototype,"attributes",{get:function(){var x=this;return Object.keys(this.attribs).map(function(k){var T,_;return{name:k,value:x.attribs[k],namespace:(T=x["x-attribsNamespace"])===null||T===void 0?void 0:T[k],prefix:(_=x["x-attribsPrefix"])===null||_===void 0?void 0:_[k]}})},enumerable:!1,configurable:!0}),w}(l);Ht.Element=O;function d(b){return(0,n.isTag)(b)}Ht.isTag=d;function f(b){return b.type===n.ElementType.CDATA}Ht.isCDATA=f;function p(b){return b.type===n.ElementType.Text}Ht.isText=p;function m(b){return b.type===n.ElementType.Comment}Ht.isComment=m;function g(b){return b.type===n.ElementType.Directive}Ht.isDirective=g;function y(b){return b.type===n.ElementType.Root}Ht.isDocument=y;function v(b){return Object.prototype.hasOwnProperty.call(b,"children")}Ht.hasChildren=v;function S(b,w){w===void 0&&(w=!1);var x;if(p(b))x=new a(b.data);else if(m(b))x=new o(b.data);else if(d(b)){var k=w?Q(b.children):[],T=new O(b.name,t({},b.attribs),k);k.forEach(function(j){return j.parent=T}),b.namespace!=null&&(T.namespace=b.namespace),b["x-attribsNamespace"]&&(T["x-attribsNamespace"]=t({},b["x-attribsNamespace"])),b["x-attribsPrefix"]&&(T["x-attribsPrefix"]=t({},b["x-attribsPrefix"])),x=T}else if(f(b)){var k=w?Q(b.children):[],_=new c(k);k.forEach(function(C){return C.parent=_}),x=_}else if(y(b)){var k=w?Q(b.children):[],E=new u(k);k.forEach(function(C){return C.parent=E}),b["x-mode"]&&(E["x-mode"]=b["x-mode"]),x=E}else if(g(b)){var R=new s(b.name,b.data);b["x-name"]!=null&&(R["x-name"]=b["x-name"],R["x-publicId"]=b["x-publicId"],R["x-systemId"]=b["x-systemId"]),x=R}else throw new Error("Not implemented yet: ".concat(b.type));return x.startIndex=b.startIndex,x.endIndex=b.endIndex,b.sourceCodeLocation!=null&&(x.sourceCodeLocation=b.sourceCodeLocation),x}Ht.cloneNode=S;function Q(b){for(var w=b.map(function(k){return S(k,!0)}),x=1;x<w.length;x++)w[x].prev=w[x-1],w[x-1].next=w[x];return w}return Ht}var uI;function dde(){return uI||(uI=1,function(e){var t=id&&id.__createBinding||(Object.create?function(s,l,c,u){u===void 0&&(u=c);var O=Object.getOwnPropertyDescriptor(l,c);(!O||("get"in O?!l.__esModule:O.writable||O.configurable))&&(O={enumerable:!0,get:function(){return l[c]}}),Object.defineProperty(s,u,O)}:function(s,l,c,u){u===void 0&&(u=c),s[u]=l[c]}),n=id&&id.__exportStar||function(s,l){for(var c in s)c!=="default"&&!Object.prototype.hasOwnProperty.call(l,c)&&t(l,s,c)};Object.defineProperty(e,"__esModule",{value:!0}),e.DomHandler=void 0;var r=Ode(),i=cI();n(cI(),e);var a={withStartIndices:!1,withEndIndices:!1,xmlMode:!1},o=function(){function s(l,c,u){this.dom=[],this.root=new i.Document(this.dom),this.done=!1,this.tagStack=[this.root],this.lastNode=null,this.parser=null,typeof c=="function"&&(u=c,c=a),typeof l=="object"&&(c=l,l=void 0),this.callback=l??null,this.options=c??a,this.elementCB=u??null}return s.prototype.onparserinit=function(l){this.parser=l},s.prototype.onreset=function(){this.dom=[],this.root=new i.Document(this.dom),this.done=!1,this.tagStack=[this.root],this.lastNode=null,this.parser=null},s.prototype.onend=function(){this.done||(this.done=!0,this.parser=null,this.handleCallback(null))},s.prototype.onerror=function(l){this.handleCallback(l)},s.prototype.onclosetag=function(){this.lastNode=null;var l=this.tagStack.pop();this.options.withEndIndices&&(l.endIndex=this.parser.endIndex),this.elementCB&&this.elementCB(l)},s.prototype.onopentag=function(l,c){var u=this.options.xmlMode?r.ElementType.Tag:void 0,O=new i.Element(l,c,void 0,u);this.addNode(O),this.tagStack.push(O)},s.prototype.ontext=function(l){var c=this.lastNode;if(c&&c.type===r.ElementType.Text)c.data+=l,this.options.withEndIndices&&(c.endIndex=this.parser.endIndex);else{var u=new i.Text(l);this.addNode(u),this.lastNode=u}},s.prototype.oncomment=function(l){if(this.lastNode&&this.lastNode.type===r.ElementType.Comment){this.lastNode.data+=l;return}var c=new i.Comment(l);this.addNode(c),this.lastNode=c},s.prototype.oncommentend=function(){this.lastNode=null},s.prototype.oncdatastart=function(){var l=new i.Text(""),c=new i.CDATA([l]);this.addNode(c),l.parent=c,this.lastNode=l},s.prototype.oncdataend=function(){this.lastNode=null},s.prototype.onprocessinginstruction=function(l,c){var u=new i.ProcessingInstruction(l,c);this.addNode(u)},s.prototype.handleCallback=function(l){if(typeof this.callback=="function")this.callback(l,this.dom);else if(l)throw l},s.prototype.addNode=function(l){var c=this.tagStack[this.tagStack.length-1],u=c.children[c.children.length-1];this.options.withStartIndices&&(l.startIndex=this.parser.startIndex),this.options.withEndIndices&&(l.endIndex=this.parser.endIndex),c.children.push(l),u&&(l.prev=u,u.next=l),l.parent=c,this.lastNode=null},s}();e.DomHandler=o,e.default=o}(id)),id}var T5={},OI;function CGe(){return OI||(OI=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CARRIAGE_RETURN_PLACEHOLDER_REGEX=e.CARRIAGE_RETURN_PLACEHOLDER=e.CARRIAGE_RETURN_REGEX=e.CARRIAGE_RETURN=e.CASE_SENSITIVE_TAG_NAMES_MAP=e.CASE_SENSITIVE_TAG_NAMES=void 0,e.CASE_SENSITIVE_TAG_NAMES=["animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","linearGradient","radialGradient","textPath"],e.CASE_SENSITIVE_TAG_NAMES_MAP=e.CASE_SENSITIVE_TAG_NAMES.reduce(function(t,n){return t[n.toLowerCase()]=n,t},{}),e.CARRIAGE_RETURN="\r",e.CARRIAGE_RETURN_REGEX=new RegExp(e.CARRIAGE_RETURN,"g"),e.CARRIAGE_RETURN_PLACEHOLDER="__HTML_DOM_PARSER_CARRIAGE_RETURN_PLACEHOLDER_".concat(Date.now(),"__"),e.CARRIAGE_RETURN_PLACEHOLDER_REGEX=new RegExp(e.CARRIAGE_RETURN_PLACEHOLDER,"g")}(T5)),T5}var dI;function fde(){if(dI)return rd;dI=1,Object.defineProperty(rd,"__esModule",{value:!0}),rd.formatAttributes=r,rd.escapeSpecialCharacters=a,rd.revertEscapedCharacters=o,rd.formatDOM=s;var e=dde(),t=CGe();function n(l){return t.CASE_SENSITIVE_TAG_NAMES_MAP[l]}function r(l){for(var c={},u=0,O=l.length;u<O;u++){var d=l[u];c[d.name]=d.value}return c}function i(l){l=l.toLowerCase();var c=n(l);return c||l}function a(l){return l.replace(t.CARRIAGE_RETURN_REGEX,t.CARRIAGE_RETURN_PLACEHOLDER)}function o(l){return l.replace(t.CARRIAGE_RETURN_PLACEHOLDER_REGEX,t.CARRIAGE_RETURN)}function s(l,c,u){c===void 0&&(c=null);for(var O=[],d,f=0,p=l.length;f<p;f++){var m=l[f];switch(m.nodeType){case 1:{var g=i(m.nodeName);d=new e.Element(g,r(m.attributes)),d.children=s(g==="template"?m.content.childNodes:m.childNodes,d);break}case 3:d=new e.Text(o(m.nodeValue));break;case 8:d=new e.Comment(m.nodeValue);break;default:continue}var y=O[f-1]||null;y&&(y.next=d),d.parent=c,d.prev=y,d.next=null,O.push(d)}return u&&(d=new e.ProcessingInstruction(u.substring(0,u.indexOf(" ")).toLowerCase(),u),d.next=O[0]||null,d.parent=c,O.unshift(d),O[1]&&(O[1].prev=O[0])),O}return rd}var fI;function AGe(){if(fI)return wb;fI=1,Object.defineProperty(wb,"__esModule",{value:!0}),wb.default=m;var e=fde(),t="html",n="head",r="body",i=/<([a-zA-Z]+[0-9]?)/,a=/<head[^]*>/i,o=/<body[^]*>/i,s=function(g,y){throw new Error("This browser does not support `document.implementation.createHTMLDocument`")},l=function(g,y){throw new Error("This browser does not support `DOMParser.prototype.parseFromString`")},c=typeof window=="object"&&window.DOMParser;if(typeof c=="function"){var u=new c,O="text/html";l=function(g,y){return y&&(g="<".concat(y,">").concat(g,"</").concat(y,">")),u.parseFromString(g,O)},s=l}if(typeof document=="object"&&document.implementation){var d=document.implementation.createHTMLDocument();s=function(g,y){if(y){var v=d.documentElement.querySelector(y);return v&&(v.innerHTML=g),d}return d.documentElement.innerHTML=g,d}}var f=typeof document=="object"&&document.createElement("template"),p;f&&f.content&&(p=function(g){return f.innerHTML=g,f.content.childNodes});function m(g){var y,v;g=(0,e.escapeSpecialCharacters)(g);var S=g.match(i),Q=S&&S[1]?S[1].toLowerCase():"";switch(Q){case t:{var b=l(g);if(!a.test(g)){var w=b.querySelector(n);(y=w?.parentNode)===null||y===void 0||y.removeChild(w)}if(!o.test(g)){var w=b.querySelector(r);(v=w?.parentNode)===null||v===void 0||v.removeChild(w)}return b.querySelectorAll(t)}case n:case r:{var x=s(g).querySelectorAll(Q);return o.test(g)&&a.test(g)?x[0].parentNode.childNodes:x}default:{if(p)return p(g);var w=s(g,r).querySelector(r);return w.childNodes}}}return wb}var hI;function zGe(){if(hI)return mh;hI=1;var e=mh&&mh.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(mh,"__esModule",{value:!0}),mh.default=i;var t=e(AGe()),n=fde(),r=/<(![a-zA-Z\s]+)>/;function i(a){if(typeof a!="string")throw new TypeError("First argument must be a string");if(!a)return[];var o=a.match(r),s=o?o[1]:void 0;return(0,n.formatDOM)((0,t.default)(a),null,s)}return mh}var Sb={},Bo={},gg={},pI;function UGe(){if(pI)return gg;pI=1;var e=0;gg.SAME=e;var t=1;return gg.CAMELCASE=t,gg.possibleStandardNames={accept:0,acceptCharset:1,"accept-charset":"acceptCharset",accessKey:1,action:0,allowFullScreen:1,alt:0,as:0,async:0,autoCapitalize:1,autoComplete:1,autoCorrect:1,autoFocus:1,autoPlay:1,autoSave:1,capture:0,cellPadding:1,cellSpacing:1,challenge:0,charSet:1,checked:0,children:0,cite:0,class:"className",classID:1,className:1,cols:0,colSpan:1,content:0,contentEditable:1,contextMenu:1,controls:0,controlsList:1,coords:0,crossOrigin:1,dangerouslySetInnerHTML:1,data:0,dateTime:1,default:0,defaultChecked:1,defaultValue:1,defer:0,dir:0,disabled:0,disablePictureInPicture:1,disableRemotePlayback:1,download:0,draggable:0,encType:1,enterKeyHint:1,for:"htmlFor",form:0,formMethod:1,formAction:1,formEncType:1,formNoValidate:1,formTarget:1,frameBorder:1,headers:0,height:0,hidden:0,high:0,href:0,hrefLang:1,htmlFor:1,httpEquiv:1,"http-equiv":"httpEquiv",icon:0,id:0,innerHTML:1,inputMode:1,integrity:0,is:0,itemID:1,itemProp:1,itemRef:1,itemScope:1,itemType:1,keyParams:1,keyType:1,kind:0,label:0,lang:0,list:0,loop:0,low:0,manifest:0,marginWidth:1,marginHeight:1,max:0,maxLength:1,media:0,mediaGroup:1,method:0,min:0,minLength:1,multiple:0,muted:0,name:0,noModule:1,nonce:0,noValidate:1,open:0,optimum:0,pattern:0,placeholder:0,playsInline:1,poster:0,preload:0,profile:0,radioGroup:1,readOnly:1,referrerPolicy:1,rel:0,required:0,reversed:0,role:0,rows:0,rowSpan:1,sandbox:0,scope:0,scoped:0,scrolling:0,seamless:0,selected:0,shape:0,size:0,sizes:0,span:0,spellCheck:1,src:0,srcDoc:1,srcLang:1,srcSet:1,start:0,step:0,style:0,summary:0,tabIndex:1,target:0,title:0,type:0,useMap:1,value:0,width:0,wmode:0,wrap:0,about:0,accentHeight:1,"accent-height":"accentHeight",accumulate:0,additive:0,alignmentBaseline:1,"alignment-baseline":"alignmentBaseline",allowReorder:1,alphabetic:0,amplitude:0,arabicForm:1,"arabic-form":"arabicForm",ascent:0,attributeName:1,attributeType:1,autoReverse:1,azimuth:0,baseFrequency:1,baselineShift:1,"baseline-shift":"baselineShift",baseProfile:1,bbox:0,begin:0,bias:0,by:0,calcMode:1,capHeight:1,"cap-height":"capHeight",clip:0,clipPath:1,"clip-path":"clipPath",clipPathUnits:1,clipRule:1,"clip-rule":"clipRule",color:0,colorInterpolation:1,"color-interpolation":"colorInterpolation",colorInterpolationFilters:1,"color-interpolation-filters":"colorInterpolationFilters",colorProfile:1,"color-profile":"colorProfile",colorRendering:1,"color-rendering":"colorRendering",contentScriptType:1,contentStyleType:1,cursor:0,cx:0,cy:0,d:0,datatype:0,decelerate:0,descent:0,diffuseConstant:1,direction:0,display:0,divisor:0,dominantBaseline:1,"dominant-baseline":"dominantBaseline",dur:0,dx:0,dy:0,edgeMode:1,elevation:0,enableBackground:1,"enable-background":"enableBackground",end:0,exponent:0,externalResourcesRequired:1,fill:0,fillOpacity:1,"fill-opacity":"fillOpacity",fillRule:1,"fill-rule":"fillRule",filter:0,filterRes:1,filterUnits:1,floodOpacity:1,"flood-opacity":"floodOpacity",floodColor:1,"flood-color":"floodColor",focusable:0,fontFamily:1,"font-family":"fontFamily",fontSize:1,"font-size":"fontSize",fontSizeAdjust:1,"font-size-adjust":"fontSizeAdjust",fontStretch:1,"font-stretch":"fontStretch",fontStyle:1,"font-style":"fontStyle",fontVariant:1,"font-variant":"fontVariant",fontWeight:1,"font-weight":"fontWeight",format:0,from:0,fx:0,fy:0,g1:0,g2:0,glyphName:1,"glyph-name":"glyphName",glyphOrientationHorizontal:1,"glyph-orientation-horizontal":"glyphOrientationHorizontal",glyphOrientationVertical:1,"glyph-orientation-vertical":"glyphOrientationVertical",glyphRef:1,gradientTransform:1,gradientUnits:1,hanging:0,horizAdvX:1,"horiz-adv-x":"horizAdvX",horizOriginX:1,"horiz-origin-x":"horizOriginX",ideographic:0,imageRendering:1,"image-rendering":"imageRendering",in2:0,in:0,inlist:0,intercept:0,k1:0,k2:0,k3:0,k4:0,k:0,kernelMatrix:1,kernelUnitLength:1,kerning:0,keyPoints:1,keySplines:1,keyTimes:1,lengthAdjust:1,letterSpacing:1,"letter-spacing":"letterSpacing",lightingColor:1,"lighting-color":"lightingColor",limitingConeAngle:1,local:0,markerEnd:1,"marker-end":"markerEnd",markerHeight:1,markerMid:1,"marker-mid":"markerMid",markerStart:1,"marker-start":"markerStart",markerUnits:1,markerWidth:1,mask:0,maskContentUnits:1,maskUnits:1,mathematical:0,mode:0,numOctaves:1,offset:0,opacity:0,operator:0,order:0,orient:0,orientation:0,origin:0,overflow:0,overlinePosition:1,"overline-position":"overlinePosition",overlineThickness:1,"overline-thickness":"overlineThickness",paintOrder:1,"paint-order":"paintOrder",panose1:0,"panose-1":"panose1",pathLength:1,patternContentUnits:1,patternTransform:1,patternUnits:1,pointerEvents:1,"pointer-events":"pointerEvents",points:0,pointsAtX:1,pointsAtY:1,pointsAtZ:1,prefix:0,preserveAlpha:1,preserveAspectRatio:1,primitiveUnits:1,property:0,r:0,radius:0,refX:1,refY:1,renderingIntent:1,"rendering-intent":"renderingIntent",repeatCount:1,repeatDur:1,requiredExtensions:1,requiredFeatures:1,resource:0,restart:0,result:0,results:0,rotate:0,rx:0,ry:0,scale:0,security:0,seed:0,shapeRendering:1,"shape-rendering":"shapeRendering",slope:0,spacing:0,specularConstant:1,specularExponent:1,speed:0,spreadMethod:1,startOffset:1,stdDeviation:1,stemh:0,stemv:0,stitchTiles:1,stopColor:1,"stop-color":"stopColor",stopOpacity:1,"stop-opacity":"stopOpacity",strikethroughPosition:1,"strikethrough-position":"strikethroughPosition",strikethroughThickness:1,"strikethrough-thickness":"strikethroughThickness",string:0,stroke:0,strokeDasharray:1,"stroke-dasharray":"strokeDasharray",strokeDashoffset:1,"stroke-dashoffset":"strokeDashoffset",strokeLinecap:1,"stroke-linecap":"strokeLinecap",strokeLinejoin:1,"stroke-linejoin":"strokeLinejoin",strokeMiterlimit:1,"stroke-miterlimit":"strokeMiterlimit",strokeWidth:1,"stroke-width":"strokeWidth",strokeOpacity:1,"stroke-opacity":"strokeOpacity",suppressContentEditableWarning:1,suppressHydrationWarning:1,surfaceScale:1,systemLanguage:1,tableValues:1,targetX:1,targetY:1,textAnchor:1,"text-anchor":"textAnchor",textDecoration:1,"text-decoration":"textDecoration",textLength:1,textRendering:1,"text-rendering":"textRendering",to:0,transform:0,typeof:0,u1:0,u2:0,underlinePosition:1,"underline-position":"underlinePosition",underlineThickness:1,"underline-thickness":"underlineThickness",unicode:0,unicodeBidi:1,"unicode-bidi":"unicodeBidi",unicodeRange:1,"unicode-range":"unicodeRange",unitsPerEm:1,"units-per-em":"unitsPerEm",unselectable:0,vAlphabetic:1,"v-alphabetic":"vAlphabetic",values:0,vectorEffect:1,"vector-effect":"vectorEffect",version:0,vertAdvY:1,"vert-adv-y":"vertAdvY",vertOriginX:1,"vert-origin-x":"vertOriginX",vertOriginY:1,"vert-origin-y":"vertOriginY",vHanging:1,"v-hanging":"vHanging",vIdeographic:1,"v-ideographic":"vIdeographic",viewBox:1,viewTarget:1,visibility:0,vMathematical:1,"v-mathematical":"vMathematical",vocab:0,widths:0,wordSpacing:1,"word-spacing":"wordSpacing",writingMode:1,"writing-mode":"writingMode",x1:0,x2:0,x:0,xChannelSelector:1,xHeight:1,"x-height":"xHeight",xlinkActuate:1,"xlink:actuate":"xlinkActuate",xlinkArcrole:1,"xlink:arcrole":"xlinkArcrole",xlinkHref:1,"xlink:href":"xlinkHref",xlinkRole:1,"xlink:role":"xlinkRole",xlinkShow:1,"xlink:show":"xlinkShow",xlinkTitle:1,"xlink:title":"xlinkTitle",xlinkType:1,"xlink:type":"xlinkType",xmlBase:1,"xml:base":"xmlBase",xmlLang:1,"xml:lang":"xmlLang",xmlns:0,"xml:space":"xmlSpace",xmlnsXlink:1,"xmlns:xlink":"xmlnsXlink",xmlSpace:1,y1:0,y2:0,y:0,yChannelSelector:1,z:0,zoomAndPan:1},gg}var mI;function WGe(){if(mI)return Bo;mI=1;const e=0,t=1,n=2,r=3,i=4,a=5,o=6;function s(b){return c.hasOwnProperty(b)?c[b]:null}function l(b,w,x,k,T,_,E){this.acceptsBooleans=w===n||w===r||w===i,this.attributeName=k,this.attributeNamespace=T,this.mustUseProperty=x,this.propertyName=b,this.type=w,this.sanitizeURL=_,this.removeEmptyString=E}const c={};["children","dangerouslySetInnerHTML","defaultValue","defaultChecked","innerHTML","suppressContentEditableWarning","suppressHydrationWarning","style"].forEach(b=>{c[b]=new l(b,e,!1,b,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(([b,w])=>{c[b]=new l(b,t,!1,w,null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(b=>{c[b]=new l(b,n,!1,b.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(b=>{c[b]=new l(b,n,!1,b,null,!1,!1)}),["allowFullScreen","async","autoFocus","autoPlay","controls","default","defer","disabled","disablePictureInPicture","disableRemotePlayback","formNoValidate","hidden","loop","noModule","noValidate","open","playsInline","readOnly","required","reversed","scoped","seamless","itemScope"].forEach(b=>{c[b]=new l(b,r,!1,b.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(b=>{c[b]=new l(b,r,!0,b,null,!1,!1)}),["capture","download"].forEach(b=>{c[b]=new l(b,i,!1,b,null,!1,!1)}),["cols","rows","size","span"].forEach(b=>{c[b]=new l(b,o,!1,b,null,!1,!1)}),["rowSpan","start"].forEach(b=>{c[b]=new l(b,a,!1,b.toLowerCase(),null,!1,!1)});const O=/[\-\:]([a-z])/g,d=b=>b[1].toUpperCase();["accent-height","alignment-baseline","arabic-form","baseline-shift","cap-height","clip-path","clip-rule","color-interpolation","color-interpolation-filters","color-profile","color-rendering","dominant-baseline","enable-background","fill-opacity","fill-rule","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","glyph-name","glyph-orientation-horizontal","glyph-orientation-vertical","horiz-adv-x","horiz-origin-x","image-rendering","letter-spacing","lighting-color","marker-end","marker-mid","marker-start","overline-position","overline-thickness","paint-order","panose-1","pointer-events","rendering-intent","shape-rendering","stop-color","stop-opacity","strikethrough-position","strikethrough-thickness","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","text-anchor","text-decoration","text-rendering","underline-position","underline-thickness","unicode-bidi","unicode-range","units-per-em","v-alphabetic","v-hanging","v-ideographic","v-mathematical","vector-effect","vert-adv-y","vert-origin-x","vert-origin-y","word-spacing","writing-mode","xmlns:xlink","x-height"].forEach(b=>{const w=b.replace(O,d);c[w]=new l(w,t,!1,b,null,!1,!1)}),["xlink:actuate","xlink:arcrole","xlink:role","xlink:show","xlink:title","xlink:type"].forEach(b=>{const w=b.replace(O,d);c[w]=new l(w,t,!1,b,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(b=>{const w=b.replace(O,d);c[w]=new l(w,t,!1,b,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(b=>{c[b]=new l(b,t,!1,b.toLowerCase(),null,!1,!1)});const f="xlinkHref";c[f]=new l("xlinkHref",t,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(b=>{c[b]=new l(b,t,!1,b.toLowerCase(),null,!0,!0)});const{CAMELCASE:p,SAME:m,possibleStandardNames:g}=UGe(),v=":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"+"\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040",S=RegExp.prototype.test.bind(new RegExp("^(data|aria)-["+v+"]*$")),Q=Object.keys(g).reduce((b,w)=>{const x=g[w];return x===m?b[w]=w:x===p?b[w.toLowerCase()]=w:b[w]=x,b},{});return Bo.BOOLEAN=r,Bo.BOOLEANISH_STRING=n,Bo.NUMERIC=a,Bo.OVERLOADED_BOOLEAN=i,Bo.POSITIVE_NUMERIC=o,Bo.RESERVED=e,Bo.STRING=t,Bo.getPropertyInfo=s,Bo.isCustomAttribute=S,Bo.possibleStandardNames=Q,Bo}var $g={},gh={},R5,gI;function NGe(){if(gI)return R5;gI=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,r=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,i=/^:\s*/,a=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,o=/^[;\s]*/,s=/^\s+|\s+$/g,l=`
516
- `,c="/",u="*",O="",d="comment",f="declaration";R5=function(m,g){if(typeof m!="string")throw new TypeError("First argument must be a string");if(!m)return[];g=g||{};var y=1,v=1;function S(j){var C=j.match(t);C&&(y+=C.length);var W=j.lastIndexOf(l);v=~W?j.length-W:v+j.length}function Q(){var j={line:y,column:v};return function(C){return C.position=new b(j),k(),C}}function b(j){this.start=j,this.end={line:y,column:v},this.source=g.source}b.prototype.content=m;function w(j){var C=new Error(g.source+":"+y+":"+v+": "+j);if(C.reason=j,C.filename=g.source,C.line=y,C.column=v,C.source=m,!g.silent)throw C}function x(j){var C=j.exec(m);if(C){var W=C[0];return S(W),m=m.slice(W.length),C}}function k(){x(n)}function T(j){var C;for(j=j||[];C=_();)C!==!1&&j.push(C);return j}function _(){var j=Q();if(!(c!=m.charAt(0)||u!=m.charAt(1))){for(var C=2;O!=m.charAt(C)&&(u!=m.charAt(C)||c!=m.charAt(C+1));)++C;if(C+=2,O===m.charAt(C-1))return w("End of comment missing");var W=m.slice(2,C-2);return v+=2,S(W),m=m.slice(C),v+=2,j({type:d,comment:W})}}function E(){var j=Q(),C=x(r);if(C){if(_(),!x(i))return w("property missing ':'");var W=x(a),G=j({type:f,property:p(C[0].replace(e,O)),value:W?p(W[0].replace(e,O)):O});return x(o),G}}function R(){var j=[];T(j);for(var C;C=E();)C!==!1&&(j.push(C),T(j));return j}return k(),R()};function p(m){return m?m.replace(s,O):O}return R5}var $I;function YGe(){if($I)return gh;$I=1;var e=gh&&gh.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(gh,"__esModule",{value:!0}),gh.default=n;var t=e(NGe());function n(r,i){var a=null;if(!r||typeof r!="string")return a;var o=(0,t.default)(r),s=typeof i=="function";return o.forEach(function(l){if(l.type==="declaration"){var c=l.property,u=l.value;s?i(c,u,l):u&&(a=a||{},a[c]=u)}}),a}return gh}var yg={},yI;function GGe(){if(yI)return yg;yI=1,Object.defineProperty(yg,"__esModule",{value:!0}),yg.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,n=/^[^-]+$/,r=/^-(webkit|moz|ms|o|khtml)-/,i=/^-(ms)-/,a=function(c){return!c||n.test(c)||e.test(c)},o=function(c,u){return u.toUpperCase()},s=function(c,u){return"".concat(u,"-")},l=function(c,u){return u===void 0&&(u={}),a(c)?c:(c=c.toLowerCase(),u.reactCompat?c=c.replace(i,s):c=c.replace(r,s),c.replace(t,o))};return yg.camelCase=l,yg}var vg,vI;function hde(){if(vI)return vg;vI=1;var e=vg&&vg.__importDefault||function(i){return i&&i.__esModule?i:{default:i}},t=e(YGe()),n=GGe();function r(i,a){var o={};return!i||typeof i!="string"||(0,t.default)(i,function(s,l){s&&l&&(o[(0,n.camelCase)(s,a)]=l)}),o}return r.default=r,vg=r,vg}var bI;function pde(){return bI||(bI=1,function(e){var t=$g&&$g.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(e,"__esModule",{value:!0}),e.returnFirstArg=e.canTextBeChildOfNode=e.ELEMENTS_WITH_NO_TEXT_CHILDREN=e.PRESERVE_CUSTOM_ATTRIBUTES=void 0,e.isCustomComponent=a,e.setStyleProp=s;var n=Bse(),r=t(hde()),i=new Set(["annotation-xml","color-profile","font-face","font-face-src","font-face-uri","font-face-format","font-face-name","missing-glyph"]);function a(u,O){return u.includes("-")?!i.has(u):!!(O&&typeof O.is=="string")}var o={reactCompat:!0};function s(u,O){if(typeof u=="string"){if(!u.trim()){O.style={};return}try{O.style=(0,r.default)(u,o)}catch{O.style={}}}}e.PRESERVE_CUSTOM_ATTRIBUTES=Number(n.version.split(".")[0])>=16,e.ELEMENTS_WITH_NO_TEXT_CHILDREN=new Set(["tr","tbody","thead","tfoot","colgroup","table","head","html","frameset"]);var l=function(u){return!e.ELEMENTS_WITH_NO_TEXT_CHILDREN.has(u.name)};e.canTextBeChildOfNode=l;var c=function(u){return u};e.returnFirstArg=c}($g)),$g}var wI;function mde(){if(wI)return Sb;wI=1,Object.defineProperty(Sb,"__esModule",{value:!0}),Sb.default=a;var e=WGe(),t=pde(),n=["checked","value"],r=["input","select","textarea"],i={reset:!0,submit:!0};function a(s,l){s===void 0&&(s={});var c={},u=!!(s.type&&i[s.type]);for(var O in s){var d=s[O];if((0,e.isCustomAttribute)(O)){c[O]=d;continue}var f=O.toLowerCase(),p=o(f);if(p){var m=(0,e.getPropertyInfo)(p);switch(n.includes(p)&&r.includes(l)&&!u&&(p=o("default"+f)),c[p]=d,m&&m.type){case e.BOOLEAN:c[p]=!0;break;case e.OVERLOADED_BOOLEAN:d===""&&(c[p]=!0);break}continue}t.PRESERVE_CUSTOM_ATTRIBUTES&&(c[O]=d)}return(0,t.setStyleProp)(s.style,c),c}function o(s){return e.possibleStandardNames[s]}return Sb}var $h={},SI;function IGe(){if(SI)return $h;SI=1;var e=$h&&$h.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty($h,"__esModule",{value:!0}),$h.default=a;var t=Bse(),n=e(mde()),r=pde(),i={cloneElement:t.cloneElement,createElement:t.createElement,isValidElement:t.isValidElement};function a(s,l){l===void 0&&(l={});for(var c=[],u=typeof l.replace=="function",O=l.transform||r.returnFirstArg,d=l.library||i,f=d.cloneElement,p=d.createElement,m=d.isValidElement,g=s.length,y=0;y<g;y++){var v=s[y];if(u){var S=l.replace(v,y);if(m(S)){g>1&&(S=f(S,{key:S.key||y})),c.push(O(S,v,y));continue}}if(v.type==="text"){var Q=!v.data.trim().length;if(Q&&v.parent&&!(0,r.canTextBeChildOfNode)(v.parent)||l.trim&&Q)continue;c.push(O(v.data,v,y));continue}var b=v,w={};o(b)?((0,r.setStyleProp)(b.attribs.style,b.attribs),w=b.attribs):b.attribs&&(w=(0,n.default)(b.attribs,b.name));var x=void 0;switch(v.type){case"script":case"style":v.children[0]&&(w.dangerouslySetInnerHTML={__html:v.children[0].data});break;case"tag":v.name==="textarea"&&v.children[0]?w.defaultValue=v.children[0].data:v.children&&v.children.length&&(x=a(v.children,l));break;default:continue}g>1&&(w.key=y),c.push(O(p(v.name,w,x),v,y))}return c.length===1?c[0]:c}function o(s){return r.PRESERVE_CUSTOM_ATTRIBUTES&&s.type==="tag"&&(0,r.isCustomComponent)(s.name,s.attribs)}return $h}var xI;function ZGe(){return xI||(xI=1,function(e){var t=mg&&mg.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(e,"__esModule",{value:!0}),e.htmlToDOM=e.domToReact=e.attributesToProps=e.Text=e.ProcessingInstruction=e.Element=e.Comment=void 0,e.default=s;var n=t(zGe());e.htmlToDOM=n.default;var r=t(mde());e.attributesToProps=r.default;var i=t(IGe());e.domToReact=i.default;var a=dde();Object.defineProperty(e,"Comment",{enumerable:!0,get:function(){return a.Comment}}),Object.defineProperty(e,"Element",{enumerable:!0,get:function(){return a.Element}}),Object.defineProperty(e,"ProcessingInstruction",{enumerable:!0,get:function(){return a.ProcessingInstruction}}),Object.defineProperty(e,"Text",{enumerable:!0,get:function(){return a.Text}});var o={lowerCaseAttributeNames:!1};function s(l,c){if(typeof l!="string")throw new TypeError("First argument must be a string");return l?(0,i.default)((0,n.default)(l,c?.htmlparser2||o),c):[]}}(mg)),mg}var DGe=ZGe();const QI=er(DGe),vun=QI.default||QI,MGe=e=>e.includes("loopback or private")?"Could not open that link. The app does not open links to your own machine or local network.":"Could not open that link.",gde=e=>{mi(MGe(e))};function bun(){const e=window.api?.onExternalOpenRefused;return typeof e!="function"?()=>{}:e(t=>{gde(t.reason)})}const $de=2200,wun=120,Sun=180,xun=.45,Qun="cubic-bezier(0.4, 0, 0.6, 1)",bg="data-lo-scrollbar",X5="active",kI="idle",VGe="data-undo-scope",LGe={now:()=>Date.now(),setTimer:(e,t)=>setTimeout(e,t),clearTimer:e=>clearTimeout(e)},PI=/^(auto|scroll)$/,FGe=e=>{const t=getComputedStyle(e);return PI.test(t.overflowX)||PI.test(t.overflowY)},BGe="contenteditable",E5=e=>{let t=e;for(;t!==null;){if(t.isContentEditable===!0||t.getAttribute(BGe)!==null||t.getAttribute(VGe)!==null)return!0;t=t.parentElement}return!1},q5=e=>e!==null&&e.nodeType===1?e:null,HGe=":focus-visible";function kun(e={}){const t=e.doc??document,n=e.clock??LGe,r=e.holdMs??$de,i=new Map,a=new WeakMap,o=new WeakMap;let s=null;const l=v=>{const S=a.get(v);if(S!==void 0)return S;const Q=(e.isScroller??FGe)(v);return Q&&a.set(v,Q),Q},c=v=>{const S=q5(v);if(S===null)return null;const Q=o.get(S);if(Q!==void 0)return Q;if(E5(S))return null;let b=null,w=S;for(;w!==null;){if(l(w)){b=w;break}w=w.parentElement}return b!==null&&o.set(S,b),b},u=v=>{if(v===null||v.isConnected!==!0)return;const S=v.getAttribute(bg);S!==X5&&(S===null&&v.setAttribute(bg,kI),v.setAttribute(bg,X5)),i.set(v,n.now()+r),d()};function O(){s=null;const v=n.now();for(const[S,Q]of[...i]){if(S.isConnected!==!0){i.delete(S);continue}Q<=v&&(i.delete(S),S.getAttribute(bg)===X5&&S.setAttribute(bg,kI))}d()}function d(){if(s!==null||i.size===0)return;let v=Number.POSITIVE_INFINITY;for(const S of i.values())S<v&&(v=S);s=n.setTimer(O,Math.max(v-n.now(),0))}const f=v=>{const S=q5(v.target);S!==null&&l(S)&&(E5(S)||u(S))},p=v=>{u(c(v.target))},m=v=>{u(c(v.target))},g=v=>{const S=q5(v.target);S===null||E5(S)||!(typeof S.matches!="function"||S.matches(HGe))||u(c(S))},y={capture:!0,passive:!0};return t.addEventListener("scroll",f,y),t.addEventListener("pointerover",p,y),t.addEventListener("pointerdown",m,y),t.addEventListener("focusin",g,y),()=>{t.removeEventListener("scroll",f,y),t.removeEventListener("pointerover",p,y),t.removeEventListener("pointerdown",m,y),t.removeEventListener("focusin",g,y),s!==null&&(n.clearTimer(s),s=null),i.clear()}}const _I=new Map,TI=new Map,RI=new Map;function Nz(e){return e===void 0?"":JSON.stringify(e)}function Yz(e,t){const n=`${e}\0${Nz(t)}`;let r=_I.get(n);return r===void 0&&(r=new Intl.DateTimeFormat(e,t),_I.set(n,r)),r}function KGe(e,t){const n=`${e}\0${Nz(t)}`;let r=TI.get(n);return r===void 0&&(r=new Intl.NumberFormat(e,t),TI.set(n,r)),r}function yde(e,t,n){return Yz(n??ov(),t).format(e)}function JGe(e,t,n){return Yz(n??ov(),t).format(e)}function eIe(e,t,n){return Yz(n??ov(),t).format(e)}function vde(e,t,n){return KGe(n??ov(),t).format(e)}function Pun(e,t,n,r){const i=ov(),a=`${i}\0${Nz(n)}`;let o=RI.get(a);return o===void 0&&(o=new Intl.RelativeTimeFormat(i,n),RI.set(a,o)),o.format(e,t)}const tIe=5e3;let bde=0;function nIe(e=tIe){bde=Date.now()+e}function _un(e=Date.now()){return e<=bde}function rIe(e){nIe(),e.invalidateQueries({queryKey:ri.capabilities})}function iIe(){const e=new Set,t=new Set;let n=0,r=null,i=0;const a=new WeakMap,o=()=>{n+=1;for(const c of t)c()},s=()=>{i+=1,e.size!==0&&(e.clear(),o())},l=c=>{e.has(c)||(e.add(c),o())};return{note:l,noteFrame:(c,u)=>{const O=a.get(u);return O===void 0&&a.set(u,i),(O??i)!==i?!1:(c!==null&&l(c),!0)},has:c=>e.has(c),reset:()=>{r=null,s()},observeProcess:c=>{const u=r;r=c,u!==null&&u!==c&&s()},subscribe:c=>(t.add(c),()=>void t.delete(c)),version:()=>n}}const j5=iIe();function wde(){const e=Ri(),t=window.api?.desktop?.feed,n=oi(e.data,"desktop_feed")&&!!t,[r,i]=$.useState(!1),[a,o]=$.useState(!1),[s,l]=$.useState(null),[c,u]=$.useState(0),[O,d]=$.useState(null),[f,p]=$.useState(0),[m,g]=$.useState(null),[y,v]=$.useState(null),S=$.useRef(!1),Q=$.useRef(!1);return $.useEffect(()=>{if(!n||!t){S.current=!1,i(!1),o(!1),j5.reset();return}const b=ar.getState().applyAttention,w=ar.getState().applySessionStatus,x=t.watchState(({connected:T})=>{T&&(Q.current&&!S.current&&p(_=>_+1),Q.current=!0),T||j5.reset(),S.current=T,o(!0),i(T)}),k=t.subscribe(T=>{if(j5.observeProcess(T.epoch),T.type==="attention"){b(T.session_id,T.payload),T.payload.unseen===!0&&u(_=>_+1);return}if(T.type==="session_status"){w(T.session_id,{code:T.payload.code,label:T.payload.label},T.payload.revision,T.epoch),u(_=>_+1);return}if(T.type==="catalogue"){l(T.payload.revision);return}if(T.type==="authoring"&&d(T.payload.revision),T.type==="code_requests"){g({sessionId:T.session_id,revision:T.payload.revision});return}T.type==="config"&&v({changedKeys:T.payload.changed_keys,language:T.payload.language,epoch:T.epoch,seq:T.seq})});return()=>{k(),x()}},[n,t]),{available:n,connected:n&&r,reported:n&&a,catalogueRevision:s,activityRevision:c,authoringRevision:O,authoringReconnectRevision:f,codeRequestsRevision:m,configChange:y}}function Gz(e){return e.label?.trim()||e.name}function Tun(e,t){return vk("profiles"),jt({queryKey:["desktop","profile",e],enabled:t&&!!e,queryFn:()=>Re({op:"profiles.get",name:e??""}),retry:!1})}function Run(e,t){return vk("teams"),jt({queryKey:["desktop","team",e],enabled:t&&!!e,queryFn:()=>Re({op:"teams.get",name:e??""}),retry:!1})}function Xun(e,t){return jt({queryKey:["desktop","team",e,"effective"],enabled:t&&!!e,queryFn:()=>Re({op:"teams.effective",name:e??""}),retry:!1})}function Eun(e){for(const t of[["desktop","profiles"],["desktop","teams"],["desktop","profile"],["desktop","team"]])e.invalidateQueries({queryKey:[...t]})}function aIe(e){return vk("profiles"),jt({queryKey:["desktop","profiles"],enabled:e,queryFn:()=>Re({op:"profiles.list"}).then(t=>t.profiles),retry:Ua,staleTime:1e4})}function vk(e){const{authoringRevision:t,authoringReconnectRevision:n}=wde(),r=cc(),i=$.useRef(t),a=$.useRef(n);$.useEffect(()=>{if(t!==null&&t!==i.current){i.current=t,a.current=n,r.invalidateQueries({queryKey:["desktop",e]}),r.invalidateQueries({queryKey:["desktop",e==="profiles"?"profile":"team"]});return}n!==a.current&&(a.current=n,r.invalidateQueries({queryKey:["desktop",e]}),r.invalidateQueries({queryKey:["desktop",e==="profiles"?"profile":"team"]}))},[t,n,e,r])}function Sde(e){return vk("teams"),jt({queryKey:["desktop","teams"],enabled:e,queryFn:()=>Re({op:"teams.list"}).then(t=>t.teams),retry:Ua,staleTime:1e4})}function oIe(e){const t=Sde(e);return $.useMemo(()=>{const n=new Map((t.data??[]).map(r=>[r.name,Gz(r)]));return r=>n.get(r)??r},[t.data])}const sIe=/\s+/g,lIe=/(?<=[.!?])\s/,cIe="The aside was not answered.";function xde(e){return Io(e,cIe)}const uIe=new Set(["aside_unanswered","aside_empty_answer"]);function Qde(e){return e instanceof Ut&&e.code!==void 0&&uIe.has(e.code)}const OIe="This aside can't continue. Press Esc to close it, which discards this exchange, then start a new one with /btw.",dIe="Ask again here to keep this exchange, or press Esc to close the aside and discard it.",fIe=/\s+[Aa]sk again\.$/;function hIe(e,t){const n=xde(e);return t?Qde(e)?`${n.replace(fIe,"")} ${dIe}`:`${n} ${OIe}`:n}const XI=60;function pIe(e){const t=e.trim().replace(sIe," ");return t.length>XI?`“${t.slice(0,XI-1)}…”`:`“${t}”`}function mIe(e,t){return`Your aside ${pIe(e)} got no answer: ${gIe(t)}`}function gIe(e){return Qde(e)?"The model didn't reply in text. Ask again.":xde(e)}const $Ie="The aside is still answering. Press Enter again once the answer is in.",yIe="This aside is queued to join the conversation. Ask again once it has been added.";function qun(e,t){return e.attached[t]?.queued?yIe:u3e(e,t)?.streaming?$Ie:null}function jun(e,t,n){const r=KA(Pr.getState(),t);e.catch(i=>{const a=Pr.getState();r&&Pce(a,r.asideId)||n(mIe(r?.question??"",i))})}const vIe="The request has invalid fields.";function bIe(e,t){return t&&e instanceof Ut&&e.status===422&&e.message===vIe}const h0=new Set,wIe=64;function SIe(e){for(h0.add(e);h0.size>wIe;){const t=h0.values().next().value;if(t===void 0)return;h0.delete(t)}}function Cun(e){Pr.getState().attachAside(e)}async function Aun(e,t,n){const r=fs(),i=Pr.getState(),a=_ce(i,e);i.beginAsk(e,r,t);const o=l=>Re({op:"sessions.aside",sessionId:e,requestId:r,text:t,asideId:a,subscriptionId:l?n:void 0}),s=!!n&&!h0.has(e);try{let l;try{l=await o(s)}catch(c){if(!bIe(c,s))throw c;SIe(e),l=await o(!1)}return Pr.getState().settleAside(r,l.data.text),r}catch(l){throw Pr.getState().failAside(r,hIe(l,a!==void 0)),l}}async function kde(e){const t=Pr.getState(),n=Tce(t,e);if(!n)return;let r;try{r=await Re({op:"sessions.adopt",sessionId:e,requestId:fs(),asideId:n,confirmed:!0})}catch(i){throw t.setAsideNotice(e,kIe(i)),i}if(xIe(r)==="queued"){Pr.getState().queueAdoption(e,n,[]),PIe(e,n).then(i=>{const a=Pr.getState().attached[e]?.queued;i.length>0&&a?.asideId===n&&Pr.getState().queueAdoption(e,n,i)});return}jce(e),Pr.getState().detachAside(e)}function xIe(e){return e?.data?.status==="queued"?"queued":"adopted"}const EI="Queued — this aside joins the conversation when the current turn finishes.",QIe={session_closed:"The aside was not added: this conversation has closed, so there is nothing to add it to.",open_tool_batch:"The conversation stopped in the middle of a tool call, so the aside was not added. Send a message to continue the conversation, then add the aside.",turn_running:"This conversation is busy, and the version it's running can't queue an aside. Add it when the reply finishes."};function kIe(e){if(e instanceof Ut&&e.code===ARe){const t=zRe(e.detail);if(t)return QIe[t]}return Io(e,"The aside was not added to the conversation.")}async function PIe(e,t){try{return((await Re({op:"sessions.aside.get",sessionId:e,asideId:t}))?.data?.turns??[]).map(r=>r?.id).filter(r=>typeof r=="string"&&r!=="")}catch{return[]}}const qI=1500,_Ie="The aside was not added to the conversation. Add it again to try once more.",TIe="The aside could not be confirmed in the conversation. If it is not there, add it again.";function RIe(e){return e.messageIds.length>0&&e.messageIds.every(t=>e.hasRecord(t))?"landed":e.turnAlive?"wait":"resync"}const Rd=new Map;function jI(e){const t=Rd.get(e);t!==void 0&&clearTimeout(t),Rd.delete(e)}function zun(e,t,n){const r=Pr.getState().attached[e]?.queued;if(!r)return;const{asideId:i}=r,a=RIe({messageIds:r.messageIds,hasRecord:t,turnAlive:n});if(a==="landed"){jI(i),Pr.getState().detachAside(e);return}if(a==="wait"){jI(i);return}if(Rd.has(i))return;const o=()=>Pr.getState().attached[e]?.queued?.asideId===i;Rd.set(i,setTimeout(()=>{if(!o()){Rd.delete(i);return}jce(e),Rd.set(i,setTimeout(()=>{if(Rd.delete(i),!o())return;const s=Pr.getState().attached[e]?.queued?.messageIds.length??0;Pr.getState().unqueueAdoption(e,i,s>0?_Ie:TIe)},qI))},qI))}function Uj(e){const t=Pr.getState(),n=_ce(t,e)??Tce(t,e);n&&Re({op:"sessions.aside.close",sessionId:e,asideId:n}).catch(()=>{}),Pr.getState().detachAside(e)}function XIe(e){return e.defaultPrevented||e.repeat||e.isComposing||e.shiftKey||e.altKey||e.key.toLowerCase()!=="f"?!1:e.metaKey||e.ctrlKey}const Pde=e=>e?"⌘+F":"Ctrl+F",CI=e=>`Press ${Pde(e)} again to add the aside to the conversation. Once added, it stays there.`,EIe=400;function qIe(e,t,n){return e?.turnId!==t?"arm":n-e.at<EIe?"ignore":"adopt"}function _de(e,t,n=!1){return!!e?.settled&&(n||!t)}function jIe(e,t,n=!1){return e?e.error!==null?"Nothing to add.":t&&!n?"This conversation is working. Adding the aside while it runs would splice a message into a live turn.":e.streaming?"The exchange is still settling — a moment before it can be added.":null:"Nothing to add yet."}function Tde(e){return e.scrollTop+(e.turnTop-e.regionTop)}function CIe(e){const t=Math.max(0,e.scrollHeight-e.clientHeight);return Math.min(t,Math.max(0,Tde(e)))}function AIe(e,t){return e===t}function zIe(e){return e.scrollTop<e.offset&&e.maxScroll<e.offset&&e.clientHeight>e.writtenClientHeight&&Math.abs(e.scrollTop-e.maxScroll)<=1}function UIe(e){return e?`${e.error!==null?"refused":e.settled?"settled":"live"}:${e.text.length}`:"none"}const AI=140,WIe=[[/!?\[([^\]]*)\]\([^)]*\)/g,"$1"],[/`(?=\S)([^`]*?\S)`/g,"$1"],[/\*\*(?=\S)([\s\S]*?\S)\*\*/g,"$1"],[/__(?=\S)([\s\S]*?\S)__/g,"$1"],[/~~(?=\S)([^~]*?\S)~~/g,"$1"],[/\*(?=\S)([^*]*?\S)\*/g,"$1"],[/(?<![A-Za-z0-9_])_(?=\S)([^_]*?\S)_(?!\w)/g,"$1"]];function NIe(e){return WIe.reduce((t,[n,r])=>t.replace(n,r),e)}function YIe(e){if(!e)return null;if(e.error!==null)return"The aside was not answered";if(e.streaming)return"Asking the aside";const t=NIe(e.text.trim()).split(lIe)[0]??"";return t.length===0?"The aside answered":t.length>AI?`The aside answered: ${t.slice(0,AI)}…`:`The aside answered: ${t}`}const GIe=new Set(["job_result","hub_message","monitor_prompt"]),IIe="no_reply";function Dc(e){return e.kind==="tool"&&e.toolName===IIe}function kO(e){return!(!Dc(e)||e.phase!=="done"||e.isError===!0||e.stopped===!0||e.neverSent===!0||e.notRunReason!==null&&e.notRunReason!==void 0||_p(e.notRunKind))}function Xp(e){switch(e.kind){case"user":return"user";case"peer":return"peer";case"wake":return"wake";case"custom":return GIe.has(e.customType)?e.customType:null;default:return null}}function PS(e){return e.kind==="assistant"&&!e.streaming&&e.stopReason==="stop"}function Rde(e){return e.kind==="notice"&&e.complete===!0}function Iz(e){switch(e.kind){case"compaction":return"compaction";case"notice":return Rde(e)?"terminal":null;case"custom":return e.level==="error"?"terminal":null;default:return null}}function bk(e){return Iz(e)==="terminal"}function Xde(e,t){const n=e.length,r=new Array(n).fill(!1);let i=!1;for(let l=n-1;l>=0;l-=1){const c=e[l];Xp(c)!==null?i=!1:c.kind==="tool"?(kO(c)&&(r[l]=!0),i=!0):c.kind==="assistant"&&!c.streaming&&t(c)&&!i&&(r[l]=!0)}const a=[];let o=0,s=!1;for(let l=0;l<n;l+=1){const c=e[l];if(bk(c)&&(s=!0),!r[l])continue;let u=-1;const O=[];for(let m=o;m<l;m+=1){const g=Xp(e[m]);u===-1&&e[m].kind==="tool"&&(u=m),g!==null&&(u===-1||g==="user")&&O.push(g)}const d=a.at(-1)??null;let f,p;d===null?(f="response",p=O.includes("user")?"user":"head-cut"):O.includes("user")?(f="response",p="user"):O.some(m=>m==="wake"||m==="peer")&&s?(f="commentary",p="post-terminal"):(f=d.class,p="continuation"),a.push({start:o,closeIndex:l,class:f,why:p,initiators:O}),o=l+1,s=!1}return a}function Ede(e,t,n){const r=t.length>0?t[t.length-1].closeIndex:-1;let i=!1;for(let a=e.length-1;a>r;a-=1)bk(e[a])&&(i=!0);for(let a=e.length-1;a>=0;a-=1){const o=e[a];if(!(o.kind==="user"||!n.paints(o))&&!n.isStatement(o)){if(o.kind==="assistant"&&!o.streaming||o.kind!=="assistant"&&i)break;return null}}for(let a=t.length-1;a>=0;a-=1)if(t[a].class==="response")return kO(e[t[a].closeIndex])?null:t[a];return null}function ZIe(e,t){const n=Xde(e,t.paints),r=Ede(e,n,t),i=new Set;if(e.forEach((s,l)=>{l>=t.from&&t.pinned(s)&&i.add(l)}),r!==null){i.add(r.closeIndex);const s=n[n.length-1].closeIndex;for(let l=e.length-1;l>s;l-=1){const c=e[l];if(!t.isStatement(c))break;i.add(l)}}for(const s of n)s.class==="response"&&!kO(e[s.closeIndex])&&i.add(s.closeIndex);if(n.length>0){const s=n[n.length-1];kO(e[s.closeIndex])||i.add(s.closeIndex)}e.forEach((s,l)=>{l<t.from||(s.kind==="user"||t.paints(s)&&PS(s))&&i.add(l)}),(t.mode??tle)==="by-response"&&e.forEach((s,l)=>{l<t.from||s.kind!=="assistant"||s.streaming||t.paints(s)&&i.add(l)});const a=[];let o=null;for(let s=t.from;s<e.length;s+=1)i.has(s)?(o!==null&&a.push({from:o,to:s-1}),o=null):o===null&&(o=s);return o!==null&&a.push({from:o,to:e.length-1}),{cycles:n,answer:r,segments:a,visible:i}}function DIe(e){switch(e){case"peer":return"Peer messages";case"wake":return"Wake messages";case"monitor":return"Monitor messages";case"job":return"Job results";default:return"Messages"}}function MIe(e,t,n,r){for(let o=n.from;o<=n.to;o+=1)if(e[o].kind==="user")return"Steered";if(r!=null)return DIe(r.family);const i=t.find(o=>o.start<=n.to&&n.to<=o.closeIndex);let a=i?.initiators.at(-1)??null;if(i===void 0){const o=t.filter(s=>s.closeIndex<n.from);for(let s=(o.at(-1)?.closeIndex??-1)+1;s<=n.to&&e[s].kind!=="tool";s+=1)a=Xp(e[s])??a}switch(a){case"wake":case"monitor_prompt":return"Wake";case"peer":case"hub_message":return"Peer message";case"job_result":return"Job result";default:for(let o=n.from;o<=n.to;o+=1){const s=e[o].kind;if(s==="ask_response"||s==="ask_timeout")return"Ask"}return null}}function VIe(e,t,n,r,i,a=null){const o=r??a;if(o===null||!(n.from>o)&&!i&&r!==null||!t.some(O=>O.start<=n.to&&n.to<=O.closeIndex))return!1;const l=e[n.to];if(!(l.kind==="assistant"?!l.streaming:l.kind==="tool"?l.phase==="done":!1))return!1;const u=n.to+1<e.length?e[n.to+1]:null;return u===null||Iz(u)!=="terminal"}const LIe=e=>{const t=e.split(`
516
+ `,c="/",u="*",O="",d="comment",f="declaration";R5=function(m,g){if(typeof m!="string")throw new TypeError("First argument must be a string");if(!m)return[];g=g||{};var y=1,v=1;function S(j){var C=j.match(t);C&&(y+=C.length);var W=j.lastIndexOf(l);v=~W?j.length-W:v+j.length}function Q(){var j={line:y,column:v};return function(C){return C.position=new b(j),k(),C}}function b(j){this.start=j,this.end={line:y,column:v},this.source=g.source}b.prototype.content=m;function w(j){var C=new Error(g.source+":"+y+":"+v+": "+j);if(C.reason=j,C.filename=g.source,C.line=y,C.column=v,C.source=m,!g.silent)throw C}function x(j){var C=j.exec(m);if(C){var W=C[0];return S(W),m=m.slice(W.length),C}}function k(){x(n)}function T(j){var C;for(j=j||[];C=_();)C!==!1&&j.push(C);return j}function _(){var j=Q();if(!(c!=m.charAt(0)||u!=m.charAt(1))){for(var C=2;O!=m.charAt(C)&&(u!=m.charAt(C)||c!=m.charAt(C+1));)++C;if(C+=2,O===m.charAt(C-1))return w("End of comment missing");var W=m.slice(2,C-2);return v+=2,S(W),m=m.slice(C),v+=2,j({type:d,comment:W})}}function E(){var j=Q(),C=x(r);if(C){if(_(),!x(i))return w("property missing ':'");var W=x(a),G=j({type:f,property:p(C[0].replace(e,O)),value:W?p(W[0].replace(e,O)):O});return x(o),G}}function R(){var j=[];T(j);for(var C;C=E();)C!==!1&&(j.push(C),T(j));return j}return k(),R()};function p(m){return m?m.replace(s,O):O}return R5}var $I;function YGe(){if($I)return gh;$I=1;var e=gh&&gh.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(gh,"__esModule",{value:!0}),gh.default=n;var t=e(NGe());function n(r,i){var a=null;if(!r||typeof r!="string")return a;var o=(0,t.default)(r),s=typeof i=="function";return o.forEach(function(l){if(l.type==="declaration"){var c=l.property,u=l.value;s?i(c,u,l):u&&(a=a||{},a[c]=u)}}),a}return gh}var yg={},yI;function GGe(){if(yI)return yg;yI=1,Object.defineProperty(yg,"__esModule",{value:!0}),yg.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,n=/^[^-]+$/,r=/^-(webkit|moz|ms|o|khtml)-/,i=/^-(ms)-/,a=function(c){return!c||n.test(c)||e.test(c)},o=function(c,u){return u.toUpperCase()},s=function(c,u){return"".concat(u,"-")},l=function(c,u){return u===void 0&&(u={}),a(c)?c:(c=c.toLowerCase(),u.reactCompat?c=c.replace(i,s):c=c.replace(r,s),c.replace(t,o))};return yg.camelCase=l,yg}var vg,vI;function hde(){if(vI)return vg;vI=1;var e=vg&&vg.__importDefault||function(i){return i&&i.__esModule?i:{default:i}},t=e(YGe()),n=GGe();function r(i,a){var o={};return!i||typeof i!="string"||(0,t.default)(i,function(s,l){s&&l&&(o[(0,n.camelCase)(s,a)]=l)}),o}return r.default=r,vg=r,vg}var bI;function pde(){return bI||(bI=1,function(e){var t=$g&&$g.__importDefault||function(u){return u&&u.__esModule?u:{default:u}};Object.defineProperty(e,"__esModule",{value:!0}),e.returnFirstArg=e.canTextBeChildOfNode=e.ELEMENTS_WITH_NO_TEXT_CHILDREN=e.PRESERVE_CUSTOM_ATTRIBUTES=void 0,e.isCustomComponent=a,e.setStyleProp=s;var n=Bse(),r=t(hde()),i=new Set(["annotation-xml","color-profile","font-face","font-face-src","font-face-uri","font-face-format","font-face-name","missing-glyph"]);function a(u,O){return u.includes("-")?!i.has(u):!!(O&&typeof O.is=="string")}var o={reactCompat:!0};function s(u,O){if(typeof u=="string"){if(!u.trim()){O.style={};return}try{O.style=(0,r.default)(u,o)}catch{O.style={}}}}e.PRESERVE_CUSTOM_ATTRIBUTES=Number(n.version.split(".")[0])>=16,e.ELEMENTS_WITH_NO_TEXT_CHILDREN=new Set(["tr","tbody","thead","tfoot","colgroup","table","head","html","frameset"]);var l=function(u){return!e.ELEMENTS_WITH_NO_TEXT_CHILDREN.has(u.name)};e.canTextBeChildOfNode=l;var c=function(u){return u};e.returnFirstArg=c}($g)),$g}var wI;function mde(){if(wI)return Sb;wI=1,Object.defineProperty(Sb,"__esModule",{value:!0}),Sb.default=a;var e=WGe(),t=pde(),n=["checked","value"],r=["input","select","textarea"],i={reset:!0,submit:!0};function a(s,l){s===void 0&&(s={});var c={},u=!!(s.type&&i[s.type]);for(var O in s){var d=s[O];if((0,e.isCustomAttribute)(O)){c[O]=d;continue}var f=O.toLowerCase(),p=o(f);if(p){var m=(0,e.getPropertyInfo)(p);switch(n.includes(p)&&r.includes(l)&&!u&&(p=o("default"+f)),c[p]=d,m&&m.type){case e.BOOLEAN:c[p]=!0;break;case e.OVERLOADED_BOOLEAN:d===""&&(c[p]=!0);break}continue}t.PRESERVE_CUSTOM_ATTRIBUTES&&(c[O]=d)}return(0,t.setStyleProp)(s.style,c),c}function o(s){return e.possibleStandardNames[s]}return Sb}var $h={},SI;function IGe(){if(SI)return $h;SI=1;var e=$h&&$h.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty($h,"__esModule",{value:!0}),$h.default=a;var t=Bse(),n=e(mde()),r=pde(),i={cloneElement:t.cloneElement,createElement:t.createElement,isValidElement:t.isValidElement};function a(s,l){l===void 0&&(l={});for(var c=[],u=typeof l.replace=="function",O=l.transform||r.returnFirstArg,d=l.library||i,f=d.cloneElement,p=d.createElement,m=d.isValidElement,g=s.length,y=0;y<g;y++){var v=s[y];if(u){var S=l.replace(v,y);if(m(S)){g>1&&(S=f(S,{key:S.key||y})),c.push(O(S,v,y));continue}}if(v.type==="text"){var Q=!v.data.trim().length;if(Q&&v.parent&&!(0,r.canTextBeChildOfNode)(v.parent)||l.trim&&Q)continue;c.push(O(v.data,v,y));continue}var b=v,w={};o(b)?((0,r.setStyleProp)(b.attribs.style,b.attribs),w=b.attribs):b.attribs&&(w=(0,n.default)(b.attribs,b.name));var x=void 0;switch(v.type){case"script":case"style":v.children[0]&&(w.dangerouslySetInnerHTML={__html:v.children[0].data});break;case"tag":v.name==="textarea"&&v.children[0]?w.defaultValue=v.children[0].data:v.children&&v.children.length&&(x=a(v.children,l));break;default:continue}g>1&&(w.key=y),c.push(O(p(v.name,w,x),v,y))}return c.length===1?c[0]:c}function o(s){return r.PRESERVE_CUSTOM_ATTRIBUTES&&s.type==="tag"&&(0,r.isCustomComponent)(s.name,s.attribs)}return $h}var xI;function ZGe(){return xI||(xI=1,function(e){var t=mg&&mg.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(e,"__esModule",{value:!0}),e.htmlToDOM=e.domToReact=e.attributesToProps=e.Text=e.ProcessingInstruction=e.Element=e.Comment=void 0,e.default=s;var n=t(zGe());e.htmlToDOM=n.default;var r=t(mde());e.attributesToProps=r.default;var i=t(IGe());e.domToReact=i.default;var a=dde();Object.defineProperty(e,"Comment",{enumerable:!0,get:function(){return a.Comment}}),Object.defineProperty(e,"Element",{enumerable:!0,get:function(){return a.Element}}),Object.defineProperty(e,"ProcessingInstruction",{enumerable:!0,get:function(){return a.ProcessingInstruction}}),Object.defineProperty(e,"Text",{enumerable:!0,get:function(){return a.Text}});var o={lowerCaseAttributeNames:!1};function s(l,c){if(typeof l!="string")throw new TypeError("First argument must be a string");return l?(0,i.default)((0,n.default)(l,c?.htmlparser2||o),c):[]}}(mg)),mg}var DGe=ZGe();const QI=er(DGe),vun=QI.default||QI,MGe=e=>e.includes("loopback or private")?"Could not open that link. The app does not open links to your own machine or local network.":"Could not open that link.",gde=e=>{mi(MGe(e))};function bun(){const e=window.api?.onExternalOpenRefused;return typeof e!="function"?()=>{}:e(t=>{gde(t.reason)})}const $de=2200,wun=120,Sun=180,xun=.45,Qun="cubic-bezier(0.4, 0, 0.6, 1)",bg="data-lo-scrollbar",X5="active",kI="idle",VGe="data-undo-scope",LGe={now:()=>Date.now(),setTimer:(e,t)=>setTimeout(e,t),clearTimer:e=>clearTimeout(e)},PI=/^(auto|scroll)$/,FGe=e=>{const t=getComputedStyle(e);return PI.test(t.overflowX)||PI.test(t.overflowY)},BGe="contenteditable",E5=e=>{let t=e;for(;t!==null;){if(t.isContentEditable===!0||t.getAttribute(BGe)!==null||t.getAttribute(VGe)!==null)return!0;t=t.parentElement}return!1},q5=e=>e!==null&&e.nodeType===1?e:null,HGe=":focus-visible";function kun(e={}){const t=e.doc??document,n=e.clock??LGe,r=e.holdMs??$de,i=new Map,a=new WeakMap,o=new WeakMap;let s=null;const l=v=>{const S=a.get(v);if(S!==void 0)return S;const Q=(e.isScroller??FGe)(v);return Q&&a.set(v,Q),Q},c=v=>{const S=q5(v);if(S===null)return null;const Q=o.get(S);if(Q!==void 0)return Q;if(E5(S))return null;let b=null,w=S;for(;w!==null;){if(l(w)){b=w;break}w=w.parentElement}return b!==null&&o.set(S,b),b},u=v=>{if(v===null||v.isConnected!==!0)return;const S=v.getAttribute(bg);S!==X5&&(S===null&&v.setAttribute(bg,kI),v.setAttribute(bg,X5)),i.set(v,n.now()+r),d()};function O(){s=null;const v=n.now();for(const[S,Q]of[...i]){if(S.isConnected!==!0){i.delete(S);continue}Q<=v&&(i.delete(S),S.getAttribute(bg)===X5&&S.setAttribute(bg,kI))}d()}function d(){if(s!==null||i.size===0)return;let v=Number.POSITIVE_INFINITY;for(const S of i.values())S<v&&(v=S);s=n.setTimer(O,Math.max(v-n.now(),0))}const f=v=>{const S=q5(v.target);S!==null&&l(S)&&(E5(S)||u(S))},p=v=>{u(c(v.target))},m=v=>{u(c(v.target))},g=v=>{const S=q5(v.target);S===null||E5(S)||!(typeof S.matches!="function"||S.matches(HGe))||u(c(S))},y={capture:!0,passive:!0};return t.addEventListener("scroll",f,y),t.addEventListener("pointerover",p,y),t.addEventListener("pointerdown",m,y),t.addEventListener("focusin",g,y),()=>{t.removeEventListener("scroll",f,y),t.removeEventListener("pointerover",p,y),t.removeEventListener("pointerdown",m,y),t.removeEventListener("focusin",g,y),s!==null&&(n.clearTimer(s),s=null),i.clear()}}const _I=new Map,TI=new Map,RI=new Map;function Nz(e){return e===void 0?"":JSON.stringify(e)}function Yz(e,t){const n=`${e}\0${Nz(t)}`;let r=_I.get(n);return r===void 0&&(r=new Intl.DateTimeFormat(e,t),_I.set(n,r)),r}function KGe(e,t){const n=`${e}\0${Nz(t)}`;let r=TI.get(n);return r===void 0&&(r=new Intl.NumberFormat(e,t),TI.set(n,r)),r}function yde(e,t,n){return Yz(n??ov(),t).format(e)}function JGe(e,t,n){return Yz(n??ov(),t).format(e)}function eIe(e,t,n){return Yz(n??ov(),t).format(e)}function vde(e,t,n){return KGe(n??ov(),t).format(e)}function Pun(e,t,n,r){const i=r??ov(),a=`${i}\0${Nz(n)}`;let o=RI.get(a);return o===void 0&&(o=new Intl.RelativeTimeFormat(i,n),RI.set(a,o)),o.format(e,t)}const tIe=5e3;let bde=0;function nIe(e=tIe){bde=Date.now()+e}function _un(e=Date.now()){return e<=bde}function rIe(e){nIe(),e.invalidateQueries({queryKey:ri.capabilities})}function iIe(){const e=new Set,t=new Set;let n=0,r=null,i=0;const a=new WeakMap,o=()=>{n+=1;for(const c of t)c()},s=()=>{i+=1,e.size!==0&&(e.clear(),o())},l=c=>{e.has(c)||(e.add(c),o())};return{note:l,noteFrame:(c,u)=>{const O=a.get(u);return O===void 0&&a.set(u,i),(O??i)!==i?!1:(c!==null&&l(c),!0)},has:c=>e.has(c),reset:()=>{r=null,s()},observeProcess:c=>{const u=r;r=c,u!==null&&u!==c&&s()},subscribe:c=>(t.add(c),()=>void t.delete(c)),version:()=>n}}const j5=iIe();function wde(){const e=Ri(),t=window.api?.desktop?.feed,n=oi(e.data,"desktop_feed")&&!!t,[r,i]=$.useState(!1),[a,o]=$.useState(!1),[s,l]=$.useState(null),[c,u]=$.useState(0),[O,d]=$.useState(null),[f,p]=$.useState(0),[m,g]=$.useState(null),[y,v]=$.useState(null),S=$.useRef(!1),Q=$.useRef(!1);return $.useEffect(()=>{if(!n||!t){S.current=!1,i(!1),o(!1),j5.reset();return}const b=ar.getState().applyAttention,w=ar.getState().applySessionStatus,x=t.watchState(({connected:T})=>{T&&(Q.current&&!S.current&&p(_=>_+1),Q.current=!0),T||j5.reset(),S.current=T,o(!0),i(T)}),k=t.subscribe(T=>{if(j5.observeProcess(T.epoch),T.type==="attention"){b(T.session_id,T.payload),T.payload.unseen===!0&&u(_=>_+1);return}if(T.type==="session_status"){w(T.session_id,{code:T.payload.code,label:T.payload.label},T.payload.revision,T.epoch),u(_=>_+1);return}if(T.type==="catalogue"){l(T.payload.revision);return}if(T.type==="authoring"&&d(T.payload.revision),T.type==="code_requests"){g({sessionId:T.session_id,revision:T.payload.revision});return}T.type==="config"&&v({changedKeys:T.payload.changed_keys,language:T.payload.language,epoch:T.epoch,seq:T.seq})});return()=>{k(),x()}},[n,t]),{available:n,connected:n&&r,reported:n&&a,catalogueRevision:s,activityRevision:c,authoringRevision:O,authoringReconnectRevision:f,codeRequestsRevision:m,configChange:y}}function Gz(e){return e.label?.trim()||e.name}function Tun(e,t){return vk("profiles"),jt({queryKey:["desktop","profile",e],enabled:t&&!!e,queryFn:()=>Re({op:"profiles.get",name:e??""}),retry:!1})}function Run(e,t){return vk("teams"),jt({queryKey:["desktop","team",e],enabled:t&&!!e,queryFn:()=>Re({op:"teams.get",name:e??""}),retry:!1})}function Xun(e,t){return jt({queryKey:["desktop","team",e,"effective"],enabled:t&&!!e,queryFn:()=>Re({op:"teams.effective",name:e??""}),retry:!1})}function Eun(e){for(const t of[["desktop","profiles"],["desktop","teams"],["desktop","profile"],["desktop","team"]])e.invalidateQueries({queryKey:[...t]})}function aIe(e){return vk("profiles"),jt({queryKey:["desktop","profiles"],enabled:e,queryFn:()=>Re({op:"profiles.list"}).then(t=>t.profiles),retry:Ua,staleTime:1e4})}function vk(e){const{authoringRevision:t,authoringReconnectRevision:n}=wde(),r=cc(),i=$.useRef(t),a=$.useRef(n);$.useEffect(()=>{if(t!==null&&t!==i.current){i.current=t,a.current=n,r.invalidateQueries({queryKey:["desktop",e]}),r.invalidateQueries({queryKey:["desktop",e==="profiles"?"profile":"team"]});return}n!==a.current&&(a.current=n,r.invalidateQueries({queryKey:["desktop",e]}),r.invalidateQueries({queryKey:["desktop",e==="profiles"?"profile":"team"]}))},[t,n,e,r])}function Sde(e){return vk("teams"),jt({queryKey:["desktop","teams"],enabled:e,queryFn:()=>Re({op:"teams.list"}).then(t=>t.teams),retry:Ua,staleTime:1e4})}function oIe(e){const t=Sde(e);return $.useMemo(()=>{const n=new Map((t.data??[]).map(r=>[r.name,Gz(r)]));return r=>n.get(r)??r},[t.data])}const sIe=/\s+/g,lIe=/(?<=[.!?])\s/,cIe="The aside was not answered.";function xde(e){return Io(e,cIe)}const uIe=new Set(["aside_unanswered","aside_empty_answer"]);function Qde(e){return e instanceof Ut&&e.code!==void 0&&uIe.has(e.code)}const OIe="This aside can't continue. Press Esc to close it, which discards this exchange, then start a new one with /btw.",dIe="Ask again here to keep this exchange, or press Esc to close the aside and discard it.",fIe=/\s+[Aa]sk again\.$/;function hIe(e,t){const n=xde(e);return t?Qde(e)?`${n.replace(fIe,"")} ${dIe}`:`${n} ${OIe}`:n}const XI=60;function pIe(e){const t=e.trim().replace(sIe," ");return t.length>XI?`“${t.slice(0,XI-1)}…”`:`“${t}”`}function mIe(e,t){return`Your aside ${pIe(e)} got no answer: ${gIe(t)}`}function gIe(e){return Qde(e)?"The model didn't reply in text. Ask again.":xde(e)}const $Ie="The aside is still answering. Press Enter again once the answer is in.",yIe="This aside is queued to join the conversation. Ask again once it has been added.";function qun(e,t){return e.attached[t]?.queued?yIe:u3e(e,t)?.streaming?$Ie:null}function jun(e,t,n){const r=KA(Pr.getState(),t);e.catch(i=>{const a=Pr.getState();r&&Pce(a,r.asideId)||n(mIe(r?.question??"",i))})}const vIe="The request has invalid fields.";function bIe(e,t){return t&&e instanceof Ut&&e.status===422&&e.message===vIe}const h0=new Set,wIe=64;function SIe(e){for(h0.add(e);h0.size>wIe;){const t=h0.values().next().value;if(t===void 0)return;h0.delete(t)}}function Cun(e){Pr.getState().attachAside(e)}async function Aun(e,t,n){const r=fs(),i=Pr.getState(),a=_ce(i,e);i.beginAsk(e,r,t);const o=l=>Re({op:"sessions.aside",sessionId:e,requestId:r,text:t,asideId:a,subscriptionId:l?n:void 0}),s=!!n&&!h0.has(e);try{let l;try{l=await o(s)}catch(c){if(!bIe(c,s))throw c;SIe(e),l=await o(!1)}return Pr.getState().settleAside(r,l.data.text),r}catch(l){throw Pr.getState().failAside(r,hIe(l,a!==void 0)),l}}async function kde(e){const t=Pr.getState(),n=Tce(t,e);if(!n)return;let r;try{r=await Re({op:"sessions.adopt",sessionId:e,requestId:fs(),asideId:n,confirmed:!0})}catch(i){throw t.setAsideNotice(e,kIe(i)),i}if(xIe(r)==="queued"){Pr.getState().queueAdoption(e,n,[]),PIe(e,n).then(i=>{const a=Pr.getState().attached[e]?.queued;i.length>0&&a?.asideId===n&&Pr.getState().queueAdoption(e,n,i)});return}jce(e),Pr.getState().detachAside(e)}function xIe(e){return e?.data?.status==="queued"?"queued":"adopted"}const EI="Queued — this aside joins the conversation when the current turn finishes.",QIe={session_closed:"The aside was not added: this conversation has closed, so there is nothing to add it to.",open_tool_batch:"The conversation stopped in the middle of a tool call, so the aside was not added. Send a message to continue the conversation, then add the aside.",turn_running:"This conversation is busy, and the version it's running can't queue an aside. Add it when the reply finishes."};function kIe(e){if(e instanceof Ut&&e.code===ARe){const t=zRe(e.detail);if(t)return QIe[t]}return Io(e,"The aside was not added to the conversation.")}async function PIe(e,t){try{return((await Re({op:"sessions.aside.get",sessionId:e,asideId:t}))?.data?.turns??[]).map(r=>r?.id).filter(r=>typeof r=="string"&&r!=="")}catch{return[]}}const qI=1500,_Ie="The aside was not added to the conversation. Add it again to try once more.",TIe="The aside could not be confirmed in the conversation. If it is not there, add it again.";function RIe(e){return e.messageIds.length>0&&e.messageIds.every(t=>e.hasRecord(t))?"landed":e.turnAlive?"wait":"resync"}const Rd=new Map;function jI(e){const t=Rd.get(e);t!==void 0&&clearTimeout(t),Rd.delete(e)}function zun(e,t,n){const r=Pr.getState().attached[e]?.queued;if(!r)return;const{asideId:i}=r,a=RIe({messageIds:r.messageIds,hasRecord:t,turnAlive:n});if(a==="landed"){jI(i),Pr.getState().detachAside(e);return}if(a==="wait"){jI(i);return}if(Rd.has(i))return;const o=()=>Pr.getState().attached[e]?.queued?.asideId===i;Rd.set(i,setTimeout(()=>{if(!o()){Rd.delete(i);return}jce(e),Rd.set(i,setTimeout(()=>{if(Rd.delete(i),!o())return;const s=Pr.getState().attached[e]?.queued?.messageIds.length??0;Pr.getState().unqueueAdoption(e,i,s>0?_Ie:TIe)},qI))},qI))}function Uj(e){const t=Pr.getState(),n=_ce(t,e)??Tce(t,e);n&&Re({op:"sessions.aside.close",sessionId:e,asideId:n}).catch(()=>{}),Pr.getState().detachAside(e)}function XIe(e){return e.defaultPrevented||e.repeat||e.isComposing||e.shiftKey||e.altKey||e.key.toLowerCase()!=="f"?!1:e.metaKey||e.ctrlKey}const Pde=e=>e?"⌘+F":"Ctrl+F",CI=e=>`Press ${Pde(e)} again to add the aside to the conversation. Once added, it stays there.`,EIe=400;function qIe(e,t,n){return e?.turnId!==t?"arm":n-e.at<EIe?"ignore":"adopt"}function _de(e,t,n=!1){return!!e?.settled&&(n||!t)}function jIe(e,t,n=!1){return e?e.error!==null?"Nothing to add.":t&&!n?"This conversation is working. Adding the aside while it runs would splice a message into a live turn.":e.streaming?"The exchange is still settling — a moment before it can be added.":null:"Nothing to add yet."}function Tde(e){return e.scrollTop+(e.turnTop-e.regionTop)}function CIe(e){const t=Math.max(0,e.scrollHeight-e.clientHeight);return Math.min(t,Math.max(0,Tde(e)))}function AIe(e,t){return e===t}function zIe(e){return e.scrollTop<e.offset&&e.maxScroll<e.offset&&e.clientHeight>e.writtenClientHeight&&Math.abs(e.scrollTop-e.maxScroll)<=1}function UIe(e){return e?`${e.error!==null?"refused":e.settled?"settled":"live"}:${e.text.length}`:"none"}const AI=140,WIe=[[/!?\[([^\]]*)\]\([^)]*\)/g,"$1"],[/`(?=\S)([^`]*?\S)`/g,"$1"],[/\*\*(?=\S)([\s\S]*?\S)\*\*/g,"$1"],[/__(?=\S)([\s\S]*?\S)__/g,"$1"],[/~~(?=\S)([^~]*?\S)~~/g,"$1"],[/\*(?=\S)([^*]*?\S)\*/g,"$1"],[/(?<![A-Za-z0-9_])_(?=\S)([^_]*?\S)_(?!\w)/g,"$1"]];function NIe(e){return WIe.reduce((t,[n,r])=>t.replace(n,r),e)}function YIe(e){if(!e)return null;if(e.error!==null)return"The aside was not answered";if(e.streaming)return"Asking the aside";const t=NIe(e.text.trim()).split(lIe)[0]??"";return t.length===0?"The aside answered":t.length>AI?`The aside answered: ${t.slice(0,AI)}…`:`The aside answered: ${t}`}const GIe=new Set(["job_result","hub_message","monitor_prompt"]),IIe="no_reply";function Dc(e){return e.kind==="tool"&&e.toolName===IIe}function kO(e){return!(!Dc(e)||e.phase!=="done"||e.isError===!0||e.stopped===!0||e.neverSent===!0||e.notRunReason!==null&&e.notRunReason!==void 0||_p(e.notRunKind))}function Xp(e){switch(e.kind){case"user":return"user";case"peer":return"peer";case"wake":return"wake";case"custom":return GIe.has(e.customType)?e.customType:null;default:return null}}function PS(e){return e.kind==="assistant"&&!e.streaming&&e.stopReason==="stop"}function Rde(e){return e.kind==="notice"&&e.complete===!0}function Iz(e){switch(e.kind){case"compaction":return"compaction";case"notice":return Rde(e)?"terminal":null;case"custom":return e.level==="error"?"terminal":null;default:return null}}function bk(e){return Iz(e)==="terminal"}function Xde(e,t){const n=e.length,r=new Array(n).fill(!1);let i=!1;for(let l=n-1;l>=0;l-=1){const c=e[l];Xp(c)!==null?i=!1:c.kind==="tool"?(kO(c)&&(r[l]=!0),i=!0):c.kind==="assistant"&&!c.streaming&&t(c)&&!i&&(r[l]=!0)}const a=[];let o=0,s=!1;for(let l=0;l<n;l+=1){const c=e[l];if(bk(c)&&(s=!0),!r[l])continue;let u=-1;const O=[];for(let m=o;m<l;m+=1){const g=Xp(e[m]);u===-1&&e[m].kind==="tool"&&(u=m),g!==null&&(u===-1||g==="user")&&O.push(g)}const d=a.at(-1)??null;let f,p;d===null?(f="response",p=O.includes("user")?"user":"head-cut"):O.includes("user")?(f="response",p="user"):O.some(m=>m==="wake"||m==="peer")&&s?(f="commentary",p="post-terminal"):(f=d.class,p="continuation"),a.push({start:o,closeIndex:l,class:f,why:p,initiators:O}),o=l+1,s=!1}return a}function Ede(e,t,n){const r=t.length>0?t[t.length-1].closeIndex:-1;let i=!1;for(let a=e.length-1;a>r;a-=1)bk(e[a])&&(i=!0);for(let a=e.length-1;a>=0;a-=1){const o=e[a];if(!(o.kind==="user"||!n.paints(o))&&!n.isStatement(o)){if(o.kind==="assistant"&&!o.streaming||o.kind!=="assistant"&&i)break;return null}}for(let a=t.length-1;a>=0;a-=1)if(t[a].class==="response")return kO(e[t[a].closeIndex])?null:t[a];return null}function ZIe(e,t){const n=Xde(e,t.paints),r=Ede(e,n,t),i=new Set;if(e.forEach((s,l)=>{l>=t.from&&t.pinned(s)&&i.add(l)}),r!==null){i.add(r.closeIndex);const s=n[n.length-1].closeIndex;for(let l=e.length-1;l>s;l-=1){const c=e[l];if(!t.isStatement(c))break;i.add(l)}}for(const s of n)s.class==="response"&&!kO(e[s.closeIndex])&&i.add(s.closeIndex);if(n.length>0){const s=n[n.length-1];kO(e[s.closeIndex])||i.add(s.closeIndex)}e.forEach((s,l)=>{l<t.from||(s.kind==="user"||t.paints(s)&&PS(s))&&i.add(l)}),(t.mode??tle)==="by-response"&&e.forEach((s,l)=>{l<t.from||s.kind!=="assistant"||s.streaming||t.paints(s)&&i.add(l)});const a=[];let o=null;for(let s=t.from;s<e.length;s+=1)i.has(s)?(o!==null&&a.push({from:o,to:s-1}),o=null):o===null&&(o=s);return o!==null&&a.push({from:o,to:e.length-1}),{cycles:n,answer:r,segments:a,visible:i}}function DIe(e){switch(e){case"peer":return"Peer messages";case"wake":return"Wake messages";case"monitor":return"Monitor messages";case"job":return"Job results";default:return"Messages"}}function MIe(e,t,n,r){for(let o=n.from;o<=n.to;o+=1)if(e[o].kind==="user")return"Steered";if(r!=null)return DIe(r.family);const i=t.find(o=>o.start<=n.to&&n.to<=o.closeIndex);let a=i?.initiators.at(-1)??null;if(i===void 0){const o=t.filter(s=>s.closeIndex<n.from);for(let s=(o.at(-1)?.closeIndex??-1)+1;s<=n.to&&e[s].kind!=="tool";s+=1)a=Xp(e[s])??a}switch(a){case"wake":case"monitor_prompt":return"Wake";case"peer":case"hub_message":return"Peer message";case"job_result":return"Job result";default:for(let o=n.from;o<=n.to;o+=1){const s=e[o].kind;if(s==="ask_response"||s==="ask_timeout")return"Ask"}return null}}function VIe(e,t,n,r,i,a=null){const o=r??a;if(o===null||!(n.from>o)&&!i&&r!==null||!t.some(O=>O.start<=n.to&&n.to<=O.closeIndex))return!1;const l=e[n.to];if(!(l.kind==="assistant"?!l.streaming:l.kind==="tool"?l.phase==="done":!1))return!1;const u=n.to+1<e.length?e[n.to+1]:null;return u===null||Iz(u)!=="terminal"}const LIe=e=>{const t=e.split(`
517
517
  `),n=t.findIndex(i=>i.trim().length>0);if(n<0)return{headline:e.trim(),rest:null};const r=t.slice(n+1).join(`
518
518
  `).trim();return{headline:t[n].trim(),rest:r||null}};function FIe(e){const t=new Set;for(const n of qde(e,r=>r))n.closingAnswerId!==null&&t.add(n.closingAnswerId);return t}function qde(e,t){const n=[];let r=null,i=null,a=!1,o=!1,s=!1;const l=()=>a||o||c()||u(),c=()=>i!==null&&i.kind==="assistant"&&!i.streaming,u=()=>r!==null&&r.openingUserIndex===null&&!s,O=(p,m)=>{const g=[];for(let Q=p;Q<=m;Q+=1)g.push(t(e[Q]));const y=Xde(g,Hc),v=Ede(g,y,{paints:Hc,isStatement:Wj});let S=null;for(const Q of y){const b=g[Q.closeIndex];kO(b)&&(S=b.id)}return{answerId:v===null?null:g[v.closeIndex].id,quietCloseId:S}},d=(p,m)=>{if(r===null)return;r.endIndex=m,r.boundary=p;const g=O(r.openingIndex,m);r.closingAnswerId=g.answerId,r.quietCloseId=g.quietCloseId,n.push(r),r=null},f=(p,m)=>(i=null,a=!1,o=!1,s=!1,{openingIndex:p,endIndex:p,openingUserIndex:m,boundary:"end",closingAnswerId:null,quietCloseId:null});return e.forEach((p,m)=>{const g=t(p);if(g.kind==="user"){(r===null||l())&&(r!==null&&d(c()?"answer":o?"quiet":"marker",m-1),r=f(m,m));return}r===null&&(r=f(m,null)),Hc(g)&&!Wj(g)&&(i=g),bk(g)&&(a=!0),kO(g)&&(o=!0),(g.kind==="tool"||g.kind==="assistant")&&(s=!0),r.endIndex=m}),d("end",e.length-1),n}function Zz(e){return qde(e,t=>t.record).map(t=>({key:t.closingAnswerId??e[t.endIndex]?.record.id??"",opensWithUserRow:t.openingUserIndex!==null,openingIndex:t.openingIndex,endIndex:t.endIndex,boundary:t.boundary,closingAnswerId:t.closingAnswerId,quietCloseId:t.quietCloseId}))}function Wj(e){return e.kind==="notice"||e.kind==="compaction"||e.kind==="custom"||e.kind==="peer"||e.kind==="wake"||e.kind==="supplement"}function Hc(e){return e.kind!=="assistant"?!0:!!e.text}function zI(e){return e.kind==="tool"||e.kind==="notice"||e.kind==="compaction"||e.kind==="custom"||e.kind==="peer"||e.kind==="wake"}function jde(e){return e.kind==="tool"?uf(e.toolName):e.kind==="peer"||e.kind==="wake"?uf(e.kind):""}function BIe(e,t){const n=new Map(t.map(o=>[o.record.id,o])),r=[],i=FIe(e);let a=null;for(const o of e){if(!Hc(o))continue;const s=zI(o),l=a!==null&&zI(a);let c="item";a?o.kind==="user"||a.kind==="user"?c="turn":s&&l&&(c="trace"):c="first";const u=i.has(o.id),O=n.get(o.id);r.push(O&&O.record===o&&O.gap===c&&O.closesTurn===u?O:{record:o,gap:c,closesTurn:u}),Dc(o)||(a=o)}return r}const y1={first:["",""],turn:["mt-8","mt-8"],item:["mt-3","mt-3"],trace:["mt-0.5","mt-0.5"]},HIe="waiting for the agent",KIe="starting the session",JIe="compacting context",eZe="stopping the turn";function tZe(e,t){if(!t)return;const n=Object.values(e).filter(r=>r.sessionId===t||r.key===`send:${t}`||r.key===t);return n.find(r=>r.pending)??n[0]}const nZe=(e,t)=>tZe(e,t)?.pending===!0;function rZe(e,t){const n=r=>(r.kind==="tool"||r.kind==="assistant")&&Hc(r);return Cde(e,t).some(n)}function Cde(e,t){if(t){const r=e.findIndex(i=>i.id===t);if(r>=0)return e.slice(r+1)}const n=e[e.length-1];return n===void 0?[]:[n]}function iZe(e,t){return Cde(e,t).some(Rde)}function Uun(e,t){return!!(e?.anchor_id&&e.anchor_id!==t&&(e.kind==="error"||e.kind==="interrupted"||e.kind==="closed"||e.kind==="retired"))}function Ade(e){const t=aZe(e);return t===null?t:e.stopping===!0?{...t,activity:eZe,clock:!1}:e.idleDisputed===!0?{...t,clock:!1}:t}function aZe({waiting:e,compacting:t,compactingSince:n,starting:r,startingAfterId:i,startingSession:a,startingSince:o,gate:s,unavailable:l,foldedPhase:c,foldedPhaseStartedAt:u,records:O}){if(s)return null;const d=f=>c!==f?null:dle(u);if(t)return l?null:{activity:JIe,phase:"compacting",...n===void 0?{}:{startedAt:n}};if(e){if(l)return null;const f=O.filter(v=>v.kind==="tool"&&v.phase==="running");if(f.length>0){const v=f.length===1?f[0].intent??`running ${uf(f[0].toolName)}`:`running ${f.length} tools`,S=f.map(b=>b.startedAt).filter(b=>b!==null),Q=S.length===f.length?Math.min(...S):null;return{activity:v,phase:"running",...Q===null?{}:{startedAt:Q}}}const p=O.filter(v=>v.kind==="tool"&&v.phase==="composing").length;if(p>0){const v=d("composing");return{activity:`composing ${p===1?"a call":`${p} calls`}`,phase:"composing",...v===null?{}:{startedAt:v}}}const m=O.filter(v=>v.kind==="tool"&&v.phase==="queued").length;if(m>0)return{activity:`waiting to run ${m===1?"a call":`${m} calls`}`,phase:"queued",clock:!1};const g=O[O.length-1];if(g?.kind==="assistant"&&g.streaming&&g.text){const v=d("responding");return{activity:"responding",phase:"responding",...v===null?{}:{startedAt:v}}}const y=d("thinking");return{activity:"thinking",phase:"thinking",...y===null?{}:{startedAt:y}}}return!r||l||rZe(O,i)||iZe(O,i)?null:{activity:a===!0?KIe:HIe,phase:"thinking",...o==null?{}:{startedAt:o}}}function Wun(e){return Ade(e)!==null}function oZe(e){const t=typeof e.foldedPhase=="string"&&e.foldedPhase!==""?{foldedPhase:e.foldedPhase,foldedPhaseStartedAt:e.foldedPhaseStartedAt??null}:{};return{waiting:e.waiting,compacting:e.compacting===!0,compactingSince:e.compactingSince,starting:e.starting,startingAfterId:e.startingAfterId??null,...e.startingSession===!0?{startingSession:!0}:{},...e.startingSince==null?{}:{startingSince:e.startingSince},...e.stopping===!0?{stopping:!0}:{},...e.idleDisputed===!0?{idleDisputed:!0}:{},gate:!!e.gate,unavailable:e.unavailable,...t,records:e.records}}const zde="@container/chatcol",Rr="w-full @min-[750px]/chatcol:max-w-[var(--lo-chat-measure)] @min-[750px]/chatcol:mx-auto",sZe="px-6",lZe="max-h-[7.5rem] overflow-y-auto leading-5",Ude=["jpg","jpeg","png","gif","webp","bmp","svg","tiff","tif","ico","heic","heif","avif","jfif","pjpeg","pjp"],Wde=["mp4","webm","ogg","mov","avi","wmv","flv","mkv","m4v","3gp","3g2"],Nde=["mp3","wav","aac","flac","m4a","oga"],Yde=["xls","xlsx","ods","csv","tsv"],cZe=["doc","docx","odt","rtf","pages"],uZe=["ppt","pptx","odp","key"],OZe=["zip","tar","gz","rar","7z"],dZe=["js","mjs","cjs","ts","tsx","jsx","py","java","c","h","cpp","cs","go","rb","php","sh","bash","zsh","fish","css","scss","less","json","jsonc","xml","yaml","yml","toml","sql","rs","swift","kt","lua","pl","r","dart","scala","clj","ex","exs","vue","svelte","astro","gradle","ini","cfg","conf","env"],Gde=["txt","log","text"],Ide=["md","markdown","mdown","mdx","mkd","mkdn"],Zde=["html","htm","xhtml"],Dde=["pdf"],Ps=e=>new Set(e.map(t=>t.toLowerCase())),Mde=Ps(Ude),Vde=Ps(Wde),Lde=Ps(Nde),Fde=Ps(Yde),Bde=Ps(cZe),Hde=Ps(uZe),Kde=Ps(OZe),Jde=Ps(dZe),efe=Ps(Gde),tfe=Ps(Ide),nfe=Ps(Zde),rfe=Ps(Dde);function wk(e){const t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\")),n=e.slice(t+1),r=n.lastIndexOf(".");return r<=0||r===n.length-1?null:n.slice(r+1).toLowerCase()}const fZe=new Set([...Mde,...Vde,...Lde,...Fde,...Bde,...Hde,...Kde,...Jde,...efe,...tfe,...nfe,...rfe]);function Dz(e){const t=wk(e);return t?Mde.has(t)?"image":Vde.has(t)?"video":Lde.has(t)?"audio":rfe.has(t)?"pdf":tfe.has(t)?"markdown":nfe.has(t)?"html":Fde.has(t)?"spreadsheet":Bde.has(t)?"document":Hde.has(t)?"presentation":Kde.has(t)?"archive":efe.has(t)?"text":Jde.has(t)?"code":"other":"other"}function Mz(e){const t=wk(e);if(!t)return"application/octet-stream";switch(t){case"pdf":return"application/pdf";case"png":return"image/png";case"jpg":case"jpeg":case"jfif":case"pjpeg":case"pjp":return"image/jpeg";case"gif":return"image/gif";case"webp":return"image/webp";case"bmp":return"image/bmp";case"svg":return"image/svg+xml";case"tiff":case"tif":return"image/tiff";case"ico":return"image/x-icon";case"avif":return"image/avif";case"heic":case"heif":return"image/heic";case"mp3":return"audio/mpeg";case"wav":return"audio/wav";case"aac":return"audio/aac";case"flac":return"audio/flac";case"m4a":return"audio/mp4";case"ogg":case"oga":return"audio/ogg";case"mp4":case"m4v":return"video/mp4";case"webm":return"video/webm";case"mov":return"video/quicktime";case"mkv":return"video/x-matroska";case"avi":return"video/x-msvideo";default:return"application/octet-stream"}}const Jd=new Map,Vz=new Map;function Lz(e,t){const n=new Blob([e],{type:t}),r=URL.createObjectURL(n);return Vz.set(r,n),r}function ife(e){return Vz.get(e)??null}function $v(e){URL.revokeObjectURL(e),Vz.delete(e)}function Fz(e){return Jd.get(e)?.url??null}function _S(e){const t=Jd.get(e);return t?(t.refs+=1,t.revoking=!1,t.url):null}function afe(e,t){if(Jd.get(e)){$v(t);return}Jd.set(e,{url:t,refs:0,revoking:!1})}function TS(e){const t=Jd.get(e);t&&(t.refs-=1,!(t.refs>0)&&(t.revoking||(t.revoking=!0,queueMicrotask(()=>{!t.revoking||t.refs>0||($v(t.url),Jd.get(e)===t&&Jd.delete(e))}))))}function hZe(e){switch(e){case"too-large":return"Too large to preview";case"not-found":return"File no longer exists";case"not-a-file":return"Not a file";case"unreadable":return"Could not be read";case"no-bridge":return null}}let pZe=0;const mZe=(e,t,n,r)=>t==null?`file:${e}:holder-${r}`:`file:${e}:${t}:${n??""}`,gZe=e=>e.startsWith("file://")?e.slice(7):e,$Ze=e=>e.startsWith("data:")||e.startsWith("http://")||e.startsWith("https://");function yZe(e,{mtimeMs:t,mimeType:n,sizeBytes:r,maxBytes:i}){const a=gZe(e),o=$Ze(a)?a:null,[s]=$.useState(()=>pZe++),l=mZe(a,t,r,s),c=Math.min(i??YN,YN),u=o===null&&(r??0)>c,[O,d]=$.useState(()=>{if(o)return{status:"ready",url:o};if(u)return{status:"unavailable",url:null,code:"too-large",message:`${a} is ${r} bytes, over the ${c}-byte preview cap`,sizeBytes:r??void 0};const f=Fz(l);return f?{status:"ready",url:f}:{status:"loading",url:null}});return $.useEffect(()=>{if(o||u)return;let f=!0;const p=_S(l);if(p)return d({status:"ready",url:p}),()=>{f=!1,TS(l)};if(d({status:"loading",url:null}),typeof window.api?.readFileBytes!="function"){d({status:"unavailable",url:null,code:"no-bridge",message:"Local file access is unavailable outside the desktop app."});return}return(async()=>{try{const g=await window.api.readFileBytes(a,c);if(!f)return;if(!g.success){d({status:"unavailable",url:null,code:g.code,message:g.error,sizeBytes:g.sizeBytes});return}const y=Lz(g.data,n);if(!f){$v(y);return}afe(l,y),d({status:"ready",url:_S(l)??y})}catch(g){if(!f)return;d({status:"unavailable",url:null,code:"unreadable",message:g instanceof Error?g.message:String(g)})}})(),()=>{f=!1,TS(l)}},[o,u,l,n,a,c]),O}const vZe=/[/\\]/,bZe=/name=([^;,]+)/,wZe=/^data:([^;,]+)/,SZe=q("relative flex size-25 flex-col items-center justify-center","overflow-hidden rounded-md bg-sunken"),xZe=q("invisible absolute -top-80 left-0 z-50 size-75 p-2","rounded-lg bg-elevated shadow-overlay","opacity-0 transition-[opacity,visibility] duration-base ease-out-quart","group-hover:visible group-hover:opacity-100 group-hover:delay-[1500ms]"),QZe=e=>{if(e.startsWith("data:image/"))return!0;const t=[".jpg",".jpeg",".png",".gif",".webp",".bmp",".svg"],n=e.toLowerCase();return t.some(r=>n.endsWith(r))},kZe=e=>{if(e.startsWith("data:video/"))return!0;const t=[".mp4",".webm",".ogg",".mov",".avi",".wmv",".flv",".mkv",".m4v",".3gp",".3g2"],n=e.toLowerCase();return t.some(r=>n.endsWith(r))},PZe=e=>{if(e.startsWith("data:image/"))return"";if(e.startsWith("data:")){const n=e.match(bZe);if(n?.[1])try{return decodeURIComponent(n[1])}catch{}const r=e.match(wZe);return r?.[1]?J("ui.chat.composer_media.pasted_type",{mimeType:r[1]}):J("ui.chat.composer_media.pasted_file")}const t=e.split(vZe);return t[t.length-1]},_Ze=({attachment:e,fileName:t,image:n,video:r,disabled:i,onRemove:a})=>{br();const o=yZe(e,{mimeType:Mz(e)}),s=o.status==="ready"?o.url:null,[l,c]=$.useState(null),u=s!==null&&s!==l?s:null,O=o.status==="unavailable"||s!==null&&s===l,d=o.status==="unavailable"?hZe(o.code):O?J("ui.chat.composer_media.preview_failed"):null,f=h.jsxs("div",{className:q("flex size-full flex-col items-center justify-center gap-1.5","bg-accent-wash p-2 text-center text-accent"),children:[h.jsx(dv,{size:18,"aria-hidden":"true"}),h.jsx("span",{className:q("line-clamp-2 break-all font-medium text-meta"),children:t})]});return h.jsxs("div",{className:q("group relative"),children:[h.jsxs("div",{className:SZe,title:d??void 0,children:[u&&n?h.jsx("img",{src:u,alt:t,onError:()=>c(u),className:q("size-full object-cover")}):u&&r?h.jsx("video",{src:u,preload:"metadata",muted:!0,onError:()=>c(u),className:q("size-full object-cover")}):!n&&!r||O?f:null,(n||r)&&t&&!O&&h.jsx("span",{className:q("absolute inset-x-0 bottom-0 truncate","bg-surface/85 px-1.5 py-0.5","text-center text-ink text-meta"),children:t}),h.jsx(Yt,{content:J("ui.chat.composer_media.remove_attachment"),disabled:i,children:h.jsx(Xe,{variant:"ghost",size:"icon-sm",className:q("absolute top-1 right-1 bg-surface/85 text-danger","hover:bg-danger-wash hover:text-danger","disabled:bg-sunken disabled:text-ink-disabled"),onClick:a,disabled:i,"aria-label":J("ui.chat.composer_media.remove_attachment"),children:h.jsx(ea,{"aria-hidden":"true"})})})]}),(n||r)&&u&&h.jsx("div",{className:xZe,children:u&&n?h.jsx("img",{src:u,alt:t,className:q("size-full object-contain")}):u&&r?h.jsx("video",{src:u,controls:!0,preload:"metadata",muted:!0,className:q("size-full object-contain")}):null})]})},TZe=({attachments:e,onRemoveAttachment:t,disabled:n=!1})=>{br();const r=$.useCallback(i=>a=>{a.stopPropagation(),n||t(i)},[t,n]);return e.length?h.jsx("div",{className:q("flex flex-wrap gap-3 py-2"),children:e.map((i,a)=>h.jsx(_Ze,{attachment:i,fileName:PZe(i),image:QZe(i),video:kZe(i),disabled:n,onRemove:r(a)},`${a}-${i}`))}):null},RZe=12,XZe="inline-flex h-5 min-w-5 items-center justify-center rounded-xs px-1 font-mono text-ink-dim text-mono-sm",EZe="inline-flex items-center gap-0",qZe={"⌘":h5,cmd:h5,command:h5,enter:vG,"↵":vG},Ad=({shortcut:e,joined:t=!1})=>{const n=e.split("+").map(r=>r.trim());return h.jsx("span",{className:EZe,children:n.map((r,i)=>{const a=qZe[r.toLowerCase()];return h.jsxs($.Fragment,{children:[i>0&&!t&&h.jsx("span",{"aria-hidden":"true",className:"text-mono-sm text-ink-dim",children:"+"}),h.jsx("kbd",{className:XZe,children:a?h.jsxs(h.Fragment,{children:[h.jsx(a,{size:RZe,"aria-hidden":"true"}),h.jsx("span",{className:"sr-only",children:r})]}):r})]},`${r}-${i}`)})})},jZe=e=>{let t=!1,n=null,r=null;const i=o=>{for(const s of o.getTracks())s.stop()},a={stop:()=>{t||(t=!0,n&&(i(n),n=null),r&&r.state!=="closed"&&r.close().catch(console.error),r=null)}};return(async()=>{let o;try{o=await e.getUserMedia({audio:!0})}catch(s){t||e.onError(s);return}if(t){i(o);return}n=o;try{const s=e.createAudioContext();r=s;const l=s.createAnalyser();l.fftSize=1024,s.createMediaStreamSource(o).connect(l),e.onAnalyser(l)}catch(s){e.onError(s)}})(),a},CZe=.015,ofe=.05,AZe=.94,zZe=.6,UZe=1.25,WZe=.5,UI={reference:ofe,shown:0},NZe=(e,t)=>{const n=Number.isFinite(t)?Math.min(1,Math.max(0,t)):0,r=Math.max(0,n-CZe),i=Math.max(r,e.reference*AZe,ofe),a=r/(i*UZe),o=Math.min(1,a**zZe),s=o>=e.shown?o:e.shown+(o-e.shown)*WZe;return{state:{reference:i,shown:s},level:s}},C5=120,ad=2,WI=34,NI=4,YZe=.5,GZe="block h-9 w-full text-accent",IZe=`
519
519
  @keyframes recording-ping {
@@ -829,7 +829,7 @@ l0,-`+(n+144)+`c-2,-159.3,-10,-310.7,-24,-454c-53.3,-528,-210,-949.7,
829
829
  `))};if(c.from==this.from&&a<this.from?c.from=a:c.to==this.to&&a>this.to&&(c.to=a),c.from==c.to&&!c.insert.length){let u=Ge.single(this.toEditorPos(r.selectionStart),this.toEditorPos(r.selectionEnd));u.main.eq(i)||t.dispatch({selection:u,userEvent:"select"});return}if((ct.mac||ct.android)&&c.from==o-1&&/^\. ?$/.test(r.text)&&t.contentDOM.getAttribute("autocorrect")=="off"&&(c={from:s,to:l,insert:Fn.of([r.text.replace("."," ")])}),this.pendingContextChange=c,!t.state.readOnly){let u=this.to-this.from+(c.to-c.from+c.insert.length);a8(t,c,Ge.single(this.toEditorPos(r.selectionStart,u),this.toEditorPos(r.selectionEnd,u)))}this.pendingContextChange&&(this.revertPending(t.state),this.setSelection(t.state))},this.handlers.characterboundsupdate=r=>{let i=[],a=null;for(let o=this.toEditorPos(r.rangeStart),s=this.toEditorPos(r.rangeEnd);o<s;o++){let l=t.coordsForChar(o);a=l&&new DOMRect(l.left,l.top,l.right-l.left,l.bottom-l.top)||a||new DOMRect,i.push(a)}n.updateCharacterBounds(r.rangeStart,i)},this.handlers.textformatupdate=r=>{let i=[];for(let a of r.getTextFormats()){let o=a.underlineStyle,s=a.underlineThickness;if(o!="None"&&s!="None"){let l=this.toEditorPos(a.rangeStart),c=this.toEditorPos(a.rangeEnd);if(l<c){let u=`text-decoration: underline ${o=="Dashed"?"dashed ":o=="Squiggle"?"wavy ":""}${s=="Thin"?1:2}px`;i.push(cn.mark({attributes:{style:u}}).range(l,c))}}}t.dispatch({effects:ege.of(cn.set(i))})},this.handlers.compositionstart=()=>{t.inputState.composing<0&&(t.inputState.composing=0,t.inputState.compositionFirstChange=!0)},this.handlers.compositionend=()=>{if(t.inputState.composing=-1,t.inputState.compositionFirstChange=null,this.composing){let{drifted:r}=this.composing;this.composing=null,r&&this.reset(t.state)}};for(let r in this.handlers)n.addEventListener(r,this.handlers[r]);this.measureReq={read:r=>{this.editContext.updateControlBounds(r.contentDOM.getBoundingClientRect());let i=L$(r.root);i&&i.rangeCount&&this.editContext.updateSelectionBounds(i.getRangeAt(0).getBoundingClientRect())}}}applyEdits(t){let n=0,r=!1,i=this.pendingContextChange;return t.changes.iterChanges((a,o,s,l,c)=>{if(r)return;let u=c.length-(o-a);if(i&&o>=i.to)if(i.from==a&&i.to==o&&i.insert.eq(c)){i=this.pendingContextChange=null,n+=u,this.to+=u;return}else i=null,this.revertPending(t.state);if(a+=n,o+=n,o<=this.from)this.from+=u,this.to+=u;else if(a<this.to){if(a<this.from||o>this.to||this.to-this.from+c.length>3e4){r=!0;return}this.editContext.updateText(this.toContextPos(a),this.toContextPos(o),c.toString()),this.to+=u}n+=u}),i&&!r&&this.revertPending(t.state),!r}update(t){let n=this.pendingContextChange,r=t.startState.selection.main;this.composing&&(this.composing.drifted||!t.changes.touchesRange(r.from,r.to)&&t.transactions.some(i=>!i.isUserEvent("input.type")&&i.changes.touchesRange(this.from,this.to)))?(this.composing.drifted=!0,this.composing.editorBase=t.changes.mapPos(this.composing.editorBase)):!this.applyEdits(t)||!this.rangeIsValid(t.state)?(this.pendingContextChange=null,this.reset(t.state)):(t.docChanged||t.selectionSet||n)&&this.setSelection(t.state),(t.geometryChanged||t.docChanged||t.selectionSet)&&t.view.requestMeasure(this.measureReq)}resetRange(t){let{head:n}=t.selection.main;this.from=Math.max(0,n-1e4),this.to=Math.min(t.doc.length,n+1e4)}reset(t){this.resetRange(t),this.editContext.updateText(0,this.editContext.text.length,t.doc.sliceString(this.from,this.to)),this.setSelection(t)}revertPending(t){let n=this.pendingContextChange;this.pendingContextChange=null,this.editContext.updateText(this.toContextPos(n.from),this.toContextPos(n.from+n.insert.length),t.doc.sliceString(n.from,n.to))}setSelection(t){let{main:n}=t.selection,r=this.toContextPos(Math.max(this.from,Math.min(this.to,n.anchor))),i=this.toContextPos(n.head);(this.editContext.selectionStart!=r||this.editContext.selectionEnd!=i)&&this.editContext.updateSelection(r,i)}rangeIsValid(t){let{head:n}=t.selection.main;return!(this.from>0&&n-this.from<500||this.to<t.doc.length&&this.to-n<500||this.to-this.from>1e4*3)}toEditorPos(t,n=this.to-this.from){t=Math.min(t,n);let r=this.composing;return r&&r.drifted?r.editorBase+(t-r.contextBase):t+this.from}toContextPos(t){let n=this.composing;return n&&n.drifted?n.contextBase+(t-n.editorBase):t-this.from}destroy(){for(let t in this.handlers)this.editContext.removeEventListener(t,this.handlers[t])}}class Pt{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(t={}){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),t.parent&&t.parent.appendChild(this.dom);let{dispatch:r}=t;this.dispatchTransactions=t.dispatchTransactions||r&&(i=>i.forEach(a=>r(a,this)))||(i=>this.update(i)),this.dispatch=this.dispatch.bind(this),this._root=t.root||_nt(t.parent)||document,this.viewState=new wM(t.state||Nn.create(t)),t.scrollTo&&t.scrollTo.is(Zb)&&(this.viewState.scrollTarget=t.scrollTo.value.clip(this.viewState.state)),this.plugins=this.state.facet(Lh).map(i=>new wT(i));for(let i of this.plugins)i.update(this);this.observer=new Mrt(this),this.inputState=new prt(this),this.inputState.ensureHandlers(this.plugins),this.docView=new rM(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure(),!((n=document.fonts)===null||n===void 0)&&n.ready&&document.fonts.ready.then(()=>this.requestMeasure())}dispatch(...t){let n=t.length==1&&t[0]instanceof Ki?t:t.length==1&&Array.isArray(t[0])?t[0]:[this.state.update(...t)];this.dispatchTransactions(n,this)}update(t){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,i,a=this.state;for(let d of t){if(d.startState!=a)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");a=d.state}if(this.destroyed){this.viewState.state=a;return}let o=this.hasFocus,s=0,l=null;t.some(d=>d.annotation(fge))?(this.inputState.notifiedFocused=o,s=1):o!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=o,l=hge(a,o),l||(s=1));let c=this.observer.delayedAndroidKey,u=null;if(c?(this.observer.clearDelayedAndroidKey(),u=this.observer.readChange(),(u&&!this.state.doc.eq(a.doc)||!this.state.selection.eq(a.selection))&&(u=null)):this.observer.clear(),a.facet(Nn.phrases)!=this.state.facet(Nn.phrases))return this.setState(a);i=MS.create(this,a,t),i.flags|=s;let O=this.viewState.scrollTarget;try{this.updateState=2;for(let d of t){if(O&&(O=O.map(d.changes)),d.scrollIntoView){let{main:f}=d.state.selection;O=new fp(f.empty?f:Ge.cursor(f.head,f.head>f.anchor?-1:1))}for(let f of d.effects)f.is(Zb)&&(O=f.value.clip(this.state))}this.viewState.update(i,O),this.bidiCache=LS.update(this.bidiCache,i.changes),i.empty||(this.updatePlugins(i),this.inputState.update(i)),n=this.docView.update(i),this.state.facet(m0)!=this.styleModules&&this.mountStyles(),r=this.updateAttrs(),this.showAnnouncements(t),this.docView.updateSelection(n,t.some(d=>d.isUserEvent("select.pointer")))}finally{this.updateState=0}if(i.startState.facet(Bb)!=i.state.facet(Bb)&&(this.viewState.mustMeasureContent=!0),(n||r||O||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),n&&this.docViewUpdate(),!i.empty)for(let d of this.state.facet(G3))try{d(i)}catch(f){no(this.state,f,"update listener")}(l||u)&&Promise.resolve().then(()=>{l&&this.state==l.startState&&this.dispatch(l),u&&!sge(this,u)&&c.force&&dp(this.contentDOM,c.key,c.keyCode)})}setState(t){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=t;return}this.updateState=2;let n=this.hasFocus;try{for(let r of this.plugins)r.destroy(this);this.viewState=new wM(t),this.plugins=t.facet(Lh).map(r=>new wT(r)),this.pluginMap.clear();for(let r of this.plugins)r.update(this);this.docView.destroy(),this.docView=new rM(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}n&&this.focus(),this.requestMeasure()}updatePlugins(t){let n=t.startState.facet(Lh),r=t.state.facet(Lh);if(n!=r){let i=[];for(let a of r){let o=n.indexOf(a);if(o<0)i.push(new wT(a));else{let s=this.plugins[o];s.mustUpdate=t,i.push(s)}}for(let a of this.plugins)a.mustUpdate!=t&&a.destroy(this);this.plugins=i,this.pluginMap.clear()}else for(let i of this.plugins)i.mustUpdate=t;for(let i=0;i<this.plugins.length;i++)this.plugins[i].update(this);n!=r&&this.inputState.ensureHandlers(this.plugins)}docViewUpdate(){for(let t of this.plugins){let n=t.value;if(n&&n.docViewUpdate)try{n.docViewUpdate(this)}catch(r){no(this.state,r,"doc view update listener")}}}measure(t=!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,t&&this.observer.forceFlush();let n=null,r=this.scrollDOM,i=r.scrollTop*this.scaleY,{scrollAnchorPos:a,scrollAnchorHeight:o}=this.viewState;Math.abs(i-this.viewState.scrollTop)>1&&(o=-1),this.viewState.scrollAnchorHeight=-1;try{for(let s=0;;s++){if(o<0)if(_me(r))a=-1,o=this.viewState.heightMap.height;else{let f=this.viewState.scrollAnchorAt(i);a=f.from,o=f.top}this.updateState=1;let l=this.viewState.measure(this);if(!l&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;if(s>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let c=[];l&4||([this.measureRequests,c]=[c,this.measureRequests]);let u=c.map(f=>{try{return f.read(this)}catch(p){return no(this.state,p),kM}}),O=MS.create(this,this.state,[]),d=!1;O.flags|=l,n?n.flags|=l:n=O,this.updateState=2,O.empty||(this.updatePlugins(O),this.inputState.update(O),this.updateAttrs(),d=this.docView.update(O),d&&this.docViewUpdate());for(let f=0;f<c.length;f++)if(u[f]!=kM)try{let p=c[f];p.write&&p.write(u[f],this)}catch(p){no(this.state,p)}if(d&&this.docView.updateSelection(!0),!O.viewportChanged&&this.measureRequests.length==0){if(this.viewState.editorHeight)if(this.viewState.scrollTarget){this.docView.scrollIntoView(this.viewState.scrollTarget),this.viewState.scrollTarget=null,o=-1;continue}else{let p=(a<0?this.viewState.heightMap.height:this.viewState.lineBlockAt(a).top)-o;if(p>1||p<-1){i=i+p,r.scrollTop=i/this.scaleY,o=-1;continue}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(n&&!n.empty)for(let s of this.state.facet(G3))s(n)}get themeClasses(){return V3+" "+(this.state.facet(M3)?$ge:gge)+" "+this.state.facet(Bb)}updateAttrs(){let t=PM(this,tge,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),n={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false",translate:"no",contenteditable:this.state.facet(Gc)?"true":"false",class:"cm-content",style:`${ct.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(n["aria-readonly"]="true"),PM(this,n8,n);let r=this.observer.ignore(()=>{let i=z3(this.contentDOM,this.contentAttrs,n),a=z3(this.dom,this.editorAttrs,t);return i||a});return this.editorAttrs=t,this.contentAttrs=n,r}showAnnouncements(t){let n=!0;for(let r of t)for(let i of r.effects)if(i.is(Pt.announce)){n&&(this.announceDOM.textContent=""),n=!1;let a=this.announceDOM.appendChild(document.createElement("div"));a.textContent=i.value}}mountStyles(){this.styleModules=this.state.facet(m0);let t=this.state.facet(Pt.cspNonce);EO.mount(this.root,this.styleModules.concat(Zrt).reverse(),t?{nonce:t}: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(t){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame(()=>this.measure())),t){if(this.measureRequests.indexOf(t)>-1)return;if(t.key!=null){for(let n=0;n<this.measureRequests.length;n++)if(this.measureRequests[n].key===t.key){this.measureRequests[n]=t;return}}this.measureRequests.push(t)}}plugin(t){let n=this.pluginMap.get(t);return(n===void 0||n&&n.plugin!=t)&&this.pluginMap.set(t,n=this.plugins.find(r=>r.plugin==t)||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(t){return this.readMeasured(),this.viewState.elementAtHeight(t)}lineBlockAtHeight(t){return this.readMeasured(),this.viewState.lineBlockAtHeight(t)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(t){return this.viewState.lineBlockAt(t)}get contentHeight(){return this.viewState.contentHeight}moveByChar(t,n,r){return xT(this,t,lM(this,t,n,r))}moveByGroup(t,n){return xT(this,t,lM(this,t,n,r=>ort(this,t.head,r)))}visualLineSide(t,n){let r=this.bidiSpans(t),i=this.textDirectionAt(t.from),a=r[n?r.length-1:0];return Ge.cursor(a.side(n,i)+t.from,a.forward(!n,i)?1:-1)}moveToLineBoundary(t,n,r=!0){return art(this,t,n,r)}moveVertically(t,n,r){return xT(this,t,srt(this,t,n,r))}domAtPos(t){return this.docView.domAtPos(t)}posAtDOM(t,n=0){return this.docView.posFromDOM(t,n)}posAtCoords(t,n=!0){return this.readMeasured(),oge(this,t,n)}coordsAtPos(t,n=1){this.readMeasured();let r=this.docView.coordsAt(t,n);if(!r||r.left==r.right)return r;let i=this.state.doc.lineAt(t),a=this.bidiSpans(i),o=a[dO.find(a,t-i.from,-1,n)];return Pv(r,o.dir==Er.LTR==n>0)}coordsForChar(t){return this.readMeasured(),this.docView.coordsForChar(t)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(t){return!this.state.facet(Hme)||t<this.viewport.from||t>this.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(t))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(t){if(t.length>Frt)return Ime(t.length);let n=this.textDirectionAt(t.from),r;for(let a of this.bidiCache)if(a.from==t.from&&a.dir==n&&(a.fresh||Gme(a.isolates,r=nM(this,t))))return a.order;r||(r=nM(this,t));let i=Int(t.text,n,r);return this.bidiCache.push(new LS(t.from,t.to,n,r,!0,i)),i}get hasFocus(){var t;return(this.dom.ownerDocument.hasFocus()||ct.safari&&((t=this.inputState)===null||t===void 0?void 0:t.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{kme(this.contentDOM),this.docView.updateSelection()})}setRoot(t){this._root!=t&&(this._root=t,this.observer.setWindow((t.nodeType==9?t:t.ownerDocument).defaultView||window),this.mountStyles())}destroy(){this.root.activeElement==this.contentDOM&&this.contentDOM.blur();for(let t of this.plugins)t.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(t,n={}){return Zb.of(new fp(typeof t=="number"?Ge.cursor(t):t,n.y,n.x,n.yMargin,n.xMargin))}scrollSnapshot(){let{scrollTop:t,scrollLeft:n}=this.scrollDOM,r=this.viewState.scrollAnchorAt(t);return Zb.of(new fp(Ge.cursor(r.from),"start","start",r.top-t,n,!0))}setTabFocusMode(t){t==null?this.inputState.tabFocusMode=this.inputState.tabFocusMode<0?0:-1:typeof t=="boolean"?this.inputState.tabFocusMode=t?0:-1:this.inputState.tabFocusMode!=0&&(this.inputState.tabFocusMode=Date.now()+t)}static domEventHandlers(t){return Ti.define(()=>({}),{eventHandlers:t})}static domEventObservers(t){return Ti.define(()=>({}),{eventObservers:t})}static theme(t,n){let r=EO.newName(),i=[Bb.of(r),m0.of(L3(`.${r}`,t))];return n&&n.dark&&i.push(M3.of(!0)),i}static baseTheme(t){return ZO.lowest(m0.of(L3("."+V3,t,yge)))}static findFromDOM(t){var n;let r=t.querySelector(".cm-content"),i=r&&ur.get(r)||ur.get(t);return((n=i?.rootView)===null||n===void 0?void 0:n.view)||null}}Pt.styleModule=m0;Pt.inputHandler=Fme;Pt.clipboardInputFilter=e8;Pt.clipboardOutputFilter=t8;Pt.scrollHandler=Jme;Pt.focusChangeEffect=Bme;Pt.perLineTextDirection=Hme;Pt.exceptionSink=Lme;Pt.updateListener=G3;Pt.editable=Gc;Pt.mouseSelectionStyle=Vme;Pt.dragMovesSelection=Mme;Pt.clickAddsSelectionRange=Dme;Pt.decorations=F$;Pt.outerDecorations=nge;Pt.atomicRanges=r8;Pt.bidiIsolatedRanges=rge;Pt.scrollMargins=ige;Pt.darkTheme=M3;Pt.cspNonce=ht.define({combine:e=>e.length?e[0]:""});Pt.contentAttributes=n8;Pt.editorAttributes=tge;Pt.lineWrapping=Pt.contentAttributes.of({class:"cm-lineWrapping"});Pt.announce=_n.define();const Frt=4096,kM={};class LS{constructor(t,n,r,i,a,o){this.from=t,this.to=n,this.dir=r,this.isolates=i,this.fresh=a,this.order=o}static update(t,n){if(n.empty&&!t.some(a=>a.fresh))return t;let r=[],i=t.length?t[t.length-1].dir:Er.LTR;for(let a=Math.max(0,t.length-10);a<t.length;a++){let o=t[a];o.dir==i&&!n.touchesRange(o.from,o.to)&&r.push(new LS(n.mapPos(o.from,1),n.mapPos(o.to,-1),o.dir,o.isolates,!1,o.order))}return r}}function PM(e,t,n){for(let r=e.state.facet(t),i=r.length-1;i>=0;i--){let a=r[i],o=typeof a=="function"?a(e):a;o&&A3(o,n)}return n}const Brt=ct.mac?"mac":ct.windows?"win":ct.linux?"linux":"key";function Hrt(e,t){const n=e.split(/-(?!$)/);let r=n[n.length-1];r=="Space"&&(r=" ");let i,a,o,s;for(let l=0;l<n.length-1;++l){const c=n[l];if(/^(cmd|meta|m)$/i.test(c))s=!0;else if(/^a(lt)?$/i.test(c))i=!0;else if(/^(c|ctrl|control)$/i.test(c))a=!0;else if(/^s(hift)?$/i.test(c))o=!0;else if(/^mod$/i.test(c))t=="mac"?s=!0:a=!0;else throw new Error("Unrecognized modifier name: "+c)}return i&&(r="Alt-"+r),a&&(r="Ctrl-"+r),s&&(r="Meta-"+r),o&&(r="Shift-"+r),r}function Hb(e,t,n){return t.altKey&&(e="Alt-"+e),t.ctrlKey&&(e="Ctrl-"+e),t.metaKey&&(e="Meta-"+e),n!==!1&&t.shiftKey&&(e="Shift-"+e),e}const Krt=ZO.default(Pt.domEventHandlers({keydown(e,t){return bge(vge(t.state),e,t,"editor")}})),Nk=ht.define({enables:Krt}),_M=new WeakMap;function vge(e){let t=e.facet(Nk),n=_M.get(t);return n||_M.set(t,n=eit(t.reduce((r,i)=>r.concat(i),[]))),n}function hOn(e,t,n){return bge(vge(e.state),t,e,n)}let iO=null;const Jrt=4e3;function eit(e,t=Brt){let n=Object.create(null),r=Object.create(null),i=(o,s)=>{let l=r[o];if(l==null)r[o]=s;else if(l!=s)throw new Error("Key binding "+o+" is used both as a regular binding and as a multi-stroke prefix")},a=(o,s,l,c,u)=>{var O,d;let f=n[o]||(n[o]=Object.create(null)),p=s.split(/ (?!$)/).map(y=>Hrt(y,t));for(let y=1;y<p.length;y++){let v=p.slice(0,y).join(" ");i(v,!0),f[v]||(f[v]={preventDefault:!0,stopPropagation:!1,run:[S=>{let Q=iO={view:S,prefix:v,scope:o};return setTimeout(()=>{iO==Q&&(iO=null)},Jrt),!0}]})}let m=p.join(" ");i(m,!1);let g=f[m]||(f[m]={preventDefault:!1,stopPropagation:!1,run:((d=(O=f._any)===null||O===void 0?void 0:O.run)===null||d===void 0?void 0:d.slice())||[]});l&&g.run.push(l),c&&(g.preventDefault=!0),u&&(g.stopPropagation=!0)};for(let o of e){let s=o.scope?o.scope.split(" "):["editor"];if(o.any)for(let c of s){let u=n[c]||(n[c]=Object.create(null));u._any||(u._any={preventDefault:!1,stopPropagation:!1,run:[]});let{any:O}=o;for(let d in u)u[d].run.push(f=>O(f,F3))}let l=o[t]||o.key;if(l)for(let c of s)a(c,l,o.run,o.preventDefault,o.stopPropagation),o.shift&&a(c,"Shift-"+l,o.shift,o.preventDefault,o.stopPropagation)}return n}let F3=null;function bge(e,t,n,r){F3=t;let i=Snt(t),a=Ro(i,0),o=Yc(a)==i.length&&i!=" ",s="",l=!1,c=!1,u=!1;iO&&iO.view==n&&iO.scope==r&&(s=iO.prefix+" ",cge.indexOf(t.keyCode)<0&&(c=!0,iO=null));let O=new Set,d=g=>{if(g){for(let y of g.run)if(!O.has(y)&&(O.add(y),y(n)))return g.stopPropagation&&(u=!0),!0;g.preventDefault&&(g.stopPropagation&&(u=!0),c=!0)}return!1},f=e[r],p,m;return f&&(d(f[s+Hb(i,t,!o)])?l=!0:o&&(t.altKey||t.metaKey||t.ctrlKey)&&!(ct.windows&&t.ctrlKey&&t.altKey)&&(p=qO[t.keyCode])&&p!=i?(d(f[s+Hb(p,t,!0)])||t.shiftKey&&(m=V$[t.keyCode])!=i&&m!=p&&d(f[s+Hb(m,t,!1)]))&&(l=!0):o&&t.shiftKey&&d(f[s+Hb(i,t,!0)])&&(l=!0),!l&&d(f._any)&&(l=!0)),c&&(l=!0),l&&u&&t.stopPropagation(),F3=null,l}class Rv{constructor(t,n,r,i,a){this.className=t,this.left=n,this.top=r,this.width=i,this.height=a}draw(){let t=document.createElement("div");return t.className=this.className,this.adjust(t),t}update(t,n){return n.className!=this.className?!1:(this.adjust(t),!0)}adjust(t){t.style.left=this.left+"px",t.style.top=this.top+"px",this.width!=null&&(t.style.width=this.width+"px"),t.style.height=this.height+"px"}eq(t){return this.left==t.left&&this.top==t.top&&this.width==t.width&&this.height==t.height&&this.className==t.className}static forRange(t,n,r){if(r.empty){let i=t.coordsAtPos(r.head,r.assoc||1);if(!i)return[];let a=wge(t);return[new Rv(n,i.left-a.left,i.top-a.top,null,i.bottom-i.top)]}else return tit(t,n,r)}}function wge(e){let t=e.scrollDOM.getBoundingClientRect();return{left:(e.textDirection==Er.LTR?t.left:t.right-e.scrollDOM.clientWidth*e.scaleX)-e.scrollDOM.scrollLeft*e.scaleX,top:t.top-e.scrollDOM.scrollTop*e.scaleY}}function TM(e,t,n,r){let i=e.coordsAtPos(t,n*2);if(!i)return r;let a=e.dom.getBoundingClientRect(),o=(i.top+i.bottom)/2,s=e.posAtCoords({x:a.left+1,y:o}),l=e.posAtCoords({x:a.right-1,y:o});return s==null||l==null?r:{from:Math.max(r.from,Math.min(s,l)),to:Math.min(r.to,Math.max(s,l))}}function tit(e,t,n){if(n.to<=e.viewport.from||n.from>=e.viewport.to)return[];let r=Math.max(n.from,e.viewport.from),i=Math.min(n.to,e.viewport.to),a=e.textDirection==Er.LTR,o=e.contentDOM,s=o.getBoundingClientRect(),l=wge(e),c=o.querySelector(".cm-line"),u=c&&window.getComputedStyle(c),O=s.left+(u?parseInt(u.paddingLeft)+Math.min(0,parseInt(u.textIndent)):0),d=s.right-(u?parseInt(u.paddingRight):0),f=Z3(e,r,1),p=Z3(e,i,-1),m=f.type==Na.Text?f:null,g=p.type==Na.Text?p:null;if(m&&(e.lineWrapping||f.widgetLineBreaks)&&(m=TM(e,r,1,m)),g&&(e.lineWrapping||p.widgetLineBreaks)&&(g=TM(e,i,-1,g)),m&&g&&m.from==g.from&&m.to==g.to)return v(S(n.from,n.to,m));{let b=m?S(n.from,null,m):Q(f,!1),w=g?S(null,n.to,g):Q(p,!0),x=[];return(m||f).to<(g||p).from-(m&&g?1:0)||f.widgetLineBreaks>1&&b.bottom+e.defaultLineHeight/2<w.top?x.push(y(O,b.bottom,d,w.top)):b.bottom<w.top&&e.elementAtHeight((b.bottom+w.top)/2).type==Na.Text&&(b.bottom=w.top=(b.bottom+w.top)/2),v(b).concat(x).concat(v(w))}function y(b,w,x,k){return new Rv(t,b-l.left,w-l.top,x-b,k-w)}function v({top:b,bottom:w,horizontal:x}){let k=[];for(let T=0;T<x.length;T+=2)k.push(y(x[T],b,x[T+1],w));return k}function S(b,w,x){let k=1e9,T=-1e9,_=[];function E(C,W,G,N,Z){let F=e.coordsAtPos(C,C==x.to?-2:2),z=e.coordsAtPos(G,G==x.from?2:-2);!F||!z||(k=Math.min(F.top,z.top,k),T=Math.max(F.bottom,z.bottom,T),Z==Er.LTR?_.push(a&&W?O:F.left,a&&N?d:z.right):_.push(!a&&N?O:z.left,!a&&W?d:F.right))}let R=b??x.from,j=w??x.to;for(let C of e.visibleRanges)if(C.to>R&&C.from<j)for(let W=Math.max(C.from,R),G=Math.min(C.to,j);;){let N=e.state.doc.lineAt(W);for(let Z of e.bidiSpans(N)){let F=Z.from+N.from,z=Z.to+N.from;if(F>=G)break;z>W&&E(Math.max(F,W),b==null&&F<=R,Math.min(z,G),w==null&&z>=j,Z.dir)}if(W=N.to+1,W>=G)break}return _.length==0&&E(R,b==null,j,w==null,e.textDirection),{top:k,bottom:T,horizontal:_}}function Q(b,w){let x=s.top+(w?b.top:b.bottom);return{top:x,bottom:x,horizontal:[]}}}function nit(e,t){return e.constructor==t.constructor&&e.eq(t)}class rit{constructor(t,n){this.view=t,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=t.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(t.state),t.requestMeasure(this.measureReq),n.mount&&n.mount(this.dom,t)}update(t){t.startState.facet(R1)!=t.state.facet(R1)&&this.setOrder(t.state),(this.layer.update(t,this.dom)||t.geometryChanged)&&(this.scale(),t.view.requestMeasure(this.measureReq))}docViewUpdate(t){this.layer.updateOnDocViewUpdate!==!1&&t.requestMeasure(this.measureReq)}setOrder(t){let n=0,r=t.facet(R1);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:t,scaleY:n}=this.view;(t!=this.scaleX||n!=this.scaleY)&&(this.scaleX=t,this.scaleY=n,this.dom.style.transform=`scale(${1/t}, ${1/n})`)}draw(t){if(t.length!=this.drawn.length||t.some((n,r)=>!nit(n,this.drawn[r]))){let n=this.dom.firstChild,r=0;for(let i of t)i.update&&n&&i.constructor&&this.drawn[r].constructor&&i.update(n,this.drawn[r])?(n=n.nextSibling,r++):this.dom.insertBefore(i.draw(),n);for(;n;){let i=n.nextSibling;n.remove(),n=i}this.drawn=t}}destroy(){this.layer.destroy&&this.layer.destroy(this.dom,this.view),this.dom.remove()}}const R1=ht.define();function Sge(e){return[Ti.define(t=>new rit(t,e)),R1.of(e)]}const B$=ht.define({combine(e){return Nm(e,{cursorBlinkRate:1200,drawRangeCursor:!0},{cursorBlinkRate:(t,n)=>Math.min(t,n),drawRangeCursor:(t,n)=>t||n})}});function pOn(e={}){return[B$.of(e),iit,ait,oit,Kme.of(!0)]}function xge(e){return e.startState.facet(B$)!=e.state.facet(B$)}const iit=Sge({above:!0,markers(e){let{state:t}=e,n=t.facet(B$),r=[];for(let i of t.selection.ranges){let a=i==t.selection.main;if(i.empty||n.drawRangeCursor){let o=a?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary",s=i.empty?i:Ge.cursor(i.head,i.head>i.anchor?-1:1);for(let l of Rv.forRange(e,o,s))r.push(l)}}return r},update(e,t){e.transactions.some(r=>r.selection)&&(t.style.animationName=t.style.animationName=="cm-blink"?"cm-blink2":"cm-blink");let n=xge(e);return n&&RM(e.state,t),e.docChanged||e.selectionSet||n},mount(e,t){RM(t.state,e)},class:"cm-cursorLayer"});function RM(e,t){t.style.animationDuration=e.facet(B$).cursorBlinkRate+"ms"}const ait=Sge({above:!1,markers(e){return e.state.selection.ranges.map(t=>t.empty?[]:Rv.forRange(e,"cm-selectionBackground",t)).reduce((t,n)=>t.concat(n))},update(e,t){return e.docChanged||e.selectionSet||e.viewportChanged||xge(e)},class:"cm-selectionLayer"}),oit=ZO.highest(Pt.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"}}}})),Qge=_n.define({map(e,t){return e==null?null:t.mapPos(e)}}),y0=co.define({create(){return null},update(e,t){return e!=null&&(e=t.changes.mapPos(e)),t.effects.reduce((n,r)=>r.is(Qge)?r.value:n,e)}}),sit=Ti.fromClass(class{constructor(e){this.view=e,this.cursor=null,this.measureReq={read:this.readPos.bind(this),write:this.drawCursor.bind(this)}}update(e){var t;let n=e.state.field(y0);n==null?this.cursor!=null&&((t=this.cursor)===null||t===void 0||t.remove(),this.cursor=null):(this.cursor||(this.cursor=this.view.scrollDOM.appendChild(document.createElement("div")),this.cursor.className="cm-dropCursor"),(e.startState.field(y0)!=n||e.docChanged||e.geometryChanged)&&this.view.requestMeasure(this.measureReq))}readPos(){let{view:e}=this,t=e.state.field(y0),n=t!=null&&e.coordsAtPos(t);if(!n)return null;let r=e.scrollDOM.getBoundingClientRect();return{left:n.left-r.left+e.scrollDOM.scrollLeft*e.scaleX,top:n.top-r.top+e.scrollDOM.scrollTop*e.scaleY,height:n.bottom-n.top}}drawCursor(e){if(this.cursor){let{scaleX:t,scaleY:n}=this.view;e?(this.cursor.style.left=e.left/t+"px",this.cursor.style.top=e.top/n+"px",this.cursor.style.height=e.height/n+"px"):this.cursor.style.left="-100000px"}}destroy(){this.cursor&&this.cursor.remove()}setDropPos(e){this.view.state.field(y0)!=e&&this.view.dispatch({effects:Qge.of(e)})}},{eventObservers:{dragover(e){this.setDropPos(this.view.posAtCoords({x:e.clientX,y:e.clientY}))},dragleave(e){(e.target==this.view.contentDOM||!this.view.contentDOM.contains(e.relatedTarget))&&this.setDropPos(null)},dragend(){this.setDropPos(null)},drop(){this.setDropPos(null)}}});function mOn(){return[y0,sit]}function XM(e,t,n,r,i){t.lastIndex=0;for(let a=e.iterRange(n,r),o=n,s;!a.next().done;o+=a.value.length)if(!a.lineBreak)for(;s=t.exec(a.value);)i(o+s.index,s)}function lit(e,t){let n=e.visibleRanges;if(n.length==1&&n[0].from==e.viewport.from&&n[0].to==e.viewport.to)return n;let r=[];for(let{from:i,to:a}of n)i=Math.max(e.state.doc.lineAt(i).from,i-t),a=Math.min(e.state.doc.lineAt(a).to,a+t),r.length&&r[r.length-1].to>=i?r[r.length-1].to=a:r.push({from:i,to:a});return r}class cit{constructor(t){const{regexp:n,decoration:r,decorate:i,boundary:a,maxLength:o=1e3}=t;if(!n.global)throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");if(this.regexp=n,i)this.addMatch=(s,l,c,u)=>i(u,c,c+s[0].length,s,l);else if(typeof r=="function")this.addMatch=(s,l,c,u)=>{let O=r(s,l,c);O&&u(c,c+s[0].length,O)};else if(r)this.addMatch=(s,l,c,u)=>u(c,c+s[0].length,r);else throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");this.boundary=a,this.maxLength=o}createDeco(t){let n=new gf,r=n.add.bind(n);for(let{from:i,to:a}of lit(t,this.maxLength))XM(t.state.doc,this.regexp,i,a,(o,s)=>this.addMatch(s,t,o,r));return n.finish()}updateDeco(t,n){let r=1e9,i=-1;return t.docChanged&&t.changes.iterChanges((a,o,s,l)=>{l>=t.view.viewport.from&&s<=t.view.viewport.to&&(r=Math.min(s,r),i=Math.max(l,i))}),t.viewportMoved||i-r>1e3?this.createDeco(t.view):i>-1?this.updateRange(t.view,n.map(t.changes),r,i):n}updateRange(t,n,r,i){for(let a of t.visibleRanges){let o=Math.max(a.from,r),s=Math.min(a.to,i);if(s>=o){let l=t.state.doc.lineAt(o),c=l.to<s?t.state.doc.lineAt(s):l,u=Math.max(a.from,l.from),O=Math.min(a.to,c.to);if(this.boundary){for(;o>l.from;o--)if(this.boundary.test(l.text[o-1-l.from])){u=o;break}for(;s<c.to;s++)if(this.boundary.test(c.text[s-c.from])){O=s;break}}let d=[],f,p=(m,g,y)=>d.push(y.range(m,g));if(l==c)for(this.regexp.lastIndex=u-l.from;(f=this.regexp.exec(l.text))&&f.index<O-l.from;)this.addMatch(f,t,f.index+l.from,p);else XM(t.state.doc,this.regexp,u,O,(m,g)=>this.addMatch(g,t,m,p));n=n.update({filterFrom:u,filterTo:O,filter:(m,g)=>m<u||g>O,add:d})}}return n}}const B3=/x/.unicode!=null?"gu":"g",uit=new RegExp(`[\0-\b
830
830
  --Ÿ­؜​‎‏\u2028\u2029‭‮⁦⁧⁩\uFEFF-]`,B3),Oit={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 PT=null;function dit(){var e;if(PT==null&&typeof document<"u"&&document.body){let t=document.body.style;PT=((e=t.tabSize)!==null&&e!==void 0?e:t.MozTabSize)!=null}return PT||!1}const X1=ht.define({combine(e){let t=Nm(e,{render:null,specialChars:uit,addSpecialChars:null});return(t.replaceTabs=!dit())&&(t.specialChars=new RegExp(" |"+t.specialChars.source,B3)),t.addSpecialChars&&(t.specialChars=new RegExp(t.specialChars.source+"|"+t.addSpecialChars.source,B3)),t}});function gOn(e={}){return[X1.of(e),fit()]}let EM=null;function fit(){return EM||(EM=Ti.fromClass(class{constructor(e){this.view=e,this.decorations=cn.none,this.decorationCache=Object.create(null),this.decorator=this.makeDecorator(e.state.facet(X1)),this.decorations=this.decorator.createDeco(e)}makeDecorator(e){return new cit({regexp:e.specialChars,decoration:(t,n,r)=>{let{doc:i}=n.state,a=Ro(t[0],0);if(a==9){let o=i.lineAt(r),s=n.state.tabSize,l=XO(o.text,s,r-o.from);return cn.replace({widget:new git((s-l%s)*this.view.defaultCharacterWidth/this.view.scaleX)})}return this.decorationCache[a]||(this.decorationCache[a]=cn.replace({widget:new mit(e,a)}))},boundary:e.replaceTabs?void 0:/[^]/})}update(e){let t=e.state.facet(X1);e.startState.facet(X1)!=t?(this.decorator=this.makeDecorator(t),this.decorations=this.decorator.createDeco(e.view)):this.decorations=this.decorator.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}))}const hit="•";function pit(e){return e>=32?hit:e==10?"␤":String.fromCharCode(9216+e)}class mit extends Tu{constructor(t,n){super(),this.options=t,this.code=n}eq(t){return t.code==this.code}toDOM(t){let n=pit(this.code),r=t.state.phrase("Control character")+" "+(Oit[this.code]||"0x"+this.code.toString(16)),i=this.options.render&&this.options.render(this.code,r,n);if(i)return i;let a=document.createElement("span");return a.textContent=n,a.title=r,a.setAttribute("aria-label",r),a.className="cm-specialChar",a}ignoreEvent(){return!1}}class git extends Tu{constructor(t){super(),this.width=t}eq(t){return t.width==this.width}toDOM(){let t=document.createElement("span");return t.textContent=" ",t.className="cm-tab",t.style.width=this.width+"px",t}ignoreEvent(){return!1}}function $On(){return yit}const $it=cn.line({class:"cm-activeLine"}),yit=Ti.fromClass(class{constructor(e){this.decorations=this.getDeco(e)}update(e){(e.docChanged||e.selectionSet)&&(this.decorations=this.getDeco(e.view))}getDeco(e){let t=-1,n=[];for(let r of e.state.selection.ranges){let i=e.lineBlockAt(r.head);i.from>t&&(n.push($it.range(i.from)),t=i.from)}return cn.set(n)}},{decorations:e=>e.decorations});class vit extends Tu{constructor(t){super(),this.content=t}toDOM(t){let n=document.createElement("span");return n.className="cm-placeholder",n.style.pointerEvents="none",n.appendChild(typeof this.content=="string"?document.createTextNode(this.content):typeof this.content=="function"?this.content(t):this.content.cloneNode(!0)),n.setAttribute("aria-hidden","true"),n}coordsAt(t){let n=t.firstChild?zp(t.firstChild):[];if(!n.length)return null;let r=window.getComputedStyle(t.parentNode),i=Pv(n[0],r.direction!="rtl"),a=parseInt(r.lineHeight);return i.bottom-i.top>a*1.5?{left:i.left,right:i.right,top:i.top,bottom:i.top+a}:i}ignoreEvent(){return!1}}function yOn(e){let t=Ti.fromClass(class{constructor(n){this.view=n,this.placeholder=e?cn.set([cn.widget({widget:new vit(e),side:1}).range(0)]):cn.none}get decorations(){return this.view.state.doc.length?cn.none:this.placeholder}},{decorations:n=>n.decorations});return typeof e=="string"?[t,Pt.contentAttributes.of({"aria-placeholder":e})]:t}const H3=2e3;function bit(e,t,n){let r=Math.min(t.line,n.line),i=Math.max(t.line,n.line),a=[];if(t.off>H3||n.off>H3||t.col<0||n.col<0){let o=Math.min(t.off,n.off),s=Math.max(t.off,n.off);for(let l=r;l<=i;l++){let c=e.doc.line(l);c.length<=s&&a.push(Ge.range(c.from+o,c.to+s))}}else{let o=Math.min(t.col,n.col),s=Math.max(t.col,n.col);for(let l=r;l<=i;l++){let c=e.doc.line(l),u=T3(c.text,o,e.tabSize,!0);if(u<0)a.push(Ge.cursor(c.to));else{let O=T3(c.text,s,e.tabSize);a.push(Ge.range(c.from+u,c.from+O))}}}return a}function wit(e,t){let n=e.coordsAtPos(e.viewport.from);return n?Math.round(Math.abs((n.left-t)/e.defaultCharacterWidth)):-1}function qM(e,t){let n=e.posAtCoords({x:t.clientX,y:t.clientY},!1),r=e.state.doc.lineAt(n),i=n-r.from,a=i>H3?-1:i==r.length?wit(e,t.clientX):XO(r.text,e.state.tabSize,n-r.from);return{line:r.number,col:a,off:i}}function Sit(e,t){let n=qM(e,t),r=e.state.selection;return n?{update(i){if(i.docChanged){let a=i.changes.mapPos(i.startState.doc.line(n.line).from),o=i.state.doc.lineAt(a);n={line:o.number,col:n.col,off:Math.min(n.off,o.length)},r=r.map(i.changes)}},get(i,a,o){let s=qM(e,i);if(!s)return r;let l=bit(e.state,n,s);return l.length?o?Ge.create(l.concat(r.ranges)):Ge.create(l):r}}:null}function vOn(e){let t=n=>n.altKey&&n.button==0;return Pt.mouseSelectionStyle.of((n,r)=>t(r)?Sit(n,r):null)}const xit={Alt:[18,e=>!!e.altKey],Control:[17,e=>!!e.ctrlKey],Shift:[16,e=>!!e.shiftKey],Meta:[91,e=>!!e.metaKey]},Qit={style:"cursor: crosshair"};function bOn(e={}){let[t,n]=xit[e.key||"Alt"],r=Ti.fromClass(class{constructor(i){this.view=i,this.isDown=!1}set(i){this.isDown!=i&&(this.isDown=i,this.view.update([]))}},{eventObservers:{keydown(i){this.set(i.keyCode==t||n(i))},keyup(i){(i.keyCode==t||!n(i))&&this.set(!1)},mousemove(i){this.set(n(i))}}});return[r,Pt.contentAttributes.of(i=>{var a;return!((a=i.plugin(r))===null||a===void 0)&&a.isDown?Qit:null})]}const kg="-10000px";class kge{constructor(t,n,r,i){this.facet=n,this.createTooltipView=r,this.removeTooltipView=i,this.input=t.state.facet(n),this.tooltips=this.input.filter(o=>o);let a=null;this.tooltipViews=this.tooltips.map(o=>a=r(o,a))}update(t,n){var r;let i=t.state.facet(this.facet),a=i.filter(l=>l);if(i===this.input){for(let l of this.tooltipViews)l.update&&l.update(t);return!1}let o=[],s=n?[]:null;for(let l=0;l<a.length;l++){let c=a[l],u=-1;if(c){for(let O=0;O<this.tooltips.length;O++){let d=this.tooltips[O];d&&d.create==c.create&&(u=O)}if(u<0)o[l]=this.createTooltipView(c,l?o[l-1]:null),s&&(s[l]=!!c.above);else{let O=o[l]=this.tooltipViews[u];s&&(s[l]=n[u]),O.update&&O.update(t)}}}for(let l of this.tooltipViews)o.indexOf(l)<0&&(this.removeTooltipView(l),(r=l.destroy)===null||r===void 0||r.call(l));return n&&(s.forEach((l,c)=>n[c]=l),n.length=s.length),this.input=i,this.tooltips=a,this.tooltipViews=o,!0}}function kit(e){let t=e.dom.ownerDocument.documentElement;return{top:0,left:0,bottom:t.clientHeight,right:t.clientWidth}}const _T=ht.define({combine:e=>{var t,n,r;return{position:ct.ios?"absolute":((t=e.find(i=>i.position))===null||t===void 0?void 0:t.position)||"fixed",parent:((n=e.find(i=>i.parent))===null||n===void 0?void 0:n.parent)||null,tooltipSpace:((r=e.find(i=>i.tooltipSpace))===null||r===void 0?void 0:r.tooltipSpace)||kit}}}),jM=new WeakMap,l8=Ti.fromClass(class{constructor(e){this.view=e,this.above=[],this.inView=!0,this.madeAbsolute=!1,this.lastTransaction=0,this.measureTimeout=-1;let t=e.state.facet(_T);this.position=t.position,this.parent=t.parent,this.classes=e.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 kge(e,c8,(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(),e.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 e of this.manager.tooltipViews)this.intersectionObserver.observe(e.dom)}}measureSoon(){this.measureTimeout<0&&(this.measureTimeout=setTimeout(()=>{this.measureTimeout=-1,this.maybeMeasure()},50))}update(e){e.transactions.length&&(this.lastTransaction=Date.now());let t=this.manager.update(e,this.above);t&&this.observeIntersection();let n=t||e.geometryChanged,r=e.state.facet(_T);if(r.position!=this.position&&!this.madeAbsolute){this.position=r.position;for(let i of this.manager.tooltipViews)i.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 i of this.manager.tooltipViews)this.container.appendChild(i.dom);n=!0}else this.parent&&this.view.themeClasses!=this.classes&&(this.classes=this.container.className=this.view.themeClasses);n&&this.maybeMeasure()}createTooltip(e,t){let n=e.create(this.view),r=t?t.dom:null;if(n.dom.classList.add("cm-tooltip"),e.arrow&&!n.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")){let i=document.createElement("div");i.className="cm-tooltip-arrow",n.dom.appendChild(i)}return n.dom.style.position=this.position,n.dom.style.top=kg,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 e,t,n;this.view.win.removeEventListener("resize",this.measureSoon);for(let r of this.manager.tooltipViews)r.dom.remove(),(e=r.destroy)===null||e===void 0||e.call(r);this.parent&&this.container.remove(),(t=this.resizeObserver)===null||t===void 0||t.disconnect(),(n=this.intersectionObserver)===null||n===void 0||n.disconnect(),clearTimeout(this.measureTimeout)}readMeasure(){let e=1,t=1,n=!1;if(this.position=="fixed"&&this.manager.tooltipViews.length){let{dom:a}=this.manager.tooltipViews[0];if(ct.gecko)n=a.offsetParent!=this.container.ownerDocument.body;else if(a.style.top==kg&&a.style.left=="0px"){let o=a.getBoundingClientRect();n=Math.abs(o.top+1e4)>1||Math.abs(o.left)>1}}if(n||this.position=="absolute")if(this.parent){let a=this.parent.getBoundingClientRect();a.width&&a.height&&(e=a.width/this.parent.offsetWidth,t=a.height/this.parent.offsetHeight)}else({scaleX:e,scaleY:t}=this.view.viewState);let r=this.view.scrollDOM.getBoundingClientRect(),i=i8(this.view);return{visible:{left:r.left+i.left,top:r.top+i.top,right:r.right-i.right,bottom:r.bottom-i.bottom},parent:this.parent?this.container.getBoundingClientRect():this.view.dom.getBoundingClientRect(),pos:this.manager.tooltips.map((a,o)=>{let s=this.manager.tooltipViews[o];return s.getCoords?s.getCoords(a.pos):this.view.coordsAtPos(a.pos)}),size:this.manager.tooltipViews.map(({dom:a})=>a.getBoundingClientRect()),space:this.view.state.facet(_T).tooltipSpace(this.view),scaleX:e,scaleY:t,makeAbsolute:n}}writeMeasure(e){var t;if(e.makeAbsolute){this.madeAbsolute=!0,this.position="absolute";for(let s of this.manager.tooltipViews)s.dom.style.position="absolute"}let{visible:n,space:r,scaleX:i,scaleY:a}=e,o=[];for(let s=0;s<this.manager.tooltips.length;s++){let l=this.manager.tooltips[s],c=this.manager.tooltipViews[s],{dom:u}=c,O=e.pos[s],d=e.size[s];if(!O||l.clip!==!1&&(O.bottom<=Math.max(n.top,r.top)||O.top>=Math.min(n.bottom,r.bottom)||O.right<Math.max(n.left,r.left)-.1||O.left>Math.min(n.right,r.right)+.1)){u.style.top=kg;continue}let f=l.arrow?c.dom.querySelector(".cm-tooltip-arrow"):null,p=f?7:0,m=d.right-d.left,g=(t=jM.get(c))!==null&&t!==void 0?t:d.bottom-d.top,y=c.offset||_it,v=this.view.textDirection==Er.LTR,S=d.width>r.right-r.left?v?r.left:r.right-d.width:v?Math.max(r.left,Math.min(O.left-(f?14:0)+y.x,r.right-m)):Math.min(Math.max(r.left,O.left-m+(f?14:0)-y.x),r.right-m),Q=this.above[s];!l.strictSide&&(Q?O.top-g-p-y.y<r.top:O.bottom+g+p+y.y>r.bottom)&&Q==r.bottom-O.bottom>O.top-r.top&&(Q=this.above[s]=!Q);let b=(Q?O.top-r.top:r.bottom-O.bottom)-p;if(b<g&&c.resize!==!1){if(b<this.view.defaultLineHeight){u.style.top=kg;continue}jM.set(c,g),u.style.height=(g=b)/a+"px"}else u.style.height&&(u.style.height="");let w=Q?O.top-g-p-y.y:O.bottom+p+y.y,x=S+m;if(c.overlap!==!0)for(let k of o)k.left<x&&k.right>S&&k.top<w+g&&k.bottom>w&&(w=Q?k.top-g-2-p:k.bottom+p+2);if(this.position=="absolute"?(u.style.top=(w-e.parent.top)/a+"px",CM(u,(S-e.parent.left)/i)):(u.style.top=w/a+"px",CM(u,S/i)),f){let k=O.left+(v?y.x:-y.x)-(S+14-7);f.style.left=k/i+"px"}c.overlap!==!0&&o.push({left:S,top:w,right:x,bottom:w+g}),u.classList.toggle("cm-tooltip-above",Q),u.classList.toggle("cm-tooltip-below",!Q),c.positioned&&c.positioned(e.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 e of this.manager.tooltipViews)e.dom.style.top=kg}},{eventObservers:{scroll(){this.maybeMeasure()}}});function CM(e,t){let n=parseInt(e.style.left,10);(isNaN(n)||Math.abs(t-n)>1)&&(e.style.left=t+"px")}const Pit=Pt.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:`${7*2}px`,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"}}}),_it={x:0,y:0},c8=ht.define({enables:[l8,Pit]}),FS=ht.define({combine:e=>e.reduce((t,n)=>t.concat(n),[])});class Yk{static create(t){return new Yk(t)}constructor(t){this.view=t,this.mounted=!1,this.dom=document.createElement("div"),this.dom.classList.add("cm-tooltip-hover"),this.manager=new kge(t,FS,(n,r)=>this.createHostedView(n,r),n=>n.dom.remove())}createHostedView(t,n){let r=t.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(t){for(let n of this.manager.tooltipViews)n.mount&&n.mount(t);this.mounted=!0}positioned(t){for(let n of this.manager.tooltipViews)n.positioned&&n.positioned(t)}update(t){this.manager.update(t)}destroy(){var t;for(let n of this.manager.tooltipViews)(t=n.destroy)===null||t===void 0||t.call(n)}passProp(t){let n;for(let r of this.manager.tooltipViews){let i=r[t];if(i!==void 0){if(n===void 0)n=i;else if(n!==i)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 Tit=c8.compute([FS],e=>{let t=e.facet(FS);return t.length===0?null:{pos:Math.min(...t.map(n=>n.pos)),end:Math.max(...t.map(n=>{var r;return(r=n.end)!==null&&r!==void 0?r:n.pos})),create:Yk.create,above:t[0].above,arrow:t.some(n=>n.arrow)}});class Rit{constructor(t,n,r,i,a){this.view=t,this.source=n,this.field=r,this.setHover=i,this.hoverTime=a,this.hoverTimeout=-1,this.restartTimeout=-1,this.pending=null,this.lastMove={x:0,y:0,target:t.dom,time:0},this.checkHover=this.checkHover.bind(this),t.dom.addEventListener("mouseleave",this.mouseleave=this.mouseleave.bind(this)),t.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 t=Date.now()-this.lastMove.time;t<this.hoverTime?this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime-t):this.startHover()}startHover(){clearTimeout(this.restartTimeout);let{view:t,lastMove:n}=this,r=t.docView.nearest(n.target);if(!r)return;let i,a=1;if(r instanceof OO)i=r.posAtStart;else{if(i=t.posAtCoords(n),i==null)return;let s=t.coordsAtPos(i);if(!s||n.y<s.top||n.y>s.bottom||n.x<s.left-t.defaultCharacterWidth||n.x>s.right+t.defaultCharacterWidth)return;let l=t.bidiSpans(t.state.doc.lineAt(i)).find(u=>u.from<=i&&u.to>=i),c=l&&l.dir==Er.RTL?-1:1;a=n.x<s.left?-c:c}let o=this.source(t,i,a);if(o?.then){let s=this.pending={pos:i};o.then(l=>{this.pending==s&&(this.pending=null,l&&!(Array.isArray(l)&&!l.length)&&t.dispatch({effects:this.setHover.of(Array.isArray(l)?l:[l])}))},l=>no(t.state,l,"hover tooltip"))}else o&&!(Array.isArray(o)&&!o.length)&&t.dispatch({effects:this.setHover.of(Array.isArray(o)?o:[o])})}get tooltip(){let t=this.view.plugin(l8),n=t?t.manager.tooltips.findIndex(r=>r.create==Yk.create):-1;return n>-1?t.manager.tooltipViews[n]:null}mousemove(t){var n,r;this.lastMove={x:t.clientX,y:t.clientY,target:t.target,time:Date.now()},this.hoverTimeout<0&&(this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime));let{active:i,tooltip:a}=this;if(i.length&&a&&!Xit(a.dom,t)||this.pending){let{pos:o}=i[0]||this.pending,s=(r=(n=i[0])===null||n===void 0?void 0:n.end)!==null&&r!==void 0?r:o;(o==s?this.view.posAtCoords(this.lastMove)!=o:!Eit(this.view,o,s,t.clientX,t.clientY))&&(this.view.dispatch({effects:this.setHover.of([])}),this.pending=null)}}mouseleave(t){clearTimeout(this.hoverTimeout),this.hoverTimeout=-1;let{active:n}=this;if(n.length){let{tooltip:r}=this;r&&r.dom.contains(t.relatedTarget)?this.watchTooltipLeave(r.dom):this.view.dispatch({effects:this.setHover.of([])})}}watchTooltipLeave(t){let n=r=>{t.removeEventListener("mouseleave",n),this.active.length&&!this.view.dom.contains(r.relatedTarget)&&this.view.dispatch({effects:this.setHover.of([])})};t.addEventListener("mouseleave",n)}destroy(){clearTimeout(this.hoverTimeout),this.view.dom.removeEventListener("mouseleave",this.mouseleave),this.view.dom.removeEventListener("mousemove",this.mousemove)}}const Kb=4;function Xit(e,t){let{left:n,right:r,top:i,bottom:a}=e.getBoundingClientRect(),o;if(o=e.querySelector(".cm-tooltip-arrow")){let s=o.getBoundingClientRect();i=Math.min(s.top,i),a=Math.max(s.bottom,a)}return t.clientX>=n-Kb&&t.clientX<=r+Kb&&t.clientY>=i-Kb&&t.clientY<=a+Kb}function Eit(e,t,n,r,i,a){let o=e.scrollDOM.getBoundingClientRect(),s=e.documentTop+e.documentPadding.top+e.contentHeight;if(o.left>r||o.right<r||o.top>i||Math.min(o.bottom,s)<i)return!1;let l=e.posAtCoords({x:r,y:i},!1);return l>=t&&l<=n}function wOn(e,t={}){let n=_n.define(),r=co.define({create(){return[]},update(i,a){if(i.length&&(t.hideOnChange&&(a.docChanged||a.selection)?i=[]:t.hideOn&&(i=i.filter(o=>!t.hideOn(a,o))),a.docChanged)){let o=[];for(let s of i){let l=a.changes.mapPos(s.pos,-1,Hi.TrackDel);if(l!=null){let c=Object.assign(Object.create(null),s);c.pos=l,c.end!=null&&(c.end=a.changes.mapPos(c.end)),o.push(c)}}i=o}for(let o of a.effects)o.is(n)&&(i=o.value),o.is(qit)&&(i=[]);return i},provide:i=>FS.from(i)});return{active:r,extension:[r,Ti.define(i=>new Rit(i,e,r,n,t.hoverTime||300)),Tit]}}function Pge(e,t){let n=e.plugin(l8);if(!n)return null;let r=n.manager.tooltips.indexOf(t);return r<0?null:n.manager.tooltipViews[r]}const qit=_n.define(),AM=ht.define({combine(e){let t,n;for(let r of e)t=t||r.topContainer,n=n||r.bottomContainer;return{topContainer:t,bottomContainer:n}}});function SOn(e,t){let n=e.plugin(_ge),r=n?n.specs.indexOf(t):-1;return r>-1?n.panels[r]:null}const _ge=Ti.fromClass(class{constructor(e){this.input=e.state.facet(UM),this.specs=this.input.filter(n=>n),this.panels=this.specs.map(n=>n(e));let t=e.state.facet(AM);this.top=new Jb(e,!0,t.topContainer),this.bottom=new Jb(e,!1,t.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(e){let t=e.state.facet(AM);this.top.container!=t.topContainer&&(this.top.sync([]),this.top=new Jb(e.view,!0,t.topContainer)),this.bottom.container!=t.bottomContainer&&(this.bottom.sync([]),this.bottom=new Jb(e.view,!1,t.bottomContainer)),this.top.syncClasses(),this.bottom.syncClasses();let n=e.state.facet(UM);if(n!=this.input){let r=n.filter(l=>l),i=[],a=[],o=[],s=[];for(let l of r){let c=this.specs.indexOf(l),u;c<0?(u=l(e.view),s.push(u)):(u=this.panels[c],u.update&&u.update(e)),i.push(u),(u.top?a:o).push(u)}this.specs=r,this.panels=i,this.top.sync(a),this.bottom.sync(o);for(let l of s)l.dom.classList.add("cm-panel"),l.mount&&l.mount()}else for(let r of this.panels)r.update&&r.update(e)}destroy(){this.top.sync([]),this.bottom.sync([])}},{provide:e=>Pt.scrollMargins.of(t=>{let n=t.plugin(e);return n&&{top:n.top.scrollMargin(),bottom:n.bottom.scrollMargin()}})});class Jb{constructor(t,n,r){this.view=t,this.top=n,this.container=r,this.dom=void 0,this.classes="",this.panels=[],this.syncClasses()}sync(t){for(let n of this.panels)n.destroy&&t.indexOf(n)<0&&n.destroy();this.panels=t,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 t=this.dom.firstChild;for(let n of this.panels)if(n.dom.parentNode==this.dom){for(;t!=n.dom;)t=zM(t);t=t.nextSibling}else this.dom.insertBefore(n.dom,t);for(;t;)t=zM(t)}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 t of this.classes.split(" "))t&&this.container.classList.remove(t);for(let t of(this.classes=this.view.themeClasses).split(" "))t&&this.container.classList.add(t)}}}function zM(e){let t=e.nextSibling;return e.remove(),t}const UM=ht.define({enables:_ge});class hu extends mf{compare(t){return this==t||this.constructor==t.constructor&&this.eq(t)}eq(t){return!1}destroy(t){}}hu.prototype.elementClass="";hu.prototype.toDOM=void 0;hu.prototype.mapMode=Hi.TrackBefore;hu.prototype.startSide=hu.prototype.endSide=-1;hu.prototype.point=!0;const E1=ht.define(),jit=ht.define(),Cit={class:"",renderEmptyElements:!1,elementStyle:"",markers:()=>Pn.empty,lineMarker:()=>null,widgetMarker:()=>null,lineMarkerChange:null,initialSpacer:null,updateSpacer:null,domEventHandlers:{}},F0=ht.define();function Ait(e){return[Tge(),F0.of({...Cit,...e})]}const WM=ht.define({combine:e=>e.some(t=>t)});function Tge(e){return[zit]}const zit=Ti.fromClass(class{constructor(e){this.view=e,this.prevViewport=e.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.gutters=e.state.facet(F0).map(t=>new YM(e,t));for(let t of this.gutters)this.dom.appendChild(t.dom);this.fixed=!e.state.facet(WM),this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),e.scrollDOM.insertBefore(this.dom,e.contentDOM)}update(e){if(this.updateGutters(e)){let t=this.prevViewport,n=e.view.viewport,r=Math.min(t.to,n.to)-Math.max(t.from,n.from);this.syncGutters(r<(n.to-n.from)*.8)}e.geometryChanged&&(this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px"),this.view.state.facet(WM)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":""),this.prevViewport=e.view.viewport}syncGutters(e){let t=this.dom.nextSibling;e&&this.dom.remove();let n=Pn.iter(this.view.state.facet(E1),this.view.viewport.from),r=[],i=this.gutters.map(a=>new Uit(a,this.view.viewport,-this.view.documentPadding.top));for(let a of this.view.viewportLineBlocks)if(r.length&&(r=[]),Array.isArray(a.type)){let o=!0;for(let s of a.type)if(s.type==Na.Text&&o){K3(n,r,s.from);for(let l of i)l.line(this.view,s,r);o=!1}else if(s.widget)for(let l of i)l.widget(this.view,s)}else if(a.type==Na.Text){K3(n,r,a.from);for(let o of i)o.line(this.view,a,r)}else if(a.widget)for(let o of i)o.widget(this.view,a);for(let a of i)a.finish();e&&this.view.scrollDOM.insertBefore(this.dom,t)}updateGutters(e){let t=e.startState.facet(F0),n=e.state.facet(F0),r=e.docChanged||e.heightChanged||e.viewportChanged||!Pn.eq(e.startState.facet(E1),e.state.facet(E1),e.view.viewport.from,e.view.viewport.to);if(t==n)for(let i of this.gutters)i.update(e)&&(r=!0);else{r=!0;let i=[];for(let a of n){let o=t.indexOf(a);o<0?i.push(new YM(this.view,a)):(this.gutters[o].update(e),i.push(this.gutters[o]))}for(let a of this.gutters)a.dom.remove(),i.indexOf(a)<0&&a.destroy();for(let a of i)this.dom.appendChild(a.dom);this.gutters=i}return r}destroy(){for(let e of this.gutters)e.destroy();this.dom.remove()}},{provide:e=>Pt.scrollMargins.of(t=>{let n=t.plugin(e);return!n||n.gutters.length==0||!n.fixed?null:t.textDirection==Er.LTR?{left:n.dom.offsetWidth*t.scaleX}:{right:n.dom.offsetWidth*t.scaleX}})});function NM(e){return Array.isArray(e)?e:[e]}function K3(e,t,n){for(;e.value&&e.from<=n;)e.from==n&&t.push(e.value),e.next()}class Uit{constructor(t,n,r){this.gutter=t,this.height=r,this.i=0,this.cursor=Pn.iter(t.markers,n.from)}addElement(t,n,r){let{gutter:i}=this,a=(n.top-this.height)/t.scaleY,o=n.height/t.scaleY;if(this.i==i.elements.length){let s=new Rge(t,o,a,r);i.elements.push(s),i.dom.appendChild(s.dom)}else i.elements[this.i].update(t,o,a,r);this.height=n.bottom,this.i++}line(t,n,r){let i=[];K3(this.cursor,i,n.from),r.length&&(i=i.concat(r));let a=this.gutter.config.lineMarker(t,n,i);a&&i.unshift(a);let o=this.gutter;i.length==0&&!o.config.renderEmptyElements||this.addElement(t,n,i)}widget(t,n){let r=this.gutter.config.widgetMarker(t,n.widget,n),i=r?[r]:null;for(let a of t.state.facet(jit)){let o=a(t,n.widget,n);o&&(i||(i=[])).push(o)}i&&this.addElement(t,n,i)}finish(){let t=this.gutter;for(;t.elements.length>this.i;){let n=t.elements.pop();t.dom.removeChild(n.dom),n.destroy()}}}class YM{constructor(t,n){this.view=t,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,i=>{let a=i.target,o;if(a!=this.dom&&this.dom.contains(a)){for(;a.parentNode!=this.dom;)a=a.parentNode;let l=a.getBoundingClientRect();o=(l.top+l.bottom)/2}else o=i.clientY;let s=t.lineBlockAtHeight(o-t.documentTop);n.domEventHandlers[r](t,s,i)&&i.preventDefault()});this.markers=NM(n.markers(t)),n.initialSpacer&&(this.spacer=new Rge(t,0,0,[n.initialSpacer(t)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none")}update(t){let n=this.markers;if(this.markers=NM(this.config.markers(t.view)),this.spacer&&this.config.updateSpacer){let i=this.config.updateSpacer(this.spacer.markers[0],t);i!=this.spacer.markers[0]&&this.spacer.update(t.view,0,0,[i])}let r=t.view.viewport;return!Pn.eq(this.markers,n,r.from,r.to)||(this.config.lineMarkerChange?this.config.lineMarkerChange(t):!1)}destroy(){for(let t of this.elements)t.destroy()}}class Rge{constructor(t,n,r,i){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(t,n,r,i)}update(t,n,r,i){this.height!=n&&(this.height=n,this.dom.style.height=n+"px"),this.above!=r&&(this.dom.style.marginTop=(this.above=r)?r+"px":""),Wit(this.markers,i)||this.setMarkers(t,i)}setMarkers(t,n){let r="cm-gutterElement",i=this.dom.firstChild;for(let a=0,o=0;;){let s=o,l=a<n.length?n[a++]:null,c=!1;if(l){let u=l.elementClass;u&&(r+=" "+u);for(let O=o;O<this.markers.length;O++)if(this.markers[O].compare(l)){s=O,c=!0;break}}else s=this.markers.length;for(;o<s;){let u=this.markers[o++];if(u.toDOM){u.destroy(i);let O=i.nextSibling;i.remove(),i=O}}if(!l)break;l.toDOM&&(c?i=i.nextSibling:this.dom.insertBefore(l.toDOM(t),i)),c&&o++}this.dom.className=r,this.markers=n}destroy(){this.setMarkers(null,[])}}function Wit(e,t){if(e.length!=t.length)return!1;for(let n=0;n<e.length;n++)if(!e[n].compare(t[n]))return!1;return!0}const Nit=ht.define(),Yit=ht.define(),Fh=ht.define({combine(e){return Nm(e,{formatNumber:String,domEventHandlers:{}},{domEventHandlers(t,n){let r=Object.assign({},t);for(let i in n){let a=r[i],o=n[i];r[i]=a?(s,l,c)=>a(s,l,c)||o(s,l,c):o}return r}})}});class TT extends hu{constructor(t){super(),this.number=t}eq(t){return this.number==t.number}toDOM(){return document.createTextNode(this.number)}}function RT(e,t){return e.state.facet(Fh).formatNumber(t,e.state)}const Git=F0.compute([Fh],e=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers(t){return t.state.facet(Nit)},lineMarker(t,n,r){return r.some(i=>i.toDOM)?null:new TT(RT(t,t.state.doc.lineAt(n.from).number))},widgetMarker:(t,n,r)=>{for(let i of t.state.facet(Yit)){let a=i(t,n,r);if(a)return a}return null},lineMarkerChange:t=>t.startState.facet(Fh)!=t.state.facet(Fh),initialSpacer(t){return new TT(RT(t,GM(t.state.doc.lines)))},updateSpacer(t,n){let r=RT(n.view,GM(n.view.state.doc.lines));return r==t.number?t:new TT(r)},domEventHandlers:e.facet(Fh).domEventHandlers}));function xOn(e={}){return[Fh.of(e),Tge(),Git]}function GM(e){let t=9;for(;t<e;)t=t*10+9;return t}const Iit=new class extends hu{constructor(){super(...arguments),this.elementClass="cm-activeLineGutter"}},Zit=E1.compute(["selection"],e=>{let t=[],n=-1;for(let r of e.selection.ranges){let i=e.doc.lineAt(r.head).from;i>n&&(n=i,t.push(Iit.range(i)))}return Pn.of(t)});function QOn(){return Zit}let Dit=0;class it{constructor(t,n,r,i){this.name=t,this.set=n,this.base=r,this.modified=i,this.id=Dit++}toString(){let{name:t}=this;for(let n of this.modified)n.name&&(t=`${n.name}(${t})`);return t}static define(t,n){let r=typeof t=="string"?t:"?";if(t instanceof it&&(n=t),n?.base)throw new Error("Can not derive from a modified tag");let i=new it(r,[],null,[]);if(i.set.push(i),n)for(let a of n.set)i.set.push(a);return i}static defineModifier(t){let n=new BS(t);return r=>r.modified.indexOf(n)>-1?r:BS.get(r.base||r,r.modified.concat(n).sort((i,a)=>i.id-a.id))}}let Mit=0;class BS{constructor(t){this.name=t,this.instances=[],this.id=Mit++}static get(t,n){if(!n.length)return t;let r=n[0].instances.find(s=>s.base==t&&Vit(n,s.modified));if(r)return r;let i=[],a=new it(t.name,i,t,n);for(let s of n)s.instances.push(a);let o=Lit(n);for(let s of t.set)if(!s.modified.length)for(let l of o)i.push(BS.get(s,l));return a}}function Vit(e,t){return e.length==t.length&&e.every((n,r)=>n==t[r])}function Lit(e){let t=[[]];for(let n=0;n<e.length;n++)for(let r=0,i=t.length;r<i;r++)t.push(t[r].concat(e[n]));return t.sort((n,r)=>r.length-n.length)}function An(e){let t=Object.create(null);for(let n in e){let r=e[n];Array.isArray(r)||(r=[r]);for(let i of n.split(" "))if(i){let a=[],o=2,s=i;for(let O=0;;){if(s=="..."&&O>0&&O+3==i.length){o=1;break}let d=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(s);if(!d)throw new RangeError("Invalid path: "+i);if(a.push(d[0]=="*"?"":d[0][0]=='"'?JSON.parse(d[0]):d[0]),O+=d[0].length,O==i.length)break;let f=i[O++];if(O==i.length&&f=="!"){o=0;break}if(f!="/")throw new RangeError("Invalid path: "+i);s=i.slice(O)}let l=a.length-1,c=a[l];if(!c)throw new RangeError("Invalid path: "+i);let u=new HS(r,o,l>0?a.slice(0,l):null);t[c]=u.sort(t[c])}}return Xge.add(t)}const Xge=new Gt;let HS=class{constructor(t,n,r,i){this.tags=t,this.mode=n,this.context=r,this.next=i}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(t){return!t||t.depth<this.depth?(this.next=t,this):(t.next=this.sort(t.next),t)}get depth(){return this.context?this.context.length:0}};HS.empty=new HS([],2,null);function Ege(e,t){let n=Object.create(null);for(let a of e)if(!Array.isArray(a.tag))n[a.tag.id]=a.class;else for(let o of a.tag)n[o.id]=a.class;let{scope:r,all:i=null}=t||{};return{style:a=>{let o=i;for(let s of a)for(let l of s.set){let c=n[l.id];if(c){o=o?o+" "+c:c;break}}return o},scope:r}}function Fit(e,t){let n=null;for(let r of e){let i=r.style(t);i&&(n=n?n+" "+i:i)}return n}function Bit(e,t,n,r=0,i=e.length){let a=new Hit(r,Array.isArray(t)?t:[t],n);a.highlightRange(e.cursor(),r,i,"",a.highlighters),a.flush(i)}class Hit{constructor(t,n,r){this.at=t,this.highlighters=n,this.span=r,this.class=""}startSpan(t,n){n!=this.class&&(this.flush(t),t>this.at&&(this.at=t),this.class=n)}flush(t){t>this.at&&this.class&&this.span(this.at,t,this.class)}highlightRange(t,n,r,i,a){let{type:o,from:s,to:l}=t;if(s>=r||l<=n)return;o.isTop&&(a=this.highlighters.filter(f=>!f.scope||f.scope(o)));let c=i,u=Kit(t)||HS.empty,O=Fit(a,u.tags);if(O&&(c&&(c+=" "),c+=O,u.mode==1&&(i+=(i?" ":"")+O)),this.startSpan(Math.max(n,s),c),u.opaque)return;let d=t.tree&&t.tree.prop(Gt.mounted);if(d&&d.overlay){let f=t.node.enter(d.overlay[0].from+s,1),p=this.highlighters.filter(g=>!g.scope||g.scope(d.tree.type)),m=t.firstChild();for(let g=0,y=s;;g++){let v=g<d.overlay.length?d.overlay[g]:null,S=v?v.from+s:l,Q=Math.max(n,y),b=Math.min(r,S);if(Q<b&&m)for(;t.from<b&&(this.highlightRange(t,Q,b,i,a),this.startSpan(Math.min(b,t.to),c),!(t.to>=S||!t.nextSibling())););if(!v||S>r)break;y=v.to+s,y>n&&(this.highlightRange(f.cursor(),Math.max(n,v.from+s),Math.min(r,y),"",p),this.startSpan(Math.min(r,y),c))}m&&t.parent()}else if(t.firstChild()){d&&(i="");do if(!(t.to<=n)){if(t.from>=r)break;this.highlightRange(t,n,r,i,a),this.startSpan(Math.min(r,t.to),c)}while(t.nextSibling());t.parent()}}}function Kit(e){let t=e.type.prop(Xge);for(;t&&t.context&&!e.matchContext(t.context);)t=t.next;return t||null}const tt=it.define,ew=tt(),Hu=tt(),IM=tt(Hu),ZM=tt(Hu),Ku=tt(),tw=tt(Ku),XT=tt(Ku),Ql=tt(),Od=tt(Ql),yl=tt(),vl=tt(),J3=tt(),Pg=tt(J3),nw=tt(),P={comment:ew,lineComment:tt(ew),blockComment:tt(ew),docComment:tt(ew),name:Hu,variableName:tt(Hu),typeName:IM,tagName:tt(IM),propertyName:ZM,attributeName:tt(ZM),className:tt(Hu),labelName:tt(Hu),namespace:tt(Hu),macroName:tt(Hu),literal:Ku,string:tw,docString:tt(tw),character:tt(tw),attributeValue:tt(tw),number:XT,integer:tt(XT),float:tt(XT),bool:tt(Ku),regexp:tt(Ku),escape:tt(Ku),color:tt(Ku),url:tt(Ku),keyword:yl,self:tt(yl),null:tt(yl),atom:tt(yl),unit:tt(yl),modifier:tt(yl),operatorKeyword:tt(yl),controlKeyword:tt(yl),definitionKeyword:tt(yl),moduleKeyword:tt(yl),operator:vl,derefOperator:tt(vl),arithmeticOperator:tt(vl),logicOperator:tt(vl),bitwiseOperator:tt(vl),compareOperator:tt(vl),updateOperator:tt(vl),definitionOperator:tt(vl),typeOperator:tt(vl),controlOperator:tt(vl),punctuation:J3,separator:tt(J3),bracket:Pg,angleBracket:tt(Pg),squareBracket:tt(Pg),paren:tt(Pg),brace:tt(Pg),content:Ql,heading:Od,heading1:tt(Od),heading2:tt(Od),heading3:tt(Od),heading4:tt(Od),heading5:tt(Od),heading6:tt(Od),contentSeparator:tt(Ql),list:tt(Ql),quote:tt(Ql),emphasis:tt(Ql),strong:tt(Ql),link:tt(Ql),monospace:tt(Ql),strikethrough:tt(Ql),inserted:tt(),deleted:tt(),changed:tt(),invalid:tt(),meta:nw,documentMeta:tt(nw),annotation:tt(nw),processingInstruction:tt(nw),definition:it.defineModifier("definition"),constant:it.defineModifier("constant"),function:it.defineModifier("function"),standard:it.defineModifier("standard"),local:it.defineModifier("local"),special:it.defineModifier("special")};for(let e in P){let t=P[e];t instanceof it&&(t.name=e)}Ege([{tag:P.link,class:"tok-link"},{tag:P.heading,class:"tok-heading"},{tag:P.emphasis,class:"tok-emphasis"},{tag:P.strong,class:"tok-strong"},{tag:P.keyword,class:"tok-keyword"},{tag:P.atom,class:"tok-atom"},{tag:P.bool,class:"tok-bool"},{tag:P.url,class:"tok-url"},{tag:P.labelName,class:"tok-labelName"},{tag:P.inserted,class:"tok-inserted"},{tag:P.deleted,class:"tok-deleted"},{tag:P.literal,class:"tok-literal"},{tag:P.string,class:"tok-string"},{tag:P.number,class:"tok-number"},{tag:[P.regexp,P.escape,P.special(P.string)],class:"tok-string2"},{tag:P.variableName,class:"tok-variableName"},{tag:P.local(P.variableName),class:"tok-variableName tok-local"},{tag:P.definition(P.variableName),class:"tok-variableName tok-definition"},{tag:P.special(P.variableName),class:"tok-variableName2"},{tag:P.definition(P.propertyName),class:"tok-propertyName tok-definition"},{tag:P.typeName,class:"tok-typeName"},{tag:P.namespace,class:"tok-namespace"},{tag:P.className,class:"tok-className"},{tag:P.macroName,class:"tok-macroName"},{tag:P.propertyName,class:"tok-propertyName"},{tag:P.operator,class:"tok-operator"},{tag:P.comment,class:"tok-comment"},{tag:P.meta,class:"tok-meta"},{tag:P.invalid,class:"tok-invalid"},{tag:P.punctuation,class:"tok-punctuation"}]);var ET;const fO=new Gt;function Gk(e){return ht.define({combine:e?t=>t.concat(e):void 0})}const u8=new Gt;class Ao{constructor(t,n,r=[],i=""){this.data=t,this.name=i,Nn.prototype.hasOwnProperty("tree")||Object.defineProperty(Nn.prototype,"tree",{get(){return Bn(this)}}),this.parser=n,this.extension=[CO.of(this),Nn.languageData.of((a,o,s)=>{let l=DM(a,o,s),c=l.type.prop(fO);if(!c)return[];let u=a.facet(c),O=l.type.prop(u8);if(O){let d=l.resolve(o-l.from,s);for(let f of O)if(f.test(d,a)){let p=a.facet(f.facet);return f.type=="replace"?p:p.concat(u)}}return u})].concat(r)}isActiveAt(t,n,r=-1){return DM(t,n,r).type.prop(fO)==this.data}findRegions(t){let n=t.facet(CO);if(n?.data==this.data)return[{from:0,to:t.doc.length}];if(!n||!n.allowsNesting)return[];let r=[],i=(a,o)=>{if(a.prop(fO)==this.data){r.push({from:o,to:o+a.length});return}let s=a.prop(Gt.mounted);if(s){if(s.tree.prop(fO)==this.data){if(s.overlay)for(let l of s.overlay)r.push({from:l.from+o,to:l.to+o});else r.push({from:o,to:o+a.length});return}else if(s.overlay){let l=r.length;if(i(s.tree,s.overlay[0].from+o),r.length>l)return}}for(let l=0;l<a.children.length;l++){let c=a.children[l];c instanceof hn&&i(c,a.positions[l]+o)}};return i(Bn(t),0),r}get allowsNesting(){return!0}}Ao.setState=_n.define();function DM(e,t,n){let r=e.facet(CO),i=Bn(e).topNode;if(!r||r.allowsNesting)for(let a=i;a;a=a.enter(t,n,cr.ExcludeBuffers))a.type.isTop&&(i=a);return i}class Rn extends Ao{constructor(t,n,r){super(t,n,[],r),this.parser=n}static define(t){let n=Gk(t.languageData);return new Rn(n,t.parser.configure({props:[fO.add(r=>r.isTop?n:void 0)]}),t.name)}configure(t,n){return new Rn(this.data,this.parser.configure(t),n||this.name)}get allowsNesting(){return this.parser.hasWrappers()}}function Bn(e){let t=e.field(Ao.state,!1);return t?t.tree:hn.empty}class Jit{constructor(t){this.doc=t,this.cursorPos=0,this.string="",this.cursor=t.iter()}get length(){return this.doc.length}syncTo(t){return this.string=this.cursor.next(t-this.cursorPos).value,this.cursorPos=t+this.string.length,this.cursorPos-this.string.length}chunk(t){return this.syncTo(t),this.string}get lineChunks(){return!0}read(t,n){let r=this.cursorPos-this.string.length;return t<r||n>=this.cursorPos?this.doc.sliceString(t,n):this.string.slice(t-r,n-r)}}let _g=null;class bf{constructor(t,n,r=[],i,a,o,s,l){this.parser=t,this.state=n,this.fragments=r,this.tree=i,this.treeLen=a,this.viewport=o,this.skipped=s,this.scheduleOn=l,this.parse=null,this.tempSkipped=[]}static create(t,n,r){return new bf(t,n,[],hn.empty,0,r,[],null)}startParse(){return this.parser.startParse(new Jit(this.state.doc),this.fragments)}work(t,n){return n!=null&&n>=this.state.doc.length&&(n=void 0),this.tree!=hn.empty&&this.isDone(n??this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{var r;if(typeof t=="number"){let i=Date.now()+t;t=()=>Date.now()>i}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 i=this.parse.advance();if(i)if(this.fragments=this.withoutTempSkipped(eu.addTree(i,this.fragments,this.parse.stoppedAt!=null)),this.treeLen=(r=this.parse.stoppedAt)!==null&&r!==void 0?r:this.state.doc.length,this.tree=i,this.parse=null,this.treeLen<(n??this.state.doc.length))this.parse=this.startParse();else return!0;if(t())return!1}})}takeTree(){let t,n;this.parse&&(t=this.parse.parsedPos)>=this.treeLen&&((this.parse.stoppedAt==null||this.parse.stoppedAt>t)&&this.parse.stopAt(t),this.withContext(()=>{for(;!(n=this.parse.advance()););}),this.treeLen=t,this.tree=n,this.fragments=this.withoutTempSkipped(eu.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(t){let n=_g;_g=this;try{return t()}finally{_g=n}}withoutTempSkipped(t){for(let n;n=this.tempSkipped.pop();)t=MM(t,n.from,n.to);return t}changes(t,n){let{fragments:r,tree:i,treeLen:a,viewport:o,skipped:s}=this;if(this.takeTree(),!t.empty){let l=[];if(t.iterChangedRanges((c,u,O,d)=>l.push({fromA:c,toA:u,fromB:O,toB:d})),r=eu.applyChanges(r,l),i=hn.empty,a=0,o={from:t.mapPos(o.from,-1),to:t.mapPos(o.to,1)},this.skipped.length){s=[];for(let c of this.skipped){let u=t.mapPos(c.from,1),O=t.mapPos(c.to,-1);u<O&&s.push({from:u,to:O})}}}return new bf(this.parser,n,r,i,a,o,s,this.scheduleOn)}updateViewport(t){if(this.viewport.from==t.from&&this.viewport.to==t.to)return!1;this.viewport=t;let n=this.skipped.length;for(let r=0;r<this.skipped.length;r++){let{from:i,to:a}=this.skipped[r];i<t.to&&a>t.from&&(this.fragments=MM(this.fragments,i,a),this.skipped.splice(r--,1))}return this.skipped.length>=n?!1:(this.reset(),!0)}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(t,n){this.skipped.push({from:t,to:n})}static getSkippingParser(t){return new class extends Ak{createParse(n,r,i){let a=i[0].from,o=i[i.length-1].to;return{parsedPos:a,advance(){let l=_g;if(l){for(let c of i)l.tempSkipped.push(c);t&&(l.scheduleOn=l.scheduleOn?Promise.all([l.scheduleOn,t]):t)}return this.parsedPos=o,new hn(yi.none,[],[],o-a)},stoppedAt:null,stopAt(){}}}}}isDone(t){t=Math.min(t,this.state.doc.length);let n=this.fragments;return this.treeLen>=t&&n.length&&n[0].from==0&&n[0].to>=t}static get(){return _g}}function MM(e,t,n){return eu.applyChanges(e,[{fromA:t,toA:n,fromB:t,toB:n}])}class Yp{constructor(t){this.context=t,this.tree=t.tree}apply(t){if(!t.docChanged&&this.tree==this.context.tree)return this;let n=this.context.changes(t.changes,t.state),r=this.context.treeLen==t.startState.doc.length?void 0:Math.max(t.changes.mapPos(this.context.treeLen),n.viewport.to);return n.work(20,r)||n.takeTree(),new Yp(n)}static init(t){let n=Math.min(3e3,t.doc.length),r=bf.create(t.facet(CO).parser,t,{from:0,to:n});return r.work(20,n)||r.takeTree(),new Yp(r)}}Ao.state=co.define({create:Yp.init,update(e,t){for(let n of t.effects)if(n.is(Ao.setState))return n.value;return t.startState.facet(CO)!=t.state.facet(CO)?Yp.init(t.state):e.apply(t)}});let qge=e=>{let t=setTimeout(()=>e(),500);return()=>clearTimeout(t)};typeof requestIdleCallback<"u"&&(qge=e=>{let t=-1,n=setTimeout(()=>{t=requestIdleCallback(e,{timeout:400})},100);return()=>t<0?clearTimeout(n):cancelIdleCallback(t)});const qT=typeof navigator<"u"&&(!((ET=navigator.scheduling)===null||ET===void 0)&&ET.isInputPending)?()=>navigator.scheduling.isInputPending():null,eat=Ti.fromClass(class{constructor(t){this.view=t,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(t){let n=this.view.state.field(Ao.state).context;(n.updateViewport(t.view.viewport)||this.view.viewport.to>n.treeLen)&&this.scheduleWork(),(t.docChanged||t.selectionSet)&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(n)}scheduleWork(){if(this.working)return;let{state:t}=this.view,n=t.field(Ao.state);(n.tree!=n.context.tree||!n.context.isDone(t.doc.length))&&(this.working=qge(this.work))}work(t){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:i}}=this.view,a=r.field(Ao.state);if(a.tree==a.context.tree&&a.context.isDone(i+1e5))return;let o=Date.now()+Math.min(this.chunkBudget,100,t&&!qT?Math.max(25,t.timeRemaining()-5):1e9),s=a.context.treeLen<i&&r.doc.length>i+1e3,l=a.context.work(()=>qT&&qT()||Date.now()>o,i+(s?0:1e5));this.chunkBudget-=Date.now()-n,(l||this.chunkBudget<=0)&&(a.context.takeTree(),this.view.dispatch({effects:Ao.setState.of(new Yp(a.context))})),this.chunkBudget>0&&!(l&&!s)&&this.scheduleWork(),this.checkAsyncSchedule(a.context)}checkAsyncSchedule(t){t.scheduleOn&&(this.workScheduled++,t.scheduleOn.then(()=>this.scheduleWork()).catch(n=>no(this.view.state,n)).then(()=>this.workScheduled--),t.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},{eventHandlers:{focus(){this.scheduleWork()}}}),CO=ht.define({combine(e){return e.length?e[0]:null},enables:e=>[Ao.state,eat,Pt.contentAttributes.compute([e],t=>{let n=t.facet(e);return n&&n.name?{"data-language":n.name}:{}})]});class wn{constructor(t,n=[]){this.language=t,this.support=n,this.extension=[t,n]}}class $e{constructor(t,n,r,i,a,o=void 0){this.name=t,this.alias=n,this.extensions=r,this.filename=i,this.loadFunc=a,this.support=o,this.loading=null}load(){return this.loading||(this.loading=this.loadFunc().then(t=>this.support=t,t=>{throw this.loading=null,t}))}static of(t){let{load:n,support:r}=t;if(!n){if(!r)throw new RangeError("Must pass either 'load' or 'support' to LanguageDescription.of");n=()=>Promise.resolve(r)}return new $e(t.name,(t.alias||[]).concat(t.name).map(i=>i.toLowerCase()),t.extensions||[],t.filename,n,r)}static matchFilename(t,n){for(let i of t)if(i.filename&&i.filename.test(n))return i;let r=/\.([^.]+)$/.exec(n);if(r){for(let i of t)if(i.extensions.indexOf(r[1])>-1)return i}return null}static matchLanguageName(t,n,r=!0){n=n.toLowerCase();for(let i of t)if(i.alias.some(a=>a==n))return i;if(r)for(let i of t)for(let a of i.alias){let o=n.indexOf(a);if(o>-1&&(a.length>2||!/\w/.test(n[o-1])&&!/\w/.test(n[o+a.length])))return i}return null}}const tat=ht.define(),Ik=ht.define({combine:e=>{if(!e.length)return" ";let t=e[0];if(!t||/\S/.test(t)||Array.from(t).some(n=>n!=t[0]))throw new Error("Invalid indent unit: "+JSON.stringify(e[0]));return t}});function KS(e){let t=e.facet(Ik);return t.charCodeAt(0)==9?e.tabSize*t.length:t.length}function nat(e,t){let n="",r=e.tabSize,i=e.facet(Ik)[0];if(i==" "){for(;t>=r;)n+=" ",t-=r;i=" "}for(let a=0;a<t;a++)n+=i;return n}function rat(e,t){e instanceof Nn&&(e=new jge(e));for(let r of e.state.facet(tat)){let i=r(e,t);if(i!==void 0)return i}let n=Bn(e.state);return n.length>=t?iat(e,n,t):null}class jge{constructor(t,n={}){this.state=t,this.options=n,this.unit=KS(t)}lineAt(t,n=1){let r=this.state.doc.lineAt(t),{simulateBreak:i,simulateDoubleBreak:a}=this.options;return i!=null&&i>=r.from&&i<=r.to?a&&i==t?{text:"",from:t}:(n<0?i<t:i<=t)?{text:r.text.slice(i-r.from),from:i}:{text:r.text.slice(0,i-r.from),from:r.from}:r}textAfterPos(t,n=1){if(this.options.simulateDoubleBreak&&t==this.options.simulateBreak)return"";let{text:r,from:i}=this.lineAt(t,n);return r.slice(t-i,Math.min(r.length,t+100-i))}column(t,n=1){let{text:r,from:i}=this.lineAt(t,n),a=this.countColumn(r,t-i),o=this.options.overrideIndentation?this.options.overrideIndentation(i):-1;return o>-1&&(a+=o-this.countColumn(r,r.search(/\S|$/))),a}countColumn(t,n=t.length){return XO(t,this.state.tabSize,n)}lineIndent(t,n=1){let{text:r,from:i}=this.lineAt(t,n),a=this.options.overrideIndentation;if(a){let o=a(i);if(o>-1)return o}return this.countColumn(r,r.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}}const Yr=new Gt;function iat(e,t,n){let r=t.resolveStack(n),i=t.resolveInner(n,-1).resolve(n,0).enterUnfinishedNodesBefore(n);if(i!=r.node){let a=[];for(let o=i;o&&!(o.from<r.node.from||o.to>r.node.to||o.from==r.node.from&&o.type==r.node.type);o=o.parent)a.push(o);for(let o=a.length-1;o>=0;o--)r={node:a[o],next:r}}return Cge(r,e,n)}function Cge(e,t,n){for(let r=e;r;r=r.next){let i=oat(r.node);if(i)return i(O8.create(t,n,r))}return 0}function aat(e){return e.pos==e.options.simulateBreak&&e.options.simulateDoubleBreak}function oat(e){let t=e.type.prop(Yr);if(t)return t;let n=e.firstChild,r;if(n&&(r=n.type.prop(Gt.closedBy))){let i=e.lastChild,a=i&&r.indexOf(i.name)>-1;return o=>Age(o,!0,1,void 0,a&&!aat(o)?i.from:void 0)}return e.parent==null?sat:null}function sat(){return 0}class O8 extends jge{constructor(t,n,r){super(t.state,t.options),this.base=t,this.pos=n,this.context=r}get node(){return this.context.node}static create(t,n,r){return new O8(t,n,r)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){return this.baseIndentFor(this.node)}baseIndentFor(t){let n=this.state.doc.lineAt(t.from);for(;;){let r=t.resolve(n.from);for(;r.parent&&r.parent.from==r.from;)r=r.parent;if(lat(r,t))break;n=this.state.doc.lineAt(r.from)}return this.lineIndent(n.from)}continue(){return Cge(this.context.next,this.base,this.pos)}}function lat(e,t){for(let n=t;n;n=n.parent)if(e==n)return!0;return!1}function cat(e){let t=e.node,n=t.childAfter(t.from),r=t.lastChild;if(!n)return null;let i=e.options.simulateBreak,a=e.state.doc.lineAt(n.from),o=i==null||i<=a.from?a.to:Math.min(a.to,i);for(let s=n.to;;){let l=t.childAfter(s);if(!l||l==r)return null;if(!l.type.isSkipped){if(l.from>=o)return null;let c=/^ */.exec(a.text.slice(n.to-a.from))[0].length;return{from:n.from,to:n.to+c}}s=l.to}}function bs({closing:e,align:t=!0,units:n=1}){return r=>Age(r,t,n,e)}function Age(e,t,n,r,i){let a=e.textAfter,o=a.match(/^\s*/)[0].length,s=r&&a.slice(o,o+r.length)==r||i==e.pos+o,l=t?cat(e):null;return l?s?e.column(l.from):e.column(l.to):e.baseIndent+(s?0:e.unit*n)}const d8=e=>e.baseIndent;function Lr({except:e,units:t=1}={}){return n=>{let r=e&&e.test(n.textAfter);return n.baseIndent+(r?0:t*n.unit)}}const uat=200;function _On(){return Nn.transactionFilter.of(e=>{if(!e.docChanged||!e.isUserEvent("input.type")&&!e.isUserEvent("input.complete"))return e;let t=e.startState.languageDataAt("indentOnInput",e.startState.selection.main.head);if(!t.length)return e;let n=e.newDoc,{head:r}=e.newSelection.main,i=n.lineAt(r);if(r>i.from+uat)return e;let a=n.sliceString(i.from,r);if(!t.some(c=>c.test(a)))return e;let{state:o}=e,s=-1,l=[];for(let{head:c}of o.selection.ranges){let u=o.doc.lineAt(c);if(u.from==s)continue;s=u.from;let O=rat(o,u.from);if(O==null)continue;let d=/^\s*/.exec(u.text)[0],f=nat(o,O);d!=f&&l.push({from:u.from,to:u.from+d.length,insert:f})}return l.length?[e,{changes:l,sequential:!0}]:e})}const zge=ht.define(),Cr=new Gt;function wa(e){let t=e.firstChild,n=e.lastChild;return t&&t.to<n.from?{from:t.to,to:n.type.isError?e.to:n.from}:null}function Oat(e,t,n){let r=Bn(e);if(r.length<n)return null;let i=r.resolveStack(n,1),a=null;for(let o=i;o;o=o.next){let s=o.node;if(s.to<=n||s.from>n)continue;if(a&&s.from<t)break;let l=s.type.prop(Cr);if(l&&(s.to<r.length-50||r.length==e.doc.length||!dat(s))){let c=l(s,e);c&&c.from<=n&&c.from>=t&&c.to>n&&(a=c)}}return a}function dat(e){let t=e.lastChild;return t&&t.to==e.to&&t.type.isError}function JS(e,t,n){for(let r of e.facet(zge)){let i=r(e,t,n);if(i)return i}return Oat(e,t,n)}function Uge(e,t){let n=t.mapPos(e.from,1),r=t.mapPos(e.to,-1);return n>=r?void 0:{from:n,to:r}}const Zk=_n.define({map:Uge}),Xv=_n.define({map:Uge});function Wge(e){let t=[];for(let{head:n}of e.state.selection.ranges)t.some(r=>r.from<=n&&r.to>=n)||t.push(e.lineBlockAt(n));return t}const wf=co.define({create(){return cn.none},update(e,t){e=e.map(t.changes);for(let n of t.effects)if(n.is(Zk)&&!fat(e,n.value.from,n.value.to)){let{preparePlaceholder:r}=t.state.facet(Gge),i=r?cn.replace({widget:new yat(r(t.state,n.value))}):VM;e=e.update({add:[i.range(n.value.from,n.value.to)]})}else n.is(Xv)&&(e=e.update({filter:(r,i)=>n.value.from!=r||n.value.to!=i,filterFrom:n.value.from,filterTo:n.value.to}));if(t.selection){let n=!1,{head:r}=t.selection.main;e.between(r,r,(i,a)=>{i<r&&a>r&&(n=!0)}),n&&(e=e.update({filterFrom:r,filterTo:r,filter:(i,a)=>a<=r||i>=r}))}return e},provide:e=>Pt.decorations.from(e),toJSON(e,t){let n=[];return e.between(0,t.doc.length,(r,i)=>{n.push(r,i)}),n},fromJSON(e){if(!Array.isArray(e)||e.length%2)throw new RangeError("Invalid JSON for fold state");let t=[];for(let n=0;n<e.length;){let r=e[n++],i=e[n++];if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid JSON for fold state");t.push(VM.range(r,i))}return cn.set(t,!0)}});function ex(e,t,n){var r;let i=null;return(r=e.field(wf,!1))===null||r===void 0||r.between(t,n,(a,o)=>{(!i||i.from>a)&&(i={from:a,to:o})}),i}function fat(e,t,n){let r=!1;return e.between(t,t,(i,a)=>{i==t&&a==n&&(r=!0)}),r}function Nge(e,t){return e.field(wf,!1)?t:t.concat(_n.appendConfig.of(Ige()))}const hat=e=>{for(let t of Wge(e)){let n=JS(e.state,t.from,t.to);if(n)return e.dispatch({effects:Nge(e.state,[Zk.of(n),Yge(e,n)])}),!0}return!1},pat=e=>{if(!e.state.field(wf,!1))return!1;let t=[];for(let n of Wge(e)){let r=ex(e.state,n.from,n.to);r&&t.push(Xv.of(r),Yge(e,r,!1))}return t.length&&e.dispatch({effects:t}),t.length>0};function Yge(e,t,n=!0){let r=e.state.doc.lineAt(t.from).number,i=e.state.doc.lineAt(t.to).number;return Pt.announce.of(`${e.state.phrase(n?"Folded lines":"Unfolded lines")} ${r} ${e.state.phrase("to")} ${i}.`)}const mat=e=>{let{state:t}=e,n=[];for(let r=0;r<t.doc.length;){let i=e.lineBlockAt(r),a=JS(t,i.from,i.to);a&&n.push(Zk.of(a)),r=(a?e.lineBlockAt(a.to):i).to+1}return n.length&&e.dispatch({effects:Nge(e.state,n)}),!!n.length},gat=e=>{let t=e.state.field(wf,!1);if(!t||!t.size)return!1;let n=[];return t.between(0,e.state.doc.length,(r,i)=>{n.push(Xv.of({from:r,to:i}))}),e.dispatch({effects:n}),!0},TOn=[{key:"Ctrl-Shift-[",mac:"Cmd-Alt-[",run:hat},{key:"Ctrl-Shift-]",mac:"Cmd-Alt-]",run:pat},{key:"Ctrl-Alt-[",run:mat},{key:"Ctrl-Alt-]",run:gat}],$at={placeholderDOM:null,preparePlaceholder:null,placeholderText:"…"},Gge=ht.define({combine(e){return Nm(e,$at)}});function Ige(e){return[wf,bat]}function Zge(e,t){let{state:n}=e,r=n.facet(Gge),i=o=>{let s=e.lineBlockAt(e.posAtDOM(o.target)),l=ex(e.state,s.from,s.to);l&&e.dispatch({effects:Xv.of(l)}),o.preventDefault()};if(r.placeholderDOM)return r.placeholderDOM(e,i,t);let a=document.createElement("span");return a.textContent=r.placeholderText,a.setAttribute("aria-label",n.phrase("folded code")),a.title=n.phrase("unfold"),a.className="cm-foldPlaceholder",a.onclick=i,a}const VM=cn.replace({widget:new class extends Tu{toDOM(e){return Zge(e,null)}}});class yat extends Tu{constructor(t){super(),this.value=t}eq(t){return this.value==t.value}toDOM(t){return Zge(t,this.value)}}const vat={openText:"⌄",closedText:"›",markerDOM:null,domEventHandlers:{},foldingChanged:()=>!1};class jT extends hu{constructor(t,n){super(),this.config=t,this.open=n}eq(t){return this.config==t.config&&this.open==t.open}toDOM(t){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=t.state.phrase(this.open?"Fold line":"Unfold line"),n}}function ROn(e={}){let t={...vat,...e},n=new jT(t,!0),r=new jT(t,!1),i=Ti.fromClass(class{constructor(o){this.from=o.viewport.from,this.markers=this.buildMarkers(o)}update(o){(o.docChanged||o.viewportChanged||o.startState.facet(CO)!=o.state.facet(CO)||o.startState.field(wf,!1)!=o.state.field(wf,!1)||Bn(o.startState)!=Bn(o.state)||t.foldingChanged(o))&&(this.markers=this.buildMarkers(o.view))}buildMarkers(o){let s=new gf;for(let l of o.viewportLineBlocks){let c=ex(o.state,l.from,l.to)?r:JS(o.state,l.from,l.to)?n:null;c&&s.add(l.from,l.from,c)}return s.finish()}}),{domEventHandlers:a}=t;return[i,Ait({class:"cm-foldGutter",markers(o){var s;return((s=o.plugin(i))===null||s===void 0?void 0:s.markers)||Pn.empty},initialSpacer(){return new jT(t,!1)},domEventHandlers:{...a,click:(o,s,l)=>{if(a.click&&a.click(o,s,l))return!0;let c=ex(o.state,s.from,s.to);if(c)return o.dispatch({effects:Xv.of(c)}),!0;let u=JS(o.state,s.from,s.to);return u?(o.dispatch({effects:Zk.of(u)}),!0):!1}}}),Ige()]}const bat=Pt.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 Dk{constructor(t,n){this.specs=t;let r;function i(s){let l=EO.newName();return(r||(r=Object.create(null)))["."+l]=s,l}const a=typeof n.all=="string"?n.all:n.all?i(n.all):void 0,o=n.scope;this.scope=o instanceof Ao?s=>s.prop(fO)==o.data:o?s=>s==o:void 0,this.style=Ege(t.map(s=>({tag:s.tag,class:s.class||i(Object.assign({},s,{tag:null}))})),{all:a}).style,this.module=r?new EO(r):null,this.themeType=n.themeType}static define(t,n){return new Dk(t,n||{})}}const eC=ht.define(),Dge=ht.define({combine(e){return e.length?[e[0]]:null}});function CT(e){let t=e.facet(eC);return t.length?t:e.facet(Dge)}function XOn(e,t){let n=[Sat],r;return e instanceof Dk&&(e.module&&n.push(Pt.styleModule.of(e.module)),r=e.themeType),t?.fallback?n.push(Dge.of(e)):r?n.push(eC.computeN([Pt.darkTheme],i=>i.facet(Pt.darkTheme)==(r=="dark")?[e]:[])):n.push(eC.of(e)),n}class wat{constructor(t){this.markCache=Object.create(null),this.tree=Bn(t.state),this.decorations=this.buildDeco(t,CT(t.state)),this.decoratedTo=t.viewport.to}update(t){let n=Bn(t.state),r=CT(t.state),i=r!=CT(t.startState),{viewport:a}=t.view,o=t.changes.mapPos(this.decoratedTo,1);n.length<a.to&&!i&&n.type==this.tree.type&&o>=a.to?(this.decorations=this.decorations.map(t.changes),this.decoratedTo=o):(n!=this.tree||t.viewportChanged||i)&&(this.tree=n,this.decorations=this.buildDeco(t.view,r),this.decoratedTo=a.to)}buildDeco(t,n){if(!n||!this.tree.length)return cn.none;let r=new gf;for(let{from:i,to:a}of t.visibleRanges)Bit(this.tree,n,(o,s,l)=>{r.add(o,s,this.markCache[l]||(this.markCache[l]=cn.mark({class:l})))},i,a);return r.finish()}}const Sat=ZO.high(Ti.fromClass(wat,{decorations:e=>e.decorations})),EOn=Dk.define([{tag:P.meta,color:"#404740"},{tag:P.link,textDecoration:"underline"},{tag:P.heading,textDecoration:"underline",fontWeight:"bold"},{tag:P.emphasis,fontStyle:"italic"},{tag:P.strong,fontWeight:"bold"},{tag:P.strikethrough,textDecoration:"line-through"},{tag:P.keyword,color:"#708"},{tag:[P.atom,P.bool,P.url,P.contentSeparator,P.labelName],color:"#219"},{tag:[P.literal,P.inserted],color:"#164"},{tag:[P.string,P.deleted],color:"#a11"},{tag:[P.regexp,P.escape,P.special(P.string)],color:"#e40"},{tag:P.definition(P.variableName),color:"#00f"},{tag:P.local(P.variableName),color:"#30a"},{tag:[P.typeName,P.namespace],color:"#085"},{tag:P.className,color:"#167"},{tag:[P.special(P.variableName),P.macroName],color:"#256"},{tag:P.definition(P.propertyName),color:"#00c"},{tag:P.comment,color:"#940"},{tag:P.invalid,color:"#f00"}]),xat=Pt.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}}),Mge=1e4,Vge="()[]{}",Lge=ht.define({combine(e){return Nm(e,{afterCursor:!0,brackets:Vge,maxScanDistance:Mge,renderMatch:Pat})}}),Qat=cn.mark({class:"cm-matchingBracket"}),kat=cn.mark({class:"cm-nonmatchingBracket"});function Pat(e){let t=[],n=e.matched?Qat:kat;return t.push(n.range(e.start.from,e.start.to)),e.end&&t.push(n.range(e.end.from,e.end.to)),t}const _at=co.define({create(){return cn.none},update(e,t){if(!t.docChanged&&!t.selection)return e;let n=[],r=t.state.facet(Lge);for(let i of t.state.selection.ranges){if(!i.empty)continue;let a=rw(t.state,i.head,-1,r)||i.head>0&&rw(t.state,i.head-1,1,r)||r.afterCursor&&(rw(t.state,i.head,1,r)||i.head<t.state.doc.length&&rw(t.state,i.head+1,-1,r));a&&(n=n.concat(r.renderMatch(a,t.state)))}return cn.set(n,!0)},provide:e=>Pt.decorations.from(e)}),Tat=[_at,xat];function qOn(e={}){return[Lge.of(e),Tat]}const f8=new Gt;function tC(e,t,n){let r=e.prop(t<0?Gt.openedBy:Gt.closedBy);if(r)return r;if(e.name.length==1){let i=n.indexOf(e.name);if(i>-1&&i%2==(t<0?1:0))return[n[i+t]]}return null}function nC(e){let t=e.type.prop(f8);return t?t(e.node):e}function rw(e,t,n,r={}){let i=r.maxScanDistance||Mge,a=r.brackets||Vge,o=Bn(e),s=o.resolveInner(t,n);for(let l=s;l;l=l.parent){let c=tC(l.type,n,a);if(c&&l.from<l.to){let u=nC(l);if(u&&(n>0?t>=u.from&&t<u.to:t>u.from&&t<=u.to))return Rat(e,t,n,l,u,c,a)}}return Xat(e,t,n,o,s.type,i,a)}function Rat(e,t,n,r,i,a,o){let s=r.parent,l={from:i.from,to:i.to},c=0,u=s?.cursor();if(u&&(n<0?u.childBefore(r.from):u.childAfter(r.to)))do if(n<0?u.to<=r.from:u.from>=r.to){if(c==0&&a.indexOf(u.type.name)>-1&&u.from<u.to){let O=nC(u);return{start:l,end:O?{from:O.from,to:O.to}:void 0,matched:!0}}else if(tC(u.type,n,o))c++;else if(tC(u.type,-n,o)){if(c==0){let O=nC(u);return{start:l,end:O&&O.from<O.to?{from:O.from,to:O.to}:void 0,matched:!1}}c--}}while(n<0?u.prevSibling():u.nextSibling());return{start:l,matched:!1}}function Xat(e,t,n,r,i,a,o){let s=n<0?e.sliceDoc(t-1,t):e.sliceDoc(t,t+1),l=o.indexOf(s);if(l<0||l%2==0!=n>0)return null;let c={from:n<0?t-1:t,to:n>0?t+1:t},u=e.doc.iterRange(t,n>0?e.doc.length:0),O=0;for(let d=0;!u.next().done&&d<=a;){let f=u.value;n<0&&(d+=f.length);let p=t+d*n;for(let m=n>0?0:f.length-1,g=n>0?f.length:-1;m!=g;m+=n){let y=o.indexOf(f[m]);if(!(y<0||r.resolveInner(p+m,1).type!=i))if(y%2==0==n>0)O++;else{if(O==1)return{start:c,end:{from:p+m,to:p+m+1},matched:y>>1==l>>1};O--}}n>0&&(d+=f.length)}return u.done?{start:c,matched:!1}:null}function LM(e,t,n,r=0,i=0){t==null&&(t=e.search(/[^\s\u00a0]/),t==-1&&(t=e.length));let a=i;for(let o=r;o<t;o++)e.charCodeAt(o)==9?a+=n-a%n:a++;return a}class Fge{constructor(t,n,r,i){this.string=t,this.tabSize=n,this.indentUnit=r,this.overrideIndent=i,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(t){let n=this.string.charAt(this.pos),r;if(typeof t=="string"?r=n==t:r=n&&(t instanceof RegExp?t.test(n):t(n)),r)return++this.pos,n}eatWhile(t){let n=this.pos;for(;this.eat(t););return this.pos>n}eatSpace(){let t=this.pos;for(;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>t}skipToEnd(){this.pos=this.string.length}skipTo(t){let n=this.string.indexOf(t,this.pos);if(n>-1)return this.pos=n,!0}backUp(t){this.pos-=t}column(){return this.lastColumnPos<this.start&&(this.lastColumnValue=LM(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue),this.lastColumnPos=this.start),this.lastColumnValue}indentation(){var t;return(t=this.overrideIndent)!==null&&t!==void 0?t:LM(this.string,null,this.tabSize)}match(t,n,r){if(typeof t=="string"){let i=o=>r?o.toLowerCase():o,a=this.string.substr(this.pos,t.length);return i(a)==i(t)?(n!==!1&&(this.pos+=t.length),!0):null}else{let i=this.string.slice(this.pos).match(t);return i&&i.index>0?null:(i&&n!==!1&&(this.pos+=i[0].length),i)}}current(){return this.string.slice(this.start,this.pos)}}function Eat(e){return{name:e.name||"",token:e.token,blankLine:e.blankLine||(()=>{}),startState:e.startState||(()=>!0),copyState:e.copyState||qat,indent:e.indent||(()=>null),languageData:e.languageData||{},tokenTable:e.tokenTable||p8,mergeTokens:e.mergeTokens!==!1}}function qat(e){if(typeof e!="object")return e;let t={};for(let n in e){let r=e[n];t[n]=r instanceof Array?r.slice():r}return t}const FM=new WeakMap;class Ae extends Ao{constructor(t){let n=Gk(t.languageData),r=Eat(t),i,a=new class extends Ak{createParse(o,s,l){return new Cat(i,o,s,l)}};super(n,a,[],t.name),this.topNode=Uat(n,this),i=this,this.streamParser=r,this.stateAfter=new Gt({perNode:!0}),this.tokenTable=t.tokenTable?new Jge(r.tokenTable):zat}static define(t){return new Ae(t)}getIndent(t){let n,{overrideIndentation:r}=t.options;r&&(n=FM.get(t.state),n!=null&&n<t.pos-1e4&&(n=void 0));let i=h8(this,t.node.tree,t.node.from,t.node.from,n??t.pos),a,o;if(i?(o=i.state,a=i.pos+1):(o=this.streamParser.startState(t.unit),a=t.node.from),t.pos-a>1e4)return null;for(;a<t.pos;){let l=t.state.doc.lineAt(a),c=Math.min(t.pos,l.to);if(l.length){let u=r?r(l.from):-1,O=new Fge(l.text,t.state.tabSize,t.unit,u<0?void 0:u);for(;O.pos<c-l.from;)Hge(this.streamParser.token,O,o)}else this.streamParser.blankLine(o,t.unit);if(c==t.pos)break;a=l.to+1}let s=t.lineAt(t.pos);return r&&n==null&&FM.set(t.state,s.from),this.streamParser.indent(o,/^\s*(.*)/.exec(s.text)[1],t)}get allowsNesting(){return!1}}function h8(e,t,n,r,i){let a=n>=r&&n+t.length<=i&&t.prop(e.stateAfter);if(a)return{state:e.streamParser.copyState(a),pos:n+t.length};for(let o=t.children.length-1;o>=0;o--){let s=t.children[o],l=n+t.positions[o],c=s instanceof hn&&l<i&&h8(e,s,l,r,i);if(c)return c}return null}function Bge(e,t,n,r,i){if(i&&n<=0&&r>=t.length)return t;!i&&n==0&&t.type==e.topNode&&(i=!0);for(let a=t.children.length-1;a>=0;a--){let o=t.positions[a],s=t.children[a],l;if(o<r&&s instanceof hn){if(!(l=Bge(e,s,n-o,r-o,i)))break;return i?new hn(t.type,t.children.slice(0,a).concat(l),t.positions.slice(0,a+1),o+l.length):l}}return null}function jat(e,t,n,r,i){for(let a of t){let o=a.from+(a.openStart?25:0),s=a.to-(a.openEnd?25:0),l=o<=n&&s>n&&h8(e,a.tree,0-a.offset,n,s),c;if(l&&l.pos<=r&&(c=Bge(e,a.tree,n+a.offset,l.pos+a.offset,!1)))return{state:l.state,tree:c}}return{state:e.streamParser.startState(i?KS(i):4),tree:hn.empty}}let Cat=class{constructor(t,n,r,i){this.lang=t,this.input=n,this.fragments=r,this.ranges=i,this.stoppedAt=null,this.chunks=[],this.chunkPos=[],this.chunk=[],this.chunkReused=void 0,this.rangeIndex=0,this.to=i[i.length-1].to;let a=bf.get(),o=i[0].from,{state:s,tree:l}=jat(t,r,o,this.to,a?.state);this.state=s,this.parsedPos=this.chunkStart=o+l.length;for(let c=0;c<l.children.length;c++)this.chunks.push(l.children[c]),this.chunkPos.push(l.positions[c]);a&&this.parsedPos<a.viewport.from-1e5&&i.some(c=>c.from<=a.viewport.from&&c.to>=a.viewport.from)&&(this.state=this.lang.streamParser.startState(KS(a.state)),a.skipUntilInView(this.parsedPos,a.viewport.from),this.parsedPos=a.viewport.from),this.moveRangeIndex()}advance(){let t=bf.get(),n=this.stoppedAt==null?this.to:Math.min(this.to,this.stoppedAt),r=Math.min(n,this.chunkStart+2048);for(t&&(r=Math.min(r,t.viewport.to));this.parsedPos<r;)this.parseLine(t);return this.chunkStart<this.parsedPos&&this.finishChunk(),this.parsedPos>=n?this.finish():t&&this.parsedPos>=t.viewport.to?(t.skipUntilInView(this.parsedPos,n),this.finish()):null}stopAt(t){this.stoppedAt=t}lineAfter(t){let n=this.input.chunk(t);if(this.input.lineChunks)n==`
831
831
  `&&(n="");else{let r=n.indexOf(`
832
- `);r>-1&&(n=n.slice(0,r))}return t+n.length<=this.to?n:n.slice(0,this.to-t)}nextLine(){let t=this.parsedPos,n=this.lineAfter(t),r=t+n.length;for(let i=this.rangeIndex;;){let a=this.ranges[i].to;if(a>=r||(n=n.slice(0,a-(r-n.length)),i++,i==this.ranges.length))break;let o=this.ranges[i].from,s=this.lineAfter(o);n+=s,r=o+s.length}return{line:n,end:r}}skipGapsTo(t,n,r){for(;;){let i=this.ranges[this.rangeIndex].to,a=t+n;if(r>0?i>a:i>=a)break;let o=this.ranges[++this.rangeIndex].from;n+=o-i}return n}moveRangeIndex(){for(;this.ranges[this.rangeIndex].to<this.parsedPos;)this.rangeIndex++}emitToken(t,n,r,i){let a=4;if(this.ranges.length>1){i=this.skipGapsTo(n,i,1),n+=i;let s=this.chunk.length;i=this.skipGapsTo(r,i,-1),r+=i,a+=this.chunk.length-s}let o=this.chunk.length-4;return this.lang.streamParser.mergeTokens&&a==4&&o>=0&&this.chunk[o]==t&&this.chunk[o+2]==n?this.chunk[o+2]=r:this.chunk.push(t,n,r,a),i}parseLine(t){let{line:n,end:r}=this.nextLine(),i=0,{streamParser:a}=this.lang,o=new Fge(n,t?t.state.tabSize:4,t?KS(t.state):2);if(o.eol())a.blankLine(this.state,o.indentUnit);else for(;!o.eol();){let s=Hge(a.token,o,this.state);if(s&&(i=this.emitToken(this.lang.tokenTable.resolve(s),this.parsedPos+o.start,this.parsedPos+o.pos,i)),o.start>1e4)break}this.parsedPos=r,this.moveRangeIndex(),this.parsedPos<this.to&&this.parsedPos++}finishChunk(){let t=hn.build({buffer:this.chunk,start:this.chunkStart,length:this.parsedPos-this.chunkStart,nodeSet:Aat,topID:0,maxBufferLength:2048,reused:this.chunkReused});t=new hn(t.type,t.children,t.positions,t.length,[[this.lang.stateAfter,this.lang.streamParser.copyState(this.state)]]),this.chunks.push(t),this.chunkPos.push(this.chunkStart-this.ranges[0].from),this.chunk=[],this.chunkReused=void 0,this.chunkStart=this.parsedPos}finish(){return new hn(this.lang.topNode,this.chunks,this.chunkPos,this.parsedPos-this.ranges[0].from).balance()}};function Hge(e,t,n){t.start=t.pos;for(let r=0;r<10;r++){let i=e(t,n);if(t.pos>t.start)return i}throw new Error("Stream parser failed to advance stream.")}const p8=Object.create(null),H$=[yi.none],Aat=new Wm(H$),BM=[],HM=Object.create(null),Kge=Object.create(null);for(let[e,t]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"]])Kge[e]=e0e(p8,t);class Jge{constructor(t){this.extra=t,this.table=Object.assign(Object.create(null),Kge)}resolve(t){return t?this.table[t]||(this.table[t]=e0e(this.extra,t)):0}}const zat=new Jge(p8);function AT(e,t){BM.indexOf(e)>-1||(BM.push(e),console.warn(t))}function e0e(e,t){let n=[];for(let s of t.split(" ")){let l=[];for(let c of s.split(".")){let u=e[c]||P[c];u?typeof u=="function"?l.length?l=l.map(u):AT(c,`Modifier ${c} used at start of tag`):l.length?AT(c,`Tag ${c} used as modifier`):l=Array.isArray(u)?u:[u]:AT(c,`Unknown highlighting tag ${c}`)}for(let c of l)n.push(c)}if(!n.length)return 0;let r=t.replace(/ /g,"_"),i=r+" "+n.map(s=>s.id),a=HM[i];if(a)return a.id;let o=HM[i]=yi.define({id:H$.length,name:r,props:[An({[r]:n})]});return H$.push(o),o.id}function Uat(e,t){let n=yi.define({id:H$.length,name:"Document",props:[fO.add(()=>e),Yr.add(()=>r=>t.getIndent(r))],top:!0});return H$.push(n),n}Er.RTL,Er.LTR;function Pe(e){return new wn(Ae.define(e))}function Yu(e){return ve(()=>Promise.resolve().then(()=>lpt),void 0,import.meta.url).then(t=>t.sql({dialect:t[e]}))}const Wat=[$e.of({name:"C",extensions:["c","h","ino"],load(){return ve(()=>Promise.resolve().then(()=>GL),void 0,import.meta.url).then(e=>e.cpp())}}),$e.of({name:"C++",alias:["cpp"],extensions:["cpp","c++","cc","cxx","hpp","h++","hh","hxx"],load(){return ve(()=>Promise.resolve().then(()=>GL),void 0,import.meta.url).then(e=>e.cpp())}}),$e.of({name:"CQL",alias:["cassandra"],extensions:["cql"],load(){return Yu("Cassandra")}}),$e.of({name:"CSS",extensions:["css"],load(){return ve(()=>Promise.resolve().then(()=>Slt),void 0,import.meta.url).then(e=>e.css())}}),$e.of({name:"Go",extensions:["go"],load(){return ve(()=>import("./index-BsV4LVu3.js"),__vite__mapDeps([0,1,2,3,4]),import.meta.url).then(e=>e.go())}}),$e.of({name:"HTML",alias:["xhtml"],extensions:["html","htm","handlebars","hbs"],load(){return ve(()=>Promise.resolve().then(()=>hct),void 0,import.meta.url).then(e=>e.html())}}),$e.of({name:"Java",extensions:["java"],load(){return ve(()=>Promise.resolve().then(()=>dpt),void 0,import.meta.url).then(e=>e.java())}}),$e.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return ve(()=>Promise.resolve().then(()=>sw),void 0,import.meta.url).then(e=>e.javascript())}}),$e.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return ve(()=>Promise.resolve().then(()=>yut),void 0,import.meta.url).then(e=>e.json())}}),$e.of({name:"JSX",extensions:["jsx"],load(){return ve(()=>Promise.resolve().then(()=>sw),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),$e.of({name:"LESS",extensions:["less"],load(){return ve(()=>Promise.resolve().then(()=>Cct),void 0,import.meta.url).then(e=>e.less())}}),$e.of({name:"Liquid",extensions:["liquid"],load(){return ve(()=>Promise.resolve().then(()=>Hgt),void 0,import.meta.url).then(e=>e.liquid())}}),$e.of({name:"MariaDB SQL",load(){return Yu("MariaSQL")}}),$e.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return ve(()=>Promise.resolve().then(()=>xct),void 0,import.meta.url).then(e=>e.markdown())}}),$e.of({name:"MS SQL",load(){return Yu("MSSQL")}}),$e.of({name:"MySQL",load(){return Yu("MySQL")}}),$e.of({name:"PHP",extensions:["php","php3","php4","php5","php7","phtml"],load(){return ve(()=>Promise.resolve().then(()=>_gt),void 0,import.meta.url).then(e=>e.php())}}),$e.of({name:"PLSQL",extensions:["pls"],load(){return Yu("PLSQL")}}),$e.of({name:"PostgreSQL",load(){return Yu("PostgreSQL")}}),$e.of({name:"Python",extensions:["BUILD","bzl","py","pyw"],filename:/^(BUCK|BUILD)$/,load(){return ve(()=>Promise.resolve().then(()=>Hft),void 0,import.meta.url).then(e=>e.python())}}),$e.of({name:"Rust",extensions:["rs"],load(){return ve(()=>Promise.resolve().then(()=>Ept),void 0,import.meta.url).then(e=>e.rust())}}),$e.of({name:"Sass",extensions:["sass"],load(){return ve(()=>Promise.resolve().then(()=>rL),void 0,import.meta.url).then(e=>e.sass({indented:!0}))}}),$e.of({name:"SCSS",extensions:["scss"],load(){return ve(()=>Promise.resolve().then(()=>rL),void 0,import.meta.url).then(e=>e.sass())}}),$e.of({name:"SQL",extensions:["sql"],load(){return Yu("StandardSQL")}}),$e.of({name:"SQLite",load(){return Yu("SQLite")}}),$e.of({name:"TSX",extensions:["tsx"],load(){return ve(()=>Promise.resolve().then(()=>sw),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),$e.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return ve(()=>Promise.resolve().then(()=>sw),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),$e.of({name:"WebAssembly",extensions:["wat","wast"],load(){return ve(()=>Promise.resolve().then(()=>e0t),void 0,import.meta.url).then(e=>e.wast())}}),$e.of({name:"XML",alias:["rss","wsdl","xsd"],extensions:["xml","xsl","xsd","svg"],load(){return ve(()=>Promise.resolve().then(()=>yht),void 0,import.meta.url).then(e=>e.xml())}}),$e.of({name:"YAML",alias:["yml"],extensions:["yaml","yml"],load(){return ve(()=>import("./index-DAoplO_Z.js"),__vite__mapDeps([5,1,2,3,4]),import.meta.url).then(e=>e.yaml())}}),$e.of({name:"APL",extensions:["dyalog","apl"],load(){return ve(()=>Promise.resolve().then(()=>Tyt),void 0,import.meta.url).then(e=>Pe(e.apl))}}),$e.of({name:"PGP",alias:["asciiarmor"],extensions:["asc","pgp","sig"],load(){return ve(()=>Promise.resolve().then(()=>Ryt),void 0,import.meta.url).then(e=>Pe(e.asciiArmor))}}),$e.of({name:"ASN.1",extensions:["asn","asn1"],load(){return ve(()=>import("./asn1-EdZsLKOL.js"),[],import.meta.url).then(e=>Pe(e.asn1({})))}}),$e.of({name:"Asterisk",filename:/^extensions\.conf$/i,load(){return ve(()=>Promise.resolve().then(()=>Cyt),void 0,import.meta.url).then(e=>Pe(e.asterisk))}}),$e.of({name:"Brainfuck",extensions:["b","bf"],load(){return ve(()=>Promise.resolve().then(()=>zyt),void 0,import.meta.url).then(e=>Pe(e.brainfuck))}}),$e.of({name:"Cobol",extensions:["cob","cpy"],load(){return ve(()=>Promise.resolve().then(()=>Ovt),void 0,import.meta.url).then(e=>Pe(e.cobol))}}),$e.of({name:"C#",alias:["csharp","cs"],extensions:["cs"],load(){return ve(()=>Promise.resolve().then(()=>pd),void 0,import.meta.url).then(e=>Pe(e.csharp))}}),$e.of({name:"Clojure",extensions:["clj","cljc","cljx"],load(){return ve(()=>import("./clojure-BMjYHr_A.js"),[],import.meta.url).then(e=>Pe(e.clojure))}}),$e.of({name:"ClojureScript",extensions:["cljs"],load(){return ve(()=>import("./clojure-BMjYHr_A.js"),[],import.meta.url).then(e=>Pe(e.clojure))}}),$e.of({name:"Closure Stylesheets (GSS)",extensions:["gss"],load(){return ve(()=>import("./css-BnMrqG3P.js"),[],import.meta.url).then(e=>Pe(e.gss))}}),$e.of({name:"CMake",extensions:["cmake","cmake.in"],filename:/^CMakeLists\.txt$/,load(){return ve(()=>Promise.resolve().then(()=>nvt),void 0,import.meta.url).then(e=>Pe(e.cmake))}}),$e.of({name:"CoffeeScript",alias:["coffee","coffee-script"],extensions:["coffee"],load(){return ve(()=>Promise.resolve().then(()=>xvt),void 0,import.meta.url).then(e=>Pe(e.coffeeScript))}}),$e.of({name:"Common Lisp",alias:["lisp"],extensions:["cl","lisp","el"],load(){return ve(()=>Promise.resolve().then(()=>Rvt),void 0,import.meta.url).then(e=>Pe(e.commonLisp))}}),$e.of({name:"Cypher",extensions:["cyp","cypher"],load(){return ve(()=>Promise.resolve().then(()=>Lvt),void 0,import.meta.url).then(e=>Pe(e.cypher))}}),$e.of({name:"Cython",extensions:["pyx","pxd","pxi"],load(){return ve(()=>import("./python-BuPzkPfP.js"),[],import.meta.url).then(e=>Pe(e.cython))}}),$e.of({name:"Crystal",extensions:["cr"],load(){return ve(()=>Promise.resolve().then(()=>Gvt),void 0,import.meta.url).then(e=>Pe(e.crystal))}}),$e.of({name:"D",extensions:["d"],load(){return ve(()=>Promise.resolve().then(()=>tbt),void 0,import.meta.url).then(e=>Pe(e.d))}}),$e.of({name:"Dart",extensions:["dart"],load(){return ve(()=>Promise.resolve().then(()=>pd),void 0,import.meta.url).then(e=>Pe(e.dart))}}),$e.of({name:"diff",extensions:["diff","patch"],load(){return ve(()=>Promise.resolve().then(()=>nbt),void 0,import.meta.url).then(e=>Pe(e.diff))}}),$e.of({name:"Dockerfile",filename:/^Dockerfile$/,load(){return ve(()=>Promise.resolve().then(()=>pbt),void 0,import.meta.url).then(e=>Pe(e.dockerFile))}}),$e.of({name:"DTD",extensions:["dtd"],load(){return ve(()=>Promise.resolve().then(()=>$bt),void 0,import.meta.url).then(e=>Pe(e.dtd))}}),$e.of({name:"Dylan",extensions:["dylan","dyl","intr"],load(){return ve(()=>Promise.resolve().then(()=>Sbt),void 0,import.meta.url).then(e=>Pe(e.dylan))}}),$e.of({name:"EBNF",load(){return ve(()=>Promise.resolve().then(()=>xbt),void 0,import.meta.url).then(e=>Pe(e.ebnf))}}),$e.of({name:"ECL",extensions:["ecl"],load(){return ve(()=>Promise.resolve().then(()=>Ebt),void 0,import.meta.url).then(e=>Pe(e.ecl))}}),$e.of({name:"edn",extensions:["edn"],load(){return ve(()=>import("./clojure-BMjYHr_A.js"),[],import.meta.url).then(e=>Pe(e.clojure))}}),$e.of({name:"Eiffel",extensions:["e"],load(){return ve(()=>Promise.resolve().then(()=>Ubt),void 0,import.meta.url).then(e=>Pe(e.eiffel))}}),$e.of({name:"Elm",extensions:["elm"],load(){return ve(()=>Promise.resolve().then(()=>Fbt),void 0,import.meta.url).then(e=>Pe(e.elm))}}),$e.of({name:"Erlang",extensions:["erl"],load(){return ve(()=>Promise.resolve().then(()=>ywt),void 0,import.meta.url).then(e=>Pe(e.erlang))}}),$e.of({name:"Esper",load(){return ve(()=>import("./sql-D0XecflT.js"),[],import.meta.url).then(e=>Pe(e.esper))}}),$e.of({name:"Factor",extensions:["factor"],load(){return ve(()=>Promise.resolve().then(()=>vwt),void 0,import.meta.url).then(e=>Pe(e.factor))}}),$e.of({name:"FCL",load(){return ve(()=>Promise.resolve().then(()=>Qwt),void 0,import.meta.url).then(e=>Pe(e.fcl))}}),$e.of({name:"Forth",extensions:["forth","fth","4th"],load(){return ve(()=>Promise.resolve().then(()=>_wt),void 0,import.meta.url).then(e=>Pe(e.forth))}}),$e.of({name:"Fortran",extensions:["f","for","f77","f90","f95"],load(){return ve(()=>Promise.resolve().then(()=>Cwt),void 0,import.meta.url).then(e=>Pe(e.fortran))}}),$e.of({name:"F#",alias:["fsharp"],extensions:["fs"],load(){return ve(()=>import("./mllike-CXdrOF99.js"),[],import.meta.url).then(e=>Pe(e.fSharp))}}),$e.of({name:"Gas",extensions:["s"],load(){return ve(()=>Promise.resolve().then(()=>zwt),void 0,import.meta.url).then(e=>Pe(e.gas))}}),$e.of({name:"Gherkin",extensions:["feature"],load(){return ve(()=>Promise.resolve().then(()=>Uwt),void 0,import.meta.url).then(e=>Pe(e.gherkin))}}),$e.of({name:"Groovy",extensions:["groovy","gradle"],filename:/^Jenkinsfile$/,load(){return ve(()=>Promise.resolve().then(()=>Fwt),void 0,import.meta.url).then(e=>Pe(e.groovy))}}),$e.of({name:"Haskell",extensions:["hs"],load(){return ve(()=>Promise.resolve().then(()=>n1t),void 0,import.meta.url).then(e=>Pe(e.haskell))}}),$e.of({name:"Haxe",extensions:["hx"],load(){return ve(()=>Promise.resolve().then(()=>OB),void 0,import.meta.url).then(e=>Pe(e.haxe))}}),$e.of({name:"HXML",extensions:["hxml"],load(){return ve(()=>Promise.resolve().then(()=>OB),void 0,import.meta.url).then(e=>Pe(e.hxml))}}),$e.of({name:"HTTP",load(){return ve(()=>Promise.resolve().then(()=>Q1t),void 0,import.meta.url).then(e=>Pe(e.http))}}),$e.of({name:"IDL",extensions:["pro"],load(){return ve(()=>Promise.resolve().then(()=>E1t),void 0,import.meta.url).then(e=>Pe(e.idl))}}),$e.of({name:"JSON-LD",alias:["jsonld"],extensions:["jsonld"],load(){return ve(()=>import("./javascript-qCveANmP.js"),[],import.meta.url).then(e=>Pe(e.jsonld))}}),$e.of({name:"Jinja2",extensions:["j2","jinja","jinja2"],load(){return ve(()=>Promise.resolve().then(()=>A1t),void 0,import.meta.url).then(e=>Pe(e.jinja2))}}),$e.of({name:"Julia",extensions:["jl"],load(){return ve(()=>Promise.resolve().then(()=>sSt),void 0,import.meta.url).then(e=>Pe(e.julia))}}),$e.of({name:"Kotlin",extensions:["kt","kts"],load(){return ve(()=>Promise.resolve().then(()=>pd),void 0,import.meta.url).then(e=>Pe(e.kotlin))}}),$e.of({name:"LiveScript",alias:["ls"],extensions:["ls"],load(){return ve(()=>Promise.resolve().then(()=>OSt),void 0,import.meta.url).then(e=>Pe(e.liveScript))}}),$e.of({name:"Lua",extensions:["lua"],load(){return ve(()=>Promise.resolve().then(()=>ySt),void 0,import.meta.url).then(e=>Pe(e.lua))}}),$e.of({name:"mIRC",extensions:["mrc"],load(){return ve(()=>Promise.resolve().then(()=>GSt),void 0,import.meta.url).then(e=>Pe(e.mirc))}}),$e.of({name:"Mathematica",extensions:["m","nb","wl","wls"],load(){return ve(()=>Promise.resolve().then(()=>PSt),void 0,import.meta.url).then(e=>Pe(e.mathematica))}}),$e.of({name:"Modelica",extensions:["mo"],load(){return ve(()=>Promise.resolve().then(()=>KSt),void 0,import.meta.url).then(e=>Pe(e.modelica))}}),$e.of({name:"MUMPS",extensions:["mps"],load(){return ve(()=>Promise.resolve().then(()=>hxt),void 0,import.meta.url).then(e=>Pe(e.mumps))}}),$e.of({name:"Mbox",extensions:["mbox"],load(){return ve(()=>Promise.resolve().then(()=>WSt),void 0,import.meta.url).then(e=>Pe(e.mbox))}}),$e.of({name:"Nginx",filename:/nginx.*\.conf$/i,load(){return ve(()=>Promise.resolve().then(()=>yxt),void 0,import.meta.url).then(e=>Pe(e.nginx))}}),$e.of({name:"NSIS",extensions:["nsh","nsi"],load(){return ve(()=>Promise.resolve().then(()=>vxt),void 0,import.meta.url).then(e=>Pe(e.nsis))}}),$e.of({name:"NTriples",extensions:["nt","nq"],load(){return ve(()=>Promise.resolve().then(()=>bxt),void 0,import.meta.url).then(e=>Pe(e.ntriples))}}),$e.of({name:"Objective-C",alias:["objective-c","objc"],extensions:["m"],load(){return ve(()=>Promise.resolve().then(()=>pd),void 0,import.meta.url).then(e=>Pe(e.objectiveC))}}),$e.of({name:"Objective-C++",alias:["objective-c++","objc++"],extensions:["mm"],load(){return ve(()=>Promise.resolve().then(()=>pd),void 0,import.meta.url).then(e=>Pe(e.objectiveCpp))}}),$e.of({name:"OCaml",extensions:["ml","mli","mll","mly"],load(){return ve(()=>import("./mllike-CXdrOF99.js"),[],import.meta.url).then(e=>Pe(e.oCaml))}}),$e.of({name:"Octave",extensions:["m"],load(){return ve(()=>Promise.resolve().then(()=>Ext),void 0,import.meta.url).then(e=>Pe(e.octave))}}),$e.of({name:"Oz",extensions:["oz"],load(){return ve(()=>Promise.resolve().then(()=>Zxt),void 0,import.meta.url).then(e=>Pe(e.oz))}}),$e.of({name:"Pascal",extensions:["p","pas"],load(){return ve(()=>Promise.resolve().then(()=>Bxt),void 0,import.meta.url).then(e=>Pe(e.pascal))}}),$e.of({name:"Perl",extensions:["pl","pm"],load(){return ve(()=>Promise.resolve().then(()=>Hxt),void 0,import.meta.url).then(e=>Pe(e.perl))}}),$e.of({name:"Pig",extensions:["pig"],load(){return ve(()=>Promise.resolve().then(()=>eQt),void 0,import.meta.url).then(e=>Pe(e.pig))}}),$e.of({name:"PowerShell",extensions:["ps1","psd1","psm1"],load(){return ve(()=>Promise.resolve().then(()=>mQt),void 0,import.meta.url).then(e=>Pe(e.powerShell))}}),$e.of({name:"Properties files",alias:["ini","properties"],extensions:["properties","ini","in"],load(){return ve(()=>Promise.resolve().then(()=>gQt),void 0,import.meta.url).then(e=>Pe(e.properties))}}),$e.of({name:"ProtoBuf",extensions:["proto"],load(){return ve(()=>Promise.resolve().then(()=>wQt),void 0,import.meta.url).then(e=>Pe(e.protobuf))}}),$e.of({name:"Pug",alias:["jade"],extensions:["pug","jade"],load(){return ve(()=>import("./pug-DukmZTjD.js"),__vite__mapDeps([6,7]),import.meta.url).then(e=>Pe(e.pug))}}),$e.of({name:"Puppet",extensions:["pp"],load(){return ve(()=>Promise.resolve().then(()=>QQt),void 0,import.meta.url).then(e=>Pe(e.puppet))}}),$e.of({name:"Q",extensions:["q"],load(){return ve(()=>Promise.resolve().then(()=>qQt),void 0,import.meta.url).then(e=>Pe(e.q))}}),$e.of({name:"R",alias:["rscript"],extensions:["r","R"],load(){return ve(()=>Promise.resolve().then(()=>NQt),void 0,import.meta.url).then(e=>Pe(e.r))}}),$e.of({name:"RPM Changes",load(){return ve(()=>import("./rpm-CTu-6PCP.js"),[],import.meta.url).then(e=>Pe(e.rpmChanges))}}),$e.of({name:"RPM Spec",extensions:["spec"],load(){return ve(()=>import("./rpm-CTu-6PCP.js"),[],import.meta.url).then(e=>Pe(e.rpmSpec))}}),$e.of({name:"Ruby",alias:["jruby","macruby","rake","rb","rbx"],extensions:["rb"],filename:/^(Gemfile|Rakefile)$/,load(){return ve(()=>Promise.resolve().then(()=>FQt),void 0,import.meta.url).then(e=>Pe(e.ruby))}}),$e.of({name:"SAS",extensions:["sas"],load(){return ve(()=>Promise.resolve().then(()=>JQt),void 0,import.meta.url).then(e=>Pe(e.sas))}}),$e.of({name:"Scala",extensions:["scala"],load(){return ve(()=>Promise.resolve().then(()=>pd),void 0,import.meta.url).then(e=>Pe(e.scala))}}),$e.of({name:"Scheme",extensions:["scm","ss"],load(){return ve(()=>Promise.resolve().then(()=>dkt),void 0,import.meta.url).then(e=>Pe(e.scheme))}}),$e.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return ve(()=>Promise.resolve().then(()=>mkt),void 0,import.meta.url).then(e=>Pe(e.shell))}}),$e.of({name:"Sieve",extensions:["siv","sieve"],load(){return ve(()=>Promise.resolve().then(()=>bkt),void 0,import.meta.url).then(e=>Pe(e.sieve))}}),$e.of({name:"Smalltalk",extensions:["st"],load(){return ve(()=>Promise.resolve().then(()=>xkt),void 0,import.meta.url).then(e=>Pe(e.smalltalk))}}),$e.of({name:"Solr",load(){return ve(()=>Promise.resolve().then(()=>Xkt),void 0,import.meta.url).then(e=>Pe(e.solr))}}),$e.of({name:"SML",extensions:["sml","sig","fun","smackspec"],load(){return ve(()=>import("./mllike-CXdrOF99.js"),[],import.meta.url).then(e=>Pe(e.sml))}}),$e.of({name:"SPARQL",alias:["sparul"],extensions:["rq","sparql"],load(){return ve(()=>Promise.resolve().then(()=>Ukt),void 0,import.meta.url).then(e=>Pe(e.sparql))}}),$e.of({name:"Spreadsheet",alias:["excel","formula"],load(){return ve(()=>Promise.resolve().then(()=>Wkt),void 0,import.meta.url).then(e=>Pe(e.spreadsheet))}}),$e.of({name:"Squirrel",extensions:["nut"],load(){return ve(()=>Promise.resolve().then(()=>pd),void 0,import.meta.url).then(e=>Pe(e.squirrel))}}),$e.of({name:"Stylus",extensions:["styl"],load(){return ve(()=>Promise.resolve().then(()=>sPt),void 0,import.meta.url).then(e=>Pe(e.stylus))}}),$e.of({name:"Swift",extensions:["swift"],load(){return ve(()=>Promise.resolve().then(()=>PPt),void 0,import.meta.url).then(e=>Pe(e.swift))}}),$e.of({name:"sTeX",load(){return ve(()=>Promise.resolve().then(()=>nH),void 0,import.meta.url).then(e=>Pe(e.stex))}}),$e.of({name:"LaTeX",alias:["tex"],extensions:["text","ltx","tex"],load(){return ve(()=>Promise.resolve().then(()=>nH),void 0,import.meta.url).then(e=>Pe(e.stex))}}),$e.of({name:"SystemVerilog",extensions:["v","sv","svh"],load(){return ve(()=>Promise.resolve().then(()=>wH),void 0,import.meta.url).then(e=>Pe(e.verilog))}}),$e.of({name:"Tcl",extensions:["tcl"],load(){return ve(()=>Promise.resolve().then(()=>XPt),void 0,import.meta.url).then(e=>Pe(e.tcl))}}),$e.of({name:"Textile",extensions:["textile"],load(){return ve(()=>Promise.resolve().then(()=>CPt),void 0,import.meta.url).then(e=>Pe(e.textile))}}),$e.of({name:"TiddlyWiki",load(){return ve(()=>Promise.resolve().then(()=>n_t),void 0,import.meta.url).then(e=>Pe(e.tiddlyWiki))}}),$e.of({name:"Tiki wiki",load(){return ve(()=>Promise.resolve().then(()=>c_t),void 0,import.meta.url).then(e=>Pe(e.tiki))}}),$e.of({name:"TOML",extensions:["toml"],load(){return ve(()=>Promise.resolve().then(()=>u_t),void 0,import.meta.url).then(e=>Pe(e.toml))}}),$e.of({name:"Troff",extensions:["1","2","3","4","5","6","7","8","9"],load(){return ve(()=>Promise.resolve().then(()=>f_t),void 0,import.meta.url).then(e=>Pe(e.troff))}}),$e.of({name:"TTCN",extensions:["ttcn","ttcn3","ttcnpp"],load(){return ve(()=>Promise.resolve().then(()=>X_t),void 0,import.meta.url).then(e=>Pe(e.ttcn))}}),$e.of({name:"TTCN_CFG",extensions:["cfg"],load(){return ve(()=>import("./ttcn-cfg-B9xdYoR4.js"),[],import.meta.url).then(e=>Pe(e.ttcnCfg))}}),$e.of({name:"Turtle",extensions:["ttl"],load(){return ve(()=>Promise.resolve().then(()=>j_t),void 0,import.meta.url).then(e=>Pe(e.turtle))}}),$e.of({name:"Web IDL",extensions:["webidl"],load(){return ve(()=>Promise.resolve().then(()=>P5t),void 0,import.meta.url).then(e=>Pe(e.webIDL))}}),$e.of({name:"VB.NET",extensions:["vb"],load(){return ve(()=>Promise.resolve().then(()=>F_t),void 0,import.meta.url).then(e=>Pe(e.vb))}}),$e.of({name:"VBScript",extensions:["vbs"],load(){return ve(()=>Promise.resolve().then(()=>H_t),void 0,import.meta.url).then(e=>Pe(e.vbScript))}}),$e.of({name:"Velocity",extensions:["vtl"],load(){return ve(()=>Promise.resolve().then(()=>e5t),void 0,import.meta.url).then(e=>Pe(e.velocity))}}),$e.of({name:"Verilog",extensions:["v"],load(){return ve(()=>Promise.resolve().then(()=>wH),void 0,import.meta.url).then(e=>Pe(e.verilog))}}),$e.of({name:"VHDL",extensions:["vhd","vhdl"],load(){return ve(()=>Promise.resolve().then(()=>c5t),void 0,import.meta.url).then(e=>Pe(e.vhdl))}}),$e.of({name:"XQuery",extensions:["xy","xquery"],load(){return ve(()=>Promise.resolve().then(()=>z5t),void 0,import.meta.url).then(e=>Pe(e.xQuery))}}),$e.of({name:"Yacas",extensions:["ys"],load(){return ve(()=>Promise.resolve().then(()=>V5t),void 0,import.meta.url).then(e=>Pe(e.yacas))}}),$e.of({name:"Z80",extensions:["z80"],load(){return ve(()=>Promise.resolve().then(()=>K5t),void 0,import.meta.url).then(e=>Pe(e.z80))}}),$e.of({name:"MscGen",extensions:["mscgen","mscin","msc"],load(){return ve(()=>Promise.resolve().then(()=>G2),void 0,import.meta.url).then(e=>Pe(e.mscgen))}}),$e.of({name:"Xù",extensions:["xu"],load(){return ve(()=>Promise.resolve().then(()=>G2),void 0,import.meta.url).then(e=>Pe(e.xu))}}),$e.of({name:"MsGenny",extensions:["msgenny"],load(){return ve(()=>Promise.resolve().then(()=>G2),void 0,import.meta.url).then(e=>Pe(e.msgenny))}}),$e.of({name:"Vue",extensions:["vue"],load(){return ve(()=>Promise.resolve().then(()=>l0t),void 0,import.meta.url).then(e=>e.vue())}}),$e.of({name:"Angular Template",load(){return ve(()=>Promise.resolve().then(()=>P0t),void 0,import.meta.url).then(e=>e.angular())}})];class m8{constructor(t,n,r,i){this.state=t,this.pos=n,this.explicit=r,this.view=i,this.abortListeners=[],this.abortOnDocChange=!1}tokenBefore(t){let n=Bn(this.state).resolveInner(this.pos,-1);for(;n&&t.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(t){let n=this.state.doc.lineAt(this.pos),r=Math.max(n.from,this.pos-250),i=n.text.slice(r-n.from,this.pos-n.from),a=i.search(t0e(t,!1));return a<0?null:{from:r+a,to:this.pos,text:i.slice(a)}}get aborted(){return this.abortListeners==null}addEventListener(t,n,r){t=="abort"&&this.abortListeners&&(this.abortListeners.push(n),r&&r.onDocChange&&(this.abortOnDocChange=!0))}}function KM(e){let t=Object.keys(e).join(""),n=/\w/.test(t);return n&&(t=t.replace(/\w/g,"")),`[${n?"\\w":""}${t.replace(/[^\w\s]/g,"\\$&")}]`}function Nat(e){let t=Object.create(null),n=Object.create(null);for(let{label:i}of e){t[i[0]]=!0;for(let a=1;a<i.length;a++)n[i[a]]=!0}let r=KM(t)+KM(n)+"*$";return[new RegExp("^"+r),new RegExp(r)]}function Ev(e){let t=e.map(i=>typeof i=="string"?{label:i}:i),[n,r]=t.every(i=>/^\w+$/.test(i.label))?[/\w*$/,/\w+$/]:Nat(t);return i=>{let a=i.matchBefore(r);return a||i.explicit?{from:a?a.from:i.pos,options:t,validFor:n}:null}}function Mk(e,t){return n=>{for(let r=Bn(n.state).resolveInner(n.pos,-1);r;r=r.parent){if(e.indexOf(r.name)>-1)return null;if(r.type.isTop)break}return t(n)}}class JM{constructor(t,n,r,i){this.completion=t,this.source=n,this.match=r,this.score=i}}function ef(e){return e.selection.main.from}function t0e(e,t){var n;let{source:r}=e,i=t&&r[0]!="^",a=r[r.length-1]!="$";return!i&&!a?e:new RegExp(`${i?"^":""}(?:${r})${a?"$":""}`,(n=e.flags)!==null&&n!==void 0?n:e.ignoreCase?"i":"")}const g8=Zf.define();function Yat(e,t,n,r){let{main:i}=e.selection,a=n-i.from,o=r-i.from;return Object.assign(Object.assign({},e.changeByRange(s=>{if(s!=i&&n!=r&&e.sliceDoc(s.from+a,s.from+o)!=e.sliceDoc(n,r))return{range:s};let l=e.toText(t);return{changes:{from:s.from+a,to:r==i.from?s.to:s.from+o,insert:l},range:Ge.cursor(s.from+a+l.length)}})),{scrollIntoView:!0,userEvent:"input.complete"})}const eV=new WeakMap;function Gat(e){if(!Array.isArray(e))return e;let t=eV.get(e);return t||eV.set(e,t=Ev(e)),t}const tx=_n.define(),K$=_n.define();class Iat{constructor(t){this.pattern=t,this.chars=[],this.folded=[],this.any=[],this.precise=[],this.byWord=[],this.score=0,this.matched=[];for(let n=0;n<t.length;){let r=Ro(t,n),i=Yc(r);this.chars.push(r);let a=t.slice(n,n+i),o=a.toUpperCase();this.folded.push(Ro(o==a?a.toLowerCase():o,0)),n+=i}this.astral=t.length!=this.chars.length}ret(t,n){return this.score=t,this.matched=n,this}match(t){if(this.pattern.length==0)return this.ret(-100,[]);if(t.length<this.pattern.length)return null;let{chars:n,folded:r,any:i,precise:a,byWord:o}=this;if(n.length==1){let v=Ro(t,0),S=Yc(v),Q=S==t.length?0:-100;if(v!=n[0])if(v==r[0])Q+=-200;else return null;return this.ret(Q,[0,S])}let s=t.indexOf(this.pattern);if(s==0)return this.ret(t.length==this.pattern.length?0:-100,[0,this.pattern.length]);let l=n.length,c=0;if(s<0){for(let v=0,S=Math.min(t.length,200);v<S&&c<l;){let Q=Ro(t,v);(Q==n[c]||Q==r[c])&&(i[c++]=v),v+=Yc(Q)}if(c<l)return null}let u=0,O=0,d=!1,f=0,p=-1,m=-1,g=/[a-z]/.test(t),y=!0;for(let v=0,S=Math.min(t.length,200),Q=0;v<S&&O<l;){let b=Ro(t,v);s<0&&(u<l&&b==n[u]&&(a[u++]=v),f<l&&(b==n[f]||b==r[f]?(f==0&&(p=v),m=v+1,f++):f=0));let w,x=b<255?b>=48&&b<=57||b>=97&&b<=122?2:b>=65&&b<=90?1:0:(w=dme(b))!=w.toLowerCase()?1:w!=w.toUpperCase()?2:0;(!v||x==1&&g||Q==0&&x!=0)&&(n[O]==b||r[O]==b&&(d=!0)?o[O++]=v:o.length&&(y=!1)),Q=x,v+=Yc(b)}return O==l&&o[0]==0&&y?this.result(-100+(d?-200:0),o,t):f==l&&p==0?this.ret(-200-t.length+(m==t.length?0:-100),[0,m]):s>-1?this.ret(-700-t.length,[s,s+this.pattern.length]):f==l?this.ret(-900-t.length,[p,m]):O==l?this.result(-100+(d?-200:0)+-700+(y?0:-1100),o,t):n.length==2?null:this.result((i[0]?-700:0)+-200+-1100,i,t)}result(t,n,r){let i=[],a=0;for(let o of n){let s=o+(this.astral?Yc(Ro(r,o)):1);a&&i[a-1]==o?i[a-1]=s:(i[a++]=o,i[a++]=s)}return this.ret(t-r.length,i)}}class Zat{constructor(t){this.pattern=t,this.matched=[],this.score=0,this.folded=t.toLowerCase()}match(t){if(t.length<this.pattern.length)return null;let n=t.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+(t.length==this.pattern.length?0:-100),this)}}const Ni=ht.define({combine(e){return Nm(e,{activateOnTyping:!0,activateOnCompletion:()=>!1,activateOnTypingDelay:100,selectOnOpen:!0,override:null,closeOnBlur:!0,maxRenderedOptions:100,defaultKeymap:!0,tooltipClass:()=>"",optionClass:()=>"",aboveCursor:!1,icons:!0,addToOptions:[],positionInfo:Dat,filterStrict:!1,compareCompletions:(t,n)=>t.label.localeCompare(n.label),interactionDelay:75,updateSyncTime:100},{defaultKeymap:(t,n)=>t&&n,closeOnBlur:(t,n)=>t&&n,icons:(t,n)=>t&&n,tooltipClass:(t,n)=>r=>tV(t(r),n(r)),optionClass:(t,n)=>r=>tV(t(r),n(r)),addToOptions:(t,n)=>t.concat(n),filterStrict:(t,n)=>t||n})}});function tV(e,t){return e?t?e+" "+t:e:t}function Dat(e,t,n,r,i,a){let o=e.textDirection==Er.RTL,s=o,l=!1,c="top",u,O,d=t.left-i.left,f=i.right-t.right,p=r.right-r.left,m=r.bottom-r.top;if(s&&d<Math.min(p,f)?s=!1:!s&&f<Math.min(p,d)&&(s=!0),p<=(s?d:f))u=Math.max(i.top,Math.min(n.top,i.bottom-m))-t.top,O=Math.min(400,s?d:f);else{l=!0,O=Math.min(400,(o?t.right:i.right-t.left)-30);let v=i.bottom-t.bottom;v>=m||v>t.top?u=n.bottom-t.top:(c="bottom",u=t.bottom-n.top)}let g=(t.bottom-t.top)/a.offsetHeight,y=(t.right-t.left)/a.offsetWidth;return{style:`${c}: ${u/g}px; max-width: ${O/y}px`,class:"cm-completionInfo-"+(l?o?"left-narrow":"right-narrow":s?"left":"right")}}function Mat(e){let t=e.addToOptions.slice();return e.icons&&t.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(i=>"cm-completionIcon-"+i)),r.setAttribute("aria-hidden","true"),r},position:20}),t.push({render(n,r,i,a){let o=document.createElement("span");o.className="cm-completionLabel";let s=n.displayLabel||n.label,l=0;for(let c=0;c<a.length;){let u=a[c++],O=a[c++];u>l&&o.appendChild(document.createTextNode(s.slice(l,u)));let d=o.appendChild(document.createElement("span"));d.appendChild(document.createTextNode(s.slice(u,O))),d.className="cm-completionMatchedText",l=O}return l<s.length&&o.appendChild(document.createTextNode(s.slice(l))),o},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}),t.sort((n,r)=>n.position-r.position).map(n=>n.render)}function zT(e,t,n){if(e<=n)return{from:0,to:e};if(t<0&&(t=0),t<=e>>1){let i=Math.floor(t/n);return{from:i*n,to:(i+1)*n}}let r=Math.floor((e-t)/n);return{from:e-(r+1)*n,to:e-r*n}}class Vat{constructor(t,n,r){this.view=t,this.stateField=n,this.applyCompletion=r,this.info=null,this.infoDestroy=null,this.placeInfoReq={read:()=>this.measureInfo(),write:l=>this.placeInfo(l),key:this},this.space=null,this.currentClass="";let i=t.state.field(n),{options:a,selected:o}=i.open,s=t.state.facet(Ni);this.optionContent=Mat(s),this.optionClass=s.optionClass,this.tooltipClass=s.tooltipClass,this.range=zT(a.length,o,s.maxRenderedOptions),this.dom=document.createElement("div"),this.dom.className="cm-tooltip-autocomplete",this.updateTooltipClass(t.state),this.dom.addEventListener("mousedown",l=>{let{options:c}=t.state.field(n).open;for(let u=l.target,O;u&&u!=this.dom;u=u.parentNode)if(u.nodeName=="LI"&&(O=/-(\d+)$/.exec(u.id))&&+O[1]<c.length){this.applyCompletion(t,c[+O[1]]),l.preventDefault();return}}),this.dom.addEventListener("focusout",l=>{let c=t.state.field(this.stateField,!1);c&&c.tooltip&&t.state.facet(Ni).closeOnBlur&&l.relatedTarget!=t.contentDOM&&t.dispatch({effects:K$.of(null)})}),this.showOptions(a,i.id)}mount(){this.updateSel()}showOptions(t,n){this.list&&this.list.remove(),this.list=this.dom.appendChild(this.createListBox(t,n,this.range)),this.list.addEventListener("scroll",()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)})}update(t){var n;let r=t.state.field(this.stateField),i=t.startState.field(this.stateField);if(this.updateTooltipClass(t.state),r!=i){let{options:a,selected:o,disabled:s}=r.open;(!i.open||i.open.options!=a)&&(this.range=zT(a.length,o,t.state.facet(Ni).maxRenderedOptions),this.showOptions(a,r.id)),this.updateSel(),s!=((n=i.open)===null||n===void 0?void 0:n.disabled)&&this.dom.classList.toggle("cm-tooltip-autocomplete-disabled",!!s)}}updateTooltipClass(t){let n=this.tooltipClass(t);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(t){this.space=t,this.info&&this.view.requestMeasure(this.placeInfoReq)}updateSel(){let t=this.view.state.field(this.stateField),n=t.open;if((n.selected>-1&&n.selected<this.range.from||n.selected>=this.range.to)&&(this.range=zT(n.options.length,n.selected,this.view.state.facet(Ni).maxRenderedOptions),this.showOptions(n.options,t.id)),this.updateSelectedOption(n.selected)){this.destroyInfo();let{completion:r}=n.options[n.selected],{info:i}=r;if(!i)return;let a=typeof i=="string"?document.createTextNode(i):i(r);if(!a)return;"then"in a?a.then(o=>{o&&this.view.state.field(this.stateField,!1)==t&&this.addInfoPane(o,r)}).catch(o=>no(this.view.state,o,"completion info")):this.addInfoPane(a,r)}}addInfoPane(t,n){this.destroyInfo();let r=this.info=document.createElement("div");if(r.className="cm-tooltip cm-completionInfo",t.nodeType!=null)r.appendChild(t),this.infoDestroy=null;else{let{dom:i,destroy:a}=t;r.appendChild(i),this.infoDestroy=a||null}this.dom.appendChild(r),this.view.requestMeasure(this.placeInfoReq)}updateSelectedOption(t){let n=null;for(let r=this.list.firstChild,i=this.range.from;r;r=r.nextSibling,i++)r.nodeName!="LI"||!r.id?i--:i==t?r.hasAttribute("aria-selected")||(r.setAttribute("aria-selected","true"),n=r):r.hasAttribute("aria-selected")&&r.removeAttribute("aria-selected");return n&&Fat(this.list,n),n}measureInfo(){let t=this.dom.querySelector("[aria-selected]");if(!t||!this.info)return null;let n=this.dom.getBoundingClientRect(),r=this.info.getBoundingClientRect(),i=t.getBoundingClientRect(),a=this.space;if(!a){let o=this.dom.ownerDocument.documentElement;a={left:0,top:0,right:o.clientWidth,bottom:o.clientHeight}}return i.top>Math.min(a.bottom,n.bottom)-10||i.bottom<Math.max(a.top,n.top)+10?null:this.view.state.facet(Ni).positionInfo(this.view,n,i,r,a,this.dom)}placeInfo(t){this.info&&(t?(t.style&&(this.info.style.cssText=t.style),this.info.className="cm-tooltip cm-completionInfo "+(t.class||"")):this.info.style.cssText="top: -1e6px")}createListBox(t,n,r){const i=document.createElement("ul");i.id=n,i.setAttribute("role","listbox"),i.setAttribute("aria-expanded","true"),i.setAttribute("aria-label",this.view.state.phrase("Completions")),i.addEventListener("mousedown",o=>{o.target==i&&o.preventDefault()});let a=null;for(let o=r.from;o<r.to;o++){let{completion:s,match:l}=t[o],{section:c}=s;if(c){let d=typeof c=="string"?c:c.name;if(d!=a&&(o>r.from||r.from==0))if(a=d,typeof c!="string"&&c.header)i.appendChild(c.header(c));else{let f=i.appendChild(document.createElement("completion-section"));f.textContent=d}}const u=i.appendChild(document.createElement("li"));u.id=n+"-"+o,u.setAttribute("role","option");let O=this.optionClass(s);O&&(u.className=O);for(let d of this.optionContent){let f=d(s,this.view.state,this.view,l);f&&u.appendChild(f)}}return r.from&&i.classList.add("cm-completionListIncompleteTop"),r.to<t.length&&i.classList.add("cm-completionListIncompleteBottom"),i}destroyInfo(){this.info&&(this.infoDestroy&&this.infoDestroy(),this.info.remove(),this.info=null)}destroy(){this.destroyInfo()}}function Lat(e,t){return n=>new Vat(n,e,t)}function Fat(e,t){let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i=n.height/e.offsetHeight;r.top<n.top?e.scrollTop-=(n.top-r.top)/i:r.bottom>n.bottom&&(e.scrollTop+=(r.bottom-n.bottom)/i)}function nV(e){return(e.boost||0)*100+(e.apply?10:0)+(e.info?5:0)+(e.type?1:0)}function Bat(e,t){let n=[],r=null,i=c=>{n.push(c);let{section:u}=c.completion;if(u){r||(r=[]);let O=typeof u=="string"?u:u.name;r.some(d=>d.name==O)||r.push(typeof u=="string"?{name:O}:u)}},a=t.facet(Ni);for(let c of e)if(c.hasResult()){let u=c.result.getMatch;if(c.result.filter===!1)for(let O of c.result.options)i(new JM(O,c.source,u?u(O):[],1e9-n.length));else{let O=t.sliceDoc(c.from,c.to),d,f=a.filterStrict?new Zat(O):new Iat(O);for(let p of c.result.options)if(d=f.match(p.label)){let m=p.displayLabel?u?u(p,d.matched):[]:d.matched;i(new JM(p,c.source,m,d.score+(p.boost||0)))}}}if(r){let c=Object.create(null),u=0,O=(d,f)=>{var p,m;return((p=d.rank)!==null&&p!==void 0?p:1e9)-((m=f.rank)!==null&&m!==void 0?m:1e9)||(d.name<f.name?-1:1)};for(let d of r.sort(O))u-=1e5,c[d.name]=u;for(let d of n){let{section:f}=d.completion;f&&(d.score+=c[typeof f=="string"?f:f.name])}}let o=[],s=null,l=a.compareCompletions;for(let c of n.sort((u,O)=>O.score-u.score||l(u.completion,O.completion))){let u=c.completion;!s||s.label!=u.label||s.detail!=u.detail||s.type!=null&&u.type!=null&&s.type!=u.type||s.apply!=u.apply||s.boost!=u.boost?o.push(c):nV(c.completion)>nV(s)&&(o[o.length-1]=c),s=c.completion}return o}class Bh{constructor(t,n,r,i,a,o){this.options=t,this.attrs=n,this.tooltip=r,this.timestamp=i,this.selected=a,this.disabled=o}setSelected(t,n){return t==this.selected||t>=this.options.length?this:new Bh(this.options,rV(n,t),this.tooltip,this.timestamp,t,this.disabled)}static build(t,n,r,i,a,o){if(i&&!o&&t.some(c=>c.isPending))return i.setDisabled();let s=Bat(t,n);if(!s.length)return i&&t.some(c=>c.isPending)?i.setDisabled():null;let l=n.facet(Ni).selectOnOpen?0:-1;if(i&&i.selected!=l&&i.selected!=-1){let c=i.options[i.selected].completion;for(let u=0;u<s.length;u++)if(s[u].completion==c){l=u;break}}return new Bh(s,rV(r,l),{pos:t.reduce((c,u)=>u.hasResult()?Math.min(c,u.from):c,1e8),create:not,above:a.aboveCursor},i?i.timestamp:Date.now(),l,!1)}map(t){return new Bh(this.options,this.attrs,Object.assign(Object.assign({},this.tooltip),{pos:t.mapPos(this.tooltip.pos)}),this.timestamp,this.selected,this.disabled)}setDisabled(){return new Bh(this.options,this.attrs,this.tooltip,this.timestamp,this.selected,!0)}}class nx{constructor(t,n,r){this.active=t,this.id=n,this.open=r}static start(){return new nx(eot,"cm-ac-"+Math.floor(Math.random()*2e6).toString(36),null)}update(t){let{state:n}=t,r=n.facet(Ni),a=(r.override||n.languageDataAt("autocomplete",ef(n)).map(Gat)).map(l=>(this.active.find(u=>u.source==l)||new gs(l,this.active.some(u=>u.state!=0)?1:0)).update(t,r));a.length==this.active.length&&a.every((l,c)=>l==this.active[c])&&(a=this.active);let o=this.open,s=t.effects.some(l=>l.is($8));o&&t.docChanged&&(o=o.map(t.changes)),t.selection||a.some(l=>l.hasResult()&&t.changes.touchesRange(l.from,l.to))||!Hat(a,this.active)||s?o=Bh.build(a,n,this.id,o,r,s):o&&o.disabled&&!a.some(l=>l.isPending)&&(o=null),!o&&a.every(l=>!l.isPending)&&a.some(l=>l.hasResult())&&(a=a.map(l=>l.hasResult()?new gs(l.source,0):l));for(let l of t.effects)l.is(r0e)&&(o=o&&o.setSelected(l.value,this.id));return a==this.active&&o==this.open?this:new nx(a,this.id,o)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:this.active.length?Kat:Jat}}function Hat(e,t){if(e==t)return!0;for(let n=0,r=0;;){for(;n<e.length&&!e[n].hasResult();)n++;for(;r<t.length&&!t[r].hasResult();)r++;let i=n==e.length,a=r==t.length;if(i||a)return i==a;if(e[n++].result!=t[r++].result)return!1}}const Kat={"aria-autocomplete":"list"},Jat={};function rV(e,t){let n={"aria-autocomplete":"list","aria-haspopup":"listbox","aria-controls":e};return t>-1&&(n["aria-activedescendant"]=e+"-"+t),n}const eot=[];function n0e(e,t){if(e.isUserEvent("input.complete")){let r=e.annotation(g8);if(r&&t.activateOnCompletion(r))return 12}let n=e.isUserEvent("input.type");return n&&t.activateOnTyping?5:n?1:e.isUserEvent("delete.backward")?2:e.selection?8:e.docChanged?16:0}class gs{constructor(t,n,r=!1){this.source=t,this.state=n,this.explicit=r}hasResult(){return!1}get isPending(){return this.state==1}update(t,n){let r=n0e(t,n),i=this;(r&8||r&16&&this.touches(t))&&(i=new gs(i.source,0)),r&4&&i.state==0&&(i=new gs(this.source,1)),i=i.updateFor(t,r);for(let a of t.effects)if(a.is(tx))i=new gs(i.source,1,a.value);else if(a.is(K$))i=new gs(i.source,0);else if(a.is($8))for(let o of a.value)o.source==i.source&&(i=o);return i}updateFor(t,n){return this.map(t.changes)}map(t){return this}touches(t){return t.changes.touchesRange(ef(t.state))}}class hp extends gs{constructor(t,n,r,i,a,o){super(t,3,n),this.limit=r,this.result=i,this.from=a,this.to=o}hasResult(){return!0}updateFor(t,n){var r;if(!(n&3))return this.map(t.changes);let i=this.result;i.map&&!t.changes.empty&&(i=i.map(i,t.changes));let a=t.changes.mapPos(this.from),o=t.changes.mapPos(this.to,1),s=ef(t.state);if(s>o||!i||n&2&&(ef(t.startState)==this.from||s<this.limit))return new gs(this.source,n&4?1:0);let l=t.changes.mapPos(this.limit);return tot(i.validFor,t.state,a,o)?new hp(this.source,this.explicit,l,i,a,o):i.update&&(i=i.update(i,a,o,new m8(t.state,s,!1)))?new hp(this.source,this.explicit,l,i,i.from,(r=i.to)!==null&&r!==void 0?r:ef(t.state)):new gs(this.source,1,this.explicit)}map(t){return t.empty?this:(this.result.map?this.result.map(this.result,t):this.result)?new hp(this.source,this.explicit,t.mapPos(this.limit),this.result,t.mapPos(this.from),t.mapPos(this.to,1)):new gs(this.source,0)}touches(t){return t.changes.touchesRange(this.from,this.to)}}function tot(e,t,n,r){if(!e)return!1;let i=t.sliceDoc(n,r);return typeof e=="function"?e(i,n,r,t):t0e(e,!0).test(i)}const $8=_n.define({map(e,t){return e.map(n=>n.map(t))}}),r0e=_n.define(),Ja=co.define({create(){return nx.start()},update(e,t){return e.update(t)},provide:e=>[c8.from(e,t=>t.tooltip),Pt.contentAttributes.from(e,t=>t.attrs)]});function y8(e,t){const n=t.completion.apply||t.completion.label;let r=e.state.field(Ja).active.find(i=>i.source==t.source);return r instanceof hp?(typeof n=="string"?e.dispatch(Object.assign(Object.assign({},Yat(e.state,n,r.from,r.to)),{annotations:g8.of(t.completion)})):n(e,t.completion,r.from,r.to),!0):!1}const not=Lat(Ja,y8);function iw(e,t="option"){return n=>{let r=n.state.field(Ja,!1);if(!r||!r.open||r.open.disabled||Date.now()-r.open.timestamp<n.state.facet(Ni).interactionDelay)return!1;let i=1,a;t=="page"&&(a=Pge(n,r.open.tooltip))&&(i=Math.max(2,Math.floor(a.dom.offsetHeight/a.dom.querySelector("li").offsetHeight)-1));let{length:o}=r.open.options,s=r.open.selected>-1?r.open.selected+i*(e?1:-1):e?0:o-1;return s<0?s=t=="page"?0:o-1:s>=o&&(s=t=="page"?o-1:0),n.dispatch({effects:r0e.of(s)}),!0}}const rot=e=>{let t=e.state.field(Ja,!1);return e.state.readOnly||!t||!t.open||t.open.selected<0||t.open.disabled||Date.now()-t.open.timestamp<e.state.facet(Ni).interactionDelay?!1:y8(e,t.open.options[t.open.selected])},iV=e=>e.state.field(Ja,!1)?(e.dispatch({effects:tx.of(!0)}),!0):!1,iot=e=>{let t=e.state.field(Ja,!1);return!t||!t.active.some(n=>n.state!=0)?!1:(e.dispatch({effects:K$.of(null)}),!0)};class aot{constructor(t,n){this.active=t,this.context=n,this.time=Date.now(),this.updates=[],this.done=void 0}}const oot=50,sot=1e3,lot=Ti.fromClass(class{constructor(e){this.view=e,this.debounceUpdate=-1,this.running=[],this.debounceAccept=-1,this.pendingStart=!1,this.composing=0;for(let t of e.state.field(Ja).active)t.isPending&&this.startQuery(t)}update(e){let t=e.state.field(Ja),n=e.state.facet(Ni);if(!e.selectionSet&&!e.docChanged&&e.startState.field(Ja)==t)return;let r=e.transactions.some(a=>{let o=n0e(a,n);return o&8||(a.selection||a.docChanged)&&!(o&3)});for(let a=0;a<this.running.length;a++){let o=this.running[a];if(r||o.context.abortOnDocChange&&e.docChanged||o.updates.length+e.transactions.length>oot&&Date.now()-o.time>sot){for(let s of o.context.abortListeners)try{s()}catch(l){no(this.view.state,l)}o.context.abortListeners=null,this.running.splice(a--,1)}else o.updates.push(...e.transactions)}this.debounceUpdate>-1&&clearTimeout(this.debounceUpdate),e.transactions.some(a=>a.effects.some(o=>o.is(tx)))&&(this.pendingStart=!0);let i=this.pendingStart?50:n.activateOnTypingDelay;if(this.debounceUpdate=t.active.some(a=>a.isPending&&!this.running.some(o=>o.active.source==a.source))?setTimeout(()=>this.startUpdate(),i):-1,this.composing!=0)for(let a of e.transactions)a.isUserEvent("input.type")?this.composing=2:this.composing==2&&a.selection&&(this.composing=3)}startUpdate(){this.debounceUpdate=-1,this.pendingStart=!1;let{state:e}=this.view,t=e.field(Ja);for(let n of t.active)n.isPending&&!this.running.some(r=>r.active.source==n.source)&&this.startQuery(n);this.running.length&&t.open&&t.open.disabled&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(Ni).updateSyncTime))}startQuery(e){let{state:t}=this.view,n=ef(t),r=new m8(t,n,e.explicit,this.view),i=new aot(e,r);this.running.push(i),Promise.resolve(e.source(r)).then(a=>{i.context.aborted||(i.done=a||null,this.scheduleAccept())},a=>{this.view.dispatch({effects:K$.of(null)}),no(this.view.state,a)})}scheduleAccept(){this.running.every(e=>e.done!==void 0)?this.accept():this.debounceAccept<0&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(Ni).updateSyncTime))}accept(){var e;this.debounceAccept>-1&&clearTimeout(this.debounceAccept),this.debounceAccept=-1;let t=[],n=this.view.state.facet(Ni),r=this.view.state.field(Ja);for(let i=0;i<this.running.length;i++){let a=this.running[i];if(a.done===void 0)continue;if(this.running.splice(i--,1),a.done){let s=ef(a.updates.length?a.updates[0].startState:this.view.state),l=Math.min(s,a.done.from+(a.active.explicit?0:1)),c=new hp(a.active.source,a.active.explicit,l,a.done,a.done.from,(e=a.done.to)!==null&&e!==void 0?e:s);for(let u of a.updates)c=c.update(u,n);if(c.hasResult()){t.push(c);continue}}let o=r.active.find(s=>s.source==a.active.source);if(o&&o.isPending)if(a.done==null){let s=new gs(a.active.source,0);for(let l of a.updates)s=s.update(l,n);s.isPending||t.push(s)}else this.startQuery(o)}(t.length||r.open&&r.open.disabled)&&this.view.dispatch({effects:$8.of(t)})}},{eventHandlers:{blur(e){let t=this.view.state.field(Ja,!1);if(t&&t.tooltip&&this.view.state.facet(Ni).closeOnBlur){let n=t.open&&Pge(this.view,t.open.tooltip);(!n||!n.dom.contains(e.relatedTarget))&&setTimeout(()=>this.view.dispatch({effects:K$.of(null)}),10)}},compositionstart(){this.composing=1},compositionend(){this.composing==3&&setTimeout(()=>this.view.dispatch({effects:tx.of(!1)}),20),this.composing=0}}}),cot=typeof navigator=="object"&&/Win/.test(navigator.platform),uot=ZO.highest(Pt.domEventHandlers({keydown(e,t){let n=t.state.field(Ja,!1);if(!n||!n.open||n.open.disabled||n.open.selected<0||e.key.length>1||e.ctrlKey&&!(cot&&e.altKey)||e.metaKey)return!1;let r=n.open.options[n.open.selected],i=n.active.find(o=>o.source==r.source),a=r.completion.commitCharacters||i.result.commitCharacters;return a&&a.indexOf(e.key)>-1&&y8(t,r),!1}})),i0e=Pt.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 Oot{constructor(t,n,r,i){this.field=t,this.line=n,this.from=r,this.to=i}}class v8{constructor(t,n,r){this.field=t,this.from=n,this.to=r}map(t){let n=t.mapPos(this.from,-1,Hi.TrackDel),r=t.mapPos(this.to,1,Hi.TrackDel);return n==null||r==null?null:new v8(this.field,n,r)}}class b8{constructor(t,n){this.lines=t,this.fieldPositions=n}instantiate(t,n){let r=[],i=[n],a=t.doc.lineAt(n),o=/^\s*/.exec(a.text)[0];for(let l of this.lines){if(r.length){let c=o,u=/^\t*/.exec(l)[0].length;for(let O=0;O<u;O++)c+=t.facet(Ik);i.push(n+c.length-u),l=c+l.slice(u)}r.push(l),n+=l.length+1}let s=this.fieldPositions.map(l=>new v8(l.field,i[l.line]+l.from,i[l.line]+l.to));return{text:r,ranges:s}}static parse(t){let n=[],r=[],i=[],a;for(let o of t.split(/\r\n?|\n/)){for(;a=/[#$]\{(?:(\d+)(?::([^}]*))?|((?:\\[{}]|[^}])*))\}/.exec(o);){let s=a[1]?+a[1]:null,l=a[2]||a[3]||"",c=-1,u=l.replace(/\\[{}]/g,O=>O[1]);for(let O=0;O<n.length;O++)(s!=null?n[O].seq==s:u&&n[O].name==u)&&(c=O);if(c<0){let O=0;for(;O<n.length&&(s==null||n[O].seq!=null&&n[O].seq<s);)O++;n.splice(O,0,{seq:s,name:u}),c=O;for(let d of i)d.field>=c&&d.field++}i.push(new Oot(c,r.length,a.index,a.index+u.length)),o=o.slice(0,a.index)+l+o.slice(a.index+a[0].length)}o=o.replace(/\\([{}])/g,(s,l,c)=>{for(let u of i)u.line==r.length&&u.from>c&&(u.from--,u.to--);return l}),r.push(o)}return new b8(r,i)}}let dot=cn.widget({widget:new class extends Tu{toDOM(){let e=document.createElement("span");return e.className="cm-snippetFieldPosition",e}ignoreEvent(){return!1}}}),fot=cn.mark({class:"cm-snippetField"});class Ym{constructor(t,n){this.ranges=t,this.active=n,this.deco=cn.set(t.map(r=>(r.from==r.to?dot:fot).range(r.from,r.to)))}map(t){let n=[];for(let r of this.ranges){let i=r.map(t);if(!i)return null;n.push(i)}return new Ym(n,this.active)}selectionInsideField(t){return t.ranges.every(n=>this.ranges.some(r=>r.field==this.active&&r.from<=n.from&&r.to>=n.to))}}const qv=_n.define({map(e,t){return e&&e.map(t)}}),hot=_n.define(),J$=co.define({create(){return null},update(e,t){for(let n of t.effects){if(n.is(qv))return n.value;if(n.is(hot)&&e)return new Ym(e.ranges,n.value)}return e&&t.docChanged&&(e=e.map(t.changes)),e&&t.selection&&!e.selectionInsideField(t.selection)&&(e=null),e},provide:e=>Pt.decorations.from(e,t=>t?t.deco:cn.none)});function w8(e,t){return Ge.create(e.filter(n=>n.field==t).map(n=>Ge.range(n.from,n.to)))}function pot(e){let t=b8.parse(e);return(n,r,i,a)=>{let{text:o,ranges:s}=t.instantiate(n.state,i),{main:l}=n.state.selection,c={changes:{from:i,to:a==l.from?l.to:a,insert:Fn.of(o)},scrollIntoView:!0,annotations:r?[g8.of(r),Ki.userEvent.of("input.complete")]:void 0};if(s.length&&(c.selection=w8(s,0)),s.some(u=>u.field>0)){let u=new Ym(s,0),O=c.effects=[qv.of(u)];n.state.field(J$,!1)===void 0&&O.push(_n.appendConfig.of([J$,vot,bot,i0e]))}n.dispatch(n.state.update(c))}}function a0e(e){return({state:t,dispatch:n})=>{let r=t.field(J$,!1);if(!r||e<0&&r.active==0)return!1;let i=r.active+e,a=e>0&&!r.ranges.some(o=>o.field==i+e);return n(t.update({selection:w8(r.ranges,i),effects:qv.of(a?null:new Ym(r.ranges,i)),scrollIntoView:!0})),!0}}const mot=({state:e,dispatch:t})=>e.field(J$,!1)?(t(e.update({effects:qv.of(null)})),!0):!1,got=a0e(1),$ot=a0e(-1),yot=[{key:"Tab",run:got,shift:$ot},{key:"Escape",run:mot}],aV=ht.define({combine(e){return e.length?e[0]:yot}}),vot=ZO.highest(Nk.compute([aV],e=>e.facet(aV)));function Qr(e,t){return Object.assign(Object.assign({},t),{apply:pot(e)})}const bot=Pt.domEventHandlers({mousedown(e,t){let n=t.state.field(J$,!1),r;if(!n||(r=t.posAtCoords({x:e.clientX,y:e.clientY}))==null)return!1;let i=n.ranges.find(a=>a.from<=r&&a.to>=r);return!i||i.field==n.active?!1:(t.dispatch({selection:w8(n.ranges,i.field),effects:qv.of(n.ranges.some(a=>a.field>i.field)?new Ym(n.ranges,i.field):null),scrollIntoView:!0}),!0)}}),ey={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},Wd=_n.define({map(e,t){let n=t.mapPos(e,-1,Hi.TrackAfter);return n??void 0}}),S8=new class extends mf{};S8.startSide=1;S8.endSide=-1;const o0e=co.define({create(){return Pn.empty},update(e,t){if(e=e.map(t.changes),t.selection){let n=t.state.doc.lineAt(t.selection.main.head);e=e.update({filter:r=>r>=n.from&&r<=n.to})}for(let n of t.effects)n.is(Wd)&&(e=e.update({add:[S8.range(n.value,n.value+1)]}));return e}});function COn(){return[Sot,o0e]}const UT="()[]{}<>«»»«[]{}";function s0e(e){for(let t=0;t<UT.length;t+=2)if(UT.charCodeAt(t)==e)return UT.charAt(t+1);return dme(e<128?e:e+1)}function l0e(e,t){return e.languageDataAt("closeBrackets",t)[0]||ey}const wot=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),Sot=Pt.inputHandler.of((e,t,n,r)=>{if((wot?e.composing:e.compositionStarted)||e.state.readOnly)return!1;let i=e.state.selection.main;if(r.length>2||r.length==2&&Yc(Ro(r,0))==1||t!=i.from||n!=i.to)return!1;let a=Qot(e.state,r);return a?(e.dispatch(a),!0):!1}),xot=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let r=l0e(e,e.selection.main.head).brackets||ey.brackets,i=null,a=e.changeByRange(o=>{if(o.empty){let s=kot(e.doc,o.head);for(let l of r)if(l==s&&Vk(e.doc,o.head)==s0e(Ro(l,0)))return{changes:{from:o.head-l.length,to:o.head+l.length},range:Ge.cursor(o.head-l.length)}}return{range:i=o}});return i||t(e.update(a,{scrollIntoView:!0,userEvent:"delete.backward"})),!i},AOn=[{key:"Backspace",run:xot}];function Qot(e,t){let n=l0e(e,e.selection.main.head),r=n.brackets||ey.brackets;for(let i of r){let a=s0e(Ro(i,0));if(t==i)return a==i?Tot(e,i,r.indexOf(i+i+i)>-1,n):Pot(e,i,a,n.before||ey.before);if(t==a&&c0e(e,e.selection.main.from))return _ot(e,i,a)}return null}function c0e(e,t){let n=!1;return e.field(o0e).between(0,e.doc.length,r=>{r==t&&(n=!0)}),n}function Vk(e,t){let n=e.sliceString(t,t+2);return n.slice(0,Yc(Ro(n,0)))}function kot(e,t){let n=e.sliceString(t-2,t);return Yc(Ro(n,0))==n.length?n:n.slice(1)}function Pot(e,t,n,r){let i=null,a=e.changeByRange(o=>{if(!o.empty)return{changes:[{insert:t,from:o.from},{insert:n,from:o.to}],effects:Wd.of(o.to+t.length),range:Ge.range(o.anchor+t.length,o.head+t.length)};let s=Vk(e.doc,o.head);return!s||/\s/.test(s)||r.indexOf(s)>-1?{changes:{insert:t+n,from:o.head},effects:Wd.of(o.head+t.length),range:Ge.cursor(o.head+t.length)}:{range:i=o}});return i?null:e.update(a,{scrollIntoView:!0,userEvent:"input.type"})}function _ot(e,t,n){let r=null,i=e.changeByRange(a=>a.empty&&Vk(e.doc,a.head)==n?{changes:{from:a.head,to:a.head+n.length,insert:n},range:Ge.cursor(a.head+n.length)}:r={range:a});return r?null:e.update(i,{scrollIntoView:!0,userEvent:"input.type"})}function Tot(e,t,n,r){let i=r.stringPrefixes||ey.stringPrefixes,a=null,o=e.changeByRange(s=>{if(!s.empty)return{changes:[{insert:t,from:s.from},{insert:t,from:s.to}],effects:Wd.of(s.to+t.length),range:Ge.range(s.anchor+t.length,s.head+t.length)};let l=s.head,c=Vk(e.doc,l),u;if(c==t){if(oV(e,l))return{changes:{insert:t+t,from:l},effects:Wd.of(l+t.length),range:Ge.cursor(l+t.length)};if(c0e(e,l)){let d=n&&e.sliceDoc(l,l+t.length*3)==t+t+t?t+t+t:t;return{changes:{from:l,to:l+d.length,insert:d},range:Ge.cursor(l+d.length)}}}else{if(n&&e.sliceDoc(l-2*t.length,l)==t+t&&(u=sV(e,l-2*t.length,i))>-1&&oV(e,u))return{changes:{insert:t+t+t+t,from:l},effects:Wd.of(l+t.length),range:Ge.cursor(l+t.length)};if(e.charCategorizer(l)(c)!=ms.Word&&sV(e,l,i)>-1&&!Rot(e,l,t,i))return{changes:{insert:t+t,from:l},effects:Wd.of(l+t.length),range:Ge.cursor(l+t.length)}}return{range:a=s}});return a?null:e.update(o,{scrollIntoView:!0,userEvent:"input.type"})}function oV(e,t){let n=Bn(e).resolveInner(t+1);return n.parent&&n.from==t}function Rot(e,t,n,r){let i=Bn(e).resolveInner(t,-1),a=r.reduce((o,s)=>Math.max(o,s.length),0);for(let o=0;o<5;o++){let s=e.sliceDoc(i.from,Math.min(i.to,i.from+n.length+a)),l=s.indexOf(n);if(!l||l>-1&&r.indexOf(s.slice(0,l))>-1){let u=i.firstChild;for(;u&&u.from==i.from&&u.to-u.from>n.length+l;){if(e.sliceDoc(u.to-n.length,u.to)==n)return!1;u=u.firstChild}return!0}let c=i.to==t&&i.parent;if(!c)break;i=c}return!1}function sV(e,t,n){let r=e.charCategorizer(t);if(r(e.sliceDoc(t-1,t))!=ms.Word)return t;for(let i of n){let a=t-i.length;if(e.sliceDoc(a,t)==i&&r(e.sliceDoc(a-1,a))!=ms.Word)return a}return-1}function zOn(e={}){return[uot,Ja,Ni.of(e),lot,Eot,i0e]}const Xot=[{key:"Ctrl-Space",run:iV},{mac:"Alt-`",run:iV},{key:"Escape",run:iot},{key:"ArrowDown",run:iw(!0)},{key:"ArrowUp",run:iw(!1)},{key:"PageDown",run:iw(!0,"page")},{key:"PageUp",run:iw(!1,"page")},{key:"Enter",run:rot}],Eot=ZO.highest(Nk.computeN([Ni],e=>e.facet(Ni).defaultKeymap?[Xot]:[]));class rx{static create(t,n,r,i,a){let o=i+(i<<8)+t+(n<<4)|0;return new rx(t,n,r,o,a,[],[])}constructor(t,n,r,i,a,o,s){this.type=t,this.value=n,this.from=r,this.hash=i,this.end=a,this.children=o,this.positions=s,this.hashProp=[[Gt.contextHash,i]]}addChild(t,n){t.prop(Gt.contextHash)!=this.hash&&(t=new hn(t.type,t.children,t.positions,t.length,this.hashProp)),this.children.push(t),this.positions.push(n)}toTree(t,n=this.end){let r=this.children.length-1;return r>=0&&(n=Math.max(n,this.positions[r]+this.children[r].length+this.from)),new hn(t.types[this.type],this.children,this.positions,n-this.from).balance({makeTree:(i,a,o)=>new hn(yi.none,i,a,o,this.hashProp)})}}var De;(function(e){e[e.Document=1]="Document",e[e.CodeBlock=2]="CodeBlock",e[e.FencedCode=3]="FencedCode",e[e.Blockquote=4]="Blockquote",e[e.HorizontalRule=5]="HorizontalRule",e[e.BulletList=6]="BulletList",e[e.OrderedList=7]="OrderedList",e[e.ListItem=8]="ListItem",e[e.ATXHeading1=9]="ATXHeading1",e[e.ATXHeading2=10]="ATXHeading2",e[e.ATXHeading3=11]="ATXHeading3",e[e.ATXHeading4=12]="ATXHeading4",e[e.ATXHeading5=13]="ATXHeading5",e[e.ATXHeading6=14]="ATXHeading6",e[e.SetextHeading1=15]="SetextHeading1",e[e.SetextHeading2=16]="SetextHeading2",e[e.HTMLBlock=17]="HTMLBlock",e[e.LinkReference=18]="LinkReference",e[e.Paragraph=19]="Paragraph",e[e.CommentBlock=20]="CommentBlock",e[e.ProcessingInstructionBlock=21]="ProcessingInstructionBlock",e[e.Escape=22]="Escape",e[e.Entity=23]="Entity",e[e.HardBreak=24]="HardBreak",e[e.Emphasis=25]="Emphasis",e[e.StrongEmphasis=26]="StrongEmphasis",e[e.Link=27]="Link",e[e.Image=28]="Image",e[e.InlineCode=29]="InlineCode",e[e.HTMLTag=30]="HTMLTag",e[e.Comment=31]="Comment",e[e.ProcessingInstruction=32]="ProcessingInstruction",e[e.Autolink=33]="Autolink",e[e.HeaderMark=34]="HeaderMark",e[e.QuoteMark=35]="QuoteMark",e[e.ListMark=36]="ListMark",e[e.LinkMark=37]="LinkMark",e[e.EmphasisMark=38]="EmphasisMark",e[e.CodeMark=39]="CodeMark",e[e.CodeText=40]="CodeText",e[e.CodeInfo=41]="CodeInfo",e[e.LinkTitle=42]="LinkTitle",e[e.LinkLabel=43]="LinkLabel",e[e.URL=44]="URL"})(De||(De={}));class qot{constructor(t,n){this.start=t,this.content=n,this.marks=[],this.parsers=[]}}let jot=class{constructor(){this.text="",this.baseIndent=0,this.basePos=0,this.depth=0,this.markers=[],this.pos=0,this.indent=0,this.next=-1}forward(){this.basePos>this.pos&&this.forwardInner()}forwardInner(){let t=this.skipSpace(this.basePos);this.indent=this.countIndent(t,this.pos,this.indent),this.pos=t,this.next=t==this.text.length?-1:this.text.charCodeAt(t)}skipSpace(t){return B0(this.text,t)}reset(t){for(this.text=t,this.baseIndent=this.basePos=this.pos=this.indent=0,this.forwardInner(),this.depth=1;this.markers.length;)this.markers.pop()}moveBase(t){this.basePos=t,this.baseIndent=this.countIndent(t,this.pos,this.indent)}moveBaseColumn(t){this.baseIndent=t,this.basePos=this.findColumn(t)}addMarker(t){this.markers.push(t)}countIndent(t,n=0,r=0){for(let i=n;i<t;i++)r+=this.text.charCodeAt(i)==9?4-r%4:1;return r}findColumn(t){let n=0;for(let r=0;n<this.text.length&&r<t;n++)r+=this.text.charCodeAt(n)==9?4-r%4:1;return n}scrub(){if(!this.baseIndent)return this.text;let t="";for(let n=0;n<this.basePos;n++)t+=" ";return t+this.text.slice(this.basePos)}};function lV(e,t,n){if(n.pos==n.text.length||e!=t.block&&n.indent>=t.stack[n.depth+1].value+n.baseIndent)return!0;if(n.indent>=n.baseIndent+4)return!1;let r=(e.type==De.OrderedList?k8:Q8)(n,t,!1);return r>0&&(e.type!=De.BulletList||x8(n,t,!1)<0)&&n.text.charCodeAt(n.pos+r-1)==e.value}const u0e={[De.Blockquote](e,t,n){return n.next!=62?!1:(n.markers.push(bn(De.QuoteMark,t.lineStart+n.pos,t.lineStart+n.pos+1)),n.moveBase(n.pos+(Ts(n.text.charCodeAt(n.pos+1))?2:1)),e.end=t.lineStart+n.text.length,!0)},[De.ListItem](e,t,n){return n.indent<n.baseIndent+e.value&&n.next>-1?!1:(n.moveBaseColumn(n.baseIndent+e.value),!0)},[De.OrderedList]:lV,[De.BulletList]:lV,[De.Document](){return!0}};function Ts(e){return e==32||e==9||e==10||e==13}function B0(e,t=0){for(;t<e.length&&Ts(e.charCodeAt(t));)t++;return t}function cV(e,t,n){for(;t>n&&Ts(e.charCodeAt(t-1));)t--;return t}function O0e(e){if(e.next!=96&&e.next!=126)return-1;let t=e.pos+1;for(;t<e.text.length&&e.text.charCodeAt(t)==e.next;)t++;if(t<e.pos+3)return-1;if(e.next==96){for(let n=t;n<e.text.length;n++)if(e.text.charCodeAt(n)==96)return-1}return t}function d0e(e){return e.next!=62?-1:e.text.charCodeAt(e.pos+1)==32?2:1}function x8(e,t,n){if(e.next!=42&&e.next!=45&&e.next!=95)return-1;let r=1;for(let i=e.pos+1;i<e.text.length;i++){let a=e.text.charCodeAt(i);if(a==e.next)r++;else if(!Ts(a))return-1}return n&&e.next==45&&p0e(e)>-1&&e.depth==t.stack.length&&t.parser.leafBlockParsers.indexOf(y0e.SetextHeading)>-1||r<3?-1:1}function f0e(e,t){for(let n=e.stack.length-1;n>=0;n--)if(e.stack[n].type==t)return!0;return!1}function Q8(e,t,n){return(e.next==45||e.next==43||e.next==42)&&(e.pos==e.text.length-1||Ts(e.text.charCodeAt(e.pos+1)))&&(!n||f0e(t,De.BulletList)||e.skipSpace(e.pos+2)<e.text.length)?1:-1}function k8(e,t,n){let r=e.pos,i=e.next;for(;i>=48&&i<=57;){r++;if(r==e.text.length)return-1;i=e.text.charCodeAt(r)}return r==e.pos||r>e.pos+9||i!=46&&i!=41||r<e.text.length-1&&!Ts(e.text.charCodeAt(r+1))||n&&!f0e(t,De.OrderedList)&&(e.skipSpace(r+1)==e.text.length||r>e.pos+1||e.next!=49)?-1:r+1-e.pos}function h0e(e){if(e.next!=35)return-1;let t=e.pos+1;for(;t<e.text.length&&e.text.charCodeAt(t)==35;)t++;if(t<e.text.length&&e.text.charCodeAt(t)!=32)return-1;let n=t-e.pos;return n>6?-1:n}function p0e(e){if(e.next!=45&&e.next!=61||e.indent>=e.baseIndent+4)return-1;let t=e.pos+1;for(;t<e.text.length&&e.text.charCodeAt(t)==e.next;)t++;let n=t;for(;t<e.text.length&&Ts(e.text.charCodeAt(t));)t++;return t==e.text.length?n:-1}const rC=/^[ \t]*$/,m0e=/-->/,g0e=/\?>/,iC=[[/^<(?:script|pre|style)(?:\s|>|$)/i,/<\/(?:script|pre|style)>/i],[/^\s*<!--/,m0e],[/^\s*<\?/,g0e],[/^\s*<![A-Z]/,/>/],[/^\s*<!\[CDATA\[/,/\]\]>/],[/^\s*<\/?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h1|h2|h3|h4|h5|h6|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?:\s|\/?>|$)/i,rC],[/^\s*(?:<\/[a-z][\w-]*\s*>|<[a-z][\w-]*(\s+[a-z:_][\w-.]*(?:\s*=\s*(?:[^\s"'=<>`]+|'[^']*'|"[^"]*"))?)*\s*>)\s*$/i,rC]];function $0e(e,t,n){if(e.next!=60)return-1;let r=e.text.slice(e.pos);for(let i=0,a=iC.length-(n?1:0);i<a;i++)if(iC[i][0].test(r))return i;return-1}function uV(e,t){let n=e.countIndent(t,e.pos,e.indent),r=e.countIndent(e.skipSpace(t),t,n);return r>=n+5?n+1:r}function dd(e,t,n){let r=e.length-1;r>=0&&e[r].to==t&&e[r].type==De.CodeText?e[r].to=n:e.push(bn(De.CodeText,t,n))}const aw={LinkReference:void 0,IndentedCode(e,t){let n=t.baseIndent+4;if(t.indent<n)return!1;let r=t.findColumn(n),i=e.lineStart+r,a=e.lineStart+t.text.length,o=[],s=[];for(dd(o,i,a);e.nextLine()&&t.depth>=e.stack.length;)if(t.pos==t.text.length){dd(s,e.lineStart-1,e.lineStart);for(let l of t.markers)s.push(l)}else{if(t.indent<n)break;{if(s.length){for(let c of s)c.type==De.CodeText?dd(o,c.from,c.to):o.push(c);s=[]}dd(o,e.lineStart-1,e.lineStart);for(let c of t.markers)o.push(c);a=e.lineStart+t.text.length;let l=e.lineStart+t.findColumn(t.baseIndent+4);l<a&&dd(o,l,a)}}return s.length&&(s=s.filter(l=>l.type!=De.CodeText),s.length&&(t.markers=s.concat(t.markers))),e.addNode(e.buffer.writeElements(o,-i).finish(De.CodeBlock,a-i),i),!0},FencedCode(e,t){let n=O0e(t);if(n<0)return!1;let r=e.lineStart+t.pos,i=t.next,a=n-t.pos,o=t.skipSpace(n),s=cV(t.text,t.text.length,o),l=[bn(De.CodeMark,r,r+a)];o<s&&l.push(bn(De.CodeInfo,e.lineStart+o,e.lineStart+s));for(let c=!0;e.nextLine()&&t.depth>=e.stack.length;c=!1){let u=t.pos;if(t.indent-t.baseIndent<4)for(;u<t.text.length&&t.text.charCodeAt(u)==i;)u++;if(u-t.pos>=a&&t.skipSpace(u)==t.text.length){for(let O of t.markers)l.push(O);l.push(bn(De.CodeMark,e.lineStart+t.pos,e.lineStart+u)),e.nextLine();break}else{c||dd(l,e.lineStart-1,e.lineStart);for(let f of t.markers)l.push(f);let O=e.lineStart+t.basePos,d=e.lineStart+t.text.length;O<d&&dd(l,O,d)}}return e.addNode(e.buffer.writeElements(l,-r).finish(De.FencedCode,e.prevLineEnd()-r),r),!0},Blockquote(e,t){let n=d0e(t);return n<0?!1:(e.startContext(De.Blockquote,t.pos),e.addNode(De.QuoteMark,e.lineStart+t.pos,e.lineStart+t.pos+1),t.moveBase(t.pos+n),null)},HorizontalRule(e,t){if(x8(t,e,!1)<0)return!1;let n=e.lineStart+t.pos;return e.nextLine(),e.addNode(De.HorizontalRule,n),!0},BulletList(e,t){let n=Q8(t,e,!1);if(n<0)return!1;e.block.type!=De.BulletList&&e.startContext(De.BulletList,t.basePos,t.next);let r=uV(t,t.pos+1);return e.startContext(De.ListItem,t.basePos,r-t.baseIndent),e.addNode(De.ListMark,e.lineStart+t.pos,e.lineStart+t.pos+n),t.moveBaseColumn(r),null},OrderedList(e,t){let n=k8(t,e,!1);if(n<0)return!1;e.block.type!=De.OrderedList&&e.startContext(De.OrderedList,t.basePos,t.text.charCodeAt(t.pos+n-1));let r=uV(t,t.pos+n);return e.startContext(De.ListItem,t.basePos,r-t.baseIndent),e.addNode(De.ListMark,e.lineStart+t.pos,e.lineStart+t.pos+n),t.moveBaseColumn(r),null},ATXHeading(e,t){let n=h0e(t);if(n<0)return!1;let r=t.pos,i=e.lineStart+r,a=cV(t.text,t.text.length,r),o=a;for(;o>r&&t.text.charCodeAt(o-1)==t.next;)o--;(o==a||o==r||!Ts(t.text.charCodeAt(o-1)))&&(o=t.text.length);let s=e.buffer.write(De.HeaderMark,0,n).writeElements(e.parser.parseInline(t.text.slice(r+n+1,o),i+n+1),-i);o<t.text.length&&s.write(De.HeaderMark,o-r,a-r);let l=s.finish(De.ATXHeading1-1+n,t.text.length-r);return e.nextLine(),e.addNode(l,i),!0},HTMLBlock(e,t){let n=$0e(t,e,!1);if(n<0)return!1;let r=e.lineStart+t.pos,i=iC[n][1],a=[],o=i!=rC;for(;!i.test(t.text)&&e.nextLine();){if(t.depth<e.stack.length){o=!1;break}for(let c of t.markers)a.push(c)}o&&e.nextLine();let s=i==m0e?De.CommentBlock:i==g0e?De.ProcessingInstructionBlock:De.HTMLBlock,l=e.prevLineEnd();return e.addNode(e.buffer.writeElements(a,-r).finish(s,l-r),r),!0},SetextHeading:void 0};class Cot{constructor(t){this.stage=0,this.elts=[],this.pos=0,this.start=t.start,this.advance(t.content)}nextLine(t,n,r){if(this.stage==-1)return!1;let i=r.content+`
832
+ `);r>-1&&(n=n.slice(0,r))}return t+n.length<=this.to?n:n.slice(0,this.to-t)}nextLine(){let t=this.parsedPos,n=this.lineAfter(t),r=t+n.length;for(let i=this.rangeIndex;;){let a=this.ranges[i].to;if(a>=r||(n=n.slice(0,a-(r-n.length)),i++,i==this.ranges.length))break;let o=this.ranges[i].from,s=this.lineAfter(o);n+=s,r=o+s.length}return{line:n,end:r}}skipGapsTo(t,n,r){for(;;){let i=this.ranges[this.rangeIndex].to,a=t+n;if(r>0?i>a:i>=a)break;let o=this.ranges[++this.rangeIndex].from;n+=o-i}return n}moveRangeIndex(){for(;this.ranges[this.rangeIndex].to<this.parsedPos;)this.rangeIndex++}emitToken(t,n,r,i){let a=4;if(this.ranges.length>1){i=this.skipGapsTo(n,i,1),n+=i;let s=this.chunk.length;i=this.skipGapsTo(r,i,-1),r+=i,a+=this.chunk.length-s}let o=this.chunk.length-4;return this.lang.streamParser.mergeTokens&&a==4&&o>=0&&this.chunk[o]==t&&this.chunk[o+2]==n?this.chunk[o+2]=r:this.chunk.push(t,n,r,a),i}parseLine(t){let{line:n,end:r}=this.nextLine(),i=0,{streamParser:a}=this.lang,o=new Fge(n,t?t.state.tabSize:4,t?KS(t.state):2);if(o.eol())a.blankLine(this.state,o.indentUnit);else for(;!o.eol();){let s=Hge(a.token,o,this.state);if(s&&(i=this.emitToken(this.lang.tokenTable.resolve(s),this.parsedPos+o.start,this.parsedPos+o.pos,i)),o.start>1e4)break}this.parsedPos=r,this.moveRangeIndex(),this.parsedPos<this.to&&this.parsedPos++}finishChunk(){let t=hn.build({buffer:this.chunk,start:this.chunkStart,length:this.parsedPos-this.chunkStart,nodeSet:Aat,topID:0,maxBufferLength:2048,reused:this.chunkReused});t=new hn(t.type,t.children,t.positions,t.length,[[this.lang.stateAfter,this.lang.streamParser.copyState(this.state)]]),this.chunks.push(t),this.chunkPos.push(this.chunkStart-this.ranges[0].from),this.chunk=[],this.chunkReused=void 0,this.chunkStart=this.parsedPos}finish(){return new hn(this.lang.topNode,this.chunks,this.chunkPos,this.parsedPos-this.ranges[0].from).balance()}};function Hge(e,t,n){t.start=t.pos;for(let r=0;r<10;r++){let i=e(t,n);if(t.pos>t.start)return i}throw new Error("Stream parser failed to advance stream.")}const p8=Object.create(null),H$=[yi.none],Aat=new Wm(H$),BM=[],HM=Object.create(null),Kge=Object.create(null);for(let[e,t]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"]])Kge[e]=e0e(p8,t);class Jge{constructor(t){this.extra=t,this.table=Object.assign(Object.create(null),Kge)}resolve(t){return t?this.table[t]||(this.table[t]=e0e(this.extra,t)):0}}const zat=new Jge(p8);function AT(e,t){BM.indexOf(e)>-1||(BM.push(e),console.warn(t))}function e0e(e,t){let n=[];for(let s of t.split(" ")){let l=[];for(let c of s.split(".")){let u=e[c]||P[c];u?typeof u=="function"?l.length?l=l.map(u):AT(c,`Modifier ${c} used at start of tag`):l.length?AT(c,`Tag ${c} used as modifier`):l=Array.isArray(u)?u:[u]:AT(c,`Unknown highlighting tag ${c}`)}for(let c of l)n.push(c)}if(!n.length)return 0;let r=t.replace(/ /g,"_"),i=r+" "+n.map(s=>s.id),a=HM[i];if(a)return a.id;let o=HM[i]=yi.define({id:H$.length,name:r,props:[An({[r]:n})]});return H$.push(o),o.id}function Uat(e,t){let n=yi.define({id:H$.length,name:"Document",props:[fO.add(()=>e),Yr.add(()=>r=>t.getIndent(r))],top:!0});return H$.push(n),n}Er.RTL,Er.LTR;function Pe(e){return new wn(Ae.define(e))}function Yu(e){return ve(()=>Promise.resolve().then(()=>lpt),void 0,import.meta.url).then(t=>t.sql({dialect:t[e]}))}const Wat=[$e.of({name:"C",extensions:["c","h","ino"],load(){return ve(()=>Promise.resolve().then(()=>GL),void 0,import.meta.url).then(e=>e.cpp())}}),$e.of({name:"C++",alias:["cpp"],extensions:["cpp","c++","cc","cxx","hpp","h++","hh","hxx"],load(){return ve(()=>Promise.resolve().then(()=>GL),void 0,import.meta.url).then(e=>e.cpp())}}),$e.of({name:"CQL",alias:["cassandra"],extensions:["cql"],load(){return Yu("Cassandra")}}),$e.of({name:"CSS",extensions:["css"],load(){return ve(()=>Promise.resolve().then(()=>Slt),void 0,import.meta.url).then(e=>e.css())}}),$e.of({name:"Go",extensions:["go"],load(){return ve(()=>import("./index-C6Pn32aB.js"),__vite__mapDeps([0,1,2,3,4]),import.meta.url).then(e=>e.go())}}),$e.of({name:"HTML",alias:["xhtml"],extensions:["html","htm","handlebars","hbs"],load(){return ve(()=>Promise.resolve().then(()=>hct),void 0,import.meta.url).then(e=>e.html())}}),$e.of({name:"Java",extensions:["java"],load(){return ve(()=>Promise.resolve().then(()=>dpt),void 0,import.meta.url).then(e=>e.java())}}),$e.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return ve(()=>Promise.resolve().then(()=>sw),void 0,import.meta.url).then(e=>e.javascript())}}),$e.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return ve(()=>Promise.resolve().then(()=>yut),void 0,import.meta.url).then(e=>e.json())}}),$e.of({name:"JSX",extensions:["jsx"],load(){return ve(()=>Promise.resolve().then(()=>sw),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),$e.of({name:"LESS",extensions:["less"],load(){return ve(()=>Promise.resolve().then(()=>Cct),void 0,import.meta.url).then(e=>e.less())}}),$e.of({name:"Liquid",extensions:["liquid"],load(){return ve(()=>Promise.resolve().then(()=>Hgt),void 0,import.meta.url).then(e=>e.liquid())}}),$e.of({name:"MariaDB SQL",load(){return Yu("MariaSQL")}}),$e.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return ve(()=>Promise.resolve().then(()=>xct),void 0,import.meta.url).then(e=>e.markdown())}}),$e.of({name:"MS SQL",load(){return Yu("MSSQL")}}),$e.of({name:"MySQL",load(){return Yu("MySQL")}}),$e.of({name:"PHP",extensions:["php","php3","php4","php5","php7","phtml"],load(){return ve(()=>Promise.resolve().then(()=>_gt),void 0,import.meta.url).then(e=>e.php())}}),$e.of({name:"PLSQL",extensions:["pls"],load(){return Yu("PLSQL")}}),$e.of({name:"PostgreSQL",load(){return Yu("PostgreSQL")}}),$e.of({name:"Python",extensions:["BUILD","bzl","py","pyw"],filename:/^(BUCK|BUILD)$/,load(){return ve(()=>Promise.resolve().then(()=>Hft),void 0,import.meta.url).then(e=>e.python())}}),$e.of({name:"Rust",extensions:["rs"],load(){return ve(()=>Promise.resolve().then(()=>Ept),void 0,import.meta.url).then(e=>e.rust())}}),$e.of({name:"Sass",extensions:["sass"],load(){return ve(()=>Promise.resolve().then(()=>rL),void 0,import.meta.url).then(e=>e.sass({indented:!0}))}}),$e.of({name:"SCSS",extensions:["scss"],load(){return ve(()=>Promise.resolve().then(()=>rL),void 0,import.meta.url).then(e=>e.sass())}}),$e.of({name:"SQL",extensions:["sql"],load(){return Yu("StandardSQL")}}),$e.of({name:"SQLite",load(){return Yu("SQLite")}}),$e.of({name:"TSX",extensions:["tsx"],load(){return ve(()=>Promise.resolve().then(()=>sw),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),$e.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return ve(()=>Promise.resolve().then(()=>sw),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),$e.of({name:"WebAssembly",extensions:["wat","wast"],load(){return ve(()=>Promise.resolve().then(()=>e0t),void 0,import.meta.url).then(e=>e.wast())}}),$e.of({name:"XML",alias:["rss","wsdl","xsd"],extensions:["xml","xsl","xsd","svg"],load(){return ve(()=>Promise.resolve().then(()=>yht),void 0,import.meta.url).then(e=>e.xml())}}),$e.of({name:"YAML",alias:["yml"],extensions:["yaml","yml"],load(){return ve(()=>import("./index-FVvzpk9i.js"),__vite__mapDeps([5,1,2,3,4]),import.meta.url).then(e=>e.yaml())}}),$e.of({name:"APL",extensions:["dyalog","apl"],load(){return ve(()=>Promise.resolve().then(()=>Tyt),void 0,import.meta.url).then(e=>Pe(e.apl))}}),$e.of({name:"PGP",alias:["asciiarmor"],extensions:["asc","pgp","sig"],load(){return ve(()=>Promise.resolve().then(()=>Ryt),void 0,import.meta.url).then(e=>Pe(e.asciiArmor))}}),$e.of({name:"ASN.1",extensions:["asn","asn1"],load(){return ve(()=>import("./asn1-EdZsLKOL.js"),[],import.meta.url).then(e=>Pe(e.asn1({})))}}),$e.of({name:"Asterisk",filename:/^extensions\.conf$/i,load(){return ve(()=>Promise.resolve().then(()=>Cyt),void 0,import.meta.url).then(e=>Pe(e.asterisk))}}),$e.of({name:"Brainfuck",extensions:["b","bf"],load(){return ve(()=>Promise.resolve().then(()=>zyt),void 0,import.meta.url).then(e=>Pe(e.brainfuck))}}),$e.of({name:"Cobol",extensions:["cob","cpy"],load(){return ve(()=>Promise.resolve().then(()=>Ovt),void 0,import.meta.url).then(e=>Pe(e.cobol))}}),$e.of({name:"C#",alias:["csharp","cs"],extensions:["cs"],load(){return ve(()=>Promise.resolve().then(()=>pd),void 0,import.meta.url).then(e=>Pe(e.csharp))}}),$e.of({name:"Clojure",extensions:["clj","cljc","cljx"],load(){return ve(()=>import("./clojure-BMjYHr_A.js"),[],import.meta.url).then(e=>Pe(e.clojure))}}),$e.of({name:"ClojureScript",extensions:["cljs"],load(){return ve(()=>import("./clojure-BMjYHr_A.js"),[],import.meta.url).then(e=>Pe(e.clojure))}}),$e.of({name:"Closure Stylesheets (GSS)",extensions:["gss"],load(){return ve(()=>import("./css-BnMrqG3P.js"),[],import.meta.url).then(e=>Pe(e.gss))}}),$e.of({name:"CMake",extensions:["cmake","cmake.in"],filename:/^CMakeLists\.txt$/,load(){return ve(()=>Promise.resolve().then(()=>nvt),void 0,import.meta.url).then(e=>Pe(e.cmake))}}),$e.of({name:"CoffeeScript",alias:["coffee","coffee-script"],extensions:["coffee"],load(){return ve(()=>Promise.resolve().then(()=>xvt),void 0,import.meta.url).then(e=>Pe(e.coffeeScript))}}),$e.of({name:"Common Lisp",alias:["lisp"],extensions:["cl","lisp","el"],load(){return ve(()=>Promise.resolve().then(()=>Rvt),void 0,import.meta.url).then(e=>Pe(e.commonLisp))}}),$e.of({name:"Cypher",extensions:["cyp","cypher"],load(){return ve(()=>Promise.resolve().then(()=>Lvt),void 0,import.meta.url).then(e=>Pe(e.cypher))}}),$e.of({name:"Cython",extensions:["pyx","pxd","pxi"],load(){return ve(()=>import("./python-BuPzkPfP.js"),[],import.meta.url).then(e=>Pe(e.cython))}}),$e.of({name:"Crystal",extensions:["cr"],load(){return ve(()=>Promise.resolve().then(()=>Gvt),void 0,import.meta.url).then(e=>Pe(e.crystal))}}),$e.of({name:"D",extensions:["d"],load(){return ve(()=>Promise.resolve().then(()=>tbt),void 0,import.meta.url).then(e=>Pe(e.d))}}),$e.of({name:"Dart",extensions:["dart"],load(){return ve(()=>Promise.resolve().then(()=>pd),void 0,import.meta.url).then(e=>Pe(e.dart))}}),$e.of({name:"diff",extensions:["diff","patch"],load(){return ve(()=>Promise.resolve().then(()=>nbt),void 0,import.meta.url).then(e=>Pe(e.diff))}}),$e.of({name:"Dockerfile",filename:/^Dockerfile$/,load(){return ve(()=>Promise.resolve().then(()=>pbt),void 0,import.meta.url).then(e=>Pe(e.dockerFile))}}),$e.of({name:"DTD",extensions:["dtd"],load(){return ve(()=>Promise.resolve().then(()=>$bt),void 0,import.meta.url).then(e=>Pe(e.dtd))}}),$e.of({name:"Dylan",extensions:["dylan","dyl","intr"],load(){return ve(()=>Promise.resolve().then(()=>Sbt),void 0,import.meta.url).then(e=>Pe(e.dylan))}}),$e.of({name:"EBNF",load(){return ve(()=>Promise.resolve().then(()=>xbt),void 0,import.meta.url).then(e=>Pe(e.ebnf))}}),$e.of({name:"ECL",extensions:["ecl"],load(){return ve(()=>Promise.resolve().then(()=>Ebt),void 0,import.meta.url).then(e=>Pe(e.ecl))}}),$e.of({name:"edn",extensions:["edn"],load(){return ve(()=>import("./clojure-BMjYHr_A.js"),[],import.meta.url).then(e=>Pe(e.clojure))}}),$e.of({name:"Eiffel",extensions:["e"],load(){return ve(()=>Promise.resolve().then(()=>Ubt),void 0,import.meta.url).then(e=>Pe(e.eiffel))}}),$e.of({name:"Elm",extensions:["elm"],load(){return ve(()=>Promise.resolve().then(()=>Fbt),void 0,import.meta.url).then(e=>Pe(e.elm))}}),$e.of({name:"Erlang",extensions:["erl"],load(){return ve(()=>Promise.resolve().then(()=>ywt),void 0,import.meta.url).then(e=>Pe(e.erlang))}}),$e.of({name:"Esper",load(){return ve(()=>import("./sql-D0XecflT.js"),[],import.meta.url).then(e=>Pe(e.esper))}}),$e.of({name:"Factor",extensions:["factor"],load(){return ve(()=>Promise.resolve().then(()=>vwt),void 0,import.meta.url).then(e=>Pe(e.factor))}}),$e.of({name:"FCL",load(){return ve(()=>Promise.resolve().then(()=>Qwt),void 0,import.meta.url).then(e=>Pe(e.fcl))}}),$e.of({name:"Forth",extensions:["forth","fth","4th"],load(){return ve(()=>Promise.resolve().then(()=>_wt),void 0,import.meta.url).then(e=>Pe(e.forth))}}),$e.of({name:"Fortran",extensions:["f","for","f77","f90","f95"],load(){return ve(()=>Promise.resolve().then(()=>Cwt),void 0,import.meta.url).then(e=>Pe(e.fortran))}}),$e.of({name:"F#",alias:["fsharp"],extensions:["fs"],load(){return ve(()=>import("./mllike-CXdrOF99.js"),[],import.meta.url).then(e=>Pe(e.fSharp))}}),$e.of({name:"Gas",extensions:["s"],load(){return ve(()=>Promise.resolve().then(()=>zwt),void 0,import.meta.url).then(e=>Pe(e.gas))}}),$e.of({name:"Gherkin",extensions:["feature"],load(){return ve(()=>Promise.resolve().then(()=>Uwt),void 0,import.meta.url).then(e=>Pe(e.gherkin))}}),$e.of({name:"Groovy",extensions:["groovy","gradle"],filename:/^Jenkinsfile$/,load(){return ve(()=>Promise.resolve().then(()=>Fwt),void 0,import.meta.url).then(e=>Pe(e.groovy))}}),$e.of({name:"Haskell",extensions:["hs"],load(){return ve(()=>Promise.resolve().then(()=>n1t),void 0,import.meta.url).then(e=>Pe(e.haskell))}}),$e.of({name:"Haxe",extensions:["hx"],load(){return ve(()=>Promise.resolve().then(()=>OB),void 0,import.meta.url).then(e=>Pe(e.haxe))}}),$e.of({name:"HXML",extensions:["hxml"],load(){return ve(()=>Promise.resolve().then(()=>OB),void 0,import.meta.url).then(e=>Pe(e.hxml))}}),$e.of({name:"HTTP",load(){return ve(()=>Promise.resolve().then(()=>Q1t),void 0,import.meta.url).then(e=>Pe(e.http))}}),$e.of({name:"IDL",extensions:["pro"],load(){return ve(()=>Promise.resolve().then(()=>E1t),void 0,import.meta.url).then(e=>Pe(e.idl))}}),$e.of({name:"JSON-LD",alias:["jsonld"],extensions:["jsonld"],load(){return ve(()=>import("./javascript-qCveANmP.js"),[],import.meta.url).then(e=>Pe(e.jsonld))}}),$e.of({name:"Jinja2",extensions:["j2","jinja","jinja2"],load(){return ve(()=>Promise.resolve().then(()=>A1t),void 0,import.meta.url).then(e=>Pe(e.jinja2))}}),$e.of({name:"Julia",extensions:["jl"],load(){return ve(()=>Promise.resolve().then(()=>sSt),void 0,import.meta.url).then(e=>Pe(e.julia))}}),$e.of({name:"Kotlin",extensions:["kt","kts"],load(){return ve(()=>Promise.resolve().then(()=>pd),void 0,import.meta.url).then(e=>Pe(e.kotlin))}}),$e.of({name:"LiveScript",alias:["ls"],extensions:["ls"],load(){return ve(()=>Promise.resolve().then(()=>OSt),void 0,import.meta.url).then(e=>Pe(e.liveScript))}}),$e.of({name:"Lua",extensions:["lua"],load(){return ve(()=>Promise.resolve().then(()=>ySt),void 0,import.meta.url).then(e=>Pe(e.lua))}}),$e.of({name:"mIRC",extensions:["mrc"],load(){return ve(()=>Promise.resolve().then(()=>GSt),void 0,import.meta.url).then(e=>Pe(e.mirc))}}),$e.of({name:"Mathematica",extensions:["m","nb","wl","wls"],load(){return ve(()=>Promise.resolve().then(()=>PSt),void 0,import.meta.url).then(e=>Pe(e.mathematica))}}),$e.of({name:"Modelica",extensions:["mo"],load(){return ve(()=>Promise.resolve().then(()=>KSt),void 0,import.meta.url).then(e=>Pe(e.modelica))}}),$e.of({name:"MUMPS",extensions:["mps"],load(){return ve(()=>Promise.resolve().then(()=>hxt),void 0,import.meta.url).then(e=>Pe(e.mumps))}}),$e.of({name:"Mbox",extensions:["mbox"],load(){return ve(()=>Promise.resolve().then(()=>WSt),void 0,import.meta.url).then(e=>Pe(e.mbox))}}),$e.of({name:"Nginx",filename:/nginx.*\.conf$/i,load(){return ve(()=>Promise.resolve().then(()=>yxt),void 0,import.meta.url).then(e=>Pe(e.nginx))}}),$e.of({name:"NSIS",extensions:["nsh","nsi"],load(){return ve(()=>Promise.resolve().then(()=>vxt),void 0,import.meta.url).then(e=>Pe(e.nsis))}}),$e.of({name:"NTriples",extensions:["nt","nq"],load(){return ve(()=>Promise.resolve().then(()=>bxt),void 0,import.meta.url).then(e=>Pe(e.ntriples))}}),$e.of({name:"Objective-C",alias:["objective-c","objc"],extensions:["m"],load(){return ve(()=>Promise.resolve().then(()=>pd),void 0,import.meta.url).then(e=>Pe(e.objectiveC))}}),$e.of({name:"Objective-C++",alias:["objective-c++","objc++"],extensions:["mm"],load(){return ve(()=>Promise.resolve().then(()=>pd),void 0,import.meta.url).then(e=>Pe(e.objectiveCpp))}}),$e.of({name:"OCaml",extensions:["ml","mli","mll","mly"],load(){return ve(()=>import("./mllike-CXdrOF99.js"),[],import.meta.url).then(e=>Pe(e.oCaml))}}),$e.of({name:"Octave",extensions:["m"],load(){return ve(()=>Promise.resolve().then(()=>Ext),void 0,import.meta.url).then(e=>Pe(e.octave))}}),$e.of({name:"Oz",extensions:["oz"],load(){return ve(()=>Promise.resolve().then(()=>Zxt),void 0,import.meta.url).then(e=>Pe(e.oz))}}),$e.of({name:"Pascal",extensions:["p","pas"],load(){return ve(()=>Promise.resolve().then(()=>Bxt),void 0,import.meta.url).then(e=>Pe(e.pascal))}}),$e.of({name:"Perl",extensions:["pl","pm"],load(){return ve(()=>Promise.resolve().then(()=>Hxt),void 0,import.meta.url).then(e=>Pe(e.perl))}}),$e.of({name:"Pig",extensions:["pig"],load(){return ve(()=>Promise.resolve().then(()=>eQt),void 0,import.meta.url).then(e=>Pe(e.pig))}}),$e.of({name:"PowerShell",extensions:["ps1","psd1","psm1"],load(){return ve(()=>Promise.resolve().then(()=>mQt),void 0,import.meta.url).then(e=>Pe(e.powerShell))}}),$e.of({name:"Properties files",alias:["ini","properties"],extensions:["properties","ini","in"],load(){return ve(()=>Promise.resolve().then(()=>gQt),void 0,import.meta.url).then(e=>Pe(e.properties))}}),$e.of({name:"ProtoBuf",extensions:["proto"],load(){return ve(()=>Promise.resolve().then(()=>wQt),void 0,import.meta.url).then(e=>Pe(e.protobuf))}}),$e.of({name:"Pug",alias:["jade"],extensions:["pug","jade"],load(){return ve(()=>import("./pug-DukmZTjD.js"),__vite__mapDeps([6,7]),import.meta.url).then(e=>Pe(e.pug))}}),$e.of({name:"Puppet",extensions:["pp"],load(){return ve(()=>Promise.resolve().then(()=>QQt),void 0,import.meta.url).then(e=>Pe(e.puppet))}}),$e.of({name:"Q",extensions:["q"],load(){return ve(()=>Promise.resolve().then(()=>qQt),void 0,import.meta.url).then(e=>Pe(e.q))}}),$e.of({name:"R",alias:["rscript"],extensions:["r","R"],load(){return ve(()=>Promise.resolve().then(()=>NQt),void 0,import.meta.url).then(e=>Pe(e.r))}}),$e.of({name:"RPM Changes",load(){return ve(()=>import("./rpm-CTu-6PCP.js"),[],import.meta.url).then(e=>Pe(e.rpmChanges))}}),$e.of({name:"RPM Spec",extensions:["spec"],load(){return ve(()=>import("./rpm-CTu-6PCP.js"),[],import.meta.url).then(e=>Pe(e.rpmSpec))}}),$e.of({name:"Ruby",alias:["jruby","macruby","rake","rb","rbx"],extensions:["rb"],filename:/^(Gemfile|Rakefile)$/,load(){return ve(()=>Promise.resolve().then(()=>FQt),void 0,import.meta.url).then(e=>Pe(e.ruby))}}),$e.of({name:"SAS",extensions:["sas"],load(){return ve(()=>Promise.resolve().then(()=>JQt),void 0,import.meta.url).then(e=>Pe(e.sas))}}),$e.of({name:"Scala",extensions:["scala"],load(){return ve(()=>Promise.resolve().then(()=>pd),void 0,import.meta.url).then(e=>Pe(e.scala))}}),$e.of({name:"Scheme",extensions:["scm","ss"],load(){return ve(()=>Promise.resolve().then(()=>dkt),void 0,import.meta.url).then(e=>Pe(e.scheme))}}),$e.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return ve(()=>Promise.resolve().then(()=>mkt),void 0,import.meta.url).then(e=>Pe(e.shell))}}),$e.of({name:"Sieve",extensions:["siv","sieve"],load(){return ve(()=>Promise.resolve().then(()=>bkt),void 0,import.meta.url).then(e=>Pe(e.sieve))}}),$e.of({name:"Smalltalk",extensions:["st"],load(){return ve(()=>Promise.resolve().then(()=>xkt),void 0,import.meta.url).then(e=>Pe(e.smalltalk))}}),$e.of({name:"Solr",load(){return ve(()=>Promise.resolve().then(()=>Xkt),void 0,import.meta.url).then(e=>Pe(e.solr))}}),$e.of({name:"SML",extensions:["sml","sig","fun","smackspec"],load(){return ve(()=>import("./mllike-CXdrOF99.js"),[],import.meta.url).then(e=>Pe(e.sml))}}),$e.of({name:"SPARQL",alias:["sparul"],extensions:["rq","sparql"],load(){return ve(()=>Promise.resolve().then(()=>Ukt),void 0,import.meta.url).then(e=>Pe(e.sparql))}}),$e.of({name:"Spreadsheet",alias:["excel","formula"],load(){return ve(()=>Promise.resolve().then(()=>Wkt),void 0,import.meta.url).then(e=>Pe(e.spreadsheet))}}),$e.of({name:"Squirrel",extensions:["nut"],load(){return ve(()=>Promise.resolve().then(()=>pd),void 0,import.meta.url).then(e=>Pe(e.squirrel))}}),$e.of({name:"Stylus",extensions:["styl"],load(){return ve(()=>Promise.resolve().then(()=>sPt),void 0,import.meta.url).then(e=>Pe(e.stylus))}}),$e.of({name:"Swift",extensions:["swift"],load(){return ve(()=>Promise.resolve().then(()=>PPt),void 0,import.meta.url).then(e=>Pe(e.swift))}}),$e.of({name:"sTeX",load(){return ve(()=>Promise.resolve().then(()=>nH),void 0,import.meta.url).then(e=>Pe(e.stex))}}),$e.of({name:"LaTeX",alias:["tex"],extensions:["text","ltx","tex"],load(){return ve(()=>Promise.resolve().then(()=>nH),void 0,import.meta.url).then(e=>Pe(e.stex))}}),$e.of({name:"SystemVerilog",extensions:["v","sv","svh"],load(){return ve(()=>Promise.resolve().then(()=>wH),void 0,import.meta.url).then(e=>Pe(e.verilog))}}),$e.of({name:"Tcl",extensions:["tcl"],load(){return ve(()=>Promise.resolve().then(()=>XPt),void 0,import.meta.url).then(e=>Pe(e.tcl))}}),$e.of({name:"Textile",extensions:["textile"],load(){return ve(()=>Promise.resolve().then(()=>CPt),void 0,import.meta.url).then(e=>Pe(e.textile))}}),$e.of({name:"TiddlyWiki",load(){return ve(()=>Promise.resolve().then(()=>n_t),void 0,import.meta.url).then(e=>Pe(e.tiddlyWiki))}}),$e.of({name:"Tiki wiki",load(){return ve(()=>Promise.resolve().then(()=>c_t),void 0,import.meta.url).then(e=>Pe(e.tiki))}}),$e.of({name:"TOML",extensions:["toml"],load(){return ve(()=>Promise.resolve().then(()=>u_t),void 0,import.meta.url).then(e=>Pe(e.toml))}}),$e.of({name:"Troff",extensions:["1","2","3","4","5","6","7","8","9"],load(){return ve(()=>Promise.resolve().then(()=>f_t),void 0,import.meta.url).then(e=>Pe(e.troff))}}),$e.of({name:"TTCN",extensions:["ttcn","ttcn3","ttcnpp"],load(){return ve(()=>Promise.resolve().then(()=>X_t),void 0,import.meta.url).then(e=>Pe(e.ttcn))}}),$e.of({name:"TTCN_CFG",extensions:["cfg"],load(){return ve(()=>import("./ttcn-cfg-B9xdYoR4.js"),[],import.meta.url).then(e=>Pe(e.ttcnCfg))}}),$e.of({name:"Turtle",extensions:["ttl"],load(){return ve(()=>Promise.resolve().then(()=>j_t),void 0,import.meta.url).then(e=>Pe(e.turtle))}}),$e.of({name:"Web IDL",extensions:["webidl"],load(){return ve(()=>Promise.resolve().then(()=>P5t),void 0,import.meta.url).then(e=>Pe(e.webIDL))}}),$e.of({name:"VB.NET",extensions:["vb"],load(){return ve(()=>Promise.resolve().then(()=>F_t),void 0,import.meta.url).then(e=>Pe(e.vb))}}),$e.of({name:"VBScript",extensions:["vbs"],load(){return ve(()=>Promise.resolve().then(()=>H_t),void 0,import.meta.url).then(e=>Pe(e.vbScript))}}),$e.of({name:"Velocity",extensions:["vtl"],load(){return ve(()=>Promise.resolve().then(()=>e5t),void 0,import.meta.url).then(e=>Pe(e.velocity))}}),$e.of({name:"Verilog",extensions:["v"],load(){return ve(()=>Promise.resolve().then(()=>wH),void 0,import.meta.url).then(e=>Pe(e.verilog))}}),$e.of({name:"VHDL",extensions:["vhd","vhdl"],load(){return ve(()=>Promise.resolve().then(()=>c5t),void 0,import.meta.url).then(e=>Pe(e.vhdl))}}),$e.of({name:"XQuery",extensions:["xy","xquery"],load(){return ve(()=>Promise.resolve().then(()=>z5t),void 0,import.meta.url).then(e=>Pe(e.xQuery))}}),$e.of({name:"Yacas",extensions:["ys"],load(){return ve(()=>Promise.resolve().then(()=>V5t),void 0,import.meta.url).then(e=>Pe(e.yacas))}}),$e.of({name:"Z80",extensions:["z80"],load(){return ve(()=>Promise.resolve().then(()=>K5t),void 0,import.meta.url).then(e=>Pe(e.z80))}}),$e.of({name:"MscGen",extensions:["mscgen","mscin","msc"],load(){return ve(()=>Promise.resolve().then(()=>G2),void 0,import.meta.url).then(e=>Pe(e.mscgen))}}),$e.of({name:"Xù",extensions:["xu"],load(){return ve(()=>Promise.resolve().then(()=>G2),void 0,import.meta.url).then(e=>Pe(e.xu))}}),$e.of({name:"MsGenny",extensions:["msgenny"],load(){return ve(()=>Promise.resolve().then(()=>G2),void 0,import.meta.url).then(e=>Pe(e.msgenny))}}),$e.of({name:"Vue",extensions:["vue"],load(){return ve(()=>Promise.resolve().then(()=>l0t),void 0,import.meta.url).then(e=>e.vue())}}),$e.of({name:"Angular Template",load(){return ve(()=>Promise.resolve().then(()=>P0t),void 0,import.meta.url).then(e=>e.angular())}})];class m8{constructor(t,n,r,i){this.state=t,this.pos=n,this.explicit=r,this.view=i,this.abortListeners=[],this.abortOnDocChange=!1}tokenBefore(t){let n=Bn(this.state).resolveInner(this.pos,-1);for(;n&&t.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(t){let n=this.state.doc.lineAt(this.pos),r=Math.max(n.from,this.pos-250),i=n.text.slice(r-n.from,this.pos-n.from),a=i.search(t0e(t,!1));return a<0?null:{from:r+a,to:this.pos,text:i.slice(a)}}get aborted(){return this.abortListeners==null}addEventListener(t,n,r){t=="abort"&&this.abortListeners&&(this.abortListeners.push(n),r&&r.onDocChange&&(this.abortOnDocChange=!0))}}function KM(e){let t=Object.keys(e).join(""),n=/\w/.test(t);return n&&(t=t.replace(/\w/g,"")),`[${n?"\\w":""}${t.replace(/[^\w\s]/g,"\\$&")}]`}function Nat(e){let t=Object.create(null),n=Object.create(null);for(let{label:i}of e){t[i[0]]=!0;for(let a=1;a<i.length;a++)n[i[a]]=!0}let r=KM(t)+KM(n)+"*$";return[new RegExp("^"+r),new RegExp(r)]}function Ev(e){let t=e.map(i=>typeof i=="string"?{label:i}:i),[n,r]=t.every(i=>/^\w+$/.test(i.label))?[/\w*$/,/\w+$/]:Nat(t);return i=>{let a=i.matchBefore(r);return a||i.explicit?{from:a?a.from:i.pos,options:t,validFor:n}:null}}function Mk(e,t){return n=>{for(let r=Bn(n.state).resolveInner(n.pos,-1);r;r=r.parent){if(e.indexOf(r.name)>-1)return null;if(r.type.isTop)break}return t(n)}}class JM{constructor(t,n,r,i){this.completion=t,this.source=n,this.match=r,this.score=i}}function ef(e){return e.selection.main.from}function t0e(e,t){var n;let{source:r}=e,i=t&&r[0]!="^",a=r[r.length-1]!="$";return!i&&!a?e:new RegExp(`${i?"^":""}(?:${r})${a?"$":""}`,(n=e.flags)!==null&&n!==void 0?n:e.ignoreCase?"i":"")}const g8=Zf.define();function Yat(e,t,n,r){let{main:i}=e.selection,a=n-i.from,o=r-i.from;return Object.assign(Object.assign({},e.changeByRange(s=>{if(s!=i&&n!=r&&e.sliceDoc(s.from+a,s.from+o)!=e.sliceDoc(n,r))return{range:s};let l=e.toText(t);return{changes:{from:s.from+a,to:r==i.from?s.to:s.from+o,insert:l},range:Ge.cursor(s.from+a+l.length)}})),{scrollIntoView:!0,userEvent:"input.complete"})}const eV=new WeakMap;function Gat(e){if(!Array.isArray(e))return e;let t=eV.get(e);return t||eV.set(e,t=Ev(e)),t}const tx=_n.define(),K$=_n.define();class Iat{constructor(t){this.pattern=t,this.chars=[],this.folded=[],this.any=[],this.precise=[],this.byWord=[],this.score=0,this.matched=[];for(let n=0;n<t.length;){let r=Ro(t,n),i=Yc(r);this.chars.push(r);let a=t.slice(n,n+i),o=a.toUpperCase();this.folded.push(Ro(o==a?a.toLowerCase():o,0)),n+=i}this.astral=t.length!=this.chars.length}ret(t,n){return this.score=t,this.matched=n,this}match(t){if(this.pattern.length==0)return this.ret(-100,[]);if(t.length<this.pattern.length)return null;let{chars:n,folded:r,any:i,precise:a,byWord:o}=this;if(n.length==1){let v=Ro(t,0),S=Yc(v),Q=S==t.length?0:-100;if(v!=n[0])if(v==r[0])Q+=-200;else return null;return this.ret(Q,[0,S])}let s=t.indexOf(this.pattern);if(s==0)return this.ret(t.length==this.pattern.length?0:-100,[0,this.pattern.length]);let l=n.length,c=0;if(s<0){for(let v=0,S=Math.min(t.length,200);v<S&&c<l;){let Q=Ro(t,v);(Q==n[c]||Q==r[c])&&(i[c++]=v),v+=Yc(Q)}if(c<l)return null}let u=0,O=0,d=!1,f=0,p=-1,m=-1,g=/[a-z]/.test(t),y=!0;for(let v=0,S=Math.min(t.length,200),Q=0;v<S&&O<l;){let b=Ro(t,v);s<0&&(u<l&&b==n[u]&&(a[u++]=v),f<l&&(b==n[f]||b==r[f]?(f==0&&(p=v),m=v+1,f++):f=0));let w,x=b<255?b>=48&&b<=57||b>=97&&b<=122?2:b>=65&&b<=90?1:0:(w=dme(b))!=w.toLowerCase()?1:w!=w.toUpperCase()?2:0;(!v||x==1&&g||Q==0&&x!=0)&&(n[O]==b||r[O]==b&&(d=!0)?o[O++]=v:o.length&&(y=!1)),Q=x,v+=Yc(b)}return O==l&&o[0]==0&&y?this.result(-100+(d?-200:0),o,t):f==l&&p==0?this.ret(-200-t.length+(m==t.length?0:-100),[0,m]):s>-1?this.ret(-700-t.length,[s,s+this.pattern.length]):f==l?this.ret(-900-t.length,[p,m]):O==l?this.result(-100+(d?-200:0)+-700+(y?0:-1100),o,t):n.length==2?null:this.result((i[0]?-700:0)+-200+-1100,i,t)}result(t,n,r){let i=[],a=0;for(let o of n){let s=o+(this.astral?Yc(Ro(r,o)):1);a&&i[a-1]==o?i[a-1]=s:(i[a++]=o,i[a++]=s)}return this.ret(t-r.length,i)}}class Zat{constructor(t){this.pattern=t,this.matched=[],this.score=0,this.folded=t.toLowerCase()}match(t){if(t.length<this.pattern.length)return null;let n=t.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+(t.length==this.pattern.length?0:-100),this)}}const Ni=ht.define({combine(e){return Nm(e,{activateOnTyping:!0,activateOnCompletion:()=>!1,activateOnTypingDelay:100,selectOnOpen:!0,override:null,closeOnBlur:!0,maxRenderedOptions:100,defaultKeymap:!0,tooltipClass:()=>"",optionClass:()=>"",aboveCursor:!1,icons:!0,addToOptions:[],positionInfo:Dat,filterStrict:!1,compareCompletions:(t,n)=>t.label.localeCompare(n.label),interactionDelay:75,updateSyncTime:100},{defaultKeymap:(t,n)=>t&&n,closeOnBlur:(t,n)=>t&&n,icons:(t,n)=>t&&n,tooltipClass:(t,n)=>r=>tV(t(r),n(r)),optionClass:(t,n)=>r=>tV(t(r),n(r)),addToOptions:(t,n)=>t.concat(n),filterStrict:(t,n)=>t||n})}});function tV(e,t){return e?t?e+" "+t:e:t}function Dat(e,t,n,r,i,a){let o=e.textDirection==Er.RTL,s=o,l=!1,c="top",u,O,d=t.left-i.left,f=i.right-t.right,p=r.right-r.left,m=r.bottom-r.top;if(s&&d<Math.min(p,f)?s=!1:!s&&f<Math.min(p,d)&&(s=!0),p<=(s?d:f))u=Math.max(i.top,Math.min(n.top,i.bottom-m))-t.top,O=Math.min(400,s?d:f);else{l=!0,O=Math.min(400,(o?t.right:i.right-t.left)-30);let v=i.bottom-t.bottom;v>=m||v>t.top?u=n.bottom-t.top:(c="bottom",u=t.bottom-n.top)}let g=(t.bottom-t.top)/a.offsetHeight,y=(t.right-t.left)/a.offsetWidth;return{style:`${c}: ${u/g}px; max-width: ${O/y}px`,class:"cm-completionInfo-"+(l?o?"left-narrow":"right-narrow":s?"left":"right")}}function Mat(e){let t=e.addToOptions.slice();return e.icons&&t.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(i=>"cm-completionIcon-"+i)),r.setAttribute("aria-hidden","true"),r},position:20}),t.push({render(n,r,i,a){let o=document.createElement("span");o.className="cm-completionLabel";let s=n.displayLabel||n.label,l=0;for(let c=0;c<a.length;){let u=a[c++],O=a[c++];u>l&&o.appendChild(document.createTextNode(s.slice(l,u)));let d=o.appendChild(document.createElement("span"));d.appendChild(document.createTextNode(s.slice(u,O))),d.className="cm-completionMatchedText",l=O}return l<s.length&&o.appendChild(document.createTextNode(s.slice(l))),o},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}),t.sort((n,r)=>n.position-r.position).map(n=>n.render)}function zT(e,t,n){if(e<=n)return{from:0,to:e};if(t<0&&(t=0),t<=e>>1){let i=Math.floor(t/n);return{from:i*n,to:(i+1)*n}}let r=Math.floor((e-t)/n);return{from:e-(r+1)*n,to:e-r*n}}class Vat{constructor(t,n,r){this.view=t,this.stateField=n,this.applyCompletion=r,this.info=null,this.infoDestroy=null,this.placeInfoReq={read:()=>this.measureInfo(),write:l=>this.placeInfo(l),key:this},this.space=null,this.currentClass="";let i=t.state.field(n),{options:a,selected:o}=i.open,s=t.state.facet(Ni);this.optionContent=Mat(s),this.optionClass=s.optionClass,this.tooltipClass=s.tooltipClass,this.range=zT(a.length,o,s.maxRenderedOptions),this.dom=document.createElement("div"),this.dom.className="cm-tooltip-autocomplete",this.updateTooltipClass(t.state),this.dom.addEventListener("mousedown",l=>{let{options:c}=t.state.field(n).open;for(let u=l.target,O;u&&u!=this.dom;u=u.parentNode)if(u.nodeName=="LI"&&(O=/-(\d+)$/.exec(u.id))&&+O[1]<c.length){this.applyCompletion(t,c[+O[1]]),l.preventDefault();return}}),this.dom.addEventListener("focusout",l=>{let c=t.state.field(this.stateField,!1);c&&c.tooltip&&t.state.facet(Ni).closeOnBlur&&l.relatedTarget!=t.contentDOM&&t.dispatch({effects:K$.of(null)})}),this.showOptions(a,i.id)}mount(){this.updateSel()}showOptions(t,n){this.list&&this.list.remove(),this.list=this.dom.appendChild(this.createListBox(t,n,this.range)),this.list.addEventListener("scroll",()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)})}update(t){var n;let r=t.state.field(this.stateField),i=t.startState.field(this.stateField);if(this.updateTooltipClass(t.state),r!=i){let{options:a,selected:o,disabled:s}=r.open;(!i.open||i.open.options!=a)&&(this.range=zT(a.length,o,t.state.facet(Ni).maxRenderedOptions),this.showOptions(a,r.id)),this.updateSel(),s!=((n=i.open)===null||n===void 0?void 0:n.disabled)&&this.dom.classList.toggle("cm-tooltip-autocomplete-disabled",!!s)}}updateTooltipClass(t){let n=this.tooltipClass(t);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(t){this.space=t,this.info&&this.view.requestMeasure(this.placeInfoReq)}updateSel(){let t=this.view.state.field(this.stateField),n=t.open;if((n.selected>-1&&n.selected<this.range.from||n.selected>=this.range.to)&&(this.range=zT(n.options.length,n.selected,this.view.state.facet(Ni).maxRenderedOptions),this.showOptions(n.options,t.id)),this.updateSelectedOption(n.selected)){this.destroyInfo();let{completion:r}=n.options[n.selected],{info:i}=r;if(!i)return;let a=typeof i=="string"?document.createTextNode(i):i(r);if(!a)return;"then"in a?a.then(o=>{o&&this.view.state.field(this.stateField,!1)==t&&this.addInfoPane(o,r)}).catch(o=>no(this.view.state,o,"completion info")):this.addInfoPane(a,r)}}addInfoPane(t,n){this.destroyInfo();let r=this.info=document.createElement("div");if(r.className="cm-tooltip cm-completionInfo",t.nodeType!=null)r.appendChild(t),this.infoDestroy=null;else{let{dom:i,destroy:a}=t;r.appendChild(i),this.infoDestroy=a||null}this.dom.appendChild(r),this.view.requestMeasure(this.placeInfoReq)}updateSelectedOption(t){let n=null;for(let r=this.list.firstChild,i=this.range.from;r;r=r.nextSibling,i++)r.nodeName!="LI"||!r.id?i--:i==t?r.hasAttribute("aria-selected")||(r.setAttribute("aria-selected","true"),n=r):r.hasAttribute("aria-selected")&&r.removeAttribute("aria-selected");return n&&Fat(this.list,n),n}measureInfo(){let t=this.dom.querySelector("[aria-selected]");if(!t||!this.info)return null;let n=this.dom.getBoundingClientRect(),r=this.info.getBoundingClientRect(),i=t.getBoundingClientRect(),a=this.space;if(!a){let o=this.dom.ownerDocument.documentElement;a={left:0,top:0,right:o.clientWidth,bottom:o.clientHeight}}return i.top>Math.min(a.bottom,n.bottom)-10||i.bottom<Math.max(a.top,n.top)+10?null:this.view.state.facet(Ni).positionInfo(this.view,n,i,r,a,this.dom)}placeInfo(t){this.info&&(t?(t.style&&(this.info.style.cssText=t.style),this.info.className="cm-tooltip cm-completionInfo "+(t.class||"")):this.info.style.cssText="top: -1e6px")}createListBox(t,n,r){const i=document.createElement("ul");i.id=n,i.setAttribute("role","listbox"),i.setAttribute("aria-expanded","true"),i.setAttribute("aria-label",this.view.state.phrase("Completions")),i.addEventListener("mousedown",o=>{o.target==i&&o.preventDefault()});let a=null;for(let o=r.from;o<r.to;o++){let{completion:s,match:l}=t[o],{section:c}=s;if(c){let d=typeof c=="string"?c:c.name;if(d!=a&&(o>r.from||r.from==0))if(a=d,typeof c!="string"&&c.header)i.appendChild(c.header(c));else{let f=i.appendChild(document.createElement("completion-section"));f.textContent=d}}const u=i.appendChild(document.createElement("li"));u.id=n+"-"+o,u.setAttribute("role","option");let O=this.optionClass(s);O&&(u.className=O);for(let d of this.optionContent){let f=d(s,this.view.state,this.view,l);f&&u.appendChild(f)}}return r.from&&i.classList.add("cm-completionListIncompleteTop"),r.to<t.length&&i.classList.add("cm-completionListIncompleteBottom"),i}destroyInfo(){this.info&&(this.infoDestroy&&this.infoDestroy(),this.info.remove(),this.info=null)}destroy(){this.destroyInfo()}}function Lat(e,t){return n=>new Vat(n,e,t)}function Fat(e,t){let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i=n.height/e.offsetHeight;r.top<n.top?e.scrollTop-=(n.top-r.top)/i:r.bottom>n.bottom&&(e.scrollTop+=(r.bottom-n.bottom)/i)}function nV(e){return(e.boost||0)*100+(e.apply?10:0)+(e.info?5:0)+(e.type?1:0)}function Bat(e,t){let n=[],r=null,i=c=>{n.push(c);let{section:u}=c.completion;if(u){r||(r=[]);let O=typeof u=="string"?u:u.name;r.some(d=>d.name==O)||r.push(typeof u=="string"?{name:O}:u)}},a=t.facet(Ni);for(let c of e)if(c.hasResult()){let u=c.result.getMatch;if(c.result.filter===!1)for(let O of c.result.options)i(new JM(O,c.source,u?u(O):[],1e9-n.length));else{let O=t.sliceDoc(c.from,c.to),d,f=a.filterStrict?new Zat(O):new Iat(O);for(let p of c.result.options)if(d=f.match(p.label)){let m=p.displayLabel?u?u(p,d.matched):[]:d.matched;i(new JM(p,c.source,m,d.score+(p.boost||0)))}}}if(r){let c=Object.create(null),u=0,O=(d,f)=>{var p,m;return((p=d.rank)!==null&&p!==void 0?p:1e9)-((m=f.rank)!==null&&m!==void 0?m:1e9)||(d.name<f.name?-1:1)};for(let d of r.sort(O))u-=1e5,c[d.name]=u;for(let d of n){let{section:f}=d.completion;f&&(d.score+=c[typeof f=="string"?f:f.name])}}let o=[],s=null,l=a.compareCompletions;for(let c of n.sort((u,O)=>O.score-u.score||l(u.completion,O.completion))){let u=c.completion;!s||s.label!=u.label||s.detail!=u.detail||s.type!=null&&u.type!=null&&s.type!=u.type||s.apply!=u.apply||s.boost!=u.boost?o.push(c):nV(c.completion)>nV(s)&&(o[o.length-1]=c),s=c.completion}return o}class Bh{constructor(t,n,r,i,a,o){this.options=t,this.attrs=n,this.tooltip=r,this.timestamp=i,this.selected=a,this.disabled=o}setSelected(t,n){return t==this.selected||t>=this.options.length?this:new Bh(this.options,rV(n,t),this.tooltip,this.timestamp,t,this.disabled)}static build(t,n,r,i,a,o){if(i&&!o&&t.some(c=>c.isPending))return i.setDisabled();let s=Bat(t,n);if(!s.length)return i&&t.some(c=>c.isPending)?i.setDisabled():null;let l=n.facet(Ni).selectOnOpen?0:-1;if(i&&i.selected!=l&&i.selected!=-1){let c=i.options[i.selected].completion;for(let u=0;u<s.length;u++)if(s[u].completion==c){l=u;break}}return new Bh(s,rV(r,l),{pos:t.reduce((c,u)=>u.hasResult()?Math.min(c,u.from):c,1e8),create:not,above:a.aboveCursor},i?i.timestamp:Date.now(),l,!1)}map(t){return new Bh(this.options,this.attrs,Object.assign(Object.assign({},this.tooltip),{pos:t.mapPos(this.tooltip.pos)}),this.timestamp,this.selected,this.disabled)}setDisabled(){return new Bh(this.options,this.attrs,this.tooltip,this.timestamp,this.selected,!0)}}class nx{constructor(t,n,r){this.active=t,this.id=n,this.open=r}static start(){return new nx(eot,"cm-ac-"+Math.floor(Math.random()*2e6).toString(36),null)}update(t){let{state:n}=t,r=n.facet(Ni),a=(r.override||n.languageDataAt("autocomplete",ef(n)).map(Gat)).map(l=>(this.active.find(u=>u.source==l)||new gs(l,this.active.some(u=>u.state!=0)?1:0)).update(t,r));a.length==this.active.length&&a.every((l,c)=>l==this.active[c])&&(a=this.active);let o=this.open,s=t.effects.some(l=>l.is($8));o&&t.docChanged&&(o=o.map(t.changes)),t.selection||a.some(l=>l.hasResult()&&t.changes.touchesRange(l.from,l.to))||!Hat(a,this.active)||s?o=Bh.build(a,n,this.id,o,r,s):o&&o.disabled&&!a.some(l=>l.isPending)&&(o=null),!o&&a.every(l=>!l.isPending)&&a.some(l=>l.hasResult())&&(a=a.map(l=>l.hasResult()?new gs(l.source,0):l));for(let l of t.effects)l.is(r0e)&&(o=o&&o.setSelected(l.value,this.id));return a==this.active&&o==this.open?this:new nx(a,this.id,o)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:this.active.length?Kat:Jat}}function Hat(e,t){if(e==t)return!0;for(let n=0,r=0;;){for(;n<e.length&&!e[n].hasResult();)n++;for(;r<t.length&&!t[r].hasResult();)r++;let i=n==e.length,a=r==t.length;if(i||a)return i==a;if(e[n++].result!=t[r++].result)return!1}}const Kat={"aria-autocomplete":"list"},Jat={};function rV(e,t){let n={"aria-autocomplete":"list","aria-haspopup":"listbox","aria-controls":e};return t>-1&&(n["aria-activedescendant"]=e+"-"+t),n}const eot=[];function n0e(e,t){if(e.isUserEvent("input.complete")){let r=e.annotation(g8);if(r&&t.activateOnCompletion(r))return 12}let n=e.isUserEvent("input.type");return n&&t.activateOnTyping?5:n?1:e.isUserEvent("delete.backward")?2:e.selection?8:e.docChanged?16:0}class gs{constructor(t,n,r=!1){this.source=t,this.state=n,this.explicit=r}hasResult(){return!1}get isPending(){return this.state==1}update(t,n){let r=n0e(t,n),i=this;(r&8||r&16&&this.touches(t))&&(i=new gs(i.source,0)),r&4&&i.state==0&&(i=new gs(this.source,1)),i=i.updateFor(t,r);for(let a of t.effects)if(a.is(tx))i=new gs(i.source,1,a.value);else if(a.is(K$))i=new gs(i.source,0);else if(a.is($8))for(let o of a.value)o.source==i.source&&(i=o);return i}updateFor(t,n){return this.map(t.changes)}map(t){return this}touches(t){return t.changes.touchesRange(ef(t.state))}}class hp extends gs{constructor(t,n,r,i,a,o){super(t,3,n),this.limit=r,this.result=i,this.from=a,this.to=o}hasResult(){return!0}updateFor(t,n){var r;if(!(n&3))return this.map(t.changes);let i=this.result;i.map&&!t.changes.empty&&(i=i.map(i,t.changes));let a=t.changes.mapPos(this.from),o=t.changes.mapPos(this.to,1),s=ef(t.state);if(s>o||!i||n&2&&(ef(t.startState)==this.from||s<this.limit))return new gs(this.source,n&4?1:0);let l=t.changes.mapPos(this.limit);return tot(i.validFor,t.state,a,o)?new hp(this.source,this.explicit,l,i,a,o):i.update&&(i=i.update(i,a,o,new m8(t.state,s,!1)))?new hp(this.source,this.explicit,l,i,i.from,(r=i.to)!==null&&r!==void 0?r:ef(t.state)):new gs(this.source,1,this.explicit)}map(t){return t.empty?this:(this.result.map?this.result.map(this.result,t):this.result)?new hp(this.source,this.explicit,t.mapPos(this.limit),this.result,t.mapPos(this.from),t.mapPos(this.to,1)):new gs(this.source,0)}touches(t){return t.changes.touchesRange(this.from,this.to)}}function tot(e,t,n,r){if(!e)return!1;let i=t.sliceDoc(n,r);return typeof e=="function"?e(i,n,r,t):t0e(e,!0).test(i)}const $8=_n.define({map(e,t){return e.map(n=>n.map(t))}}),r0e=_n.define(),Ja=co.define({create(){return nx.start()},update(e,t){return e.update(t)},provide:e=>[c8.from(e,t=>t.tooltip),Pt.contentAttributes.from(e,t=>t.attrs)]});function y8(e,t){const n=t.completion.apply||t.completion.label;let r=e.state.field(Ja).active.find(i=>i.source==t.source);return r instanceof hp?(typeof n=="string"?e.dispatch(Object.assign(Object.assign({},Yat(e.state,n,r.from,r.to)),{annotations:g8.of(t.completion)})):n(e,t.completion,r.from,r.to),!0):!1}const not=Lat(Ja,y8);function iw(e,t="option"){return n=>{let r=n.state.field(Ja,!1);if(!r||!r.open||r.open.disabled||Date.now()-r.open.timestamp<n.state.facet(Ni).interactionDelay)return!1;let i=1,a;t=="page"&&(a=Pge(n,r.open.tooltip))&&(i=Math.max(2,Math.floor(a.dom.offsetHeight/a.dom.querySelector("li").offsetHeight)-1));let{length:o}=r.open.options,s=r.open.selected>-1?r.open.selected+i*(e?1:-1):e?0:o-1;return s<0?s=t=="page"?0:o-1:s>=o&&(s=t=="page"?o-1:0),n.dispatch({effects:r0e.of(s)}),!0}}const rot=e=>{let t=e.state.field(Ja,!1);return e.state.readOnly||!t||!t.open||t.open.selected<0||t.open.disabled||Date.now()-t.open.timestamp<e.state.facet(Ni).interactionDelay?!1:y8(e,t.open.options[t.open.selected])},iV=e=>e.state.field(Ja,!1)?(e.dispatch({effects:tx.of(!0)}),!0):!1,iot=e=>{let t=e.state.field(Ja,!1);return!t||!t.active.some(n=>n.state!=0)?!1:(e.dispatch({effects:K$.of(null)}),!0)};class aot{constructor(t,n){this.active=t,this.context=n,this.time=Date.now(),this.updates=[],this.done=void 0}}const oot=50,sot=1e3,lot=Ti.fromClass(class{constructor(e){this.view=e,this.debounceUpdate=-1,this.running=[],this.debounceAccept=-1,this.pendingStart=!1,this.composing=0;for(let t of e.state.field(Ja).active)t.isPending&&this.startQuery(t)}update(e){let t=e.state.field(Ja),n=e.state.facet(Ni);if(!e.selectionSet&&!e.docChanged&&e.startState.field(Ja)==t)return;let r=e.transactions.some(a=>{let o=n0e(a,n);return o&8||(a.selection||a.docChanged)&&!(o&3)});for(let a=0;a<this.running.length;a++){let o=this.running[a];if(r||o.context.abortOnDocChange&&e.docChanged||o.updates.length+e.transactions.length>oot&&Date.now()-o.time>sot){for(let s of o.context.abortListeners)try{s()}catch(l){no(this.view.state,l)}o.context.abortListeners=null,this.running.splice(a--,1)}else o.updates.push(...e.transactions)}this.debounceUpdate>-1&&clearTimeout(this.debounceUpdate),e.transactions.some(a=>a.effects.some(o=>o.is(tx)))&&(this.pendingStart=!0);let i=this.pendingStart?50:n.activateOnTypingDelay;if(this.debounceUpdate=t.active.some(a=>a.isPending&&!this.running.some(o=>o.active.source==a.source))?setTimeout(()=>this.startUpdate(),i):-1,this.composing!=0)for(let a of e.transactions)a.isUserEvent("input.type")?this.composing=2:this.composing==2&&a.selection&&(this.composing=3)}startUpdate(){this.debounceUpdate=-1,this.pendingStart=!1;let{state:e}=this.view,t=e.field(Ja);for(let n of t.active)n.isPending&&!this.running.some(r=>r.active.source==n.source)&&this.startQuery(n);this.running.length&&t.open&&t.open.disabled&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(Ni).updateSyncTime))}startQuery(e){let{state:t}=this.view,n=ef(t),r=new m8(t,n,e.explicit,this.view),i=new aot(e,r);this.running.push(i),Promise.resolve(e.source(r)).then(a=>{i.context.aborted||(i.done=a||null,this.scheduleAccept())},a=>{this.view.dispatch({effects:K$.of(null)}),no(this.view.state,a)})}scheduleAccept(){this.running.every(e=>e.done!==void 0)?this.accept():this.debounceAccept<0&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(Ni).updateSyncTime))}accept(){var e;this.debounceAccept>-1&&clearTimeout(this.debounceAccept),this.debounceAccept=-1;let t=[],n=this.view.state.facet(Ni),r=this.view.state.field(Ja);for(let i=0;i<this.running.length;i++){let a=this.running[i];if(a.done===void 0)continue;if(this.running.splice(i--,1),a.done){let s=ef(a.updates.length?a.updates[0].startState:this.view.state),l=Math.min(s,a.done.from+(a.active.explicit?0:1)),c=new hp(a.active.source,a.active.explicit,l,a.done,a.done.from,(e=a.done.to)!==null&&e!==void 0?e:s);for(let u of a.updates)c=c.update(u,n);if(c.hasResult()){t.push(c);continue}}let o=r.active.find(s=>s.source==a.active.source);if(o&&o.isPending)if(a.done==null){let s=new gs(a.active.source,0);for(let l of a.updates)s=s.update(l,n);s.isPending||t.push(s)}else this.startQuery(o)}(t.length||r.open&&r.open.disabled)&&this.view.dispatch({effects:$8.of(t)})}},{eventHandlers:{blur(e){let t=this.view.state.field(Ja,!1);if(t&&t.tooltip&&this.view.state.facet(Ni).closeOnBlur){let n=t.open&&Pge(this.view,t.open.tooltip);(!n||!n.dom.contains(e.relatedTarget))&&setTimeout(()=>this.view.dispatch({effects:K$.of(null)}),10)}},compositionstart(){this.composing=1},compositionend(){this.composing==3&&setTimeout(()=>this.view.dispatch({effects:tx.of(!1)}),20),this.composing=0}}}),cot=typeof navigator=="object"&&/Win/.test(navigator.platform),uot=ZO.highest(Pt.domEventHandlers({keydown(e,t){let n=t.state.field(Ja,!1);if(!n||!n.open||n.open.disabled||n.open.selected<0||e.key.length>1||e.ctrlKey&&!(cot&&e.altKey)||e.metaKey)return!1;let r=n.open.options[n.open.selected],i=n.active.find(o=>o.source==r.source),a=r.completion.commitCharacters||i.result.commitCharacters;return a&&a.indexOf(e.key)>-1&&y8(t,r),!1}})),i0e=Pt.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 Oot{constructor(t,n,r,i){this.field=t,this.line=n,this.from=r,this.to=i}}class v8{constructor(t,n,r){this.field=t,this.from=n,this.to=r}map(t){let n=t.mapPos(this.from,-1,Hi.TrackDel),r=t.mapPos(this.to,1,Hi.TrackDel);return n==null||r==null?null:new v8(this.field,n,r)}}class b8{constructor(t,n){this.lines=t,this.fieldPositions=n}instantiate(t,n){let r=[],i=[n],a=t.doc.lineAt(n),o=/^\s*/.exec(a.text)[0];for(let l of this.lines){if(r.length){let c=o,u=/^\t*/.exec(l)[0].length;for(let O=0;O<u;O++)c+=t.facet(Ik);i.push(n+c.length-u),l=c+l.slice(u)}r.push(l),n+=l.length+1}let s=this.fieldPositions.map(l=>new v8(l.field,i[l.line]+l.from,i[l.line]+l.to));return{text:r,ranges:s}}static parse(t){let n=[],r=[],i=[],a;for(let o of t.split(/\r\n?|\n/)){for(;a=/[#$]\{(?:(\d+)(?::([^}]*))?|((?:\\[{}]|[^}])*))\}/.exec(o);){let s=a[1]?+a[1]:null,l=a[2]||a[3]||"",c=-1,u=l.replace(/\\[{}]/g,O=>O[1]);for(let O=0;O<n.length;O++)(s!=null?n[O].seq==s:u&&n[O].name==u)&&(c=O);if(c<0){let O=0;for(;O<n.length&&(s==null||n[O].seq!=null&&n[O].seq<s);)O++;n.splice(O,0,{seq:s,name:u}),c=O;for(let d of i)d.field>=c&&d.field++}i.push(new Oot(c,r.length,a.index,a.index+u.length)),o=o.slice(0,a.index)+l+o.slice(a.index+a[0].length)}o=o.replace(/\\([{}])/g,(s,l,c)=>{for(let u of i)u.line==r.length&&u.from>c&&(u.from--,u.to--);return l}),r.push(o)}return new b8(r,i)}}let dot=cn.widget({widget:new class extends Tu{toDOM(){let e=document.createElement("span");return e.className="cm-snippetFieldPosition",e}ignoreEvent(){return!1}}}),fot=cn.mark({class:"cm-snippetField"});class Ym{constructor(t,n){this.ranges=t,this.active=n,this.deco=cn.set(t.map(r=>(r.from==r.to?dot:fot).range(r.from,r.to)))}map(t){let n=[];for(let r of this.ranges){let i=r.map(t);if(!i)return null;n.push(i)}return new Ym(n,this.active)}selectionInsideField(t){return t.ranges.every(n=>this.ranges.some(r=>r.field==this.active&&r.from<=n.from&&r.to>=n.to))}}const qv=_n.define({map(e,t){return e&&e.map(t)}}),hot=_n.define(),J$=co.define({create(){return null},update(e,t){for(let n of t.effects){if(n.is(qv))return n.value;if(n.is(hot)&&e)return new Ym(e.ranges,n.value)}return e&&t.docChanged&&(e=e.map(t.changes)),e&&t.selection&&!e.selectionInsideField(t.selection)&&(e=null),e},provide:e=>Pt.decorations.from(e,t=>t?t.deco:cn.none)});function w8(e,t){return Ge.create(e.filter(n=>n.field==t).map(n=>Ge.range(n.from,n.to)))}function pot(e){let t=b8.parse(e);return(n,r,i,a)=>{let{text:o,ranges:s}=t.instantiate(n.state,i),{main:l}=n.state.selection,c={changes:{from:i,to:a==l.from?l.to:a,insert:Fn.of(o)},scrollIntoView:!0,annotations:r?[g8.of(r),Ki.userEvent.of("input.complete")]:void 0};if(s.length&&(c.selection=w8(s,0)),s.some(u=>u.field>0)){let u=new Ym(s,0),O=c.effects=[qv.of(u)];n.state.field(J$,!1)===void 0&&O.push(_n.appendConfig.of([J$,vot,bot,i0e]))}n.dispatch(n.state.update(c))}}function a0e(e){return({state:t,dispatch:n})=>{let r=t.field(J$,!1);if(!r||e<0&&r.active==0)return!1;let i=r.active+e,a=e>0&&!r.ranges.some(o=>o.field==i+e);return n(t.update({selection:w8(r.ranges,i),effects:qv.of(a?null:new Ym(r.ranges,i)),scrollIntoView:!0})),!0}}const mot=({state:e,dispatch:t})=>e.field(J$,!1)?(t(e.update({effects:qv.of(null)})),!0):!1,got=a0e(1),$ot=a0e(-1),yot=[{key:"Tab",run:got,shift:$ot},{key:"Escape",run:mot}],aV=ht.define({combine(e){return e.length?e[0]:yot}}),vot=ZO.highest(Nk.compute([aV],e=>e.facet(aV)));function Qr(e,t){return Object.assign(Object.assign({},t),{apply:pot(e)})}const bot=Pt.domEventHandlers({mousedown(e,t){let n=t.state.field(J$,!1),r;if(!n||(r=t.posAtCoords({x:e.clientX,y:e.clientY}))==null)return!1;let i=n.ranges.find(a=>a.from<=r&&a.to>=r);return!i||i.field==n.active?!1:(t.dispatch({selection:w8(n.ranges,i.field),effects:qv.of(n.ranges.some(a=>a.field>i.field)?new Ym(n.ranges,i.field):null),scrollIntoView:!0}),!0)}}),ey={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},Wd=_n.define({map(e,t){let n=t.mapPos(e,-1,Hi.TrackAfter);return n??void 0}}),S8=new class extends mf{};S8.startSide=1;S8.endSide=-1;const o0e=co.define({create(){return Pn.empty},update(e,t){if(e=e.map(t.changes),t.selection){let n=t.state.doc.lineAt(t.selection.main.head);e=e.update({filter:r=>r>=n.from&&r<=n.to})}for(let n of t.effects)n.is(Wd)&&(e=e.update({add:[S8.range(n.value,n.value+1)]}));return e}});function COn(){return[Sot,o0e]}const UT="()[]{}<>«»»«[]{}";function s0e(e){for(let t=0;t<UT.length;t+=2)if(UT.charCodeAt(t)==e)return UT.charAt(t+1);return dme(e<128?e:e+1)}function l0e(e,t){return e.languageDataAt("closeBrackets",t)[0]||ey}const wot=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),Sot=Pt.inputHandler.of((e,t,n,r)=>{if((wot?e.composing:e.compositionStarted)||e.state.readOnly)return!1;let i=e.state.selection.main;if(r.length>2||r.length==2&&Yc(Ro(r,0))==1||t!=i.from||n!=i.to)return!1;let a=Qot(e.state,r);return a?(e.dispatch(a),!0):!1}),xot=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let r=l0e(e,e.selection.main.head).brackets||ey.brackets,i=null,a=e.changeByRange(o=>{if(o.empty){let s=kot(e.doc,o.head);for(let l of r)if(l==s&&Vk(e.doc,o.head)==s0e(Ro(l,0)))return{changes:{from:o.head-l.length,to:o.head+l.length},range:Ge.cursor(o.head-l.length)}}return{range:i=o}});return i||t(e.update(a,{scrollIntoView:!0,userEvent:"delete.backward"})),!i},AOn=[{key:"Backspace",run:xot}];function Qot(e,t){let n=l0e(e,e.selection.main.head),r=n.brackets||ey.brackets;for(let i of r){let a=s0e(Ro(i,0));if(t==i)return a==i?Tot(e,i,r.indexOf(i+i+i)>-1,n):Pot(e,i,a,n.before||ey.before);if(t==a&&c0e(e,e.selection.main.from))return _ot(e,i,a)}return null}function c0e(e,t){let n=!1;return e.field(o0e).between(0,e.doc.length,r=>{r==t&&(n=!0)}),n}function Vk(e,t){let n=e.sliceString(t,t+2);return n.slice(0,Yc(Ro(n,0)))}function kot(e,t){let n=e.sliceString(t-2,t);return Yc(Ro(n,0))==n.length?n:n.slice(1)}function Pot(e,t,n,r){let i=null,a=e.changeByRange(o=>{if(!o.empty)return{changes:[{insert:t,from:o.from},{insert:n,from:o.to}],effects:Wd.of(o.to+t.length),range:Ge.range(o.anchor+t.length,o.head+t.length)};let s=Vk(e.doc,o.head);return!s||/\s/.test(s)||r.indexOf(s)>-1?{changes:{insert:t+n,from:o.head},effects:Wd.of(o.head+t.length),range:Ge.cursor(o.head+t.length)}:{range:i=o}});return i?null:e.update(a,{scrollIntoView:!0,userEvent:"input.type"})}function _ot(e,t,n){let r=null,i=e.changeByRange(a=>a.empty&&Vk(e.doc,a.head)==n?{changes:{from:a.head,to:a.head+n.length,insert:n},range:Ge.cursor(a.head+n.length)}:r={range:a});return r?null:e.update(i,{scrollIntoView:!0,userEvent:"input.type"})}function Tot(e,t,n,r){let i=r.stringPrefixes||ey.stringPrefixes,a=null,o=e.changeByRange(s=>{if(!s.empty)return{changes:[{insert:t,from:s.from},{insert:t,from:s.to}],effects:Wd.of(s.to+t.length),range:Ge.range(s.anchor+t.length,s.head+t.length)};let l=s.head,c=Vk(e.doc,l),u;if(c==t){if(oV(e,l))return{changes:{insert:t+t,from:l},effects:Wd.of(l+t.length),range:Ge.cursor(l+t.length)};if(c0e(e,l)){let d=n&&e.sliceDoc(l,l+t.length*3)==t+t+t?t+t+t:t;return{changes:{from:l,to:l+d.length,insert:d},range:Ge.cursor(l+d.length)}}}else{if(n&&e.sliceDoc(l-2*t.length,l)==t+t&&(u=sV(e,l-2*t.length,i))>-1&&oV(e,u))return{changes:{insert:t+t+t+t,from:l},effects:Wd.of(l+t.length),range:Ge.cursor(l+t.length)};if(e.charCategorizer(l)(c)!=ms.Word&&sV(e,l,i)>-1&&!Rot(e,l,t,i))return{changes:{insert:t+t,from:l},effects:Wd.of(l+t.length),range:Ge.cursor(l+t.length)}}return{range:a=s}});return a?null:e.update(o,{scrollIntoView:!0,userEvent:"input.type"})}function oV(e,t){let n=Bn(e).resolveInner(t+1);return n.parent&&n.from==t}function Rot(e,t,n,r){let i=Bn(e).resolveInner(t,-1),a=r.reduce((o,s)=>Math.max(o,s.length),0);for(let o=0;o<5;o++){let s=e.sliceDoc(i.from,Math.min(i.to,i.from+n.length+a)),l=s.indexOf(n);if(!l||l>-1&&r.indexOf(s.slice(0,l))>-1){let u=i.firstChild;for(;u&&u.from==i.from&&u.to-u.from>n.length+l;){if(e.sliceDoc(u.to-n.length,u.to)==n)return!1;u=u.firstChild}return!0}let c=i.to==t&&i.parent;if(!c)break;i=c}return!1}function sV(e,t,n){let r=e.charCategorizer(t);if(r(e.sliceDoc(t-1,t))!=ms.Word)return t;for(let i of n){let a=t-i.length;if(e.sliceDoc(a,t)==i&&r(e.sliceDoc(a-1,a))!=ms.Word)return a}return-1}function zOn(e={}){return[uot,Ja,Ni.of(e),lot,Eot,i0e]}const Xot=[{key:"Ctrl-Space",run:iV},{mac:"Alt-`",run:iV},{key:"Escape",run:iot},{key:"ArrowDown",run:iw(!0)},{key:"ArrowUp",run:iw(!1)},{key:"PageDown",run:iw(!0,"page")},{key:"PageUp",run:iw(!1,"page")},{key:"Enter",run:rot}],Eot=ZO.highest(Nk.computeN([Ni],e=>e.facet(Ni).defaultKeymap?[Xot]:[]));class rx{static create(t,n,r,i,a){let o=i+(i<<8)+t+(n<<4)|0;return new rx(t,n,r,o,a,[],[])}constructor(t,n,r,i,a,o,s){this.type=t,this.value=n,this.from=r,this.hash=i,this.end=a,this.children=o,this.positions=s,this.hashProp=[[Gt.contextHash,i]]}addChild(t,n){t.prop(Gt.contextHash)!=this.hash&&(t=new hn(t.type,t.children,t.positions,t.length,this.hashProp)),this.children.push(t),this.positions.push(n)}toTree(t,n=this.end){let r=this.children.length-1;return r>=0&&(n=Math.max(n,this.positions[r]+this.children[r].length+this.from)),new hn(t.types[this.type],this.children,this.positions,n-this.from).balance({makeTree:(i,a,o)=>new hn(yi.none,i,a,o,this.hashProp)})}}var De;(function(e){e[e.Document=1]="Document",e[e.CodeBlock=2]="CodeBlock",e[e.FencedCode=3]="FencedCode",e[e.Blockquote=4]="Blockquote",e[e.HorizontalRule=5]="HorizontalRule",e[e.BulletList=6]="BulletList",e[e.OrderedList=7]="OrderedList",e[e.ListItem=8]="ListItem",e[e.ATXHeading1=9]="ATXHeading1",e[e.ATXHeading2=10]="ATXHeading2",e[e.ATXHeading3=11]="ATXHeading3",e[e.ATXHeading4=12]="ATXHeading4",e[e.ATXHeading5=13]="ATXHeading5",e[e.ATXHeading6=14]="ATXHeading6",e[e.SetextHeading1=15]="SetextHeading1",e[e.SetextHeading2=16]="SetextHeading2",e[e.HTMLBlock=17]="HTMLBlock",e[e.LinkReference=18]="LinkReference",e[e.Paragraph=19]="Paragraph",e[e.CommentBlock=20]="CommentBlock",e[e.ProcessingInstructionBlock=21]="ProcessingInstructionBlock",e[e.Escape=22]="Escape",e[e.Entity=23]="Entity",e[e.HardBreak=24]="HardBreak",e[e.Emphasis=25]="Emphasis",e[e.StrongEmphasis=26]="StrongEmphasis",e[e.Link=27]="Link",e[e.Image=28]="Image",e[e.InlineCode=29]="InlineCode",e[e.HTMLTag=30]="HTMLTag",e[e.Comment=31]="Comment",e[e.ProcessingInstruction=32]="ProcessingInstruction",e[e.Autolink=33]="Autolink",e[e.HeaderMark=34]="HeaderMark",e[e.QuoteMark=35]="QuoteMark",e[e.ListMark=36]="ListMark",e[e.LinkMark=37]="LinkMark",e[e.EmphasisMark=38]="EmphasisMark",e[e.CodeMark=39]="CodeMark",e[e.CodeText=40]="CodeText",e[e.CodeInfo=41]="CodeInfo",e[e.LinkTitle=42]="LinkTitle",e[e.LinkLabel=43]="LinkLabel",e[e.URL=44]="URL"})(De||(De={}));class qot{constructor(t,n){this.start=t,this.content=n,this.marks=[],this.parsers=[]}}let jot=class{constructor(){this.text="",this.baseIndent=0,this.basePos=0,this.depth=0,this.markers=[],this.pos=0,this.indent=0,this.next=-1}forward(){this.basePos>this.pos&&this.forwardInner()}forwardInner(){let t=this.skipSpace(this.basePos);this.indent=this.countIndent(t,this.pos,this.indent),this.pos=t,this.next=t==this.text.length?-1:this.text.charCodeAt(t)}skipSpace(t){return B0(this.text,t)}reset(t){for(this.text=t,this.baseIndent=this.basePos=this.pos=this.indent=0,this.forwardInner(),this.depth=1;this.markers.length;)this.markers.pop()}moveBase(t){this.basePos=t,this.baseIndent=this.countIndent(t,this.pos,this.indent)}moveBaseColumn(t){this.baseIndent=t,this.basePos=this.findColumn(t)}addMarker(t){this.markers.push(t)}countIndent(t,n=0,r=0){for(let i=n;i<t;i++)r+=this.text.charCodeAt(i)==9?4-r%4:1;return r}findColumn(t){let n=0;for(let r=0;n<this.text.length&&r<t;n++)r+=this.text.charCodeAt(n)==9?4-r%4:1;return n}scrub(){if(!this.baseIndent)return this.text;let t="";for(let n=0;n<this.basePos;n++)t+=" ";return t+this.text.slice(this.basePos)}};function lV(e,t,n){if(n.pos==n.text.length||e!=t.block&&n.indent>=t.stack[n.depth+1].value+n.baseIndent)return!0;if(n.indent>=n.baseIndent+4)return!1;let r=(e.type==De.OrderedList?k8:Q8)(n,t,!1);return r>0&&(e.type!=De.BulletList||x8(n,t,!1)<0)&&n.text.charCodeAt(n.pos+r-1)==e.value}const u0e={[De.Blockquote](e,t,n){return n.next!=62?!1:(n.markers.push(bn(De.QuoteMark,t.lineStart+n.pos,t.lineStart+n.pos+1)),n.moveBase(n.pos+(Ts(n.text.charCodeAt(n.pos+1))?2:1)),e.end=t.lineStart+n.text.length,!0)},[De.ListItem](e,t,n){return n.indent<n.baseIndent+e.value&&n.next>-1?!1:(n.moveBaseColumn(n.baseIndent+e.value),!0)},[De.OrderedList]:lV,[De.BulletList]:lV,[De.Document](){return!0}};function Ts(e){return e==32||e==9||e==10||e==13}function B0(e,t=0){for(;t<e.length&&Ts(e.charCodeAt(t));)t++;return t}function cV(e,t,n){for(;t>n&&Ts(e.charCodeAt(t-1));)t--;return t}function O0e(e){if(e.next!=96&&e.next!=126)return-1;let t=e.pos+1;for(;t<e.text.length&&e.text.charCodeAt(t)==e.next;)t++;if(t<e.pos+3)return-1;if(e.next==96){for(let n=t;n<e.text.length;n++)if(e.text.charCodeAt(n)==96)return-1}return t}function d0e(e){return e.next!=62?-1:e.text.charCodeAt(e.pos+1)==32?2:1}function x8(e,t,n){if(e.next!=42&&e.next!=45&&e.next!=95)return-1;let r=1;for(let i=e.pos+1;i<e.text.length;i++){let a=e.text.charCodeAt(i);if(a==e.next)r++;else if(!Ts(a))return-1}return n&&e.next==45&&p0e(e)>-1&&e.depth==t.stack.length&&t.parser.leafBlockParsers.indexOf(y0e.SetextHeading)>-1||r<3?-1:1}function f0e(e,t){for(let n=e.stack.length-1;n>=0;n--)if(e.stack[n].type==t)return!0;return!1}function Q8(e,t,n){return(e.next==45||e.next==43||e.next==42)&&(e.pos==e.text.length-1||Ts(e.text.charCodeAt(e.pos+1)))&&(!n||f0e(t,De.BulletList)||e.skipSpace(e.pos+2)<e.text.length)?1:-1}function k8(e,t,n){let r=e.pos,i=e.next;for(;i>=48&&i<=57;){r++;if(r==e.text.length)return-1;i=e.text.charCodeAt(r)}return r==e.pos||r>e.pos+9||i!=46&&i!=41||r<e.text.length-1&&!Ts(e.text.charCodeAt(r+1))||n&&!f0e(t,De.OrderedList)&&(e.skipSpace(r+1)==e.text.length||r>e.pos+1||e.next!=49)?-1:r+1-e.pos}function h0e(e){if(e.next!=35)return-1;let t=e.pos+1;for(;t<e.text.length&&e.text.charCodeAt(t)==35;)t++;if(t<e.text.length&&e.text.charCodeAt(t)!=32)return-1;let n=t-e.pos;return n>6?-1:n}function p0e(e){if(e.next!=45&&e.next!=61||e.indent>=e.baseIndent+4)return-1;let t=e.pos+1;for(;t<e.text.length&&e.text.charCodeAt(t)==e.next;)t++;let n=t;for(;t<e.text.length&&Ts(e.text.charCodeAt(t));)t++;return t==e.text.length?n:-1}const rC=/^[ \t]*$/,m0e=/-->/,g0e=/\?>/,iC=[[/^<(?:script|pre|style)(?:\s|>|$)/i,/<\/(?:script|pre|style)>/i],[/^\s*<!--/,m0e],[/^\s*<\?/,g0e],[/^\s*<![A-Z]/,/>/],[/^\s*<!\[CDATA\[/,/\]\]>/],[/^\s*<\/?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h1|h2|h3|h4|h5|h6|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?:\s|\/?>|$)/i,rC],[/^\s*(?:<\/[a-z][\w-]*\s*>|<[a-z][\w-]*(\s+[a-z:_][\w-.]*(?:\s*=\s*(?:[^\s"'=<>`]+|'[^']*'|"[^"]*"))?)*\s*>)\s*$/i,rC]];function $0e(e,t,n){if(e.next!=60)return-1;let r=e.text.slice(e.pos);for(let i=0,a=iC.length-(n?1:0);i<a;i++)if(iC[i][0].test(r))return i;return-1}function uV(e,t){let n=e.countIndent(t,e.pos,e.indent),r=e.countIndent(e.skipSpace(t),t,n);return r>=n+5?n+1:r}function dd(e,t,n){let r=e.length-1;r>=0&&e[r].to==t&&e[r].type==De.CodeText?e[r].to=n:e.push(bn(De.CodeText,t,n))}const aw={LinkReference:void 0,IndentedCode(e,t){let n=t.baseIndent+4;if(t.indent<n)return!1;let r=t.findColumn(n),i=e.lineStart+r,a=e.lineStart+t.text.length,o=[],s=[];for(dd(o,i,a);e.nextLine()&&t.depth>=e.stack.length;)if(t.pos==t.text.length){dd(s,e.lineStart-1,e.lineStart);for(let l of t.markers)s.push(l)}else{if(t.indent<n)break;{if(s.length){for(let c of s)c.type==De.CodeText?dd(o,c.from,c.to):o.push(c);s=[]}dd(o,e.lineStart-1,e.lineStart);for(let c of t.markers)o.push(c);a=e.lineStart+t.text.length;let l=e.lineStart+t.findColumn(t.baseIndent+4);l<a&&dd(o,l,a)}}return s.length&&(s=s.filter(l=>l.type!=De.CodeText),s.length&&(t.markers=s.concat(t.markers))),e.addNode(e.buffer.writeElements(o,-i).finish(De.CodeBlock,a-i),i),!0},FencedCode(e,t){let n=O0e(t);if(n<0)return!1;let r=e.lineStart+t.pos,i=t.next,a=n-t.pos,o=t.skipSpace(n),s=cV(t.text,t.text.length,o),l=[bn(De.CodeMark,r,r+a)];o<s&&l.push(bn(De.CodeInfo,e.lineStart+o,e.lineStart+s));for(let c=!0;e.nextLine()&&t.depth>=e.stack.length;c=!1){let u=t.pos;if(t.indent-t.baseIndent<4)for(;u<t.text.length&&t.text.charCodeAt(u)==i;)u++;if(u-t.pos>=a&&t.skipSpace(u)==t.text.length){for(let O of t.markers)l.push(O);l.push(bn(De.CodeMark,e.lineStart+t.pos,e.lineStart+u)),e.nextLine();break}else{c||dd(l,e.lineStart-1,e.lineStart);for(let f of t.markers)l.push(f);let O=e.lineStart+t.basePos,d=e.lineStart+t.text.length;O<d&&dd(l,O,d)}}return e.addNode(e.buffer.writeElements(l,-r).finish(De.FencedCode,e.prevLineEnd()-r),r),!0},Blockquote(e,t){let n=d0e(t);return n<0?!1:(e.startContext(De.Blockquote,t.pos),e.addNode(De.QuoteMark,e.lineStart+t.pos,e.lineStart+t.pos+1),t.moveBase(t.pos+n),null)},HorizontalRule(e,t){if(x8(t,e,!1)<0)return!1;let n=e.lineStart+t.pos;return e.nextLine(),e.addNode(De.HorizontalRule,n),!0},BulletList(e,t){let n=Q8(t,e,!1);if(n<0)return!1;e.block.type!=De.BulletList&&e.startContext(De.BulletList,t.basePos,t.next);let r=uV(t,t.pos+1);return e.startContext(De.ListItem,t.basePos,r-t.baseIndent),e.addNode(De.ListMark,e.lineStart+t.pos,e.lineStart+t.pos+n),t.moveBaseColumn(r),null},OrderedList(e,t){let n=k8(t,e,!1);if(n<0)return!1;e.block.type!=De.OrderedList&&e.startContext(De.OrderedList,t.basePos,t.text.charCodeAt(t.pos+n-1));let r=uV(t,t.pos+n);return e.startContext(De.ListItem,t.basePos,r-t.baseIndent),e.addNode(De.ListMark,e.lineStart+t.pos,e.lineStart+t.pos+n),t.moveBaseColumn(r),null},ATXHeading(e,t){let n=h0e(t);if(n<0)return!1;let r=t.pos,i=e.lineStart+r,a=cV(t.text,t.text.length,r),o=a;for(;o>r&&t.text.charCodeAt(o-1)==t.next;)o--;(o==a||o==r||!Ts(t.text.charCodeAt(o-1)))&&(o=t.text.length);let s=e.buffer.write(De.HeaderMark,0,n).writeElements(e.parser.parseInline(t.text.slice(r+n+1,o),i+n+1),-i);o<t.text.length&&s.write(De.HeaderMark,o-r,a-r);let l=s.finish(De.ATXHeading1-1+n,t.text.length-r);return e.nextLine(),e.addNode(l,i),!0},HTMLBlock(e,t){let n=$0e(t,e,!1);if(n<0)return!1;let r=e.lineStart+t.pos,i=iC[n][1],a=[],o=i!=rC;for(;!i.test(t.text)&&e.nextLine();){if(t.depth<e.stack.length){o=!1;break}for(let c of t.markers)a.push(c)}o&&e.nextLine();let s=i==m0e?De.CommentBlock:i==g0e?De.ProcessingInstructionBlock:De.HTMLBlock,l=e.prevLineEnd();return e.addNode(e.buffer.writeElements(a,-r).finish(s,l-r),r),!0},SetextHeading:void 0};class Cot{constructor(t){this.stage=0,this.elts=[],this.pos=0,this.start=t.start,this.advance(t.content)}nextLine(t,n,r){if(this.stage==-1)return!1;let i=r.content+`
833
833
  `+n.scrub(),a=this.advance(i);return a>-1&&a<i.length?this.complete(t,r,a):!1}finish(t,n){return(this.stage==2||this.stage==3)&&B0(n.content,this.pos)==n.content.length?this.complete(t,n,n.content.length):!1}complete(t,n,r){return t.addLeafElement(n,bn(De.LinkReference,this.start,this.start+r,this.elts)),!0}nextStage(t){return t?(this.pos=t.to-this.start,this.elts.push(t),this.stage++,!0):(t===!1&&(this.stage=-1),!1)}advance(t){for(;;){if(this.stage==-1)return-1;if(this.stage==0){if(!this.nextStage(_0e(t,this.pos,this.start,!0)))return-1;if(t.charCodeAt(this.pos)!=58)return this.stage=-1;this.elts.push(bn(De.LinkMark,this.pos+this.start,this.pos+this.start+1)),this.pos++}else if(this.stage==1){if(!this.nextStage(k0e(t,B0(t,this.pos),this.start)))return-1}else if(this.stage==2){let n=B0(t,this.pos),r=0;if(n>this.pos){let i=P0e(t,n,this.start);if(i){let a=WT(t,i.to-this.start);a>0&&(this.nextStage(i),r=a)}}return r||(r=WT(t,this.pos)),r>0&&r<t.length?r:-1}else return WT(t,this.pos)}}}function WT(e,t){for(;t<e.length;t++){let n=e.charCodeAt(t);if(n==10)break;if(!Ts(n))return-1}return t}class Aot{nextLine(t,n,r){let i=n.depth<t.stack.length?-1:p0e(n),a=n.next;if(i<0)return!1;let o=bn(De.HeaderMark,t.lineStart+n.pos,t.lineStart+i);return t.nextLine(),t.addLeafElement(r,bn(a==61?De.SetextHeading1:De.SetextHeading2,r.start,t.prevLineEnd(),[...t.parser.parseInline(r.content,r.start),o])),!0}finish(){return!1}}const y0e={LinkReference(e,t){return t.content.charCodeAt(0)==91?new Cot(t):null},SetextHeading(){return new Aot}},zot=[(e,t)=>h0e(t)>=0,(e,t)=>O0e(t)>=0,(e,t)=>d0e(t)>=0,(e,t)=>Q8(t,e,!0)>=0,(e,t)=>k8(t,e,!0)>=0,(e,t)=>x8(t,e,!0)>=0,(e,t)=>$0e(t,e,!0)>=0],Uot={text:"",end:0};class Wot{constructor(t,n,r,i){this.parser=t,this.input=n,this.ranges=i,this.line=new jot,this.atEnd=!1,this.reusePlaceholders=new Map,this.stoppedAt=null,this.rangeI=0,this.to=i[i.length-1].to,this.lineStart=this.absoluteLineStart=this.absoluteLineEnd=i[0].from,this.block=rx.create(De.Document,0,this.lineStart,0,0),this.stack=[this.block],this.fragments=r.length?new Iot(r,n):null,this.readLine()}get parsedPos(){return this.absoluteLineStart}advance(){if(this.stoppedAt!=null&&this.absoluteLineStart>this.stoppedAt)return this.finish();let{line:t}=this;for(;;){for(let r=0;;){let i=t.depth<this.stack.length?this.stack[this.stack.length-1]:null;for(;r<t.markers.length&&(!i||t.markers[r].from<i.end);){let a=t.markers[r++];this.addNode(a.type,a.from,a.to)}if(!i)break;this.finishContext()}if(t.pos<t.text.length)break;if(!this.nextLine())return this.finish()}if(this.fragments&&this.reuseFragment(t.basePos))return null;e:for(;;){for(let r of this.parser.blockParsers)if(r){let i=r(this,t);if(i!=!1){if(i==!0)return null;t.forward();continue e}}break}let n=new qot(this.lineStart+t.pos,t.text.slice(t.pos));for(let r of this.parser.leafBlockParsers)if(r){let i=r(this,n);i&&n.parsers.push(i)}e:for(;this.nextLine()&&t.pos!=t.text.length;){if(t.indent<t.baseIndent+4){for(let r of this.parser.endLeafBlock)if(r(this,t,n))break e}for(let r of n.parsers)if(r.nextLine(this,t,n))return null;n.content+=`
834
834
  `+t.scrub();for(let r of t.markers)n.marks.push(r)}return this.finishLeaf(n),null}stopAt(t){if(this.stoppedAt!=null&&this.stoppedAt<t)throw new RangeError("Can't move stoppedAt forward");this.stoppedAt=t}reuseFragment(t){if(!this.fragments.moveTo(this.absoluteLineStart+t,this.absoluteLineStart)||!this.fragments.matches(this.block.hash))return!1;let n=this.fragments.takeNodes(this);return n?(this.absoluteLineStart+=n,this.lineStart=T0e(this.absoluteLineStart,this.ranges),this.moveRangeI(),this.absoluteLineStart<this.to?(this.lineStart++,this.absoluteLineStart++,this.readLine()):(this.atEnd=!0,this.readLine()),!0):!1}get depth(){return this.stack.length}parentType(t=this.depth-1){return this.parser.nodeSet.types[this.stack[t].type]}nextLine(){return this.lineStart+=this.line.text.length,this.absoluteLineEnd>=this.to?(this.absoluteLineStart=this.absoluteLineEnd,this.atEnd=!0,this.readLine(),!1):(this.lineStart++,this.absoluteLineStart=this.absoluteLineEnd+1,this.moveRangeI(),this.readLine(),!0)}peekLine(){return this.scanLine(this.absoluteLineEnd+1).text}moveRangeI(){for(;this.rangeI<this.ranges.length-1&&this.absoluteLineStart>=this.ranges[this.rangeI].to;)this.rangeI++,this.absoluteLineStart=Math.max(this.absoluteLineStart,this.ranges[this.rangeI].from)}scanLine(t){let n=Uot;if(n.end=t,t>=this.to)n.text="";else if(n.text=this.lineChunkAt(t),n.end+=n.text.length,this.ranges.length>1){let r=this.absoluteLineStart,i=this.rangeI;for(;this.ranges[i].to<n.end;){i++;let a=this.ranges[i].from,o=this.lineChunkAt(a);n.end=a+o.length,n.text=n.text.slice(0,this.ranges[i-1].to-r)+o,r=n.end-n.text.length}}return n}readLine(){let{line:t}=this,{text:n,end:r}=this.scanLine(this.absoluteLineStart);for(this.absoluteLineEnd=r,t.reset(n);t.depth<this.stack.length;t.depth++){let i=this.stack[t.depth],a=this.parser.skipContextMarkup[i.type];if(!a)throw new Error("Unhandled block context "+De[i.type]);if(!a(i,this,t))break;t.forward()}}lineChunkAt(t){let n=this.input.chunk(t),r;if(this.input.lineChunks)r=n==`
835
835
  `?"":n;else{let i=n.indexOf(`
@@ -863,7 +863,7 @@ l0,-`+(n+144)+`c-2,-159.3,-10,-310.7,-24,-454c-53.3,-528,-210,-949.7,
863
863
  `,o.end),l=t.slice(o.end,s===-1?t.length:s);if(l2t.test(l))return eo;const c=l.length-l.replace(c2t,"").length,u={start:o.start,end:o.end+c},O=e.typingAt;if(O!==null){const d=O+Kp(e.value).length;return n<O||n>d?{arm:u,typingAt:null,value:""}:{arm:u,typingAt:O,value:e.value}}return a&&n===u.end&&t[n-1]===kP?{arm:u,typingAt:n,value:""}:{arm:u,typingAt:null,value:""}}const ql=e=>e.typingAt!==null,h2t=e=>e.arm!==null;function Jf(e){return e.typingAt===null?null:{start:e.typingAt,end:e.typingAt+Kp(e.value).length}}function PU(e,t,n,r){const i=Jf(e);if(i===null)return null;const{top:a,bottom:o,inserted:s}=r;if(a>i.end||o<i.start)return null;const l=Kp(e.value),c=s7(a-i.start,0,l.length),u=s7(o-i.start,0,l.length),O=Kp(s),d=[...l.slice(0,c),...O,...l.slice(u)].join(""),f=a+O.length,p=t.slice(0,a)+uxe.repeat(O.length)+t.slice(f),m=O.length-s.length,g=n>=f?n+m:n;return{buffer:p,caret:g,capture:{...e,value:d}}}function UH(e,t,n,r){const i={capture:e,buffer:t.slice(0,n.start)+r+t.slice(n.end),caret:n.start+r.length},a=ql(e)&&e.value===""&&r.startsWith("-");if(ql(e)&&(a||r.includes(`
864
864
  `))){const o=Ex(e);return r.includes(`
865
865
  `)?{...i,capture:o}:{...i,capture:Jh(o,i.buffer,i.caret,"typing")}}return PU(e,i.buffer,i.caret,{top:n.start,bottom:n.end,inserted:r})??i}function Ex(e){return ql(e)?{arm:e.arm,typingAt:null,value:""}:e}function p2t(e,t){let n=0;const r=Math.min(e.length,t.length);for(;n<r&&e[n]===t[n];)n++;let i=e.length,a=t.length;for(;i>n&&a>n&&e[i-1]===t[a-1];)i--,a--;return{top:n,bottom:i,inserted:t.slice(n,a)}}function m2t(e,t,n,r,i){const a=p2t(t,n),o=Jf(e);let s={capture:e,buffer:n,caret:r};if(a.inserted!==""&&o!==null&&a.top<=o.end&&a.bottom>=o.start)s={capture:Ex(e),buffer:n,caret:r};else{const l=PU(e,n,r,a);l?s=l:ql(e)&&a.inserted.includes(`
866
- `)&&(s={capture:Ex(e),buffer:n,caret:r})}return{...s,capture:Jh(s.capture,s.buffer,s.caret,i)}}function g2t(e){const{capture:t,buffer:n,caret:r,index:i,taken:a}=e,o=Jf(t);if(o===null||t.value==="")return{minted:!1,capture:t,buffer:n,caret:r,payload:null};const s=t.arm===null?o.start:t.arm.start,l=yxe(i,t.value),c=l+kP,u=n.slice(0,s)+c+n.slice(o.end);return{minted:!0,capture:eo,buffer:u,caret:s+c.length,payload:{index:i,key:Sxe(a,e.draw),value:t.value,marker:l}}}function $2t(e,t){const n=Jf(e);if(n===null)return{cancelled:!1,capture:e,buffer:t,caret:0,restored:0,token:null};const r=e.value,i=wxe(t,e),a=e.arm===null?n.start:e.arm.start;return{cancelled:!0,capture:eo,buffer:i,caret:n.start+r.length,restored:o7(r),token:{span:{start:a,end:n.start},text:t.slice(a,n.start),restored:o7(r),restoredText:r}}}function WH(e,t){return t===null||t.text.length===0?!1:e.slice(t.span.start,t.span.start+t.text.length)===t.text}function y2t(e,t,n,r){const i=t.slice(0,n.start)+r+t.slice(n.end),a=n.start+r.length,o=Jf(e);return o===null?{kind:"passthrough",capture:e,buffer:i,caret:a,payload:null}:n.start<=o.start?{kind:"passthrough",capture:{...e,typingAt:o.start+r.length},buffer:i,caret:a,payload:null}:n.start>=o.end?{kind:"passthrough",capture:e,buffer:i,caret:a,payload:null}:{kind:"passthrough",capture:Ex(e),buffer:i,caret:a,payload:null}}function v2t(e){const{capture:t,buffer:n,caret:r,pasted:i}=e;if(t.arm===null)return null;if(t.typingAt!==null&&t.value!==""){if(i==="")return null;const u=PU(t,n,r,{top:e.selection.start,bottom:e.selection.end,inserted:i});return u===null?null:{kind:"masked",...u,payload:null}}const a=on(i);if(!a)return i===""?null:y2t(t,n,e.selection,i);const o=t.arm,s=yxe(e.index,a),l=s+kP,c=n.slice(0,o.start)+l+n.slice(o.end);return{kind:"minted",capture:eo,buffer:c,caret:o.start+l.length,payload:{index:e.index,key:Sxe(e.taken,e.draw),value:a,marker:s}}}const $xe=e=>`${o7(e)} chars`,yxe=(e,t)=>`[Credential #${e}, ${$xe(t)}]`;function b2t(e){Dl.lastIndex=0;const t=Dl.exec(e);return Dl.lastIndex=0,t===null||t[0]!==e?null:Number.parseInt(t[1],10)}function w2t(e){Dl.lastIndex=0;const t=Dl.exec(e);if(Dl.lastIndex=0,t===null||t[0]!==e)return null;const n=Number.parseInt(t[1],10);return{index:n,label:`#${n}`,chars:Number.parseInt(t[2],10)}}function Zv(e,t){if(b2t(t.marker)!==t.index)return null;const n=e.indexOf(t.marker);return n===-1?null:{start:n,end:n+t.marker.length}}const aR=/\[credential ([A-Za-z_][A-Za-z0-9_]*) \((\d+) chars\) \u2014 available to bash and eval as \$([A-Za-z_][A-Za-z0-9_]*); its value cannot be read\]/y,oR=/\[credential NOT stored \u2014 [^\]\n]*\]/y,sR=/\[credential unconfirmed \u2014 [^\]\n]*\]/y,S2t=e=>{const t=/\$([A-Z0-9_]+)/.exec(e);return t!==null&&a7.test(t[1])?t[1]:""};function x2t(e,t){if(e.charCodeAt(t)!==91)return null;aR.lastIndex=t;const n=aR.exec(e);if(aR.lastIndex=0,n!==null&&n[1]===n[3])return{kind:"stored",text:n[0],key:n[1],chars:Number.parseInt(n[2],10)};oR.lastIndex=t;const r=oR.exec(e);if(oR.lastIndex=0,r!==null)return{kind:"unstored",text:r[0]};sR.lastIndex=t;const i=sR.exec(e);return sR.lastIndex=0,i!==null?{kind:"unconfirmed",text:i[0],key:S2t(i[0])}:null}function PP(e){const t=[];let n=0,r=0;for(;r<e.length;){const i=x2t(e,r);if(i===null){r++;continue}r>n&&t.push({kind:"text",text:e.slice(n,r)}),t.push(i),r+=i.text.length,n=r}return n<e.length&&t.push({kind:"text",text:e.slice(n)}),t}function NH(e,t){const n=[];for(const r of t){const i=Zv(e,r);i!==null&&n.push({at:i.start,payload:r})}return n.sort((r,i)=>r.at-i.at).map(r=>r.payload)}function Q2t(e,t=""){return e==="unconfirmed"?t?`[credential unconfirmed — it may be held as $${t}, so check list_variables before assuming it is missing]`:"[credential unconfirmed — the session may hold it, so check list_variables before assuming it is missing]":e==="unreachable"?"[credential NOT stored — the session could not be reached; try again]":e==="rejected-key"?"[credential NOT stored — the store rejected its name]":"[credential NOT stored — its value did not survive; ask the operator to paste it again]"}const k2t=e=>`[credential ${e.key} (${$xe(e.value)}) — available to bash and eval as $${e.key}; its value cannot be read]`;function P2t(e,t,n=new Map){const r=[...t],i=[];for(const o of r){const s=Zv(e,o);s!==null&&i.push({span:s,payload:o})}for(const o of hxe(e,r))i.push({span:o,payload:null});let a=e;for(const{span:o,payload:s}of i.sort((l,c)=>c.span.start-l.span.start)){const l=s===null?"lost":n.get(s.index),c=s===null||l!==void 0?Q2t(l??"lost",s?.key):k2t(s);a=a.slice(0,o.start)+c+a.slice(o.end)}return a}const _2t=(e,t,n)=>`Removed ${e} (credential #${t}) from this message. Its value is gone — press ${n} to put it back, or paste it again after /credential to reuse it.`,T2t=e=>`Remove credential #${e}`,R2t=(e,t)=>`Credential #${e}, ${t} chars — held in this message; its value cannot be read`,X2t=(e,t,n)=>_2t(e,t,n),E2t="Undo",q2t=e=>`Credential #${e} removed`,j2t=e=>e.unredacted!==null?e.unredacted:e.armed?Y2t:e.cleared!==null?X2t(e.cleared.key,e.cleared.index,e.undoCap):null;function C2t(e){const{buffer:t,payload:n}=e,r=Zv(t,n);if(r===null)return{cleared:!1,buffer:t,caret:t.length,removed:""};const i=t[r.end]===kP?r.end+1:r.end;return{cleared:!0,buffer:t.slice(0,r.start)+t.slice(i),caret:r.start,removed:t.slice(r.start,i)}}function A2t(e){const{buffer:t,cleared:n}=e;return n.removed===""||t!==n.buffer?null:{buffer:t.slice(0,n.caret)+n.removed+t.slice(n.caret),caret:n.caret+n.removed.length}}const YH=e=>`Stored ${e.join(", ")}. Injected into every bash command as an environment variable; the agent cannot read the value.`;function GH(e){const t=e.length===1?"credential":"credentials";return`${e.length} ${t} could not be stored (${[...e].sort().join(", ")}); the agent has been told so. Paste the value again after /credential to retry.`}const z2t="store unconfirmed",U2t="Credential store unconfirmed",W2t=e=>e===""?U2t:`${e} · ${z2t}`,vxe="Paste the value again after /credential to store it again.",N2t=e=>`${e} ${vxe}`;function IH(e){const t=e.length===1?"credential":"credentials";return`${e.length} ${t} could not be confirmed as stored (${[...e].sort().join(", ")}); the agent has been told to check before using it. ${vxe}`}const Y2t="armed — add a space, then type or paste the secret",G2t="masked as you type — Enter turns it into a pill, Esc cancels",I2t="masked — Enter opens the credential picker; type or paste the secret into this span",Z2t="masked — Enter runs /credential, which needs an open conversation; type or paste the secret into this span",bxe="\0held",D2t=(e,t)=>t===void 0?`${e} characters are now PLAIN TEXT in the composer — Enter will expose them`:t===bxe?`${e} characters are now PLAIN TEXT in the composer — Enter is held: clear the box to release your words`:`${e} characters are now PLAIN TEXT in the composer — Enter will take them as /${t}'s argument, not send them`;function wxe(e,t){const n=Jf(t);return n===null?e:e.slice(0,n.start)+t.value+e.slice(n.end)}const ZH=(e,t)=>e&&e.over===t?e.chars:null,M2t=e=>{const t=Math.floor(4294967296/e)*e,n=new Uint32Array(1);for(;;)if(globalThis.crypto.getRandomValues(n),n[0]<t)return n[0]%e},V2t=16,L2t=16;function Sxe(e=[],t=M2t){const n=new Set(e);for(let r=0;r<V2t;r++){const i=AH+DH(8,t);if(!n.has(i))return i}return AH+DH(L2t,t)}const DH=(e,t)=>{let n="";for(let r=0;r<e;r++)n+=CH[t(CH.length)];return n},F2t=8,B2t=256,H2t=/^[/@$#]/,K2t=/^\w+:\/\//,J2t=/^[A-Za-z]+$/,eRt=/^\d+$/,tRt=[/[a-z]/,/[A-Z]/,/\d/,/[^A-Za-z0-9]/],nRt=3,rRt=20,iRt=/^[A-Za-z0-9_\-+/=.]+$/,aRt=new RegExp(`^[^${ba}@]+@[^${ba}@]+\\.[A-Za-z]{2,}$`),oRt=/^[\w.-]+(?:\/[\w.-]+)+$/,sRt=/\.[A-Za-z][A-Za-z0-9]{0,7}$/,lRt=/^v?\d+(?:\.\d+)+(?:[-+][0-9A-Za-z.-]+)?$/,cRt=/^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/,uRt=/^[\w.-]+:\d{2,5}$/,ORt=/^(?:[0-9a-f]{7,12}|[0-9a-f]{40})$/i,dRt=/^[a-z]+(?:_[a-z]+)+$/,fRt=/^[a-z]+(?:-[a-z]+)+$/,hRt=/^[a-z][a-z0-9]*(?:[A-Z][a-z0-9]+)+$/,pRt=/^[a-z0-9]+(?:-[a-z0-9]+)+$/,mRt=/\d{4,}/,gRt=e=>{const t=e.trim();return t.length<F2t||t.length>B2t||Zo.test(t)||H2t.test(t)||K2t.test(t)||oOe(t)!==null||aRt.test(t)||oRt.test(t)||sRt.test(t)||lRt.test(t)||cRt.test(t)||uRt.test(t)||ORt.test(t)||dRt.test(t)||fRt.test(t)||hRt.test(t)||pRt.test(t)&&mRt.test(t)||J2t.test(t)||eRt.test(t)?!1:tRt.filter(r=>r.test(t)).length>=nRt?!0:t.length>=rRt&&iRt.test(t)},xxe=q("rounded-xs bg-info-wash","outline-1 outline-solid outline-info-border","box-decoration-clone"),Qxe=q("rounded-xs bg-warning-wash","outline-1 outline-dashed outline-warning-border","box-decoration-clone"),kxe=({label:e,chars:t=null,tone:n="live",title:r,onClear:i,clearLabel:a,className:o,style:s,small:l=!1})=>h.jsxs("span",{className:q("inline-flex max-w-full items-center justify-between gap-1.5 px-3 text-ink",n==="warning"?Qxe:xxe,l?"text-body-sm":"text-body",o),title:r,style:s,children:[n==="warning"?h.jsx(ole,{"aria-hidden":"true",className:"size-3 shrink-0"}):h.jsx(Yze,{"aria-hidden":"true",className:"size-3 shrink-0"}),h.jsx("span",{className:"min-w-0 truncate",children:e}),t!==null&&h.jsx("span",{className:"shrink-0",children:`· ${t} chars`}),i&&h.jsx("button",{type:"button","aria-label":a,onClick:i,className:"pointer-events-auto -mr-1 flex shrink-0 cursor-pointer items-center rounded-xs p-0.5 text-ink-muted hover:bg-elevated hover:text-ink focus-visible:outline-offset-1! active:bg-sunken",children:h.jsx(ea,{"aria-hidden":"true",className:"size-3"})}),r&&h.jsx("span",{className:"sr-only",children:r})]}),py="#lo-credential/",$Rt=`${py}unstored`,MH=`${py}unconfirmed`,yRt=/^\d+$/,Pxe=e=>e.kind==="stored"?`${py}${e.key??""}/${e.chars??0}`:e.kind==="unconfirmed"?e.key?`${MH}/${e.key}`:MH:$Rt;function vRt(e){if(!e||!e.startsWith(py))return null;const t=e.slice(py.length);if(t==="unstored")return{kind:"unstored"};if(t==="unconfirmed")return{kind:"unconfirmed",key:""};if(t.startsWith("unconfirmed/")){const a=t.slice(12);return a7.test(a)?{kind:"unconfirmed",key:a}:null}const n=t.lastIndexOf("/");if(n===-1)return null;const r=t.slice(0,n),i=t.slice(n+1);return!a7.test(r)||!yRt.test(i)?null:{kind:"stored",key:r,chars:Number.parseInt(i,10)}}function VH(e,t){const n=vRt(e);if(n===null)return null;const r=PP(t);if(r.length!==1||r[0].kind==="text")return null;const i=r[0];return Pxe(i)!==e?null:n}const _P=()=>e=>{const t=n=>{if(!n.children)return;const r=[];let i=!1;for(const a of n.children){if(a.type!=="text"||typeof a.value!="string"){t(a),r.push(a);continue}const o=PP(a.value);if(o.length===1&&o[0].kind==="text"){r.push(a);continue}i=!0;for(const s of o){if(s.kind==="text"){r.push({type:"text",value:s.text});continue}r.push({type:"link",url:Pxe(s),title:s.text,children:[{type:"text",value:s.text}]})}}i&&(n.children=r)};t(e)},bRt=e=>e.kind==="stored"?e.key:e.kind==="unconfirmed"?W2t(e.key):"Credential not stored",wRt=(e,t)=>e.kind==="unconfirmed"&&t!==void 0?N2t(t):t,SRt=({citation:e,title:t})=>h.jsx(kxe,{tone:e.kind==="stored"?"live":"warning",label:bRt(e),chars:e.kind==="stored"?e.chars:null,title:wRt(e,t),className:"align-middle"}),xRt=(e,t)=>typeof t=="string"?VH(e,t):t==null?VH(e,""):null,QRt=e=>({href:t,title:n,children:r})=>{const i=xRt(t,r);if(i===null){const a=e;return h.jsx(a,{href:t,title:n,children:r})}return h.jsx(SRt,{citation:i,title:n})},_xe=e=>$tt(e)?"artifact":e.startsWith("data:")?"data":e.startsWith("blob:")?"blob":e.startsWith("http://")||e.startsWith("https://")?"http":e.startsWith("file://")||e.startsWith("/")||e.startsWith("~")?"path":"other",Txe=e=>{const t=_xe(e);return t==="other"?"path":t},LH={id:"open-file",label:"Open file"},kRt={id:"show-in-canvas",label:"Show in canvas"},PRt={id:"save-as",label:"Save as…"},FH={id:"open-folder",label:"Open folder"},BH={id:"copy-file-path",label:"Copy file path"},Mg={id:"copy-image",label:"Copy image"},_Rt={id:"copy-image-url",label:"Copy image URL"},TRt={id:"open-in-browser",label:"Open in browser"};function Rxe(e,{canShowInCanvas:t,source:n,mediaKind:r,artifactPathActions:i,canExpand:a}){const o=[...t?[kRt]:[],...a?[{id:"expand-image",label:"Expand image"}]:[]];switch(e){case"artifact":return[...o,...i?[LH,FH,BH]:[],PRt,...r==="video"||r==="audio"?[]:[Mg]];case"path":return[...o,LH,FH,BH,...r==="video"||r==="audio"?[]:[Mg]];case"data":return[...o,Mg];case"blob":return[Mg];case"http":return[...RRt(n)?[Mg]:[],_Rt,TRt];case"other":return[]}}const Xxe=(e,t)=>Rxe(e,t).length>0;function RRt(e){try{const t=new URL(e),n=t.hostname==="localhost"||t.hostname==="127.0.0.1";return t.protocol==="http:"&&n&&(t.port==="1111"||t.port==="8080")}catch{return!1}}const _U=e=>e.startsWith("file://")?e.slice(7):e;function XRt(e){const t=e.indexOf(",");if(t===-1)throw new Error("Malformed data URL");const n=e.slice(5,t),r=e.slice(t+1),i=n.split(";")[0]||"application/octet-stream";if(n.endsWith(";base64")){const s=atob(r),l=new Uint8Array(s.length);for(let c=0;c<s.length;c+=1)l[c]=s.charCodeAt(c);return new Blob([l],{type:i})}const a=decodeURIComponent(r),o=new Uint8Array(a.length);for(let s=0;s<a.length;s+=1)o[s]=a.charCodeAt(s);return new Blob([o],{type:i})}async function HH(e,t,n){if(e==="data")return XRt(t);if(e==="blob"){const o=ife(n??t);if(o===null)throw new Error("These image bytes are not available in this window");return o}if(e==="http"){const o=await fetch(n??t);if(!o.ok)throw new Error(`The image server answered ${o.status}`);return o.blob()}const r=window.api?.readFileBytes;if(typeof r!="function")throw new Error("This window cannot read local files");const i=_U(t),a=await r(i);if(!a.success)throw new Error(a.error??`Could not read ${i}`);return new Blob([a.data],{type:Mz(i)})}const ERt=e=>e.trim().toLowerCase()!=="image/png";async function qRt(e){if(e.size===0)throw new Error("This image has no bytes to copy");if(!ERt(e.type))return e;const t=URL.createObjectURL(e);try{const n=await jRt(t);if(n.naturalWidth===0||n.naturalHeight===0)throw new Error("This image could not be decoded for the clipboard");const r=document.createElement("canvas");r.width=n.naturalWidth,r.height=n.naturalHeight;const i=r.getContext("2d");if(i===null)throw new Error("This window cannot re-encode the image for the clipboard");i.drawImage(n,0,0);const a=await new Promise(o=>{r.toBlob(o,"image/png")});if(a===null)throw new Error("This image could not be re-encoded for the clipboard");return a}finally{URL.revokeObjectURL(t)}}function jRt(e){return new Promise((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=()=>n(new Error("This image could not be decoded for the clipboard")),r.src=e})}const CRt=6e4;function ARt(e,t){const n=URL.createObjectURL(e),r=document.createElement("a");r.href=n,r.download=t,document.body.appendChild(r),r.click(),document.body.removeChild(r),window.setTimeout(()=>URL.revokeObjectURL(n),CRt)}const F1=new Map;function zRt(e,t){const n=F1.get(t);if(n)return n.holders+=1,n.promise;const r={holders:1,promise:null};return r.promise=(async()=>{try{const i=await su(e.childId?{op:"subagents.attachment",sessionId:e.sessionId,childId:e.childId,digest:t}:{op:"sessions.attachment",sessionId:e.sessionId,digest:t},null);if(i.kind!=="bytes")return null;const a=Lz(i.data,i.mimeType);return r.holders<=0?($v(a),null):(afe(t,a),a)}catch{return null}finally{F1.delete(t)}})(),F1.set(t,r),r.promise}class TU extends Error{constructor(){super("This item is no longer in the session"),this.name="AttachmentGoneError"}}async function Exe(e,t){const n=Fz(t),r=n?ife(n):null;if(r)return r;const i=await su(e.childId?{op:"subagents.attachment",sessionId:e.sessionId,childId:e.childId,digest:t}:{op:"sessions.attachment",sessionId:e.sessionId,digest:t},null);if(i.kind!=="bytes")throw i.status===404?new TU:new Error("These bytes are not available right now");return new Blob([i.data],{type:i.mimeType})}function URt(e){const t=F1.get(e);t&&(t.holders-=1)}function Dv(e,t){const n=e.data?`data:${e.mimeType};base64,${e.data}`:null,[r,i]=$.useState(()=>e.attachment?Fz(e.attachment):null),[a,o]=$.useState(!1),s=t?.sessionId??null,l=t?.childId??null;$.useEffect(()=>{const u=e.attachment;if(n||!u||!s)return;let O=!0;const d=_S(u);if(d)return i(d),o(!1),()=>{O=!1,TS(u)};i(null),o(!1);let f=!0;return zRt({sessionId:s,childId:l},u).then(p=>{if(f=!1,!!O){if(!p){o(!0);return}i(_S(u))}}),()=>{O=!1,f&&URt(u),TS(u)}},[e.attachment,n,s,l]);const c=n??r;return c?{state:"ready",url:c}:e.attachment&&s&&!a?{state:"resolving"}:{state:"missing"}}function RU(e,t){return Dv(e,t)}const DOn=Object.freeze(Object.defineProperty({__proto__:null,AttachmentGoneError:TU,fetchAttachmentBlob:Exe,useAttachmentSource:Dv,useAttachmentUrl:RU},Symbol.toStringTag,{value:"Module"})),WRt={"expand-image":h.jsx(Eue,{"aria-hidden":"true"}),"open-file":h.jsx(dv,{"aria-hidden":"true"}),"show-in-canvas":h.jsx(Xue,{"aria-hidden":"true"}),"save-as":h.jsx(Ov,{"aria-hidden":"true"}),"open-folder":h.jsx(Rp,{"aria-hidden":"true"}),"copy-file-path":h.jsx(Que,{"aria-hidden":"true"}),"copy-image":h.jsx(hk,{"aria-hidden":"true"}),"copy-image-url":h.jsx(Dze,{"aria-hidden":"true"}),"open-in-browser":h.jsx(Pue,{"aria-hidden":"true"})},KH=(e,t)=>t instanceof TU?`${e}: it is no longer in the session`:e,qxe=({file:e,src:t,label:n,open:r,onOpenChange:i,onCloseAutoFocus:a,triggerTabIndex:o,resolvePath:s,missing:l,onShowInCanvas:c,mediaKind:u,onExpand:O,saveName:d,resolveBytes:f,tooltip:p="Image actions","aria-label":m})=>{const g=Txe(e),y=Rxe(g,{canShowInCanvas:!!c,source:t??e,mediaKind:u,artifactPathActions:!!s,canExpand:!!O}).filter(x=>(x.id!=="save-as"||!!d)&&(!l||x.id==="copy-file-path"));if(y.length===0)return null;const v=async(x,k,T)=>{try{await navigator.clipboard.writeText(x),Of(k)}catch(_){console.error(`${T}: `,_),mi(T)}},S=async()=>{try{if(typeof ClipboardItem>"u")throw new Error("this window cannot write an image to the clipboard");const x=f?await f():await HH(g,e,t),k=await qRt(x);await navigator.clipboard.write([new ClipboardItem({[k.type]:k})]),Of("Image copied to clipboard")}catch(x){console.error("Failed to copy image: ",x),mi(KH("Failed to copy image",x))}},Q=async()=>{try{const x=f?await f():await HH(g,e,t);ARt(x,d??"download")}catch(x){console.error("Failed to save file: ",x),mi(KH("Failed to save file",x))}},b=async x=>{let k=_U(e);if(s&&["open-file","open-folder","copy-file-path"].includes(x.id))try{k=await s()}catch{mi(J("ui.canvas.files.prepareError"));return}switch(x.id){case"expand-image":O?.();return;case"open-file":AO(k);return;case"open-folder":xU(k);return;case"show-in-canvas":c?.();return;case"copy-file-path":v(k,"File path copied to clipboard","Failed to copy file path");return;case"copy-image":S();return;case"save-as":Q();return;case"copy-image-url":v(t??e,"Image URL copied to clipboard","Failed to copy image URL");return;case"open-in-browser":QU(t??e);return}},w=m??`Actions for ${n??"this image"}`;return h.jsxs(bA,{open:r,onOpenChange:i,children:[h.jsx(Yt,{content:p,children:h.jsx(wA,{asChild:!0,children:h.jsx(Xe,{variant:"ghost",size:"icon-sm",className:"bg-accent-wash","aria-label":w,tabIndex:o,onClick:x=>x.stopPropagation(),children:h.jsx(vj,{"aria-hidden":"true"})})})}),h.jsxs(SA,{onCloseAutoFocus:a,align:"end",className:"min-w-45",onClick:x=>x.stopPropagation(),children:[s&&h.jsx("div",{role:"note",className:q("max-w-64 px-2 py-1 text-meta text-ink-muted"),children:J("ui.canvas.files.pathCopyNote")}),y.map(x=>h.jsxs(jl,{onSelect:()=>b(x),children:[WRt[x.id],h.jsx("span",{children:x.label})]},x.id))]})]})},NRt=({src:e,alt:t,title:n,className:r})=>{const i=SP(),a=e??"",o=_xe(a);if(o==="other")return h.jsx("img",{src:e,alt:t,title:n,className:r});const s=i!==null&&o==="path",l=Xxe(o,{canShowInCanvas:s,source:a});return h.jsxs("span",{className:q("group/mdimg relative inline-block max-w-full"),children:[h.jsx("img",{src:e,alt:t,title:n,className:r}),l&&h.jsx("span",{"data-markdown-image":"",className:q("pointer-events-none absolute top-1 right-1 z-[2] opacity-0","transition-opacity duration-fast ease-out-quart","group-hover/mdimg:pointer-events-auto group-hover/mdimg:opacity-100","group-focus-within/mdimg:pointer-events-auto group-focus-within/mdimg:opacity-100","has-[[aria-expanded=true]]:pointer-events-auto has-[[aria-expanded=true]]:opacity-100"),children:h.jsx(qxe,{file:a,src:e,label:t,onShowInCanvas:s&&i?()=>{i.openInCanvas(a).then(c=>{c||AO(_U(a))})}:void 0})})]})};function YRt(){return{enter:{mathFlow:e,mathFlowFenceMeta:t,mathText:a},exit:{mathFlow:i,mathFlowFence:r,mathFlowFenceMeta:n,mathFlowValue:s,mathText:o,mathTextData:s}};function e(l){const c={type:"element",tagName:"code",properties:{className:["language-math","math-display"]},children:[]};this.enter({type:"math",meta:null,value:"",data:{hName:"pre",hChildren:[c]}},l)}function t(){this.buffer()}function n(){const l=this.resume(),c=this.stack[this.stack.length-1];c.type,c.meta=l}function r(){this.data.mathFlowInside||(this.buffer(),this.data.mathFlowInside=!0)}function i(l){const c=this.resume().replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),u=this.stack[this.stack.length-1];u.type,this.exit(l),u.value=c;const O=u.data.hChildren[0];O.type,O.tagName,O.children.push({type:"text",value:c}),this.data.mathFlowInside=void 0}function a(l){this.enter({type:"inlineMath",value:"",data:{hName:"code",hProperties:{className:["language-math","math-inline"]},hChildren:[]}},l),this.buffer()}function o(l){const c=this.resume(),u=this.stack[this.stack.length-1];u.type,this.exit(l),u.value=c,u.data.hChildren.push({type:"text",value:c})}function s(l){this.config.enter.data.call(this,l),this.config.exit.data.call(this,l)}}const GRt={tokenize:IRt,concrete:!0,name:"mathFlow"},JH={tokenize:ZRt,partial:!0};function IRt(e,t,n){const r=this,i=r.events[r.events.length-1],a=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0;let o=0;return s;function s(v){return e.enter("mathFlow"),e.enter("mathFlowFence"),e.enter("mathFlowFenceSequence"),l(v)}function l(v){return v===36?(e.consume(v),o++,l):o<2?n(v):(e.exit("mathFlowFenceSequence"),ln(e,c,"whitespace")(v))}function c(v){return v===null||bt(v)?O(v):(e.enter("mathFlowFenceMeta"),e.enter("chunkString",{contentType:"string"}),u(v))}function u(v){return v===null||bt(v)?(e.exit("chunkString"),e.exit("mathFlowFenceMeta"),O(v)):v===36?n(v):(e.consume(v),u)}function O(v){return e.exit("mathFlowFence"),r.interrupt?t(v):e.attempt(JH,d,g)(v)}function d(v){return e.attempt({tokenize:y,partial:!0},g,f)(v)}function f(v){return(a?ln(e,p,"linePrefix",a+1):p)(v)}function p(v){return v===null?g(v):bt(v)?e.attempt(JH,d,g)(v):(e.enter("mathFlowValue"),m(v))}function m(v){return v===null||bt(v)?(e.exit("mathFlowValue"),p(v)):(e.consume(v),m)}function g(v){return e.exit("mathFlow"),t(v)}function y(v,S,Q){let b=0;return ln(v,w,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4);function w(T){return v.enter("mathFlowFence"),v.enter("mathFlowFenceSequence"),x(T)}function x(T){return T===36?(b++,v.consume(T),x):b<o?Q(T):(v.exit("mathFlowFenceSequence"),ln(v,k,"whitespace")(T))}function k(T){return T===null||bt(T)?(v.exit("mathFlowFence"),S(T)):Q(T)}}}function ZRt(e,t,n){const r=this;return i;function i(o){return o===null?t(o):(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),a)}function a(o){return r.parser.lazy[r.now().line]?n(o):t(o)}}function DRt(e){let n={}.singleDollarTextMath;return n==null&&(n=!0),{tokenize:r,resolve:MRt,previous:VRt,name:"mathText"};function r(i,a,o){let s=0,l,c;return u;function u(m){return i.enter("mathText"),i.enter("mathTextSequence"),O(m)}function O(m){return m===36?(i.consume(m),s++,O):s<2&&!n?o(m):(i.exit("mathTextSequence"),d(m))}function d(m){return m===null?o(m):m===36?(c=i.enter("mathTextSequence"),l=0,p(m)):m===32?(i.enter("space"),i.consume(m),i.exit("space"),d):bt(m)?(i.enter("lineEnding"),i.consume(m),i.exit("lineEnding"),d):(i.enter("mathTextData"),f(m))}function f(m){return m===null||m===32||m===36||bt(m)?(i.exit("mathTextData"),d(m)):(i.consume(m),f)}function p(m){return m===36?(i.consume(m),l++,p):l===s?(i.exit("mathTextSequence"),i.exit("mathText"),a(m)):(c.type="mathTextData",f(m))}}}function MRt(e){let t=e.length-4,n=3,r,i;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(r=n;++r<t;)if(e[r][1].type==="mathTextData"){e[t][1].type="mathTextPadding",e[n][1].type="mathTextPadding",n+=2,t-=2;break}}for(r=n-1,t++;++r<=t;)i===void 0?r!==t&&e[r][1].type!=="lineEnding"&&(i=r):(r===t||e[r][1].type==="lineEnding")&&(e[i][1].type="mathTextData",r!==i+2&&(e[i][1].end=e[r-1][1].end,e.splice(i+2,r-i-2),t-=r-i-2,r=i+2),i=void 0);return e}function VRt(e){return e!==36||this.events[this.events.length-1][1].type==="characterEscape"}function LRt(e){return{flow:{36:GRt},text:{36:DRt()}}}const ep=36,eK=e=>e!==null&&e<-2,tK=e=>e===null||e===32||e<0,nK=e=>e!==null&&e>=48&&e<=57,jxe=e=>{const t=e?.singleDollarTextMath??!0;return{tokenize:n,resolve:FRt,previous:BRt,name:"mathText"};function n(r,i,a){const o=this;let s=0,l=null,c,u;return O;function O(g){return r.enter("mathText"),r.enter("mathTextSequence"),d(g)}function d(g){return g===ep?(r.consume(g),s++,d):s<2&&!t||s===1&&(tK(g)||nK(g))?a(g):(r.exit("mathTextSequence"),f(g))}function f(g){return g===null?a(g):g===ep?(u=r.enter("mathTextSequence"),c=0,l=o.previous,m(g)):g===32?(r.enter("space"),r.consume(g),r.exit("space"),f):eK(g)?(r.enter("lineEnding"),r.consume(g),r.exit("lineEnding"),f):(r.enter("mathTextData"),p(g))}function p(g){return g===null||g===32||g===ep||eK(g)?(r.exit("mathTextData"),f(g)):(r.consume(g),p)}function m(g){return g===ep?(r.consume(g),c++,m):c===s?s===1&&(tK(l)||nK(g))?a(g):(r.exit("mathTextSequence"),r.exit("mathText"),i(g)):(u.type="mathTextData",p(g))}}};function FRt(e){let t=e.length-4,n=3,r,i;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(r=n;++r<t;)if(e[r][1].type==="mathTextData"){e[t][1].type="mathTextPadding",e[n][1].type="mathTextPadding",n+=2,t-=2;break}}for(r=n-1,t++;++r<=t;)i===void 0?r!==t&&e[r][1].type!=="lineEnding"&&(i=r):(r===t||e[r][1].type==="lineEnding")&&(e[i][1].type="mathTextData",r!==i+2&&(e[i][1].end=e[r-1][1].end,e.splice(i+2,r-i-2),t-=r-i-2,r=i+2),i=void 0);return e}function BRt(e){return e!==ep||this.events[this.events.length-1][1].type==="characterEscape"}const HRt=LRt().flow,KRt=jxe();function TP(e){const t=this.data();t.micromarkExtensions??=[],t.fromMarkdownExtensions??=[];const n=t.micromarkExtensions,r=t.fromMarkdownExtensions,i=e?.singleDollarTextMath===void 0?KRt:jxe(e);n.push({flow:HRt,text:{[ep]:i}}),r.push(YRt())}const JRt=({node:e,...t})=>h.jsx("div",{className:"lo-md-table-scroll",children:h.jsx("table",{...t})}),eXt=/\$(?!\d)(.+?)\$/,tXt=/\$\$([\s\S]+?)\$\$/,nXt=/\\begin\{([^}]+)\}([\s\S]+?)\\end\{\1\}/,rXt=/\\[a-zA-Z]+(\{[^}]*\})?/,rK=e=>eXt.test(e)||tXt.test(e)||nXt.test(e)?!0:rXt.test(e)&&(e.includes("\\frac")||e.includes("\\sum")||e.includes("\\int")||e.includes("\\sqrt")),iXt=e=>{const t=PP(e);if(t.length===1&&t[0].kind==="text")return null;let n="",r=!1;for(const i of t){if(i.kind==="text"){n+=i.text;continue}r=!0,n+="x".repeat(i.text.length)}return r?n:null},aXt=e=>PP(e).filter(t=>t.kind!=="text").length,oXt=e=>{if(!rK(e))return!1;const t=iXt(e);return t===null?!0:rK(t)||t.includes("$")?!1:aXt(e)<2},Kt="var(--color-ink)",bc="var(--color-ink-muted)",Sl="var(--color-surface)",Du="var(--color-elevated)",wc="var(--color-sunken)",oa="var(--color-hairline)",Mu="var(--color-control)",Xh="var(--color-accent)",Q0="var(--color-accent-wash)",sXt="var(--color-accent-alt-wash)",lXt="var(--color-on-accent)",cXt="var(--color-info)",Cxe="var(--color-info-wash)",uXt="var(--color-success)",Axe="var(--color-success-wash)",OXt="var(--color-warning)",l7="var(--color-warning-wash)",dXt="var(--color-warning-border)",lR="var(--color-danger)",c7="var(--color-danger-wash)",iK=[Q0,sXt,Cxe,Axe,l7,c7],Vu=e=>getComputedStyle(document.documentElement).getPropertyValue(e).trim(),fXt=()=>{const e={primaryColor:Vu("--color-accent"),secondaryColor:Vu("--color-success"),tertiaryColor:Vu("--color-info"),mainBkg:Vu("--color-elevated"),clusterBkg:Vu("--color-sunken"),clusterBorder:Vu("--color-hairline"),edgeLabelBackground:Vu("--color-surface"),quadrant1Fill:Vu("--color-accent-wash")};for(const[n,r]of Object.entries(e))r===""&&delete e[n];const t={darkMode:getComputedStyle(document.documentElement).colorScheme.includes("dark"),background:Sl,primaryTextColor:Kt,primaryBorderColor:Mu,secondaryTextColor:Kt,secondaryBorderColor:oa,tertiaryTextColor:Kt,tertiaryBorderColor:oa,lineColor:bc,arrowheadColor:bc,textColor:Kt,secondBkg:wc,border1:Mu,border2:oa,labelColor:Kt,nodeBkg:Du,nodeBorder:Mu,nodeTextColor:Kt,defaultLinkColor:bc,titleColor:Kt,noteBkgColor:l7,noteBorderColor:dXt,noteTextColor:Kt,actorBkg:Du,actorBorder:Mu,actorTextColor:Kt,actorLineColor:oa,signalColor:bc,signalTextColor:Kt,labelBoxBkgColor:Du,labelBoxBorderColor:oa,labelTextColor:Kt,loopTextColor:Kt,activationBkgColor:Q0,activationBorderColor:Xh,sequenceNumberColor:Sl,sectionBkgColor:wc,sectionBkgColor2:Sl,altSectionBkgColor:wc,excludeBkgColor:wc,taskBkgColor:Q0,taskBorderColor:Mu,taskTextColor:Kt,taskTextLightColor:Kt,taskTextDarkColor:Kt,taskTextOutsideColor:Kt,taskTextClickableColor:Xh,activeTaskBkgColor:Q0,activeTaskBorderColor:Xh,gridColor:oa,doneTaskBkgColor:wc,doneTaskBorderColor:oa,critBkgColor:c7,critBorderColor:lR,todayLineColor:Xh,transitionColor:bc,transitionLabelColor:Kt,stateLabelColor:Kt,stateBkg:Du,labelBackgroundColor:Sl,compositeBackground:wc,altBackground:wc,compositeTitleBackground:Du,compositeBorder:oa,innerEndBackground:Kt,specialStateColor:Kt,classText:Kt,attributeBackgroundColorOdd:Sl,attributeBackgroundColorEven:wc,rowOdd:Sl,rowEven:wc,errorBkgColor:c7,errorTextColor:lR,pieTitleTextColor:Kt,pieSectionTextColor:Kt,pieLegendTextColor:Kt,pieStrokeColor:Sl,pieOuterStrokeColor:oa,requirementBackground:Du,requirementBorderColor:Mu,requirementTextColor:Kt,relationColor:bc,relationLabelBackground:Sl,relationLabelColor:Kt,branchLabelColor:lXt,commitLabelColor:Kt,commitLabelBackground:Sl,tagLabelColor:Kt,tagLabelBackground:Q0,tagLabelBorder:Mu,quadrant2Fill:Cxe,quadrant3Fill:Axe,quadrant4Fill:l7,quadrant2TextFill:Kt,quadrant3TextFill:Kt,quadrant4TextFill:Kt,quadrantPointFill:Xh,archEdgeColor:bc,archEdgeArrowColor:bc,archGroupBorderColor:oa,scaleLabelColor:Kt,packet:{startByteColor:Kt,endByteColor:Kt,labelColor:Kt,titleColor:Kt,blockStrokeColor:Mu,blockFillColor:Du},radar:{axisColor:bc,axisStrokeWidth:2,axisLabelFontSize:12,curveOpacity:.5,curveStrokeWidth:2,graticuleColor:oa,graticuleStrokeWidth:1,graticuleOpacity:.3,legendBoxSize:12,legendFontSize:12},xyChart:{backgroundColor:Sl,titleColor:Kt,xAxisTitleColor:Kt,xAxisLabelColor:Kt,xAxisTickColor:oa,xAxisLineColor:oa,yAxisTitleColor:Kt,yAxisLabelColor:Kt,yAxisTickColor:oa,yAxisLineColor:oa,plotColorPalette:[Xh,cXt,uXt,OXt,lR].join(",")}};for(let n=0;n<5;n++)t[`surface${n}`]=Du,t[`surfacePeer${n}`]=oa;for(let n=0;n<8;n++)t[`fillType${n}`]=iK[n%iK.length];return{...t,...e}};let cR=null,aK=null;const hXt=async e=>{cR||(cR=ve(async()=>{const{default:n}=await import("./mermaid.core-BHqZ2SZO.js").then(r=>r.b4);return{default:n}},__vite__mapDeps([8,1,2]),import.meta.url).then(({default:n})=>n));const t=await cR;return aK!==e&&(t.initialize({startOnLoad:!0,theme:"base",securityLevel:"loose",fontFamily:"var(--font-sans)",fontSize:14,suppressErrorRendering:!0,themeVariables:fXt()}),aK=e),t},oK=({className:e,copied:t,onZoomIn:n,onZoomOut:r,onReset:i,onSave:a,onCopy:o,children:s})=>h.jsxs("div",{className:q("absolute z-10 flex items-center gap-0.5 rounded-md bg-elevated p-1 shadow-overlay",e),children:[h.jsx(Yt,{content:"Zoom in",children:h.jsx(Xe,{variant:"ghost",size:"icon-sm","aria-label":"Zoom in",onClick:n,children:h.jsx(Iue,{})})}),h.jsx(Yt,{content:"Zoom out",children:h.jsx(Xe,{variant:"ghost",size:"icon-sm","aria-label":"Zoom out",onClick:r,children:h.jsx(Zue,{})})}),h.jsx(Yt,{content:"Drag the diagram to pan",children:h.jsx(Xe,{variant:"ghost",size:"icon-sm","aria-label":"Drag to pan",children:h.jsx(c9e,{})})}),h.jsx(Yt,{content:"Reset view",children:h.jsx(Xe,{variant:"ghost",size:"icon-sm","aria-label":"Reset view",onClick:i,children:h.jsx(mk,{})})}),h.jsx(Yt,{content:"Save as SVG",children:h.jsx(Xe,{variant:"ghost",size:"icon-sm","aria-label":"Save as SVG",onClick:a,children:h.jsx(Ov,{})})}),h.jsx(Yt,{content:t?"Copied":"Copy mermaid text",children:h.jsx(Xe,{variant:"ghost",size:"icon-sm","aria-label":t?"Copied":"Copy mermaid text",onClick:o,children:h.jsx(hk,{className:q(t&&"text-success")})})}),s]}),u7=({title:e,children:t})=>h.jsxs(Ll,{variant:"danger",role:"alert",className:"my-4",children:[h.jsx(E0,{children:e}),h.jsx(q0,{children:t})]});class pXt extends $.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("Mermaid Error Boundary caught an error:",t,n)}render(){return this.state.hasError?this.props.fallback||h.jsxs(u7,{title:"Mermaid diagram error",children:[this.state.error?.message||"An unexpected error occurred while rendering the diagram"," ","The error was contained within the diagram component."]}):this.props.children}}const mXt=$.memo(({chart:e,id:t})=>{const n=$.useRef(null),r=$.useRef(null),[i,a]=$.useState(null),[o,s]=$.useState(!0),[l,c]=$.useState(""),[u,O]=$.useState(!1),[d,f]=$.useState({scale:1,x:0,y:0}),[p,m]=$.useState({scale:1,x:0,y:0}),[g,y]=$.useState(!1),[v,S]=$.useState({x:0,y:0}),[Q,b]=$.useState("idle"),[w,x]=$.useState("idle"),k=Jn(U=>U.themeName),T=$.useCallback(async()=>{try{if(s(!0),a(null),c(""),!e||typeof e!="string"||e.trim().length===0)throw new Error("Invalid or empty chart content");const U=await hXt(k),H=t||`mermaid-${Date.now()}-${Math.floor(Math.random()*1e6)}`,{svg:D}=await U.render(H,e);if(!D||typeof D!="string"||D.trim().length===0)throw new Error("Mermaid failed to generate valid SVG output");c(D)}catch(U){console.error("Mermaid rendering error:",U);const H=U instanceof Error?U.message:"Failed to render mermaid diagram";a(H),c("")}finally{s(!1)}},[e,t,k]);$.useEffect(()=>{T().catch(U=>{console.error("Error in renderDiagram effect:",U),a("Failed to initialize diagram rendering"),s(!1)})},[T]);const _=$.useCallback(()=>{try{if(!l||!r.current)return 1;const H=r.current.getBoundingClientRect(),D=document.createElement("div");D.innerHTML=l;const V=D.querySelector("svg");if(!V)return 1;const se=V.getBoundingClientRect?.()?.width||Number.parseFloat(V.getAttribute("width")||"0")||V.viewBox?.baseVal?.width||800,B=V.getBoundingClientRect?.()?.height||Number.parseFloat(V.getAttribute("height")||"0")||V.viewBox?.baseVal?.height||600,K=H.width*.9/se,ne=H.height*.9/B;return Math.min(K,ne,1)}catch(U){return console.error("Error calculating fullscreen scale:",U),1}},[l]);$.useEffect(()=>{u&&l&&setTimeout(()=>{try{const U=_();m({scale:U,x:0,y:0})}catch(U){console.error("Error setting fullscreen transform:",U)}},100)},[u,l,_]);const E=$.useCallback((U=!1)=>{try{(U?m:f)(D=>({...D,scale:Math.min(D.scale*1.2,10)}))}catch(H){console.error("Error in zoom in:",H)}},[]),R=$.useCallback((U=!1)=>{try{(U?m:f)(D=>({...D,scale:Math.max(D.scale/1.2,.1)}))}catch(H){console.error("Error in zoom out:",H)}},[]),j=$.useCallback((U=!1)=>{try{const H=U?m:f;if(U){const D=_();H({scale:D,x:0,y:0})}else H({scale:1,x:0,y:0})}catch(H){console.error("Error in reset:",H)}},[_]),C=$.useCallback(()=>{if(l)try{const U=new Blob([l],{type:"image/svg+xml"}),H=URL.createObjectURL(U),D=document.createElement("a");D.href=H,D.download=`mermaid-diagram-${Date.now()}.svg`,document.body.appendChild(D),D.click(),document.body.removeChild(D),URL.revokeObjectURL(H)}catch(U){console.error("Failed to save SVG:",U)}},[l]),W=$.useCallback(async()=>{try{await navigator.clipboard.writeText(e),b("copied"),setTimeout(()=>b("idle"),1200)}catch(U){console.error("Failed to copy Mermaid chart text:",U)}},[e]),G=$.useCallback(async()=>{try{await navigator.clipboard.writeText(e),x("copied"),setTimeout(()=>x("idle"),1200)}catch(U){console.error("Failed to copy Mermaid chart text:",U)}},[e]),N=$.useCallback(U=>{try{y(!0),S({x:U.clientX,y:U.clientY}),U.preventDefault()}catch(H){console.error("Error in mouse down:",H)}},[]),Z=$.useCallback((U,H=!1)=>{try{if(!g)return;const D=U.clientX-v.x,V=U.clientY-v.y;(H?m:f)(B=>({...B,x:B.x+D,y:B.y+V})),S({x:U.clientX,y:U.clientY})}catch(D){console.error("Error in mouse move:",D)}},[g,v]),F=$.useCallback(()=>{try{y(!1)}catch(U){console.error("Error in mouse up:",U)}},[]),z=$.useCallback((U,H=!1)=>{try{U.preventDefault();const D=U.deltaY>0?.9:1.1;(H?m:f)(se=>({...se,scale:Math.min(Math.max(se.scale*D,.1),5)}))}catch(D){console.error("Error in wheel:",D)}},[]),M=$.useCallback(U=>{try{O(U)}catch(H){console.error("Error toggling fullscreen:",H)}},[]);if(i)return h.jsxs(u7,{title:"Mermaid diagram error",children:[i,h.jsx("span",{className:q("mt-2 block text-ink-muted"),children:"Chart"}),h.jsx("span",{className:q("mt-1 block whitespace-pre-wrap font-mono text-mono-sm"),children:e})]});const te=(U=!1)=>{try{const H=U?r:n,D=U?p:d;return h.jsx("div",{ref:H,className:q("mermaid flex w-full items-center justify-center",U?"h-full min-h-full":"h-auto min-h-50",g?"cursor-grabbing":"cursor-grab"),onMouseDown:N,onMouseMove:V=>Z(V,U),onMouseUp:F,onMouseLeave:F,onWheel:V=>z(V,U),children:o?h.jsx("div",{className:q("p-4 text-body-sm text-ink-muted"),children:"Loading diagram..."}):l?h.jsx("div",{className:q("flex h-full w-full items-center justify-center"),style:{transform:`translate(${D.x}px, ${D.y}px) scale(${D.scale})`,transformOrigin:"center center"},dangerouslySetInnerHTML:{__html:l}}):null})}catch(H){return console.error("Error rendering diagram content:",H),h.jsx(u7,{title:"Rendering error",children:"Failed to render diagram content."})}};return h.jsxs(h.Fragment,{children:[h.jsxs("div",{className:q("relative flex items-center justify-center overflow-hidden rounded-md bg-surface","[&_svg]:h-auto [&_svg]:min-h-100 [&_svg]:max-w-none [&_svg]:bg-transparent"),children:[te(!1),h.jsx(oK,{className:"top-2 right-2",copied:Q==="copied",onZoomIn:()=>E(!1),onZoomOut:()=>R(!1),onReset:()=>j(!1),onSave:C,onCopy:W,children:h.jsx(Yt,{content:"Fullscreen",children:h.jsx(Xe,{variant:"ghost",size:"icon-sm","aria-label":"Open diagram fullscreen",onClick:()=>M(!0),children:h.jsx(Eue,{})})})})]}),h.jsx(R$,{open:u,onClose:()=>M(!1),title:"Mermaid diagram",maxWidth:"xl",fullWidth:!0,dialogProps:{className:"h-[90vh] max-h-[90vh]"},children:h.jsxs("div",{className:q("relative flex h-[80vh] w-full items-center justify-center overflow-hidden","[&_svg]:h-auto [&_svg]:max-h-full [&_svg]:w-auto [&_svg]:max-w-full [&_svg]:bg-transparent"),children:[te(!0),h.jsx(oK,{className:"top-4 right-4",copied:w==="copied",onZoomIn:()=>E(!0),onZoomOut:()=>R(!0),onReset:()=>j(!0),onSave:C,onCopy:G,children:h.jsx(Yt,{content:"Close fullscreen",children:h.jsx(Xe,{variant:"ghost",size:"icon-sm","aria-label":"Close fullscreen",onClick:()=>M(!1),children:h.jsx(ea,{})})})})]})})]})}),gXt=$.memo(e=>h.jsx(pXt,{children:h.jsx(mXt,{...e})}));let zxe=!1,uR=null;const $Xt=()=>(uR||(uR=ve(()=>Promise.resolve({}),__vite__mapDeps([9]),import.meta.url).then(e=>(zxe=!0,e))),uR),yXt=/language-(\w+)/,vXt=JQ,bXt=new RegExp(`^[^${ba}\\d*+-]`),wXt=/\n$/,Uxe=({href:e,children:t})=>{const n=GSe(e),r=SP();return!n||n.kind==="other"?h.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",children:t}):h.jsx("a",{href:n.target,"data-lo-kind":n.kind,"data-lo-target":n.target,draggable:!1,target:n.kind==="url"?"_blank":void 0,rel:n.kind==="url"?"noopener noreferrer":void 0,onClick:n.kind==="file"?i=>QXt(i,r):void 0,children:t})},SXt=e=>GSe(e)?.kind==="file",xXt=VSe,QXt=(e,t)=>{const n=e.currentTarget,r=n.getAttribute(MSe)??"file",i=n.getAttribute(xXt),a=oTt({kind:r,hasHighlight:bTt(n),canOpenInCanvas:SU(t,i)});if(a!=="browse"&&(e.preventDefault(),!(a==="hold"||!i))){if(a==="canvas"&&t){t.openInCanvas(i).then(o=>{o||AO(i)});return}AO(i)}},O7=(e,t)=>t==="href"&&SXt(e)?e:uhe(e),my={a:Uxe,table:JRt,img:NRt,code:({node:e,className:t,children:n,...r})=>yXt.exec(t??"")?.[1]==="mermaid"?h.jsx(gXt,{chart:String(n).replace(wXt,"")}):h.jsx("code",{className:t,...r,children:n})},kXt={...my,a:QRt(Uxe)},PXt=[IO],_Xt=[IO,TP],TXt=[IO,xP],RXt=[IO,TP,xP],XXt=[IO,_P,QP],EXt=[IO,TP,_P,QP],qXt=[IO,xP,_P,QP],jXt=[IO,TP,xP,_P,QP],CXt={"000":PXt,"001":XXt,"010":TXt,"011":qXt,100:_Xt,101:EXt,110:RXt,111:jXt},AXt=[],zXt=[iJe],Wxe=e=>$.useMemo(()=>{if(!(!e?.fontSize&&!e?.lineHeight))return{"--md-font-size":e.fontSize,"--md-line-height":e.lineHeight}},[e?.fontSize,e?.lineHeight]),Nxe=(e,t,n)=>{const r=$.useMemo(()=>oXt(e),[e]),[i,a]=$.useState(zxe),o=r&&i;return $.useEffect(()=>{if(!r||i)return;let s=!1;return $Xt().then(()=>{s||a(!0)}),()=>{s=!0}},[r,i]),{remarkPlugins:CXt[`${o?1:0}${t?1:0}${n?1:0}`],rehypePlugins:o?zXt:AXt}},Yxe=(e,t)=>{const[,n]=$.useState(0);$.useEffect(()=>{if(!t)return;const r=Ytt(e);if(r.length===0)return;let i=!0;const a=new Set(r),o=lTt(s=>{i&&s.some(l=>a.has(l))&&n(l=>l+1)});return DSe(r,window.api?.probeFiles,nle).then(()=>{i&&r.some(s=>ZSe(s)!=="unknown")&&n(s=>s+1)}),()=>{i=!1,o()}},[e,t])},gy=$.memo(({content:e,styleProps:t,className:n,linkify:r=!0,credentialCitations:i=!1})=>{const a=$.useMemo(()=>e.trim(),[e]),{remarkPlugins:o,rehypePlugins:s}=Nxe(a,r,i),l=Wxe(t);return Yxe(a,r),h.jsx("div",{className:q("lo-markdown",n),style:l,children:h.jsx(Jj,{remarkPlugins:o,rehypePlugins:s,urlTransform:O7,components:i?kXt:my,children:a})})});gy.displayName="MarkdownRenderer";const sK={...my,a:({children:e})=>h.jsx(h.Fragment,{children:e})},Gxe=$.memo(({source:e,closed:t})=>{const n=$.useMemo(()=>t?e:EH(e),[t,e]),r=$.useMemo(()=>{if(t)return null;const o=oxe(e);return o!==null&&!o.nested?o:null},[t,e]),{remarkPlugins:i,rehypePlugins:a}=Nxe(n,t,!1);if(Yxe(e,t),r!==null){const o=EH(r.before);return h.jsxs(h.Fragment,{children:[o.trim()!==""&&h.jsx(Jj,{remarkPlugins:i,rehypePlugins:a,urlTransform:O7,components:t?my:sK,children:o}),h.jsx(UXt,{info:r.info,body:r.body})]})}return h.jsx(Jj,{remarkPlugins:i,rehypePlugins:a,urlTransform:O7,components:t?my:sK,children:n})});Gxe.displayName="ParsedBlock";const UXt=({info:e,body:t})=>{const n=e.split(vXt)[0];return h.jsx("pre",{children:h.jsx("code",{className:n?`language-${n}`:void 0,children:t===""?"":`${t}${t.endsWith(`
866
+ `)&&(s={capture:Ex(e),buffer:n,caret:r})}return{...s,capture:Jh(s.capture,s.buffer,s.caret,i)}}function g2t(e){const{capture:t,buffer:n,caret:r,index:i,taken:a}=e,o=Jf(t);if(o===null||t.value==="")return{minted:!1,capture:t,buffer:n,caret:r,payload:null};const s=t.arm===null?o.start:t.arm.start,l=yxe(i,t.value),c=l+kP,u=n.slice(0,s)+c+n.slice(o.end);return{minted:!0,capture:eo,buffer:u,caret:s+c.length,payload:{index:i,key:Sxe(a,e.draw),value:t.value,marker:l}}}function $2t(e,t){const n=Jf(e);if(n===null)return{cancelled:!1,capture:e,buffer:t,caret:0,restored:0,token:null};const r=e.value,i=wxe(t,e),a=e.arm===null?n.start:e.arm.start;return{cancelled:!0,capture:eo,buffer:i,caret:n.start+r.length,restored:o7(r),token:{span:{start:a,end:n.start},text:t.slice(a,n.start),restored:o7(r),restoredText:r}}}function WH(e,t){return t===null||t.text.length===0?!1:e.slice(t.span.start,t.span.start+t.text.length)===t.text}function y2t(e,t,n,r){const i=t.slice(0,n.start)+r+t.slice(n.end),a=n.start+r.length,o=Jf(e);return o===null?{kind:"passthrough",capture:e,buffer:i,caret:a,payload:null}:n.start<=o.start?{kind:"passthrough",capture:{...e,typingAt:o.start+r.length},buffer:i,caret:a,payload:null}:n.start>=o.end?{kind:"passthrough",capture:e,buffer:i,caret:a,payload:null}:{kind:"passthrough",capture:Ex(e),buffer:i,caret:a,payload:null}}function v2t(e){const{capture:t,buffer:n,caret:r,pasted:i}=e;if(t.arm===null)return null;if(t.typingAt!==null&&t.value!==""){if(i==="")return null;const u=PU(t,n,r,{top:e.selection.start,bottom:e.selection.end,inserted:i});return u===null?null:{kind:"masked",...u,payload:null}}const a=on(i);if(!a)return i===""?null:y2t(t,n,e.selection,i);const o=t.arm,s=yxe(e.index,a),l=s+kP,c=n.slice(0,o.start)+l+n.slice(o.end);return{kind:"minted",capture:eo,buffer:c,caret:o.start+l.length,payload:{index:e.index,key:Sxe(e.taken,e.draw),value:a,marker:s}}}const $xe=e=>`${o7(e)} chars`,yxe=(e,t)=>`[Credential #${e}, ${$xe(t)}]`;function b2t(e){Dl.lastIndex=0;const t=Dl.exec(e);return Dl.lastIndex=0,t===null||t[0]!==e?null:Number.parseInt(t[1],10)}function w2t(e){Dl.lastIndex=0;const t=Dl.exec(e);if(Dl.lastIndex=0,t===null||t[0]!==e)return null;const n=Number.parseInt(t[1],10);return{index:n,label:`#${n}`,chars:Number.parseInt(t[2],10)}}function Zv(e,t){if(b2t(t.marker)!==t.index)return null;const n=e.indexOf(t.marker);return n===-1?null:{start:n,end:n+t.marker.length}}const aR=/\[credential ([A-Za-z_][A-Za-z0-9_]*) \((\d+) chars\) \u2014 available to bash and eval as \$([A-Za-z_][A-Za-z0-9_]*); its value cannot be read\]/y,oR=/\[credential NOT stored \u2014 [^\]\n]*\]/y,sR=/\[credential unconfirmed \u2014 [^\]\n]*\]/y,S2t=e=>{const t=/\$([A-Z0-9_]+)/.exec(e);return t!==null&&a7.test(t[1])?t[1]:""};function x2t(e,t){if(e.charCodeAt(t)!==91)return null;aR.lastIndex=t;const n=aR.exec(e);if(aR.lastIndex=0,n!==null&&n[1]===n[3])return{kind:"stored",text:n[0],key:n[1],chars:Number.parseInt(n[2],10)};oR.lastIndex=t;const r=oR.exec(e);if(oR.lastIndex=0,r!==null)return{kind:"unstored",text:r[0]};sR.lastIndex=t;const i=sR.exec(e);return sR.lastIndex=0,i!==null?{kind:"unconfirmed",text:i[0],key:S2t(i[0])}:null}function PP(e){const t=[];let n=0,r=0;for(;r<e.length;){const i=x2t(e,r);if(i===null){r++;continue}r>n&&t.push({kind:"text",text:e.slice(n,r)}),t.push(i),r+=i.text.length,n=r}return n<e.length&&t.push({kind:"text",text:e.slice(n)}),t}function NH(e,t){const n=[];for(const r of t){const i=Zv(e,r);i!==null&&n.push({at:i.start,payload:r})}return n.sort((r,i)=>r.at-i.at).map(r=>r.payload)}function Q2t(e,t=""){return e==="unconfirmed"?t?`[credential unconfirmed — it may be held as $${t}, so check list_variables before assuming it is missing]`:"[credential unconfirmed — the session may hold it, so check list_variables before assuming it is missing]":e==="unreachable"?"[credential NOT stored — the session could not be reached; try again]":e==="rejected-key"?"[credential NOT stored — the store rejected its name]":"[credential NOT stored — its value did not survive; ask the operator to paste it again]"}const k2t=e=>`[credential ${e.key} (${$xe(e.value)}) — available to bash and eval as $${e.key}; its value cannot be read]`;function P2t(e,t,n=new Map){const r=[...t],i=[];for(const o of r){const s=Zv(e,o);s!==null&&i.push({span:s,payload:o})}for(const o of hxe(e,r))i.push({span:o,payload:null});let a=e;for(const{span:o,payload:s}of i.sort((l,c)=>c.span.start-l.span.start)){const l=s===null?"lost":n.get(s.index),c=s===null||l!==void 0?Q2t(l??"lost",s?.key):k2t(s);a=a.slice(0,o.start)+c+a.slice(o.end)}return a}const _2t=(e,t,n)=>`Removed ${e} (credential #${t}) from this message. Its value is gone — press ${n} to put it back, or paste it again after /credential to reuse it.`,T2t=e=>`Remove credential #${e}`,R2t=(e,t)=>`Credential #${e}, ${t} chars — held in this message; its value cannot be read`,X2t=(e,t,n)=>_2t(e,t,n),E2t="Undo",q2t=e=>`Credential #${e} removed`,j2t=e=>e.unredacted!==null?e.unredacted:e.armed?Y2t:e.cleared!==null?X2t(e.cleared.key,e.cleared.index,e.undoCap):null;function C2t(e){const{buffer:t,payload:n}=e,r=Zv(t,n);if(r===null)return{cleared:!1,buffer:t,caret:t.length,removed:""};const i=t[r.end]===kP?r.end+1:r.end;return{cleared:!0,buffer:t.slice(0,r.start)+t.slice(i),caret:r.start,removed:t.slice(r.start,i)}}function A2t(e){const{buffer:t,cleared:n}=e;return n.removed===""||t!==n.buffer?null:{buffer:t.slice(0,n.caret)+n.removed+t.slice(n.caret),caret:n.caret+n.removed.length}}const YH=e=>`Stored ${e.join(", ")}. Injected into every bash command as an environment variable; the agent cannot read the value.`;function GH(e){const t=e.length===1?"credential":"credentials";return`${e.length} ${t} could not be stored (${[...e].sort().join(", ")}); the agent has been told so. Paste the value again after /credential to retry.`}const z2t="store unconfirmed",U2t="Credential store unconfirmed",W2t=e=>e===""?U2t:`${e} · ${z2t}`,vxe="Paste the value again after /credential to store it again.",N2t=e=>`${e} ${vxe}`;function IH(e){const t=e.length===1?"credential":"credentials";return`${e.length} ${t} could not be confirmed as stored (${[...e].sort().join(", ")}); the agent has been told to check before using it. ${vxe}`}const Y2t="armed — add a space, then type or paste the secret",G2t="masked as you type — Enter turns it into a pill, Esc cancels",I2t="masked — Enter opens the credential picker; type or paste the secret into this span",Z2t="masked — Enter runs /credential, which needs an open conversation; type or paste the secret into this span",bxe="\0held",D2t=(e,t)=>t===void 0?`${e} characters are now PLAIN TEXT in the composer — Enter will expose them`:t===bxe?`${e} characters are now PLAIN TEXT in the composer — Enter is held: clear the box to release your words`:`${e} characters are now PLAIN TEXT in the composer — Enter will take them as /${t}'s argument, not send them`;function wxe(e,t){const n=Jf(t);return n===null?e:e.slice(0,n.start)+t.value+e.slice(n.end)}const ZH=(e,t)=>e&&e.over===t?e.chars:null,M2t=e=>{const t=Math.floor(4294967296/e)*e,n=new Uint32Array(1);for(;;)if(globalThis.crypto.getRandomValues(n),n[0]<t)return n[0]%e},V2t=16,L2t=16;function Sxe(e=[],t=M2t){const n=new Set(e);for(let r=0;r<V2t;r++){const i=AH+DH(8,t);if(!n.has(i))return i}return AH+DH(L2t,t)}const DH=(e,t)=>{let n="";for(let r=0;r<e;r++)n+=CH[t(CH.length)];return n},F2t=8,B2t=256,H2t=/^[/@$#]/,K2t=/^\w+:\/\//,J2t=/^[A-Za-z]+$/,eRt=/^\d+$/,tRt=[/[a-z]/,/[A-Z]/,/\d/,/[^A-Za-z0-9]/],nRt=3,rRt=20,iRt=/^[A-Za-z0-9_\-+/=.]+$/,aRt=new RegExp(`^[^${ba}@]+@[^${ba}@]+\\.[A-Za-z]{2,}$`),oRt=/^[\w.-]+(?:\/[\w.-]+)+$/,sRt=/\.[A-Za-z][A-Za-z0-9]{0,7}$/,lRt=/^v?\d+(?:\.\d+)+(?:[-+][0-9A-Za-z.-]+)?$/,cRt=/^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/,uRt=/^[\w.-]+:\d{2,5}$/,ORt=/^(?:[0-9a-f]{7,12}|[0-9a-f]{40})$/i,dRt=/^[a-z]+(?:_[a-z]+)+$/,fRt=/^[a-z]+(?:-[a-z]+)+$/,hRt=/^[a-z][a-z0-9]*(?:[A-Z][a-z0-9]+)+$/,pRt=/^[a-z0-9]+(?:-[a-z0-9]+)+$/,mRt=/\d{4,}/,gRt=e=>{const t=e.trim();return t.length<F2t||t.length>B2t||Zo.test(t)||H2t.test(t)||K2t.test(t)||oOe(t)!==null||aRt.test(t)||oRt.test(t)||sRt.test(t)||lRt.test(t)||cRt.test(t)||uRt.test(t)||ORt.test(t)||dRt.test(t)||fRt.test(t)||hRt.test(t)||pRt.test(t)&&mRt.test(t)||J2t.test(t)||eRt.test(t)?!1:tRt.filter(r=>r.test(t)).length>=nRt?!0:t.length>=rRt&&iRt.test(t)},xxe=q("rounded-xs bg-info-wash","outline-1 outline-solid outline-info-border","box-decoration-clone"),Qxe=q("rounded-xs bg-warning-wash","outline-1 outline-dashed outline-warning-border","box-decoration-clone"),kxe=({label:e,chars:t=null,tone:n="live",title:r,onClear:i,clearLabel:a,className:o,style:s,small:l=!1})=>h.jsxs("span",{className:q("inline-flex max-w-full items-center justify-between gap-1.5 px-3 text-ink",n==="warning"?Qxe:xxe,l?"text-body-sm":"text-body",o),title:r,style:s,children:[n==="warning"?h.jsx(ole,{"aria-hidden":"true",className:"size-3 shrink-0"}):h.jsx(Yze,{"aria-hidden":"true",className:"size-3 shrink-0"}),h.jsx("span",{className:"min-w-0 truncate",children:e}),t!==null&&h.jsx("span",{className:"shrink-0",children:`· ${t} chars`}),i&&h.jsx("button",{type:"button","aria-label":a,onClick:i,className:"pointer-events-auto -mr-1 flex shrink-0 cursor-pointer items-center rounded-xs p-0.5 text-ink-muted hover:bg-elevated hover:text-ink focus-visible:outline-offset-1! active:bg-sunken",children:h.jsx(ea,{"aria-hidden":"true",className:"size-3"})}),r&&h.jsx("span",{className:"sr-only",children:r})]}),py="#lo-credential/",$Rt=`${py}unstored`,MH=`${py}unconfirmed`,yRt=/^\d+$/,Pxe=e=>e.kind==="stored"?`${py}${e.key??""}/${e.chars??0}`:e.kind==="unconfirmed"?e.key?`${MH}/${e.key}`:MH:$Rt;function vRt(e){if(!e||!e.startsWith(py))return null;const t=e.slice(py.length);if(t==="unstored")return{kind:"unstored"};if(t==="unconfirmed")return{kind:"unconfirmed",key:""};if(t.startsWith("unconfirmed/")){const a=t.slice(12);return a7.test(a)?{kind:"unconfirmed",key:a}:null}const n=t.lastIndexOf("/");if(n===-1)return null;const r=t.slice(0,n),i=t.slice(n+1);return!a7.test(r)||!yRt.test(i)?null:{kind:"stored",key:r,chars:Number.parseInt(i,10)}}function VH(e,t){const n=vRt(e);if(n===null)return null;const r=PP(t);if(r.length!==1||r[0].kind==="text")return null;const i=r[0];return Pxe(i)!==e?null:n}const _P=()=>e=>{const t=n=>{if(!n.children)return;const r=[];let i=!1;for(const a of n.children){if(a.type!=="text"||typeof a.value!="string"){t(a),r.push(a);continue}const o=PP(a.value);if(o.length===1&&o[0].kind==="text"){r.push(a);continue}i=!0;for(const s of o){if(s.kind==="text"){r.push({type:"text",value:s.text});continue}r.push({type:"link",url:Pxe(s),title:s.text,children:[{type:"text",value:s.text}]})}}i&&(n.children=r)};t(e)},bRt=e=>e.kind==="stored"?e.key:e.kind==="unconfirmed"?W2t(e.key):"Credential not stored",wRt=(e,t)=>e.kind==="unconfirmed"&&t!==void 0?N2t(t):t,SRt=({citation:e,title:t})=>h.jsx(kxe,{tone:e.kind==="stored"?"live":"warning",label:bRt(e),chars:e.kind==="stored"?e.chars:null,title:wRt(e,t),className:"align-middle"}),xRt=(e,t)=>typeof t=="string"?VH(e,t):t==null?VH(e,""):null,QRt=e=>({href:t,title:n,children:r})=>{const i=xRt(t,r);if(i===null){const a=e;return h.jsx(a,{href:t,title:n,children:r})}return h.jsx(SRt,{citation:i,title:n})},_xe=e=>$tt(e)?"artifact":e.startsWith("data:")?"data":e.startsWith("blob:")?"blob":e.startsWith("http://")||e.startsWith("https://")?"http":e.startsWith("file://")||e.startsWith("/")||e.startsWith("~")?"path":"other",Txe=e=>{const t=_xe(e);return t==="other"?"path":t},LH={id:"open-file",label:"Open file"},kRt={id:"show-in-canvas",label:"Show in canvas"},PRt={id:"save-as",label:"Save as…"},FH={id:"open-folder",label:"Open folder"},BH={id:"copy-file-path",label:"Copy file path"},Mg={id:"copy-image",label:"Copy image"},_Rt={id:"copy-image-url",label:"Copy image URL"},TRt={id:"open-in-browser",label:"Open in browser"};function Rxe(e,{canShowInCanvas:t,source:n,mediaKind:r,artifactPathActions:i,canExpand:a}){const o=[...t?[kRt]:[],...a?[{id:"expand-image",label:"Expand image"}]:[]];switch(e){case"artifact":return[...o,...i?[LH,FH,BH]:[],PRt,...r==="video"||r==="audio"?[]:[Mg]];case"path":return[...o,LH,FH,BH,...r==="video"||r==="audio"?[]:[Mg]];case"data":return[...o,Mg];case"blob":return[Mg];case"http":return[...RRt(n)?[Mg]:[],_Rt,TRt];case"other":return[]}}const Xxe=(e,t)=>Rxe(e,t).length>0;function RRt(e){try{const t=new URL(e),n=t.hostname==="localhost"||t.hostname==="127.0.0.1";return t.protocol==="http:"&&n&&(t.port==="1111"||t.port==="8080")}catch{return!1}}const _U=e=>e.startsWith("file://")?e.slice(7):e;function XRt(e){const t=e.indexOf(",");if(t===-1)throw new Error("Malformed data URL");const n=e.slice(5,t),r=e.slice(t+1),i=n.split(";")[0]||"application/octet-stream";if(n.endsWith(";base64")){const s=atob(r),l=new Uint8Array(s.length);for(let c=0;c<s.length;c+=1)l[c]=s.charCodeAt(c);return new Blob([l],{type:i})}const a=decodeURIComponent(r),o=new Uint8Array(a.length);for(let s=0;s<a.length;s+=1)o[s]=a.charCodeAt(s);return new Blob([o],{type:i})}async function HH(e,t,n){if(e==="data")return XRt(t);if(e==="blob"){const o=ife(n??t);if(o===null)throw new Error("These image bytes are not available in this window");return o}if(e==="http"){const o=await fetch(n??t);if(!o.ok)throw new Error(`The image server answered ${o.status}`);return o.blob()}const r=window.api?.readFileBytes;if(typeof r!="function")throw new Error("This window cannot read local files");const i=_U(t),a=await r(i);if(!a.success)throw new Error(a.error??`Could not read ${i}`);return new Blob([a.data],{type:Mz(i)})}const ERt=e=>e.trim().toLowerCase()!=="image/png";async function qRt(e){if(e.size===0)throw new Error("This image has no bytes to copy");if(!ERt(e.type))return e;const t=URL.createObjectURL(e);try{const n=await jRt(t);if(n.naturalWidth===0||n.naturalHeight===0)throw new Error("This image could not be decoded for the clipboard");const r=document.createElement("canvas");r.width=n.naturalWidth,r.height=n.naturalHeight;const i=r.getContext("2d");if(i===null)throw new Error("This window cannot re-encode the image for the clipboard");i.drawImage(n,0,0);const a=await new Promise(o=>{r.toBlob(o,"image/png")});if(a===null)throw new Error("This image could not be re-encoded for the clipboard");return a}finally{URL.revokeObjectURL(t)}}function jRt(e){return new Promise((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=()=>n(new Error("This image could not be decoded for the clipboard")),r.src=e})}const CRt=6e4;function ARt(e,t){const n=URL.createObjectURL(e),r=document.createElement("a");r.href=n,r.download=t,document.body.appendChild(r),r.click(),document.body.removeChild(r),window.setTimeout(()=>URL.revokeObjectURL(n),CRt)}const F1=new Map;function zRt(e,t){const n=F1.get(t);if(n)return n.holders+=1,n.promise;const r={holders:1,promise:null};return r.promise=(async()=>{try{const i=await su(e.childId?{op:"subagents.attachment",sessionId:e.sessionId,childId:e.childId,digest:t}:{op:"sessions.attachment",sessionId:e.sessionId,digest:t},null);if(i.kind!=="bytes")return null;const a=Lz(i.data,i.mimeType);return r.holders<=0?($v(a),null):(afe(t,a),a)}catch{return null}finally{F1.delete(t)}})(),F1.set(t,r),r.promise}class TU extends Error{constructor(){super("This item is no longer in the session"),this.name="AttachmentGoneError"}}async function Exe(e,t){const n=Fz(t),r=n?ife(n):null;if(r)return r;const i=await su(e.childId?{op:"subagents.attachment",sessionId:e.sessionId,childId:e.childId,digest:t}:{op:"sessions.attachment",sessionId:e.sessionId,digest:t},null);if(i.kind!=="bytes")throw i.status===404?new TU:new Error("These bytes are not available right now");return new Blob([i.data],{type:i.mimeType})}function URt(e){const t=F1.get(e);t&&(t.holders-=1)}function Dv(e,t){const n=e.data?`data:${e.mimeType};base64,${e.data}`:null,[r,i]=$.useState(()=>e.attachment?Fz(e.attachment):null),[a,o]=$.useState(!1),s=t?.sessionId??null,l=t?.childId??null;$.useEffect(()=>{const u=e.attachment;if(n||!u||!s)return;let O=!0;const d=_S(u);if(d)return i(d),o(!1),()=>{O=!1,TS(u)};i(null),o(!1);let f=!0;return zRt({sessionId:s,childId:l},u).then(p=>{if(f=!1,!!O){if(!p){o(!0);return}i(_S(u))}}),()=>{O=!1,f&&URt(u),TS(u)}},[e.attachment,n,s,l]);const c=n??r;return c?{state:"ready",url:c}:e.attachment&&s&&!a?{state:"resolving"}:{state:"missing"}}function RU(e,t){return Dv(e,t)}const DOn=Object.freeze(Object.defineProperty({__proto__:null,AttachmentGoneError:TU,fetchAttachmentBlob:Exe,useAttachmentSource:Dv,useAttachmentUrl:RU},Symbol.toStringTag,{value:"Module"})),WRt={"expand-image":h.jsx(Eue,{"aria-hidden":"true"}),"open-file":h.jsx(dv,{"aria-hidden":"true"}),"show-in-canvas":h.jsx(Xue,{"aria-hidden":"true"}),"save-as":h.jsx(Ov,{"aria-hidden":"true"}),"open-folder":h.jsx(Rp,{"aria-hidden":"true"}),"copy-file-path":h.jsx(Que,{"aria-hidden":"true"}),"copy-image":h.jsx(hk,{"aria-hidden":"true"}),"copy-image-url":h.jsx(Dze,{"aria-hidden":"true"}),"open-in-browser":h.jsx(Pue,{"aria-hidden":"true"})},KH=(e,t)=>t instanceof TU?`${e}: it is no longer in the session`:e,qxe=({file:e,src:t,label:n,open:r,onOpenChange:i,onCloseAutoFocus:a,triggerTabIndex:o,resolvePath:s,missing:l,onShowInCanvas:c,mediaKind:u,onExpand:O,saveName:d,resolveBytes:f,tooltip:p="Image actions","aria-label":m})=>{const g=Txe(e),y=Rxe(g,{canShowInCanvas:!!c,source:t??e,mediaKind:u,artifactPathActions:!!s,canExpand:!!O}).filter(x=>(x.id!=="save-as"||!!d)&&(!l||x.id==="copy-file-path"));if(y.length===0)return null;const v=async(x,k,T)=>{try{await navigator.clipboard.writeText(x),Of(k)}catch(_){console.error(`${T}: `,_),mi(T)}},S=async()=>{try{if(typeof ClipboardItem>"u")throw new Error("this window cannot write an image to the clipboard");const x=f?await f():await HH(g,e,t),k=await qRt(x);await navigator.clipboard.write([new ClipboardItem({[k.type]:k})]),Of("Image copied to clipboard")}catch(x){console.error("Failed to copy image: ",x),mi(KH("Failed to copy image",x))}},Q=async()=>{try{const x=f?await f():await HH(g,e,t);ARt(x,d??"download")}catch(x){console.error("Failed to save file: ",x),mi(KH("Failed to save file",x))}},b=async x=>{let k=_U(e);if(s&&["open-file","open-folder","copy-file-path"].includes(x.id))try{k=await s()}catch{mi(J("ui.canvas.files.prepareError"));return}switch(x.id){case"expand-image":O?.();return;case"open-file":AO(k);return;case"open-folder":xU(k);return;case"show-in-canvas":c?.();return;case"copy-file-path":v(k,"File path copied to clipboard","Failed to copy file path");return;case"copy-image":S();return;case"save-as":Q();return;case"copy-image-url":v(t??e,"Image URL copied to clipboard","Failed to copy image URL");return;case"open-in-browser":QU(t??e);return}},w=m??`Actions for ${n??"this image"}`;return h.jsxs(bA,{open:r,onOpenChange:i,children:[h.jsx(Yt,{content:p,children:h.jsx(wA,{asChild:!0,children:h.jsx(Xe,{variant:"ghost",size:"icon-sm",className:"bg-accent-wash","aria-label":w,tabIndex:o,onClick:x=>x.stopPropagation(),children:h.jsx(vj,{"aria-hidden":"true"})})})}),h.jsxs(SA,{onCloseAutoFocus:a,align:"end",className:"min-w-45",onClick:x=>x.stopPropagation(),children:[s&&h.jsx("div",{role:"note",className:q("max-w-64 px-2 py-1 text-meta text-ink-muted"),children:J("ui.canvas.files.pathCopyNote")}),y.map(x=>h.jsxs(jl,{onSelect:()=>b(x),children:[WRt[x.id],h.jsx("span",{children:x.label})]},x.id))]})]})},NRt=({src:e,alt:t,title:n,className:r})=>{const i=SP(),a=e??"",o=_xe(a);if(o==="other")return h.jsx("img",{src:e,alt:t,title:n,className:r});const s=i!==null&&o==="path",l=Xxe(o,{canShowInCanvas:s,source:a});return h.jsxs("span",{className:q("group/mdimg relative inline-block max-w-full"),children:[h.jsx("img",{src:e,alt:t,title:n,className:r}),l&&h.jsx("span",{"data-markdown-image":"",className:q("pointer-events-none absolute top-1 right-1 z-[2] opacity-0","transition-opacity duration-fast ease-out-quart","group-hover/mdimg:pointer-events-auto group-hover/mdimg:opacity-100","group-focus-within/mdimg:pointer-events-auto group-focus-within/mdimg:opacity-100","has-[[aria-expanded=true]]:pointer-events-auto has-[[aria-expanded=true]]:opacity-100"),children:h.jsx(qxe,{file:a,src:e,label:t,onShowInCanvas:s&&i?()=>{i.openInCanvas(a).then(c=>{c||AO(_U(a))})}:void 0})})]})};function YRt(){return{enter:{mathFlow:e,mathFlowFenceMeta:t,mathText:a},exit:{mathFlow:i,mathFlowFence:r,mathFlowFenceMeta:n,mathFlowValue:s,mathText:o,mathTextData:s}};function e(l){const c={type:"element",tagName:"code",properties:{className:["language-math","math-display"]},children:[]};this.enter({type:"math",meta:null,value:"",data:{hName:"pre",hChildren:[c]}},l)}function t(){this.buffer()}function n(){const l=this.resume(),c=this.stack[this.stack.length-1];c.type,c.meta=l}function r(){this.data.mathFlowInside||(this.buffer(),this.data.mathFlowInside=!0)}function i(l){const c=this.resume().replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),u=this.stack[this.stack.length-1];u.type,this.exit(l),u.value=c;const O=u.data.hChildren[0];O.type,O.tagName,O.children.push({type:"text",value:c}),this.data.mathFlowInside=void 0}function a(l){this.enter({type:"inlineMath",value:"",data:{hName:"code",hProperties:{className:["language-math","math-inline"]},hChildren:[]}},l),this.buffer()}function o(l){const c=this.resume(),u=this.stack[this.stack.length-1];u.type,this.exit(l),u.value=c,u.data.hChildren.push({type:"text",value:c})}function s(l){this.config.enter.data.call(this,l),this.config.exit.data.call(this,l)}}const GRt={tokenize:IRt,concrete:!0,name:"mathFlow"},JH={tokenize:ZRt,partial:!0};function IRt(e,t,n){const r=this,i=r.events[r.events.length-1],a=i&&i[1].type==="linePrefix"?i[2].sliceSerialize(i[1],!0).length:0;let o=0;return s;function s(v){return e.enter("mathFlow"),e.enter("mathFlowFence"),e.enter("mathFlowFenceSequence"),l(v)}function l(v){return v===36?(e.consume(v),o++,l):o<2?n(v):(e.exit("mathFlowFenceSequence"),ln(e,c,"whitespace")(v))}function c(v){return v===null||bt(v)?O(v):(e.enter("mathFlowFenceMeta"),e.enter("chunkString",{contentType:"string"}),u(v))}function u(v){return v===null||bt(v)?(e.exit("chunkString"),e.exit("mathFlowFenceMeta"),O(v)):v===36?n(v):(e.consume(v),u)}function O(v){return e.exit("mathFlowFence"),r.interrupt?t(v):e.attempt(JH,d,g)(v)}function d(v){return e.attempt({tokenize:y,partial:!0},g,f)(v)}function f(v){return(a?ln(e,p,"linePrefix",a+1):p)(v)}function p(v){return v===null?g(v):bt(v)?e.attempt(JH,d,g)(v):(e.enter("mathFlowValue"),m(v))}function m(v){return v===null||bt(v)?(e.exit("mathFlowValue"),p(v)):(e.consume(v),m)}function g(v){return e.exit("mathFlow"),t(v)}function y(v,S,Q){let b=0;return ln(v,w,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4);function w(T){return v.enter("mathFlowFence"),v.enter("mathFlowFenceSequence"),x(T)}function x(T){return T===36?(b++,v.consume(T),x):b<o?Q(T):(v.exit("mathFlowFenceSequence"),ln(v,k,"whitespace")(T))}function k(T){return T===null||bt(T)?(v.exit("mathFlowFence"),S(T)):Q(T)}}}function ZRt(e,t,n){const r=this;return i;function i(o){return o===null?t(o):(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),a)}function a(o){return r.parser.lazy[r.now().line]?n(o):t(o)}}function DRt(e){let n={}.singleDollarTextMath;return n==null&&(n=!0),{tokenize:r,resolve:MRt,previous:VRt,name:"mathText"};function r(i,a,o){let s=0,l,c;return u;function u(m){return i.enter("mathText"),i.enter("mathTextSequence"),O(m)}function O(m){return m===36?(i.consume(m),s++,O):s<2&&!n?o(m):(i.exit("mathTextSequence"),d(m))}function d(m){return m===null?o(m):m===36?(c=i.enter("mathTextSequence"),l=0,p(m)):m===32?(i.enter("space"),i.consume(m),i.exit("space"),d):bt(m)?(i.enter("lineEnding"),i.consume(m),i.exit("lineEnding"),d):(i.enter("mathTextData"),f(m))}function f(m){return m===null||m===32||m===36||bt(m)?(i.exit("mathTextData"),d(m)):(i.consume(m),f)}function p(m){return m===36?(i.consume(m),l++,p):l===s?(i.exit("mathTextSequence"),i.exit("mathText"),a(m)):(c.type="mathTextData",f(m))}}}function MRt(e){let t=e.length-4,n=3,r,i;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(r=n;++r<t;)if(e[r][1].type==="mathTextData"){e[t][1].type="mathTextPadding",e[n][1].type="mathTextPadding",n+=2,t-=2;break}}for(r=n-1,t++;++r<=t;)i===void 0?r!==t&&e[r][1].type!=="lineEnding"&&(i=r):(r===t||e[r][1].type==="lineEnding")&&(e[i][1].type="mathTextData",r!==i+2&&(e[i][1].end=e[r-1][1].end,e.splice(i+2,r-i-2),t-=r-i-2,r=i+2),i=void 0);return e}function VRt(e){return e!==36||this.events[this.events.length-1][1].type==="characterEscape"}function LRt(e){return{flow:{36:GRt},text:{36:DRt()}}}const ep=36,eK=e=>e!==null&&e<-2,tK=e=>e===null||e===32||e<0,nK=e=>e!==null&&e>=48&&e<=57,jxe=e=>{const t=e?.singleDollarTextMath??!0;return{tokenize:n,resolve:FRt,previous:BRt,name:"mathText"};function n(r,i,a){const o=this;let s=0,l=null,c,u;return O;function O(g){return r.enter("mathText"),r.enter("mathTextSequence"),d(g)}function d(g){return g===ep?(r.consume(g),s++,d):s<2&&!t||s===1&&(tK(g)||nK(g))?a(g):(r.exit("mathTextSequence"),f(g))}function f(g){return g===null?a(g):g===ep?(u=r.enter("mathTextSequence"),c=0,l=o.previous,m(g)):g===32?(r.enter("space"),r.consume(g),r.exit("space"),f):eK(g)?(r.enter("lineEnding"),r.consume(g),r.exit("lineEnding"),f):(r.enter("mathTextData"),p(g))}function p(g){return g===null||g===32||g===ep||eK(g)?(r.exit("mathTextData"),f(g)):(r.consume(g),p)}function m(g){return g===ep?(r.consume(g),c++,m):c===s?s===1&&(tK(l)||nK(g))?a(g):(r.exit("mathTextSequence"),r.exit("mathText"),i(g)):(u.type="mathTextData",p(g))}}};function FRt(e){let t=e.length-4,n=3,r,i;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(r=n;++r<t;)if(e[r][1].type==="mathTextData"){e[t][1].type="mathTextPadding",e[n][1].type="mathTextPadding",n+=2,t-=2;break}}for(r=n-1,t++;++r<=t;)i===void 0?r!==t&&e[r][1].type!=="lineEnding"&&(i=r):(r===t||e[r][1].type==="lineEnding")&&(e[i][1].type="mathTextData",r!==i+2&&(e[i][1].end=e[r-1][1].end,e.splice(i+2,r-i-2),t-=r-i-2,r=i+2),i=void 0);return e}function BRt(e){return e!==ep||this.events[this.events.length-1][1].type==="characterEscape"}const HRt=LRt().flow,KRt=jxe();function TP(e){const t=this.data();t.micromarkExtensions??=[],t.fromMarkdownExtensions??=[];const n=t.micromarkExtensions,r=t.fromMarkdownExtensions,i=e?.singleDollarTextMath===void 0?KRt:jxe(e);n.push({flow:HRt,text:{[ep]:i}}),r.push(YRt())}const JRt=({node:e,...t})=>h.jsx("div",{className:"lo-md-table-scroll",children:h.jsx("table",{...t})}),eXt=/\$(?!\d)(.+?)\$/,tXt=/\$\$([\s\S]+?)\$\$/,nXt=/\\begin\{([^}]+)\}([\s\S]+?)\\end\{\1\}/,rXt=/\\[a-zA-Z]+(\{[^}]*\})?/,rK=e=>eXt.test(e)||tXt.test(e)||nXt.test(e)?!0:rXt.test(e)&&(e.includes("\\frac")||e.includes("\\sum")||e.includes("\\int")||e.includes("\\sqrt")),iXt=e=>{const t=PP(e);if(t.length===1&&t[0].kind==="text")return null;let n="",r=!1;for(const i of t){if(i.kind==="text"){n+=i.text;continue}r=!0,n+="x".repeat(i.text.length)}return r?n:null},aXt=e=>PP(e).filter(t=>t.kind!=="text").length,oXt=e=>{if(!rK(e))return!1;const t=iXt(e);return t===null?!0:rK(t)||t.includes("$")?!1:aXt(e)<2},Kt="var(--color-ink)",bc="var(--color-ink-muted)",Sl="var(--color-surface)",Du="var(--color-elevated)",wc="var(--color-sunken)",oa="var(--color-hairline)",Mu="var(--color-control)",Xh="var(--color-accent)",Q0="var(--color-accent-wash)",sXt="var(--color-accent-alt-wash)",lXt="var(--color-on-accent)",cXt="var(--color-info)",Cxe="var(--color-info-wash)",uXt="var(--color-success)",Axe="var(--color-success-wash)",OXt="var(--color-warning)",l7="var(--color-warning-wash)",dXt="var(--color-warning-border)",lR="var(--color-danger)",c7="var(--color-danger-wash)",iK=[Q0,sXt,Cxe,Axe,l7,c7],Vu=e=>getComputedStyle(document.documentElement).getPropertyValue(e).trim(),fXt=()=>{const e={primaryColor:Vu("--color-accent"),secondaryColor:Vu("--color-success"),tertiaryColor:Vu("--color-info"),mainBkg:Vu("--color-elevated"),clusterBkg:Vu("--color-sunken"),clusterBorder:Vu("--color-hairline"),edgeLabelBackground:Vu("--color-surface"),quadrant1Fill:Vu("--color-accent-wash")};for(const[n,r]of Object.entries(e))r===""&&delete e[n];const t={darkMode:getComputedStyle(document.documentElement).colorScheme.includes("dark"),background:Sl,primaryTextColor:Kt,primaryBorderColor:Mu,secondaryTextColor:Kt,secondaryBorderColor:oa,tertiaryTextColor:Kt,tertiaryBorderColor:oa,lineColor:bc,arrowheadColor:bc,textColor:Kt,secondBkg:wc,border1:Mu,border2:oa,labelColor:Kt,nodeBkg:Du,nodeBorder:Mu,nodeTextColor:Kt,defaultLinkColor:bc,titleColor:Kt,noteBkgColor:l7,noteBorderColor:dXt,noteTextColor:Kt,actorBkg:Du,actorBorder:Mu,actorTextColor:Kt,actorLineColor:oa,signalColor:bc,signalTextColor:Kt,labelBoxBkgColor:Du,labelBoxBorderColor:oa,labelTextColor:Kt,loopTextColor:Kt,activationBkgColor:Q0,activationBorderColor:Xh,sequenceNumberColor:Sl,sectionBkgColor:wc,sectionBkgColor2:Sl,altSectionBkgColor:wc,excludeBkgColor:wc,taskBkgColor:Q0,taskBorderColor:Mu,taskTextColor:Kt,taskTextLightColor:Kt,taskTextDarkColor:Kt,taskTextOutsideColor:Kt,taskTextClickableColor:Xh,activeTaskBkgColor:Q0,activeTaskBorderColor:Xh,gridColor:oa,doneTaskBkgColor:wc,doneTaskBorderColor:oa,critBkgColor:c7,critBorderColor:lR,todayLineColor:Xh,transitionColor:bc,transitionLabelColor:Kt,stateLabelColor:Kt,stateBkg:Du,labelBackgroundColor:Sl,compositeBackground:wc,altBackground:wc,compositeTitleBackground:Du,compositeBorder:oa,innerEndBackground:Kt,specialStateColor:Kt,classText:Kt,attributeBackgroundColorOdd:Sl,attributeBackgroundColorEven:wc,rowOdd:Sl,rowEven:wc,errorBkgColor:c7,errorTextColor:lR,pieTitleTextColor:Kt,pieSectionTextColor:Kt,pieLegendTextColor:Kt,pieStrokeColor:Sl,pieOuterStrokeColor:oa,requirementBackground:Du,requirementBorderColor:Mu,requirementTextColor:Kt,relationColor:bc,relationLabelBackground:Sl,relationLabelColor:Kt,branchLabelColor:lXt,commitLabelColor:Kt,commitLabelBackground:Sl,tagLabelColor:Kt,tagLabelBackground:Q0,tagLabelBorder:Mu,quadrant2Fill:Cxe,quadrant3Fill:Axe,quadrant4Fill:l7,quadrant2TextFill:Kt,quadrant3TextFill:Kt,quadrant4TextFill:Kt,quadrantPointFill:Xh,archEdgeColor:bc,archEdgeArrowColor:bc,archGroupBorderColor:oa,scaleLabelColor:Kt,packet:{startByteColor:Kt,endByteColor:Kt,labelColor:Kt,titleColor:Kt,blockStrokeColor:Mu,blockFillColor:Du},radar:{axisColor:bc,axisStrokeWidth:2,axisLabelFontSize:12,curveOpacity:.5,curveStrokeWidth:2,graticuleColor:oa,graticuleStrokeWidth:1,graticuleOpacity:.3,legendBoxSize:12,legendFontSize:12},xyChart:{backgroundColor:Sl,titleColor:Kt,xAxisTitleColor:Kt,xAxisLabelColor:Kt,xAxisTickColor:oa,xAxisLineColor:oa,yAxisTitleColor:Kt,yAxisLabelColor:Kt,yAxisTickColor:oa,yAxisLineColor:oa,plotColorPalette:[Xh,cXt,uXt,OXt,lR].join(",")}};for(let n=0;n<5;n++)t[`surface${n}`]=Du,t[`surfacePeer${n}`]=oa;for(let n=0;n<8;n++)t[`fillType${n}`]=iK[n%iK.length];return{...t,...e}};let cR=null,aK=null;const hXt=async e=>{cR||(cR=ve(async()=>{const{default:n}=await import("./mermaid.core-DePJ3QoR.js").then(r=>r.b4);return{default:n}},__vite__mapDeps([8,1,2]),import.meta.url).then(({default:n})=>n));const t=await cR;return aK!==e&&(t.initialize({startOnLoad:!0,theme:"base",securityLevel:"loose",fontFamily:"var(--font-sans)",fontSize:14,suppressErrorRendering:!0,themeVariables:fXt()}),aK=e),t},oK=({className:e,copied:t,onZoomIn:n,onZoomOut:r,onReset:i,onSave:a,onCopy:o,children:s})=>h.jsxs("div",{className:q("absolute z-10 flex items-center gap-0.5 rounded-md bg-elevated p-1 shadow-overlay",e),children:[h.jsx(Yt,{content:"Zoom in",children:h.jsx(Xe,{variant:"ghost",size:"icon-sm","aria-label":"Zoom in",onClick:n,children:h.jsx(Iue,{})})}),h.jsx(Yt,{content:"Zoom out",children:h.jsx(Xe,{variant:"ghost",size:"icon-sm","aria-label":"Zoom out",onClick:r,children:h.jsx(Zue,{})})}),h.jsx(Yt,{content:"Drag the diagram to pan",children:h.jsx(Xe,{variant:"ghost",size:"icon-sm","aria-label":"Drag to pan",children:h.jsx(c9e,{})})}),h.jsx(Yt,{content:"Reset view",children:h.jsx(Xe,{variant:"ghost",size:"icon-sm","aria-label":"Reset view",onClick:i,children:h.jsx(mk,{})})}),h.jsx(Yt,{content:"Save as SVG",children:h.jsx(Xe,{variant:"ghost",size:"icon-sm","aria-label":"Save as SVG",onClick:a,children:h.jsx(Ov,{})})}),h.jsx(Yt,{content:t?"Copied":"Copy mermaid text",children:h.jsx(Xe,{variant:"ghost",size:"icon-sm","aria-label":t?"Copied":"Copy mermaid text",onClick:o,children:h.jsx(hk,{className:q(t&&"text-success")})})}),s]}),u7=({title:e,children:t})=>h.jsxs(Ll,{variant:"danger",role:"alert",className:"my-4",children:[h.jsx(E0,{children:e}),h.jsx(q0,{children:t})]});class pXt extends $.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("Mermaid Error Boundary caught an error:",t,n)}render(){return this.state.hasError?this.props.fallback||h.jsxs(u7,{title:"Mermaid diagram error",children:[this.state.error?.message||"An unexpected error occurred while rendering the diagram"," ","The error was contained within the diagram component."]}):this.props.children}}const mXt=$.memo(({chart:e,id:t})=>{const n=$.useRef(null),r=$.useRef(null),[i,a]=$.useState(null),[o,s]=$.useState(!0),[l,c]=$.useState(""),[u,O]=$.useState(!1),[d,f]=$.useState({scale:1,x:0,y:0}),[p,m]=$.useState({scale:1,x:0,y:0}),[g,y]=$.useState(!1),[v,S]=$.useState({x:0,y:0}),[Q,b]=$.useState("idle"),[w,x]=$.useState("idle"),k=Jn(U=>U.themeName),T=$.useCallback(async()=>{try{if(s(!0),a(null),c(""),!e||typeof e!="string"||e.trim().length===0)throw new Error("Invalid or empty chart content");const U=await hXt(k),H=t||`mermaid-${Date.now()}-${Math.floor(Math.random()*1e6)}`,{svg:D}=await U.render(H,e);if(!D||typeof D!="string"||D.trim().length===0)throw new Error("Mermaid failed to generate valid SVG output");c(D)}catch(U){console.error("Mermaid rendering error:",U);const H=U instanceof Error?U.message:"Failed to render mermaid diagram";a(H),c("")}finally{s(!1)}},[e,t,k]);$.useEffect(()=>{T().catch(U=>{console.error("Error in renderDiagram effect:",U),a("Failed to initialize diagram rendering"),s(!1)})},[T]);const _=$.useCallback(()=>{try{if(!l||!r.current)return 1;const H=r.current.getBoundingClientRect(),D=document.createElement("div");D.innerHTML=l;const V=D.querySelector("svg");if(!V)return 1;const se=V.getBoundingClientRect?.()?.width||Number.parseFloat(V.getAttribute("width")||"0")||V.viewBox?.baseVal?.width||800,B=V.getBoundingClientRect?.()?.height||Number.parseFloat(V.getAttribute("height")||"0")||V.viewBox?.baseVal?.height||600,K=H.width*.9/se,ne=H.height*.9/B;return Math.min(K,ne,1)}catch(U){return console.error("Error calculating fullscreen scale:",U),1}},[l]);$.useEffect(()=>{u&&l&&setTimeout(()=>{try{const U=_();m({scale:U,x:0,y:0})}catch(U){console.error("Error setting fullscreen transform:",U)}},100)},[u,l,_]);const E=$.useCallback((U=!1)=>{try{(U?m:f)(D=>({...D,scale:Math.min(D.scale*1.2,10)}))}catch(H){console.error("Error in zoom in:",H)}},[]),R=$.useCallback((U=!1)=>{try{(U?m:f)(D=>({...D,scale:Math.max(D.scale/1.2,.1)}))}catch(H){console.error("Error in zoom out:",H)}},[]),j=$.useCallback((U=!1)=>{try{const H=U?m:f;if(U){const D=_();H({scale:D,x:0,y:0})}else H({scale:1,x:0,y:0})}catch(H){console.error("Error in reset:",H)}},[_]),C=$.useCallback(()=>{if(l)try{const U=new Blob([l],{type:"image/svg+xml"}),H=URL.createObjectURL(U),D=document.createElement("a");D.href=H,D.download=`mermaid-diagram-${Date.now()}.svg`,document.body.appendChild(D),D.click(),document.body.removeChild(D),URL.revokeObjectURL(H)}catch(U){console.error("Failed to save SVG:",U)}},[l]),W=$.useCallback(async()=>{try{await navigator.clipboard.writeText(e),b("copied"),setTimeout(()=>b("idle"),1200)}catch(U){console.error("Failed to copy Mermaid chart text:",U)}},[e]),G=$.useCallback(async()=>{try{await navigator.clipboard.writeText(e),x("copied"),setTimeout(()=>x("idle"),1200)}catch(U){console.error("Failed to copy Mermaid chart text:",U)}},[e]),N=$.useCallback(U=>{try{y(!0),S({x:U.clientX,y:U.clientY}),U.preventDefault()}catch(H){console.error("Error in mouse down:",H)}},[]),Z=$.useCallback((U,H=!1)=>{try{if(!g)return;const D=U.clientX-v.x,V=U.clientY-v.y;(H?m:f)(B=>({...B,x:B.x+D,y:B.y+V})),S({x:U.clientX,y:U.clientY})}catch(D){console.error("Error in mouse move:",D)}},[g,v]),F=$.useCallback(()=>{try{y(!1)}catch(U){console.error("Error in mouse up:",U)}},[]),z=$.useCallback((U,H=!1)=>{try{U.preventDefault();const D=U.deltaY>0?.9:1.1;(H?m:f)(se=>({...se,scale:Math.min(Math.max(se.scale*D,.1),5)}))}catch(D){console.error("Error in wheel:",D)}},[]),M=$.useCallback(U=>{try{O(U)}catch(H){console.error("Error toggling fullscreen:",H)}},[]);if(i)return h.jsxs(u7,{title:"Mermaid diagram error",children:[i,h.jsx("span",{className:q("mt-2 block text-ink-muted"),children:"Chart"}),h.jsx("span",{className:q("mt-1 block whitespace-pre-wrap font-mono text-mono-sm"),children:e})]});const te=(U=!1)=>{try{const H=U?r:n,D=U?p:d;return h.jsx("div",{ref:H,className:q("mermaid flex w-full items-center justify-center",U?"h-full min-h-full":"h-auto min-h-50",g?"cursor-grabbing":"cursor-grab"),onMouseDown:N,onMouseMove:V=>Z(V,U),onMouseUp:F,onMouseLeave:F,onWheel:V=>z(V,U),children:o?h.jsx("div",{className:q("p-4 text-body-sm text-ink-muted"),children:"Loading diagram..."}):l?h.jsx("div",{className:q("flex h-full w-full items-center justify-center"),style:{transform:`translate(${D.x}px, ${D.y}px) scale(${D.scale})`,transformOrigin:"center center"},dangerouslySetInnerHTML:{__html:l}}):null})}catch(H){return console.error("Error rendering diagram content:",H),h.jsx(u7,{title:"Rendering error",children:"Failed to render diagram content."})}};return h.jsxs(h.Fragment,{children:[h.jsxs("div",{className:q("relative flex items-center justify-center overflow-hidden rounded-md bg-surface","[&_svg]:h-auto [&_svg]:min-h-100 [&_svg]:max-w-none [&_svg]:bg-transparent"),children:[te(!1),h.jsx(oK,{className:"top-2 right-2",copied:Q==="copied",onZoomIn:()=>E(!1),onZoomOut:()=>R(!1),onReset:()=>j(!1),onSave:C,onCopy:W,children:h.jsx(Yt,{content:"Fullscreen",children:h.jsx(Xe,{variant:"ghost",size:"icon-sm","aria-label":"Open diagram fullscreen",onClick:()=>M(!0),children:h.jsx(Eue,{})})})})]}),h.jsx(R$,{open:u,onClose:()=>M(!1),title:"Mermaid diagram",maxWidth:"xl",fullWidth:!0,dialogProps:{className:"h-[90vh] max-h-[90vh]"},children:h.jsxs("div",{className:q("relative flex h-[80vh] w-full items-center justify-center overflow-hidden","[&_svg]:h-auto [&_svg]:max-h-full [&_svg]:w-auto [&_svg]:max-w-full [&_svg]:bg-transparent"),children:[te(!0),h.jsx(oK,{className:"top-4 right-4",copied:w==="copied",onZoomIn:()=>E(!0),onZoomOut:()=>R(!0),onReset:()=>j(!0),onSave:C,onCopy:G,children:h.jsx(Yt,{content:"Close fullscreen",children:h.jsx(Xe,{variant:"ghost",size:"icon-sm","aria-label":"Close fullscreen",onClick:()=>M(!1),children:h.jsx(ea,{})})})})]})})]})}),gXt=$.memo(e=>h.jsx(pXt,{children:h.jsx(mXt,{...e})}));let zxe=!1,uR=null;const $Xt=()=>(uR||(uR=ve(()=>Promise.resolve({}),__vite__mapDeps([9]),import.meta.url).then(e=>(zxe=!0,e))),uR),yXt=/language-(\w+)/,vXt=JQ,bXt=new RegExp(`^[^${ba}\\d*+-]`),wXt=/\n$/,Uxe=({href:e,children:t})=>{const n=GSe(e),r=SP();return!n||n.kind==="other"?h.jsx("a",{href:e,target:"_blank",rel:"noopener noreferrer",children:t}):h.jsx("a",{href:n.target,"data-lo-kind":n.kind,"data-lo-target":n.target,draggable:!1,target:n.kind==="url"?"_blank":void 0,rel:n.kind==="url"?"noopener noreferrer":void 0,onClick:n.kind==="file"?i=>QXt(i,r):void 0,children:t})},SXt=e=>GSe(e)?.kind==="file",xXt=VSe,QXt=(e,t)=>{const n=e.currentTarget,r=n.getAttribute(MSe)??"file",i=n.getAttribute(xXt),a=oTt({kind:r,hasHighlight:bTt(n),canOpenInCanvas:SU(t,i)});if(a!=="browse"&&(e.preventDefault(),!(a==="hold"||!i))){if(a==="canvas"&&t){t.openInCanvas(i).then(o=>{o||AO(i)});return}AO(i)}},O7=(e,t)=>t==="href"&&SXt(e)?e:uhe(e),my={a:Uxe,table:JRt,img:NRt,code:({node:e,className:t,children:n,...r})=>yXt.exec(t??"")?.[1]==="mermaid"?h.jsx(gXt,{chart:String(n).replace(wXt,"")}):h.jsx("code",{className:t,...r,children:n})},kXt={...my,a:QRt(Uxe)},PXt=[IO],_Xt=[IO,TP],TXt=[IO,xP],RXt=[IO,TP,xP],XXt=[IO,_P,QP],EXt=[IO,TP,_P,QP],qXt=[IO,xP,_P,QP],jXt=[IO,TP,xP,_P,QP],CXt={"000":PXt,"001":XXt,"010":TXt,"011":qXt,100:_Xt,101:EXt,110:RXt,111:jXt},AXt=[],zXt=[iJe],Wxe=e=>$.useMemo(()=>{if(!(!e?.fontSize&&!e?.lineHeight))return{"--md-font-size":e.fontSize,"--md-line-height":e.lineHeight}},[e?.fontSize,e?.lineHeight]),Nxe=(e,t,n)=>{const r=$.useMemo(()=>oXt(e),[e]),[i,a]=$.useState(zxe),o=r&&i;return $.useEffect(()=>{if(!r||i)return;let s=!1;return $Xt().then(()=>{s||a(!0)}),()=>{s=!0}},[r,i]),{remarkPlugins:CXt[`${o?1:0}${t?1:0}${n?1:0}`],rehypePlugins:o?zXt:AXt}},Yxe=(e,t)=>{const[,n]=$.useState(0);$.useEffect(()=>{if(!t)return;const r=Ytt(e);if(r.length===0)return;let i=!0;const a=new Set(r),o=lTt(s=>{i&&s.some(l=>a.has(l))&&n(l=>l+1)});return DSe(r,window.api?.probeFiles,nle).then(()=>{i&&r.some(s=>ZSe(s)!=="unknown")&&n(s=>s+1)}),()=>{i=!1,o()}},[e,t])},gy=$.memo(({content:e,styleProps:t,className:n,linkify:r=!0,credentialCitations:i=!1})=>{const a=$.useMemo(()=>e.trim(),[e]),{remarkPlugins:o,rehypePlugins:s}=Nxe(a,r,i),l=Wxe(t);return Yxe(a,r),h.jsx("div",{className:q("lo-markdown",n),style:l,children:h.jsx(Jj,{remarkPlugins:o,rehypePlugins:s,urlTransform:O7,components:i?kXt:my,children:a})})});gy.displayName="MarkdownRenderer";const sK={...my,a:({children:e})=>h.jsx(h.Fragment,{children:e})},Gxe=$.memo(({source:e,closed:t})=>{const n=$.useMemo(()=>t?e:EH(e),[t,e]),r=$.useMemo(()=>{if(t)return null;const o=oxe(e);return o!==null&&!o.nested?o:null},[t,e]),{remarkPlugins:i,rehypePlugins:a}=Nxe(n,t,!1);if(Yxe(e,t),r!==null){const o=EH(r.before);return h.jsxs(h.Fragment,{children:[o.trim()!==""&&h.jsx(Jj,{remarkPlugins:i,rehypePlugins:a,urlTransform:O7,components:t?my:sK,children:o}),h.jsx(UXt,{info:r.info,body:r.body})]})}return h.jsx(Jj,{remarkPlugins:i,rehypePlugins:a,urlTransform:O7,components:t?my:sK,children:n})});Gxe.displayName="ParsedBlock";const UXt=({info:e,body:t})=>{const n=e.split(vXt)[0];return h.jsx("pre",{children:h.jsx("code",{className:n?`language-${n}`:void 0,children:t===""?"":`${t}${t.endsWith(`
867
867
  `)?"":`
868
868
  `}`})})},Ixe=({content:e,styleProps:t,className:n})=>{const r=$.useRef(null);r.current===null&&(r.current=QTt());const i=r.current;TTt(i,e);const{blockStart:a}=i,o=a+RTt(e.slice(a));let s=null,l=a;(i.kind==="other"||(i.kind==="list"||i.kind==="indented-code")&&bXt.test(e.slice(i.cursor)))&&i.fence===null&&i.blankRunStart>=a&&i.cursor<o&&e.slice(i.cursor,o).trim().length>0&&(s=e.slice(a,i.blankRunStart),l=i.cursor);const c=e.slice(l,o),u=i.blocks.map((d,f)=>({key:f,source:d,closed:!0}));s!==null&&u.push({key:i.blocks.length,source:s,closed:!0}),c!==""&&u.push({key:u.length,source:c,closed:!1});const O=Wxe(t);return h.jsx("div",{className:q("lo-markdown",n),style:O,children:u.map(d=>h.jsx(Gxe,{source:d.source,closed:d.closed},d.key))})};Ixe.displayName="StreamingMarkdown";const No=({isUser:e,children:t,className:n})=>e?h.jsx("div",{className:q("flex w-full justify-end",n),children:t}):h.jsx("div",{className:q("group relative w-full",n),children:t}),XU=e=>{const t=new Date(e);return t.setHours(0,0,0,0),t.getTime()},WXt=e=>{const t=new Date(e);return t.setHours(0,0,0,0),t.setDate(t.getDate()+1),Math.max(1,t.getTime()-e)};let EU=XU(Date.now()),aO=null;const B1=new Set,Zxe=()=>{aO!==null&&clearTimeout(aO),aO=setTimeout(()=>{aO=null,EU=XU(Date.now());for(const e of B1)e();Zxe()},WXt(Date.now())),aO.unref?.()},NXt=e=>(B1.add(e),EU=XU(Date.now()),Zxe(),()=>{B1.delete(e),B1.size===0&&aO!==null&&(clearTimeout(aO),aO=null)}),lK=()=>EU,YXt=()=>$.useSyncExternalStore(NXt,lK,lK),GXt=e=>new Date(e+1e3),IXt=()=>GXt(YXt()),MOn=e=>{if(!e)return"";try{const t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?"":yde(t,{year:"numeric",month:"long",day:"numeric"})}catch(t){return console.error("Error formatting calendar date:",t),""}},ZXt=(e,t=new Date)=>{if(e==null)return"";try{const n=e instanceof Date?e:new Date(e);if(Number.isNaN(n.getTime()))return"";const r=JGe(n,{hour:"numeric",minute:"2-digit",hour12:!0});if(n.toDateString()===t.toDateString())return r;const i=new Date(t);if(i.setDate(t.getDate()-1),n.toDateString()===i.toDateString())return`Yesterday ${r}`;const a=yde(n,{month:"short",day:"numeric"});return n.getFullYear()===t.getFullYear()?`${a}, ${r}`:`${a}, ${n.getFullYear()}, ${r}`}catch(n){return console.error("Error formatting turn timestamp:",n),""}},DXt=(e,t)=>{if(!e)return"";try{const n=e instanceof Date?e:new Date(e);return Number.isNaN(n.getTime())?"":eIe(n,{year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit",...t})}catch(n){return console.error("Error formatting calendar date-time:",n),""}},MXt={turn:"Sent",answer:"Answered",tool:"Ran"},Dxe=({timestamp:e,scope:t,className:n})=>{const r=e instanceof Date?e:new Date(e),i=IXt();if(Number.isNaN(r.getTime()))return null;const a=DXt(r,{hour12:!0});return h.jsx(Yt,{content:a,side:"bottom",delayDuration:1200,children:h.jsx("time",{dateTime:r.toISOString(),"data-stamp":t,"aria-label":`${MXt[t]} ${a}`,className:q("shrink-0 select-none whitespace-nowrap text-ink-dim text-meta",n),children:ZXt(r,i)})})},qU=({replies:e,onRemoveReply:t})=>h.jsxs("div",{className:"mb-2 flex flex-col gap-1.5 rounded-sm bg-sunken p-2",children:[h.jsxs("div",{className:"flex items-center gap-1.5 text-ink-dim",children:[h.jsx(n9e,{size:12,"aria-hidden":"true"}),h.jsx("span",{className:"text-meta",children:"Replying to"})]}),e.map(n=>h.jsxs("div",{className:"flex items-center gap-2 border-hairline border-l-2 py-0.5 pl-2",children:[h.jsx("span",{className:"flex-1 truncate text-body-sm text-ink-muted",title:n.text,children:n.text}),t&&h.jsx(Xe,{variant:"ghost",size:"icon-sm",className:"shrink-0 text-ink-dim hover:bg-elevated hover:text-ink",onClick:()=>t(n.id),"aria-label":"Remove reply",children:h.jsx(ea,{"aria-hidden":"true"})})]},n.id))]}),VXt=({children:e,className:t})=>h.jsx("span",{"aria-hidden":!0,className:q("flex size-3.5 shrink-0 [&_svg]:size-3.5",t),children:e}),LXt={hunk:"text-ink-muted",added:"text-success",removed:"text-danger",context:"text-ink-dim"},FXt=({line:e})=>h.jsx("span",{className:q(LXt[e.kind],"block"),children:e.text}),BXt=({diff:e,className:t})=>{const n=mEe(e);return h.jsxs("div",{className:q("max-h-[740px] overflow-y-auto overflow-x-hidden rounded-md bg-sunken p-3 font-mono text-ink text-mono-sm whitespace-pre-wrap break-words",t),children:[n.lines.map((r,i)=>h.jsx(FXt,{line:r},i)),n.hidden>0&&h.jsx("span",{className:"sticky -bottom-3 -mb-3 block bg-sunken pb-3 text-ink-dim",children:gEe(n.hidden)})]})},HXt=(e,t=72)=>{let i=e.replace(/```[\s\S]*?```/g," ").replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/\s+/g," ").trim();if(i.length>t){const a=i.slice(0,t),o=a.lastIndexOf(" ");i=`${a.slice(0,o>32?o:t).trimEnd()}…`}return i.replace(/[.!?…]+$/g,"").trimEnd()},cK=e=>e.startsWith("file://")?e.slice(7):e,KXt={READ:{verb:"Read",runningVerb:"Reading",icon:hz},WRITE:{verb:"Wrote",runningVerb:"Writing",icon:zue},EDIT:{verb:"Edited",runningVerb:"Editing",icon:b9e},CODE:{verb:"Ran code",runningVerb:"Running code",icon:kue},DELEGATE:{verb:"Delegated work",runningVerb:"Delegating work",icon:A9e},DONE:{verb:"Finished",runningVerb:"Finishing",icon:xA},ASK:{verb:"Asked",runningVerb:"Asking",icon:dk},BYE:{verb:"Ended the conversation",runningVerb:"Ending",icon:hze}},JXt={verb:"Worked on the request",runningVerb:"Working on the request",icon:kue},e4t=(e,t,n,r)=>{const i=e?KXt[e]:JXt;let a;if(t)a=cK(t);else if(n&&n.length>0){const s=n.filter(l=>!l.startsWith("data:"));s.length===1?a=cK(s[0]):s.length>1&&(a=`${s.length} files`)}const o=!a&&r?HXt(r):"";return{verb:i.verb,runningVerb:i.runningVerb,object:a,narration:o||void 0,icon:i.icon}},uK="min-h-5 py-0",t4t=({icon:e,verb:t,object:n,narration:r,running:i,failed:a,wrap:o})=>h.jsxs("span",{className:q("flex min-w-0 gap-2",o?"items-start":"items-center"),"aria-busy":i||void 0,children:[h.jsx(VXt,{className:q(a?"text-danger":"text-ink-dim",o&&KOe),children:e}),h.jsxs("span",{className:q(o?"min-w-0 whitespace-pre-wrap break-words":"truncate"),children:[h.jsxs("span",{...x5,className:q("select-text font-mono text-mono-sm",a?"text-danger":"text-ink-muted"),children:[t,r?":":null]}),n?h.jsxs("span",{...x5,className:"select-text font-mono text-ink-muted text-mono-sm",children:[" ",n]}):null,r?h.jsxs("span",{...x5,className:"select-text text-body-sm text-ink-muted",children:[" ",r]}):null]})]}),OK=({action:e,filePath:t,files:n,narration:r,running:i=!1,failed:a=!1,defaultOpen:o=!1,details:s,className:l,verbOverride:c,object:u,glyph:O,wrap:d,dense:f=!1})=>{const p=e4t(e,t,n,r),m=c??(i?p.runningVerb:p.verb),g=a?kp:p.icon,y=a||!c||!O?h.jsx(g,{}):O,v=h.jsx(t4t,{icon:y,verb:m,object:c?u:p.object,narration:c?r:p.narration,running:i,failed:a,wrap:d}),S=d?"firstLine":"center";return s?h.jsx($a,{summary:v,chevron:"leading",summaryAlign:S,defaultOpen:o,className:l,rowClassName:f?uK:void 0,triggerClassName:"-mx-2 rounded-sm px-2 hover:bg-elevated",children:s}):h.jsx($a,{disabled:!0,summary:v,summaryAlign:S,className:l,rowClassName:f?uK:void 0})},Mxe=8,n4t="… deeper values not shown",r4t="(empty)";function i4t(e){return`… ${e} more line${e===1?"":"s"}`}const dK=.5;function a4t(e,t,n,r){if(!Number.isFinite(t)||t<=0)return 0;let i=0;for(const a of e){if(a.height<=0)continue;const o=Math.max(1,Math.round(a.height/t));for(let s=1;s<=o;s++)a.top+s*t>n+r&&i++}return i}function Vxe(e){return e==null?"null":typeof e=="string"?e.trim()||null:typeof e=="number"||typeof e=="boolean"?String(e):null}function jU(e){return typeof e=="object"&&e!==null}function Lxe(e,t,n,r){if(n>Mxe){r.push({key:t,value:n4t,depth:n});return}if(jU(e)){for(const[a,o]of Object.entries(e))Lxe(o,t?`${t}.${a}`:a,n+1,r);return}const i=Vxe(e);i!==null&&r.push({key:t,value:i,depth:n})}function Fxe(e){if(!e)return[];const t=[];for(const[n,r]of Object.entries(e))Lxe(r,n,1,t);return t}const o4t=512;function s4t(e,t){if(t)return!0;if(!e)return!1;let n=o4t;const r=(i,a)=>{if(n--<=0||a>Mxe)return!0;if(!jU(i))return Vxe(i)!==null;for(const o of Object.values(i))if(r(o,a+1))return!0;return!1};for(const i of Object.values(e))if(r(i,1))return!0;return!1}function l4t(e){if(!e)return null;const t=e.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;let n;try{n=JSON.parse(t)}catch{return null}if(!jU(n))return null;const r=Fxe(n);return r.length>0?r:[{key:"",value:r4t,depth:1}]}const c4t=8,d7="max-h-[min(320px,40vh)]",Bxe=d7,u4t=({line:e})=>h.jsxs("div",{className:q("whitespace-pre-wrap break-words"),style:{paddingInlineStart:(e.depth-1)*c4t},children:[e.key?h.jsxs("span",{className:q("text-ink-muted"),children:[e.key,": "]}):null,h.jsx("span",{className:q("text-ink-dim"),children:e.value})]}),fK=({lines:e,label:t})=>h.jsx("div",{className:q("flex flex-col gap-1"),"data-detail-lines":t,children:e.map((n,r)=>h.jsx(u4t,{line:n},r))});function hK(e){const[t,n]=$.useState(0),[r,i]=$.useState(!1);return $.useLayoutEffect(()=>{const a=e.current;if(!a)return;const o=a.firstElementChild,s=()=>{const c=o??a,u=Number.parseFloat(getComputedStyle(c).lineHeight);if(!Number.isFinite(u)||u<=0){n(0),i(!1);return}const O=a.getBoundingClientRect(),d=c.getBoundingClientRect();i(d.height>O.height+dK);const f=c.children.length>0?Array.from(c.children):[c];n(a4t(f.map(p=>{const m=p.getBoundingClientRect();return{top:m.top,height:m.height}}),u,O.bottom,dK))};s(),a.addEventListener("scroll",s,{passive:!0});const l=new ResizeObserver(s);return l.observe(o??a),()=>{a.removeEventListener("scroll",s),l.disconnect()}}),{lines:t,overflowing:r}}const pK=({lines:e,overflowing:t})=>t?h.jsx("span",{className:q("mt-1 block text-ink-dim"),children:e>0?i4t(e):" "}):null,O4t=({args:e,output:t,isError:n,interrupted:r=!1,note:i=null})=>{const a=Fxe(e),o=l4t(t),s=$.useRef(null),l=$.useRef(null),c=hK(s),u=hK(l);return a.length===0&&!t&&!i?null:h.jsxs("div",{className:q("w-full rounded-md bg-sunken p-3 font-mono text-mono-sm"),children:[a.length>0&&h.jsxs("div",{"data-detail-section":"input",children:[h.jsx("div",{ref:s,className:q(d7,"overflow-auto"),children:h.jsx(fK,{lines:a,label:"input"})}),h.jsx(pK,{lines:c.lines,overflowing:c.overflowing})]}),i&&h.jsx("div",{className:q("whitespace-normal font-sans text-body-sm text-ink-muted",a.length>0&&"mt-3"),"data-detail-section":"note",children:i}),t&&h.jsxs("div",{className:q(a.length>0&&"mt-3"),"data-detail-section":"output",children:[h.jsx("span",{className:q("mb-1 block text-meta",n&&!r?"text-danger":"text-ink-dim"),children:r?"Interrupted":n?"Error":"Output"}),h.jsx("div",{ref:l,className:q(d7,"overflow-auto"),children:o?h.jsx(fK,{lines:o,label:"result-json"}):h.jsx("pre",{className:q("whitespace-pre font-mono",n&&!r?"text-danger":"text-ink"),children:t})}),h.jsx(pK,{lines:u.lines,overflowing:u.overflowing})]})]})},d4t="mcp__",f4t={bash:N9e,read:pk,write:bG,edit:bG,glob:Rp,grep:fv,todo:Vze,wake:fk,list_variables:xG,read_variable:xG,browser:wG,console:mz,project:lze,project_delete:G9e,web_search:wG,web_fetch:Ov,task:Bd,agent:Bd,send:Nue,peer:Wze,sessions:x9e};function h4t(e){const t=e.trim().toLowerCase(),n=f4t[t];return n||(t.startsWith(d4t)?Uue:B9e)}const p4t=pz,m4t=Jze,g4t=Hze,mK="min-h-5 py-0",gK={read:"text-info",mutate:"text-ink-muted",exec:"text-ink-muted",meta:"text-accent-alt",plain:"text-ink-muted"},$4t=(e,t)=>e==="running"?"text-accent":e==="error"||e==="not-run"?"text-danger":e==="receipt"?gK.plain:gK[iEe(t)],y4t=e=>e==="running"?"text-accent":e==="error"||e==="not-run"?"text-danger":"text-ink-muted",v4t=({added:e,removed:t})=>e<=0&&t<=0?null:h.jsxs("span",{className:q("hidden shrink-0 gap-1 font-mono text-mono-sm tabular-nums @[34rem]/toolrow:flex"),children:[e>0&&h.jsxs("span",{className:q("text-success"),children:["+",e]}),t>0&&h.jsxs("span",{className:q("text-danger"),children:["-",t]})]}),OR={running:"",success:"succeeded",error:"failed",interrupted:"interrupted","not-run":"never ran",partial:"",receipt:""},b4t=1e3;function w4t(e){const[t,n]=$.useState(()=>e===null?null:Math.max(0,(Date.now()-e)/1e3));return $.useEffect(()=>{if(e===null){n(null);return}const r=()=>n(Math.max(0,(Date.now()-e)/1e3));r();const i=window.setInterval(r,b4t);return()=>window.clearInterval(i)},[e]),t}const S4t=({outcome:e,deliveryState:t=null,durationS:n,startedAt:r})=>{const i=e==="running",a=w4t(i?r??null:null),o=e==="error"||e==="not-run",s=e==="partial",l=t?M4e[t]:void 0,c=s?l??null:o?l??OR[e]:null,O=q("font-medium text-meta",s?"text-warning":"text-danger",s&&"hidden @[19rem]/toolrow:inline"),d=s&&t?F4e[t]??null:null,f=s&&t?V4e[t]:void 0,p=s?t==="mailbox"?m4t:t==="unconfirmed"?g4t:null:e==="interrupted"?p4t:null,m=p&&s?"text-warning":"text-ink-dim",g=i?r==null?"":ec(a??0):jA(n);return h.jsxs("span",{className:q("flex shrink-0 items-center gap-1.5"),children:[c?h.jsx("span",{className:O,title:f,"aria-hidden":d?!0:void 0,children:c}):null,h.jsxs("span",{className:q("flex shrink-0 [&_svg]:size-3.5",p&&"size-3.5",m),children:[p?h.jsx(p,{"aria-hidden":!0}):null,!o&&OR[e]?h.jsx("span",{className:q("sr-only"),children:OR[e]}):null,d?h.jsx("span",{className:q("sr-only"),children:d}):null]}),h.jsx("span",{className:q("hidden w-[5ch] text-right font-mono text-ink-dim text-mono-sm tabular-nums @[19rem]/toolrow:inline"),children:g})]})},xO=({toolName:e,op:t="",verbless:n=!1,summary:r,summaryFallback:i=null,summaryHold:a=!1,outcome:o,deliveryState:s=null,durationS:l,startedAt:c=null,added:u=0,removed:O=0,details:d,defaultOpen:f=!1,className:p,media:m})=>{const g=o==="running",y=o==="error",v=h4t(e),S=uf(e),{verb:Q,object:b}=Ale(e,r,i,g,t,H4e(s)),w=h.jsxs("span",{className:q("flex min-w-0 flex-1 items-center gap-2"),children:[h.jsx("span",{"aria-hidden":!0,className:q("flex size-3.5 shrink-0 [&_svg]:size-3.5",$4t(o,e)),children:h.jsx(v,{})}),n?null:h.jsx("span",{"data-trace-verb":"",className:q("shrink-0 whitespace-nowrap text-body-sm",y4t(o)),title:S,children:Q}),h.jsx("span",{className:q("min-w-0 flex-1 truncate font-mono text-ink-muted text-mono-sm"),title:a?void 0:b,children:a?h.jsxs(h.Fragment,{children:[h.jsx("span",{className:"text-ink-dim","data-label-hold":"true","aria-hidden":!0,children:"…"}),h.jsx("span",{className:q("sr-only"),children:"pending"})]}):b}),h.jsx(v4t,{added:u,removed:O}),h.jsx(S4t,{outcome:o,deliveryState:s,durationS:l,startedAt:c})]}),x=g?{"data-glass-state":"running"}:void 0,k=g?"bg-elevated":y?"bg-danger-wash":"hover:bg-row-hover",T=d?h.jsx($a,{summary:w,chevron:"leading",defaultOpen:f,className:q("@container/toolrow",p),triggerData:x,rowClassName:mK,triggerClassName:q("-mx-2 rounded-sm px-2",k),children:d}):h.jsx($a,{disabled:!0,summary:w,triggerData:x,rowClassName:mK,className:q("@container/toolrow",(g||y)&&q("-mx-2 rounded-sm px-2",k),p)});return m?h.jsxs("div",{className:q("flex flex-col"),children:[T,m]}):T},x4t=3,Q4t=2;function k4t(e){const t={incoming:0,job_result:0,wake:0,monitor_prompt:0};let n=!1,r=!1;for(const{record:o}of e){const s=Qle(o);s&&(t[s]+=1),o.kind==="custom"&&(o.receipt?.expectsReply===!0&&(n=!0),o.receipt?.steer===!0&&(r=!0))}const i=[],a=(o,s,l)=>{o>0&&i.push(`${o} ${o===1?s:l}`)};return a(t.incoming,"incoming message","incoming messages"),a(t.job_result,"job result","job results"),a(t.wake,"wake receipt","wake receipts"),a(t.monitor_prompt,"monitor prompt","monitor prompts"),a(e.length-t.incoming-t.job_result-t.wake-t.monitor_prompt,"other receipt","other receipts"),n&&i.push("Reply requested"),r&&i.push("Steered"),i}const Hxe=e=>{const t=e.toLowerCase();return t==="read"||t==="grep"||t==="glob"||t==="ls"||t==="list"?"files":t==="search_the_web"||t==="web_search"||t==="search"?"web":t==="bash"||t==="exec"||t==="shell"||t==="run"?"commands":t==="edit"||t==="write"||t==="multiedit"?"edits":t==="task"||t==="delegate"?"delegated":t==="fetch"||t==="web_fetch"||t==="fetch_url"?"searches":null},Kxe=e=>{const t=new Map;let n=0;for(const a of e){const o=Hxe(a.name);o===null?n+=1:t.set(o,(t.get(o)??0)+1)}if(n>0||t.size>2){const a=Jxe(eQe(e));return{units:a.length===0?[`${e.length} actions`]:a,prose:!1}}const r=["files","searches","web","commands","edits","delegated"],i=[];for(const a of r){const o=t.get(a)??0;o!==0&&(a==="files"&&i.push(`Explored ${o} file${o===1?"":"s"}`),a==="searches"&&i.push(`${o} search${o===1?"":"es"}`),a==="web"&&i.push(`Searched the web ${o} time${o===1?"":"s"}`),a==="commands"&&i.push(`Ran ${o} command${o===1?"":"s"}`),a==="edits"&&i.push(`Edited ${o} file${o===1?"":"s"}`),a==="delegated"&&i.push(`Delegated ${o} task${o===1?"":"s"}`))}return i.length===0?{units:[`${e.length} actions`],prose:!0}:{units:[i.length===1?i[0]:`${i[0]}, ${i[1].charAt(0).toLowerCase()}${i[1].slice(1)}`],prose:!0}},P4t=e=>Kxe(e).units;function _4t(e){return P4t(e).join(" · ")}const dR={agent:{noun:"agent",plural:"agents"},team:{noun:"team",plural:"teams"},team_delete:{noun:"team deletion",plural:"team deletions"},hub:{noun:"subagent",plural:"subagents"},secret:{noun:"secret",plural:"secrets"},project:{noun:"project",plural:"projects"},project_delete:{noun:"project deletion",plural:"project deletions"},wake:{noun:"wake",plural:"wakes"},jobs:{noun:"job check",plural:"job checks"},console:{noun:"console",plural:"consoles"},network:{noun:"network call",plural:"network calls"},browser:{noun:"browser action",plural:"browser actions"},todo:{noun:"todo update",plural:"todo updates"},send:{noun:"message",plural:"messages"},ask:{noun:"question",plural:"questions"},wait:{noun:"wait",plural:"waits"},lsp:{noun:"code lookup",plural:"code lookups"},web_read:{noun:"page",plural:"pages"},list_variables:{noun:"variable lookup",plural:"variable lookups"},read_variable:{noun:"variable read",plural:"variable reads"},sessions:{noun:"session",plural:"sessions"}},fR=5,Jxe=e=>{if(e.length<=fR)return e.map(r=>r.label);const t=e.slice(0,fR),n=e.slice(fR).reduce((r,i)=>r+i.count,0);return[...t.map(r=>r.label),`and ${n} other action${n===1?"":"s"}`]},eQe=e=>{const t=new Map,n=(s,l)=>{const c=t.get(s);c?c.count+=1:t.set(s,{kind:l,count:1})};for(const s of e){const l=s.name.toLowerCase();if(l==="bash"||l==="exec"||l==="shell"||l==="run"){n("kind:shell",{noun:"shell",plural:null});continue}if(l==="eval"){n("kind:python",{noun:"python",plural:null});continue}const c=Hxe(s.name);if(c==="files")n("class:files",{noun:"file",plural:"files"});else if(c==="searches")n("class:searches",{noun:"search",plural:"searches"});else if(c==="web")n("class:web",{noun:"web search",plural:"web searches"});else if(c==="edits")n("class:edits",{noun:"edit",plural:"edits"});else if(c==="delegated")n("class:delegated",{noun:"task",plural:"tasks"});else if(l==="todo")(s.op??"").toLowerCase()==="view"?n("kind:todo:view",{noun:"todo read",plural:"todo reads"}):n("kind:todo",dR.todo);else if(l==="jobs")(s.op??"").toLowerCase()==="cancel"?n("kind:jobs:cancel",{noun:"job cancellation",plural:"job cancellations"}):n("kind:jobs",dR.jobs);else{const u=dR[l];if(u)n(`kind:${l}`,u);else{const O=uf(s.name);n(`name:${O}`,{noun:O,plural:null})}}}const r=["class:files","class:searches","class:web","kind:shell","kind:python","class:edits","class:delegated","kind:agent","kind:team","kind:hub"],i=[],a=(s,l)=>`${s} ${s===1||l.plural===null?l.noun:l.plural}`;for(const s of r){const l=t.get(s);l&&i.push({label:a(l.count,l.kind),count:l.count})}const o=[...t.entries()].filter(([s])=>!r.includes(s)).sort(([,s],[,l])=>l.count-s.count||s.kind.noun.localeCompare(l.kind.noun));for(const[,s]of o)i.push({label:a(s.count,s.kind),count:s.count});return i};function T4t(e){return e.running===!0?typeof e.startedAtMs!="number"?null:{startMs:e.startedAtMs,endMs:null}:typeof e.endedAtMs!="number"||typeof e.durationS!="number"?null:{startMs:e.endedAtMs-e.durationS*1e3,endMs:e.endedAtMs}}function R4t(e){let t=null,n=null,r=!1;for(const i of e){i.running===!0&&(r=!0);const a=T4t(i);a&&(t=t===null?a.startMs:Math.min(t,a.startMs),a.endMs!==null&&(n=n===null?a.endMs:Math.max(n,a.endMs)))}return t===null||n===null&&!r?null:{startedAtMs:t,endedAtMs:n,running:r}}function X4t(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n.executing===!0)return Ale(n.name,n.summary??"",null,!0,n.op)}return null}function E4t(e,t){let n=0;for(let r=e.length-1;r>=0&&t(e[r]);r-=1)n+=1;return n}function q4t(e,t){const n=[];let r=[];const i=()=>{if(r.length===0)return;const a=r.filter(u=>t.isReceipt?.(u)),o=r.filter(u=>t.isFoldable(u)).map(u=>{const O={name:t.nameOf(u),failed:t.failedOf(u),durationS:t.durationOf?t.durationOf(u):null,startedAtMs:t.startedAtOf?t.startedAtOf(u):null,endedAtMs:t.endedAtOf?t.endedAtOf(u):null};return t.summaryOf&&(O.summary=t.summaryOf(u)),t.opOf&&(O.op=t.opOf(u)),t.runningOf&&(O.running=t.runningOf(u)),t.executingOf&&(O.executing=t.executingOf(u)),O}),s=a.length?t.receiptSummaryOf?.(a)??[]:[],l=s.length>0?s:a.length>0?[`${a.length} receipt${a.length===1?"":"s"}`]:[],c=t.isReceipt?E4t(r,t.isReceipt):0;if(o.length>=x4t||c>=Q4t){const u=o.length===0?{units:[],prose:!1}:l.length>0?{units:Jxe(eQe(o)),prose:!1}:Kxe(o);n.push({kind:"run",id:r[0].record.id,gap:r[0].gap,rows:r,actions:o,summary:{units:[...u.units,...l],prose:u.prose},failedCount:o.filter(O=>O.failed).length,span:R4t(o),live:X4t(o)})}else for(const u of r)n.push({kind:"row",row:u});r=[]};for(const a of e){if((a.gap==="turn"||a.gap==="first")&&i(),t.isFoldable(a)||t.isReceipt?.(a)){r.push(a);continue}i(),n.push({kind:"row",row:a})}return i(),n}const $K=e=>{const t=[];for(const n of e)if(!(n.record.kind!=="tool"&&!(n.record.kind==="custom"&&n.record.customType==="hub_message")))for(const r of n.record.images??[])x$(r)&&t.push(r);return t},H1=5,j4t=(e,{uncapped:t=!1}={})=>t?{shown:Math.max(e,0),more:0}:e<H1?{shown:Math.max(e,0),more:0}:{shown:H1-1,more:e-(H1-1)},C4t=e=>{const t=H1-1;if(e<=0)return[];if(e<=t)return[e];const n=Array.from({length:Math.floor(e/t)},()=>t),r=e%t;return r===1?(n[n.length-1]=t-1,n.push(2)):r>1&&n.push(r),n},qx=e=>e<=0?null:`${e} image${e===1?"":"s"}`;function jx(e){return e.record.kind==="tool"?e.record.durationS:null}function tQe(e){let t=null;for(const n of e){const r=jx(n);typeof r=="number"&&(t=(t??0)+r)}return t}function A4t(e,t){const n=new Map,r=t.opensRun??(l=>l.gap==="turn"||l.gap==="first");let i=0,a=0,o=null,s=null;for(const l of e){if(r(l)&&(i=0,a=0,o=null,s=null),t.isAction(l)){i+=1,t.failedOf(l)&&(a+=1,s??=l.record.id);const c=t.durationOf?t.durationOf(l):null;typeof c=="number"&&(o=(o??0)+c)}l.closesTurn&&n.set(l.record.id,{actions:i,failed:a,durationS:o,firstFailedId:s})}return n}const z4t="min-h-5 py-0",U4t=1e3;function W4t(e){const[t,n]=$.useState(()=>Date.now());return $.useEffect(()=>{if(!e)return;const r=()=>n(Date.now());r();const i=window.setInterval(r,U4t);return()=>window.clearInterval(i)},[e]),t}const N4t=({summary:e,span:t,live:n,open:r,onOpenChange:i,className:a,condensedMedia:o,mediaCount:s=0,recordIds:l,children:c})=>{const u=W4t(t?.running===!0),O=t===null?null:Math.max(0,((t.running?u:t.endedAtMs??u)-t.startedAtMs)/1e3),d=O===null?"":jA(O),f=$.useRef(null),p=()=>{f.current?.querySelector("button[aria-expanded]")?.focus(),i(!0)};return h.jsxs("div",{ref:f,className:a,"data-fold-ids":l.join(" "),children:[h.jsx($a,{animate:r||!o,open:r,onOpenChange:i,rowClassName:z4t,triggerClassName:q("-mx-2 rounded-sm px-2","hover:bg-row-hover"),summary:h.jsxs("span",{className:q("flex min-w-0 flex-1 items-center gap-2"),children:[n!==null&&!r&&h.jsxs(h.Fragment,{children:[h.jsxs("span",{"data-fold-live":"",className:q("min-w-0 shrink-[100000] truncate"),title:`${n.verb} ${n.object}`,children:[h.jsx("span",{className:q("text-accent"),children:n.verb})," ",h.jsx("span",{className:q("font-mono text-mono-sm text-ink-muted"),children:n.object})]}),h.jsx("span",{"aria-hidden":!0,className:q("text-ink-dim text-meta"),children:"·"})]}),h.jsx("span",{className:q("min-w-0 break-words text-body-sm text-ink-muted"),title:e.units.join(" · "),"data-fold-summary":"",children:e.units.map((m,g)=>h.jsxs($.Fragment,{children:[g>0&&h.jsx("span",{"aria-hidden":"true",children:" · "}),h.jsx("span",{className:q(e.prose?"whitespace-normal":"whitespace-nowrap"),children:m})]},m))}),qx(s)!==null&&h.jsxs(h.Fragment,{children:[h.jsx("span",{"aria-hidden":!0,className:q("text-ink-dim text-meta"),children:"·"}),h.jsx("span",{className:q("shrink-0 text-ink-muted text-meta"),children:qx(s)})]}),d!==""&&h.jsxs(h.Fragment,{children:[h.jsx("span",{"aria-hidden":!0,className:q("text-ink-dim text-meta"),children:"·"}),h.jsx("span",{"data-fold-span":"",className:q("shrink-0 font-mono text-ink-dim text-mono-sm tabular-nums"),children:d})]})]}),children:h.jsx("div",{className:q("flex flex-col"),children:c})}),!r&&o&&o(p)]})},yK=["⣾","⣽","⣻","⢿","⡿","⣟","⣯","⣷"],Y4t=80,G4t=1e3,nQe=({activity:e,phase:t,startedAt:n,clock:r,className:i})=>{const[a,o]=$.useState(0),[s,l]=$.useState(()=>n===void 0?0:Math.floor((Date.now()-n)/1e3)),[c,u]=$.useState(!1),O=r!==!1&&!c,d=Ez("(prefers-reduced-motion: reduce)"),f=$.useRef(n??Date.now()),p=$.useRef(t),m=$.useRef(n);if(p.current!==t)p.current=t,m.current=n,f.current=n??Date.now(),c&&u(!1),l(0);else if(m.current!==n){const v=m.current!==void 0&&n===void 0;m.current=n,u(v),v||(f.current=n,l(Math.floor((Date.now()-n)/1e3)))}const g=$.useRef(r!==!1),y=$.useRef(t);return $.useEffect(()=>{const v=r!==!1,S=g.current,Q=y.current===t;g.current=v,y.current=t,!S&&v&&Q&&l(Math.floor((Date.now()-f.current)/1e3))},[r,t]),$.useEffect(()=>{const v=O?window.setInterval(()=>l(Math.floor((Date.now()-f.current)/1e3)),G4t):null;if(d)return o(0),()=>{v!==null&&window.clearInterval(v)};const S=window.setInterval(()=>o(Q=>(Q+1)%yK.length),Y4t);return()=>{window.clearInterval(S),v!==null&&window.clearInterval(v)}},[d,O]),h.jsxs("div",{className:q("flex items-center gap-2",i),"data-lo-working-line":!0,"aria-live":"polite",children:[h.jsx("span",{"aria-hidden":!0,className:q("w-[1ch] shrink-0 select-none font-mono text-ink-muted text-mono-sm"),children:yK[a]}),h.jsx("span",{className:q("min-w-0 truncate font-mono text-ink-dim text-mono-sm"),children:e}),h.jsx("span",{"aria-hidden":!0,className:q("w-[6ch] shrink-0 font-mono text-ink-dim text-mono-sm tabular-nums"),children:O?ec(s):""})]})},I4t="min-h-5 py-0",Lu=()=>h.jsx("span",{"aria-hidden":!0,className:q("text-ink-dim text-meta"),children:"·"}),Z4t=({recordIds:e,segmentIds:t,anchorRecordId:n,className:r,durationS:i,actionCount:a,partial:o=!1,title:s,stampTs:l,label:c=null,completed:u=!1,open:O,onOpenChange:d,children:f,condensedMedia:p,mediaCount:m=0,group:g=null,episode:y=null})=>{const v=o?`${a}+ actions`:a===1?"1 action":`${a} actions`,S=`At least ${a===1?"1 action":`${a} actions`} — earlier rows of this turn are not loaded`,Q=y?.receipts??g?.count,b=Q===void 0?null:`At least ${Q} messages — earlier rows are not loaded`,w=$.useRef(null),x=()=>{w.current?.querySelector("button[aria-expanded]")?.focus(),d(!0)};return h.jsxs("div",{ref:w,className:q("border-b border-hairline pb-3",r),"data-turn-summary":"","data-run-ids":e.join(" "),"data-segment-ids":t?.join(" "),"data-segment-complete":u&&!y?.active?"true":void 0,"data-segment-active":y?.active?"true":void 0,"data-record-id":n,children:[h.jsx($a,{open:O,onOpenChange:d,chevron:"trailing",rowClassName:I4t,triggerClassName:q("-ml-2 -mr-2 w-[calc(100%+1rem)] rounded-sm pl-2 pr-6","hover:bg-row-hover"),chevronClassName:q("-mr-6","text-ink-muted"),summary:h.jsxs("span",{className:q("flex min-w-0 flex-1 items-center gap-2"),title:s??void 0,children:[c!==null&&h.jsx("span",{className:q("shrink-0 text-body-sm text-ink-muted"),"data-segment-label":"",children:c}),u&&!y?.active&&h.jsx(h.Fragment,{children:h.jsx(xA,{"aria-hidden":!0,className:q("size-3.5 shrink-0 text-success")})}),y?.active?h.jsxs(h.Fragment,{children:[c!==null&&h.jsx(Lu,{}),h.jsx("span",{className:"shrink-0 text-body-sm text-ink-muted",title:o?b??void 0:void 0,"aria-label":o?b??void 0:void 0,children:o?`${y.receipts}+`:y.receipts}),a>0&&h.jsxs(h.Fragment,{children:[h.jsx(Lu,{}),h.jsx("span",{className:"shrink-0 text-body-sm text-ink-muted",title:o?S:void 0,children:v})]}),y.phaseLine!==null&&h.jsxs(h.Fragment,{children:[h.jsx(Lu,{}),h.jsx(nQe,{activity:y.phaseLine.activity,phase:y.phaseLine.phase,startedAt:y.phaseLine.startedAt,clock:y.phaseLine.clock,className:"min-w-0"})]})]}):g!==null?h.jsxs(h.Fragment,{children:[c!==null&&h.jsx(Lu,{}),h.jsx("span",{className:q("shrink-0 text-body-sm text-ink-muted"),title:o?b??void 0:void 0,"aria-label":o?b??void 0:void 0,children:o?`${y?.receipts??g.count}+`:`${y?.receipts??g.count}`}),g.spanS!==null&&h.jsxs(h.Fragment,{children:[h.jsx(Lu,{}),h.jsx("span",{className:q("shrink-0 text-body-sm text-ink-muted"),children:ec(g.spanS)})]})]}):h.jsxs(h.Fragment,{children:[c!==null&&(i!==null||a>0)&&h.jsx(Lu,{}),i!==null&&h.jsxs("span",{className:q("shrink-0 text-body-sm text-ink-muted"),children:["Took ",ec(i)]}),i!==null&&a>0&&h.jsx(Lu,{}),a>0&&h.jsx("span",{className:q("shrink-0 text-body-sm text-ink-muted"),title:o?S:void 0,"aria-label":o?S:void 0,children:v})]}),qx(m)!==null&&h.jsxs(h.Fragment,{children:[h.jsx(Lu,{}),h.jsx("span",{className:q("shrink-0 text-body-sm text-ink-muted"),children:qx(m)})]}),u&&!y?.active&&h.jsx("span",{className:q("sr-only"),children:"completed"}),l!==null&&h.jsx("span",{className:q("ml-auto"),children:h.jsx(Dxe,{timestamp:l,scope:"answer"})})]}),children:h.jsx("div",{className:q("flex flex-col"),children:f})}),!O&&p&&h.jsx("div",{className:q("pb-2"),children:p(x)})]})},rQe="lo-missing-session-notice",zO=({children:e,className:t,boundary:n="hairline",...r})=>h.jsx("div",{className:q("flex max-w-full items-center justify-center overflow-hidden","min-h-16 min-w-16 rounded-sm",n==="control"?["bg-media-surface","border border-transparent","transition-colors duration-fast ease-out-quart","group-hover/tile:border-control group-focus-visible/tile:border-control"]:["border border-hairline","bg-sunken"],t),...r,children:e}),D4t="could not be displayed. It may have been moved, renamed, or deleted.",CU="could not be displayed. Its stored copy is not available to this reader.",iQe="could not be played. Its stored copy is not available to this reader.",aQe=iQe,_f=({name:e,detail:t=D4t,className:n,compact:r=!1})=>r?h.jsx("div",{className:q("flex h-[78px] w-[117px] items-center justify-center rounded-sm border border-control bg-sunken",n),role:"img","aria-label":`${e} ${t}`,title:`${e} ${t}`,children:h.jsx(SG,{className:"size-4 shrink-0 text-ink-dim","aria-hidden":!0})}):h.jsxs("div",{className:q("flex w-fit max-w-full items-center gap-2.5 rounded-sm border border-hairline bg-sunken px-3 py-2",n),children:[h.jsx(SG,{className:"size-4 shrink-0 text-ink-dim","aria-hidden":!0}),h.jsxs("span",{className:"min-w-0 text-body-sm text-ink-muted",children:[h.jsx("span",{className:"truncate font-mono text-ink text-mono-sm",children:e}),` ${t}`]})]}),Uw=(e,t,n)=>Math.min(n,Math.max(t,e)),Fi=ta((e,t)=>{const n=new Map,r=o=>{o.onended=()=>{const{ownerId:l,handlers:c}=t();l!==null&&(e({status:"ended",currentTime:o.currentTime}),c?.onEnded?.())},o.onerror=()=>{const{ownerId:l,handlers:c}=t();l!==null&&(e({status:"error"}),c?.onError?.())};const s=()=>{e({duration:Number.isFinite(o.duration)?o.duration:0,currentTime:o.currentTime})};o.onloadedmetadata=s,o.ondurationchange=s,o.ontimeupdate=()=>{e({currentTime:o.currentTime})}},i=()=>{const o=t().element;if(o)return o;const s=new Audio;return s.preload="metadata",r(s),oQe?.(s),e({element:s}),s},a=o=>{o.pause(),o.removeAttribute("src"),o.load?.()};return{element:null,ownerId:null,url:null,status:"idle",currentTime:0,duration:0,volume:1,playbackRate:1,generation:0,handlers:null,play:async(o,s,l)=>{const c=t().generation+1,u=i();a(u),u.volume=t().volume,u.playbackRate=t().playbackRate,u.src=s,e({ownerId:o,url:s,status:"loading",currentTime:0,duration:Number.isFinite(u.duration)?u.duration:0,generation:c,handlers:l??null});try{await u.play()}catch{return t().generation!==c||(e({status:"error"}),t().handlers?.onError?.()),!1}if(t().generation!==c)return!1;const O=n.get(o);return O!==void 0&&(t().seek(o,O),n.delete(o)),e({status:"playing"}),!0},resume:async o=>{const{element:s,ownerId:l,status:c}=t();if(!s||l!==o||c!=="paused"&&c!=="ended")return!1;const u=t().generation+1;e({generation:u,status:"loading"}),c==="ended"&&(s.currentTime=0);try{await s.play()}catch{return t().generation!==u||(e({status:"error"}),t().handlers?.onError?.()),!1}return t().generation!==u?!1:(e({status:"playing"}),!0)},pause:o=>{const{element:s,ownerId:l}=t();!s||l!==o||(s.pause(),e({generation:t().generation+1,status:"paused",currentTime:s.currentTime}))},toggle:async(o,s,l)=>{const{ownerId:c,status:u}=t();return c===o&&u==="playing"?(t().pause(o),!1):c===o&&(u==="paused"||u==="ended")?t().resume(o):t().play(o,s,l)},seek:(o,s)=>{const{element:l,ownerId:c,duration:u}=t();if(!l||c!==o){n.set(o,Math.max(0,s));return}const O=Uw(s,0,u>0?u:s);l.currentTime=O,e({currentTime:O})},scrub:(o,s)=>{const{element:l,ownerId:c,duration:u}=t();if(!l||c!==o){n.set(o,Math.max(0,s));return}const O=Uw(s,0,u>0?u:s);typeof l.fastSeek=="function"?l.fastSeek(O):l.currentTime=O},stop:o=>{const{element:s,ownerId:l}=t();s&&(o!==void 0&&l!==o||(a(s),e({generation:t().generation+1,ownerId:null,url:null,status:"idle",currentTime:0,duration:0,handlers:null})))},setVolume:o=>{const s=Uw(o,0,1),l=t().element;l&&(l.volume=s),e({volume:s})},setPlaybackRate:o=>{const s=Uw(o,.5,4),l=t().element;l&&(l.playbackRate=s),e({playbackRate:s})}}});let oQe=null;function VOn(e){oQe=e}function hR(){return Fi.getState().element}const f7=4,sQe=2,M4t=2,V4t=4,lQe=f7+sQe,L4t=.8,F4t=24,vK=.3,bK=1;function B4t(e){return!Number.isFinite(e)||e<=0?1:Math.max(1,Math.floor((e+sQe)/lQe))}function H4t(e,t){const n=Math.min(e,t-e);return Number.isFinite(n)?Math.max(0,Math.min(1,n/F4t)):0}function K4t(e,t){if(t<=0)return[];if(e.length===0)return new Array(t).fill(0);const n=new Array(t),r=e.length/t;for(let i=0;i<t;i+=1){const a=Math.floor(i*r),o=Math.max(a+1,Math.floor((i+1)*r));let s=0;for(let l=a;l<o&&l<e.length;l+=1){const c=e[l];Number.isFinite(c)&&c>s&&(s=c)}n[i]=Math.max(0,Math.min(1,s))}return n}function J4t(e,t,n){const r=B4t(t),i=e===null?null:K4t(e,r),a=[],o=Math.max(1,r-1);for(let s=0;s<r;s+=1){const l=s*lQe,c=l+f7/2,O=(i===null?0:i[s])*n*L4t,d=Math.max(V4t,Math.round(O)),f=vK+(bK-vK)*(s/o);a.push({x:l,width:f7,height:d,alpha:Math.min(bK,f)*H4t(c,t)})}return a}function s$(e){if(!Number.isFinite(e)||e<=0)return"0:00";const t=Math.floor(e),n=Math.floor(t/60),r=t%60;return`${n}:${r.toString().padStart(2,"0")}`}function eEt(e,t,n){if(!Number.isFinite(e)||!Number.isFinite(t)||t<=0)return 0;const r=Math.max(0,Math.min(1,e/t));return!Number.isFinite(n)||n<=0?0:r*n}function tEt(e,t){return!Number.isFinite(e)||!Number.isFinite(t)||t<=0?0:Math.max(0,Math.min(1,e/t))}function wK(e,t){return`${s$(e)} of ${s$(t)}`}const nEt=4,SK=1,rEt="flex min-h-11 min-w-11 shrink-0 items-center justify-center text-ink-muted transition-colors duration-fast ease-out-quart hover:text-ink disabled:pointer-events-none disabled:text-ink-disabled",cQe=({ownerId:e,src:t,label:n,peaks:r,durationHint:i=null,variant:a="full",className:o})=>{const s=Fi(H=>H.ownerId===e),l=Fi(H=>H.ownerId===e?H.status:"idle"),c=Fi(H=>H.ownerId===e?H.duration:0),[u,O]=$.useState(!1),[d,f]=$.useState(!1);$.useEffect(()=>{(l==="loading"||l==="playing")&&f(!1)},[l]);const p=c>0?c:i??0,m=s&&l==="playing",g=s&&l==="loading",y=d||s&&l==="error",v=$.useRef(null),S=$.useRef(null),Q=$.useRef(null),b=$.useRef(null),w=$.useRef(null),[x,k]=$.useState({width:0,height:0,dpr:1});$.useEffect(()=>{const H=v.current;if(!H)return;const D=()=>{const se=H.getBoundingClientRect();k({width:se.width,height:se.height,dpr:window.devicePixelRatio||1})};D();const V=new ResizeObserver(D);return V.observe(H),()=>V.disconnect()},[]);const T=$.useCallback(H=>{if(!H||x.width<=0)return;const D=H.getContext("2d");if(!D)return;H.width=Math.max(1,Math.round(x.width*x.dpr)),H.height=Math.max(1,Math.round(x.height*x.dpr)),D.setTransform(x.dpr,0,0,x.dpr,0,0),D.clearRect(0,0,x.width,x.height);const V=getComputedStyle(H).color,se=J4t(r,x.width,x.height);D.fillStyle=V;for(const B of se)D.globalAlpha=B.alpha,D.beginPath(),D.roundRect(B.x,(x.height-B.height)/2,B.width,B.height,M4t),D.fill();D.globalAlpha=1},[x.width,x.height,x.dpr,r]);$.useEffect(()=>{T(S.current),T(Q.current)},[T]);const _=$.useRef(null),E=$.useCallback(H=>{const D=tEt(H,p),V=Q.current;v.current?.style.setProperty("--sound-progress",`${D*100}%`),V&&(V.style.clipPath=`inset(0 ${(1-D)*100}% 0 0)`);const se=s$(H);w.current&&w.current.textContent!==se&&(w.current.textContent=se);const B=b.current;B&&(B.setAttribute("aria-valuenow",String(Math.floor(H))),B.setAttribute("aria-valuetext",wK(H,p)))},[p]);$.useEffect(()=>{const H=m||u,D=()=>E(s?hR()?.currentTime??0:W.current);if(!H){D();return}let V=0;const se=()=>{const B=_.current??hR()?.currentTime??0;E(B),V=requestAnimationFrame(se)};return V=requestAnimationFrame(se),()=>cancelAnimationFrame(V)},[m,u,s,E]);const R=$.useCallback(async()=>(f(!1),Fi.getState().play(e,t,{onError:()=>f(!0)})),[e,t]),j=$.useCallback(H=>{const D=Fi.getState();if(m){D.seek(e,H),E(H);return}R().then(V=>{V!==!1&&(Fi.getState().seek(e,H),E(H))})},[e,m,R,E]),C=$.useCallback(async()=>{if(m){Fi.getState().pause(e);return}f(!1),await Fi.getState().toggle(e,t,{onError:()=>f(!0)})},[e,t,m]),W=$.useRef(0),G=$.useRef(null),N=$.useCallback(H=>{const D=v.current;if(!D)return 0;const V=D.getBoundingClientRect();return eEt(H-V.left,V.width,p)},[p]),Z=H=>{if(g)return;H.currentTarget.setPointerCapture?.(H.pointerId),G.current={pointerId:H.pointerId,startX:H.clientX,moved:!1,pendingX:H.clientX,raf:0}},F=H=>{const D=G.current;!D||D.pointerId!==H.pointerId||(Math.abs(H.clientX-D.startX)>nEt&&(D.moved||O(!0),D.moved=!0),D.pendingX=H.clientX,D.moved&&D.raf===0&&(D.raf=requestAnimationFrame(()=>{const V=G.current;if(!V)return;V.raf=0;const se=N(V.pendingX);_.current=se,Fi.getState().scrub(e,se),E(se)})))},z=H=>{const D=G.current;if(!D||D.pointerId!==H.pointerId)return;D.raf!==0&&cancelAnimationFrame(D.raf),G.current=null,_.current=null,H.currentTarget.releasePointerCapture?.(H.pointerId);const V=N(H.clientX);if(D.moved){W.current=V,O(!1),Fi.getState().seek(e,V),E(V);return}j(V)},M=H=>{const D=hR(),V=s&&D?D.currentTime:0;if(H.key===" "||H.key==="Enter"){H.preventDefault(),C();return}let se=null;if(H.key==="ArrowLeft"?se=V-SK:H.key==="ArrowRight"?se=V+SK:H.key==="Home"?se=0:H.key==="End"&&(se=p),se===null)return;H.preventDefault();const B=Math.max(0,Math.min(p,se));j(B)},te=a==="compact",U=`${n} position`;return h.jsxs("div",{"data-sound-player":a,"data-sound-status":y?"error":u?"scrubbing":s?l:"idle",className:q("flex w-full min-w-0 items-center gap-2",te?"gap-1.5":"gap-2",o),children:[h.jsx("button",{type:"button",className:rEt,disabled:g,onClick:()=>void C(),"aria-label":`${m?"Pause":"Play"} ${n}`,children:g?h.jsx(Go,{size:"sm"}):m?h.jsx(xue,{size:22,"aria-hidden":"true"}):h.jsx(nze,{size:22,"aria-hidden":"true"})}),h.jsx("div",{ref:b,role:"slider",tabIndex:0,"aria-label":U,"aria-valuemin":0,"aria-valuemax":Math.max(0,Math.round(p)),"aria-valuenow":0,"aria-valuetext":wK(0,p),"data-sound-slider":"",className:q("group relative min-h-11 min-w-0 flex-1 cursor-pointer touch-none select-none","rounded-sm outline-offset-2 focus-visible:outline-2 focus-visible:outline-accent",y&&"cursor-default"),onPointerDown:Z,onPointerMove:F,onPointerUp:z,onPointerCancel:z,onKeyDown:M,children:h.jsxs("div",{ref:v,className:"absolute inset-0",children:[h.jsx("canvas",{ref:S,className:"absolute inset-0 h-full w-full text-ink-dim"}),h.jsx("canvas",{ref:Q,style:{clipPath:"inset(0 100% 0 0)"},className:"absolute inset-0 h-full w-full text-ink-muted"}),h.jsx("span",{"data-sound-thumb":"",className:q("pointer-events-none absolute top-1/2 size-2 -translate-x-1/2 -translate-y-1/2 rounded-full bg-ink-muted group-hover:bg-ink group-focus-visible:bg-accent",u&&"bg-accent"),style:{left:"var(--sound-progress, 0%)"}})]})}),h.jsx("span",{ref:w,"data-sound-time":"",className:q("min-w-10 shrink-0 text-center text-meta text-ink-muted tabular-nums"),children:s$(0)}),h.jsx("span",{className:q("min-w-10 shrink-0 text-center text-meta text-ink-dim tabular-nums"),children:s$(p)}),y?h.jsx("span",{"data-sound-error":"",className:q("shrink-0 text-meta text-ink-muted"),children:"This sound could not be played"}):null]})};function xK(e){const t=Array.isArray(e)?e:e&&typeof e=="object"&&Array.isArray(e.peaks)?e.peaks:null;if(!t||t.length===0)return null;const n=[];for(const r of t){if(typeof r!="number"||!Number.isFinite(r))return null;n.push(Math.max(0,Math.min(1,r)))}return n}const QK=new Map;async function iEt(e,t){try{const n=await su({op:"sessions.attachment.waveform",sessionId:e.sessionId,digest:t},null);if(n.kind==="json")return xK(n.body);if(n.kind==="bytes"){const r=new TextDecoder().decode(n.data);try{return xK(JSON.parse(r))}catch{return null}}return null}catch{return null}}function uQe(e,t){const n=t?.sessionId??null,r=t?.childId??null,[i,a]=$.useState(()=>e?aEt(e):null);return $.useEffect(()=>{if(!e||!n){a(null);return}let o=!0;return oEt({sessionId:n,childId:r},e).then(s=>{o&&a(s)}),()=>{o=!1}},[e,n,r]),i}function aEt(e){return h7.get(e)??null}const h7=new Map;function oEt(e,t){const n=QK.get(t);if(n)return n;const r=iEt(e,t).then(i=>(h7.set(t,i),i)).catch(()=>(h7.set(t,null),null));return QK.set(t,r),r}function OQe(e){return`sound:${e.attachment??e.id}`}const AU=({audio:e,scope:t,label:n,ownerId:r})=>{const i=Dv(e,t),a=uQe(e.attachment,t);return i.state==="missing"?h.jsx(_f,{name:n,detail:aQe}):i.state==="resolving"?h.jsx("div",{className:q("inline-block max-w-full self-start"),"aria-hidden":!0,children:h.jsx(zO,{"data-attachment-reserved":""})}):h.jsx("div",{className:q("w-full max-w-[560px] self-start"),children:h.jsx(cQe,{ownerId:r??OQe(e),src:i.url,label:n,peaks:a,durationHint:e.durationS??null})})},Qd=1,dQe=4,kK=(e,t)=>Math.min(dQe,Math.max(Qd,e+t)),Vg=Object.freeze({x:0,y:0}),pR=(e,t)=>t<=0?0:Math.min(t-1,Math.max(0,Math.trunc(e))),mR=(e,t,n)=>t<=0?0:((e+n)%t+t)%t,sEt=(e,t)=>`Image ${e+1} of ${t}`,PK=(e,t,n)=>{const r=Math.max(0,n-1)/2,i=t.width*r||0,a=t.height*r||0;return{x:Math.min(i,Math.max(-i,e.x)),y:Math.min(a,Math.max(-a,e.y))}},lEt="max-h-[min(90vh,calc(100vh-104px))] max-w-[min(90vw,calc(100vw-104px))]",cEt="max-h-[min(90vh,calc(100vh-208px))] max-w-[min(90vw,calc(100vw-104px))]",_K=e=>q(e,"flex min-h-16 min-w-64 items-center justify-center p-6"),uEt="opacity-45",zU=({src:e,label:t,open:n,onOpenChange:r,restoreFocusTo:i,fallback:a,pending:o=!1,group:s,layerRef:l})=>{const[c,u]=$.useState(null),O=e!==void 0&&c===e,[d,f]=$.useState(Qd),[p,m]=$.useState(Vg),g=$.useRef(e);$.useLayoutEffect(()=>{g.current!==e&&(g.current=e,f(Qd),m(Vg))},[e]);const[y,v]=$.useState(!0),S=$.useRef(null);$.useEffect(()=>{if(!n)return;let U;const H=()=>{clearTimeout(U),U=setTimeout(()=>{const V=S.current;if(V&&(V.matches(":hover")||V.contains(document.activeElement))){H();return}v(!1)},$de)},D=()=>{v(!0),H()};return v(!0),H(),document.addEventListener("pointermove",D,{passive:!0}),document.addEventListener("pointerdown",D,{passive:!0}),document.addEventListener("keydown",D),document.addEventListener("focusin",D),()=>{clearTimeout(U),document.removeEventListener("pointermove",D),document.removeEventListener("pointerdown",D),document.removeEventListener("keydown",D),document.removeEventListener("focusin",D)}},[n]);const Q=s?.onPrev,b=s?.onNext,w=s!==void 0&&s.count>1,x=w?cEt:lEt,k=$.useRef(null),T=l??k;$.useEffect(()=>{if(!n||!w)return;const U=H=>{H.defaultPrevented||H.metaKey||H.ctrlKey||H.altKey||(H.key==="ArrowLeft"?(H.preventDefault(),Q?.()):H.key==="ArrowRight"&&(H.preventDefault(),b?.()))};return document.addEventListener("keydown",U),()=>document.removeEventListener("keydown",U)},[n,w,Q,b]),gA(n,"image-lightbox");const _=$.useRef(null),E=e!==void 0&&!O,R=d===Qd&&p.x===Vg.x&&p.y===Vg.y,j=U=>{if(!E)return;f(U);const H=_.current;H&&m(D=>PK(D,{width:H.clientWidth,height:H.clientHeight},U))},C=()=>{E&&(f(Qd),m(Vg))},W=$.useRef(null),[G,N]=$.useState(!1),Z=E&&d>Qd,F=U=>{!Z||U.button!==0||(U.currentTarget.setPointerCapture(U.pointerId),W.current={pointerId:U.pointerId,startX:U.clientX,startY:U.clientY,pan:p},N(!0))},z=U=>{const H=W.current,D=_.current;!H||H.pointerId!==U.pointerId||!D||m(PK({x:H.pan.x+(U.clientX-H.startX),y:H.pan.y+(U.clientY-H.startY)},{width:D.clientWidth,height:D.clientHeight},d))},M=U=>{W.current?.pointerId===U.pointerId&&(W.current=null,N(!1))},te=e!==void 0&&!O?h.jsx("div",{ref:_,"data-image-viewport":"",tabIndex:-1,className:q(x,"relative h-fit w-fit overflow-hidden leading-none outline-none",Z&&(G?"cursor-grabbing":"cursor-grab"),Z&&"touch-none"),onPointerDown:F,onPointerMove:z,onPointerUp:M,onPointerCancel:M,children:h.jsx("img",{src:e,alt:t,draggable:!1,className:q(x,"block select-none object-contain"),style:R?void 0:{transform:`translate(${p.x}px, ${p.y}px) scale(${d})`},onError:()=>u(e)})}):e===void 0&&o?h.jsx("div",{className:_K(x),"aria-hidden":"true"}):h.jsx("div",{className:_K(x),children:a});return h.jsx($A,{open:n,onOpenChange:r,children:h.jsxs(yA,{ref:T,tabIndex:-1,onOpenAutoFocus:U=>{U.preventDefault(),(_.current??T.current)?.focus()},showClose:!1,"aria-describedby":void 0,onCloseAutoFocus:U=>{const H=i?.current;H&&(U.preventDefault(),H.focus())},className:q("inset-0 top-0 left-0 m-auto h-fit w-fit translate-none outline-none",x,"gap-0 rounded-none border-0 border-transparent bg-transparent p-0 shadow-none"),children:[h.jsx(vA,{className:"sr-only",children:t}),w&&s?h.jsx("div",{"aria-live":"polite",className:"sr-only",children:sEt(s.index,s.count)}):null,te,h.jsxs("div",{ref:S,"data-image-viewer-controls":"",className:q("pointer-events-none fixed inset-0 transition-opacity ease-out-quart",y?"opacity-100 duration-fast":`${uEt} duration-base`),children:[w&&s?.filmstrip?h.jsx("div",{className:"pointer-events-auto fixed inset-x-0 bottom-4 mx-auto w-fit max-w-[calc(100vw-256px)]",children:s.filmstrip}):null,w?h.jsxs(h.Fragment,{children:[h.jsx(Xe,{variant:"ghost",size:"icon-sm","aria-label":"Previous image",title:"Previous image",onClick:s?.onPrev,className:"pointer-events-auto fixed top-0 bottom-0 left-4 my-auto","data-image-viewer-prev":"",children:h.jsx(ZAe,{"aria-hidden":"true"})}),h.jsx(Xe,{variant:"ghost",size:"icon-sm","aria-label":"Next image",title:"Next image",onClick:s?.onNext,className:"pointer-events-auto fixed top-0 right-4 bottom-0 my-auto","data-image-viewer-next":"",children:h.jsx(ale,{"aria-hidden":"true"})})]}):null,h.jsxs("div",{className:"pointer-events-auto fixed right-4 bottom-4 flex items-center gap-1",children:[h.jsx(Xe,{variant:"ghost",size:"icon-sm","aria-label":"Zoom out",title:"Zoom out",disabled:!E||d===Qd,onClick:()=>j(kK(d,-1)),children:h.jsx(Zue,{"aria-hidden":"true"})}),h.jsx(Xe,{variant:"ghost",size:"icon-sm","aria-label":"Zoom in",title:"Zoom in",disabled:!E||d===dQe,onClick:()=>j(kK(d,1)),children:h.jsx(Iue,{"aria-hidden":"true"})}),h.jsx(Xe,{variant:"ghost",size:"icon-sm","aria-label":"Reset view",title:"Reset view",disabled:!E||R,onClick:C,children:h.jsx(mk,{"aria-hidden":"true"})})]}),h.jsx(KRe,{asChild:!0,children:h.jsx(Xe,{variant:"ghost",size:"icon-sm",className:q("pointer-events-auto fixed top-4 right-4"),"aria-label":"Close image",title:"Close image",children:h.jsx(ea,{"aria-hidden":"true"})})})]})]})})};zU.displayName="ImageLightbox";const OEt={full:"max-h-[240px] max-w-full object-contain",thumbnail:["h-[76px] w-[115px] object-contain","motion-safe:transition-transform motion-safe:duration-fast motion-safe:ease-out-quart","motion-safe:group-hover/tile:scale-[1.04]"].join(" ")},dEt=/[/\\]/,TK=e=>{const t=e.split(dEt);return t[t.length-1]},fQe=$.memo(({file:e,src:t,conversationId:n,label:r,size:i="full",overlay:a,press:o})=>{const[s,l]=$.useState(!1),[c,u]=$.useState(!1),[O,d]=$.useState(!1),f=$.useRef(null),p=Jn(T=>T.setCanvasOpen),{setViewMode:m}=zd(),g=$.useCallback(async()=>{const T=TK(e),_=C=>{C&&console.error("Error processing file:",C);const W=e.startsWith("file://")?e.substring(7):e;window.api.openFile(W).catch(G=>{console.error("Error opening file:",G)})},{setFiles:E,setOpenTabs:R,setSelectedTab:j}=zd.getState();if(e.startsWith("data:"))if(n7(T)){const C=e,W={id:C,title:T,path:C,content:e,type:NS(e)},N=zd.getState().conversations?.[n],Z=N?.files??[],F=N?.openTabs??[],z=(()=>{const U=Z.findIndex(H=>H.id===C);return U!==-1?[...Z.slice(0,U),W,...Z.slice(U+1)]:[...Z,W]})();E(n,z);const te=F.some(U=>U.id===C)?F:[...F,{id:C,title:T}];R(n,te),j(n,C),p(!0),m(n,"documents")}else p(!0),m(n,"files");else{const C=e.startsWith("file://")?e.substring(7):e;try{const W=await window.api.readFile(C);if(W.success&&n7(T)){const G=C,N={id:G,title:T,path:C,content:W.data,type:NS(e)},F=zd.getState().conversations?.[n],z=F?.files??[],M=F?.openTabs??[],te=(()=>{const D=z.findIndex(V=>V.id===G);return D!==-1?[...z.slice(0,D),N,...z.slice(D+1)]:[...z,N]})();E(n,te);const H=M.some(D=>D.id===G)?M:[...M,{id:G,title:T}];R(n,H),j(n,G),p(!0),m(n,"documents");return}p(!0),m(n,"files")}catch(W){const G=W instanceof Error?W.message:String(W??"Unknown error reading file");return _(G)}}},[e,p,m,n]),y=()=>{l(!0)},v=Txe(e),Q=(v==="path"||v==="data")&&n!=="",b=Xxe(v,{canShowInCanvas:Q,source:t}),w=v==="path",x=r??TK(e);if(s)return h.jsx(_f,{name:x,compact:i==="thumbnail"});const k=h.jsx(zO,{boundary:i==="thumbnail"?"control":"hairline",children:h.jsx("img",{className:q(OEt[i],c?"opacity-100":"opacity-0"),src:t,alt:x,onLoad:()=>u(!0),onError:y})});return h.jsxs("div",{className:"group relative inline-block",children:[h.jsx("button",{ref:f,type:"button",className:q("block max-w-full cursor-pointer",i==="thumbnail"&&"group/tile rounded-sm"),onClick:o?o.onPress:()=>d(!0),"aria-label":o?o.label:`Expand ${x}`,title:o?o.title:`Click to expand ${x}`,"aria-current":o?.current?"true":void 0,children:k}),b&&h.jsx("div",{className:"file-actions-menu pointer-events-none absolute top-1 right-1 z-[2] opacity-0 transition-opacity duration-fast ease-out-quart group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100 has-[[aria-expanded=true]]:pointer-events-auto has-[[aria-expanded=true]]:opacity-100",onClick:T=>{T.stopPropagation()},onKeyDown:T=>T.stopPropagation(),children:h.jsx(qxe,{file:e,src:t,label:x,onShowInCanvas:Q?g:void 0})}),o?null:a?a({open:O,onOpenChange:d,restoreFocusTo:f}):h.jsx(zU,{src:t,label:x,open:O,onOpenChange:d,restoreFocusTo:f,fallback:h.jsx(_f,{name:x,detail:w?void 0:CU})})]})});fQe.displayName="ImageAttachment";const fEt=(e,t,n)=>e.name??(n===1?"Image":`Image ${t+1}`),hEt={id:"image-group:empty",data:null,attachment:null,mimeType:"image/png"},pEt=({cold:e,children:t})=>e?h.jsx("div",{className:"flex h-[79px] w-[117px] items-start leading-none",children:t}):t,mEt=({images:e,index:t,scope:n,open:r,onOpenChange:i,restoreFocusTo:a,labelFor:o=fEt})=>{const s=e.length,[l,c]=$.useState(()=>pR(t,s)),[u,O]=$.useState(r);u!==r&&(O(r),r&&c(pR(t,s)));const d=pR(l,s),f=e[d]??hEt,p=o(f,d,s),m=RU(f,n),g=$.useRef(null),y=$.useRef(null),[v,S]=$.useState(!1),Q=$.useCallback(N=>{g.current=N,S(N!==null)},[]),b=N=>{const Z=g.current?.querySelector(`button[aria-label="Show image ${N+1} of ${s}"]`);Z?Z.focus():y.current?.focus()},w=N=>{const Z=mR(d,s,N),F=g.current?.contains(document.activeElement)??!1;c(Z),F&&b(Z)},x=()=>w(-1),k=()=>w(1),T=JSON.stringify([n?.sessionId,n?.childId,e.map(N=>[N.id,N.attachment,N.mimeType])]),[_,E]=$.useState(()=>({identity:T,open:r,indices:new Set}));(_.identity!==T||_.open!==r)&&E({identity:T,open:r,indices:new Set});const R=$.useCallback(N=>{E(Z=>{if(!r||Z.identity!==T||!Z.open||N.every(z=>Z.indices.has(z)))return Z;const F=new Set(Z.indices);for(const z of N)F.add(z);return{...Z,indices:F}})},[T,r]),j=mR(d,s,-1),C=mR(d,s,1);$.useEffect(()=>{r&&R([d,j,C])},[r,d,j,C,R]),$.useEffect(()=>{const N=g.current;if(!r||!v||!N||typeof IntersectionObserver>"u")return;let Z=!0;const F=new IntersectionObserver(z=>{Z&&R(z.filter(M=>M.isIntersecting).map(M=>Number(M.target.dataset.imageSlot)-1))},{root:N});for(const z of N.querySelectorAll("[data-image-slot]"))F.observe(z);return()=>{Z=!1,F.disconnect()}},[r,v,R]);const W=(N,Z)=>!!N.data||!N.attachment||Z===d||Z===j||Z===C||_.identity===T&&_.open&&_.indices.has(Z);$.useEffect(()=>{(g.current?.querySelector(`[data-image-slot="${d+1}"]`)??g.current)?.scrollIntoView?.({block:"nearest",inline:"nearest"})},[v,d]);const G=s>1?h.jsx("ul",{role:"list",ref:Q,"aria-label":`${s} images`,"data-image-filmstrip":"",className:"flex max-w-full items-center gap-2 overflow-x-auto px-2 py-1 leading-none",children:e.map((N,Z)=>h.jsx("li",{"data-image-slot":Z+1,className:q("flex shrink-0 scroll-mx-px rounded-sm leading-none",Z===d&&"ring-1 ring-ink"),children:h.jsx(pEt,{cold:!!N.attachment&&!N.data,children:W(N,Z)?h.jsx(Dm,{image:N,scope:n,size:"thumbnail",label:o(N,Z,s),press:{onPress:()=>c(Z),label:`Show image ${Z+1} of ${s}`,title:`Show image ${Z+1} of ${s}`,current:Z===d}}):h.jsx("button",{type:"button","aria-label":`Show image ${Z+1} of ${s}`,title:`Show image ${Z+1} of ${s}`,className:"group/tile inline-block max-w-full cursor-zoom-in rounded-sm leading-none",onClick:()=>{R([Z]),c(Z)},children:h.jsx(zO,{boundary:"control",className:"h-[78px] w-[117px]","data-attachment-reserved":"","data-attachment-deferred":""})})})},N.id))}):void 0;return h.jsx(zU,{src:m.state==="ready"?m.url:void 0,pending:m.state==="resolving",label:p,open:r,onOpenChange:i,restoreFocusTo:a,fallback:h.jsx(_f,{name:p,detail:CU}),layerRef:y,group:{index:d,count:s,onPrev:x,onNext:k,filmstrip:G}})},Dm=({image:e,scope:t,label:n,size:r,group:i,press:a})=>{const o=RU(e,t);if(o.state==="resolving"){const l=h.jsx(zO,{boundary:r==="thumbnail"?"control":"hairline",className:r==="thumbnail"?"h-[78px] w-[117px]":void 0,"data-attachment-reserved":""});return a?h.jsx("button",{type:"button","aria-label":a.label,title:a.title,"aria-current":a.current||void 0,className:"group/tile inline-block max-w-full cursor-zoom-in rounded-sm leading-none",onClick:a.onPress,children:l}):h.jsx("div",{className:q("inline-block max-w-full"),"aria-hidden":!0,children:l})}if(o.state==="missing")return h.jsx(_f,{name:n,compact:r==="thumbnail",detail:CU});const s=o.url;return h.jsx("div",{className:q("inline-block max-w-full"),children:h.jsx(fQe,{file:s,src:s,label:n,size:r,conversationId:t?.sessionId??"",press:a,overlay:i?l=>h.jsx(mEt,{images:i.images,index:i.index,labelFor:i.labelFor,scope:t,open:l.open,onOpenChange:l.onOpenChange,restoreFocusTo:l.restoreFocusTo}):void 0})})},gEt="Generating name…",$Et={rest:"scale-x-60 bg-ink-dim",preview:"scale-x-90 bg-ink-muted",active:"scale-x-100 bg-ink",unloaded:"scale-x-40 bg-ink-dim opacity-75"};function yEt(e){return e.id===e.activeId?"active":e.id===e.previewId?"preview":e.loaded===!1?"unloaded":"rest"}function UU(e,t){return`Turn ${e} of ${t}`}const vEt=e=>e.charAt(0).toLowerCase()+e.slice(1);function bEt(e,t){const n=UU(e.turn,t),r=e.naming?.state==="ready"?e.naming.name?.trim():"";return r?`${n} · ${r}`:n}function wEt(e){return e.kind==="completion"&&e.naming?.state==="pending"}function SEt(e){const t=e.naming?.state==="ready"?e.naming.summary:null;return t?.trim()?t:null}function xEt(e){let t=0;for(const n of e)n.turn>t&&(t=n.turn);return t}const QEt={complete:"Complete",error:"Error",interrupted:"Interrupted",open:"Open"};function kEt(e){if(!Number.isFinite(e)||e<=0)return"";const t=new Date(e*1e3);if(Number.isNaN(t.getTime()))return"";const n=t.getHours(),r=t.getMinutes().toString().padStart(2,"0"),i=n%12===0?12:n%12,a=n<12?"AM":"PM";return`${i}:${r} ${a}`}function PEt(e,t){const n=vEt(UU(e.turn,t));if(e.kind==="user"){const i=kEt(e.ts);return i?`Jump to your message in ${n}, ${i}`:`Jump to your message in ${n}`}const r=e.naming?.state==="ready"?e.naming.name?.trim():"";return r?`Jump to ${n}, ${r}`:`Jump to ${n}`}function _Et(e,t){const n=e.checkpoints.find(i=>i.id===t);return n?n.kind==="completion"?n.naming?.state??null:e.checkpoints.find(i=>i.kind==="completion"&&i.turn===n.turn)?.naming?.state??null:null}function gR(e,t){const n=[];for(const r of t)_Et(e,r)==="pending"&&n.push(r);return n}const TEt=120,RK=80,REt="Turn checkpoints",XEt={complete:xu,error:kp,interrupted:pz,open:KAe},EEt={complete:"text-success",error:"text-danger",interrupted:"text-warning",open:"text-ink-dim"},qEt=({checkpoint:e,turnCount:t})=>{const n=e.outcome,r=n?XEt[n]:null,i=SEt(e),a=e.naming?.state==="ready"?e.naming.name?.trim():"";return h.jsxs(h.Fragment,{children:[h.jsxs("p",{className:q("text-body-sm font-medium text-ink"),children:[UU(e.turn,t),a&&h.jsxs(h.Fragment,{children:[h.jsx("span",{"aria-hidden":"true",children:" · "}),h.jsx("span",{className:q("font-normal text-ink-muted"),children:a})]})]}),wEt(e)&&h.jsx("p",{className:q("text-ink-dim text-meta"),children:gEt}),i&&h.jsx("p",{className:q("line-clamp-2 break-words text-body-sm text-ink-muted"),children:i}),n&&r&&h.jsx("div",{className:q("flex items-center gap-1.5 text-ink-dim text-meta"),children:h.jsxs("span",{className:q("flex items-center gap-1",EEt[n]),children:[h.jsx(r,{"aria-hidden":"true",className:q("size-3.5 shrink-0")}),QEt[n]]})})]})},jEt=$.memo(function({checkpoint:t,state:n,label:r,roving:i,registerTick:a,onPreview:o,onPreviewEnd:s,onFocusMark:l,onBlurMark:c,onActivate:u,onKeyMark:O,describedBy:d}){const f=p=>{p.pointerType!=="touch"&&o(t.id)};return h.jsx("button",{ref:p=>a(t.id,p),type:"button","data-checkpoint-id":t.id,"data-mark-state":n,"aria-label":r,"aria-describedby":d,tabIndex:i?0:-1,className:q("group pointer-events-auto block h-2.5 w-7"),onPointerMove:f,onPointerLeave:s,onFocus:()=>l(t.id),onBlur:c,onClick:()=>u(t.id),onKeyDown:p=>O(p,t.id),children:h.jsx("span",{"aria-hidden":"true",className:q("ml-auto mr-1.5 block h-0.5 w-5 origin-right rounded-full","transition-[transform,background-color] duration-fast ease-out-quart","motion-reduce:transition-none",$Et[n])})})}),CEt=({sessionId:e,checkpoints:t,onJump:n,onHover:r,building:i=!1,loadedIds:a,activeId:o=null})=>{const s=$.useId(),[l,c]=$.useState(null),[u,O]=$.useState(null),[d,f]=$.useState(null),p=$.useRef(t);p.current=t;const m=$.useRef(new Map),g=$.useRef(null),y=$.useRef(null),v=$.useRef(null),S=$.useCallback(()=>{y.current!==null&&(clearTimeout(y.current),y.current=null),v.current!==null&&(clearTimeout(v.current),v.current=null)},[]),Q=$.useCallback((B,K)=>{S();const ne=()=>{O(B),f(p.current.find(le=>le.id===B)??null)};if(K<=0){ne();return}y.current=setTimeout(()=>{y.current=null,ne()},K)},[S]),b=$.useCallback(B=>{if(S(),B<=0){O(null);return}v.current=setTimeout(()=>{v.current=null,O(null)},B)},[S]),w=$.useRef(e);$.useEffect(()=>{w.current!==e&&(w.current=e,S(),M.current=null,c(null),O(null),f(null))},[e,S]);const x=$.useRef(null);$.useLayoutEffect(()=>{const B=g.current;if(!(t.length===0||B===null)){if(o!==null&&k.current===e){x.current=e;return}x.current!==e&&(x.current=e,B.scrollTop=B.scrollHeight)}},[o,t.length,e]);const k=$.useRef(null);$.useLayoutEffect(()=>{if(o===null)return;const B=g.current,K=m.current.get(o);if(B===null||K===void 0)return;k.current=e;const ne=B.getBoundingClientRect(),le=K.getBoundingClientRect(),Oe=le.top-ne.top+B.scrollTop,Qe=Oe+le.height,we=24;Oe<B.scrollTop+we?B.scrollTop=Math.max(0,Oe-we):Qe>B.scrollTop+B.clientHeight-we&&(B.scrollTop=Qe-B.clientHeight+we)},[o,e]),$.useEffect(()=>()=>S(),[S]);const T=$.useRef(r);$.useEffect(()=>{T.current=r});const _=$.useMemo(()=>xEt(t),[t]),E=$.useMemo(()=>new Map(t.map(B=>[B.id,PEt(B,_)])),[t,_]),R=u&&d?.id===u?d:null,j=u&&m.current.get(u)||null,C=$.useMemo(()=>({current:j}),[j]),W=R!==null&&j!==null;$.useEffect(()=>{T.current(W&&u?u:null)},[W,u]);const G=$.useCallback((B,K)=>{K?m.current.set(B,K):m.current.delete(B)},[]),[N,Z]=$.useState(null),F=N&&t.some(B=>B.id===N)?N:t[0]?.id??null,z=$.useCallback(B=>{const K=Math.max(0,Math.min(t.length-1,B)),ne=t[K];ne&&(Z(ne.id),m.current.get(ne.id)?.focus())},[t]),M=$.useRef(null),te=$.useCallback(B=>{M.current!==B&&(M.current=B,c(B),Q(B,TEt))},[Q]),U=$.useCallback(()=>{M.current=null,c(B=>B===null?B:null),b(RK)},[b]),H=$.useCallback(B=>{M.current=B,Z(B),c(K=>K===B?K:B),Q(B,0)},[Q]),D=$.useCallback(()=>{M.current=null,c(B=>B===null?B:null),b(RK)},[b]),V=$.useCallback(B=>{b(0),M.current=null,c(null),n(B)},[b,n]),se=$.useCallback((B,K)=>{if(B.key==="Escape"){b(0);return}const ne=t.findIndex(le=>le.id===K);if(!(ne<0)){if(B.key==="ArrowDown"){B.preventDefault(),B.stopPropagation(),z(ne+1);return}if(B.key==="ArrowUp"){B.preventDefault(),B.stopPropagation(),z(ne-1);return}if(B.key==="Home"){B.preventDefault(),B.stopPropagation(),z(0);return}B.key==="End"&&(B.preventDefault(),B.stopPropagation(),z(t.length-1))}},[t,b,z]);return t.length===0&&!i?null:h.jsxs("div",{"data-lo-checkpoint-rail":"",role:"toolbar","aria-orientation":"vertical","aria-label":REt,className:q("pointer-events-none absolute inset-y-0 right-3 z-10 hidden w-7 select-none","flex-col justify-center","@[900px]/chatcol:flex"),children:[h.jsxs("div",{"data-rail-frame":"",ref:g,className:q("max-h-[min(calc(100%-4rem),420px)] w-7 overflow-y-auto overscroll-contain","[&::-webkit-scrollbar]:hidden","[mask-image:linear-gradient(to_bottom,transparent_0,#000_24px,#000_calc(100%-24px),transparent_100%)]"),children:[i&&h.jsx("span",{"aria-hidden":"true","data-rail-building":"",className:q("ml-auto mr-1.5 block h-0.5 w-5 animate-pulse-visible rounded-full bg-ink-dim")}),h.jsx("div",{"data-rail-track":"",className:"py-6",children:t.map(B=>h.jsx(jEt,{checkpoint:B,state:yEt({id:B.id,previewId:l,activeId:o,loaded:a?a.has(B.id):!0}),label:E.get(B.id)??"",roving:B.id===F,registerTick:G,onPreview:te,onPreviewEnd:U,onFocusMark:H,onBlurMark:D,onActivate:V,onKeyMark:se,describedBy:W&&u===B.id?s:void 0},B.id))})]}),h.jsxs(JRe,{open:W,onOpenChange:B=>{B||b(0)},children:[h.jsx(eXe,{virtualRef:C}),R&&h.jsx(tXe,{id:s,"data-checkpoint-card":"",side:"left",align:"center",sideOffset:10,collisionPadding:8,role:"tooltip","aria-label":R.kind==="user"?"Your message":bEt(R,_),onOpenAutoFocus:B=>B.preventDefault(),onCloseAutoFocus:B=>B.preventDefault(),onFocusOutside:B=>{const K=B.detail?.originalEvent?.target;K instanceof Element&&K.closest("[data-lo-checkpoint-rail]")&&B.preventDefault()},className:q("pointer-events-none max-h-[176px] w-[300px] max-w-[300px] overflow-hidden","flex flex-col gap-2"),children:R.kind==="user"?h.jsx("div",{"data-checkpoint-card-text":"",className:q("line-clamp-3 break-words whitespace-pre-wrap","text-body-sm text-ink"),children:R.text}):h.jsx(qEt,{checkpoint:R,turnCount:_})})]})]})},AEt=$.memo(CEt);function zEt(e,t){if(!t)return e;let n=!1;const r=[];for(const i of e){if(i.kind==="peer"||i.kind==="tool"&&i.toolName==="send"){n=!0;continue}r.push(i)}return n?r:e}const UEt=(e,t,n)=>(e.getAttribute(t)??"").split(" ").includes(n);function WEt(e,t){return e.querySelector(`[data-record-id="${t}"]:not([data-turn-summary])`)!==null}function hQe(e,t){const n=[["[data-turn-summary]","data-run-ids"],["[data-fold-ids]","data-fold-ids"]];for(const[r,i]of n)for(const a of e.querySelectorAll(r)){const o=a.getAttribute("data-segment-ids");if(o!==null?!o.split(" ").includes(t):!UEt(a,i,t))continue;if(a.querySelector("button[aria-expanded]")?.getAttribute("aria-expanded")==="false")return a}return null}function NEt(e,t){return WEt(e,t)||hQe(e,t)!==null}const YEt=3;function GEt(e,t,n){const r=i=>{if(n.isCurrent&&!n.isCurrent()){n.onMissing();return}const a=e.querySelector(`[data-record-id="${t}"]:not([data-turn-summary])`);if(a){const l=a.querySelector("button[aria-expanded]");l?.getAttribute("aria-expanded")==="false"&&l.click(),n.onRevealed(a);return}if(i>=YEt){n.onMissing();return}const s=hQe(e,t)?.querySelector("button[aria-expanded]");if(!s){n.onMissing();return}s.click(),window.requestAnimationFrame(()=>{r(i+1)})};r(0)}const XK=(e,t,n)=>n===1?"Image":`Image ${t+1}`,EK=({images:e,scope:t,onRevealMore:n,uncapped:r=!1,indent:i="content"})=>{const{shown:a,more:o}=j4t(e.length,{uncapped:r}),s=C4t(a),l=s.length>1,c=new Set;for(let O=0,d=0;d<s.length;d+=1)c.add(O),O+=s[d];const u=e.slice(0,a).map((O,d)=>h.jsx("li",{className:q("flex leading-none",l&&c.has(d)&&"col-start-1"),children:h.jsx(Dm,{image:O,scope:t,size:"thumbnail",label:XK(O,d,e.length),group:{images:e,index:d,labelFor:XK}})},O.id));return h.jsxs("ul",{role:"list","aria-label":e.length===1?"1 image from this run":`${e.length} images from this run`,"data-fold-media":"",className:q("mt-2 gap-2",l?"grid grid-cols-[repeat(4,max-content)] items-start":"flex flex-wrap items-center",i==="content"?"ml-5":"ml-0"),children:[u,o>0&&h.jsx("li",{className:q("flex h-[78px] items-center leading-none"),children:h.jsx(Xe,{variant:"outline",size:"sm",onClick:n,"aria-label":`+${o} more image${o===1?"":"s"}`,title:`+${o} more image${o===1?"":"s"}`,children:`+${o}`})},"fold-media-more")]})};function qK(e,t){if(t.length===0)return!1;const n=e.find(i=>i.ids[0]===t[0]);return n?n.open:e.find(i=>i.ids.some(a=>t.includes(a)))?.open??!1}function IEt(e,t,n,r){if(t.length===0)return[...e];const i=t[0],a=[];let o=!1;for(const s of e){if(!(s.ids[0]===i||s.ids.some(c=>t.includes(c)))){a.push(s);continue}o||(a.push({ids:[...t],open:n}),o=!0)}return o||a.push({ids:[...t],open:n}),a.filter(s=>s.ids.some(l=>r.has(l)))}const ZEt=({video:e,scope:t,label:n})=>{const r=Dv(e,t),[i,a]=$.useState(!1);return r.state==="missing"||i?h.jsx(_f,{name:n,detail:iQe}):r.state==="resolving"?h.jsx("div",{className:q("inline-block max-w-full self-start"),"aria-hidden":!0,children:h.jsx(zO,{"data-attachment-reserved":""})}):h.jsx("div",{className:q("inline-block max-w-full self-start"),children:h.jsx(zO,{children:h.jsx("video",{controls:!0,preload:"metadata",src:r.url,"aria-label":n,className:q("max-h-[240px] max-w-full object-contain"),onError:()=>a(!0)})})})};function DEt({items:e,summary:t,scope:n}){return h.jsxs("div",{"data-sound-batch":"",className:q("flex w-full min-w-0 max-w-[560px] flex-col gap-4"),children:[h.jsx("p",{className:q("text-meta text-ink-muted break-words [overflow-wrap:anywhere]"),children:t}),h.jsx("ul",{className:"flex min-w-0 flex-col gap-4",children:e.map(r=>h.jsxs("li",{"data-sound-batch-item":"",className:q("min-w-0"),children:[h.jsxs("p",{className:q("text-body text-ink break-words [overflow-wrap:anywhere]"),children:[r.label,r.status!=="completed"?` · ${r.status==="unknown"?"Status unknown":r.status==="cancelled"?"Stopped":"Failed"}`:""]}),r.error?h.jsx("p",{className:q("text-body-sm text-ink break-words [overflow-wrap:anywhere]"),children:r.error}):r.audio?h.jsx(AU,{audio:r.audio,ownerId:`${OQe(r.audio)}:batch:${r.audio.id}:${r.id}`,scope:n,label:r.label}):h.jsx("p",{className:q("text-meta text-ink-muted"),children:"Audio attachment unavailable."}),h.jsx("p",{className:q("text-meta text-ink-dim"),children:r.costCaption??"Cost not yet known."})]},r.id))})]})}function LOn({sessionId:e,runningSound:t,available:n,onInterrupt:r,onRestoreFocus:i}){const[a,o]=$.useState(!1),s=$.useRef(null),l=$.useRef(e);$.useEffect(()=>{const f=l.current!==e;l.current=e,!(!f&&t)&&a&&(o(!1),i())},[e,t,a,i]);const c=$.useCallback(()=>{o(!1),i()},[i]),u=$.useCallback(()=>{if(!e||!n)return;const f=s.current?.querySelector("[data-sound-stop-confirmation] button");if(f){f.focus();return}if(t){o(!0);return}r()},[e,n,t,r]),O=$.useCallback(()=>{o(!1),i(),r()},[r,i]),d=$.useMemo(()=>a&&t?h.jsx(pQe,{onKeepWaiting:c,onRequestStop:O}):null,[a,t,c,O]);return{paneRef:s,stop:u,confirmation:d}}function pQe({onKeepWaiting:e,onRequestStop:t}){const n=$.useRef(null),r=$.useId();return $.useEffect(()=>{n.current?.focus();const i=a=>{a.key!=="Escape"||a.isComposing||a.defaultPrevented||(a.preventDefault(),a.stopPropagation(),e())};return document.addEventListener("keydown",i),()=>document.removeEventListener("keydown",i)},[e]),h.jsxs("fieldset",{"data-sound-stop-confirmation":"","aria-label":"Confirm stop request",className:"flex flex-col items-start gap-2",children:[h.jsx("p",{className:"text-meta text-ink","aria-live":"polite",children:"Stop this generation?"}),h.jsx("p",{id:r,className:"text-body-sm text-ink-dim",children:"The provider has no cancellation endpoint. The generation continues and will be charged if it produces audio. Stopping is best-effort; it does not guarantee cancellation or no charge."}),h.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[h.jsx(Xe,{ref:n,"aria-describedby":r,variant:"ghost",size:"sm",onClick:e,children:"Keep waiting"}),h.jsx(Xe,{variant:"secondary",size:"sm",onClick:t,children:"Request stop"})]})]})}const MEt=1e3;function VEt(e){const[t,n]=$.useState(()=>e===null?null:Math.max(0,(Date.now()-e)/1e3));return $.useEffect(()=>{if(e===null){n(null);return}const r=()=>n(Math.max(0,(Date.now()-e)/1e3));r();const i=window.setInterval(r,MEt);return()=>window.clearInterval(i)},[e]),t}function LEt(){return h.jsx("div",{"aria-hidden":!0,"data-imagegen-tile":"",className:q("relative aspect-[3/2] w-[240px] max-w-full overflow-hidden rounded-sm bg-sunken"),children:h.jsx("span",{className:q("absolute inset-0","animate-shimmer","bg-gradient-to-r from-transparent via-elevated to-transparent","bg-[length:200%_100%]","bg-[position:-200%_50%]","bg-no-repeat")})})}function FEt({view:e,elapsed:t}){let n,r=null,i=!1;switch(e.state){case"queued":n=e.composing?"Writing the request…":"Queued",r=e.queuePosition!==null?`${e.queuePosition} ahead`:e.argumentBytes>0?O1(e.argumentBytes):null;break;case"running":n=e.batchProgress?`Generating ${e.batchProgress.total} ${Dh(e.material)}${e.batchProgress.total===1?"":"s"}…`:`Generating ${Dh(e.material)}…`,r=t===null?null:ec(t);break;case"cancelling":n=e.generating?cY:lY;break;case"done":n=e.receipt==="already-finished"?"Already finished.":e.batch?`${$R(e.material)} batch`:`Generated ${Dh(e.material)}`,r=e.receipt==="already-finished"||e.durationS===null?null:jA(e.durationS);break;case"failed":n=e.batch?`${$R(e.material)} batch failed.`:e.message??`The ${Dh(e.material)} could not be generated.`,i=!0;break;case"cancelled":{const a=e.message??(e.generating?cY:lY);n=e.batch?`${$R(e.material??"sound-effect")} batch stopped.`:e.settlementCaption||e.settled?WEe(a):a;break}}return h.jsxs("p",{className:q("flex min-w-0 items-baseline gap-1.5 text-body-sm"),children:[h.jsx("span",{className:q("min-w-0",i?"text-ink":"text-ink-muted"),children:n}),r===null?null:h.jsxs("span",{className:q("shrink-0 text-meta text-ink-dim"),children:["· ",r]})]})}function BEt({line:e}){return h.jsx("p",{"data-imagegen-log":"",title:e,className:q("min-w-0 truncate font-mono text-mono-sm text-ink-dim"),children:e})}function $R(e){const t=Dh(e);return t.charAt(0).toUpperCase()+t.slice(1)}function Lg({line:e,prominent:t=!1}){return h.jsx("p",{"data-imagegen-note":"",className:q("min-w-0 text-body-sm",t?"text-ink-muted":"text-ink-dim"),children:e})}function HEt(e,t){return e==="cancel"?"Stop":e==="restart"?t==="failed"?"Retry":"Restart":"Edit and restart"}const KEt=({view:e,scope:t,actions:n})=>{const[r,i]=$.useState(!1),a=$.useCallback(()=>i(!1),[]),o=$.useRef(null),s=$.useRef(!1);$.useLayoutEffect(()=>{s.current&&!r&&(o.current?.querySelector("[data-imagegen-controls] button")??o.current)?.focus(),s.current=r},[r]),$.useLayoutEffect(()=>{const g=o.current;return()=>{g?.contains(document.activeElement)&&g.closest("[data-chat-pane]")?.querySelector("textarea")?.focus()}},[]);const l=e.state==="running"&&(e.material==="voiceover"||e.material==="sound-effect");$.useEffect(()=>{l||i(!1)},[l]);const c=e.state==="running"||e.state==="cancelling"?e.startedAtMs:null,u=VEt(c),O=YEe(e,n),d={cancel:n?.onCancel,restart:n?.onRestart,editRestart:n?.onEditRestart},f=e.state==="running"||e.state==="cancelling",p=f&&(e.state==="running"||e.generating),m=f&&e.progress.logs.length>0?e.progress.logs[e.progress.logs.length-1]:null;return h.jsxs("div",{ref:o,tabIndex:-1,"data-imagegen-card":e.state,className:q("flex w-full flex-col gap-2"),children:[p?h.jsx(LEt,{}):null,e.state==="failed"&&(e.material==="voiceover"||e.material==="sound-effect")&&e.errorType?h.jsx("p",{className:q("text-meta text-ink-dim"),children:e.errorType}):null,h.jsx(FEt,{view:e,elapsed:u}),(e.state==="done"||e.state==="failed"||e.state==="cancelled")&&e.costCaption?h.jsx(Lg,{line:e.costCaption,prominent:!!e.batch}):null,(e.state==="done"||e.state==="failed"||e.state==="cancelled")&&e.batchNote?h.jsx(Lg,{line:e.batchNote,prominent:!0}):null,e.state==="running"&&e.batchProgress?.note?h.jsx(Lg,{line:e.batchProgress.note}):null,e.state==="cancelled"&&e.settlementCaption?h.jsx(Lg,{line:e.settlementCaption}):null,l&&r?h.jsx(pQe,{onKeepWaiting:a,onRequestStop:()=>{i(!1),n?.onCancel?.()}}):null,e.state==="running"&&typeof e.note=="string"?h.jsx(Lg,{line:e.note}):null,p&&e.progress.fraction!==null?h.jsx(nXe,{"aria-label":"Image generation progress",className:q("max-w-[240px]"),value:Math.round(Math.min(1,Math.max(0,e.progress.fraction))*100)}):null,m===null?null:h.jsx(BEt,{line:m}),(e.state==="done"||e.state==="failed"||e.state==="cancelled")&&e.batch?h.jsx(DEt,{items:e.batch,summary:e.batchSummary??`${e.batch.length} items`,scope:t}):e.state==="done"&&e.images.length>0?h.jsx("div",{className:q("flex flex-col gap-2"),children:e.images.map((g,y)=>{const v=`Generated ${Dh(g.kind==="audio"?e.material:g.kind??"image")}`,S=e.images.length===1?v:`${v} ${y+1}`;return g.kind==="video"?h.jsx(ZEt,{video:g,scope:t,label:S},g.id):g.kind==="audio"?h.jsx(AU,{audio:g,scope:t,label:S},g.id):h.jsx(Dm,{image:g,scope:t,label:S},g.id)})}):null,O.length>0&&!(l&&r)?h.jsx("div",{"data-imagegen-controls":"",className:q("flex items-center gap-2"),children:O.map(g=>h.jsx(Xe,{variant:"secondary",size:"sm",disabled:g.disabled,title:g.kind==="cancel"?e.state==="queued"||e.state==="cancelling"&&!e.generating?"Stops before the provider is called.":"Requests a stop; the provider may finish anyway.":void 0,onClick:g.kind==="cancel"&&l?()=>{const y=o.current?.closest("[data-chat-pane]")?.querySelector("[data-sound-stop-confirmation] button");if(y){y.focus();return}i(!0)}:d[g.kind],children:HEt(g.kind,e.state)},g.kind))}):null]})},l$=1e4,mQe=/\s/,JEt=e=>{for(let t=e.length;t>0;t-=1){const n=e[t-1];if(n===`
869
869
  `)return t;if(n==="."||n==="!"||n==="?"){const r=e[t];if(r===void 0||mQe.test(r))return t}}return-1},eqt=e=>{for(let t=e.length;t>0;t-=1)if(mQe.test(e[t-1]))return t;return-1},tqt=/[\uD800-\uDBFF]/,nqt=e=>tqt.test(e[l$-1])?l$-1:l$;function WU(e){if(e.length<=l$)return{text:e,clipped:!1};const t=e.slice(0,l$),n=JEt(t),r=eqt(t),i=n>0?n:r>0?r:nqt(t),a=e.slice(0,i).trimEnd();return{text:a.length>0?a:t,clipped:!0}}const gQe="[speech]",rqt="Couldn't speak this aloud. Try again.",iqt="Couldn't speak this aloud. Try again.",$Qe="This conversation's agent is no longer available.",aqt=new Set(["Your Radient sign-in has stopped working. Sign in again in Settings.","Your Radient credit balance is too low for speech. Add credits in the Radient Console to continue.","Speech is unavailable right now. Try again in a moment.","Speech is temporarily unavailable. Try again in a moment.","Speech is temporarily unavailable.","Sign in to Radient in Settings to enable speaking aloud.",$Qe,"ElevenLabs refused your API key. Replace it.","Your ElevenLabs credit balance is too low for speech. Add credits with ElevenLabs to continue.","OpenAI refused your API key. Replace it.","Your OpenAI credit balance is too low for speech. Add credits with OpenAI to continue.","Your Radient sign-in has stopped working. Sign in again in the settings page.","Sign in to Radient in the settings page to enable text to speech."]);function oqt(e){const t=e instanceof Error?e.message:String(e);return aqt.has(t)?t:(console.error(`${gQe} ${t}`),rqt)}function sqt(e){return(e instanceof Error?e.message:String(e))===$Qe}function lqt(e){const t=e?.binding?.agent;return typeof t=="string"&&t.length>0?t:null}function cqt(e,t){if(!e)return{state:"unknown"};const n=(t??[]).find(r=>r.name===e);return n?n.agent_id?{state:"agent",agentId:n.agent_id}:{state:"role-without-agent"}:{state:"unknown"}}const uqt=100;function Oqt(e,t){if(!e)return null;const n=t?.agents??[],r=t?.total;if(typeof r=="number"&&r>n.length)return n.find(s=>s.name===e||s.id===e)?.id??null;const i=n.find(o=>o.name===e);if(i)return i.id;const a=n.find(o=>o.id===e);return a?a.id:null}async function yR(e){try{return await e()}catch{return null}}async function dqt(e){if(!e)return null;const t=hv(Nf.baseUrl),n=await yR(async()=>{const{profiles:a}=await Re({op:"profiles.list"});return cqt(e,a)});if(n?.state==="agent")return n.agentId;if(n?.state==="role-without-agent")return null;const r=await yR(async()=>{const a=await t.agents.listAgents(1,uqt,e);return a.status<400?Oqt(e,a.result??null):null});return r||await yR(async()=>{const a=await t.agents.getAgent(e);return a.status<400?a.result?.id??null:null})}function NU(e){return ar(t=>e?lqt(t.sessions.find(n=>n.session_id===e)):null)}const fqt=20,yQe=e=>`msg:${e}`,jK=e=>`speech:${e}`,hqt="speech:",pqt=e=>{let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")},Cx=(e,t)=>`sel:${e}:${pqt(t)}`,YU=(e,t)=>async()=>{const n=()=>CK.speech.create({input:t}),r=await dqt(e);return r===null?n():CK.speech.createForAgent(r,{input_text:t}).catch(i=>{if(!sqt(i))throw i;return n()})},CK=hv(Nf.baseUrl),mqt=e=>{for(;e.size>fqt;){const t=e.keys().next().value;if(t===void 0)return;e.delete(t)}},vR=new Map,gqt=(e,t)=>{let n=vR.get(e);return n===void 0&&(n=t().finally(()=>{vR.delete(e)}),vR.set(e,n)),n},Mv=ta((e,t)=>({audioCache:new Map,heardKeys:new Set,loadingKey:null,playingKey:null,error:null,audioElement:null,currentUrl:null,generation:0,speak:async(n,r)=>{const i=t().generation+1;t().stopSpeech(),e({loadingKey:n,error:null,generation:i});try{let a=t().audioCache.get(n);if(a){const c=new Map(t().audioCache);c.delete(n),c.set(n,a),e({audioCache:c})}else{const c=await gqt(n,r);if(!c)throw new Error("Speech generation failed, no audio data received.");a=c;const u=new Map(t().audioCache);if(u.set(n,c),mqt(u),e({audioCache:u}),t().generation!==i)return}if(t().generation!==i)return;const o=URL.createObjectURL(a);if(!await Fi.getState().play(jK(n),o,{onEnded:()=>{URL.revokeObjectURL(o),e(c=>c.audioElement===Fi.getState().element?{playingKey:null,audioElement:null,currentUrl:null}:{})},onError:()=>{URL.revokeObjectURL(o),e(c=>c.audioElement===Fi.getState().element?{error:"Error playing audio.",playingKey:null,audioElement:null,currentUrl:null}:{}),console.error(`${gQe} playback failed for ${n}`),mi(iqt)}})||t().generation!==i){Fi.getState().stop(jK(n)),URL.revokeObjectURL(o);return}const l=new Set(t().heardKeys);l.add(n),e({playingKey:n,loadingKey:null,audioElement:Fi.getState().element,currentUrl:o,heardKeys:l})}catch(a){if(t().generation!==i)return;const o=a instanceof Error?a.message:"Failed to generate speech";e({error:o,loadingKey:null}),mi(oqt(a))}},stopSpeech:()=>{const n=Fi.getState();n.ownerId?.startsWith(hqt)&&n.stop();const{currentUrl:r}=t();r&&URL.revokeObjectURL(r),e({playingKey:null,audioElement:null,currentUrl:null})},dismiss:n=>{const{loadingKey:r,playingKey:i,generation:a}=t();r===n&&e({generation:a+1,loadingKey:null}),i===n&&t().stopSpeech()},playSpeech:async(n,r,i)=>{await t().speak(yQe(n),YU(r,i))}}));function GU({key:e,getText:t,play:n,available:r=!0}){const{dismiss:i,stopSpeech:a,loadingKey:o,playingKey:s,audioCache:l,heardKeys:c}=Mv(),{canUseRadientSpeech:u,speechBlock:O}=fGe(),d=e!==null&&s===e,f=e!==null&&o===e,p=e!==null&&l.has(e),m=p&&e!==null&&c.has(e),g=u?null:ode("speaking-aloud",O),y=!d&&!f&&(!u||!r);return{label:d?"Stop":f?"Loading speech. Press again to cancel.":m?"Replay speech":"Speak aloud",tooltip:d?"Stop":f?"Loading speech. Press again to cancel.":g??(m?"Replay speech":"Speak aloud"),isPlaying:d,isLoading:f,disabled:y,reason:g,active:d||f,press:()=>{if(d){a();return}if(f){e!==null&&i(e);return}if(y)return;const b=t();if(b===null||b.trim().length===0)return;const{text:w,clipped:x}=WU(b);x&&!p&&Tp(`Reading the first ${w.length.toLocaleString("en-US")} characters. The rest is not read aloud.`),n({text:w})}}}function vQe(e){$.useEffect(()=>{if(e!==null)return()=>{Mv.getState().dismiss(e)}},[e])}const IU=({control:e,side:t="top"})=>{const n=$.useId(),r=e.disabled&&e.reason!==null;return h.jsx(Yt,{content:e.tooltip,side:t,children:h.jsxs("span",{className:q("flex"),tabIndex:r?0:void 0,"aria-describedby":r?n:void 0,children:[h.jsx(Xe,{variant:"ghost",size:"icon-sm","aria-label":e.label,className:q("text-ink-dim hover:bg-accent-wash hover:text-accent"),onClick:e.press,disabled:e.disabled,children:e.isPlaying?h.jsx(m1,{"aria-hidden":"true"}):e.isLoading?h.jsx(Go,{size:"xs"}):h.jsx(L9e,{"aria-hidden":"true"})}),r&&h.jsx("span",{id:n,className:"sr-only",children:e.reason})]})})},Mm="data-lo-quote-toolkit";function p7(e,t){return e.kind!=="user"&&e.kind!=="assistant"||t.trim().length===0?!1:e.kind!=="assistant"?!0:!e.streaming}const AK=e=>(e.nodeType===Node.ELEMENT_NODE?e:e.parentElement)?.closest(`[${Mm}]`)??null,$qt=e=>e.nodeType===Node.ELEMENT_NODE,yqt=e=>{const t=Array.from(e.childNodes),n=t.findIndex(r=>$qt(r)&&r.hasAttribute(Mm));return n===-1?t.length:n},vqt=(e,t)=>Math.abs(e.top-t.top)<.5&&Math.abs(e.left-t.left)<.5&&Math.abs(e.right-t.right)<.5&&Math.abs(e.bottom-t.bottom)<.5,bqt=e=>{const t=Array.from(document.querySelectorAll(`[${Mm}]`),n=>n.getBoundingClientRect());return Array.from(e.getClientRects()).filter(n=>!t.some(r=>vqt(r,n))).map(n=>({top:n.top,left:n.left,right:n.right,bottom:n.bottom}))};function $y(e){if(!e)return null;const t=window.getSelection();if(!t||t.rangeCount===0||t.isCollapsed)return null;const n=t.getRangeAt(0);if(AK(n.startContainer)||AK(n.endContainer)||!e.contains(n.startContainer))return null;const r=n.cloneRange();e.contains(n.endContainer)||r.setEnd(e,yqt(e));const i=r.toString().trim();return i.length===0?null:{text:i,lines:bqt(n)}}const bQe=8,wqt=.5;function Sqt(e,t){const n={top:Math.max(e.top,t.top),left:Math.max(e.left,t.left),right:Math.min(e.right,t.right),bottom:Math.min(e.bottom,t.bottom)};return n.right>n.left&&n.bottom>n.top?n:null}const zK=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function xqt({lines:e,container:t,viewport:n,size:r,gap:i=bQe,row:a,belowWhenOffFirstLine:o=!1}){if(e.length===0)return null;const s=Sqt(t,n);if(!s)return null;const l=e[0],c=e[e.length-1];if(l.bottom<=s.top||l.top>=s.bottom)return null;const u=Math.max(l.bottom-l.top,1),O=a!==void 0&&l.top-a.top>u*wqt,d=l.top-i-r.height>=s.top,f=c.bottom+i+r.height<=s.bottom,m=d&&!(o&&O&&f);return{top:zK(m?l.top-i-r.height:c.bottom+i,s.top,s.bottom-r.height),left:zK(l.left,s.left,s.right-r.width),placement:m?"above":"below"}}const UK="[data-lo-canonical-transcript]",Qqt="[data-lo-transcript-content]",WK=e=>({top:e.top,left:e.left,right:e.right,bottom:e.bottom}),kqt=()=>({top:0,left:0,right:window.innerWidth,bottom:window.innerHeight});function wQe(e){const{turnRef:t,visible:n,lines:r,measureKey:i,belowWhenOffFirstLine:a}=e,o=$.useRef(null),[s,l]=$.useState(null),c=$.useRef(r);c.current=r;const u=$.useCallback(()=>{const O=t.current,d=o.current;if(!O||!d){l(null);return}const f=c.current();if(!f||f.length===0){l(null);return}const p=xqt({lines:f,container:WK((O.closest(UK)??O).getBoundingClientRect()),viewport:kqt(),size:{width:d.offsetWidth,height:d.offsetHeight},row:WK(O.getBoundingClientRect()),belowWhenOffFirstLine:a}),m=O.getBoundingClientRect(),g=p?{top:p.top-m.top,left:p.left-m.left,placement:p.placement}:null;l(y=>y===g||y&&g&&y.top===g.top&&y.left===g.left&&y.placement===g.placement?y:g)},[t,a]);return $.useLayoutEffect(()=>{if(!n){l(null);return}u();let O=0;const d=()=>{O||(O=requestAnimationFrame(()=>{O=0,u()}))};document.addEventListener("scroll",d,!0),document.addEventListener("selectionchange",d),window.addEventListener("resize",d);const f=t.current?.closest(UK),p=f?.querySelector(Qqt),m=new ResizeObserver(d);return f&&m.observe(f),p&&m.observe(p),()=>{O&&cancelAnimationFrame(O),document.removeEventListener("scroll",d,!0),document.removeEventListener("selectionchange",d),window.removeEventListener("resize",d),m.disconnect()}},[n,u,t,i]),{controlRef:o,placement:s}}function SQe(e){const[t,n]=$.useState(null);$.useEffect(()=>{const i=()=>n($y(e.current)?.text??null);return i(),document.addEventListener("selectionchange",i),()=>document.removeEventListener("selectionchange",i)},[e]);const r=$.useCallback(()=>n(null),[]);return{text:t,clear:r}}const Ih="data-lo-link-toolbar",Pqt=120,_qt=2;function xQe(e){const[t,n]=$.useState(null),[r,i]=$.useState(!1),a=$.useRef(null);a.current=t;const o=$.useRef(null),s=$.useRef(null),l=$.useCallback(()=>{const u=e.current;if(!u){o.current=null,n(f=>f===null?f:null),i(f=>f===!1?f:!1);return}const O=OTt(u);if(O){n(f=>f===O?f:O),i(f=>f===!0?f:!0);return}if(i(f=>f===!1?f:!1),FSe()){n(f=>f===null?f:null);return}const d=o.current&&u.contains(o.current)?o.current:null;n(f=>f===d?f:d)},[e]);$.useEffect(()=>{const u=e.current;if(!u)return;let O=0;const d=x=>{O&&(clearTimeout(O),O=0),o.current=x,l()},f=x=>{if(O&&clearTimeout(O),!x){O=0,o.current=null,l();return}o.current!==x&&(s.current=null,O=setTimeout(()=>{O=0,o.current=x,l()},Pqt))},p=(x,k)=>{const T=o.current;if(!T||!u.contains(T))return!1;const _=u.querySelector(`[${Ih}]`),E=bQe+_qt;for(const R of[T,_]){if(!R)continue;const j=R.getBoundingClientRect();if(!(j.width<=0||j.height<=0)&&x>=j.left-E&&x<=j.right+E&&k>=j.top-E&&k<=j.bottom+E)return!0}return!1},m=x=>{const k=x.target;if(k?.closest(`[${Mm}]`))return;const T=k?.closest(Gh)??null;!T&&p(x.clientX,x.clientY)||f(T)},g=x=>{const k=x.relatedTarget;k&&u.contains(k)||p(x.clientX,x.clientY)||d(null)},y=x=>{const k=x.target?.closest(Gh);if(k){if(k===s.current){s.current=null;return}d(k)}},v=x=>{const k=x.relatedTarget;k&&u.contains(k)||d(null)},S=()=>Array.from(u.querySelectorAll(`[${Ih}] button:not([disabled])`)),Q=x=>{const k=x.target;if(!k)return!1;if(k.closest(`[${Ih}]`)){const R=S(),j=R.indexOf(k);if(j===-1)return!1;if(x.shiftKey&&j===0){const C=o.current;return C instanceof HTMLElement?(C.focus(),!0):!1}if(!x.shiftKey&&j===R.length-1){const C=Array.from(u.querySelectorAll(Gh)),W=o.current,G=W?C.indexOf(W)+1:-1,N=G>0?C[G]:void 0;return N?(N.focus(),!0):!1}return!1}if(x.shiftKey)return!1;const _=k.closest(Gh);if(!_||!u.contains(_))return!1;o.current!==_&&d(_);const[E]=S();return E?(E.focus(),!0):!1},b=x=>{if(x.key==="Tab"&&Q(x)){x.preventDefault();return}if(!(x.key==="ContextMenu"||x.shiftKey&&x.key==="F10"))return;const T=x.target?.closest(Gh);!T||!u.contains(T)||(x.preventDefault(),d(T),requestAnimationFrame(()=>{u.querySelector(`[${Ih}] button`)?.focus()}))},w=x=>{const k=x.target;k&&u.contains(k)||d(null)};return u.addEventListener("pointerover",m),u.addEventListener("pointerout",g),u.addEventListener("focusin",y),u.addEventListener("focusout",v),u.addEventListener("keydown",b),document.addEventListener("pointerdown",w,!0),document.addEventListener("selectionchange",l),l(),()=>{O&&clearTimeout(O),u.removeEventListener("pointerover",m),u.removeEventListener("pointerout",g),u.removeEventListener("focusin",y),u.removeEventListener("focusout",v),u.removeEventListener("keydown",b),document.removeEventListener("pointerdown",w,!0),document.removeEventListener("selectionchange",l)}},[e,l]);const c=$.useCallback(()=>{s.current=a.current,o.current=null,l()},[l]);return $.useEffect(()=>{if(!t)return;const u=O=>{if(O.key!=="Escape"||O.target?.closest(`[${Ih}]`))return;const f=window.getSelection();f&&!f.isCollapsed&&f.removeAllRanges(),c()};return document.addEventListener("keydown",u),()=>document.removeEventListener("keydown",u)},[t,c]),{subject:t,quoteAvailable:r,dismiss:c}}function QQe(e,t,n){const r=an(i=>i.addReply);return $.useCallback(()=>{const a=$y(t.current)?.text??(FSe()?null:n?.()??null);a&&(r(e,{id:fs(),text:a}),window.getSelection()?.removeAllRanges(),_z())},[r,e,t,n])}const kQe=({conversationId:e,turnRef:t,subject:n,quoteAvailable:r,onDismiss:i})=>{const a=n.getAttribute(VSe)??"",o=n.getAttribute("data-lo-kind")??"file",s=SP(),l=$.useCallback(()=>(n.textContent??"").trim()||null,[n]),c=QQe(e,t,l),{text:u}=SQe(t),{speak:O}=Mv(),d=NU(e),f=u??l(),p=f===null?null:Cx(e,WU(f).text);vQe(p);const m=GU({key:p,getText:()=>$y(t.current)?.text??l(),play:({text:W})=>O(Cx(e,W),YU(d,W))}),[g,y]=$.useState(!1),[v,S]=$.useState(()=>L1(a)??null),{controlRef:Q,placement:b}=wQe({turnRef:t,visible:!0,lines:()=>{const W=n.getClientRects();return Array.from(W,G=>({top:G.top,left:G.left,right:G.right,bottom:G.bottom}))},measureKey:n,belowWhenOffFirstLine:!0});$.useEffect(()=>{const W=L1(a);if(S(W??null),y(!1),W!==void 0)return;let G=!0;return sTt(a,window.api?.probeFiles).then(()=>{G&&S(L1(a)??null)}),()=>{G=!1}},[a]);const w=o==="file"&&SU(s,a),x=KSe({target:a,isDirectory:v?.exists===!0&&!v.isFile,probe:v,canOpenInCanvas:w}),k=hTt({kind:o,target:a,probe:v,quotable:r,canOpenInCanvas:w});if(!k||!a)return null;const T=async()=>{await txe(a)&&y(!0)},_=async()=>{if(o==="url"){await TH(o,a);return}s&&x&&await s.openInCanvas(a)||await TH(o,a)||S(null)},E=async()=>{await AO(a)||S(null)},R=async()=>{await xU(a)||S(null)},j={quote:h.jsx(Wue,{}),copy:g?h.jsx(xu,{}):h.jsx(hk,{}),open:x?h.jsx(g9e,{}):o==="url"?h.jsx(Pue,{}):h.jsx(dv,{}),"open-default":h.jsx(AAe,{}),"open-folder":h.jsx(Rp,{})},C={quote:c,copy:()=>{T()},open:()=>{_()},"open-default":()=>{E()},"open-folder":()=>{R()}};return h.jsxs("div",{[Mm]:"",[Ih]:"",ref:Q,role:"toolbar","aria-label":k.label,className:q("absolute z-10 flex h-8 items-center gap-0.5 rounded-md border border-hairline bg-elevated px-1",!b&&"invisible"),style:b?{top:b.top,left:b.left}:void 0,onMouseDown:W=>W.preventDefault(),onKeyDown:W=>{if(W.key!=="Escape")return;window.getSelection()?.removeAllRanges();const G=n;W.preventDefault(),i(),G.focus?.()},children:[k.actions.map(W=>h.jsxs($.Fragment,{children:[h.jsx(Yt,{content:W.id==="copy"&&g?"Copied":W.label,side:b?.placement==="below"?"bottom":"top",children:h.jsx(Xe,{variant:"ghost",size:"icon-sm","aria-label":W.id==="copy"&&g?"Copied":W.label,className:"text-ink-dim hover:bg-accent-wash hover:text-accent",onClick:C[W.id],children:j[W.id]})}),W.id==="quote"&&h.jsx(IU,{control:m,side:b?.placement==="below"?"bottom":"top"})]},W.id)),k.note&&h.jsx("span",{className:"max-w-56 truncate pl-1 text-ink-dim text-meta",title:k.noteTitle??k.note,children:k.note})]})};function Tqt({role:e="answer",forkable:t=!1}={}){const n=t?["fork"]:[];return e==="user"?["copy",...n]:e==="response"?["copy"]:["copy","speak",...n]}function PQe(e){return e.kind!=="user"&&e.kind!=="assistant"||e.kind==="assistant"&&e.streaming?null:e.id||null}const NK=96;function Rqt(e){const t=e.replace(/\s+/g," ").trim();return t.length<=NK?t:`${t.slice(0,NK-1).trimEnd()}…`}const Xqt="Answer actions",Eqt="Your message actions",qqt="pointer-events-none opacity-0 transition-opacity duration-fast ease-out-quart group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100 [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100";function jqt(e){return e?"opacity-100":qqt}const Cqt=2e3,Aqt=1e4;function FOn(e){const{request:t}=e;return t?e.now-t.requestedAt>Aqt?"retire":e.presentable?e.claimed?"hold":"present":"yield":null}let YK=0,Ww=0;const zqt=ta(e=>({request:null,requestPanel:(t,n,r,i)=>{YK+=1,e({request:{destination:t,nonce:YK,requestedAt:Date.now(),invoker:n??null,...r?{sessionId:r}:{},...i?.id?{entryId:i.id}:{},...i?.id&&i.excerpt?{entryExcerpt:i.excerpt}:{},...r&&i?.subjectName?{subjectName:i.subjectName}:{}}})},consumePanel:t=>e(n=>n.request?.nonce===t?{request:null}:n),presenterClaimed:!1,claimPresenter:()=>{Ww+=1,e({presenterClaimed:!0});let t=!1;return()=>{t||(t=!0,Ww=Math.max(0,Ww-1),Ww===0&&e({presenterClaimed:!1}))}}})),Uqt=(e,t)=>{let n=e;for(;n!==null;){if(n.matches(":hover"))return!0;if(n===t)break;n=n.parentElement}const r=e.ownerDocument.activeElement;return r!==null&&t.contains(r)},Wqt=9e4,GK=new Set,Nqt=2600,m7=$.memo(function({bodyText:t,kind:n="answer",agentId:r,speechId:i,revealId:a,revealAt:o,conversationId:s,entryId:l}){const[c,u]=$.useState(!1),[O,d]=$.useState(!1),f=$.useRef(null),p=$.useRef(null),m=$.useRef(null),g=$.useRef(null),{playSpeech:y}=Mv(),v=NU(r??null),S=GU({key:i?yQe(i):null,getText:()=>t,play:({text:E})=>{i&&y(i,v,E)}}),Q=zqt(E=>E.requestPanel),b=!!(s&&l);br();const w=Tqt({role:n,forkable:b}),x=c||S.active;$.useEffect(()=>()=>{f.current!==null&&clearTimeout(f.current)},[]),$.useEffect(()=>{if(!a||o===void 0||GK.has(a)||(GK.add(a),Date.now()-o>Wqt))return;const E=p.current;if(E===null)return;const R=E.closest(".group")??E;if(Uqt(E,R))return;d(!0);const j=()=>{d(!1),R.removeEventListener("pointerenter",j),R.removeEventListener("focusin",j)};return R.addEventListener("pointerenter",j),R.addEventListener("focusin",j),()=>{R.removeEventListener("pointerenter",j),R.removeEventListener("focusin",j)}},[a,o]),$.useEffect(()=>{if(O)return g.current=setTimeout(()=>{g.current=null,d(!1)},Nqt),()=>{g.current!==null&&clearTimeout(g.current)}},[O]);const k=async()=>{await txe(t)&&(u(!0),f.current!==null&&clearTimeout(f.current),f.current=setTimeout(()=>{f.current=null,u(!1)},Cqt))},T=()=>{!s||!l||Q("session.fork",m.current,s,{id:l,excerpt:Rqt(t)})},_={copy:h.jsx(Yt,{content:c?"Copied":"Copy",side:"bottom",children:h.jsx(Xe,{variant:"ghost",size:"icon-sm","aria-label":c?"Copied":"Copy",className:q("text-ink-dim hover:bg-accent-wash hover:text-accent"),onClick:k,children:c?h.jsx(xu,{"aria-hidden":"true"}):h.jsx(hk,{"aria-hidden":"true"})})}),speak:h.jsx(IU,{control:S,side:"bottom"}),fork:h.jsx(Yt,{content:"Fork from this message",side:"bottom",children:h.jsx(Xe,{variant:"ghost",size:"icon-sm","aria-label":"Fork from this message",ref:m,className:q("text-ink-dim hover:bg-accent-wash hover:text-accent"),onClick:T,children:h.jsx(Rze,{"aria-hidden":"true"})})})};return h.jsx("div",{role:"toolbar","aria-label":n==="user"?Eqt:n==="response"?J("ui.chat.response_actions.label"):Xqt,ref:p,onAnimationEnd:E=>{E.target===E.currentTarget&&d(!1)},...O?{"data-lo-arrive":""}:{},...n==="user"?{"data-lo-user-actions":""}:n==="response"?{"data-lo-response-actions":""}:{"data-lo-answer-actions":""},className:q("flex shrink-0 items-center gap-1",jqt(x)),children:w.map(E=>h.jsx($.Fragment,{children:_[E]},E))})}),Yqt="@container/olderhistory mb-4 flex h-7 min-w-0 items-center gap-2",Nw="@min-[260px]/olderhistory:hidden",Yw="@max-[260px]/olderhistory:hidden",_Qe="lo-older-history-hint",Gqt=({state:e,transportDown:t=!1,onLoadOlder:n,onRetryHydration:r})=>{const i=e==="loading"?"Loading earlier messages":e==="failed"?t?"Earlier messages did not load":"Could not load earlier messages":e==="unproven"?"Earlier history not loaded":null,a=e==="loading";return h.jsxs("div",{className:Yqt,children:[h.jsx("output",{className:"sr-only","aria-live":"polite",children:i}),e==="failed"&&t?h.jsxs("span",{className:"min-w-0 truncate text-ink-dim text-meta",children:[h.jsx("span",{className:Nw,children:"Not loaded"}),h.jsx("span",{className:Yw,children:"Earlier messages did not load"})]}):e==="failed"?h.jsxs(h.Fragment,{children:[h.jsxs("span",{className:"min-w-0 truncate text-danger text-meta",title:"Could not load earlier messages",children:[h.jsx("span",{className:Nw,children:"Did not load"}),h.jsx("span",{className:Yw,children:"Could not load earlier messages"})]}),h.jsx(Xe,{variant:"ghost",size:"sm",className:"shrink-0",onClick:n,children:"Try again"})]}):a?h.jsxs(Xe,{variant:"ghost",size:"sm","aria-disabled":!0,onClick:o=>{o.preventDefault()},className:"text-ink-muted",children:[h.jsx(Go,{size:"sm"}),"Loading earlier messages"]}):e==="idle"?h.jsx(Xe,{variant:"ghost",size:"sm",onClick:n,children:"Load earlier messages"}):e==="windowed"?h.jsxs("span",{id:_Qe,className:"min-w-0 truncate text-ink-dim text-meta",title:t?"Earlier history above":"Earlier history above — scroll up to load",children:[h.jsx("span",{className:Nw,children:t?"Earlier history above":"Scroll up for earlier"}),h.jsxs("span",{className:Yw,children:["Earlier history above",t?"":" — scroll up to load"]})]}):e==="unproven"?h.jsxs(h.Fragment,{children:[h.jsxs("span",{className:"min-w-0 truncate text-ink-dim text-meta",title:"Earlier history not loaded",children:[h.jsx("span",{className:Nw,children:"Earlier not loaded"}),h.jsx("span",{className:Yw,children:"Earlier history not loaded"})]}),!t&&r&&h.jsx(Xe,{variant:"ghost",size:"sm",className:"shrink-0",onClick:r,children:"Try again"})]}):h.jsx("span",{className:"min-w-0 truncate text-ink-dim text-meta",children:"Start of conversation"})]})},Iqt="/settings?section=providers",IK="/settings?section=providers&provider=radient",Zqt="/settings?section=radient",ZK=/sign in to radient/i,Dqt=[/insufficient credits/i,/credit balance is too low/i],Mqt=[/rate limit or quota/i],Vqt=[/insufficient credits/i,/\bHTTP 402\b/i];function TQe(e){return(e??"").split("/")[0]?.trim().toLowerCase()==="radient"}function ZU(e){return TQe(e.provider)?e.category==="billing"?!0:(e.category==null||e.category==="unknown"||e.category==="rate-limit")&&Vqt.some(n=>n.test(e.text)):!1}function Lqt(e){if(!ZU(e))return null;const t=/rate limit or quota( exceeded)?\s*/i;if(!t.test(e.headline))return{label:"billing",headline:e.headline};const n=e.headline.replace(t,"").trim(),r=/^\((HTTP \d{3})\):?\s*(.*)$/i.exec(n),i=(r?r[2]:n.replace(/^:\s*/,"")).trim(),a=r?` (${r[1]})`:"";return{label:"billing",headline:i?`Out of credits${a}: ${i}`:`Out of credits${a}: Radient refused the request`}}function Fqt(e){return e==="auth"?"sign-in":e==="billing"?"billing":e==="rate-limit"?"quota":null}function DK(e){const t=TQe(e.provider)||ZK.test(e.text);let n=Fqt(e.category);return ZU(e)&&(n="billing"),n===null&&(e.category==null||e.category==="unknown")&&(ZK.test(e.text)?n="sign-in":Dqt.some(r=>r.test(e.text))?n="billing":Mqt.some(r=>r.test(e.text))&&(n="quota")),n===null?null:n==="sign-in"&&t?{label:"Sign in to Radient",to:IK}:n==="billing"&&t?{label:"Open Radient account",to:Zqt}:{label:"Open provider settings",to:t?IK:Iqt}}const RQe=({conversationId:e,turnRef:t})=>{const{text:n,clear:r}=SQe(t),i=n!==null,a=QQe(e,t),{controlRef:o,placement:s}=wQe({turnRef:t,visible:i,lines:()=>$y(t.current)?.lines??null}),{speak:l}=Mv(),c=NU(e),u=n===null?null:Cx(e,WU(n).text);vQe(u);const O=GU({key:u,getText:()=>$y(t.current)?.text??null,play:({text:d})=>l(Cx(e,d),YU(c,d))});return $.useEffect(()=>{if(!i)return;const d=f=>{f.key!=="Escape"||f.defaultPrevented||(window.getSelection()?.removeAllRanges(),r())};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[i,r]),i?h.jsxs("div",{[Mm]:"",ref:o,className:q("absolute z-10 flex h-8 items-center gap-0.5 rounded-md border border-hairline bg-elevated px-1",!s&&"invisible"),style:s?{top:s.top,left:s.left}:void 0,onMouseDown:d=>d.preventDefault(),children:[h.jsx(Yt,{content:"Quote",side:s?.placement==="below"?"bottom":"top",children:h.jsx(Xe,{variant:"ghost",size:"icon-sm","aria-label":"Quote",className:"text-ink-dim hover:bg-accent-wash hover:text-accent",onClick:a,children:h.jsx(Wue,{})})}),h.jsx(IU,{control:O,side:s?.placement==="below"?"bottom":"top"})]}):null},XQe={all:["radient-prices"],prices:()=>[...XQe.all,"prices"]},Bqt=()=>{const e=jt({queryKey:XQe.prices(),queryFn:()=>Az({operation:"prices"}),staleTime:36e5,refetchOnWindowFocus:!1,refetchOnMount:!0,refetchInterval:!1,retry:3});return{prices:e.data,isLoading:e.isLoading,isFetching:e.isFetching,error:e.error,pricesQuery:e}},MK="https://console.radienthq.com/dashboard/verification",VK="https://console.radienthq.com/dashboard/billing",LK="Top up in Radient console";function Hqt(e){return!e.email_verified&&e.signup_grant!=="claimed"}const BOn=e=>typeof e!="number"||!Number.isFinite(e)?"your free credits":`$${e.toFixed(2)} in free credits`,g7=e=>Number.isInteger(e)?`$${e}`:`$${e.toFixed(2)}`,Kqt=e=>typeof e!="number"||!Number.isFinite(e)?"your free credits":`${g7(e)} in free credits`;function FK(e,t){if(!e)return t;try{const{protocol:n}=new URL(e);return n==="https:"||n==="http:"?e:t}catch{return t}}function Jqt(e){window.api?.openExternal?window.api.openExternal(e):window.open(e,"_blank")}const ejt=(e,t)=>e==="pending"?{sentence:`Verify your email to claim ${t}. Check your inbox for the link Radient sent.`,action:"Open verification page"}:e==="expired"?{sentence:`The link to claim ${t} has expired. Request a new one from the verification page.`,action:"Request a new link"}:{sentence:"No signup grant is attached to this account. Open the verification page to check the account.",action:"Open verification page"};function tjt(e,t){if(e===void 0)return{state:"unknown",lines:["You're out of credits. If you haven't verified your email yet, verify it to claim free credits and start using Local Operator for free.","Otherwise, top up in the Radient console."],links:[{label:"Open verification page",url:MK},{label:LK,url:VK}]};if(Hqt(e)){const i=FK(e.claim_url,MK),{action:a}=ejt(e.signup_grant,"");return e.signup_grant==="none"?{state:"unverified",lines:["You haven't verified your email yet. Open the verification page to check whether free credits are waiting on your account."],links:[{label:a,url:i}]}:{state:"unverified",lines:[`You haven't verified your email yet. Verify to claim ${Kqt(e.grant_amount??t)} and start using Local Operator for free.`,e.signup_grant==="expired"?"The link you were sent has expired. Request a new one on the verification page.":"Check your inbox for the link Radient sent."],links:[{label:a,url:i}]}}const n=e.first_topup,r=["You're out of credits. Top up in the Radient console."];return n!==void 0&&n.bonus_received===!1&&Number.isFinite(n.bonus_amount)&&Number.isFinite(n.minimum_purchase)&&r.push(`Get an extra ${g7(n.bonus_amount)} free on your first top-up of ${g7(n.minimum_purchase)} or more.`),{state:"verified",lines:r,links:[{label:LK,url:FK(n?.topup_url,VK)}]}}const njt=5*1e3,rjt=({action:e})=>{const{user:t,accountRead:n}=cde({staleTime:njt,retryOnMount:!1}),r=Ri(),{prices:i}=Bqt(),o=r.isPending||n==="checking"?null:tjt(n==="ready"?t?.verification:void 0,i?.default_new_credits);return h.jsxs("div",{className:"mt-1 flex flex-col items-start gap-2 pl-6",children:[o?h.jsxs("div",{"data-radient-credits-state":o.state,className:"flex max-w-[60ch] items-start gap-3 rounded-sm border border-hairline bg-surface p-3",children:[h.jsx(KQ,{className:"mt-0.5 size-4 shrink-0 text-ink-muted","aria-hidden":"true"}),h.jsx("div",{className:"min-w-0 text-body-sm text-ink",children:o.lines.map(s=>h.jsx("p",{className:"[&:not(:first-child)]:mt-1",children:s},s))})]}):null,h.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o?.links.map(s=>h.jsx(Xe,{variant:"secondary",size:"sm",onClick:()=>Jqt(s.url),children:s.label},s.url)),h.jsx(Xe,{variant:"ghost",size:"sm",asChild:!0,children:h.jsx(wue,{to:e.to,children:e.label})})]})]})},bR=(e,t,n="normal",r=0)=>{const a=e.scrollTop+t.getBoundingClientRect().top-e.getBoundingClientRect().top-e.clientTop-r;e.scrollTop=n==="reversed"?Math.min(0,a):Math.max(0,a)},K1=24,EQe=6,$7=()=>new Promise(e=>{window.requestAnimationFrame(()=>{e()})}),BK=async e=>{for(let t=0;t<EQe;t+=1){if(e())return;await $7()}},qQe=e=>{let t=null;return()=>(t!==null||(t=e().finally(()=>{t=null})),t)},ijt=e=>{const t=qQe(e.loadOlder),n=()=>BK(()=>e.reachable()||e.rowDistance()!==null);return{loadOne:t,loadThrough:async i=>{const a=e.hasHeadroom??(()=>!0);let o=0;for(;;){if(e.reachable())return"landed";const s=e.rowDistance();if(s!==null){if(i.maxRows!==void 0&&s>i.maxRows)return"over-budget";if(!a()&&o<i.maxPages&&(o+=1,await t())){await n();continue}return e.mount(s),await BK(()=>e.reachable()),e.reachable()?"landed":"exhausted"}if(o>=i.maxPages||(o+=1,!await t()))return"exhausted";await n()}}}},k0="data-jump-highlight",ajt=1400,ojt=12,sjt=1200,ljt=EQe,cjt=ljt+2,ujt=2,Ojt=30,HK=1,Fg=K1;let Eh=0;async function djt(e){const{isReachable:t,rowDistance:n,mount:r,loadOlder:i}=e,a=e.hasHeadroom??(()=>!0);return await ijt({reachable:t,rowDistance:n,mount:r,loadOlder:i,hasHeadroom:a}).loadThrough({maxPages:ojt,maxRows:sjt})==="landed"}async function fjt(e,t,n){if(!n()||!t.isConnected)return;Eh+=1;const r=Eh;bR(e,t,"reversed",Fg);const i=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," "]);let a=!1;const o=()=>{a=!0},s=l=>{i.has(l.key)&&(a=!0)};e.addEventListener("wheel",o,{passive:!0,once:!0}),e.addEventListener("pointerdown",o,{passive:!0,once:!0}),e.addEventListener("touchstart",o,{passive:!0,once:!0}),window.addEventListener("keydown",s);try{let l=0,c=!1;for(let u=0;u<cjt&&(await $7(),!(!n()||!t.isConnected||a||r!==Eh));u+=1){const O=t.getBoundingClientRect().top-e.getBoundingClientRect().top-e.clientTop-Fg;if(Math.abs(O)<=HK){if(l+=1,l>=ujt){c=!0;break}continue}l=0,bR(e,t,"reversed",Fg)}if(c&&!a&&r===Eh){const u=e,O=t,d=()=>{a=!0};u.addEventListener("wheel",d,{passive:!0,once:!0}),u.addEventListener("pointerdown",d,{passive:!0,once:!0}),u.addEventListener("touchstart",d,{passive:!0,once:!0}),window.addEventListener("keydown",s),(async()=>{try{for(let f=0;f<Ojt;f+=1){if(await $7(),!n()||a||r!==Eh||!u.isConnected||!O.isConnected)return;const p=O.getBoundingClientRect().top-u.getBoundingClientRect().top-u.clientTop-Fg;if(Math.abs(p)<=HK)continue;bR(u,O,"reversed",Fg);const m=u.ownerDocument?.defaultView;m!=null&&u.dispatchEvent(new m.Event("scroll"))}}finally{u.removeEventListener("wheel",d),u.removeEventListener("pointerdown",d),u.removeEventListener("touchstart",d),window.removeEventListener("keydown",s)}})()}}finally{e.removeEventListener("wheel",o),e.removeEventListener("pointerdown",o),e.removeEventListener("touchstart",o),window.removeEventListener("keydown",s)}if(n()&&!a&&r===Eh){const l=e.ownerDocument?.defaultView;l!=null&&e.dispatchEvent(new l.Event("scroll"))}}function jQe(e,t,n,r=()=>!0){return r()?new Promise(i=>{GEt(e,n,{isCurrent:r,onRevealed:a=>{if(!r()){i("missing");return}KK(a),fjt(t,a,r).then(()=>{r()&&a.isConnected&&!a.hasAttribute(k0)&&KK(a),i(r()?"landed":"missing")})},onMissing:()=>{i("missing")}})}):Promise.resolve("missing")}const wR=new WeakMap;function KK(e){const t=wR.get(e);t!==void 0&&window.clearTimeout(t);const n=e.hasAttribute(k0);e.removeAttribute(k0),n&&e.offsetHeight,e.setAttribute(k0,""),wR.set(e,window.setTimeout(()=>{wR.delete(e),e.removeAttribute(k0)},ajt))}const mO=120,Gw=400,hjt=.5,pjt=320,mjt=900,Iw=64,RP=2,SR=24,xR=3,gjt=4,yy=12,y7=yy,$jt=120,yjt=.35,JK=12,vjt=8,bjt=yy,wjt=.5,eJ=()=>({armed:!1,deliberate:!1,retained:!1,busy:!1,continuation:!1,clampLatched:!1,actFetchSpent:!1,travelledSinceLatch:!1,actTravelled:!1,pressDemand:!1,pageWidenOwed:!1,turnedAround:!1,lastInputAt:Number.NEGATIVE_INFINITY,failures:0,chainFetch:0,chainWiden:0,chainInvisible:0,actAsks:0,revealsThisAct:0}),CQe=e=>Math.min(mjt,Math.max(pjt,Math.round(e*hjt))),Sjt=(e,t)=>{if(t.direction==="down")return{...e,armed:!1,deliberate:!1,retained:!1,actFetchSpent:t.at-e.lastInputAt>=Gw?!1:e.actFetchSpent,actAsks:t.at-e.lastInputAt>=Gw?0:e.actAsks,revealsThisAct:t.at-e.lastInputAt>=Gw?0:e.revealsThisAct,continuation:!1,clampLatched:!1,travelledSinceLatch:!1,actTravelled:e.actTravelled||t.travelledPx>=Iw,pageWidenOwed:!1,turnedAround:e.busy,chainFetch:0,chainWiden:0,chainInvisible:0,lastInputAt:t.at};const n=t.at-e.lastInputAt>=Gw,r={...e,actFetchSpent:n?!1:e.actFetchSpent,actAsks:n?0:e.actAsks,revealsThisAct:n?0:e.revealsThisAct,travelledSinceLatch:n?!1:e.travelledSinceLatch,actTravelled:n?t.travelledPx>=Iw:e.actTravelled||t.travelledPx>=Iw,continuation:!1,turnedAround:!1,chainFetch:0,chainInvisible:0,chainWiden:0,lastInputAt:t.at};return t.deliberate?{...r,clampLatched:!1,failures:0,deliberate:!0,actFetchSpent:!1,actAsks:0,revealsThisAct:0,actTravelled:!1,pressDemand:!1,...e.busy?{retained:!0}:{armed:!0}}:t.atHardTop&&t.continuous&&e.clampLatched&&!n?t.travelledPx>=Iw&&!e.travelledSinceLatch?{...r,armed:!0,pressDemand:!1,clampLatched:!1,travelledSinceLatch:!0}:!e.armed&&e.clampLatched&&!e.actTravelled?{...e,armed:!0,pressDemand:!0,lastInputAt:t.at}:{...e,lastInputAt:t.at}:e.busy?{...r,retained:!0,pressDemand:!1}:{...r,armed:!0,pressDemand:!1}},Bg=(e,t,n)=>({action:t,state:{...e,armed:!1,deliberate:!1,busy:!0,continuation:!1,clampLatched:e.clampLatched||e.armed&&n.distanceFromTopPx<=RP,pageWidenOwed:e.pageWidenOwed&&t!=="widen",actFetchSpent:t==="fetch"?!0:e.actFetchSpent,chainWiden:t==="widen"?e.chainWiden+1:e.chainWiden,chainFetch:t==="fetch"?e.chainFetch+1:e.chainFetch,actAsks:t==="fetch"?e.actAsks+1:e.actAsks,revealsThisAct:e.revealsThisAct+1,chainInvisible:e.chainInvisible}}),xjt=(e,t,n)=>e.busy||e.pageWidenOwed?!0:!e.armed||!AQe(t).inZone?!1:t.distanceFromTopPx<=RP?!e.pressDemand||!e.clampLatched||e.actTravelled||e.actAsks>=y7?!1:n-e.lastInputAt>=mO:!0;function AQe(e,t=CQe(e.clientHeight)){return{inZone:e.distanceFromTopPx<=t}}const Qjt=(e,t,n)=>{if(e.busy)return{action:"none",state:e};const r=t.hiddenRows>0?"widen":t.hasMore?"fetch":"none";if(r==="none")return{action:"none",state:e.armed||e.continuation?{...e,armed:!1,deliberate:!1,continuation:!1}:e};if(t.followingTail&&t.scrollable)return e.armed?{action:"none",state:{...e,armed:!1}}:{action:"none",state:e};const i=CQe(t.clientHeight),{inZone:a}=AQe(t,i),o=n-e.lastInputAt>=mO||t.distanceFromTopPx<=RP,s=e.revealsThisAct<bjt;if(e.pageWidenOwed&&r==="widen"&&e.chainWiden<JK&&s)return o?Bg({...e,pageWidenOwed:!1,continuation:!1,armed:!1,retained:!1,deliberate:!1},r,t):{action:"none",state:e};if(e.armed){if(e.deliberate)return Bg(e,r,t);if(r==="fetch"&&e.failures>=xR)return{action:"none",state:{...e,armed:!1}};if(!o)return{action:"none",state:e};if(!a)return{action:"none",state:{...e,armed:!1}};if(r==="fetch"&&e.actFetchSpent){const l=n-e.lastInputAt>=mO;return l&&e.clampLatched&&!e.actTravelled&&e.pressDemand&&e.actAsks<y7?Bg(e,r,t):l?{action:"none",state:{...e,armed:!1}}:{action:"none",state:e}}return Bg(e,r,t)}if(e.continuation){const l=e.actAsks<y7,c=l&&e.chainInvisible>0&&e.chainInvisible<yy;return t.scrollable&&!(e.pageWidenOwed&&r==="widen")&&!c?{action:"none",state:{...e,continuation:!1,pageWidenOwed:!1}}:s&&(r==="widen"?e.chainWiden<JK:(c||l&&e.chainFetch<gjt)&&e.failures<xR)?Bg({...e,pageWidenOwed:!1,continuation:!1},r,t):{action:"none",state:{...e,continuation:!1,pageWidenOwed:!1}}}return{action:"none",state:e}},tJ=(e,{network:t=!0,hiddenRowsAfter:n=0,paintedDelta:r=null,growthPx:i=null,clientHeight:a=0,newRecords:o=null}={})=>{const s=r!==null&&r<vjt,l=r===null&&t&&i!==null&&i<Math.max($jt,yjt*a),c=s||t&&o===0||l;return{...e,busy:!1,failures:t?0:e.failures,armed:e.retained,pressDemand:e.retained&&e.pressDemand,deliberate:e.retained?e.deliberate:!1,retained:!1,turnedAround:!1,pageWidenOwed:t&&n>0,actFetchSpent:c?!1:e.actFetchSpent,chainInvisible:c?Math.min(e.chainInvisible+1,yy):0,continuation:t&&n>0||c&&e.chainInvisible+1<yy||!e.retained&&!e.turnedAround}},kjt=e=>({...e,busy:!1,pressDemand:!1,failures:e.failures+1,armed:!1,deliberate:!1,retained:!1,turnedAround:!1,continuation:!1,actFetchSpent:!1,pageWidenOwed:!1}),Pjt=e=>({...e,busy:!1,pressDemand:!1,armed:!1,deliberate:!1,retained:!1,turnedAround:!1,continuation:!1,actFetchSpent:!1,pageWidenOwed:!1}),_jt=(e,t,n,r)=>n===r?zQe(e,t):null,zQe=(e,t)=>{if(!e||!t||e.id!==t.id||e.extent===t.extent)return 0;const n=t.viewportOffset-e.viewportOffset;return Math.abs(n)<wjt?0:n};function UQe({path:e}){switch(Dz(e)){case"image":return h.jsx(yze,{"aria-hidden":"true",className:"size-3.5 shrink-0"});case"spreadsheet":return h.jsx(wze,{"aria-hidden":"true",className:"size-3.5 shrink-0"});case"markdown":case"text":case"document":return h.jsx(pk,{"aria-hidden":"true",className:"size-3.5 shrink-0"});default:return h.jsx(dv,{"aria-hidden":"true",className:"size-3.5 shrink-0"})}}function Tjt(e,t){try{return SU(e,t)}catch{return!1}}function DU(e,t,n){const r=$.useCallback(async o=>{try{const[s]=await window.api.probeFiles([e],t??void 0);if(!s?.resolved.startsWith("/"))throw new Error("File path has no session working directory");await o(s.resolved)}catch{mi(J("ui.chat.highlights.file_resolution_failed"))}},[e,t]),i=Tjt(n??null,e),a=$.useCallback(()=>{r(async o=>{i&&n&&await n.openInCanvas(o)||await AO(o)})},[r,i,n]);return{canOpenInCanvas:i,press:a,withTarget:r}}const WQe=$.memo(function({actionPath:t,label:n,cwd:r,pane:i,overlay:a=!1}){const{canOpenInCanvas:o,withTarget:s}=DU(t,r,i),[l,c]=$.useState(!1),u=`Actions for ${n||"this file"}`;return h.jsxs(bA,{children:[h.jsx(Yt,{content:"File actions",children:h.jsx(wA,{asChild:!0,children:a?h.jsx(Xe,{variant:"ghost",size:"icon-sm",className:"bg-accent-wash","aria-label":u,children:h.jsx(vj,{"aria-hidden":"true"})}):h.jsx("button",{type:"button",className:"flex size-6 shrink-0 items-center justify-center text-ink-dim opacity-0 group-hover:opacity-100 focus-visible:opacity-100","aria-label":u,children:h.jsx(vj,{"aria-hidden":"true",className:"size-3.5"})})})}),h.jsxs(SA,{align:"end",className:"min-w-45",children:[o&&h.jsxs(jl,{onSelect:()=>{s(O=>i?.openInCanvas(O))},children:[h.jsx(Xue,{"aria-hidden":"true"}),h.jsx("span",{children:"Open in canvas"})]}),h.jsxs(jl,{onSelect:()=>{s(AO)},children:[h.jsx(dv,{"aria-hidden":"true"}),h.jsx("span",{children:"Open in default app"})]}),h.jsxs(jl,{onSelect:()=>{s(xU)},children:[h.jsx(Rp,{"aria-hidden":"true"}),h.jsx("span",{children:"Reveal in Finder"})]}),h.jsxs(jl,{onSelect:()=>{navigator.clipboard.writeText(t).then(()=>c(!0)).catch(()=>mi("Failed to copy file path"))},children:[h.jsx(Que,{"aria-hidden":"true"}),h.jsx("span",{children:l?"Copied":"Copy file path"})]})]})]})}),Rjt="lo-supplement",Xjt="s";function Ejt(e,t){return`${Rjt}://${Xjt}/${e}/${t}`}const qjt="[supplement] frame torn down after a second load (hostile navigation or a blocked attempt)";function jjt(e){let t=e.parentElement;for(;t;){const n=window.getComputedStyle(t);if((n.overflowY==="auto"||n.overflowY==="scroll")&&t.scrollHeight>t.clientHeight)return t;t=t.parentElement}return null}function Cjt({component:e,sessionId:t,documentHtml:n,documentFailed:r=!1,onRetry:i,onHeightChange:a,className:o}){const s=Ble(e),[l,c]=$.useState(s),[u,O]=$.useState(!1),[d,f]=$.useState(!0),p=$.useRef(null),m=$.useRef(null),g=$.useRef(""),y=$.useRef(!1),v=$.useRef(""),S=$.useRef(()=>{}),Q=$.useRef(0),b=$.useRef(s),w=$.useRef(null),x=$.useRef(()=>{}),k=$.useRef(a),T=$.useRef(()=>{}),_=$.useCallback(E=>{y.current||(y.current=!0,v.current=E,O(!0))},[]);return $.useEffect(()=>{if(n===null)return;const E=m.current;if(!E)return;g.current=bqe();const R=window.api?.desktop?.armSupplementFrame,j=t!==null&&S$(e.attachment);let C;if(R===void 0)C=Qqe(n);else if(j)C=Ejt(t,e.attachment);else{_("no-address");return}let W=!1,G=!1,N=null,Z=null,F=null;const z={resize:null,error:!1},M=window.setTimeout(()=>{W||_("no-ready")},dY),te=ne=>{E.contentWindow?.postMessage(ne,"*")},U=()=>{y.current||Z===null&&(te({lo:"supplement-host",t:"ping"}),Z=window.setTimeout(()=>{Z=null,_("no-pong")},dY))};S.current=()=>{G||y.current||(G=!0,U(),N=window.setInterval(U,yqe))};const H=ne=>{const le=p.current;if(le){const Oe=jjt(le);if(Oe&&le.getBoundingClientRect().top<Oe.getBoundingClientRect().top){w.current=ne,k.current?.(ne);return}}w.current=null,k.current?.(ne),ne!==b.current&&(b.current=ne,c(ne))},D=()=>{F===null&&(F=window.requestAnimationFrame(()=>{F=null;const{resize:ne,error:le}=z;if(z.resize=null,z.error=!1,le){_("frame-error");return}ne!==null&&H(ne)}))},V=ne=>{if(y.current||ne.source!==E.contentWindow||ne.origin!=="null")return;const le=vqe(ne.data,g.current);if(le){if(le.t==="ready"){W||(W=!0,window.clearTimeout(M));return}if(le.t==="pong"){Z!==null&&(window.clearTimeout(Z),Z=null);return}if(le.t==="resize"){z.resize=Hle(le.h),f(!1),D();return}z.error=!0,D()}},se=()=>{const ne=w.current;ne!==null&&H(ne)};window.addEventListener("message",V),window.addEventListener("scroll",se,!0);let B=!1;return(async()=>{if(R)try{await R(C)}catch{}B||(E.src=C)})(),()=>{B=!0,window.clearTimeout(M),N!==null&&window.clearInterval(N),Z!==null&&window.clearTimeout(Z),F!==null&&window.cancelAnimationFrame(F),window.removeEventListener("message",V),window.removeEventListener("scroll",se,!0),S.current=()=>{}}},[n,_,t,e.attachment]),k.current=a,T.current=E=>{y.current||Q.current!==1||m.current?.contentWindow?.postMessage({lo:"supplement-host",t:"theme",mode:E.mode,vars:E.vars,nonce:g.current},"*")},$.useEffect(()=>xqe(E=>T.current(E)),[]),x.current=()=>{const E=Q.current+1;if(Q.current=E,E>1){console.debug(qjt),_("second-load");return}T.current(Fle()),S.current()},u||r?h.jsxs("div",{className:"text-ink-dim text-meta","data-supplement-frame-fallback":r?"document":v.current,children:["Couldn't render this graphic",i&&h.jsxs(h.Fragment,{children:[h.jsx("span",{"aria-hidden":"true",className:"px-1 text-ink-dim",children:"·"}),h.jsx("button",{type:"button",className:"text-ink-dim","data-supplement-frame-retry":"",onClick:()=>i(),children:"Retry"})]})]}):h.jsxs("div",{className:o,"data-supplement-frame-box":"",children:[h.jsxs("div",{ref:p,"data-supplement-frame":"",className:"relative overflow-hidden",style:{height:l,width:"100%"},children:[n!==null&&h.jsx("iframe",{ref:m,title:e.title,sandbox:"allow-scripts",onLoad:()=>x.current(),className:"block h-full w-full border-0"}),d&&h.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 animate-shimmer bg-elevated/40 bg-gradient-to-r from-transparent via-elevated/60 to-transparent bg-[length:200%_100%] bg-[position:-200%_50%] bg-no-repeat"})]}),h.jsxs("span",{className:"block truncate text-ink-muted text-meta",title:`Source: ${e.source}`,"data-supplement-source":"",children:["Source: ",Ld(e.source)]})]})}function Ajt(e="200px"){const[t,n]=$.useState(()=>typeof IntersectionObserver>"u"),[r,i]=$.useState(null),a=$.useCallback(o=>i(o),[]);return $.useEffect(()=>{if(r===null||t||typeof IntersectionObserver>"u")return;const o=new IntersectionObserver(s=>{s.some(l=>l.isIntersecting)&&(n(!0),o.disconnect())},{rootMargin:e});return o.observe(r),()=>o.disconnect()},[r,e,t]),[a,t]}const zjt=150,v7=16*1024*1024,Js=new Map,$p=[];let P0=0,NQe=0,YQe=0,b7=0;const HOn=()=>({entries:Js.size,queued:$p.length,active:P0,reads:NQe,decodes:YQe,peakActive:b7}),Ujt=e=>e.artifact?`finder:${e.artifact.sessionId}:${e.artifact.childId??"self"}:${e.artifact.digest}`:`finder:${e.path}:${e.lastAgentModified??0}:${e.sizeBytes??0}`;async function Wjt(e){if(e.artifact)return Exe({sessionId:e.artifact.sessionId,childId:e.artifact.childId??null},e.artifact.digest);const t=await window.api.readFileBytes(e.path,v7);if(!t.success)throw new Error(t.error??"Could not be read");return new Blob([t.data],{type:Mz(e.path)})}function GQe(){for(const[e,t]of Js){if(Js.size<=zjt)return;t.listeners.size||t.started||(t.state.url&&$v(t.state.url),Js.delete(e))}}function nJ(e,t){e.state=t;for(const n of e.listeners)n(t)}function IQe(){for(;P0<4&&$p.length;){const e=$p.shift();if(!e||!e.listeners.size){e&&Js.delete(e.key);continue}e.started=!0,P0++,NQe++,b7=Math.max(b7,P0),(async()=>{try{if((e.document.sizeBytes??0)>v7)throw new Error("Too large to preview");const t=await Wjt(e.document);if(t.size>v7)throw new Error("Too large to preview");const n=e.document.artifact?.width,r=e.document.artifact?.height,i=n&&r?Math.min(1,640/Math.max(n,r)):null,a=i&&n&&r?{resizeWidth:Math.max(1,Math.round(n*i)),resizeHeight:Math.max(1,Math.round(r*i)),resizeQuality:"high"}:{resizeWidth:640,resizeQuality:"high"};let o,s=null;if(t.type==="image/svg+xml"||e.document.path.toLowerCase().endsWith(".svg")){s=URL.createObjectURL(t);const l=new Image;l.src=s;try{await l.decode()}catch(u){throw URL.revokeObjectURL(s),u}const c=Math.min(1,640/Math.max(l.naturalWidth,l.naturalHeight));l.width=Math.max(1,Math.round(l.naturalWidth*c)),l.height=Math.max(1,Math.round(l.naturalHeight*c)),o=l}else o=await createImageBitmap(t,a);YQe++;try{const l=Math.min(1,640/Math.max(o.width,o.height)),c=new OffscreenCanvas(Math.max(1,Math.round(o.width*l)),Math.max(1,Math.round(o.height*l))),u=c.getContext("2d");if(!u)throw new Error("Can't preview this image");u.drawImage(o,0,0,c.width,c.height);const O=await c.convertToBlob({type:"image/png"});nJ(e,{state:"ready",url:Lz(await O.arrayBuffer(),"image/png")})}finally{"close"in o&&o.close(),s&&URL.revokeObjectURL(s)}}catch(t){nJ(e,{state:"unavailable",reason:t instanceof Error?t.message:"Could not be read"})}finally{e.started=!1,P0--,GQe(),IQe()}})()}}function Njt(e,t){const n=Ujt(e),[r,i]=$.useState({state:"loading"});return $.useEffect(()=>{if(!t)return;let a=Js.get(n);a?.state.state==="unavailable"&&!a.listeners.size&&(Js.delete(n),a=void 0),a?(Js.delete(n),Js.set(n,a)):(a={key:n,document:e,state:{state:"loading"},listeners:new Set,started:!1},Js.set(n,a),$p.push(a)),a.listeners.add(i),i(a.state),IQe();const o=a;return()=>{if(o.listeners.delete(i),!o.started&&o.state.state==="loading"&&!o.listeners.size){const s=$p.indexOf(o);s>=0&&$p.splice(s,1),Js.delete(n)}GQe()}},[n,t,e]),r}const Yjt="pointer-events-none absolute top-1 right-1 flex opacity-0 transition-opacity duration-fast ease-out-quart group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100 has-[[aria-expanded=true]]:pointer-events-auto has-[[aria-expanded=true]]:opacity-100",Gjt=$.memo(function({file:t,cwd:n,pane:r}){const{name:i,path:a}=Lle(t),o=i||a||t.path,[s,l]=Ajt(),[c,u]=$.useState(null),[O,d]=$.useState(!1);$.useEffect(()=>{let S=!1;const Q=window.api?.probeFiles;if(typeof Q!="function"){u(null),d(!0);return}return u(null),d(!1),(async()=>{try{const[b]=await Q([t.path],n??void 0),w=b?.resolved??"";S||u(w.startsWith("/")?w:null)}catch{S||u(null)}finally{S||d(!0)}})(),()=>{S=!0}},[t.path,n]);const f=$.useMemo(()=>({id:`supplement:${t.path}`,title:o,path:c??t.path,content:"",type:"image",sizeBytes:t.sizeBytes,lastAgentModified:t.mtime?t.mtime*1e3:void 0}),[t.path,o,t.sizeBytes,t.mtime,c]),p=Njt(f,l&&c!==null),{press:m}=DU(t.path,n,r),g=p.state==="ready"&&typeof p.url=="string",v=!(!O||c!==null&&p.state==="loading")&&(c===null||p.state==="unavailable");return h.jsx("li",{className:"flex leading-none","data-supplement-image-tile":"",children:h.jsxs("div",{className:"group relative",ref:s,children:[h.jsx("button",{type:"button",className:"group/tile block cursor-pointer rounded-sm","aria-label":`Open ${o}`,title:t.path,onClick:()=>void m(),children:g?h.jsx(zO,{boundary:"control",className:"h-[78px] w-[117px]",children:h.jsx("img",{alt:"",className:"h-[76px] w-[115px] object-contain",src:p.url})}):v?h.jsx("span",{className:"flex h-[78px] w-[117px] items-center justify-center rounded-sm border border-control bg-sunken text-ink-dim","data-supplement-image-fallback":"",children:h.jsx(UQe,{path:t.path})}):h.jsx(zO,{boundary:"control",className:"h-[78px] w-[117px]"})}),h.jsx("div",{className:Yjt,children:h.jsx(WQe,{overlay:!0,actionPath:t.path,label:o,cwd:n,pane:r})})]})})}),Ijt=({files:e,cwd:t,pane:n,className:r})=>h.jsx("ul",{role:"list","aria-label":e.length===1?"1 image from this run":`${e.length} images from this run`,"data-supplement-images":"",className:q("grid grid-cols-[repeat(4,max-content)] gap-2",r),children:e.map(i=>h.jsx(Gjt,{file:i,cwd:t,pane:n},i.path))}),Zjt=2*1024*1024,tp=new Map,QR=new Map,Djt=64,rJ={html:null,failed:!1};async function Mjt(e,t){const n=`${e}:${t}`,r=QR.get(n);if(r)return r;const i=(async()=>{try{const a=await su({op:"sessions.supplementDocument",sessionId:e,digest:t},null);if(a.kind!=="json")return null;const o=a.body,s=o&&typeof o.html=="string"?o.html:null;if(s===null||s.length>Zjt)return null;for(tp.set(n,s);tp.size>Djt;){const l=tp.keys().next().value;if(l===void 0)break;tp.delete(l)}return s}catch{return null}finally{QR.delete(n)}})();return QR.set(n,i),i}function Vjt(e,t,n){const[r,i]=$.useState(()=>{if(!e||!S$(t))return rJ;const a=tp.get(`${e}:${t}`);return a!==void 0?{html:a,failed:!1}:rJ});return $.useEffect(()=>{if(!n||!e||!S$(t))return;const a=tp.get(`${e}:${t}`);if(a!==void 0){i({html:a,failed:!1});return}let o=!1;return Mjt(e,t).then(s=>{o||i(s!==null?{html:s,failed:!1}:{html:null,failed:!0})}),()=>{o=!0}},[n,e,t]),r}const iJ=$.memo(function({actionPath:t,cwd:n,label:r,suffix:i,size:a,pane:o}){const{press:s}=DU(t,n,o);return h.jsxs("div",{className:"group flex w-full items-center gap-2 text-meta",children:[h.jsx(UQe,{path:t}),h.jsxs("button",{type:"button",className:"min-w-0 flex-1 truncate text-left text-ink hover:text-ink-dim","data-supplement-file":"",title:t,onClick:()=>{s()},children:[Ld(r),i&&i!==r&&h.jsx("span",{className:"ml-2 text-ink-muted",children:Ld(i)})]}),a&&h.jsx("span",{className:"shrink-0 text-ink-dim",children:a}),h.jsx(WQe,{actionPath:t,label:r,cwd:n,pane:o})]})}),Ljt=$.memo(function({sound:t,sessionId:n}){const r=$.useMemo(()=>n?{sessionId:n,childId:null}:null,[n]),i=Dv({data:null,attachment:t.attachment,mimeType:t.mime},r),a=uQe(t.attachment,r),o=t.title||"Generated sound";return h.jsxs("div",{className:"flex min-w-0 flex-col gap-0.5",children:[t.title&&h.jsx("span",{"data-supplement-sound-title":"",title:t.title,className:"truncate text-meta text-ink-muted",children:Ld(t.title)}),i.state==="missing"?h.jsx(_f,{name:o,detail:aQe}):i.state==="resolving"?h.jsx("div",{className:"h-11","aria-hidden":!0}):h.jsx(cQe,{variant:"compact",ownerId:`sound:${t.attachment}`,src:i.url,label:o,peaks:a,durationHint:t.durationS})]})}),aJ=$.memo(function({component:t,sessionId:n,onRetry:r,onHeight:i}){const a=$.useRef(null),[o,s]=$.useState(!1);$.useEffect(()=>{const u=a.current;if(u===null)return;if(typeof IntersectionObserver>"u"){s(!0);return}const O=new IntersectionObserver(d=>{for(const f of d)f.isIntersecting&&s(!0)},{rootMargin:"200px 0px"});return O.observe(u),()=>O.disconnect()},[]);const l=Vjt(n,t.attachment,o),c=$.useCallback(u=>{i?.(t.attachment,u)},[i,t.attachment]);return h.jsx("div",{ref:a,"data-supplement-slot":"",children:h.jsx(Cjt,{component:t,sessionId:n,documentHtml:l.html,documentFailed:l.failed,onRetry:r,onHeightChange:i?c:void 0})})}),Fjt=$.memo(function({record:t,sessionId:n,cwd:r,condensed:i=!1}){const a=SP(),[o,s]=$.useState(!1),[l,c]=$.useState(!1),[u,O]=$.useState(!1),[d,f]=$.useState(!1),[p,m]=$.useState(""),[g,y]=$.useState(!1),[v,S]=$.useState(()=>new Map),[Q,b]=$.useState(0),w=eqe(t,t.live),x=cqe(t.cause),k=t.files,T=t.filesMore,_=t.components,E=t.sounds??[],R=k.length+T,j=async se=>{if(n){y(!0);try{await Re({...se,sessionId:n,job:t.job,anchor:t.anchor})}catch(B){mi(pv("Highlights could not be updated.",B))}finally{y(!1)}}},C=()=>{j({op:"supplements.cancel"})},W=()=>{j({op:"supplements.restart"})},G=()=>{const se=p.trim();se&&(f(!1),m(""),j({op:"supplements.steer",text:se}))},N=$.useCallback((se,B)=>{S(K=>{if(K.get(se)===B)return K;const ne=new Map(K);return ne.set(se,B),ne})},[]),Z=_qe(typeof window>"u"?900:window.innerHeight),{visible:F}=Tqe(_,Z,v);$.useEffect(()=>{b(se=>Math.max(se,F.length))},[F.length]);const z=Math.min(_.length,Math.max(Q,F.length)),M=_.slice(0,z),te=_.slice(z),U=()=>w==="preparing"||w==="files_preparing"||w==="cancelled_retry"||w==="files_cancelled_retry"||w==="failed_retry"||w==="files_failed_retry"?h.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-meta","data-supplement-line":"",children:[(w==="preparing"||w==="files_preparing")&&h.jsxs(h.Fragment,{children:[h.jsx("span",{"aria-hidden":"true",className:"relative inline-block size-3 overflow-hidden rounded-full bg-sunken",children:h.jsx("span",{className:"absolute inset-0 animate-shimmer bg-gradient-to-r from-transparent via-elevated to-transparent bg-[length:200%_100%] bg-[position:-200%_50%] bg-no-repeat"})}),h.jsx("span",{className:"text-ink-muted",children:tqe})]}),(w==="cancelled_retry"||w==="files_cancelled_retry")&&h.jsx("span",{className:"text-ink-muted",children:nqe}),(w==="failed_retry"||w==="files_failed_retry")&&h.jsxs("span",{className:"text-ink-muted",children:[rqe,x?` — ${x}`:""]}),(w==="preparing"||w==="files_preparing")&&n&&h.jsxs(h.Fragment,{children:[h.jsx("span",{"aria-hidden":"true",className:"text-ink-dim",children:"·"}),!d&&h.jsx("button",{type:"button",className:"text-ink-dim","data-supplement-adjust":"",onClick:()=>f(!0),children:iqe}),h.jsx("button",{type:"button",className:"text-ink-dim disabled:text-ink-dim/60","data-supplement-cancel":"",disabled:g||t.state==="cancelling",onClick:C,children:aqe})]}),(w==="cancelled_retry"||w==="files_cancelled_retry"||w==="failed_retry"||w==="files_failed_retry")&&n&&h.jsxs(h.Fragment,{children:[h.jsx("span",{"aria-hidden":"true",className:"text-ink-dim",children:"·"}),h.jsx("button",{type:"button",className:"text-ink-dim","data-supplement-retry":"",onClick:W,children:oqe})]})]}):null,H=d?h.jsxs("div",{className:"flex items-center gap-2 text-meta","data-supplement-adjust-form":"",children:[h.jsx("input",{autoFocus:!0,className:"min-w-0 flex-1 rounded-sm border border-control bg-canvas px-1.5 py-0.5 text-ink text-meta",maxLength:DEe,placeholder:"Adjust the graphic…",value:p,onChange:se=>m(se.target.value),onKeyDown:se=>{se.key==="Enter"&&G(),se.key==="Escape"&&(f(!1),m(""))}}),h.jsx("button",{type:"button",className:"text-ink-dim disabled:text-ink-dim/60",disabled:g||!p.trim(),onClick:G,children:"Send"})]}):null;if(w==="nothing")return null;let D=null;if(k.length>0||T>0){const se=[],B=[];for(const ne of k)Dz(ne.path)==="image"?se.push(ne):B.push(ne);const K=R<=2&&_.length===0&&T===0;D=h.jsxs("div",{className:"flex flex-col gap-1","data-supplement-files-summary":K?"":void 0,"data-supplement-files":K?void 0:"",children:[se.length>0&&h.jsx(Ijt,{files:se,cwd:r,pane:a,className:B.length>0||T>0?"mb-1":void 0}),B.map(ne=>{const{name:le,path:Oe,size:Qe}=Lle(ne);return h.jsx(iJ,{actionPath:ne.path,cwd:r,label:le||Oe,suffix:Oe,size:Qe,pane:a},`${ne.path}:${ne.name}`)}),T>0&&h.jsx($a,{chevronClassName:"text-ink-dim",open:o,onOpenChange:s,rowClassName:"min-h-0 py-0",summary:h.jsx("span",{"data-supplement-more":"",children:o?"Show fewer":uqe(T)}),children:t.more.slice(0,20).map(ne=>h.jsx(iJ,{actionPath:ne,cwd:r,label:ne,suffix:"",size:"",pane:a},ne))})]})}const V=E.length>0?h.jsx("div",{className:"flex flex-col gap-1","data-supplement-sounds":"",children:E.map(se=>h.jsx(Ljt,{sound:se,sessionId:n},se.attachment))}):null;return h.jsxs("div",{className:"flex flex-col gap-2","data-supplement-record":t.anchor,"data-supplement-condensed":i?"":void 0,children:[D,V,U(),i&&w==="block"&&D===null&&_.length>0&&h.jsx("div",{className:"text-ink-muted text-meta",children:dqe(_.length,"graphic")}),!i&&t.detail?.includes("prepared:unsupported")&&h.jsx("p",{className:"text-meta text-ink-muted","data-supplement-refusal":"",children:"Inline preview unavailable. This HTML needs unsupported resources or document content. Open the file to view it."}),!i&&(w==="failed_retry"||w==="files_failed_retry")&&h.jsxs("div",{className:"flex flex-col gap-1 text-meta text-ink-muted","data-supplement-diagnostic":"",children:[h.jsx("p",{children:jqe(t)}),((t.attempts?.length??0)>0||(t.detail?.length??0)>0)&&h.jsx($a,{open:l,onOpenChange:c,rowClassName:"min-h-6 py-0",chevronClassName:"text-ink-dim",summary:"Details",children:h.jsxs("div",{className:"max-h-[min(320px,40vh)] overflow-auto break-words font-mono text-ink-dim",children:[t.model&&h.jsxs("p",{children:["Model: ",t.model]}),h.jsxs("p",{children:["Attempts: ",t.attempts?.length??0]}),t.detail?.map(se=>h.jsx("p",{children:qqe(se)},se))]})})]}),(w==="preparing"||w==="files_preparing")&&H,!i&&w==="block"&&_.length>0&&h.jsxs("div",{className:"flex flex-col gap-2","data-supplement-components":"",children:[M.map(se=>h.jsx(aJ,{component:se,sessionId:n,onRetry:n?W:void 0,onHeight:N},se.attachment)),te.length>0&&h.jsx($a,{chevronClassName:"text-ink-dim",open:u,onOpenChange:O,rowClassName:"min-h-0 py-0",summary:h.jsx("span",{"data-supplement-show-all":"",children:u?"Show fewer":fqe(te.length)}),children:te.map(se=>h.jsx(aJ,{component:se,sessionId:n,onRetry:n?W:void 0,onHeight:N},se.attachment))})]})]})});function Bjt(e){return e.shiftKey||e.altKey||!(e.metaKey||e.ctrlKey)?!1:e.key.toLowerCase()==="f"}const Hjt=e=>e?"⌘F":"Ctrl+F";function Kjt(e){switch(e){case"ready":case"building":case"unsupported":case"error":return e;default:return"error"}}function Jjt(e,t,n){return n<=0?-1:(((e<0||e>=n?t>0?-1:0:e)+t)%n+n)%n}function e3t(e,t){return t>=0&&t<e.length?e[t]:null}function t3t(e,t){const n=[];let r=0;for(const[i,a]of t){const o=Math.max(r,Math.min(e.length,i)),s=Math.max(o,Math.min(e.length,a));s<=o||(o>r&&n.push({text:e.slice(r,o),matched:!1}),n.push({text:e.slice(o,s),matched:!0}),r=s)}return r<e.length&&n.push({text:e.slice(r),matched:!1}),n}const n3t={user:"You",agent:"Agent"},r3t="related match",oJ="Search this conversation",i3t="Search results",a3t="Close search";function o3t(e){const t=e.filter(r=>r.tier==="exact").length,n=e.length-t;return n===0?e.length===1?"1 match":`${e.length} matches`:t===0?n===1?"1 related match":`${n} related matches`:`${t} exact · ${n} related`}const s3t="No messages match this search.",l3t="Still indexing this conversation.",c3t="Results appear as the index catches up.",u3t="Newer messages may be missing while the index catches up.",O3t="This conversation lives on another device, so it cannot be searched here.",d3t="This conversation could not be searched.",f3t="Try again",h3t="Check again",p3t="Could not reach that message. It is further back than the loaded history — scroll up in the transcript to load more.",m3t="Updating — the list below is the previous search's.",g3t="Going to that message…";function $3t(e){return e===1?"(the first match shown)":`(first ${e} shown)`}function y3t(e){return e.state==="building"}async function v3t(e,t){if(e===null)return"not-mounted";const n=e.querySelector("[data-lo-transcript-content]")??e;return await jQe(n,e,t)==="landed"?"revealed":"not-mounted"}async function b3t(e){const t=e.query.trim().slice(0,rle);if(t.length===0)return{query:"",state:"ready",partial:!1,hits:[],truncated:!1};const n=Math.min(Math.max(e.limit??URe,1),WRe);return Re({op:"sessions.find",sessionId:e.sessionId,q:t,limit:n})}const w3t=200,S3t=1500;function x3t({sessionId:e,enabled:t}){const[n,r]=$.useState(""),[i,a]=$.useState("idle"),[o,s]=$.useState([]),[l,c]=$.useState(!1),[u,O]=$.useState(!1),[d,f]=$.useState(-1),p=$.useRef(0),m=$.useRef(0),g=$.useRef(0),y=$.useRef(""),v=$.useRef(null),S=$.useRef(null),Q=$.useRef(new Set),b=$.useRef(e);b.current=e;const w=$.useCallback(()=>{S.current!==null&&(clearTimeout(S.current),S.current=null)},[]),x=$.useCallback((C,W)=>{Q.current.has(C)||(Q.current.add(C),console.warn(C,W))},[]),k=$.useCallback(()=>{p.current+=1,w(),v.current=null,g.current=0,a("idle"),s(C=>C.length===0?C:[]),c(!1),O(!1),f(-1)},[w]),T=$.useRef(()=>{}),_=$.useCallback((C,W)=>{const G=Kjt(W.state);a(G);const N=G==="ready"||G==="building",Z=N?W.hits:[];if(g.current=Z.length,s(Z),c(N&&W.truncated),O(G==="building"&&W.partial),f(Z.length>0?0:-1),G==="building"&&y3t(W)){if(v.current!==C){v.current=C;const F=p.current;S.current=setTimeout(()=>{S.current=null,p.current===F&&T.current(C,"follow-up")},S3t)}}else w()},[w]),E=$.useCallback((C,W)=>{const G=b.current;if(!G)return;const N=p.current,Z=++m.current;W==="fresh"&&(w(),v.current=null,a("loading")),b3t({sessionId:G,query:C}).then(F=>{Z!==m.current||p.current!==N||_(C,F)}).catch(F=>{Z!==m.current||p.current!==N||(x("thread search could not be answered:",F),w(),v.current=null,g.current=0,s([]),c(!1),O(!1),f(-1),a("error"))})},[_,w,x]);T.current=E,$.useEffect(()=>{const C=`${t?"1":"0"}:${e??""}`;if(y.current!==C&&(y.current=C,Q.current=new Set,k(),r(Z=>Z===""?Z:""),!t||!e))return;if(!t||!e){k();return}const W=n.trim();if(W.length===0){k();return}const G=p.current,N=setTimeout(()=>{p.current===G&&T.current(W,"fresh")},w3t);return()=>clearTimeout(N)},[n,t,e,k]),$.useEffect(()=>()=>w(),[w]);const R=$.useCallback(C=>{f(W=>Jjt(W,C,g.current))},[]),j=$.useCallback(()=>{const C=n.trim();!t||!e||C.length===0||T.current(C,"fresh")},[t,e,n]);return{query:n,setQuery:r,state:i,hits:o,truncated:l,partial:u,cursor:d,moveCursor:R,activeHit:e3t(o,d),refresh:j}}const Q3t=q("bg-accent-wash","before:absolute before:inset-y-0 before:left-0 before:w-0.5 before:bg-accent"),k3t="bg-accent-wash font-medium text-ink underline decoration-accent decoration-2 underline-offset-2",P3t=()=>navigator.platform.toUpperCase().indexOf("MAC")>=0,_3t=({hit:e,active:t,optionId:n,onNavigate:r})=>{const i=t3t(e.snippet,e.ranges);return h.jsxs("li",{id:n,role:"option","aria-selected":t,onMouseDown:a=>a.preventDefault(),onClick:()=>r(e),className:q("relative flex cursor-pointer flex-col gap-0.5 px-3 py-2",t?Q3t:"hover:bg-accent-wash"),children:[h.jsxs("span",{className:"flex items-center gap-1.5 text-ink-muted text-meta",children:[h.jsx("span",{children:n3t[e.role]}),e.tier==="soft"&&h.jsxs(h.Fragment,{children:[h.jsx("span",{"aria-hidden":"true",children:"·"}),h.jsx("span",{className:"text-ink-dim",children:r3t})]})]}),h.jsx("span",{className:"line-clamp-2 text-body-sm text-ink",children:i.map((a,o)=>a.matched?h.jsx("mark",{className:k3t,children:a.text},o):h.jsx("span",{children:a.text},o))})]})},T3t=({query:e,onQueryChange:t,state:n,hits:r,cursor:i,truncated:a,partial:o,onMoveCursor:s,onNavigate:l,onRetry:c,onClose:u,isMac:O,jumping:d=!1})=>{const f=$.useId(),p=`${f}-list`,m=$.useCallback(b=>`${f}-opt-${b}`,[f]),g=$.useRef(null),y=i>=0&&i<r.length?r[i]:null,v=r.length>0,S=n==="error"||n==="building";$.useEffect(()=>{g.current?.focus(),g.current?.select()},[]),$.useEffect(()=>{i<0||document.getElementById(m(i))?.scrollIntoView({block:"nearest"})},[i,m]);const Q=b=>{if(b.key==="ArrowDown"){b.preventDefault(),s(1);return}if(b.key==="ArrowUp"){b.preventDefault(),s(-1);return}if(b.key==="Enter"){b.preventDefault(),y!==null?l(y):S&&c();return}};return h.jsxs("div",{"data-lo-thread-search":"",role:"presentation",onKeyDown:b=>{b.defaultPrevented||b.key==="Escape"&&(b.preventDefault(),u())},className:"pointer-events-auto w-[26rem] max-w-full rounded-md border border-hairline bg-elevated text-body-sm text-ink shadow-overlay",children:[h.jsx("div",{className:"p-2",children:h.jsxs("div",{className:q("flex items-center gap-2 rounded-sm border border-control bg-surface px-2","transition-colors duration-fast ease-out-quart","has-[:focus-visible]:outline-solid has-[:focus-visible]:outline-2","has-[:focus-visible]:outline-accent has-[:focus-visible]:outline-offset-2"),children:[h.jsx(fv,{"aria-hidden":"true",className:"size-3.5 shrink-0 text-ink-dim"}),h.jsx("input",{ref:g,type:"text",value:e,onChange:b=>t(b.target.value),onKeyDown:Q,maxLength:rle,placeholder:oJ,"aria-label":oJ,role:"combobox","aria-expanded":v,"aria-controls":v?p:void 0,"aria-activedescendant":y!==null?m(i):void 0,"aria-autocomplete":"list",autoComplete:"off",spellCheck:!1,className:"h-8 min-w-0 flex-1 border-0 bg-transparent text-body-sm text-ink outline-none placeholder:text-ink-dim"}),h.jsx(Xe,{type:"button",variant:"ghost",size:"icon-sm","aria-label":a3t,onClick:u,children:h.jsx(ea,{"aria-hidden":"true"})})]})}),h.jsxs("div",{className:"flex items-start gap-2 px-3 pb-2",children:[h.jsxs("p",{className:"min-w-0 flex-1 text-ink-muted text-meta",children:[n==="loading"&&(v?m3t:"Searching…"),n==="ready"&&(r.length>0?o3t(r):s3t),n==="building"&&(o?u3t:l3t),n==="unsupported"&&O3t,n==="error"&&d3t,n==="ready"&&a&&v&&h.jsxs("span",{className:"text-ink-dim",children:[" ",$3t(r.length)]}),n==="building"&&!o&&h.jsxs("span",{className:"text-ink-dim",children:[" ",c3t]})]}),S&&h.jsx(Xe,{type:"button",variant:"ghost",size:"sm",onClick:c,className:"shrink-0",children:n==="building"?h3t:f3t})]}),v&&h.jsx("ul",{id:p,role:"listbox","aria-label":i3t,"aria-busy":n==="loading",className:q("max-h-80 overflow-y-auto border-t border-hairline py-1",n==="loading"&&"opacity-60"),children:r.map((b,w)=>h.jsx(_3t,{hit:b,active:w===i,optionId:m(w),onNavigate:l},b.id))}),d&&h.jsx("output",{className:"block border-t border-hairline px-3 py-1.5 text-ink-muted text-meta",children:g3t}),h.jsxs("div",{className:"flex items-center gap-3 border-t border-hairline px-3 py-1.5",children:[h.jsxs("span",{className:"flex items-center gap-1 text-ink-dim text-meta",children:[h.jsx(Ad,{shortcut:"↑"}),h.jsx(Ad,{shortcut:"↓"}),h.jsx("span",{children:"browse"})]}),h.jsxs("span",{className:"flex items-center gap-1 text-ink-dim text-meta",children:[h.jsx(Ad,{shortcut:"↵"}),h.jsx("span",{children:"jump"})]}),h.jsxs("span",{className:"flex items-center gap-1 text-ink-dim text-meta",children:[h.jsx(Ad,{shortcut:"esc"}),h.jsx("span",{children:"close"})]}),h.jsx("span",{className:"ml-auto text-ink-dim text-meta",children:Hjt(O)})]})]})},R3t=({sessionId:e,containerRef:t,onReveal:n})=>{const[r,i]=$.useState(!1),[a,o]=$.useState(!1),s=$.useRef(null),l=$.useRef(null),c=x3t({sessionId:e,enabled:r}),u=$.useCallback(()=>{const f=document.activeElement;l.current=f instanceof HTMLElement?f:null,i(!0)},[]),O=$.useCallback(()=>{i(!1);const f=l.current;l.current=null,f?.isConnected&&f.focus()},[]);$.useEffect(()=>{const f=p=>{if(p.defaultPrevented||!Bjt(p))return;const m=p.target;if(!(!(s.current!==null&&m!==null&&s.current.contains(m))&&(X$(p.target)||nOe(p.target)===null))){if(p.preventDefault(),r){const y=s.current?.querySelector("input");y?.focus(),y?.select();return}u()}};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[r,u]);const d=$.useCallback(async f=>{o(!0);try{if(n){await n(f.id);return}await v3t(t.current,f.id)}finally{o(!1)}},[t,n]);return r?h.jsx("div",{ref:s,className:"pointer-events-none absolute top-3 right-6 z-20 max-w-[calc(100%-1.5rem)]",children:h.jsx(T3t,{query:c.query,onQueryChange:c.setQuery,state:c.state,hits:c.hits,cursor:c.cursor,truncated:c.truncated,partial:c.partial,onMoveCursor:c.moveCursor,onNavigate:d,onRetry:c.refresh,onClose:O,isMac:P3t(),jumping:a})}):null};function X3t(e,t,n){const r=new Set,i=[0];for(const a of e){if(r.has(a.key))throw new Error(`Duplicate transcript entry: ${a.key}`);r.add(a.key);const o=t.get(a.key),s=o?.signature===a.signature&&o.width===n?o.height:a.estimate;if(!Number.isFinite(s)||s<0)throw new Error(`Invalid transcript extent: ${a.key}`);i.push(i[i.length-1]+s)}return i}function E3t(e,t){for(const[n,r]of e)t.set(n,{...r});e.clear()}function sJ(e,t){let n=0,r=e.length;for(;n<r;){const i=n+r>>>1;e[i]<t?n=i+1:r=i}return n}function q3t(e,t,n,r,i){const a=e.length-1,o=new Set(i.filter(O=>O>=0&&O<a)),s=Math.max(0,sJ(e,t-r)-1),l=Math.min(a,sJ(e,n+r));for(let O=s;O<l;O++)e[O+1]>t-r&&e[O]<n+r&&o.add(O);const c=[];let u=0;for(const O of[...o].sort((d,f)=>d-f))u<O&&c.push({kind:"spacer",start:u,end:O,height:e[O]-e[u]}),c.push({kind:"entry",index:O}),u=O+1;return u<a&&c.push({kind:"spacer",start:u,end:a,height:e[a]-e[u]}),c}function j3t(e,t,n,r){return!e||!t||e.id!==t.id||n!==r?null:t.viewportOffset-e.viewportOffset}function C3t(e){const t=[];let n=null;return e.forEach((r,i)=>{if((!r.candidate||r.boundary)&&(n=null),r.candidate&&n)n.indices.push(i);else{const a={key:r.firstId,indices:[i],representation:r.representation};t.push(a),n=r.candidate?a:null}}),t}function A3t(e,t){return e==="inline"&&t}function ZQe(e,t,n,r){const i=Math.max(24,Math.floor((r||810)/7.2)),a=t.split(`
@@ -972,4 +972,4 @@ ${m}`,te=j.current;j.current=M,!(te===null||te===M)&&(pin(te.split(`
972
972
  }`,W2e=()=>h.jsxs("div",{className:"flex h-6 items-center gap-0.5 [&>span]:animate-[waveform-bar_1.2s_infinite_ease-in-out]","aria-hidden":"true",children:[h.jsx("style",{children:Ssn}),h.jsx("span",{className:"size-[3px] rounded-[1px] bg-accent"}),h.jsx("span",{className:"h-2 size-[3px] rounded-[1px] bg-accent",style:{animationDelay:"0.2s"}}),h.jsx("span",{className:"size-[3px] rounded-[1px] bg-accent",style:{animationDelay:"0.4s"}}),h.jsx("span",{className:"h-3 size-[3px] rounded-[1px] bg-accent",style:{animationDelay:"0.6s"}}),h.jsx("span",{className:"size-[3px] rounded-[1px] bg-accent",style:{animationDelay:"0.8s"}})]});W2e.displayName="WaveformAnimation";const xsn=120;function Qsn({text:e,cwd:t,enabled:n=!1}){const r=$.useMemo(()=>n?nan(e):[],[e,n]),i=$.useRef(new Map),a=$.useRef(t),[o,s]=$.useState(new Map),l=Ri(),c=oi(l.data,"projects",1),u=$.useRef(new Set),O=$.useMemo(()=>{const g=new Set;for(const y of r)if(y.path&&g.add(y.path),g.size>=nle)break;return[...g]},[r]),d=O.join(`
973
973
  `),f=$.useMemo(()=>{const g=new Set;for(const y of O){const v=wse(y);v&&g.add(v.toLowerCase())}return[...g]},[O]),p=()=>{const g=new Map(i.current);if(u.current.size===0)return g;for(const y of O){const v=wse(y);v&&u.current.has(v.toLowerCase())&&g.set(y,{exists:!0,outside:!1})}return g};$.useEffect(()=>{const g=window.api;if(a.current!==t&&(a.current=t,i.current.clear(),s(p())),!n||O.length===0){s(b=>b.size>0?new Map:b);return}if(typeof g?.probeFiles!="function"&&f.length===0){s(b=>b.size>0?p():b);return}const y=O.filter(b=>!i.current.has(b)),v=c?f.filter(b=>!u.current.has(b)):[];if(y.length===0&&v.length===0){s(p());return}let S=!1;const Q=setTimeout(()=>{const b=y.length>0&&typeof g?.probeFiles=="function"?g.probeFiles(y,t).then(x=>{if(!S)for(const k of x)k.exists&&i.current.set(k.input,{exists:!0,outside:k.outsideWorkspace===!0})}).catch(()=>{}):Promise.resolve(),w=v.length>0?Re({op:"projects.list"}).then(x=>{if(!S)for(const k of x.projects){const T=k.name.toLowerCase();v.includes(T)&&u.current.add(T)}}).catch(()=>{}):Promise.resolve();Promise.allSettled([b,w]).then(()=>{S||s(p())})},xsn);return()=>{S=!0,clearTimeout(Q)}},[d,t,c]);const m=$.useMemo(()=>Fin(r,o),[r,o]);return{spans:r,resolved:m}}const zse=""+new URL("brand-mark-Bv0Hu-Cz.png",import.meta.url).href,ksn={ink:"bg-ink","ink-muted":"bg-ink-muted"},Psn={maskImage:`linear-gradient(#000, #000), url(${zse})`,WebkitMaskImage:`linear-gradient(#000, #000), url(${zse})`,maskSize:"100% 100%, auto 50%",WebkitMaskSize:"100% 100%, auto 50%",maskRepeat:"no-repeat",WebkitMaskRepeat:"no-repeat",maskPosition:"center",WebkitMaskPosition:"center",maskComposite:"exclude",WebkitMaskComposite:"xor"},_sn=({className:e,tone:t="ink",label:n})=>h.jsx("span",{role:n?"img":void 0,"aria-label":n,"aria-hidden":n?void 0:!0,"data-brand-mark":"",className:q("inline-block shrink-0 rounded-full",ksn[t],e),style:Psn}),Tsn=new Set(Oxe),Uq=navigator.platform.toUpperCase().indexOf("MAC")>=0,Use="composer-credential-notice",Wse="composer-secret-closure-notice",Rsn="Answer the secret request in the asks panel — this box is paused until it is answered, and your draft is kept.",Nse="composer-secret-ask-notice",Xsn="composer-secret-ask-refusal",Esn="composer-secret-confirm",Yse="composer-secret-confirm-message",Gse="composer-mention-outside-notice",Ise="composer-host-blocked-reason",Zse="composer-delivery-remedies-hint",qsn={canUseRadientSpeech:!1,speechBlock:"could-not-check"},jsn=1500;function N2e(e,t){return new Promise((n,r)=>{const i=setTimeout(()=>r(new Error("credential store timed out")),t);e.then(a=>{clearTimeout(i),n(a)},a=>{clearTimeout(i),r(a)})})}const Csn=fA("sessions.credential"),Dse=5e3;async function Mse(e,t,n){try{const r=await N2e(Re({op:"sessions.credential",sessionId:e,action:"store",key:t.key,value:t.value}),n);return r?.data?.ok===!1?{kind:"fate",fate:r.data.reason==="empty-key"?"rejected-key":"lost"}:{kind:"stored"}}catch(r){const i=r instanceof Ut?r.status:null;return i!==null&&i>=400&&i<500?{kind:"fate",fate:"lost"}:null}}async function Asn(e,t,n){try{const r=await N2e(Re({op:"sessions.credential",sessionId:e,action:"list"}),n),i=r?.data;return i?.ok===!1||!Array.isArray(i?.credentials)?null:kU(r).includes(t)}catch{return null}}async function zsn(e,t){const n=await Mse(e,t,Csn);if(n?.kind==="stored")return n;const r=n===null;let i=n;if(i===null&&(i=await Mse(e,t,Dse)),i?.kind==="stored")return i;const a=await Asn(e,t.key,Dse);return a===!0?{kind:"stored"}:a===!1&&i!==null&&!r?i:null}const Vse=[],Lse=[],Usn=e=>new Promise(t=>{const n=new FileReader;n.onload=r=>t(typeof r.target?.result=="string"?r.target.result:null),n.onerror=()=>t(null),n.readAsDataURL(e)}),Wsn=()=>document.querySelector('[aria-label="Answer options"] button:not([disabled])'),Nsn=()=>document.querySelector(ROe),Ysn='[aria-label="Remove reply"]';let OA=!1;const dfn=()=>wUe(Nsn(),document.activeElement,OA),Gsn=q("mx-auto flex w-full flex-col bg-elevated","box-border transition-colors duration-fast ease-out-quart"),Isn=q("has-[textarea:focus-visible]:outline-solid has-[textarea:focus-visible]:outline-2","has-[textarea:focus-visible]:outline-accent has-[textarea:focus-visible]:outline-offset-2"),Zsn=$.forwardRef(({onSendMessage:e,isLoading:t,awaitingReply:n=!1,awaitingAnswer:r=!1,deliveryRemediesReachable:i=!1,deviceHold:a,hostNotice:o,secretAnswer:s=!1,secretAsk:l=null,asideSessionId:c,asideStreaming:u=!1,asideAdoptQueue:O=!1,conversationId:d,messages:f,currentJobId:p,onCancelJob:m,onComposerInput:g,isFarFromBottom:y=!1,hasNewActivity:v=!1,scrollToBottom:S=()=>{},canonicalStop:Q,canonicalStopAvailable:b=!1,interruptNotice:w,sendError:x,stopConfirmation:k,initialSuggestions:T,noProvider:_=!1,noModel:E=!1,agentData:R,cwd:j,cwdWritePath:C,cwdReadOnlyReason:W,cwdPending:G,cwdPendingAccepted:N,isSmallView:Z=!1,askExpanded:F,onAskToggle:z,askOutcomes:M,ownGutter:te=!1,isHydrating:U=!1,transcriptless:H=!1,autoFocus:D=!0,unavailable:V=!1,mentionsEnabled:se=!1,mentionsUnsupported:B=!1,sessionStatus:K,onSlashCommand:ne,onSlashNote:le,paneHasSession:Oe,runDetails:Qe,recordingProbe:we=qsn,onCredentialsStored:He,onDictationStateChange:Ne,placeholderOverride:Ke},Le)=>{br();const ze=j??(C?.kind==="move"?void 0:R?.current_working_directory),ye=Pr(I=>c?I.attached[c]??null:null),_e=$.useRef(null);$.useEffect(()=>{if(O||!u||_e.current===null)return;_e.current=null;const I=Pr.getState(),he=c??"";I.attached[he]?.notice===CI(Uq)&&I.setAsideNotice(he,null)},[u,c,O]);const et=an(I=>I.removeReply),ae=an(I=>I.addAttachment),ce=an(I=>I.removeAttachment),be=an($.useCallback(I=>d?I.inputByConversation[d]?.replies??Vse:Vse,[d])),oe=an($.useCallback(I=>d?I.inputByConversation[d]?.attachments??Lse:Lse,[d])),pe=$.useRef(He);$.useEffect(()=>{pe.current=He});const[me,Se]=$.useState(!1),[Me,gt]=$.useState(!1),[Rt,pt]=$.useState(null),[Ee,xt]=$.useState(!1),[en,Sn]=$.useState(!1);$.useEffect(()=>{if(!en)return;const I=window.setTimeout(()=>Sn(!1),5e3);return()=>window.clearTimeout(I)},[en]);const hr=$.useRef(null),Gr=$.useRef([]),[Ia,xa]=$.useState(""),Ii=$.useRef(0);$.useEffect(()=>{const I=x?.message;Ii.current=I?Date.now():0},[x?.message]);const{canUseRadientSpeech:Xs,speechBlock:At}=we,En=Xs,tr=ode("recording",At),pr=!H&&f.length===0&&!U,St=pr,nt=$.useMemo(()=>{const I=K?.frontend?.effective_model??K?.frontend?.selected_model??null;return I?{provider:I.provider,model_id:I.model_id}:null},[K]),mt=$.useRef(null),_t=$.useRef(null),Ze=$.useMemo(()=>!T||T.length===0?[]:St?(mt.current===null&&(mt.current=jrn(T)),mt.current):[],[T,St]),[ut,Wt]=$.useState(null),[tn,gn]=$.useState(null),[zn,nr]=$.useState(null),[Zn,Za]=$.useState(eo),qn=$.useRef(eo),Ar=$.useCallback(I=>{qn.current=I,Za(I)},[]),or=$.useRef(new Map),qi=$.useRef(1),[pc,Qa]=$.useState(null),Zi=$.useRef(null),mr=$.useCallback(I=>{Zi.current=I,Qa(I)},[]),[mc,qe]=$.useState(null),ke=$.useRef(null),$n=$.useCallback(I=>{ke.current=I,qe(I)},[]),Hn=$.useCallback(I=>ZH(Zi.current,I)??0,[]),gr=$.useRef(null),Qt=$.useRef(null),Da=$.useRef(null),yt=$.useRef(null),Kn=$.useRef(null),xn=$.useRef(!1),[Es,fo]=$.useState(0),Fr=$.useRef([]),Ol=$.useRef(void 0),Ft=K&&!K.draft?d:void 0,na=$.useCallback(async(I,he=Ft)=>{const je=[...or.current.values()],Je=NH(I,je);if(Je.length===0&&hxe(I,je).length===0)return{text:I,stored:[],refused:[],unconfirmed:[]};const On=new Map,Mt=[],rr=await Promise.all(Je.map(async Di=>({payload:Di,attempt:he?await zsn(he,Di):{kind:"fate",fate:"unreachable"}})));for(const{payload:Di,attempt:mo}of rr){if(mo===null){On.set(Di.index,"unconfirmed");continue}if(mo.kind==="stored"){Mt.push(Di.key);continue}On.set(Di.index,mo.fate)}Mt.length>0&&he&&await pe.current?.(he);const Zr=Di=>[...On.entries()].filter(([,mo])=>Di(mo)).map(([mo])=>je.find(ml=>ml.index===mo)?.key??`#${mo}`);return{text:P2t(I,je,On),stored:Mt,refused:Zr(Di=>Di!=="unconfirmed"),unconfirmed:Zr(Di=>Di==="unconfirmed")}},[Ft]),qs=K?.draft===!0&&K?.draftResolved===!1,ho=$.useCallback(()=>{xn.current=!0,fo(I=>I+1),mr(null),Kn.current=null},[mr]),dl=$.useRef(!1),oh=$.useRef(!1),ig=$.useCallback(()=>oh.current?dl.current?"mixed":"dictated":"typed",[]),ag=$.useRef([]),{client:tb,provided:nb}=oo(),sh=$.useMemo(()=>async(I,he)=>{if(qs)return K?.onOpenDraftPicker?.("session.model"),!1;if(me||Ee)return!1;let je;const Je=Ft?await na(I):{text:I,stored:[],refused:[],unconfirmed:[]};Je.stored.length>0&&Of(YH(Je.stored)),Je.refused.length>0&&pg(GH(Je.refused)),Je.unconfirmed.length>0&&pg(IH(Je.unconfirmed));const On=ag.current,Mt=HN(I,On);let rr=null;if(Mt&&nb){const Cs=await xon(tb,j??"",Mt.name);Cs!==null&&FXe(Cs)?rr=Cs:le?.(Cs!==null?`skill \`${Mt.name}\` has an empty body — sending your message as written`:`could not load skill \`${Mt.name}\` — sending your message as written`)}const Zr=Cs=>{if(Mt!==null&&rr!==null){const U_=HN(Cs,On),pRe=U_&&U_.name===Mt.name?U_.request:Mt.request;return r5(BXe({...Mt,request:pRe},rr),be)}return r5(Cs,be)},Di=Ft?void 0:async Cs=>(je=await na(I,Cs),Zr(je.text)),mo=Zr(Je.text),ml=await e(mo,oe.map(Cs=>Cs.path),he,I,Di,ig());return ml!==!1&&(dl.current=!1,oh.current=!1),ml!==!1&&je&&(je.stored.length>0&&Of(YH(je.stored)),je.refused.length>0&&pg(GH(je.refused)),je.unconfirmed.length>0&&pg(IH(je.unconfirmed))),ml===!1?ml:Wz(ml)?(ude(ml,ho),ml):(ho(),ml)},[e,oe,be,ho,na,Ft,qs,K?.onOpenDraftPicker,ig,me,Ee,tb,nb,j,le]),lh=ar(I=>nZe(I.drafts,d)),{inputValue:Te,setInputValue:sr,handleKeyDown:rb,handleSubmit:ch,textareaRef:It,sendInFlight:og,appendTranscriptText:ra}=XGe({conversationId:d,onSubmit:sh,scrollToBottom:S,draftHeld:ql(Zn),transcriptless:H,draftUnredacted:Hn});$.useEffect(()=>{Te===""&&!og&&!lh&&(dl.current=!1,oh.current=!1)},[Te,og,lh]);const uh=ZH(pc,Te),[Br,ji]=$.useState(0),[Oh,ib]=$.useState(!1),Q_=Ron(d),fl=Oe??!1,ot=psn({inputValue:Te,selectionStart:Br,sessionId:Q_,paneHasSession:fl,activeProfile:{team:K?.frontend?.active_team,agent:K?.frontend?.active_agent},activeModel:Ax(K?.frontend?.effective_model??K?.frontend?.selected_model),activeSpec:K?.frontend?.effective_model??K?.frontend?.selected_model,cwd:j}),dh=St&&!(ot.open&&ot.phase==="argument"),Hr=Son({text:Te,caret:Br,cwd:j,attached:fl,commandNames:ot.commandNames,argumentWords:ot.argumentWords,enabled:!ql(Zn)});$.useEffect(()=>{ag.current=Hr.vocabulary.map(I=>I.name)},[Hr.vocabulary]);const ka=qan({text:Te,caret:Br,cwd:j,enabled:se,unsupported:B}),Vo=Qsn({text:Te,cwd:j,enabled:se}),ia=$.useMemo(()=>[...Vo.resolved.values()].filter(I=>I.outside).length,[Vo.resolved]),si=$.useRef(null),sg=$.useRef(null),ed=$.useRef(null);$.useLayoutEffect(()=>{d!==void 0&&ed.current!==d&&Te&&(ed.current=d,si.current=Te.length,ji(Te.length))},[Te,d]);const lg=$.useRef(Te);$.useLayoutEffect(()=>{lg.current=Te;const I=It.current,he=si.current;!I||he===null||(si.current=null,I.setSelectionRange(he,he))},[Te,It,mr]);const cg=$.useCallback(()=>[...Fr.current,...[...or.current.values()].map(I=>I.key)],[]),de=$.useCallback((I,he)=>{d&&(ql(I)||an.getState().setCurrentInput(d,he,Hn(he)))},[d,Hn]),ue=$.useCallback(I=>{const he=I.payload??null;he&&(or.current.set(he.index,he),qi.current=Math.max(qi.current,he.index+1)),I.buffer!==lg.current&&(si.current=I.caret,ji(I.caret)),gr.current=I.buffer,Da.current!==null&&!I.buffer.includes(Da.current.trim())&&(Da.current=null),Qt.current!==null&&!I.buffer.includes(Qt.current.text.trim())&&(Qt.current=null),Ar(I.capture),sr(I.buffer),de(I.capture,I.buffer)},[de,Ar,sr]);$.useLayoutEffect(()=>{gr.current!==Te&&(gr.current=Te,h2t(qn.current)&&(Ar(eo),mr(null)))},[Te,Ar,mr]),$.useEffect(()=>{qn.current=eo,Ar(eo),or.current.clear(),qi.current=1,xn.current=!1,Qt.current=null,Da.current=null,Kn.current=null,mr(null)},[d,Ar,mr]);const Fe=an(I=>d?I.getUnredactedChars(d):0),rt=an(I=>d?I.getCurrentInput(d):"");$.useEffect(()=>{Fe<=0||!rt||Te!==rt||Zi.current?.over!==rt&&mr({chars:Fe,over:rt})},[Fe,rt,Te,mr]),$.useLayoutEffect(()=>{const I=Zi.current;I&&I.over!==Te&&mr(null)},[Te,mr]),$.useLayoutEffect(()=>{const I=ke.current;I&&I.over!==Te&&$n(null)},[Te,$n]),$.useEffect(()=>{xn.current&&(NH(Te,or.current.values()).length>0||(or.current.clear(),qi.current=1,xn.current=!1))},[Te,Es]),$.useEffect(()=>{Zn.arm===null||!Ft||Ol.current!==Ft&&(Ol.current=Ft,Re({op:"sessions.credential",sessionId:Ft,action:"list"}).then(I=>{Fr.current=kU(I)}).catch(()=>{}))},[Zn.arm,Ft]);const ft=$.useCallback(()=>{const I=qn.current;if(!ql(I))return!1;const he=g2t({capture:I,buffer:Te,caret:It.current?.selectionEnd??Te.length,index:qi.current,taken:cg()});return he.minted?(ue(he),mr(null),!0):!1},[ue,Te,cg,mr]),kt=$.useCallback(I=>{const he=qn.current;if(!ql(he))return!1;const je=I.currentTarget,Je={start:je.selectionStart??Te.length,end:je.selectionEnd??Te.length};if(I.key==="Enter"&&!I.shiftKey&&!I.nativeEvent.isComposing)return ft();if(I.key==="Escape"){const Mt=$2t(he,Te);return Mt.cancelled?(Qt.current=Mt.token,mr(Mt.restored>0?{chars:Mt.restored,over:Mt.buffer}:null),ue(Mt),!0):!1}return I.key==="Enter"?(ue(UH(he,Te,Je,`
974
974
  `)),!0):I.key==="Tab"?!0:Array.from(I.key).length===1&&!I.ctrlKey&&!I.metaKey&&!I.altKey&&!I.nativeEvent.isComposing?(ue(UH(he,Te,Je,I.key)),!0):!1},[Te,ue,ft,mr]),Dn=$.useCallback((I,he,je="typed")=>csn({gesture:je,draft:I,caret:he,commandNames:ot.commandNames,promptCommands:ot.promptCommands,armedOnlyCommands:ot.armedOnlyCommands,valueArgumentCommands:ot.valueArgumentCommands,argumentCommands:ot.argumentCommands,argumentShapes:ot.argumentShapes,prefixingCommands:ot.prefixingCommands,commandLockedWords:Tsn,unmaskedRunWord:Ir(I)?Qt.current?.text.trim().replace(/^\//,""):aa(I)?yt.current?.word:void 0,nameListCommands:ot.nameListCommands,enabled:ot.available&&!!ne}),[ot.commandNames,ot.promptCommands,ot.armedOnlyCommands,ot.valueArgumentCommands,ot.argumentCommands,ot.argumentShapes,ot.prefixingCommands,ot.nameListCommands,ot.available,ne]),vn=$.useCallback((I,he,je)=>{si.current=he,sr(I),ji(he),le?.(je)},[le,sr]),Sr=$.useCallback(I=>{const he=Qt.current;if(he!==null&&he.text.trim().length>0&&I.includes(he.text.trim()))return he.text.trim();const je=Da.current;return je!==null&&je.trim().length>0&&I.includes(je.trim())?je.trim():null},[]),sn=$.useCallback(I=>WH(I,Qt.current)?"send":Sr(I)===null?"typed":"pick",[Sr]),Ir=$.useCallback(I=>{const he=Qt.current;return he===null||he.restored===0?!1:zH(I,he.restoredText)},[]),aa=$.useCallback(I=>{const he=yt.current;return he!==null&&zH(I,he.run)},[]),Qn=$.useCallback(I=>{const he=Qt.current;return he!==null&&he.restored>0&&WH(I,he)},[]),li=$.useCallback((I,he)=>{const je=sn(I);if(je==="send"&&Qn(I))return{kind:"held",notice:"These characters are still the credentials you cancelled — clear the box to release your words and send your sentence."};if(je==="send")return{kind:"send"};const Je=je==="pick"?Dn(I,he,"pick"):Dn(I,he);if(je!=="pick"||Je.kind!=="send")return Je;const On=Sr(I);if(On===null)return Je;const Mt=I.indexOf(On);return Mt<0?Je:Dn(I,Mt+On.length,"pick")},[sn,Qn,Dn,Sr]),pn=$.useMemo(()=>{if(Oh)return[];const I=Uan({draft:Te,commandNames:ot.commandNames,nameListCommands:ot.nameListCommands,nameChoices:ot.nameChoices,picking:ot.open&&ot.matches.length>0});if(I.length===0)return I;const he=Dn(Te,Br,"typed");return Wan(I,Te,{sendsAsWritten:he.kind==="send"})},[Te,Br,Oh,Dn,ot.commandNames,ot.nameListCommands,ot.nameChoices,ot.open,ot.matches.length]),ju=$.useMemo(()=>Oh?[]:uon({draft:Te,vocabulary:Hr.vocabulary,settled:Hr.settled,picking:Hr.open}),[Te,Oh,Hr.vocabulary,Hr.settled,Hr.open]),ab=$.useMemo(()=>[...pn,...ju],[pn,ju]),Kr=x2e(ab),ug=$.useCallback(async(I,he,je)=>{const Je=ne;if(I.kind==="held"){const Mt=Qt.current;Mt!==null&&(_t.current?.token!==Mt||_t.current?.notice!==I.notice)&&(_t.current={token:Mt,notice:I.notice},le?.(I.notice));return}if(!Je)return;if(I.kind==="whole"||I.kind==="splice"){const Mt=ot.commands.find(Zr=>Zr.name===I.command.name||Zr.aliases.includes(I.command.name)),rr=on(I.command.args??"");if(Mt?.destination==="session.model"&&rr){const Zr=gke(ot.argumentList.rows,rr);if(Zr){SO.getState().openConnect({providerId:Zr});return}}}if(I.kind==="list-open"){if(ot.open&&ot.matches.length>0)return;le?.(`Type a name after /${I.command.name}, or choose one from the list.`);return}if(I.kind==="unrecognised"){await Je(I.command),si.current=je,sr(he),ji(je);return}if(I.kind==="reassemble"){vn(I.text,I.caret,Don(I.text.trim(),fl));return}if(await Je(I.command)==="consumed"){const Mt=I.kind==="whole"?"":I.text,rr=I.kind==="whole"?0:I.caret;if(si.current=rr,sr(Mt),ji(rr),I.locked===!0){const Zr=wxe(he,qn.current),mo=!(I.kind==="whole"?Zr:Zr.slice(I.start,I.end)).includes(uxe);Kn.current=mo?{text:Zr,caret:je,plain:Kp(I.command.args).length}:null,le?.(Mon(I.command.name,{dialog:fl&&ot.commandNames.has(I.command.name),undo:mo},Uq))}return}si.current=je,sr(he),ji(je)},[ne,le,sr,ot.commandNames,ot.open,ot.matches.length,ot.commands,ot.argumentList.rows,vn,fl]),G2e=!!(t&&p),k_=!!s,un=V||G2e||k_||!!o?.blocksInput,[ci,Cu]=$.useState(null),[mN,fh]=$.useState(null),[po,gN]=$.useState(!1),$N=$.useRef(null),ob=$.useRef(null),yN=$.useRef(Te);$.useEffect(()=>{yN.current=Te},[Te]),$.useEffect(()=>{Cu(null),fh(null)},[d]),$.useEffect(()=>{ci!==null&&$N.current?.focus()},[ci]),$.useEffect(()=>{if(!po)return;const I=document.activeElement;I!==null&&I!==document.body&&!ob.current?.contains(I)||ob.current?.focus()},[po]),$.useEffect(()=>{if(ci===null||l!==null&&l.key===ci.key)return;Cu(null),fh(l===null?J("ui.chat.composer.secret_fill_gone"):J("ui.chat.composer.secret_fill_changed"));const I=document.activeElement;I!==null&&I!==document.body&&I!==It.current&&!ob.current?.contains(I)||It.current?.focus()},[l,ci,It]),$.useEffect(()=>{fh(null)},[Te]),$.useEffect(()=>{ci!==null&&Te.trim()!==ci.value&&Cu(null)},[Te,ci]);const sb=$.useCallback(I=>!l||!gRt(I)?!1:(Cu({value:I.trim(),key:l.key}),!0),[l]),lb=$.useCallback(()=>{Cu(null),fh(null),It.current?.focus()},[It]),vN=$.useCallback(I=>{switch(I){case"locked":return J("ui.chat.composer.secret_fill_locked");case"stale":return J("ui.chat.composer.secret_fill_changed");case"multi":return J("ui.chat.composer.secret_fill_multi");case"refused":return J("ui.chat.composer.secret_fill_refused");case"unavailable":return J("ui.chat.composer.secret_fill_unavailable")}},[]),I2e=$.useCallback(async()=>{if(ci===null||l===null||po)return;if(!l.fillable){Cu(null),fh(J("ui.chat.composer.secret_fill_multi")),l.onOpen({focus:!1}),It.current?.focus();return}gN(!0);let I;try{I=await l.onFill(ci.value,ci.key)}catch{I="unavailable"}finally{gN(!1)}if(Cu(null),I==="sent"){yN.current.trim()===ci.value&&sr(""),It.current?.focus();return}fh(vN(I)),I!=="unavailable"&&l.onOpen({focus:!1}),It.current?.focus()},[l,ci,po,vN,sr,It]),Z2e=$.useCallback(()=>{Cu(null),ch(),It.current?.focus()},[ch,It]),Og=_||E,cb=$.useCallback(()=>{Sn(!0)},[]),P_=$.useCallback(async I=>{const he=Ax(I.model);if(!(un||!Wke(I)||I.id!=="model-default"||!he)){ot.close();try{await Uke(he,(je,Je)=>Re({op:"settings.edit",key:je,value:Je})),sr(""),le?.(`Default for new sessions: ${he.provider}/${he.model_id}`)}catch(je){le?.(`The default was not saved: ${je instanceof Error?je.message:"the backend refused it"}`)}}},[un,ot.close,sr,le]),__=$.useCallback(async(I,he)=>{if(I.kind==="action"){he.run&&await P_(I.row);return}if(un)return;const je=wsn(Te,Br,I,ot.commandNames,ot.argumentWords,ot.inline?.nameThenMessage??!1);if(!je)return;if(ot.close(),he.run&&I.kind==="argument"&&!fl&&ne){const rr=brn(ot.inline?.source);if(rr){const Zr=b$(Te,Br,ot.commandNames),Di=Zr?on(vO(Te,Zr.start,Zr.end,"").text):"";ar.getState().restageDraft({kind:rr,name:I.row.value},Di);return}}Kh.lastIndex=0;const Je=Kh.exec(je.text);if(Da.current=Je?Je[0].trim():null,I.kind==="command"&&he.run&&uA(I,ot.armedOnlyCommands)){const rr=usn({draft:je.text,caret:je.caret,commandNames:ot.commandNames,armedOnlyCommands:ot.armedOnlyCommands});if(rr.kind==="armed"){vn(rr.text,rr.caret,Zon(rr.text.trim(),I.command.destination,r2e(I.command.destination)?fl:!0));return}}if(ue({capture:Jh(qn.current,je.text,je.caret,"completion"),buffer:je.text,caret:je.caret}),!(he.run&&(I.kind==="command"?E2e(I.command.destination,ot.effectiveEntry(I.command.destination)):ot.inline?.runs??!1)&&!!ne))return;const Mt=Dn(je.text,je.caret,"pick");Mt.kind!=="send"&&await ug(Mt,Te,Br)},[Te,Br,ot,ue,ne,Dn,ug,vn,fl,un,P_]),bN=$.useCallback(I=>{const he=Xon(Te,Br,I,ot.commandNames);he&&(si.current=he.caret,sr(he.text),ji(he.caret))},[Te,Br,ot.commandNames,sr]),wN=$.useCallback(I=>{if(un)return;const he=y2e(Te,Br);if(!he)return;const je=ian(I),Je=Te.slice(he.end,he.end+1),On=he.start>0&&(Je===" "||Je===`
975
- `)?1:0,Mt=vO(Te,he.start,he.end+On,je),rr=je.endsWith('"')?Mt.caret-1:Mt.caret;si.current=rr,sr(Mt.text),ji(rr),ka.remember(I.path),ka.close()},[Te,Br,ka,sr,un]),T_=$.useCallback(I=>{if(un||!Hr.token)return;const he=ion(Te,Hr.token,I.name);Hr.close(),si.current=he.caret,sr(he.text),ji(he.caret)},[Te,Hr,sr,un]),D2e=$.useCallback(I=>{const he=Kn.current;return he===null||!(I.metaKey||I.ctrlKey)||I.altKey||I.shiftKey||I.key.toLowerCase()!=="z"?!1:(Kn.current=null,si.current=he.caret,he.plain>0&&mr({chars:he.plain,over:he.text}),sr(he.text),ji(he.caret),!0)},[mr,sr]),M2e=$.useCallback(I=>{if(un)return;if(kt(I)){I.preventDefault();return}if(I.key==="Escape"&&ci!==null){if(I.preventDefault(),po)return;lb();return}if(L2e(I)){I.preventDefault();return}if(D2e(I)){I.preventDefault();return}if(jan(I,ka,wN)){I.preventDefault();return}if(bsn(I,ot,__,bN)){I.preventDefault();return}if(kon(I,Hr,T_)){I.preventDefault();return}if(ye!==null&&I.key==="Escape"){I.preventDefault(),Uj(c??"");return}if(ye!==null&&XIe(I)){const Je=ye.turns.at(-1),On=Je?Pr.getState().streams[Je.asideId]:void 0;if(!Je||ye.queued!==void 0||!_de(On,u,O))return;I.preventDefault();const Mt=c??"",rr=Date.now(),Zr=qIe(_e.current,Je.asideId,rr);if(Zr==="arm"){_e.current={turnId:Je.asideId,at:rr},Pr.getState().setAsideNotice(Mt,CI(Uq));return}if(Zr==="ignore")return;_e.current=null,kde(Mt).catch(()=>{});return}if(I.key==="Backspace"||I.key==="Delete"){const Je=Lin(Br,I.key==="Backspace"?"back":"forward",Vo.spans,Vo.resolved);if(Je&&!I.nativeEvent.isComposing){const On=vO(Te,Je.start,Je.end,"");si.current=On.caret,ji(On.caret),sr(On.text),I.preventDefault();return}}const he=It.current,je=Wsn();if(je&&bUe(I,{value:Te,selectionStart:he?.selectionStart??null,selectionEnd:he?.selectionEnd??null})){je.focus(),I.preventDefault();return}if(Og&&I.key==="Enter"&&!I.shiftKey&&!I.nativeEvent.isComposing){I.preventDefault(),cb();return}if(I.key==="Enter"&&!I.shiftKey&&!I.nativeEvent.isComposing){const Je=li(Te,Br);if(Je.kind!=="send"){I.preventDefault(),ug(Je,Te,Br);return}if(sb(Te)){I.preventDefault();return}}rb(I)},[ot,__,bN,Hr,T_,sb,rb,kt,ci,lb,li,ug,Te,Br,un,ye,c,u,O]),SN=$.useRef(null),hl=$.useCallback(I=>{OA=!1,It.current?.focus({preventScroll:I?.preventScroll===!0})},[It]),V2e=$.useCallback(()=>{oOe(Te)!==null&&sr("")},[Te,sr]);$.useImperativeHandle(Le,()=>({focusInput:hl,openWorkingDirectoryMenu:()=>{SN.current?.openMenu()},submitNow:()=>{sb(Te)||ch()},consumeApprovalAnswerDraft:V2e}));const xN=$.useCallback(()=>It.current,[It]);$.useEffect(()=>ZWe(hl,xN),[hl,xN]);const pl=$.useRef(null),QN=$.useRef(Te);$.useLayoutEffect(()=>{QN.current=Te},[Te]);const kN=$.useCallback(I=>{pl.current===I&&(pl.current=null,or.current.delete(I.index))},[]),ub=$.useCallback(I=>{if(pl.current!==I)return!1;const he=A2t({buffer:QN.current,cleared:I.cleared});return he?(or.current.set(I.index,I.payload),pl.current===I&&(pl.current=null),I.toastId!==null&&U0(I.toastId),ue({capture:Jh(qn.current,he.buffer,he.caret,"arrival"),buffer:he.buffer,caret:he.caret}),$n(null),!0):!1},[ue,$n]);$.useLayoutEffect(()=>{const I=pl.current;I!==null&&I.cleared.buffer!==Te&&(I.toastId!==null&&U0(I.toastId),kN(I))},[Te,kN]);const L2e=$.useCallback(I=>{const he=pl.current;return he===null||!(I.metaKey||I.ctrlKey)||I.altKey||I.shiftKey||I.key.toLowerCase()!=="z"?!1:(ub(he),!0)},[ub]),PN=$.useCallback(I=>{ub(I)&&hl()},[hl,ub]),F2e=$.useCallback(I=>{if(un)return;const he=or.current.get(I);if(!he)return;const je=C2t({buffer:Te,payload:he});if(!je.cleared)return;const Je=pl.current;Je&&(pl.current=null,or.current.delete(Je.index),Je.toastId!==null&&U0(Je.toastId));const On={index:I,payload:he,cleared:je,toastId:null};pl.current=On,ue({capture:Jh(qn.current,je.buffer,je.caret,"arrival"),buffer:je.buffer,caret:je.caret}),$n({key:he.key,index:I,over:je.buffer}),On.toastId=pg(q2t(I),{action:{label:E2t,onClick:()=>PN(On)}}),hl()},[ue,hl,un,Te,$n,PN]),B2e=trn(!!Q?.active),_N=b&&!Q?.active&&(B2e.held||me)&&!(t&&p),H2e=!!Q?.active||_N,K2e=un||me||Ee||Te.trim().length>0;$.useEffect(()=>{const I=It.current;I&&(I.style.height="auto",I.style.height=`${I.scrollHeight}px`)},[Te,It,me,Ee]);const TN=$.useRef(!1);$.useEffect(()=>{const I=me||Ee,he=TN.current&&!I;if(TN.current=I,!D&&!he||un||I)return;const je=document.activeElement;!(je&&(je.tagName==="INPUT"||je.tagName==="TEXTAREA"))&&!_&&It.current?.focus({preventScroll:!0})},[D,un,me,Ee,It,_]),$.useEffect(()=>{window.electron.ipcRenderer.invoke("get-platform-info").then(I=>{xa(I.platform)}).catch(I=>{console.error("Failed to get platform info:",I)})},[]);const js=$.useRef(null),J2e=250,RN=$.useRef(Ne);$.useEffect(()=>{RN.current=Ne}),$.useEffect(()=>(fse("message-input",me||Me),()=>fse("message-input",!1)),[me,Me]),$.useEffect(()=>{RN.current?.(me)},[me]);const Au=$.useCallback(I=>{gt(!1);const he=hr.current;if(!he)return;const je=js.current?.startedAt??null,Je=je===null?Number.POSITIVE_INFINITY:performance.now()-je;if(js.current=null,he.state==="inactive"){Se(!1);return}(I==="abort"||Je<J2e)&&(he.onstop=()=>{if(he.stream)for(const On of he.stream.getTracks())On.stop();pt(null),Gr.current=[]}),he.stop(),Se(!1)},[]);$.useEffect(()=>()=>{const I=js.current!==null;js.current=null;const he=hr.current;if(he&&he.state!=="inactive"){Au("abort");return}I&&gt(!1)},[Au]);const R_=$.useCallback((I="release")=>{const he=js.current;if(he){if(he.startedAt===null){js.current=null,gt(!1);return}Au(I)}},[Au]),XN=$.useCallback(async()=>{if(!(un||!En)&&!js.current)if(navigator?.mediaDevices?.getUserMedia){const I={startedAt:null};js.current=I,gt(!0);try{const he=await navigator.mediaDevices.getUserMedia({audio:!0});if(js.current!==I){for(const je of he.getTracks())je.stop();return}hr.current=new MediaRecorder(he),Gr.current=[],hr.current.ondataavailable=je=>{Gr.current.push(je.data)},hr.current.onstop=()=>{const je=new Blob(Gr.current,{type:"audio/webm"});pt(je);for(const Je of he.getTracks())Je.stop()},hr.current.start(),I.startedAt=performance.now(),gt(!1),Se(!0),pt(null)}catch(he){if(js.current!==I)return;js.current=null,gt(!1),console.error("Error accessing microphone:",he),mi("Error accessing microphone. Please ensure microphone permissions are granted.")}}else console.error("This runtime exposes no MediaRecorder"),mi("Dictation is not available on this device.")},[En,un]),X_=$.useCallback(()=>{me&&Au("release")},[me,Au]),E_=$.useCallback(()=>{me&&Au("abort")},[me,Au]);$.useEffect(()=>{if(!me&&!Me)return;const I=he=>{if(me){he.key==="Enter"?(he.preventDefault(),X_()):he.key==="Escape"&&(he.preventDefault(),E_());return}he.key==="Escape"&&(he.preventDefault(),R_("abort"),gt(!1))};return window.addEventListener("keydown",I),()=>{window.removeEventListener("keydown",I)}},[me,Me,X_,E_,R_]);const EN=$.useCallback(async()=>{if(Rt)try{xt(!0);const I=await Hue.createTranscription(Nf.baseUrl,{file:new File([Rt],"recording.webm",{type:"audio/webm"})});if(I.result?.text){const he=I.result?.text||"";oh.current=!0,ra(he)}else Tp(Z8e);pt(null)}catch(I){console.error("Error transcribing audio:",I),mi(b8e(I))}finally{xt(!1)}},[Rt,ra]);$.useEffect(()=>{Rt&&EN()},[Rt,EN]);const qN=$.useRef(!0);$.useEffect(()=>{if(typeof IntersectionObserver>"u")return;const I=It.current;if(I===null)return;const he=new IntersectionObserver(je=>{const Je=je[je.length-1];Je!==void 0&&(qN.current=Je.isIntersecting)});return he.observe(I),()=>he.disconnect()},[It]),Rrn("message-input",i2e.MESSAGE_INPUT,{start:XN,stop:R_},()=>!!(!un&&!me&&!Ee&&En&&qN.current));const eRe=I=>{if(I.preventDefault(),un||_)return;if(E){cb();return}if(!Te.trim()&&oe.length===0||ft())return;const he=li(Te,Br);if(he.kind!=="send"){ug(he,Te,Br);return}sb(Te)||ch()},q_=$.useCallback(I=>{un&&I.preventDefault()},[un]),tRe=$.useCallback(I=>{!un&&!Og||(I.preventDefault(),Og&&!un&&cb())},[un,Og,cb]),nRe=I=>{d&&ce(d,I)},rRe=async()=>{const I=await window.electron.ipcRenderer.invoke("show-open-dialog",{properties:["openFile","multiSelections"]});if(!I.canceled&&I.filePaths.length>0&&d)for(const he of I.filePaths)ae(d,{id:fs(),path:q$(he)})},iRe=I=>{if(un)return;const he=I.clipboardData?.getData("text/plain")??"";if(he&&qn.current.arm!==null){const Je=I.currentTarget,On=v2t({capture:qn.current,buffer:Te,caret:Je.selectionEnd??Te.length,selection:{start:Je.selectionStart??Te.length,end:Je.selectionEnd??Te.length},pasted:he,index:qi.current,taken:cg()});if(On){I.preventDefault(),ue(On),mr(null);return}}he&&(yt.current=O2t(he));const je=I.clipboardData?.items;if(je){for(let Je=0;Je<je.length;Je++)if(je[Je].type.indexOf("image")!==-1||je[Je].kind==="file"){const On=je[Je].getAsFile();if(On){const Mt=new FileReader;Mt.onload=rr=>{rr.target?.result&&d&&ae(d,{id:fs(),path:rr.target.result})},Mt.readAsDataURL(On)}}}},aRe=I=>{un||I.dataTransfer?.types.includes("Files")&&(I.preventDefault(),I.stopPropagation(),I.dataTransfer.dropEffect="copy",j_(!0))},oRe=I=>{I.currentTarget.contains(I.relatedTarget)||j_(!1)},sRe=I=>{if(j_(!1),un)return;const he=I.dataTransfer?.files;!he||he.length===0||(I.preventDefault(),I.stopPropagation(),d&&lRe(d,Array.from(he)))},lRe=async(I,he)=>{for(const je of he){const Je=window.api?.getPathForFile?window.api.getPathForFile(je):"";if(Je){ae(I,{id:fs(),path:q$(Je)});continue}const On=await Usn(je);On&&ae(I,{id:fs(),path:On})}},[jN,j_]=$.useState(!1),cRe=I=>{un||(Te||g?.(),si.current=I.length,sr(I),ji(I.length),It.current?.focus())},C_=ql(Zn)?Zn.value!==""?G2t:Ft?I2t:Z2t:j2t({unredacted:uh!==null?D2t(uh,Qn(Te)?bxe:void 0):null,armed:Zn.arm!==null&&mxe(Te,Te.length)!==null,cleared:mc===null?null:{key:mc.key,index:mc.index},undoCap:A2e(Ia==="darwin")}),uRe=$.useMemo(()=>Ia==="darwin"?"Cmd+Shift+S":"Ctrl+Shift+S",[Ia]),A_=$.useRef(null),ORe=I=>{d&&(A_.current=be.findIndex(he=>he.id===I),et(d,I))};$.useEffect(()=>{const I=A_.current;if(I===null)return;A_.current=null;const he=document.querySelectorAll(Ysn),je=he[Math.min(I,he.length-1)];je?je.focus():hl()},[be,hl]);const Lo=$.useMemo(()=>{const he=r5(Te,be)!==""||oe.length>0,je=_||x?.message&&Sfe.test(x.message)?[{label:"Connect a provider",onClick:()=>SO.getState().openConnect()}]:[];return{message:x?.message,muted:x?.muted===!0,polite:x?.polite===!0,actions:[...x?.actions??[],...je],retry:x?.retry===!0,clear:x?.muted!==!0&&(x?.onClear!==void 0||he)}},[x,Te,be,oe,_]),hh=h7t(),CN=q("block text-body-sm",Z?"px-2 pb-1":"px-4 pb-2",uh!==null?"text-warning":"text-ink-muted"),z_=q("flex flex-wrap items-center gap-2 text-body-sm text-ink-muted",Z?"px-2 pb-1":"px-4 pb-2"),AN=k_&&Te.length>0,dRe=h.jsx("output",{className:q(Rr,"block pb-2",hh.issue.kind==="hidden"&&"hidden"),children:h.jsx(ton,{issue:hh.issue,onSignIn:hh.start,onCancel:hh.cancel,onDismiss:hh.dismiss,isSmallView:Z,onFocusComposer:()=>It.current?.focus()})}),dg=i3e(K),fRe=dg&&!l3e(dg,o3e(hh.issue))?h.jsx("output",{className:q(Rr,"block pb-2"),children:h.jsx(wrn,{access:dg,isSmallView:Z,onSwitchModel:K?.onCommand?()=>K.onCommand?.({name:"model",args:""}):void 0,onConnect:()=>SO.getState().openConnect({providerId:dg.provider})})}):null,zN=Me||!me&&!Ee&&!(t&&p),hRe=h.jsxs("form",{onSubmit:eRe,"data-chat-region":"composer","aria-label":tOe.composer,tabIndex:-1,className:"w-full",children:[h.jsx(VN,{fallback:null,children:h.jsx(Knn,{frontend:K?.frontend,askFrontend:K?.asks,runDetails:Qe,isSmallView:Z,askExpanded:F,onAskToggle:z,askOutcomes:M,onNote:le,onFocusComposer:()=>It.current?.focus()},d)}),!s3e(dg)&&dRe,fRe,a,o?.blocksInput&&o.placeholder&&!o.statedByNode&&Te.trim().length>0?h.jsx("p",{id:Ise,className:"mb-2 text-meta text-ink-muted",children:o.placeholder}):null,o?.node,Lo.message!==void 0&&h.jsxs("div",{role:Lo.polite?"status":"alert","data-composer-notice":!0,"data-composer-queued":x?.message===Ta.queuedSend?!0:void 0,className:q(Rr,"flex flex-wrap items-center gap-x-3 gap-y-1 text-body-sm",Z?"px-2 pb-1":"px-4 pb-2"),children:[h.jsxs("p",{className:q("flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1",Lo.muted?"text-ink-muted":"text-danger"),children:[!Lo.muted&&h.jsx("span",{className:"flex shrink-0 items-center pt-0.5",children:h.jsx(kp,{size:14,"aria-hidden":"true"})}),h.jsx("span",{className:q("min-w-0 break-words",!Lo.muted&&"font-medium"),children:Lo.message})]}),(Lo.retry||Lo.clear||Lo.actions.length>0)&&h.jsxs(h.Fragment,{children:[Lo.actions.map(I=>h.jsx(Xe,{type:"button",variant:"link",size:"sm",className:q("min-h-6 cursor-pointer text-body-sm underline"),onClick:I.onClick,children:I.label},I.label)),Lo.retry&&x?.onRetry&&h.jsx(Xe,{type:"button",variant:"link",size:"sm",className:q("min-h-6 cursor-pointer font-semibold text-body-sm underline"),onClick:()=>x.onRetry?.(),children:yCe}),Lo.clear&&x?.onClear&&h.jsx(Xe,{type:"button",variant:"link",size:"sm","aria-label":J("ui.chat.composer.clear_message"),className:q("min-h-6 cursor-pointer text-ink-dim text-body-sm underline"),onClick:()=>x.onClear?.(),children:vCe})]})]}),w&&h.jsx("output",{className:q(Rr,"block text-body-sm text-ink-muted",Z?"px-2 pb-1":"px-4 pb-2"),children:w}),c&&ye!==null&&h.jsx(jin,{sessionId:c,sessionStreaming:u,adoptQueueSupported:O,isSmallView:Z,onReturnFocus:()=>It.current?.focus()}),k?h.jsx("div",{className:q(Rr,Z?"px-2 pb-2":"px-4 pb-2"),children:k}):null,h.jsxs("div",{className:q(Rr,"relative w-full"),children:[h.jsx(gsn,{state:ot,onPick:__,onActionPick:P_}),h.jsx(Aan,{state:ka,onPick:wN}),h.jsx(Qon,{state:Hr,onPick:T_}),!H&&!ot.open&&!ka.open&&!Hr.open&&h.jsx(W6t,{visible:y,onClick:S,hasNewActivity:v}),h.jsx("output",{id:Use,className:q(Rr,C_?CN:"hidden"),children:C_}),AN&&h.jsx("output",{id:Wse,className:q(Rr,CN),children:Rsn}),l&&ci===null&&h.jsxs("output",{id:Nse,className:q(z_,Rr),children:[h.jsx("span",{className:"min-w-0",children:J("ui.chat.composer.secret_ask_notice")}),h.jsx(Xe,{type:"button",size:"sm",variant:"secondary","data-lo-ask-item-toggle":"",onClick:()=>l.onOpen(),children:J("ui.chat.composer.secret_ask_open")})]}),mN!==null&&ci===null&&h.jsx("output",{id:Xsn,className:q(z_,Rr),children:h.jsx("span",{className:"min-w-0",children:mN})}),ci!==null&&h.jsxs("fieldset",{ref:ob,tabIndex:-1,id:Esn,"aria-labelledby":Yse,"aria-busy":po,onKeyDown:I=>{I.key==="Escape"&&(I.preventDefault(),!po&&lb())},className:q("m-0 min-w-0 border-0 p-0",z_,Rr),children:[h.jsxs("span",{id:Yse,className:"min-w-0",children:[po?J("ui.chat.composer.secret_confirm_sending"):J("ui.chat.composer.secret_confirm_message"),h.jsx("span",{className:q("whitespace-nowrap",po&&"invisible"),"aria-hidden":po||void 0,children:` ${J("ui.chat.composer.secret_confirm_chars",{count:ci.value.length})}`})]}),h.jsx(Xe,{ref:$N,type:"button",size:"sm",disabled:po,onClick:I2e,children:l?.fillable?J("ui.chat.composer.secret_confirm_put"):J("ui.chat.composer.secret_confirm_put_multi")}),h.jsx(Xe,{type:"button",size:"sm",variant:"secondary",disabled:po,onClick:Z2e,children:J("ui.chat.composer.secret_confirm_send")}),h.jsx(Xe,{type:"button",size:"sm",variant:"ghost",disabled:po,onClick:lb,children:J("ui.chat.composer.secret_confirm_cancel")})]}),ia>0&&h.jsx("span",{id:Gse,className:"sr-only",children:ia===1?"1 reference points outside this session's working directory; the agent will ask you to approve it before reading.":`${ia} references point outside this session's working directory; the agent will ask you to approve them before reading.`}),i&&h.jsx("span",{id:Zse,className:"sr-only",children:J("ui.chat.composer.delivery_remedies_hint")}),h.jsxs("div",{"data-glass-region":"composer",className:q(Gsn,jN?void 0:Isn,Z?"gap-2 rounded-md p-2":"gap-3 rounded-frame p-4",Rr,jN&&"outline-dashed outline-2 outline-accent outline-offset-2"),"data-lo-composer-measure":"","data-tour-tag":"chat-input-textarea",children:[(be.length>0||oe.length>0)&&h.jsxs("div",{className:"max-h-[240px] shrink-0 overflow-y-auto",children:[be.length>0&&h.jsx(qU,{replies:be,onRemoveReply:ORe}),oe.length>0&&h.jsx(TZe,{attachments:oe.map(I=>I.path),onRemoveAttachment:I=>nRe(oe[I].id),disabled:un||me||Ee})]}),h.jsxs("div",{className:"relative isolate w-full",children:[h.jsx(Vrn,{text:Te,payloads:or.current,capture:Zn,fieldRef:It,mirrorRef:sg,isSmallView:Z}),h.jsx(Oan,{text:Te,spans:Vo.spans,resolved:Vo.resolved,fieldRef:It,isSmallView:Z}),h.jsx(Ian,{draft:Te,runs:ab,textareaRef:It,fieldClassName:GQ(Z),refused:un,children:h.jsx("textarea",{ref:It,"data-region-entry":!0,className:q(GQ(Z),"block",Z?"max-h-24":"max-h-28","resize-none overflow-y-auto bg-transparent",Kr?"text-transparent caret-ink":"text-ink","outline-none placeholder:text-ink-dim",o?.blocksInput?"read-only:text-ink-muted read-only:placeholder:text-ink-muted disabled:text-ink-disabled disabled:placeholder:text-ink-disabled":"read-only:text-ink-disabled read-only:placeholder:text-ink-disabled disabled:text-ink-disabled disabled:placeholder:text-ink-disabled"),placeholder:me?Ys.recording:QGe({unavailable:V,secretAnswer:k_,inputDisabled:un,awaitingAnswer:r,asideAttached:ye!==null,sendingUnsettled:lh||og,awaitingReply:n,stopping:Q?.stopping===!0,noProvider:_,idle:Ke,hostLine:o?.placeholder??null}),value:Te,onCompositionStart:()=>ib(!0),onCompositionEnd:()=>ib(!1),onChange:I=>{dl.current=!0;const he=I.target.value,je=I.target.selectionStart??he.length;Kn.current=null;const Je=m2t(qn.current,Te,he,je,"typing");Je.buffer!==he?(si.current=Je.caret,ji(Je.caret)):ji(je),Je.capture!==qn.current&&Ar(Je.capture),!Te&&Je.buffer&&g?.(),gr.current=Je.buffer,de(Je.capture,Je.buffer),sr(Je.buffer),Date.now()-Ii.current>=jsn&&x?.onDismiss?.()},onSelect:I=>{const he=I.target,je=si.current;if(je!==null){he.selectionStart===je&&(si.current=null);return}ji(he.selectionStart),Ar(Jh(qn.current,Te,he.selectionStart,"caret"))},onKeyDown:M2e,onPointerDown:()=>{OA=!0},onPaste:iRe,rows:1,readOnly:un,"aria-disabled":un||void 0,"aria-label":J("ui.chat.composer.message"),role:"combobox","aria-describedby":[o?o.id:null,o?.blocksInput&&o.placeholder&&!o.statedByNode&&Te.trim().length>0?Ise:null,C_?Use:null,AN?Wse:null,l&&ci===null?Nse:null,ia>0?Gse:null,V?rQe:null,i?Zse:null].filter(Boolean).join(" ")||void 0,"aria-expanded":ot.open||ka.open,"aria-controls":ot.open?ot.listId:ka.open?ka.listId:void 0,"aria-activedescendant":(ot.open?ot.activeDescendantId:ka.activeDescendantId)??void 0})}),h.jsx(Zrn,{small:Z,text:Te,payloads:or.current,capture:Zn,mirrorRef:sg,fieldRef:It,onClear:un?null:F2e,onControlUnmounted:hl})]}),me&&h.jsx(sfe,{isRecording:me}),Ee&&h.jsxs("div",{"data-transcribing-indicator":"",className:"mt-1 flex items-center gap-2 px-2 [min-height:1.5rem]",children:[h.jsx("span",{className:"font-medium text-body-sm text-ink-muted",children:J("ui.chat.composer.processing_audio")}),h.jsx(W2e,{})]}),h.jsxs("div",{className:"flex min-w-0 flex-nowrap items-center gap-x-2",children:[K&&h.jsx(VN,{fallback:null,children:h.jsx(pMe,{frontend:K.frontend,onCommand:K.onCommand,effortEntities:K.effortEntities,draft:K.draft,onOpenDraftPicker:K.onOpenDraftPicker,draftResolution:K.draftResolution,held:K.held,contextHeld:K.contextHeld,readingsDropped:K.readingsDropped,pendingModel:K.pendingModel,costChannels:K.costChannels,controlsThirdBox:H2e})}),h.jsxs("div",{className:"contents",children:[h.jsxs("div",{className:"flex min-w-0 items-center gap-1 shrink-0",children:[h.jsx(Yt,{content:J("ui.chat.composer.attach_file"),children:h.jsx("span",{children:h.jsx(Xe,{variant:"ghost",size:Z?"icon-sm":"icon",className:"text-ink-dim hover:bg-elevated hover:text-ink",onPointerDown:q_,onClick:rRe,"aria-label":J("ui.chat.composer.attach_file"),"data-tour-tag":"chat-input-attach-file-button",disabled:un||me||Ee,children:h.jsx(y9e,{"aria-hidden":"true"})})})}),ze!==void 0&&h.jsx(Ban,{ref:SN,currentWorkingDirectory:ze,writePath:C,pending:G,pendingAccepted:N,readOnlyReason:C?void 0:W??t2e})]}),h.jsxs("div",{className:"ml-auto flex order-3 items-center gap-1",children:[Me&&zN&&h.jsx("output",{"data-preparing-indicator":"",className:"shrink-0 font-medium text-body-sm text-ink-muted",children:Z?J("ui.chat.composer.starting"):J("ui.chat.composer.starting_recording")}),zN&&h.jsx(Yt,{content:Me?J("ui.chat.composer.starting_recording"):En?J("ui.chat.composer.start_recording_hint",{shortcut:uRe,pushToTalk:oA().label}):tr,children:h.jsx("span",{children:h.jsx(Xe,{variant:"ghost",size:Z?"icon-sm":"icon",className:"text-ink-dim hover:bg-elevated hover:text-ink",onPointerDown:q_,onClick:XN,"aria-label":J("ui.chat.composer.start_recording"),"aria-busy":Me||void 0,disabled:un||!En,children:Me?h.jsx(Go,{size:"sm"}):h.jsx(o9e,{"aria-hidden":"true"})})})}),me&&h.jsxs(h.Fragment,{children:[h.jsx(Yt,{content:J("ui.chat.composer.confirm_recording_hint"),children:h.jsx("span",{children:h.jsx(Xe,{variant:"ghost",size:Z?"icon-sm":"icon",className:"text-success hover:bg-success-wash hover:text-success",onClick:X_,"aria-label":J("ui.chat.composer.confirm_recording"),children:h.jsx(xu,{"aria-hidden":"true"})})})}),h.jsx(Yt,{content:J("ui.chat.composer.cancel_recording_hint"),children:h.jsx("span",{children:h.jsx(Xe,{variant:"ghost",size:Z?"icon-sm":"icon",className:"text-danger hover:bg-danger-wash hover:text-danger",onClick:E_,"aria-label":J("ui.chat.composer.cancel_recording"),children:h.jsx(ea,{"aria-hidden":"true"})})})})]}),_N&&h.jsx("span",{"aria-hidden":"true","data-interrupt-slot":"",className:q("pointer-events-none invisible flex items-center"),children:h.jsx(Xe,{variant:"danger",size:Z?"icon-sm":"icon",type:"button",tabIndex:-1,children:h.jsx(m1,{"aria-hidden":"true"})})}),Q?.active&&h.jsx(Yt,{content:J("ui.chat.composer.stop_work_hint"),children:h.jsx("span",{children:h.jsx(Xe,{variant:"danger",size:Z?"icon-sm":"icon",type:"button",onClick:Q.onStop,"aria-label":J("ui.chat.composer.stop"),"aria-keyshortcuts":"Escape","data-stopping":Q.stopping===!0?"true":void 0,"aria-busy":Q.stopping===!0?!0:void 0,className:q("data-[stopping]:border-danger data-[stopping]:text-ink data-[stopping]:bg-[color-mix(in_oklab,var(--color-danger-wash)_80%,var(--color-danger))]"),children:h.jsx(m1,{"aria-hidden":"true"})})})}),t&&p?h.jsx(Yt,{content:J("ui.chat.composer.stop_agent"),children:h.jsx("span",{children:h.jsx(Xe,{variant:"danger",size:Z?"icon-sm":"icon",type:"button",onClick:()=>m?.(p),"aria-label":J("ui.chat.composer.stop_agent"),children:h.jsx(m1,{"aria-hidden":"true"})})})}):!me&&!Ee&&h.jsx(Yt,{content:ye!==null&&!r?J("ui.chat.composer.ask_aside"):J("ui.chat.composer.send_message"),children:h.jsx("span",{children:h.jsx(Xe,{variant:"primary",size:Z?"icon-sm":"icon",type:"submit",onPointerDown:tRe,disabled:un||Og||!Te.trim()&&oe.length===0,className:"rounded-full disabled:bg-surface","aria-label":ye!==null&&!r?J("ui.chat.composer.ask_aside"):J("ui.chat.composer.send_message"),children:h.jsx(Nue,{"aria-hidden":"true"})})})})]})]})]})]})]}),_&&!St?h.jsx("div",{className:q("mt-2",Rr),children:h.jsx(Sin,{})}):null,(_||E)&&en?h.jsx("div",{className:q("mt-2",Rr),children:h.jsx("output",{className:"block text-body-sm text-ink-muted",children:E?"Choose a model for this conversation before sending.":"Connect a provider to send."})}):null]});return h.jsxs("div",{className:q(zde,"flex w-full flex-col items-center",pr?"grow":"shrink-0",te?void 0:sZe,Z?"pb-1 pt-0.5":"pb-4 pt-2"),"data-lo-composer-band":!0,ref:Wt,onDragOver:aRe,onDragLeave:oRe,onDrop:sRe,children:[h.jsx("div",{"data-lo-composer-splash":"",className:q("flex w-full flex-col items-center justify-center",pr?"grow":null),children:h.jsx("div",{ref:gn,className:q(dh?"flex w-full flex-col items-center gap-6 py-4":"hidden"),children:dh?h.jsxs(h.Fragment,{children:[h.jsx("span",{"data-lo-empty-mark":"",className:"contents",children:h.jsx(_sn,{className:"size-8",tone:"ink-muted"})}),_?null:h.jsx("h2",{className:"text-center text-ink text-title",children:J("ui.chat.composer.welcome")}),_?h.jsx("div",{className:q("w-full",Rr),children:h.jsx(win,{})}):h.jsxs("div",{className:q("flex flex-col gap-3",Rr),children:[h.jsx(Kan,{band:ut,splash:tn,foot:zn,suggestions:Ze,disabled:K2e,onRefusedPress:q_,onSelect:cRe,focusComposer:()=>It.current?.focus()}),h.jsx(Grn,{suspended:Te.trim().length>0,mentionsEnabled:se})]})]}):null})}),St?h.jsx("div",{className:q("mb-2 mt-2",Rr),children:h.jsx(bin,{selection:nt})}):null,h.jsx("div",{ref:nr,"data-lo-composer-foot":"",className:"w-full",children:hRe})]})}),Dsn=$.memo(Zsn);Dsn.displayName="MessageInput";const Y2e=1024,aS=1024*1024,pN=.85,Msn=new Set(["image/png","image/jpeg","image/webp"]),Vsn=[{maxEdge:Y2e,quality:.8},{maxEdge:768,quality:.7},{maxEdge:512,quality:.6}];function Lsn(e){const t=e.endsWith("==")?2:e.endsWith("=")?1:0;return Math.floor(e.length*3/4)-t}function Fsn(e){const t=Uint8Array.fromBase64;if(typeof t=="function")return t.call(Uint8Array,e);const n=atob(e),r=new Uint8Array(n.length);for(let i=0;i<n.length;i+=1)r[i]=n.charCodeAt(i);return r}function Bsn(e){const t=e.toBase64;if(typeof t=="function")return t.call(e);let n="";const r=32768;for(let i=0;i<e.length;i+=r)n+=String.fromCharCode(...e.subarray(i,i+r));return btoa(n)}async function Hsn(e,t,n,r,i){const a=Math.max(e.width,e.height),o=a>r?r/a:1,s=Math.max(1,Math.round(e.width*o)),l=Math.max(1,Math.round(e.height*o)),c=new OffscreenCanvas(s,l),u=c.getContext("2d");if(!u)return null;u.drawImage(e,0,0,s,l);const O=[],d=await c.convertToBlob({type:"image/png"}),f=new Uint8Array(await d.arrayBuffer());if(f.byteLength<=aS&&O.push({bytes:f,mime_type:"image/png"}),f.byteLength>aS||i<pN){const g=new OffscreenCanvas(s,l),y=g.getContext("2d");if(!y)return null;y.fillStyle="#ffffff",y.fillRect(0,0,s,l),y.drawImage(e,0,0,s,l);const v=await g.convertToBlob({type:"image/jpeg",quality:i}),S=new Uint8Array(await v.arrayBuffer());O.push({bytes:S,mime_type:"image/jpeg"}),f.byteLength>aS&&S.byteLength>f.byteLength&&O.push({bytes:f,mime_type:"image/png"})}let p=null,m=Number.POSITIVE_INFINITY;for(const g of O)g.bytes.byteLength<m&&(p=g,m=g.bytes.byteLength);return p?m>=n?t:{data_b64:Bsn(p.bytes),mime_type:p.mime_type}:null}async function Ksn(e){if(!Msn.has(e.mime_type)||typeof createImageBitmap!="function"||typeof OffscreenCanvas!="function")return null;try{return await createImageBitmap(new Blob([Fsn(e.data_b64)],{type:e.mime_type}))}catch{return null}}async function Jsn(e,t,n,r){const i=Lsn(e.data_b64);try{return Math.max(t.width,t.height)<=n&&i<=aS&&r>=pN?e:await Hsn(t,e,i,n,r)??e}catch{return e}}async function eln(e,t,n){if(!e.length)return e;const r=await Promise.all(e.map(i=>Ksn(i)));try{return await tln(e,r,t,n)}finally{for(const i of r)i?.close()}}async function tln(e,t,n,r){const i=(c,u)=>Promise.all(e.map((O,d)=>{const f=t[d];return f?Jsn(O,f,c,u):Promise.resolve(O)})),a=await i(Y2e,pN);if(r(a)<=n)return a;let o=e,s=r(e);const l=c=>{const u=r(c);return u<s&&(o=c,s=u),u};l(a);for(const c of Vsn){const u=await i(c.maxEdge,c.quality);if(l(u)<=n)return u}return o}const nln=/^data:(image\/(png|jpeg|gif|webp));base64,(.+)$/,rln=/^file:\/\//,iln={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp"};async function ffn(e,t){const n=[],r=[];for(const a of e){const o=nln.exec(a);if(o){n.push({data_b64:o[3],mime_type:o[1]});continue}const s=a.split(".").pop()?.toLowerCase()??"",l=iln[s];if(!l||!window.api?.readFile)continue;const c=await window.api.readFile(a.replace(rln,""),"base64");c.success?n.push({data_b64:c.data,mime_type:l}):r.push(a)}const i=Math.max(0,n.length-Nq);return{images:await eln(n.slice(0,Nq),HQ,a=>Ej(t,a)),unreadable:r,overflow:i}}function hfn(e){if(e.length===0)return null;const t=e.map(Ck);return t.length===1?`${t[0]} could not be read (it may have been moved or deleted), so this message was not sent. Attach it again, or remove it from the draft.`:`${t.join(", ")} could not be read (they may have been moved or deleted), so this message was not sent. Attach them again, or remove them from the draft.`}function pfn(e){if(e<=0)return null;const t=Nq,n=t+e;return e===1?`This draft carries ${n} images and one message carries up to ${t}, so this message was not sent. Remove the extra image, or send it in a second message.`:`This draft carries ${n} images and one message carries up to ${t}, so this message was not sent. Remove ${e} of them, or send them in a second message.`}function mfn(e){const t=e.trim();if(t.startsWith("="))return null;const n=t.toLowerCase();return n==="pause"||n==="resume"||n==="status"?n:null}function gfn(e){const t=e.trim();return t.startsWith("=")?t.slice(1).trimStart():t}function $fn(e,t){return e==="pause"?{text:"Aida is paused. She will not check in until you resume her.",kind:"success"}:e==="resume"?{text:"Aida is resumed. She will check in on her usual schedule.",kind:"success"}:{kind:"info",text:t.paused?"Aida is paused.":"Aida is active."}}function aln(e){return Io(e,"Aida's controls could not reach the backend.")}const yfn="The chief of staff is switched off on this install.",oln="aida_no_provider",sln="aida_disabled";function vfn(e,t){const n=e instanceof Ut?e.code:void 0;return n===sln?null:n===oln?{kind:"info",text:`${t} will say hello once an AI account is connected. Connect one from the chat to start.`}:{kind:"error",text:`${t}'s conversation could not be opened, so you are in a new chat instead. ${aln(e)}`}}function bfn(e,t){if(e.held===!0)return`${t} is already open in another window, so she will say hello there.`;const n=e.greeting_state==="delivered"||e.greeting_state==="skipped"||e.greeting_state==null&&e.greeted===!0;return e.paused&&!n?`${t} is paused, so she will say hello when you resume her: type /aida resume.`:null}function wfn(e){const t=e?.greeting_state;return t==null||t==="owed"}function lln(e){return e.eventKey===e.storeKey&&!e.focused}let Fse=!1;function Sfn(){if(Fse)return;Fse=!0;const e=an.persist?.getOptions?.()?.name??"conversation-input-store",t=n=>{lln({eventKey:n.key,storeKey:e,focused:document.hasFocus()})&&an.persist?.rehydrate?.()?.catch?.(()=>{})};window.addEventListener("storage",t)}export{Jln as $,rGe as A,uGe as B,jt as C,Ua as D,lt as E,El as F,An as G,Df as H,P as I,Rn as J,Qr as K,Xn as L,wn as M,Mk as N,Ev as O,Yr as P,Cr as Q,Lr as R,bs as S,d8 as T,wa as U,Bn as V,L9 as W,cr as X,_s as Y,Ut as Z,pv as _,Ri as a,kW as a$,Io as a0,Pln as a1,ecn as a2,R$ as a3,mi as a4,dW as a5,QW as a6,Rc as a7,Nr as a8,$De as a9,Ad as aA,Dsn as aB,vUe as aC,Dcn as aD,Nln as aE,Gln as aF,Sfn as aG,bun as aH,yun as aI,Yln as aJ,pj as aK,Of as aL,G9e as aM,uv as aN,Lln as aO,Ov as aP,MOn as aQ,Tl as aR,Mh as aS,$a as aT,jue as aU,mz as aV,vj as aW,ade as aX,Fln as aY,ro as aZ,LNt as a_,j$ as aa,sdn as ab,ldn as ac,Pke as ad,B8e as ae,Az as af,jj as ag,hv as ah,Nf as ai,KYe as aj,yfn as ak,ffn as al,hfn as am,Uce as an,pfn as ao,cun as ap,wln as aq,ar,kln as as,Ta as at,Qtt as au,zd as av,xCe as aw,bCe as ax,an as ay,Pm as az,icn as b,Rp as b$,i_e as b0,Bv as b1,s_e as b2,nfn as b3,VGt as b4,Vre as b5,Mre as b6,Q_e as b7,NW as b8,FP as b9,Sde as bA,Tun as bB,Run as bC,Bd as bD,fv as bE,ve as bF,ZAe as bG,ri as bH,pg as bI,a8e as bJ,x5 as bK,lke as bL,wG as bM,xG as bN,kue as bO,ccn as bP,yz as bQ,lun as bR,qm as bS,rUe as bT,p6e as bU,sG as bV,Dln as bW,Zln as bX,T6e as bY,lcn as bZ,su as b_,CYt as ba,jYt as bb,sm as bc,qYt as bd,EYt as be,iQ as bf,Kv as bg,UW as bh,AW as bi,Id as bj,rQ as bk,fGe as bl,zx as bm,Rr as bn,sZe as bo,zde as bp,m1 as bq,vln as br,Eun as bs,Kln as bt,eIe as bu,H8e as bv,Xun as bw,Gz as bx,iun as by,aIe as bz,oi as c,KAt as c$,zue as c0,Que as c1,dv as c2,pk as c3,Gue as c4,que as c5,Rue as c6,Fze as c7,Ajt as c8,Pue as c9,cUe as cA,JRt as cB,yZe as cC,Mz as cD,fQe as cE,zO as cF,_f as cG,oIe as cH,MAe as cI,WAe as cJ,TKt as cK,nd as cL,tun as cM,DYe as cN,Zc as cO,_Kt as cP,d_ as cQ,f_ as cR,HLt as cS,u_ as cT,cde as cU,Wln as cV,SYe as cW,Lue as cX,sO as cY,pGe as cZ,cke as c_,Zue as ca,Iue as cb,Jj as cc,IO as cd,Eue as ce,Xue as cf,Xm as cg,Si as ch,tue as ci,y6e as cj,w6e as ck,k6e as cl,S6e as cm,x6e as cn,hj as co,_6e as cp,uG as cq,P6e as cr,Q6e as cs,vde as ct,yde as cu,JGe as cv,_ln as cw,Tp as cx,Tln as cy,U0 as cz,Re as d,L9t as d$,ok as d0,kce as d1,e3e as d2,sk as d3,Xke as d4,DXt as d5,hk as d6,adn as d7,C7t as d8,xke as d9,Sc as dA,tUe as dB,hun as dC,i6t as dD,kd as dE,i7t as dF,K9e as dG,Iln as dH,cfn as dI,dGe as dJ,$Ge as dK,NCt as dL,nze as dM,Odn as dN,sf as dO,fPe as dP,Yx as dQ,Jx as dR,nie as dS,oYt as dT,qy as dU,J9t as dV,e8t as dW,K9t as dX,H9t as dY,B9t as dZ,F9t as d_,odn as da,I6t as db,T7 as dc,Xle as dd,qCe as de,Pon as df,ufn as dg,Uc as dh,Ofn as di,Ton as dj,Cke as dk,Uue as dl,QU as dm,grn as dn,AO as dp,sde as dq,pun as dr,Bqt as ds,ejt as dt,BOn as du,FK as dv,MK as dw,Jqt as dx,QJt as dy,Wi as dz,Cz as e,wcn as e$,NP as e0,E9t as e1,X9t as e2,V9t as e3,M9t as e4,f8e as e5,Mn as e6,fk as e7,Qdn as e8,Pdn as e9,OGe as eA,RYe as eB,vun as eC,k5 as eD,VJe as eE,eet as eF,lFe as eG,Y$ as eH,DJe as eI,Ape as eJ,oYe as eK,sYe as eL,DWe as eM,xj as eN,gy as eO,_z as eP,Gcn as eQ,hdn as eR,fdn as eS,qWe as eT,Ccn as eU,qcn as eV,jcn as eW,Ncn as eX,Ycn as eY,uWe as eZ,xcn as e_,wdn as ea,vdn as eb,rA as ec,mdn as ed,gdn as ee,$dn as ef,kdn as eg,_dn as eh,Sdn as ei,pdn as ej,xdn as ek,bdn as el,ydn as em,Uln as en,GCe as eo,YCe as ep,Fce as eq,Lce as er,uun as es,Oun as et,l8e as eu,dun as ev,fun as ew,mun as ex,$un as ey,nUe as ez,iPe as f,Nun as f$,Ls as f0,z0 as f1,kcn as f2,$cn as f3,SR as f4,Pcn as f5,_7 as f6,G6t as f7,W6t as f8,ddn as f9,zcn as fA,Xcn as fB,_We as fC,Wcn as fD,dWe as fE,Ecn as fF,sAt as fG,Qj as fH,yWe as fI,jce as fJ,ou as fK,Tdn as fL,YTe as fM,Rdn as fN,KOn as fO,u6t as fP,Pun as fQ,YAe as fR,ROe as fS,HWe as fT,_sn as fU,L9e as fV,Tue as fW,FZe as fX,KZe as fY,Iun as fZ,Zun as f_,_cn as fa,ple as fb,SS as fc,QWe as fd,Rcn as fe,V6t as ff,BAe as fg,dk as fh,wue as fi,JU as fj,WJ as fk,d0 as fl,vcn as fm,$Oe as fn,X9e as fo,Ucn as fp,Acn as fq,jAe as fr,ycn as fs,gOe as ft,Qcn as fu,bR as fv,Icn as fw,p9e as fx,YUe as fy,Scn as fz,yr as g,ms as g$,Yun as g0,Gun as g1,Mun as g2,iDe as g3,lfe as g4,Fun as g5,Eze as g6,sDe as g7,Dun as g8,fDe as g9,Vpe as gA,Lpe as gB,lOn as gC,UCe as gD,QA as gE,Tz as gF,AOe as gG,cNe as gH,Dv as gI,uQe as gJ,cQe as gK,co as gL,_n as gM,ZO as gN,Pt as gO,Ge as gP,ht as gQ,SOn as gR,Ti as gS,UM as gT,Nm as gU,Ro as gV,Yc as gW,dme as gX,cn as gY,Nn as gZ,gf as g_,Bun as ga,Vun as gb,HZe as gc,Gn as gd,Lun as ge,Sue as gf,aUe as gg,J8e as gh,scn as gi,ocn as gj,acn as gk,Vcn as gl,kj as gm,iAt as gn,dln as go,GCt as gp,Z9 as gq,cOn as gr,iOn as gs,gtt as gt,rOn as gu,G9 as gv,Hpe as gw,Y9 as gx,Kpe as gy,Fpe as gz,$te as h,o9e as h$,Zl as h0,hOn as h1,Mv as h2,NU as h3,GU as h4,Cx as h5,WU as h6,YU as h7,IU as h8,n9e as h9,_On as hA,XOn as hB,qOn as hC,COn as hD,zOn as hE,vOn as hF,bOn as hG,$On as hH,Nk as hI,EOn as hJ,Dk as hK,yOn as hL,YSe as hM,wU as hN,fse as hO,Hue as hP,oI as hQ,Z8e as hR,b8e as hS,Rrn as hT,i2e as hU,TZe as hV,sfe as hW,W2e as hX,y9e as hY,ode as hZ,oA as h_,fs as ha,jge as hb,rat as hc,XO as hd,nat as he,Fn as hf,Gt as hg,Zf as hh,Ki as hi,Er as hj,zi as hk,tu as hl,rw as hm,KS as hn,Ik as ho,wOn as hp,Tu as hq,AOn as hr,TOn as hs,Xot as ht,xOn as hu,QOn as hv,gOn as hw,ROn as hx,pOn as hy,mOn as hz,Jdn as i,uUe as i$,Nue as i0,q$ as i1,ZOn as i2,$8e as i3,y8e as i4,qxe as i5,Exe as i6,aOn as i7,NS as i8,Sk as i9,fFe as iA,oBe as iB,Dze as iC,Wue as iD,Ck as iE,Mpe as iF,$tt as iG,xtt as iH,mle as iI,uk as iJ,mXe as iK,VY as iL,TXe as iM,ECe as iN,AYe as iO,Ez as iP,LAe as iQ,Hcn as iR,zqt as iS,wde as iT,VNe as iU,Kcn as iV,Dce as iW,zln as iX,Xln as iY,Rln as iZ,BY as i_,Cfe as ia,K5 as ib,YBe as ic,NBe as id,jfe as ie,Hun as ig,che as ih,Sa as ii,YO as ij,wv as ik,Jun as il,qMe as im,tHe as io,pet as ip,qS as iq,p9 as ir,s9 as is,Fj as it,lhe as iu,DMe as iv,_Me as iw,GMe as ix,bD as iy,xBe as iz,ul as j,qln as j$,Eln as j0,Ocn as j1,Rze as j2,ucn as j3,dcn as j4,$Ue as j5,Wjt as j6,Lz as j7,$v as j8,xU as j9,yk as jA,Lcn as jB,sNe as jC,Fcn as jD,Mcn as jE,nDe as jF,lfn as jG,Wun as jH,oZe as jI,nI as jJ,nde as jK,hle as jL,fle as jM,yYe as jN,run as jO,M3t as jP,MQe as jQ,nrn as jR,t2e as jS,rfn as jT,rg as jU,mfn as jV,$fn as jW,aln as jX,gfn as jY,hln as jZ,pln as j_,zU as ja,Njt as jb,oOn as jc,ZXt as jd,sOn as je,_ue as jf,Ban as jg,Zcn as jh,X$ as ji,czt as jj,Lke as jk,j5 as jl,_m as jm,ja as jn,EGe as jo,gun as jp,gGe as jq,ndn as jr,rdn as js,idn as jt,Yue as ju,ncn as jv,sUe as jw,Pr as jx,zun as jy,fln as jz,Fdn as k,g9e as k$,G7e as k0,jln as k1,Aln as k2,Cln as k3,r2e as k4,JQ as k5,qun as k6,Aun as k7,jun as k8,Cun as k9,yln as kA,gln as kB,ofn as kC,Bcn as kD,UUe as kE,lCe as kF,WUe as kG,NUe as kH,gcn as kI,mcn as kJ,WNe as kK,UNe as kL,VOe as kM,pcn as kN,Yce as kO,oOe as kP,fcn as kQ,Gce as kR,mCe as kS,MY as kT,hcn as kU,bln as kV,sfn as kW,LWe as kX,FOn as kY,afn as kZ,tS as k_,sun as ka,Gke as kb,Aqt as kc,cv as kd,SCe as ke,Jue as kf,rcn as kg,nz as kh,SUe as ki,$ln as kj,rZe as kk,iZe as kl,Uun as km,bcn as kn,Tcn as ko,lAt as kp,ifn as kq,mln as kr,Ice as ks,dfn as kt,LOn as ku,PCe as kv,ck as kw,xln as kx,Qln as ky,s4e as kz,Bdn as l,Fi as l$,SO as l0,eun as l1,rYe as l2,Sln as l3,Jcn as l4,BYe as l5,h7t as l6,$ke as l7,Ddn as l8,JOn as l9,EP as lA,Ndn as lB,Wdn as lC,zdn as lD,$z as lE,l2e as lF,zke as lG,qj as lH,wfn as lI,bfn as lJ,vfn as lK,t6t as lL,Tke as lM,_ke as lN,rIe as lO,wJ as lP,cdn as lQ,udn as lR,_un as lS,XYe as lT,EYe as lU,nun as lV,aun as lW,qGe as lX,oun as lY,Bln as lZ,bAe as l_,tdn as la,wke as lb,yu as lc,edn as ld,cGe as le,yke as lf,Cdn as lg,Mdn as lh,Vdn as li,Adn as lj,Ldn as lk,mk as ll,f7t as lm,EXe as ln,Lrn as lo,Ydn as lp,Gdn as lq,b7t as lr,qdn as ls,yAt as lt,Edn as lu,jdn as lv,mAt as lw,Udn as lx,Zdn as ly,Idn as lz,Kdn as m,VOn as m0,Xdn as m1,HOn as m2,u6e as m3,I7t as m4,xun as m5,wun as m6,Sun as m7,bg as m8,Qun as m9,Vln as ma,tcn as mb,g1 as mc,kun as md,Hln as me,nOn as mf,DOn as mg,tfn as n,Hdn as o,em as p,efn as q,Kd as r,Nx as s,WP as t,cc as u,nQ as v,OW as w,Ry as x,cPe as y,D9t as z};
975
+ `)?1:0,Mt=vO(Te,he.start,he.end+On,je),rr=je.endsWith('"')?Mt.caret-1:Mt.caret;si.current=rr,sr(Mt.text),ji(rr),ka.remember(I.path),ka.close()},[Te,Br,ka,sr,un]),T_=$.useCallback(I=>{if(un||!Hr.token)return;const he=ion(Te,Hr.token,I.name);Hr.close(),si.current=he.caret,sr(he.text),ji(he.caret)},[Te,Hr,sr,un]),D2e=$.useCallback(I=>{const he=Kn.current;return he===null||!(I.metaKey||I.ctrlKey)||I.altKey||I.shiftKey||I.key.toLowerCase()!=="z"?!1:(Kn.current=null,si.current=he.caret,he.plain>0&&mr({chars:he.plain,over:he.text}),sr(he.text),ji(he.caret),!0)},[mr,sr]),M2e=$.useCallback(I=>{if(un)return;if(kt(I)){I.preventDefault();return}if(I.key==="Escape"&&ci!==null){if(I.preventDefault(),po)return;lb();return}if(L2e(I)){I.preventDefault();return}if(D2e(I)){I.preventDefault();return}if(jan(I,ka,wN)){I.preventDefault();return}if(bsn(I,ot,__,bN)){I.preventDefault();return}if(kon(I,Hr,T_)){I.preventDefault();return}if(ye!==null&&I.key==="Escape"){I.preventDefault(),Uj(c??"");return}if(ye!==null&&XIe(I)){const Je=ye.turns.at(-1),On=Je?Pr.getState().streams[Je.asideId]:void 0;if(!Je||ye.queued!==void 0||!_de(On,u,O))return;I.preventDefault();const Mt=c??"",rr=Date.now(),Zr=qIe(_e.current,Je.asideId,rr);if(Zr==="arm"){_e.current={turnId:Je.asideId,at:rr},Pr.getState().setAsideNotice(Mt,CI(Uq));return}if(Zr==="ignore")return;_e.current=null,kde(Mt).catch(()=>{});return}if(I.key==="Backspace"||I.key==="Delete"){const Je=Lin(Br,I.key==="Backspace"?"back":"forward",Vo.spans,Vo.resolved);if(Je&&!I.nativeEvent.isComposing){const On=vO(Te,Je.start,Je.end,"");si.current=On.caret,ji(On.caret),sr(On.text),I.preventDefault();return}}const he=It.current,je=Wsn();if(je&&bUe(I,{value:Te,selectionStart:he?.selectionStart??null,selectionEnd:he?.selectionEnd??null})){je.focus(),I.preventDefault();return}if(Og&&I.key==="Enter"&&!I.shiftKey&&!I.nativeEvent.isComposing){I.preventDefault(),cb();return}if(I.key==="Enter"&&!I.shiftKey&&!I.nativeEvent.isComposing){const Je=li(Te,Br);if(Je.kind!=="send"){I.preventDefault(),ug(Je,Te,Br);return}if(sb(Te)){I.preventDefault();return}}rb(I)},[ot,__,bN,Hr,T_,sb,rb,kt,ci,lb,li,ug,Te,Br,un,ye,c,u,O]),SN=$.useRef(null),hl=$.useCallback(I=>{OA=!1,It.current?.focus({preventScroll:I?.preventScroll===!0})},[It]),V2e=$.useCallback(()=>{oOe(Te)!==null&&sr("")},[Te,sr]);$.useImperativeHandle(Le,()=>({focusInput:hl,openWorkingDirectoryMenu:()=>{SN.current?.openMenu()},submitNow:()=>{sb(Te)||ch()},consumeApprovalAnswerDraft:V2e}));const xN=$.useCallback(()=>It.current,[It]);$.useEffect(()=>ZWe(hl,xN),[hl,xN]);const pl=$.useRef(null),QN=$.useRef(Te);$.useLayoutEffect(()=>{QN.current=Te},[Te]);const kN=$.useCallback(I=>{pl.current===I&&(pl.current=null,or.current.delete(I.index))},[]),ub=$.useCallback(I=>{if(pl.current!==I)return!1;const he=A2t({buffer:QN.current,cleared:I.cleared});return he?(or.current.set(I.index,I.payload),pl.current===I&&(pl.current=null),I.toastId!==null&&U0(I.toastId),ue({capture:Jh(qn.current,he.buffer,he.caret,"arrival"),buffer:he.buffer,caret:he.caret}),$n(null),!0):!1},[ue,$n]);$.useLayoutEffect(()=>{const I=pl.current;I!==null&&I.cleared.buffer!==Te&&(I.toastId!==null&&U0(I.toastId),kN(I))},[Te,kN]);const L2e=$.useCallback(I=>{const he=pl.current;return he===null||!(I.metaKey||I.ctrlKey)||I.altKey||I.shiftKey||I.key.toLowerCase()!=="z"?!1:(ub(he),!0)},[ub]),PN=$.useCallback(I=>{ub(I)&&hl()},[hl,ub]),F2e=$.useCallback(I=>{if(un)return;const he=or.current.get(I);if(!he)return;const je=C2t({buffer:Te,payload:he});if(!je.cleared)return;const Je=pl.current;Je&&(pl.current=null,or.current.delete(Je.index),Je.toastId!==null&&U0(Je.toastId));const On={index:I,payload:he,cleared:je,toastId:null};pl.current=On,ue({capture:Jh(qn.current,je.buffer,je.caret,"arrival"),buffer:je.buffer,caret:je.caret}),$n({key:he.key,index:I,over:je.buffer}),On.toastId=pg(q2t(I),{action:{label:E2t,onClick:()=>PN(On)}}),hl()},[ue,hl,un,Te,$n,PN]),B2e=trn(!!Q?.active),_N=b&&!Q?.active&&(B2e.held||me)&&!(t&&p),H2e=!!Q?.active||_N,K2e=un||me||Ee||Te.trim().length>0;$.useEffect(()=>{const I=It.current;I&&(I.style.height="auto",I.style.height=`${I.scrollHeight}px`)},[Te,It,me,Ee]);const TN=$.useRef(!1);$.useEffect(()=>{const I=me||Ee,he=TN.current&&!I;if(TN.current=I,!D&&!he||un||I)return;const je=document.activeElement;!(je&&(je.tagName==="INPUT"||je.tagName==="TEXTAREA"))&&!_&&It.current?.focus({preventScroll:!0})},[D,un,me,Ee,It,_]),$.useEffect(()=>{window.electron.ipcRenderer.invoke("get-platform-info").then(I=>{xa(I.platform)}).catch(I=>{console.error("Failed to get platform info:",I)})},[]);const js=$.useRef(null),J2e=250,RN=$.useRef(Ne);$.useEffect(()=>{RN.current=Ne}),$.useEffect(()=>(fse("message-input",me||Me),()=>fse("message-input",!1)),[me,Me]),$.useEffect(()=>{RN.current?.(me)},[me]);const Au=$.useCallback(I=>{gt(!1);const he=hr.current;if(!he)return;const je=js.current?.startedAt??null,Je=je===null?Number.POSITIVE_INFINITY:performance.now()-je;if(js.current=null,he.state==="inactive"){Se(!1);return}(I==="abort"||Je<J2e)&&(he.onstop=()=>{if(he.stream)for(const On of he.stream.getTracks())On.stop();pt(null),Gr.current=[]}),he.stop(),Se(!1)},[]);$.useEffect(()=>()=>{const I=js.current!==null;js.current=null;const he=hr.current;if(he&&he.state!=="inactive"){Au("abort");return}I&&gt(!1)},[Au]);const R_=$.useCallback((I="release")=>{const he=js.current;if(he){if(he.startedAt===null){js.current=null,gt(!1);return}Au(I)}},[Au]),XN=$.useCallback(async()=>{if(!(un||!En)&&!js.current)if(navigator?.mediaDevices?.getUserMedia){const I={startedAt:null};js.current=I,gt(!0);try{const he=await navigator.mediaDevices.getUserMedia({audio:!0});if(js.current!==I){for(const je of he.getTracks())je.stop();return}hr.current=new MediaRecorder(he),Gr.current=[],hr.current.ondataavailable=je=>{Gr.current.push(je.data)},hr.current.onstop=()=>{const je=new Blob(Gr.current,{type:"audio/webm"});pt(je);for(const Je of he.getTracks())Je.stop()},hr.current.start(),I.startedAt=performance.now(),gt(!1),Se(!0),pt(null)}catch(he){if(js.current!==I)return;js.current=null,gt(!1),console.error("Error accessing microphone:",he),mi("Error accessing microphone. Please ensure microphone permissions are granted.")}}else console.error("This runtime exposes no MediaRecorder"),mi("Dictation is not available on this device.")},[En,un]),X_=$.useCallback(()=>{me&&Au("release")},[me,Au]),E_=$.useCallback(()=>{me&&Au("abort")},[me,Au]);$.useEffect(()=>{if(!me&&!Me)return;const I=he=>{if(me){he.key==="Enter"?(he.preventDefault(),X_()):he.key==="Escape"&&(he.preventDefault(),E_());return}he.key==="Escape"&&(he.preventDefault(),R_("abort"),gt(!1))};return window.addEventListener("keydown",I),()=>{window.removeEventListener("keydown",I)}},[me,Me,X_,E_,R_]);const EN=$.useCallback(async()=>{if(Rt)try{xt(!0);const I=await Hue.createTranscription(Nf.baseUrl,{file:new File([Rt],"recording.webm",{type:"audio/webm"})});if(I.result?.text){const he=I.result?.text||"";oh.current=!0,ra(he)}else Tp(Z8e);pt(null)}catch(I){console.error("Error transcribing audio:",I),mi(b8e(I))}finally{xt(!1)}},[Rt,ra]);$.useEffect(()=>{Rt&&EN()},[Rt,EN]);const qN=$.useRef(!0);$.useEffect(()=>{if(typeof IntersectionObserver>"u")return;const I=It.current;if(I===null)return;const he=new IntersectionObserver(je=>{const Je=je[je.length-1];Je!==void 0&&(qN.current=Je.isIntersecting)});return he.observe(I),()=>he.disconnect()},[It]),Rrn("message-input",i2e.MESSAGE_INPUT,{start:XN,stop:R_},()=>!!(!un&&!me&&!Ee&&En&&qN.current));const eRe=I=>{if(I.preventDefault(),un||_)return;if(E){cb();return}if(!Te.trim()&&oe.length===0||ft())return;const he=li(Te,Br);if(he.kind!=="send"){ug(he,Te,Br);return}sb(Te)||ch()},q_=$.useCallback(I=>{un&&I.preventDefault()},[un]),tRe=$.useCallback(I=>{!un&&!Og||(I.preventDefault(),Og&&!un&&cb())},[un,Og,cb]),nRe=I=>{d&&ce(d,I)},rRe=async()=>{const I=await window.electron.ipcRenderer.invoke("show-open-dialog",{properties:["openFile","multiSelections"]});if(!I.canceled&&I.filePaths.length>0&&d)for(const he of I.filePaths)ae(d,{id:fs(),path:q$(he)})},iRe=I=>{if(un)return;const he=I.clipboardData?.getData("text/plain")??"";if(he&&qn.current.arm!==null){const Je=I.currentTarget,On=v2t({capture:qn.current,buffer:Te,caret:Je.selectionEnd??Te.length,selection:{start:Je.selectionStart??Te.length,end:Je.selectionEnd??Te.length},pasted:he,index:qi.current,taken:cg()});if(On){I.preventDefault(),ue(On),mr(null);return}}he&&(yt.current=O2t(he));const je=I.clipboardData?.items;if(je){for(let Je=0;Je<je.length;Je++)if(je[Je].type.indexOf("image")!==-1||je[Je].kind==="file"){const On=je[Je].getAsFile();if(On){const Mt=new FileReader;Mt.onload=rr=>{rr.target?.result&&d&&ae(d,{id:fs(),path:rr.target.result})},Mt.readAsDataURL(On)}}}},aRe=I=>{un||I.dataTransfer?.types.includes("Files")&&(I.preventDefault(),I.stopPropagation(),I.dataTransfer.dropEffect="copy",j_(!0))},oRe=I=>{I.currentTarget.contains(I.relatedTarget)||j_(!1)},sRe=I=>{if(j_(!1),un)return;const he=I.dataTransfer?.files;!he||he.length===0||(I.preventDefault(),I.stopPropagation(),d&&lRe(d,Array.from(he)))},lRe=async(I,he)=>{for(const je of he){const Je=window.api?.getPathForFile?window.api.getPathForFile(je):"";if(Je){ae(I,{id:fs(),path:q$(Je)});continue}const On=await Usn(je);On&&ae(I,{id:fs(),path:On})}},[jN,j_]=$.useState(!1),cRe=I=>{un||(Te||g?.(),si.current=I.length,sr(I),ji(I.length),It.current?.focus())},C_=ql(Zn)?Zn.value!==""?G2t:Ft?I2t:Z2t:j2t({unredacted:uh!==null?D2t(uh,Qn(Te)?bxe:void 0):null,armed:Zn.arm!==null&&mxe(Te,Te.length)!==null,cleared:mc===null?null:{key:mc.key,index:mc.index},undoCap:A2e(Ia==="darwin")}),uRe=$.useMemo(()=>Ia==="darwin"?"Cmd+Shift+S":"Ctrl+Shift+S",[Ia]),A_=$.useRef(null),ORe=I=>{d&&(A_.current=be.findIndex(he=>he.id===I),et(d,I))};$.useEffect(()=>{const I=A_.current;if(I===null)return;A_.current=null;const he=document.querySelectorAll(Ysn),je=he[Math.min(I,he.length-1)];je?je.focus():hl()},[be,hl]);const Lo=$.useMemo(()=>{const he=r5(Te,be)!==""||oe.length>0,je=_||x?.message&&Sfe.test(x.message)?[{label:"Connect a provider",onClick:()=>SO.getState().openConnect()}]:[];return{message:x?.message,muted:x?.muted===!0,polite:x?.polite===!0,actions:[...x?.actions??[],...je],retry:x?.retry===!0,clear:x?.muted!==!0&&(x?.onClear!==void 0||he)}},[x,Te,be,oe,_]),hh=h7t(),CN=q("block text-body-sm",Z?"px-2 pb-1":"px-4 pb-2",uh!==null?"text-warning":"text-ink-muted"),z_=q("flex flex-wrap items-center gap-2 text-body-sm text-ink-muted",Z?"px-2 pb-1":"px-4 pb-2"),AN=k_&&Te.length>0,dRe=h.jsx("output",{className:q(Rr,"block pb-2",hh.issue.kind==="hidden"&&"hidden"),children:h.jsx(ton,{issue:hh.issue,onSignIn:hh.start,onCancel:hh.cancel,onDismiss:hh.dismiss,isSmallView:Z,onFocusComposer:()=>It.current?.focus()})}),dg=i3e(K),fRe=dg&&!l3e(dg,o3e(hh.issue))?h.jsx("output",{className:q(Rr,"block pb-2"),children:h.jsx(wrn,{access:dg,isSmallView:Z,onSwitchModel:K?.onCommand?()=>K.onCommand?.({name:"model",args:""}):void 0,onConnect:()=>SO.getState().openConnect({providerId:dg.provider})})}):null,zN=Me||!me&&!Ee&&!(t&&p),hRe=h.jsxs("form",{onSubmit:eRe,"data-chat-region":"composer","aria-label":tOe.composer,tabIndex:-1,className:"w-full",children:[h.jsx(VN,{fallback:null,children:h.jsx(Knn,{frontend:K?.frontend,askFrontend:K?.asks,runDetails:Qe,isSmallView:Z,askExpanded:F,onAskToggle:z,askOutcomes:M,onNote:le,onFocusComposer:()=>It.current?.focus()},d)}),!s3e(dg)&&dRe,fRe,a,o?.blocksInput&&o.placeholder&&!o.statedByNode&&Te.trim().length>0?h.jsx("p",{id:Ise,className:"mb-2 text-meta text-ink-muted",children:o.placeholder}):null,o?.node,Lo.message!==void 0&&h.jsxs("div",{role:Lo.polite?"status":"alert","data-composer-notice":!0,"data-composer-queued":x?.message===Ta.queuedSend?!0:void 0,className:q(Rr,"flex flex-wrap items-center gap-x-3 gap-y-1 text-body-sm",Z?"px-2 pb-1":"px-4 pb-2"),children:[h.jsxs("p",{className:q("flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1",Lo.muted?"text-ink-muted":"text-danger"),children:[!Lo.muted&&h.jsx("span",{className:"flex shrink-0 items-center pt-0.5",children:h.jsx(kp,{size:14,"aria-hidden":"true"})}),h.jsx("span",{className:q("min-w-0 break-words",!Lo.muted&&"font-medium"),children:Lo.message})]}),(Lo.retry||Lo.clear||Lo.actions.length>0)&&h.jsxs(h.Fragment,{children:[Lo.actions.map(I=>h.jsx(Xe,{type:"button",variant:"link",size:"sm",className:q("min-h-6 cursor-pointer text-body-sm underline"),onClick:I.onClick,children:I.label},I.label)),Lo.retry&&x?.onRetry&&h.jsx(Xe,{type:"button",variant:"link",size:"sm",className:q("min-h-6 cursor-pointer font-semibold text-body-sm underline"),onClick:()=>x.onRetry?.(),children:yCe}),Lo.clear&&x?.onClear&&h.jsx(Xe,{type:"button",variant:"link",size:"sm","aria-label":J("ui.chat.composer.clear_message"),className:q("min-h-6 cursor-pointer text-ink-dim text-body-sm underline"),onClick:()=>x.onClear?.(),children:vCe})]})]}),w&&h.jsx("output",{className:q(Rr,"block text-body-sm text-ink-muted",Z?"px-2 pb-1":"px-4 pb-2"),children:w}),c&&ye!==null&&h.jsx(jin,{sessionId:c,sessionStreaming:u,adoptQueueSupported:O,isSmallView:Z,onReturnFocus:()=>It.current?.focus()}),k?h.jsx("div",{className:q(Rr,Z?"px-2 pb-2":"px-4 pb-2"),children:k}):null,h.jsxs("div",{className:q(Rr,"relative w-full"),children:[h.jsx(gsn,{state:ot,onPick:__,onActionPick:P_}),h.jsx(Aan,{state:ka,onPick:wN}),h.jsx(Qon,{state:Hr,onPick:T_}),!H&&!ot.open&&!ka.open&&!Hr.open&&h.jsx(W6t,{visible:y,onClick:S,hasNewActivity:v}),h.jsx("output",{id:Use,className:q(Rr,C_?CN:"hidden"),children:C_}),AN&&h.jsx("output",{id:Wse,className:q(Rr,CN),children:Rsn}),l&&ci===null&&h.jsxs("output",{id:Nse,className:q(z_,Rr),children:[h.jsx("span",{className:"min-w-0",children:J("ui.chat.composer.secret_ask_notice")}),h.jsx(Xe,{type:"button",size:"sm",variant:"secondary","data-lo-ask-item-toggle":"",onClick:()=>l.onOpen(),children:J("ui.chat.composer.secret_ask_open")})]}),mN!==null&&ci===null&&h.jsx("output",{id:Xsn,className:q(z_,Rr),children:h.jsx("span",{className:"min-w-0",children:mN})}),ci!==null&&h.jsxs("fieldset",{ref:ob,tabIndex:-1,id:Esn,"aria-labelledby":Yse,"aria-busy":po,onKeyDown:I=>{I.key==="Escape"&&(I.preventDefault(),!po&&lb())},className:q("m-0 min-w-0 border-0 p-0",z_,Rr),children:[h.jsxs("span",{id:Yse,className:"min-w-0",children:[po?J("ui.chat.composer.secret_confirm_sending"):J("ui.chat.composer.secret_confirm_message"),h.jsx("span",{className:q("whitespace-nowrap",po&&"invisible"),"aria-hidden":po||void 0,children:` ${J("ui.chat.composer.secret_confirm_chars",{count:ci.value.length})}`})]}),h.jsx(Xe,{ref:$N,type:"button",size:"sm",disabled:po,onClick:I2e,children:l?.fillable?J("ui.chat.composer.secret_confirm_put"):J("ui.chat.composer.secret_confirm_put_multi")}),h.jsx(Xe,{type:"button",size:"sm",variant:"secondary",disabled:po,onClick:Z2e,children:J("ui.chat.composer.secret_confirm_send")}),h.jsx(Xe,{type:"button",size:"sm",variant:"ghost",disabled:po,onClick:lb,children:J("ui.chat.composer.secret_confirm_cancel")})]}),ia>0&&h.jsx("span",{id:Gse,className:"sr-only",children:ia===1?"1 reference points outside this session's working directory; the agent will ask you to approve it before reading.":`${ia} references point outside this session's working directory; the agent will ask you to approve them before reading.`}),i&&h.jsx("span",{id:Zse,className:"sr-only",children:J("ui.chat.composer.delivery_remedies_hint")}),h.jsxs("div",{"data-glass-region":"composer",className:q(Gsn,jN?void 0:Isn,Z?"gap-2 rounded-md p-2":"gap-3 rounded-frame p-4",Rr,jN&&"outline-dashed outline-2 outline-accent outline-offset-2"),"data-lo-composer-measure":"","data-tour-tag":"chat-input-textarea",children:[(be.length>0||oe.length>0)&&h.jsxs("div",{className:"max-h-[240px] shrink-0 overflow-y-auto",children:[be.length>0&&h.jsx(qU,{replies:be,onRemoveReply:ORe}),oe.length>0&&h.jsx(TZe,{attachments:oe.map(I=>I.path),onRemoveAttachment:I=>nRe(oe[I].id),disabled:un||me||Ee})]}),h.jsxs("div",{className:"relative isolate w-full",children:[h.jsx(Vrn,{text:Te,payloads:or.current,capture:Zn,fieldRef:It,mirrorRef:sg,isSmallView:Z}),h.jsx(Oan,{text:Te,spans:Vo.spans,resolved:Vo.resolved,fieldRef:It,isSmallView:Z}),h.jsx(Ian,{draft:Te,runs:ab,textareaRef:It,fieldClassName:GQ(Z),refused:un,children:h.jsx("textarea",{ref:It,"data-region-entry":!0,className:q(GQ(Z),"block",Z?"max-h-24":"max-h-28","resize-none overflow-y-auto bg-transparent",Kr?"text-transparent caret-ink":"text-ink","outline-none placeholder:text-ink-dim",o?.blocksInput?"read-only:text-ink-muted read-only:placeholder:text-ink-muted disabled:text-ink-disabled disabled:placeholder:text-ink-disabled":"read-only:text-ink-disabled read-only:placeholder:text-ink-disabled disabled:text-ink-disabled disabled:placeholder:text-ink-disabled"),placeholder:me?Ys.recording:QGe({unavailable:V,secretAnswer:k_,inputDisabled:un,awaitingAnswer:r,asideAttached:ye!==null,sendingUnsettled:lh||og,awaitingReply:n,stopping:Q?.stopping===!0,noProvider:_,idle:Ke,hostLine:o?.placeholder??null}),value:Te,onCompositionStart:()=>ib(!0),onCompositionEnd:()=>ib(!1),onChange:I=>{dl.current=!0;const he=I.target.value,je=I.target.selectionStart??he.length;Kn.current=null;const Je=m2t(qn.current,Te,he,je,"typing");Je.buffer!==he?(si.current=Je.caret,ji(Je.caret)):ji(je),Je.capture!==qn.current&&Ar(Je.capture),!Te&&Je.buffer&&g?.(),gr.current=Je.buffer,de(Je.capture,Je.buffer),sr(Je.buffer),Date.now()-Ii.current>=jsn&&x?.onDismiss?.()},onSelect:I=>{const he=I.target,je=si.current;if(je!==null){he.selectionStart===je&&(si.current=null);return}ji(he.selectionStart),Ar(Jh(qn.current,Te,he.selectionStart,"caret"))},onKeyDown:M2e,onPointerDown:()=>{OA=!0},onPaste:iRe,rows:1,readOnly:un,"aria-disabled":un||void 0,"aria-label":J("ui.chat.composer.message"),role:"combobox","aria-describedby":[o?o.id:null,o?.blocksInput&&o.placeholder&&!o.statedByNode&&Te.trim().length>0?Ise:null,C_?Use:null,AN?Wse:null,l&&ci===null?Nse:null,ia>0?Gse:null,V?rQe:null,i?Zse:null].filter(Boolean).join(" ")||void 0,"aria-expanded":ot.open||ka.open,"aria-controls":ot.open?ot.listId:ka.open?ka.listId:void 0,"aria-activedescendant":(ot.open?ot.activeDescendantId:ka.activeDescendantId)??void 0})}),h.jsx(Zrn,{small:Z,text:Te,payloads:or.current,capture:Zn,mirrorRef:sg,fieldRef:It,onClear:un?null:F2e,onControlUnmounted:hl})]}),me&&h.jsx(sfe,{isRecording:me}),Ee&&h.jsxs("div",{"data-transcribing-indicator":"",className:"mt-1 flex items-center gap-2 px-2 [min-height:1.5rem]",children:[h.jsx("span",{className:"font-medium text-body-sm text-ink-muted",children:J("ui.chat.composer.processing_audio")}),h.jsx(W2e,{})]}),h.jsxs("div",{className:"flex min-w-0 flex-nowrap items-center gap-x-2",children:[K&&h.jsx(VN,{fallback:null,children:h.jsx(pMe,{frontend:K.frontend,onCommand:K.onCommand,effortEntities:K.effortEntities,draft:K.draft,onOpenDraftPicker:K.onOpenDraftPicker,draftResolution:K.draftResolution,held:K.held,contextHeld:K.contextHeld,readingsDropped:K.readingsDropped,pendingModel:K.pendingModel,costChannels:K.costChannels,controlsThirdBox:H2e})}),h.jsxs("div",{className:"contents",children:[h.jsxs("div",{className:"flex min-w-0 items-center gap-1 shrink-0",children:[h.jsx(Yt,{content:J("ui.chat.composer.attach_file"),children:h.jsx("span",{children:h.jsx(Xe,{variant:"ghost",size:Z?"icon-sm":"icon",className:"text-ink-dim hover:bg-elevated hover:text-ink",onPointerDown:q_,onClick:rRe,"aria-label":J("ui.chat.composer.attach_file"),"data-tour-tag":"chat-input-attach-file-button",disabled:un||me||Ee,children:h.jsx(y9e,{"aria-hidden":"true"})})})}),ze!==void 0&&h.jsx(Ban,{ref:SN,currentWorkingDirectory:ze,writePath:C,pending:G,pendingAccepted:N,readOnlyReason:C?void 0:W??t2e})]}),h.jsxs("div",{className:"ml-auto flex order-3 items-center gap-1",children:[Me&&zN&&h.jsx("output",{"data-preparing-indicator":"",className:"shrink-0 font-medium text-body-sm text-ink-muted",children:Z?J("ui.chat.composer.starting"):J("ui.chat.composer.starting_recording")}),zN&&h.jsx(Yt,{content:Me?J("ui.chat.composer.starting_recording"):En?J("ui.chat.composer.start_recording_hint",{shortcut:uRe,pushToTalk:oA().label}):tr,children:h.jsx("span",{children:h.jsx(Xe,{variant:"ghost",size:Z?"icon-sm":"icon",className:"text-ink-dim hover:bg-elevated hover:text-ink",onPointerDown:q_,onClick:XN,"aria-label":J("ui.chat.composer.start_recording"),"aria-busy":Me||void 0,disabled:un||!En,children:Me?h.jsx(Go,{size:"sm"}):h.jsx(o9e,{"aria-hidden":"true"})})})}),me&&h.jsxs(h.Fragment,{children:[h.jsx(Yt,{content:J("ui.chat.composer.confirm_recording_hint"),children:h.jsx("span",{children:h.jsx(Xe,{variant:"ghost",size:Z?"icon-sm":"icon",className:"text-success hover:bg-success-wash hover:text-success",onClick:X_,"aria-label":J("ui.chat.composer.confirm_recording"),children:h.jsx(xu,{"aria-hidden":"true"})})})}),h.jsx(Yt,{content:J("ui.chat.composer.cancel_recording_hint"),children:h.jsx("span",{children:h.jsx(Xe,{variant:"ghost",size:Z?"icon-sm":"icon",className:"text-danger hover:bg-danger-wash hover:text-danger",onClick:E_,"aria-label":J("ui.chat.composer.cancel_recording"),children:h.jsx(ea,{"aria-hidden":"true"})})})})]}),_N&&h.jsx("span",{"aria-hidden":"true","data-interrupt-slot":"",className:q("pointer-events-none invisible flex items-center"),children:h.jsx(Xe,{variant:"danger",size:Z?"icon-sm":"icon",type:"button",tabIndex:-1,children:h.jsx(m1,{"aria-hidden":"true"})})}),Q?.active&&h.jsx(Yt,{content:J("ui.chat.composer.stop_work_hint"),children:h.jsx("span",{children:h.jsx(Xe,{variant:"danger",size:Z?"icon-sm":"icon",type:"button",onClick:Q.onStop,"aria-label":J("ui.chat.composer.stop"),"aria-keyshortcuts":"Escape","data-stopping":Q.stopping===!0?"true":void 0,"aria-busy":Q.stopping===!0?!0:void 0,className:q("data-[stopping]:border-danger data-[stopping]:text-ink data-[stopping]:bg-[color-mix(in_oklab,var(--color-danger-wash)_80%,var(--color-danger))]"),children:h.jsx(m1,{"aria-hidden":"true"})})})}),t&&p?h.jsx(Yt,{content:J("ui.chat.composer.stop_agent"),children:h.jsx("span",{children:h.jsx(Xe,{variant:"danger",size:Z?"icon-sm":"icon",type:"button",onClick:()=>m?.(p),"aria-label":J("ui.chat.composer.stop_agent"),children:h.jsx(m1,{"aria-hidden":"true"})})})}):!me&&!Ee&&h.jsx(Yt,{content:ye!==null&&!r?J("ui.chat.composer.ask_aside"):J("ui.chat.composer.send_message"),children:h.jsx("span",{children:h.jsx(Xe,{variant:"primary",size:Z?"icon-sm":"icon",type:"submit",onPointerDown:tRe,disabled:un||Og||!Te.trim()&&oe.length===0,className:"rounded-full disabled:bg-surface","aria-label":ye!==null&&!r?J("ui.chat.composer.ask_aside"):J("ui.chat.composer.send_message"),children:h.jsx(Nue,{"aria-hidden":"true"})})})})]})]})]})]})]}),_&&!St?h.jsx("div",{className:q("mt-2",Rr),children:h.jsx(Sin,{})}):null,(_||E)&&en?h.jsx("div",{className:q("mt-2",Rr),children:h.jsx("output",{className:"block text-body-sm text-ink-muted",children:E?"Choose a model for this conversation before sending.":"Connect a provider to send."})}):null]});return h.jsxs("div",{className:q(zde,"flex w-full flex-col items-center",pr?"grow":"shrink-0",te?void 0:sZe,Z?"pb-1 pt-0.5":"pb-4 pt-2"),"data-lo-composer-band":!0,ref:Wt,onDragOver:aRe,onDragLeave:oRe,onDrop:sRe,children:[h.jsx("div",{"data-lo-composer-splash":"",className:q("flex w-full flex-col items-center justify-center",pr?"grow":null),children:h.jsx("div",{ref:gn,className:q(dh?"flex w-full flex-col items-center gap-6 py-4":"hidden"),children:dh?h.jsxs(h.Fragment,{children:[h.jsx("span",{"data-lo-empty-mark":"",className:"contents",children:h.jsx(_sn,{className:"size-8",tone:"ink-muted"})}),_?null:h.jsx("h2",{className:"text-center text-ink text-title",children:J("ui.chat.composer.welcome")}),_?h.jsx("div",{className:q("w-full",Rr),children:h.jsx(win,{})}):h.jsxs("div",{className:q("flex flex-col gap-3",Rr),children:[h.jsx(Kan,{band:ut,splash:tn,foot:zn,suggestions:Ze,disabled:K2e,onRefusedPress:q_,onSelect:cRe,focusComposer:()=>It.current?.focus()}),h.jsx(Grn,{suspended:Te.trim().length>0,mentionsEnabled:se})]})]}):null})}),St?h.jsx("div",{className:q("mb-2 mt-2",Rr),children:h.jsx(bin,{selection:nt})}):null,h.jsx("div",{ref:nr,"data-lo-composer-foot":"",className:"w-full",children:hRe})]})}),Dsn=$.memo(Zsn);Dsn.displayName="MessageInput";const Y2e=1024,aS=1024*1024,pN=.85,Msn=new Set(["image/png","image/jpeg","image/webp"]),Vsn=[{maxEdge:Y2e,quality:.8},{maxEdge:768,quality:.7},{maxEdge:512,quality:.6}];function Lsn(e){const t=e.endsWith("==")?2:e.endsWith("=")?1:0;return Math.floor(e.length*3/4)-t}function Fsn(e){const t=Uint8Array.fromBase64;if(typeof t=="function")return t.call(Uint8Array,e);const n=atob(e),r=new Uint8Array(n.length);for(let i=0;i<n.length;i+=1)r[i]=n.charCodeAt(i);return r}function Bsn(e){const t=e.toBase64;if(typeof t=="function")return t.call(e);let n="";const r=32768;for(let i=0;i<e.length;i+=r)n+=String.fromCharCode(...e.subarray(i,i+r));return btoa(n)}async function Hsn(e,t,n,r,i){const a=Math.max(e.width,e.height),o=a>r?r/a:1,s=Math.max(1,Math.round(e.width*o)),l=Math.max(1,Math.round(e.height*o)),c=new OffscreenCanvas(s,l),u=c.getContext("2d");if(!u)return null;u.drawImage(e,0,0,s,l);const O=[],d=await c.convertToBlob({type:"image/png"}),f=new Uint8Array(await d.arrayBuffer());if(f.byteLength<=aS&&O.push({bytes:f,mime_type:"image/png"}),f.byteLength>aS||i<pN){const g=new OffscreenCanvas(s,l),y=g.getContext("2d");if(!y)return null;y.fillStyle="#ffffff",y.fillRect(0,0,s,l),y.drawImage(e,0,0,s,l);const v=await g.convertToBlob({type:"image/jpeg",quality:i}),S=new Uint8Array(await v.arrayBuffer());O.push({bytes:S,mime_type:"image/jpeg"}),f.byteLength>aS&&S.byteLength>f.byteLength&&O.push({bytes:f,mime_type:"image/png"})}let p=null,m=Number.POSITIVE_INFINITY;for(const g of O)g.bytes.byteLength<m&&(p=g,m=g.bytes.byteLength);return p?m>=n?t:{data_b64:Bsn(p.bytes),mime_type:p.mime_type}:null}async function Ksn(e){if(!Msn.has(e.mime_type)||typeof createImageBitmap!="function"||typeof OffscreenCanvas!="function")return null;try{return await createImageBitmap(new Blob([Fsn(e.data_b64)],{type:e.mime_type}))}catch{return null}}async function Jsn(e,t,n,r){const i=Lsn(e.data_b64);try{return Math.max(t.width,t.height)<=n&&i<=aS&&r>=pN?e:await Hsn(t,e,i,n,r)??e}catch{return e}}async function eln(e,t,n){if(!e.length)return e;const r=await Promise.all(e.map(i=>Ksn(i)));try{return await tln(e,r,t,n)}finally{for(const i of r)i?.close()}}async function tln(e,t,n,r){const i=(c,u)=>Promise.all(e.map((O,d)=>{const f=t[d];return f?Jsn(O,f,c,u):Promise.resolve(O)})),a=await i(Y2e,pN);if(r(a)<=n)return a;let o=e,s=r(e);const l=c=>{const u=r(c);return u<s&&(o=c,s=u),u};l(a);for(const c of Vsn){const u=await i(c.maxEdge,c.quality);if(l(u)<=n)return u}return o}const nln=/^data:(image\/(png|jpeg|gif|webp));base64,(.+)$/,rln=/^file:\/\//,iln={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp"};async function ffn(e,t){const n=[],r=[];for(const a of e){const o=nln.exec(a);if(o){n.push({data_b64:o[3],mime_type:o[1]});continue}const s=a.split(".").pop()?.toLowerCase()??"",l=iln[s];if(!l||!window.api?.readFile)continue;const c=await window.api.readFile(a.replace(rln,""),"base64");c.success?n.push({data_b64:c.data,mime_type:l}):r.push(a)}const i=Math.max(0,n.length-Nq);return{images:await eln(n.slice(0,Nq),HQ,a=>Ej(t,a)),unreadable:r,overflow:i}}function hfn(e){if(e.length===0)return null;const t=e.map(Ck);return t.length===1?`${t[0]} could not be read (it may have been moved or deleted), so this message was not sent. Attach it again, or remove it from the draft.`:`${t.join(", ")} could not be read (they may have been moved or deleted), so this message was not sent. Attach them again, or remove them from the draft.`}function pfn(e){if(e<=0)return null;const t=Nq,n=t+e;return e===1?`This draft carries ${n} images and one message carries up to ${t}, so this message was not sent. Remove the extra image, or send it in a second message.`:`This draft carries ${n} images and one message carries up to ${t}, so this message was not sent. Remove ${e} of them, or send them in a second message.`}function mfn(e){const t=e.trim();if(t.startsWith("="))return null;const n=t.toLowerCase();return n==="pause"||n==="resume"||n==="status"?n:null}function gfn(e){const t=e.trim();return t.startsWith("=")?t.slice(1).trimStart():t}function $fn(e,t){return e==="pause"?{text:"Aida is paused. She will not check in until you resume her.",kind:"success"}:e==="resume"?{text:"Aida is resumed. She will check in on her usual schedule.",kind:"success"}:{kind:"info",text:t.paused?"Aida is paused.":"Aida is active."}}function aln(e){return Io(e,"Aida's controls could not reach the backend.")}const yfn="The chief of staff is switched off on this install.",oln="aida_no_provider",sln="aida_disabled";function vfn(e,t){const n=e instanceof Ut?e.code:void 0;return n===sln?null:n===oln?{kind:"info",text:`${t} will say hello once an AI account is connected. Connect one from the chat to start.`}:{kind:"error",text:`${t}'s conversation could not be opened, so you are in a new chat instead. ${aln(e)}`}}function bfn(e,t){if(e.held===!0)return`${t} is already open in another window, so she will say hello there.`;const n=e.greeting_state==="delivered"||e.greeting_state==="skipped"||e.greeting_state==null&&e.greeted===!0;return e.paused&&!n?`${t} is paused, so she will say hello when you resume her: type /aida resume.`:null}function wfn(e){const t=e?.greeting_state;return t==null||t==="owed"}function lln(e){return e.eventKey===e.storeKey&&!e.focused}let Fse=!1;function Sfn(){if(Fse)return;Fse=!0;const e=an.persist?.getOptions?.()?.name??"conversation-input-store",t=n=>{lln({eventKey:n.key,storeKey:e,focused:document.hasFocus()})&&an.persist?.rehydrate?.()?.catch?.(()=>{})};window.addEventListener("storage",t)}export{Bd as $,rGe as A,uGe as B,jt as C,Ua as D,lt as E,El as F,An as G,Df as H,P as I,Rn as J,Qr as K,Xn as L,wn as M,Mk as N,Ev as O,Yr as P,Cr as Q,Lr as R,bs as S,d8 as T,wa as U,Bn as V,L9 as W,cr as X,_s as Y,Ut as Z,Nue as _,Ri as a,Fln as a$,Pun as a0,pv as a1,Jln as a2,Io as a3,Pln as a4,ecn as a5,R$ as a6,mi as a7,dW as a8,QW as a9,bCe as aA,an as aB,Pm as aC,Ad as aD,Dsn as aE,vUe as aF,Dcn as aG,Nln as aH,Gln as aI,Sfn as aJ,bun as aK,yun as aL,Yln as aM,pj as aN,Of as aO,G9e as aP,uv as aQ,Lln as aR,Ov as aS,MOn as aT,Tl as aU,Mh as aV,$a as aW,jue as aX,mz as aY,vj as aZ,ade as a_,Rc as aa,Nr as ab,$De as ac,j$ as ad,sdn as ae,ldn as af,Pke as ag,B8e as ah,Az as ai,jj as aj,hv as ak,Nf as al,KYe as am,yfn as an,ffn as ao,hfn as ap,Uce as aq,pfn as ar,cun as as,wln as at,ar as au,kln as av,Ta as aw,Qtt as ax,zd as ay,xCe as az,icn as b,lcn as b$,ro as b0,LNt as b1,kW as b2,i_e as b3,Bv as b4,s_e as b5,nfn as b6,VGt as b7,Vre as b8,Mre as b9,Gz as bA,iun as bB,aIe as bC,Sde as bD,Tun as bE,Run as bF,fv as bG,ve as bH,ZAe as bI,ri as bJ,pg as bK,a8e as bL,x5 as bM,lke as bN,wG as bO,xG as bP,kue as bQ,ccn as bR,yz as bS,lun as bT,qm as bU,rUe as bV,p6e as bW,sG as bX,Dln as bY,Zln as bZ,T6e as b_,Q_e as ba,NW as bb,FP as bc,CYt as bd,jYt as be,sm as bf,qYt as bg,EYt as bh,iQ as bi,Kv as bj,UW as bk,AW as bl,Id as bm,rQ as bn,fGe as bo,zx as bp,Rr as bq,sZe as br,zde as bs,m1 as bt,vln as bu,Eun as bv,Kln as bw,eIe as bx,H8e as by,Xun as bz,oi as c,pGe as c$,su as c0,Rp as c1,zue as c2,Que as c3,dv as c4,pk as c5,Gue as c6,que as c7,Rue as c8,Fze as c9,Tln as cA,U0 as cB,cUe as cC,JRt as cD,yZe as cE,Mz as cF,fQe as cG,zO as cH,_f as cI,oIe as cJ,MAe as cK,WAe as cL,TKt as cM,nd as cN,tun as cO,DYe as cP,Zc as cQ,_Kt as cR,d_ as cS,f_ as cT,HLt as cU,u_ as cV,cde as cW,Wln as cX,SYe as cY,Lue as cZ,sO as c_,Ajt as ca,Pue as cb,Zue as cc,Iue as cd,Jj as ce,IO as cf,Eue as cg,Xue as ch,Xm as ci,Si as cj,tue as ck,y6e as cl,w6e as cm,k6e as cn,S6e as co,x6e as cp,hj as cq,_6e as cr,uG as cs,P6e as ct,Q6e as cu,vde as cv,yde as cw,JGe as cx,_ln as cy,Tp as cz,Re as d,B9t as d$,cke as d0,KAt as d1,ok as d2,kce as d3,e3e as d4,sk as d5,Xke as d6,DXt as d7,hk as d8,adn as d9,QJt as dA,Wi as dB,Sc as dC,tUe as dD,hun as dE,i6t as dF,kd as dG,i7t as dH,K9e as dI,Iln as dJ,cfn as dK,dGe as dL,$Ge as dM,NCt as dN,nze as dO,Odn as dP,sf as dQ,fPe as dR,Yx as dS,Jx as dT,nie as dU,oYt as dV,qy as dW,J9t as dX,e8t as dY,K9t as dZ,H9t as d_,C7t as da,xke as db,odn as dc,I6t as dd,T7 as de,Xle as df,qCe as dg,Pon as dh,ufn as di,Uc as dj,Ofn as dk,Ton as dl,Cke as dm,Uue as dn,QU as dp,grn as dq,AO as dr,sde as ds,pun as dt,Bqt as du,ejt as dv,BOn as dw,FK as dx,MK as dy,Jqt as dz,Cz as e,uWe as e$,F9t as e0,L9t as e1,NP as e2,E9t as e3,X9t as e4,V9t as e5,M9t as e6,f8e as e7,Mn as e8,fk as e9,$un as eA,nUe as eB,OGe as eC,RYe as eD,vun as eE,k5 as eF,VJe as eG,eet as eH,lFe as eI,Y$ as eJ,DJe as eK,Ape as eL,oYe as eM,sYe as eN,DWe as eO,xj as eP,gy as eQ,_z as eR,Gcn as eS,hdn as eT,fdn as eU,qWe as eV,Ccn as eW,qcn as eX,jcn as eY,Ncn as eZ,Ycn as e_,Qdn as ea,Pdn as eb,wdn as ec,vdn as ed,rA as ee,mdn as ef,gdn as eg,$dn as eh,kdn as ei,_dn as ej,Sdn as ek,pdn as el,xdn as em,bdn as en,ydn as eo,Uln as ep,GCe as eq,YCe as er,Fce as es,Lce as et,uun as eu,Oun as ev,l8e as ew,dun as ex,fun as ey,mun as ez,iPe as f,Zun as f$,xcn as f0,wcn as f1,Ls as f2,z0 as f3,kcn as f4,$cn as f5,SR as f6,Pcn as f7,_7 as f8,G6t as f9,YUe as fA,Scn as fB,zcn as fC,Xcn as fD,_We as fE,Wcn as fF,dWe as fG,Ecn as fH,sAt as fI,Qj as fJ,yWe as fK,jce as fL,ou as fM,Tdn as fN,YTe as fO,Rdn as fP,KOn as fQ,u6t as fR,YAe as fS,ROe as fT,HWe as fU,_sn as fV,L9e as fW,Tue as fX,FZe as fY,KZe as fZ,Iun as f_,W6t as fa,ddn as fb,_cn as fc,ple as fd,SS as fe,QWe as ff,Rcn as fg,V6t as fh,BAe as fi,dk as fj,wue as fk,JU as fl,WJ as fm,d0 as fn,vcn as fo,$Oe as fp,X9e as fq,Ucn as fr,Acn as fs,jAe as ft,ycn as fu,gOe as fv,Qcn as fw,bR as fx,Icn as fy,p9e as fz,yr as g,gf as g$,Nun as g0,Yun as g1,Gun as g2,Mun as g3,iDe as g4,lfe as g5,Fun as g6,Eze as g7,sDe as g8,Dun as g9,Fpe as gA,Vpe as gB,Lpe as gC,lOn as gD,UCe as gE,QA as gF,Tz as gG,AOe as gH,cNe as gI,Dv as gJ,uQe as gK,cQe as gL,co as gM,_n as gN,ZO as gO,Pt as gP,Ge as gQ,ht as gR,SOn as gS,Ti as gT,UM as gU,Nm as gV,Ro as gW,Yc as gX,dme as gY,cn as gZ,Nn as g_,fDe as ga,Bun as gb,Vun as gc,HZe as gd,Gn as ge,Lun as gf,Sue as gg,aUe as gh,J8e as gi,scn as gj,ocn as gk,acn as gl,Vcn as gm,kj as gn,iAt as go,dln as gp,GCt as gq,Z9 as gr,cOn as gs,iOn as gt,gtt as gu,rOn as gv,G9 as gw,Hpe as gx,Y9 as gy,Kpe as gz,$te as h,oA as h$,ms as h0,Zl as h1,hOn as h2,Mv as h3,NU as h4,GU as h5,Cx as h6,WU as h7,YU as h8,IU as h9,mOn as hA,_On as hB,XOn as hC,qOn as hD,COn as hE,zOn as hF,vOn as hG,bOn as hH,$On as hI,Nk as hJ,EOn as hK,Dk as hL,yOn as hM,YSe as hN,wU as hO,fse as hP,Hue as hQ,oI as hR,Z8e as hS,b8e as hT,Rrn as hU,i2e as hV,TZe as hW,sfe as hX,W2e as hY,y9e as hZ,ode as h_,n9e as ha,fs as hb,jge as hc,rat as hd,XO as he,nat as hf,Fn as hg,Gt as hh,Zf as hi,Ki as hj,Er as hk,zi as hl,tu as hm,rw as hn,KS as ho,Ik as hp,wOn as hq,Tu as hr,AOn as hs,TOn as ht,Xot as hu,xOn as hv,QOn as hw,gOn as hx,ROn as hy,pOn as hz,Jdn as i,uUe as i$,o9e as i0,q$ as i1,ZOn as i2,$8e as i3,y8e as i4,qxe as i5,Exe as i6,aOn as i7,NS as i8,Sk as i9,fFe as iA,oBe as iB,Dze as iC,Wue as iD,Ck as iE,Mpe as iF,$tt as iG,xtt as iH,mle as iI,uk as iJ,mXe as iK,VY as iL,TXe as iM,ECe as iN,AYe as iO,Ez as iP,LAe as iQ,Hcn as iR,zqt as iS,wde as iT,VNe as iU,Kcn as iV,Dce as iW,zln as iX,Xln as iY,Rln as iZ,BY as i_,Cfe as ia,K5 as ib,YBe as ic,NBe as id,jfe as ie,Hun as ig,che as ih,Sa as ii,YO as ij,wv as ik,Jun as il,qMe as im,tHe as io,pet as ip,qS as iq,p9 as ir,s9 as is,Fj as it,lhe as iu,DMe as iv,_Me as iw,GMe as ix,bD as iy,xBe as iz,ul as j,qln as j$,Eln as j0,Ocn as j1,Rze as j2,ucn as j3,dcn as j4,$Ue as j5,Wjt as j6,Lz as j7,$v as j8,xU as j9,yk as jA,Lcn as jB,sNe as jC,Fcn as jD,Mcn as jE,nDe as jF,lfn as jG,Wun as jH,oZe as jI,nI as jJ,nde as jK,hle as jL,fle as jM,yYe as jN,run as jO,M3t as jP,MQe as jQ,nrn as jR,t2e as jS,rfn as jT,rg as jU,mfn as jV,$fn as jW,aln as jX,gfn as jY,hln as jZ,pln as j_,zU as ja,Njt as jb,oOn as jc,ZXt as jd,sOn as je,_ue as jf,Ban as jg,Zcn as jh,X$ as ji,czt as jj,Lke as jk,j5 as jl,_m as jm,ja as jn,EGe as jo,gun as jp,gGe as jq,ndn as jr,rdn as js,idn as jt,Yue as ju,ncn as jv,sUe as jw,Pr as jx,zun as jy,fln as jz,Fdn as k,g9e as k$,G7e as k0,jln as k1,Aln as k2,Cln as k3,r2e as k4,JQ as k5,qun as k6,Aun as k7,jun as k8,Cun as k9,yln as kA,gln as kB,ofn as kC,Bcn as kD,UUe as kE,lCe as kF,WUe as kG,NUe as kH,gcn as kI,mcn as kJ,WNe as kK,UNe as kL,VOe as kM,pcn as kN,Yce as kO,oOe as kP,fcn as kQ,Gce as kR,mCe as kS,MY as kT,hcn as kU,bln as kV,sfn as kW,LWe as kX,FOn as kY,afn as kZ,tS as k_,sun as ka,Gke as kb,Aqt as kc,cv as kd,SCe as ke,Jue as kf,rcn as kg,nz as kh,SUe as ki,$ln as kj,rZe as kk,iZe as kl,Uun as km,bcn as kn,Tcn as ko,lAt as kp,ifn as kq,mln as kr,Ice as ks,dfn as kt,LOn as ku,PCe as kv,ck as kw,xln as kx,Qln as ky,s4e as kz,Bdn as l,Fi as l$,SO as l0,eun as l1,rYe as l2,Sln as l3,Jcn as l4,BYe as l5,h7t as l6,$ke as l7,Ddn as l8,JOn as l9,EP as lA,Ndn as lB,Wdn as lC,zdn as lD,$z as lE,l2e as lF,zke as lG,qj as lH,wfn as lI,bfn as lJ,vfn as lK,t6t as lL,Tke as lM,_ke as lN,rIe as lO,wJ as lP,cdn as lQ,udn as lR,_un as lS,XYe as lT,EYe as lU,nun as lV,aun as lW,qGe as lX,oun as lY,Bln as lZ,bAe as l_,tdn as la,wke as lb,yu as lc,edn as ld,cGe as le,yke as lf,Cdn as lg,Mdn as lh,Vdn as li,Adn as lj,Ldn as lk,mk as ll,f7t as lm,EXe as ln,Lrn as lo,Ydn as lp,Gdn as lq,b7t as lr,qdn as ls,yAt as lt,Edn as lu,jdn as lv,mAt as lw,Udn as lx,Zdn as ly,Idn as lz,Kdn as m,VOn as m0,Xdn as m1,HOn as m2,u6e as m3,I7t as m4,xun as m5,wun as m6,Sun as m7,bg as m8,Qun as m9,Vln as ma,tcn as mb,g1 as mc,kun as md,Hln as me,nOn as mf,DOn as mg,tfn as n,Hdn as o,em as p,efn as q,Kd as r,Nx as s,WP as t,cc as u,nQ as v,OW as w,Ry as x,cPe as y,D9t as z};