@rudderhq/server 0.7.24-canary.21 → 0.7.24-canary.22

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 (144) hide show
  1. package/dist/bootstrap/register-api-routes.d.ts.map +1 -1
  2. package/dist/bootstrap/register-api-routes.js +2 -2
  3. package/dist/bootstrap/register-api-routes.js.map +1 -1
  4. package/dist/routes/approvals.d.ts +2 -1
  5. package/dist/routes/approvals.d.ts.map +1 -1
  6. package/dist/routes/approvals.js +49 -4
  7. package/dist/routes/approvals.js.map +1 -1
  8. package/dist/routes/chats.d.ts +2 -1
  9. package/dist/routes/chats.d.ts.map +1 -1
  10. package/dist/routes/chats.js +3 -3
  11. package/dist/routes/chats.js.map +1 -1
  12. package/dist/routes/chats.stream-routes.d.ts.map +1 -1
  13. package/dist/routes/chats.stream-routes.js +1 -0
  14. package/dist/routes/chats.stream-routes.js.map +1 -1
  15. package/dist/routes/organization-rust-foundation-routes.d.ts.map +1 -1
  16. package/dist/routes/organization-rust-foundation-routes.js +27 -14
  17. package/dist/routes/organization-rust-foundation-routes.js.map +1 -1
  18. package/dist/routes/orgs.d.ts +1 -1
  19. package/dist/routes/orgs.d.ts.map +1 -1
  20. package/dist/routes/orgs.js +23 -2
  21. package/dist/routes/orgs.js.map +1 -1
  22. package/dist/services/chat-organization-branding-rust-idempotency.test.d.ts +2 -0
  23. package/dist/services/chat-organization-branding-rust-idempotency.test.d.ts.map +1 -0
  24. package/dist/services/chat-organization-branding-rust-idempotency.test.js +367 -0
  25. package/dist/services/chat-organization-branding-rust-idempotency.test.js.map +1 -0
  26. package/dist/services/chat-organization-branding.d.ts +78 -0
  27. package/dist/services/chat-organization-branding.d.ts.map +1 -0
  28. package/dist/services/chat-organization-branding.js +212 -0
  29. package/dist/services/chat-organization-branding.js.map +1 -0
  30. package/dist/services/chats.d.ts +24 -6
  31. package/dist/services/chats.d.ts.map +1 -1
  32. package/dist/services/chats.js +76 -86
  33. package/dist/services/chats.js.map +1 -1
  34. package/dist/services/organization-branding-fence.d.ts +4 -3
  35. package/dist/services/organization-branding-fence.d.ts.map +1 -1
  36. package/dist/services/organization-branding-fence.js +4 -3
  37. package/dist/services/organization-branding-fence.js.map +1 -1
  38. package/dist/services/orgs.d.ts +1 -0
  39. package/dist/services/orgs.d.ts.map +1 -1
  40. package/dist/services/orgs.js +11 -2
  41. package/dist/services/orgs.js.map +1 -1
  42. package/dist/services/rust-foundation-bridge.d.ts +3 -0
  43. package/dist/services/rust-foundation-bridge.d.ts.map +1 -1
  44. package/dist/services/rust-foundation-bridge.js +160 -26
  45. package/dist/services/rust-foundation-bridge.js.map +1 -1
  46. package/dist/services/rust-foundation-bridge.test.js +164 -3
  47. package/dist/services/rust-foundation-bridge.test.js.map +1 -1
  48. package/dist/services/workspace-backups.d.ts +0 -1
  49. package/dist/services/workspace-backups.d.ts.map +1 -1
  50. package/dist/services/workspace-backups.js +0 -11
  51. package/dist/services/workspace-backups.js.map +1 -1
  52. package/package.json +13 -13
  53. package/resources/bundled-skills/rudder-docs/references/cli-reference.md +1 -1
  54. package/resources/native/aarch64-apple-darwin/rudder-server-foundation +0 -0
  55. package/resources/native/aarch64-pc-windows-msvc/migration-preflight.exe +0 -0
  56. package/resources/native/aarch64-pc-windows-msvc/rudder-server-foundation.exe +0 -0
  57. package/resources/native/aarch64-unknown-linux-gnu/rudder-server-foundation +0 -0
  58. package/resources/native/x86_64-apple-darwin/rudder-server-foundation +0 -0
  59. package/resources/native/x86_64-pc-windows-msvc/migration-preflight.exe +0 -0
  60. package/resources/native/x86_64-pc-windows-msvc/rudder-server-foundation.exe +0 -0
  61. package/resources/native/x86_64-unknown-linux-gnu/rudder-server-foundation +0 -0
  62. package/skills/rudder-docs/references/cli-reference.md +1 -1
  63. package/ui-dist/assets/{LibraryLiveSurface-Bs8V_pMU.js → LibraryLiveSurface-CodApFW-.js} +1 -1
  64. package/ui-dist/assets/{abnfDiagram-VRR7QNED-DneqWru9.js → abnfDiagram-VRR7QNED-BDz58rQS.js} +1 -1
  65. package/ui-dist/assets/{addon-fit-DCRNyXYv.js → addon-fit-DZOvRzIT.js} +1 -1
  66. package/ui-dist/assets/{arc-D_2I_R5Z.js → arc-C9TMZvvd.js} +1 -1
  67. package/ui-dist/assets/{architectureDiagram-ZJ3FMSHR-C0ANAv78.js → architectureDiagram-ZJ3FMSHR-D4twxoE1.js} +1 -1
  68. package/ui-dist/assets/{blockDiagram-677ZJIJ3-BqFGOix5.js → blockDiagram-677ZJIJ3-DJs0gNG4.js} +1 -1
  69. package/ui-dist/assets/{c4Diagram-LMCZKHZV-82LfEi1P.js → c4Diagram-LMCZKHZV-6oq8lq8q.js} +1 -1
  70. package/ui-dist/assets/channel-CmUGU_Az.js +1 -0
  71. package/ui-dist/assets/{chunk-2Q5K7J3B-DijvvGcl.js → chunk-2Q5K7J3B-m2MTxaYE.js} +1 -1
  72. package/ui-dist/assets/{chunk-32BRIVSS-Z09s337w.js → chunk-32BRIVSS-BYbeAqiG.js} +1 -1
  73. package/ui-dist/assets/{chunk-5VM5RSS4-DgQWkO6B.js → chunk-5VM5RSS4-Dy6Af71u.js} +1 -1
  74. package/ui-dist/assets/{chunk-EX3LRPZG-UTEQqeds.js → chunk-EX3LRPZG-DBbU0fB6.js} +1 -1
  75. package/ui-dist/assets/{chunk-JWPE2WC7-DAaSu1vD.js → chunk-JWPE2WC7-D3_gHXg6.js} +1 -1
  76. package/ui-dist/assets/{chunk-MOJQB5TN-D_fTXJM3.js → chunk-MOJQB5TN-Di4_CsSE.js} +1 -1
  77. package/ui-dist/assets/{chunk-RYQCIY6F-C7H_axhC.js → chunk-RYQCIY6F-CnLAkiBe.js} +1 -1
  78. package/ui-dist/assets/{chunk-V7JOEXUC-B2toa05O.js → chunk-V7JOEXUC-D3UVXcJk.js} +1 -1
  79. package/ui-dist/assets/{chunk-VR4S4FIN-CkRvPkE2.js → chunk-VR4S4FIN-BJHYVSXv.js} +1 -1
  80. package/ui-dist/assets/{chunk-XXDRQBXY-DOO_r0VK.js → chunk-XXDRQBXY-C4VVlQgO.js} +1 -1
  81. package/ui-dist/assets/classDiagram-OUVF2IWQ-Dy5r3CRw.js +1 -0
  82. package/ui-dist/assets/classDiagram-v2-EOCWNBFH-Dy5r3CRw.js +1 -0
  83. package/ui-dist/assets/{cose-bilkent-JH36ORCC-BzYjE_M-.js → cose-bilkent-JH36ORCC-2YJ4B2bE.js} +1 -1
  84. package/ui-dist/assets/{cynefin-VYW2F7L2-Dcf0eQJ5.js → cynefin-VYW2F7L2-293DKtI3.js} +1 -1
  85. package/ui-dist/assets/{cynefinDiagram-TSTJHNR4-Cs_Lv8Ua.js → cynefinDiagram-TSTJHNR4-d23XGkDy.js} +1 -1
  86. package/ui-dist/assets/{dagre-VKFMJZFB-B8oZME7g.js → dagre-VKFMJZFB-EJXBSBZ7.js} +1 -1
  87. package/ui-dist/assets/{diagram-FQU43EPY-DFHkB-_t.js → diagram-FQU43EPY-CcQzLlPj.js} +1 -1
  88. package/ui-dist/assets/{diagram-G47NLZAW-FGxRm1A-.js → diagram-G47NLZAW-Bke8VP0c.js} +1 -1
  89. package/ui-dist/assets/{diagram-NH7WQ7WH-Ot83ScOb.js → diagram-NH7WQ7WH-CDVrkJeo.js} +1 -1
  90. package/ui-dist/assets/{diagram-OA4YK3LP-CkiHNUvw.js → diagram-OA4YK3LP-Dw_uKvbb.js} +1 -1
  91. package/ui-dist/assets/{diagram-WEI45ONY-CxM3g_L3.js → diagram-WEI45ONY-DmhFc8DI.js} +1 -1
  92. package/ui-dist/assets/{ebnfDiagram-CCIWWBDH-DbcqsHcY.js → ebnfDiagram-CCIWWBDH-CdqBJkjm.js} +1 -1
  93. package/ui-dist/assets/{erDiagram-Q63AITRT-DLROlxDN.js → erDiagram-Q63AITRT-DOkjjwWL.js} +1 -1
  94. package/ui-dist/assets/{flowDiagram-23GEKE2U-DphM_YLM.js → flowDiagram-23GEKE2U-DG8rqW-P.js} +1 -1
  95. package/ui-dist/assets/{ganttDiagram-NO4QXBWP--QIRtWYP.js → ganttDiagram-NO4QXBWP-BEkgTSEf.js} +1 -1
  96. package/ui-dist/assets/{gitGraphDiagram-IHSO6WYX-Bg3QwNvE.js → gitGraphDiagram-IHSO6WYX-BjXwkXS6.js} +1 -1
  97. package/ui-dist/assets/{graph-B_1y14m_.js → graph-D3KzI4sR.js} +1 -1
  98. package/ui-dist/assets/{index-E2v-0TkN.js → index-B2UcZ_IJ.js} +1 -1
  99. package/ui-dist/assets/{index-Bi9I1TFJ.js → index-BDH__Lgs.js} +5 -5
  100. package/ui-dist/assets/{index-CcWXJMSa.js → index-BIQKbQUa.js} +1 -1
  101. package/ui-dist/assets/{index-XWYyP2hU.js → index-BIwzh-U4.js} +1 -1
  102. package/ui-dist/assets/{index-BlFoD6Gg.js → index-BNdZbjyn.js} +1 -1
  103. package/ui-dist/assets/{index-B-yeMW3t.js → index-BONjSnI2.js} +1 -1
  104. package/ui-dist/assets/{index-Aj3Mi7R6.js → index-BrgGIOAR.js} +1 -1
  105. package/ui-dist/assets/{index-CS2TW9nf.js → index-By6wVGNY.js} +1 -1
  106. package/ui-dist/assets/{index-BABow2kh.js → index-C6RzrVdO.js} +1 -1
  107. package/ui-dist/assets/{index-BueQLOw6.js → index-ChpzeG1B.js} +1 -1
  108. package/ui-dist/assets/{index-6O1Ef9oA.js → index-D-jdXuoy.js} +1 -1
  109. package/ui-dist/assets/{index-CdAtz86o.js → index-D2RUPIgv.js} +1 -1
  110. package/ui-dist/assets/{index-BEgTumxB.js → index-D3MTazer.js} +1 -1
  111. package/ui-dist/assets/{index-CMUgKK2j.js → index-DepPPcF2.js} +1 -1
  112. package/ui-dist/assets/{index-BQheb_6L.js → index-fZqqDrca.js} +1 -1
  113. package/ui-dist/assets/{infoDiagram-FWYZ7A6U-BxygKDVp.js → infoDiagram-FWYZ7A6U-sxoY23rO.js} +1 -1
  114. package/ui-dist/assets/{ishikawaDiagram-FXEZZL3T-47zucfG2.js → ishikawaDiagram-FXEZZL3T-DS6bgeAA.js} +1 -1
  115. package/ui-dist/assets/{journeyDiagram-5HDEW3XC-D8cyI8aY.js → journeyDiagram-5HDEW3XC-DzVKXP7n.js} +1 -1
  116. package/ui-dist/assets/{kanban-definition-HUTT4EX6-CrxRNese.js → kanban-definition-HUTT4EX6--VTcXs7-.js} +1 -1
  117. package/ui-dist/assets/{layout-OyZo5VN3.js → layout-DMOyxlK9.js} +1 -1
  118. package/ui-dist/assets/{linear-CuiwlwQB.js → linear-C76BMUjd.js} +1 -1
  119. package/ui-dist/assets/{map-rixHzQ5d.js → map-CeACQf-M.js} +1 -1
  120. package/ui-dist/assets/{mermaid.core-BBG92fxH.js → mermaid.core-C39RyJW7.js} +4 -4
  121. package/ui-dist/assets/{mindmap-definition-LN4V7U3C-CivqbhCV.js → mindmap-definition-LN4V7U3C-CC5aZy3e.js} +1 -1
  122. package/ui-dist/assets/{pegDiagram-2B236MQR-JrPSWk9k.js → pegDiagram-2B236MQR-Pfr90o3u.js} +1 -1
  123. package/ui-dist/assets/{pieDiagram-ENE6RG2P-F4HEWR5n.js → pieDiagram-ENE6RG2P-cFuaxMwf.js} +1 -1
  124. package/ui-dist/assets/{quadrantDiagram-ABIIQ3AL-BJNly8dn.js → quadrantDiagram-ABIIQ3AL-CcQ7rg5U.js} +1 -1
  125. package/ui-dist/assets/{railroadDiagram-RFXS5EU6-DNORDnb2.js → railroadDiagram-RFXS5EU6-Dn0G1sUQ.js} +1 -1
  126. package/ui-dist/assets/{requirementDiagram-TGXJPOKE-710xtGEU.js → requirementDiagram-TGXJPOKE-C55Bzmxm.js} +1 -1
  127. package/ui-dist/assets/{sankeyDiagram-HTMAVEWB-BmWJHmHA.js → sankeyDiagram-HTMAVEWB-rC-F0WZY.js} +1 -1
  128. package/ui-dist/assets/{sequenceDiagram-DBY2YBRQ-A73TFc3V.js → sequenceDiagram-DBY2YBRQ-DKnrOS-d.js} +1 -1
  129. package/ui-dist/assets/{sizeCapture-X5ZJPWSS-B8otrPI2.js → sizeCapture-X5ZJPWSS-CftJxMqM.js} +1 -1
  130. package/ui-dist/assets/{stateDiagram-2N3HPSRC-BZ9k729q.js → stateDiagram-2N3HPSRC-BWk2fDZE.js} +1 -1
  131. package/ui-dist/assets/stateDiagram-v2-6OUMAXLB-CAKipX8h.js +1 -0
  132. package/ui-dist/assets/{swimlanes-5IMT3BWC-W_CH_z9Z.js → swimlanes-5IMT3BWC-DEOS3o8Q.js} +2 -2
  133. package/ui-dist/assets/swimlanesDiagram-G3AALYLV-BICPV_pK.js +8 -0
  134. package/ui-dist/assets/{timeline-definition-FHXFAJF6-CcXbC6J1.js → timeline-definition-FHXFAJF6-_6-BAwLW.js} +1 -1
  135. package/ui-dist/assets/{vennDiagram-L72KCM5P-BMHmsQqg.js → vennDiagram-L72KCM5P-BjCktz3U.js} +1 -1
  136. package/ui-dist/assets/{wardleyDiagram-EHGQE667-Bq2-CEvU.js → wardleyDiagram-EHGQE667-DrmL6CAw.js} +1 -1
  137. package/ui-dist/assets/{xterm-8vrqRuWm.js → xterm-Jvo0xPzf.js} +1 -1
  138. package/ui-dist/assets/{xychartDiagram-FW5EYKEG-De3RUAME.js → xychartDiagram-FW5EYKEG-DyJoUa3f.js} +1 -1
  139. package/ui-dist/index.html +1 -1
  140. package/ui-dist/assets/channel-DjvWm5jR.js +0 -1
  141. package/ui-dist/assets/classDiagram-OUVF2IWQ-CNSRItW2.js +0 -1
  142. package/ui-dist/assets/classDiagram-v2-EOCWNBFH-CNSRItW2.js +0 -1
  143. package/ui-dist/assets/stateDiagram-v2-6OUMAXLB-DepHJpk7.js +0 -1
  144. package/ui-dist/assets/swimlanesDiagram-G3AALYLV-BRL-ddud.js +0 -8
@@ -1618,7 +1618,7 @@ Error generating stack: `+P.message+`
1618
1618
  `))),s=[])};for(const c of n){const d=c.match(/^[ \t]{0,3}(`{3,}|~{3,})/u);if(d){const u=(l=d[1])==null?void 0:l[0];if(!a){o(),a=u??null,r.push(c);continue}if(u===a){r.push(c),a=null;continue}}a?r.push(c):s.push(c)}return o(),r.join(`
1619
1619
  `)}function RWt(e,t,n){const r=[{length:0,link:-1,firstEnd:n.rawStart-1,next:new Map}];let s=0;for(let c=n.rawStart;c<n.rawEnd;c+=1){const d=r.length;r.push({length:r[s].length+1,link:0,firstEnd:c,next:new Map});let u=s;const f=e[c];for(;u>=0&&!r[u].next.has(f);)r[u].next.set(f,d),u=r[u].link;if(u>=0){const m=r[u].next.get(f);if(r[u].length+1===r[m].length)r[d].link=m;else{const h=r.length;for(r.push({length:r[u].length+1,link:r[m].link,firstEnd:r[m].firstEnd,next:new Map(r[m].next)});u>=0&&r[u].next.get(f)===m;)r[u].next.set(f,h),u=r[u].link;r[m].link=h,r[d].link=h}}s=d}let a=0,o=0,l=null;for(let c=n.renderedStart;c<n.renderedEnd;c+=1){const d=t[c];for(;a!==0&&!r[a].next.has(d);)a=r[a].link,o=Math.min(o,r[a].length);const u=r[a].next.get(d);if(u===void 0){a=0,o=0;continue}a=u,o+=1;const m=r[a].firstEnd-o+1,h=c-o+1;(!l||o>l.length||o===l.length&&(h<l.renderedStart||h===l.renderedStart&&m<l.rawStart))&&(l={rawStart:m,renderedStart:h,length:o})}return l}function LWt(e,t){const n=[],r=[{rawStart:0,rawEnd:e.length,renderedStart:0,renderedEnd:t.length}];for(;r.length>0;){const s=r.pop();let{rawStart:a,rawEnd:o,renderedStart:l,renderedEnd:c}=s,d=0;for(;a+d<o&&l+d<c&&e[a+d]===t[l+d];)d+=1;d>0&&(n.push({rawStart:a,renderedStart:l,length:d}),a+=d,l+=d);let u=0;for(;o-u>a&&c-u>l&&e[o-u-1]===t[c-u-1];)u+=1;if(u>0&&(o-=u,c-=u,n.push({rawStart:o,renderedStart:c,length:u})),a>=o||l>=c)continue;const f=RWt(e,t,{rawStart:a,rawEnd:o,renderedStart:l,renderedEnd:c});if(!f||f.length===0)continue;n.push(f),a<f.rawStart&&l<f.renderedStart&&r.push({rawStart:a,rawEnd:f.rawStart,renderedStart:l,renderedEnd:f.renderedStart});const m=f.rawStart+f.length,h=f.renderedStart+f.length;m<o&&h<c&&r.push({rawStart:m,rawEnd:o,renderedStart:h,renderedEnd:c})}return n.sort((s,a)=>s.renderedStart-a.renderedStart||s.rawStart-a.rawStart).reduce((s,a)=>{const o=s.at(-1);return o&&o.rawStart+o.length===a.rawStart&&o.renderedStart+o.length===a.renderedStart?o.length+=a.length:s.push({...a}),s},[])}function m8e(e,t,n,r,s){const a=n-t,o=s-r;if(o===0){e[r]=n;return}for(let l=0;l<=o;l+=1)e[r+l]=t+Math.round(l/o*a)}function zWt(e,t){const n=Array(t.length+1).fill(0);let r=0,s=0;for(const a of LWt(e,t)){m8e(n,r,a.rawStart,s,a.renderedStart);for(let o=0;o<=a.length;o+=1)n[a.renderedStart+o]=a.rawStart+o;r=a.rawStart+a.length,s=a.renderedStart+a.length}m8e(n,r,e.length,s,t.length),n[0]=0,n[t.length]=e.length;for(let a=1;a<n.length;a+=1)n[a]=Math.max(n[a-1],Math.min(e.length,n[a]));return{rawSource:e,renderedSource:t,renderedBoundaryToRaw:n}}const $Wt={get:(e,t="preview")=>Qe.get(`/website-metadata?url=${encodeURIComponent(e)}&purpose=${encodeURIComponent(t)}`)},FWt=256,BWt=600*1e3,ky=new Map,j$=new Map;function QWt(e){try{const t=new URL(e);return t.hash="",t.href}catch{return e}}function UWt(e,t){return JSON.stringify([QWt(e),t])}function qWt(e){const t=e.split(".");if(t.length!==4)return!1;const n=t.map(Number);if(n.some(o=>!Number.isInteger(o)||o<0||o>255))return!1;const[r,s,a]=n;return r===0||r===10||r===127||r===100&&s>=64&&s<=127||r===169&&s===254||r===172&&s>=16&&s<=31||r===192&&(s===0||s===168||s===0&&a===2)||r===198&&(s===18||s===19||s===51&&a===100)||r===203&&s===0&&a===113||r>=224}function NKe(e,t=typeof window>"u"?null:window.location.origin){try{const n=new URL(e);if(n.protocol!=="http:"&&n.protocol!=="https:"||n.username||n.password||t&&n.origin===t)return!1;const r=n.hostname.replace(/^\[|\]$/gu,"").toLowerCase();return!(!r||r.includes(":")||r==="localhost"||r.endsWith(".localhost")||r.endsWith(".local")||r.endsWith(".lan")||r.endsWith(".home")||r.endsWith(".internal")||r.endsWith(".corp")||r.endsWith(".intranet")||!r.includes(".")&&!/^\d+(?:\.\d+){3}$/u.test(r)||qWt(r))}catch{return!1}}function VWt(e){const t=ky.get(e);return t?t.expiresAt<=Date.now()?(ky.delete(e),null):(ky.delete(e),ky.set(e,t),t.value):null}function WWt(e,t,n){const r=t==="authoring"?{...n,iconUrl:null}:n;for(ky.delete(e),ky.set(e,{expiresAt:Date.now()+BWt,value:r});ky.size>FWt;){const s=ky.keys().next().value;if(typeof s!="string")break;ky.delete(s)}return r}function yge(e,t){if(!NKe(e))return Promise.resolve({url:e,siteName:null,pageTitle:null,iconUrl:null});const n=UWt(e,t),r=VWt(n);if(r)return Promise.resolve(r);const s=j$.get(n);if(s)return s;const a=Promise.resolve().then(()=>$Wt.get(e,t)).then(o=>WWt(n,t,o)).finally(()=>{j$.get(n)===a&&j$.delete(n)});return j$.set(n,a),a}function vs({...e}){return i.jsx(ED,{"data-slot":"dialog",...e})}function HWt({...e}){return i.jsx(T$e,{"data-slot":"dialog-trigger",...e})}function IKe({...e}){return i.jsx(DD,{"data-slot":"dialog-portal",...e})}function KWt({...e}){return i.jsx(nN,{"data-slot":"dialog-close",...e})}function ZWt({className:e,...t}){return i.jsx(RD,{"data-slot":"dialog-overlay",className:q("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-[rgb(31_27_23/0.22)] duration-200 dark:bg-[rgb(10_11_14/0.46)]",e),...t})}function Ns({className:e,children:t,onEscapeKeyDown:n,overlayClassName:r,showCloseButton:s=!0,...a}){return i.jsxs(IKe,{"data-slot":"dialog-portal",children:[i.jsx(ZWt,{className:r}),i.jsxs(tN,{"data-slot":"dialog-content",className:q("glass-modal motion-modal fixed top-[max(0.75rem,env(safe-area-inset-top))] md:top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-1.5rem)] translate-x-[-50%] translate-y-0 gap-4 rounded-md border bg-card p-6 shadow-[0_32px_90px_-46px_rgb(20_20_20/0.34)] outline-none md:translate-y-[-50%] sm:max-w-lg dark:shadow-[0_36px_96px_-48px_rgb(0_0_0/0.58)]",e),onEscapeKeyDown:o=>{const l=o.target,c=l instanceof HTMLElement?l.closest('[data-editor-engine="codemirror-live-preview"]'):null;if(c!=null&&c.querySelector('[data-markdown-source-editor="true"][aria-expanded="true"]')){o.preventDefault();return}n==null||n(o)},...a,children:[t,s&&i.jsxs(nN,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[i.jsx(Jr,{}),i.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function di({className:e,...t}){return i.jsx("div",{"data-slot":"dialog-header",className:q("flex flex-col gap-2 text-center sm:text-left",e),...t})}function pa({className:e,showCloseButton:t=!1,children:n,...r}){return i.jsxs("div",{"data-slot":"dialog-footer",className:q("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...r,children:[n,t&&i.jsx(nN,{asChild:!0,children:i.jsx(oe,{variant:"outline",children:"Close"})})]})}function Ps({className:e,...t}){return i.jsx(LD,{"data-slot":"dialog-title",className:q("text-lg leading-none font-semibold",e),...t})}function ti({className:e,...t}){return i.jsx(_$e,{"data-slot":"dialog-description",className:q("text-muted-foreground text-sm",e),...t})}function XZ(e){return!!(e!=null&&e.toLowerCase().startsWith("image/"))}const XWt=/\.(?:bmp|gif|jpe?g|png|webp)$/i,GWt=new Set(["application/octet-stream","application/x-binary","binary/octet-stream"]);function Kx(e,t){var s;const n=(s=e==null?void 0:e.split(";",1)[0])==null?void 0:s.trim().toLowerCase();if(n){if(XZ(n))return!0;if(!GWt.has(n))return!1}const r=t.split(/[?#]/u,1)[0]??t;return XWt.test(r)}function YWt(e){switch(e.toLowerCase().split(";")[0]){case"image/jpeg":case"image/jpg":return".jpg";case"image/gif":return".gif";case"image/webp":return".webp";case"image/svg+xml":return".svg";case"image/png":default:return".png"}}function PKe(e,t,n="image"){const r=e.trim()||n;return/\.[a-z0-9]{2,8}$/i.test(r)?r:`${r}${YWt(t)}`}async function JWt(e){const t=await e.arrayBuffer(),n=new Uint8Array(t);let r="";const s=32768;for(let a=0;a<n.length;a+=s)r+=String.fromCharCode(...n.subarray(a,a+s));return btoa(r)}async function TKe(e,t,n="image"){const r=e.type||"image/png";return{filename:PKe(t,r,n),contentType:r,base64:await JWt(e)}}async function vge(e){const t=await fetch(e,{credentials:"include"});if(!t.ok)throw new Error(`Unable to load image (${t.status}).`);const n=await t.blob();if(!XZ(n.type))throw new Error("The selected asset is not an image.");return n}async function eHt(e){var n;const t=typeof ClipboardItem>"u"?null:ClipboardItem;if(!((n=navigator.clipboard)!=null&&n.write)||!t)throw new Error("Copy Image is only available in the desktop app or a clipboard-enabled browser.");await navigator.clipboard.write([new t({[e.type||"image/png"]:e})])}async function _Ke(e,t){const n=await vge(e),r=_n();if(r!=null&&r.copyImage){await r.copyImage(await TKe(n,t));return}await eHt(n)}async function MKe(e,t){const n=_n();if(!(n!=null&&n.showImageInFolder))throw new Error("Show in folder is available in the desktop app.");const r=await vge(e);await n.showImageInFolder(await TKe(r,t))}function EKe(){var e;return!!((e=_n())!=null&&e.showImageInFolder)}async function DKe(e,t){const n=await vge(e),r=URL.createObjectURL(n),s=document.createElement("a");s.href=r,s.download=PKe(t,n.type||"image/png"),document.body.appendChild(s),s.click(),s.remove(),URL.revokeObjectURL(r)}const A8e=24,tHt=1440,nHt=48,h8e=8,rHt=8,sHt=32,iHt=4,aHt=8,oHt=32;function jle(e){return!!(e&&e.width>0&&e.height>0)}function GZ(e){return{alt:e.alt,naturalSize:e.naturalWidth>0&&e.naturalHeight>0?{width:e.naturalWidth,height:e.naturalHeight}:null,src:e.currentSrc||e.src}}function YZ(e,t,n=typeof window>"u"?"http://localhost":window.location.href){var s;const r=e==null?void 0:e.trim();if(r)return r;try{const o=(s=new URL(t,n).pathname.split("/").filter(Boolean).at(-1))==null?void 0:s.trim();if(o)return decodeURIComponent(o)}catch{}return"Image preview"}function lHt(e){const t=Math.max(0,Math.floor(e)),n=t>0?aHt+t*sHt+(t-1)*iHt:0;return h8e+n+(n>0?rHt:0)+oHt+h8e}function wge(e,t){return{maxWidth:Math.max(0,Math.min(e-A8e,tHt)),maxHeight:Math.max(0,t-A8e)}}function cHt(e,t,n){const r=wge(t,n);if(!jle(e)||r.maxWidth===0||r.maxHeight===0)return{width:0,height:0};const s=Math.min(r.maxWidth/e.width,r.maxHeight/e.height,1);return{width:Math.max(1,Math.floor(e.width*s)),height:Math.max(1,Math.floor(e.height*s))}}function dHt(e,t,n,r=2){const s=wge(t,n);return{width:Math.min(s.maxWidth,Math.max(e.width,lHt(r))),height:Math.min(s.maxHeight,Math.max(e.height,nHt))}}const uHt=190,fHt=178;function RKe(e,t){return typeof window>"u"?{left:e,top:t}:{left:Math.min(e,Math.max(8,window.innerWidth-uHt)),top:Math.min(t,Math.max(8,window.innerHeight-fHt))}}function kge(e,t,n){const r=GZ(e);return{...r,name:YZ(e.getAttribute("alt"),r.src),position:RKe(t,n)}}function mHt(e){return e instanceof Error?e.message:String(e)}function JZ({name:e,onClose:t,onOpen:n,position:r,portalContainer:s,src:a,testId:o="markdown-image-context-menu"}){const l=g8(),c=A.useRef(null),d=EKe();A.useEffect(()=>{const f=h=>{var p;(p=c.current)!=null&&p.contains(h.target)||t()},m=h=>{h.key==="Escape"&&t()};return document.addEventListener("pointerdown",f),document.addEventListener("keydown",m),()=>{document.removeEventListener("pointerdown",f),document.removeEventListener("keydown",m)}},[t]);const u=async(f,m,h)=>{t();try{await m(),h&&(l==null||l.pushToast({title:h,tone:"success"}))}catch(p){l==null||l.pushToast({title:f,body:mHt(p),tone:"error"})}};return typeof document>"u"?null:ja.createPortal(i.jsxs("div",{ref:c,"data-testid":o,role:"menu",className:`motion-chat-composer-menu-pop surface-overlay z-50 min-w-[190px] rounded-[var(--radius-lg)] border p-1.5 text-foreground shadow-[var(--shadow-lg)] ${s?"absolute":"fixed"}`,style:r,children:[n?i.jsxs("button",{type:"button",role:"menuitem",className:"chat-composer-menu-row w-full",onClick:()=>{t(),n()},children:[i.jsx(Ki,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:"Open Image"})]}):null,i.jsxs("button",{type:"button",role:"menuitem",className:"chat-composer-menu-row w-full",onClick:()=>u("Copy Image failed",()=>_Ke(a,e),"Image copied"),children:[i.jsx(No,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:"Copy Image"})]}),i.jsxs("button",{type:"button",role:"menuitem",className:"chat-composer-menu-row w-full",onClick:()=>u("Download Image failed",()=>DKe(a,e)),children:[i.jsx(Rf,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:"Download Image"})]}),d?i.jsxs("button",{type:"button",role:"menuitem",className:"chat-composer-menu-row w-full",onClick:()=>u("Show in folder failed",()=>MKe(a,e)),children:[i.jsx(Bo,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:"Show in folder"})]}):null]}),s??document.body)}function p8e(){return typeof window>"u"?{width:1440,height:900}:{width:window.innerWidth,height:window.innerHeight}}function AHt({onCloseAutoFocus:e,preview:t,onOpenChange:n,testId:r,titleFallback:s}){const a=g8(),o=A.useRef(null),[l,c]=A.useState((t==null?void 0:t.naturalSize)??null),[d,u]=A.useState(()=>p8e()),[f,m]=A.useState(null),h=EKe();A.useEffect(()=>{if(m(null),!t){c(null);return}if(c(jle(t.naturalSize)?t.naturalSize:null),!t.src||jle(t.naturalSize))return;const w=new window.Image;return w.onload=()=>{c({width:w.naturalWidth,height:w.naturalHeight})},w.onerror=()=>{c(null)},w.src=t.src,()=>{w.onload=null,w.onerror=null}},[t]),A.useEffect(()=>{if(!t||typeof window>"u")return;const w=()=>{u(p8e())};return w(),window.addEventListener("resize",w),()=>{window.removeEventListener("resize",w)}},[t]);const p=A.useMemo(()=>l?cHt(l,d.width,d.height):null,[l,d.height,d.width]),x=A.useMemo(()=>wge(d.width,d.height),[d.height,d.width]),b=A.useMemo(()=>dHt(p??{width:0,height:0},d.width,d.height,h?3:2),[h,p,d.height,d.width]),y=async(w,k,S)=>{if(t)try{await k(),S&&(a==null||a.pushToast({title:S,tone:"success"}))}catch(j){a==null||a.pushToast({title:w,body:j instanceof Error?j.message:String(j),tone:"error"})}};return i.jsx(vs,{open:t!==null,onOpenChange:n,children:i.jsxs(Ns,{ref:o,"aria-describedby":void 0,role:t?"dialog":void 0,showCloseButton:!1,onCloseAutoFocus:w=>{w.preventDefault(),e==null||e()},className:"rudder-markdown-editor-image-preview-panel top-[50%] w-fit translate-y-[-50%] border-0 bg-transparent p-0 shadow-none",style:{maxWidth:`${x.maxWidth}px`,width:`${b.width}px`},children:[i.jsx(Ps,{className:"sr-only",children:(t==null?void 0:t.name)??s}),t?i.jsxs("div",{"data-testid":r,className:"rudder-markdown-editor-image-preview-media relative flex w-fit max-w-full items-center justify-center overflow-hidden",style:{width:`${b.width}px`,height:`${b.height}px`},children:[i.jsxs(KWt,{className:"absolute right-2 top-2 z-10 flex size-8 items-center justify-center rounded-sm bg-black/55 text-white shadow-[0_6px_18px_rgb(0_0_0/0.28)] transition-colors hover:bg-black/70 focus:outline-none focus:ring-2 focus:ring-white/80",children:[i.jsx(Jr,{className:"size-4","aria-hidden":"true"}),i.jsx("span",{className:"sr-only",children:"Close image preview"})]}),i.jsxs("div",{className:"absolute left-2 top-2 z-10 flex items-center gap-1 rounded-sm bg-black/55 p-1 text-white shadow-[0_6px_18px_rgb(0_0_0/0.28)]",children:[i.jsxs("button",{type:"button",className:"rudder-image-preview-action",title:"Copy Image",onClick:()=>y("Copy Image failed",()=>_Ke(t.src,t.name),"Image copied"),children:[i.jsx(No,{className:"size-4","aria-hidden":"true"}),i.jsx("span",{className:"sr-only",children:"Copy Image"})]}),i.jsxs("button",{type:"button",className:"rudder-image-preview-action",title:"Download Image",onClick:()=>y("Download Image failed",()=>DKe(t.src,t.name)),children:[i.jsx(Rf,{className:"size-4","aria-hidden":"true"}),i.jsx("span",{className:"sr-only",children:"Download Image"})]}),h?i.jsxs("button",{type:"button",className:"rudder-image-preview-action",title:"Show in folder",onClick:()=>y("Show in folder failed",()=>MKe(t.src,t.name)),children:[i.jsx(Bo,{className:"size-4","aria-hidden":"true"}),i.jsx("span",{className:"sr-only",children:"Show in folder"})]}):null]}),i.jsx("img",{src:t.src,alt:t.alt,className:"chat-attachment-preview-image",style:p?{width:"100%",height:"100%"}:void 0,onContextMenu:w=>{var j;w.preventDefault(),w.stopPropagation();const k=kge(w.currentTarget,w.clientX,w.clientY),S=(j=o.current)==null?void 0:j.getBoundingClientRect();m(S?{...k,position:{left:k.position.left-S.left,top:k.position.top-S.top}}:k)}}),f?i.jsx(JZ,{name:f.name,onClose:()=>m(null),position:f.position,portalContainer:o.current,src:f.src,testId:"image-preview-context-menu"}):null]}):null]})})}const hHt={closeImagePreview:()=>{},openImagePreview:()=>{}},LKe=A.createContext(hHt);function pHt({children:e}){const t=Ir(),[n,r]=A.useState(null),s=A.useRef(null),a=A.useRef(null),o=A.useCallback(()=>{s.current=null,r(null)},[]),l=A.useCallback(u=>{if(!s.current&&typeof document<"u"){const f=document.activeElement;a.current=f instanceof HTMLElement?f:null}s.current=u,r(u)},[]),c=A.useCallback(()=>{const u=a.current;a.current=null,u!=null&&u.isConnected&&u.focus()},[]),d=A.useMemo(()=>({closeImagePreview:o,openImagePreview:l}),[o,l]);return A.useEffect(()=>{o()},[o,t.hash,t.pathname,t.search]),i.jsxs(LKe.Provider,{value:d,children:[e,i.jsx(AHt,{onCloseAutoFocus:c,preview:n,onOpenChange:u=>{u||o()},testId:(n==null?void 0:n.testId)??"global-image-preview-dialog",titleFallback:(n==null?void 0:n.titleFallback)??"Image preview"})]})}function AR(){return A.useContext(LKe)}const gHt=16/9;function g8e(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)&&t>0?t:null}function xHt(e,t){const n=g8e(e),r=g8e(t);return n&&r?n/r:null}function U0({alt:e,className:t,name:n,previewTestId:r,previewTitleFallback:s,showInspectOverlay:a=!0,src:o,triggerClassName:l,wrapperClassName:c,onLoad:d,onError:u,...f}){const{openImagePreview:m}=AR(),h=A.useRef(null),[p,x]=A.useState(null),[b,y]=A.useState("loading"),[w,k]=A.useState(null),[S,j]=A.useState(0),C=A.useCallback(()=>x(null),[]),I=xHt(f.width,f.height),N=b==="error",E={"--rudder-image-aspect-ratio":String(w??I??gHt)};A.useEffect(()=>{y("loading"),k(null),j(0),x(null)},[I,o]),A.useEffect(()=>{const Y=h.current;!(Y!=null&&Y.complete)||Y.naturalWidth<=0||Y.naturalHeight<=0||(k(Y.naturalWidth/Y.naturalHeight),y("loaded"))},[S,o]);const _=Y=>{const G=Y.currentTarget;G.naturalWidth>0&&G.naturalHeight>0&&k(G.naturalWidth/G.naturalHeight),y("loaded"),d==null||d(Y)},z=()=>{y("loading"),k(I),x(null),j(Y=>Y+1)},T=()=>{const Y=h.current;Y&&m({...GZ(Y),name:n,testId:r,titleFallback:s})},$=Y=>{if(Y.preventDefault(),Y.stopPropagation(),N){z();return}T()},B=Y=>{if(!(Y.key!=="Enter"&&Y.key!==" ")){if(Y.preventDefault(),Y.stopPropagation(),N){z();return}T()}},F=Y=>{N||(Y.preventDefault(),Y.stopPropagation(),x(RKe(Y.clientX,Y.clientY)))},W=Y=>{y("error"),x(null),u==null||u(Y)};return i.jsxs("span",{className:`rudder-inspectable-image${c?` ${c}`:""}`,"data-image-state":b,children:[i.jsxs("button",{type:"button",className:`rudder-inspectable-image-trigger${l?` ${l}`:""}`,"aria-busy":b==="loading"?"true":void 0,"aria-label":N?`Retry loading image: ${n}`:`Open image preview: ${n}`,"data-image-state":b,title:N?`Retry loading image: ${n}`:"Open image preview",onClick:$,onDoubleClick:$,onKeyDown:B,onContextMenu:F,children:[N?i.jsxs("span",{className:"rudder-inspectable-image-fallback",role:"img","aria-label":`${n} unavailable`,children:[i.jsx(_ze,{className:"size-4 shrink-0","aria-hidden":"true"}),i.jsx("span",{className:"rudder-inspectable-image-fallback-label",children:"Image unavailable. Click to retry."})]}):i.jsxs("span",{className:"rudder-inspectable-image-frame","data-image-state":b,style:E,children:[b==="loading"?i.jsx("span",{"aria-label":`Loading image: ${n}`,className:"rudder-inspectable-image-skeleton","data-testid":"inspectable-image-skeleton",role:"status"}):null,i.jsx("img",{...f,ref:h,src:o,alt:e??"",className:t,onError:W,onLoad:_,onContextMenu:F},`${o}:${S}`)]}),a&&b==="loaded"?i.jsx("span",{className:"rudder-inspectable-image-overlay","aria-hidden":"true",children:i.jsx(v0,{className:"size-3.5"})}):null]}),p?i.jsx(JZ,{name:n,onClose:C,onOpen:T,position:p,src:o}):null]})}function bHt(e){var n,r;const t=((r=(n=e.split(/[\\/]/u).at(-1))==null?void 0:n.toLowerCase().match(/\.([^.]+)$/u))==null?void 0:r[1])??"";return["png","jpg","jpeg","gif","webp","svg","bmp","ico","avif"].includes(t)?"image":["zip","tar","gz","tgz","bz2","xz","7z","rar"].includes(t)?"archive":["csv","tsv","xls","xlsx","ods"].includes(t)?"spreadsheet":["ts","tsx","js","jsx","mjs","cjs","py","rb","go","rs","java","kt","kts","c","cc","cpp","h","hpp","cs","swift","php","sh","bash","zsh","fish","html","css","scss","less","json","jsonc","yaml","yml","toml","xml","sql","vue","svelte"].includes(t)?"code":["md","mdx","txt","pdf","doc","docx","rtf"].includes(t)?"document":"file"}const yHt={archive:D3t,code:Bp,document:Aa,file:Nze,image:jze,spreadsheet:G3t};function zKe(e){const t=bHt(e),n=yHt[t];return{Icon:n,kind:t,mask:A3(n,`local-file:${t}`)}}function vHt(e){var n;const t=((n=e.contentType.split(";",1)[0])==null?void 0:n.trim().toLowerCase())??"";return e.previewKind!=="image"||!t.startsWith("image/")||!e.base64?null:`data:${t};base64,${e.base64}`}function $Ke({filePath:e}){const{Icon:t,kind:n}=zKe(e);return i.jsx(t,{className:"mr-1 inline-block size-[0.95em] align-[-0.12em]","data-local-file-icon":n,"aria-hidden":"true"})}function FKe({children:e,enablePreview:t,href:n,imageName:r,onClick:s,sourceAttributes:a,targetPath:o}){const[l,c]=A.useState(null);return A.useEffect(()=>{let d=!1;c(null);const u=_n();if(u)return u.previewLocalFile(o).then(f=>{if(d)return;const m=vHt(f);m&&c(m)}).catch(()=>{}),()=>{d=!0}},[o]),l?t?i.jsx(U0,{...a,src:l,alt:r,name:r,className:"rudder-local-image-media",wrapperClassName:"rudder-local-image",triggerClassName:"rudder-local-image-trigger",previewTestId:"markdown-body-image-preview-dialog",previewTitleFallback:"Image preview"}):i.jsx("img",{...a,src:l,alt:r,className:"rudder-local-image-media"}):i.jsxs("a",{href:n,className:"rudder-local-file-link",title:r||void 0,...a,onClick:s,children:[i.jsx($Ke,{filePath:o}),i.jsx("span",{className:"rudder-inline-token-label",children:e})]})}function BKe({children:e,enablePreview:t,filePath:n,href:r,label:s,onClick:a,sourceAttributes:o}){if(Kx(null,n)){const l=s.trim()||n.split(/[\\/]/u).at(-1)||"Local image";return i.jsx(FKe,{href:r,enablePreview:t,imageName:l,targetPath:n,sourceAttributes:o,onClick:a,children:e})}return i.jsxs("a",{href:r,className:"rudder-local-file-link",title:s||void 0,...o,onClick:a,children:[i.jsx($Ke,{filePath:n}),i.jsx("span",{className:"rudder-inline-token-label",children:e})]})}function wHt({alt:e,enablePreview:t,onClick:n,sourceAttributes:r,src:s}){const a=mR(s),o=ZZ(s);if(!a||!o)return null;const l=(e==null?void 0:e.trim())||o.split(/[\\/]/u).at(-1)||"Local image";return Kx(null,o)?i.jsx(FKe,{href:s,enablePreview:t,imageName:l,targetPath:a,sourceAttributes:r,onClick:c=>n(c,l),children:l}):i.jsx(BKe,{enablePreview:t,href:s,filePath:o,label:l,sourceAttributes:r,onClick:c=>n(c,l),children:l})}const kHt=700;function OHt(e){if(!e||typeof window>"u")return null;try{const t=window.sessionStorage.getItem(e);if(t===null)return null;const n=Number.parseFloat(t);return Number.isFinite(n)?n:null}catch{return null}}function SHt(e,t){if(!(!e||typeof window>"u"))try{window.sessionStorage.setItem(e,String(t))}catch{}}function is(e){const t=A.useRef(null),n=A.useRef(null);return A.useCallback(r=>{var o;if((o=t.current)==null||o.call(t),t.current=null,n.current&&(clearTimeout(n.current),n.current=null),!r)return;const s=OHt(e);s!==null&&requestAnimationFrame(()=>{r.scrollTop=s});const a=()=>{r.classList.add("is-scrolling"),SHt(e,r.scrollTop),n.current&&clearTimeout(n.current),n.current=setTimeout(()=>{r.classList.remove("is-scrolling"),n.current=null},kHt)};r.addEventListener("scroll",a,{passive:!0}),t.current=()=>{r.removeEventListener("scroll",a),n.current&&(clearTimeout(n.current),n.current=null),r.classList.remove("is-scrolling")}},[e])}const jHt="rudder.libraryEntryCache",x8e=300*1e3,CHt="rudder.selectedOrganizationId",DP=new Map;function QKe(e,t){return`${e}:library-entry:${t}`}function Cle(){return Date.now()}function UKe(e){return!!(e&&e.expiresAt>Cle())}function NHt(e,t){return`${jHt}.${e}.${t}`}function IHt(e){return typeof e=="string"&&e.trim().length>0?e:null}function PHt(e,t){var n;if(typeof window>"u")return null;try{const r=(n=window.sessionStorage)==null?void 0:n.getItem(NHt(e,t));if(!r)return null;const s=JSON.parse(r),a=IHt(s==null?void 0:s.currentPath);return a?{currentPath:a}:null}catch{return null}}function THt(){var e;return typeof window>"u"||typeof((e=window.localStorage)==null?void 0:e.getItem)!="function"?null:window.localStorage.getItem(CHt)}function _Ht(e,t){if(!e||!t)return null;const n=DP.get(QKe(e,t));return UKe(n)&&(n!=null&&n.entry)?n.entry:PHt(e,t)}function qKe(e,t){const n=QKe(e,t),r=DP.get(n);if(UKe(r)){if(r!=null&&r.entry)return Promise.resolve(r.entry);if(r!=null&&r.promise)return r.promise}const s=Hn.getLibraryEntry(e,t).then(a=>(DP.set(n,{entry:a,expiresAt:Cle()+x8e}),a)).catch(a=>{throw DP.delete(n),a});return DP.set(n,{promise:s,expiresAt:Cle()+x8e}),s}function MHt(e,t){!e||!t||qKe(e,t).catch(()=>{})}const EHt={backlog:"text-orange-500 dark:text-orange-400",todo:"text-muted-foreground",in_progress:"text-yellow-600 dark:text-yellow-400",in_review:"text-violet-600 dark:text-violet-400",done:"text-green-600 dark:text-green-400",cancelled:"text-neutral-500 dark:text-neutral-400",blocked:"text-red-600 dark:text-red-400"},DHt="text-muted-foreground",yI={backlog:"text-muted-foreground",todo:"text-blue-600 dark:text-blue-400",in_progress:"text-yellow-600 dark:text-yellow-400",in_review:"text-violet-600 dark:text-violet-400",done:"text-green-600 dark:text-green-400"},hR={active:"border-green-200/80 bg-green-100/85 text-green-800 dark:border-green-700/50 dark:bg-green-900/30 dark:text-green-200",running:"border-cyan-200/80 bg-cyan-100/85 text-cyan-800 dark:border-cyan-700/50 dark:bg-cyan-900/30 dark:text-cyan-200",paused:"border-orange-200/80 bg-orange-100/85 text-orange-800 dark:border-orange-700/50 dark:bg-orange-900/30 dark:text-orange-200",idle:"border-yellow-200/80 bg-yellow-100/85 text-yellow-800 dark:border-yellow-700/50 dark:bg-yellow-900/30 dark:text-yellow-200",archived:"border-[color:var(--border-soft)] bg-muted text-muted-foreground",planned:"border-[color:var(--border-soft)] bg-muted text-muted-foreground",achieved:"border-green-200/80 bg-green-100/85 text-green-800 dark:border-green-700/50 dark:bg-green-900/30 dark:text-green-200",completed:"border-green-200/80 bg-green-100/85 text-green-800 dark:border-green-700/50 dark:bg-green-900/30 dark:text-green-200",failed:"border-red-200/80 bg-red-100/85 text-red-800 dark:border-red-700/50 dark:bg-red-900/30 dark:text-red-200",timed_out:"border-orange-200/80 bg-orange-100/85 text-orange-800 dark:border-orange-700/50 dark:bg-orange-900/30 dark:text-orange-200",succeeded:"border-green-200/80 bg-green-100/85 text-green-800 dark:border-green-700/50 dark:bg-green-900/30 dark:text-green-200",waiting_for_network:"border-amber-200/80 bg-amber-100/85 text-amber-800 dark:border-amber-700/50 dark:bg-amber-900/30 dark:text-amber-200",error:"border-red-200/80 bg-red-100/85 text-red-800 dark:border-red-700/50 dark:bg-red-900/30 dark:text-red-200",terminated:"border-red-200/80 bg-red-100/85 text-red-800 dark:border-red-700/50 dark:bg-red-900/30 dark:text-red-200",pending:"border-yellow-200/80 bg-yellow-100/85 text-yellow-800 dark:border-yellow-700/50 dark:bg-yellow-900/30 dark:text-yellow-200",pending_approval:"border-amber-200/80 bg-amber-100/85 text-amber-800 dark:border-amber-700/50 dark:bg-amber-900/30 dark:text-amber-200",revision_requested:"border-amber-200/80 bg-amber-100/85 text-amber-800 dark:border-amber-700/50 dark:bg-amber-900/30 dark:text-amber-200",approved:"border-green-200/80 bg-green-100/85 text-green-800 dark:border-green-700/50 dark:bg-green-900/30 dark:text-green-200",rejected:"border-red-200/80 bg-red-100/85 text-red-800 dark:border-red-700/50 dark:bg-red-900/30 dark:text-red-200",backlog:"border-[color:var(--border-soft)] bg-muted text-muted-foreground",todo:"border-blue-200/80 bg-blue-100/85 text-blue-800 dark:border-blue-700/50 dark:bg-blue-900/30 dark:text-blue-200",in_progress:"border-yellow-200/80 bg-yellow-100/85 text-yellow-800 dark:border-yellow-700/50 dark:bg-yellow-900/30 dark:text-yellow-200",in_review:"border-violet-200/80 bg-violet-100/85 text-violet-800 dark:border-violet-700/50 dark:bg-violet-900/30 dark:text-violet-200",blocked:"border-red-200/80 bg-red-100/85 text-red-800 dark:border-red-700/50 dark:bg-red-900/30 dark:text-red-200",done:"border-green-200/80 bg-green-100/85 text-green-800 dark:border-green-700/50 dark:bg-green-900/30 dark:text-green-200",cancelled:"border-[color:var(--border-soft)] bg-muted text-muted-foreground"},pR="border-[color:var(--border-soft)] bg-muted text-muted-foreground",RHt={running:"bg-cyan-400 animate-pulse",active:"bg-green-400",paused:"bg-yellow-400",idle:"bg-yellow-400",pending_approval:"bg-amber-400",error:"bg-red-400",archived:"bg-neutral-400"},LHt="bg-neutral-400",C$={critical:"text-orange-600 dark:text-orange-400",high:"text-orange-500 dark:text-orange-400",medium:"text-orange-400 dark:text-orange-300/80",low:"text-orange-300 dark:text-orange-300/55"},cM={critical:{value:"critical",label:"Urgent",level:4,color:C$.critical,menuLabelClassName:"font-medium text-orange-700 dark:text-orange-300"},high:{value:"high",label:"High",level:3,color:C$.high,menuLabelClassName:"font-medium text-orange-600 dark:text-orange-300"},medium:{value:"medium",label:"Medium",level:2,color:C$.medium,menuLabelClassName:"font-medium text-foreground"},low:{value:"low",label:"Low",level:1,color:C$.low,menuLabelClassName:"font-medium text-muted-foreground"}},VKe=["critical","high","medium","low"],zHt=VKe.map(e=>cM[e]);function $Ht(e){return e.replace(/_/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function WKe(e){return cM[e]??cM.medium}function Hd(e){var t;return((t=cM[e])==null?void 0:t.label)??$Ht(e)}function uu({className:e,size:t="default",...n}){return i.jsx(a7t,{"data-slot":"avatar","data-size":t,className:q("group/avatar relative flex size-8 shrink-0 overflow-hidden rounded-full select-none data-[size=lg]:size-10 data-[size=sm]:size-6 data-[size=xs]:size-5",e),...n})}function gR({className:e,...t}){return i.jsx(o7t,{"data-slot":"avatar-image",className:q("aspect-square size-full",e),...t})}function fu({className:e,...t}){return i.jsx(l7t,{"data-slot":"avatar-fallback",className:q("bg-muted text-muted-foreground flex size-full items-center justify-center rounded-full text-sm group-data-[size=sm]/avatar:text-xs group-data-[size=xs]/avatar:text-[10px]",e),...t})}function HKe({className:e,...t}){return i.jsx("div",{"data-slot":"avatar-group",className:q("*:data-[slot=avatar]:ring-background group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2",e),...t})}function KKe({className:e,...t}){return i.jsx("div",{"data-slot":"avatar-group-count",className:q("bg-muted text-muted-foreground ring-background relative flex size-8 shrink-0 items-center justify-center rounded-full text-sm ring-2 group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=sm]/avatar-group:size-6 [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3",e),...t})}const FHt={xs:"text-sm",sm:"text-xs",default:"text-sm",lg:"text-sm"},BHt={xs:"h-3 w-3 text-[10px]",sm:"h-3 w-3 text-xs",default:"h-4 w-4 text-sm",lg:"h-4.5 w-4.5 text-base"};function Rh({icon:e,role:t,fallbackSeed:n,className:r,style:s}){const o=jp(e)??oge(t),l=xN(o)??ige(n);if(l){const d=Iq(o);return i.jsx("img",{src:l,alt:"",className:q("inline-flex rounded-full object-cover",r),style:{background:d==="oreo"?void 0:gS(o).background,...age(o),...s},loading:"lazy"})}const c=lge(o);return i.jsx(c,{className:r})}function zl({name:e,icon:t,role:n,size:r="default",className:s}){const a=jp(t)??oge(n),o=xN(a)??ige(e);return i.jsxs("span",{className:q("inline-flex gap-1.5",r==="xs"?"items-baseline gap-1":"items-center",r==="lg"&&"gap-2",s),children:[i.jsx(uu,{size:r,className:r==="xs"?"relative -top-px":void 0,children:o?i.jsx(Rh,{icon:a,fallbackSeed:e,className:"size-full"}):i.jsx(fu,{children:i.jsx(Rh,{icon:a,className:BHt[r]})})}),i.jsx("span",{className:q("truncate",FHt[r]),children:e})]})}function bi({...e}){return i.jsx(nZ,{"data-slot":"popover",...e})}function Hi({...e}){return i.jsx(kjt,{"data-slot":"popover-trigger",...e})}function yi({className:e,align:t="center",sideOffset:n=4,disablePortal:r=!1,...s}){const a=i.jsx(WBe,{"data-slot":"popover-content",align:t,sideOffset:n,className:q("motion-surface-pop bg-popover text-popover-foreground z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",e),...s});return r?a:i.jsx(rZ,{children:a})}function Mq({...e}){return i.jsx(VBe,{"data-slot":"popover-anchor",...e})}const QHt=["h-1","h-1.5","h-2.5","h-3.5"],ZKe="w-48 rounded-lg border-[color:var(--border-base)] bg-[color:var(--surface-overlay)] p-1.5 shadow-[var(--shadow-md)]";function eX({priority:e,className:t}){const n=WKe(e);return i.jsx("span",{"data-slot":"priority-bars-icon",className:q("inline-flex h-3.5 w-4 items-end gap-[2px]",n.color,t),"aria-hidden":"true",children:QHt.map((r,s)=>i.jsx("span",{className:q("w-[3px] rounded-[1px] bg-current",r,s>=n.level&&"opacity-25")},r))})}function XKe({priority:e,selected:t,onSelect:n}){const r=cM[e];return i.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":t,className:q("group flex h-8 w-full items-center justify-between gap-3 rounded-md px-2 text-left text-sm transition-colors hover:bg-[color:var(--surface-active)] focus-visible:bg-[color:var(--surface-active)] focus-visible:outline-none",t&&"bg-[color:color-mix(in_oklab,var(--surface-active)_72%,transparent)] text-foreground"),onClick:()=>n(e),children:[i.jsxs("span",{className:"inline-flex min-w-0 items-center gap-2",children:[i.jsx(eX,{priority:e,className:"shrink-0"}),i.jsx("span",{className:q("truncate",r.menuLabelClassName),children:r.label})]}),t?i.jsx(zi,{"data-slot":"priority-menu-check",className:"h-4 w-4 shrink-0 text-muted-foreground"}):i.jsx("span",{className:"h-4 w-4 shrink-0","aria-hidden":"true"})]})}function Dc({priority:e,onChange:t,className:n,showLabel:r}){const[s,a]=A.useState(!1),o=WKe(e),l=i.jsx("span",{className:q("inline-flex items-center justify-center shrink-0",t&&!r&&"cursor-pointer",n),children:i.jsx(eX,{priority:e})});if(!t)return r?i.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[l,i.jsx("span",{className:"text-sm",children:o.label})]}):l;const c=r?i.jsxs("button",{type:"button","aria-label":`Edit priority, current priority ${o.label}`,className:"-mx-1 inline-flex cursor-pointer items-center gap-1.5 rounded-md px-1 py-0.5 transition-colors hover:bg-[color:var(--surface-active)]",children:[l,i.jsx("span",{className:"text-sm",children:o.label})]}):l;return i.jsxs(bi,{open:s,onOpenChange:a,children:[i.jsx(Hi,{asChild:!0,children:c}),i.jsx(yi,{className:ZKe,align:"start",role:"menu","aria-label":"Issue priority",children:VKe.map(d=>{const u=d===e;return i.jsx(XKe,{priority:d,selected:u,onSelect:f=>{t(f),a(!1)}},d)})})]})}const UHt="linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)",qHt=/^#[0-9a-fA-F]{6}$/,VHt=/^#[0-9a-fA-F]{3}$/,WHt=/^linear-gradient\(\s*(?:\d{1,3}deg|to\s+(?:top|bottom|left|right)(?:\s+(?:top|bottom|left|right))?)\s*,\s*#[0-9a-fA-F]{6}(?:\s+\d{1,3}%?)?\s*,\s*#[0-9a-fA-F]{6}(?:\s+\d{1,3}%?)?\s*\)$/;function HHt(e){const t=e.slice(1).toLowerCase();return`#${t[0]}${t[0]}${t[1]}${t[1]}${t[2]}${t[2]}`}function Oge(e,t=UHt){const n=e==null?void 0:e.trim();return n?qHt.test(n)?n.toLowerCase():VHt.test(n)?HHt(n):WHt.test(n)?n:t:t}function KHt(e){return{background:Oge(e)}}function ZHt(e){var r;const n=(r=Oge(e).match(/#[0-9a-fA-F]{6}/))==null?void 0:r[0];return(n==null?void 0:n.toLowerCase())??"#6366f1"}function Sge(e){return{"--project-color":Oge(e),"--project-accent-color":ZHt(e)}}const XHt={xs:"h-4 w-4 rounded-[calc(var(--radius-sm)-3px)]",sm:"h-5 w-5 rounded-[calc(var(--radius-sm)-2px)]",md:"h-6 w-6 rounded-[calc(var(--radius-sm)-1px)]",lg:"h-9 w-9 rounded-[var(--radius-sm)]"},GHt={xs:"h-4 w-4",sm:"h-[18px] w-[18px]",md:"h-5 w-5",lg:"h-7 w-7"};function Fo({color:e,icon:t,size:n="sm",className:r,iconClassName:s,label:a,testId:o}){const l=WZ(t);return i.jsx("span",{"data-testid":o,className:q("inline-flex shrink-0 items-center justify-center text-[color:var(--project-accent-color)]",XHt[n],r),style:Sge(e),"aria-label":a,"aria-hidden":a?void 0:!0,children:i.jsx(l,{className:q(GHt[n],s),strokeWidth:2.3})})}const jge=A.forwardRef(({projectColor:e,projectIcon:t,label:n,className:r,title:s,...a},o)=>i.jsx("button",{...a,ref:o,type:"button",className:q("inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] outline-none transition-[box-shadow,transform] hover:scale-[1.03] focus-visible:ring-2 focus-visible:ring-ring",r),"aria-label":n,title:s??n,children:i.jsx(Fo,{color:e,icon:t,size:"lg"})}));jge.displayName="ProjectIdentityTriggerButton";function GKe({color:e,icon:t,onColorChange:n,onIconChange:r,className:s}){const a=VZ(t);return i.jsxs("div",{className:q("w-72 space-y-3 p-2",s),style:Sge(e),children:[i.jsx("div",{className:"grid grid-cols-6 gap-1.5","aria-label":"Project colors",children:vT.map(o=>{const l=o===e;return i.jsx("button",{type:"button",className:q("relative h-7 w-7 rounded-[calc(var(--radius-sm)-1px)] outline-none transition-[box-shadow,transform] hover:scale-[1.04] focus-visible:ring-2 focus-visible:ring-ring",l?"ring-2 ring-foreground ring-offset-1 ring-offset-background":"ring-1 ring-[color:color-mix(in_oklab,var(--border-base)_72%,transparent)]"),style:KHt(o),"aria-label":"Select project color","aria-pressed":l,onClick:()=>n(o)},o)})}),i.jsx(YHt,{icon:a,onIconChange:r}),i.jsxs("div",{className:"flex items-center gap-2 rounded-[calc(var(--radius-sm)-1px)] border border-border/70 bg-muted/35 px-2 py-1.5",children:[i.jsx(Fo,{color:e,icon:a||gZ,size:"lg"}),i.jsx("span",{className:"min-w-0 truncate text-xs text-muted-foreground",children:a})]})]})}function YHt({icon:e,selectedIcon:t,onIconChange:n,ariaLabel:r="Project icons"}){const s=t===null?null:VZ(t??e);return i.jsx("div",{className:"grid grid-cols-6 gap-1.5","aria-label":r,children:JD.map(a=>{const o=WZ(a),l=a===s;return i.jsxs("button",{type:"button",className:q("relative inline-flex h-9 w-9 items-center justify-center rounded-[calc(var(--radius-sm)-1px)] border text-muted-foreground outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring",l?"border-[color:color-mix(in_oklab,var(--project-accent-color)_54%,var(--border-base))] bg-muted/55 text-[color:var(--project-accent-color)]":"border-border/70 bg-transparent"),"aria-label":`Select ${a} project icon`,"aria-pressed":l,onClick:()=>n(a),children:[i.jsx(o,{className:"h-5 w-5",strokeWidth:2.2}),l?i.jsx(zi,{className:"absolute h-2.5 w-2.5 translate-x-3 translate-y-3 text-[color:var(--project-accent-color)]"}):null]},a)})})}const YKe=["backlog","todo","in_progress","in_review","done","cancelled","blocked"],JHt="w-48 rounded-lg border-[color:var(--border-base)] bg-[color:var(--surface-overlay)] p-1.5 shadow-[var(--shadow-md)]";function JKe(e){return e.replace(/_/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function eZe({status:e,className:t,dataSlot:n="issue-status-icon"}){const r=EHt[e]??DHt,s=YKe.includes(e)?e:"default";return i.jsx("span",{"data-slot":n,"data-status":e,className:q("inline-flex h-4 w-4 shrink-0 items-center justify-center",r,t),"aria-hidden":"true",children:i.jsxs("svg",{viewBox:"0 0 16 16",className:"h-full w-full overflow-visible text-current",fill:"none",children:[s==="backlog"&&i.jsx("circle",{"data-slot":"status-backlog-ring",cx:"8",cy:"8",r:"5.5",stroke:"currentColor",strokeWidth:"2",strokeDasharray:"1 3",strokeLinecap:"round"}),s==="todo"&&i.jsx("circle",{cx:"8",cy:"8",r:"5.5",stroke:"currentColor",strokeWidth:"2"}),s==="in_progress"&&i.jsxs(i.Fragment,{children:[i.jsx("circle",{cx:"8",cy:"8",r:"5.5",stroke:"currentColor",strokeWidth:"2",opacity:"0.22"}),i.jsx("path",{"data-slot":"status-progress-arc",d:"M8 2.5a5.5 5.5 0 0 1 5.5 5.5",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round"}),i.jsx("path",{d:"M13.5 8a5.5 5.5 0 0 1-5.5 5.5",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",opacity:"0.72"})]}),s==="in_review"&&i.jsxs(i.Fragment,{children:[i.jsx("circle",{cx:"8",cy:"8",r:"5.5",stroke:"currentColor",strokeWidth:"2"}),i.jsx("circle",{"data-slot":"status-review-dot",cx:"8",cy:"8",r:"2",fill:"currentColor"})]}),s==="done"&&i.jsxs(i.Fragment,{children:[i.jsx("circle",{cx:"8",cy:"8",r:"6.5",fill:"currentColor"}),i.jsx("path",{"data-slot":"status-done-check",d:"M4.75 8.25 7 10.5l4.25-5",stroke:"var(--background)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]}),s==="cancelled"&&i.jsxs(i.Fragment,{children:[i.jsx("circle",{cx:"8",cy:"8",r:"6",fill:"currentColor",opacity:"0.16"}),i.jsx("circle",{cx:"8",cy:"8",r:"5.5",stroke:"currentColor",strokeWidth:"2"}),i.jsx("path",{"data-slot":"status-cancel-mark",d:"m5.25 5.25 5.5 5.5m0-5.5-5.5 5.5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),s==="blocked"&&i.jsxs(i.Fragment,{children:[i.jsx("path",{d:"M5.1 2.25h5.8l3.05 3.05v5.4l-3.05 3.05H5.1L2.05 10.7V5.3Z",stroke:"currentColor",strokeWidth:"2",strokeLinejoin:"round"}),i.jsx("path",{"data-slot":"status-blocked-mark",d:"m5.25 5.25 5.5 5.5",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"})]}),s==="default"&&i.jsx("circle",{cx:"8",cy:"8",r:"5.5",stroke:"currentColor",strokeWidth:"2"})]})})}function eKt({status:e,selected:t,onSelect:n}){return i.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":t,className:q("group flex h-8 w-full items-center justify-between gap-3 rounded-md px-2 text-left text-sm transition-colors hover:bg-[color:var(--surface-active)] focus-visible:bg-[color:var(--surface-active)] focus-visible:outline-none",t&&"bg-[color:color-mix(in_oklab,var(--surface-active)_72%,transparent)] text-foreground"),onClick:()=>n(e),children:[i.jsxs("span",{className:"inline-flex min-w-0 items-center gap-2",children:[i.jsx(eZe,{status:e}),i.jsx("span",{className:"truncate",children:JKe(e)})]}),t?i.jsx(zi,{"data-slot":"status-menu-check",className:"h-4 w-4 shrink-0 text-muted-foreground"}):i.jsx("span",{className:"h-4 w-4 shrink-0","aria-hidden":"true"})]})}function ki({status:e,onChange:t,className:n,showLabel:r,label:s,dataSlot:a}){const[o,l]=A.useState(!1),c=i.jsx(eZe,{status:e,className:n,dataSlot:a}),d=s??JKe(e);if(!t)return r?i.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[c,i.jsx("span",{className:"text-sm",children:d})]}):c;const u=r?i.jsxs("button",{type:"button",className:"-mx-1 inline-flex cursor-pointer items-center gap-1.5 rounded-md px-1 py-0.5 transition-colors hover:bg-[color:var(--surface-active)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40",children:[c,i.jsx("span",{className:"text-sm",children:d})]}):i.jsx("button",{type:"button",className:"inline-flex cursor-pointer items-center justify-center rounded-sm transition-colors hover:bg-[color:var(--surface-active)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40",children:c});return i.jsxs(bi,{open:o,onOpenChange:l,children:[i.jsx(Hi,{asChild:!0,children:u}),i.jsx(yi,{className:JHt,align:"start",role:"menu","aria-label":"Issue status",children:YKe.map(f=>i.jsx(eKt,{status:f,selected:f===e,onSelect:m=>{t(m),l(!1)}},f))})]})}const tKt=600*1e3,b8e=1e3,nKt=160,rKt=new Map,sKt=new Map;function iKt(){return THt()}function Jj(e){return e?e.replace(/_/g," ").replace(/\b\w/g,t=>t.toUpperCase()):null}function tZe(e,t=220){const n=(e==null?void 0:e.replace(/\s+/g," ").trim())??"";return n?n.length>t?`${n.slice(0,t-1).trimEnd()}...`:n:null}function tX(e){const t=(e==null?void 0:e.trim())??"";if(!t)return null;const n=t.split(/\n\s*\n/u).map(s=>s.trim()).filter(Boolean),r=n.find(s=>!/^#{1,6}\s+/u.test(s))??n[0]??t;return tZe(r.replace(/^#{1,6}\s+/gm,""))}function nZe(e){return((e==null?void 0:e.split("/").filter(Boolean))??[]).at(-1)??e??"Library item"}function rZe(e){return e?e.length>8?e.slice(0,8):e:null}function sZe(e,t,n,r=tKt){const s=Date.now(),a=e.get(t);if(a&&a.expiresAt>s)return a.promise;const o=n().catch(l=>{throw e.delete(t),l});return e.set(t,{expiresAt:s+r,promise:o}),o}function iZe(e,t){return sZe(sKt,`${t}:agent:${e}`,()=>$n.get(e,t))}function aZe(e,t){return e.kind==="issue"?`${t}:issue:${e.issueId}:${e.commentId??""}`:e.kind==="agent"?`${t}:agent:${e.agentId}`:e.kind==="project"?`${t}:project:${e.projectId}`:e.kind==="library_doc"?`${t}:library_doc:${e.documentId}`:e.kind==="library_entry"?`${t}:library_entry:${e.entryId}`:e.kind==="library_file"?`${t}:library_file:${e.filePath}`:`${t}:library_directory:${e.directoryPath}`}async function y8e(e,t){if(!e)return null;try{const n=await iZe(e,t);return{name:n.name,icon:n.icon,role:n.role}}catch{return{name:`agent ${rZe(e)}`,icon:null,role:null}}}async function aKt(e,t){var l,c;const[n,r]=await Promise.all([fr.getComment(e.issueId,e.commentId),fr.get(e.issueId).catch(()=>null)]),s=e.ref??"Issue",a=((l=r==null?void 0:r.title)==null?void 0:l.trim())||s,o=((c=n.body)==null?void 0:c.trim())||null;return{kind:"issue_comment",eyebrow:`${s} comment`,title:a,rows:[],summary:o?null:"No comment body.",body:o}}async function oKt(e,t){if(e.commentId)return aKt(e);const n=await fr.get(e.issueId),r=n.project,[s,a,o]=await Promise.all([y8e(n.assigneeAgentId,t),y8e(n.reviewerAgentId,t),r!=null&&r.color||r!=null&&r.icon?Promise.resolve(r):n.projectId&&!(r!=null&&r.name)?Wi.get(n.projectId,t).catch(()=>null):Promise.resolve(null)]),l=(r==null?void 0:r.name)??(o==null?void 0:o.name)??null,c=o??r??null;return{kind:"issue",eyebrow:n.identifier??e.ref??"Issue",title:n.title,status:n.status,rows:[{label:"Status",value:Jj(n.status),issueStatus:n.status},{label:"Priority",value:Hd(n.priority),priority:n.priority},{label:"Project",value:l,project:l?{color:(c==null?void 0:c.color)??null,icon:(c==null?void 0:c.icon)??null}:void 0},{label:"Assignee",value:s==null?void 0:s.name,agent:s?{icon:s.icon,role:s.role}:void 0},{label:"Reviewer",value:a==null?void 0:a.name,agent:a?{icon:a.icon,role:a.role}:void 0}],summary:tX(n.description)}}function lKt(e){return{kind:"agent",eyebrow:"Agent",title:e.name,subtitle:e.title??Jj(e.role),status:Jj(e.status)??e.status,icon:e.icon,role:e.role,summary:tZe(e.capabilities)}}function cKt(e,t){return{kind:"agent",eyebrow:"Agent",title:t.replace(/^@(?=\S)/,"")||`Agent ${rZe(e.agentId)??""}`.trim(),subtitle:null,status:"",icon:e.icon,role:null,summary:null}}function dKt(e){var r;const t=e.goals.length>0?e.goals.map(s=>s.title).slice(0,2).join(", "):null,n=((r=e.primaryWorkspace)==null?void 0:r.cwd)??e.codebase.repoName??e.codebase.repoUrl??e.codebase.effectiveLocalFolder??null;return{kind:"project",eyebrow:"Project",title:e.name,color:e.color,icon:e.icon,rows:[{label:"Status",value:Jj(e.status)},{label:"Goal",value:t},{label:"Context",value:n}],summary:tX(e.description)}}function uKt(e){return e.previewKind==="text"?tX(e.content)??(e.truncated?"Text preview is truncated.":null):e.previewKind==="image"?"Image file.":e.previewKind==="pdf"?"PDF file.":e.message??"Preview is not available for this file type."}function fKt(e){return{kind:"library",eyebrow:"Library document",title:e.title??"Untitled document",icon:"file",rows:[{label:"Revision",value:String(e.latestRevisionNumber)},{label:"Format",value:Jj(e.format)}],summary:tX(e.body)}}function v8e(e,t){return{kind:"library",eyebrow:e.previewKind==="text"?"Library file":"Library asset",title:t??nZe(e.filePath),icon:"file",rows:[{label:"Path",value:e.filePath},{label:"Type",value:e.contentType}],summary:uKt(e)}}async function mKt(e,t,n){if(e.kind==="issue")return oKt(e,n);if(e.kind==="agent")return lKt(await iZe(e.agentId,n));if(e.kind==="project")return dKt(await Wi.get(e.projectId,n));if(e.kind==="library_doc")return fKt(await Hn.getLibraryDocument(n,e.documentId));if(e.kind==="library_entry"){const r=await qKe(n,e.entryId);return r.status!=="active"||!r.currentPath?{kind:"library",eyebrow:"Library file",title:r.title||t,icon:"file",rows:[{label:"Path",value:r.currentPath??e.path},{label:"Status",value:Jj(r.status)}],summary:"This Library reference is not currently readable."}:v8e(await Hn.readWorkspaceFile(n,r.currentPath),r.title)}return e.kind==="library_file"?v8e(await Hn.readWorkspaceFile(n,e.filePath),e.title):{kind:"library",eyebrow:"Library folder",title:e.title??nZe(e.directoryPath),icon:"folder",rows:[{label:"Path",value:e.directoryPath}],summary:"Open the folder to inspect its files."}}function AKt(e,t,n){return sZe(rKt,aZe(e,n),()=>mKt(e,t,n))}function hKt({row:e}){return e.issueStatus?i.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center","aria-hidden":"true",children:i.jsx(ki,{status:e.issueStatus,className:"size-3.5"})}):e.priority?i.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center","aria-hidden":"true",children:i.jsx(Dc,{priority:e.priority,className:"h-3.5 w-4"})}):e.agent?i.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center","aria-hidden":"true",children:i.jsx(Rh,{icon:e.agent.icon,role:e.agent.role,fallbackSeed:e.value,className:"size-4 rounded-full"})}):e.project?i.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center","aria-hidden":"true",children:i.jsx(Fo,{color:e.project.color,icon:e.project.icon,size:"xs"})}):null}function w8e({rows:e}){const t=e.filter(n=>n.value);return t.length===0?null:i.jsx("span",{className:"rudder-entity-preview-rows",children:t.map(n=>i.jsxs("span",{className:"rudder-entity-preview-row",children:[i.jsx("span",{className:"rudder-entity-preview-row-label",children:n.label}),i.jsxs("span",{className:"rudder-entity-preview-row-value",children:[i.jsx(hKt,{row:n}),i.jsx("span",{className:"rudder-entity-preview-row-value-text",children:n.value})]})]},n.label))})}function pKt({preview:e}){if(e.kind==="agent")return i.jsx(Rh,{icon:e.icon,role:e.role,fallbackSeed:e.title,className:"rudder-entity-preview-main-icon rudder-entity-preview-main-icon--agent"});if(e.kind==="issue")return i.jsx(ki,{status:e.status,className:"rudder-entity-preview-main-icon"});if(e.kind==="issue_comment")return i.jsx("span",{className:"rudder-entity-preview-main-icon rudder-entity-preview-main-icon--comment","data-slot":"issue-comment-preview-icon",children:i.jsx(PD,{className:"size-4","aria-hidden":"true"})});if(e.kind==="project")return i.jsx(Fo,{color:e.color,icon:e.icon,size:"sm",className:"rudder-entity-preview-main-icon--project"});const t=e.icon==="folder"?Bo:Aa;return i.jsx("span",{className:"rudder-entity-preview-main-icon rudder-entity-preview-main-icon--library",children:i.jsx(t,{className:"size-4","aria-hidden":"true"})})}function Kee({preview:e}){return i.jsxs("span",{className:"rudder-entity-preview-head",children:[i.jsx(pKt,{preview:e}),i.jsxs("span",{className:"min-w-0",children:[i.jsx("span",{className:"rudder-entity-preview-eyebrow",children:e.eyebrow}),i.jsx("span",{className:"rudder-entity-preview-title",children:e.title}),e.kind==="agent"&&e.subtitle?i.jsx("span",{className:"rudder-entity-preview-subtitle",children:e.subtitle}):null]})]})}const oZe={a:({node:e,href:t,children:n,...r})=>{const s=xKt(t);return s?i.jsx("a",{...r,href:s,target:s.startsWith("http")?"_blank":void 0,rel:"noreferrer",children:n}):i.jsx("span",{children:n})},img:({node:e,src:t,alt:n,...r})=>{const s=t??"";return i.jsx(U0,{...r,src:s,alt:n??"",name:YZ(n,s),loading:"lazy",previewTestId:"entity-image-preview-dialog",previewTitleFallback:"Image preview"})}};function gKt(){return typeof window>"u"?null:Zf(window.location.pathname)}function xKt(e){const t=e==null?void 0:e.trim();if(!t)return null;const n=Fc(t);if(n)return rc(C5(n),gKt());if(t.startsWith("/")||t.startsWith("#")||!/^[a-z][a-z\d+.-]*:/iu.test(t)&&!t.startsWith("//"))return t;try{const r=new URL(t);if(r.protocol==="http:"||r.protocol==="https:")return t}catch{return null}return null}function bKt({body:e}){const t=is(),n=bge(e);return i.jsx("div",{ref:t,className:"rudder-entity-preview-comment-body scrollbar-auto-hide","data-testid":"issue-comment-preview-body",children:i.jsx(Gpe,{remarkPlugins:[FZ],components:oZe,urlTransform:r=>r,children:n})})}function Zee({summary:e}){const t=is(),n=bge(e);return i.jsx("div",{ref:t,className:"rudder-entity-preview-summary scrollbar-auto-hide",children:i.jsx(Gpe,{remarkPlugins:[FZ],components:oZe,urlTransform:r=>r,children:n})})}function yKt({preview:e}){return e.kind==="agent"?i.jsxs(i.Fragment,{children:[i.jsx(Kee,{preview:e}),i.jsx(w8e,{rows:[{label:"Status",value:e.status}]}),e.summary?i.jsx(Zee,{summary:e.summary}):null]}):e.kind==="issue_comment"?i.jsxs(i.Fragment,{children:[i.jsx(Kee,{preview:e}),e.body?i.jsx(bKt,{body:e.body}):null,e.summary?i.jsx(Zee,{summary:e.summary}):null]}):i.jsxs(i.Fragment,{children:[i.jsx(Kee,{preview:e}),i.jsx(w8e,{rows:e.rows}),e.summary?i.jsx(Zee,{summary:e.summary}):null]})}function nX({mention:e,label:t,children:n}){const[r,s]=A.useState(!1),[a,o]=A.useState(!1),[l,c]=A.useState({status:"idle"}),d=A.useRef(null),u=A.useRef(null),f=A.useRef(null),m=A.useRef(null),h=A.useMemo(iKt,[]),p=A.useRef(e),x=A.useRef(t);p.current=e,x.current=t;const b=h?aZe(e,h):null;A.useEffect(()=>{e.kind==="library_entry"&&MHt(h,e.entryId)},[e,h]);const y=()=>{u.current&&(clearTimeout(u.current),u.current=null)},w=()=>{f.current&&(clearTimeout(f.current),f.current=null)};A.useEffect(()=>{if(!r)return;if(!h){c({status:"error",message:"Preview unavailable outside an organization."});return}if(!b||d.current===b)return;d.current=b;let I=!1;const N=p.current,M=x.current;return N.kind==="agent"?c({status:"ready",preview:cKt(N,M)}):c({status:"loading"}),AKt(N,M,h).then(E=>{I||c({status:"ready",preview:E})}).catch(()=>{I||c({status:"error",message:"Preview unavailable."})}),()=>{I=!0}},[r,h,b]),A.useEffect(()=>()=>{u.current&&clearTimeout(u.current),f.current&&clearTimeout(f.current)},[]),A.useEffect(()=>{if(!a)return;const I=N=>{var _;const M=N.target;if(!(M instanceof Node))return;if((_=m.current)!=null&&_.contains(M)){w();return}if(Array.from(document.querySelectorAll(".rudder-entity-preview-card")).some(z=>{const T=z.getBoundingClientRect();return N.clientX>=T.left&&N.clientX<=T.right&&N.clientY>=T.top&&N.clientY<=T.bottom})){w();return}j()};return window.addEventListener("mousemove",I),()=>{window.removeEventListener("mousemove",I)}},[a]);const k=()=>{y(),w(),s(!0),o(!0)},S=()=>{y(),w(),u.current=setTimeout(()=>{u.current=null,k()},b8e)},j=()=>{if(y(),w(),!a){o(!1);return}f.current=setTimeout(()=>{f.current=null,o(!1)},nKt)},C=()=>{y(),w(),o(!1)};return i.jsx($c,{delayDuration:b8e,skipDelayDuration:0,children:i.jsxs(Mi,{open:a,onOpenChange:I=>{I||y(),I?k():j()},children:[i.jsx(Ei,{asChild:!0,children:i.jsx("span",{ref:m,className:"rudder-entity-preview-wrap",onMouseEnter:S,onMouseLeave:j,onFocusCapture:k,onBlurCapture:C,children:n})}),r?i.jsx(Di,{side:"bottom",align:"center",sideOffset:8,collisionPadding:16,className:q("rudder-entity-preview-card motion-entity-preview-pop",l.status==="loading"&&"rudder-entity-preview-card--loading"),onMouseEnter:k,onMouseLeave:j,children:l.status==="ready"?i.jsx(yKt,{preview:l.preview}):l.status==="error"?i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"rudder-entity-preview-eyebrow",children:t}),i.jsx("span",{className:"rudder-entity-preview-empty",children:l.message})]}):i.jsxs(i.Fragment,{children:[i.jsx(Aa,{className:"size-3.5","aria-hidden":"true"}),i.jsx("span",{children:"Loading preview..."})]})}):null]})})}const gw="data-chat-annotation-source",Eq="data-chat-annotation-block",N5="data-chat-annotation-ignore",xR="data-chat-annotation-text-ignore",lZe=new WeakMap;function vKt(e,t){lZe.set(e,t)}function wKt(e){return lZe.get(e)??null}const kKt=new Set(["ArrowDown","ArrowLeft","ArrowRight","ArrowUp","End","Home"]);function Cge(e){return e instanceof KeyboardEvent&&e.type==="keyup"&&e.shiftKey&&kKt.has(e.key)}async function Sk(e){const t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}function UO(e,t){const n=e instanceof HTMLElement?e:e.parentElement;return(n==null?void 0:n.closest(`[${t}]`))??null}const OKt=new Set(["ADDRESS","ARTICLE","ASIDE","BLOCKQUOTE","DIV","FIGCAPTION","FIGURE","FOOTER","H1","H2","H3","H4","H5","H6","HEADER","LI","MAIN","NAV","P","PRE","SECTION","TR"]);function Nge(e,t,n={value:0}){if(e instanceof Element&&(e.hasAttribute(N5)||e.hasAttribute(xR)))return"";if(e.nodeType===Node.TEXT_NODE){const s=e.textContent??"";return s&&t&&t.push({node:e,start:n.value,end:n.value+s.length}),n.value+=s.length,s}if(e instanceof HTMLBRElement)return n.value+=1,`
1620
1620
  `;const r=Array.from(e.childNodes).map(s=>Nge(s,t,n)).join("");return e instanceof HTMLElement&&OKt.has(e.tagName)&&r.length>0?(n.value+=1,`${r}
1621
- `):r}function c2(e){const t=e.cloneNode(!0);return Nge(t).replace(/^\n+|\n+$/gu,"")}function cZe(e){var a;const t=[],n=Nge(e,t),r=((a=n.match(/^\n+/u))==null?void 0:a[0].length)??0,s=n.replace(/^\n+|\n+$/gu,"").length;return t.map(o=>({...o,start:o.start-r,end:o.end-r})).filter(o=>o.end>0&&o.start<s).map(o=>({...o,start:Math.max(0,o.start),end:Math.min(s,o.end)}))}function dZe(e,t,n){const r=cZe(e);if(t.nodeType===Node.TEXT_NODE){const o=r.find(l=>l.node===t);return o?Math.max(o.start,Math.min(o.end,o.start+n)):null}if(!(t instanceof Element||t instanceof DocumentFragment))return null;const s=t.childNodes[n]??null;if(s){const o=r.find(l=>s===l.node||s.contains(l.node));if(o)return o.start}const a=n>0?t.childNodes[n-1]??null:null;if(a){const o=[...r].reverse().find(l=>a===l.node||a.contains(l.node));if(o)return o.end}return t===e&&n===0?0:t===e&&n===e.childNodes.length?c2(e).length:null}function uZe(e,t,n){const r=dZe(e,t,n);if(r!==null)return c2(e).slice(0,r);const s=document.createRange();s.selectNodeContents(e);try{s.setEnd(t,n)}catch{return null}return c2(s.cloneContents())}function fZe(e){return c2(e.cloneContents())}function SKt(e,t){var a;if(e[t]!=="&")return null;const n=(a=e.slice(t).match(/^&(?:#[xX][\da-fA-F]+|#\d+|[a-zA-Z][a-zA-Z\d]+);/u))==null?void 0:a[0];if(!n||typeof document>"u")return null;const r=document.createElement("textarea");r.innerHTML=n;const s=r.value;return s.length===1?{decoded:s,length:n.length}:null}function jKt(e){const t=Array(e.length).fill(!0),n=(r,s)=>{for(let a=r;a<s;a+=1)t[a]=!1};for(const r of e.matchAll(/!?\[[^\]\n]*\]\[[^\]\n]*\]/gu)){const s=r[0],a=r.index,o=s.indexOf("]");s.startsWith("!")?n(a,a+s.length):(n(a,a+1),o>=0&&n(a+o,a+s.length))}for(const r of e.matchAll(/!?\[[^\]\n]*\]\((?:\\.|[^)\n])*\)/gu)){const s=r[0],a=r.index,o=s.indexOf("]");o>=0&&n(a+o,a+s.length),n(a,a+(s.startsWith("!")?2:1))}for(const r of e.matchAll(/!\[[^\]\n]*\](?![\[(])/gu))n(r.index,r.index+r[0].length);for(const r of e.matchAll(/^[\t ]*\[[^\]\n]+\]:[^\n]*$/gmu))n(r.index,r.index+r[0].length);for(const r of e.matchAll(/<\/?[a-zA-Z][^>\n]*>/gu))n(r.index,r.index+r[0].length);return t}function bR(e,t,n=0){const r=[],s=sMt(t,e),a=jKt(t);let o=0;for(let l=0;l<e.length;l+=1){const c=e[l],d=Math.max(o,s.renderedBoundaryToRaw[l+1]-1);let u=-1,f=-1,m=Number.POSITIVE_INFINITY;const h=(p,x)=>{const b=Math.abs(p-d);(b<m||b===m&&(p>u||p===u&&x>f))&&(u=p,f=x,m=b)};for(let p=t.indexOf(c,o);p>=0&&!(a[p]&&(h(p,p+1),p>=d));p=t.indexOf(c,p+1));for(let p=t.indexOf("&",o);p>=0;p=t.indexOf("&",p+1)){const x=SKt(t,p);if(a[p]&&(x==null?void 0:x.decoded)===c&&(h(p,p+x.length),p>=d))break}if(u<0)return Array.from({length:e.length},(p,x)=>({start:n+s.renderedBoundaryToRaw[x],end:n+s.renderedBoundaryToRaw[x+1]}));r.push({start:n+u,end:n+f}),o=f}return r}function CKt(e,t){const n=e instanceof HTMLElement?e:e.parentElement,r=(n==null?void 0:n.closest("[data-markdown-source-start][data-markdown-source-end]"))??null;return r&&t.contains(r)?r:null}function mZe(e,t){const n=Number(e.dataset.markdownSourceStart),r=Number(e.dataset.markdownSourceEnd);return!Number.isInteger(n)||!Number.isInteger(r)||n<0||r<=n||r>t?null:{start:n,end:r}}function NKt(e,t,n){const r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(o){return UO(o,N5)||UO(o,xR)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}});let s=t,a=null;for(let o=r.nextNode();o;o=r.nextNode()){const l=o;a=l;const c=l.data.length;if(s<c||s===c&&n==="end")return{container:l,offset:s};s-=c}return s===0&&a?{container:a,offset:a.data.length}:null}function IKt(e,t,n,r){return Array.from(e.querySelectorAll("[data-markdown-source-start][data-markdown-source-end]")).map(a=>({element:a,bounds:mZe(a,t)})).filter(a=>!!a.bounds).filter(({bounds:a})=>r==="start"?a.start<=n&&n<a.end:a.start<n&&n<=a.end).sort((a,o)=>a.bounds.end-a.bounds.start-(o.bounds.end-o.bounds.start))[0]??null}function k8e(e,t,n,r){const s=IKt(e,t.length,n,r);if(!s)return null;const a=c2(s.element),o=bR(a,t.slice(s.bounds.start,s.bounds.end),s.bounds.start);if(!o)return null;const l=r==="start"?o.findIndex(c=>c.end>n):o.findLastIndex(c=>c.start<n)+1;return l<0?null:NKt(s.element,l,r)}function AZe(e){if(e.start<0||e.end<=e.start||e.end>e.source.length)return null;const t=k8e(e.sourceRoot,e.source,e.start,"start"),n=k8e(e.sourceRoot,e.source,e.end,"end");if(!t||!n)return null;const r=document.createRange();try{r.setStart(t.container,t.offset),r.setEnd(n.container,n.offset)}catch{return null}return r.collapsed?null:r}function PKt(e,t=document){return Array.from(t.querySelectorAll(`[${gw}]`)).find(r=>!r.isConnected||r.dataset.messageId!==e.sourceMessageId||r.dataset.annotationSurface!==e.surface?!1:e.surface==="assistant_body"?!0:r.dataset.transcriptKind===e.transcriptKind&&r.dataset.generationId===e.generationId&&Number(r.dataset.generationSeqStart)===e.generationSeqStart&&Number(r.dataset.generationSeqEnd)===e.generationSeqEnd)??null}function Dq(e){const t=PKt(e.anchor,e.searchRoot);if(!t)return null;const n=AZe({sourceRoot:t,source:e.source,start:e.anchor.start,end:e.anchor.end});return n?{range:n,sourceRoot:t}:null}function O8e(e,t,n,r,s){var u,f;const a=CKt(n,e);if(!a)return null;const o=mZe(a,t.length);if(!o)return null;const l=uZe(a,n,r);if(l===null)return null;const c=c2(a),d=bR(c,t.slice(o.start,o.end),o.start);return d?s==="start"?l.length===d.length?o.end:((u=d[l.length])==null?void 0:u.start)??null:l.length===0?o.start:((f=d[l.length-1])==null?void 0:f.end)??null:null}function S8e(e){var x,b;const{range:t,sourceRoot:n}=e;if(t.collapsed||!n.contains(t.startContainer)||!n.contains(t.endContainer))return null;const r=n.getAttribute(gw),s=UO(t.startContainer,gw),a=UO(t.endContainer,gw);if(!r||s!==n||a!==n||Array.from(n.querySelectorAll(`[${N5}]`)).some(y=>{try{return t.intersectsNode(y)}catch{return!1}}))return null;if(e.surface==="process_transcript"){const y=UO(t.startContainer,Eq),w=UO(t.endContainer,Eq);if(!y||y!==w)return null}const l=fZe(t);if(!l)return null;const c=uZe(n,t.startContainer,t.startOffset);if(c===null)return null;const d=O8e(n,e.source,t.startContainer,t.startOffset,"start"),u=O8e(n,e.source,t.endContainer,t.endOffset,"end");let f=d??void 0,m=u??void 0;if(f===void 0||m===void 0){const y=c2(n),w=bR(y,e.source);if(!w)return null;const k=c.length,S=k+l.length;if(k<0||S>w.length||S<=k)return null;f??(f=(x=w[k])==null?void 0:x.start),m??(m=(b=w[S-1])==null?void 0:b.end)}if(f===void 0||m===void 0||m<=f)return null;for(;f<m&&new RegExp("\\p{White_Space}","u").test(e.source[f]??"")&&!l.startsWith(e.source[f]??"");)f+=1;for(;m>f&&new RegExp("\\p{White_Space}","u").test(e.source[m-1]??"")&&!l.endsWith(e.source[m-1]??"");)m-=1;const h=Math.min(160,Math.max(0,e.contextLength??160)),p={selectedText:l,sourceConversationId:e.sourceConversationId,sourceMessageId:e.sourceMessageId,sourceHash:e.sourceHash,start:f,end:m,prefix:e.source.slice(Math.max(0,f-h),f),suffix:e.source.slice(m,m+h)};return e.surface==="process_transcript"?{...p,surface:e.surface,transcriptKind:e.transcriptKind,generationId:e.generationId,generationSeqStart:e.generationSeqStart,generationSeqEnd:e.generationSeqEnd}:{...p,surface:e.surface}}function Ige({label:e,preview:t,fallbackOpenHref:n,sourceAttributes:r,onOpen:s}){var x,b,y,w,k,S;const a=((x=t==null?void 0:t.displayName)==null?void 0:x.trim())||e,o=((b=t==null?void 0:t.description)==null?void 0:b.trim())||null,l=((y=t==null?void 0:t.categoryLabel)==null?void 0:y.trim())||null,c=((w=t==null?void 0:t.locationLabel)==null?void 0:w.trim())||null,d=((k=t==null?void 0:t.detailsHref)==null?void 0:k.trim())||null,u=(n==null?void 0:n.trim())||((S=t==null?void 0:t.openHref)==null?void 0:S.trim())||null,f=!!(o||l||c||d),m=is(),h=s?u??d:d,p=h?i.jsx("a",{className:"rudder-skill-token","data-skill-token":"true",href:h,"aria-label":`${a} skill`,title:a,style:Tq(),...r,onClick:j=>s==null?void 0:s(j,h,a),children:i.jsx("span",{className:"rudder-inline-token-label",children:e})}):i.jsx("span",{className:"rudder-skill-token","data-skill-token":"true",tabIndex:f?0:void 0,"aria-label":f?`${a} skill`:void 0,title:a,style:Tq(),...r,children:i.jsx("span",{className:"rudder-inline-token-label",children:e})});return i.jsxs("span",{className:q("rudder-skill-token-wrap",f&&"rudder-skill-token-wrap--preview"),children:[p,f?i.jsxs("span",{ref:m,className:"rudder-skill-hover-card scrollbar-auto-hide",role:"tooltip",[xR]:"",children:[i.jsxs("span",{className:"flex items-start gap-3",children:[i.jsx("span",{className:"mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-[var(--radius-md)] bg-[#2f80ed]/10 text-[#2f80ed]",children:i.jsx(nd,{className:"h-4 w-4","aria-hidden":!0})}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"block break-words text-sm font-medium leading-5 text-foreground",children:a}),l||c?i.jsxs("span",{className:"mt-1.5 flex min-w-0 flex-wrap items-center gap-1.5",children:[l?i.jsx("span",{className:"inline-flex items-center rounded-[var(--radius-sm)] border border-border/70 bg-muted/50 px-1.5 py-0.5 text-[11px] font-medium leading-none text-muted-foreground",children:l}):null,c?i.jsx("span",{className:"min-w-0 break-all text-[11px] leading-4 text-muted-foreground",children:c}):null]}):null,o?i.jsx("span",{className:"mt-1 block text-xs leading-5 text-muted-foreground",children:o}):null]})]}),d?i.jsxs("a",{className:"rudder-skill-hover-card-action",href:d,children:[i.jsx("span",{children:"View details"}),i.jsx(Jy,{className:"h-3.5 w-3.5","aria-hidden":!0})]}):null]}):null]})}let Xee=null;function TKt(){return Xee||(Xee=on(()=>import("./mermaid.core-BBG92fxH.js").then(e=>e.bo),[]).then(e=>e.default)),Xee}function jk(e){return e==null?"":typeof e=="string"||typeof e=="number"?String(e):Array.isArray(e)?e.map(t=>jk(t)).join(""):A.isValidElement(e)?jk(e.props.children):""}function N$(e){return(e==null?void 0:e.trim().replace(/\/+$/u,"").toLowerCase())??""}function gx(e){const t=(e==null?void 0:e.trim())??"";if(!t)return"item";const n=t.split(/[-/]/u).find(Boolean);return n&&n.length>=6?n.slice(0,12):t.length>12?t.slice(0,12):t}function Gee(e){return((e==null?void 0:e.trim().replace(/\/+$/u,""))??"").split("/").filter(Boolean).at(-1)??""}function Yee(e){var t,n,r,s,a,o,l;return e.kind==="agent"?gx(e.agentId):e.kind==="project"?gx(e.projectId):e.kind==="automation"?((t=e.title)==null?void 0:t.trim())||gx(e.automationId):e.kind==="issue"?((n=e.ref)==null?void 0:n.trim())||gx(e.issueId):e.kind==="chat"?((r=e.title)==null?void 0:r.trim())||gx(e.conversationId):e.kind==="library_doc"?((s=e.title)==null?void 0:s.trim())||gx(e.documentId):e.kind==="library_entry"?((a=e.title)==null?void 0:a.trim())||Gee(e.path)||gx(e.entryId):e.kind==="library_file"?((o=e.title)==null?void 0:o.trim())||Gee(e.filePath)||gx(e.filePath):e.kind==="plugin"?gx(e.pluginId):((l=e.title)==null?void 0:l.trim())||Gee(e.directoryPath)||gx(e.directoryPath)}function _Kt(e){if(!/[&][#a-z\d]+;/iu.test(e)||typeof document>"u")return e;const t=document.createElement("textarea");return t.innerHTML=e,t.value}function Jee(e){return _Kt(e).replace(/\s+/gu," ").trim()}function MKt(){return typeof window>"u"?null:Zf(window.location.pathname)}function EKt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function DKt(e){return e.replace(/([\\[\]])/g,"\\$1")}function RKt(e){return e.trim().replace(/^@+/u,"")}function LKt(e){return/^[^\s@,!?.]+$/u.test(e)}function ete(e,t,n){const r=e.indexOf(t,n);return r>=0?r:null}function zKt(e,t){let n=!1;for(let r=t;r<e.length;r+=1){const s=e[r];if(n){n=!1;continue}if(s==="\\"){n=!0;continue}if(s===")")return r}return null}function $Kt(e){var o;const t=[];let n=0,r=0;function s(l){l>r&&t.push({text:e.slice(r,l),protected:!1})}function a(l){s(n),t.push({text:e.slice(n,l),protected:!0}),n=l,r=l}for(;n<e.length;){const l=e[n];if(l==="`"){const d=((o=e.slice(n).match(/^`+/u))==null?void 0:o[0])??"`",u=ete(e,d,n+d.length);if(u!==null){a(u+d.length);continue}}const c=l==="["?n:l==="!"&&e[n+1]==="["?n+1:null;if(c!==null){const d=ete(e,"]",c+1);if(d!==null&&e[d+1]==="("){const u=zKt(e,d+2);if(u!==null){a(u+1);continue}}}if(l==="<"){const d=ete(e,">",n+1);if(d!==null){a(d+1);continue}}n+=1}return s(e.length),t}function FKt(e,t){if(!e.includes("@")||!(t!=null&&t.length))return e;const n=t.map(o=>({...o,name:RKt(o.name)})).filter(o=>o.name&&o.agentId&&LKt(o.name)).sort((o,l)=>l.name.length-o.name.length);if(n.length===0)return e;const r=new RegExp(`(^|[^\\w/[\\]\`])@(${n.map(o=>EKt(o.name)).join("|")})(?=$|[\\s@,!?.])`,"giu"),s=/^(```|~~~)/;let a=!1;return e.split(/(\n)/).map(o=>o===`
1621
+ `):r}function c2(e){const t=e.cloneNode(!0);return Nge(t).replace(/^\n+|\n+$/gu,"")}function cZe(e){var a;const t=[],n=Nge(e,t),r=((a=n.match(/^\n+/u))==null?void 0:a[0].length)??0,s=n.replace(/^\n+|\n+$/gu,"").length;return t.map(o=>({...o,start:o.start-r,end:o.end-r})).filter(o=>o.end>0&&o.start<s).map(o=>({...o,start:Math.max(0,o.start),end:Math.min(s,o.end)}))}function dZe(e,t,n){const r=cZe(e);if(t.nodeType===Node.TEXT_NODE){const o=r.find(l=>l.node===t);return o?Math.max(o.start,Math.min(o.end,o.start+n)):null}if(!(t instanceof Element||t instanceof DocumentFragment))return null;const s=t.childNodes[n]??null;if(s){const o=r.find(l=>s===l.node||s.contains(l.node));if(o)return o.start}const a=n>0?t.childNodes[n-1]??null:null;if(a){const o=[...r].reverse().find(l=>a===l.node||a.contains(l.node));if(o)return o.end}return t===e&&n===0?0:t===e&&n===e.childNodes.length?c2(e).length:null}function uZe(e,t,n){const r=dZe(e,t,n);if(r!==null)return c2(e).slice(0,r);const s=document.createRange();s.selectNodeContents(e);try{s.setEnd(t,n)}catch{return null}return c2(s.cloneContents())}function fZe(e){return c2(e.cloneContents())}function SKt(e,t){var a;if(e[t]!=="&")return null;const n=(a=e.slice(t).match(/^&(?:#[xX][\da-fA-F]+|#\d+|[a-zA-Z][a-zA-Z\d]+);/u))==null?void 0:a[0];if(!n||typeof document>"u")return null;const r=document.createElement("textarea");r.innerHTML=n;const s=r.value;return s.length===1?{decoded:s,length:n.length}:null}function jKt(e){const t=Array(e.length).fill(!0),n=(r,s)=>{for(let a=r;a<s;a+=1)t[a]=!1};for(const r of e.matchAll(/!?\[[^\]\n]*\]\[[^\]\n]*\]/gu)){const s=r[0],a=r.index,o=s.indexOf("]");s.startsWith("!")?n(a,a+s.length):(n(a,a+1),o>=0&&n(a+o,a+s.length))}for(const r of e.matchAll(/!?\[[^\]\n]*\]\((?:\\.|[^)\n])*\)/gu)){const s=r[0],a=r.index,o=s.indexOf("]");o>=0&&n(a+o,a+s.length),n(a,a+(s.startsWith("!")?2:1))}for(const r of e.matchAll(/!\[[^\]\n]*\](?![\[(])/gu))n(r.index,r.index+r[0].length);for(const r of e.matchAll(/^[\t ]*\[[^\]\n]+\]:[^\n]*$/gmu))n(r.index,r.index+r[0].length);for(const r of e.matchAll(/<\/?[a-zA-Z][^>\n]*>/gu))n(r.index,r.index+r[0].length);return t}function bR(e,t,n=0){const r=[],s=sMt(t,e),a=jKt(t);let o=0;for(let l=0;l<e.length;l+=1){const c=e[l],d=Math.max(o,s.renderedBoundaryToRaw[l+1]-1);let u=-1,f=-1,m=Number.POSITIVE_INFINITY;const h=(p,x)=>{const b=Math.abs(p-d);(b<m||b===m&&(p>u||p===u&&x>f))&&(u=p,f=x,m=b)};for(let p=t.indexOf(c,o);p>=0&&!(a[p]&&(h(p,p+1),p>=d));p=t.indexOf(c,p+1));for(let p=t.indexOf("&",o);p>=0;p=t.indexOf("&",p+1)){const x=SKt(t,p);if(a[p]&&(x==null?void 0:x.decoded)===c&&(h(p,p+x.length),p>=d))break}if(u<0)return Array.from({length:e.length},(p,x)=>({start:n+s.renderedBoundaryToRaw[x],end:n+s.renderedBoundaryToRaw[x+1]}));r.push({start:n+u,end:n+f}),o=f}return r}function CKt(e,t){const n=e instanceof HTMLElement?e:e.parentElement,r=(n==null?void 0:n.closest("[data-markdown-source-start][data-markdown-source-end]"))??null;return r&&t.contains(r)?r:null}function mZe(e,t){const n=Number(e.dataset.markdownSourceStart),r=Number(e.dataset.markdownSourceEnd);return!Number.isInteger(n)||!Number.isInteger(r)||n<0||r<=n||r>t?null:{start:n,end:r}}function NKt(e,t,n){const r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(o){return UO(o,N5)||UO(o,xR)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}});let s=t,a=null;for(let o=r.nextNode();o;o=r.nextNode()){const l=o;a=l;const c=l.data.length;if(s<c||s===c&&n==="end")return{container:l,offset:s};s-=c}return s===0&&a?{container:a,offset:a.data.length}:null}function IKt(e,t,n,r){return Array.from(e.querySelectorAll("[data-markdown-source-start][data-markdown-source-end]")).map(a=>({element:a,bounds:mZe(a,t)})).filter(a=>!!a.bounds).filter(({bounds:a})=>r==="start"?a.start<=n&&n<a.end:a.start<n&&n<=a.end).sort((a,o)=>a.bounds.end-a.bounds.start-(o.bounds.end-o.bounds.start))[0]??null}function k8e(e,t,n,r){const s=IKt(e,t.length,n,r);if(!s)return null;const a=c2(s.element),o=bR(a,t.slice(s.bounds.start,s.bounds.end),s.bounds.start);if(!o)return null;const l=r==="start"?o.findIndex(c=>c.end>n):o.findLastIndex(c=>c.start<n)+1;return l<0?null:NKt(s.element,l,r)}function AZe(e){if(e.start<0||e.end<=e.start||e.end>e.source.length)return null;const t=k8e(e.sourceRoot,e.source,e.start,"start"),n=k8e(e.sourceRoot,e.source,e.end,"end");if(!t||!n)return null;const r=document.createRange();try{r.setStart(t.container,t.offset),r.setEnd(n.container,n.offset)}catch{return null}return r.collapsed?null:r}function PKt(e,t=document){return Array.from(t.querySelectorAll(`[${gw}]`)).find(r=>!r.isConnected||r.dataset.messageId!==e.sourceMessageId||r.dataset.annotationSurface!==e.surface?!1:e.surface==="assistant_body"?!0:r.dataset.transcriptKind===e.transcriptKind&&r.dataset.generationId===e.generationId&&Number(r.dataset.generationSeqStart)===e.generationSeqStart&&Number(r.dataset.generationSeqEnd)===e.generationSeqEnd)??null}function Dq(e){const t=PKt(e.anchor,e.searchRoot);if(!t)return null;const n=AZe({sourceRoot:t,source:e.source,start:e.anchor.start,end:e.anchor.end});return n?{range:n,sourceRoot:t}:null}function O8e(e,t,n,r,s){var u,f;const a=CKt(n,e);if(!a)return null;const o=mZe(a,t.length);if(!o)return null;const l=uZe(a,n,r);if(l===null)return null;const c=c2(a),d=bR(c,t.slice(o.start,o.end),o.start);return d?s==="start"?l.length===d.length?o.end:((u=d[l.length])==null?void 0:u.start)??null:l.length===0?o.start:((f=d[l.length-1])==null?void 0:f.end)??null:null}function S8e(e){var x,b;const{range:t,sourceRoot:n}=e;if(t.collapsed||!n.contains(t.startContainer)||!n.contains(t.endContainer))return null;const r=n.getAttribute(gw),s=UO(t.startContainer,gw),a=UO(t.endContainer,gw);if(!r||s!==n||a!==n||Array.from(n.querySelectorAll(`[${N5}]`)).some(y=>{try{return t.intersectsNode(y)}catch{return!1}}))return null;if(e.surface==="process_transcript"){const y=UO(t.startContainer,Eq),w=UO(t.endContainer,Eq);if(!y||y!==w)return null}const l=fZe(t);if(!l)return null;const c=uZe(n,t.startContainer,t.startOffset);if(c===null)return null;const d=O8e(n,e.source,t.startContainer,t.startOffset,"start"),u=O8e(n,e.source,t.endContainer,t.endOffset,"end");let f=d??void 0,m=u??void 0;if(f===void 0||m===void 0){const y=c2(n),w=bR(y,e.source);if(!w)return null;const k=c.length,S=k+l.length;if(k<0||S>w.length||S<=k)return null;f??(f=(x=w[k])==null?void 0:x.start),m??(m=(b=w[S-1])==null?void 0:b.end)}if(f===void 0||m===void 0||m<=f)return null;for(;f<m&&new RegExp("\\p{White_Space}","u").test(e.source[f]??"")&&!l.startsWith(e.source[f]??"");)f+=1;for(;m>f&&new RegExp("\\p{White_Space}","u").test(e.source[m-1]??"")&&!l.endsWith(e.source[m-1]??"");)m-=1;const h=Math.min(160,Math.max(0,e.contextLength??160)),p={selectedText:l,sourceConversationId:e.sourceConversationId,sourceMessageId:e.sourceMessageId,sourceHash:e.sourceHash,start:f,end:m,prefix:e.source.slice(Math.max(0,f-h),f),suffix:e.source.slice(m,m+h)};return e.surface==="process_transcript"?{...p,surface:e.surface,transcriptKind:e.transcriptKind,generationId:e.generationId,generationSeqStart:e.generationSeqStart,generationSeqEnd:e.generationSeqEnd}:{...p,surface:e.surface}}function Ige({label:e,preview:t,fallbackOpenHref:n,sourceAttributes:r,onOpen:s}){var x,b,y,w,k,S;const a=((x=t==null?void 0:t.displayName)==null?void 0:x.trim())||e,o=((b=t==null?void 0:t.description)==null?void 0:b.trim())||null,l=((y=t==null?void 0:t.categoryLabel)==null?void 0:y.trim())||null,c=((w=t==null?void 0:t.locationLabel)==null?void 0:w.trim())||null,d=((k=t==null?void 0:t.detailsHref)==null?void 0:k.trim())||null,u=(n==null?void 0:n.trim())||((S=t==null?void 0:t.openHref)==null?void 0:S.trim())||null,f=!!(o||l||c||d),m=is(),h=s?u??d:d,p=h?i.jsx("a",{className:"rudder-skill-token","data-skill-token":"true",href:h,"aria-label":`${a} skill`,title:a,style:Tq(),...r,onClick:j=>s==null?void 0:s(j,h,a),children:i.jsx("span",{className:"rudder-inline-token-label",children:e})}):i.jsx("span",{className:"rudder-skill-token","data-skill-token":"true",tabIndex:f?0:void 0,"aria-label":f?`${a} skill`:void 0,title:a,style:Tq(),...r,children:i.jsx("span",{className:"rudder-inline-token-label",children:e})});return i.jsxs("span",{className:q("rudder-skill-token-wrap",f&&"rudder-skill-token-wrap--preview"),children:[p,f?i.jsxs("span",{ref:m,className:"rudder-skill-hover-card scrollbar-auto-hide",role:"tooltip",[xR]:"",children:[i.jsxs("span",{className:"flex items-start gap-3",children:[i.jsx("span",{className:"mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-[var(--radius-md)] bg-[#2f80ed]/10 text-[#2f80ed]",children:i.jsx(nd,{className:"h-4 w-4","aria-hidden":!0})}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"block break-words text-sm font-medium leading-5 text-foreground",children:a}),l||c?i.jsxs("span",{className:"mt-1.5 flex min-w-0 flex-wrap items-center gap-1.5",children:[l?i.jsx("span",{className:"inline-flex items-center rounded-[var(--radius-sm)] border border-border/70 bg-muted/50 px-1.5 py-0.5 text-[11px] font-medium leading-none text-muted-foreground",children:l}):null,c?i.jsx("span",{className:"min-w-0 break-all text-[11px] leading-4 text-muted-foreground",children:c}):null]}):null,o?i.jsx("span",{className:"mt-1 block text-xs leading-5 text-muted-foreground",children:o}):null]})]}),d?i.jsxs("a",{className:"rudder-skill-hover-card-action",href:d,children:[i.jsx("span",{children:"View details"}),i.jsx(Jy,{className:"h-3.5 w-3.5","aria-hidden":!0})]}):null]}):null]})}let Xee=null;function TKt(){return Xee||(Xee=on(()=>import("./mermaid.core-C39RyJW7.js").then(e=>e.bo),[]).then(e=>e.default)),Xee}function jk(e){return e==null?"":typeof e=="string"||typeof e=="number"?String(e):Array.isArray(e)?e.map(t=>jk(t)).join(""):A.isValidElement(e)?jk(e.props.children):""}function N$(e){return(e==null?void 0:e.trim().replace(/\/+$/u,"").toLowerCase())??""}function gx(e){const t=(e==null?void 0:e.trim())??"";if(!t)return"item";const n=t.split(/[-/]/u).find(Boolean);return n&&n.length>=6?n.slice(0,12):t.length>12?t.slice(0,12):t}function Gee(e){return((e==null?void 0:e.trim().replace(/\/+$/u,""))??"").split("/").filter(Boolean).at(-1)??""}function Yee(e){var t,n,r,s,a,o,l;return e.kind==="agent"?gx(e.agentId):e.kind==="project"?gx(e.projectId):e.kind==="automation"?((t=e.title)==null?void 0:t.trim())||gx(e.automationId):e.kind==="issue"?((n=e.ref)==null?void 0:n.trim())||gx(e.issueId):e.kind==="chat"?((r=e.title)==null?void 0:r.trim())||gx(e.conversationId):e.kind==="library_doc"?((s=e.title)==null?void 0:s.trim())||gx(e.documentId):e.kind==="library_entry"?((a=e.title)==null?void 0:a.trim())||Gee(e.path)||gx(e.entryId):e.kind==="library_file"?((o=e.title)==null?void 0:o.trim())||Gee(e.filePath)||gx(e.filePath):e.kind==="plugin"?gx(e.pluginId):((l=e.title)==null?void 0:l.trim())||Gee(e.directoryPath)||gx(e.directoryPath)}function _Kt(e){if(!/[&][#a-z\d]+;/iu.test(e)||typeof document>"u")return e;const t=document.createElement("textarea");return t.innerHTML=e,t.value}function Jee(e){return _Kt(e).replace(/\s+/gu," ").trim()}function MKt(){return typeof window>"u"?null:Zf(window.location.pathname)}function EKt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function DKt(e){return e.replace(/([\\[\]])/g,"\\$1")}function RKt(e){return e.trim().replace(/^@+/u,"")}function LKt(e){return/^[^\s@,!?.]+$/u.test(e)}function ete(e,t,n){const r=e.indexOf(t,n);return r>=0?r:null}function zKt(e,t){let n=!1;for(let r=t;r<e.length;r+=1){const s=e[r];if(n){n=!1;continue}if(s==="\\"){n=!0;continue}if(s===")")return r}return null}function $Kt(e){var o;const t=[];let n=0,r=0;function s(l){l>r&&t.push({text:e.slice(r,l),protected:!1})}function a(l){s(n),t.push({text:e.slice(n,l),protected:!0}),n=l,r=l}for(;n<e.length;){const l=e[n];if(l==="`"){const d=((o=e.slice(n).match(/^`+/u))==null?void 0:o[0])??"`",u=ete(e,d,n+d.length);if(u!==null){a(u+d.length);continue}}const c=l==="["?n:l==="!"&&e[n+1]==="["?n+1:null;if(c!==null){const d=ete(e,"]",c+1);if(d!==null&&e[d+1]==="("){const u=zKt(e,d+2);if(u!==null){a(u+1);continue}}}if(l==="<"){const d=ete(e,">",n+1);if(d!==null){a(d+1);continue}}n+=1}return s(e.length),t}function FKt(e,t){if(!e.includes("@")||!(t!=null&&t.length))return e;const n=t.map(o=>({...o,name:RKt(o.name)})).filter(o=>o.name&&o.agentId&&LKt(o.name)).sort((o,l)=>l.name.length-o.name.length);if(n.length===0)return e;const r=new RegExp(`(^|[^\\w/[\\]\`])@(${n.map(o=>EKt(o.name)).join("|")})(?=$|[\\s@,!?.])`,"giu"),s=/^(```|~~~)/;let a=!1;return e.split(/(\n)/).map(o=>o===`
1622
1622
  `?o:s.test(o.trimStart())?(a=!a,o):a?o:$Kt(o).map(l=>l.protected?l.text:l.text.replace(r,(c,d,u)=>{const f=n.find(h=>h.name.toLowerCase()===u.toLowerCase());if(!f)return c;const m=ZD(f.agentId,f.agentIcon);return`${d}[@${DKt(f.name)}](${m})`})).join("")).join("")}function BKt(e){const t=(e==null?void 0:e.trim())??"";if(!t)return!1;if(t.startsWith("//"))return!0;if(!/^[a-z][a-z\d+.-]*:/iu.test(t))return!1;try{const n=new URL(t);return typeof window<"u"&&(n.protocol==="http:"||n.protocol==="https:")&&n.origin===window.location.origin?!1:n.protocol==="http:"||n.protocol==="https:"||n.protocol==="mailto:"}catch{return!1}}function hZe(e){const t=(e==null?void 0:e.trim())??"";if(!t)return null;const n=t.startsWith("//")?`${typeof window>"u"?"https:":window.location.protocol}${t}`:t;try{const r=new URL(n);return r.protocol!=="http:"&&r.protocol!=="https:"||typeof window<"u"&&r.origin===window.location.origin?null:r}catch{return null}}function QKt(e){const t=e.trim();return/^(?:https?:\/\/|www\.|\/\/)/iu.test(t)}function UKt(e){const t=(e==null?void 0:e.trim())??"";return t.startsWith("//")||/^[a-z][a-z\d+.-]*:/iu.test(t)}function qKt(e){if(!e||typeof window>"u")return!1;const t=window.getSelection();if(!t||t.isCollapsed||t.rangeCount===0)return!1;for(let n=0;n<t.rangeCount;n+=1)try{if(t.getRangeAt(n).intersectsNode(e))return!0}catch{}return!1}function VKt(e){const t=A.useRef(null),n=A.useRef(e),r=A.useRef(!1),[s,a]=A.useState(e);n.current=e;const o=A.useCallback(()=>{r.current||qKt(t.current)||a(l=>l===n.current?l:n.current)},[]);return A.useLayoutEffect(()=>{o()},[o,e]),A.useEffect(()=>{const l=t.current;if(!l)return;let c=null;const d=()=>{r.current=!0},u=()=>{r.current=!1,c!==null&&window.cancelAnimationFrame(c),c=window.requestAnimationFrame(()=>{c=null,o()})};return l.addEventListener("pointerdown",d,!0),l.addEventListener("selectstart",d,!0),document.addEventListener("pointerup",u,!0),document.addEventListener("pointercancel",u,!0),document.addEventListener("selectionchange",o),()=>{c!==null&&window.cancelAnimationFrame(c),l.removeEventListener("pointerdown",d,!0),l.removeEventListener("selectstart",d,!0),document.removeEventListener("pointerup",u,!0),document.removeEventListener("pointercancel",u,!0),document.removeEventListener("selectionchange",o)}},[o]),{renderedSource:s,rootRef:t}}const j8e=new Set(["agents","automations","dashboard","goals","inbox","issues","library","messenger","organization","projects","settings","skills"]);function WKt(e){return e.button===0&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey}function C8e(e,t){if(typeof window>"u")return null;try{const n=new URL(e,window.location.href);if(n.origin!==window.location.origin)return null;const r=n.pathname.split("/").filter(Boolean);return(r[0]&&j8e.has(r[0])?r[0]:r[1]&&j8e.has(r[1])?r[1]:null)?rc(`${n.pathname}${n.search}${n.hash}`,t):null}catch{return null}}function N8e(e){if(!e||typeof window>"u")return null;try{const t=new URL(e,window.location.href);if(t.origin!==window.location.origin)return null;const n=t.pathname.split("/").filter(Boolean),r=n.findIndex(a=>a.toLowerCase()==="issues");if(r<0)return null;const s=n[r+1];return s?decodeURIComponent(s):null}catch{return null}}function I7(e,t){const n=e==null?void 0:e.trim().toLowerCase();return n?t.find(r=>{var o;if(r.kind!=="issue"||!r.issueId)return!1;const s=r.issueId.toLowerCase(),a=((o=r.issueIdentifier)==null?void 0:o.toLowerCase())??"";return s===n||a===n||n.length>=6&&s.startsWith(n)})??null:null}function I8e({mention:e,label:t,targetHref:n,sourceAttributes:r,onClick:s}){const a=CKe(e),o=i.jsx("a",{href:n,className:q("rudder-mention-chip rudder-mention-chip--issue",a.status&&"rudder-mention-chip--with-status-icon"),"data-mention-kind":"issue","data-mention-comment":a.commentId?"true":void 0,"data-mention-status":a.status??void 0,title:t,...r,onClick:s,children:i.jsx("span",{className:"rudder-inline-token-label",children:t})});return i.jsx(nX,{mention:a,label:t,children:o})}function HKt(e){if(typeof window>"u")return;const t=`${window.location.pathname}${window.location.search}${window.location.hash}`;e!==t&&(window.history.pushState(window.history.state,"",e),window.dispatchEvent(new PopStateEvent("popstate",{state:window.history.state})))}const KKt=600*1e3,ZKt=256,Oy=new Map;function Nle(e){const t=Oy.get(e);return t?t.expiresAt<=Date.now()?(Oy.delete(e),null):(Oy.delete(e),Oy.set(e,t),t.state):null}function tte(e,t){for(Oy.delete(e),Oy.set(e,{expiresAt:Date.now()+KKt,state:t});Oy.size>ZKt;){const n=Oy.keys().next().value;if(typeof n!="string")break;Oy.delete(n)}}function XKt(e){let t;try{t=typeof e=="string"?new URL(e):e}catch{return null}const n=v5(t);if(n)return n.iconDataUrl;const r=Nle(t.href);return(r==null?void 0:r.status)==="ready"?r.iconUrl:null}function GKt(e){const t=e.href,n=v5(e),[r,s]=A.useState(()=>({href:t,state:n?{status:"ready",iconUrl:n.iconDataUrl}:Nle(t)??{status:"idle",iconUrl:null}})),a=r.href===t?r.state:n?{status:"ready",iconUrl:n.iconDataUrl}:{status:"loading",iconUrl:null};return A.useEffect(()=>{if(n){const u={status:"ready",iconUrl:n.iconDataUrl};tte(t,u),s({href:t,state:u});return}const o=Nle(t);if(o&&o.status!=="loading"){s({href:t,state:o});return}const l={status:"loading",iconUrl:null};tte(t,l),s({href:t,state:l});let c=!1;return Promise.resolve(yge(t,"preview")).then(u=>u!=null&&u.iconUrl?{status:"ready",iconUrl:u.iconUrl}:{status:"none",iconUrl:null}).catch(()=>({status:"error",iconUrl:null})).then(u=>{tte(t,u),c||s({href:t,state:u})}),()=>{c=!0}},[t,n]),a}function rX({url:e}){const t=GKt(e),n=v5(e),[r,s]=A.useState(()=>new Set),[a,o]=A.useState(()=>new Set),l=t.status==="ready"?t.iconUrl:null,c=l&&!r.has(l)?l:null;if(c){const d=a.has(c);return i.jsxs("span",{className:"rudder-website-link-icon","aria-hidden":"true","data-website-icon":d?"metadata":"generic",children:[d?null:i.jsx(jA,{className:"rudder-website-link-generic","aria-hidden":"true"}),i.jsx("img",{src:c,alt:"",className:"rudder-website-link-logo","aria-hidden":"true","data-website-icon":"metadata","data-dark-mode":n==null?void 0:n.darkMode,referrerPolicy:"no-referrer",style:d?void 0:{visibility:"hidden"},onLoad:()=>o(u=>new Set(u).add(c)),onError:()=>{s(u=>new Set(u).add(c))}})]})}return i.jsx("span",{className:"rudder-website-link-icon","aria-hidden":"true","data-website-icon":"generic",children:i.jsx(jA,{className:"rudder-website-link-generic","aria-hidden":"true"})})}function YKt(e){if(!A.isValidElement(e))return null;const t=e.props;return typeof t.className!="string"||!/\blanguage-mermaid\b/i.test(t.className)?null:jk(t.children).replace(/\n$/,"")}function P8e(e){return jk(e).replace(/\n$/,"")}function JKt(e){var r;if(!A.isValidElement(e))return null;const t=e.props;if(typeof t.className!="string")return null;const n=(r=t.className.match(/\blanguage-([^\s]+)/i))==null?void 0:r[1];return(n==null?void 0:n.toLowerCase())??null}function eZt(e){return e==="diff"||e==="patch"||e==="udiff"}function tZt(e){return/^(?:diff --git|index |new file mode |deleted file mode |old mode |new mode |rename from |rename to |similarity index )/.test(e)?"meta":e.startsWith("@@")?"hunk":e.startsWith("+++")||e.startsWith("---")?"file":e.startsWith("+")?"add":e.startsWith("-")?"remove":"context"}function nZt({source:e,preProps:t,sourceAttributes:n}){const r=e.split(`
1623
1623
  `);return i.jsx("pre",{...t,...n,className:q(typeof t.className=="string"?t.className:null,"rudder-markdown-patch-block"),children:i.jsx("code",{children:r.map((s,a)=>{const o=tZt(s),l=o==="add"||o==="remove",c=l?s.slice(0,1):"",d=l?s.slice(1):s;return i.jsxs("span",{className:q("rudder-markdown-patch-line",`rudder-markdown-patch-line--${o}`),children:[i.jsx("span",{className:"rudder-markdown-patch-line-marker","aria-hidden":!c,children:c}),i.jsx("span",{className:"rudder-markdown-patch-line-content",children:d})]},`${a}-${o}`)})})})}async function rZt(e){var r,s;if((r=navigator.clipboard)!=null&&r.writeText){await navigator.clipboard.writeText(e);return}const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly",""),t.style.position="fixed",t.style.left="-9999px",t.style.top="0",document.body.appendChild(t),t.select();const n=(s=document.execCommand)==null?void 0:s.call(document,"copy");if(t.remove(),!n)throw new Error("Clipboard write failed.")}function sZt(e,t,n=0){var c,d;const r=e==null?void 0:e.position,s=(c=r==null?void 0:r.start)==null?void 0:c.offset,a=(d=r==null?void 0:r.end)==null?void 0:d.offset;if(typeof s!="number"||typeof a!="number")return{};const o=n+((t==null?void 0:t.renderedBoundaryToRaw[s])??s),l=n+((t==null?void 0:t.renderedBoundaryToRaw[a])??a);return{"data-markdown-source-start":String(o),"data-markdown-source-end":String(l),"data-markdown-rendered-source-start":String(s),"data-markdown-rendered-source-end":String(a)}}function T8e(e){const t=e instanceof HTMLElement?e:(e==null?void 0:e.parentElement)??null;return(t==null?void 0:t.closest("[data-markdown-rendered-source-start][data-markdown-rendered-source-end]"))??null}function iZt(e,t){const n=Number(t.dataset.markdownRenderedSourceStart),r=Number(t.dataset.markdownRenderedSourceEnd);return!Number.isFinite(n)||!Number.isFinite(r)||r<=n?null:e.slice(n,r)}function aZt(e,t,n){const r=T8e(t.anchorNode),s=T8e(t.focusNode);if(r&&r===s)return iZt(n,r);const a=t.getRangeAt(0),o=Array.from(e.querySelectorAll("[data-markdown-rendered-source-start][data-markdown-rendered-source-end]")).filter(f=>{try{return a.intersectsNode(f)}catch{return!1}}),c=o.filter(f=>!o.some(m=>m!==f&&m.contains(f))).map(f=>({start:Number(f.dataset.markdownRenderedSourceStart),end:Number(f.dataset.markdownRenderedSourceEnd)})).filter(f=>Number.isFinite(f.start)&&Number.isFinite(f.end)&&f.end>f.start);if(c.length===0)return null;const d=Math.min(...c.map(f=>f.start)),u=Math.max(...c.map(f=>f.end));return n.slice(d,u)}const oZt=A.memo(function({source:t,darkMode:n}){const r=A.useId().replace(/[^a-zA-Z0-9_-]/g,""),[s,a]=A.useState(null),[o,l]=A.useState(null);return A.useEffect(()=>{let c=!0;return a(null),l(null),TKt().then(async d=>{d.initialize({startOnLoad:!1,securityLevel:"strict",theme:n?"dark":"default",fontFamily:"inherit",suppressErrorRendering:!0});const u=await d.render(`rudder-mermaid-${r}`,t);c&&a(u.svg)}).catch(d=>{if(!c)return;const u=d instanceof Error&&d.message?d.message:"Failed to render Mermaid diagram.";l(u)}),()=>{c=!1}},[n,r,t]),i.jsx("div",{className:"rudder-mermaid",children:s?i.jsx("div",{dangerouslySetInnerHTML:{__html:s}}):i.jsxs(i.Fragment,{children:[i.jsx("p",{className:q("rudder-mermaid-status",o&&"rudder-mermaid-status-error"),children:o?`Unable to render Mermaid diagram: ${o}`:"Rendering Mermaid diagram..."}),i.jsx("pre",{className:"rudder-mermaid-source",children:i.jsx("code",{className:"language-mermaid",children:t})})]})})});function _8e({children:e,copyText:t,preProps:n,sourceAttributes:r,block:s}){const[a,o]=A.useState("idle"),l=A.useRef(void 0),c=a==="copied"?"Copied":a==="failed"?"Copy failed":"Copy code";A.useEffect(()=>()=>clearTimeout(l.current),[]);const d=A.useCallback(async()=>{clearTimeout(l.current);try{await rZt(t),o("copied")}catch{o("failed")}l.current=setTimeout(()=>o("idle"),1600)},[t]);return i.jsxs("div",{className:"rudder-code-block-copy-wrap",children:[s??i.jsx("pre",{...n,...r,children:e}),i.jsx($c,{delayDuration:120,children:i.jsxs(Mi,{children:[i.jsx(Ei,{asChild:!0,children:i.jsx("button",{type:"button",className:"rudder-code-block-copy-button","aria-label":c,"data-copy-state":a,onClick:()=>void d(),children:a==="copied"?i.jsx(zi,{className:"h-3.5 w-3.5","aria-hidden":"true"}):i.jsx(No,{className:"h-3.5 w-3.5","aria-hidden":"true"})})}),i.jsx(Di,{side:"left",sideOffset:8,children:c})]})})]})}function Ya({children:e,className:t,resolveImageSrc:n,onLinkClick:r,agentMentions:s,skillReferences:a,enableImagePreview:o=!0,copyMarkdownOnCopy:l=!1,enableCodeBlockCopy:c=!1,sourceOffsetBase:d=0}){const{renderedSource:u,rootRef:f}=VKt(e),{resolvedTheme:m}=fR(),{mentions:h}=gge(),p=A.useMemo(()=>({agentMentionById:new Map(h.filter(L=>L.kind==="agent").map(L=>[L.agentId??L.id.replace(/^agent:/,""),L])),projectMentionById:new Map(h.filter(L=>L.kind==="project"&&L.projectId).map(L=>[L.projectId,L])),issueMentionById:new Map(h.filter(L=>L.kind==="issue"&&L.issueId).map(L=>[L.issueId,L])),issueMentions:h.filter(L=>L.kind==="issue"&&L.issueId),automationMentionById:new Map(h.filter(L=>L.kind==="automation"&&L.automationId).map(L=>[L.automationId,L])),chatMentionById:new Map(h.filter(L=>L.kind==="chat"&&L.chatConversationId).map(L=>[L.chatConversationId,L])),libraryDocMentionById:new Map(h.filter(L=>L.kind==="library_doc"&&L.libraryDocumentId).map(L=>[L.libraryDocumentId,L])),libraryEntryMentionById:new Map(h.filter(L=>L.kind==="library_file"&&L.libraryEntryId).map(L=>[L.libraryEntryId,L])),libraryFileMentionByPath:new Map(h.filter(L=>L.kind==="library_file"&&L.libraryFilePath).map(L=>[L.libraryFilePath,L])),libraryDirectoryMentionByPath:new Map(h.filter(L=>L.kind==="library_directory"&&L.libraryDirectoryPath).map(L=>[L.libraryDirectoryPath,L]))}),[h]),{agentMentionById:x,automationMentionById:b,chatMentionById:y,issueMentionById:w,issueMentions:k,libraryDirectoryMentionByPath:S,libraryDocMentionById:j,libraryEntryMentionById:C,libraryFileMentionByPath:I,projectMentionById:N}=p,{skillPreviewByHref:M,skillPreviewByLabel:E}=A.useMemo(()=>({skillPreviewByHref:new Map((a??[]).map(L=>[N$(L.href),L]).filter(([L])=>L.length>0)),skillPreviewByLabel:new Map((a??[]).map(L=>[N$(L.label),L]).filter(([L])=>L.length>0))}),[a]),_=MKt(),{normalizedChildren:z,sourceMap:T}=A.useMemo(()=>{const L=FKt(bge(u),s);return{normalizedChildren:L,sourceMap:zWt(u,L)}},[s,u]),$=A.useCallback(L=>sZt(L,T,d),[T,d]),B=A.useCallback(({node:L,children:R,...D})=>i.jsx("li",{...D,...$(L),children:R}),[$]),F=L=>{if(!l)return;const R=window.getSelection();if(!R||R.rangeCount===0||R.isCollapsed||!L.currentTarget.contains(R.anchorNode)||!L.currentTarget.contains(R.focusNode))return;const D=aZt(L.currentTarget,R,z)??z;L.clipboardData.setData("text/plain",D),L.preventDefault()},W=A.useCallback((L,R,D,X)=>{if(r==null?void 0:r({event:L,href:R,label:D,sourceHref:X})){L.preventDefault();return}if(L.defaultPrevented||!WKt(L))return;const se=C8e(R,_);se&&(L.preventDefault(),HKt(se))},[r,_]),Y=A.useCallback(({node:L,children:R,...D})=>{const X=YKt(R);if(X)return i.jsx(oZt,{source:X,darkMode:m==="dark"});const ee=$(L),se=JKt(R),ne=eZt(se)?P8e(R):null;if(ne!==null){const le=i.jsx(nZt,{source:ne,preProps:D,sourceAttributes:ee});return c?i.jsx(_8e,{copyText:ne,preProps:{},sourceAttributes:{},block:le}):le}return c?i.jsx(_8e,{copyText:P8e(R),preProps:D,sourceAttributes:ee,children:R}):i.jsx("pre",{...D,...ee,children:R})},[c,m,$]),G=A.useRef({agentMentionById:x,automationMentionById:b,chatMentionById:y,enableImagePreview:o,handleMarkdownLinkClick:W,issueMentionById:w,issueMentions:k,libraryDirectoryMentionByPath:S,libraryDocMentionById:j,libraryEntryMentionById:C,libraryFileMentionByPath:I,onLinkClick:r,organizationPrefix:_,projectMentionById:N,renderListItem:B,renderPre:Y,resolveImageSrc:n,skillPreviewByHref:M,skillPreviewByLabel:E,sourceAttributesForNode:$});G.current={agentMentionById:x,automationMentionById:b,chatMentionById:y,enableImagePreview:o,handleMarkdownLinkClick:W,issueMentionById:w,issueMentions:k,libraryDirectoryMentionByPath:S,libraryDocMentionById:j,libraryEntryMentionById:C,libraryFileMentionByPath:I,onLinkClick:r,organizationPrefix:_,projectMentionById:N,renderListItem:B,renderPre:Y,resolveImageSrc:n,skillPreviewByHref:M,skillPreviewByLabel:E,sourceAttributesForNode:$};const V=A.useMemo(()=>({p:({node:L,children:R,...D})=>i.jsx("p",{...D,...G.current.sourceAttributesForNode(L),children:R}),h1:({node:L,children:R,...D})=>i.jsx("h1",{...D,...G.current.sourceAttributesForNode(L),children:R}),h2:({node:L,children:R,...D})=>i.jsx("h2",{...D,...G.current.sourceAttributesForNode(L),children:R}),h3:({node:L,children:R,...D})=>i.jsx("h3",{...D,...G.current.sourceAttributesForNode(L),children:R}),h4:({node:L,children:R,...D})=>i.jsx("h4",{...D,...G.current.sourceAttributesForNode(L),children:R}),h5:({node:L,children:R,...D})=>i.jsx("h5",{...D,...G.current.sourceAttributesForNode(L),children:R}),h6:({node:L,children:R,...D})=>i.jsx("h6",{...D,...G.current.sourceAttributesForNode(L),children:R}),strong:({node:L,children:R,...D})=>i.jsx("strong",{...D,...G.current.sourceAttributesForNode(L),children:R}),em:({node:L,children:R,...D})=>i.jsx("em",{...D,...G.current.sourceAttributesForNode(L),children:R}),del:({node:L,children:R,...D})=>i.jsx("del",{...D,...G.current.sourceAttributesForNode(L),children:R}),code:({node:L,children:R,...D})=>i.jsx("code",{...D,...G.current.sourceAttributesForNode(L),children:R}),li:L=>G.current.renderListItem(L),table:({node:L,children:R,...D})=>i.jsx("div",{className:"rudder-markdown-table-scroll",children:i.jsx("table",{...D,...G.current.sourceAttributesForNode(L),children:R})}),th:({node:L,children:R,...D})=>i.jsx("th",{...D,...G.current.sourceAttributesForNode(L),children:R}),td:({node:L,children:R,...D})=>i.jsx("td",{...D,...G.current.sourceAttributesForNode(L),children:R}),pre:L=>G.current.renderPre(L),a:({node:L,href:R,children:D})=>{const{agentMentionById:X,automationMentionById:ee,chatMentionById:se,handleMarkdownLinkClick:ne,issueMentionById:le,issueMentions:ie,libraryDirectoryMentionByPath:re,libraryDocMentionById:de,libraryEntryMentionById:Be,libraryFileMentionByPath:ae,onLinkClick:Ee,organizationPrefix:he,projectMentionById:_e,skillPreviewByHref:Ie,skillPreviewByLabel:$e,sourceAttributesForNode:ce}=G.current,Oe=R?Fc(R):null;if(Oe){const ut=Jee(j5(jk(D))),ge=(()=>{var Se;if(Oe.kind==="agent")return{...Oe,icon:((Se=X.get(Oe.agentId))==null?void 0:Se.agentIcon)??Oe.icon};if(Oe.kind==="project"){const We=_e.get(Oe.projectId);return{...Oe,color:(We==null?void 0:We.projectColor)??Oe.color,icon:(We==null?void 0:We.projectIcon)??Oe.icon}}if(Oe.kind==="issue"){const We=le.get(Oe.issueId)??I7(Oe.issueId,ie)??I7(Oe.ref,ie)??I7(N8e(R),ie);return{...Oe,issueId:Oe.issueId,ref:(We==null?void 0:We.issueIdentifier)??Oe.ref,status:(We==null?void 0:We.issueStatus)??Oe.status}}return Oe})(),Le=(()=>{var Se,We,Te,He,fe,je,ye,tt,me,ze,De;if(ge.kind==="agent")return((Se=X.get(ge.agentId))==null?void 0:Se.name)??ut;if(ge.kind==="project")return((We=_e.get(ge.projectId))==null?void 0:We.name)??ut;if(ge.kind==="issue"){const kt=le.get(ge.issueId)??I7(ge.issueId,ie)??I7(ge.ref,ie);return((kt==null?void 0:kt.name)??ut??((Te=ge.ref)==null?void 0:Te.trim())??"")||((He=ge.ref)==null?void 0:He.trim())||Yee(ge)}return ge.kind==="automation"?((fe=ee.get(ge.automationId))==null?void 0:fe.name)??((je=ge.title)==null?void 0:je.trim())??ut:ge.kind==="chat"?((ye=se.get(ge.conversationId))==null?void 0:ye.name)??ut:ge.kind==="library_doc"?((tt=de.get(ge.documentId))==null?void 0:tt.name)??ut:ge.kind==="library_entry"?((me=Be.get(ge.entryId))==null?void 0:me.name)??ut:ge.kind==="library_file"?((ze=ae.get(ge.filePath))==null?void 0:ze.name)??ut:ge.kind==="library_directory"?((De=re.get(ge.directoryPath))==null?void 0:De.name)??ut:ut})()||Yee(ge),rt=Jee(Le),At=rc(C5(ge),he);if(ge.kind==="issue")return i.jsx(I8e,{mention:ge,label:rt,targetHref:At,sourceAttributes:ce(L),onClick:Se=>{ne(Se,At,rt)}});const Ue=i.jsx("a",{href:At,className:q("rudder-mention-chip",`rudder-mention-chip--${ge.kind}`,ge.kind==="project"&&"rudder-project-mention-chip"),"data-mention-kind":ge.kind,title:rt,style:bN(ge),...ce(L),onClick:Se=>{ne(Se,At,rt)},children:i.jsx("span",{className:"rudder-inline-token-label",children:rt})});return ge.kind==="automation"||ge.kind==="chat"||ge.kind==="plugin"?Ue:i.jsx(nX,{mention:ge,label:rt,children:Ue})}const Ye=LA(R,jk(D));if(Ye){const ut=Ie.get(N$(Ye.href))??$e.get(N$(Ye.label))??null,ge=pw(ut==null?void 0:ut.label)||Ye.label;return i.jsx(Ige,{label:ge,preview:ut,fallbackOpenHref:fge(Ye.href)??(ut==null?void 0:ut.openHref)??"#",sourceAttributes:ce(L),onOpen:Ee?(Le,rt,At)=>{ne(Le,rt,At,Ye.href)}:void 0})}const J=jk(D),qe=BKt(R),be=hZe(R),ot=ZZ(R),ke=qe&&QKt(J),Ce=R?C8e(R,he):null,ue=I7(N8e(R),ie);if(ue&&Ce){const ut={kind:"issue",issueId:ue.issueId,ref:ue.issueIdentifier??null,commentId:null,status:ue.issueStatus??null},ge=Jee(ue.name||J||Yee(ut));return i.jsx(I8e,{mention:ut,label:ge,targetHref:Ce,sourceAttributes:ce(L),onClick:Le=>{ne(Le,Ce,ge)}})}const mt=Ce&&!UKt(R)?Ce:R;if(be)return i.jsxs("a",{href:R,target:"_blank",rel:"noreferrer noopener",title:J.trim()||(ke?R:void 0),className:"rudder-website-link",...ce(L),onClick:ut=>{R&&ne(ut,R,J)},children:[i.jsx(rX,{url:be}),i.jsx("span",{className:"rudder-website-link-label rudder-inline-token-label",children:D})]});if(ot){const{enableImagePreview:ut}=G.current;return i.jsx(BKe,{enablePreview:ut,href:R??ot,filePath:ot,label:J,sourceAttributes:ce(L),onClick:ge=>{R&&ne(ge,R,J)},children:D})}return i.jsx("a",{href:mt,target:qe?"_blank":void 0,rel:qe?"noreferrer noopener":"noreferrer",title:ke?R:void 0,...ce(L),onClick:ut=>{R&&ne(ut,Ce??R,J)},children:D})},img:({node:L,src:R,alt:D,...X})=>{const{enableImagePreview:ee,resolveImageSrc:se}=G.current,le=(R&&se?se(R):null)??R??"",ie=R?wHt({alt:D,enablePreview:ee,sourceAttributes:G.current.sourceAttributesForNode(L),src:R,onClick:(re,de)=>{G.current.handleMarkdownLinkClick(re,R,de)}}):null;return ie||(ee&&le?i.jsx(U0,{...X,src:le,alt:D??"",name:(D==null?void 0:D.trim())||"Markdown image",previewTestId:"markdown-body-image-preview-dialog",previewTitleFallback:"Image preview"}):i.jsx("img",{...X,src:le,alt:D??""}))}}),[]);return i.jsx(i.Fragment,{children:i.jsx("div",{ref:f,className:q("rudder-markdown prose prose-sm max-w-none break-words overflow-hidden",m==="dark"&&"prose-invert",t),onCopyCapture:F,"data-copy-markdown-source":l?"true":void 0,children:i.jsx(Gpe,{remarkPlugins:[FZ],components:V,urlTransform:L=>L,children:z})})})}const _s={listSavedViews:(e,t={})=>{const n=new URLSearchParams({visibility:t.visibility??"visible"});return t.limit!==void 0&&n.set("limit",String(t.limit)),t.offset!==void 0&&n.set("offset",String(t.offset)),t.primaryRailPinned!==void 0&&n.set("primaryRailPinned",String(t.primaryRailPinned)),Qe.get(`/orgs/${e}/messenger/saved-views?${n.toString()}`)},getSavedView:(e,t)=>Qe.get(`/orgs/${e}/messenger/saved-views/${t}`),keepSavedView:(e,t)=>Qe.post(`/orgs/${e}/messenger/saved-views/keep`,t),createSavedView:(e,t)=>Qe.post(`/orgs/${e}/messenger/saved-views`,t),updateSavedView:(e,t,n)=>Qe.patch(`/orgs/${e}/messenger/saved-views/${t}`,n),reorderSavedViews:(e,t)=>Qe.patch(`/orgs/${e}/messenger/saved-views/reorder`,{ids:t}),deleteSavedView:(e,t)=>Qe.delete(`/orgs/${e}/messenger/saved-views/${t}`),listThreads:e=>Qe.get(`/orgs/${e}/messenger/threads`),listThreadPage:(e,t={})=>{const n=new URLSearchParams;t.cursor&&n.set("cursor",t.cursor),typeof t.limit=="number"&&n.set("limit",String(t.limit)),t.splitIssues&&n.set("splitIssues","true");const r=n.toString();return Qe.get(`/orgs/${e}/messenger/threads${r?`?${r}`:""}`)},markThreadRead:(e,t,n)=>Qe.post(`/orgs/${e}/messenger/threads/${encodeURIComponent(t)}/read`,n?{lastReadAt:n}:{}),dismissUnreads:e=>Qe.post(`/orgs/${e}/messenger/unreads/dismiss`,{}),updateThreadUserState:(e,t,n)=>Qe.post(`/orgs/${e}/messenger/threads/${encodeURIComponent(t)}/user-state`,n),getIssuesThread:(e,t={})=>{const n=new URLSearchParams;t.cursor&&n.set("cursor",t.cursor),typeof t.limit=="number"&&n.set("limit",String(t.limit));const r=n.toString();return Qe.get(`/orgs/${e}/messenger/issues${r?`?${r}`:""}`)},getApprovalsThread:e=>Qe.get(`/orgs/${e}/messenger/approvals`),getSystemThread:(e,t)=>Qe.get(`/orgs/${e}/messenger/system/${t}`),listCustomGroups:e=>Qe.get(`/orgs/${e}/messenger/groups`),createCustomGroup:(e,t)=>Qe.post(`/orgs/${e}/messenger/groups`,t),createCustomGroupWithEntries:(e,t)=>Qe.post(`/orgs/${e}/messenger/groups/merge`,t),updateCustomGroup:(e,t,n)=>Qe.patch(`/orgs/${e}/messenger/groups/${t}`,n),regenerateCustomGroupTitle:(e,t)=>Qe.post(`/orgs/${e}/messenger/groups/${t}/title/regenerate`,{}),separateCustomGroup:(e,t)=>Qe.post(`/orgs/${e}/messenger/groups/${t}/separate`,{}),deleteCustomGroup:(e,t)=>Qe.delete(`/orgs/${e}/messenger/groups/${t}`),reorderCustomGroups:(e,t)=>Qe.patch(`/orgs/${e}/messenger/groups/reorder`,{groupIds:t}),assignCustomGroupEntry:(e,t,n)=>Qe.post(`/orgs/${e}/messenger/groups/${t}/entries`,{itemKey:n}),removeCustomGroupEntry:(e,t)=>Qe.delete(`/orgs/${e}/messenger/groups/entries/${encodeURIComponent(t)}`),reorderCustomGroupEntries:(e,t,n)=>Qe.patch(`/orgs/${e}/messenger/groups/${t}/entries/reorder`,{itemKeys:n})},lZt=400,cZt=2e3;function sX(e){return e==="starting"||e==="stopping"?lZt:e==="running"?cZt:!1}function eC(e,t){return e.desktopInstallationId===t.desktopInstallationId&&e.appPublicId===t.appPublicId&&e.localBindingId===t.localBindingId}function pZe(e){return["A Local App could not open in Rudder Desktop.",`Local App label (context only): ${e.trim().replace(/[\r\n]+/g," ").slice(0,160)||"this Local App"}`,"Help me diagnose the startup issue. Ask for any error details or logs you need; I will review them before sharing."].join(`
1624
1624
 
@@ -1702,7 +1702,7 @@ When you submit the join request, use:
1702
1702
  - \`agentRuntimeType: "openclaw_gateway"\`
1703
1703
  - \`agentDefaultsPayload.url\` 填你的 \`ws://\` 或 \`wss://\` gateway URL
1704
1704
  - \`agentDefaultsPayload.headers["x-openclaw-token"]\` 填你的 gateway token
1705
- - (兼容旧字段)\`agentDefaultsPayload.headers["x-openclaw-auth"]\``,"organizationSettings.packages.description":"在不同 Rudder 安装之间迁移组织配置与工作数据。","organizationSettings.packages.export":"导出","organizationSettings.packages.import":"导入","organizationSettings.danger.description":"归档这个 organization 后,它会从侧边栏中隐藏。这个状态会持久化到数据库。","organizationSettings.danger.confirm":"要归档 organization “{{name}}” 吗?它会从侧边栏中隐藏。","organizationSettings.danger.archiving":"归档中...","organizationSettings.danger.alreadyArchived":"已归档","organizationSettings.danger.archive":"归档 organization","organizationSettings.danger.failed":"归档 organization 失败","settings.eyebrow.system":"系统设置","settings.eyebrow.labs":"实验室","app.instanceSetupRequired":"需要完成实例初始化","app.bootstrapInvite.active":"当前还没有实例管理员。引导邀请已经激活。请查看 Rudder 启动日志中的首个管理员邀请链接,或运行下面的命令重新生成:","app.bootstrapInvite.inactive":"当前还没有实例管理员。请在 Rudder 运行环境中执行下面的命令生成首个管理员邀请链接:","app.failedToLoadAppState":"加载应用状态失败","app.addAnotherAgentToOrganization":"为 {{name}} 再添加一个智能体","app.createAnotherOrganization":"创建另一个组织","app.createFirstOrganization":"创建你的第一个组织","app.onboarding.addAgentDescription":"再次运行引导,为这个组织添加一个智能体和一个初始任务。","app.onboarding.createAnotherDescription":"再次运行引导,创建另一个组织并初始化它的第一个智能体。","app.onboarding.createFirstDescription":"从创建一个组织和你的第一个智能体开始。","app.addAgent":"添加智能体","app.startOnboarding":"开始引导","app.noCompaniesDescription":"从创建一个组织开始。","app.newOrganization":"新建组织","general.title":"通用","general.description":"这台设备上的核心应用偏好。","general.updateFailed":"更新通用设置失败。","general.loadLoading":"正在加载通用设置...","general.loadFailed":"加载通用设置失败。","general.language.title":"语言","general.language.description":"选择这个 Rudder 实例在控制台界面中使用的语言。","general.language.label":"界面语言","general.language.help":"这是实例级界面语言,会影响所有使用这个实例的用户看到的控制台外壳和设置页面。","general.language.option.en.label":"英语","general.language.option.en.description":"默认产品语言","general.language.option.zh-CN.label":"简体中文","general.language.option.zh-CN.description":"中文界面","general.language.preview.en.primary":"Hello","general.language.preview.en.secondary":"Board UI","general.language.preview.zh-CN.primary":"你好","general.language.preview.zh-CN.secondary":"控制台界面","general.basics.title":"基础","general.productTour.title":"工作台教程","general.productTour.description":"重新播放引导教程。","general.productTour.start":"开始教程","general.logs.title":"操作日志","general.logs.description":"调整界面中面向操作员展示的输出方式。","general.logs.censor.title":"对日志中的用户名做脱敏","general.logs.censor.description":"对日志中显示的主目录路径用户名做脱敏。","general.updates.title":"桌面应用","general.updates.description":"选择这台机器安装 Rudder Desktop 时使用哪个发布渠道。","general.updates.loadFailed":"加载桌面更新设置失败。","general.updates.updateFailed":"更新桌面更新设置失败。","general.updates.unavailable":"当前环境不支持桌面更新设置。","general.updates.canary.title":"接收桌面测试版更新","general.updates.canary.disabledDescription":"安装最新正式版;当测试版更新时也纳入检测。","general.updates.canary.enabledDescription":"这台机器会同时检查正式版和更新的测试版。","general.diagnostics.developer.title":"显示开发诊断信息","general.diagnostics.developer.description":"在 transcript 中显示 Rudder 内部运行时、workspace、session 和 adapter 诊断信息。","general.developer.title":"开发者","general.appearance.title":"外观","general.appearance.description":"选择这个设备上的 Rudder 外观。视觉风格遵循低眩光、克制的 Claude 风格界面。","general.appearance.colorMode":"颜色模式","general.appearance.light.label":"浅色","general.appearance.light.description":"暖色纸面风格","general.appearance.system.label":"自动","general.appearance.system.description":"跟随系统外观","general.appearance.dark.label":"深色","general.appearance.dark.description":"低眩光工作区","general.appearance.designStyle":"设计风格","general.appearance.defaultStyle.label":"Classic","general.appearance.defaultStyle.description":"平衡的低眩光界面","general.appearance.mira.label":"Compact","general.appearance.mira.description":"紧凑卡片与控件","general.appearance.luma.label":"Rudder","general.appearance.luma.description":"柔和宽松的控件","general.appearance.baseColor":"基础色","general.appearance.base.neutral.label":"Neutral","general.appearance.base.neutral.description":"平衡的中性灰界面","general.appearance.base.stone.label":"Stone","general.appearance.base.stone.description":"暖调石色界面","general.appearance.base.zinc.label":"Zinc","general.appearance.base.zinc.description":"冷调灰色界面","general.appearance.base.mauve.label":"Mauve","general.appearance.base.mauve.description":"低饱和玫瑰灰界面","general.appearance.base.olive.label":"Olive","general.appearance.base.olive.description":"低饱和橄榄色界面","general.appearance.base.mist.label":"Mist","general.appearance.base.mist.description":"柔和蓝灰界面","general.appearance.base.taupe.label":"Taupe","general.appearance.base.taupe.description":"暖调灰褐界面","general.appearance.themeColor":"主题色","general.appearance.theme.neutral.label":"Neutral","general.appearance.theme.neutral.description":"单色操作状态","general.appearance.theme.amber.label":"Amber","general.appearance.theme.amber.description":"琥珀色操作状态","general.appearance.theme.blue.label":"Blue","general.appearance.theme.blue.description":"蓝色操作状态","general.appearance.theme.cyan.label":"Cyan","general.appearance.theme.cyan.description":"青色操作状态","general.appearance.theme.emerald.label":"Rudder","general.appearance.theme.emerald.description":"Rudder 绿色操作状态","general.appearance.theme.fuchsia.label":"Fuchsia","general.appearance.theme.fuchsia.description":"紫红色操作状态","general.appearance.theme.green.label":"Green","general.appearance.theme.green.description":"绿色操作状态","general.appearance.theme.indigo.label":"Indigo","general.appearance.theme.indigo.description":"靛蓝色操作状态","general.appearance.theme.lime.label":"Lime","general.appearance.theme.lime.description":"青柠色操作状态","general.appearance.theme.orange.label":"Orange","general.appearance.theme.orange.description":"橙色操作状态","general.appearance.theme.pink.label":"Pink","general.appearance.theme.pink.description":"粉色操作状态","general.appearance.toolCalls.title":"Tool Call","general.appearance.toolCalls.failureIndicators.label":"显示失败标识","general.appearance.toolCalls.failureIndicators.description":"Tool Call 失败时使用红色样式并显示失败标签。","general.appearance.toolCalls.failureIndicators.ariaLabel":"切换 Tool Call 失败标识","notifications.title":"通知","notifications.description":"管理这个 Rudder 实例的未读 inbox 提醒。","notifications.loadFailed":"加载通知设置失败。","notifications.updateFailed":"更新通知设置失败。","notifications.support.available":"可用","notifications.support.unavailable":"不可用","notifications.permission.title":"权限","notifications.permission.description":"通知权限由操作系统或浏览器掌控,所以 Rudder 需要同时展示当前状态和修复入口。","notifications.permission.requestFailed":"请求通知权限失败。","notifications.permission.openSettingsFailed":"打开通知设置失败。","notifications.permission.access.title":"通知访问权限","notifications.permission.access.summary":"权限:{{permission}}。提醒:{{notificationsSupport}}。","notifications.permission.access.summaryDesktop":"权限:{{permission}}。原生提醒:{{notificationsSupport}}。","notifications.permission.access.default":"Rudder 还没有请求通知权限,因此未读 inbox 提醒可能不会出现。","notifications.permission.access.denied.desktop":"通知权限已被操作系统拦截。请在系统通知设置中重新允许 Rudder,才能恢复 macOS 提醒。","notifications.permission.access.denied.browser":"通知权限已被浏览器拦截。请在浏览器站点通知设置中重新允许 Rudder,才能在 `pnpm dev` 里预览 inbox 提醒。","notifications.permission.access.requesting":"请求中...","notifications.permission.access.enable":"开启通知","notifications.permission.access.desktopHelp":"这里能触发原生通知,但真正的允许/阻止状态由 macOS 管理。如果没有弹出通知,请打开系统设置并检查 {{appName}}。","notifications.permission.access.desktopHelpProd":"真正的允许/阻止状态由 macOS 管理。如果没有弹出通知,请打开系统设置并检查 {{appName}}。","notifications.permission.access.openSettings":"打开通知设置","notifications.environment.title":"当前环境","notifications.environment.desktop":"当前运行在 Electron 桌面壳中。","notifications.environment.browser":"当前运行在浏览器预览模式中。","notifications.environment.desktopHelp":"这里可以使用原生系统通知来提示未读 inbox 变化。","notifications.environment.browserHelp":"浏览器模式可以通过 Web Notifications API 预览未读 inbox 提醒。","notifications.behavior.title":"行为","notifications.behavior.description":"选择 Rudder 是否提示未读 inbox 活动。","notifications.behavior.inbox.title":"Inbox 活动提醒","notifications.behavior.inbox.description":"当未读 inbox 数量增加时显示提醒。","notifications.behavior.inbox.toggle":"切换 inbox 通知","systemPermissions.title":"系统权限","systemPermissions.description":"管理本地自动化、文件访问和 inbox 提醒所需的系统权限。","systemPermissions.section.title":"权限","systemPermissions.section.description":"Rudder 会尽量打开对应系统设置;最终状态仍以操作系统为准。","systemPermissions.status.authorized":"已授权","systemPermissions.status.needsAccess":"需要授权","systemPermissions.status.blocked":"已阻止","systemPermissions.status.checking":"检查中","systemPermissions.status.desktopOnly":"仅桌面应用","systemPermissions.status.perApp":"按应用授权","systemPermissions.status.unknown":"未知","systemPermissions.status.unavailable":"不可用","systemPermissions.action.openSettings":"打开设置","systemPermissions.action.desktopOnly":"仅桌面可用","systemPermissions.action.browserManaged":"由浏览器管理","systemPermissions.openSettingsFailed":"打开系统设置失败。","systemPermissions.permission.fullDiskAccess.title":"完全磁盘访问权限","systemPermissions.permission.fullDiskAccess.description":"在需要更广文件访问时读取本地项目文件和工作区元数据。","systemPermissions.permission.accessibility.title":"辅助功能","systemPermissions.permission.accessibility.description":"让 Rudder 驱动的桌面自动化在需要时观察并控制应用界面。","systemPermissions.permission.automation.title":"自动化","systemPermissions.permission.automation.description":"macOS 会按目标应用分别授权自动化;可打开此面板查看具体应用条目。","systemPermissions.permission.notifications.title":"通知","systemPermissions.permission.notifications.description":"Rudder 通知的系统访问权限。Issue 和 chat 通知可以在下方分别控制。","systemPermissions.permission.notifications.inboxLabel":"Inbox 活动提醒","systemPermissions.notifications.title":"通知","systemPermissions.notifications.description":"系统通知权限可用后,选择 Rudder 哪些事件需要提醒你。","systemPermissions.notifications.system.title":"系统通知访问权限","systemPermissions.notifications.system.description":"如果 Rudder 通知被阻止或没有出现,可以打开系统通知设置检查。","systemPermissions.notifications.issue.title":"Issue 通知","systemPermissions.notifications.issue.description":"当 issue 被创建、更新、评论或重新打开时提醒。","systemPermissions.notifications.issue.toggle":"切换 issue 通知","systemPermissions.notifications.chat.title":"Chat 通知","systemPermissions.notifications.chat.description":"当 assistant chat 回复、提议 issue 或操作时提醒。","systemPermissions.notifications.chat.toggle":"切换 chat 通知","about.title":"关于","about.version.title":"版本","about.version.description":"这里显示当前机器上运行的 Rudder 构建版本。","about.version.current":"版本","about.desktop.title":"桌面应用","about.desktop.description":"这个壳层连接到与控制台、CLI 以及其他本地 Rudder 界面共用的同一份本地实例数据。","about.desktop.profile":"环境","about.desktop.instance":"实例 ID","about.desktop.runtime":"运行时","about.desktop.owner":"拥有者","about.desktop.instanceDataPath":"实例数据路径","about.actions.title":"操作","about.actions.description":"这些动作属于应用生命周期,不应该埋在通用偏好里。","about.notifications.description":"Inbox 提醒、角标行为和权限修复入口现在都集中在独立的通知设置页中管理。","about.notifications.open":"打开通知设置","about.updates.title":"检查更新","about.updates.check":"检查更新","about.updates.install":"更新","about.updates.download":"下载更新","about.updates.installing":"正在更新...","about.updates.channel.stable":"正式版","about.updates.channel.canary":"正式版 + Canary","about.updates.available.inline":"发现 {{channel}} 新版本:{{latestVersion}}。","about.updates.current.inline":"{{channel}} 当前已经是最新版本:{{currentVersion}}。","about.updates.unavailable.inline":"暂时无法完成 {{channel}} 版本对比。","about.updates.available.toastTitle":"发现新版本","about.updates.available.toastBody":"{{latestVersion}} 已可下载。","about.updates.installStarted.toastTitle":"已开始更新","about.updates.installStarted.toastBody":"Rudder 会在安装 {{latestVersion}} 后关闭并重新打开。","about.updates.installWaiting.toastTitle":"更新已排队","about.updates.installWaiting.toastBody":"安装包正在下载。Rudder 会在 {{totalRuns}} 个活跃运行结束后自动更新。","about.updates.installBlocked.toastTitle":"更新已暂停","about.updates.installUnavailable":"当前构建不支持应用内安装更新。","about.updates.installFailed":"无法开始更新。","about.updates.installFailedToastTitle":"无法开始更新","about.updates.progress.title":"正在更新到 {{version}}","about.updates.progress.readyTitle":"更新已准备好","about.updates.progress.completeTitle":"重启交接已完成","about.updates.progress.detailsTitle":"更新进度详情","about.updates.progress.failedTitle":"更新失败","about.updates.progress.retry":"重试","about.updates.progress.restartToUpdate":"退出并更新","about.updates.progress.updateWhenIdle":"空闲时更新","about.updates.progress.forceRestartToUpdate":"停止运行并立即更新","about.updates.progress.blockersTitle":"正在延迟更新的运行","about.updates.progress.blockerRun":"{{organization}} · {{agent}} · 运行 {{runId}}","about.updates.progress.automaticApply":"这些运行结束后,Rudder 会自动完成更新。","about.updates.progress.openReleases":"打开发布页","about.updates.progress.dismiss":"关闭更新状态","about.updates.progress.phase.starting":"正在开始更新...","about.updates.progress.phase.preparing_runtime":"正在准备轻量更新...","about.updates.progress.phase.resolving_release":"正在解析发布版本...","about.updates.progress.phase.downloading_checksums":"正在下载校验文件...","about.updates.progress.phase.downloading_asset":"正在下载桌面安装包...","about.updates.progress.phase.verifying_checksum":"正在校验安装包...","about.updates.progress.phase.ready_to_install":"安装包已下载并校验完成,正在检查运行状态...","about.updates.progress.phase.waiting_for_active_runs":"正在等待运行结束...","about.updates.progress.phase.preparing_restart":"正在准备重启...","about.updates.progress.phase.closing":"Rudder 将关闭并重新打开以完成更新。","about.updates.progress.phase.complete":"Rudder Desktop 启动交接已完成。","about.updates.progress.phase.failed":"更新失败。","about.updates.current.toastTitle":"已经是最新版本","about.updates.current.toastBody":"当前桌面构建已经是 {{currentVersion}}。","about.updates.unavailable.toastTitle":"暂时无法检查更新","about.updates.unavailable.toastBody":"当前无法把这个构建与最新桌面版本进行对比。","about.updates.browserFallback.toastTitle":"已打开发布页","about.updates.browserFallback.toastBody":"桌面更新检查只能在打包后的应用内运行,因此已改为打开发布页面。","about.updates.failed":"检查更新失败。","about.updates.failedToastTitle":"检查更新失败","about.feedback.title":"发送反馈","about.feedback.send":"发送反馈","about.feedback.toastTitle":"正在打开邮件应用","about.feedback.toastBody":"正在为 Rudder 维护者邮箱创建新邮件草稿。","about.feedback.failed":"打开反馈邮件草稿失败。","about.feedback.failedToastTitle":"发送反馈失败","profile.title":"个人资料","profile.loadLoading":"正在加载个人资料设置...","profile.loadFailed":"加载个人资料设置失败。","profile.updateFailed":"更新个人资料设置失败。","profile.toastSaved.title":"个人资料已保存","profile.toastSaved.body":"你的操作员资料已更新。","profile.toastSaveFailed.title":"保存个人资料失败","profile.about.title":"关于你","profile.nickname.label":"你的称呼","profile.nickname.placeholder":"Rudder 应该怎么称呼你?","profile.moreAboutYou.label":"更多关于你","profile.moreAboutYou.placeholder":"补充一些长期有效的背景信息,帮助内置聊天助手更好理解你的请求。","profile.moreAboutYou.help":"Rudder 只会把这段内容注入内置聊天助手。如果留空,则不会追加到聊天系统提示词中。","profile.import.helper.title":"从其他 AI 导入 memories","profile.import.helper.description":"把这段提示词复制到 ChatGPT、Claude 或其他 AI provider,再把导出的 memory 粘贴到下面。","profile.import.copyPrompt":"复制 memory 导入提示词","profile.import.copiedButton":"已复制","profile.import.copied.title":"提示词已复制","profile.import.copied.body":"把结果粘贴到“更多关于你”,再编辑并保存。","profile.import.copyFailed.title":"提示词未复制","profile.import.copyFailed.body":"请手动选中提示词文本并复制。","profile.save":"保存资料","profile.saving":"保存中...","productTour.checklist.title":"完成首次工作闭环","productTour.checklist.workspace":"读懂控制台","productTour.checklist.create":"创建小任务","productTour.checklist.issues":"使用 issue 结构","productTour.checklist.inspect":"检查工作输出","productTour.checklist.settings":"再次找到教程","productTour.stepCounter":"{{current}} / {{total}}","productTour.step.workspace.title":"Rudder 是 agent work 的控制台","productTour.step.workspace.body":"主导航汇集消息、任务、智能体、项目和自动化。打开项目,可以访问具体项目和文档。其他可选工作区会在启用后显示。","productTour.step.create.title":"从一个 agent 真能推进的小任务开始","productTour.step.create.body":"创建菜单是新 Chat、issue、agent 和 project 的入口。第一次闭环可以选择边界清楚、结果可 review 的小 Chat 或 issue。","productTour.step.issues.title":"Issue 增加明确的工作流结构","productTour.step.issues.body":"Issue 页面展示哪些工作在等待、执行、阻塞或完成。Chat 是并列的对话式路径;需要明确 owner、状态、优先级、依赖或 review 时,再使用 issue。","productTour.step.inspect.title":"先检查工作,再审批或继续推进","productTour.step.inspect.body":"Dashboard 会展示当前页面、详情、transcript、产出和审批入口。Rudder 应该让你清楚看到发生了什么,以及哪里需要你介入。","productTour.step.settings.title":"你可以从 Settings 重新播放教程","productTour.step.settings.body":"第一次导览结束后,Rudder 会保持安静。以后想重新查看时,打开系统设置,再进入通用即可再次运行。","productTour.back":"上一步","productTour.next":"下一步","productTour.finish":"完成","productTour.skip":"跳过教程","heartbeats.title":"心跳","heartbeats.description":"查看所有组织的定时心跳配置。你可以在这里看到哪些已调度、哪些只是已配置,并直接按行启停心跳。","heartbeats.loadLoading":"正在加载调度心跳...","heartbeats.loadFailed":"加载调度心跳失败。","heartbeats.updateFailed":"更新心跳失败。","heartbeats.disableAllFailed":"批量关闭所有心跳失败。","heartbeats.summary.scheduled":"已调度","heartbeats.summary.configuredInactive":"已配置未激活","heartbeats.summary.disabled":"已关闭","heartbeats.summary.organization":"个组织","heartbeats.summary.organizations":"个组织","heartbeats.disableAll":"全部关闭","heartbeats.disabling":"关闭中...","heartbeats.confirmDisableAll.one":"确定要关闭全部 {{count}} 个已启用智能体的定时心跳吗?","heartbeats.confirmDisableAll.many":"确定要关闭全部 {{count}} 个已启用智能体的定时心跳吗?","heartbeats.empty":"没有符合当前条件的调度心跳。","heartbeats.section.title":"已调度智能体","heartbeats.section.description":"按组织分组展示已启用心跳的智能体,方便你统一查看归属、频率与最近心跳状态。","heartbeats.table.agent":"智能体","heartbeats.table.role":"角色","heartbeats.table.scheduler":"调度状态","heartbeats.table.interval":"间隔","heartbeats.table.lastHeartbeat":"最近心跳","heartbeats.table.actions":"操作","heartbeats.scheduler.scheduled":"已调度","heartbeats.scheduler.configuredInactive":"已配置,未激活","heartbeats.scheduler.disabled":"已关闭","heartbeats.never":"从未","heartbeats.fullAgentConfig":"完整智能体配置","heartbeats.timerState":"定时心跳状态","heartbeats.on":"开","heartbeats.off":"关","chat.annotations.selectionUnavailable":"选区已不可用","chat.annotations.selectionUnavailableBody":"请重新选择回复中的文字后再试。","chat.annotations.couldNotAdd":"无法添加批注","chat.annotations.added":"已添加批注","chat.annotations.removed":"已移除批注","newIssue.agentRequest.accepted":"已发送给 Agent,完成后会在 Inbox 通知你","newIssue.agentRequest.undo":"撤销","newIssue.agentRequest.undoing":"正在取消...","newIssue.agentRequest.cancelling":"正在取消本次 Agent Run...","newIssue.agentRequest.undoUnavailable":"该 Agent Run 已无法取消","newIssue.agentRequest.runFinished":"该 Agent Run 已处于 {{status}} 状态。","newIssue.agentRequest.runUnavailable":"该 Agent Run 已不可用。","newIssue.agentRequest.undoFailed":"无法取消 Agent Run","newIssue.agentRequest.undoFailedBody":"Agent Run 可能仍在运行,请重试撤销。"},OZe=["placeholder","title","aria-label"],PZt=["code","pre","script","style","textarea","[contenteditable='true']",".cm-editor",".cm-content",".mdxeditor","[data-i18n-ignore='true']"].join(", "),R8e=new WeakMap,L8e=new WeakMap;function SZe(e){return e?e.closest(PZt)!=null:!0}function jZe(e,t){const n=e.parentElement;if(!n||SZe(n))return;const r=e.textContent??"";let s=R8e.get(e);s?r!==s.rendered&&r!==s.source&&(s.source=r):(s={source:r,rendered:r},R8e.set(e,s));const a=b5(t,s.source);s.rendered=a,r!==a&&(e.textContent=a)}function CZe(e,t,n){if(!e.hasAttribute(t)||SZe(e))return;const r=e.getAttribute(t)??"";let s=L8e.get(e);s||(s=new Map,L8e.set(e,s));let a=s.get(t);a?r!==a.rendered&&r!==a.source&&(a.source=r):(a={source:r,rendered:r},s.set(t,a));const o=b5(n,a.source);a.rendered=o,r!==o&&e.setAttribute(t,o)}function Ple(e,t){if(e.nodeType===Node.TEXT_NODE){jZe(e,t);return}if(e.nodeType!==Node.ELEMENT_NODE)return;const n=e;for(const r of OZe)CZe(n,r,t);for(const r of Array.from(n.childNodes))Ple(r,t)}function TZt({locale:e}){return A.useEffect(()=>{if(typeof document>"u")return;const t=document.body;if(!t)return;Ple(t,e);const n=new MutationObserver(r=>{for(const s of r){if(s.type==="characterData"){jZe(s.target,e);continue}if(s.type==="attributes"){CZe(s.target,s.attributeName,e);continue}for(const a of Array.from(s.addedNodes))Ple(a,e)}});return n.observe(t,{subtree:!0,childList:!0,characterData:!0,attributes:!0,attributeFilter:[...OZe]}),()=>n.disconnect()},[e]),null}const _Zt={en:kZe,"zh-CN":IZt},NZe=A.createContext(null);function MZt(e,t){return t?e.replaceAll(/\{\{(\w+)\}\}/g,(n,r)=>{const s=t[r];return s==null?n:String(s)}):e}function RP(e,t,n){const r=_Zt[e][t]??kZe[t];return MZt(r,n)}function EZt({children:e}){var a;const n=((a=Ve({queryKey:U.health,queryFn:()=>EA.get(),retry:!1}).data)==null?void 0:a.uiLocale)??"en";A.useEffect(()=>{typeof document>"u"||(document.documentElement.lang=n)},[n]);const r=A.useCallback((o,l)=>RP(n,o,l),[n]),s=A.useMemo(()=>({locale:n,t:r}),[n,r]);return i.jsxs(NZe.Provider,{value:s,children:[i.jsx(TZt,{locale:n}),e]})}function es(){const e=A.useContext(NZe);if(!e)throw new Error("useI18n must be used within I18nProvider");return e}const U3="about:blank";function DZt(e){try{return new URL(e).hostname||e}catch{return e}}function RZt(e){const t=DZt(e.url);return e.code==="ERR_CONNECTION_REFUSED"?{summary:`${t} refused to connect.`,suggestions:["Checking the connection","Checking the proxy and firewall"]}:e.code==="ERR_NAME_NOT_RESOLVED"?{summary:`${t}'s server IP address could not be found.`,suggestions:["Checking the address","Checking the connection"]}:e.code==="ERR_TIMED_OUT"?{summary:`${t} took too long to respond.`,suggestions:["Checking the connection","Trying again later"]}:{summary:`The page at ${t} could not be loaded.`,suggestions:["Checking the address","Trying again later"]}}function LZt(e){var r;return!e||e.type==="keyUp"||!(((r=e.key)==null?void 0:r.toLowerCase())==="w"||e.code==="KeyW")||e.alt||e.shift?!1:navigator.platform.toLowerCase().includes("mac")?!!e.meta&&!e.control:!!e.control&&!e.meta}function P$(e){return`https://www.google.com/search?q=${encodeURIComponent(e)}`}function zZt(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function $Zt(e){try{return new URL(e).toString()}catch{return e.trim()}}function FZt(e){return decodeURIComponent(e.pathname).replace(/\/+$/g,"").split("/").filter(Boolean).at(-1)||"File"}function BZt(e,t){try{const n=decodeURIComponent(t.pathname);return/^file:\/\/\//i.test(e)&&t.protocol==="file:"&&t.hostname===""&&n.startsWith("/")&&!/^\/[\\/]/.test(n)}catch{return!1}}function Xv(e){const t=e.trim();if(!t||t===U3)return"New tab";try{const n=new URL(t);return n.protocol==="file:"?FZt(n):n.hostname||n.protocol.replace(":","")||"Browser"}catch{return t}}function QZt(e){const t=e.trim();if(!t||/^about:blank$/i.test(t))return U3;if(/^(https?|file):/i.test(t))try{const n=new URL(t);return n.protocol==="http:"||n.protocol==="https:"||BZt(t,n)?n.toString():P$(t)}catch{return P$(t)}return/^(localhost|\d{1,3}(?:\.\d{1,3}){3})(:\d+)?(\/.*)?$/i.test(t)?`http://${t}`:/^[a-z][a-z0-9+.-]*:/i.test(t)||/\s/.test(t)?P$(t):t.includes(".")?`https://${t}`:P$(t)}function j6(e=U3,t={newTab:!0}){return{kind:"browser",url:e,label:Xv(e),tabId:zZt(),...t.favicon?{favicon:t.favicon}:{},...t.newTab===!1?{dedupeKey:$Zt(e)}:{}}}const nte=[.25,.33,.5,.67,.75,.8,.9,1,1.1,1.25,1.5,1.75,2,2.5,3,4,5],IZe="rudder.browser.side-panel-onboarding.dismissed.v1",PZe="rudder.browser.side-panel-onboarding.session-dismissed.v1",rte="rudder:browser-side-panel-onboarding-dismissed",UZt=1500;function qZt(){if(typeof window>"u")return!0;try{if(window.localStorage.getItem(IZe)==="true")return!0}catch{}try{return window.sessionStorage.getItem(PZe)==="true"}catch{return!1}}function VZt(e){if(typeof e!="string")return null;const t=e.trim();if(!t||t.length>eR)return null;if(t.startsWith("data:image/"))return t;try{const n=new URL(t);return n.protocol==="http:"||n.protocol==="https:"?t:null}catch{return null}}function TZe({active:e,canOpenNewTab:t,surface:n,target:r,targetKey:s,onOpenBrowserSettings:a,onOpenTarget:o,onReplaceTarget:l,onCloseTarget:c,onCycleTab:d,onWebContentsIdChange:u,onRegisterShortcutController:f}){const{t:m}=es(),h=A.useRef(null),p=A.useRef(null),x=A.useRef(!1),b=A.useRef(null),y=A.useRef(null),w=A.useRef(null),k=A.useRef([]),S=A.useRef(null),j=A.useRef(null),C=A.useRef(0),I=A.useRef(null),N=A.useRef(null),M=A.useRef(null),E=A.useRef(r.url),_=A.useRef(r.url),z=A.useRef(r),T=A.useRef(l),$=A.useRef(c),B=A.useRef(d),F=A.useRef(u),W=A.useRef(e),Y=A.useRef(null),[G,V]=A.useState(null),L=A.useRef(1),[R,D]=A.useState(r.url===U3?"":r.url),[X,ee]=A.useState(r.url),[se,ne]=A.useState(r.url),[le,ie]=A.useState(!1),[re,de]=A.useState({canGoBack:!1,canGoForward:!1}),[Be,ae]=A.useState(null),[Ee,he]=A.useState(!1),[_e,Ie]=A.useState(()=>!qZt()),$e=X===U3,ce=Be?RZt(Be):null;_.current=X,z.current=r,T.current=l,$.current=c,B.current=d,F.current=u,W.current=e;const Oe=A.useCallback((Ue,Se)=>{const We=p.current;if(!x.current||!We||We.tagName.toLowerCase()!=="webview")return Se;try{return Ue(We)}catch{return Se}},[]),Ye=A.useCallback(Ue=>Oe(Se=>{var We;return((We=Se.getURL)==null?void 0:We.call(Se))??Ue},Ue),[Oe]),J=A.useCallback(()=>{de({canGoBack:Oe(Ue=>{var Se;return!!((Se=Ue.canGoBack)!=null&&Se.call(Ue))},!1),canGoForward:Oe(Ue=>{var Se;return!!((Se=Ue.canGoForward)!=null&&Se.call(Ue))},!1)})},[Oe]),qe=A.useCallback(Ue=>{Oe(We=>We.setZoomFactor?(We.setZoomFactor(Ue),!0):!1,!1)&&(L.current=Ue)},[Oe]),be=A.useCallback(Ue=>{const Se=L.current;let We=0,Te=Number.POSITIVE_INFINITY;nte.forEach((fe,je)=>{const ye=Math.abs(fe-Se);ye<Te&&(Te=ye,We=je)});const He=Math.max(0,Math.min(nte.length-1,We+Ue));qe(nte[He]??1)},[qe]),ot=A.useCallback(Ue=>{var He;if(j.current)return;N.current=null,b.current=null,y.current=null,w.current!==null&&(clearTimeout(w.current),w.current=null);const Se=Ye(_.current),We=C.current+1;if(C.current=We,j.current={baselineUrl:Se,token:We},b.current=null,!Oe(fe=>{var ye,tt,me,ze;return(Ue===-1?(ye=fe.canGoBack)==null?void 0:ye.call(fe):(tt=fe.canGoForward)==null?void 0:tt.call(fe))?(Ue===-1?(me=fe.goBack)==null||me.call(fe):(ze=fe.goForward)==null||ze.call(fe),!0):!1},!1)){j.current=null;return}(He=M.current)==null||He.call(M,We,Se)},[Ye,Oe]),ke=A.useCallback(Ue=>{var Se,We;if(e)switch(Ue){case"new_tab":t&&o(j6());return;case"focus_location":(Se=h.current)==null||Se.focus(),(We=h.current)==null||We.select();return;case"reload":$e||(N.current=null,b.current=null,j.current=null,Oe(Te=>{var He;return(He=Te.reload)==null?void 0:He.call(Te)},void 0));return;case"reload_ignoring_cache":$e||(N.current=null,b.current=null,j.current=null,Oe(Te=>{var He;return(He=Te.reloadIgnoringCache)==null?void 0:He.call(Te)},void 0));return;case"go_back":$e||ot(-1);return;case"go_forward":$e||ot(1);return;case"zoom_in":$e||be(1);return;case"zoom_out":$e||be(-1);return;case"zoom_reset":$e||qe(1)}},[e,qe,t,$e,ot,o,Oe,be]);Y.current=ke,A.useEffect(()=>(f(s,ke),()=>f(s,null)),[ke,f,s]);const Ce=A.useCallback((Ue,Se=Xv(Ue))=>{const We=z.current.url!==Ue,Te={...z.current,url:Ue,label:Se,favicon:We?void 0:z.current.favicon};_.current=Ue,z.current=Te,ee(Ue),D(Ue===U3?"":Ue),E.current=Ue,T.current(s,Te)},[s]),ue=A.useCallback((Ue,Se)=>{const We=Date.now()+1e4,Te=()=>{const He=j.current;if(!He||He.token!==Ue)return;const fe=Ye("");if(fe&&fe!==Se){j.current=null,k.current=[...new Set([...k.current.filter(je=>je!==fe),Se])].slice(-16),b.current={expectedUrl:fe,staleUrls:k.current},Ce(fe,Xv(fe)),J();return}if(Date.now()>=We){j.current=null,J();return}I.current=setTimeout(Te,50)};I.current!==null&&clearTimeout(I.current),I.current=setTimeout(Te,0)},[Ce,Ye,J]);M.current=ue,A.useEffect(()=>()=>{I.current!==null&&clearTimeout(I.current),w.current!==null&&clearTimeout(w.current)},[]),A.useEffect(()=>{const Ue=E.current!==r.url;if(E.current=r.url,_.current=r.url,z.current=r,ee(r.url),D(r.url===U3?"":r.url),Ue){const Se=Ye("");(!x.current||Se!==r.url)&&ne(r.url),ae(null),he(!1)}x.current?J():de({canGoBack:!1,canGoForward:!1})},[Ye,r.label,r.url,J]),A.useEffect(()=>{const Ue=G;if(!Ue||Ue.tagName.toLowerCase()!=="webview")return;const Se=Je=>{try{const wt=new URL(Je);return`${wt.origin}${wt.pathname==="/"?"":wt.pathname}${wt.search}${wt.hash}`}catch{return Je}},We=(Je,wt)=>wt?Se(Je)===Se(wt):!1,Te=(Je,wt=!1)=>{if(j.current)return!0;const Z=b.current,Me=y.current;return Je?We(Je,Z==null?void 0:Z.expectedUrl)||We(Je,Me==null?void 0:Me.expectedUrl)?(We(Je,N.current??void 0)&&(N.current=null),!1):We(Je,N.current??void 0)?(N.current=null,b.current=null,y.current=null,w.current!==null&&(clearTimeout(w.current),w.current=null),!1):((Z==null?void 0:Z.staleUrls)??(Me==null?void 0:Me.staleUrls)??[]).some(Pe=>We(Je,Pe))||(Z||Me)&&!wt?!0:(Z&&(b.current=null),Me&&(y.current=null),!1):!1},He=Je=>{const wt=b.current;!wt||!We(Je,wt.expectedUrl)||(b.current=null,y.current={...wt},w.current!==null&&clearTimeout(w.current),w.current=setTimeout(()=>{y.current=null,w.current=null},UZt))},fe=()=>{ie(!0),ae(null),he(!1)},je=Je=>{const wt=!("isMainFrame"in Je)||Je.isMainFrame!==!1,Z="url"in Je&&typeof Je.url=="string"?Je.url:"";wt&&Z&&(N.current=Z)},ye=Je=>{var Re,Nt;const wt=!("isMainFrame"in Je)||Je.isMainFrame!==!1,Z="url"in Je&&typeof Je.url=="string"?Je.url:"";if(!wt||!Z)return;const Me=((Re=b.current)==null?void 0:Re.expectedUrl)??((Nt=y.current)==null?void 0:Nt.expectedUrl),Pe=We(Z,Me)&&Me!==Z;!Te(Z)&&Z!==_.current&&!Pe&&Ce(Z,Xv(Z))},tt=()=>{var lt,Pe;if(ie(!1),j.current){J();return}const Je=Ye(""),wt=((lt=b.current)==null?void 0:lt.expectedUrl)??((Pe=y.current)==null?void 0:Pe.expectedUrl),Me=We(Je,wt)&&wt!==Je;Je&&He(Je),Je&&!Te(Je,!0)&&Je!==_.current&&!Me&&Ce(Je,Xv(Je)),J()},me=Je=>{var Re,Nt;const wt=Ye(""),Z="url"in Je&&typeof Je.url=="string"?Je.url:wt,Me=((Re=b.current)==null?void 0:Re.expectedUrl)??((Nt=y.current)==null?void 0:Nt.expectedUrl),Pe=We(Z,Me)&&Me!==Z;Z&&!Te(Z,Je.type==="did-navigate-in-page")&&!Pe&&Ce(Z,Xv(Z)),J()},ze=Je=>{const wt=Ye(_.current);if(Te(wt))return;const Z="title"in Je&&typeof Je.title=="string"&&Je.title.trim()?Je.title.trim():Xv(wt),Me={...z.current,url:wt,label:Z};z.current=Me,T.current(s,Me)},De=Je=>{const Z=("favicons"in Je&&Array.isArray(Je.favicons)?Je.favicons:[]).map(VZt).find(lt=>!!lt);if(!Z||Z===z.current.favicon)return;const Me={...z.current,favicon:Z};z.current=Me,T.current(s,Me)},kt=Je=>{const wt="errorDescription"in Je&&typeof Je.errorDescription=="string"?Je.errorDescription:"Could not load this page.",Z="validatedURL"in Je&&typeof Je.validatedURL=="string"&&Je.validatedURL?Je.validatedURL:_.current;(!("isMainFrame"in Je)||Je.isMainFrame!==!1)&&!Te(Z)&&wt!=="ERR_ABORTED"&&(ie(!1),ae({code:wt,url:Z}),he(!1)),J()},gt=()=>{var wt,Z;x.current=!0;const Je=(wt=Ue.getWebContentsId)==null?void 0:wt.call(Ue);typeof Je=="number"&&Number.isFinite(Je)&&((Z=F.current)==null||Z.call(F,Je)),L.current!==1&&Oe(Me=>{var lt;return(lt=Me.setZoomFactor)==null?void 0:lt.call(Me,L.current)},void 0),J()},Ke=Je=>{var Pe,Re;const wt=Je,Z=wt.input;if(Z&&Z.type!=="keyUp"&&(Z.key==="Tab"||Z.code==="Tab")&&!!Z.control&&!Z.meta&&!Z.alt&&W.current&&B.current){Je.preventDefault(),B.current(Z.shift?-1:1);return}if((Pe=_n())!=null&&Pe.onBrowserShortcut)return;if(LZt(wt.input)){Je.preventDefault(),$.current(z.current);return}if(!wt.input||!W.current)return;const lt=TUe(wt.input,{isMac:navigator.platform.toLowerCase().includes("mac")});lt&&(Je.preventDefault(),(Re=Y.current)==null||Re.call(Y,lt))};return Ue.addEventListener("dom-ready",gt),Ue.addEventListener("before-input-event",Ke),Ue.addEventListener("will-navigate",je),Ue.addEventListener("did-start-loading",fe),Ue.addEventListener("did-start-navigation",ye),Ue.addEventListener("did-stop-loading",tt),Ue.addEventListener("did-navigate",me),Ue.addEventListener("did-navigate-in-page",me),Ue.addEventListener("page-title-updated",ze),Ue.addEventListener("page-favicon-updated",De),Ue.addEventListener("did-fail-load",kt),J(),()=>{Ue.removeEventListener("dom-ready",gt),Ue.removeEventListener("before-input-event",Ke),Ue.removeEventListener("will-navigate",je),Ue.removeEventListener("did-start-loading",fe),Ue.removeEventListener("did-start-navigation",ye),Ue.removeEventListener("did-stop-loading",tt),Ue.removeEventListener("did-navigate",me),Ue.removeEventListener("did-navigate-in-page",me),Ue.removeEventListener("page-title-updated",ze),Ue.removeEventListener("page-favicon-updated",De),Ue.removeEventListener("did-fail-load",kt)}},[Ce,Ye,Oe,s,J,G]);const mt=A.useCallback(Ue=>{p.current=Ue,x.current=!1,V(Ue),Ue||de({canGoBack:!1,canGoForward:!1})},[]);A.useEffect(()=>()=>{var Ue;(Ue=F.current)==null||Ue.call(F,null)},[]),A.useEffect(()=>{const Ue=()=>Ie(!1);return window.addEventListener(rte,Ue),()=>{window.removeEventListener(rte,Ue)}},[]);const ut=()=>{Ie(!1);try{window.localStorage.setItem(IZe,"true")}catch{}try{window.sessionStorage.setItem(PZe,"true")}catch{}window.dispatchEvent(new Event(rte))},ge=A.useCallback(Ue=>{const Se=QZt(Ue);N.current=null,y.current=null,w.current!==null&&(clearTimeout(w.current),w.current=null),C.current+=1,j.current=null,k.current=k.current.filter(Te=>Te!==Se),_.current&&_.current!==Se&&(k.current=[...new Set([...k.current,_.current])].slice(-16)),b.current={expectedUrl:Se,staleUrls:k.current},ae(null),he(!1),Oe(Te=>{if(!Te.loadURL)return!1;const He=()=>Te.loadURL(Se),fe=S.current,ye=(fe?fe.catch(()=>{}).then(He):Promise.resolve(He())).catch(()=>{});return S.current=ye,ye.then(()=>{S.current===ye&&(S.current=null)}),!0},!1)||ne(Se),Ce(Se,Xv(Se))},[Ce,Oe]),Le=A.useCallback(()=>{N.current=null,b.current=null,y.current=null,w.current!==null&&(clearTimeout(w.current),w.current=null),j.current=null,he(!1),Oe(Ue=>{var Se;(Se=Ue.reload)==null||Se.call(Ue)},void 0)},[Oe]),rt=Ue=>{Ue.preventDefault();const We=new FormData(Ue.currentTarget).get("browser-url");ge(typeof We=="string"?We:R)},At=()=>{var Se;if($e)return;const Ue=_n();if(Ue){((Se=Ue.forceOpenExternal)==null?void 0:Se.call(Ue,X))??Ue.openExternal(X);return}window.open(X,"_blank","noopener,noreferrer")};return i.jsxs("div",{className:"flex min-h-full flex-col bg-[color:var(--surface-elevated)]","data-testid":e?"chat-side-panel-browser-view":"chat-side-panel-browser-view-hidden","data-browser-tab-id":r.tabId,"data-active":e?"true":"false",children:[i.jsxs("div",{className:"flex shrink-0 items-center gap-1 border-b border-[color:var(--border-soft)] bg-[color:var(--surface-elevated)] px-2 py-2","data-testid":"chat-side-panel-browser-toolbar",children:[i.jsx(oe,{type:"button",variant:"ghost",size:"icon-xs","aria-label":"Back",disabled:!re.canGoBack,onClick:()=>ot(-1),children:i.jsx(n1,{className:"h-3.5 w-3.5"})}),i.jsx(oe,{type:"button",variant:"ghost",size:"icon-xs","aria-label":"Forward",disabled:!re.canGoForward,onClick:()=>ot(1),children:i.jsx(b0,{className:"h-3.5 w-3.5"})}),i.jsx(oe,{type:"button",variant:"ghost",size:"icon-xs","aria-label":"Reload",disabled:$e,onClick:Le,children:i.jsx(A0,{className:q("h-3.5 w-3.5",le&&"animate-spin")})}),i.jsx("form",{className:"min-w-0 flex-1",onSubmit:rt,children:i.jsx(nr,{ref:h,"aria-label":"Browser URL",name:"browser-url",value:R,onChange:Ue=>D(Ue.currentTarget.value),placeholder:"Enter a URL",className:"h-8 rounded-[var(--radius-md)] bg-[color:var(--surface-inset)] font-mono text-xs"})}),i.jsx(oe,{type:"button",variant:"ghost",size:"icon-xs","aria-label":"Open new browser tab",title:t?"Open new browser tab":"Browser tab limit reached",disabled:!t,onClick:()=>o(j6()),children:i.jsx(ps,{className:"h-3.5 w-3.5"})}),i.jsx(oe,{type:"button",variant:"ghost",size:"icon-xs","aria-label":"Open browser page externally",disabled:$e,onClick:At,children:i.jsx(Ki,{className:"h-3.5 w-3.5"})})]}),i.jsxs("div",{className:"relative flex min-h-0 flex-1 flex-col bg-[color:var(--surface-inset)]","data-testid":"chat-side-panel-browser-content",children:[e&&n==="side_panel"&&_e?i.jsx(wZe,{testId:"browser-side-panel-onboarding",className:"absolute right-3 top-3 z-20 w-[min(24rem,calc(100%-1.5rem))] shadow-[var(--shadow-lg)]",icon:i.jsx(BAe,{"aria-hidden":"true"}),title:m("browser.onboarding.title"),description:m("browser.onboarding.description"),stackActions:!0,actions:i.jsxs(i.Fragment,{children:[a?i.jsx(oe,{type:"button",variant:"outline",size:"sm",onClick:()=>{ut(),a()},children:m("browser.onboarding.settings")}):null,i.jsx(oe,{type:"button",size:"sm",onClick:ut,children:m("browser.onboarding.dismiss")})]})}):null,$e?i.jsx("div",{className:"flex min-h-[44vh] flex-1 items-center justify-center px-6 text-center","data-testid":"chat-side-panel-browser-start",children:i.jsxs("div",{className:"max-w-[18rem]",children:[i.jsx(jA,{className:"mx-auto h-12 w-12 text-muted-foreground"}),i.jsx("h3",{className:"mt-4 text-base font-semibold text-foreground",children:"Start browsing"}),i.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Enter a URL to open a page."})]})}):i.jsxs("div",{className:"relative flex min-h-[52vh] flex-1",children:[A.createElement("webview",{ref:mt,src:se,className:q("min-h-[52vh] flex-1 bg-[color:var(--surface-elevated)]",Be&&"invisible"),"data-testid":e?"chat-side-panel-browser-webview":"chat-side-panel-browser-webview-hidden","data-browser-tab-id":r.tabId,"data-active":e?"true":"false",allowpopups:"true"}),Be?i.jsx("div",{role:"alert","data-testid":"chat-side-panel-browser-error",className:"absolute inset-0 flex overflow-y-auto bg-[color:var(--surface-elevated)] px-8 py-10",children:i.jsxs("div",{className:"m-auto w-full max-w-[32rem]",children:[i.jsx(U3t,{className:"h-12 w-12 text-muted-foreground","aria-hidden":"true"}),i.jsx("h3",{className:"mt-6 text-xl font-semibold text-foreground",children:"This site can't be reached"}),i.jsx("p",{className:"mt-4 text-sm text-muted-foreground",children:ce==null?void 0:ce.summary}),i.jsxs("div",{className:"mt-5 text-sm text-muted-foreground",children:[i.jsx("p",{children:"Try:"}),i.jsx("ul",{className:"mt-2 list-disc space-y-1 pl-6",children:ce==null?void 0:ce.suggestions.map(Ue=>i.jsx("li",{children:Ue},Ue))})]}),i.jsx("p",{className:"mt-5 font-mono text-xs text-muted-foreground",children:Be.code}),Ee?i.jsx("p",{className:"mt-4 break-all rounded-[var(--radius-md)] border border-[color:var(--border-soft)] bg-[color:var(--surface-inset)] px-3 py-2 font-mono text-xs text-muted-foreground",children:Be.url}):null,i.jsxs("div",{className:"mt-7 flex items-center justify-between gap-3",children:[i.jsx(oe,{type:"button",variant:"outline",size:"sm","aria-expanded":Ee,onClick:()=>he(Ue=>!Ue),children:"Details"}),i.jsxs(oe,{type:"button",size:"sm",onClick:Le,children:[i.jsx(A0,{className:"h-3.5 w-3.5"}),"Reload"]})]})]})}):null]})]})]})}const WZt=A.lazy(async()=>({default:(await on(async()=>{const{AutomationDetail:e}=await Promise.resolve().then(()=>BVn);return{AutomationDetail:e}},void 0)).AutomationDetail})),HZt=A.lazy(async()=>({default:(await on(async()=>{const{LibraryLiveSurface:e}=await import("./LibraryLiveSurface-Bs8V_pMU.js");return{LibraryLiveSurface:e}},[])).LibraryLiveSurface})),Mge=A.createContext(null);function $q(e){var n;const t=((n=e.viewInstanceId)==null?void 0:n.trim())||(e.kind==="browser"?e.tabId.trim():"");if(!t)throw new Error(`${e.kind} live surface requires a viewInstanceId`);return t}function uM(e,t){return JSON.stringify([e.trim(),t.kind,$q(t)])}function _Ze(e){try{const t=JSON.parse(e);return Array.isArray(t)&&typeof t[0]=="string"?t[0]:""}catch{return""}}function ste(e,t){return e.kind===t.kind&&$q(e)===$q(t)}function Tle(e,t){if(Object.is(e,t))return!0;if(e===null||t===null||typeof e!="object"||typeof t!="object")return!1;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((o,l)=>Tle(o,t[l]));const n=e,r=t,s=Object.keys(n).filter(o=>n[o]!==void 0),a=Object.keys(r).filter(o=>r[o]!==void 0);return s.length===a.length&&s.every(o=>Object.hasOwn(r,o)&&Tle(n[o],r[o]))}function MZe(e){return e.startsWith("main:")?"workbench":"side_panel"}function _le(e){if(!EZe(e))return!1;const t=e.element.getBoundingClientRect();return t.width>0&&t.height>0}function EZe(e){return!!(e!=null&&e.active&&e.element.isConnected)}function KZt({children:e}){const t=A.useRef(new Map),n=A.useRef(new Map),[r,s]=A.useState(0),a=A.useCallback(()=>{s(_=>_+1)},[]),o=A.useCallback(_=>{const z=t.current.get(_.runtimeId);if(z&&!ste(z.target,_.target))return()=>{};const T=z??{interactionLocked:!1,leaseOwnerId:null,owners:new Map,renderSurface:_.renderSurface??null,runtimeId:_.runtimeId,shortcutController:null,target:_.target,webContentsId:null};return T.owners.set(_.ownerId,_),_.renderSurface&&(T.renderSurface=_.renderSurface),t.current.set(_.runtimeId,T),a(),()=>{const $=t.current.get(_.runtimeId);$&&($.owners.delete(_.ownerId),$.leaseOwnerId===_.ownerId&&($.leaseOwnerId=null),a())}},[a]),l=A.useCallback(_=>{const z=t.current.get(_.runtimeId);if(!z||!ste(z.target,_.target))return;const T=z.owners.get(_.ownerId);if(!T)return;const $=!Tle(T.target,_.target);(T.active!==_.active||T.callbacks!==_.callbacks||T.element!==_.element||T.hostId!==_.hostId||T.renderSurface!==_.renderSurface||$)&&(z.owners.set(_.ownerId,_),$&&z.leaseOwnerId===_.ownerId&&!z.interactionLocked&&(z.target=_.target),_.renderSurface&&(z.renderSurface=_.renderSurface),a())},[a]),c=A.useCallback((_,z)=>{const T=t.current.get(_),$=T==null?void 0:T.owners.get(z);return!T||!_le($)?!1:(T.leaseOwnerId===z||(T.leaseOwnerId=z,a()),!0)},[a]),d=A.useCallback((_,z)=>{const T=t.current.get(_),$=T==null?void 0:T.owners.get(z);return!T||!EZe($)||T.leaseOwnerId&&T.leaseOwnerId!==z?!1:(T.leaseOwnerId===z||(T.leaseOwnerId=z,a()),!0)},[a]),u=A.useCallback(async(_,z,T=5e3)=>{var B;const $=Date.now();for(;Date.now()-$<=T;){const F=(B=t.current.get(_))==null?void 0:B.owners.get(z);if(_le(F))return!0;await new Promise(W=>{window.setTimeout(W,16)})}return!1},[]),f=A.useCallback((_,z)=>{const T=t.current.get(_);!T||T.interactionLocked===z||(T.interactionLocked=z,a())},[a]),m=A.useCallback((_,z)=>{const T=t.current.get(_);return!T||!ste(T.target,z)?!1:(T.target=z,a(),!0)},[a]),h=A.useCallback(_=>{const z=t.current.get(_);z&&(z.webContentsId!==null&&n.current.delete(z.webContentsId),t.current.delete(_),a())},[a]),p=A.useCallback((_,z)=>{const T=t.current.get(_);!T||T.webContentsId===z||(T.webContentsId!==null&&n.current.delete(T.webContentsId),T.webContentsId=z,z!==null&&n.current.set(z,_))},[]),x=A.useCallback(_=>{const z=n.current.get(_),T=z?t.current.get(z):null,$=T!=null&&T.leaseOwnerId?T.owners.get(T.leaseOwnerId):null;return!T||!$?null:{hostId:$.hostId,ownerId:$.ownerId,runtimeId:T.runtimeId,surface:MZe($.ownerId),targetKind:T.target.kind}},[]),b=A.useCallback((_,z)=>{const T=n.current.get(_),$=T?t.current.get(T):null,B=$!=null&&$.leaseOwnerId?$.owners.get($.leaseOwnerId):null;return B!=null&&B.callbacks.onOpenTarget?(B.callbacks.onOpenTarget(z),!0):!1},[]),y=A.useCallback(_=>{const z=t.current.get(_),T=z!=null&&z.leaseOwnerId?z.owners.get(z.leaseOwnerId):null;return!z||!(T!=null&&T.callbacks.onCloseTarget)?!1:(T.callbacks.onCloseTarget(z.target),!0)},[]),w=A.useCallback(_=>{const z=n.current.get(_);return z?y(z):!1},[y]),k=A.useCallback((_,z)=>{const T=t.current.get(_);!T||T.target.kind!=="browser"||(T.shortcutController=z)},[]),S=A.useCallback((_,z)=>{const T=t.current.get(_);return!T||T.target.kind!=="browser"||!T.leaseOwnerId||!T.shortcutController?!1:(T.shortcutController(z),!0)},[]),j=A.useCallback((_,z)=>{const T=n.current.get(_);return T?S(T,z):!1},[S]),C=A.useCallback(_=>Array.from(t.current.values()).filter(z=>z.target.kind==="browser"&&_Ze(z.runtimeId)===_).length,[]),I=A.useCallback(_=>{var z;return((z=t.current.get(_))==null?void 0:z.target)??null},[]),N=A.useCallback(_=>t.current.has(_),[]),M=A.useCallback(()=>Array.from(t.current.values()),[]),E=A.useMemo(()=>({autoClaimSurface:d,claimSurface:c,closeTargetForGuest:w,closeTargetForRuntime:y,dispatchBrowserShortcutForGuest:j,dispatchBrowserShortcutForRuntime:S,disposeSurface:h,getGuestOwner:x,getLiveBrowserCount:C,getRuntimeTarget:I,hasSurface:N,listRecords:M,openTargetForGuest:b,registerBrowserShortcutController:k,registerOwner:o,registerWebContentsId:p,revision:r,setInteractionLocked:f,updateOwner:l,updateTarget:m,waitForOwner:u}),[d,c,w,y,j,S,h,x,C,I,N,M,b,k,o,p,r,f,l,m,u]);return i.jsx(Mge.Provider,{value:E,children:e})}function yR(){const e=A.useContext(Mge);if(!e)throw new Error("useLiveSurfaceRuntime must be used inside LiveSurfaceRuntimeProvider");return e}function Ege(){return A.useContext(Mge)}function DZe({active:e,autoClaim:t=!0,callbacks:n={},hostId:r,ownerId:s,renderSurface:a,runtimeId:o,target:l,...c}){const{autoClaimSurface:d,registerOwner:u,updateOwner:f}=yR(),m=A.useRef(null),h=A.useRef(n);h.current=n;const p=A.useMemo(()=>({get annotationConversationId(){return h.current.annotationConversationId},get canOpenNewTab(){return h.current.canOpenNewTab},get savedViewId(){return h.current.savedViewId},onCloseTarget:x=>{var b,y;return(y=(b=h.current).onCloseTarget)==null?void 0:y.call(b,x)},onCycleTab:x=>{var b,y;return(y=(b=h.current).onCycleTab)==null?void 0:y.call(b,x)},onLocalAppTitleChange:x=>{var b,y;return(y=(b=h.current).onLocalAppTitleChange)==null?void 0:y.call(b,x)},onOpenBrowserSettings:()=>{var x,b;return(b=(x=h.current).onOpenBrowserSettings)==null?void 0:b.call(x)},onOpenTarget:x=>{var b,y;return(y=(b=h.current).onOpenTarget)==null?void 0:y.call(b,x)},onRegisterShortcutController:(x,b)=>{var y,w;return(w=(y=h.current).onRegisterShortcutController)==null?void 0:w.call(y,x,b)},onReplaceTarget:x=>{var b,y;return(y=(b=h.current).onReplaceTarget)==null?void 0:y.call(b,x)}}),[]);return A.useLayoutEffect(()=>{const x=m.current;if(x)return u({active:e,callbacks:p,element:x,hostId:r,ownerId:s,renderSurface:a,runtimeId:o,target:l})},[r,s,u,o]),A.useLayoutEffect(()=>{const x=m.current;if(!x)return;f({active:e,callbacks:p,element:x,hostId:r,ownerId:s,renderSurface:a,runtimeId:o,target:l}),e&&t&&d(o,s)},[e,t,d,r,s,a,o,p,l,f]),i.jsx("div",{...c,ref:m,"data-owner-id":s})}function ZZt({record:e,owner:t,visible:n}){var f;const r=yR(),s=e.target,a=t==null?void 0:t.callbacks,o=t?MZe(t.ownerId):"side_panel",l=m=>{var h;(h=a==null?void 0:a.onCloseTarget)==null||h.call(a,m)},c=m=>{var h;(h=a==null?void 0:a.onOpenTarget)==null||h.call(a,m)},d=m=>{var h;(m.kind==="automation"||m.kind==="browser"||m.kind==="library_directory"||m.kind==="library_document"||m.kind==="library_entry"||m.kind==="library_file"||m.kind==="local_app")&&r.updateTarget(e.runtimeId,m),e.interactionLocked||(h=a==null?void 0:a.onReplaceTarget)==null||h.call(a,m)},u=(f=e.renderSurface)==null?void 0:f.call(e,{active:n,closeTarget:l,openTarget:c,replaceTarget:d,surface:o,target:s});return s.kind==="browser"?i.jsx(TZe,{active:n,canOpenNewTab:(a==null?void 0:a.canOpenNewTab)??!1,surface:o,target:s,targetKey:fs(s),onCloseTarget:l,onCycleTab:a==null?void 0:a.onCycleTab,onOpenBrowserSettings:a==null?void 0:a.onOpenBrowserSettings,onOpenTarget:c,onRegisterShortcutController:(m,h)=>{var p;r.registerBrowserShortcutController(e.runtimeId,h),(p=a==null?void 0:a.onRegisterShortcutController)==null||p.call(a,m,h)},onReplaceTarget:(m,h)=>d(h),onWebContentsIdChange:m=>{r.registerWebContentsId(e.runtimeId,m)}}):s.kind==="local_app"?i.jsx(vZe,{active:n,savedViewId:a==null?void 0:a.savedViewId,target:s,onTitleChange:a==null?void 0:a.onLocalAppTitleChange}):u!==void 0?i.jsx(i.Fragment,{children:u}):s.kind==="automation"?i.jsx(A.Suspense,{fallback:i.jsx("div",{className:"h-full"}),children:i.jsx(WZt,{automationId:s.automationId,onClose:()=>l(s),surface:o})}):i.jsx(A.Suspense,{fallback:i.jsx("div",{className:"h-full"}),children:i.jsx(HZt,{active:n,annotationConversationId:a==null?void 0:a.annotationConversationId,organizationId:_Ze(e.runtimeId),onOpenTarget:c,surface:o,target:s})})}function XZt(){const e=yR(),t=e.listRecords(),[,n]=A.useState(0);return A.useEffect(()=>{const r=()=>n(a=>a+1);window.addEventListener("resize",r),window.addEventListener("scroll",r,!0);const s=typeof ResizeObserver>"u"?null:new ResizeObserver(r);for(const a of e.listRecords())for(const o of a.owners.values())s==null||s.observe(o.element);return()=>{window.removeEventListener("resize",r),window.removeEventListener("scroll",r,!0),s==null||s.disconnect()}},[e]),i.jsx("div",{className:"pointer-events-none fixed inset-0","data-testid":"live-surface-runtime-layer","aria-label":"Live workspace surfaces",children:t.map(r=>{const s=r.leaseOwnerId?r.owners.get(r.leaseOwnerId)??null:null,a=_le(s),o=a?s.element.getBoundingClientRect():null,l=!a||r.interactionLocked;return i.jsx("div",{"data-testid":"live-surface-runtime-host","data-host-id":s==null?void 0:s.hostId,"data-owner-id":s==null?void 0:s.ownerId,"data-runtime-id":r.runtimeId,"data-target-kind":r.target.kind,"data-view-instance-id":$q(r.target),"aria-hidden":!a,hidden:!a,inert:l?!0:void 0,className:`fixed flex min-h-0 flex-col overflow-hidden bg-[color:var(--surface-panel)] ${s!=null&&s.ownerId.startsWith("side:")?"rounded-[var(--desktop-workspace-radius)]":s!=null&&s.ownerId.startsWith("main:")?r.target.kind==="browser"?"rounded-[var(--desktop-workspace-radius)]":"rounded-b-[var(--desktop-workspace-radius)]":""}`,style:{height:o?`${o.height}px`:"0px",left:o?`${o.left}px`:"0px",pointerEvents:l?"none":"auto",top:o?`${o.top}px`:"0px",width:o?`${o.width}px`:"0px",zIndex:s!=null&&s.ownerId.startsWith("side:")?70:40},children:i.jsx(ZZt,{record:r,owner:s,visible:a&&!r.interactionLocked})},r.runtimeId)})})}const vS=[{actionId:"commandPalette.open",label:"Open command palette",description:"Search and jump across Rudder.",scope:"Global",defaultBindings:[{key:"k",code:"KeyK",metaKey:!0},{key:"k",code:"KeyK",ctrlKey:!0}],defaultBindingsByPlatform:{mac:[{key:"k",code:"KeyK",metaKey:!0}],nonMac:[{key:"k",code:"KeyK",ctrlKey:!0}]},configurable:!0,disableable:!0},{actionId:"settings.open",label:"Open settings",description:"Open System Settings.",scope:"Global",defaultBindings:[{key:",",metaKey:!0},{key:",",ctrlKey:!0}],defaultBindingsByPlatform:{mac:[{key:",",metaKey:!0}],nonMac:[{key:",",ctrlKey:!0}]},configurable:!0,disableable:!0},{actionId:"chat.create",label:"New chat",description:"Open the new chat composer.",scope:"Global",defaultBindings:[{key:"s",code:"KeyS",metaKey:!0,altKey:!0},{key:"s",code:"KeyS",ctrlKey:!0,altKey:!0}],defaultBindingsByPlatform:{mac:[{key:"s",code:"KeyS",metaKey:!0,altKey:!0}],nonMac:[{key:"s",code:"KeyS",ctrlKey:!0,altKey:!0}]},configurable:!0,disableable:!0},{actionId:"issue.create",label:"Create issue",description:"Open the new issue dialog.",scope:"Global",defaultBindings:[{key:"n",code:"KeyN",metaKey:!0},{key:"n",code:"KeyN",ctrlKey:!0}],defaultBindingsByPlatform:{mac:[{key:"n",code:"KeyN",metaKey:!0}],nonMac:[{key:"n",code:"KeyN",ctrlKey:!0}]},configurable:!0,disableable:!0},{actionId:"sidebar.toggle",label:"Toggle sidebar",description:"Show or hide the workspace sidebar.",scope:"Global",defaultBindings:[{key:"["}],configurable:!0,disableable:!0},{actionId:"panel.toggle",label:"Toggle panel",description:"Show or hide the context panel.",scope:"Global",defaultBindings:[{key:"]"}],configurable:!0,disableable:!0},{actionId:"system.escapeBack",label:"Navigate back / close detail",description:"System Escape behavior is read-only in this version.",scope:"System",defaultBindings:[{key:"Escape"}],configurable:!1,disableable:!1}],GZt=new Set(vS.filter(e=>e.configurable).map(e=>e.actionId)),YZt=new Set(["Alt","Control","Meta","Shift"]),z8e=new Set(["meta+n","meta+shift+o"]);function vR(){var n,r,s;if(typeof navigator>"u")return"nonMac";const e=navigator,t=((r=(n=e.userAgentData)==null?void 0:n.platform)==null?void 0:r.trim())||((s=e.platform)==null?void 0:s.trim())||"";return/mac|iphone|ipad|ipod/i.test(t)?"mac":"nonMac"}function RZe(e,t=vR()){var n;return(((n=e.defaultBindingsByPlatform)==null?void 0:n[t])??e.defaultBindings).map(y8)}function LZe(e){return e.length===1?e.toLowerCase():e}function y8(e){return{key:LZe(e.key.trim()),...e.code?{code:e.code.trim()}:{},...e.metaKey?{metaKey:!0}:{},...e.ctrlKey?{ctrlKey:!0}:{},...e.altKey?{altKey:!0}:{},...e.shiftKey?{shiftKey:!0}:{}}}function Mle(e){const t=y8(e);return[t.metaKey?"meta":"",t.ctrlKey?"ctrl":"",t.altKey?"alt":"",t.shiftKey?"shift":"",t.key].filter(Boolean).join("+")}function zZe(e){if(!(e instanceof HTMLElement)||JZt(e))return!1;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable||!!e.closest('[contenteditable="true"], [contenteditable="plaintext-only"]')}function JZt(e){let t=e;for(;t;){if(t.hidden||t.getAttribute("aria-hidden")==="true")return!0;const n=window.getComputedStyle(t);if(n.display==="none"||n.visibility==="hidden"||n.visibility==="collapse")return!0;t=t.parentElement}return!1}function eXt(e){return YZt.has(e.key)?null:y8({key:e.key,code:e.code||void 0,metaKey:e.metaKey,ctrlKey:e.ctrlKey,altKey:e.altKey,shiftKey:e.shiftKey})}function tXt(e,t){const n=y8(t);return(n.code&&e.code?e.code===n.code:LZe(e.key)===n.key)&&e.metaKey===!!n.metaKey&&e.ctrlKey===!!n.ctrlKey&&e.altKey===!!n.altKey&&e.shiftKey===!!n.shiftKey}function Dge(e,t=vR()){const n={};for(const r of vS)GZt.has(r.actionId)&&(n[r.actionId]=RZe(r,t));for(const r of(e==null?void 0:e.shortcuts)??[]){const s=vS.find(a=>a.actionId===r.actionId);if(s!=null&&s.configurable){if(r.disabled===!0){n[r.actionId]=[];continue}if(r.bindings&&r.bindings.length>0){const a=r.bindings.map(y8);if(nXt(r.actionId,a))continue;n[r.actionId]=a}}}return n}function nXt(e,t){return e!=="chat.create"||t.length!==z8e.size?!1:t.every(n=>z8e.has(Mle(n)))}function hO(e,t,n,r){return n===void 0?!1:(Dge(n,r)[t]??[]).some(a=>tXt(e,a))}function $8e(e,t=vR()){const n=y8(e),r=[];return n.ctrlKey&&r.push(t==="mac"?"⌃":"Ctrl"),n.altKey&&r.push(t==="mac"?"⌥":"Alt"),n.shiftKey&&r.push(t==="mac"?"⇧":"Shift"),n.metaKey&&r.push(t==="mac"?"⌘":"Meta"),r.push(rXt(n.key)),t==="mac"?r.join(""):r.join("+")}function rXt(e){return e===" "?"Space":e==="Escape"?"Esc":e.length===1?e.toUpperCase():e}function sXt(e){const t=y8(e),n=t.key.toLowerCase();return t.metaKey||t.ctrlKey?["l","r","w","q"].includes(n):!1}function iXt(e,t,n,r){const s=Mle(t),a=Dge(n,r);for(const[o,l]of Object.entries(a))if(o!==e&&l.some(c=>Mle(c)===s))return o;return null}function T$(e,t,n){const r=e.shortcuts.filter(s=>s.actionId!==t);return n&&r.push({actionId:t,...n}),{shortcuts:r}}const Rge=A.createContext(null),LP="global",NT=8;function g4(e){return(e==null?void 0:e.trim())||LP}function aXt(e){const t=hZt(e);return t||(e.kind==="issue_proposal"?`/messenger/chat/${e.conversationId}?messageId=${encodeURIComponent(e.messageId)}`:e.kind==="subagents"?`/messenger/chat/${e.conversationId}`:e.kind==="subagent"?e.conversationId?`/messenger/chat/${e.conversationId}${e.sourceMessageId?`?messageId=${encodeURIComponent(e.sourceMessageId)}`:""}`:"/messenger/chat":e.kind==="goal_chat"?e.conversationId?`/messenger/chat/${e.conversationId}`:`/goals/${e.goalId}`:e.kind==="local_file"?"/library":e.kind==="local_apps"||e.kind==="local_app"?"/apps":"/messenger/chat")}function ite(e){if(typeof window>"u"||window.innerWidth>=768||e.kind==="goal_chat"||e.kind==="run_debug_chat"||e.kind==="local_file")return!1;const t=aXt(e);if(/^https?:\/\//i.test(t)&&!t.startsWith(window.location.origin))return window.location.assign(t),!0;const n=Zf(window.location.pathname),r=rc(t,n);return window.history.pushState({},"",r),window.dispatchEvent(new PopStateEvent("popstate")),!0}function xx(){return{activeKey:null,hasPanelState:!1,open:!1,tabs:[]}}function _$(e){return!!(e&&(e.hasPanelState||e.tabs.length>0||e.activeKey!==null))}function F8e(e){return e instanceof Element&&!!e.closest("[data-testid='messenger-main-workbench'],[data-testid='live-surface-runtime-host'][data-owner-id^='main:']")}function oXt(){var e,t;return((t=(e=globalThis.crypto)==null?void 0:e.randomUUID)==null?void 0:t.call(e))??`view-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function ate(e,t,n){if(!jm(t))return t;if(t.kind==="browser")return{...t,viewInstanceId:t.viewInstanceId??t.tabId};if(!n&&t.viewInstanceId)return t;if(!n){const r=Ile(t),s=e.find(a=>jm(a)&&Ile(a)===r);if(s&&s.kind!=="browser"&&"viewInstanceId"in s&&s.viewInstanceId)return{...t,viewInstanceId:s.viewInstanceId}}return{...t,viewInstanceId:oXt()}}function B8e(e,t){return{...e,tabId:t.tabId,viewInstanceId:t.viewInstanceId??t.tabId,savedViewRecovery:t.savedViewRecovery??e.savedViewRecovery}}function ote(e,t,n,r=!0){const s=fs(n),a=n.kind==="browser"&&n.dedupeKey?e.find(d=>d.kind==="browser"&&d.dedupeKey===n.dedupeKey):void 0;if(n.kind==="browser"&&(a==null?void 0:a.kind)==="browser"){const d=fs(a),u=B8e(n,a);return{activeKey:d,tabs:e.map(f=>fs(f)===d?u:f),openResult:{admitted:!0}}}const o=e.find(d=>fs(d)===s);if(o){const d=n.kind==="browser"&&o.kind==="browser"?B8e(n,o):n;return{activeKey:s,tabs:e.map(u=>fs(u)===s?d:u),openResult:{admitted:!0}}}const l=[...e,n];if(n.kind!=="browser")return{activeKey:s,tabs:l,openResult:{admitted:!0}};const c=e.filter(d=>d.kind==="browser").length;return r&&c<NT?{activeKey:s,tabs:l,openResult:{admitted:!0}}:{activeKey:t,tabs:e,openResult:{admitted:!1,reason:"browser_capacity"}}}function Ele(e){var t;return((t=e.viewInstanceId)==null?void 0:t.trim())||e.tabId.trim()}function lte(e){const t=new Set;for(const n of Object.values(e))for(const r of n.tabs)r.kind==="browser"&&t.add(Ele(r));return t}function lXt(e,t,n){const r=e.activeKey?e.tabs.findIndex(l=>fs(l)===e.activeKey):-1,s=e.tabs.filter(l=>l.kind!=="browser"||(n==null?void 0:n(t,l))==="preserve");if(s.length===e.tabs.length)return e;const a=e.activeKey!==null&&s.some(l=>fs(l)===e.activeKey),o=s[Math.min(Math.max(r,0),s.length-1)]??s.at(-1)??null;return{...e,activeKey:e.activeKey===null?null:a?e.activeKey:o?fs(o):null,tabs:s}}function cXt({children:e}){const t=A.useRef({[LP]:xx()}),n=A.useRef({[LP]:{}}),r=A.useRef(LP),[s,a]=A.useState(LP),[o,l]=A.useState(()=>xx()),[c,d]=A.useState(null),[u,f]=A.useState(!1),m=A.useRef(u);m.current=u;const h=A.useRef(null),p=A.useRef(null),x=A.useRef(new Set),b=A.useCallback((ne,le)=>{const ie=t.current[ne]??xx(),re=le(ie);if(re!==ie){const de=new Map(ie.tabs.map(Ee=>[fs(Ee),Ee])),Be=n.current[ne]??{},ae={...Be};for(const Ee of re.tabs){const he=fs(Ee),_e=de.get(he),Ie=Be[he]??0;ae[he]=_e?_e!==Ee?Ie+1:Ie:Object.hasOwn(Be,he)?Ie+1:0}n.current={...n.current,[ne]:ae}}return t.current={...t.current,[ne]:re},ne===r.current&&l(re),re},[]),y=A.useCallback(()=>{if(!m.current)for(const ne of x.current)ne()},[]),w=A.useCallback(ne=>(x.current.add(ne),()=>{x.current.delete(ne)}),[]),k=A.useCallback(ne=>{const le=g4(ne);if(r.current===le)return;const ie=t.current[le]??xx();!m.current&&_$(ie)&&ie.open&&y(),r.current=le,l(ie),f(_$(ie)&&ie.open),a(re=>re===le?re:le)},[y]),S=A.useCallback((ne,le)=>{if(ite(ne))return{admitted:!0};y();let ie={admitted:!0};return b(s,re=>{const de=lte(t.current),Be=ne.kind!=="browser"||de.has(Ele(ne))||(le==null?void 0:le.allowNewBrowserGuest)!==!1&&de.size<NT,ae=ote(re.tabs,re.activeKey,ate(re.tabs,ne,!1),Be);return ie=ae.openResult,{activeKey:ae.activeKey,hasPanelState:!0,open:!0,tabs:ae.tabs}}),f(!0),ie},[s,y,b]),j=A.useCallback((ne,le)=>{if(ite(ne))return{admitted:!0};y();let ie={admitted:!0};return b(s,re=>{const de=lte(t.current),Be=ne.kind!=="browser"||(le==null?void 0:le.allowNewBrowserGuest)!==!1&&de.size<NT,ae=ote(re.tabs,re.activeKey,ate(re.tabs,ne,!0),Be);return ie=ae.openResult,{activeKey:ae.activeKey,hasPanelState:!0,open:!0,tabs:ae.tabs}}),f(!0),ie},[s,y,b]),C=A.useCallback((ne,le,ie)=>{if(ite(le))return{admitted:!0};y();const re=g4(ne);let de={admitted:!0};const Be=b(re,ae=>{const Ee=lte(t.current),he=le.kind!=="browser"||Ee.has(Ele(le))||(ie==null?void 0:ie.allowNewBrowserGuest)!==!1&&Ee.size<NT,_e=ote(ae.tabs,ae.activeKey,ate(ae.tabs,le,!1),he);return de=_e.openResult,{activeKey:_e.activeKey,hasPanelState:!0,open:!0,tabs:_e.tabs}});return re===r.current&&(l(Be),f(!0)),de},[y,b]),I=A.useCallback(()=>{y(),b(s,ne=>({...ne,hasPanelState:!0,open:!0})),f(!0)},[s,y,b]),N=A.useCallback(ne=>{y();const le=g4(ne),re={...t.current[le]??xx(),hasPanelState:!0,open:!0};t.current={...t.current,[le]:re},r.current=le,a(le),l(re),f(!0)},[y]),M=A.useCallback(()=>{y(),f(!0),b(s,ne=>({...ne,activeKey:null,hasPanelState:!0,open:!0}))},[s,y,b]),E=A.useCallback(()=>{d(null),b(s,ne=>_$(ne)?{...ne,open:!1}:ne),f(!1)},[s,b]),_=A.useCallback(()=>{d(null),b(s,()=>xx()),f(!1)},[s,b]),z=E,T=A.useCallback(()=>{d(null)},[]),$=A.useCallback((ne,le=r.current)=>{const ie=ne.trim(),re=g4(le);return!ie||!re.startsWith("chat:")&&!re.startsWith("issue:")?!1:(d({organizationId:ie,contextKey:re}),!0)},[]),B=A.useCallback((ne,le)=>{var de,Be;const ie=g4(ne);return(((de=t.current[ie])==null?void 0:de.tabs)??[]).some(ae=>fs(ae)===le)?((Be=n.current[ie])==null?void 0:Be[le])??0:null},[]),F=A.useCallback((ne,le,ie)=>{var _e;const re=g4(ne),de=t.current[re]??xx(),Be=de.tabs.findIndex(Ie=>fs(Ie)===le);if(Be<0)return{detached:!1,reason:"not_found",revision:null};const ae=((_e=n.current[re])==null?void 0:_e[le])??0;if(ie!==ae)return{detached:!1,reason:"revision_mismatch",revision:ae};const Ee=de.tabs[Be],he=b(re,Ie=>{const $e=Ie.tabs.filter(Oe=>fs(Oe)!==le);if($e.length===0)return{activeKey:null,hasPanelState:!0,open:!1,tabs:[]};if(Ie.activeKey!==le)return{...Ie,tabs:$e};const ce=$e[Math.min(Be,$e.length-1)]??null;return{activeKey:ce?fs(ce):null,hasPanelState:!0,open:!0,tabs:$e}});return re===r.current&&f(he.open),{detached:!0,revision:ae,target:Ee}},[b]),W=A.useCallback(ne=>{b(s,le=>{const ie=le.tabs.findIndex(Be=>fs(Be)===ne),re=le.tabs.filter(Be=>fs(Be)!==ne);if(re.length===0)return f(!1),{activeKey:null,hasPanelState:!0,open:!1,tabs:[]};if(le.activeKey!==ne)return{...le,tabs:re};const de=re[Math.min(Math.max(ie,0),re.length-1)]??re.at(-1)??null;return{activeKey:de?fs(de):null,hasPanelState:!0,open:!0,tabs:re}})},[s,b]),Y=A.useCallback(ne=>(h.current=ne,()=>{h.current===ne&&(h.current=null)}),[]),G=A.useCallback(ne=>(p.current=ne,()=>{p.current===ne&&(p.current=null)}),[]),V=A.useCallback(ne=>{const ie=(t.current[r.current]??xx()).tabs.find(de=>fs(de)===ne);if(!ie)return;const re=h.current;if(re){re(ie);return}W(ne)},[W]),L=u&&!!o.activeKey;A.useEffect(()=>{const ne=_n(),le=ne==null?void 0:ne.setSidePanelCloseShortcutActive;if(!le)return;let ie=!1,re=null;const de=()=>{if(ie)return;const ae=L&&!F8e(document.activeElement);re!==ae&&(re=ae,le(ae).catch(()=>{}))},Be=()=>queueMicrotask(de);return document.addEventListener("focusin",Be,!0),document.addEventListener("focusout",Be,!0),de(),()=>{ie=!0,document.removeEventListener("focusin",Be,!0),document.removeEventListener("focusout",Be,!0)}},[L]),A.useEffect(()=>{const ne=_n(),le=ne==null?void 0:ne.setSidePanelCloseShortcutActive;if(le)return()=>{le(!1).catch(()=>{})}},[]),A.useEffect(()=>{const ne=_n();if(ne!=null&&ne.onBrowserReset)return ne.onBrowserReset(()=>{const le=Object.fromEntries(Object.entries(t.current).map(([re,de])=>[re,lXt(de,re,p.current)]));t.current=le;const ie=le[r.current]??xx();l(ie),f(_$(ie)&&ie.open)})},[]),A.useEffect(()=>{if(!L)return;const ne=_n();if(ne!=null&&ne.onCloseSidePanelActiveTab)return ne.onCloseSidePanelActiveTab(()=>{const le=o.activeKey;le&&V(le)})},[o.activeKey,L,V]),A.useEffect(()=>{const ne=_n();if(ne!=null&&ne.onOpenEmptySidePanel)return ne.onOpenEmptySidePanel(M)},[M]),A.useEffect(()=>{if(!u||!o.activeKey)return;const ne=le=>{F8e(le.target)||le.key.toLowerCase()!=="w"||(vR()==="mac"?!le.metaKey||le.ctrlKey:!le.ctrlKey||le.metaKey)||le.altKey||le.shiftKey||(le.preventDefault(),le.stopPropagation(),V(o.activeKey))};return document.addEventListener("keydown",ne,!0),()=>document.removeEventListener("keydown",ne,!0)},[o.activeKey,u,V]);const R=A.useCallback((ne,le,ie)=>{const re=g4(ne);if(!(t.current[re]??xx()).tabs.some(ae=>fs(ae)===le))return!1;const Be=fs(ie);return b(re,ae=>({...ae,activeKey:ae.activeKey===le?Be:ae.activeKey,tabs:ae.tabs.map(Ee=>fs(Ee)===le?ie:Ee)})),!0},[b]),D=A.useCallback((ne,le)=>{R(s,ne,le)},[s,R]),X=A.useCallback((ne,le,ie)=>{ne!==le&&b(s,re=>{const de=re.tabs.findIndex(Ie=>fs(Ie)===ne),Be=re.tabs.findIndex(Ie=>fs(Ie)===le);if(de<0||Be<0)return re;const ae=[...re.tabs],[Ee]=ae.splice(de,1);if(!Ee)return re;const _e=ae.findIndex(Ie=>fs(Ie)===le)+(ie==="after"?1:0);return ae.splice(_e,0,Ee),{...re,tabs:ae}})},[s,b]),ee=A.useCallback(ne=>{y(),b(s,le=>({...le,activeKey:ne,hasPanelState:!0,open:!0}))},[s,y,b]),se=A.useMemo(()=>({activeKey:o.activeKey,clearCurrentContext:_,clearDisplayedContextHold:T,closePanel:z,closeTarget:W,contextKey:s,detachTargetForContext:F,displayedContextHold:c,getTargetRevisionForContext:B,hidePanel:E,holdDisplayedContext:$,open:u,openEmpty:M,openTarget:S,openTargetInNewTab:j,openTargetForContext:C,registerCloseRequestHandler:Y,registerBrowserResetHandler:G,registerBeforeOpen:w,replaceTarget:D,replaceTargetForContext:R,reorderTarget:X,setActiveKey:ee,setContextKey:k,showPanel:I,showPanelForContext:N,tabs:o.tabs}),[_,T,z,W,s,o.activeKey,o.tabs,F,c,B,E,$,u,M,S,C,j,w,G,Y,X,D,R,ee,k,I,N]);return i.jsx(Rge.Provider,{value:se,children:e})}function Qm(){const e=A.useContext(Rge);if(!e)throw new Error("useSidePanel must be used inside SidePanelProvider");return e}function dXt(){return A.useContext(Rge)}function uXt(e){try{const t=new URL(e).protocol;return t==="http:"||t==="https:"}catch{return!1}}async function fXt(e){var r;const{request:t}=e;if(!uXt(t.url))return"ignored";let n;try{n=await e.getSettings()}catch{return await e.forceOpenExternal(t.url),"default_browser"}return n.openLinksIn==="built_in"||t.source==="browser_popup"?(e.openBuiltIn(j6(t.url,{favicon:(r=e.resolveFavicon)==null?void 0:r.call(e,t.url),newTab:t.source==="browser_popup"})),"built_in"):(await e.forceOpenExternal(t.url),"default_browser")}const xw=8;function mXt(){return{activeViewInstanceId:null,tabOrder:[],tabsByViewInstanceId:{},runtimesById:{},promotionsById:{}}}function AXt(){return{organizations:{}}}function H4(e){return e.kind==="side"||e.kind==="transferring"||e.kind==="main"||e.kind==="parked"}function hXt(e,t){const n=e.organizations[t];return n?Object.values(n.runtimesById).filter(r=>r.targetKind==="browser"&&H4(r.host)).length:0}function pXt(e){return Object.values(e.runtimesById).filter(t=>t.targetKind==="browser"&&H4(t.host)).length}function gXt(e,t){return e.kind!==t.kind?!1:e.kind==="side"&&t.kind==="side"?e.contextKey===t.contextKey:e.kind==="main"&&t.kind==="main"?e.organizationId===t.organizationId:!0}function xXt(e){return{...e}}function $Ze(e,t,n){if(!n.id||!n.viewInstanceId||n.target.viewInstanceId!==n.viewInstanceId||n.target.kind!==n.targetKind||n.host.kind==="main"&&n.host.organizationId!==t)return!1;const r=e.runtimesById[n.id];return r&&(r.viewInstanceId!==n.viewInstanceId||r.targetKind!==n.targetKind)||n.targetKind==="browser"&&H4(n.host)&&!((r==null?void 0:r.targetKind)==="browser"&&H4(r.host))&&pXt(e)>=xw?!1:!(H4(n.host)&&Object.values(e.runtimesById).some(o=>o.id!==n.id&&o.viewInstanceId===n.viewInstanceId&&H4(o.host)))}function k1(e,t,n){if(!$Ze(e,t,n))return e;const r=e.runtimesById[n.id];return r&&gXt(r.host,n.host)?e:{...e,runtimesById:{...e.runtimesById,[n.id]:{...n,organizationId:t,target:(r==null?void 0:r.target)??v8(n.target),host:xXt(n.host)}}}}function v8(e){return e.kind!=="browser"||!e.savedViewRecovery?{...e}:{...e,savedViewRecovery:{...e.savedViewRecovery,persistedMetadata:{...e.savedViewRecovery.persistedMetadata,target:{...e.savedViewRecovery.persistedMetadata.target}}}}}function FZe(e){return!!(e.viewInstanceId&&e.runtimeId&&e.originContextKey&&e.target.viewInstanceId===e.viewInstanceId)}function Lge(e,t){return Object.values(e.tabsByViewInstanceId).find(n=>n.savedViewId===t)??null}function Dle(e,t,n,r){if(!FZe(n)||r!==null&&!r)return{organization:e,outcome:"rejected"};const s=r?Lge(e,r):null;if(s&&s.viewInstanceId!==n.viewInstanceId)return e.activeViewInstanceId===s.viewInstanceId?{organization:e,outcome:"focused_existing_binding"}:{organization:{...e,activeViewInstanceId:s.viewInstanceId},outcome:"focused_existing_binding"};const a=e.tabsByViewInstanceId[n.viewInstanceId];if(a){const c=r!==null&&a.savedViewId!==null&&a.savedViewId!==r,d=r===null||a.savedViewId===r,u=e.activeViewInstanceId===n.viewInstanceId;return d&&u?{organization:e,outcome:"already_satisfied"}:{organization:{...e,activeViewInstanceId:n.viewInstanceId,tabsByViewInstanceId:r===null||d||c?e.tabsByViewInstanceId:{...e.tabsByViewInstanceId,[n.viewInstanceId]:{...a,savedViewId:r}}},outcome:c?"binding_conflict":"already_satisfied"}}const o={id:n.runtimeId,viewInstanceId:n.viewInstanceId,targetKind:n.target.kind,target:n.target,host:{kind:"main",organizationId:t}};if(!$Ze(e,t,o))return{organization:e,outcome:"rejected"};const l=k1(e,t,o);return{organization:{...l,activeViewInstanceId:n.viewInstanceId,tabOrder:[...l.tabOrder,n.viewInstanceId],tabsByViewInstanceId:{...l.tabsByViewInstanceId,[n.viewInstanceId]:{organizationId:t,viewInstanceId:n.viewInstanceId,savedViewId:r,target:v8(n.target),originContextKey:n.originContextKey,runtimeId:n.runtimeId}}},outcome:"opened"}}function Xl(e,t,n){if(!t)return e;const r=e.organizations[t]??mXt(),s=n(r);return s===r?e:{...e,organizations:{...e.organizations,[t]:s}}}function bXt(e,t,n){const r=e.tabsByViewInstanceId[t];return!r||!n||r.savedViewId===n||r.savedViewId!==null||Lge(e,n)?e:{...e,tabsByViewInstanceId:{...e.tabsByViewInstanceId,[t]:{...r,savedViewId:n}}}}function yXt(e,t,n){const r=e.tabsByViewInstanceId[t];return!r||r.savedViewId!==n?e:{...e,tabsByViewInstanceId:{...e.tabsByViewInstanceId,[t]:{...r,savedViewId:null}}}}function vXt(e,t,n){var u;const r=e.tabsByViewInstanceId[n];if(!r)return e;const s=e.tabOrder.indexOf(n),a=e.tabOrder.filter(f=>f!==n),{[n]:o,...l}=e.tabsByViewInstanceId,c=k1(e,t,{id:r.runtimeId,viewInstanceId:r.viewInstanceId,targetKind:r.target.kind,target:((u=e.runtimesById[r.runtimeId])==null?void 0:u.target)??r.target,host:{kind:"disposed"}}),d=e.activeViewInstanceId===n?a[Math.min(Math.max(s,0),a.length-1)]??null:e.activeViewInstanceId;return{...c,activeViewInstanceId:d,tabOrder:a,tabsByViewInstanceId:l}}function wXt(e,t,n){const r=e.tabOrder.indexOf(t);if(r<0||!Number.isFinite(n))return e;const s=Math.max(0,Math.min(Math.trunc(n),e.tabOrder.length-1));if(r===s)return e;const a=[...e.tabOrder];return a.splice(r,1),a.splice(s,0,t),{...e,tabOrder:a}}function kXt(e){return{...e,target:v8(e.target)}}function oX(e){return Number.isInteger(e)&&e>=0}function OXt(e){return e.status==="pending"||e.status==="reconciling"||e.status==="claiming"||e.status==="detaching"}function SXt(e,t,n,r,s){if(!n||!s||!FZe(r)||!oX(r.sourceRevision)||e.promotionsById[n]||Object.values(e.promotionsById).some(l=>OXt(l)&&l.source.runtimeId===r.runtimeId))return e;const a=e.runtimesById[r.runtimeId];if(!a||a.viewInstanceId!==r.viewInstanceId||a.targetKind!==r.target.kind||a.host.kind!=="side"||a.host.contextKey!==r.originContextKey)return e;const o=k1(e,t,{id:a.id,viewInstanceId:a.viewInstanceId,targetKind:a.targetKind,target:a.target,host:{kind:"transferring"}});return{...o,promotionsById:{...o.promotionsById,[n]:{id:n,organizationId:t,clientMutationId:s,status:"pending",source:kXt(r)}}}}function kN(e,t,n){const r=e.runtimesById[n.runtimeId];return r?k1(e,t,{id:r.id,viewInstanceId:r.viewInstanceId,targetKind:r.targetKind,target:r.target,host:{kind:"side",contextKey:n.originContextKey}}):e}function wR(e,t,n){const r=e.promotionsById[t];if(!r||r.status!=="pending"&&r.status!=="reconciling"&&r.status!=="claiming"||r.source.sourceRevision!==n)return null;const s=e.runtimesById[r.source.runtimeId];return!s||s.viewInstanceId!==r.source.viewInstanceId||s.targetKind!==r.source.target.kind||s.host.kind!=="transferring"?null:r}function jXt(e,t,n,r,s){const a=e.promotionsById[n];if(!a||a.status!=="server_failed"&&a.status!=="commit_unknown"||a.source.sourceRevision!==r||!oX(s)||s<=r)return e;const o=e.runtimesById[a.source.runtimeId];if(!o||o.host.kind!=="side"||o.host.contextKey!==a.source.originContextKey)return e;const l=k1(e,t,{id:o.id,viewInstanceId:o.viewInstanceId,targetKind:o.targetKind,target:o.target,host:{kind:"transferring"}});return{...l,promotionsById:{...l.promotionsById,[n]:{id:a.id,organizationId:t,clientMutationId:a.clientMutationId,status:"pending",source:{...a.source,sourceRevision:s}}}}}function CXt(e,t,n,r,s){const a=e.promotionsById[n];if(!a||a.status!=="commit_unknown"||a.source.sourceRevision!==r||!oX(s)||s<=r)return e;const o=e.runtimesById[a.source.runtimeId];if(!o||o.host.kind!=="side"||o.host.contextKey!==a.source.originContextKey)return e;const l=k1(e,t,{id:o.id,viewInstanceId:o.viewInstanceId,targetKind:o.targetKind,target:o.target,host:{kind:"transferring"}});return{...l,promotionsById:{...l.promotionsById,[n]:{id:a.id,organizationId:t,clientMutationId:a.clientMutationId,status:"reconciling",source:{...a.source,sourceRevision:s}}}}}function NXt(e,t,n,r,s){const a=e.promotionsById[n];if(!a||a.status!=="claim_failed"||a.source.sourceRevision!==r||!oX(s)||s<=r)return e;const o=e.runtimesById[a.source.runtimeId];if(!o||o.host.kind!=="side"||o.host.contextKey!==a.source.originContextKey)return e;const l=k1(e,t,{id:o.id,viewInstanceId:o.viewInstanceId,targetKind:o.targetKind,target:o.target,host:{kind:"transferring"}});return{...l,promotionsById:{...l.promotionsById,[n]:{id:a.id,organizationId:t,clientMutationId:a.clientMutationId,status:"claiming",savedViewId:a.savedViewId,source:{...a.source,sourceRevision:s}}}}}function IXt(e,t,n,r,s){const a=wR(e,n,s);return!a||a.status==="claiming"||!r?e:{...e,promotionsById:{...e.promotionsById,[n]:{id:a.id,organizationId:t,clientMutationId:a.clientMutationId,source:a.source,status:"claiming",savedViewId:r}}}}function PXt(e,t,n,r,s){const a=wR(e,n,r);if(!a||a.status==="claiming")return e;const o=kN(e,t,a.source);return{...o,promotionsById:{...o.promotionsById,[n]:{id:a.id,organizationId:t,clientMutationId:a.clientMutationId,source:a.source,status:"server_failed",error:s}}}}function TXt(e,t,n,r,s){const a=wR(e,n,r);if(!a||a.status==="claiming")return e;const o=kN(e,t,a.source);return{...o,promotionsById:{...o.promotionsById,[n]:{id:a.id,organizationId:t,clientMutationId:a.clientMutationId,source:a.source,status:"commit_unknown",error:s}}}}function _Xt(e,t,n,r,s,a){const o=wR(e,n,s);if(!o||o.status!=="claiming"||!r||o.savedViewId!==r)return e;const l=kN(e,t,o.source);return{...l,promotionsById:{...l.promotionsById,[n]:{id:o.id,organizationId:t,clientMutationId:o.clientMutationId,source:o.source,status:"claim_failed",savedViewId:r,error:a}}}}function Fq(e,t){const{[t]:n,...r}=e.promotionsById;return{...e,promotionsById:r}}function MXt(e,t,n){const r=e.promotionsById[t];return!r||r.status!=="server_failed"&&r.status!=="commit_unknown"&&r.status!=="claim_failed"||r.source.sourceRevision!==n?e:Fq(e,t)}function EXt(e,t,n,r,s){const a=e.promotionsById[n];if(!a||a.source.sourceRevision!==s||a.source.savedViewId!==r&&(!("savedViewId"in a)||a.savedViewId!==r))return e;if(a.status==="detaching"){const o=UZe(e,t,n,r,s,"saved_view_removed");return Fq(o,n)}return Fq(kN(e,t,a.source),n)}function vI(e,t,n,r,s){const a=kN(e,t,n.source);return{...a,promotionsById:{...a.promotionsById,[n.id]:{id:n.id,organizationId:t,clientMutationId:n.clientMutationId,source:n.source,status:"claim_failed",savedViewId:r,error:s}}}}function BZe(e){return{...e,target:v8(e.target)}}function Q8e(e,t,n,r){return{...e,promotionsById:{...e.promotionsById,[n.id]:{...n,organizationId:t,status:"detaching",rollback:r}}}}function DXt(e,t,n,r,s){var u;const a=wR(e,n,s);if(!a||a.status!=="claiming"||!r||a.savedViewId!==r)return e;const o={activeViewInstanceId:e.activeViewInstanceId,tab:e.tabsByViewInstanceId[a.source.viewInstanceId]?BZe(e.tabsByViewInstanceId[a.source.viewInstanceId]):null},l=e.tabsByViewInstanceId[a.source.viewInstanceId],c=Lge(e,r);if(c&&c.viewInstanceId!==a.source.viewInstanceId){const f=e.activeViewInstanceId===c.viewInstanceId?e:{...e,activeViewInstanceId:c.viewInstanceId};return vI(f,t,a,r,"saved_view_already_bound")}if(l!=null&&l.savedViewId&&l.savedViewId!==r){const f=e.activeViewInstanceId===l.viewInstanceId?e:{...e,activeViewInstanceId:l.viewInstanceId};return vI(f,t,a,r,"saved_view_binding_conflict")}if(l){let f=e,m=l.runtimeId;if(l.runtimeId===a.source.runtimeId){const h=f.runtimesById[a.source.runtimeId];f=k1(f,t,{id:h.id,viewInstanceId:h.viewInstanceId,targetKind:h.targetKind,target:h.target,host:{kind:"main",organizationId:t}})}else{const h=f.runtimesById[l.runtimeId];if(!h||h.viewInstanceId!==l.viewInstanceId||h.targetKind!==l.target.kind||H4(h.host))return vI(e,t,a,r,"existing_tab_runtime_unavailable");const p=f.runtimesById[a.source.runtimeId];if(f=k1(f,t,{id:p.id,viewInstanceId:p.viewInstanceId,targetKind:p.targetKind,target:p.target,host:{kind:"main",organizationId:t}}),((u=f.runtimesById[p.id])==null?void 0:u.host.kind)!=="main")return vI(e,t,a,r,"existing_tab_runtime_unavailable");m=p.id}return f={...f,activeViewInstanceId:l.viewInstanceId,tabsByViewInstanceId:l.savedViewId===r&&l.runtimeId===m?f.tabsByViewInstanceId:{...f.tabsByViewInstanceId,[l.viewInstanceId]:{...l,savedViewId:r,runtimeId:m,target:v8(a.source.target),originContextKey:a.source.originContextKey}}},Q8e(f,t,a,o)}const d=Dle(e,t,{viewInstanceId:a.source.viewInstanceId,runtimeId:a.source.runtimeId,target:a.source.target,originContextKey:a.source.originContextKey},r);return d.outcome!=="opened"?vI(d.organization,t,a,r,d.outcome==="binding_conflict"?"saved_view_binding_conflict":"main_host_claim_rejected"):Q8e(d.organization,t,a,o)}function QZe(e,t,n,r){const s=e.promotionsById[t];if(!s||s.status!=="detaching"||s.savedViewId!==n||s.source.sourceRevision!==r)return null;const a=e.runtimesById[s.source.runtimeId],o=e.tabsByViewInstanceId[s.source.viewInstanceId];return!a||a.viewInstanceId!==s.source.viewInstanceId||a.host.kind!=="main"||a.host.organizationId!==s.organizationId||!o||o.runtimeId!==a.id||o.savedViewId!==n?null:s}function RXt(e,t,n,r){const s=QZe(e,t,n,r);return s?Fq(e,s.id):e}function UZe(e,t,n,r,s,a){const o=QZe(e,n,r,s);if(!o)return e;const l=kN(e,t,o.source),c={...l.tabsByViewInstanceId};let d=l.tabOrder;return o.rollback.tab?c[o.source.viewInstanceId]=BZe(o.rollback.tab):(delete c[o.source.viewInstanceId],d=d.filter(u=>u!==o.source.viewInstanceId)),{...l,activeViewInstanceId:o.rollback.activeViewInstanceId,tabOrder:d,tabsByViewInstanceId:c,promotionsById:{...l.promotionsById,[n]:{id:o.id,organizationId:t,clientMutationId:o.clientMutationId,source:o.source,status:"claim_failed",savedViewId:r,error:a}}}}function LXt(e,t,n,r){const s=e.runtimesById[t];return!s||s.viewInstanceId!==n||r.viewInstanceId!==n||s.targetKind!==r.kind?e:{...e,runtimesById:{...e.runtimesById,[t]:{...s,target:v8(r)}}}}function zXt(e,t,n,r){const s=e.tabsByViewInstanceId[n],a=e.runtimesById[t];return!s||s.runtimeId!==t||s.target.kind!==r.kind||r.viewInstanceId!==n||!a||a.viewInstanceId!==n||a.targetKind!==r.kind?e:{...e,tabsByViewInstanceId:{...e.tabsByViewInstanceId,[n]:{...s,target:v8(r)}}}}function $Xt(e,t){switch(t.type){case"saved-tab/open":return Xl(e,t.organizationId,n=>Dle(n,t.organizationId,t.tab,t.savedViewId).organization);case"session-tab/create":return Xl(e,t.organizationId,n=>Dle(n,t.organizationId,t.tab,null).organization);case"tab/focus":return Xl(e,t.organizationId,n=>n.activeViewInstanceId===t.viewInstanceId||!n.tabsByViewInstanceId[t.viewInstanceId]?n:{...n,activeViewInstanceId:t.viewInstanceId});case"tab/reorder":return Xl(e,t.organizationId,n=>wXt(n,t.viewInstanceId,t.toIndex));case"tab/bind-saved-view":return Xl(e,t.organizationId,n=>bXt(n,t.viewInstanceId,t.savedViewId));case"tab/unbind-saved-view":return Xl(e,t.organizationId,n=>yXt(n,t.viewInstanceId,t.savedViewId));case"tab/close":return Xl(e,t.organizationId,n=>vXt(n,t.organizationId,t.viewInstanceId));case"tab/update-target":return Xl(e,t.organizationId,n=>zXt(n,t.runtimeId,t.viewInstanceId,t.target));case"runtime/admit":return Xl(e,t.organizationId,n=>k1(n,t.organizationId,t.runtime));case"runtime/set-host":return Xl(e,t.organizationId,n=>{const r=n.runtimesById[t.runtimeId];return r?k1(n,t.organizationId,{id:r.id,viewInstanceId:r.viewInstanceId,targetKind:r.targetKind,target:r.target,host:t.host}):n});case"runtime/update-target":return Xl(e,t.organizationId,n=>LXt(n,t.runtimeId,t.viewInstanceId,t.target));case"promotion/start":return Xl(e,t.organizationId,n=>SXt(n,t.organizationId,t.promotionId,t.source,t.clientMutationId));case"promotion/server-commit":return Xl(e,t.organizationId,n=>IXt(n,t.organizationId,t.promotionId,t.savedViewId,t.expectedSourceRevision));case"promotion/claim":return Xl(e,t.organizationId,n=>DXt(n,t.organizationId,t.promotionId,t.savedViewId,t.expectedSourceRevision));case"promotion/detach-succeed":return Xl(e,t.organizationId,n=>RXt(n,t.promotionId,t.savedViewId,t.expectedSourceRevision));case"promotion/detach-fail":return Xl(e,t.organizationId,n=>UZe(n,t.organizationId,t.promotionId,t.savedViewId,t.expectedSourceRevision,t.error));case"promotion/server-fail":return Xl(e,t.organizationId,n=>PXt(n,t.organizationId,t.promotionId,t.expectedSourceRevision,t.error));case"promotion/timeout":return Xl(e,t.organizationId,n=>TXt(n,t.organizationId,t.promotionId,t.expectedSourceRevision,t.error));case"promotion/retry":return Xl(e,t.organizationId,n=>jXt(n,t.organizationId,t.promotionId,t.expectedSourceRevision,t.nextSourceRevision));case"promotion/reconcile":return Xl(e,t.organizationId,n=>CXt(n,t.organizationId,t.promotionId,t.expectedSourceRevision,t.nextSourceRevision));case"promotion/claim-fail":return Xl(e,t.organizationId,n=>_Xt(n,t.organizationId,t.promotionId,t.savedViewId,t.expectedSourceRevision,t.error));case"promotion/claim-retry":return Xl(e,t.organizationId,n=>NXt(n,t.organizationId,t.promotionId,t.expectedSourceRevision,t.nextSourceRevision));case"promotion/discard":return Xl(e,t.organizationId,n=>MXt(n,t.promotionId,t.expectedSourceRevision));case"promotion/cancel-saved-view":return Xl(e,t.organizationId,n=>EXt(n,t.organizationId,t.promotionId,t.savedViewId,t.expectedSourceRevision))}}function qZe(){var n,r;const e=(n=document.activeElement)==null?void 0:n.closest("[data-runtime-id]");if(!e||e.hidden||e.hasAttribute("inert")||e.getAttribute("aria-hidden")==="true")return null;const t=e.dataset.runtimeId;return t?{runtimeId:t,owner:(r=e.dataset.ownerId)!=null&&r.startsWith("main:")?"main_workbench":"side_panel"}:null}function FXt(){var e;return((e=qZe())==null?void 0:e.runtimeId)??null}function BXt(){const e=er(),t=Ege(),n=mWe(),{openTarget:r}=Qm(),s=g8(),a=A.useRef({liveSurfaceRuntime:t,openTarget:r,organizationId:n==null?void 0:n.selectedOrganizationId,queryClient:e,toast:s});return a.current={liveSurfaceRuntime:t,openTarget:r,organizationId:n==null?void 0:n.selectedOrganizationId,queryClient:e,toast:s},A.useEffect(()=>{const o=_n();if(o!=null&&o.onOpenWebLink)return o.onOpenWebLink(l=>{const c=a.current;fXt({request:l,getSettings:()=>c.queryClient.fetchQuery({queryKey:U.instance.browserSettings,queryFn:()=>Va.getBrowser(),staleTime:0}),openBuiltIn:d=>{var h,p,x;if(l.sourceWebContentsId){(((h=c.liveSurfaceRuntime)==null?void 0:h.openTargetForGuest(l.sourceWebContentsId,d))??!1)||console.warn("[rudder-ui] ignored Browser popup without a live guest owner",l.sourceWebContentsId);return}const u=((p=c.organizationId)==null?void 0:p.trim())??"",f=!c.liveSurfaceRuntime||!u||c.liveSurfaceRuntime.getLiveBrowserCount(u)<xw;c.openTarget(d,{allowNewBrowserGuest:f}).admitted||(x=c.toast)==null||x.pushToast({title:"Browser tab limit reached",body:`Close a Browser tab to open another. Side Panel and Main share ${xw} live tabs.`,tone:"error"})},forceOpenExternal:d=>{var u;return((u=o.forceOpenExternal)==null?void 0:u.call(o,d))??o.openExternal(d)},resolveFavicon:XKt}).catch(d=>{console.warn("[rudder-ui] failed to route Desktop web link",d)})})},[]),A.useEffect(()=>{const o=_n();if(o!=null&&o.onBrowserShortcut)return o.onBrowserShortcut(l=>{if(!t)return;const c=l.sourceWebContentsId?null:FXt();if(l.action==="close_tab"){l.sourceWebContentsId?t.closeTargetForGuest(l.sourceWebContentsId):c&&t.closeTargetForRuntime(c);return}l.sourceWebContentsId?t.dispatchBrowserShortcutForGuest(l.sourceWebContentsId,l.action):c&&t.dispatchBrowserShortcutForRuntime(c,l.action)})},[t]),A.useEffect(()=>{var m;const o=(m=_n())==null?void 0:m.setBrowserSurfaceShortcutActive;if(!o||!t)return;let l=!1,c=!1,d;const u=()=>{var y;if(l)return;const h=qZe(),p=(h==null?void 0:h.runtimeId)??null,x=p?((y=t.getRuntimeTarget(p))==null?void 0:y.kind)==="browser":!1,b=h==null?void 0:h.owner;c===x&&b===d||(c=x,d=b,o(x,b).catch(()=>{}))},f=()=>queueMicrotask(u);return document.addEventListener("focusin",f,!0),document.addEventListener("focusout",f,!0),u(),()=>{l=!0,document.removeEventListener("focusin",f,!0),document.removeEventListener("focusout",f,!0),o(!1).catch(()=>{})}},[t]),null}const lX="https://docs.rudderhq.dev",QXt="https://docs.rudderhq.dev/zh/releases",VZe="https://discord.gg/ZcfWwPVkUz";function WZe({alt:e="",className:t,...n}){return i.jsx("img",{src:"/rudder-logo.png",alt:e,"aria-hidden":e?void 0:!0,className:q("inline-block shrink-0 rounded-full bg-white object-cover ring-1 ring-black/5 dark:ring-white/10",t),...n})}function UXt(){var c;const{locale:e,t}=es(),[n,r]=A.useState(null),s=A.useRef(null),a=e==="zh-CN"?((c=n==null?void 0:n.translations)==null?void 0:c["zh-CN"])??n:n;A.useEffect(()=>{const d=_n();if(!(d!=null&&d.getReleaseNotes))return;let u=!1;return d.getReleaseNotes().then(f=>{u||f.status!=="available"||(s.current=f.notes,r(f.notes))}).catch(()=>{}),()=>{u=!0}},[]);async function o(){var u,f;const d=s.current;s.current=null,r(null),d&&await((f=(u=_n())==null?void 0:u.markReleaseNotesShown)==null?void 0:f.call(u,d.version).catch(()=>{}))}async function l(){const d=e==="zh-CN"?QXt:lX,u=_n();if(u){await u.openExternal(d).catch(()=>{});return}window.open(d,"_blank","noopener,noreferrer")}return i.jsx(vs,{open:n!==null,onOpenChange:d=>{d||o()},children:i.jsxs(Ns,{className:"gap-0 overflow-hidden p-0 sm:max-w-[36rem]",showCloseButton:!1,children:[i.jsxs("div",{className:"flex items-start gap-3 border-b border-border/70 px-5 pb-4 pt-5",children:[i.jsx("span",{className:"mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-[var(--radius-md)] border border-border bg-background shadow-sm",children:i.jsx(WZe,{alt:"Rudder",className:"h-6 w-6 ring-0"})}),i.jsxs(di,{className:"min-w-0 gap-1 text-left",children:[i.jsx(Ps,{className:"text-base leading-6",children:(a==null?void 0:a.title)??t("desktopReleaseNotes.defaultTitle")}),i.jsx(ti,{className:"text-sm leading-5",children:t("desktopReleaseNotes.description")})]})]}),i.jsx("div",{className:"max-h-[min(62vh,34rem)] overflow-y-auto px-5 py-4",children:i.jsx("div",{className:"space-y-4",children:a==null?void 0:a.sections.map(d=>i.jsxs("section",{className:"space-y-2",children:[i.jsx("h2",{className:"text-sm font-semibold text-foreground",children:d.title}),i.jsx("ul",{className:"space-y-1.5 text-sm leading-5 text-muted-foreground",children:d.items.map(u=>i.jsxs("li",{className:"flex gap-2",children:[i.jsx("span",{className:"mt-2 h-1 w-1 shrink-0 rounded-full bg-muted-foreground/70"}),i.jsx("span",{children:u})]},u))})]},d.title))})}),i.jsxs(pa,{className:"border-t border-border/70 px-5 py-4 sm:justify-between",children:[i.jsxs(oe,{type:"button",variant:"outline",onClick:()=>void l(),children:[i.jsx(Ki,{className:"h-4 w-4"}),t("desktopReleaseNotes.docs")]}),i.jsx(oe,{type:"button",onClick:()=>void o(),children:t("desktopReleaseNotes.continue")})]})]})})}function qXt(e){const[t="",...n]=e.split(/\n{2,}/);return{body:t.trim(),runDetail:n.join(`
1705
+ - (兼容旧字段)\`agentDefaultsPayload.headers["x-openclaw-auth"]\``,"organizationSettings.packages.description":"在不同 Rudder 安装之间迁移组织配置与工作数据。","organizationSettings.packages.export":"导出","organizationSettings.packages.import":"导入","organizationSettings.danger.description":"归档这个 organization 后,它会从侧边栏中隐藏。这个状态会持久化到数据库。","organizationSettings.danger.confirm":"要归档 organization “{{name}}” 吗?它会从侧边栏中隐藏。","organizationSettings.danger.archiving":"归档中...","organizationSettings.danger.alreadyArchived":"已归档","organizationSettings.danger.archive":"归档 organization","organizationSettings.danger.failed":"归档 organization 失败","settings.eyebrow.system":"系统设置","settings.eyebrow.labs":"实验室","app.instanceSetupRequired":"需要完成实例初始化","app.bootstrapInvite.active":"当前还没有实例管理员。引导邀请已经激活。请查看 Rudder 启动日志中的首个管理员邀请链接,或运行下面的命令重新生成:","app.bootstrapInvite.inactive":"当前还没有实例管理员。请在 Rudder 运行环境中执行下面的命令生成首个管理员邀请链接:","app.failedToLoadAppState":"加载应用状态失败","app.addAnotherAgentToOrganization":"为 {{name}} 再添加一个智能体","app.createAnotherOrganization":"创建另一个组织","app.createFirstOrganization":"创建你的第一个组织","app.onboarding.addAgentDescription":"再次运行引导,为这个组织添加一个智能体和一个初始任务。","app.onboarding.createAnotherDescription":"再次运行引导,创建另一个组织并初始化它的第一个智能体。","app.onboarding.createFirstDescription":"从创建一个组织和你的第一个智能体开始。","app.addAgent":"添加智能体","app.startOnboarding":"开始引导","app.noCompaniesDescription":"从创建一个组织开始。","app.newOrganization":"新建组织","general.title":"通用","general.description":"这台设备上的核心应用偏好。","general.updateFailed":"更新通用设置失败。","general.loadLoading":"正在加载通用设置...","general.loadFailed":"加载通用设置失败。","general.language.title":"语言","general.language.description":"选择这个 Rudder 实例在控制台界面中使用的语言。","general.language.label":"界面语言","general.language.help":"这是实例级界面语言,会影响所有使用这个实例的用户看到的控制台外壳和设置页面。","general.language.option.en.label":"英语","general.language.option.en.description":"默认产品语言","general.language.option.zh-CN.label":"简体中文","general.language.option.zh-CN.description":"中文界面","general.language.preview.en.primary":"Hello","general.language.preview.en.secondary":"Board UI","general.language.preview.zh-CN.primary":"你好","general.language.preview.zh-CN.secondary":"控制台界面","general.basics.title":"基础","general.productTour.title":"工作台教程","general.productTour.description":"重新播放引导教程。","general.productTour.start":"开始教程","general.logs.title":"操作日志","general.logs.description":"调整界面中面向操作员展示的输出方式。","general.logs.censor.title":"对日志中的用户名做脱敏","general.logs.censor.description":"对日志中显示的主目录路径用户名做脱敏。","general.updates.title":"桌面应用","general.updates.description":"选择这台机器安装 Rudder Desktop 时使用哪个发布渠道。","general.updates.loadFailed":"加载桌面更新设置失败。","general.updates.updateFailed":"更新桌面更新设置失败。","general.updates.unavailable":"当前环境不支持桌面更新设置。","general.updates.canary.title":"接收桌面测试版更新","general.updates.canary.disabledDescription":"安装最新正式版;当测试版更新时也纳入检测。","general.updates.canary.enabledDescription":"这台机器会同时检查正式版和更新的测试版。","general.diagnostics.developer.title":"显示开发诊断信息","general.diagnostics.developer.description":"在 transcript 中显示 Rudder 内部运行时、workspace、session 和 adapter 诊断信息。","general.developer.title":"开发者","general.appearance.title":"外观","general.appearance.description":"选择这个设备上的 Rudder 外观。视觉风格遵循低眩光、克制的 Claude 风格界面。","general.appearance.colorMode":"颜色模式","general.appearance.light.label":"浅色","general.appearance.light.description":"暖色纸面风格","general.appearance.system.label":"自动","general.appearance.system.description":"跟随系统外观","general.appearance.dark.label":"深色","general.appearance.dark.description":"低眩光工作区","general.appearance.designStyle":"设计风格","general.appearance.defaultStyle.label":"Classic","general.appearance.defaultStyle.description":"平衡的低眩光界面","general.appearance.mira.label":"Compact","general.appearance.mira.description":"紧凑卡片与控件","general.appearance.luma.label":"Rudder","general.appearance.luma.description":"柔和宽松的控件","general.appearance.baseColor":"基础色","general.appearance.base.neutral.label":"Neutral","general.appearance.base.neutral.description":"平衡的中性灰界面","general.appearance.base.stone.label":"Stone","general.appearance.base.stone.description":"暖调石色界面","general.appearance.base.zinc.label":"Zinc","general.appearance.base.zinc.description":"冷调灰色界面","general.appearance.base.mauve.label":"Mauve","general.appearance.base.mauve.description":"低饱和玫瑰灰界面","general.appearance.base.olive.label":"Olive","general.appearance.base.olive.description":"低饱和橄榄色界面","general.appearance.base.mist.label":"Mist","general.appearance.base.mist.description":"柔和蓝灰界面","general.appearance.base.taupe.label":"Taupe","general.appearance.base.taupe.description":"暖调灰褐界面","general.appearance.themeColor":"主题色","general.appearance.theme.neutral.label":"Neutral","general.appearance.theme.neutral.description":"单色操作状态","general.appearance.theme.amber.label":"Amber","general.appearance.theme.amber.description":"琥珀色操作状态","general.appearance.theme.blue.label":"Blue","general.appearance.theme.blue.description":"蓝色操作状态","general.appearance.theme.cyan.label":"Cyan","general.appearance.theme.cyan.description":"青色操作状态","general.appearance.theme.emerald.label":"Rudder","general.appearance.theme.emerald.description":"Rudder 绿色操作状态","general.appearance.theme.fuchsia.label":"Fuchsia","general.appearance.theme.fuchsia.description":"紫红色操作状态","general.appearance.theme.green.label":"Green","general.appearance.theme.green.description":"绿色操作状态","general.appearance.theme.indigo.label":"Indigo","general.appearance.theme.indigo.description":"靛蓝色操作状态","general.appearance.theme.lime.label":"Lime","general.appearance.theme.lime.description":"青柠色操作状态","general.appearance.theme.orange.label":"Orange","general.appearance.theme.orange.description":"橙色操作状态","general.appearance.theme.pink.label":"Pink","general.appearance.theme.pink.description":"粉色操作状态","general.appearance.toolCalls.title":"Tool Call","general.appearance.toolCalls.failureIndicators.label":"显示失败标识","general.appearance.toolCalls.failureIndicators.description":"Tool Call 失败时使用红色样式并显示失败标签。","general.appearance.toolCalls.failureIndicators.ariaLabel":"切换 Tool Call 失败标识","notifications.title":"通知","notifications.description":"管理这个 Rudder 实例的未读 inbox 提醒。","notifications.loadFailed":"加载通知设置失败。","notifications.updateFailed":"更新通知设置失败。","notifications.support.available":"可用","notifications.support.unavailable":"不可用","notifications.permission.title":"权限","notifications.permission.description":"通知权限由操作系统或浏览器掌控,所以 Rudder 需要同时展示当前状态和修复入口。","notifications.permission.requestFailed":"请求通知权限失败。","notifications.permission.openSettingsFailed":"打开通知设置失败。","notifications.permission.access.title":"通知访问权限","notifications.permission.access.summary":"权限:{{permission}}。提醒:{{notificationsSupport}}。","notifications.permission.access.summaryDesktop":"权限:{{permission}}。原生提醒:{{notificationsSupport}}。","notifications.permission.access.default":"Rudder 还没有请求通知权限,因此未读 inbox 提醒可能不会出现。","notifications.permission.access.denied.desktop":"通知权限已被操作系统拦截。请在系统通知设置中重新允许 Rudder,才能恢复 macOS 提醒。","notifications.permission.access.denied.browser":"通知权限已被浏览器拦截。请在浏览器站点通知设置中重新允许 Rudder,才能在 `pnpm dev` 里预览 inbox 提醒。","notifications.permission.access.requesting":"请求中...","notifications.permission.access.enable":"开启通知","notifications.permission.access.desktopHelp":"这里能触发原生通知,但真正的允许/阻止状态由 macOS 管理。如果没有弹出通知,请打开系统设置并检查 {{appName}}。","notifications.permission.access.desktopHelpProd":"真正的允许/阻止状态由 macOS 管理。如果没有弹出通知,请打开系统设置并检查 {{appName}}。","notifications.permission.access.openSettings":"打开通知设置","notifications.environment.title":"当前环境","notifications.environment.desktop":"当前运行在 Electron 桌面壳中。","notifications.environment.browser":"当前运行在浏览器预览模式中。","notifications.environment.desktopHelp":"这里可以使用原生系统通知来提示未读 inbox 变化。","notifications.environment.browserHelp":"浏览器模式可以通过 Web Notifications API 预览未读 inbox 提醒。","notifications.behavior.title":"行为","notifications.behavior.description":"选择 Rudder 是否提示未读 inbox 活动。","notifications.behavior.inbox.title":"Inbox 活动提醒","notifications.behavior.inbox.description":"当未读 inbox 数量增加时显示提醒。","notifications.behavior.inbox.toggle":"切换 inbox 通知","systemPermissions.title":"系统权限","systemPermissions.description":"管理本地自动化、文件访问和 inbox 提醒所需的系统权限。","systemPermissions.section.title":"权限","systemPermissions.section.description":"Rudder 会尽量打开对应系统设置;最终状态仍以操作系统为准。","systemPermissions.status.authorized":"已授权","systemPermissions.status.needsAccess":"需要授权","systemPermissions.status.blocked":"已阻止","systemPermissions.status.checking":"检查中","systemPermissions.status.desktopOnly":"仅桌面应用","systemPermissions.status.perApp":"按应用授权","systemPermissions.status.unknown":"未知","systemPermissions.status.unavailable":"不可用","systemPermissions.action.openSettings":"打开设置","systemPermissions.action.desktopOnly":"仅桌面可用","systemPermissions.action.browserManaged":"由浏览器管理","systemPermissions.openSettingsFailed":"打开系统设置失败。","systemPermissions.permission.fullDiskAccess.title":"完全磁盘访问权限","systemPermissions.permission.fullDiskAccess.description":"在需要更广文件访问时读取本地项目文件和工作区元数据。","systemPermissions.permission.accessibility.title":"辅助功能","systemPermissions.permission.accessibility.description":"让 Rudder 驱动的桌面自动化在需要时观察并控制应用界面。","systemPermissions.permission.automation.title":"自动化","systemPermissions.permission.automation.description":"macOS 会按目标应用分别授权自动化;可打开此面板查看具体应用条目。","systemPermissions.permission.notifications.title":"通知","systemPermissions.permission.notifications.description":"Rudder 通知的系统访问权限。Issue 和 chat 通知可以在下方分别控制。","systemPermissions.permission.notifications.inboxLabel":"Inbox 活动提醒","systemPermissions.notifications.title":"通知","systemPermissions.notifications.description":"系统通知权限可用后,选择 Rudder 哪些事件需要提醒你。","systemPermissions.notifications.system.title":"系统通知访问权限","systemPermissions.notifications.system.description":"如果 Rudder 通知被阻止或没有出现,可以打开系统通知设置检查。","systemPermissions.notifications.issue.title":"Issue 通知","systemPermissions.notifications.issue.description":"当 issue 被创建、更新、评论或重新打开时提醒。","systemPermissions.notifications.issue.toggle":"切换 issue 通知","systemPermissions.notifications.chat.title":"Chat 通知","systemPermissions.notifications.chat.description":"当 assistant chat 回复、提议 issue 或操作时提醒。","systemPermissions.notifications.chat.toggle":"切换 chat 通知","about.title":"关于","about.version.title":"版本","about.version.description":"这里显示当前机器上运行的 Rudder 构建版本。","about.version.current":"版本","about.desktop.title":"桌面应用","about.desktop.description":"这个壳层连接到与控制台、CLI 以及其他本地 Rudder 界面共用的同一份本地实例数据。","about.desktop.profile":"环境","about.desktop.instance":"实例 ID","about.desktop.runtime":"运行时","about.desktop.owner":"拥有者","about.desktop.instanceDataPath":"实例数据路径","about.actions.title":"操作","about.actions.description":"这些动作属于应用生命周期,不应该埋在通用偏好里。","about.notifications.description":"Inbox 提醒、角标行为和权限修复入口现在都集中在独立的通知设置页中管理。","about.notifications.open":"打开通知设置","about.updates.title":"检查更新","about.updates.check":"检查更新","about.updates.install":"更新","about.updates.download":"下载更新","about.updates.installing":"正在更新...","about.updates.channel.stable":"正式版","about.updates.channel.canary":"正式版 + Canary","about.updates.available.inline":"发现 {{channel}} 新版本:{{latestVersion}}。","about.updates.current.inline":"{{channel}} 当前已经是最新版本:{{currentVersion}}。","about.updates.unavailable.inline":"暂时无法完成 {{channel}} 版本对比。","about.updates.available.toastTitle":"发现新版本","about.updates.available.toastBody":"{{latestVersion}} 已可下载。","about.updates.installStarted.toastTitle":"已开始更新","about.updates.installStarted.toastBody":"Rudder 会在安装 {{latestVersion}} 后关闭并重新打开。","about.updates.installWaiting.toastTitle":"更新已排队","about.updates.installWaiting.toastBody":"安装包正在下载。Rudder 会在 {{totalRuns}} 个活跃运行结束后自动更新。","about.updates.installBlocked.toastTitle":"更新已暂停","about.updates.installUnavailable":"当前构建不支持应用内安装更新。","about.updates.installFailed":"无法开始更新。","about.updates.installFailedToastTitle":"无法开始更新","about.updates.progress.title":"正在更新到 {{version}}","about.updates.progress.readyTitle":"更新已准备好","about.updates.progress.completeTitle":"重启交接已完成","about.updates.progress.detailsTitle":"更新进度详情","about.updates.progress.failedTitle":"更新失败","about.updates.progress.retry":"重试","about.updates.progress.restartToUpdate":"退出并更新","about.updates.progress.updateWhenIdle":"空闲时更新","about.updates.progress.forceRestartToUpdate":"停止运行并立即更新","about.updates.progress.blockersTitle":"正在延迟更新的运行","about.updates.progress.blockerRun":"{{organization}} · {{agent}} · 运行 {{runId}}","about.updates.progress.automaticApply":"这些运行结束后,Rudder 会自动完成更新。","about.updates.progress.openReleases":"打开发布页","about.updates.progress.dismiss":"关闭更新状态","about.updates.progress.phase.starting":"正在开始更新...","about.updates.progress.phase.preparing_runtime":"正在准备轻量更新...","about.updates.progress.phase.resolving_release":"正在解析发布版本...","about.updates.progress.phase.downloading_checksums":"正在下载校验文件...","about.updates.progress.phase.downloading_asset":"正在下载桌面安装包...","about.updates.progress.phase.verifying_checksum":"正在校验安装包...","about.updates.progress.phase.ready_to_install":"安装包已下载并校验完成,正在检查运行状态...","about.updates.progress.phase.waiting_for_active_runs":"正在等待运行结束...","about.updates.progress.phase.preparing_restart":"正在准备重启...","about.updates.progress.phase.closing":"Rudder 将关闭并重新打开以完成更新。","about.updates.progress.phase.complete":"Rudder Desktop 启动交接已完成。","about.updates.progress.phase.failed":"更新失败。","about.updates.current.toastTitle":"已经是最新版本","about.updates.current.toastBody":"当前桌面构建已经是 {{currentVersion}}。","about.updates.unavailable.toastTitle":"暂时无法检查更新","about.updates.unavailable.toastBody":"当前无法把这个构建与最新桌面版本进行对比。","about.updates.browserFallback.toastTitle":"已打开发布页","about.updates.browserFallback.toastBody":"桌面更新检查只能在打包后的应用内运行,因此已改为打开发布页面。","about.updates.failed":"检查更新失败。","about.updates.failedToastTitle":"检查更新失败","about.feedback.title":"发送反馈","about.feedback.send":"发送反馈","about.feedback.toastTitle":"正在打开邮件应用","about.feedback.toastBody":"正在为 Rudder 维护者邮箱创建新邮件草稿。","about.feedback.failed":"打开反馈邮件草稿失败。","about.feedback.failedToastTitle":"发送反馈失败","profile.title":"个人资料","profile.loadLoading":"正在加载个人资料设置...","profile.loadFailed":"加载个人资料设置失败。","profile.updateFailed":"更新个人资料设置失败。","profile.toastSaved.title":"个人资料已保存","profile.toastSaved.body":"你的操作员资料已更新。","profile.toastSaveFailed.title":"保存个人资料失败","profile.about.title":"关于你","profile.nickname.label":"你的称呼","profile.nickname.placeholder":"Rudder 应该怎么称呼你?","profile.moreAboutYou.label":"更多关于你","profile.moreAboutYou.placeholder":"补充一些长期有效的背景信息,帮助内置聊天助手更好理解你的请求。","profile.moreAboutYou.help":"Rudder 只会把这段内容注入内置聊天助手。如果留空,则不会追加到聊天系统提示词中。","profile.import.helper.title":"从其他 AI 导入 memories","profile.import.helper.description":"把这段提示词复制到 ChatGPT、Claude 或其他 AI provider,再把导出的 memory 粘贴到下面。","profile.import.copyPrompt":"复制 memory 导入提示词","profile.import.copiedButton":"已复制","profile.import.copied.title":"提示词已复制","profile.import.copied.body":"把结果粘贴到“更多关于你”,再编辑并保存。","profile.import.copyFailed.title":"提示词未复制","profile.import.copyFailed.body":"请手动选中提示词文本并复制。","profile.save":"保存资料","profile.saving":"保存中...","productTour.checklist.title":"完成首次工作闭环","productTour.checklist.workspace":"读懂控制台","productTour.checklist.create":"创建小任务","productTour.checklist.issues":"使用 issue 结构","productTour.checklist.inspect":"检查工作输出","productTour.checklist.settings":"再次找到教程","productTour.stepCounter":"{{current}} / {{total}}","productTour.step.workspace.title":"Rudder 是 agent work 的控制台","productTour.step.workspace.body":"主导航汇集消息、任务、智能体、项目和自动化。打开项目,可以访问具体项目和文档。其他可选工作区会在启用后显示。","productTour.step.create.title":"从一个 agent 真能推进的小任务开始","productTour.step.create.body":"创建菜单是新 Chat、issue、agent 和 project 的入口。第一次闭环可以选择边界清楚、结果可 review 的小 Chat 或 issue。","productTour.step.issues.title":"Issue 增加明确的工作流结构","productTour.step.issues.body":"Issue 页面展示哪些工作在等待、执行、阻塞或完成。Chat 是并列的对话式路径;需要明确 owner、状态、优先级、依赖或 review 时,再使用 issue。","productTour.step.inspect.title":"先检查工作,再审批或继续推进","productTour.step.inspect.body":"Dashboard 会展示当前页面、详情、transcript、产出和审批入口。Rudder 应该让你清楚看到发生了什么,以及哪里需要你介入。","productTour.step.settings.title":"你可以从 Settings 重新播放教程","productTour.step.settings.body":"第一次导览结束后,Rudder 会保持安静。以后想重新查看时,打开系统设置,再进入通用即可再次运行。","productTour.back":"上一步","productTour.next":"下一步","productTour.finish":"完成","productTour.skip":"跳过教程","heartbeats.title":"心跳","heartbeats.description":"查看所有组织的定时心跳配置。你可以在这里看到哪些已调度、哪些只是已配置,并直接按行启停心跳。","heartbeats.loadLoading":"正在加载调度心跳...","heartbeats.loadFailed":"加载调度心跳失败。","heartbeats.updateFailed":"更新心跳失败。","heartbeats.disableAllFailed":"批量关闭所有心跳失败。","heartbeats.summary.scheduled":"已调度","heartbeats.summary.configuredInactive":"已配置未激活","heartbeats.summary.disabled":"已关闭","heartbeats.summary.organization":"个组织","heartbeats.summary.organizations":"个组织","heartbeats.disableAll":"全部关闭","heartbeats.disabling":"关闭中...","heartbeats.confirmDisableAll.one":"确定要关闭全部 {{count}} 个已启用智能体的定时心跳吗?","heartbeats.confirmDisableAll.many":"确定要关闭全部 {{count}} 个已启用智能体的定时心跳吗?","heartbeats.empty":"没有符合当前条件的调度心跳。","heartbeats.section.title":"已调度智能体","heartbeats.section.description":"按组织分组展示已启用心跳的智能体,方便你统一查看归属、频率与最近心跳状态。","heartbeats.table.agent":"智能体","heartbeats.table.role":"角色","heartbeats.table.scheduler":"调度状态","heartbeats.table.interval":"间隔","heartbeats.table.lastHeartbeat":"最近心跳","heartbeats.table.actions":"操作","heartbeats.scheduler.scheduled":"已调度","heartbeats.scheduler.configuredInactive":"已配置,未激活","heartbeats.scheduler.disabled":"已关闭","heartbeats.never":"从未","heartbeats.fullAgentConfig":"完整智能体配置","heartbeats.timerState":"定时心跳状态","heartbeats.on":"开","heartbeats.off":"关","chat.annotations.selectionUnavailable":"选区已不可用","chat.annotations.selectionUnavailableBody":"请重新选择回复中的文字后再试。","chat.annotations.couldNotAdd":"无法添加批注","chat.annotations.added":"已添加批注","chat.annotations.removed":"已移除批注","newIssue.agentRequest.accepted":"已发送给 Agent,完成后会在 Inbox 通知你","newIssue.agentRequest.undo":"撤销","newIssue.agentRequest.undoing":"正在取消...","newIssue.agentRequest.cancelling":"正在取消本次 Agent Run...","newIssue.agentRequest.undoUnavailable":"该 Agent Run 已无法取消","newIssue.agentRequest.runFinished":"该 Agent Run 已处于 {{status}} 状态。","newIssue.agentRequest.runUnavailable":"该 Agent Run 已不可用。","newIssue.agentRequest.undoFailed":"无法取消 Agent Run","newIssue.agentRequest.undoFailedBody":"Agent Run 可能仍在运行,请重试撤销。"},OZe=["placeholder","title","aria-label"],PZt=["code","pre","script","style","textarea","[contenteditable='true']",".cm-editor",".cm-content",".mdxeditor","[data-i18n-ignore='true']"].join(", "),R8e=new WeakMap,L8e=new WeakMap;function SZe(e){return e?e.closest(PZt)!=null:!0}function jZe(e,t){const n=e.parentElement;if(!n||SZe(n))return;const r=e.textContent??"";let s=R8e.get(e);s?r!==s.rendered&&r!==s.source&&(s.source=r):(s={source:r,rendered:r},R8e.set(e,s));const a=b5(t,s.source);s.rendered=a,r!==a&&(e.textContent=a)}function CZe(e,t,n){if(!e.hasAttribute(t)||SZe(e))return;const r=e.getAttribute(t)??"";let s=L8e.get(e);s||(s=new Map,L8e.set(e,s));let a=s.get(t);a?r!==a.rendered&&r!==a.source&&(a.source=r):(a={source:r,rendered:r},s.set(t,a));const o=b5(n,a.source);a.rendered=o,r!==o&&e.setAttribute(t,o)}function Ple(e,t){if(e.nodeType===Node.TEXT_NODE){jZe(e,t);return}if(e.nodeType!==Node.ELEMENT_NODE)return;const n=e;for(const r of OZe)CZe(n,r,t);for(const r of Array.from(n.childNodes))Ple(r,t)}function TZt({locale:e}){return A.useEffect(()=>{if(typeof document>"u")return;const t=document.body;if(!t)return;Ple(t,e);const n=new MutationObserver(r=>{for(const s of r){if(s.type==="characterData"){jZe(s.target,e);continue}if(s.type==="attributes"){CZe(s.target,s.attributeName,e);continue}for(const a of Array.from(s.addedNodes))Ple(a,e)}});return n.observe(t,{subtree:!0,childList:!0,characterData:!0,attributes:!0,attributeFilter:[...OZe]}),()=>n.disconnect()},[e]),null}const _Zt={en:kZe,"zh-CN":IZt},NZe=A.createContext(null);function MZt(e,t){return t?e.replaceAll(/\{\{(\w+)\}\}/g,(n,r)=>{const s=t[r];return s==null?n:String(s)}):e}function RP(e,t,n){const r=_Zt[e][t]??kZe[t];return MZt(r,n)}function EZt({children:e}){var a;const n=((a=Ve({queryKey:U.health,queryFn:()=>EA.get(),retry:!1}).data)==null?void 0:a.uiLocale)??"en";A.useEffect(()=>{typeof document>"u"||(document.documentElement.lang=n)},[n]);const r=A.useCallback((o,l)=>RP(n,o,l),[n]),s=A.useMemo(()=>({locale:n,t:r}),[n,r]);return i.jsxs(NZe.Provider,{value:s,children:[i.jsx(TZt,{locale:n}),e]})}function es(){const e=A.useContext(NZe);if(!e)throw new Error("useI18n must be used within I18nProvider");return e}const U3="about:blank";function DZt(e){try{return new URL(e).hostname||e}catch{return e}}function RZt(e){const t=DZt(e.url);return e.code==="ERR_CONNECTION_REFUSED"?{summary:`${t} refused to connect.`,suggestions:["Checking the connection","Checking the proxy and firewall"]}:e.code==="ERR_NAME_NOT_RESOLVED"?{summary:`${t}'s server IP address could not be found.`,suggestions:["Checking the address","Checking the connection"]}:e.code==="ERR_TIMED_OUT"?{summary:`${t} took too long to respond.`,suggestions:["Checking the connection","Trying again later"]}:{summary:`The page at ${t} could not be loaded.`,suggestions:["Checking the address","Trying again later"]}}function LZt(e){var r;return!e||e.type==="keyUp"||!(((r=e.key)==null?void 0:r.toLowerCase())==="w"||e.code==="KeyW")||e.alt||e.shift?!1:navigator.platform.toLowerCase().includes("mac")?!!e.meta&&!e.control:!!e.control&&!e.meta}function P$(e){return`https://www.google.com/search?q=${encodeURIComponent(e)}`}function zZt(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function $Zt(e){try{return new URL(e).toString()}catch{return e.trim()}}function FZt(e){return decodeURIComponent(e.pathname).replace(/\/+$/g,"").split("/").filter(Boolean).at(-1)||"File"}function BZt(e,t){try{const n=decodeURIComponent(t.pathname);return/^file:\/\/\//i.test(e)&&t.protocol==="file:"&&t.hostname===""&&n.startsWith("/")&&!/^\/[\\/]/.test(n)}catch{return!1}}function Xv(e){const t=e.trim();if(!t||t===U3)return"New tab";try{const n=new URL(t);return n.protocol==="file:"?FZt(n):n.hostname||n.protocol.replace(":","")||"Browser"}catch{return t}}function QZt(e){const t=e.trim();if(!t||/^about:blank$/i.test(t))return U3;if(/^(https?|file):/i.test(t))try{const n=new URL(t);return n.protocol==="http:"||n.protocol==="https:"||BZt(t,n)?n.toString():P$(t)}catch{return P$(t)}return/^(localhost|\d{1,3}(?:\.\d{1,3}){3})(:\d+)?(\/.*)?$/i.test(t)?`http://${t}`:/^[a-z][a-z0-9+.-]*:/i.test(t)||/\s/.test(t)?P$(t):t.includes(".")?`https://${t}`:P$(t)}function j6(e=U3,t={newTab:!0}){return{kind:"browser",url:e,label:Xv(e),tabId:zZt(),...t.favicon?{favicon:t.favicon}:{},...t.newTab===!1?{dedupeKey:$Zt(e)}:{}}}const nte=[.25,.33,.5,.67,.75,.8,.9,1,1.1,1.25,1.5,1.75,2,2.5,3,4,5],IZe="rudder.browser.side-panel-onboarding.dismissed.v1",PZe="rudder.browser.side-panel-onboarding.session-dismissed.v1",rte="rudder:browser-side-panel-onboarding-dismissed",UZt=1500;function qZt(){if(typeof window>"u")return!0;try{if(window.localStorage.getItem(IZe)==="true")return!0}catch{}try{return window.sessionStorage.getItem(PZe)==="true"}catch{return!1}}function VZt(e){if(typeof e!="string")return null;const t=e.trim();if(!t||t.length>eR)return null;if(t.startsWith("data:image/"))return t;try{const n=new URL(t);return n.protocol==="http:"||n.protocol==="https:"?t:null}catch{return null}}function TZe({active:e,canOpenNewTab:t,surface:n,target:r,targetKey:s,onOpenBrowserSettings:a,onOpenTarget:o,onReplaceTarget:l,onCloseTarget:c,onCycleTab:d,onWebContentsIdChange:u,onRegisterShortcutController:f}){const{t:m}=es(),h=A.useRef(null),p=A.useRef(null),x=A.useRef(!1),b=A.useRef(null),y=A.useRef(null),w=A.useRef(null),k=A.useRef([]),S=A.useRef(null),j=A.useRef(null),C=A.useRef(0),I=A.useRef(null),N=A.useRef(null),M=A.useRef(null),E=A.useRef(r.url),_=A.useRef(r.url),z=A.useRef(r),T=A.useRef(l),$=A.useRef(c),B=A.useRef(d),F=A.useRef(u),W=A.useRef(e),Y=A.useRef(null),[G,V]=A.useState(null),L=A.useRef(1),[R,D]=A.useState(r.url===U3?"":r.url),[X,ee]=A.useState(r.url),[se,ne]=A.useState(r.url),[le,ie]=A.useState(!1),[re,de]=A.useState({canGoBack:!1,canGoForward:!1}),[Be,ae]=A.useState(null),[Ee,he]=A.useState(!1),[_e,Ie]=A.useState(()=>!qZt()),$e=X===U3,ce=Be?RZt(Be):null;_.current=X,z.current=r,T.current=l,$.current=c,B.current=d,F.current=u,W.current=e;const Oe=A.useCallback((Ue,Se)=>{const We=p.current;if(!x.current||!We||We.tagName.toLowerCase()!=="webview")return Se;try{return Ue(We)}catch{return Se}},[]),Ye=A.useCallback(Ue=>Oe(Se=>{var We;return((We=Se.getURL)==null?void 0:We.call(Se))??Ue},Ue),[Oe]),J=A.useCallback(()=>{de({canGoBack:Oe(Ue=>{var Se;return!!((Se=Ue.canGoBack)!=null&&Se.call(Ue))},!1),canGoForward:Oe(Ue=>{var Se;return!!((Se=Ue.canGoForward)!=null&&Se.call(Ue))},!1)})},[Oe]),qe=A.useCallback(Ue=>{Oe(We=>We.setZoomFactor?(We.setZoomFactor(Ue),!0):!1,!1)&&(L.current=Ue)},[Oe]),be=A.useCallback(Ue=>{const Se=L.current;let We=0,Te=Number.POSITIVE_INFINITY;nte.forEach((fe,je)=>{const ye=Math.abs(fe-Se);ye<Te&&(Te=ye,We=je)});const He=Math.max(0,Math.min(nte.length-1,We+Ue));qe(nte[He]??1)},[qe]),ot=A.useCallback(Ue=>{var He;if(j.current)return;N.current=null,b.current=null,y.current=null,w.current!==null&&(clearTimeout(w.current),w.current=null);const Se=Ye(_.current),We=C.current+1;if(C.current=We,j.current={baselineUrl:Se,token:We},b.current=null,!Oe(fe=>{var ye,tt,me,ze;return(Ue===-1?(ye=fe.canGoBack)==null?void 0:ye.call(fe):(tt=fe.canGoForward)==null?void 0:tt.call(fe))?(Ue===-1?(me=fe.goBack)==null||me.call(fe):(ze=fe.goForward)==null||ze.call(fe),!0):!1},!1)){j.current=null;return}(He=M.current)==null||He.call(M,We,Se)},[Ye,Oe]),ke=A.useCallback(Ue=>{var Se,We;if(e)switch(Ue){case"new_tab":t&&o(j6());return;case"focus_location":(Se=h.current)==null||Se.focus(),(We=h.current)==null||We.select();return;case"reload":$e||(N.current=null,b.current=null,j.current=null,Oe(Te=>{var He;return(He=Te.reload)==null?void 0:He.call(Te)},void 0));return;case"reload_ignoring_cache":$e||(N.current=null,b.current=null,j.current=null,Oe(Te=>{var He;return(He=Te.reloadIgnoringCache)==null?void 0:He.call(Te)},void 0));return;case"go_back":$e||ot(-1);return;case"go_forward":$e||ot(1);return;case"zoom_in":$e||be(1);return;case"zoom_out":$e||be(-1);return;case"zoom_reset":$e||qe(1)}},[e,qe,t,$e,ot,o,Oe,be]);Y.current=ke,A.useEffect(()=>(f(s,ke),()=>f(s,null)),[ke,f,s]);const Ce=A.useCallback((Ue,Se=Xv(Ue))=>{const We=z.current.url!==Ue,Te={...z.current,url:Ue,label:Se,favicon:We?void 0:z.current.favicon};_.current=Ue,z.current=Te,ee(Ue),D(Ue===U3?"":Ue),E.current=Ue,T.current(s,Te)},[s]),ue=A.useCallback((Ue,Se)=>{const We=Date.now()+1e4,Te=()=>{const He=j.current;if(!He||He.token!==Ue)return;const fe=Ye("");if(fe&&fe!==Se){j.current=null,k.current=[...new Set([...k.current.filter(je=>je!==fe),Se])].slice(-16),b.current={expectedUrl:fe,staleUrls:k.current},Ce(fe,Xv(fe)),J();return}if(Date.now()>=We){j.current=null,J();return}I.current=setTimeout(Te,50)};I.current!==null&&clearTimeout(I.current),I.current=setTimeout(Te,0)},[Ce,Ye,J]);M.current=ue,A.useEffect(()=>()=>{I.current!==null&&clearTimeout(I.current),w.current!==null&&clearTimeout(w.current)},[]),A.useEffect(()=>{const Ue=E.current!==r.url;if(E.current=r.url,_.current=r.url,z.current=r,ee(r.url),D(r.url===U3?"":r.url),Ue){const Se=Ye("");(!x.current||Se!==r.url)&&ne(r.url),ae(null),he(!1)}x.current?J():de({canGoBack:!1,canGoForward:!1})},[Ye,r.label,r.url,J]),A.useEffect(()=>{const Ue=G;if(!Ue||Ue.tagName.toLowerCase()!=="webview")return;const Se=Je=>{try{const wt=new URL(Je);return`${wt.origin}${wt.pathname==="/"?"":wt.pathname}${wt.search}${wt.hash}`}catch{return Je}},We=(Je,wt)=>wt?Se(Je)===Se(wt):!1,Te=(Je,wt=!1)=>{if(j.current)return!0;const Z=b.current,Me=y.current;return Je?We(Je,Z==null?void 0:Z.expectedUrl)||We(Je,Me==null?void 0:Me.expectedUrl)?(We(Je,N.current??void 0)&&(N.current=null),!1):We(Je,N.current??void 0)?(N.current=null,b.current=null,y.current=null,w.current!==null&&(clearTimeout(w.current),w.current=null),!1):((Z==null?void 0:Z.staleUrls)??(Me==null?void 0:Me.staleUrls)??[]).some(Pe=>We(Je,Pe))||(Z||Me)&&!wt?!0:(Z&&(b.current=null),Me&&(y.current=null),!1):!1},He=Je=>{const wt=b.current;!wt||!We(Je,wt.expectedUrl)||(b.current=null,y.current={...wt},w.current!==null&&clearTimeout(w.current),w.current=setTimeout(()=>{y.current=null,w.current=null},UZt))},fe=()=>{ie(!0),ae(null),he(!1)},je=Je=>{const wt=!("isMainFrame"in Je)||Je.isMainFrame!==!1,Z="url"in Je&&typeof Je.url=="string"?Je.url:"";wt&&Z&&(N.current=Z)},ye=Je=>{var Re,Nt;const wt=!("isMainFrame"in Je)||Je.isMainFrame!==!1,Z="url"in Je&&typeof Je.url=="string"?Je.url:"";if(!wt||!Z)return;const Me=((Re=b.current)==null?void 0:Re.expectedUrl)??((Nt=y.current)==null?void 0:Nt.expectedUrl),Pe=We(Z,Me)&&Me!==Z;!Te(Z)&&Z!==_.current&&!Pe&&Ce(Z,Xv(Z))},tt=()=>{var lt,Pe;if(ie(!1),j.current){J();return}const Je=Ye(""),wt=((lt=b.current)==null?void 0:lt.expectedUrl)??((Pe=y.current)==null?void 0:Pe.expectedUrl),Me=We(Je,wt)&&wt!==Je;Je&&He(Je),Je&&!Te(Je,!0)&&Je!==_.current&&!Me&&Ce(Je,Xv(Je)),J()},me=Je=>{var Re,Nt;const wt=Ye(""),Z="url"in Je&&typeof Je.url=="string"?Je.url:wt,Me=((Re=b.current)==null?void 0:Re.expectedUrl)??((Nt=y.current)==null?void 0:Nt.expectedUrl),Pe=We(Z,Me)&&Me!==Z;Z&&!Te(Z,Je.type==="did-navigate-in-page")&&!Pe&&Ce(Z,Xv(Z)),J()},ze=Je=>{const wt=Ye(_.current);if(Te(wt))return;const Z="title"in Je&&typeof Je.title=="string"&&Je.title.trim()?Je.title.trim():Xv(wt),Me={...z.current,url:wt,label:Z};z.current=Me,T.current(s,Me)},De=Je=>{const Z=("favicons"in Je&&Array.isArray(Je.favicons)?Je.favicons:[]).map(VZt).find(lt=>!!lt);if(!Z||Z===z.current.favicon)return;const Me={...z.current,favicon:Z};z.current=Me,T.current(s,Me)},kt=Je=>{const wt="errorDescription"in Je&&typeof Je.errorDescription=="string"?Je.errorDescription:"Could not load this page.",Z="validatedURL"in Je&&typeof Je.validatedURL=="string"&&Je.validatedURL?Je.validatedURL:_.current;(!("isMainFrame"in Je)||Je.isMainFrame!==!1)&&!Te(Z)&&wt!=="ERR_ABORTED"&&(ie(!1),ae({code:wt,url:Z}),he(!1)),J()},gt=()=>{var wt,Z;x.current=!0;const Je=(wt=Ue.getWebContentsId)==null?void 0:wt.call(Ue);typeof Je=="number"&&Number.isFinite(Je)&&((Z=F.current)==null||Z.call(F,Je)),L.current!==1&&Oe(Me=>{var lt;return(lt=Me.setZoomFactor)==null?void 0:lt.call(Me,L.current)},void 0),J()},Ke=Je=>{var Pe,Re;const wt=Je,Z=wt.input;if(Z&&Z.type!=="keyUp"&&(Z.key==="Tab"||Z.code==="Tab")&&!!Z.control&&!Z.meta&&!Z.alt&&W.current&&B.current){Je.preventDefault(),B.current(Z.shift?-1:1);return}if((Pe=_n())!=null&&Pe.onBrowserShortcut)return;if(LZt(wt.input)){Je.preventDefault(),$.current(z.current);return}if(!wt.input||!W.current)return;const lt=TUe(wt.input,{isMac:navigator.platform.toLowerCase().includes("mac")});lt&&(Je.preventDefault(),(Re=Y.current)==null||Re.call(Y,lt))};return Ue.addEventListener("dom-ready",gt),Ue.addEventListener("before-input-event",Ke),Ue.addEventListener("will-navigate",je),Ue.addEventListener("did-start-loading",fe),Ue.addEventListener("did-start-navigation",ye),Ue.addEventListener("did-stop-loading",tt),Ue.addEventListener("did-navigate",me),Ue.addEventListener("did-navigate-in-page",me),Ue.addEventListener("page-title-updated",ze),Ue.addEventListener("page-favicon-updated",De),Ue.addEventListener("did-fail-load",kt),J(),()=>{Ue.removeEventListener("dom-ready",gt),Ue.removeEventListener("before-input-event",Ke),Ue.removeEventListener("will-navigate",je),Ue.removeEventListener("did-start-loading",fe),Ue.removeEventListener("did-start-navigation",ye),Ue.removeEventListener("did-stop-loading",tt),Ue.removeEventListener("did-navigate",me),Ue.removeEventListener("did-navigate-in-page",me),Ue.removeEventListener("page-title-updated",ze),Ue.removeEventListener("page-favicon-updated",De),Ue.removeEventListener("did-fail-load",kt)}},[Ce,Ye,Oe,s,J,G]);const mt=A.useCallback(Ue=>{p.current=Ue,x.current=!1,V(Ue),Ue||de({canGoBack:!1,canGoForward:!1})},[]);A.useEffect(()=>()=>{var Ue;(Ue=F.current)==null||Ue.call(F,null)},[]),A.useEffect(()=>{const Ue=()=>Ie(!1);return window.addEventListener(rte,Ue),()=>{window.removeEventListener(rte,Ue)}},[]);const ut=()=>{Ie(!1);try{window.localStorage.setItem(IZe,"true")}catch{}try{window.sessionStorage.setItem(PZe,"true")}catch{}window.dispatchEvent(new Event(rte))},ge=A.useCallback(Ue=>{const Se=QZt(Ue);N.current=null,y.current=null,w.current!==null&&(clearTimeout(w.current),w.current=null),C.current+=1,j.current=null,k.current=k.current.filter(Te=>Te!==Se),_.current&&_.current!==Se&&(k.current=[...new Set([...k.current,_.current])].slice(-16)),b.current={expectedUrl:Se,staleUrls:k.current},ae(null),he(!1),Oe(Te=>{if(!Te.loadURL)return!1;const He=()=>Te.loadURL(Se),fe=S.current,ye=(fe?fe.catch(()=>{}).then(He):Promise.resolve(He())).catch(()=>{});return S.current=ye,ye.then(()=>{S.current===ye&&(S.current=null)}),!0},!1)||ne(Se),Ce(Se,Xv(Se))},[Ce,Oe]),Le=A.useCallback(()=>{N.current=null,b.current=null,y.current=null,w.current!==null&&(clearTimeout(w.current),w.current=null),j.current=null,he(!1),Oe(Ue=>{var Se;(Se=Ue.reload)==null||Se.call(Ue)},void 0)},[Oe]),rt=Ue=>{Ue.preventDefault();const We=new FormData(Ue.currentTarget).get("browser-url");ge(typeof We=="string"?We:R)},At=()=>{var Se;if($e)return;const Ue=_n();if(Ue){((Se=Ue.forceOpenExternal)==null?void 0:Se.call(Ue,X))??Ue.openExternal(X);return}window.open(X,"_blank","noopener,noreferrer")};return i.jsxs("div",{className:"flex min-h-full flex-col bg-[color:var(--surface-elevated)]","data-testid":e?"chat-side-panel-browser-view":"chat-side-panel-browser-view-hidden","data-browser-tab-id":r.tabId,"data-active":e?"true":"false",children:[i.jsxs("div",{className:"flex shrink-0 items-center gap-1 border-b border-[color:var(--border-soft)] bg-[color:var(--surface-elevated)] px-2 py-2","data-testid":"chat-side-panel-browser-toolbar",children:[i.jsx(oe,{type:"button",variant:"ghost",size:"icon-xs","aria-label":"Back",disabled:!re.canGoBack,onClick:()=>ot(-1),children:i.jsx(n1,{className:"h-3.5 w-3.5"})}),i.jsx(oe,{type:"button",variant:"ghost",size:"icon-xs","aria-label":"Forward",disabled:!re.canGoForward,onClick:()=>ot(1),children:i.jsx(b0,{className:"h-3.5 w-3.5"})}),i.jsx(oe,{type:"button",variant:"ghost",size:"icon-xs","aria-label":"Reload",disabled:$e,onClick:Le,children:i.jsx(A0,{className:q("h-3.5 w-3.5",le&&"animate-spin")})}),i.jsx("form",{className:"min-w-0 flex-1",onSubmit:rt,children:i.jsx(nr,{ref:h,"aria-label":"Browser URL",name:"browser-url",value:R,onChange:Ue=>D(Ue.currentTarget.value),placeholder:"Enter a URL",className:"h-8 rounded-[var(--radius-md)] bg-[color:var(--surface-inset)] font-mono text-xs"})}),i.jsx(oe,{type:"button",variant:"ghost",size:"icon-xs","aria-label":"Open new browser tab",title:t?"Open new browser tab":"Browser tab limit reached",disabled:!t,onClick:()=>o(j6()),children:i.jsx(ps,{className:"h-3.5 w-3.5"})}),i.jsx(oe,{type:"button",variant:"ghost",size:"icon-xs","aria-label":"Open browser page externally",disabled:$e,onClick:At,children:i.jsx(Ki,{className:"h-3.5 w-3.5"})})]}),i.jsxs("div",{className:"relative flex min-h-0 flex-1 flex-col bg-[color:var(--surface-inset)]","data-testid":"chat-side-panel-browser-content",children:[e&&n==="side_panel"&&_e?i.jsx(wZe,{testId:"browser-side-panel-onboarding",className:"absolute right-3 top-3 z-20 w-[min(24rem,calc(100%-1.5rem))] shadow-[var(--shadow-lg)]",icon:i.jsx(BAe,{"aria-hidden":"true"}),title:m("browser.onboarding.title"),description:m("browser.onboarding.description"),stackActions:!0,actions:i.jsxs(i.Fragment,{children:[a?i.jsx(oe,{type:"button",variant:"outline",size:"sm",onClick:()=>{ut(),a()},children:m("browser.onboarding.settings")}):null,i.jsx(oe,{type:"button",size:"sm",onClick:ut,children:m("browser.onboarding.dismiss")})]})}):null,$e?i.jsx("div",{className:"flex min-h-[44vh] flex-1 items-center justify-center px-6 text-center","data-testid":"chat-side-panel-browser-start",children:i.jsxs("div",{className:"max-w-[18rem]",children:[i.jsx(jA,{className:"mx-auto h-12 w-12 text-muted-foreground"}),i.jsx("h3",{className:"mt-4 text-base font-semibold text-foreground",children:"Start browsing"}),i.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Enter a URL to open a page."})]})}):i.jsxs("div",{className:"relative flex min-h-[52vh] flex-1",children:[A.createElement("webview",{ref:mt,src:se,className:q("min-h-[52vh] flex-1 bg-[color:var(--surface-elevated)]",Be&&"invisible"),"data-testid":e?"chat-side-panel-browser-webview":"chat-side-panel-browser-webview-hidden","data-browser-tab-id":r.tabId,"data-active":e?"true":"false",allowpopups:"true"}),Be?i.jsx("div",{role:"alert","data-testid":"chat-side-panel-browser-error",className:"absolute inset-0 flex overflow-y-auto bg-[color:var(--surface-elevated)] px-8 py-10",children:i.jsxs("div",{className:"m-auto w-full max-w-[32rem]",children:[i.jsx(U3t,{className:"h-12 w-12 text-muted-foreground","aria-hidden":"true"}),i.jsx("h3",{className:"mt-6 text-xl font-semibold text-foreground",children:"This site can't be reached"}),i.jsx("p",{className:"mt-4 text-sm text-muted-foreground",children:ce==null?void 0:ce.summary}),i.jsxs("div",{className:"mt-5 text-sm text-muted-foreground",children:[i.jsx("p",{children:"Try:"}),i.jsx("ul",{className:"mt-2 list-disc space-y-1 pl-6",children:ce==null?void 0:ce.suggestions.map(Ue=>i.jsx("li",{children:Ue},Ue))})]}),i.jsx("p",{className:"mt-5 font-mono text-xs text-muted-foreground",children:Be.code}),Ee?i.jsx("p",{className:"mt-4 break-all rounded-[var(--radius-md)] border border-[color:var(--border-soft)] bg-[color:var(--surface-inset)] px-3 py-2 font-mono text-xs text-muted-foreground",children:Be.url}):null,i.jsxs("div",{className:"mt-7 flex items-center justify-between gap-3",children:[i.jsx(oe,{type:"button",variant:"outline",size:"sm","aria-expanded":Ee,onClick:()=>he(Ue=>!Ue),children:"Details"}),i.jsxs(oe,{type:"button",size:"sm",onClick:Le,children:[i.jsx(A0,{className:"h-3.5 w-3.5"}),"Reload"]})]})]})}):null]})]})]})}const WZt=A.lazy(async()=>({default:(await on(async()=>{const{AutomationDetail:e}=await Promise.resolve().then(()=>BVn);return{AutomationDetail:e}},void 0)).AutomationDetail})),HZt=A.lazy(async()=>({default:(await on(async()=>{const{LibraryLiveSurface:e}=await import("./LibraryLiveSurface-CodApFW-.js");return{LibraryLiveSurface:e}},[])).LibraryLiveSurface})),Mge=A.createContext(null);function $q(e){var n;const t=((n=e.viewInstanceId)==null?void 0:n.trim())||(e.kind==="browser"?e.tabId.trim():"");if(!t)throw new Error(`${e.kind} live surface requires a viewInstanceId`);return t}function uM(e,t){return JSON.stringify([e.trim(),t.kind,$q(t)])}function _Ze(e){try{const t=JSON.parse(e);return Array.isArray(t)&&typeof t[0]=="string"?t[0]:""}catch{return""}}function ste(e,t){return e.kind===t.kind&&$q(e)===$q(t)}function Tle(e,t){if(Object.is(e,t))return!0;if(e===null||t===null||typeof e!="object"||typeof t!="object")return!1;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((o,l)=>Tle(o,t[l]));const n=e,r=t,s=Object.keys(n).filter(o=>n[o]!==void 0),a=Object.keys(r).filter(o=>r[o]!==void 0);return s.length===a.length&&s.every(o=>Object.hasOwn(r,o)&&Tle(n[o],r[o]))}function MZe(e){return e.startsWith("main:")?"workbench":"side_panel"}function _le(e){if(!EZe(e))return!1;const t=e.element.getBoundingClientRect();return t.width>0&&t.height>0}function EZe(e){return!!(e!=null&&e.active&&e.element.isConnected)}function KZt({children:e}){const t=A.useRef(new Map),n=A.useRef(new Map),[r,s]=A.useState(0),a=A.useCallback(()=>{s(_=>_+1)},[]),o=A.useCallback(_=>{const z=t.current.get(_.runtimeId);if(z&&!ste(z.target,_.target))return()=>{};const T=z??{interactionLocked:!1,leaseOwnerId:null,owners:new Map,renderSurface:_.renderSurface??null,runtimeId:_.runtimeId,shortcutController:null,target:_.target,webContentsId:null};return T.owners.set(_.ownerId,_),_.renderSurface&&(T.renderSurface=_.renderSurface),t.current.set(_.runtimeId,T),a(),()=>{const $=t.current.get(_.runtimeId);$&&($.owners.delete(_.ownerId),$.leaseOwnerId===_.ownerId&&($.leaseOwnerId=null),a())}},[a]),l=A.useCallback(_=>{const z=t.current.get(_.runtimeId);if(!z||!ste(z.target,_.target))return;const T=z.owners.get(_.ownerId);if(!T)return;const $=!Tle(T.target,_.target);(T.active!==_.active||T.callbacks!==_.callbacks||T.element!==_.element||T.hostId!==_.hostId||T.renderSurface!==_.renderSurface||$)&&(z.owners.set(_.ownerId,_),$&&z.leaseOwnerId===_.ownerId&&!z.interactionLocked&&(z.target=_.target),_.renderSurface&&(z.renderSurface=_.renderSurface),a())},[a]),c=A.useCallback((_,z)=>{const T=t.current.get(_),$=T==null?void 0:T.owners.get(z);return!T||!_le($)?!1:(T.leaseOwnerId===z||(T.leaseOwnerId=z,a()),!0)},[a]),d=A.useCallback((_,z)=>{const T=t.current.get(_),$=T==null?void 0:T.owners.get(z);return!T||!EZe($)||T.leaseOwnerId&&T.leaseOwnerId!==z?!1:(T.leaseOwnerId===z||(T.leaseOwnerId=z,a()),!0)},[a]),u=A.useCallback(async(_,z,T=5e3)=>{var B;const $=Date.now();for(;Date.now()-$<=T;){const F=(B=t.current.get(_))==null?void 0:B.owners.get(z);if(_le(F))return!0;await new Promise(W=>{window.setTimeout(W,16)})}return!1},[]),f=A.useCallback((_,z)=>{const T=t.current.get(_);!T||T.interactionLocked===z||(T.interactionLocked=z,a())},[a]),m=A.useCallback((_,z)=>{const T=t.current.get(_);return!T||!ste(T.target,z)?!1:(T.target=z,a(),!0)},[a]),h=A.useCallback(_=>{const z=t.current.get(_);z&&(z.webContentsId!==null&&n.current.delete(z.webContentsId),t.current.delete(_),a())},[a]),p=A.useCallback((_,z)=>{const T=t.current.get(_);!T||T.webContentsId===z||(T.webContentsId!==null&&n.current.delete(T.webContentsId),T.webContentsId=z,z!==null&&n.current.set(z,_))},[]),x=A.useCallback(_=>{const z=n.current.get(_),T=z?t.current.get(z):null,$=T!=null&&T.leaseOwnerId?T.owners.get(T.leaseOwnerId):null;return!T||!$?null:{hostId:$.hostId,ownerId:$.ownerId,runtimeId:T.runtimeId,surface:MZe($.ownerId),targetKind:T.target.kind}},[]),b=A.useCallback((_,z)=>{const T=n.current.get(_),$=T?t.current.get(T):null,B=$!=null&&$.leaseOwnerId?$.owners.get($.leaseOwnerId):null;return B!=null&&B.callbacks.onOpenTarget?(B.callbacks.onOpenTarget(z),!0):!1},[]),y=A.useCallback(_=>{const z=t.current.get(_),T=z!=null&&z.leaseOwnerId?z.owners.get(z.leaseOwnerId):null;return!z||!(T!=null&&T.callbacks.onCloseTarget)?!1:(T.callbacks.onCloseTarget(z.target),!0)},[]),w=A.useCallback(_=>{const z=n.current.get(_);return z?y(z):!1},[y]),k=A.useCallback((_,z)=>{const T=t.current.get(_);!T||T.target.kind!=="browser"||(T.shortcutController=z)},[]),S=A.useCallback((_,z)=>{const T=t.current.get(_);return!T||T.target.kind!=="browser"||!T.leaseOwnerId||!T.shortcutController?!1:(T.shortcutController(z),!0)},[]),j=A.useCallback((_,z)=>{const T=n.current.get(_);return T?S(T,z):!1},[S]),C=A.useCallback(_=>Array.from(t.current.values()).filter(z=>z.target.kind==="browser"&&_Ze(z.runtimeId)===_).length,[]),I=A.useCallback(_=>{var z;return((z=t.current.get(_))==null?void 0:z.target)??null},[]),N=A.useCallback(_=>t.current.has(_),[]),M=A.useCallback(()=>Array.from(t.current.values()),[]),E=A.useMemo(()=>({autoClaimSurface:d,claimSurface:c,closeTargetForGuest:w,closeTargetForRuntime:y,dispatchBrowserShortcutForGuest:j,dispatchBrowserShortcutForRuntime:S,disposeSurface:h,getGuestOwner:x,getLiveBrowserCount:C,getRuntimeTarget:I,hasSurface:N,listRecords:M,openTargetForGuest:b,registerBrowserShortcutController:k,registerOwner:o,registerWebContentsId:p,revision:r,setInteractionLocked:f,updateOwner:l,updateTarget:m,waitForOwner:u}),[d,c,w,y,j,S,h,x,C,I,N,M,b,k,o,p,r,f,l,m,u]);return i.jsx(Mge.Provider,{value:E,children:e})}function yR(){const e=A.useContext(Mge);if(!e)throw new Error("useLiveSurfaceRuntime must be used inside LiveSurfaceRuntimeProvider");return e}function Ege(){return A.useContext(Mge)}function DZe({active:e,autoClaim:t=!0,callbacks:n={},hostId:r,ownerId:s,renderSurface:a,runtimeId:o,target:l,...c}){const{autoClaimSurface:d,registerOwner:u,updateOwner:f}=yR(),m=A.useRef(null),h=A.useRef(n);h.current=n;const p=A.useMemo(()=>({get annotationConversationId(){return h.current.annotationConversationId},get canOpenNewTab(){return h.current.canOpenNewTab},get savedViewId(){return h.current.savedViewId},onCloseTarget:x=>{var b,y;return(y=(b=h.current).onCloseTarget)==null?void 0:y.call(b,x)},onCycleTab:x=>{var b,y;return(y=(b=h.current).onCycleTab)==null?void 0:y.call(b,x)},onLocalAppTitleChange:x=>{var b,y;return(y=(b=h.current).onLocalAppTitleChange)==null?void 0:y.call(b,x)},onOpenBrowserSettings:()=>{var x,b;return(b=(x=h.current).onOpenBrowserSettings)==null?void 0:b.call(x)},onOpenTarget:x=>{var b,y;return(y=(b=h.current).onOpenTarget)==null?void 0:y.call(b,x)},onRegisterShortcutController:(x,b)=>{var y,w;return(w=(y=h.current).onRegisterShortcutController)==null?void 0:w.call(y,x,b)},onReplaceTarget:x=>{var b,y;return(y=(b=h.current).onReplaceTarget)==null?void 0:y.call(b,x)}}),[]);return A.useLayoutEffect(()=>{const x=m.current;if(x)return u({active:e,callbacks:p,element:x,hostId:r,ownerId:s,renderSurface:a,runtimeId:o,target:l})},[r,s,u,o]),A.useLayoutEffect(()=>{const x=m.current;if(!x)return;f({active:e,callbacks:p,element:x,hostId:r,ownerId:s,renderSurface:a,runtimeId:o,target:l}),e&&t&&d(o,s)},[e,t,d,r,s,a,o,p,l,f]),i.jsx("div",{...c,ref:m,"data-owner-id":s})}function ZZt({record:e,owner:t,visible:n}){var f;const r=yR(),s=e.target,a=t==null?void 0:t.callbacks,o=t?MZe(t.ownerId):"side_panel",l=m=>{var h;(h=a==null?void 0:a.onCloseTarget)==null||h.call(a,m)},c=m=>{var h;(h=a==null?void 0:a.onOpenTarget)==null||h.call(a,m)},d=m=>{var h;(m.kind==="automation"||m.kind==="browser"||m.kind==="library_directory"||m.kind==="library_document"||m.kind==="library_entry"||m.kind==="library_file"||m.kind==="local_app")&&r.updateTarget(e.runtimeId,m),e.interactionLocked||(h=a==null?void 0:a.onReplaceTarget)==null||h.call(a,m)},u=(f=e.renderSurface)==null?void 0:f.call(e,{active:n,closeTarget:l,openTarget:c,replaceTarget:d,surface:o,target:s});return s.kind==="browser"?i.jsx(TZe,{active:n,canOpenNewTab:(a==null?void 0:a.canOpenNewTab)??!1,surface:o,target:s,targetKey:fs(s),onCloseTarget:l,onCycleTab:a==null?void 0:a.onCycleTab,onOpenBrowserSettings:a==null?void 0:a.onOpenBrowserSettings,onOpenTarget:c,onRegisterShortcutController:(m,h)=>{var p;r.registerBrowserShortcutController(e.runtimeId,h),(p=a==null?void 0:a.onRegisterShortcutController)==null||p.call(a,m,h)},onReplaceTarget:(m,h)=>d(h),onWebContentsIdChange:m=>{r.registerWebContentsId(e.runtimeId,m)}}):s.kind==="local_app"?i.jsx(vZe,{active:n,savedViewId:a==null?void 0:a.savedViewId,target:s,onTitleChange:a==null?void 0:a.onLocalAppTitleChange}):u!==void 0?i.jsx(i.Fragment,{children:u}):s.kind==="automation"?i.jsx(A.Suspense,{fallback:i.jsx("div",{className:"h-full"}),children:i.jsx(WZt,{automationId:s.automationId,onClose:()=>l(s),surface:o})}):i.jsx(A.Suspense,{fallback:i.jsx("div",{className:"h-full"}),children:i.jsx(HZt,{active:n,annotationConversationId:a==null?void 0:a.annotationConversationId,organizationId:_Ze(e.runtimeId),onOpenTarget:c,surface:o,target:s})})}function XZt(){const e=yR(),t=e.listRecords(),[,n]=A.useState(0);return A.useEffect(()=>{const r=()=>n(a=>a+1);window.addEventListener("resize",r),window.addEventListener("scroll",r,!0);const s=typeof ResizeObserver>"u"?null:new ResizeObserver(r);for(const a of e.listRecords())for(const o of a.owners.values())s==null||s.observe(o.element);return()=>{window.removeEventListener("resize",r),window.removeEventListener("scroll",r,!0),s==null||s.disconnect()}},[e]),i.jsx("div",{className:"pointer-events-none fixed inset-0","data-testid":"live-surface-runtime-layer","aria-label":"Live workspace surfaces",children:t.map(r=>{const s=r.leaseOwnerId?r.owners.get(r.leaseOwnerId)??null:null,a=_le(s),o=a?s.element.getBoundingClientRect():null,l=!a||r.interactionLocked;return i.jsx("div",{"data-testid":"live-surface-runtime-host","data-host-id":s==null?void 0:s.hostId,"data-owner-id":s==null?void 0:s.ownerId,"data-runtime-id":r.runtimeId,"data-target-kind":r.target.kind,"data-view-instance-id":$q(r.target),"aria-hidden":!a,hidden:!a,inert:l?!0:void 0,className:`fixed flex min-h-0 flex-col overflow-hidden bg-[color:var(--surface-panel)] ${s!=null&&s.ownerId.startsWith("side:")?"rounded-[var(--desktop-workspace-radius)]":s!=null&&s.ownerId.startsWith("main:")?r.target.kind==="browser"?"rounded-[var(--desktop-workspace-radius)]":"rounded-b-[var(--desktop-workspace-radius)]":""}`,style:{height:o?`${o.height}px`:"0px",left:o?`${o.left}px`:"0px",pointerEvents:l?"none":"auto",top:o?`${o.top}px`:"0px",width:o?`${o.width}px`:"0px",zIndex:s!=null&&s.ownerId.startsWith("side:")?70:40},children:i.jsx(ZZt,{record:r,owner:s,visible:a&&!r.interactionLocked})},r.runtimeId)})})}const vS=[{actionId:"commandPalette.open",label:"Open command palette",description:"Search and jump across Rudder.",scope:"Global",defaultBindings:[{key:"k",code:"KeyK",metaKey:!0},{key:"k",code:"KeyK",ctrlKey:!0}],defaultBindingsByPlatform:{mac:[{key:"k",code:"KeyK",metaKey:!0}],nonMac:[{key:"k",code:"KeyK",ctrlKey:!0}]},configurable:!0,disableable:!0},{actionId:"settings.open",label:"Open settings",description:"Open System Settings.",scope:"Global",defaultBindings:[{key:",",metaKey:!0},{key:",",ctrlKey:!0}],defaultBindingsByPlatform:{mac:[{key:",",metaKey:!0}],nonMac:[{key:",",ctrlKey:!0}]},configurable:!0,disableable:!0},{actionId:"chat.create",label:"New chat",description:"Open the new chat composer.",scope:"Global",defaultBindings:[{key:"s",code:"KeyS",metaKey:!0,altKey:!0},{key:"s",code:"KeyS",ctrlKey:!0,altKey:!0}],defaultBindingsByPlatform:{mac:[{key:"s",code:"KeyS",metaKey:!0,altKey:!0}],nonMac:[{key:"s",code:"KeyS",ctrlKey:!0,altKey:!0}]},configurable:!0,disableable:!0},{actionId:"issue.create",label:"Create issue",description:"Open the new issue dialog.",scope:"Global",defaultBindings:[{key:"n",code:"KeyN",metaKey:!0},{key:"n",code:"KeyN",ctrlKey:!0}],defaultBindingsByPlatform:{mac:[{key:"n",code:"KeyN",metaKey:!0}],nonMac:[{key:"n",code:"KeyN",ctrlKey:!0}]},configurable:!0,disableable:!0},{actionId:"sidebar.toggle",label:"Toggle sidebar",description:"Show or hide the workspace sidebar.",scope:"Global",defaultBindings:[{key:"["}],configurable:!0,disableable:!0},{actionId:"panel.toggle",label:"Toggle panel",description:"Show or hide the context panel.",scope:"Global",defaultBindings:[{key:"]"}],configurable:!0,disableable:!0},{actionId:"system.escapeBack",label:"Navigate back / close detail",description:"System Escape behavior is read-only in this version.",scope:"System",defaultBindings:[{key:"Escape"}],configurable:!1,disableable:!1}],GZt=new Set(vS.filter(e=>e.configurable).map(e=>e.actionId)),YZt=new Set(["Alt","Control","Meta","Shift"]),z8e=new Set(["meta+n","meta+shift+o"]);function vR(){var n,r,s;if(typeof navigator>"u")return"nonMac";const e=navigator,t=((r=(n=e.userAgentData)==null?void 0:n.platform)==null?void 0:r.trim())||((s=e.platform)==null?void 0:s.trim())||"";return/mac|iphone|ipad|ipod/i.test(t)?"mac":"nonMac"}function RZe(e,t=vR()){var n;return(((n=e.defaultBindingsByPlatform)==null?void 0:n[t])??e.defaultBindings).map(y8)}function LZe(e){return e.length===1?e.toLowerCase():e}function y8(e){return{key:LZe(e.key.trim()),...e.code?{code:e.code.trim()}:{},...e.metaKey?{metaKey:!0}:{},...e.ctrlKey?{ctrlKey:!0}:{},...e.altKey?{altKey:!0}:{},...e.shiftKey?{shiftKey:!0}:{}}}function Mle(e){const t=y8(e);return[t.metaKey?"meta":"",t.ctrlKey?"ctrl":"",t.altKey?"alt":"",t.shiftKey?"shift":"",t.key].filter(Boolean).join("+")}function zZe(e){if(!(e instanceof HTMLElement)||JZt(e))return!1;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable||!!e.closest('[contenteditable="true"], [contenteditable="plaintext-only"]')}function JZt(e){let t=e;for(;t;){if(t.hidden||t.getAttribute("aria-hidden")==="true")return!0;const n=window.getComputedStyle(t);if(n.display==="none"||n.visibility==="hidden"||n.visibility==="collapse")return!0;t=t.parentElement}return!1}function eXt(e){return YZt.has(e.key)?null:y8({key:e.key,code:e.code||void 0,metaKey:e.metaKey,ctrlKey:e.ctrlKey,altKey:e.altKey,shiftKey:e.shiftKey})}function tXt(e,t){const n=y8(t);return(n.code&&e.code?e.code===n.code:LZe(e.key)===n.key)&&e.metaKey===!!n.metaKey&&e.ctrlKey===!!n.ctrlKey&&e.altKey===!!n.altKey&&e.shiftKey===!!n.shiftKey}function Dge(e,t=vR()){const n={};for(const r of vS)GZt.has(r.actionId)&&(n[r.actionId]=RZe(r,t));for(const r of(e==null?void 0:e.shortcuts)??[]){const s=vS.find(a=>a.actionId===r.actionId);if(s!=null&&s.configurable){if(r.disabled===!0){n[r.actionId]=[];continue}if(r.bindings&&r.bindings.length>0){const a=r.bindings.map(y8);if(nXt(r.actionId,a))continue;n[r.actionId]=a}}}return n}function nXt(e,t){return e!=="chat.create"||t.length!==z8e.size?!1:t.every(n=>z8e.has(Mle(n)))}function hO(e,t,n,r){return n===void 0?!1:(Dge(n,r)[t]??[]).some(a=>tXt(e,a))}function $8e(e,t=vR()){const n=y8(e),r=[];return n.ctrlKey&&r.push(t==="mac"?"⌃":"Ctrl"),n.altKey&&r.push(t==="mac"?"⌥":"Alt"),n.shiftKey&&r.push(t==="mac"?"⇧":"Shift"),n.metaKey&&r.push(t==="mac"?"⌘":"Meta"),r.push(rXt(n.key)),t==="mac"?r.join(""):r.join("+")}function rXt(e){return e===" "?"Space":e==="Escape"?"Esc":e.length===1?e.toUpperCase():e}function sXt(e){const t=y8(e),n=t.key.toLowerCase();return t.metaKey||t.ctrlKey?["l","r","w","q"].includes(n):!1}function iXt(e,t,n,r){const s=Mle(t),a=Dge(n,r);for(const[o,l]of Object.entries(a))if(o!==e&&l.some(c=>Mle(c)===s))return o;return null}function T$(e,t,n){const r=e.shortcuts.filter(s=>s.actionId!==t);return n&&r.push({actionId:t,...n}),{shortcuts:r}}const Rge=A.createContext(null),LP="global",NT=8;function g4(e){return(e==null?void 0:e.trim())||LP}function aXt(e){const t=hZt(e);return t||(e.kind==="issue_proposal"?`/messenger/chat/${e.conversationId}?messageId=${encodeURIComponent(e.messageId)}`:e.kind==="subagents"?`/messenger/chat/${e.conversationId}`:e.kind==="subagent"?e.conversationId?`/messenger/chat/${e.conversationId}${e.sourceMessageId?`?messageId=${encodeURIComponent(e.sourceMessageId)}`:""}`:"/messenger/chat":e.kind==="goal_chat"?e.conversationId?`/messenger/chat/${e.conversationId}`:`/goals/${e.goalId}`:e.kind==="local_file"?"/library":e.kind==="local_apps"||e.kind==="local_app"?"/apps":"/messenger/chat")}function ite(e){if(typeof window>"u"||window.innerWidth>=768||e.kind==="goal_chat"||e.kind==="run_debug_chat"||e.kind==="local_file")return!1;const t=aXt(e);if(/^https?:\/\//i.test(t)&&!t.startsWith(window.location.origin))return window.location.assign(t),!0;const n=Zf(window.location.pathname),r=rc(t,n);return window.history.pushState({},"",r),window.dispatchEvent(new PopStateEvent("popstate")),!0}function xx(){return{activeKey:null,hasPanelState:!1,open:!1,tabs:[]}}function _$(e){return!!(e&&(e.hasPanelState||e.tabs.length>0||e.activeKey!==null))}function F8e(e){return e instanceof Element&&!!e.closest("[data-testid='messenger-main-workbench'],[data-testid='live-surface-runtime-host'][data-owner-id^='main:']")}function oXt(){var e,t;return((t=(e=globalThis.crypto)==null?void 0:e.randomUUID)==null?void 0:t.call(e))??`view-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function ate(e,t,n){if(!jm(t))return t;if(t.kind==="browser")return{...t,viewInstanceId:t.viewInstanceId??t.tabId};if(!n&&t.viewInstanceId)return t;if(!n){const r=Ile(t),s=e.find(a=>jm(a)&&Ile(a)===r);if(s&&s.kind!=="browser"&&"viewInstanceId"in s&&s.viewInstanceId)return{...t,viewInstanceId:s.viewInstanceId}}return{...t,viewInstanceId:oXt()}}function B8e(e,t){return{...e,tabId:t.tabId,viewInstanceId:t.viewInstanceId??t.tabId,savedViewRecovery:t.savedViewRecovery??e.savedViewRecovery}}function ote(e,t,n,r=!0){const s=fs(n),a=n.kind==="browser"&&n.dedupeKey?e.find(d=>d.kind==="browser"&&d.dedupeKey===n.dedupeKey):void 0;if(n.kind==="browser"&&(a==null?void 0:a.kind)==="browser"){const d=fs(a),u=B8e(n,a);return{activeKey:d,tabs:e.map(f=>fs(f)===d?u:f),openResult:{admitted:!0}}}const o=e.find(d=>fs(d)===s);if(o){const d=n.kind==="browser"&&o.kind==="browser"?B8e(n,o):n;return{activeKey:s,tabs:e.map(u=>fs(u)===s?d:u),openResult:{admitted:!0}}}const l=[...e,n];if(n.kind!=="browser")return{activeKey:s,tabs:l,openResult:{admitted:!0}};const c=e.filter(d=>d.kind==="browser").length;return r&&c<NT?{activeKey:s,tabs:l,openResult:{admitted:!0}}:{activeKey:t,tabs:e,openResult:{admitted:!1,reason:"browser_capacity"}}}function Ele(e){var t;return((t=e.viewInstanceId)==null?void 0:t.trim())||e.tabId.trim()}function lte(e){const t=new Set;for(const n of Object.values(e))for(const r of n.tabs)r.kind==="browser"&&t.add(Ele(r));return t}function lXt(e,t,n){const r=e.activeKey?e.tabs.findIndex(l=>fs(l)===e.activeKey):-1,s=e.tabs.filter(l=>l.kind!=="browser"||(n==null?void 0:n(t,l))==="preserve");if(s.length===e.tabs.length)return e;const a=e.activeKey!==null&&s.some(l=>fs(l)===e.activeKey),o=s[Math.min(Math.max(r,0),s.length-1)]??s.at(-1)??null;return{...e,activeKey:e.activeKey===null?null:a?e.activeKey:o?fs(o):null,tabs:s}}function cXt({children:e}){const t=A.useRef({[LP]:xx()}),n=A.useRef({[LP]:{}}),r=A.useRef(LP),[s,a]=A.useState(LP),[o,l]=A.useState(()=>xx()),[c,d]=A.useState(null),[u,f]=A.useState(!1),m=A.useRef(u);m.current=u;const h=A.useRef(null),p=A.useRef(null),x=A.useRef(new Set),b=A.useCallback((ne,le)=>{const ie=t.current[ne]??xx(),re=le(ie);if(re!==ie){const de=new Map(ie.tabs.map(Ee=>[fs(Ee),Ee])),Be=n.current[ne]??{},ae={...Be};for(const Ee of re.tabs){const he=fs(Ee),_e=de.get(he),Ie=Be[he]??0;ae[he]=_e?_e!==Ee?Ie+1:Ie:Object.hasOwn(Be,he)?Ie+1:0}n.current={...n.current,[ne]:ae}}return t.current={...t.current,[ne]:re},ne===r.current&&l(re),re},[]),y=A.useCallback(()=>{if(!m.current)for(const ne of x.current)ne()},[]),w=A.useCallback(ne=>(x.current.add(ne),()=>{x.current.delete(ne)}),[]),k=A.useCallback(ne=>{const le=g4(ne);if(r.current===le)return;const ie=t.current[le]??xx();!m.current&&_$(ie)&&ie.open&&y(),r.current=le,l(ie),f(_$(ie)&&ie.open),a(re=>re===le?re:le)},[y]),S=A.useCallback((ne,le)=>{if(ite(ne))return{admitted:!0};y();let ie={admitted:!0};return b(s,re=>{const de=lte(t.current),Be=ne.kind!=="browser"||de.has(Ele(ne))||(le==null?void 0:le.allowNewBrowserGuest)!==!1&&de.size<NT,ae=ote(re.tabs,re.activeKey,ate(re.tabs,ne,!1),Be);return ie=ae.openResult,{activeKey:ae.activeKey,hasPanelState:!0,open:!0,tabs:ae.tabs}}),f(!0),ie},[s,y,b]),j=A.useCallback((ne,le)=>{if(ite(ne))return{admitted:!0};y();let ie={admitted:!0};return b(s,re=>{const de=lte(t.current),Be=ne.kind!=="browser"||(le==null?void 0:le.allowNewBrowserGuest)!==!1&&de.size<NT,ae=ote(re.tabs,re.activeKey,ate(re.tabs,ne,!0),Be);return ie=ae.openResult,{activeKey:ae.activeKey,hasPanelState:!0,open:!0,tabs:ae.tabs}}),f(!0),ie},[s,y,b]),C=A.useCallback((ne,le,ie)=>{if(ite(le))return{admitted:!0};y();const re=g4(ne);let de={admitted:!0};const Be=b(re,ae=>{const Ee=lte(t.current),he=le.kind!=="browser"||Ee.has(Ele(le))||(ie==null?void 0:ie.allowNewBrowserGuest)!==!1&&Ee.size<NT,_e=ote(ae.tabs,ae.activeKey,ate(ae.tabs,le,!1),he);return de=_e.openResult,{activeKey:_e.activeKey,hasPanelState:!0,open:!0,tabs:_e.tabs}});return re===r.current&&(l(Be),f(!0)),de},[y,b]),I=A.useCallback(()=>{y(),b(s,ne=>({...ne,hasPanelState:!0,open:!0})),f(!0)},[s,y,b]),N=A.useCallback(ne=>{y();const le=g4(ne),re={...t.current[le]??xx(),hasPanelState:!0,open:!0};t.current={...t.current,[le]:re},r.current=le,a(le),l(re),f(!0)},[y]),M=A.useCallback(()=>{y(),f(!0),b(s,ne=>({...ne,activeKey:null,hasPanelState:!0,open:!0}))},[s,y,b]),E=A.useCallback(()=>{d(null),b(s,ne=>_$(ne)?{...ne,open:!1}:ne),f(!1)},[s,b]),_=A.useCallback(()=>{d(null),b(s,()=>xx()),f(!1)},[s,b]),z=E,T=A.useCallback(()=>{d(null)},[]),$=A.useCallback((ne,le=r.current)=>{const ie=ne.trim(),re=g4(le);return!ie||!re.startsWith("chat:")&&!re.startsWith("issue:")?!1:(d({organizationId:ie,contextKey:re}),!0)},[]),B=A.useCallback((ne,le)=>{var de,Be;const ie=g4(ne);return(((de=t.current[ie])==null?void 0:de.tabs)??[]).some(ae=>fs(ae)===le)?((Be=n.current[ie])==null?void 0:Be[le])??0:null},[]),F=A.useCallback((ne,le,ie)=>{var _e;const re=g4(ne),de=t.current[re]??xx(),Be=de.tabs.findIndex(Ie=>fs(Ie)===le);if(Be<0)return{detached:!1,reason:"not_found",revision:null};const ae=((_e=n.current[re])==null?void 0:_e[le])??0;if(ie!==ae)return{detached:!1,reason:"revision_mismatch",revision:ae};const Ee=de.tabs[Be],he=b(re,Ie=>{const $e=Ie.tabs.filter(Oe=>fs(Oe)!==le);if($e.length===0)return{activeKey:null,hasPanelState:!0,open:!1,tabs:[]};if(Ie.activeKey!==le)return{...Ie,tabs:$e};const ce=$e[Math.min(Be,$e.length-1)]??null;return{activeKey:ce?fs(ce):null,hasPanelState:!0,open:!0,tabs:$e}});return re===r.current&&f(he.open),{detached:!0,revision:ae,target:Ee}},[b]),W=A.useCallback(ne=>{b(s,le=>{const ie=le.tabs.findIndex(Be=>fs(Be)===ne),re=le.tabs.filter(Be=>fs(Be)!==ne);if(re.length===0)return f(!1),{activeKey:null,hasPanelState:!0,open:!1,tabs:[]};if(le.activeKey!==ne)return{...le,tabs:re};const de=re[Math.min(Math.max(ie,0),re.length-1)]??re.at(-1)??null;return{activeKey:de?fs(de):null,hasPanelState:!0,open:!0,tabs:re}})},[s,b]),Y=A.useCallback(ne=>(h.current=ne,()=>{h.current===ne&&(h.current=null)}),[]),G=A.useCallback(ne=>(p.current=ne,()=>{p.current===ne&&(p.current=null)}),[]),V=A.useCallback(ne=>{const ie=(t.current[r.current]??xx()).tabs.find(de=>fs(de)===ne);if(!ie)return;const re=h.current;if(re){re(ie);return}W(ne)},[W]),L=u&&!!o.activeKey;A.useEffect(()=>{const ne=_n(),le=ne==null?void 0:ne.setSidePanelCloseShortcutActive;if(!le)return;let ie=!1,re=null;const de=()=>{if(ie)return;const ae=L&&!F8e(document.activeElement);re!==ae&&(re=ae,le(ae).catch(()=>{}))},Be=()=>queueMicrotask(de);return document.addEventListener("focusin",Be,!0),document.addEventListener("focusout",Be,!0),de(),()=>{ie=!0,document.removeEventListener("focusin",Be,!0),document.removeEventListener("focusout",Be,!0)}},[L]),A.useEffect(()=>{const ne=_n(),le=ne==null?void 0:ne.setSidePanelCloseShortcutActive;if(le)return()=>{le(!1).catch(()=>{})}},[]),A.useEffect(()=>{const ne=_n();if(ne!=null&&ne.onBrowserReset)return ne.onBrowserReset(()=>{const le=Object.fromEntries(Object.entries(t.current).map(([re,de])=>[re,lXt(de,re,p.current)]));t.current=le;const ie=le[r.current]??xx();l(ie),f(_$(ie)&&ie.open)})},[]),A.useEffect(()=>{if(!L)return;const ne=_n();if(ne!=null&&ne.onCloseSidePanelActiveTab)return ne.onCloseSidePanelActiveTab(()=>{const le=o.activeKey;le&&V(le)})},[o.activeKey,L,V]),A.useEffect(()=>{const ne=_n();if(ne!=null&&ne.onOpenEmptySidePanel)return ne.onOpenEmptySidePanel(M)},[M]),A.useEffect(()=>{if(!u||!o.activeKey)return;const ne=le=>{F8e(le.target)||le.key.toLowerCase()!=="w"||(vR()==="mac"?!le.metaKey||le.ctrlKey:!le.ctrlKey||le.metaKey)||le.altKey||le.shiftKey||(le.preventDefault(),le.stopPropagation(),V(o.activeKey))};return document.addEventListener("keydown",ne,!0),()=>document.removeEventListener("keydown",ne,!0)},[o.activeKey,u,V]);const R=A.useCallback((ne,le,ie)=>{const re=g4(ne);if(!(t.current[re]??xx()).tabs.some(ae=>fs(ae)===le))return!1;const Be=fs(ie);return b(re,ae=>({...ae,activeKey:ae.activeKey===le?Be:ae.activeKey,tabs:ae.tabs.map(Ee=>fs(Ee)===le?ie:Ee)})),!0},[b]),D=A.useCallback((ne,le)=>{R(s,ne,le)},[s,R]),X=A.useCallback((ne,le,ie)=>{ne!==le&&b(s,re=>{const de=re.tabs.findIndex(Ie=>fs(Ie)===ne),Be=re.tabs.findIndex(Ie=>fs(Ie)===le);if(de<0||Be<0)return re;const ae=[...re.tabs],[Ee]=ae.splice(de,1);if(!Ee)return re;const _e=ae.findIndex(Ie=>fs(Ie)===le)+(ie==="after"?1:0);return ae.splice(_e,0,Ee),{...re,tabs:ae}})},[s,b]),ee=A.useCallback(ne=>{y(),b(s,le=>({...le,activeKey:ne,hasPanelState:!0,open:!0}))},[s,y,b]),se=A.useMemo(()=>({activeKey:o.activeKey,clearCurrentContext:_,clearDisplayedContextHold:T,closePanel:z,closeTarget:W,contextKey:s,detachTargetForContext:F,displayedContextHold:c,getTargetRevisionForContext:B,hidePanel:E,holdDisplayedContext:$,open:u,openEmpty:M,openTarget:S,openTargetInNewTab:j,openTargetForContext:C,registerCloseRequestHandler:Y,registerBrowserResetHandler:G,registerBeforeOpen:w,replaceTarget:D,replaceTargetForContext:R,reorderTarget:X,setActiveKey:ee,setContextKey:k,showPanel:I,showPanelForContext:N,tabs:o.tabs}),[_,T,z,W,s,o.activeKey,o.tabs,F,c,B,E,$,u,M,S,C,j,w,G,Y,X,D,R,ee,k,I,N]);return i.jsx(Rge.Provider,{value:se,children:e})}function Qm(){const e=A.useContext(Rge);if(!e)throw new Error("useSidePanel must be used inside SidePanelProvider");return e}function dXt(){return A.useContext(Rge)}function uXt(e){try{const t=new URL(e).protocol;return t==="http:"||t==="https:"}catch{return!1}}async function fXt(e){var r;const{request:t}=e;if(!uXt(t.url))return"ignored";let n;try{n=await e.getSettings()}catch{return await e.forceOpenExternal(t.url),"default_browser"}return n.openLinksIn==="built_in"||t.source==="browser_popup"?(e.openBuiltIn(j6(t.url,{favicon:(r=e.resolveFavicon)==null?void 0:r.call(e,t.url),newTab:t.source==="browser_popup"})),"built_in"):(await e.forceOpenExternal(t.url),"default_browser")}const xw=8;function mXt(){return{activeViewInstanceId:null,tabOrder:[],tabsByViewInstanceId:{},runtimesById:{},promotionsById:{}}}function AXt(){return{organizations:{}}}function H4(e){return e.kind==="side"||e.kind==="transferring"||e.kind==="main"||e.kind==="parked"}function hXt(e,t){const n=e.organizations[t];return n?Object.values(n.runtimesById).filter(r=>r.targetKind==="browser"&&H4(r.host)).length:0}function pXt(e){return Object.values(e.runtimesById).filter(t=>t.targetKind==="browser"&&H4(t.host)).length}function gXt(e,t){return e.kind!==t.kind?!1:e.kind==="side"&&t.kind==="side"?e.contextKey===t.contextKey:e.kind==="main"&&t.kind==="main"?e.organizationId===t.organizationId:!0}function xXt(e){return{...e}}function $Ze(e,t,n){if(!n.id||!n.viewInstanceId||n.target.viewInstanceId!==n.viewInstanceId||n.target.kind!==n.targetKind||n.host.kind==="main"&&n.host.organizationId!==t)return!1;const r=e.runtimesById[n.id];return r&&(r.viewInstanceId!==n.viewInstanceId||r.targetKind!==n.targetKind)||n.targetKind==="browser"&&H4(n.host)&&!((r==null?void 0:r.targetKind)==="browser"&&H4(r.host))&&pXt(e)>=xw?!1:!(H4(n.host)&&Object.values(e.runtimesById).some(o=>o.id!==n.id&&o.viewInstanceId===n.viewInstanceId&&H4(o.host)))}function k1(e,t,n){if(!$Ze(e,t,n))return e;const r=e.runtimesById[n.id];return r&&gXt(r.host,n.host)?e:{...e,runtimesById:{...e.runtimesById,[n.id]:{...n,organizationId:t,target:(r==null?void 0:r.target)??v8(n.target),host:xXt(n.host)}}}}function v8(e){return e.kind!=="browser"||!e.savedViewRecovery?{...e}:{...e,savedViewRecovery:{...e.savedViewRecovery,persistedMetadata:{...e.savedViewRecovery.persistedMetadata,target:{...e.savedViewRecovery.persistedMetadata.target}}}}}function FZe(e){return!!(e.viewInstanceId&&e.runtimeId&&e.originContextKey&&e.target.viewInstanceId===e.viewInstanceId)}function Lge(e,t){return Object.values(e.tabsByViewInstanceId).find(n=>n.savedViewId===t)??null}function Dle(e,t,n,r){if(!FZe(n)||r!==null&&!r)return{organization:e,outcome:"rejected"};const s=r?Lge(e,r):null;if(s&&s.viewInstanceId!==n.viewInstanceId)return e.activeViewInstanceId===s.viewInstanceId?{organization:e,outcome:"focused_existing_binding"}:{organization:{...e,activeViewInstanceId:s.viewInstanceId},outcome:"focused_existing_binding"};const a=e.tabsByViewInstanceId[n.viewInstanceId];if(a){const c=r!==null&&a.savedViewId!==null&&a.savedViewId!==r,d=r===null||a.savedViewId===r,u=e.activeViewInstanceId===n.viewInstanceId;return d&&u?{organization:e,outcome:"already_satisfied"}:{organization:{...e,activeViewInstanceId:n.viewInstanceId,tabsByViewInstanceId:r===null||d||c?e.tabsByViewInstanceId:{...e.tabsByViewInstanceId,[n.viewInstanceId]:{...a,savedViewId:r}}},outcome:c?"binding_conflict":"already_satisfied"}}const o={id:n.runtimeId,viewInstanceId:n.viewInstanceId,targetKind:n.target.kind,target:n.target,host:{kind:"main",organizationId:t}};if(!$Ze(e,t,o))return{organization:e,outcome:"rejected"};const l=k1(e,t,o);return{organization:{...l,activeViewInstanceId:n.viewInstanceId,tabOrder:[...l.tabOrder,n.viewInstanceId],tabsByViewInstanceId:{...l.tabsByViewInstanceId,[n.viewInstanceId]:{organizationId:t,viewInstanceId:n.viewInstanceId,savedViewId:r,target:v8(n.target),originContextKey:n.originContextKey,runtimeId:n.runtimeId}}},outcome:"opened"}}function Xl(e,t,n){if(!t)return e;const r=e.organizations[t]??mXt(),s=n(r);return s===r?e:{...e,organizations:{...e.organizations,[t]:s}}}function bXt(e,t,n){const r=e.tabsByViewInstanceId[t];return!r||!n||r.savedViewId===n||r.savedViewId!==null||Lge(e,n)?e:{...e,tabsByViewInstanceId:{...e.tabsByViewInstanceId,[t]:{...r,savedViewId:n}}}}function yXt(e,t,n){const r=e.tabsByViewInstanceId[t];return!r||r.savedViewId!==n?e:{...e,tabsByViewInstanceId:{...e.tabsByViewInstanceId,[t]:{...r,savedViewId:null}}}}function vXt(e,t,n){var u;const r=e.tabsByViewInstanceId[n];if(!r)return e;const s=e.tabOrder.indexOf(n),a=e.tabOrder.filter(f=>f!==n),{[n]:o,...l}=e.tabsByViewInstanceId,c=k1(e,t,{id:r.runtimeId,viewInstanceId:r.viewInstanceId,targetKind:r.target.kind,target:((u=e.runtimesById[r.runtimeId])==null?void 0:u.target)??r.target,host:{kind:"disposed"}}),d=e.activeViewInstanceId===n?a[Math.min(Math.max(s,0),a.length-1)]??null:e.activeViewInstanceId;return{...c,activeViewInstanceId:d,tabOrder:a,tabsByViewInstanceId:l}}function wXt(e,t,n){const r=e.tabOrder.indexOf(t);if(r<0||!Number.isFinite(n))return e;const s=Math.max(0,Math.min(Math.trunc(n),e.tabOrder.length-1));if(r===s)return e;const a=[...e.tabOrder];return a.splice(r,1),a.splice(s,0,t),{...e,tabOrder:a}}function kXt(e){return{...e,target:v8(e.target)}}function oX(e){return Number.isInteger(e)&&e>=0}function OXt(e){return e.status==="pending"||e.status==="reconciling"||e.status==="claiming"||e.status==="detaching"}function SXt(e,t,n,r,s){if(!n||!s||!FZe(r)||!oX(r.sourceRevision)||e.promotionsById[n]||Object.values(e.promotionsById).some(l=>OXt(l)&&l.source.runtimeId===r.runtimeId))return e;const a=e.runtimesById[r.runtimeId];if(!a||a.viewInstanceId!==r.viewInstanceId||a.targetKind!==r.target.kind||a.host.kind!=="side"||a.host.contextKey!==r.originContextKey)return e;const o=k1(e,t,{id:a.id,viewInstanceId:a.viewInstanceId,targetKind:a.targetKind,target:a.target,host:{kind:"transferring"}});return{...o,promotionsById:{...o.promotionsById,[n]:{id:n,organizationId:t,clientMutationId:s,status:"pending",source:kXt(r)}}}}function kN(e,t,n){const r=e.runtimesById[n.runtimeId];return r?k1(e,t,{id:r.id,viewInstanceId:r.viewInstanceId,targetKind:r.targetKind,target:r.target,host:{kind:"side",contextKey:n.originContextKey}}):e}function wR(e,t,n){const r=e.promotionsById[t];if(!r||r.status!=="pending"&&r.status!=="reconciling"&&r.status!=="claiming"||r.source.sourceRevision!==n)return null;const s=e.runtimesById[r.source.runtimeId];return!s||s.viewInstanceId!==r.source.viewInstanceId||s.targetKind!==r.source.target.kind||s.host.kind!=="transferring"?null:r}function jXt(e,t,n,r,s){const a=e.promotionsById[n];if(!a||a.status!=="server_failed"&&a.status!=="commit_unknown"||a.source.sourceRevision!==r||!oX(s)||s<=r)return e;const o=e.runtimesById[a.source.runtimeId];if(!o||o.host.kind!=="side"||o.host.contextKey!==a.source.originContextKey)return e;const l=k1(e,t,{id:o.id,viewInstanceId:o.viewInstanceId,targetKind:o.targetKind,target:o.target,host:{kind:"transferring"}});return{...l,promotionsById:{...l.promotionsById,[n]:{id:a.id,organizationId:t,clientMutationId:a.clientMutationId,status:"pending",source:{...a.source,sourceRevision:s}}}}}function CXt(e,t,n,r,s){const a=e.promotionsById[n];if(!a||a.status!=="commit_unknown"||a.source.sourceRevision!==r||!oX(s)||s<=r)return e;const o=e.runtimesById[a.source.runtimeId];if(!o||o.host.kind!=="side"||o.host.contextKey!==a.source.originContextKey)return e;const l=k1(e,t,{id:o.id,viewInstanceId:o.viewInstanceId,targetKind:o.targetKind,target:o.target,host:{kind:"transferring"}});return{...l,promotionsById:{...l.promotionsById,[n]:{id:a.id,organizationId:t,clientMutationId:a.clientMutationId,status:"reconciling",source:{...a.source,sourceRevision:s}}}}}function NXt(e,t,n,r,s){const a=e.promotionsById[n];if(!a||a.status!=="claim_failed"||a.source.sourceRevision!==r||!oX(s)||s<=r)return e;const o=e.runtimesById[a.source.runtimeId];if(!o||o.host.kind!=="side"||o.host.contextKey!==a.source.originContextKey)return e;const l=k1(e,t,{id:o.id,viewInstanceId:o.viewInstanceId,targetKind:o.targetKind,target:o.target,host:{kind:"transferring"}});return{...l,promotionsById:{...l.promotionsById,[n]:{id:a.id,organizationId:t,clientMutationId:a.clientMutationId,status:"claiming",savedViewId:a.savedViewId,source:{...a.source,sourceRevision:s}}}}}function IXt(e,t,n,r,s){const a=wR(e,n,s);return!a||a.status==="claiming"||!r?e:{...e,promotionsById:{...e.promotionsById,[n]:{id:a.id,organizationId:t,clientMutationId:a.clientMutationId,source:a.source,status:"claiming",savedViewId:r}}}}function PXt(e,t,n,r,s){const a=wR(e,n,r);if(!a||a.status==="claiming")return e;const o=kN(e,t,a.source);return{...o,promotionsById:{...o.promotionsById,[n]:{id:a.id,organizationId:t,clientMutationId:a.clientMutationId,source:a.source,status:"server_failed",error:s}}}}function TXt(e,t,n,r,s){const a=wR(e,n,r);if(!a||a.status==="claiming")return e;const o=kN(e,t,a.source);return{...o,promotionsById:{...o.promotionsById,[n]:{id:a.id,organizationId:t,clientMutationId:a.clientMutationId,source:a.source,status:"commit_unknown",error:s}}}}function _Xt(e,t,n,r,s,a){const o=wR(e,n,s);if(!o||o.status!=="claiming"||!r||o.savedViewId!==r)return e;const l=kN(e,t,o.source);return{...l,promotionsById:{...l.promotionsById,[n]:{id:o.id,organizationId:t,clientMutationId:o.clientMutationId,source:o.source,status:"claim_failed",savedViewId:r,error:a}}}}function Fq(e,t){const{[t]:n,...r}=e.promotionsById;return{...e,promotionsById:r}}function MXt(e,t,n){const r=e.promotionsById[t];return!r||r.status!=="server_failed"&&r.status!=="commit_unknown"&&r.status!=="claim_failed"||r.source.sourceRevision!==n?e:Fq(e,t)}function EXt(e,t,n,r,s){const a=e.promotionsById[n];if(!a||a.source.sourceRevision!==s||a.source.savedViewId!==r&&(!("savedViewId"in a)||a.savedViewId!==r))return e;if(a.status==="detaching"){const o=UZe(e,t,n,r,s,"saved_view_removed");return Fq(o,n)}return Fq(kN(e,t,a.source),n)}function vI(e,t,n,r,s){const a=kN(e,t,n.source);return{...a,promotionsById:{...a.promotionsById,[n.id]:{id:n.id,organizationId:t,clientMutationId:n.clientMutationId,source:n.source,status:"claim_failed",savedViewId:r,error:s}}}}function BZe(e){return{...e,target:v8(e.target)}}function Q8e(e,t,n,r){return{...e,promotionsById:{...e.promotionsById,[n.id]:{...n,organizationId:t,status:"detaching",rollback:r}}}}function DXt(e,t,n,r,s){var u;const a=wR(e,n,s);if(!a||a.status!=="claiming"||!r||a.savedViewId!==r)return e;const o={activeViewInstanceId:e.activeViewInstanceId,tab:e.tabsByViewInstanceId[a.source.viewInstanceId]?BZe(e.tabsByViewInstanceId[a.source.viewInstanceId]):null},l=e.tabsByViewInstanceId[a.source.viewInstanceId],c=Lge(e,r);if(c&&c.viewInstanceId!==a.source.viewInstanceId){const f=e.activeViewInstanceId===c.viewInstanceId?e:{...e,activeViewInstanceId:c.viewInstanceId};return vI(f,t,a,r,"saved_view_already_bound")}if(l!=null&&l.savedViewId&&l.savedViewId!==r){const f=e.activeViewInstanceId===l.viewInstanceId?e:{...e,activeViewInstanceId:l.viewInstanceId};return vI(f,t,a,r,"saved_view_binding_conflict")}if(l){let f=e,m=l.runtimeId;if(l.runtimeId===a.source.runtimeId){const h=f.runtimesById[a.source.runtimeId];f=k1(f,t,{id:h.id,viewInstanceId:h.viewInstanceId,targetKind:h.targetKind,target:h.target,host:{kind:"main",organizationId:t}})}else{const h=f.runtimesById[l.runtimeId];if(!h||h.viewInstanceId!==l.viewInstanceId||h.targetKind!==l.target.kind||H4(h.host))return vI(e,t,a,r,"existing_tab_runtime_unavailable");const p=f.runtimesById[a.source.runtimeId];if(f=k1(f,t,{id:p.id,viewInstanceId:p.viewInstanceId,targetKind:p.targetKind,target:p.target,host:{kind:"main",organizationId:t}}),((u=f.runtimesById[p.id])==null?void 0:u.host.kind)!=="main")return vI(e,t,a,r,"existing_tab_runtime_unavailable");m=p.id}return f={...f,activeViewInstanceId:l.viewInstanceId,tabsByViewInstanceId:l.savedViewId===r&&l.runtimeId===m?f.tabsByViewInstanceId:{...f.tabsByViewInstanceId,[l.viewInstanceId]:{...l,savedViewId:r,runtimeId:m,target:v8(a.source.target),originContextKey:a.source.originContextKey}}},Q8e(f,t,a,o)}const d=Dle(e,t,{viewInstanceId:a.source.viewInstanceId,runtimeId:a.source.runtimeId,target:a.source.target,originContextKey:a.source.originContextKey},r);return d.outcome!=="opened"?vI(d.organization,t,a,r,d.outcome==="binding_conflict"?"saved_view_binding_conflict":"main_host_claim_rejected"):Q8e(d.organization,t,a,o)}function QZe(e,t,n,r){const s=e.promotionsById[t];if(!s||s.status!=="detaching"||s.savedViewId!==n||s.source.sourceRevision!==r)return null;const a=e.runtimesById[s.source.runtimeId],o=e.tabsByViewInstanceId[s.source.viewInstanceId];return!a||a.viewInstanceId!==s.source.viewInstanceId||a.host.kind!=="main"||a.host.organizationId!==s.organizationId||!o||o.runtimeId!==a.id||o.savedViewId!==n?null:s}function RXt(e,t,n,r){const s=QZe(e,t,n,r);return s?Fq(e,s.id):e}function UZe(e,t,n,r,s,a){const o=QZe(e,n,r,s);if(!o)return e;const l=kN(e,t,o.source),c={...l.tabsByViewInstanceId};let d=l.tabOrder;return o.rollback.tab?c[o.source.viewInstanceId]=BZe(o.rollback.tab):(delete c[o.source.viewInstanceId],d=d.filter(u=>u!==o.source.viewInstanceId)),{...l,activeViewInstanceId:o.rollback.activeViewInstanceId,tabOrder:d,tabsByViewInstanceId:c,promotionsById:{...l.promotionsById,[n]:{id:o.id,organizationId:t,clientMutationId:o.clientMutationId,source:o.source,status:"claim_failed",savedViewId:r,error:a}}}}function LXt(e,t,n,r){const s=e.runtimesById[t];return!s||s.viewInstanceId!==n||r.viewInstanceId!==n||s.targetKind!==r.kind?e:{...e,runtimesById:{...e.runtimesById,[t]:{...s,target:v8(r)}}}}function zXt(e,t,n,r){const s=e.tabsByViewInstanceId[n],a=e.runtimesById[t];return!s||s.runtimeId!==t||s.target.kind!==r.kind||r.viewInstanceId!==n||!a||a.viewInstanceId!==n||a.targetKind!==r.kind?e:{...e,tabsByViewInstanceId:{...e.tabsByViewInstanceId,[n]:{...s,target:v8(r)}}}}function $Xt(e,t){switch(t.type){case"saved-tab/open":return Xl(e,t.organizationId,n=>Dle(n,t.organizationId,t.tab,t.savedViewId).organization);case"session-tab/create":return Xl(e,t.organizationId,n=>Dle(n,t.organizationId,t.tab,null).organization);case"tab/focus":return Xl(e,t.organizationId,n=>n.activeViewInstanceId===t.viewInstanceId||!n.tabsByViewInstanceId[t.viewInstanceId]?n:{...n,activeViewInstanceId:t.viewInstanceId});case"tab/reorder":return Xl(e,t.organizationId,n=>wXt(n,t.viewInstanceId,t.toIndex));case"tab/bind-saved-view":return Xl(e,t.organizationId,n=>bXt(n,t.viewInstanceId,t.savedViewId));case"tab/unbind-saved-view":return Xl(e,t.organizationId,n=>yXt(n,t.viewInstanceId,t.savedViewId));case"tab/close":return Xl(e,t.organizationId,n=>vXt(n,t.organizationId,t.viewInstanceId));case"tab/update-target":return Xl(e,t.organizationId,n=>zXt(n,t.runtimeId,t.viewInstanceId,t.target));case"runtime/admit":return Xl(e,t.organizationId,n=>k1(n,t.organizationId,t.runtime));case"runtime/set-host":return Xl(e,t.organizationId,n=>{const r=n.runtimesById[t.runtimeId];return r?k1(n,t.organizationId,{id:r.id,viewInstanceId:r.viewInstanceId,targetKind:r.targetKind,target:r.target,host:t.host}):n});case"runtime/update-target":return Xl(e,t.organizationId,n=>LXt(n,t.runtimeId,t.viewInstanceId,t.target));case"promotion/start":return Xl(e,t.organizationId,n=>SXt(n,t.organizationId,t.promotionId,t.source,t.clientMutationId));case"promotion/server-commit":return Xl(e,t.organizationId,n=>IXt(n,t.organizationId,t.promotionId,t.savedViewId,t.expectedSourceRevision));case"promotion/claim":return Xl(e,t.organizationId,n=>DXt(n,t.organizationId,t.promotionId,t.savedViewId,t.expectedSourceRevision));case"promotion/detach-succeed":return Xl(e,t.organizationId,n=>RXt(n,t.promotionId,t.savedViewId,t.expectedSourceRevision));case"promotion/detach-fail":return Xl(e,t.organizationId,n=>UZe(n,t.organizationId,t.promotionId,t.savedViewId,t.expectedSourceRevision,t.error));case"promotion/server-fail":return Xl(e,t.organizationId,n=>PXt(n,t.organizationId,t.promotionId,t.expectedSourceRevision,t.error));case"promotion/timeout":return Xl(e,t.organizationId,n=>TXt(n,t.organizationId,t.promotionId,t.expectedSourceRevision,t.error));case"promotion/retry":return Xl(e,t.organizationId,n=>jXt(n,t.organizationId,t.promotionId,t.expectedSourceRevision,t.nextSourceRevision));case"promotion/reconcile":return Xl(e,t.organizationId,n=>CXt(n,t.organizationId,t.promotionId,t.expectedSourceRevision,t.nextSourceRevision));case"promotion/claim-fail":return Xl(e,t.organizationId,n=>_Xt(n,t.organizationId,t.promotionId,t.savedViewId,t.expectedSourceRevision,t.error));case"promotion/claim-retry":return Xl(e,t.organizationId,n=>NXt(n,t.organizationId,t.promotionId,t.expectedSourceRevision,t.nextSourceRevision));case"promotion/discard":return Xl(e,t.organizationId,n=>MXt(n,t.promotionId,t.expectedSourceRevision));case"promotion/cancel-saved-view":return Xl(e,t.organizationId,n=>EXt(n,t.organizationId,t.promotionId,t.savedViewId,t.expectedSourceRevision))}}function qZe(){var n,r;const e=(n=document.activeElement)==null?void 0:n.closest("[data-runtime-id]");if(!e||e.hidden||e.hasAttribute("inert")||e.getAttribute("aria-hidden")==="true")return null;const t=e.dataset.runtimeId;return t?{runtimeId:t,owner:(r=e.dataset.ownerId)!=null&&r.startsWith("main:")?"main_workbench":"side_panel"}:null}function FXt(){var e;return((e=qZe())==null?void 0:e.runtimeId)??null}function BXt(){const e=er(),t=Ege(),n=mWe(),{openTarget:r}=Qm(),s=g8(),a=A.useRef({liveSurfaceRuntime:t,openTarget:r,organizationId:n==null?void 0:n.selectedOrganizationId,queryClient:e,toast:s});return a.current={liveSurfaceRuntime:t,openTarget:r,organizationId:n==null?void 0:n.selectedOrganizationId,queryClient:e,toast:s},A.useEffect(()=>{const o=_n();if(o!=null&&o.onOpenWebLink)return o.onOpenWebLink(l=>{const c=a.current;fXt({request:l,getSettings:()=>c.queryClient.fetchQuery({queryKey:U.instance.browserSettings,queryFn:()=>Va.getBrowser(),staleTime:0}),openBuiltIn:d=>{var h,p,x;if(l.sourceWebContentsId){(((h=c.liveSurfaceRuntime)==null?void 0:h.openTargetForGuest(l.sourceWebContentsId,d))??!1)||console.warn("[rudder-ui] ignored Browser popup without a live guest owner",l.sourceWebContentsId);return}const u=((p=c.organizationId)==null?void 0:p.trim())??"",f=!c.liveSurfaceRuntime||!u||c.liveSurfaceRuntime.getLiveBrowserCount(u)<xw;c.openTarget(d,{allowNewBrowserGuest:f}).admitted||(x=c.toast)==null||x.pushToast({title:"Browser tab limit reached",body:`Close a Browser tab to open another. Side Panel and Main share ${xw} live tabs.`,tone:"error"})},forceOpenExternal:d=>{var u;return((u=o.forceOpenExternal)==null?void 0:u.call(o,d))??o.openExternal(d)},resolveFavicon:XKt}).catch(d=>{console.warn("[rudder-ui] failed to route Desktop web link",d)})})},[]),A.useEffect(()=>{const o=_n();if(o!=null&&o.onBrowserShortcut)return o.onBrowserShortcut(l=>{if(!t)return;const c=l.sourceWebContentsId?null:FXt();if(l.action==="close_tab"){l.sourceWebContentsId?t.closeTargetForGuest(l.sourceWebContentsId):c&&t.closeTargetForRuntime(c);return}l.sourceWebContentsId?t.dispatchBrowserShortcutForGuest(l.sourceWebContentsId,l.action):c&&t.dispatchBrowserShortcutForRuntime(c,l.action)})},[t]),A.useEffect(()=>{var m;const o=(m=_n())==null?void 0:m.setBrowserSurfaceShortcutActive;if(!o||!t)return;let l=!1,c=!1,d;const u=()=>{var y;if(l)return;const h=qZe(),p=(h==null?void 0:h.runtimeId)??null,x=p?((y=t.getRuntimeTarget(p))==null?void 0:y.kind)==="browser":!1,b=h==null?void 0:h.owner;c===x&&b===d||(c=x,d=b,o(x,b).catch(()=>{}))},f=()=>queueMicrotask(u);return document.addEventListener("focusin",f,!0),document.addEventListener("focusout",f,!0),u(),()=>{l=!0,document.removeEventListener("focusin",f,!0),document.removeEventListener("focusout",f,!0),o(!1).catch(()=>{})}},[t]),null}const lX="https://docs.rudderhq.dev",QXt="https://docs.rudderhq.dev/zh/releases",VZe="https://discord.gg/ZcfWwPVkUz";function WZe({alt:e="",className:t,...n}){return i.jsx("img",{src:"/rudder-logo.png",alt:e,"aria-hidden":e?void 0:!0,className:q("inline-block shrink-0 rounded-full bg-white object-cover ring-1 ring-black/5 dark:ring-white/10",t),...n})}function UXt(){var c;const{locale:e,t}=es(),[n,r]=A.useState(null),s=A.useRef(null),a=e==="zh-CN"?((c=n==null?void 0:n.translations)==null?void 0:c["zh-CN"])??n:n;A.useEffect(()=>{const d=_n();if(!(d!=null&&d.getReleaseNotes))return;let u=!1;return d.getReleaseNotes().then(f=>{u||f.status!=="available"||(s.current=f.notes,r(f.notes))}).catch(()=>{}),()=>{u=!0}},[]);async function o(){var u,f;const d=s.current;s.current=null,r(null),d&&await((f=(u=_n())==null?void 0:u.markReleaseNotesShown)==null?void 0:f.call(u,d.version).catch(()=>{}))}async function l(){const d=e==="zh-CN"?QXt:lX,u=_n();if(u){await u.openExternal(d).catch(()=>{});return}window.open(d,"_blank","noopener,noreferrer")}return i.jsx(vs,{open:n!==null,onOpenChange:d=>{d||o()},children:i.jsxs(Ns,{className:"gap-0 overflow-hidden p-0 sm:max-w-[36rem]",showCloseButton:!1,children:[i.jsxs("div",{className:"flex items-start gap-3 border-b border-border/70 px-5 pb-4 pt-5",children:[i.jsx("span",{className:"mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-[var(--radius-md)] border border-border bg-background shadow-sm",children:i.jsx(WZe,{alt:"Rudder",className:"h-6 w-6 ring-0"})}),i.jsxs(di,{className:"min-w-0 gap-1 text-left",children:[i.jsx(Ps,{className:"text-base leading-6",children:(a==null?void 0:a.title)??t("desktopReleaseNotes.defaultTitle")}),i.jsx(ti,{className:"text-sm leading-5",children:t("desktopReleaseNotes.description")})]})]}),i.jsx("div",{className:"max-h-[min(62vh,34rem)] overflow-y-auto px-5 py-4",children:i.jsx("div",{className:"space-y-4",children:a==null?void 0:a.sections.map(d=>i.jsxs("section",{className:"space-y-2",children:[i.jsx("h2",{className:"text-sm font-semibold text-foreground",children:d.title}),i.jsx("ul",{className:"space-y-1.5 text-sm leading-5 text-muted-foreground",children:d.items.map(u=>i.jsxs("li",{className:"flex gap-2",children:[i.jsx("span",{className:"mt-2 h-1 w-1 shrink-0 rounded-full bg-muted-foreground/70"}),i.jsx("span",{children:u})]},u))})]},d.title))})}),i.jsxs(pa,{className:"border-t border-border/70 px-5 py-4 sm:justify-between",children:[i.jsxs(oe,{type:"button",variant:"outline",onClick:()=>void l(),children:[i.jsx(Ki,{className:"h-4 w-4"}),t("desktopReleaseNotes.docs")]}),i.jsx(oe,{type:"button",onClick:()=>void o(),children:t("desktopReleaseNotes.continue")})]})]})})}function qXt(e){const[t="",...n]=e.split(/\n{2,}/);return{body:t.trim(),runDetail:n.join(`
1706
1706
 
1707
1707
  `).trim()}}function VXt(){const[e,t]=A.useState(null),[n,r]=A.useState(!1),[s,a]=A.useState(null),o=A.useRef(null),l=A.useRef(0);A.useEffect(()=>{var h;const m=_n();if(m!=null&&m.onDeferredUpdatePrompt)return(h=m.setDeferredUpdatePromptReady)==null||h.call(m,!0),m.onDeferredUpdatePrompt(p=>{l.current+=1,o.current=p,t(p),r(!1),a(null)})},[]),A.useEffect(()=>()=>{var m,h;(h=(m=_n())==null?void 0:m.setDeferredUpdatePromptReady)==null||h.call(m,!1)},[]);async function c(m){var b;const h=o.current;if(!h)return;const p=l.current,x=_n();o.current=null,r(!0),a(m);try{await((b=x==null?void 0:x.respondDeferredUpdatePrompt)==null?void 0:b.call(x,h.promptId,m).catch(()=>{}))}finally{l.current===p&&(t(null),r(!1),a(null))}}const{body:d,runDetail:u}=qXt((e==null?void 0:e.detail)??""),f=(m,h)=>i.jsxs(i.Fragment,{children:[s===m?i.jsx(fn,{className:"mr-1.5 h-4 w-4 animate-spin","aria-hidden":"true"}):null,i.jsx("span",{children:h})]});return i.jsx(vs,{open:e!==null,onOpenChange:m=>{m||c("cancel")},children:i.jsxs(Ns,{"aria-busy":n,className:"gap-0 p-0 sm:max-w-[34rem]",showCloseButton:!1,children:[i.jsxs("div",{className:"flex items-start gap-3 px-5 pb-4 pt-5",children:[i.jsx("span",{className:"mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-[var(--radius-md)] border border-amber-500/30 bg-amber-500/12 text-amber-600 dark:text-amber-300",children:i.jsx(Dm,{className:"h-5 w-5"})}),i.jsxs(di,{className:"min-w-0 gap-2 text-left",children:[i.jsx(Ps,{className:"text-base leading-6",children:e==null?void 0:e.message}),d?i.jsx(ti,{className:"text-sm leading-5",children:d}):null]})]}),u?i.jsx("div",{className:"mx-5 rounded-[var(--radius-md)] border border-border/70 bg-muted/35 px-3 py-2.5",children:i.jsx("p",{className:"whitespace-pre-wrap break-words text-xs font-medium leading-5 text-foreground",children:u})}):null,i.jsxs(pa,{className:"grid grid-cols-1 gap-2 px-5 pb-5 pt-4 sm:grid-cols-2 sm:justify-stretch",children:[i.jsx(oe,{type:"button",variant:"outline",className:"h-auto min-h-10 min-w-0 whitespace-normal leading-5",disabled:n,"aria-busy":s==="cancel",onClick:()=>void c("cancel"),children:f("cancel",(e==null?void 0:e.cancelLabel)??"Cancel")}),i.jsx(oe,{type:"button",variant:"outline",className:"h-auto min-h-10 min-w-0 whitespace-normal leading-5",disabled:n,"aria-busy":s==="force",onClick:()=>void c("force"),children:f("force",(e==null?void 0:e.forceLabel)??"Stop Runs and Update Now")}),i.jsx(oe,{type:"button",className:"h-auto min-h-10 min-w-0 whitespace-normal leading-5 sm:col-span-2",disabled:n,"aria-busy":s==="wait",onClick:()=>void c("wait"),children:f("wait",(e==null?void 0:e.confirmLabel)??"Download and Update When Idle")})]})]})})}const HZe=A.createContext(null),WXt={progress:null,dismissProgress:()=>{}};function HXt({children:e}){const[t,n]=A.useState(null),[r,s]=A.useState(null);A.useEffect(()=>{var d,u;const l=_n();if(!l)return;function c(f){n(f),f.phase==="complete"&&window.setTimeout(()=>{n(m=>(m==null?void 0:m.updateId)===f.updateId&&m.phase==="complete"?null:m)},4e3)}return(d=l.getUpdateProgress)==null||d.call(l).then(f=>{f&&c(f)}).catch(()=>{}),(u=l.onUpdateProgress)==null?void 0:u.call(l,f=>{c(f),s(m=>m===f.updateId&&f.phase!=="failed"?m:null)})},[]);const a=(t==null?void 0:t.updateId)===r?null:t,o=A.useMemo(()=>({progress:a,dismissProgress:()=>{t&&s(t.updateId)}}),[t,a]);return i.jsx(HZe.Provider,{value:o,children:e})}function KZe(){return A.useContext(HZe)??WXt}const U8e="https://github.com/Undertone0809/rudder/releases",q8e={starting:"about.updates.progress.phase.starting",preparing_runtime:"about.updates.progress.phase.preparing_runtime",resolving_release:"about.updates.progress.phase.resolving_release",downloading_checksums:"about.updates.progress.phase.downloading_checksums",downloading_asset:"about.updates.progress.phase.downloading_asset",verifying_checksum:"about.updates.progress.phase.verifying_checksum",ready_to_install:"about.updates.progress.phase.ready_to_install",waiting_for_active_runs:"about.updates.progress.phase.waiting_for_active_runs",preparing_restart:"about.updates.progress.phase.preparing_restart",closing:"about.updates.progress.phase.closing",complete:"about.updates.progress.phase.complete",failed:"about.updates.progress.phase.failed"};function V8e(e){if(typeof e!="number"||!Number.isFinite(e))return null;const t=["B","KB","MB","GB"];let n=Math.max(0,e),r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return r===0?`${Math.round(n)} ${t[r]}`:`${n.toFixed(1)} ${t[r]}`}function KXt(e){return e==="failed"?"failed":e==="ready_to_install"||e==="closing"||e==="complete"?"ready":"active"}function ZXt(){const{progress:e,dismissProgress:t}=KZe(),{t:n}=es(),[r,s]=A.useState(null),[a,o]=A.useState(null);if(A.useEffect(()=>{(!e||["preparing_restart","closing","complete","failed"].includes(e.phase))&&o(null)},[e==null?void 0:e.phase,e==null?void 0:e.updateId]),!e)return null;const l=e,c=KXt(l.phase),d=V8e(l.transferredBytes),u=V8e(l.totalBytes),f=typeof l.percent=="number"?Math.max(0,Math.min(100,l.percent)):null,m=f!==null,h=f!==null?`${f}%`:d?u?`${d} / ${u}`:d:null,p=a===l.updateId,x=l.phase!=="failed"&&l.phase!=="complete"&&(p||l.phase==="preparing_restart"||l.phase==="closing"),b=(c==="active"||x)&&!m,y=l.blockers??[],w=l.phase==="waiting_for_active_runs"&&y.length>0;async function k(){const C=_n();C&&(s(null),await C.installUpdate(l.version))}async function S(C={}){const I=_n();if(s(null),!(I!=null&&I.applyUpdate)){s(n("about.updates.installUnavailable"));return}o(l.updateId);try{const N=await I.applyUpdate(l.updateId,C.force?{force:!0}:void 0);N.status!=="started"&&(s(N.message||n("about.updates.installFailed")),o(null))}catch(N){s(N instanceof Error?N.message:n("about.updates.installFailed")),o(null)}}async function j(){const C=_n();C?await C.openExternal(U8e):window.open(U8e,"_blank","noopener,noreferrer")}return i.jsx("aside",{"aria-live":"polite","aria-busy":x,className:"pointer-events-none fixed bottom-[calc(1rem+5.75rem)] right-4 z-[1001] w-[min(calc(100vw-2rem),20rem)] md:bottom-4","data-testid":"desktop-update-status-card","data-update-applying":x?"true":"false","data-update-phase":l.phase,children:i.jsx("div",{className:q("pointer-events-auto overflow-hidden rounded-[var(--radius-md)] border bg-popover text-popover-foreground shadow-[0_16px_40px_rgba(15,23,42,0.16)] backdrop-blur-xl dark:shadow-[0_16px_44px_rgba(0,0,0,0.45)]",c==="failed"?"border-destructive/35":"border-border/70"),children:i.jsxs("div",{className:"flex items-start gap-3 px-3.5 py-3",children:[i.jsx("span",{className:q("flex h-7 w-7 shrink-0 items-center justify-center rounded-[var(--radius-sm)] bg-muted text-muted-foreground",c==="failed"&&"bg-destructive/10 text-destructive",c==="ready"&&"bg-emerald-500/10 text-emerald-700 dark:text-emerald-300"),children:c==="failed"?i.jsx(Dm,{className:"h-4 w-4"}):x?i.jsx(fn,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}):c==="ready"?i.jsx(Id,{className:"h-4 w-4"}):i.jsx(Rf,{className:"h-4 w-4"})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-start justify-between gap-2",children:[i.jsx("p",{className:"text-sm font-semibold leading-5",children:c==="failed"?n("about.updates.progress.failedTitle"):l.phase==="ready_to_install"?n("about.updates.progress.readyTitle"):l.phase==="complete"?n("about.updates.progress.completeTitle"):n("about.updates.progress.title",{version:l.version.startsWith("v")?l.version:`v${l.version}`})}),h?i.jsx("span",{className:"shrink-0 text-xs tabular-nums text-muted-foreground",children:h}):null]}),i.jsx("p",{className:"mt-0.5 whitespace-pre-wrap break-words text-xs leading-4 text-muted-foreground",children:l.error??l.message??n(q8e[l.phase])}),w?i.jsxs("div",{className:"mt-2 rounded-[var(--radius-sm)] border border-amber-500/25 bg-amber-500/8 px-2.5 py-2",children:[i.jsx("p",{className:"text-[11px] font-semibold text-foreground",children:n("about.updates.progress.blockersTitle")}),i.jsxs("div",{className:"mt-1 grid gap-0.5",children:[y.slice(0,3).map(C=>i.jsx("p",{className:"break-words text-[11px] leading-4 text-muted-foreground",children:n("about.updates.progress.blockerRun",{organization:C.organizationName,agent:C.agentName,runId:C.runId.slice(0,8)})},C.runId)),y.length>3?i.jsxs("p",{className:"text-[11px] leading-4 text-muted-foreground",children:["+",y.length-3]}):null]}),i.jsx("p",{className:"mt-1 text-[11px] leading-4 text-muted-foreground",children:n("about.updates.progress.automaticApply")})]}):null,r?i.jsx("p",{className:"mt-2 rounded-[var(--radius-sm)] border border-destructive/25 bg-destructive/8 px-2.5 py-2 text-xs leading-4 text-destructive",children:r}):null,m?i.jsx("div",{className:"mt-2 h-1.5 overflow-hidden rounded-full bg-muted",role:"progressbar","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":f,children:i.jsx("div",{className:q("h-full rounded-full bg-emerald-700 transition-[width] duration-300",c==="failed"&&"bg-destructive"),style:{width:`${f}%`}})}):b?i.jsx("div",{className:"mt-2 h-1.5 overflow-hidden rounded-full bg-muted",role:"progressbar","aria-label":n(q8e[l.phase]),children:i.jsx("div",{className:"h-full w-2/5 rounded-full bg-emerald-700/70 animate-pulse"})}):null,l.phase==="ready_to_install"&&l.automaticApply!==!0?i.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:i.jsxs(oe,{type:"button",size:"sm",className:"h-8 px-3 text-xs",disabled:p,"aria-busy":p,onClick:()=>void S(),children:[p?i.jsx(fn,{className:"mr-1.5 h-3.5 w-3.5 animate-spin","aria-hidden":"true"}):null,i.jsx("span",{children:n(p?"about.updates.installing":"about.updates.progress.restartToUpdate")})]})}):null,w?i.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:i.jsxs(oe,{type:"button",variant:"outline",size:"sm",className:"h-8 px-3 text-xs",disabled:p,"aria-busy":p,onClick:()=>void S({force:!0}),children:[p?i.jsx(fn,{className:"mr-1.5 h-3.5 w-3.5 animate-spin","aria-hidden":"true"}):null,i.jsx("span",{children:n(p?"about.updates.installing":"about.updates.progress.forceRestartToUpdate")})]})}):null,c==="failed"?i.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[i.jsx(oe,{type:"button",size:"sm",className:"h-8 px-3 text-xs",onClick:()=>void k(),children:n("about.updates.progress.retry")}),i.jsx(oe,{type:"button",variant:"outline",size:"sm",className:"h-8 px-3 text-xs",onClick:()=>void j(),children:n("about.updates.progress.openReleases")})]}):null]}),i.jsx("button",{type:"button","aria-label":n("about.updates.progress.dismiss"),onClick:t,className:"-mr-1 -mt-1 shrink-0 rounded-[var(--radius-sm)] p-1 text-muted-foreground hover:bg-muted hover:text-foreground",children:i.jsx(Jr,{className:"h-3.5 w-3.5"})})]})})})}const fM=100,W8e=200,H8e=1e3,xo={overview:e=>Qe.get(`/orgs/${e}/agent-runs/overview`),list:(e,t,n=fM,r={})=>{const s=new URLSearchParams;t&&s.set("agentId",t),n!==null&&s.set("limit",String(n)),r.startDate&&s.set("startDate",r.startDate),r.endDate&&s.set("endDate",r.endDate),r.goalId&&s.set("goalId",r.goalId);const a=s.toString();return Qe.get(`/orgs/${e}/agent-runs${a?`?${a}`:""}`)},get:e=>Qe.get(`/agent-runs/${e}`),events:(e,t=0,n=200)=>Qe.get(`/agent-runs/${e}/events?afterSeq=${encodeURIComponent(String(t))}&limit=${encodeURIComponent(String(n))}`),allEvents:async e=>{var r;const t=[];let n=0;for(;;){const s=await Qe.get(`/agent-runs/${e}/events?afterSeq=${encodeURIComponent(String(n))}&limit=${H8e}`);if(t.push(...s),s.length<H8e)return t;const a=(r=s[s.length-1])==null?void 0:r.seq;if(typeof a!="number"||a<=n)return t;n=a}},log:(e,t=0,n=256e3)=>Qe.get(`/agent-runs/${e}/log?offset=${encodeURIComponent(String(t))}&limitBytes=${encodeURIComponent(String(n))}`,{cache:"no-store"}),workspaceOperations:e=>Qe.get(`/agent-runs/${e}/workspace-operations`),workspaceOperationLog:(e,t=0,n=256e3)=>Qe.get(`/workspace-operations/${e}/log?offset=${encodeURIComponent(String(t))}&limitBytes=${encodeURIComponent(String(n))}`,{cache:"no-store"}),cancel:e=>Qe.post(`/agent-runs/${e}/cancel`,{}),retry:e=>Qe.post(`/agent-runs/${e}/retry`,{}),liveRunsForIssue:e=>Qe.get(`/issues/${e}/live-runs`),activeRunForIssue:e=>Qe.get(`/issues/${e}/active-run`),liveRunsForCompany:(e,t)=>Qe.get(`/orgs/${e}/live-runs${t?`?minCount=${t}`:""}`),liveRunsForGoal:(e,t)=>Qe.get(`/orgs/${e}/live-runs?goalId=${encodeURIComponent(t)}`)},ZZe=A.createContext(null);function XXt({children:e}){const[t,n]=A.useState(!1),[r,s]=A.useState({}),[a,o]=A.useState(!1),[l,c]=A.useState(!1),[d,u]=A.useState({}),[f,m]=A.useState(!1),[h,p]=A.useState(!1),[x,b]=A.useState({}),[y,w]=A.useState(!1),[k,S]=A.useState({}),[j,C]=A.useState(null),[I,N]=A.useState(!1),[M,E]=A.useState(null),[_,z]=A.useState(!1),[T,$]=A.useState(""),B=A.useRef(null),F=A.useRef(null),W=A.useRef(null),Y=A.useRef(null),G=A.useRef(0),V=A.useCallback((_e={})=>{s(_e),n(!0)},[]),L=A.useCallback(()=>{n(!1),s({})},[]),R=A.useCallback(()=>{o(!0)},[]),D=A.useCallback(()=>{o(!1)},[]),X=A.useCallback((_e={})=>{u(_e),c(!0)},[]),ee=A.useCallback(()=>{c(!1),u({})},[]),se=A.useCallback(()=>{m(!0)},[]),ne=A.useCallback(()=>{m(!1)},[]),le=A.useCallback((_e={})=>{b(_e),p(!0)},[]),ie=A.useCallback(()=>{p(!1),b({})},[]),re=A.useCallback((_e={})=>{S(_e),w(!0)},[]),de=A.useCallback(()=>{w(!1),S({})},[]),Be=A.useCallback(_e=>new Promise(Ie=>{G.current+=1;const $e={id:G.current,resolve:Ie,returnFocus:document.activeElement instanceof HTMLElement?document.activeElement:null,..._e};B.current=$e,C($e),N(!0)}),[]),ae=A.useCallback(_e=>new Promise(Ie=>{G.current+=1;const $e={id:G.current,resolve:Ie,returnFocus:document.activeElement instanceof HTMLElement?document.activeElement:null,..._e};F.current=$e,E($e),z(!0)}),[]),Ee=A.useCallback(_e=>{const Ie=B.current;Ie&&(B.current=null,W.current={request:Ie,confirmed:_e},Ie.resolve(_e),N(!1))},[]),he=A.useCallback(_e=>{const Ie=F.current;Ie&&(F.current=null,Y.current=Ie,Ie.resolve(_e),z(!1))},[]);return A.useEffect(()=>{$((M==null?void 0:M.defaultValue)??"")},[M==null?void 0:M.id,M==null?void 0:M.defaultValue]),i.jsxs(ZZe.Provider,{value:{newIssueOpen:t,newIssueDefaults:r,openNewIssue:V,closeNewIssue:L,newProjectOpen:a,openNewProject:R,closeNewProject:D,newGoalOpen:l,newGoalDefaults:d,openNewGoal:X,closeNewGoal:ee,newAgentOpen:f,openNewAgent:se,closeNewAgent:ne,onboardingOpen:h,onboardingOptions:x,openOnboarding:le,closeOnboarding:ie,productTourOpen:y,productTourOptions:k,openProductTour:re,closeProductTour:de,confirm:Be,promptText:ae},children:[e,i.jsx(vs,{open:I,onOpenChange:_e=>{_e||Ee(!1)},children:i.jsxs(Ns,{className:"sm:max-w-md",showCloseButton:!1,onCloseAutoFocus:_e=>{var ce;_e.preventDefault();const Ie=W.current;if(!Ie||(W.current=null,C(Oe=>(Oe==null?void 0:Oe.id)===Ie.request.id?null:Oe),B.current))return;const{restoreFocus:$e}=Ie.request;if($e){$e(Ie.confirmed);return}(ce=Ie.request.returnFocus)!=null&&ce.isConnected&&Ie.request.returnFocus.focus({preventScroll:!0})},children:[i.jsxs(di,{children:[i.jsx(Ps,{className:"text-base leading-6",children:j==null?void 0:j.title}),j!=null&&j.description?i.jsx(ti,{children:j.description}):null]}),i.jsxs(pa,{children:[i.jsx(oe,{type:"button",variant:"outline",onClick:()=>Ee(!1),children:(j==null?void 0:j.cancelLabel)??"Cancel"}),i.jsx(oe,{type:"button",variant:(j==null?void 0:j.tone)==="destructive"?"destructive":"default",onClick:()=>Ee(!0),children:(j==null?void 0:j.confirmLabel)??"Confirm"})]})]})}),i.jsx(vs,{open:_,onOpenChange:_e=>{_e||he(null)},children:i.jsx(Ns,{className:"sm:max-w-md",showCloseButton:!1,onCloseAutoFocus:_e=>{var $e;_e.preventDefault();const Ie=Y.current;Ie&&(Y.current=null,E(ce=>(ce==null?void 0:ce.id)===Ie.id?null:ce),!F.current&&($e=Ie.returnFocus)!=null&&$e.isConnected&&Ie.returnFocus.focus({preventScroll:!0}))},children:i.jsxs("form",{className:"space-y-4",onSubmit:_e=>{_e.preventDefault(),he(T.trim())},children:[i.jsxs(di,{children:[i.jsx(Ps,{className:"text-base leading-6",children:M==null?void 0:M.title}),M!=null&&M.description?i.jsx(ti,{children:M.description}):null]}),i.jsxs("div",{className:"space-y-1.5",children:[M!=null&&M.label?i.jsx(mo,{htmlFor:"app-prompt-text-input",children:M.label}):null,i.jsx(nr,{id:"app-prompt-text-input",autoFocus:!0,value:T,placeholder:M==null?void 0:M.placeholder,onChange:_e=>$(_e.target.value)})]}),i.jsxs(pa,{children:[i.jsx(oe,{type:"button",variant:"outline",onClick:()=>he(null),children:(M==null?void 0:M.cancelLabel)??"Cancel"}),i.jsx(oe,{type:"submit",children:(M==null?void 0:M.confirmLabel)??"Save"})]})]})})})]})}function Bs(){const e=A.useContext(ZZe);if(!e)throw new Error("useDialog must be used within DialogProvider");return e}const GXt={get:e=>Qe.get(`/orgs/${e}/sidebar-badges`,{cache:"no-store"})},YXt=100,JXt=new Set(["failed","timed_out"]),Rle=new Set(["pending"]),XZe="rudder:inbox:dismissed",eGt="rudder:inbox:last-tab";function P7(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function tGt(e){if(!e)return null;const t=[e.chatAttention>0?P7(e.chatAttention,"chat thread"):null,e.unreadTouchedIssues>0?P7(e.unreadTouchedIssues,"issue update"):null,e.approvals>0?P7(e.approvals,"approval"):null,e.failedRuns>0?P7(e.failedRuns,"failed run"):null,e.joinRequests>0?P7(e.joinRequests,"join request"):null,e.alerts>0?P7(e.alerts,"system alert"):null].filter(n=>!!n);return t.length>0?t.join(", "):null}function K8e(){try{const e=localStorage.getItem(XZe);return e?new Set(JSON.parse(e)):new Set}catch{return new Set}}function nGt(e){try{localStorage.setItem(XZe,JSON.stringify([...e]))}catch{}}function rGt(e){try{localStorage.setItem(eGt,e)}catch{}}function sGt(e){const t=[...e].sort((r,s)=>new Date(s.createdAt).getTime()-new Date(r.createdAt).getTime()),n=new Map;for(const r of t)n.has(r.agentId)||n.set(r.agentId,r);return Array.from(n.values()).filter(r=>JXt.has(r.status))}function mu(e){if(!e)return 0;const t=new Date(e).getTime();return Number.isFinite(t)?t:0}function Lle(e){const t=mu(e.lastExternalCommentAt);if(t>0)return t;const n=mu(e.updatedAt),r=mu(e.myLastTouchAt);return r>0&&n<=r?0:n}function GZe(e,t){const n=Lle(t)-Lle(e);return n!==0?n:mu(t.updatedAt)-mu(e.updatedAt)}function iGt(e){return[...e].sort(GZe).slice(0,YXt)}function aGt(e,t,n){const r=[...e].sort((s,a)=>mu(a.updatedAt)-mu(s.updatedAt));return t==="recent"?r:t==="unread"?r.filter(s=>Rle.has(s.status)):n==="all"?r:r.filter(s=>{const a=Rle.has(s.status);return n==="actionable"?a:!a})}function cte(e){const t=mu(e.updatedAt);return t>0?t:mu(e.createdAt)}function oGt({issues:e,approvals:t,chats:n=[],failedRuns:r=[],agentIssueRequests:s=[]}){return[...e.map(a=>({kind:"issue",timestamp:Lle(a),issue:a})),...t.map(a=>({kind:"approval",timestamp:cte(a),approval:a})),...n.map(a=>({kind:"chat",timestamp:mu(a.lastMessageAt??a.updatedAt),conversation:a})),...r.map(a=>({kind:"failed_run",timestamp:mu(a.createdAt),run:a})),...s.map(a=>({kind:"agent_issue_request",timestamp:mu(a.updatedAt??a.createdAt),request:a}))].sort((a,o)=>{const l=o.timestamp-a.timestamp;return l!==0?l:a.kind==="issue"&&o.kind==="issue"?GZe(a.issue,o.issue):a.kind==="approval"&&o.kind==="approval"?cte(o.approval)-cte(a.approval):a.kind==="chat"&&o.kind==="chat"?mu(o.conversation.lastMessageAt??o.conversation.updatedAt)-mu(a.conversation.lastMessageAt??a.conversation.updatedAt):a.kind==="agent_issue_request"&&o.kind==="agent_issue_request"?mu(o.request.updatedAt??o.request.createdAt)-mu(a.request.updatedAt??a.request.createdAt):a.kind==="approval"?-1:1})}function lGt({tab:e,hasItems:t,showOnRecent:n,showOnUnread:r,showOnAll:s}){return t?e==="recent"?n:e==="unread"?r:s:!1}function dte(e){return(e==null?void 0:e.replace(/(^|\n)\s{0,3}#{1,6}\s+/g,"$1").replace(/[*_`~]+/g,"").replace(/\s+/g," ").trim())||null}function Z8e(e,t){return e.length<=t?e:`${e.slice(0,Math.max(0,t-1)).trimEnd()}...`}function cGt(e,t){const n=mu(e.latestActivityAt),r=mu(t.latestActivityAt);return n!==r?r-n:e.title.localeCompare(t.title)}function dGt({unreadCount:e,badgeCounts:t,messengerThreads:n}){const r=Math.max(0,Math.floor(e)),s=tGt(t),o={title:"New inbox activity",body:s?r===1?`You have 1 inbox item needing attention: ${s}.`:`You have ${r} inbox items needing attention: ${s}.`:r===1?"You have 1 unread inbox item.":`You have ${r} unread inbox items.`},l=[...n].filter(m=>(m.unreadCount??0)>0).sort(cGt)[0];if(!l)return o;const c=dte(l.title)??o.title,d=dte(l.preview),u=dte(l.subtitle),f=d&&d!==c?d:u&&u!==c?u:o.body;return{title:Z8e(c,80),body:Z8e(f,160)}}const uGt=10,fGt={inbox:0,approvals:0,failedRuns:0,joinRequests:0,unreadTouchedIssues:0,chatAttention:0,alerts:0};function mGt(){const[e,t]=A.useState(K8e);return A.useEffect(()=>{const r=s=>{s.key==="rudder:inbox:dismissed"&&t(K8e())};return window.addEventListener("storage",r),()=>window.removeEventListener("storage",r)},[]),{dismissed:e,dismiss:r=>{t(s=>{const a=new Set(s);return a.add(r),nGt(a),a})}}}function zge(e){const{data:t}=Ve({queryKey:U.messenger.threadPreview(e??"__none__"),queryFn:()=>_s.listThreadPage(e,{limit:uGt}),enabled:!!e}),n=(t==null?void 0:t.items)??[],r=Ve({queryKey:U.sidebarBadges(e??"__none__"),queryFn:()=>GXt.get(e),enabled:!!e});return A.useMemo(()=>{const s=r.data??fGt;return{...s,isReady:!e||r.isSuccess,notificationContent:dGt({unreadCount:s.inbox,badgeCounts:s,messengerThreads:n})}},[n,e,r.data,r.isSuccess])}const AGt="rudder.companyOrder";function hGt(){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(AGt);if(e)return JSON.parse(e)}catch{}return[]}function YZe(e){const t=hGt();if(t.length===0)return e;const n=new Map(e.map(s=>[s.id,s])),r=[];for(const s of t){const a=n.get(s);a&&(r.push(a),n.delete(s))}for(const s of n.values())r.push(s);return r}const Bq="settingsOverlayBackgroundPath",$ge="rudder.settingsOverlayBackgroundPath";function Qq(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function mM(e){const t=Qo(e);return t.startsWith("/instance/settings")||t.startsWith("/organization/settings")}function ON(e){const t=Qq(e),n=t==null?void 0:t[Bq];return typeof n=="string"&&n.length>0?n:null}function cX(e){const t=ON(e.state);if(t)return Qq(e.state)??{[Bq]:t};const n=`${e.pathname}${e.search}${e.hash}`;return mM(n)?void 0:{...Qq(e.state)??{},[Bq]:n}}function dX(e){const t=ON(e);if(t)return Qq(e)??{[Bq]:t}}function Fge(e){if(!(typeof window>"u"||mM(e)))try{window.sessionStorage.setItem($ge,e)}catch{}}function Bge(){if(typeof window>"u")return null;try{const e=window.sessionStorage.getItem($ge);return e&&!mM(e)?e:null}catch{return null}}function AM(){if(!(typeof window>"u"))try{window.sessionStorage.removeItem($ge)}catch{}}const JZe=A.createContext(null),ute=768;function pGt({children:e}){const[t,n]=A.useState(()=>window.innerWidth<ute),[r,s]=A.useState(()=>window.innerWidth),[a,o]=A.useState(()=>window.innerWidth>=ute),[l,c]=A.useState(!1);A.useEffect(()=>{const f=()=>s(window.innerWidth);return window.addEventListener("resize",f),()=>window.removeEventListener("resize",f)},[]),A.useEffect(()=>{const f=window.matchMedia(`(max-width: ${ute-1}px)`),m=h=>{n(h.matches),o(!h.matches)};return f.addEventListener("change",m),()=>f.removeEventListener("change",m)},[]);const d=A.useCallback(()=>o(f=>!f),[]),u=A.useCallback(()=>{c(!0),o(!0)},[]);return i.jsx(JZe.Provider,{value:{sidebarOpen:a,setSidebarOpen:o,contextSidebarExpandedByUser:l,setContextSidebarExpandedByUser:c,openSidebarByUser:u,toggleSidebar:d,isMobile:t,viewportWidth:r},children:e})}function Bc(){const e=A.useContext(JZe);if(!e)throw new Error("useSidebar must be used within SidebarProvider");return e}const gGt=[[0,8,2,10],[12,4,14,6],[3,11,1,9],[15,7,13,5]];function xGt(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return t>>>0}function bGt(e){let t=e>>>0;return()=>{t=t+1831565813>>>0;let n=Math.imul(t^t>>>15,1|t);return n^=n+Math.imul(n^n>>>7,61|n),((n^n>>>14)>>>0)/4294967296}}function X8e(e,t,n){const r=(e%360+360)%360,s=Math.max(0,Math.min(100,t))/100,a=Math.max(0,Math.min(100,n))/100,o=(1-Math.abs(2*a-1))*s,l=o*(1-Math.abs(r/60%2-1)),c=a-o/2;let d=0,u=0,f=0;return r<60?(d=o,u=l):r<120?(d=l,u=o):r<180?(u=o,f=l):r<240?(u=l,f=o):r<300?(d=l,f=o):(d=o,f=l),[Math.round((d+c)*255),Math.round((u+c)*255),Math.round((f+c)*255)]}function yGt(e){const t=parseInt(e.slice(1,3),16)/255,n=parseInt(e.slice(3,5),16)/255,r=parseInt(e.slice(5,7),16)/255,s=Math.max(t,n,r),a=Math.min(t,n,r),o=s-a;if(o===0)return 0;let l=0;return s===t?l=(n-r)/o%6:s===n?l=(r-t)/o+2:l=(t-n)/o+4,(l*60+360)%360}function vGt(e,t,n=22,r=2){if(typeof document>"u")return"";const s=document.createElement("canvas");s.width=n*r,s.height=n*r;const a=s.getContext("2d");if(!a)return"";const o=bGt(xGt(e)),l=t?yGt(t):Math.floor(o()*360),[c,d,u]=X8e(l,54+Math.floor(o()*14),36+Math.floor(o()*12)),[f,m,h]=X8e(l+(o()>.5?10:-10),86+Math.floor(o()*10),82+Math.floor(o()*10)),p=(n-1)/2,x=Math.max(p,1),b=o()*Math.PI*2,y=Math.cos(b),w=Math.sin(b),k=Math.abs(y*x)+Math.abs(w*x),S=.34+o()*.12,j=.33+o()*.12,C=o()*Math.PI*2,I=o()*Math.PI*2;a.fillStyle=`rgb(${c} ${d} ${u})`,a.fillRect(0,0,s.width,s.height),a.fillStyle=`rgb(${f} ${m} ${h})`;const N=r*.46;for(let M=0;M<n;M++){const E=M-p;for(let _=0;_<n;_++){const z=_-p,$=((z*y+E*w)/k+1)*.5,B=Math.sin((z+E)*S+C)*.5+.5,F=Math.sin((z-E)*j+I)*.5+.5,W=B*.5+F*.5,Y=Math.max(0,Math.min(1,$+(W-.5)*.22)),G=Math.max(0,Math.min(15,Math.floor(Y*16))),V=gGt[M&3][_&3];if(G<=V)continue;const L=_*r+r/2,R=M*r+r/2;a.beginPath(),a.arc(L,R,N,0,Math.PI*2),a.fill()}}return s.toDataURL("image/png")}function IT({organizationName:e,logoUrl:t,brandColor:n,className:r}){const s=e.trim().charAt(0).toUpperCase()||"?",[a,o]=A.useState(!1),l=!a&&typeof t=="string"&&t.trim().length>0?t:null;A.useEffect(()=>{o(!1)},[t]);const c=A.useMemo(()=>vGt(e.trim().toLowerCase(),n),[e,n]);return i.jsxs("div",{className:q("relative flex items-center justify-center w-11 h-11 text-base font-semibold text-white overflow-hidden",r),children:[l?i.jsx("img",{src:l,alt:`${e} logo`,onError:()=>o(!0),className:"absolute inset-0 h-full w-full object-cover"}):c?i.jsx("img",{src:c,alt:"","aria-hidden":"true",className:"absolute inset-0 h-full w-full",style:{imageRendering:"pixelated"}}):i.jsx("div",{className:"absolute inset-0 bg-muted"}),!l&&i.jsx("span",{className:"relative z-10 drop-shadow-[0_1px_2px_rgba(0,0,0,0.65)]",children:s})]})}function Qge({compact:e=!1}){const{organizations:t,selectedOrganization:n,setSelectedOrganizationId:r}=Mr(),{openOnboarding:s}=Bs(),{isMobile:a,setSidebarOpen:o}=Bc(),l=is(),c=Kr(),d=Ir(),u=cX(d),f=YZe(t.filter(w=>w.status!=="archived"));function m(w){return{"--motion-org-menu-item-index":w,"--motion-org-menu-item-delay":`${Math.min(54+w*18,180)}ms`}}function h(){a&&o(!1)}function p(w){r(w),h()}function x(){s(),h()}function b(){Fge(`${d.pathname}${d.search}${d.hash}`),c("/organization/settings",u?{state:u}:void 0),h()}const y=e?i.jsx(oe,{variant:"ghost",className:"h-10 w-10 rounded-full p-0 hover:bg-[color:var(--surface-active)]","aria-label":"Organization menu",children:n?i.jsx(IT,{organizationName:n.name,logoUrl:n.logoUrl,brandColor:n.brandColor,className:"h-9 w-9 shrink-0 rounded-full text-sm"}):i.jsx("span",{className:"text-xs font-semibold text-muted-foreground",children:"--"})}):i.jsxs(oe,{variant:"ghost",className:"h-auto w-full justify-between rounded-[var(--radius-md)] px-2.5 py-2 text-left hover:bg-[color:var(--surface-active)]",children:[i.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n?i.jsx(IT,{organizationName:n.name,logoUrl:n.logoUrl,brandColor:n.brandColor,className:"h-9 w-9 shrink-0 rounded-xl text-sm"}):null,i.jsxs("div",{className:"min-w-0",children:[i.jsx("div",{className:"text-[10px] font-medium tracking-[0.08em] text-muted-foreground/75",children:"Organization"}),i.jsx("span",{className:"mt-0.5 block truncate text-sm font-semibold text-foreground",title:(n==null?void 0:n.name)??"Select organization",children:(n==null?void 0:n.name)??"Select organization"})]})]}),i.jsx($vt,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"})]});return i.jsxs(ui,{children:[i.jsx(fi,{asChild:!0,children:y}),i.jsx(mi,{align:"start",className:"surface-overlay motion-organization-menu-pop w-[340px] overflow-hidden p-0 text-foreground",children:i.jsxs("div",{ref:l,className:"scrollbar-auto-hide max-h-(--radix-dropdown-menu-content-available-height) overflow-y-auto p-1",children:[i.jsx(dM,{"data-org-menu-item":!0,style:m(0),children:"Organizations"}),i.jsx(hl,{}),f.map((w,k)=>i.jsxs(Ht,{onClick:()=>p(w.id),"data-org-menu-item":!0,style:m(k+1),className:q("gap-3 rounded-[calc(var(--radius-md)-2px)] px-2.5 py-2",w.id===(n==null?void 0:n.id)&&"bg-[color:var(--surface-active)]"),children:[i.jsx(IT,{organizationName:w.name,logoUrl:w.logoUrl,brandColor:w.brandColor,className:"h-7 w-7 shrink-0 rounded-lg text-xs"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",title:w.name,children:w.name}),w.id===(n==null?void 0:n.id)?i.jsx(zi,{className:"h-4 w-4 text-[color:var(--accent-strong)]"}):null]},w.id)),f.length===0&&i.jsx(Ht,{disabled:!0,"data-org-menu-item":!0,style:m(1),children:"No organizations"}),i.jsx(hl,{}),i.jsxs(Ht,{onClick:x,"data-org-menu-item":!0,style:m(f.length+1),className:"gap-3 rounded-[calc(var(--radius-md)-2px)] px-2.5 py-2",children:[i.jsx(ps,{className:"h-4 w-4"}),"Add organization"]}),i.jsx(hl,{}),i.jsxs(Ht,{onClick:b,"data-org-menu-item":!0,style:m(f.length+2),className:"gap-3 rounded-[calc(var(--radius-md)-2px)] px-2.5 py-2",children:[i.jsx(_w,{className:"h-4 w-4"}),"Organization settings"]})]})})]})}function w8({...e}){return i.jsx(F6t,{"data-slot":"collapsible",...e})}function uX({...e}){return i.jsx(n$e,{"data-slot":"collapsible-trigger",...e})}function k8({className:e,...t}){return i.jsx(r$e,{"data-slot":"collapsible-content",className:q("motion-accordion-content",e),...t})}const zle="rudder:agent-order-updated",wGt="rudder.agentOrder",G8e="anonymous";function eXe(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function kGt(e){if(!e)return G8e;const t=e.trim();return t.length>0?t:G8e}function tXe(e,t){return`${wGt}:${e}:${kGt(t)}`}function fte(e){try{const t=localStorage.getItem(e);return t?eXe(JSON.parse(t)):[]}catch{return[]}}function nXe(e,t){const n=eXe(t);try{localStorage.setItem(e,JSON.stringify(n))}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(zle,{detail:{storageKey:e,orderedIds:n}}))}function OGt(e){return[...e].sort((t,n)=>t.name.localeCompare(n.name))}function $le(e,t){if(e.length===0)return[];const n=OGt(e);if(t.length===0)return n;const r=new Map(n.map(a=>[a.id,a])),s=[];for(const a of t){const o=r.get(a);o&&(s.push(o),r.delete(a))}for(const a of n)r.has(a.id)&&(s.push(a),r.delete(a.id));return s}function mte(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function Ate(e,t){return $le(e,t).map(n=>n.id)}function rXe({agents:e,orgId:t,userId:n}){const r=A.useMemo(()=>t?tXe(t,n):null,[t,n]),[s,a]=A.useState(()=>r?Ate(e,fte(r)):e.map(c=>c.id));A.useEffect(()=>{const c=r?Ate(e,fte(r)):e.map(d=>d.id);a(d=>mte(d,c)?d:c)},[e,r]),A.useEffect(()=>{if(!r)return;const c=f=>{const m=Ate(e,f);a(h=>mte(h,m)?h:m)},d=f=>{f.key===r&&c(fte(r))},u=f=>{const m=f.detail;!m||m.storageKey!==r||c(m.orderedIds)};return window.addEventListener("storage",d),window.addEventListener(zle,u),()=>{window.removeEventListener("storage",d),window.removeEventListener(zle,u)}},[e,r]);const o=A.useMemo(()=>$le(e,s),[e,s]),l=A.useCallback(c=>{const d=new Set(e.map(f=>f.id)),u=c.filter(f=>d.has(f));for(const f of $le(e,[]))u.includes(f.id)||u.push(f.id);a(f=>mte(f,u)?f:u),r&&nXe(r,u)},[e,r]);return{orderedAgents:o,orderedIds:s,persistOrder:l}}function sXe(e){return e.status==="paused"?"paused":null}function ku({className:e,orientation:t="horizontal",...n}){return i.jsx(hCt,{"data-slot":"tabs","data-orientation":t,orientation:t,className:q("group/tabs flex gap-2 data-[orientation=horizontal]:flex-col",e),...n})}const SGt=AN("p-[3px] group-data-[orientation=horizontal]/tabs:h-10 group/tabs-list text-muted-foreground inline-flex w-fit items-center justify-center rounded-[calc(var(--radius-sm)+2px)] border group-data-[orientation=vertical]/tabs:h-fit group-data-[orientation=vertical]/tabs:flex-col",{variants:{variant:{default:"border-[color:var(--border-soft)] bg-muted",line:"gap-1 border-transparent bg-transparent"}},defaultVariants:{variant:"default"}});function O0({className:e,variant:t="default",...n}){return i.jsx(pCt,{"data-slot":"tabs-list","data-variant":t,className:q(SGt({variant:t}),e),...n})}function vc({className:e,...t}){return i.jsx(gCt,{"data-slot":"tabs-trigger",className:q("focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring text-foreground/60 hover:text-foreground dark:text-muted-foreground dark:hover:text-foreground relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-[calc(var(--radius-sm)-1px)] border border-transparent px-2.5 py-1 text-sm font-medium whitespace-nowrap transition-[color,background-color,border-color,box-shadow] group-data-[orientation=vertical]/tabs:w-full group-data-[orientation=vertical]/tabs:justify-start focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 group-data-[variant=default]/tabs-list:data-[state=active]:shadow-none group-data-[variant=line]/tabs-list:data-[state=active]:shadow-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4","group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:border-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent","data-[state=active]:border-[color:var(--border-base)] data-[state=active]:bg-background dark:data-[state=active]:text-foreground dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 data-[state=active]:text-foreground","after:bg-foreground after:absolute after:opacity-0 after:transition-opacity group-data-[orientation=horizontal]/tabs:after:inset-x-0 group-data-[orientation=horizontal]/tabs:after:bottom-[-5px] group-data-[orientation=horizontal]/tabs:after:h-0.5 group-data-[orientation=vertical]/tabs:after:inset-y-0 group-data-[orientation=vertical]/tabs:after:-right-1 group-data-[orientation=vertical]/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-[state=active]:after:opacity-100",e),...t})}function fa({className:e,motion:t=!0,...n}){return i.jsx(xCt,{"data-slot":"tabs-content",className:q(t&&"rudder-tabs-content-motion","flex-1 outline-none",e),...n})}function lc({icon:e,role:t,fallbackSeed:n,className:r,style:s,testId:a}){const l=jp(e)??oge(t),c=xN(l)??ige(n);if(c){const u=Iq(l);return i.jsx("img",{src:c,alt:"","data-testid":a,className:q("inline-flex rounded-full object-cover",r),style:{background:u==="oreo"?void 0:gS(l).background,...age(l),...s},loading:"lazy"})}const d=lge(l);return i.jsx(d,{className:r,"data-testid":a})}function iXe({value:e,onChange:t,onUpload:n,uploadPending:r=!1,uploadError:s=null,children:a}){const[o,l]=A.useState(!1),[c,d]=A.useState("oreo"),[u,f]=A.useState(()=>hw(e)?jp(e):pS()),[m,h]=A.useState(()=>Iq(e)==="dicebear"?jp(e):sQ(gS(e).id)),p=A.useRef(null),x=is("rudder:agent-avatar:oreo-palettes"),b=hw(u),y=gS(m);function w(N){t(N),l(!1)}function k(N){var E;const M=((E=N.currentTarget.files)==null?void 0:E[0])??null;N.currentTarget.value="",!(!M||!n)&&n(M)}function S(){if(c==="oreo"){const M=vVt();f(M),w(M);return}const N=sQ(y.id);h(N),w(N)}function j(N){const M=wVt(u,N);f(M),t(M)}function C(N){const M=kVt(u,N);f(M),t(M)}function I(N){const M=OVt(m,N);h(M),t(M)}return i.jsxs(bi,{open:o,onOpenChange:N=>{N&&(d("oreo"),f(hw(e)?jp(e):pS()),h(Iq(e)==="dicebear"?jp(e):sQ(gS(e).id))),l(N)},children:[i.jsx(Hi,{asChild:!0,children:a}),i.jsx(yi,{className:"flex max-h-[calc(100dvh-1rem)] w-[min(22rem,calc(100vw-1rem))] flex-col overflow-hidden p-3",align:"start","data-testid":"agent-avatar-picker",children:i.jsxs("div",{className:"flex min-h-0 flex-col gap-3",children:[i.jsxs("div",{className:"flex items-center justify-between gap-2",children:[i.jsx("div",{className:"text-sm font-medium text-foreground",children:"Avatar"}),i.jsxs("button",{type:"button",onClick:S,className:"inline-flex h-7 items-center gap-1 rounded-md px-2 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",children:[i.jsx(pkt,{className:"h-3.5 w-3.5"}),"Random"]})]}),i.jsxs(ku,{value:c,onValueChange:N=>d(N),className:"min-h-0 gap-3",children:[i.jsxs(O0,{className:"grid h-8 w-full grid-cols-2 rounded-[var(--control-radius)] p-0.5","aria-label":"Avatar style",children:[i.jsx(vc,{value:"oreo",className:"h-7 rounded-[var(--control-radius)] py-0 text-xs",children:"Oreo"}),i.jsx(vc,{value:"dicebear",className:"h-7 rounded-[var(--control-radius)] py-0 text-xs",children:"DiceBear"})]}),i.jsxs(fa,{value:"oreo",className:"mt-0 min-h-0 space-y-3",children:[i.jsxs("div",{className:"space-y-2",children:[i.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Shape"}),i.jsx("div",{className:"grid grid-cols-3 gap-2",children:pVt.map(N=>{const M=pS(N.id,b.palette,b.variantId);return i.jsxs("button",{type:"button",onClick:()=>j(N.id),"aria-label":`Oreo shape ${N.label}`,"aria-pressed":b.shape===N.id,className:q("flex h-11 items-center gap-2 rounded-md border border-border px-2 text-xs text-foreground transition-colors hover:bg-accent",b.shape===N.id&&"border-primary ring-1 ring-primary"),children:[i.jsx(lc,{icon:M,className:"size-5 shrink-0"}),i.jsx("span",{className:"truncate",children:N.label})]},N.id)})})]}),i.jsxs("div",{className:"min-h-0 space-y-2",children:[i.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Palette"}),i.jsx("div",{ref:x,className:"scrollbar-auto-hide max-h-[min(15rem,calc(100dvh-19rem))] min-h-24 overflow-y-auto overscroll-contain pr-1","data-testid":"agent-avatar-oreo-palettes",children:i.jsx("div",{className:"grid grid-cols-2 gap-2",children:gVt.map(N=>i.jsxs("button",{type:"button",onClick:()=>C(N.id),"aria-label":`Oreo palette ${N.label}`,"aria-pressed":b.palette===N.id,className:q("flex h-9 min-w-0 items-center gap-2 rounded-md border border-border px-2 text-xs text-foreground transition-colors hover:bg-accent",b.palette===N.id&&"border-primary ring-1 ring-primary"),children:[i.jsx("span",{className:"size-4 shrink-0 rounded-full border border-border",style:{background:N.background}}),i.jsx("span",{className:"truncate",children:N.label})]},N.id))})})]})]}),i.jsxs(fa,{value:"dicebear",className:"mt-0 space-y-2",children:[i.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Background"}),i.jsx("div",{className:"grid grid-cols-3 gap-2",children:gle.map(N=>i.jsxs("button",{type:"button",onClick:()=>I(N.id),"aria-label":`DiceBear background ${N.label}`,"aria-pressed":y.id===N.id,className:q("flex h-9 items-center gap-2 rounded-md border border-border px-2 text-xs text-foreground transition-colors hover:bg-accent",y.id===N.id&&"border-primary ring-1 ring-primary"),title:N.label,children:[i.jsx("span",{className:"size-4 shrink-0 rounded-full border border-border",style:{background:N.background}}),i.jsx("span",{className:"truncate",children:N.label})]},N.id))})]})]}),n?i.jsxs("div",{className:"grid gap-2 border-t border-border pt-3",children:[i.jsx("input",{ref:p,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",className:"hidden",onChange:k}),i.jsxs("button",{type:"button",onClick:()=>{var N;return(N=p.current)==null?void 0:N.click()},disabled:r,className:"flex h-9 items-center justify-center gap-2 rounded-md border border-border px-3 text-sm text-foreground transition-colors hover:bg-accent disabled:cursor-not-allowed disabled:opacity-60",children:[i.jsx(Hwt,{className:"h-4 w-4"}),r?"Uploading...":"Upload image"]}),s?i.jsx("p",{className:"text-xs text-destructive",children:s}):null]}):null]})})]})}function jGt({title:e="Paused by budget"}){return i.jsx("span",{title:e,"aria-label":e,className:"ml-auto inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-red-500/90 text-white shadow-[0_0_0_1px_rgba(255,255,255,0.08)]",children:i.jsx(y0,{className:"h-3 w-3"})})}const Y8e="truncate text-[10px] font-medium tracking-[0.08em] text-muted-foreground/60",J8e="flex h-3 w-3 shrink-0 items-center justify-center",CGt="flex h-4 w-4 shrink-0 items-center justify-center rounded text-muted-foreground/60 transition-colors hover:bg-accent/50 hover:text-foreground";function fX({className:e,type:t="button",...n}){return i.jsx("button",{type:t,className:q(CGt,e),...n})}function kR({label:e,action:t,collapsible:n=!1,open:r=!1,onToggle:s}){return i.jsxs("div",{className:"group flex items-center px-3 py-1.5",children:[n?i.jsxs("button",{type:"button","aria-expanded":r,onClick:s,className:"flex min-w-0 flex-1 items-center gap-1 text-left",children:[i.jsx("span",{className:J8e,children:i.jsx(vi,{className:q("h-3 w-3 text-muted-foreground/60 transition-transform opacity-0 group-hover:opacity-100",r&&"rotate-90")})}),i.jsx("span",{className:Y8e,children:e})]}):i.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1",children:[i.jsx("span",{"aria-hidden":!0,className:J8e}),i.jsx("span",{className:Y8e,children:e})]}),t?i.jsx("div",{className:"ml-2 shrink-0",children:t}):null]})}const OR=AN("flex items-center gap-2.5 rounded-[calc(var(--radius-sm)-1px)] border text-[13px] font-medium transition-[background-color,color,border-color,box-shadow]",{variants:{variant:{default:"px-3 py-2.5",compact:"px-2.5 py-2"},active:{true:"surface-active border-[color:var(--border-strong)] text-foreground",false:"border-transparent text-foreground/80 hover:border-[color:var(--border-soft)] hover:bg-[color:color-mix(in_oklab,var(--surface-active)_52%,transparent)] hover:text-foreground"}},compoundVariants:[{variant:"default",active:!0,className:"shadow-[var(--shadow-sm)]"},{variant:"compact",active:!0,className:"border-transparent bg-[color:var(--surface-active)] shadow-none"}],defaultVariants:{variant:"default",active:!1}});function NGt(){var y,w;const[e,t]=A.useState(!0),{selectedOrganizationId:n}=Mr(),{openNewAgent:r}=Bs(),{isMobile:s,setSidebarOpen:a}=Bc(),o=Ir(),{data:l}=Ve({queryKey:U.agents.list(n),queryFn:()=>$n.list(n),enabled:!!n}),{data:c}=Ve({queryKey:U.auth.session,queryFn:()=>Ll.getSession()}),{data:d}=Ve({queryKey:U.liveRuns(n),queryFn:()=>xo.liveRunsForCompany(n),enabled:!!n,refetchInterval:1e4}),u=A.useMemo(()=>{const k=new Map;for(const S of d??[])k.set(S.agentId,(k.get(S.agentId)??0)+1);return k},[d]),f=A.useMemo(()=>(l??[]).filter(S=>S.status!=="terminated"),[l]),m=((y=c==null?void 0:c.user)==null?void 0:y.id)??((w=c==null?void 0:c.session)==null?void 0:w.userId)??null,{orderedAgents:h}=rXe({agents:f,orgId:n,userId:m}),p=o.pathname.match(/^\/(?:[^/]+\/)?agents\/([^/]+)(?:\/([^/]+))?/),x=(p==null?void 0:p[1])??null,b=(p==null?void 0:p[2])??null;return i.jsxs(w8,{open:e,onOpenChange:t,children:[i.jsx(kR,{label:"Agents",collapsible:!0,open:e,onToggle:()=>t(k=>!k),action:i.jsx(fX,{onClick:k=>{k.stopPropagation(),r()},"aria-label":"New agent",children:i.jsx(ps,{className:"h-3 w-3"})})}),i.jsx(k8,{children:i.jsx("div",{className:"flex flex-col gap-0.5 mt-0.5",children:h.map(k=>{const S=u.get(k.id)??0,j=sXe(k);return i.jsxs(DZ,{to:b?`${Ph(k)}/${b}`:Ph(k),onClick:()=>{s&&a(!1)},className:OR({variant:"compact",active:x===uw(k)}),children:[i.jsx(lc,{icon:k.icon,role:k.role,className:"shrink-0 h-3.5 w-3.5 text-muted-foreground"}),i.jsx("span",{className:"flex-1 truncate",title:xS(k),children:xS(k)}),(j||k.pauseReason==="budget"||S>0)&&i.jsxs("span",{className:"ml-auto flex items-center gap-1.5 shrink-0",children:[j?i.jsx("span",{title:`Agent status: ${j}`,className:q("inline-flex h-5 shrink-0 items-center rounded-[calc(var(--radius-sm)-1px)] border px-1.5 text-[10px] font-medium leading-none whitespace-nowrap",hR[j]??pR),children:j}):null,k.pauseReason==="budget"?i.jsx(jGt,{title:"Agent paused by budget"}):null,S>0?i.jsxs("span",{className:"relative flex h-2 w-2",children:[i.jsx("span",{className:"animate-pulse absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75"}),i.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-blue-500"})]}):null,S>0?i.jsxs("span",{className:"text-[11px] font-medium text-blue-600 dark:text-blue-400",children:[S," live"]}):null]})]},k.id)})})})]})}function aXe(e){const t=new Date(e),n=t.getFullYear()!==new Date().getFullYear();return t.toLocaleString("en-US",{month:"short",day:"numeric",...n?{year:"numeric"}:{},hour:"2-digit",minute:"2-digit",hourCycle:"h23"})}function nC({date:e,label:t,className:n,testId:r}){const s=aXe(e);return i.jsx("span",{"data-testid":r,title:s,"aria-label":s,className:q("inline-block whitespace-nowrap tabular-nums",n),children:t})}function Fle({date:e,children:t,side:n="top"}){const r=aXe(e),s=A.cloneElement(t,{title:t.props.title??r,"aria-label":t.props["aria-label"]??r});return i.jsxs(Mi,{children:[i.jsx(Ei,{asChild:!0,children:s}),i.jsx(Di,{side:n,className:"px-2.5 py-1.5 text-[11px] tabular-nums tracking-normal",children:r})]})}function zP(e,t,n){return Promise.all([e.prefetchQuery({queryKey:U.chats.detail(t,n),queryFn:()=>Zn.get(n)}),e.prefetchQuery({queryKey:U.chats.messages(t,n),queryFn:()=>Zn.listMessages(t,n,{includeTranscript:!1})})])}function q3(e){const t=e==null?void 0:e.sourceMetadata;return!!(t&&typeof t=="object"&&!Array.isArray(t)&&t.source==="agent_integration"&&t.provider==="feishu")}const IGt="New chat",aQ=80;function mX(e){return(e==null?void 0:e.trim())===IGt}function PGt(e,t){return mX(e)?OT(t,{max:aQ})??e:e}function C6(e){if(mX(e.title)){const t=OT(e.summary,{max:aQ})??OT(e.latestUserMessagePreview,{max:aQ});if(t)return t}return OT(e.title,{max:aQ})??e.title}function oXe(e){return e.item.type==="thread"}function TGt(e){const t={activityAt:new Date(e.latestActivityAt??0).toISOString(),title:e.title,threadKey:e.threadKey,isPinned:!!e.isPinned},n=new TextEncoder().encode(JSON.stringify(t));let r="";for(const a of n)r+=String.fromCharCode(a);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}function _Gt(e,t){const n=!!e.isPinned,r=!!t.isPinned;if(n!==r)return n?-1:1;const s=e.latestActivityAt?new Date(e.latestActivityAt).getTime():Number.NEGATIVE_INFINITY,a=t.latestActivityAt?new Date(t.latestActivityAt).getTime():Number.NEGATIVE_INFINITY;if(s!==a)return a-s;const o=e.title.localeCompare(t.title);return o!==0?o:e.threadKey.localeCompare(t.threadKey)}function lXe(e,t){const n=e.filter(r=>r.threadKey!==t.threadKey);return[t,...n].sort(_Gt)}function MGt(e,t){return e&&{...e,pages:e.pages.map((n,r)=>{const s=r===0?lXe(n.items,t):n.items.filter(d=>d.threadKey!==t.threadKey),a=typeof n.pageInfo.limit=="number"?n.pageInfo.limit:null,o=r===0&&a!==null?s.slice(0,a):s,l=o.at(-1),c=n.pageInfo.hasMore===!0||s.length>o.length;return{...n,items:o,pageInfo:r===0&&c&&l?{...n.pageInfo,hasMore:!0,nextCursor:TGt(l)}:n.pageInfo}})}}function cXe(e){if(!e)return new Date;const t=new Date(e);return Number.isNaN(t.getTime())?new Date:t}function Uq(e,t,n){return e.threadKey!==t?e:{...e,lastReadAt:n,unreadCount:0,needsAttention:!1}}function hte(e,t,n){return e.threadKey!==t?e:{...e,isPinned:n}}function pte(e,t,n){return e.threadKey!==t?e:{...e,title:n}}function EGt(e,t,n){return e&&{...e,pages:e.pages.map(r=>({...r,items:r.items.map(s=>Uq(s,t,n))}))}}function Uge(e,t){return e&&{...e,pages:e.pages.map(n=>({...n,items:n.items.map(t).filter(r=>!!r)}))}}function qge(e,t){return e&&{...e,items:e.items.map(t).filter(n=>!!n)}}function DGt(e,t,n){return e&&{...e,items:e.items.map(r=>Uq(r,t,n))}}function RGt(e,t){return e&&{...e,groups:e.groups.map(n=>({...n,entries:n.entries.map(r=>{if(!oXe(r))return r;const s=t(r.thread);return{...r,thread:s,item:{...r.item,title:s.title,thread:s}}})}))}}function e7e(e,t){return{...e,isPinned:t}}function t7e(e,t){return{...e,title:t}}function n7e(e){return{...e,status:"archived"}}function gte(e,t){return{...e,lastReadAt:t,isUnread:!1,unreadCount:0,needsAttention:!1}}function LGt(e){if(!e)return e;const t=Math.max(0,e.chatAttention-1);return{...e,inbox:Math.max(0,e.inbox-(e.chatAttention>t?1:0)),chatAttention:t}}function zGt(e,t){if(!e||t<=0)return e;const n=Math.max(0,e.unreadTouchedIssues-t),r=e.unreadTouchedIssues-n;return r<=0?e:{...e,inbox:Math.max(0,e.inbox-r),unreadTouchedIssues:n}}function xte(e,t){var n;return((n=e==null?void 0:e.find(r=>r.threadKey===t))==null?void 0:n.unreadCount)??null}function $Gt(e,t,n){var o;const r=xte(e.getQueryData(U.messenger.threads(t)),n);if(r!==null)return r;for(const l of[!1,!0]){const c=e.getQueryData(U.messenger.threadPages(t,l));for(const d of(c==null?void 0:c.pages)??[]){const u=xte(d.items,n);if(u!==null)return u}}const s=xte((o=e.getQueryData(U.messenger.threadPreview(t)))==null?void 0:o.items,n);if(s!==null)return s;const a=e.getQueryData(U.messenger.customGroups(t));for(const l of(a==null?void 0:a.groups)??[])for(const c of l.entries)if(oXe(c)&&c.thread.threadKey===n)return c.thread.unreadCount;return 0}function Yu(e,t){return Promise.all([e.invalidateQueries({queryKey:U.messenger.threads(t)}),e.invalidateQueries({queryKey:U.messenger.customGroups(t)})])}function dXe(e,t){return Promise.all([e.cancelQueries({queryKey:["chats",t]}),e.cancelQueries({queryKey:U.messenger.threads(t)})])}function FGt(e,t,n){e.setQueryData(U.messenger.customGroups(t),r=>{if(!r||Array.isArray(r))return r;let s=!1;const a=r.groups.map(o=>{const l=o.entries.filter(c=>c.item.type!=="saved_view"||c.item.savedView.id!==n);return l.length===o.entries.length?o:(s=!0,{...o,entries:l})});return s?{...r,groups:a}:r})}function uXe(e,t,n,r){e.setQueryData(U.messenger.threads(t),s=>(s==null?void 0:s.map(a=>hte(a,n,r)))??s),e.setQueriesData({queryKey:U.messenger.threadPages(t)},s=>Uge(s,a=>hte(a,n,r))),e.setQueryData(U.messenger.threadPreview(t),s=>qge(s,a=>hte(a,n,r)))}function fXe(e,t,n,r){e.setQueryData(U.chats.detail(t,n),s=>s&&e7e(s,r));for(const s of["active","all"])e.setQueryData(U.chats.list(t,s),a=>(a==null?void 0:a.map(o=>o.id===n?e7e(o,r):o))??a);uXe(e,t,`chat:${n}`,r)}function Nk(e,t,n,r){e.setQueryData(U.chats.detail(t,n),a=>a&&t7e(a,r));for(const a of["active","resolved","archived","all"])e.setQueryData(U.chats.list(t,a),o=>(o==null?void 0:o.map(l=>l.id===n?t7e(l,r):l))??o);const s=`chat:${n}`;e.setQueryData(U.messenger.threads(t),a=>(a==null?void 0:a.map(o=>pte(o,s,r)))??a),e.setQueriesData({queryKey:U.messenger.threadPages(t)},a=>Uge(a,o=>pte(o,s,r))),e.setQueryData(U.messenger.threadPreview(t),a=>qge(a,o=>pte(o,s,r)))}function mXe(e,t,n){e.setQueryData(U.chats.detail(t,n),r=>r&&n7e(r)),e.setQueryData(U.chats.list(t,"active"),r=>(r==null?void 0:r.filter(s=>s.id!==n))??r),e.setQueryData(U.chats.list(t,"all"),r=>(r==null?void 0:r.map(s=>s.id===n?n7e(s):s))??r),e.setQueryData(U.messenger.threads(t),r=>(r==null?void 0:r.filter(s=>s.threadKey!==`chat:${n}`))??r),e.setQueriesData({queryKey:U.messenger.threadPages(t)},r=>Uge(r,s=>s.threadKey===`chat:${n}`?null:s)),e.setQueryData(U.messenger.threadPreview(t),r=>qge(r,s=>s.threadKey===`chat:${n}`?null:s))}function Ble(e,t,n,r){const s=cXe(r),a=$Gt(e,t,n);e.setQueryData(U.messenger.threads(t),o=>(o==null?void 0:o.map(l=>Uq(l,n,s)))??o),e.setQueriesData({queryKey:U.messenger.threadPages(t)},o=>EGt(o,n,s)),e.setQueryData(U.messenger.threadPreview(t),o=>DGt(o,n,s)),e.setQueryData(U.messenger.customGroups(t),o=>RGt(o,l=>Uq(l,n,s))),(n==="issues"||n.startsWith("issue:"))&&e.setQueryData(U.sidebarBadges(t),o=>zGt(o,a))}function BGt(e,t,n,r={}){const s=cXe(r.readAt??n.lastMessageAt??n.updatedAt),a=gte(n,s);e.setQueryData(U.chats.detail(t,n.id),o=>o?gte(o,s):a);for(const o of["active","all"])e.setQueryData(U.chats.list(t,o),l=>(l==null?void 0:l.map(c=>c.id===n.id?gte(c,s):c))??l);Ble(e,t,`chat:${n.id}`,s),r.decrementSidebarBadge&&e.setQueryData(U.sidebarBadges(t),LGt)}function QGt(e,t,n){e.setQueryData(U.messenger.threads(t),r=>lXe(r??[],n)),e.setQueriesData({queryKey:U.messenger.threadPages(t)},r=>MGt(r,n))}function UGt(e){return C6(e)}function qGt(e){return e.primaryIssue?`${e.primaryIssue.identifier??e.primaryIssue.id} · ${e.primaryIssue.title}`:e.chatRuntime.model?`${e.chatRuntime.sourceLabel} · ${e.chatRuntime.model}`:Sm(e.summary)||"Execute, refine, or add issue structure"}function r7e({conversation:e,active:t,renaming:n,renameDraft:r,onRenameDraftChange:s,onSelect:a,onPrefetch:o,onStartRename:l,onCommitRename:c,onArchive:d,onTogglePin:u,archiveAllowed:f=!0}){const m=qGt(e),h=e.lastMessageAt?Ca(e.lastMessageAt):Ca(e.updatedAt),[p,x]=A.useState(!1);return i.jsx(Fle,{date:e.lastMessageAt??e.updatedAt,children:i.jsx("div",{"data-testid":`sidebar-chat-${e.id}`,className:q(OR({variant:"compact",active:t}),"group transition-[background-color,color,border-color] duration-150"),children:n?i.jsx("input",{autoFocus:!0,value:r,onChange:b=>s(b.target.value),onBlur:c,onKeyDown:b=>{b.key==="Enter"&&(b.preventDefault(),c())},className:"min-h-0 w-full min-w-0 flex-1 rounded-[var(--radius-sm)] border border-border bg-background px-2 py-1 text-[13px] leading-tight outline-none"}):i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button",onClick:a,onPointerDown:o,onMouseEnter:o,onFocus:o,className:"min-w-0 flex-1 truncate text-left text-[13px] font-medium leading-tight text-foreground/90",title:m,children:i.jsxs("span",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"truncate",children:UGt(e)}),e.isUnread?i.jsx("span",{className:"inline-flex h-2 w-2 shrink-0 rounded-full bg-red-500","aria-label":"Unread chat"}):null]})}),i.jsxs("div",{className:"relative ml-auto h-5 w-12 shrink-0",children:[i.jsx("span",{className:q("pointer-events-none absolute inset-y-0 right-0 flex items-center whitespace-nowrap text-[11px] tabular-nums text-muted-foreground transition-opacity duration-150 group-hover:opacity-0 group-focus-within:opacity-0",p&&"opacity-0"),children:h}),i.jsxs(ui,{open:p,onOpenChange:x,children:[i.jsx(fi,{asChild:!0,children:i.jsx("button",{type:"button",className:q("absolute inset-y-0 right-0 z-10 flex items-center justify-end rounded p-0.5 text-muted-foreground transition-[opacity,background-color,color] duration-150 hover:bg-[color:var(--surface-active)] hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100 group-focus-within:opacity-100",p?"opacity-100":"opacity-0"),"aria-label":"Chat actions",children:i.jsx(Tl,{className:"h-3.5 w-3.5"})})}),i.jsxs(mi,{className:"surface-overlay text-foreground",children:[i.jsxs(Ht,{onClick:l,children:[i.jsx(r1,{className:"h-4 w-4"}),"Rename"]}),i.jsx(Ht,{onClick:u,children:e.isPinned?i.jsxs(i.Fragment,{children:[i.jsx(u5,{className:"h-4 w-4"}),"Unpin"]}):i.jsxs(i.Fragment,{children:[i.jsx(Eh,{className:"h-4 w-4"}),"Pin"]})}),f?i.jsxs(Ht,{onClick:d,children:[i.jsx(l6,{className:"h-4 w-4"}),"Archive"]}):null]})]})]})]})})})}function VGt(e){const t=e.match(/\/(?:messenger\/)?chat\/([^/]+)\/?/);return(t==null?void 0:t[1])??null}function WGt(){const[e,t]=A.useState(!0),[n,r]=A.useState(null),[s,a]=A.useState(""),{selectedOrganizationId:o}=Mr(),{isMobile:l,setSidebarOpen:c}=Bc(),d=Ir(),u=Kr(),f=er(),m=VGt(d.pathname),h=Ve({queryKey:U.chats.listPreview(o??"__none__","active",40),queryFn:()=>Zn.list(o,"active",{limit:40}),enabled:!!o}),p=async j=>{o&&(await f.invalidateQueries({queryKey:U.chats.list(o,"active")}),j&&(await f.invalidateQueries({queryKey:U.chats.detail(o,j)}),await f.invalidateQueries({queryKey:U.chats.messages(o,j)})))},x=xt({mutationFn:({chatId:j,data:C})=>Zn.update(j,C),onSuccess:async j=>{j.status==="archived"&&j.id===m&&u("/messenger/chat"),r(C=>C===j.id?null:C),await p(j.id)},onError:async(j,C)=>{await p(C.chatId)}}),b=xt({mutationFn:({chatId:j,pinned:C})=>Zn.updateUserState(j,{pinned:C}),onSuccess:async j=>{await p(j.id)}}),y=()=>{const j=s.trim();if(!n||!j){r(null);return}o&&Nk(f,o,n,j),r(null),x.mutate({chatId:n,data:{title:j}})};if(!o)return null;const w=h.data??[],k=w.filter(j=>j.isPinned),S=w.filter(j=>!j.isPinned);return i.jsxs(w8,{open:e,onOpenChange:t,children:[i.jsx(kR,{label:"Chats",collapsible:!0,open:e,onToggle:()=>t(j=>!j),action:i.jsx(fX,{"aria-label":"New chat",onClick:j=>{j.stopPropagation(),u("/messenger/chat"),l&&c(!1)},children:i.jsx(ps,{className:"h-3 w-3"})})}),i.jsx(k8,{children:i.jsx("div",{className:"mt-0.5 flex flex-col gap-0.5",children:w.length===0?i.jsx("div",{className:"surface-inset rounded-[var(--radius-md)] border border-dashed px-3 py-6 text-center text-xs text-muted-foreground",children:"No active conversations yet."}):i.jsxs(i.Fragment,{children:[k.length>0?i.jsx("div",{className:"px-2 pb-1 pt-2 text-[10px] font-semibold uppercase tracking-[0.18em] text-muted-foreground/70",children:"Pinned"}):null,k.map(j=>i.jsx(r7e,{conversation:j,active:j.id===m,renaming:n===j.id,renameDraft:s,onRenameDraftChange:a,onSelect:()=>{zP(f,o,j.id),u(`/messenger/chat/${j.id}`),l&&c(!1)},onPrefetch:()=>{j.id!==m&&zP(f,o,j.id)},onStartRename:()=>{r(j.id),a(j.title)},onCommitRename:y,onTogglePin:()=>{b.mutate({chatId:j.id,pinned:!j.isPinned})},onArchive:()=>{x.mutate({chatId:j.id,data:{status:"archived"}})},archiveAllowed:!q3(j)},j.id)),S.length>0?i.jsx("div",{className:"px-2 pb-1 pt-2 text-[10px] font-semibold uppercase tracking-[0.18em] text-muted-foreground/70",children:"Recent"}):null,S.map(j=>i.jsx(r7e,{conversation:j,active:j.id===m,renaming:n===j.id,renameDraft:s,onRenameDraftChange:a,onSelect:()=>{zP(f,o,j.id),u(`/messenger/chat/${j.id}`),l&&c(!1)},onPrefetch:()=>{j.id!==m&&zP(f,o,j.id)},onStartRename:()=>{r(j.id),a(j.title)},onCommitRename:y,onTogglePin:()=>{b.mutate({chatId:j.id,pinned:!j.isPinned})},onArchive:()=>{x.mutate({chatId:j.id,data:{status:"archived"}})},archiveAllowed:!q3(j)},j.id))]})})})]})}function Wu({to:e,state:t,label:n,icon:r,end:s,className:a,variant:o="default",badge:l,badgeTone:c="default",textBadge:d,textBadgeTone:u="default",alert:f=!1,liveCount:m}){const{isMobile:h,setSidebarOpen:p}=Bc(),x=Kr();return i.jsxs(DZ,{to:e,state:t,end:s,onClick:b=>{t!==void 0&&(b.preventDefault(),x(e,{state:t})),h&&p(!1)},className:({isActive:b})=>q(OR({variant:o,active:b}),a),children:[i.jsxs("span",{className:"relative shrink-0",children:[i.jsx(r,{className:"h-4 w-4"}),f&&i.jsx("span",{className:"absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full bg-red-500 shadow-[0_0_0_2px_hsl(var(--background))]"})]}),i.jsx("span",{className:"flex-1 truncate",children:n}),d&&i.jsx("span",{className:q("ml-auto rounded-full px-1.5 py-0.5 text-[10px] font-medium leading-none",u==="amber"?"border border-amber-200/80 bg-amber-100/85 text-amber-800 dark:border-amber-700/50 dark:bg-amber-900/30 dark:text-amber-200":"border border-[color:var(--border-soft)] bg-muted text-muted-foreground"),children:d}),m!=null&&m>0&&i.jsxs("span",{className:"ml-auto flex items-center gap-1.5",children:[i.jsxs("span",{className:"relative flex h-2 w-2",children:[i.jsx("span",{className:"absolute inline-flex h-full w-full animate-pulse rounded-full bg-[color:var(--accent-base)] opacity-75"}),i.jsx("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-[color:var(--accent-strong)]"})]}),i.jsxs("span",{className:"text-[11px] font-medium text-[color:var(--accent-strong)]",children:[m," live"]})]}),l!=null&&l>0&&i.jsx("span",{className:q("ml-auto rounded-full border px-1.5 py-0.5 text-xs leading-none shadow-[var(--shadow-sm)]",c==="danger"?"border-red-700/20 bg-red-600/90 text-red-50":"border-transparent bg-primary text-primary-foreground"),children:l})]})}function HGt(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return A.useMemo(()=>r=>{t.forEach(s=>s(r))},t)}const AX=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function SN(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function Vge(e){return"nodeType"in e}function Um(e){var t,n;return e?SN(e)?e:Vge(e)&&(t=(n=e.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function Wge(e){const{Document:t}=Um(e);return e instanceof t}function SR(e){return SN(e)?!1:e instanceof Um(e).HTMLElement}function AXe(e){return e instanceof Um(e).SVGElement}function jN(e){return e?SN(e)?e.document:Vge(e)?Wge(e)?e:SR(e)||AXe(e)?e.ownerDocument:document:document:document}const O1=AX?A.useLayoutEffect:A.useEffect;function hX(e){const t=A.useRef(e);return O1(()=>{t.current=e}),A.useCallback(function(){for(var n=arguments.length,r=new Array(n),s=0;s<n;s++)r[s]=arguments[s];return t.current==null?void 0:t.current(...r)},[])}function KGt(){const e=A.useRef(null),t=A.useCallback((r,s)=>{e.current=setInterval(r,s)},[]),n=A.useCallback(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[]);return[t,n]}function hM(e,t){t===void 0&&(t=[e]);const n=A.useRef(e);return O1(()=>{n.current!==e&&(n.current=e)},t),n}function jR(e,t){const n=A.useRef();return A.useMemo(()=>{const r=e(n.current);return n.current=r,r},[...t])}function qq(e){const t=hX(e),n=A.useRef(null),r=A.useCallback(s=>{s!==n.current&&(t==null||t(s,n.current)),n.current=s},[]);return[n,r]}function Vq(e){const t=A.useRef();return A.useEffect(()=>{t.current=e},[e]),t.current}let bte={};function CR(e,t){return A.useMemo(()=>{if(t)return t;const n=bte[e]==null?0:bte[e]+1;return bte[e]=n,e+"-"+n},[e,t])}function hXe(e){return function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),s=1;s<n;s++)r[s-1]=arguments[s];return r.reduce((a,o)=>{const l=Object.entries(o);for(const[c,d]of l){const u=a[c];u!=null&&(a[c]=u+e*d)}return a},{...t})}}const wS=hXe(1),pM=hXe(-1);function ZGt(e){return"clientX"in e&&"clientY"in e}function pX(e){if(!e)return!1;const{KeyboardEvent:t}=Um(e.target);return t&&e instanceof t}function XGt(e){if(!e)return!1;const{TouchEvent:t}=Um(e.target);return t&&e instanceof t}function Wq(e){if(XGt(e)){if(e.touches&&e.touches.length){const{clientX:t,clientY:n}=e.touches[0];return{x:t,y:n}}else if(e.changedTouches&&e.changedTouches.length){const{clientX:t,clientY:n}=e.changedTouches[0];return{x:t,y:n}}}return ZGt(e)?{x:e.clientX,y:e.clientY}:null}const S1=Object.freeze({Translate:{toString(e){if(!e)return;const{x:t,y:n}=e;return"translate3d("+(t?Math.round(t):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:t,scaleY:n}=e;return"scaleX("+t+") scaleY("+n+")"}},Transform:{toString(e){if(e)return[S1.Translate.toString(e),S1.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:n,easing:r}=e;return t+" "+n+"ms "+r}}}),s7e="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function GGt(e){return e.matches(s7e)?e:e.querySelector(s7e)}const YGt={display:"none"};function JGt(e){let{id:t,value:n}=e;return xe.createElement("div",{id:t,style:YGt},n)}function eYt(e){let{id:t,announcement:n,ariaLiveType:r="assertive"}=e;const s={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return xe.createElement("div",{id:t,style:s,role:"status","aria-live":r,"aria-atomic":!0},n)}function tYt(){const[e,t]=A.useState("");return{announce:A.useCallback(r=>{r!=null&&t(r)},[]),announcement:e}}const pXe=A.createContext(null);function nYt(e){const t=A.useContext(pXe);A.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of <DndContext>");return t(e)},[e,t])}function rYt(){const[e]=A.useState(()=>new Set),t=A.useCallback(r=>(e.add(r),()=>e.delete(r)),[e]);return[A.useCallback(r=>{let{type:s,event:a}=r;e.forEach(o=>{var l;return(l=o[s])==null?void 0:l.call(o,a)})},[e]),t]}const sYt={draggable:`
1708
1708
  To pick up a draggable item, press the space bar.
@@ -1780,7 +1780,7 @@ When you submit the join request, use:
1780
1780
  constructor(\${params}) {
1781
1781
  \${}
1782
1782
  }
1783
- }`,{label:"class",detail:"definition",type:"keyword"}),xc('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),xc('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],kit=K0e.concat([xc("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),xc("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),xc("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),gNe=new b0e,Oit=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function MI(e){return(t,n)=>{let r=t.node.getChild("VariableDefinition");return r&&n(r,e),!0}}const xxn=["FunctionDeclaration"],bxn={FunctionDeclaration:MI("function"),ClassDeclaration:MI("class"),ClassExpression:()=>!0,EnumDeclaration:MI("constant"),TypeAliasDeclaration:MI("type"),NamespaceDeclaration:MI("namespace"),VariableDefinition(e,t){e.matchContext(xxn)||t(e,"variable")},TypeDefinition(e,t){t(e,"type")},__proto__:null};function Sit(e,t){let n=gNe.get(t);if(n)return n;let r=[],s=!0;function a(o,l){let c=e.sliceString(o.from,o.to);r.push({label:c,type:l})}return t.cursor(Ao.IncludeAnonymous).iterate(o=>{if(s)s=!1;else if(o.name){let l=bxn[o.name];if(l&&l(o,a)||Oit.has(o.name))return!1}else if(o.to-o.from>8192){for(let l of Sit(e,o.node))r.push(l);return!1}}),gNe.set(t,r),r}const aW=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,Z0e=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function jit(e){let t=Ha(e.state).resolveInner(e.pos,-1);if(Z0e.indexOf(t.name)>-1)return null;let n=t.name=="VariableName"||t.to-t.from<20&&aW.test(e.state.sliceDoc(t.from,t.to));if(!n&&!e.explicit)return null;let r=[];for(let s=t;s;s=s.parent)Oit.has(s.name)&&(r=r.concat(Sit(e.state.doc,s)));return{options:r,from:n?t.from:e.pos,validFor:aW}}function zne(e,t,n){var r;let s=[];for(;;){let a=t.firstChild,o;if((a==null?void 0:a.name)=="VariableName")return s.push(e(a)),{path:s.reverse(),name:n};if((a==null?void 0:a.name)=="MemberExpression"&&((r=o=a.lastChild)===null||r===void 0?void 0:r.name)=="PropertyName")s.push(e(o)),t=a;else return null}}function Cit(e){let t=r=>e.state.doc.sliceString(r.from,r.to),n=Ha(e.state).resolveInner(e.pos,-1);return n.name=="PropertyName"?zne(t,n.parent,t(n)):(n.name=="."||n.name=="?.")&&n.parent.name=="MemberExpression"?zne(t,n.parent,""):Z0e.indexOf(n.name)>-1?null:n.name=="VariableName"||n.to-n.from<20&&aW.test(t(n))?{path:[],name:t(n)}:n.name=="MemberExpression"?zne(t,n,""):e.explicit?{path:[],name:""}:null}function yxn(e,t){let n=e,r=[],s=new Set;for(let a=0;;a++){for(let l of(Object.getOwnPropertyNames||Object.keys)(e)){if(!/^[a-zA-Z_$\xaa-\uffdc][\w$\xaa-\uffdc]*$/.test(l)||s.has(l))continue;s.add(l);let c;try{c=n[l]}catch{continue}r.push({label:l,type:typeof c=="function"?/^[A-Z]/.test(l)?"class":t?"function":"method":t?"variable":"property",boost:-a})}let o=Object.getPrototypeOf(e);if(!o)return r;e=o}}function vxn(e){let t=new Map;return n=>{let r=Cit(n);if(!r)return null;let s=e;for(let o of r.path)if(s=s[o],!s)return null;let a=t.get(s);return a||t.set(s,a=yxn(s,!r.path.length)),{from:n.pos-r.name.length,options:a,validFor:aW}}}const Dp=I0.define({name:"javascript",parser:gxn.configure({props:[Q2.add({IfStatement:ES({except:/^\s*({|else\b)/}),TryStatement:ES({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:jAn,SwitchBody:e=>{let t=e.textAfter,n=/^\s*\}/.test(t),r=/^\s*(case|default)\b/.test(t);return e.baseIndent+(n?0:r?1:2)*e.unit},Block:MS({closing:"}"}),ArrowFunction:e=>e.baseIndent+e.unit,"TemplateString BlockComment":()=>null,"Statement Property":ES({except:/^\s*{/}),JSXElement(e){let t=/^\s*<\//.test(e.textAfter);return e.lineIndent(e.node.from)+(t?0:e.unit)},JSXEscape(e){let t=/\s*\}/.test(e.textAfter);return e.lineIndent(e.node.from)+(t?0:e.unit)},"JSXOpenTag JSXSelfClosingTag"(e){return e.column(e.node.from)+e.unit}}),U2.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":YR,BlockComment(e){return{from:e.from+2,to:e.to-2}},JSXElement(e){let t=e.firstChild;if(!t||t.name=="JSXSelfClosingTag")return null;let n=e.lastChild;return{from:t.to,to:n.type.isError?e.to:n.from}},"JSXSelfClosingTag JSXOpenTag"(e){var t;let n=(t=e.firstChild)===null||t===void 0?void 0:t.nextSibling,r=e.lastChild;return!n||n.type.isError?null:{from:n.to,to:r.type.isError?e.to:r.from}}})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:"$"}}),Nit={test:e=>/^JSX/.test(e.name),facet:aG({commentTokens:{block:{open:"{/*",close:"*/}"}}})},X0e=Dp.configure({dialect:"ts"},"typescript"),G0e=Dp.configure({dialect:"jsx",props:[v0e.add(e=>e.isTop?[Nit]:void 0)]}),Y0e=Dp.configure({dialect:"jsx ts",props:[v0e.add(e=>e.isTop?[Nit]:void 0)]},"typescript");let Iit=e=>({label:e,type:"keyword"});const Pit="break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(Iit),wxn=Pit.concat(["declare","implements","private","protected","public"].map(Iit));function oW(e={}){let t=e.jsx?e.typescript?Y0e:G0e:e.typescript?X0e:Dp,n=e.typescript?kit.concat(wxn):K0e.concat(Pit);return new _1(t,[Dp.data.of({autocomplete:Ast(Z0e,N0e(n))}),Dp.data.of({autocomplete:jit}),e.jsx?Tit:[]])}function kxn(e){for(;;){if(e.name=="JSXOpenTag"||e.name=="JSXSelfClosingTag"||e.name=="JSXFragmentTag")return e;if(e.name=="JSXEscape"||!e.parent)return null;e=e.parent}}function xNe(e,t,n=e.length){for(let r=t==null?void 0:t.firstChild;r;r=r.nextSibling)if(r.name=="JSXIdentifier"||r.name=="JSXBuiltin"||r.name=="JSXNamespacedName"||r.name=="JSXMemberExpression")return e.sliceString(r.from,Math.min(r.to,n));return""}const Oxn=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),Tit=Jn.inputHandler.of((e,t,n,r,s)=>{if((Oxn?e.composing:e.compositionStarted)||e.state.readOnly||t!=n||r!=">"&&r!="/"||!Dp.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:o}=a,l=o.changeByRange(c=>{var d;let{head:u}=c,f=Ha(o).resolveInner(u-1,-1),m;if(f.name=="JSXStartTag"&&(f=f.parent),!(o.doc.sliceString(u-1,u)!=r||f.name=="JSXAttributeValue"&&f.to>u)){if(r==">"&&f.name=="JSXFragmentTag")return{range:c,changes:{from:u,insert:"</>"}};if(r=="/"&&f.name=="JSXStartCloseTag"){let h=f.parent,p=h.parent;if(p&&h.from==u-2&&((m=xNe(o.doc,p.firstChild,u))||((d=p.firstChild)===null||d===void 0?void 0:d.name)=="JSXFragmentTag")){let x=`${m}>`;return{range:cn.cursor(u+x.length,-1),changes:{from:u,insert:x}}}}else if(r==">"){let h=kxn(f);if(h&&h.name=="JSXOpenTag"&&!/^\/?>|^<\//.test(o.doc.sliceString(u,u+2))&&(m=xNe(o.doc,h,u)))return{range:c,changes:{from:u,insert:`</${m}>`}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([a,o.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)});function Sxn(e,t){return t||(t={parserOptions:{ecmaVersion:2019,sourceType:"module"},env:{browser:!0,node:!0,es6:!0,es2015:!0,es2017:!0,es2020:!0},rules:{}},e.getRules().forEach((n,r)=>{var s;!((s=n.meta.docs)===null||s===void 0)&&s.recommended&&(t.rules[r]=2)})),n=>{let{state:r}=n,s=[];for(let{from:a,to:o}of Dp.findRegions(r)){let l=r.doc.lineAt(a),c={line:l.number-1,col:a-l.from,pos:a};for(let d of e.verify(r.sliceDoc(a,o),t))s.push(jxn(d,r.doc,c))}return s}}function bNe(e,t,n,r){return n.line(e+r.line).from+t+(e==1?r.col-1:-1)}function jxn(e,t,n){let r=bNe(e.line,e.column,t,n),s={from:r,to:e.endLine!=null&&e.endColumn!=1?bNe(e.endLine,e.endColumn,t,n):r,message:e.message,source:e.ruleId?"eslint:"+e.ruleId:"eslint",severity:e.severity==1?"warning":"error"};if(e.fix){let{range:a,text:o}=e.fix,l=a[0]+n.pos-r,c=a[1]+n.pos-r;s.actions=[{name:"fix",apply(d,u){d.dispatch({changes:{from:u+l,to:u+c,insert:o},scrollIntoView:!0})}}]}return s}const bF=Object.freeze(Object.defineProperty({__proto__:null,autoCloseTags:Tit,completionPath:Cit,esLint:Sxn,javascript:oW,javascriptLanguage:Dp,jsxLanguage:G0e,localCompletionSource:jit,scopeCompletionSource:vxn,snippets:K0e,tsxLanguage:Y0e,typescriptLanguage:X0e,typescriptSnippets:kit},Symbol.toStringTag,{value:"Module"})),EI=["_blank","_self","_top","_parent"],$ne=["ascii","utf-8","utf-16","latin1","latin1"],Fne=["get","post","put","delete"],Bne=["application/x-www-form-urlencoded","multipart/form-data","text/plain"],eh=["true","false"],Yr={},Cxn={a:{attrs:{href:null,ping:null,type:null,media:null,target:EI,hreflang:null}},abbr:Yr,address:Yr,area:{attrs:{alt:null,coords:null,href:null,target:null,ping:null,media:null,hreflang:null,type:null,shape:["default","rect","circle","poly"]}},article:Yr,aside:Yr,audio:{attrs:{src:null,mediagroup:null,crossorigin:["anonymous","use-credentials"],preload:["none","metadata","auto"],autoplay:["autoplay"],loop:["loop"],controls:["controls"]}},b:Yr,base:{attrs:{href:null,target:EI}},bdi:Yr,bdo:Yr,blockquote:{attrs:{cite:null}},body:Yr,br:Yr,button:{attrs:{form:null,formaction:null,name:null,value:null,autofocus:["autofocus"],disabled:["autofocus"],formenctype:Bne,formmethod:Fne,formnovalidate:["novalidate"],formtarget:EI,type:["submit","reset","button"]}},canvas:{attrs:{width:null,height:null}},caption:Yr,center:Yr,cite:Yr,code:Yr,col:{attrs:{span:null}},colgroup:{attrs:{span:null}},command:{attrs:{type:["command","checkbox","radio"],label:null,icon:null,radiogroup:null,command:null,title:null,disabled:["disabled"],checked:["checked"]}},data:{attrs:{value:null}},datagrid:{attrs:{disabled:["disabled"],multiple:["multiple"]}},datalist:{attrs:{data:null}},dd:Yr,del:{attrs:{cite:null,datetime:null}},details:{attrs:{open:["open"]}},dfn:Yr,div:Yr,dl:Yr,dt:Yr,em:Yr,embed:{attrs:{src:null,type:null,width:null,height:null}},eventsource:{attrs:{src:null}},fieldset:{attrs:{disabled:["disabled"],form:null,name:null}},figcaption:Yr,figure:Yr,footer:Yr,form:{attrs:{action:null,name:null,"accept-charset":$ne,autocomplete:["on","off"],enctype:Bne,method:Fne,novalidate:["novalidate"],target:EI}},h1:Yr,h2:Yr,h3:Yr,h4:Yr,h5:Yr,h6:Yr,head:{children:["title","base","link","style","meta","script","noscript","command"]},header:Yr,hgroup:Yr,hr:Yr,html:{attrs:{manifest:null}},i:Yr,iframe:{attrs:{src:null,srcdoc:null,name:null,width:null,height:null,sandbox:["allow-top-navigation","allow-same-origin","allow-forms","allow-scripts"],seamless:["seamless"]}},img:{attrs:{alt:null,src:null,ismap:null,usemap:null,width:null,height:null,crossorigin:["anonymous","use-credentials"]}},input:{attrs:{alt:null,dirname:null,form:null,formaction:null,height:null,list:null,max:null,maxlength:null,min:null,name:null,pattern:null,placeholder:null,size:null,src:null,step:null,value:null,width:null,accept:["audio/*","video/*","image/*"],autocomplete:["on","off"],autofocus:["autofocus"],checked:["checked"],disabled:["disabled"],formenctype:Bne,formmethod:Fne,formnovalidate:["novalidate"],formtarget:EI,multiple:["multiple"],readonly:["readonly"],required:["required"],type:["hidden","text","search","tel","url","email","password","datetime","date","month","week","time","datetime-local","number","range","color","checkbox","radio","file","submit","image","reset","button"]}},ins:{attrs:{cite:null,datetime:null}},kbd:Yr,keygen:{attrs:{challenge:null,form:null,name:null,autofocus:["autofocus"],disabled:["disabled"],keytype:["RSA"]}},label:{attrs:{for:null,form:null}},legend:Yr,li:{attrs:{value:null}},link:{attrs:{href:null,type:null,hreflang:null,media:null,sizes:["all","16x16","16x16 32x32","16x16 32x32 64x64"]}},map:{attrs:{name:null}},mark:Yr,menu:{attrs:{label:null,type:["list","context","toolbar"]}},meta:{attrs:{content:null,charset:$ne,name:["viewport","application-name","author","description","generator","keywords"],"http-equiv":["content-language","content-type","default-style","refresh"]}},meter:{attrs:{value:null,min:null,low:null,high:null,max:null,optimum:null}},nav:Yr,noscript:Yr,object:{attrs:{data:null,type:null,name:null,usemap:null,form:null,width:null,height:null,typemustmatch:["typemustmatch"]}},ol:{attrs:{reversed:["reversed"],start:null,type:["1","a","A","i","I"]},children:["li","script","template","ul","ol"]},optgroup:{attrs:{disabled:["disabled"],label:null}},option:{attrs:{disabled:["disabled"],label:null,selected:["selected"],value:null}},output:{attrs:{for:null,form:null,name:null}},p:Yr,param:{attrs:{name:null,value:null}},pre:Yr,progress:{attrs:{value:null,max:null}},q:{attrs:{cite:null}},rp:Yr,rt:Yr,ruby:Yr,samp:Yr,script:{attrs:{type:["text/javascript"],src:null,async:["async"],defer:["defer"],charset:$ne}},section:Yr,select:{attrs:{form:null,name:null,size:null,autofocus:["autofocus"],disabled:["disabled"],multiple:["multiple"]}},slot:{attrs:{name:null}},small:Yr,source:{attrs:{src:null,type:null,media:null}},span:Yr,strong:Yr,style:{attrs:{type:["text/css"],media:null,scoped:null}},sub:Yr,summary:Yr,sup:Yr,table:Yr,tbody:Yr,td:{attrs:{colspan:null,rowspan:null,headers:null}},template:Yr,textarea:{attrs:{dirname:null,form:null,maxlength:null,name:null,placeholder:null,rows:null,cols:null,autofocus:["autofocus"],disabled:["disabled"],readonly:["readonly"],required:["required"],wrap:["soft","hard"]}},tfoot:Yr,th:{attrs:{colspan:null,rowspan:null,headers:null,scope:["row","col","rowgroup","colgroup"]}},thead:Yr,time:{attrs:{datetime:null}},title:Yr,tr:Yr,track:{attrs:{src:null,label:null,default:null,kind:["subtitles","captions","descriptions","chapters","metadata"],srclang:null}},ul:{children:["li","script","template","ul","ol"]},var:Yr,video:{attrs:{src:null,poster:null,width:null,height:null,crossorigin:["anonymous","use-credentials"],preload:["auto","metadata","none"],autoplay:["autoplay"],mediagroup:["movie"],muted:["muted"],controls:["controls"]}},wbr:Yr},_it={accesskey:null,class:null,contenteditable:eh,contextmenu:null,dir:["ltr","rtl","auto"],draggable:["true","false","auto"],dropzone:["copy","move","link","string:","file:"],hidden:["hidden"],id:null,inert:["inert"],itemid:null,itemprop:null,itemref:null,itemscope:["itemscope"],itemtype:null,lang:["ar","bn","de","en-GB","en-US","es","fr","hi","id","ja","pa","pt","ru","tr","zh"],spellcheck:eh,autocorrect:eh,autocapitalize:eh,style:null,tabindex:null,title:null,translate:["yes","no"],rel:["stylesheet","alternate","author","bookmark","help","license","next","nofollow","noreferrer","prefetch","prev","search","tag"],role:"alert application article banner button cell checkbox complementary contentinfo dialog document feed figure form grid gridcell heading img list listbox listitem main navigation region row rowgroup search switch tab table tabpanel textbox timer".split(" "),"aria-activedescendant":null,"aria-atomic":eh,"aria-autocomplete":["inline","list","both","none"],"aria-busy":eh,"aria-checked":["true","false","mixed","undefined"],"aria-controls":null,"aria-describedby":null,"aria-disabled":eh,"aria-dropeffect":null,"aria-expanded":["true","false","undefined"],"aria-flowto":null,"aria-grabbed":["true","false","undefined"],"aria-haspopup":eh,"aria-hidden":eh,"aria-invalid":["true","false","grammar","spelling"],"aria-label":null,"aria-labelledby":null,"aria-level":null,"aria-live":["off","polite","assertive"],"aria-multiline":eh,"aria-multiselectable":eh,"aria-owns":null,"aria-posinset":null,"aria-pressed":["true","false","mixed","undefined"],"aria-readonly":eh,"aria-relevant":null,"aria-required":eh,"aria-selected":["true","false","undefined"],"aria-setsize":null,"aria-sort":["ascending","descending","none","other"],"aria-valuemax":null,"aria-valuemin":null,"aria-valuenow":null,"aria-valuetext":null},Mit="beforeunload copy cut dragstart dragover dragleave dragenter dragend drag paste focus blur change click load mousedown mouseenter mouseleave mouseup keydown keyup resize scroll unload".split(" ").map(e=>"on"+e);for(let e of Mit)_it[e]=null;let rE=class{constructor(t,n){this.tags={...Cxn,...t},this.globalAttrs={..._it,...n},this.allTags=Object.keys(this.tags),this.globalAttrNames=Object.keys(this.globalAttrs)}};rE.default=new rE;function vC(e,t,n=e.length){if(!t)return"";let r=t.firstChild,s=r&&r.getChild("TagName");return s?e.sliceString(s.from,Math.min(s.to,n)):""}function wC(e,t=!1){for(;e;e=e.parent)if(e.name=="Element")if(t)t=!1;else return e;return null}function Eit(e,t,n){let r=n.tags[vC(e,wC(t))];return(r==null?void 0:r.children)||n.allTags}function J0e(e,t){let n=[];for(let r=wC(t);r&&!r.type.isTop;r=wC(r.parent)){let s=vC(e,r);if(s&&r.lastChild.name=="CloseTag")break;s&&n.indexOf(s)<0&&(t.name=="EndTag"||t.from>=r.firstChild.to)&&n.push(s)}return n}const Dit=/^[:\-\.\w\u00b7-\uffff]*$/;function yNe(e,t,n,r,s){let a=/\s*>/.test(e.sliceDoc(s,s+5))?"":">",o=wC(n,n.name=="StartTag"||n.name=="TagName");return{from:r,to:s,options:Eit(e.doc,o,t).map(l=>({label:l,type:"type"})).concat(J0e(e.doc,n).map((l,c)=>({label:"/"+l,apply:"/"+l+a,type:"type",boost:99-c}))),validFor:/^\/?[:\-\.\w\u00b7-\uffff]*$/}}function vNe(e,t,n,r){let s=/\s*>/.test(e.sliceDoc(r,r+5))?"":">";return{from:n,to:r,options:J0e(e.doc,t).map((a,o)=>({label:a,apply:a+s,type:"type",boost:99-o})),validFor:Dit}}function Nxn(e,t,n,r){let s=[],a=0;for(let o of Eit(e.doc,n,t))s.push({label:"<"+o,type:"type"});for(let o of J0e(e.doc,n))s.push({label:"</"+o+">",type:"type",boost:99-a++});return{from:r,to:r,options:s,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}function Ixn(e,t,n,r,s){let a=wC(n),o=a?t.tags[vC(e.doc,a)]:null,l=o&&o.attrs?Object.keys(o.attrs):[],c=o&&o.globalAttrs===!1?l:l.length?l.concat(t.globalAttrNames):t.globalAttrNames;return{from:r,to:s,options:c.map(d=>({label:d,type:"property"})),validFor:Dit}}function Pxn(e,t,n,r,s){var a;let o=(a=n.parent)===null||a===void 0?void 0:a.getChild("AttributeName"),l=[],c;if(o){let d=e.sliceDoc(o.from,o.to),u=t.globalAttrs[d];if(!u){let f=wC(n),m=f?t.tags[vC(e.doc,f)]:null;u=(m==null?void 0:m.attrs)&&m.attrs[d]}if(u){let f=e.sliceDoc(r,s).toLowerCase(),m='"',h='"';/^['"]/.test(f)?(c=f[0]=='"'?/^[^"]*$/:/^[^']*$/,m="",h=e.sliceDoc(s,s+1)==f[0]?"":f[0],f=f.slice(1),r++):c=/^[^\s<>='"]*$/;for(let p of u)l.push({label:p,apply:m+p+h,type:"constant"})}}return{from:r,to:s,options:l,validFor:c}}function Rit(e,t){let{state:n,pos:r}=t,s=Ha(n).resolveInner(r,-1),a=s.resolve(r);for(let o=r,l;a==s&&(l=s.childBefore(o));){let c=l.lastChild;if(!c||!c.type.isError||c.from<c.to)break;a=s=l,o=c.from}return s.name=="TagName"?s.parent&&/CloseTag$/.test(s.parent.name)?vNe(n,s,s.from,r):yNe(n,e,s,s.from,r):s.name=="StartTag"||s.name=="IncompleteTag"?yNe(n,e,s,r,r):s.name=="StartCloseTag"||s.name=="IncompleteCloseTag"?vNe(n,s,r,r):s.name=="OpenTag"||s.name=="SelfClosingTag"||s.name=="AttributeName"?Ixn(n,e,s,s.name=="AttributeName"?s.from:r,r):s.name=="Is"||s.name=="AttributeValue"||s.name=="UnquotedAttributeValue"?Pxn(n,e,s,s.name=="Is"?r:s.from,r):t.explicit&&(a.name=="Element"||a.name=="Text"||a.name=="Document")?Nxn(n,e,s,r):null}function Lit(e){return Rit(rE.default,e)}function zit(e){let{extraTags:t,extraGlobalAttributes:n}=e,r=n||t?new rE(t,n):rE.default;return s=>Rit(r,s)}const Txn=Dp.parser.configure({top:"SingleExpression"}),$it=[{tag:"script",attrs:e=>e.type=="text/typescript"||e.lang=="ts",parser:X0e.parser},{tag:"script",attrs:e=>e.type=="text/babel"||e.type=="text/jsx",parser:G0e.parser},{tag:"script",attrs:e=>e.type=="text/typescript-jsx",parser:Y0e.parser},{tag:"script",attrs(e){return/^(importmap|speculationrules|application\/(.+\+)?json)$/i.test(e.type)},parser:Txn},{tag:"script",attrs(e){return!e.type||/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i.test(e.type)},parser:Dp.parser},{tag:"style",attrs(e){return(!e.lang||e.lang=="css")&&(!e.type||/^(text\/)?(x-)?(stylesheet|css)$/i.test(e.type))},parser:nE.parser}],Fit=[{name:"style",parser:nE.parser.configure({top:"Styles"})}].concat(Mit.map(e=>({name:e,parser:Dp.parser}))),Bit=I0.define({name:"html",parser:F1n.configure({props:[Q2.add({Element(e){let t=/^(\s*)(<\/)?/.exec(e.textAfter);return e.node.to<=e.pos+t[0].length?e.continue():e.lineIndent(e.node.from)+(t[2]?0:e.unit)},"OpenTag CloseTag SelfClosingTag"(e){return e.column(e.node.from)+e.unit},Document(e){if(e.pos+/\s*/.exec(e.textAfter)[0].length<e.node.to)return e.continue();let t=null,n;for(let r=e.node;;){let s=r.lastChild;if(!s||s.name!="Element"||s.to!=r.to)break;t=r=s}return t&&!((n=t.lastChild)&&(n.name=="CloseTag"||n.name=="SelfClosingTag"))?e.lineIndent(t.from)+e.unit:null}}),U2.add({Element(e){let t=e.firstChild,n=e.lastChild;return!t||t.name!="OpenTag"?null:{from:t.to,to:n.name=="CloseTag"?n.from:e.to}}}),ost.add({"OpenTag CloseTag":e=>e.getChild("TagName")})]}),languageData:{commentTokens:{block:{open:"<!--",close:"-->"}},indentOnInput:/^\s*<\/\w+\W$/,wordChars:"-_"}}),t_=Bit.configure({wrap:vit($it,Fit)});function Qit(e={}){let t="",n;e.matchClosingTags===!1&&(t="noMatch"),e.selfClosingTags===!0&&(t=(t?t+" ":"")+"selfClosing"),(e.nestedLanguages&&e.nestedLanguages.length||e.nestedAttributes&&e.nestedAttributes.length)&&(n=vit((e.nestedLanguages||[]).concat($it),(e.nestedAttributes||[]).concat(Fit)));let r=n?Bit.configure({wrap:n,dialect:t}):t?t_.configure({dialect:t}):t_;return new _1(r,[t_.data.of({autocomplete:zit(e)}),e.autoCloseTags!==!1?Uit:[],oW().support,uit().support])}const wNe=new Set("area base br col command embed frame hr img input keygen link meta param source track wbr menuitem".split(" ")),Uit=Jn.inputHandler.of((e,t,n,r,s)=>{if(e.composing||e.state.readOnly||t!=n||r!=">"&&r!="/"||!t_.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:o}=a,l=o.changeByRange(c=>{var d,u,f;let m=o.doc.sliceString(c.from-1,c.to)==r,{head:h}=c,p=Ha(o).resolveInner(h,-1),x;if(m&&r==">"&&p.name=="EndTag"){let b=p.parent;if(((u=(d=b.parent)===null||d===void 0?void 0:d.lastChild)===null||u===void 0?void 0:u.name)!="CloseTag"&&(x=vC(o.doc,b.parent,h))&&!wNe.has(x)){let y=h+(o.doc.sliceString(h,h+1)===">"?1:0),w=`</${x}>`;return{range:c,changes:{from:h,to:y,insert:w}}}}else if(m&&r=="/"&&p.name=="IncompleteCloseTag"){let b=p.parent;if(p.from==h-2&&((f=b.lastChild)===null||f===void 0?void 0:f.name)!="CloseTag"&&(x=vC(o.doc,b,h))&&!wNe.has(x)){let y=h+(o.doc.sliceString(h,h+1)===">"?1:0),w=`${x}>`;return{range:cn.cursor(h+w.length,-1),changes:{from:h,to:y,insert:w}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([a,o.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)}),_xn=Object.freeze(Object.defineProperty({__proto__:null,autoCloseTags:Uit,html:Qit,htmlCompletionSource:Lit,htmlCompletionSourceWith:zit,htmlLanguage:t_},Symbol.toStringTag,{value:"Module"}));function Mxn(e,t,n,r){const s=j0(ic),a=kh(Bet),o=xe.useRef(null),{lexicalNode:l}=cde(),c=xe.useRef(!1),d=xe.useRef(!1),u=xe.useCallback(()=>{a({editorType:t,rootNode:l,editorRef:o.current})},[t,l,a]),f=xe.useCallback(m=>{var h,p,x,b,y,w;if(m.key==="ArrowDown"){const k=(p=(h=o.current)==null?void 0:h.getCodemirror())==null?void 0:p.state;if(k){const S=k.doc.length,j=k.selection.ranges[0].to;S===j&&(c.current?(s==null||s.update(()=>{var C,I;const N=g0(e);N.getNextSibling()?((I=(C=o.current)==null?void 0:C.getCodemirror())==null||I.contentDOM.blur(),N.selectNext()):N.insertAfter(gl())}),c.current=!1):c.current=!0)}}else if(m.key==="ArrowUp"){const k=(b=(x=o.current)==null?void 0:x.getCodemirror())==null?void 0:b.state;k&&k.selection.ranges[0].from===0&&(d.current?(s==null||s.update(()=>{var j,C;const I=g0(e);I.getPreviousSibling()&&((C=(j=o.current)==null?void 0:j.getCodemirror())==null||C.contentDOM.blur(),I.selectPrevious())}),d.current=!1):d.current=!0)}else if(m.key==="Enter")m.stopPropagation();else if(m.key==="Backspace"||m.key==="Delete"){const k=(w=(y=o.current)==null?void 0:y.getCodemirror())==null?void 0:w.state;(k==null?void 0:k.doc.length)===0&&(s==null||s.update(()=>{g0(e).remove()}))}},[s,e]);return xe.useEffect(()=>{const m=o.current;return setTimeout(()=>{var h,p;(h=m==null?void 0:m.getCodemirror())==null||h.contentDOM.addEventListener("focus",u),(p=m==null?void 0:m.getCodemirror())==null||p.contentDOM.addEventListener("keydown",f)},300),()=>{var h,p;(h=m==null?void 0:m.getCodemirror())==null||h.contentDOM.removeEventListener("focus",u),(p=m==null?void 0:m.getCodemirror())==null||p.contentDOM.removeEventListener("keydown",f)}},[o,u,f,n]),xe.useEffect(()=>{r.subscribe(()=>{var m,h;(h=(m=o.current)==null?void 0:m.getCodemirror())==null||h.focus(),u()})},[r,o,e,u]),o}function Dn(e){return new _1(O0e.define(e))}function _v(e){return on(()=>import("./index-6O1Ef9oA.js"),[]).then(t=>t.sql({dialect:t[e]}))}const Exn=[an.of({name:"C",extensions:["c","h","ino"],load(){return on(()=>import("./index-CS2TW9nf.js"),[]).then(e=>e.cpp())}}),an.of({name:"C++",alias:["cpp"],extensions:["cpp","c++","cc","cxx","hpp","h++","hh","hxx"],load(){return on(()=>import("./index-CS2TW9nf.js"),[]).then(e=>e.cpp())}}),an.of({name:"CQL",alias:["cassandra"],extensions:["cql"],load(){return _v("Cassandra")}}),an.of({name:"CSS",extensions:["css"],load(){return on(()=>Promise.resolve().then(()=>n1n),void 0).then(e=>e.css())}}),an.of({name:"Go",extensions:["go"],load(){return on(()=>import("./index-XWYyP2hU.js"),[]).then(e=>e.go())}}),an.of({name:"HTML",alias:["xhtml"],extensions:["html","htm","handlebars","hbs"],load(){return on(()=>Promise.resolve().then(()=>_xn),void 0).then(e=>e.html())}}),an.of({name:"Java",extensions:["java"],load(){return on(()=>import("./index-B-yeMW3t.js"),[]).then(e=>e.java())}}),an.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return on(()=>Promise.resolve().then(()=>bF),void 0).then(e=>e.javascript())}}),an.of({name:"Jinja",extensions:["j2","jinja","jinja2"],load(){return on(()=>import("./index-Aj3Mi7R6.js"),[]).then(e=>e.jinja())}}),an.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return on(()=>Promise.resolve().then(()=>eUn),void 0).then(e=>e.json())}}),an.of({name:"JSX",extensions:["jsx"],load(){return on(()=>Promise.resolve().then(()=>bF),void 0).then(e=>e.javascript({jsx:!0}))}}),an.of({name:"LESS",extensions:["less"],load(){return on(()=>import("./index-BABow2kh.js"),[]).then(e=>e.less())}}),an.of({name:"Liquid",extensions:["liquid"],load(){return on(()=>import("./index-BueQLOw6.js"),[]).then(e=>e.liquid())}}),an.of({name:"MariaDB SQL",load(){return _v("MariaSQL")}}),an.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return on(()=>Promise.resolve().then(()=>kbn),void 0).then(e=>e.markdown())}}),an.of({name:"MS SQL",load(){return _v("MSSQL")}}),an.of({name:"MySQL",load(){return _v("MySQL")}}),an.of({name:"PHP",extensions:["php","php3","php4","php5","php7","phtml"],load(){return on(()=>import("./index-BlFoD6Gg.js"),[]).then(e=>e.php())}}),an.of({name:"PLSQL",extensions:["pls"],load(){return _v("PLSQL")}}),an.of({name:"PostgreSQL",load(){return _v("PostgreSQL")}}),an.of({name:"Python",extensions:["BUILD","bzl","py","pyw"],filename:/^(BUCK|BUILD)$/,load(){return on(()=>Promise.resolve().then(()=>Aqn),void 0).then(e=>e.python())}}),an.of({name:"Rust",extensions:["rs"],load(){return on(()=>import("./index-BEgTumxB.js"),[]).then(e=>e.rust())}}),an.of({name:"Sass",extensions:["sass"],load(){return on(()=>import("./index-CdAtz86o.js"),[]).then(e=>e.sass({indented:!0}))}}),an.of({name:"SCSS",extensions:["scss"],load(){return on(()=>import("./index-CdAtz86o.js"),[]).then(e=>e.sass())}}),an.of({name:"SQL",extensions:["sql"],load(){return _v("StandardSQL")}}),an.of({name:"SQLite",load(){return _v("SQLite")}}),an.of({name:"TSX",extensions:["tsx"],load(){return on(()=>Promise.resolve().then(()=>bF),void 0).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),an.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return on(()=>Promise.resolve().then(()=>bF),void 0).then(e=>e.javascript({typescript:!0}))}}),an.of({name:"WebAssembly",extensions:["wat","wast"],load(){return on(()=>import("./index-E2v-0TkN.js"),[]).then(e=>e.wast())}}),an.of({name:"XML",alias:["rss","wsdl","xsd"],extensions:["xml","xsl","xsd","svg"],load(){return on(()=>import("./index-CcWXJMSa.js"),[]).then(e=>e.xml())}}),an.of({name:"YAML",alias:["yml"],extensions:["yaml","yml"],load(){return on(()=>Promise.resolve().then(()=>Wqn),void 0).then(e=>e.yaml())}}),an.of({name:"APL",extensions:["dyalog","apl"],load(){return on(()=>import("./apl-B4CMkyY2.js"),[]).then(e=>Dn(e.apl))}}),an.of({name:"PGP",alias:["asciiarmor"],extensions:["asc","pgp","sig"],load(){return on(()=>import("./asciiarmor-Df11BRmG.js"),[]).then(e=>Dn(e.asciiArmor))}}),an.of({name:"ASN.1",extensions:["asn","asn1"],load(){return on(()=>import("./asn1-EdZsLKOL.js"),[]).then(e=>Dn(e.asn1({})))}}),an.of({name:"Asterisk",filename:/^extensions\.conf$/i,load(){return on(()=>import("./asterisk-B-8jnY81.js"),[]).then(e=>Dn(e.asterisk))}}),an.of({name:"Brainfuck",extensions:["b","bf"],load(){return on(()=>import("./brainfuck-C4LP7Hcl.js"),[]).then(e=>Dn(e.brainfuck))}}),an.of({name:"Cobol",extensions:["cob","cpy"],load(){return on(()=>import("./cobol-CWcv1MsR.js"),[]).then(e=>Dn(e.cobol))}}),an.of({name:"C#",alias:["csharp","cs"],extensions:["cs"],load(){return on(()=>import("./clike-B9uivgTg.js"),[]).then(e=>Dn(e.csharp))}}),an.of({name:"Clojure",extensions:["clj","cljc","cljx"],load(){return on(()=>import("./clojure-BMjYHr_A.js"),[]).then(e=>Dn(e.clojure))}}),an.of({name:"ClojureScript",extensions:["cljs"],load(){return on(()=>import("./clojure-BMjYHr_A.js"),[]).then(e=>Dn(e.clojure))}}),an.of({name:"Closure Stylesheets (GSS)",extensions:["gss"],load(){return on(()=>import("./css-BnMrqG3P.js"),[]).then(e=>Dn(e.gss))}}),an.of({name:"CMake",extensions:["cmake","cmake.in"],filename:/^CMakeLists\.txt$/,load(){return on(()=>import("./cmake-BQqOBYOt.js"),[]).then(e=>Dn(e.cmake))}}),an.of({name:"CoffeeScript",alias:["coffee","coffee-script"],extensions:["coffee"],load(){return on(()=>import("./coffeescript-S37ZYGWr.js"),[]).then(e=>Dn(e.coffeeScript))}}),an.of({name:"Common Lisp",alias:["lisp"],extensions:["cl","lisp","el"],load(){return on(()=>import("./commonlisp-DBKNyK5s.js"),[]).then(e=>Dn(e.commonLisp))}}),an.of({name:"Cypher",extensions:["cyp","cypher"],load(){return on(()=>import("./cypher-C_CwsFkJ.js"),[]).then(e=>Dn(e.cypher))}}),an.of({name:"Cython",extensions:["pyx","pxd","pxi"],load(){return on(()=>import("./python-BuPzkPfP.js"),[]).then(e=>Dn(e.cython))}}),an.of({name:"Crystal",extensions:["cr"],load(){return on(()=>import("./crystal-SjHAIU92.js"),[]).then(e=>Dn(e.crystal))}}),an.of({name:"D",extensions:["d"],load(){return on(()=>import("./d-pRatUO7H.js"),[]).then(e=>Dn(e.d))}}),an.of({name:"Dart",extensions:["dart"],load(){return on(()=>import("./clike-B9uivgTg.js"),[]).then(e=>Dn(e.dart))}}),an.of({name:"diff",extensions:["diff","patch"],load(){return on(()=>import("./diff-DbItnlRl.js"),[]).then(e=>Dn(e.diff))}}),an.of({name:"Dockerfile",filename:/^Dockerfile$/,load(){return on(()=>import("./dockerfile-BKs6k2Af.js"),__vite__mapDeps([0,1])).then(e=>Dn(e.dockerFile))}}),an.of({name:"DTD",extensions:["dtd"],load(){return on(()=>import("./dtd-DF_7sFjM.js"),[]).then(e=>Dn(e.dtd))}}),an.of({name:"Dylan",extensions:["dylan","dyl","intr"],load(){return on(()=>import("./dylan-DwRh75JA.js"),[]).then(e=>Dn(e.dylan))}}),an.of({name:"EBNF",load(){return on(()=>import("./ebnf-CDyGwa7X.js"),[]).then(e=>Dn(e.ebnf))}}),an.of({name:"ECL",extensions:["ecl"],load(){return on(()=>import("./ecl-Cabwm37j.js"),[]).then(e=>Dn(e.ecl))}}),an.of({name:"edn",extensions:["edn"],load(){return on(()=>import("./clojure-BMjYHr_A.js"),[]).then(e=>Dn(e.clojure))}}),an.of({name:"Eiffel",extensions:["e"],load(){return on(()=>import("./eiffel-CnydiIhH.js"),[]).then(e=>Dn(e.eiffel))}}),an.of({name:"Elm",extensions:["elm"],load(){return on(()=>import("./elm-vLlmbW-K.js"),[]).then(e=>Dn(e.elm))}}),an.of({name:"Erlang",extensions:["erl"],load(){return on(()=>import("./erlang-BNw1qcRV.js"),[]).then(e=>Dn(e.erlang))}}),an.of({name:"Esper",load(){return on(()=>import("./sql-D0XecflT.js"),[]).then(e=>Dn(e.esper))}}),an.of({name:"Factor",extensions:["factor"],load(){return on(()=>import("./factor-kuTfRLto.js"),__vite__mapDeps([2,1])).then(e=>Dn(e.factor))}}),an.of({name:"FCL",load(){return on(()=>import("./fcl-Kvtd6kyn.js"),[]).then(e=>Dn(e.fcl))}}),an.of({name:"Forth",extensions:["forth","fth","4th"],load(){return on(()=>import("./forth-Ffai-XNe.js"),[]).then(e=>Dn(e.forth))}}),an.of({name:"Fortran",extensions:["f","for","f77","f90","f95"],load(){return on(()=>import("./fortran-DYz_wnZ1.js"),[]).then(e=>Dn(e.fortran))}}),an.of({name:"F#",alias:["fsharp"],extensions:["fs"],load(){return on(()=>import("./mllike-CXdrOF99.js"),[]).then(e=>Dn(e.fSharp))}}),an.of({name:"Gas",extensions:["s"],load(){return on(()=>import("./gas-Bneqetm1.js"),[]).then(e=>Dn(e.gas))}}),an.of({name:"Gherkin",extensions:["feature"],load(){return on(()=>import("./gherkin-heZmZLOM.js"),[]).then(e=>Dn(e.gherkin))}}),an.of({name:"Groovy",extensions:["groovy","gradle"],filename:/^Jenkinsfile$/,load(){return on(()=>import("./groovy-D9Dt4D0W.js"),[]).then(e=>Dn(e.groovy))}}),an.of({name:"Haskell",extensions:["hs"],load(){return on(()=>import("./haskell-Cw1EW3IL.js"),[]).then(e=>Dn(e.haskell))}}),an.of({name:"Haxe",extensions:["hx"],load(){return on(()=>import("./haxe-H-WmDvRZ.js"),[]).then(e=>Dn(e.haxe))}}),an.of({name:"HXML",extensions:["hxml"],load(){return on(()=>import("./haxe-H-WmDvRZ.js"),[]).then(e=>Dn(e.hxml))}}),an.of({name:"HTTP",load(){return on(()=>import("./http-DBlCnlav.js"),[]).then(e=>Dn(e.http))}}),an.of({name:"IDL",extensions:["pro"],load(){return on(()=>import("./idl-BEugSyMb.js"),[]).then(e=>Dn(e.idl))}}),an.of({name:"JSON-LD",alias:["jsonld"],extensions:["jsonld"],load(){return on(()=>import("./javascript-iXu5QeM3.js"),[]).then(e=>Dn(e.jsonld))}}),an.of({name:"Julia",extensions:["jl"],load(){return on(()=>import("./julia-DuME0IfC.js"),[]).then(e=>Dn(e.julia))}}),an.of({name:"Kotlin",extensions:["kt","kts"],load(){return on(()=>import("./clike-B9uivgTg.js"),[]).then(e=>Dn(e.kotlin))}}),an.of({name:"LiveScript",alias:["ls"],extensions:["ls"],load(){return on(()=>import("./livescript-BwQOo05w.js"),[]).then(e=>Dn(e.liveScript))}}),an.of({name:"Lua",extensions:["lua"],load(){return on(()=>import("./lua-BgMRiT3U.js"),[]).then(e=>Dn(e.lua))}}),an.of({name:"mIRC",extensions:["mrc"],load(){return on(()=>import("./mirc-CjQqDB4T.js"),[]).then(e=>Dn(e.mirc))}}),an.of({name:"Mathematica",extensions:["m","nb","wl","wls"],load(){return on(()=>import("./mathematica-DTrFuWx2.js"),[]).then(e=>Dn(e.mathematica))}}),an.of({name:"Modelica",extensions:["mo"],load(){return on(()=>import("./modelica-Dc1JOy9r.js"),[]).then(e=>Dn(e.modelica))}}),an.of({name:"MUMPS",extensions:["mps"],load(){return on(()=>import("./mumps-BT43cFF4.js"),[]).then(e=>Dn(e.mumps))}}),an.of({name:"Mbox",extensions:["mbox"],load(){return on(()=>import("./mbox-CNhZ1qSd.js"),[]).then(e=>Dn(e.mbox))}}),an.of({name:"Nginx",filename:/nginx.*\.conf$/i,load(){return on(()=>import("./nginx-DdIZxoE0.js"),[]).then(e=>Dn(e.nginx))}}),an.of({name:"NSIS",extensions:["nsh","nsi"],load(){return on(()=>import("./nsis-LdVXkNf5.js"),__vite__mapDeps([3,1])).then(e=>Dn(e.nsis))}}),an.of({name:"NTriples",extensions:["nt","nq"],load(){return on(()=>import("./ntriples-BfvgReVJ.js"),[]).then(e=>Dn(e.ntriples))}}),an.of({name:"Objective-C",alias:["objective-c","objc"],extensions:["m"],load(){return on(()=>import("./clike-B9uivgTg.js"),[]).then(e=>Dn(e.objectiveC))}}),an.of({name:"Objective-C++",alias:["objective-c++","objc++"],extensions:["mm"],load(){return on(()=>import("./clike-B9uivgTg.js"),[]).then(e=>Dn(e.objectiveCpp))}}),an.of({name:"OCaml",extensions:["ml","mli","mll","mly"],load(){return on(()=>import("./mllike-CXdrOF99.js"),[]).then(e=>Dn(e.oCaml))}}),an.of({name:"Octave",extensions:["m"],load(){return on(()=>import("./octave-Ck1zUtKM.js"),[]).then(e=>Dn(e.octave))}}),an.of({name:"Oz",extensions:["oz"],load(){return on(()=>import("./oz-BzwKVEFT.js"),[]).then(e=>Dn(e.oz))}}),an.of({name:"Pascal",extensions:["p","pas"],load(){return on(()=>import("./pascal--L3eBynH.js"),[]).then(e=>Dn(e.pascal))}}),an.of({name:"Perl",extensions:["pl","pm"],load(){return on(()=>import("./perl-CdXCOZ3F.js"),[]).then(e=>Dn(e.perl))}}),an.of({name:"Pig",extensions:["pig"],load(){return on(()=>import("./pig-CevX1Tat.js"),[]).then(e=>Dn(e.pig))}}),an.of({name:"PowerShell",extensions:["ps1","psd1","psm1"],load(){return on(()=>import("./powershell-CFHJl5sT.js"),[]).then(e=>Dn(e.powerShell))}}),an.of({name:"Properties files",alias:["ini","properties"],extensions:["properties","ini","in"],load(){return on(()=>import("./properties-C78fOPTZ.js"),[]).then(e=>Dn(e.properties))}}),an.of({name:"ProtoBuf",extensions:["proto"],load(){return on(()=>import("./protobuf-ChK-085T.js"),[]).then(e=>Dn(e.protobuf))}}),an.of({name:"Pug",alias:["jade"],extensions:["pug","jade"],load(){return on(()=>import("./pug-DeIclll2.js"),__vite__mapDeps([4,5])).then(e=>Dn(e.pug))}}),an.of({name:"Puppet",extensions:["pp"],load(){return on(()=>import("./puppet-DMA9R1ak.js"),[]).then(e=>Dn(e.puppet))}}),an.of({name:"Q",extensions:["q"],load(){return on(()=>import("./q-pXgVlZs6.js"),[]).then(e=>Dn(e.q))}}),an.of({name:"R",alias:["rscript"],extensions:["r","R"],load(){return on(()=>import("./r-B6wPVr8A.js"),[]).then(e=>Dn(e.r))}}),an.of({name:"RPM Changes",load(){return on(()=>import("./rpm-CTu-6PCP.js"),[]).then(e=>Dn(e.rpmChanges))}}),an.of({name:"RPM Spec",extensions:["spec"],load(){return on(()=>import("./rpm-CTu-6PCP.js"),[]).then(e=>Dn(e.rpmSpec))}}),an.of({name:"Ruby",alias:["jruby","macruby","rake","rb","rbx"],extensions:["rb"],filename:/^(Gemfile|Rakefile)$/,load(){return on(()=>import("./ruby-B2Rjki9n.js"),[]).then(e=>Dn(e.ruby))}}),an.of({name:"SAS",extensions:["sas"],load(){return on(()=>import("./sas-B4kiWyti.js"),[]).then(e=>Dn(e.sas))}}),an.of({name:"Scala",extensions:["scala"],load(){return on(()=>import("./clike-B9uivgTg.js"),[]).then(e=>Dn(e.scala))}}),an.of({name:"Scheme",extensions:["scm","ss"],load(){return on(()=>import("./scheme-C41bIUwD.js"),[]).then(e=>Dn(e.scheme))}}),an.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return on(()=>import("./shell-CjFT_Tl9.js"),[]).then(e=>Dn(e.shell))}}),an.of({name:"Sieve",extensions:["siv","sieve"],load(){return on(()=>import("./sieve-C3Gn_uJK.js"),[]).then(e=>Dn(e.sieve))}}),an.of({name:"Smalltalk",extensions:["st"],load(){return on(()=>import("./smalltalk-CnHTOXQT.js"),[]).then(e=>Dn(e.smalltalk))}}),an.of({name:"Solr",load(){return on(()=>import("./solr-DehyRSwq.js"),[]).then(e=>Dn(e.solr))}}),an.of({name:"SML",extensions:["sml","sig","fun","smackspec"],load(){return on(()=>import("./mllike-CXdrOF99.js"),[]).then(e=>Dn(e.sml))}}),an.of({name:"SPARQL",alias:["sparul"],extensions:["rq","sparql"],load(){return on(()=>import("./sparql-DkYu6x3z.js"),[]).then(e=>Dn(e.sparql))}}),an.of({name:"Spreadsheet",alias:["excel","formula"],load(){return on(()=>import("./spreadsheet-BCZA_wO0.js"),[]).then(e=>Dn(e.spreadsheet))}}),an.of({name:"Squirrel",extensions:["nut"],load(){return on(()=>import("./clike-B9uivgTg.js"),[]).then(e=>Dn(e.squirrel))}}),an.of({name:"Stylus",extensions:["styl"],load(){return on(()=>import("./stylus-B533Al4x.js"),[]).then(e=>Dn(e.stylus))}}),an.of({name:"Swift",extensions:["swift"],load(){return on(()=>import("./swift-BzpIVaGY.js"),[]).then(e=>Dn(e.swift))}}),an.of({name:"sTeX",load(){return on(()=>import("./stex-C3f8Ysf7.js"),[]).then(e=>Dn(e.stex))}}),an.of({name:"LaTeX",alias:["tex"],extensions:["text","ltx","tex"],load(){return on(()=>import("./stex-C3f8Ysf7.js"),[]).then(e=>Dn(e.stex))}}),an.of({name:"SystemVerilog",extensions:["v","sv","svh"],load(){return on(()=>import("./verilog-C6RDOZhf.js"),[]).then(e=>Dn(e.verilog))}}),an.of({name:"Tcl",extensions:["tcl"],load(){return on(()=>import("./tcl-DVfN8rqt.js"),[]).then(e=>Dn(e.tcl))}}),an.of({name:"Textile",extensions:["textile"],load(){return on(()=>import("./textile-CnDTJFAw.js"),[]).then(e=>Dn(e.textile))}}),an.of({name:"TiddlyWiki",load(){return on(()=>import("./tiddlywiki-DO-Gjzrf.js"),[]).then(e=>Dn(e.tiddlyWiki))}}),an.of({name:"Tiki wiki",load(){return on(()=>import("./tiki-DGYXhP31.js"),[]).then(e=>Dn(e.tiki))}}),an.of({name:"TOML",extensions:["toml"],load(){return on(()=>import("./toml-Bm5Em-hy.js"),[]).then(e=>Dn(e.toml))}}),an.of({name:"Troff",extensions:["1","2","3","4","5","6","7","8","9"],load(){return on(()=>import("./troff-wAsdV37c.js"),[]).then(e=>Dn(e.troff))}}),an.of({name:"TTCN",extensions:["ttcn","ttcn3","ttcnpp"],load(){return on(()=>import("./ttcn-CfJYG6tj.js"),[]).then(e=>Dn(e.ttcn))}}),an.of({name:"TTCN_CFG",extensions:["cfg"],load(){return on(()=>import("./ttcn-cfg-B9xdYoR4.js"),[]).then(e=>Dn(e.ttcnCfg))}}),an.of({name:"Turtle",extensions:["ttl"],load(){return on(()=>import("./turtle-B1tBg_DP.js"),[]).then(e=>Dn(e.turtle))}}),an.of({name:"Web IDL",extensions:["webidl"],load(){return on(()=>import("./webidl-ZXfAyPTL.js"),[]).then(e=>Dn(e.webIDL))}}),an.of({name:"VB.NET",extensions:["vb"],load(){return on(()=>import("./vb-CmGdzxic.js"),[]).then(e=>Dn(e.vb))}}),an.of({name:"VBScript",extensions:["vbs"],load(){return on(()=>import("./vbscript-BuJXcnF6.js"),[]).then(e=>Dn(e.vbScript))}}),an.of({name:"Velocity",extensions:["vtl"],load(){return on(()=>import("./velocity-D8B20fx6.js"),[]).then(e=>Dn(e.velocity))}}),an.of({name:"Verilog",extensions:["v"],load(){return on(()=>import("./verilog-C6RDOZhf.js"),[]).then(e=>Dn(e.verilog))}}),an.of({name:"VHDL",extensions:["vhd","vhdl"],load(){return on(()=>import("./vhdl-lSbBsy5d.js"),[]).then(e=>Dn(e.vhdl))}}),an.of({name:"XQuery",extensions:["xy","xquery","xq","xqm","xqy"],load(){return on(()=>import("./xquery-DzFWVndE.js"),[]).then(e=>Dn(e.xQuery))}}),an.of({name:"Yacas",extensions:["ys"],load(){return on(()=>import("./yacas-BJ4BC0dw.js"),[]).then(e=>Dn(e.yacas))}}),an.of({name:"Z80",extensions:["z80"],load(){return on(()=>import("./z80-Hz9HOZM7.js"),[]).then(e=>Dn(e.z80))}}),an.of({name:"MscGen",extensions:["mscgen","mscin","msc"],load(){return on(()=>import("./mscgen-BA5vi2Kp.js"),[]).then(e=>Dn(e.mscgen))}}),an.of({name:"Xù",extensions:["xu"],load(){return on(()=>import("./mscgen-BA5vi2Kp.js"),[]).then(e=>Dn(e.xu))}}),an.of({name:"MsGenny",extensions:["msgenny"],load(){return on(()=>import("./mscgen-BA5vi2Kp.js"),[]).then(e=>Dn(e.msgenny))}}),an.of({name:"Vue",extensions:["vue"],load(){return on(()=>import("./index-CMUgKK2j.js"),[]).then(e=>e.vue())}}),an.of({name:"Angular Template",load(){return on(()=>import("./index-BQheb_6L.js"),[]).then(e=>e.angular())}})],kNe="#2e3440",ebe="#3b4252",ONe="#434c5e",yF="#4c566a",SNe="#e5e9f0",cue="#eceff4",Qne="#8fbcbb",jNe="#88c0d0",Dxn="#81a1c1",vg="#5e81ac",Rxn="#bf616a",D7="#d08770",Une="#ebcb8b",CNe="#a3be8c",Lxn="#b48ead",NNe="#d30102",tbe=cue,qne=tbe,zxn="#ffffff",Vne=ebe,$xn=tbe,INe=ebe,Fxn=Jn.theme({"&":{color:kNe,backgroundColor:zxn},".cm-content":{caretColor:INe},".cm-cursor, .cm-dropCursor":{borderLeftColor:INe},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:$xn},".cm-panels":{backgroundColor:tbe,color:yF},".cm-panels.cm-panels-top":{borderBottom:"2px solid black"},".cm-panels.cm-panels-bottom":{borderTop:"2px solid black"},".cm-searchMatch":{backgroundColor:"#72a1ff59",outline:`1px solid ${yF}`},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:SNe},".cm-activeLine":{backgroundColor:qne},".cm-selectionMatch":{backgroundColor:SNe},"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket":{outline:`1px solid ${yF}`},"&.cm-focused .cm-matchingBracket":{backgroundColor:cue},".cm-gutters":{backgroundColor:cue,color:kNe,border:"none"},".cm-activeLineGutter":{backgroundColor:qne},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:Vne},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:Vne,borderBottomColor:Vne},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:qne,color:yF}}},{dark:!1}),Bxn=T8.define([{tag:Xe.keyword,color:vg},{tag:[Xe.name,Xe.deleted,Xe.character,Xe.propertyName,Xe.macroName],color:D7},{tag:[Xe.variableName],color:D7},{tag:[Xe.function(Xe.variableName)],color:vg},{tag:[Xe.labelName],color:Dxn},{tag:[Xe.color,Xe.constant(Xe.name),Xe.standard(Xe.name)],color:vg},{tag:[Xe.definition(Xe.name),Xe.separator],color:CNe},{tag:[Xe.brace],color:Qne},{tag:[Xe.annotation],color:NNe},{tag:[Xe.number,Xe.changed,Xe.annotation,Xe.modifier,Xe.self,Xe.namespace],color:jNe},{tag:[Xe.typeName,Xe.className],color:Une},{tag:[Xe.operator,Xe.operatorKeyword],color:CNe},{tag:[Xe.tagName],color:Lxn},{tag:[Xe.squareBracket],color:Rxn},{tag:[Xe.angleBracket],color:D7},{tag:[Xe.attributeName],color:Une},{tag:[Xe.regexp],color:vg},{tag:[Xe.quote],color:ebe},{tag:[Xe.string],color:D7},{tag:Xe.link,color:Qne,textDecoration:"underline",textUnderlinePosition:"under"},{tag:[Xe.url,Xe.escape,Xe.special(Xe.string)],color:D7},{tag:[Xe.meta],color:jNe},{tag:[Xe.comment],color:ONe,fontStyle:"italic"},{tag:Xe.strong,fontWeight:"bold",color:vg},{tag:Xe.emphasis,fontStyle:"italic",color:vg},{tag:Xe.strikethrough,textDecoration:"line-through"},{tag:Xe.heading,fontWeight:"bold",color:vg},{tag:Xe.special(Xe.heading1),fontWeight:"bold",color:vg},{tag:Xe.heading1,fontWeight:"bold",color:vg},{tag:[Xe.heading2,Xe.heading3,Xe.heading4],fontWeight:"bold",color:vg},{tag:[Xe.heading5,Xe.heading6],color:vg},{tag:[Xe.atom,Xe.bool,Xe.special(Xe.variableName)],color:D7},{tag:[Xe.processingInstruction,Xe.inserted],color:Qne},{tag:[Xe.contentSeparator],color:Une},{tag:Xe.invalid,color:ONe,borderBottom:`1px dotted ${NNe}`}]),Qxn=[Fxn,cG(Bxn)],PNe=typeof String.prototype.normalize=="function"?e=>e.normalize("NFKD"):e=>e;class kC{constructor(t,n,r=0,s=t.length,a,o){this.test=o,this.value={from:0,to:0},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=t.iterRange(r,s),this.bufferStart=r,this.normalize=a?l=>a(PNe(l)):PNe,this.query=this.normalize(n)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return hA(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let t=this.peek();if(t<0)return this.done=!0,this;let n=Gxe(t),r=this.bufferStart+this.bufferPos;this.bufferPos+=Xx(t);let s=this.normalize(n);if(s.length)for(let a=0,o=r;;a++){let l=s.charCodeAt(a),c=this.match(l,o,this.bufferPos+this.bufferStart);if(a==s.length-1){if(c)return this.value=c,this;break}o==r&&a<n.length&&n.charCodeAt(a)==l&&o++}}}match(t,n,r){let s=null;for(let a=0;a<this.matches.length;a+=2){let o=this.matches[a],l=!1;this.query.charCodeAt(o)==t&&(o==this.query.length-1?s={from:this.matches[a+1],to:r}:(this.matches[a]++,l=!0)),l||(this.matches.splice(a,2),a-=2)}return this.query.charCodeAt(0)==t&&(this.query.length==1?s={from:n,to:r}:this.matches.push(1,n)),s&&this.test&&!this.test(s.from,s.to,this.buffer,this.bufferStart)&&(s=null),s}}typeof Symbol<"u"&&(kC.prototype[Symbol.iterator]=function(){return this});const qit={from:-1,to:-1,match:/.*/.exec("")},nbe="gm"+(/x/.unicode==null?"":"u");class Vit{constructor(t,n,r,s=0,a=t.length){if(this.text=t,this.to=a,this.curLine="",this.done=!1,this.value=qit,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new Wit(t,n,r,s,a);this.re=new RegExp(n,nbe+(r!=null&&r.ignoreCase?"i":"")),this.test=r==null?void 0:r.test,this.iter=t.iter();let o=t.lineAt(s);this.curLineStart=o.from,this.matchPos=lW(t,s),this.getLine(this.curLineStart)}getLine(t){this.iter.next(t),this.iter.lineBreak?this.curLine="":(this.curLine=this.iter.value,this.curLineStart+this.curLine.length>this.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let t=this.matchPos-this.curLineStart;;){this.re.lastIndex=t;let n=this.matchPos<=this.to&&this.re.exec(this.curLine);if(n){let r=this.curLineStart+n.index,s=r+n[0].length;if(this.matchPos=lW(this.text,s+(r==s?1:0)),r==this.curLineStart+this.curLine.length&&this.nextLine(),(r<s||r>this.value.to)&&(!this.test||this.test(r,s,n)))return this.value={from:r,to:s,match:n},this;t=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length<this.to)this.nextLine(),t=0;else return this.done=!0,this}}}const Wne=new WeakMap;class LS{constructor(t,n){this.from=t,this.text=n}get to(){return this.from+this.text.length}static get(t,n,r){let s=Wne.get(t);if(!s||s.from>=r||s.to<=n){let l=new LS(n,t.sliceString(n,r));return Wne.set(t,l),l}if(s.from==n&&s.to==r)return s;let{text:a,from:o}=s;return o>n&&(a=t.sliceString(n,o)+a,o=n),s.to<r&&(a+=t.sliceString(s.to,r)),Wne.set(t,new LS(o,a)),new LS(n,a.slice(n-o,r-o))}}class Wit{constructor(t,n,r,s,a){this.text=t,this.to=a,this.done=!1,this.value=qit,this.matchPos=lW(t,s),this.re=new RegExp(n,nbe+(r!=null&&r.ignoreCase?"i":"")),this.test=r==null?void 0:r.test,this.flat=LS.get(t,s,this.chunkEnd(s+5e3))}chunkEnd(t){return t>=this.to?this.to:this.text.lineAt(t).to}next(){for(;;){let t=this.re.lastIndex=this.matchPos-this.flat.from,n=this.re.exec(this.flat.text);if(n&&!n[0]&&n.index==t&&(this.re.lastIndex=t+1,n=this.re.exec(this.flat.text)),n){let r=this.flat.from+n.index,s=r+n[0].length;if((this.flat.to>=this.to||n.index+n[0].length<=this.flat.text.length-10)&&(!this.test||this.test(r,s,n)))return this.value={from:r,to:s,match:n},this.matchPos=lW(this.text,s+(r==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=LS.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(Vit.prototype[Symbol.iterator]=Wit.prototype[Symbol.iterator]=function(){return this});function Uxn(e){try{return new RegExp(e,nbe),!0}catch{return!1}}function lW(e,t){if(t>=e.length)return t;let n=e.lineAt(t),r;for(;t<n.to&&(r=n.text.charCodeAt(t-n.from))>=56320&&r<57344;)t++;return t}const qxn=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:s}=Rmn(e,{label:t.phrase("Go to line"),input:{type:"text",name:"line",value:n},focus:!0,submitLabel:t.phrase("go")});return s.then(a=>{let o=a&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(a.elements.line.value);if(!o){e.dispatch({effects:r});return}let l=t.doc.lineAt(t.selection.main.head),[,c,d,u,f]=o,m=u?+u.slice(1):0,h=d?+d:l.number;if(d&&f){let b=h/100;c&&(b=b*(c=="-"?-1:1)+l.number/t.doc.lines),h=Math.round(t.doc.lines*b)}else d&&c&&(h=h*(c=="-"?-1:1)+l.number);let p=t.doc.line(Math.max(1,Math.min(t.doc.lines,h))),x=cn.cursor(p.from+Math.max(0,Math.min(m,p.length)));e.dispatch({effects:[r,Jn.scrollIntoView(x.from,{y:"center"})],selection:x})}),!0},Vxn={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},Wxn=jr.define({combine(e){return W0(e,Vxn,{highlightWordAroundCursor:(t,n)=>t||n,minSelectionLength:Math.min,maxMatches:Math.min})}});function Hxn(e){return[Yxn,Gxn]}const Kxn=Nr.mark({class:"cm-selectionMatch"}),Zxn=Nr.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function TNe(e,t,n,r){return(n==0||e(t.sliceDoc(n-1,n))!=ac.Word)&&(r==t.doc.length||e(t.sliceDoc(r,r+1))!=ac.Word)}function Xxn(e,t,n,r){return e(t.sliceDoc(n,n+1))==ac.Word&&e(t.sliceDoc(r-1,r))==ac.Word}const Gxn=id.fromClass(class{constructor(e){this.decorations=this.getDeco(e)}update(e){(e.selectionSet||e.docChanged||e.viewportChanged)&&(this.decorations=this.getDeco(e.view))}getDeco(e){let t=e.state.facet(Wxn),{state:n}=e,r=n.selection;if(r.ranges.length>1)return Nr.none;let s=r.main,a,o=null;if(s.empty){if(!t.highlightWordAroundCursor)return Nr.none;let c=n.wordAt(s.head);if(!c)return Nr.none;o=n.charCategorizer(s.head),a=n.sliceDoc(c.from,c.to)}else{let c=s.to-s.from;if(c<t.minSelectionLength||c>200)return Nr.none;if(t.wholeWords){if(a=n.sliceDoc(s.from,s.to),o=n.charCategorizer(s.head),!(TNe(o,n,s.from,s.to)&&Xxn(o,n,s.from,s.to)))return Nr.none}else if(a=n.sliceDoc(s.from,s.to),!a)return Nr.none}let l=[];for(let c of e.visibleRanges){let d=new kC(n.doc,a,c.from,c.to);for(;!d.next().done;){let{from:u,to:f}=d.value;if((!o||TNe(o,n,u,f))&&(s.empty&&u<=s.from&&f>=s.to?l.push(Zxn.range(u,f)):(u>=s.to||f<=s.from)&&l.push(Kxn.range(u,f)),l.length>t.maxMatches))return Nr.none}}return Nr.set(l)}},{decorations:e=>e.decorations}),Yxn=Jn.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),Jxn=({state:e,dispatch:t})=>{let{selection:n}=e,r=cn.create(n.ranges.map(s=>e.wordAt(s.head)||cn.cursor(s.head)),n.mainIndex);return r.eq(n)?!1:(t(e.update({selection:r})),!0)};function e0n(e,t){let{main:n,ranges:r}=e.selection,s=e.wordAt(n.head),a=s&&s.from==n.from&&s.to==n.to;for(let o=!1,l=new kC(e.doc,t,r[r.length-1].to);;)if(l.next(),l.done){if(o)return null;l=new kC(e.doc,t,0,Math.max(0,r[r.length-1].from-1)),o=!0}else{if(o&&r.some(c=>c.from==l.value.from))continue;if(a){let c=e.wordAt(l.value.from);if(!c||c.from!=l.value.from||c.to!=l.value.to)continue}return l.value}}const t0n=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(a=>a.from===a.to))return Jxn({state:e,dispatch:t});let r=e.sliceDoc(n[0].from,n[0].to);if(e.selection.ranges.some(a=>e.sliceDoc(a.from,a.to)!=r))return!1;let s=e0n(e,r);return s?(t(e.update({selection:e.selection.addRange(cn.range(s.from,s.to),!1),effects:Jn.scrollIntoView(s.to)})),!0):!1},GN=jr.define({combine(e){return W0(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new h0n(t),scrollToMatch:t=>Jn.scrollIntoView(t)})}});class Hit{constructor(t){this.search=t.search,this.caseSensitive=!!t.caseSensitive,this.literal=!!t.literal,this.regexp=!!t.regexp,this.replace=t.replace||"",this.valid=!!this.search&&(!this.regexp||Uxn(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!t.wholeWord,this.test=t.test}unquote(t){return this.literal?t:t.replace(/\\([nrt\\])/g,(n,r)=>r=="n"?`
1783
+ }`,{label:"class",detail:"definition",type:"keyword"}),xc('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),xc('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],kit=K0e.concat([xc("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),xc("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),xc("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),gNe=new b0e,Oit=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function MI(e){return(t,n)=>{let r=t.node.getChild("VariableDefinition");return r&&n(r,e),!0}}const xxn=["FunctionDeclaration"],bxn={FunctionDeclaration:MI("function"),ClassDeclaration:MI("class"),ClassExpression:()=>!0,EnumDeclaration:MI("constant"),TypeAliasDeclaration:MI("type"),NamespaceDeclaration:MI("namespace"),VariableDefinition(e,t){e.matchContext(xxn)||t(e,"variable")},TypeDefinition(e,t){t(e,"type")},__proto__:null};function Sit(e,t){let n=gNe.get(t);if(n)return n;let r=[],s=!0;function a(o,l){let c=e.sliceString(o.from,o.to);r.push({label:c,type:l})}return t.cursor(Ao.IncludeAnonymous).iterate(o=>{if(s)s=!1;else if(o.name){let l=bxn[o.name];if(l&&l(o,a)||Oit.has(o.name))return!1}else if(o.to-o.from>8192){for(let l of Sit(e,o.node))r.push(l);return!1}}),gNe.set(t,r),r}const aW=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,Z0e=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function jit(e){let t=Ha(e.state).resolveInner(e.pos,-1);if(Z0e.indexOf(t.name)>-1)return null;let n=t.name=="VariableName"||t.to-t.from<20&&aW.test(e.state.sliceDoc(t.from,t.to));if(!n&&!e.explicit)return null;let r=[];for(let s=t;s;s=s.parent)Oit.has(s.name)&&(r=r.concat(Sit(e.state.doc,s)));return{options:r,from:n?t.from:e.pos,validFor:aW}}function zne(e,t,n){var r;let s=[];for(;;){let a=t.firstChild,o;if((a==null?void 0:a.name)=="VariableName")return s.push(e(a)),{path:s.reverse(),name:n};if((a==null?void 0:a.name)=="MemberExpression"&&((r=o=a.lastChild)===null||r===void 0?void 0:r.name)=="PropertyName")s.push(e(o)),t=a;else return null}}function Cit(e){let t=r=>e.state.doc.sliceString(r.from,r.to),n=Ha(e.state).resolveInner(e.pos,-1);return n.name=="PropertyName"?zne(t,n.parent,t(n)):(n.name=="."||n.name=="?.")&&n.parent.name=="MemberExpression"?zne(t,n.parent,""):Z0e.indexOf(n.name)>-1?null:n.name=="VariableName"||n.to-n.from<20&&aW.test(t(n))?{path:[],name:t(n)}:n.name=="MemberExpression"?zne(t,n,""):e.explicit?{path:[],name:""}:null}function yxn(e,t){let n=e,r=[],s=new Set;for(let a=0;;a++){for(let l of(Object.getOwnPropertyNames||Object.keys)(e)){if(!/^[a-zA-Z_$\xaa-\uffdc][\w$\xaa-\uffdc]*$/.test(l)||s.has(l))continue;s.add(l);let c;try{c=n[l]}catch{continue}r.push({label:l,type:typeof c=="function"?/^[A-Z]/.test(l)?"class":t?"function":"method":t?"variable":"property",boost:-a})}let o=Object.getPrototypeOf(e);if(!o)return r;e=o}}function vxn(e){let t=new Map;return n=>{let r=Cit(n);if(!r)return null;let s=e;for(let o of r.path)if(s=s[o],!s)return null;let a=t.get(s);return a||t.set(s,a=yxn(s,!r.path.length)),{from:n.pos-r.name.length,options:a,validFor:aW}}}const Dp=I0.define({name:"javascript",parser:gxn.configure({props:[Q2.add({IfStatement:ES({except:/^\s*({|else\b)/}),TryStatement:ES({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:jAn,SwitchBody:e=>{let t=e.textAfter,n=/^\s*\}/.test(t),r=/^\s*(case|default)\b/.test(t);return e.baseIndent+(n?0:r?1:2)*e.unit},Block:MS({closing:"}"}),ArrowFunction:e=>e.baseIndent+e.unit,"TemplateString BlockComment":()=>null,"Statement Property":ES({except:/^\s*{/}),JSXElement(e){let t=/^\s*<\//.test(e.textAfter);return e.lineIndent(e.node.from)+(t?0:e.unit)},JSXEscape(e){let t=/\s*\}/.test(e.textAfter);return e.lineIndent(e.node.from)+(t?0:e.unit)},"JSXOpenTag JSXSelfClosingTag"(e){return e.column(e.node.from)+e.unit}}),U2.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":YR,BlockComment(e){return{from:e.from+2,to:e.to-2}},JSXElement(e){let t=e.firstChild;if(!t||t.name=="JSXSelfClosingTag")return null;let n=e.lastChild;return{from:t.to,to:n.type.isError?e.to:n.from}},"JSXSelfClosingTag JSXOpenTag"(e){var t;let n=(t=e.firstChild)===null||t===void 0?void 0:t.nextSibling,r=e.lastChild;return!n||n.type.isError?null:{from:n.to,to:r.type.isError?e.to:r.from}}})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:"$"}}),Nit={test:e=>/^JSX/.test(e.name),facet:aG({commentTokens:{block:{open:"{/*",close:"*/}"}}})},X0e=Dp.configure({dialect:"ts"},"typescript"),G0e=Dp.configure({dialect:"jsx",props:[v0e.add(e=>e.isTop?[Nit]:void 0)]}),Y0e=Dp.configure({dialect:"jsx ts",props:[v0e.add(e=>e.isTop?[Nit]:void 0)]},"typescript");let Iit=e=>({label:e,type:"keyword"});const Pit="break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(Iit),wxn=Pit.concat(["declare","implements","private","protected","public"].map(Iit));function oW(e={}){let t=e.jsx?e.typescript?Y0e:G0e:e.typescript?X0e:Dp,n=e.typescript?kit.concat(wxn):K0e.concat(Pit);return new _1(t,[Dp.data.of({autocomplete:Ast(Z0e,N0e(n))}),Dp.data.of({autocomplete:jit}),e.jsx?Tit:[]])}function kxn(e){for(;;){if(e.name=="JSXOpenTag"||e.name=="JSXSelfClosingTag"||e.name=="JSXFragmentTag")return e;if(e.name=="JSXEscape"||!e.parent)return null;e=e.parent}}function xNe(e,t,n=e.length){for(let r=t==null?void 0:t.firstChild;r;r=r.nextSibling)if(r.name=="JSXIdentifier"||r.name=="JSXBuiltin"||r.name=="JSXNamespacedName"||r.name=="JSXMemberExpression")return e.sliceString(r.from,Math.min(r.to,n));return""}const Oxn=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),Tit=Jn.inputHandler.of((e,t,n,r,s)=>{if((Oxn?e.composing:e.compositionStarted)||e.state.readOnly||t!=n||r!=">"&&r!="/"||!Dp.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:o}=a,l=o.changeByRange(c=>{var d;let{head:u}=c,f=Ha(o).resolveInner(u-1,-1),m;if(f.name=="JSXStartTag"&&(f=f.parent),!(o.doc.sliceString(u-1,u)!=r||f.name=="JSXAttributeValue"&&f.to>u)){if(r==">"&&f.name=="JSXFragmentTag")return{range:c,changes:{from:u,insert:"</>"}};if(r=="/"&&f.name=="JSXStartCloseTag"){let h=f.parent,p=h.parent;if(p&&h.from==u-2&&((m=xNe(o.doc,p.firstChild,u))||((d=p.firstChild)===null||d===void 0?void 0:d.name)=="JSXFragmentTag")){let x=`${m}>`;return{range:cn.cursor(u+x.length,-1),changes:{from:u,insert:x}}}}else if(r==">"){let h=kxn(f);if(h&&h.name=="JSXOpenTag"&&!/^\/?>|^<\//.test(o.doc.sliceString(u,u+2))&&(m=xNe(o.doc,h,u)))return{range:c,changes:{from:u,insert:`</${m}>`}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([a,o.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)});function Sxn(e,t){return t||(t={parserOptions:{ecmaVersion:2019,sourceType:"module"},env:{browser:!0,node:!0,es6:!0,es2015:!0,es2017:!0,es2020:!0},rules:{}},e.getRules().forEach((n,r)=>{var s;!((s=n.meta.docs)===null||s===void 0)&&s.recommended&&(t.rules[r]=2)})),n=>{let{state:r}=n,s=[];for(let{from:a,to:o}of Dp.findRegions(r)){let l=r.doc.lineAt(a),c={line:l.number-1,col:a-l.from,pos:a};for(let d of e.verify(r.sliceDoc(a,o),t))s.push(jxn(d,r.doc,c))}return s}}function bNe(e,t,n,r){return n.line(e+r.line).from+t+(e==1?r.col-1:-1)}function jxn(e,t,n){let r=bNe(e.line,e.column,t,n),s={from:r,to:e.endLine!=null&&e.endColumn!=1?bNe(e.endLine,e.endColumn,t,n):r,message:e.message,source:e.ruleId?"eslint:"+e.ruleId:"eslint",severity:e.severity==1?"warning":"error"};if(e.fix){let{range:a,text:o}=e.fix,l=a[0]+n.pos-r,c=a[1]+n.pos-r;s.actions=[{name:"fix",apply(d,u){d.dispatch({changes:{from:u+l,to:u+c,insert:o},scrollIntoView:!0})}}]}return s}const bF=Object.freeze(Object.defineProperty({__proto__:null,autoCloseTags:Tit,completionPath:Cit,esLint:Sxn,javascript:oW,javascriptLanguage:Dp,jsxLanguage:G0e,localCompletionSource:jit,scopeCompletionSource:vxn,snippets:K0e,tsxLanguage:Y0e,typescriptLanguage:X0e,typescriptSnippets:kit},Symbol.toStringTag,{value:"Module"})),EI=["_blank","_self","_top","_parent"],$ne=["ascii","utf-8","utf-16","latin1","latin1"],Fne=["get","post","put","delete"],Bne=["application/x-www-form-urlencoded","multipart/form-data","text/plain"],eh=["true","false"],Yr={},Cxn={a:{attrs:{href:null,ping:null,type:null,media:null,target:EI,hreflang:null}},abbr:Yr,address:Yr,area:{attrs:{alt:null,coords:null,href:null,target:null,ping:null,media:null,hreflang:null,type:null,shape:["default","rect","circle","poly"]}},article:Yr,aside:Yr,audio:{attrs:{src:null,mediagroup:null,crossorigin:["anonymous","use-credentials"],preload:["none","metadata","auto"],autoplay:["autoplay"],loop:["loop"],controls:["controls"]}},b:Yr,base:{attrs:{href:null,target:EI}},bdi:Yr,bdo:Yr,blockquote:{attrs:{cite:null}},body:Yr,br:Yr,button:{attrs:{form:null,formaction:null,name:null,value:null,autofocus:["autofocus"],disabled:["autofocus"],formenctype:Bne,formmethod:Fne,formnovalidate:["novalidate"],formtarget:EI,type:["submit","reset","button"]}},canvas:{attrs:{width:null,height:null}},caption:Yr,center:Yr,cite:Yr,code:Yr,col:{attrs:{span:null}},colgroup:{attrs:{span:null}},command:{attrs:{type:["command","checkbox","radio"],label:null,icon:null,radiogroup:null,command:null,title:null,disabled:["disabled"],checked:["checked"]}},data:{attrs:{value:null}},datagrid:{attrs:{disabled:["disabled"],multiple:["multiple"]}},datalist:{attrs:{data:null}},dd:Yr,del:{attrs:{cite:null,datetime:null}},details:{attrs:{open:["open"]}},dfn:Yr,div:Yr,dl:Yr,dt:Yr,em:Yr,embed:{attrs:{src:null,type:null,width:null,height:null}},eventsource:{attrs:{src:null}},fieldset:{attrs:{disabled:["disabled"],form:null,name:null}},figcaption:Yr,figure:Yr,footer:Yr,form:{attrs:{action:null,name:null,"accept-charset":$ne,autocomplete:["on","off"],enctype:Bne,method:Fne,novalidate:["novalidate"],target:EI}},h1:Yr,h2:Yr,h3:Yr,h4:Yr,h5:Yr,h6:Yr,head:{children:["title","base","link","style","meta","script","noscript","command"]},header:Yr,hgroup:Yr,hr:Yr,html:{attrs:{manifest:null}},i:Yr,iframe:{attrs:{src:null,srcdoc:null,name:null,width:null,height:null,sandbox:["allow-top-navigation","allow-same-origin","allow-forms","allow-scripts"],seamless:["seamless"]}},img:{attrs:{alt:null,src:null,ismap:null,usemap:null,width:null,height:null,crossorigin:["anonymous","use-credentials"]}},input:{attrs:{alt:null,dirname:null,form:null,formaction:null,height:null,list:null,max:null,maxlength:null,min:null,name:null,pattern:null,placeholder:null,size:null,src:null,step:null,value:null,width:null,accept:["audio/*","video/*","image/*"],autocomplete:["on","off"],autofocus:["autofocus"],checked:["checked"],disabled:["disabled"],formenctype:Bne,formmethod:Fne,formnovalidate:["novalidate"],formtarget:EI,multiple:["multiple"],readonly:["readonly"],required:["required"],type:["hidden","text","search","tel","url","email","password","datetime","date","month","week","time","datetime-local","number","range","color","checkbox","radio","file","submit","image","reset","button"]}},ins:{attrs:{cite:null,datetime:null}},kbd:Yr,keygen:{attrs:{challenge:null,form:null,name:null,autofocus:["autofocus"],disabled:["disabled"],keytype:["RSA"]}},label:{attrs:{for:null,form:null}},legend:Yr,li:{attrs:{value:null}},link:{attrs:{href:null,type:null,hreflang:null,media:null,sizes:["all","16x16","16x16 32x32","16x16 32x32 64x64"]}},map:{attrs:{name:null}},mark:Yr,menu:{attrs:{label:null,type:["list","context","toolbar"]}},meta:{attrs:{content:null,charset:$ne,name:["viewport","application-name","author","description","generator","keywords"],"http-equiv":["content-language","content-type","default-style","refresh"]}},meter:{attrs:{value:null,min:null,low:null,high:null,max:null,optimum:null}},nav:Yr,noscript:Yr,object:{attrs:{data:null,type:null,name:null,usemap:null,form:null,width:null,height:null,typemustmatch:["typemustmatch"]}},ol:{attrs:{reversed:["reversed"],start:null,type:["1","a","A","i","I"]},children:["li","script","template","ul","ol"]},optgroup:{attrs:{disabled:["disabled"],label:null}},option:{attrs:{disabled:["disabled"],label:null,selected:["selected"],value:null}},output:{attrs:{for:null,form:null,name:null}},p:Yr,param:{attrs:{name:null,value:null}},pre:Yr,progress:{attrs:{value:null,max:null}},q:{attrs:{cite:null}},rp:Yr,rt:Yr,ruby:Yr,samp:Yr,script:{attrs:{type:["text/javascript"],src:null,async:["async"],defer:["defer"],charset:$ne}},section:Yr,select:{attrs:{form:null,name:null,size:null,autofocus:["autofocus"],disabled:["disabled"],multiple:["multiple"]}},slot:{attrs:{name:null}},small:Yr,source:{attrs:{src:null,type:null,media:null}},span:Yr,strong:Yr,style:{attrs:{type:["text/css"],media:null,scoped:null}},sub:Yr,summary:Yr,sup:Yr,table:Yr,tbody:Yr,td:{attrs:{colspan:null,rowspan:null,headers:null}},template:Yr,textarea:{attrs:{dirname:null,form:null,maxlength:null,name:null,placeholder:null,rows:null,cols:null,autofocus:["autofocus"],disabled:["disabled"],readonly:["readonly"],required:["required"],wrap:["soft","hard"]}},tfoot:Yr,th:{attrs:{colspan:null,rowspan:null,headers:null,scope:["row","col","rowgroup","colgroup"]}},thead:Yr,time:{attrs:{datetime:null}},title:Yr,tr:Yr,track:{attrs:{src:null,label:null,default:null,kind:["subtitles","captions","descriptions","chapters","metadata"],srclang:null}},ul:{children:["li","script","template","ul","ol"]},var:Yr,video:{attrs:{src:null,poster:null,width:null,height:null,crossorigin:["anonymous","use-credentials"],preload:["auto","metadata","none"],autoplay:["autoplay"],mediagroup:["movie"],muted:["muted"],controls:["controls"]}},wbr:Yr},_it={accesskey:null,class:null,contenteditable:eh,contextmenu:null,dir:["ltr","rtl","auto"],draggable:["true","false","auto"],dropzone:["copy","move","link","string:","file:"],hidden:["hidden"],id:null,inert:["inert"],itemid:null,itemprop:null,itemref:null,itemscope:["itemscope"],itemtype:null,lang:["ar","bn","de","en-GB","en-US","es","fr","hi","id","ja","pa","pt","ru","tr","zh"],spellcheck:eh,autocorrect:eh,autocapitalize:eh,style:null,tabindex:null,title:null,translate:["yes","no"],rel:["stylesheet","alternate","author","bookmark","help","license","next","nofollow","noreferrer","prefetch","prev","search","tag"],role:"alert application article banner button cell checkbox complementary contentinfo dialog document feed figure form grid gridcell heading img list listbox listitem main navigation region row rowgroup search switch tab table tabpanel textbox timer".split(" "),"aria-activedescendant":null,"aria-atomic":eh,"aria-autocomplete":["inline","list","both","none"],"aria-busy":eh,"aria-checked":["true","false","mixed","undefined"],"aria-controls":null,"aria-describedby":null,"aria-disabled":eh,"aria-dropeffect":null,"aria-expanded":["true","false","undefined"],"aria-flowto":null,"aria-grabbed":["true","false","undefined"],"aria-haspopup":eh,"aria-hidden":eh,"aria-invalid":["true","false","grammar","spelling"],"aria-label":null,"aria-labelledby":null,"aria-level":null,"aria-live":["off","polite","assertive"],"aria-multiline":eh,"aria-multiselectable":eh,"aria-owns":null,"aria-posinset":null,"aria-pressed":["true","false","mixed","undefined"],"aria-readonly":eh,"aria-relevant":null,"aria-required":eh,"aria-selected":["true","false","undefined"],"aria-setsize":null,"aria-sort":["ascending","descending","none","other"],"aria-valuemax":null,"aria-valuemin":null,"aria-valuenow":null,"aria-valuetext":null},Mit="beforeunload copy cut dragstart dragover dragleave dragenter dragend drag paste focus blur change click load mousedown mouseenter mouseleave mouseup keydown keyup resize scroll unload".split(" ").map(e=>"on"+e);for(let e of Mit)_it[e]=null;let rE=class{constructor(t,n){this.tags={...Cxn,...t},this.globalAttrs={..._it,...n},this.allTags=Object.keys(this.tags),this.globalAttrNames=Object.keys(this.globalAttrs)}};rE.default=new rE;function vC(e,t,n=e.length){if(!t)return"";let r=t.firstChild,s=r&&r.getChild("TagName");return s?e.sliceString(s.from,Math.min(s.to,n)):""}function wC(e,t=!1){for(;e;e=e.parent)if(e.name=="Element")if(t)t=!1;else return e;return null}function Eit(e,t,n){let r=n.tags[vC(e,wC(t))];return(r==null?void 0:r.children)||n.allTags}function J0e(e,t){let n=[];for(let r=wC(t);r&&!r.type.isTop;r=wC(r.parent)){let s=vC(e,r);if(s&&r.lastChild.name=="CloseTag")break;s&&n.indexOf(s)<0&&(t.name=="EndTag"||t.from>=r.firstChild.to)&&n.push(s)}return n}const Dit=/^[:\-\.\w\u00b7-\uffff]*$/;function yNe(e,t,n,r,s){let a=/\s*>/.test(e.sliceDoc(s,s+5))?"":">",o=wC(n,n.name=="StartTag"||n.name=="TagName");return{from:r,to:s,options:Eit(e.doc,o,t).map(l=>({label:l,type:"type"})).concat(J0e(e.doc,n).map((l,c)=>({label:"/"+l,apply:"/"+l+a,type:"type",boost:99-c}))),validFor:/^\/?[:\-\.\w\u00b7-\uffff]*$/}}function vNe(e,t,n,r){let s=/\s*>/.test(e.sliceDoc(r,r+5))?"":">";return{from:n,to:r,options:J0e(e.doc,t).map((a,o)=>({label:a,apply:a+s,type:"type",boost:99-o})),validFor:Dit}}function Nxn(e,t,n,r){let s=[],a=0;for(let o of Eit(e.doc,n,t))s.push({label:"<"+o,type:"type"});for(let o of J0e(e.doc,n))s.push({label:"</"+o+">",type:"type",boost:99-a++});return{from:r,to:r,options:s,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}function Ixn(e,t,n,r,s){let a=wC(n),o=a?t.tags[vC(e.doc,a)]:null,l=o&&o.attrs?Object.keys(o.attrs):[],c=o&&o.globalAttrs===!1?l:l.length?l.concat(t.globalAttrNames):t.globalAttrNames;return{from:r,to:s,options:c.map(d=>({label:d,type:"property"})),validFor:Dit}}function Pxn(e,t,n,r,s){var a;let o=(a=n.parent)===null||a===void 0?void 0:a.getChild("AttributeName"),l=[],c;if(o){let d=e.sliceDoc(o.from,o.to),u=t.globalAttrs[d];if(!u){let f=wC(n),m=f?t.tags[vC(e.doc,f)]:null;u=(m==null?void 0:m.attrs)&&m.attrs[d]}if(u){let f=e.sliceDoc(r,s).toLowerCase(),m='"',h='"';/^['"]/.test(f)?(c=f[0]=='"'?/^[^"]*$/:/^[^']*$/,m="",h=e.sliceDoc(s,s+1)==f[0]?"":f[0],f=f.slice(1),r++):c=/^[^\s<>='"]*$/;for(let p of u)l.push({label:p,apply:m+p+h,type:"constant"})}}return{from:r,to:s,options:l,validFor:c}}function Rit(e,t){let{state:n,pos:r}=t,s=Ha(n).resolveInner(r,-1),a=s.resolve(r);for(let o=r,l;a==s&&(l=s.childBefore(o));){let c=l.lastChild;if(!c||!c.type.isError||c.from<c.to)break;a=s=l,o=c.from}return s.name=="TagName"?s.parent&&/CloseTag$/.test(s.parent.name)?vNe(n,s,s.from,r):yNe(n,e,s,s.from,r):s.name=="StartTag"||s.name=="IncompleteTag"?yNe(n,e,s,r,r):s.name=="StartCloseTag"||s.name=="IncompleteCloseTag"?vNe(n,s,r,r):s.name=="OpenTag"||s.name=="SelfClosingTag"||s.name=="AttributeName"?Ixn(n,e,s,s.name=="AttributeName"?s.from:r,r):s.name=="Is"||s.name=="AttributeValue"||s.name=="UnquotedAttributeValue"?Pxn(n,e,s,s.name=="Is"?r:s.from,r):t.explicit&&(a.name=="Element"||a.name=="Text"||a.name=="Document")?Nxn(n,e,s,r):null}function Lit(e){return Rit(rE.default,e)}function zit(e){let{extraTags:t,extraGlobalAttributes:n}=e,r=n||t?new rE(t,n):rE.default;return s=>Rit(r,s)}const Txn=Dp.parser.configure({top:"SingleExpression"}),$it=[{tag:"script",attrs:e=>e.type=="text/typescript"||e.lang=="ts",parser:X0e.parser},{tag:"script",attrs:e=>e.type=="text/babel"||e.type=="text/jsx",parser:G0e.parser},{tag:"script",attrs:e=>e.type=="text/typescript-jsx",parser:Y0e.parser},{tag:"script",attrs(e){return/^(importmap|speculationrules|application\/(.+\+)?json)$/i.test(e.type)},parser:Txn},{tag:"script",attrs(e){return!e.type||/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i.test(e.type)},parser:Dp.parser},{tag:"style",attrs(e){return(!e.lang||e.lang=="css")&&(!e.type||/^(text\/)?(x-)?(stylesheet|css)$/i.test(e.type))},parser:nE.parser}],Fit=[{name:"style",parser:nE.parser.configure({top:"Styles"})}].concat(Mit.map(e=>({name:e,parser:Dp.parser}))),Bit=I0.define({name:"html",parser:F1n.configure({props:[Q2.add({Element(e){let t=/^(\s*)(<\/)?/.exec(e.textAfter);return e.node.to<=e.pos+t[0].length?e.continue():e.lineIndent(e.node.from)+(t[2]?0:e.unit)},"OpenTag CloseTag SelfClosingTag"(e){return e.column(e.node.from)+e.unit},Document(e){if(e.pos+/\s*/.exec(e.textAfter)[0].length<e.node.to)return e.continue();let t=null,n;for(let r=e.node;;){let s=r.lastChild;if(!s||s.name!="Element"||s.to!=r.to)break;t=r=s}return t&&!((n=t.lastChild)&&(n.name=="CloseTag"||n.name=="SelfClosingTag"))?e.lineIndent(t.from)+e.unit:null}}),U2.add({Element(e){let t=e.firstChild,n=e.lastChild;return!t||t.name!="OpenTag"?null:{from:t.to,to:n.name=="CloseTag"?n.from:e.to}}}),ost.add({"OpenTag CloseTag":e=>e.getChild("TagName")})]}),languageData:{commentTokens:{block:{open:"<!--",close:"-->"}},indentOnInput:/^\s*<\/\w+\W$/,wordChars:"-_"}}),t_=Bit.configure({wrap:vit($it,Fit)});function Qit(e={}){let t="",n;e.matchClosingTags===!1&&(t="noMatch"),e.selfClosingTags===!0&&(t=(t?t+" ":"")+"selfClosing"),(e.nestedLanguages&&e.nestedLanguages.length||e.nestedAttributes&&e.nestedAttributes.length)&&(n=vit((e.nestedLanguages||[]).concat($it),(e.nestedAttributes||[]).concat(Fit)));let r=n?Bit.configure({wrap:n,dialect:t}):t?t_.configure({dialect:t}):t_;return new _1(r,[t_.data.of({autocomplete:zit(e)}),e.autoCloseTags!==!1?Uit:[],oW().support,uit().support])}const wNe=new Set("area base br col command embed frame hr img input keygen link meta param source track wbr menuitem".split(" ")),Uit=Jn.inputHandler.of((e,t,n,r,s)=>{if(e.composing||e.state.readOnly||t!=n||r!=">"&&r!="/"||!t_.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:o}=a,l=o.changeByRange(c=>{var d,u,f;let m=o.doc.sliceString(c.from-1,c.to)==r,{head:h}=c,p=Ha(o).resolveInner(h,-1),x;if(m&&r==">"&&p.name=="EndTag"){let b=p.parent;if(((u=(d=b.parent)===null||d===void 0?void 0:d.lastChild)===null||u===void 0?void 0:u.name)!="CloseTag"&&(x=vC(o.doc,b.parent,h))&&!wNe.has(x)){let y=h+(o.doc.sliceString(h,h+1)===">"?1:0),w=`</${x}>`;return{range:c,changes:{from:h,to:y,insert:w}}}}else if(m&&r=="/"&&p.name=="IncompleteCloseTag"){let b=p.parent;if(p.from==h-2&&((f=b.lastChild)===null||f===void 0?void 0:f.name)!="CloseTag"&&(x=vC(o.doc,b,h))&&!wNe.has(x)){let y=h+(o.doc.sliceString(h,h+1)===">"?1:0),w=`${x}>`;return{range:cn.cursor(h+w.length,-1),changes:{from:h,to:y,insert:w}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([a,o.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)}),_xn=Object.freeze(Object.defineProperty({__proto__:null,autoCloseTags:Uit,html:Qit,htmlCompletionSource:Lit,htmlCompletionSourceWith:zit,htmlLanguage:t_},Symbol.toStringTag,{value:"Module"}));function Mxn(e,t,n,r){const s=j0(ic),a=kh(Bet),o=xe.useRef(null),{lexicalNode:l}=cde(),c=xe.useRef(!1),d=xe.useRef(!1),u=xe.useCallback(()=>{a({editorType:t,rootNode:l,editorRef:o.current})},[t,l,a]),f=xe.useCallback(m=>{var h,p,x,b,y,w;if(m.key==="ArrowDown"){const k=(p=(h=o.current)==null?void 0:h.getCodemirror())==null?void 0:p.state;if(k){const S=k.doc.length,j=k.selection.ranges[0].to;S===j&&(c.current?(s==null||s.update(()=>{var C,I;const N=g0(e);N.getNextSibling()?((I=(C=o.current)==null?void 0:C.getCodemirror())==null||I.contentDOM.blur(),N.selectNext()):N.insertAfter(gl())}),c.current=!1):c.current=!0)}}else if(m.key==="ArrowUp"){const k=(b=(x=o.current)==null?void 0:x.getCodemirror())==null?void 0:b.state;k&&k.selection.ranges[0].from===0&&(d.current?(s==null||s.update(()=>{var j,C;const I=g0(e);I.getPreviousSibling()&&((C=(j=o.current)==null?void 0:j.getCodemirror())==null||C.contentDOM.blur(),I.selectPrevious())}),d.current=!1):d.current=!0)}else if(m.key==="Enter")m.stopPropagation();else if(m.key==="Backspace"||m.key==="Delete"){const k=(w=(y=o.current)==null?void 0:y.getCodemirror())==null?void 0:w.state;(k==null?void 0:k.doc.length)===0&&(s==null||s.update(()=>{g0(e).remove()}))}},[s,e]);return xe.useEffect(()=>{const m=o.current;return setTimeout(()=>{var h,p;(h=m==null?void 0:m.getCodemirror())==null||h.contentDOM.addEventListener("focus",u),(p=m==null?void 0:m.getCodemirror())==null||p.contentDOM.addEventListener("keydown",f)},300),()=>{var h,p;(h=m==null?void 0:m.getCodemirror())==null||h.contentDOM.removeEventListener("focus",u),(p=m==null?void 0:m.getCodemirror())==null||p.contentDOM.removeEventListener("keydown",f)}},[o,u,f,n]),xe.useEffect(()=>{r.subscribe(()=>{var m,h;(h=(m=o.current)==null?void 0:m.getCodemirror())==null||h.focus(),u()})},[r,o,e,u]),o}function Dn(e){return new _1(O0e.define(e))}function _v(e){return on(()=>import("./index-D-jdXuoy.js"),[]).then(t=>t.sql({dialect:t[e]}))}const Exn=[an.of({name:"C",extensions:["c","h","ino"],load(){return on(()=>import("./index-By6wVGNY.js"),[]).then(e=>e.cpp())}}),an.of({name:"C++",alias:["cpp"],extensions:["cpp","c++","cc","cxx","hpp","h++","hh","hxx"],load(){return on(()=>import("./index-By6wVGNY.js"),[]).then(e=>e.cpp())}}),an.of({name:"CQL",alias:["cassandra"],extensions:["cql"],load(){return _v("Cassandra")}}),an.of({name:"CSS",extensions:["css"],load(){return on(()=>Promise.resolve().then(()=>n1n),void 0).then(e=>e.css())}}),an.of({name:"Go",extensions:["go"],load(){return on(()=>import("./index-BIwzh-U4.js"),[]).then(e=>e.go())}}),an.of({name:"HTML",alias:["xhtml"],extensions:["html","htm","handlebars","hbs"],load(){return on(()=>Promise.resolve().then(()=>_xn),void 0).then(e=>e.html())}}),an.of({name:"Java",extensions:["java"],load(){return on(()=>import("./index-BONjSnI2.js"),[]).then(e=>e.java())}}),an.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return on(()=>Promise.resolve().then(()=>bF),void 0).then(e=>e.javascript())}}),an.of({name:"Jinja",extensions:["j2","jinja","jinja2"],load(){return on(()=>import("./index-BrgGIOAR.js"),[]).then(e=>e.jinja())}}),an.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return on(()=>Promise.resolve().then(()=>eUn),void 0).then(e=>e.json())}}),an.of({name:"JSX",extensions:["jsx"],load(){return on(()=>Promise.resolve().then(()=>bF),void 0).then(e=>e.javascript({jsx:!0}))}}),an.of({name:"LESS",extensions:["less"],load(){return on(()=>import("./index-C6RzrVdO.js"),[]).then(e=>e.less())}}),an.of({name:"Liquid",extensions:["liquid"],load(){return on(()=>import("./index-ChpzeG1B.js"),[]).then(e=>e.liquid())}}),an.of({name:"MariaDB SQL",load(){return _v("MariaSQL")}}),an.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return on(()=>Promise.resolve().then(()=>kbn),void 0).then(e=>e.markdown())}}),an.of({name:"MS SQL",load(){return _v("MSSQL")}}),an.of({name:"MySQL",load(){return _v("MySQL")}}),an.of({name:"PHP",extensions:["php","php3","php4","php5","php7","phtml"],load(){return on(()=>import("./index-BNdZbjyn.js"),[]).then(e=>e.php())}}),an.of({name:"PLSQL",extensions:["pls"],load(){return _v("PLSQL")}}),an.of({name:"PostgreSQL",load(){return _v("PostgreSQL")}}),an.of({name:"Python",extensions:["BUILD","bzl","py","pyw"],filename:/^(BUCK|BUILD)$/,load(){return on(()=>Promise.resolve().then(()=>Aqn),void 0).then(e=>e.python())}}),an.of({name:"Rust",extensions:["rs"],load(){return on(()=>import("./index-D3MTazer.js"),[]).then(e=>e.rust())}}),an.of({name:"Sass",extensions:["sass"],load(){return on(()=>import("./index-D2RUPIgv.js"),[]).then(e=>e.sass({indented:!0}))}}),an.of({name:"SCSS",extensions:["scss"],load(){return on(()=>import("./index-D2RUPIgv.js"),[]).then(e=>e.sass())}}),an.of({name:"SQL",extensions:["sql"],load(){return _v("StandardSQL")}}),an.of({name:"SQLite",load(){return _v("SQLite")}}),an.of({name:"TSX",extensions:["tsx"],load(){return on(()=>Promise.resolve().then(()=>bF),void 0).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),an.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return on(()=>Promise.resolve().then(()=>bF),void 0).then(e=>e.javascript({typescript:!0}))}}),an.of({name:"WebAssembly",extensions:["wat","wast"],load(){return on(()=>import("./index-B2UcZ_IJ.js"),[]).then(e=>e.wast())}}),an.of({name:"XML",alias:["rss","wsdl","xsd"],extensions:["xml","xsl","xsd","svg"],load(){return on(()=>import("./index-BIQKbQUa.js"),[]).then(e=>e.xml())}}),an.of({name:"YAML",alias:["yml"],extensions:["yaml","yml"],load(){return on(()=>Promise.resolve().then(()=>Wqn),void 0).then(e=>e.yaml())}}),an.of({name:"APL",extensions:["dyalog","apl"],load(){return on(()=>import("./apl-B4CMkyY2.js"),[]).then(e=>Dn(e.apl))}}),an.of({name:"PGP",alias:["asciiarmor"],extensions:["asc","pgp","sig"],load(){return on(()=>import("./asciiarmor-Df11BRmG.js"),[]).then(e=>Dn(e.asciiArmor))}}),an.of({name:"ASN.1",extensions:["asn","asn1"],load(){return on(()=>import("./asn1-EdZsLKOL.js"),[]).then(e=>Dn(e.asn1({})))}}),an.of({name:"Asterisk",filename:/^extensions\.conf$/i,load(){return on(()=>import("./asterisk-B-8jnY81.js"),[]).then(e=>Dn(e.asterisk))}}),an.of({name:"Brainfuck",extensions:["b","bf"],load(){return on(()=>import("./brainfuck-C4LP7Hcl.js"),[]).then(e=>Dn(e.brainfuck))}}),an.of({name:"Cobol",extensions:["cob","cpy"],load(){return on(()=>import("./cobol-CWcv1MsR.js"),[]).then(e=>Dn(e.cobol))}}),an.of({name:"C#",alias:["csharp","cs"],extensions:["cs"],load(){return on(()=>import("./clike-B9uivgTg.js"),[]).then(e=>Dn(e.csharp))}}),an.of({name:"Clojure",extensions:["clj","cljc","cljx"],load(){return on(()=>import("./clojure-BMjYHr_A.js"),[]).then(e=>Dn(e.clojure))}}),an.of({name:"ClojureScript",extensions:["cljs"],load(){return on(()=>import("./clojure-BMjYHr_A.js"),[]).then(e=>Dn(e.clojure))}}),an.of({name:"Closure Stylesheets (GSS)",extensions:["gss"],load(){return on(()=>import("./css-BnMrqG3P.js"),[]).then(e=>Dn(e.gss))}}),an.of({name:"CMake",extensions:["cmake","cmake.in"],filename:/^CMakeLists\.txt$/,load(){return on(()=>import("./cmake-BQqOBYOt.js"),[]).then(e=>Dn(e.cmake))}}),an.of({name:"CoffeeScript",alias:["coffee","coffee-script"],extensions:["coffee"],load(){return on(()=>import("./coffeescript-S37ZYGWr.js"),[]).then(e=>Dn(e.coffeeScript))}}),an.of({name:"Common Lisp",alias:["lisp"],extensions:["cl","lisp","el"],load(){return on(()=>import("./commonlisp-DBKNyK5s.js"),[]).then(e=>Dn(e.commonLisp))}}),an.of({name:"Cypher",extensions:["cyp","cypher"],load(){return on(()=>import("./cypher-C_CwsFkJ.js"),[]).then(e=>Dn(e.cypher))}}),an.of({name:"Cython",extensions:["pyx","pxd","pxi"],load(){return on(()=>import("./python-BuPzkPfP.js"),[]).then(e=>Dn(e.cython))}}),an.of({name:"Crystal",extensions:["cr"],load(){return on(()=>import("./crystal-SjHAIU92.js"),[]).then(e=>Dn(e.crystal))}}),an.of({name:"D",extensions:["d"],load(){return on(()=>import("./d-pRatUO7H.js"),[]).then(e=>Dn(e.d))}}),an.of({name:"Dart",extensions:["dart"],load(){return on(()=>import("./clike-B9uivgTg.js"),[]).then(e=>Dn(e.dart))}}),an.of({name:"diff",extensions:["diff","patch"],load(){return on(()=>import("./diff-DbItnlRl.js"),[]).then(e=>Dn(e.diff))}}),an.of({name:"Dockerfile",filename:/^Dockerfile$/,load(){return on(()=>import("./dockerfile-BKs6k2Af.js"),__vite__mapDeps([0,1])).then(e=>Dn(e.dockerFile))}}),an.of({name:"DTD",extensions:["dtd"],load(){return on(()=>import("./dtd-DF_7sFjM.js"),[]).then(e=>Dn(e.dtd))}}),an.of({name:"Dylan",extensions:["dylan","dyl","intr"],load(){return on(()=>import("./dylan-DwRh75JA.js"),[]).then(e=>Dn(e.dylan))}}),an.of({name:"EBNF",load(){return on(()=>import("./ebnf-CDyGwa7X.js"),[]).then(e=>Dn(e.ebnf))}}),an.of({name:"ECL",extensions:["ecl"],load(){return on(()=>import("./ecl-Cabwm37j.js"),[]).then(e=>Dn(e.ecl))}}),an.of({name:"edn",extensions:["edn"],load(){return on(()=>import("./clojure-BMjYHr_A.js"),[]).then(e=>Dn(e.clojure))}}),an.of({name:"Eiffel",extensions:["e"],load(){return on(()=>import("./eiffel-CnydiIhH.js"),[]).then(e=>Dn(e.eiffel))}}),an.of({name:"Elm",extensions:["elm"],load(){return on(()=>import("./elm-vLlmbW-K.js"),[]).then(e=>Dn(e.elm))}}),an.of({name:"Erlang",extensions:["erl"],load(){return on(()=>import("./erlang-BNw1qcRV.js"),[]).then(e=>Dn(e.erlang))}}),an.of({name:"Esper",load(){return on(()=>import("./sql-D0XecflT.js"),[]).then(e=>Dn(e.esper))}}),an.of({name:"Factor",extensions:["factor"],load(){return on(()=>import("./factor-kuTfRLto.js"),__vite__mapDeps([2,1])).then(e=>Dn(e.factor))}}),an.of({name:"FCL",load(){return on(()=>import("./fcl-Kvtd6kyn.js"),[]).then(e=>Dn(e.fcl))}}),an.of({name:"Forth",extensions:["forth","fth","4th"],load(){return on(()=>import("./forth-Ffai-XNe.js"),[]).then(e=>Dn(e.forth))}}),an.of({name:"Fortran",extensions:["f","for","f77","f90","f95"],load(){return on(()=>import("./fortran-DYz_wnZ1.js"),[]).then(e=>Dn(e.fortran))}}),an.of({name:"F#",alias:["fsharp"],extensions:["fs"],load(){return on(()=>import("./mllike-CXdrOF99.js"),[]).then(e=>Dn(e.fSharp))}}),an.of({name:"Gas",extensions:["s"],load(){return on(()=>import("./gas-Bneqetm1.js"),[]).then(e=>Dn(e.gas))}}),an.of({name:"Gherkin",extensions:["feature"],load(){return on(()=>import("./gherkin-heZmZLOM.js"),[]).then(e=>Dn(e.gherkin))}}),an.of({name:"Groovy",extensions:["groovy","gradle"],filename:/^Jenkinsfile$/,load(){return on(()=>import("./groovy-D9Dt4D0W.js"),[]).then(e=>Dn(e.groovy))}}),an.of({name:"Haskell",extensions:["hs"],load(){return on(()=>import("./haskell-Cw1EW3IL.js"),[]).then(e=>Dn(e.haskell))}}),an.of({name:"Haxe",extensions:["hx"],load(){return on(()=>import("./haxe-H-WmDvRZ.js"),[]).then(e=>Dn(e.haxe))}}),an.of({name:"HXML",extensions:["hxml"],load(){return on(()=>import("./haxe-H-WmDvRZ.js"),[]).then(e=>Dn(e.hxml))}}),an.of({name:"HTTP",load(){return on(()=>import("./http-DBlCnlav.js"),[]).then(e=>Dn(e.http))}}),an.of({name:"IDL",extensions:["pro"],load(){return on(()=>import("./idl-BEugSyMb.js"),[]).then(e=>Dn(e.idl))}}),an.of({name:"JSON-LD",alias:["jsonld"],extensions:["jsonld"],load(){return on(()=>import("./javascript-iXu5QeM3.js"),[]).then(e=>Dn(e.jsonld))}}),an.of({name:"Julia",extensions:["jl"],load(){return on(()=>import("./julia-DuME0IfC.js"),[]).then(e=>Dn(e.julia))}}),an.of({name:"Kotlin",extensions:["kt","kts"],load(){return on(()=>import("./clike-B9uivgTg.js"),[]).then(e=>Dn(e.kotlin))}}),an.of({name:"LiveScript",alias:["ls"],extensions:["ls"],load(){return on(()=>import("./livescript-BwQOo05w.js"),[]).then(e=>Dn(e.liveScript))}}),an.of({name:"Lua",extensions:["lua"],load(){return on(()=>import("./lua-BgMRiT3U.js"),[]).then(e=>Dn(e.lua))}}),an.of({name:"mIRC",extensions:["mrc"],load(){return on(()=>import("./mirc-CjQqDB4T.js"),[]).then(e=>Dn(e.mirc))}}),an.of({name:"Mathematica",extensions:["m","nb","wl","wls"],load(){return on(()=>import("./mathematica-DTrFuWx2.js"),[]).then(e=>Dn(e.mathematica))}}),an.of({name:"Modelica",extensions:["mo"],load(){return on(()=>import("./modelica-Dc1JOy9r.js"),[]).then(e=>Dn(e.modelica))}}),an.of({name:"MUMPS",extensions:["mps"],load(){return on(()=>import("./mumps-BT43cFF4.js"),[]).then(e=>Dn(e.mumps))}}),an.of({name:"Mbox",extensions:["mbox"],load(){return on(()=>import("./mbox-CNhZ1qSd.js"),[]).then(e=>Dn(e.mbox))}}),an.of({name:"Nginx",filename:/nginx.*\.conf$/i,load(){return on(()=>import("./nginx-DdIZxoE0.js"),[]).then(e=>Dn(e.nginx))}}),an.of({name:"NSIS",extensions:["nsh","nsi"],load(){return on(()=>import("./nsis-LdVXkNf5.js"),__vite__mapDeps([3,1])).then(e=>Dn(e.nsis))}}),an.of({name:"NTriples",extensions:["nt","nq"],load(){return on(()=>import("./ntriples-BfvgReVJ.js"),[]).then(e=>Dn(e.ntriples))}}),an.of({name:"Objective-C",alias:["objective-c","objc"],extensions:["m"],load(){return on(()=>import("./clike-B9uivgTg.js"),[]).then(e=>Dn(e.objectiveC))}}),an.of({name:"Objective-C++",alias:["objective-c++","objc++"],extensions:["mm"],load(){return on(()=>import("./clike-B9uivgTg.js"),[]).then(e=>Dn(e.objectiveCpp))}}),an.of({name:"OCaml",extensions:["ml","mli","mll","mly"],load(){return on(()=>import("./mllike-CXdrOF99.js"),[]).then(e=>Dn(e.oCaml))}}),an.of({name:"Octave",extensions:["m"],load(){return on(()=>import("./octave-Ck1zUtKM.js"),[]).then(e=>Dn(e.octave))}}),an.of({name:"Oz",extensions:["oz"],load(){return on(()=>import("./oz-BzwKVEFT.js"),[]).then(e=>Dn(e.oz))}}),an.of({name:"Pascal",extensions:["p","pas"],load(){return on(()=>import("./pascal--L3eBynH.js"),[]).then(e=>Dn(e.pascal))}}),an.of({name:"Perl",extensions:["pl","pm"],load(){return on(()=>import("./perl-CdXCOZ3F.js"),[]).then(e=>Dn(e.perl))}}),an.of({name:"Pig",extensions:["pig"],load(){return on(()=>import("./pig-CevX1Tat.js"),[]).then(e=>Dn(e.pig))}}),an.of({name:"PowerShell",extensions:["ps1","psd1","psm1"],load(){return on(()=>import("./powershell-CFHJl5sT.js"),[]).then(e=>Dn(e.powerShell))}}),an.of({name:"Properties files",alias:["ini","properties"],extensions:["properties","ini","in"],load(){return on(()=>import("./properties-C78fOPTZ.js"),[]).then(e=>Dn(e.properties))}}),an.of({name:"ProtoBuf",extensions:["proto"],load(){return on(()=>import("./protobuf-ChK-085T.js"),[]).then(e=>Dn(e.protobuf))}}),an.of({name:"Pug",alias:["jade"],extensions:["pug","jade"],load(){return on(()=>import("./pug-DeIclll2.js"),__vite__mapDeps([4,5])).then(e=>Dn(e.pug))}}),an.of({name:"Puppet",extensions:["pp"],load(){return on(()=>import("./puppet-DMA9R1ak.js"),[]).then(e=>Dn(e.puppet))}}),an.of({name:"Q",extensions:["q"],load(){return on(()=>import("./q-pXgVlZs6.js"),[]).then(e=>Dn(e.q))}}),an.of({name:"R",alias:["rscript"],extensions:["r","R"],load(){return on(()=>import("./r-B6wPVr8A.js"),[]).then(e=>Dn(e.r))}}),an.of({name:"RPM Changes",load(){return on(()=>import("./rpm-CTu-6PCP.js"),[]).then(e=>Dn(e.rpmChanges))}}),an.of({name:"RPM Spec",extensions:["spec"],load(){return on(()=>import("./rpm-CTu-6PCP.js"),[]).then(e=>Dn(e.rpmSpec))}}),an.of({name:"Ruby",alias:["jruby","macruby","rake","rb","rbx"],extensions:["rb"],filename:/^(Gemfile|Rakefile)$/,load(){return on(()=>import("./ruby-B2Rjki9n.js"),[]).then(e=>Dn(e.ruby))}}),an.of({name:"SAS",extensions:["sas"],load(){return on(()=>import("./sas-B4kiWyti.js"),[]).then(e=>Dn(e.sas))}}),an.of({name:"Scala",extensions:["scala"],load(){return on(()=>import("./clike-B9uivgTg.js"),[]).then(e=>Dn(e.scala))}}),an.of({name:"Scheme",extensions:["scm","ss"],load(){return on(()=>import("./scheme-C41bIUwD.js"),[]).then(e=>Dn(e.scheme))}}),an.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return on(()=>import("./shell-CjFT_Tl9.js"),[]).then(e=>Dn(e.shell))}}),an.of({name:"Sieve",extensions:["siv","sieve"],load(){return on(()=>import("./sieve-C3Gn_uJK.js"),[]).then(e=>Dn(e.sieve))}}),an.of({name:"Smalltalk",extensions:["st"],load(){return on(()=>import("./smalltalk-CnHTOXQT.js"),[]).then(e=>Dn(e.smalltalk))}}),an.of({name:"Solr",load(){return on(()=>import("./solr-DehyRSwq.js"),[]).then(e=>Dn(e.solr))}}),an.of({name:"SML",extensions:["sml","sig","fun","smackspec"],load(){return on(()=>import("./mllike-CXdrOF99.js"),[]).then(e=>Dn(e.sml))}}),an.of({name:"SPARQL",alias:["sparul"],extensions:["rq","sparql"],load(){return on(()=>import("./sparql-DkYu6x3z.js"),[]).then(e=>Dn(e.sparql))}}),an.of({name:"Spreadsheet",alias:["excel","formula"],load(){return on(()=>import("./spreadsheet-BCZA_wO0.js"),[]).then(e=>Dn(e.spreadsheet))}}),an.of({name:"Squirrel",extensions:["nut"],load(){return on(()=>import("./clike-B9uivgTg.js"),[]).then(e=>Dn(e.squirrel))}}),an.of({name:"Stylus",extensions:["styl"],load(){return on(()=>import("./stylus-B533Al4x.js"),[]).then(e=>Dn(e.stylus))}}),an.of({name:"Swift",extensions:["swift"],load(){return on(()=>import("./swift-BzpIVaGY.js"),[]).then(e=>Dn(e.swift))}}),an.of({name:"sTeX",load(){return on(()=>import("./stex-C3f8Ysf7.js"),[]).then(e=>Dn(e.stex))}}),an.of({name:"LaTeX",alias:["tex"],extensions:["text","ltx","tex"],load(){return on(()=>import("./stex-C3f8Ysf7.js"),[]).then(e=>Dn(e.stex))}}),an.of({name:"SystemVerilog",extensions:["v","sv","svh"],load(){return on(()=>import("./verilog-C6RDOZhf.js"),[]).then(e=>Dn(e.verilog))}}),an.of({name:"Tcl",extensions:["tcl"],load(){return on(()=>import("./tcl-DVfN8rqt.js"),[]).then(e=>Dn(e.tcl))}}),an.of({name:"Textile",extensions:["textile"],load(){return on(()=>import("./textile-CnDTJFAw.js"),[]).then(e=>Dn(e.textile))}}),an.of({name:"TiddlyWiki",load(){return on(()=>import("./tiddlywiki-DO-Gjzrf.js"),[]).then(e=>Dn(e.tiddlyWiki))}}),an.of({name:"Tiki wiki",load(){return on(()=>import("./tiki-DGYXhP31.js"),[]).then(e=>Dn(e.tiki))}}),an.of({name:"TOML",extensions:["toml"],load(){return on(()=>import("./toml-Bm5Em-hy.js"),[]).then(e=>Dn(e.toml))}}),an.of({name:"Troff",extensions:["1","2","3","4","5","6","7","8","9"],load(){return on(()=>import("./troff-wAsdV37c.js"),[]).then(e=>Dn(e.troff))}}),an.of({name:"TTCN",extensions:["ttcn","ttcn3","ttcnpp"],load(){return on(()=>import("./ttcn-CfJYG6tj.js"),[]).then(e=>Dn(e.ttcn))}}),an.of({name:"TTCN_CFG",extensions:["cfg"],load(){return on(()=>import("./ttcn-cfg-B9xdYoR4.js"),[]).then(e=>Dn(e.ttcnCfg))}}),an.of({name:"Turtle",extensions:["ttl"],load(){return on(()=>import("./turtle-B1tBg_DP.js"),[]).then(e=>Dn(e.turtle))}}),an.of({name:"Web IDL",extensions:["webidl"],load(){return on(()=>import("./webidl-ZXfAyPTL.js"),[]).then(e=>Dn(e.webIDL))}}),an.of({name:"VB.NET",extensions:["vb"],load(){return on(()=>import("./vb-CmGdzxic.js"),[]).then(e=>Dn(e.vb))}}),an.of({name:"VBScript",extensions:["vbs"],load(){return on(()=>import("./vbscript-BuJXcnF6.js"),[]).then(e=>Dn(e.vbScript))}}),an.of({name:"Velocity",extensions:["vtl"],load(){return on(()=>import("./velocity-D8B20fx6.js"),[]).then(e=>Dn(e.velocity))}}),an.of({name:"Verilog",extensions:["v"],load(){return on(()=>import("./verilog-C6RDOZhf.js"),[]).then(e=>Dn(e.verilog))}}),an.of({name:"VHDL",extensions:["vhd","vhdl"],load(){return on(()=>import("./vhdl-lSbBsy5d.js"),[]).then(e=>Dn(e.vhdl))}}),an.of({name:"XQuery",extensions:["xy","xquery","xq","xqm","xqy"],load(){return on(()=>import("./xquery-DzFWVndE.js"),[]).then(e=>Dn(e.xQuery))}}),an.of({name:"Yacas",extensions:["ys"],load(){return on(()=>import("./yacas-BJ4BC0dw.js"),[]).then(e=>Dn(e.yacas))}}),an.of({name:"Z80",extensions:["z80"],load(){return on(()=>import("./z80-Hz9HOZM7.js"),[]).then(e=>Dn(e.z80))}}),an.of({name:"MscGen",extensions:["mscgen","mscin","msc"],load(){return on(()=>import("./mscgen-BA5vi2Kp.js"),[]).then(e=>Dn(e.mscgen))}}),an.of({name:"Xù",extensions:["xu"],load(){return on(()=>import("./mscgen-BA5vi2Kp.js"),[]).then(e=>Dn(e.xu))}}),an.of({name:"MsGenny",extensions:["msgenny"],load(){return on(()=>import("./mscgen-BA5vi2Kp.js"),[]).then(e=>Dn(e.msgenny))}}),an.of({name:"Vue",extensions:["vue"],load(){return on(()=>import("./index-DepPPcF2.js"),[]).then(e=>e.vue())}}),an.of({name:"Angular Template",load(){return on(()=>import("./index-fZqqDrca.js"),[]).then(e=>e.angular())}})],kNe="#2e3440",ebe="#3b4252",ONe="#434c5e",yF="#4c566a",SNe="#e5e9f0",cue="#eceff4",Qne="#8fbcbb",jNe="#88c0d0",Dxn="#81a1c1",vg="#5e81ac",Rxn="#bf616a",D7="#d08770",Une="#ebcb8b",CNe="#a3be8c",Lxn="#b48ead",NNe="#d30102",tbe=cue,qne=tbe,zxn="#ffffff",Vne=ebe,$xn=tbe,INe=ebe,Fxn=Jn.theme({"&":{color:kNe,backgroundColor:zxn},".cm-content":{caretColor:INe},".cm-cursor, .cm-dropCursor":{borderLeftColor:INe},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:$xn},".cm-panels":{backgroundColor:tbe,color:yF},".cm-panels.cm-panels-top":{borderBottom:"2px solid black"},".cm-panels.cm-panels-bottom":{borderTop:"2px solid black"},".cm-searchMatch":{backgroundColor:"#72a1ff59",outline:`1px solid ${yF}`},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:SNe},".cm-activeLine":{backgroundColor:qne},".cm-selectionMatch":{backgroundColor:SNe},"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket":{outline:`1px solid ${yF}`},"&.cm-focused .cm-matchingBracket":{backgroundColor:cue},".cm-gutters":{backgroundColor:cue,color:kNe,border:"none"},".cm-activeLineGutter":{backgroundColor:qne},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:Vne},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:Vne,borderBottomColor:Vne},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:qne,color:yF}}},{dark:!1}),Bxn=T8.define([{tag:Xe.keyword,color:vg},{tag:[Xe.name,Xe.deleted,Xe.character,Xe.propertyName,Xe.macroName],color:D7},{tag:[Xe.variableName],color:D7},{tag:[Xe.function(Xe.variableName)],color:vg},{tag:[Xe.labelName],color:Dxn},{tag:[Xe.color,Xe.constant(Xe.name),Xe.standard(Xe.name)],color:vg},{tag:[Xe.definition(Xe.name),Xe.separator],color:CNe},{tag:[Xe.brace],color:Qne},{tag:[Xe.annotation],color:NNe},{tag:[Xe.number,Xe.changed,Xe.annotation,Xe.modifier,Xe.self,Xe.namespace],color:jNe},{tag:[Xe.typeName,Xe.className],color:Une},{tag:[Xe.operator,Xe.operatorKeyword],color:CNe},{tag:[Xe.tagName],color:Lxn},{tag:[Xe.squareBracket],color:Rxn},{tag:[Xe.angleBracket],color:D7},{tag:[Xe.attributeName],color:Une},{tag:[Xe.regexp],color:vg},{tag:[Xe.quote],color:ebe},{tag:[Xe.string],color:D7},{tag:Xe.link,color:Qne,textDecoration:"underline",textUnderlinePosition:"under"},{tag:[Xe.url,Xe.escape,Xe.special(Xe.string)],color:D7},{tag:[Xe.meta],color:jNe},{tag:[Xe.comment],color:ONe,fontStyle:"italic"},{tag:Xe.strong,fontWeight:"bold",color:vg},{tag:Xe.emphasis,fontStyle:"italic",color:vg},{tag:Xe.strikethrough,textDecoration:"line-through"},{tag:Xe.heading,fontWeight:"bold",color:vg},{tag:Xe.special(Xe.heading1),fontWeight:"bold",color:vg},{tag:Xe.heading1,fontWeight:"bold",color:vg},{tag:[Xe.heading2,Xe.heading3,Xe.heading4],fontWeight:"bold",color:vg},{tag:[Xe.heading5,Xe.heading6],color:vg},{tag:[Xe.atom,Xe.bool,Xe.special(Xe.variableName)],color:D7},{tag:[Xe.processingInstruction,Xe.inserted],color:Qne},{tag:[Xe.contentSeparator],color:Une},{tag:Xe.invalid,color:ONe,borderBottom:`1px dotted ${NNe}`}]),Qxn=[Fxn,cG(Bxn)],PNe=typeof String.prototype.normalize=="function"?e=>e.normalize("NFKD"):e=>e;class kC{constructor(t,n,r=0,s=t.length,a,o){this.test=o,this.value={from:0,to:0},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=t.iterRange(r,s),this.bufferStart=r,this.normalize=a?l=>a(PNe(l)):PNe,this.query=this.normalize(n)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return hA(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let t=this.peek();if(t<0)return this.done=!0,this;let n=Gxe(t),r=this.bufferStart+this.bufferPos;this.bufferPos+=Xx(t);let s=this.normalize(n);if(s.length)for(let a=0,o=r;;a++){let l=s.charCodeAt(a),c=this.match(l,o,this.bufferPos+this.bufferStart);if(a==s.length-1){if(c)return this.value=c,this;break}o==r&&a<n.length&&n.charCodeAt(a)==l&&o++}}}match(t,n,r){let s=null;for(let a=0;a<this.matches.length;a+=2){let o=this.matches[a],l=!1;this.query.charCodeAt(o)==t&&(o==this.query.length-1?s={from:this.matches[a+1],to:r}:(this.matches[a]++,l=!0)),l||(this.matches.splice(a,2),a-=2)}return this.query.charCodeAt(0)==t&&(this.query.length==1?s={from:n,to:r}:this.matches.push(1,n)),s&&this.test&&!this.test(s.from,s.to,this.buffer,this.bufferStart)&&(s=null),s}}typeof Symbol<"u"&&(kC.prototype[Symbol.iterator]=function(){return this});const qit={from:-1,to:-1,match:/.*/.exec("")},nbe="gm"+(/x/.unicode==null?"":"u");class Vit{constructor(t,n,r,s=0,a=t.length){if(this.text=t,this.to=a,this.curLine="",this.done=!1,this.value=qit,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new Wit(t,n,r,s,a);this.re=new RegExp(n,nbe+(r!=null&&r.ignoreCase?"i":"")),this.test=r==null?void 0:r.test,this.iter=t.iter();let o=t.lineAt(s);this.curLineStart=o.from,this.matchPos=lW(t,s),this.getLine(this.curLineStart)}getLine(t){this.iter.next(t),this.iter.lineBreak?this.curLine="":(this.curLine=this.iter.value,this.curLineStart+this.curLine.length>this.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let t=this.matchPos-this.curLineStart;;){this.re.lastIndex=t;let n=this.matchPos<=this.to&&this.re.exec(this.curLine);if(n){let r=this.curLineStart+n.index,s=r+n[0].length;if(this.matchPos=lW(this.text,s+(r==s?1:0)),r==this.curLineStart+this.curLine.length&&this.nextLine(),(r<s||r>this.value.to)&&(!this.test||this.test(r,s,n)))return this.value={from:r,to:s,match:n},this;t=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length<this.to)this.nextLine(),t=0;else return this.done=!0,this}}}const Wne=new WeakMap;class LS{constructor(t,n){this.from=t,this.text=n}get to(){return this.from+this.text.length}static get(t,n,r){let s=Wne.get(t);if(!s||s.from>=r||s.to<=n){let l=new LS(n,t.sliceString(n,r));return Wne.set(t,l),l}if(s.from==n&&s.to==r)return s;let{text:a,from:o}=s;return o>n&&(a=t.sliceString(n,o)+a,o=n),s.to<r&&(a+=t.sliceString(s.to,r)),Wne.set(t,new LS(o,a)),new LS(n,a.slice(n-o,r-o))}}class Wit{constructor(t,n,r,s,a){this.text=t,this.to=a,this.done=!1,this.value=qit,this.matchPos=lW(t,s),this.re=new RegExp(n,nbe+(r!=null&&r.ignoreCase?"i":"")),this.test=r==null?void 0:r.test,this.flat=LS.get(t,s,this.chunkEnd(s+5e3))}chunkEnd(t){return t>=this.to?this.to:this.text.lineAt(t).to}next(){for(;;){let t=this.re.lastIndex=this.matchPos-this.flat.from,n=this.re.exec(this.flat.text);if(n&&!n[0]&&n.index==t&&(this.re.lastIndex=t+1,n=this.re.exec(this.flat.text)),n){let r=this.flat.from+n.index,s=r+n[0].length;if((this.flat.to>=this.to||n.index+n[0].length<=this.flat.text.length-10)&&(!this.test||this.test(r,s,n)))return this.value={from:r,to:s,match:n},this.matchPos=lW(this.text,s+(r==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=LS.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(Vit.prototype[Symbol.iterator]=Wit.prototype[Symbol.iterator]=function(){return this});function Uxn(e){try{return new RegExp(e,nbe),!0}catch{return!1}}function lW(e,t){if(t>=e.length)return t;let n=e.lineAt(t),r;for(;t<n.to&&(r=n.text.charCodeAt(t-n.from))>=56320&&r<57344;)t++;return t}const qxn=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:s}=Rmn(e,{label:t.phrase("Go to line"),input:{type:"text",name:"line",value:n},focus:!0,submitLabel:t.phrase("go")});return s.then(a=>{let o=a&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(a.elements.line.value);if(!o){e.dispatch({effects:r});return}let l=t.doc.lineAt(t.selection.main.head),[,c,d,u,f]=o,m=u?+u.slice(1):0,h=d?+d:l.number;if(d&&f){let b=h/100;c&&(b=b*(c=="-"?-1:1)+l.number/t.doc.lines),h=Math.round(t.doc.lines*b)}else d&&c&&(h=h*(c=="-"?-1:1)+l.number);let p=t.doc.line(Math.max(1,Math.min(t.doc.lines,h))),x=cn.cursor(p.from+Math.max(0,Math.min(m,p.length)));e.dispatch({effects:[r,Jn.scrollIntoView(x.from,{y:"center"})],selection:x})}),!0},Vxn={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},Wxn=jr.define({combine(e){return W0(e,Vxn,{highlightWordAroundCursor:(t,n)=>t||n,minSelectionLength:Math.min,maxMatches:Math.min})}});function Hxn(e){return[Yxn,Gxn]}const Kxn=Nr.mark({class:"cm-selectionMatch"}),Zxn=Nr.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function TNe(e,t,n,r){return(n==0||e(t.sliceDoc(n-1,n))!=ac.Word)&&(r==t.doc.length||e(t.sliceDoc(r,r+1))!=ac.Word)}function Xxn(e,t,n,r){return e(t.sliceDoc(n,n+1))==ac.Word&&e(t.sliceDoc(r-1,r))==ac.Word}const Gxn=id.fromClass(class{constructor(e){this.decorations=this.getDeco(e)}update(e){(e.selectionSet||e.docChanged||e.viewportChanged)&&(this.decorations=this.getDeco(e.view))}getDeco(e){let t=e.state.facet(Wxn),{state:n}=e,r=n.selection;if(r.ranges.length>1)return Nr.none;let s=r.main,a,o=null;if(s.empty){if(!t.highlightWordAroundCursor)return Nr.none;let c=n.wordAt(s.head);if(!c)return Nr.none;o=n.charCategorizer(s.head),a=n.sliceDoc(c.from,c.to)}else{let c=s.to-s.from;if(c<t.minSelectionLength||c>200)return Nr.none;if(t.wholeWords){if(a=n.sliceDoc(s.from,s.to),o=n.charCategorizer(s.head),!(TNe(o,n,s.from,s.to)&&Xxn(o,n,s.from,s.to)))return Nr.none}else if(a=n.sliceDoc(s.from,s.to),!a)return Nr.none}let l=[];for(let c of e.visibleRanges){let d=new kC(n.doc,a,c.from,c.to);for(;!d.next().done;){let{from:u,to:f}=d.value;if((!o||TNe(o,n,u,f))&&(s.empty&&u<=s.from&&f>=s.to?l.push(Zxn.range(u,f)):(u>=s.to||f<=s.from)&&l.push(Kxn.range(u,f)),l.length>t.maxMatches))return Nr.none}}return Nr.set(l)}},{decorations:e=>e.decorations}),Yxn=Jn.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),Jxn=({state:e,dispatch:t})=>{let{selection:n}=e,r=cn.create(n.ranges.map(s=>e.wordAt(s.head)||cn.cursor(s.head)),n.mainIndex);return r.eq(n)?!1:(t(e.update({selection:r})),!0)};function e0n(e,t){let{main:n,ranges:r}=e.selection,s=e.wordAt(n.head),a=s&&s.from==n.from&&s.to==n.to;for(let o=!1,l=new kC(e.doc,t,r[r.length-1].to);;)if(l.next(),l.done){if(o)return null;l=new kC(e.doc,t,0,Math.max(0,r[r.length-1].from-1)),o=!0}else{if(o&&r.some(c=>c.from==l.value.from))continue;if(a){let c=e.wordAt(l.value.from);if(!c||c.from!=l.value.from||c.to!=l.value.to)continue}return l.value}}const t0n=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(a=>a.from===a.to))return Jxn({state:e,dispatch:t});let r=e.sliceDoc(n[0].from,n[0].to);if(e.selection.ranges.some(a=>e.sliceDoc(a.from,a.to)!=r))return!1;let s=e0n(e,r);return s?(t(e.update({selection:e.selection.addRange(cn.range(s.from,s.to),!1),effects:Jn.scrollIntoView(s.to)})),!0):!1},GN=jr.define({combine(e){return W0(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new h0n(t),scrollToMatch:t=>Jn.scrollIntoView(t)})}});class Hit{constructor(t){this.search=t.search,this.caseSensitive=!!t.caseSensitive,this.literal=!!t.literal,this.regexp=!!t.regexp,this.replace=t.replace||"",this.valid=!!this.search&&(!this.regexp||Uxn(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!t.wholeWord,this.test=t.test}unquote(t){return this.literal?t:t.replace(/\\([nrt\\])/g,(n,r)=>r=="n"?`
1784
1784
  `:r=="r"?"\r":r=="t"?" ":"\\")}eq(t){return this.search==t.search&&this.replace==t.replace&&this.caseSensitive==t.caseSensitive&&this.regexp==t.regexp&&this.wholeWord==t.wholeWord&&this.test==t.test}create(){return this.regexp?new o0n(this):new s0n(this)}getCursor(t,n=0,r){let s=t.doc?t:go.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?wO(this,s,n,r):vO(this,s,n,r)}}class Kit{constructor(t){this.spec=t}}function n0n(e,t,n){return(r,s,a,o)=>{if(n&&!n(r,s,a,o))return!1;let l=r>=o&&s<=o+a.length?a.slice(r-o,s-o):t.doc.sliceString(r,s);return e(l,t,r,s)}}function vO(e,t,n,r){let s;return e.wholeWord&&(s=r0n(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=n0n(e.test,t,s)),new kC(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function r0n(e,t){return(n,r,s,a)=>((a>n||a+s.length<r)&&(a=Math.max(0,n-2),s=e.sliceString(a,Math.min(e.length,r+2))),(t(cW(s,n-a))!=ac.Word||t(dW(s,n-a))!=ac.Word)&&(t(dW(s,r-a))!=ac.Word||t(cW(s,r-a))!=ac.Word))}class s0n extends Kit{constructor(t){super(t)}nextMatch(t,n,r){let s=vO(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=vO(this.spec,t,0,a).nextOverlapping()}return s.done||s.value.from==n&&s.value.to==r?null:s.value}prevMatchInRange(t,n,r){for(let s=r;;){let a=Math.max(n,s-1e4-this.spec.unquoted.length),o=vO(this.spec,t,a,s),l=null;for(;!o.nextOverlapping().done;)l=o.value;if(l)return l;if(a==n)return null;s-=1e4}}prevMatch(t,n,r){let s=this.prevMatchInRange(t,0,n);return s||(s=this.prevMatchInRange(t,Math.max(0,r-this.spec.unquoted.length),t.doc.length)),s&&(s.from!=n||s.to!=r)?s:null}getReplacement(t){return this.spec.unquote(this.spec.replace)}matchAll(t,n){let r=vO(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=vO(this.spec,t,Math.max(0,n-this.spec.unquoted.length),Math.min(r+this.spec.unquoted.length,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}function i0n(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function wO(e,t,n,r){let s;return e.wholeWord&&(s=a0n(t.charCategorizer(t.selection.main.head))),e.test&&(s=i0n(e.test,t,s)),new Vit(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function cW(e,t){return e.slice(vu(e,t,!1),t)}function dW(e,t){return e.slice(t,vu(e,t))}function a0n(e){return(t,n,r)=>!r[0].length||(e(cW(r.input,r.index))!=ac.Word||e(dW(r.input,r.index))!=ac.Word)&&(e(dW(r.input,r.index+r[0].length))!=ac.Word||e(cW(r.input,r.index+r[0].length))!=ac.Word)}class o0n extends Kit{nextMatch(t,n,r){let s=wO(this.spec,t,r,t.doc.length).next();return s.done&&(s=wO(this.spec,t,0,n).next()),s.done?null:s.value}prevMatchInRange(t,n,r){for(let s=1;;s++){let a=Math.max(n,r-s*1e4),o=wO(this.spec,t,a,r),l=null;for(;!o.next().done;)l=o.value;if(l&&(a==n||l.from>a+10))return l;if(a==n)return null}}prevMatch(t,n,r){return this.prevMatchInRange(t,0,n)||this.prevMatchInRange(t,r,t.doc.length)}getReplacement(t){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(n,r)=>{if(r=="&")return t.match[0];if(r=="$")return"$";for(let s=r.length;s>0;s--){let a=+r.slice(0,s);if(a>0&&a<t.match.length)return t.match[a]+r.slice(s)}return n})}matchAll(t,n){let r=wO(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=wO(this.spec,t,Math.max(0,n-250),Math.min(r+250,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}const sE=Fs.define(),rbe=Fs.define(),kw=Tu.define({create(e){return new Hne(due(e).create(),null)},update(e,t){for(let n of t.effects)n.is(sE)?e=new Hne(n.value.create(),e.panel):n.is(rbe)&&(e=new Hne(e.query,n.value?sbe:null));return e},provide:e=>HM.from(e,t=>t.panel)});class Hne{constructor(t,n){this.query=t,this.panel=n}}const l0n=Nr.mark({class:"cm-searchMatch"}),c0n=Nr.mark({class:"cm-searchMatch cm-searchMatch-selected"}),d0n=id.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(kw))}update(e){let t=e.state.field(kw);(t!=e.startState.field(kw)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return Nr.none;let{view:n}=this,r=new b2;for(let s=0,a=n.visibleRanges,o=a.length;s<o;s++){let{from:l,to:c}=a[s];for(;s<o-1&&c>a[s+1].from-500;)c=a[++s].to;e.highlight(n.state,l,c,(d,u)=>{let f=n.state.selection.ranges.some(m=>m.from==d&&m.to==u);r.add(d,u,f?c0n:l0n)})}return r.finish()}},{decorations:e=>e.decorations});function nL(e){return t=>{let n=t.state.field(kw,!1);return n&&n.query.spec.valid?e(t,n):Git(t)}}const uW=nL((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=cn.single(r.from,r.to),a=e.state.facet(GN);return e.dispatch({selection:s,effects:[ibe(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),Xit(e),!0}),fW=nL((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let a=cn.single(s.from,s.to),o=e.state.facet(GN);return e.dispatch({selection:a,effects:[ibe(e,s),o.scrollToMatch(a.main,e)],userEvent:"select.search"}),Xit(e),!0}),u0n=nL((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:cn.create(n.map(r=>cn.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),f0n=({state:e,dispatch:t})=>{let n=e.selection;if(n.ranges.length>1||n.main.empty)return!1;let{from:r,to:s}=n.main,a=[],o=0;for(let l=new kC(e.doc,e.sliceDoc(r,s));!l.next().done;){if(a.length>1e3)return!1;l.value.from==r&&(o=a.length),a.push(cn.range(l.value.from,l.value.to))}return t(e.update({selection:cn.create(a,o),userEvent:"select.search.matches"})),!0},_Ne=nL((e,{query:t})=>{let{state:n}=e,{from:r,to:s}=n.selection.main;if(n.readOnly)return!1;let a=t.nextMatch(n,r,r);if(!a)return!1;let o=a,l=[],c,d,u=[];o.from==r&&o.to==s&&(d=n.toText(t.getReplacement(o)),l.push({from:o.from,to:o.to,insert:d}),o=t.nextMatch(n,o.from,o.to),u.push(Jn.announce.of(n.phrase("replaced match on line $",n.doc.lineAt(r).number)+".")));let f=e.state.changes(l);return o&&(c=cn.single(o.from,o.to).map(f),u.push(ibe(e,o)),u.push(n.facet(GN).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:u,userEvent:"input.replace"}),!0}),m0n=nL((e,{query:t})=>{if(e.state.readOnly)return!1;let n=t.matchAll(e.state,1e9).map(s=>{let{from:a,to:o}=s;return{from:a,to:o,insert:t.getReplacement(s)}});if(!n.length)return!1;let r=e.state.phrase("replaced $ matches",n.length)+".";return e.dispatch({changes:n,effects:Jn.announce.of(r),userEvent:"input.replace.all"}),!0});function sbe(e){return e.state.facet(GN).createPanel(e)}function due(e,t){var n,r,s,a,o;let l=e.selection.main,c=l.empty||l.to>l.from+100?"":e.sliceDoc(l.from,l.to);if(t&&!c)return t;let d=e.facet(GN);return new Hit({search:((n=t==null?void 0:t.literal)!==null&&n!==void 0?n:d.literal)?c:c.replace(/\n/g,"\\n"),caseSensitive:(r=t==null?void 0:t.caseSensitive)!==null&&r!==void 0?r:d.caseSensitive,literal:(s=t==null?void 0:t.literal)!==null&&s!==void 0?s:d.literal,regexp:(a=t==null?void 0:t.regexp)!==null&&a!==void 0?a:d.regexp,wholeWord:(o=t==null?void 0:t.wholeWord)!==null&&o!==void 0?o:d.wholeWord})}function Zit(e){let t=h0e(e,sbe);return t&&t.dom.querySelector("[main-field]")}function Xit(e){let t=Zit(e);t&&t==e.root.activeElement&&t.select()}const Git=e=>{let t=e.state.field(kw,!1);if(t&&t.panel){let n=Zit(e);if(n&&n!=e.root.activeElement){let r=due(e.state,t.query.spec);r.valid&&e.dispatch({effects:sE.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[rbe.of(!0),t?sE.of(due(e.state,t.query.spec)):Fs.appendConfig.of(g0n)]});return!0},Yit=e=>{let t=e.state.field(kw,!1);if(!t||!t.panel)return!1;let n=h0e(e,sbe);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:rbe.of(!1)}),!0},A0n=[{key:"Mod-f",run:Git,scope:"editor search-panel"},{key:"F3",run:uW,shift:fW,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:uW,shift:fW,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:Yit,scope:"editor search-panel"},{key:"Mod-Shift-l",run:f0n},{key:"Mod-Alt-g",run:qxn},{key:"Mod-d",run:t0n,preventDefault:!0}];class h0n{constructor(t){this.view=t;let n=this.query=t.state.field(kw).query.spec;this.commit=this.commit.bind(this),this.searchField=Yo("input",{value:n.search,placeholder:th(t,"Find"),"aria-label":th(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=Yo("input",{value:n.replace,placeholder:th(t,"Replace"),"aria-label":th(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=Yo("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=Yo("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=Yo("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,o){return Yo("button",{class:"cm-button",name:s,onclick:a,type:"button"},o)}this.dom=Yo("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>uW(t),[th(t,"next")]),r("prev",()=>fW(t),[th(t,"previous")]),r("select",()=>u0n(t),[th(t,"all")]),Yo("label",null,[this.caseField,th(t,"match case")]),Yo("label",null,[this.reField,th(t,"regexp")]),Yo("label",null,[this.wordField,th(t,"by word")]),...t.state.readOnly?[]:[Yo("br"),this.replaceField,r("replace",()=>_Ne(t),[th(t,"replace")]),r("replaceAll",()=>m0n(t),[th(t,"replace all")])],Yo("button",{name:"close",onclick:()=>Yit(t),"aria-label":th(t,"close"),type:"button"},["×"])])}commit(){let t=new Hit({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});t.eq(this.query)||(this.query=t,this.view.dispatch({effects:sE.of(t)}))}keydown(t){Kfn(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?fW:uW)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),_Ne(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(sE)&&!r.value.eq(this.query)&&this.setQuery(r.value)}setQuery(t){this.query=t,this.searchField.value=t.search,this.replaceField.value=t.replace,this.caseField.checked=t.caseSensitive,this.reField.checked=t.regexp,this.wordField.checked=t.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(GN).top}}function th(e,t){return e.state.phrase(t)}const vF=30,wF=/[\s\.,:;?!]/;function ibe(e,{from:t,to:n}){let r=e.state.doc.lineAt(t),s=e.state.doc.lineAt(n).to,a=Math.max(r.from,t-vF),o=Math.min(s,n+vF),l=e.state.sliceDoc(a,o);if(a!=r.from){for(let c=0;c<vF;c++)if(!wF.test(l[c+1])&&wF.test(l[c])){l=l.slice(c);break}}if(o!=s){for(let c=l.length-1;c>l.length-vF;c--)if(!wF.test(l[c-1])&&wF.test(l[c])){l=l.slice(0,c);break}}return Jn.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const p0n=Jn.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),g0n=[kw,Ep.low(d0n),p0n];class MNe{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class F4{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(iE).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((h,p)=>h.from-p.from||h.to-p.to),o=new b2,l=[],c=0,d=r.doc.iter(),u=0,f=r.doc.length;for(let h=0;;){let p=h==a.length?null:a[h];if(!p&&!l.length)break;let x,b;if(l.length)x=c,b=l.reduce((k,S)=>Math.min(k,S.to),p&&p.from>x?p.from:1e8);else{if(x=p.from,x>f)break;b=p.to,l.push(p),h++}for(;h<a.length;){let k=a[h];if(k.from==x&&(k.to>k.from||k.to==x))l.push(k),h++,b=Math.min(k.to,b);else{b=Math.min(k.from,b);break}}b=Math.min(b,f);let y=!1;if(l.some(k=>k.from==x&&(k.to==b||b==f))&&(y=x==b,!y&&b-x<10)){let k=x-(u+d.value.length);k>0&&(d.next(k),u=x);for(let S=x;;){if(S>=b){y=!0;break}if(!d.lineBreak&&u+d.value.length>S)break;S=u+d.value.length,u+=d.value.length,d.next()}}let w=P0n(l);if(y)o.add(x,x,Nr.widget({widget:new j0n(w),diagnostics:l.slice()}));else{let k=l.reduce((S,j)=>j.markClass?S+" "+j.markClass:S,"");o.add(x,b,Nr.mark({class:"cm-lintRange cm-lintRange-"+w+k,diagnostics:l.slice(),inclusiveEnd:l.some(S=>S.to>b)}))}if(c=b,c==f)break;for(let k=0;k<l.length;k++)l[k].to<=c&&l.splice(k--,1)}let m=o.finish();return new F4(m,n,t5(m))}}function t5(e,t=null,n=0){let r=null;return e.between(n,1e9,(s,a,{spec:o})=>{if(!(t&&o.diagnostics.indexOf(t)<0))if(!r)r=new MNe(s,a,t||o.diagnostics[0]);else{if(o.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new MNe(r.from,a,r.diagnostic)}}),r}function x0n(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(iE).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(o=>o.is(Jit))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function b0n(e,t){return e.field(Nh,!1)?t:t.concat(Fs.appendConfig.of(T0n))}const Jit=Fs.define(),abe=Fs.define(),eat=Fs.define(),Nh=Tu.define({create(){return new F4(Nr.none,null,null)},update(e,t){if(t.docChanged&&e.diagnostics.size){let n=e.diagnostics.map(t.changes),r=null,s=e.panel;if(e.selected){let a=t.changes.mapPos(e.selected.from,1);r=t5(n,e.selected.diagnostic,a)||t5(n,null,a)}!n.size&&s&&t.state.facet(iE).autoPanel&&(s=null),e=new F4(n,s,r)}for(let n of t.effects)if(n.is(Jit)){let r=t.state.facet(iE).autoPanel?n.value.length?aE.open:null:e.panel;e=F4.init(n.value,r,t.state)}else n.is(abe)?e=new F4(e.diagnostics,n.value?aE.open:null,e.selected):n.is(eat)&&(e=new F4(e.diagnostics,e.panel,n.value));return e},provide:e=>[HM.from(e,t=>t.panel),Jn.decorations.from(e,t=>t.diagnostics)]}),y0n=Nr.mark({class:"cm-lintRange cm-lintRange-active"});function v0n(e,t,n){let{diagnostics:r}=e.state.field(Nh),s,a=-1,o=-1;r.between(t-(n<0?1:0),t+(n>0?1:0),(c,d,{spec:u})=>{if(t>=c&&t<=d&&(c==d||(t>c||n>0)&&(t<d||n<0)))return s=u.diagnostics,a=c,o=d,!1});let l=e.state.facet(iE).tooltipFilter;return s&&l&&(s=l(s,e.state)),s?{pos:a,end:o,above:e.state.doc.lineAt(a).to<o,create(){return{dom:w0n(e,s)}}}:null}function w0n(e,t){return Yo("ul",{class:"cm-tooltip-lint"},t.map(n=>nat(e,n,!1)))}const k0n=e=>{let t=e.state.field(Nh,!1);(!t||!t.panel)&&e.dispatch({effects:b0n(e.state,[abe.of(!0)])});let n=h0e(e,aE.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},ENe=e=>{let t=e.state.field(Nh,!1);return!t||!t.panel?!1:(e.dispatch({effects:abe.of(!1)}),!0)},O0n=e=>{let t=e.state.field(Nh,!1);if(!t)return!1;let n=e.state.selection.main,r=t5(t.diagnostics,null,n.to+1);return!r&&(r=t5(t.diagnostics,null,0),!r||r.from==n.from&&r.to==n.to)?!1:(e.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0}),!0)},S0n=[{key:"Mod-Shift-m",run:k0n,preventDefault:!0},{key:"F8",run:O0n}],iE=jr.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...W0(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:DNe,tooltipFilter:DNe,needsRefresh:(t,n)=>t?n?r=>t(r)||n(r):t:n,hideOn:(t,n)=>t?n?(r,s,a)=>t(r,s,a)||n(r,s,a):t:n,autoPanel:(t,n)=>t||n})}}});function DNe(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function tat(e){let t=[];if(e)e:for(let{name:n}of e){for(let r=0;r<n.length;r++){let s=n[r];if(/[a-zA-Z]/.test(s)&&!t.some(a=>a.toLowerCase()==s.toLowerCase())){t.push(s);continue e}}t.push("")}return t}function nat(e,t,n){var r;let s=n?tat(t.actions):[];return Yo("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},Yo("span",{class:"cm-diagnosticText"},t.renderMessage?t.renderMessage(e):t.message),(r=t.actions)===null||r===void 0?void 0:r.map((a,o)=>{let l=!1,c=h=>{if(h.preventDefault(),l)return;l=!0;let p=t5(e.state.field(Nh).diagnostics,t);p&&a.apply(e,p.from,p.to)},{name:d}=a,u=s[o]?d.indexOf(s[o]):-1,f=u<0?d:[d.slice(0,u),Yo("u",d.slice(u,u+1)),d.slice(u+1)],m=a.markClass?" "+a.markClass:"";return Yo("button",{type:"button",class:"cm-diagnosticAction"+m,onclick:c,onmousedown:c,"aria-label":` Action: ${d}${u<0?"":` (access key "${s[o]})"`}.`},f)}),t.source&&Yo("div",{class:"cm-diagnosticSource"},t.source))}class j0n extends Bh{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return Yo("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class RNe{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=nat(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class aE{constructor(t){this.view=t,this.items=[];let n=s=>{if(!(s.ctrlKey||s.altKey||s.metaKey)){if(s.keyCode==27)ENe(this.view),this.view.focus();else if(s.keyCode==38||s.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(s.keyCode==40||s.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(s.keyCode==36)this.moveSelection(0);else if(s.keyCode==35)this.moveSelection(this.items.length-1);else if(s.keyCode==13)this.view.focus();else if(s.keyCode>=65&&s.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:a}=this.items[this.selectedIndex],o=tat(a.actions);for(let l=0;l<o.length;l++)if(o[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=t5(this.view.state.field(Nh).diagnostics,a);c&&a.actions[l].apply(t,c.from,c.to)}}else return;s.preventDefault()}},r=s=>{for(let a=0;a<this.items.length;a++)this.items[a].dom.contains(s.target)&&this.moveSelection(a)};this.list=Yo("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=Yo("div",{class:"cm-panel-lint"},this.list,Yo("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>ENe(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Nh).selected;if(!t)return-1;for(let n=0;n<this.items.length;n++)if(this.items[n].diagnostic==t.diagnostic)return n;return-1}update(){let{diagnostics:t,selected:n}=this.view.state.field(Nh),r=0,s=!1,a=null,o=new Set;for(t.between(0,this.view.state.doc.length,(l,c,{spec:d})=>{for(let u of d.diagnostics){if(o.has(u))continue;o.add(u);let f=-1,m;for(let h=r;h<this.items.length;h++)if(this.items[h].diagnostic==u){f=h;break}f<0?(m=new RNe(this.view,u),this.items.splice(r,0,m),s=!0):(m=this.items[f],f>r&&(this.items.splice(r,f-r),s=!0)),n&&m.diagnostic==n.diagnostic?m.dom.hasAttribute("aria-selected")||(m.dom.setAttribute("aria-selected","true"),a=m):m.dom.hasAttribute("aria-selected")&&m.dom.removeAttribute("aria-selected"),r++}});r<this.items.length&&!(this.items.length==1&&this.items[0].diagnostic.from<0);)s=!0,this.items.pop();this.items.length==0&&(this.items.push(new RNe(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")})),s=!0),a?(this.list.setAttribute("aria-activedescendant",a.id),this.view.requestMeasure({key:this,read:()=>({sel:a.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:l,panel:c})=>{let d=c.height/this.list.offsetHeight;l.top<c.top?this.list.scrollTop-=(c.top-l.top)/d:l.bottom>c.bottom&&(this.list.scrollTop+=(l.bottom-c.bottom)/d)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),s&&this.sync()}sync(){let t=this.list.firstChild;function n(){let r=t;t=r.nextSibling,r.remove()}for(let r of this.items)if(r.dom.parentNode==this.list){for(;t!=r.dom;)n();t=r.dom.nextSibling}else this.list.insertBefore(r.dom,t);for(;t;)n()}moveSelection(t){if(this.selectedIndex<0)return;let n=this.view.state.field(Nh),r=t5(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:eat.of(r)})}static open(t){return new aE(t)}}function C0n(e,t='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${t}>${encodeURIComponent(e)}</svg>')`}function kF(e){return C0n(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${e}" fill="none" stroke-width=".7"/>`,'width="6" height="3"')}const N0n=Jn.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:kF("#d11")},".cm-lintRange-warning":{backgroundImage:kF("orange")},".cm-lintRange-info":{backgroundImage:kF("#999")},".cm-lintRange-hint":{backgroundImage:kF("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}},"&dark .cm-lintRange-active":{backgroundColor:"#86714a80"},"&dark .cm-panel.cm-panel-lint ul":{"& [aria-selected]":{backgroundColor:"#2e343e"}}});function I0n(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function P0n(e){let t="hint",n=1;for(let r of e){let s=I0n(r.severity);s>n&&(n=s,t=r.severity)}return t}const T0n=[Nh,Jn.decorations.compute([Nh],e=>{let{selected:t,panel:n}=e.field(Nh);return!t||!n||t.from==t.to?Nr.none:Nr.set([y0n.range(t.from,t.to)])}),Emn(v0n,{hideOn:x0n}),N0n],obe=[zrt(),Zmn(),umn(),jst(),FAn(),emn(),imn(),go.allowMultipleSelections.of(!0),NAn(),cG(qAn,{fallback:!0}),GAn(),Uhn(),epn(),kmn(),jmn(),gmn(),Hxn(),w2.of([...Hhn,...nit,...A0n,...Pst,...RAn,...kst,...S0n])],_0n=xe.forwardRef(({title:e,children:t},n)=>{const r=j0(N8);return xe.createElement(Ehe,{delayDuration:100},xe.createElement(Dhe,null,xe.createElement(Rhe,{ref:n,asChild:!0},xe.createElement("span",{className:Wn.tooltipTrigger},t)),xe.createElement(Lhe,{container:r==null?void 0:r.current},xe.createElement(zhe,{className:el(Wn.tooltipContent),sideOffset:10},e))))}),M0n=xe.forwardRef(({children:e,className:t,...n},r)=>xe.createElement(BQe,{...n,ref:r,className:el(t,Wn.selectItem)},xe.createElement(QQe,null,e))),E0n=({title:e,placeholder:t,className:n})=>{const[r,s]=R1(I1,z2);return xe.createElement(_0n,{title:e},xe.createElement(DQe,{"aria-label":t,className:el(Wn.selectTrigger,n),"data-toolbar-item":!0,disabled:r},xe.createElement(RQe,{placeholder:t}),xe.createElement(LQe,{className:Wn.selectDropdownArrow},s("arrow_drop_down"))))},D0n=({children:e,className:t=Wn.selectContainer})=>{const n=j0(N8);return xe.createElement(zQe,{container:n==null?void 0:n.current},xe.createElement($Qe,{className:el(t,"mdxeditor-select-content"),onCloseAutoFocus:r=>{r.preventDefault()},position:"popper"},xe.createElement(FQe,{"data-editor-dropdown":!0,style:{maxHeight:"var(--radix-select-content-available-height)"}},e)))},R0n=e=>xe.createElement(EQe,{value:e.value||"",onValueChange:e.onChange,disabled:e.disabled},xe.createElement(E0n,{title:e.triggerTitle,placeholder:e.placeholder}),xe.createElement(D0n,null,e.items.map((t,n)=>t==="separator"?xe.createElement(cCt,{key:n}):xe.createElement(M0n,{key:n,value:t.value},t.label)))),rat=({language:e,nodeKey:t,code:n,focusEmitter:r})=>{const s=$2(),{parentEditor:a,lexicalNode:o}=cde(),[l,c,d,u,f]=R1(I1,Aue,hue,z2,mue),m=Mxn(t,"codeblock",e,r),{setCode:h}=cde(),p=xe.useRef(null),x=xe.useRef(null),b=xe.useRef(h);return b.current=h,m.current={getCodemirror:()=>p.current},xe.useEffect(()=>{const y=x.current;return(async()=>{const w=[...c,obe,Qxn,zrt(),w2.of([mgn]),Jn.lineWrapping,Jn.updateListener.of(({state:k})=>{b.current(k.doc.toString())}),Jn.domEventHandlers({focus:()=>{a.update(()=>{Jp(null)})}})];if(l&&w.push(go.readOnly.of(!0)),e!==""&&d){const k=Exn.find(S=>S.name===e||S.alias.includes(e)||S.extensions.includes(e));if(k)try{const S=await k.load();w.push(S.extension)}catch{console.warn("failed to load language support for",e)}}y.innerHTML="",p.current=new Jn({parent:y,state:go.create({doc:n,extensions:w})}),y.addEventListener("keydown",LNe)})(),()=>{var w;(w=p.current)==null||w.destroy(),p.current=null,y.removeEventListener("keydown",LNe)}},[l,e,...c]),xe.createElement("div",{className:Wn.codeMirrorWrapper},xe.createElement("div",{className:Wn.codeMirrorToolbar},xe.createElement(R0n,{disabled:l,value:f.keyMap[e]??e,onChange:y=>{a.update(()=>{o.setLanguage(y===uue?"":y),setTimeout(()=>{a.update(()=>{o.getLatest().select()})})})},triggerTitle:s("codeBlock.selectLanguage","Select code block language"),placeholder:s("codeBlock.inlineLanguage","Language"),items:f.items}),xe.createElement("button",{className:Wn.iconButton,type:"button",disabled:l,title:s("codeblock.delete","Delete code block"),onClick:y=>{y.preventDefault(),a.update(()=>{o.remove()})}},u("delete_small"))),xe.createElement("div",{ref:x}))};function LNe(e){e.stopPropagation()}const uue="__EMPTY_VALUE__";function fue(e){var t;const n=[],r={};if(Array.isArray(e))for(const s of e){const a=((t=s.alias)==null?void 0:t[0])??s.name.toLowerCase();if(n.push({value:a,label:s.name}),r[a]=a,s.alias)for(const o of s.alias)r[o]=a;if(s.extensions)for(const o of s.extensions)r[o]=a;r[s.name.toLowerCase()]=a}else{const s={};for(const[a,o]of Object.entries(e))o in s||(s[o]=a,n.push({value:a||uue,label:o})),r[a]=s[o]||uue}return{items:n,keyMap:r}}const mue=Pr(fue({js:"JavaScript",ts:"TypeScript",tsx:"TypeScript (React)",jsx:"JavaScript (React)",css:"CSS"})),L0n=ld(e=>{e.link(e.pipe(L0n,qw(({language:t,code:n})=>({code:n,language:t,meta:""}))),dnt)}),Aue=Pr([]),hue=Pr(!0),z0n=hf({update(e,t){e.pubIn({[mue]:fue((t==null?void 0:t.codeBlockLanguages)??{}),[Aue]:(t==null?void 0:t.codeMirrorExtensions)??[],[hue]:(t==null?void 0:t.autoLoadLanguageSupport)??!0})},init(e,t){const n=fue((t==null?void 0:t.codeBlockLanguages)??{});e.pubIn({[mue]:n,[Aue]:(t==null?void 0:t.codeMirrorExtensions)??[],[Bdn]:$0n(n),[hue]:(t==null?void 0:t.autoLoadLanguageSupport)??!0})}});function $0n(e){return{match(t,n){return Object.hasOwn(e.keyMap,t??"")&&!n},priority:1,Editor:rat}}function F0n({url:e,title:t,text:n,onSubmit:r,onCancel:s,linkAutocompleteSuggestions:a,showLinkTitleField:o,showAnchorTextField:l}){const{register:c,handleSubmit:d,control:u,setValue:f,reset:m}=$tt({values:{url:e,title:t,text:n}}),h=$2();return xe.createElement("form",{onSubmit:p=>{d(r)(p),p.stopPropagation(),p.preventDefault()},onReset:p=>{p.stopPropagation(),s()},onKeyDown:p=>{p.key==="Escape"&&(p.stopPropagation(),s())},className:el(Wn.multiFieldForm,Wn.linkDialogEditForm)},xe.createElement("div",{className:Wn.formField},xe.createElement("label",{htmlFor:"link-url"},h("createLink.url","URL")),xe.createElement(rnt,{register:c,initialInputValue:e,inputName:"url",suggestions:a,setValue:f,control:u,placeholder:h("createLink.urlPlaceholder","Select or paste an URL"),autofocus:!0})),l?xe.createElement("div",{className:Wn.formField},xe.createElement("label",{htmlFor:"link-text",title:h("createLink.textTooltip","The text to be displayed for the link")},h("createLink.text","Anchor text")),xe.createElement("input",{id:"link-text",className:Wn.textInput,size:40,...c("text")})):null,o?xe.createElement("div",{className:Wn.formField},xe.createElement("label",{htmlFor:"link-title",title:h("createLink.titleTooltip","The link's title attribute, shown on hover")},h("createLink.title","Link title")),xe.createElement("input",{id:"link-title",className:Wn.textInput,size:40,...c("title")})):null,xe.createElement("div",{style:{display:"flex",justifyContent:"flex-end",gap:"var(--spacing-2)"}},xe.createElement("button",{type:"submit",title:h("createLink.saveTooltip","Set URL"),"aria-label":h("createLink.saveTooltip","Set URL"),className:el(Wn.primaryButton)},h("dialogControls.save","Save")),xe.createElement("button",{type:"reset",title:h("createLink.cancelTooltip","Cancel change"),"aria-label":h("createLink.cancelTooltip","Cancel change"),className:el(Wn.secondaryButton)},h("dialogControls.cancel","Cancel"))))}const B0n=()=>{const[e,t,n,r,s,a,o]=R1(N8,ic,z2,sA,dat,uat,mat),l=kh(sat),c=kh(iat),d=kh(aat),u=kh(oat),f=kh(lat);xe.useEffect(()=>{const y=()=>{t==null||t.getEditorState().read(()=>{l(!0)})};return window.addEventListener("resize",y),window.addEventListener("scroll",y),()=>{window.removeEventListener("resize",y),window.removeEventListener("scroll",y)}},[t,l]);const[m,h]=xe.useState(!1),p=$2();if(r.type==="inactive")return null;const x=r.rectangle,b=r.type==="preview"&&r.url.startsWith("http");return xe.createElement(nZ,{open:!0},xe.createElement(VBe,{"data-visible":r.type==="edit",className:Wn.linkDialogAnchor,style:{top:`${x.top}px`,left:`${x.left}px`,width:`${x.width}px`,height:`${x.height}px`}}),xe.createElement(rZ,{container:e==null?void 0:e.current},xe.createElement(WBe,{className:el(Wn.linkDialogPopoverContent),sideOffset:5,onOpenAutoFocus:y=>{y.preventDefault()},key:r.linkNodeKey},r.type==="edit"&&xe.createElement(F0n,{url:r.url,title:r.title,text:r.text,onSubmit:c,onCancel:d.bind(null),linkAutocompleteSuggestions:s,showLinkTitleField:o,showAnchorTextField:r.withAnchorText}),r.type==="preview"&&xe.createElement(xe.Fragment,null,xe.createElement("a",{className:Wn.linkDialogPreviewAnchor,href:r.url,...b?{target:"_blank",rel:"noreferrer"}:{},onClick:y=>{a!==null&&(y.preventDefault(),a(r.url))},title:b?p("linkPreview.open","Open {{url}} in new window",{url:r.url}):r.url},xe.createElement("span",null,r.url),b&&n("open_in_new")),xe.createElement(Kne,{onClick:()=>{u()},title:p("linkPreview.edit","Edit link URL"),"aria-label":p("linkPreview.edit","Edit link URL")},n("edit")),xe.createElement(Ehe,null,xe.createElement(Dhe,{open:m},xe.createElement(Rhe,{asChild:!0},xe.createElement(Kne,{title:p("linkPreview.copyToClipboard","Copy to clipboard"),"aria-label":p("linkPreview.copyToClipboard","Copy to clipboard"),onClick:()=>{window.navigator.clipboard.writeText(r.url).then(()=>{h(!0),setTimeout(()=>{h(!1)},1e3)})}},n(m?"check":"content_copy"))),xe.createElement(Lhe,{container:e==null?void 0:e.current},xe.createElement(zhe,{className:el(Wn.tooltipContent),sideOffset:5},p("linkPreview.copied","Copied!"),xe.createElement(PUe,null))))),xe.createElement(Kne,{title:p("linkPreview.remove","Remove link"),"aria-label":p("linkPreview.remove","Remove link"),onClick:()=>{f()}},n("link_off"))),xe.createElement(whe,{className:Wn.popoverArrow}))))},Kne=xe.forwardRef(({className:e,...t},n)=>xe.createElement("button",{className:el(Wn.actionButton,e),ref:n,...t}));function pue(e){if(!e)return null;const t=Mon(e);if(t===null)return null;const n=t.getParent();return ym(n)?n:ym(t)?t:null}const sat=ld(),sA=Pr({type:"inactive"},e=>{e.pub(DM,t=>t.registerCommand(BX,()=>e.getValue(sA).type==="preview"?(e.pub(sA,{type:"inactive"}),!0):!1,Il)),e.sub(e.pipe(RM),t=>{t!=="rich-text"&&e.pub(sA,{type:"inactive"})}),e.pub(DM,t=>t.registerCommand(zJe,n=>{if(n.key==="k"&&(Att?n.metaKey:n.ctrlKey)&&!e.getValue(I1)){const r=Tr();return Qr(r)?(e.pub(cat),n.stopPropagation(),n.preventDefault(),!0):!1}return!1},TM)),e.sub(e.pipe(oat,kc(sA,ic)),([,t,n])=>{if(t.type==="preview")setTimeout(()=>{n==null||n.getEditorState().read(()=>{const r=g0(t.linkNodeKey),s=ym(r)?r.getTextContent().length>0&&r.getChildrenSize()<=1:!1,a=s&&r?r.getTextContent():"";e.pub(sA,{type:"edit",initialUrl:t.url,url:t.url,title:t.title,text:a,withAnchorText:s,linkNodeKey:t.linkNodeKey,rectangle:t.rectangle})})});else throw new Error("Cannot switch to edit mode when not in preview mode")}),e.sub(e.pipe(iat,kc(ic,sA,uC)),([t,n,r,s])=>{var a,o,l;const c=((a=t.text)==null?void 0:a.trim())??"",d=((o=t.url)==null?void 0:o.trim())??"",u=((l=t.title)==null?void 0:l.trim())??"";if(d!==""){if(s!=null&&s.isCollapsed()){const f=c||u||d;n==null||n.update(()=>{const m=pue(s);if(m)if(Vg(m)){const h=x2(d,{title:u});h.append(qp(c)),m.replace(h),h.select()}else m.setURL(d),m.setTitle(u),zNe(m.getFirstChild(),c);else{const h=x2(d,{title:u});h.append(qp(f)),BN([h]),h.select()}},{discrete:!0})}else n==null||n.update(()=>{zNe(s==null?void 0:s.anchor.getNode(),c)}),n==null||n.dispatchCommand(fC,{url:d,title:u});e.pub(sA,{type:"preview",linkNodeKey:r.linkNodeKey,rectangle:r.rectangle,title:u,url:d})}else r.type==="edit"&&r.initialUrl!==""&&(n==null||n.dispatchCommand(fC,null)),e.pub(sA,{type:"inactive"})}),e.link(e.pipe(aat,kc(sA,ic),qw(([,t,n])=>{if(t.type==="edit")return n==null||n.focus(),t.initialUrl===""?{type:"inactive"}:{type:"preview",url:t.initialUrl,linkNodeKey:t.linkNodeKey,rectangle:t.rectangle};throw new Error("Cannot cancel edit when not in edit mode")})),sA),e.link(e.pipe(e.combine(uC,sat),kc(ic,sA,I1),qw(([[t],n,r,s])=>{if(Qr(t)&&n&&!s){const a=pue(t);if(!t.isCollapsed())return{type:"inactive"};if(a){const o=utt(n);return o?{type:"preview",url:a.getURL(),linkNodeKey:a.getKey(),title:a.getTitle(),rectangle:o}:{type:"inactive"}}else return{type:"inactive"}}else return{type:"inactive"}})),sA)}),iat=ld(),aat=P5();P5();const oat=P5(),lat=P5(e=>{e.sub(e.pipe(lat,kc(ic)),([,t])=>{t==null||t.dispatchCommand(fC,null)})}),cat=P5(e=>{e.sub(e.pipe(cat,kc(uC,ic),ER(([,t])=>Qr(t))),([,t,n])=>{n==null||n.focus(()=>{setTimeout(()=>{n.getEditorState().read(()=>{const r=pue(t),s=utt(n),a=(r==null?void 0:r.getURL())??"",o=(r==null?void 0:r.getURL())??"",l=(r==null?void 0:r.getTitle())??"",c=(r==null?void 0:r.getKey())??"",d=r?r.getTextContent().length>0&&r.getChildrenSize()<=1:!!(t!=null&&t.isCollapsed()),u=d&&r?r.getTextContent():"";e.pub(sA,{type:"edit",initialUrl:a,url:o,title:l,text:u,withAnchorText:d,linkNodeKey:c,rectangle:s})})})})})}),dat=Pr([]),uat=Pr(null),fat=Pr(null,e=>{e.pub(DM,t=>{function n(r){const[s,a]=e.getValues([I1,fat]);!s||a===null||t.update(()=>{const o=z6(r.target);if(o!==null){const l=d1(o,c=>c instanceof F1);l!==null&&a(r,l,l.getURL())}})}return t.registerRootListener((r,s)=>{r&&r.addEventListener("click",n),s&&s.removeEventListener("click",n)})})});function zNe(e,t){ao(e)&&t&&(e.setTextContent(t),e.selectStart())}const mat=Pr(!0),Q0n=hf({init(e,t){e.pub(I8,(t==null?void 0:t.LinkDialog)??B0n),e.pub(uat,(t==null?void 0:t.onClickLinkCallback)??null),e.pub(fat,(t==null?void 0:t.onReadOnlyClickLinkCallback)??null),e.pub(mat,(t==null?void 0:t.showLinkTitleField)??!0)},update(e,t={}){e.pub(dat,t.linkAutocompleteSuggestions??[])}});class mW{static create(t,n,r,s,a){let o=s+(s<<8)+t+(n<<4)|0;return new mW(t,n,r,o,a,[],[])}constructor(t,n,r,s,a,o,l){this.type=t,this.value=n,this.from=r,this.hash=s,this.end=a,this.children=o,this.positions=l,this.hashProp=[[Ks.contextHash,s]]}addChild(t,n){t.prop(Ks.contextHash)!=this.hash&&(t=new ta(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 ta(t.types[this.type],this.children,this.positions,n-this.from).balance({makeTree:(s,a,o)=>new ta(Iu.none,s,a,o,this.hashProp)})}}var tr;(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"})(tr||(tr={}));class U0n{constructor(t,n){this.start=t,this.content=n,this.marks=[],this.parsers=[]}}class q0n{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 n_(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 s=n;s<t;s++)r+=this.text.charCodeAt(s)==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 $Ne(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==tr.OrderedList?dbe:cbe)(n,t,!1);return r>0&&(e.type!=tr.BulletList||lbe(n,t,!1)<0)&&n.text.charCodeAt(n.pos+r-1)==e.value}const Aat={[tr.Blockquote](e,t,n){return n.next!=62?!1:(n.markers.push(Ua(tr.QuoteMark,t.lineStart+n.pos,t.lineStart+n.pos+1)),n.moveBase(n.pos+(tg(n.text.charCodeAt(n.pos+1))?2:1)),e.end=t.lineStart+n.text.length,!0)},[tr.ListItem](e,t,n){return n.indent<n.baseIndent+e.value&&n.next>-1?!1:(n.moveBaseColumn(n.baseIndent+e.value),!0)},[tr.OrderedList]:$Ne,[tr.BulletList]:$Ne,[tr.Document](){return!0}};function tg(e){return e==32||e==9||e==10||e==13}function n_(e,t=0){for(;t<e.length&&tg(e.charCodeAt(t));)t++;return t}function FNe(e,t,n){for(;t>n&&tg(e.charCodeAt(t-1));)t--;return t}function hat(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 pat(e){return e.next!=62?-1:e.text.charCodeAt(e.pos+1)==32?2:1}function lbe(e,t,n){if(e.next!=42&&e.next!=45&&e.next!=95)return-1;let r=1;for(let s=e.pos+1;s<e.text.length;s++){let a=e.text.charCodeAt(s);if(a==e.next)r++;else if(!tg(a))return-1}return n&&e.next==45&&bat(e)>-1&&e.depth==t.stack.length&&t.parser.leafBlockParsers.indexOf(kat.SetextHeading)>-1||r<3?-1:1}function gat(e,t){for(let n=e.stack.length-1;n>=0;n--)if(e.stack[n].type==t)return!0;return!1}function cbe(e,t,n){return(e.next==45||e.next==43||e.next==42)&&(e.pos==e.text.length-1||tg(e.text.charCodeAt(e.pos+1)))&&(!n||gat(t,tr.BulletList)||e.skipSpace(e.pos+2)<e.text.length)?1:-1}function dbe(e,t,n){let r=e.pos,s=e.next;for(;s>=48&&s<=57;){r++;if(r==e.text.length)return-1;s=e.text.charCodeAt(r)}return r==e.pos||r>e.pos+9||s!=46&&s!=41||r<e.text.length-1&&!tg(e.text.charCodeAt(r+1))||n&&!gat(t,tr.OrderedList)&&(e.skipSpace(r+1)==e.text.length||r>e.pos+1||e.next!=49)?-1:r+1-e.pos}function xat(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 bat(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&&tg(e.text.charCodeAt(t));)t++;return t==e.text.length?n:-1}const gue=/^[ \t]*$/,yat=/-->/,vat=/\?>/,xue=[[/^<(?:script|pre|style)(?:\s|>|$)/i,/<\/(?:script|pre|style)>/i],[/^\s*<!--/,yat],[/^\s*<\?/,vat],[/^\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,gue],[/^\s*(?:<\/[a-z][\w-]*\s*>|<[a-z][\w-]*(\s+[a-z:_][\w-.]*(?:\s*=\s*(?:[^\s"'=<>`]+|'[^']*'|"[^"]*"))?)*\s*>)\s*$/i,gue]];function wat(e,t,n){if(e.next!=60)return-1;let r=e.text.slice(e.pos);for(let s=0,a=xue.length-(n?1:0);s<a;s++)if(xue[s][0].test(r))return s;return-1}function BNe(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 Mv(e,t,n){let r=e.length-1;r>=0&&e[r].to==t&&e[r].type==tr.CodeText?e[r].to=n:e.push(Ua(tr.CodeText,t,n))}const OF={LinkReference:void 0,IndentedCode(e,t){let n=t.baseIndent+4;if(t.indent<n)return!1;let r=t.findColumn(n),s=e.lineStart+r,a=e.lineStart+t.text.length,o=[],l=[];for(Mv(o,s,a);e.nextLine()&&t.depth>=e.stack.length;)if(t.pos==t.text.length){Mv(l,e.lineStart-1,e.lineStart);for(let c of t.markers)l.push(c)}else{if(t.indent<n)break;{if(l.length){for(let d of l)d.type==tr.CodeText?Mv(o,d.from,d.to):o.push(d);l=[]}Mv(o,e.lineStart-1,e.lineStart);for(let d of t.markers)o.push(d);a=e.lineStart+t.text.length;let c=e.lineStart+t.findColumn(t.baseIndent+4);c<a&&Mv(o,c,a)}}return l.length&&(l=l.filter(c=>c.type!=tr.CodeText),l.length&&(t.markers=l.concat(t.markers))),e.addNode(e.buffer.writeElements(o,-s).finish(tr.CodeBlock,a-s),s),!0},FencedCode(e,t){let n=hat(t);if(n<0)return!1;let r=e.lineStart+t.pos,s=t.next,a=n-t.pos,o=t.skipSpace(n),l=FNe(t.text,t.text.length,o),c=[Ua(tr.CodeMark,r,r+a)];o<l&&c.push(Ua(tr.CodeInfo,e.lineStart+o,e.lineStart+l));for(let d=!0,u=!0,f=!1;e.nextLine()&&t.depth>=e.stack.length;d=!1){let m=t.pos;if(t.indent-t.baseIndent<4)for(;m<t.text.length&&t.text.charCodeAt(m)==s;)m++;if(m-t.pos>=a&&t.skipSpace(m)==t.text.length){for(let h of t.markers)c.push(h);u&&f&&Mv(c,e.lineStart-1,e.lineStart),c.push(Ua(tr.CodeMark,e.lineStart+t.pos,e.lineStart+m)),e.nextLine();break}else{f=!0,d||(Mv(c,e.lineStart-1,e.lineStart),u=!1);for(let x of t.markers)c.push(x);let h=e.lineStart+t.basePos,p=e.lineStart+t.text.length;h<p&&(Mv(c,h,p),u=!1)}}return e.addNode(e.buffer.writeElements(c,-r).finish(tr.FencedCode,e.prevLineEnd()-r),r),!0},Blockquote(e,t){let n=pat(t);return n<0?!1:(e.startContext(tr.Blockquote,t.pos),e.addNode(tr.QuoteMark,e.lineStart+t.pos,e.lineStart+t.pos+1),t.moveBase(t.pos+n),null)},HorizontalRule(e,t){if(lbe(t,e,!1)<0)return!1;let n=e.lineStart+t.pos;return e.nextLine(),e.addNode(tr.HorizontalRule,n),!0},BulletList(e,t){let n=cbe(t,e,!1);if(n<0)return!1;e.block.type!=tr.BulletList&&e.startContext(tr.BulletList,t.basePos,t.next);let r=BNe(t,t.pos+1);return e.startContext(tr.ListItem,t.basePos,r-t.baseIndent),e.addNode(tr.ListMark,e.lineStart+t.pos,e.lineStart+t.pos+n),t.moveBaseColumn(r),null},OrderedList(e,t){let n=dbe(t,e,!1);if(n<0)return!1;e.block.type!=tr.OrderedList&&e.startContext(tr.OrderedList,t.basePos,t.text.charCodeAt(t.pos+n-1));let r=BNe(t,t.pos+n);return e.startContext(tr.ListItem,t.basePos,r-t.baseIndent),e.addNode(tr.ListMark,e.lineStart+t.pos,e.lineStart+t.pos+n),t.moveBaseColumn(r),null},ATXHeading(e,t){let n=xat(t);if(n<0)return!1;let r=t.pos,s=e.lineStart+r,a=FNe(t.text,t.text.length,r),o=a;for(;o>r&&t.text.charCodeAt(o-1)==t.next;)o--;(o==a||o==r||!tg(t.text.charCodeAt(o-1)))&&(o=t.text.length);let l=e.buffer.write(tr.HeaderMark,0,n).writeElements(e.parser.parseInline(t.text.slice(r+n+1,o),s+n+1),-s);o<t.text.length&&l.write(tr.HeaderMark,o-r,a-r);let c=l.finish(tr.ATXHeading1-1+n,t.text.length-r);return e.nextLine(),e.addNode(c,s),!0},HTMLBlock(e,t){let n=wat(t,e,!1);if(n<0)return!1;let r=e.lineStart+t.pos,s=xue[n][1],a=[],o=s!=gue;for(;!s.test(t.text)&&e.nextLine();){if(t.depth<e.stack.length){o=!1;break}for(let d of t.markers)a.push(d)}o&&e.nextLine();let l=s==yat?tr.CommentBlock:s==vat?tr.ProcessingInstructionBlock:tr.HTMLBlock,c=e.prevLineEnd();return e.addNode(e.buffer.writeElements(a,-r).finish(l,c-r),r),!0},SetextHeading:void 0};class V0n{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 s=r.content+`
1785
1785
  `+n.scrub(),a=this.advance(s);return a>-1&&a<s.length?this.complete(t,r,a):!1}finish(t,n){return(this.stage==2||this.stage==3)&&n_(n.content,this.pos)==n.content.length?this.complete(t,n,n.content.length):!1}complete(t,n,r){return t.addLeafElement(n,Ua(tr.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(_at(t,this.pos,this.start,!0)))return-1;if(t.charCodeAt(this.pos)!=58)return this.stage=-1;this.elts.push(Ua(tr.LinkMark,this.pos+this.start,this.pos+this.start+1)),this.pos++}else if(this.stage==1){if(!this.nextStage(Pat(t,n_(t,this.pos),this.start)))return-1}else if(this.stage==2){let n=n_(t,this.pos),r=0;if(n>this.pos){let s=Tat(t,n,this.start);if(s){let a=Zne(t,s.to-this.start);a>0&&(this.nextStage(s),r=a)}}return r||(r=Zne(t,this.pos)),r>0&&r<t.length?r:-1}else return Zne(t,this.pos)}}}function Zne(e,t){for(;t<e.length;t++){let n=e.charCodeAt(t);if(n==10)break;if(!tg(n))return-1}return t}class W0n{nextLine(t,n,r){let s=n.depth<t.stack.length?-1:bat(n),a=n.next;if(s<0)return!1;let o=Ua(tr.HeaderMark,t.lineStart+n.pos,t.lineStart+s);return t.nextLine(),t.addLeafElement(r,Ua(a==61?tr.SetextHeading1:tr.SetextHeading2,r.start,t.prevLineEnd(),[...t.parser.parseInline(r.content,r.start),o])),!0}finish(){return!1}}const kat={LinkReference(e,t){return t.content.charCodeAt(0)==91?new V0n(t):null},SetextHeading(){return new W0n}},H0n=[(e,t)=>xat(t)>=0,(e,t)=>hat(t)>=0,(e,t)=>pat(t)>=0,(e,t)=>cbe(t,e,!0)>=0,(e,t)=>dbe(t,e,!0)>=0,(e,t)=>lbe(t,e,!0)>=0,(e,t)=>wat(t,e,!0)>=0],K0n={text:"",end:0};class Z0n{constructor(t,n,r,s){this.parser=t,this.input=n,this.ranges=s,this.line=new q0n,this.atEnd=!1,this.reusePlaceholders=new Map,this.stoppedAt=null,this.rangeI=0,this.to=s[s.length-1].to,this.lineStart=this.absoluteLineStart=this.absoluteLineEnd=s[0].from,this.block=mW.create(tr.Document,0,this.lineStart,0,0),this.stack=[this.block],this.fragments=r.length?new Y0n(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 s=t.depth<this.stack.length?this.stack[this.stack.length-1]:null;for(;r<t.markers.length&&(!s||t.markers[r].from<s.end);){let a=t.markers[r++];this.addNode(a.type,a.from,a.to)}if(!s)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 s=r(this,t);if(s!=!1){if(s==!0)return null;t.forward();continue e}}break}let n=new U0n(this.lineStart+t.pos,t.text.slice(t.pos));for(let r of this.parser.leafBlockParsers)if(r){let s=r(this,n);s&&n.parsers.push(s)}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+=`
1786
1786
  `+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=Mat(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=K0n;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,s=this.rangeI;for(;this.ranges[s].to<n.end;){s++;let a=this.ranges[s].from,o=this.lineChunkAt(a);n.end=a+o.length,n.text=n.text.slice(0,this.ranges[s-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 s=this.stack[t.depth],a=this.parser.skipContextMarkup[s.type];if(!a)throw new Error("Unhandled block context "+tr[s.type]);let o=this.line.markers.length;if(!a(s,this,t)){this.line.markers.length>o&&(s.end=this.line.markers[this.line.markers.length-1].to),t.forward();break}t.forward()}}lineChunkAt(t){let n=this.input.chunk(t),r;if(this.input.lineChunks)r=n==`
@@ -1864,7 +1864,7 @@ ${a(l,0)}
1864
1864
 
1865
1865
  `);t(ne?`${ne}
1866
1866
 
1867
- ${le}`:le)}}else if(p)for(const se of D)try{await p(se)}catch(ne){x==null||x(ne instanceof Error?ne:new Error("Attachment upload failed"),se)}}finally{B(!1),_.current&&(_.current.value=""),requestAnimationFrame(()=>{var se;return(se=z.current)==null?void 0:se.focus()})}}}return i.jsxs("div",{ref:T,"aria-label":l,className:"chat-composer grid min-w-0 grid-cols-[var(--control-height-sm)_minmax(0,1fr)_auto] items-end gap-x-1.5 rounded-[var(--radius-lg)] p-2 md:block md:p-3","data-composer-state":e.trim()?"composing":"empty","data-issue-detail-escape-back":C?e.trim()?"dirty":"empty":void 0,"data-detail-escape-layer":I?"true":void 0,"data-testid":N,onMouseDown:V,tabIndex:-1,children:[i.jsx("div",{className:"col-start-2 row-start-1 min-w-0 md:block",children:i.jsxs("div",{ref:W,"data-testid":"issue-comment-composer-editor-scroll",className:"motion-comment-composer-height scrollbar-auto-hide relative h-[var(--comment-composer-editor-height)] min-w-0 max-h-[min(24dvh,10rem)] overflow-y-auto overscroll-contain pr-1 md:h-auto md:max-h-[min(38dvh,22rem)]",style:{"--comment-composer-editor-height":"1.875rem"},children:[e.trim()?null:i.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-0 left-0 z-10 flex items-start pt-px text-sm text-muted-foreground md:hidden",children:d}),i.jsx(Cu,{ref:z,engine:"milkdown",value:e,onChange:t,ariaLabel:c,placeholder:d,mentions:f,agentMentionIntent:"wake",onMentionQueryChange:m,mentionMenuAnchorRef:T,mentionMenuPlacement:"container",onSubmit:n,imageUploadHandler:h,className:"rounded-[var(--radius-md)] bg-transparent",contentClassName:"min-h-7 bg-transparent text-sm leading-6 text-foreground md:min-h-16",bordered:!1})]})}),k?i.jsx("div",{className:"col-span-3 mt-2 md:mt-2",children:k}):null,i.jsxs("div",{"data-testid":"issue-comment-composer-toolbar",className:"contents md:mt-3 md:flex md:items-center md:justify-end md:gap-3",children:[h||p?i.jsxs("div",{className:`col-start-1 row-start-1 flex items-center self-end md:gap-3 ${G.length===0?"md:mr-auto":""}`,children:[i.jsx("input",{ref:_,type:"file",accept:b,"aria-label":y,multiple:w,className:"hidden",onChange:L}),i.jsx(oe,{type:"button",variant:"ghost",size:"icon-sm",onClick:()=>{var R;return(R=_.current)==null?void 0:R.click()},disabled:$||s,title:"Attach file",children:i.jsx(df,{className:"h-4 w-4"})})]}):null,G.length>0?i.jsxs("div",{"data-testid":"comment-agent-wake-status",className:"col-span-3 row-start-2 mt-2 flex min-w-0 flex-wrap items-center gap-2 md:mt-0 md:flex-1",children:[i.jsx("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-1.5",role:"status","aria-live":"polite",children:i.jsx(o7n,{mentionedAgents:G,onToggle:(R,D,X)=>{t(PNt(e,R,D?"reference":"wake")),X&&requestAnimationFrame(()=>{var ee;return(ee=z.current)==null?void 0:ee.focus()})}})}),S?i.jsx("div",{className:"ml-auto flex shrink-0 items-center",children:S}):null]}):S?i.jsx("div",{className:"col-span-3 row-start-2 mt-2 flex justify-end md:contents",children:S}):null,i.jsxs("div",{className:"col-start-3 row-start-1 flex items-center gap-1.5 self-end",children:[j,i.jsx(oe,{type:"button",size:"sm",disabled:!r||$,onClick:n,children:s?"Posting...":u})]})]})]})}function c7n(e,t){return e.map(n=>{var s,a;const r=t==null?void 0:t.get(n.agentId);return{id:n.runId,status:n.status,invocationSource:"issue_timeline",triggerDetail:null,startedAt:typeof n.startedAt=="string"?n.startedAt:((s=n.startedAt)==null?void 0:s.toISOString())??null,finishedAt:typeof n.finishedAt=="string"?n.finishedAt:((a=n.finishedAt)==null?void 0:a.toISOString())??null,createdAt:typeof n.createdAt=="string"?n.createdAt:n.createdAt.toISOString(),agentId:n.agentId,agentName:(r==null?void 0:r.name)??n.agentId.slice(0,8),agentRuntimeType:(r==null?void 0:r.agentRuntimeType)??"process",issueId:null,resultJson:n.resultJson??null}})}function Kdt(e){return e!=null&&e!=="paused"&&e!=="terminated"&&e!=="pending_approval"}function d7n(e,t=new Set,n=!1){return n?!1:!XUe(e).some(r=>{if(t.has(r))return!0;const s=yqe(r);if((s==null?void 0:s.kind)!=="agent")return!1;let a=0;for(const o of t)if(o.replace(/-/g,"").toLowerCase().startsWith(s.prefix)&&(a+=1),a>1)return!1;return a===1})}function u7n(e){try{localStorage.removeItem(e)}catch{}}function f7n({agentMap:e,body:t,canReopen:n,composerSurfaceRef:r,draftKey:s,editorRef:a,locale:o,onAdd:l,reopen:c,reopenWillWakeAgent:d,setReopen:u,updateBody:f}){const{confirm:m}=Bs(),[h,p]=A.useState(!1),[x,b]=A.useState(!1),y=A.useRef(!1),w=A.useRef(null),k=A.useRef(null),S=A.useMemo(()=>new Set((e==null?void 0:e.keys())??[]),[e]);A.useEffect(()=>()=>{w.current!==null&&window.cancelAnimationFrame(w.current),k.current!==null&&window.clearTimeout(k.current)},[]);function j(){var I;if((I=a.current)==null||I.focus(),typeof window<"u"){w.current!==null&&(window.cancelAnimationFrame(w.current),w.current=null),k.current!==null&&(window.clearTimeout(k.current),k.current=null);const N=()=>{var E;w.current=null;const M=document.activeElement;(!M||M===document.body||M instanceof HTMLElement&&M.closest('[role="dialog"]'))&&((E=a.current)==null||E.focus())};w.current=window.requestAnimationFrame(N),k.current=window.setTimeout(()=>{k.current=null,N()},250)}}async function C(I="comment"){var _,z;if(y.current)return;const M=(((z=(_=a.current)==null?void 0:_.getMarkdown)==null?void 0:z.call(_))??t).trim();if(!M)return;const E=n&&c?!0:void 0;y.current=!0;try{if(d7n(M,S,I==="steer"||!!(E&&d))){b(!0);const T=await m({title:RP(o,"comments.unmentionedConfirm.title"),description:RP(o,"comments.unmentionedConfirm.description"),cancelLabel:RP(o,"comments.unmentionedConfirm.cancel"),confirmLabel:RP(o,"comments.unmentionedConfirm.confirm"),restoreFocus:$=>{var B;$?(B=r.current)==null||B.focus({preventScroll:!0}):j()}});if(b(!1),!T){j();return}}p(!0),I==="steer"?await l(M,E,"steer"):await l(M,E),f(""),s&&u7n(s),u(n)}finally{p(!1),b(!1),y.current=!1}}return{canSubmit:!h&&!x&&!!t.trim(),handleSubmit:C,submitting:h}}function ZO(e){return`${e.kind}:${e.id}`}function m7n({activityItems:e,comments:t,linkedRuns:n}){const r=t.map(l=>({kind:"comment",id:l.id,createdAtMs:new Date(l.createdAt).getTime(),comment:l})),s=n.map(l=>({kind:"run",id:l.runId,createdAtMs:new Date(l.startedAt??l.createdAt).getTime(),run:l})),a=e.map(l=>({kind:"activity",id:l.id,createdAtMs:new Date(l.createdAt).getTime(),activity:l})),o={activity:0,comment:1,run:2};return[...r,...s,...a].sort((l,c)=>l.createdAtMs!==c.createdAtMs?l.createdAtMs-c.createdAtMs:l.kind!==c.kind?o[l.kind]-o[c.kind]:l.id.localeCompare(c.id))}function A7n(e){return e.map(t=>({key:ZO(t),kind:t.kind,createdAtMs:t.createdAtMs,...t.kind==="comment"?{commentBody:t.comment.body}:{},...t.kind==="run"?{runStatus:t.run.status}:{}}))}function h7n(e,t){var s;if(t.hidden.length===0)return e;const n=new Map(e.map(a=>[ZO(a),a])),r=a=>a.map(o=>n.get(o.key)).filter(o=>!!o);return[...r(t.visibleHead),{kind:"disclosure",id:"middle",createdAtMs:((s=t.hidden[0])==null?void 0:s.createdAtMs)??0,hiddenCount:t.hidden.length},...r(t.visibleTail)]}function p7n(e,t,n){const r=new Array(e);return new Proxy(r,{get(s,a,o){if(typeof a=="string"){const l=a.charCodeAt(0);if(l>=48&&l<=57){const c=+a;if(Number.isInteger(c)&&c>=0&&c<e){let d=s[c];if(!d){const u=t[c*2];d=s[c]={index:c,key:n(c),start:u,size:t[c*2+1],end:u+t[c*2+1],lane:0}}return d}}if(a==="length")return e}return Reflect.get(s,a,o)}})}function F7(e,t,n){let r=n.initialDeps??[],s,a=!0;function o(){const l=e();return(l.length!==r.length||l.some((d,u)=>r[u]!==d))&&(r=l,s=t(...l),n!=null&&n.onChange&&!(a&&n.skipInitialOnChange)&&n.onChange(s),a=!1),s}return o.updateDeps=l=>{r=l},o}function pPe(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const g7n=(e,t)=>Math.abs(e-t)<1.01,x7n=(e,t,n)=>{let r;return function(...s){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,s),n)}};let BI;const Wre=()=>{if(BI!==void 0)return BI;if(typeof navigator>"u")return BI=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return BI=!0;const e=navigator.maxTouchPoints;return BI=navigator.platform==="MacIntel"&&e!==void 0&&e>0},gPe=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},b7n=e=>e,y7n=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,s=new Array(r);for(let a=0;a<r;a++)s[a]=t+a;return s},v7n=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const s=o=>{const{width:l,height:c}=o;t({width:Math.round(l),height:Math.round(c)})};if(s(gPe(n)),!r.ResizeObserver)return()=>{};const a=new r.ResizeObserver(o=>{const l=()=>{const c=o[0];if(c!=null&&c.borderBoxSize){const d=c.borderBoxSize[0];if(d){s({width:d.inlineSize,height:d.blockSize});return}}s(gPe(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return a.observe(n,{box:"border-box"}),()=>{a.unobserve(n)}},vE={passive:!0},w7n=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=()=>{t({width:n.innerWidth,height:n.innerHeight})};return r(),n.addEventListener("resize",r,vE),()=>{n.removeEventListener("resize",r)}},k7n=typeof window>"u"?!0:"onscrollend"in window,Zdt=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const s=e.targetWindow;if(!s)return;const a=e.options.useScrollendEvent&&k7n;let o=0;const l=a?null:x7n(s,()=>t(o,!1),e.options.isScrollingResetDelay),c=f=>()=>{o=n(r),l==null||l(),t(o,f)},d=c(!0),u=c(!1);return r.addEventListener("scroll",d,vE),a&&r.addEventListener("scrollend",u,vE),()=>{r.removeEventListener("scroll",d),a&&r.removeEventListener("scrollend",u)}},O7n=(e,t)=>Zdt(e,t,n=>{const{horizontal:r,isRtl:s}=e.options;return r?n.scrollLeft*(s&&-1||1):n.scrollTop}),S7n=(e,t)=>Zdt(e,t,n=>e.options.horizontal?n.scrollX:n.scrollY),j7n=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),s=n.options.getItemKey(r);return n.itemSizeCache.get(s)??n.options.estimateSize(r)}if(t!=null&&t.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),s=n.options.getItemKey(r),a=n.itemSizeCache.get(s);if(a!==void 0)return a}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},Xdt=(e,{adjustments:t=0,behavior:n},r)=>{var s,a;(a=(s=r.scrollElement)==null?void 0:s.scrollTo)==null||a.call(s,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},C7n=Xdt,N7n=Xdt;class I7n{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,s;return((s=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:s.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(s=>{s.forEach(a=>{const o=()=>{const l=a.target,c=this.indexFromElement(l);if(!l.isConnected){this.observer.unobserve(l);for(const[d,u]of this.elementsCache)if(u===l){this.elementsCache.delete(d);break}return}this.shouldMeasureDuringScroll(c)&&this.resizeItem(c,this.options.measureElement(l,a,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(o):o()})}));return{disconnect:()=>{var s;(s=r())==null||s.disconnect(),n=null},observe:s=>{var a;return(a=r())==null?void 0:a.observe(s,{box:"border-box"})},unobserve:s=>{var a;return(a=r())==null?void 0:a.unobserve(s)}}})(),this.range=null,this.setOptions=n=>{var r,s;const a={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:b7n,rangeExtractor:y7n,onChange:()=>{},measureElement:j7n,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const m in n){const h=n[m];h!==void 0&&(a[m]=h)}const o=this.options;let l=null,c=null,d=!1;if(o!==void 0&&o.enabled&&a.enabled&&a.anchorTo==="end"&&this.scrollElement!==null){const m=o.count,h=a.count,p=this.getMeasurements(),x=m>0?((r=p[0])==null?void 0:r.key)??o.getItemKey(0):null,b=m>0?((s=p[m-1])==null?void 0:s.key)??o.getItemKey(m-1):null;if(h!==m||m>0&&h>0&&(a.getItemKey(0)!==x||a.getItemKey(h-1)!==b)){d=!0;const k=m>0?this.getVirtualItemForOffset(this.getScrollOffset())??p[0]:null;k&&(l=[k.key,this.getScrollOffset()-k.start]);const S=a.followOnAppend===!0?"auto":a.followOnAppend||null;S&&h>m&&this.isAtEnd(o.scrollEndThreshold)&&(m===0||a.getItemKey(h-1)!==b)&&(c=S)}}this.options=a,d&&(this.pendingMin=0,this.itemSizeCacheVersion++);let u=!1,f=0;if(l&&this.scrollOffset!==null){const[m,h]=l,p=this.getMeasurements(),{count:x,getItemKey:b}=this.options;let y=0;for(;y<x&&b(y)!==m;)y++;if(y<x){const w=p[y];if(w){const k=Math.max(0,w.start+h);k!==this.scrollOffset&&(f=k-this.scrollOffset,this.scrollOffset=k,u=!0)}}}(u||c)&&(this.pendingScrollAnchor=[u?l[0]:null,u?l[1]:0,c,f])},this.notify=n=>{var r,s;(s=(r=this.options).onChange)==null||s.call(r,this,n)},this.maybeNotify=F7(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(a=>{this.observer.observe(a)}),this.unsubs.push(this.options.observeElementRect(this,a=>{this.scrollRect=a,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(a,o)=>{if(o&&this._intendedScrollOffset===null&&a===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(a-this._intendedScrollOffset)<1.5&&(a=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const l=this.getScrollOffset();this.scrollDirection=o?l===a?this.scrollDirection:l<a?"forward":"backward":null,this.scrollOffset=a,this.isScrolling=o,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),"addEventListener"in this.scrollElement){const a=this.scrollElement,o=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},l=()=>{this._iosTouching=!1,!(!Wre()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};a.addEventListener("touchstart",o,vE),a.addEventListener("touchend",l,vE),this.unsubs.push(()=>{a.removeEventListener("touchstart",o),a.removeEventListener("touchend",l),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const s=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,s&&this.scrollElement&&this.options.enabled){const[a,o,l,c]=s;a!==null&&!l&&(Wre()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?c!==0&&(this._iosDeferredAdjustment+=c):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),l&&this.scrollToEnd({behavior:l})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;if(this._iosDeferredAdjustment<0&&n>=r-1){this._iosDeferredAdjustment=0;return}const s=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=s,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=F7(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,s,a,o,l,c,d)=>(this.prevLanes!==void 0&&this.prevLanes!==l&&(this.lanesChangedFlag=!0),this.prevLanes=l,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:s,getItemKey:a,enabled:o,lanes:l,laneAssignmentMode:c,gap:d}),{key:!1}),this.getMeasurements=F7(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:s,getItemKey:a,enabled:o,lanes:l,laneAssignmentMode:c,gap:d},u)=>{const f=this.itemSizeCache;if(!o)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const y of this.laneAssignments.keys())y>=n&&this.laneAssignments.delete(y);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(y=>{this.itemSizeCache.set(y.key,y.size)}));const m=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),l===1){const y=n*2;let w=this._flatMeasurements;if(!w||w.length<y){const j=new Float64Array(y);w&&m>0&&j.set(w.subarray(0,m*2)),w=j,this._flatMeasurements=w}let k;if(m===0)k=r+s;else{const j=m-1;k=w[j*2]+w[j*2+1]+d}for(let j=m;j<n;j++){const C=a(j),I=f.get(C),N=typeof I=="number"?I:this.options.estimateSize(j);w[j*2]=k,w[j*2+1]=N,k+=N+d}const S=p7n(n,w,a);return this.measurementsCache=S,S}const h=this.measurementsCache.slice(0,m),p=new Array(l).fill(void 0),x=new Float64Array(l);let b=0;for(let y=0;y<m;y++){const w=h[y];w&&(p[w.lane]===void 0&&b++,p[w.lane]=y,x[w.lane]=w.end)}for(let y=m;y<n;y++){const w=a(y),k=this.laneAssignments.get(y);let S,j;const C=c==="estimate"||f.has(w);if(k!==void 0&&this.options.lanes>1){S=k;const E=p[S],_=E!==void 0?h[E]:void 0;j=_?_.end+d:r+s}else if(b===l){let E=0,_=x[0],z=p[0];for(let T=1;T<l;T++){const $=x[T];($<_||$===_&&p[T]<z)&&(E=T,_=$,z=p[T])}S=E,j=_+d,C&&this.laneAssignments.set(y,S)}else S=y%this.options.lanes,j=r+s,C&&this.laneAssignments.set(y,S);const I=f.get(w),N=typeof I=="number"?I:this.options.estimateSize(y),M=j+N;h[y]={index:y,start:j,size:N,end:M,key:w,lane:S},p[S]===void 0&&b++,p[S]=y,x[S]=M}return this.measurementsCache=h,h},{key:!1,debug:()=>this.options.debug}),this.calculateRange=F7(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,a)=>n.length===0||r===0?(this.range=null,null):(this.range=T7n(n,r,s,a,a===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=F7(()=>{let n=null,r=null;const s=this.calculateRange();return s&&(n=s.startIndex,r=s.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,s,a,o)=>a===null||o===null?[]:n({startIndex:a,endIndex:o,overscan:r,count:s}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,s=n.getAttribute(r);return s?parseInt(s,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const s=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(s!==void 0&&this.range){const a=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),o=Math.max(0,s-a),l=Math.min(this.options.count-1,s+a);return n>=o&&n<=l}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((o,l)=>{o.isConnected||(this.observer.unobserve(o),this.elementsCache.delete(l))});return}const r=this.indexFromElement(n),s=this.options.getItemKey(r),a=this.elementsCache.get(s);a!==n&&(a&&this.observer.unobserve(a),this.observer.observe(n),this.elementsCache.set(s,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var s,a;if(n<0||n>=this.options.count)return;let o,l,c;const d=this._flatMeasurements;if(this.options.lanes===1&&d!==null)c=this.options.getItemKey(n),l=d[n*2],o=d[n*2+1];else{const m=this.measurementsCache[n];if(!m)return;c=m.key,l=m.start,o=m.size}const u=this.itemSizeCache.get(c)??o,f=r-u;if(f!==0){const m=this.options.anchorTo==="end"&&((s=this.scrollState)==null?void 0:s.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,h=m?this.getTotalSize():0,p=this.getScrollOffset()+this.scrollAdjustments,b=!this.itemSizeCache.has(c)?l<p:l+u<=p&&this.scrollDirection!=="backward",y=((a=this.scrollState)==null?void 0:a.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:c,start:l,size:o,end:l+o,lane:0},f,this):b);(this.pendingMin===null||n<this.pendingMin)&&(this.pendingMin=n),this.itemSizeCache.set(c,r),this.itemSizeCacheVersion++,m?this.applyScrollAdjustment(this.getTotalSize()-h):y&&this.applyScrollAdjustment(f),this.notify(!1)}},this.getVirtualItems=F7(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const s=[];for(let a=0,o=n.length;a<o;a++){const l=n[a],c=r[l];s.push(c)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const s=this._flatMeasurements,a=this.options.lanes===1&&s!=null,o=Gdt(0,r.length-1,a?l=>s[l*2]:l=>pPe(r[l]).start,n);return pPe(r[o])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,s=0)=>{if(!this.scrollElement)return 0;const a=this.getSize(),o=this.getScrollOffset();r==="auto"&&(r=n>=o+a?"end":"start"),r==="center"?n+=(s-a)/2:r==="end"&&(n-=a);const l=this.getMaxScrollOffset();return Math.max(Math.min(l,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const s=this.getSize(),a=this.getScrollOffset(),o=this.measurementsCache[n];if(!o)return;if(r==="auto")if(o.end>=a+s-this.options.scrollPaddingEnd)r="end";else if(o.start<=a+this.options.scrollPaddingStart)r="start";else return[a,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const l=r==="end"?o.end+this.options.scrollPaddingEnd:o.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(l,r,o.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:s="auto"}={})=>{this._iosDeferredAdjustment=0;const a=this.getOffsetForAlignment(n,r),o=this.now();this.scrollState={index:null,align:r,behavior:s,startedAt:o,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:s="auto"}={})=>{this._iosDeferredAdjustment=0,n=Math.max(0,Math.min(n,this.options.count-1));const a=this.getOffsetForIndex(n,r);if(!a)return;const[o,l]=a,c=this.now();this.scrollState={index:n,align:l,behavior:s,startedAt:c,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const s=this.getScrollOffset()+n,a=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:a,lastTargetOffset:s,stableFrames:0},this._scrollToOffset(s,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let s;if(r.length===0)s=this.options.paddingStart;else if(this.options.lanes===1){const a=r.length-1,o=this._flatMeasurements;o!=null?s=o[a*2]+o[a*2+1]:s=((n=r[a])==null?void 0:n.end)??0}else{const a=Array(this.options.lanes).fill(null);let o=r.length-1;for(;o>=0&&a.some(l=>l===null);){const l=r[o];a[l.lane]===null&&(a[l.lane]=l.end),o--}s=Math.max(...a.filter(l=>l!==null))}return Math.max(s-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const s of r)s&&this.itemSizeCache.has(s.key)&&n.push({index:s.index,key:s.key,start:s.start,size:s.size,end:s.end,lane:s.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:s})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:s,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(Wre()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollOffset<0&&(this.scrollOffset=0),this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,s=r?r[0]:this.scrollState.lastTargetOffset,a=1,o=s!==this.scrollState.lastTargetOffset;if(!o&&g7n(s,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=a){this.getScrollOffset()!==s&&this._scrollToOffset(s,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,o){const l=this.getSize()||600,c=Math.abs(s-this.getScrollOffset()),d=this.scrollState.behavior==="smooth"&&c>l;this.scrollState.lastTargetOffset=s,d||(this.scrollState.behavior="auto"),this._scrollToOffset(s,{adjustments:void 0,behavior:d?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Gdt=(e,t,n,r)=>{for(;e<=t;){const s=(e+t)/2|0,a=n(s);if(a<r)e=s+1;else if(a>r)t=s-1;else return s}return e>0?e-1:0};function P7n(e,t,n){let r=0;for(;r<=t;){const s=(r+t)/2|0,a=e[s*2];if(a<n)r=s+1;else if(a>n)t=s-1;else return s}return r>0?r-1:0}function T7n(e,t,n,r,s){const a=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:a};if(r===1&&s!==null){const d=P7n(s,a,n);let u=d;const f=n+t;for(;u<a&&s[u*2]+s[u*2+1]<f;)u++;return{startIndex:d,endIndex:u}}let l=Gdt(0,a,d=>e[d].start,n),c=l;if(r===1)for(;c<a&&e[c].end<n+t;)c++;else if(r>1){const d=Array(r).fill(0);for(;c<a&&d.some(f=>f<n+t);){const f=e[c];d[f.lane]=f.end,c++}const u=Array(r).fill(n+t);for(;l>=0&&u.some(f=>f>=n);){const f=e[l];u[f.lane]=f.start,l--}l=Math.max(0,l-l%r),c=Math.min(a,c+(r-1-c%r))}return{startIndex:l,endIndex:c}}const Hre=typeof document<"u"?A.useLayoutEffect:A.useEffect;function Ydt({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",directDomPrepaintRows:r=0,...s}){const a=A.useReducer(f=>f+1,0)[1],o=A.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});o.current.enabled=t,o.current.mode=n;const l=f=>{const m=o.current;if(!m.enabled||!m.container)return;const h=f.getTotalSize();if(h!==m.lastSize){m.lastSize=h;const p=f.options.horizontal?"width":"height";m.container.style[p]=`${h}px`}},c=f=>{const m=o.current;if(!m.enabled||!m.container)return;l(f);const h=!!f.options.horizontal,p=m.mode==="transform",x=h?"left":"top",b=f.options.scrollMargin,y=f.getVirtualItems();for(const w of y){const k=w.start-b,S=f.elementsCache.get(w.key);S&&m.lastPositions.get(S)!==k&&(m.lastPositions.set(S,k),p?S.style.transform=h?`translate3d(${k}px, 0, 0)`:`translate3d(0, ${k}px, 0)`:S.style[x]=`${k}px`)}},d={...s,onChange:(f,m)=>{var y,w;var h;const p=o.current;let x=!0,b=!1;if(p.enabled){c(f);const k=f.getVirtualItems(),S=(y=k[0])==null?void 0:y.index,j=(w=k[k.length-1])==null?void 0:w.index,C=p.prevRange;if(x=!C||C.isScrolling!==f.isScrolling||C.startIndex!==S||C.endIndex!==j,x){p.prevRange=k.length?{startIndex:S,endIndex:j,isScrolling:f.isScrolling}:null;const I=f.range,N=k.flatMap(B=>f.elementsCache.has(B.key)?[B.index]:[]),M=N[0],E=N[N.length-1],_=!I||M===void 0||E===void 0?0:f.scrollDirection==="backward"?I.startIndex-M:f.scrollDirection==="forward"?E-I.endIndex:Math.min(I.startIndex-M,E-I.endIndex),z=I?f.scrollDirection==="backward"?I.startIndex:f.scrollDirection==="forward"?f.options.count-1-I.endIndex:0:0,T=Math.min(r,Math.max(0,z)),$=!!I&&M!==void 0&&E!==void 0&&M<=I.startIndex&&E>=I.endIndex;b=r>0&&f.scrollDirection!==null&&(!$||_<T)}}x&&((e||b)&&m?ja.flushSync(a):a()),(h=s.onChange)==null||h.call(s,f,m)}},[u]=A.useState(()=>{const f=new I7n(d);return Object.assign(f,{containerRef:m=>{const h=o.current;if(h.container=m,h.lastSize=null,m&&h.enabled){const p=f.getTotalSize();h.lastSize=p;const x=f.options.horizontal?"width":"height";m.style[x]=`${p}px`}}})});return u.setOptions(d),Hre(()=>u._didMount(),[]),Hre(()=>(l(u),u._willUpdate())),Hre(()=>{c(u)}),u}function Jdt(e){return Ydt({observeElementRect:v7n,observeElementOffset:O7n,scrollToFn:N7n,...e})}function _7n(e){return Ydt({getScrollElement:()=>typeof document<"u"?window:null,observeElementRect:w7n,observeElementOffset:S7n,scrollToFn:C7n,initialOffset:()=>typeof document<"u"?window.scrollY:0,...e})}const qF=4,M7n=22;function xPe(e){if(!e||typeof window>"u")return e;let t=e;for(;t&&t!==document.body&&t!==document.documentElement;){const r=window.getComputedStyle(t),s=/(auto|scroll|overlay)/.test(`${r.overflow} ${r.overflowY}`),a=t.scrollHeight>t.clientHeight+1,o=t.clientHeight<=window.innerHeight+1;if(s&&(a||o))return t;t=t.parentElement}const n=document.scrollingElement;return n instanceof HTMLElement?n:e}function d2e({children:e,estimateSize:t,getItemKey:n,items:r,itemGap:s=20,leadingOverscan:a=0,overscan:o=3,preventScrollBlanking:l=!1,onTargetMounted:c,scrollElementRef:d,targetKey:u,testId:f}){const m=A.useRef(null),h=A.useRef(null),p=A.useRef(null),[x,b]=A.useState(0),[y,w]=A.useState(0),k=A.useMemo(()=>r.map((F,W)=>n(F,W)),[n,r]),S=A.useCallback(F=>k[F]??F,[k]),j=typeof window<"u"&&new URLSearchParams(window.location.search).get("perfBaseline")==="1",C=A.useCallback(F=>{var ee;const W=(ee=p.current)==null?void 0:ee.scrollDirection,Y=Math.max(8,Math.ceil(o/2)),G=Math.max(a,W==="backward"?o:Y),V=W==="backward"?Y:o,L=Math.max(0,F.startIndex-G),R=Math.min(F.count-1,F.endIndex+V),D=Math.floor(L/qF)*qF,X=Math.min(F.count-1,Math.ceil((R+1)/qF)*qF-1);return Array.from({length:X-D+1},(se,ne)=>D+ne)},[a,o]);A.useLayoutEffect(()=>{let F=null;const W=()=>{F!==null&&cancelAnimationFrame(F),F=requestAnimationFrame(()=>{F=null,b(Y=>Y+1)})};return b(Y=>Y+1),window.addEventListener("resize",W),()=>{F!==null&&cancelAnimationFrame(F),window.removeEventListener("resize",W)}},[]);const I=xPe(d.current),N=typeof document<"u"&&I===document.scrollingElement,M=A.useCallback(()=>xPe(d.current),[d,x]),E={count:r.length,estimateSize:t,getItemKey:S,...l?{overscan:0,rangeExtractor:C}:{overscan:o},scrollMargin:y,directDomUpdates:l&&!j,directDomUpdatesMode:"transform",directDomPrepaintRows:l&&!j?M7n:0,useFlushSync:!1},_=Jdt({...E,enabled:!j&&!N,getScrollElement:M}),z=_7n({...E,enabled:!j&&N}),T=N?z:_;p.current=T;const $=A.useCallback(F=>{m.current=F,l&&!j&&T.containerRef(F)},[j,l,T]),B=T.getVirtualItems();return A.useLayoutEffect(()=>{const F=m.current,W=I;if(!F||!W)return;const Y=()=>{const X=F.getBoundingClientRect(),ee=W===document.scrollingElement?Math.max(0,X.top+W.scrollTop):Math.max(0,X.top-W.getBoundingClientRect().top+W.scrollTop);w(se=>Math.abs(se-ee)<1?se:ee)};Y();const G=[];let V=F.parentElement;for(;V&&V!==W;)G.push(V),V=V.parentElement;const L=typeof ResizeObserver>"u"?null:new ResizeObserver(()=>Y());L==null||L.observe(F);for(const X of G)L==null||L.observe(X);let R=null;const D=typeof MutationObserver>"u"?null:new MutationObserver(()=>{var X;if(!((X=p.current)!=null&&X.isScrolling)){Y();return}R!==null&&clearTimeout(R),R=setTimeout(()=>{R=null,Y()},180)});for(const X of G)D==null||D.observe(X,{attributeFilter:["class","style"],attributes:!0});return()=>{R!==null&&clearTimeout(R),D==null||D.disconnect(),L==null||L.disconnect()}},[l,I]),A.useLayoutEffect(()=>{if(!u)return;const F=k.indexOf(u);F!==-1&&T.scrollToIndex(F,{align:"center"})},[k,u,T]),A.useLayoutEffect(()=>{if(!u||!c||h.current===u||!B.some(W=>k[W.index]===u))return;h.current=u;const F=requestAnimationFrame(()=>c(u));return()=>cancelAnimationFrame(F)},[k,c,u,B]),A.useLayoutEffect(()=>{u!==h.current&&(h.current=null)},[u]),j?i.jsx("div",{"data-testid":`${f}-baseline`,className:"flex w-full flex-col gap-5",children:r.map((F,W)=>i.jsx("div",{"data-virtualized-activity-key":k[W],children:e(F,W)},k[W]))}):i.jsx("div",{ref:$,"data-testid":f,"data-virtualized-scroll-root":N?"window":"element",style:{...l?{}:{height:`${T.getTotalSize()}px`},position:"relative",width:"100%"},children:B.map(F=>{const W=r[F.index];return W?i.jsx("div",{ref:T.measureElement,"data-index":F.index,"data-virtualized-activity-key":k[F.index],style:{left:0,paddingBottom:`${s}px`,position:"absolute",top:0,...l?{}:{transform:`translateY(${F.start-y}px)`},width:"100%"},children:e(W,F.index)},F.key):null})})}function E7n({announcement:e,children:t,mountAll:n,onTargetMounted:r,reserveHashScrollEndSpace:s,regionLabel:a,scrollElementRef:o,targetKey:l,timeline:c,timelineRegionId:d}){const u=!n&&!!o&&c.length>60;A.useLayoutEffect(()=>{u||!l||!r||c.some(h=>ZO(h)===l)&&r(l)},[r,l,c,u]);const f=h=>i.jsx("div",{"data-issue-timeline-key":ZO(h),tabIndex:h.kind==="disclosure"?void 0:-1,children:t(h)}),m=u&&o?i.jsx(d2e,{items:c,getItemKey:ZO,estimateSize:h=>{const p=c[h];return(p==null?void 0:p.kind)==="disclosure"?64:(p==null?void 0:p.kind)==="run"?p.run.status==="queued"||p.run.status==="running"?320:52:(p==null?void 0:p.kind)==="activity"?48:168},overscan:5,preventScrollBlanking:!0,scrollElementRef:o,targetKey:l,onTargetMounted:r,testId:"comment-thread-virtual-timeline",children:h=>f(h)}):c.map(h=>i.jsx("div",{children:f(h)},ZO(h)));return i.jsxs("div",{id:d,className:"space-y-3",role:a?"region":void 0,"aria-label":a,children:[m,i.jsx("span",{className:"sr-only","aria-live":"polite","aria-atomic":"true",children:e}),s?i.jsx("div",{"aria-hidden":"true",className:"h-[var(--comment-hash-scroll-end-space)]",style:{"--comment-hash-scroll-end-space":"min(6rem, 12vh)"},"data-testid":"comment-hash-scroll-end-space"}):null]})}function D7n(e){const t=e.replace(/\s*\([^)]*\)\s*/g," ").trim()||e.trim(),n=t.split(/\s+/);return n.length>=2?(n[0][0]+n[n.length-1][0]).toUpperCase():t.slice(0,2).toUpperCase()}const R7n={xs:"text-sm",sm:"text-xs",default:"text-sm",lg:"text-sm"};function Bd({name:e,avatarUrl:t,initials:n,size:r="default",className:s}){const a=n??D7n(e);return i.jsxs("span",{className:q("inline-flex gap-1.5",r==="xs"?"items-baseline gap-1":"items-center",r==="lg"&&"gap-2",s),children:[i.jsxs(uu,{size:r,className:r==="xs"?"relative -top-px":void 0,"data-avatar-url":t??void 0,children:[t&&i.jsx(gR,{src:t,alt:e}),i.jsx(fu,{children:a})]}),i.jsx("span",{className:q("truncate",R7n[r]),children:e})]})}const eut=12,L7n=4,bPe=24,z7n=640,$7n=900,F7n=144,B7n=720,Q7n=112,U7n=20,q7n=240,V7n=32,W7n=7,yPe={activity:0,comment:1,run:2};function tut(e,t,n){return Math.min(n,Math.max(t,e))}function XQ(e,t){return e.createdAtMs!==t.createdAtMs?e.createdAtMs-t.createdAtMs:e.kind!==t.kind?yPe[e.kind]-yPe[t.kind]:e.key.localeCompare(t.key)}function wE(e){return{key:e.key,kind:e.kind,createdAtMs:e.createdAtMs}}function nut(e){return tut(e*.8,z7n,$7n)}function H7n(e,t){const n=Math.max(1,t-V7n),r=Math.max(1,Math.floor(n/W7n)),s=e.split(/\r?\n/u);return Math.max(1,s.reduce((a,o)=>a+Math.max(1,Math.ceil(o.length/r)),0))}function K7n(e){var r,s;const t=((r=e.match(/!\[[^\]]*\]\([^\n)]+\)/gu))==null?void 0:r.length)??0,n=((s=e.match(/<img\b/giu))==null?void 0:s.length)??0;return t+n}function rut(e,t){if(e.kind==="activity")return 40;if(e.kind==="run")return e.runStatus==="queued"||e.runStatus==="running"?320:52;const n=e.commentBody??"",r=H7n(n,t);return tut(Q7n+r*U7n+K7n(n)*q7n,F7n,B7n)}function Z7n(e,t){return e.reduce((n,r,s)=>n+rut(r,t)+(s>0?eut:0),0)}function EW(e,t,n,r=!1){let s=0,a=0;const o=r?[...e].reverse():e;for(const l of o){const c=rut(l,n)+(a>0?eut:0);if(a>0&&s+c>t)break;s+=c,a+=1}return a}function sut(e,t,n){return e.length>=L7n&&Z7n(e,n)>=t*.5}function X7n(e,t,n){const r=[...e].sort(XQ);if(r.length===0||t<=0||n<=0)return{fullyExpanded:!0,prefixBoundary:null,suffixBoundary:null};const s=nut(t),a=EW(r,s*.4,n),o=r.slice(a),l=EW(o,s*.8,n,!0),c=Math.max(a,r.length-l),d=r.slice(a,c);return sut(d,s,n)?{fullyExpanded:!1,prefixBoundary:wE(r[Math.max(0,a-1)]),suffixBoundary:wE(r[c])}:{fullyExpanded:!0,prefixBoundary:null,suffixBoundary:null}}function DC(e,t){const n=[...e].sort(XQ);if(t.fullyExpanded||!t.prefixBoundary||!t.suffixBoundary)return{hidden:[],visibleHead:n,visibleTail:[]};const r=[],s=[],a=[];for(const o of n)XQ(o,t.prefixBoundary)<=0?r.push(o):XQ(o,t.suffixBoundary)>=0?a.push(o):s.push(o);return{hidden:s,visibleHead:r,visibleTail:a}}function G7n(e,t,n,r){const s=DC(e,t);if(s.hidden.length===0)return{fullyExpanded:!0,prefixBoundary:null,suffixBoundary:null};const a=nut(n),o=a*1.2,l=Math.min(bPe,EW(s.hidden,o,r)),c=Math.min(bPe,EW(s.hidden,o,r,!0));if(l+c>=s.hidden.length)return{fullyExpanded:!0,prefixBoundary:null,suffixBoundary:null};const d=s.hidden[Math.max(0,l-1)],u=s.hidden[Math.max(l,s.hidden.length-c)],f={...t,prefixBoundary:wE(d),suffixBoundary:wE(u)},m=DC(e,f).hidden;return sut(m,a,r)?f:{fullyExpanded:!0,prefixBoundary:null,suffixBoundary:null}}function Y7n(e,t,n){if(t.fullyExpanded)return t;const s=DC(e,t).hidden.find(o=>o.key===n);if(!s)return t;const a={...t,prefixBoundary:wE(s)};return DC(e,a).hidden.length===0?{fullyExpanded:!0,prefixBoundary:null,suffixBoundary:null}:a}const vPe={fullyExpanded:!0,prefixBoundary:null,suffixBoundary:null};function Kre(e){let t=e.parentElement;for(;t;){const n=window.getComputedStyle(t);if(/(auto|scroll|overlay)/.test(`${n.overflow} ${n.overflowY}`))return t;t=t.parentElement}return null}function J7n({hiddenCount:e,locale:t,onRevealMore:n,timelineRegionId:r}){const s=t==="zh-CN"?`已隐藏 ${e} 条动态`:`${e} hidden ${e===1?"item":"items"}`;return i.jsxs("div",{className:"flex min-h-16 items-center gap-3 py-1","data-testid":"issue-timeline-disclosure",children:[i.jsx("span",{"aria-hidden":"true",className:"h-px min-w-4 flex-1 border-t border-dashed border-border"}),i.jsxs("div",{className:"flex shrink-0 flex-col items-center gap-0.5 text-center",children:[i.jsx("span",{className:"text-xs tabular-nums text-muted-foreground",children:s}),i.jsxs(oe,{type:"button",variant:"outline",size:"sm",className:"group h-8 cursor-pointer !bg-[color:var(--surface-elevated)] px-3 text-xs !shadow-[var(--shadow-sm)] hover:border-[color:var(--border-strong)] hover:!bg-[color:var(--surface-active)]","aria-controls":r,"aria-expanded":"false",onClick:a=>{var o;return n==null?void 0:n(a.detail===0,((o=a.currentTarget.closest("[data-testid='issue-timeline-disclosure']"))==null?void 0:o.getBoundingClientRect().top)??a.currentTarget.getBoundingClientRect().top)},children:[t==="zh-CN"?"加载更多":"Load more",i.jsx(rs,{"aria-hidden":"true",className:"size-3.5 text-muted-foreground transition-transform duration-150 group-active:translate-y-0.5"})]})]}),i.jsx("span",{"aria-hidden":"true",className:"h-px min-w-4 flex-1 border-t border-dashed border-border"})]})}function eOn({config:e,items:t,locale:n}){const s=`issue-activity-timeline-${A.useId().replace(/:/gu,"")}`,[a,o]=A.useState({height:0,width:0}),[l,c]=A.useState(null),[d,u]=A.useState(""),f=A.useRef(null);A.useLayoutEffect(()=>{if(!e)return;const y=document.getElementById(s);if(!y)return;let w=null;const k=()=>{w!==null&&cancelAnimationFrame(w),w=requestAnimationFrame(()=>{const C=Kre(y),I={height:(C==null?void 0:C.clientHeight)??window.innerHeight,width:y.clientWidth};o(N=>N.height===I.height&&N.width===I.width?N:I),w=null})},S=typeof ResizeObserver>"u"?null:new ResizeObserver(k);S==null||S.observe(y);const j=Kre(y);return j&&(S==null||S.observe(j)),window.addEventListener("resize",k,{passive:!0}),k(),()=>{w!==null&&cancelAnimationFrame(w),S==null||S.disconnect(),window.removeEventListener("resize",k)}},[e,s]),A.useLayoutEffect(()=>{if(e){if(e.failOpen||e.forceExpanded){c(y=>(y==null?void 0:y.key)===e.key&&y.state.fullyExpanded?y:{key:e.key,state:vPe});return}!e.ready||a.height<=0||a.width<=0||c(y=>(y==null?void 0:y.key)===e.key?y:{key:e.key,state:X7n(t,a.height,a.width)})}},[e,a,t]);const m=A.useMemo(()=>!e||e.failOpen||e.forceExpanded||(l==null?void 0:l.key)!==e.key?vPe:l.state,[e,l]),h=A.useMemo(()=>DC(t,m),[m,t]),p=A.useCallback((y,w)=>{if(!e||h.hidden.length===0)return;f.current={dividerTop:w,focus:y,key:h.hidden[0].key};const k=G7n(t,m,a.height,a.width),S=DC(t,k).hidden.length;c({key:e.key,state:k}),u(S===0?n==="zh-CN"?"已显示全部动态":"All activity is shown":n==="zh-CN"?`仍有 ${S} 条动态被隐藏`:`${S} hidden ${S===1?"item remains":"items remain"}`)},[e,a,m,t,n,h.hidden]),x=A.useCallback(y=>{if(!e||m.fullyExpanded)return;const w=Y7n(t,m,y);w!==m&&c({key:e.key,state:w})},[e,m,t]);A.useLayoutEffect(()=>{const y=f.current;if(!y)return;const w=document.getElementById(s),k=Array.from((w==null?void 0:w.querySelectorAll("[data-issue-timeline-key]"))??[]).find(C=>C.dataset.issueTimelineKey===y.key);if(!k)return;const S=Kre(k),j=k.getBoundingClientRect().top-y.dividerTop;S?S.scrollTop+=j:window.scrollBy({top:j,behavior:"auto"}),y.focus&&k.focus({preventScroll:!0}),f.current=null},[h,s]);const b=e==null?void 0:e.onVisibilityChange;return A.useEffect(()=>{b==null||b()},[b,h.hidden.length]),{announcement:d,mountAll:e==null?void 0:e.mountAll,revealMore:p,revealTarget:x,selection:h,timelineRegionId:s}}function Oi({status:e}){return i.jsx("span",{className:q("inline-flex shrink-0 items-center rounded-[calc(var(--radius-sm)-1px)] border px-2.5 py-1 text-xs font-medium whitespace-nowrap shadow-[var(--shadow-sm)]",hR[e]??pR),children:e.replace("_"," ")})}function iut(e){const t=e==null?void 0:e.trim().replace(/\\/g,"/").replace(/\/+/g,"/");return(t==null?void 0:t.replace(/\/$/g,""))||null}function aut(e){var n;const t=e==null?void 0:e.trim().toLowerCase().replace(/^\$/,"");return t&&((n=t.replace(/^bundled:/,"").split("/").filter(Boolean).at(-1))==null?void 0:n.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""))||null}function tOn(e){return[e.sourcePath,e.workspaceEditPath].flatMap(t=>{const n=iut(t);if(!n)return[];const r=n.toLowerCase();return r==="skill.md"||r.endsWith("/skill.md")?[n]:[`${n}/SKILL.md`]})}function nOn(e,t){return[e.slug,e.key,e.name].map(aut).some(n=>n===t)}function out(e,t){const n=iut(e.path),r=t??[];if(n){const a=r.filter(o=>tOn(o).some(l=>l===n));if(a.length===1){const o=a[0];return{kind:"organization_skill_file",skillId:o.id,filePath:"SKILL.md",label:o.slug||o.name}}}const s=aut(e.name);if(s){const a=r.filter(o=>nOn(o,s));if(a.length===1){const o=a[0];return{kind:"organization_skill_file",skillId:o.id,filePath:"SKILL.md",label:o.slug||o.name}}}return n?{kind:"local_file",filePath:n,label:e.name||n.split("/").at(-2)||"Skill"}:null}function rOn(e,t,n){const r=LA(e,t??"");if(!r)return null;try{const a=new URL(r.href);if(a.hostname==="org"){const o=decodeURIComponent(a.pathname.replace(/^\/+/u,"")).trim();if(o){const l=(n??[]).find(c=>c.id===o);return{kind:"organization_skill_file",skillId:o,filePath:"SKILL.md",label:(l==null?void 0:l.slug)||(l==null?void 0:l.name)||r.label}}}if(a.hostname==="agent")return null}catch{}const s=fge(r.href);return out({name:s?"":r.label,path:s},n)}function sOn({label:e,className:t,constrain:n=!0}){return i.jsx("span",{"data-slot":"agent-title-badge",className:q("inline-flex min-w-0 shrink items-center rounded-sm border border-border/70 bg-muted/50 px-1.5 py-0.5 text-[10px] font-medium leading-3 text-muted-foreground",n?"max-w-[9rem]":"max-w-full whitespace-normal",t),title:e,children:i.jsx("span",{className:q("min-w-0",n?"truncate":"whitespace-normal break-words text-left"),children:e})})}function Ro({kind:e,label:t,agentAvatarStyle:n="framed",badgeLabel:r,agentIcon:s,agentRole:a,avatarUrl:o,className:l,layout:c="inline",muted:d=!1}){const u=c==="stacked";return i.jsxs("span",{"data-slot":"assignee-label","data-kind":e,"data-layout":c,"data-agent-avatar-style":e==="agent"?n:void 0,className:q("inline-flex min-w-0 max-w-full items-center gap-1.5",u&&"w-full",l),children:[e==="agent"?n==="bare"?i.jsx(lc,{icon:s,role:a,className:"h-6 w-6 shrink-0 text-muted-foreground"}):i.jsx("span",{"data-slot":"assignee-agent-avatar-frame",className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-border/70 bg-muted/40 text-muted-foreground",children:i.jsx(lc,{icon:s,role:a,className:"h-3.5 w-3.5"})}):i.jsxs(uu,{size:"sm","data-avatar-url":e==="user"&&o?o:void 0,children:[e==="user"&&o?i.jsx(gR,{src:o,alt:t}):null,i.jsx(fu,{className:q(e==="unassigned"&&"border border-dashed border-muted-foreground/35 bg-muted/30"),children:e==="user"?i.jsx(zj,{className:"h-3 w-3"}):i.jsx(qAe,{className:"h-3 w-3"})})]}),i.jsxs("span",{className:q("inline-flex min-w-0 max-w-full flex-1 items-center gap-1.5 overflow-hidden",u&&"w-full flex-col items-start gap-1"),children:[i.jsx("span",{"data-slot":"assignee-label-text",className:q("block min-w-0 max-w-full truncate text-xs",d&&"text-muted-foreground"),title:t,children:t}),r?i.jsx(sOn,{label:r,constrain:!u}):null]})]})}function yh({agent:e,agentAvatarStyle:t="framed"}){const n=_q(e);return i.jsxs("span",{"data-slot":"agent-menu-label",className:"flex min-w-0 flex-1 items-center gap-2",children:[t==="bare"?i.jsx(lc,{icon:e.icon,role:e.role,className:"h-6 w-6 shrink-0 text-muted-foreground"}):i.jsx("span",{"data-slot":"agent-menu-avatar-frame",className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-border/70 bg-muted/40 text-muted-foreground",children:i.jsx(lc,{icon:e.icon,role:e.role,className:"h-3.5 w-3.5"})}),i.jsxs("span",{className:"flex min-w-0 flex-1 flex-col text-left",children:[i.jsx("span",{className:"truncate text-xs font-medium leading-4 text-foreground",children:e.name}),n?i.jsx("span",{"data-slot":"agent-menu-supporting-label",className:"truncate text-[11px] leading-3 text-muted-foreground",children:n}):null]})]})}function ufe({label:e="Assign to me",avatarUrl:t}){return i.jsxs("span",{"data-slot":"assignee-self-action-label",className:"flex min-w-0 flex-1 items-center gap-2",children:[i.jsxs(uu,{size:"sm","data-avatar-url":t??void 0,children:[t?i.jsx(gR,{src:t,alt:e}):null,i.jsx(fu,{className:"border border-border/70 bg-muted/40",children:i.jsx(zj,{className:"h-3.5 w-3.5"})})]}),i.jsx("span",{className:"truncate text-xs font-medium leading-4 text-foreground",children:e})]})}function lut({message:e,currentUserId:t=null,currentUserAvatarUrl:n=null}){const r=A.useMemo(()=>tTt(e.structuredPayload).filter(s=>s.display==="card"),[e.structuredPayload]);return r.length===0?null:i.jsx("div",{className:"mt-3 flex max-w-[72ch] flex-col gap-2","data-testid":"chat-rich-references",children:r.map((s,a)=>i.jsx(iOn,{reference:s,currentUserId:t,currentUserAvatarUrl:n},`${s.type}:${s.issueId??s.identifier??"issue"}:${s.type==="issue_comment"?s.commentId:a}`))})}function iOn({reference:e,currentUserId:t,currentUserAvatarUrl:n}){return e.type==="issue"?i.jsx(aOn,{reference:e,currentUserId:t,currentUserAvatarUrl:n}):i.jsx(oOn,{reference:e,currentUserId:t,currentUserAvatarUrl:n})}function aOn({reference:e,currentUserId:t,currentUserAvatarUrl:n}){const r=cut(e),s=Ve({queryKey:U.issues.detail(r),queryFn:()=>fr.get(r),retry:!1,enabled:!!r});return s.isLoading?i.jsx(Bk,{icon:"issue",title:"Loading issue",detail:r,tone:"loading"}):s.isError?i.jsx(ffe,{error:s.error,kind:"issue"}):s.data?i.jsx(lOn,{issue:s.data,currentUserId:t,currentUserAvatarUrl:n}):i.jsx(Bk,{icon:"issue",title:"Issue unavailable",detail:"The issue could not be loaded.",tone:"muted"})}function oOn({reference:e,currentUserId:t,currentUserAvatarUrl:n}){const r=cut(e),s=Ve({queryKey:U.issues.detail(r),queryFn:()=>fr.get(r),retry:!1,enabled:!!r}),a=Ve({queryKey:U.issues.comment(r,e.commentId),queryFn:()=>fr.getComment(r,e.commentId),retry:!1,enabled:!!r});return s.isLoading||a.isLoading?i.jsx(Bk,{icon:"comment",title:"Loading comment",detail:r,tone:"loading"}):s.isError?i.jsx(ffe,{error:s.error,kind:"issue"}):a.isError?i.jsx(ffe,{error:a.error,kind:"comment"}):!s.data||!a.data?i.jsx(Bk,{icon:"comment",title:"Comment unavailable",detail:"The comment could not be loaded.",tone:"muted"}):i.jsx(cOn,{issue:s.data,comment:a.data,currentUserId:t,currentUserAvatarUrl:n})}function lOn({issue:e,currentUserId:t,currentUserAvatarUrl:n}){const r=e.identifier??e.id.slice(0,8),s=e.assigneeAgentId?e.assigneeAgentId.slice(0,8):e.assigneeUserId?NA(e.assigneeUserId,null)??e.assigneeUserId.slice(0,8):"Unassigned";return i.jsx(gn,{to:`/issues/${e.identifier??e.id}`,className:"group block rounded-lg border border-border bg-card px-3 py-2.5 text-left shadow-[var(--shadow-sm)] transition-colors hover:border-[color:var(--accent-strong)]/40 hover:bg-[color:var(--surface-active)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":`Open issue ${r}`,children:i.jsxs("div",{className:"flex min-w-0 items-start gap-3",children:[i.jsx("div",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-border bg-background text-muted-foreground",children:i.jsx(Aa,{className:"h-4 w-4","aria-hidden":!0})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[i.jsx("span",{className:"font-mono text-[11px] font-medium text-foreground",children:r}),i.jsx(Oi,{status:e.status}),i.jsx("span",{children:Hd(e.priority)})]}),i.jsx("div",{className:"mt-1 truncate text-sm font-medium leading-5 text-foreground",children:e.title}),i.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground",children:[e.assigneeUserId?i.jsx(Bd,{name:s,avatarUrl:e.assigneeUserId===t?n:null,size:"xs"}):i.jsx("span",{children:s}),i.jsxs("span",{children:["Updated ",Ca(e.updatedAt)]})]})]})]})})}function cOn({issue:e,comment:t,currentUserId:n,currentUserAvatarUrl:r}){const s=e.identifier??e.id.slice(0,8),a=t.authorAgentId?t.authorAgentId.slice(0,8):t.authorUserId?NA(t.authorUserId,null)??t.authorUserId.slice(0,8):"System",o=dOn(t.body);return i.jsx(gn,{to:`/issues/${e.identifier??e.id}#comment-${t.id}`,className:"group block rounded-lg border border-border bg-card px-3 py-2.5 text-left shadow-[var(--shadow-sm)] transition-colors hover:border-[color:var(--accent-strong)]/40 hover:bg-[color:var(--surface-active)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":`Open comment on issue ${s}`,children:i.jsxs("div",{className:"flex min-w-0 items-start gap-3",children:[i.jsx("div",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-border bg-background text-muted-foreground",children:i.jsx(PD,{className:"h-4 w-4","aria-hidden":!0})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[i.jsx("span",{className:"font-mono text-[11px] font-medium text-foreground",children:s}),t.authorUserId?i.jsx(Bd,{name:a,avatarUrl:t.authorUserId===n?r:null,size:"xs"}):i.jsx("span",{children:a}),i.jsx("span",{children:Ca(t.createdAt)})]}),i.jsx("div",{className:"mt-1 truncate text-sm font-medium leading-5 text-foreground",children:e.title}),i.jsx("p",{className:"mt-1 max-h-[3.75rem] overflow-hidden text-sm leading-5 text-muted-foreground",children:o})]})]})})}function ffe({error:e,kind:t}){if(e instanceof $o){if(e.status===403)return i.jsx(Bk,{icon:t,title:"Permission denied",detail:"You do not have access to this reference.",tone:"warning"});if(e.status===404)return i.jsx(Bk,{icon:t,title:t==="issue"?"Issue not found":"Comment not found",detail:"The reference may have been deleted or moved.",tone:"muted"})}return i.jsx(Bk,{icon:t,title:"Reference unavailable",detail:"The reference could not be loaded.",tone:"warning"})}function Bk({icon:e,title:t,detail:n,tone:r}){const s=e==="issue"?Aa:Co;return i.jsx("div",{className:q("rounded-lg border border-dashed px-3 py-2.5 text-sm",r==="warning"?"border-amber-500/35 bg-amber-500/5 text-amber-800 dark:text-amber-200":"border-border bg-card text-muted-foreground"),children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("div",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-current/15 bg-background/70",children:i.jsx(s,{className:"h-4 w-4","aria-hidden":!0})}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("div",{className:"font-medium text-foreground",children:t}),i.jsx("div",{className:"mt-0.5 break-words text-xs",children:n})]})]})})}function cut(e){return e.issueId??e.identifier??""}function dOn(e){return e.replace(/!\[[^\]]*]\([^)]*\)/g,"").replace(/\[([^\]]+)]\([^)]*\)/g,"$1").replace(/[`*_>#~-]+/g,"").replace(/\s+/g," ").trim()||"No comment body."}const vh=A.forwardRef(function({value:t,options:n,placeholder:r,noneLabel:s,searchPlaceholder:a,emptyMessage:o,onChange:l,onConfirm:c,className:d,ariaLabel:u,renderTriggerValue:f,renderOption:m,renderOptionAccessory:h,keepOpenOnOptionChange:p=!1,disablePortal:x,side:b="bottom",sideOffset:y,contentClassName:w,variant:k="inline"},S){const[j,C]=A.useState(!1),[I,N]=A.useState(""),[M,E]=A.useState(0),[_,z]=A.useState(!1),T=A.useRef(null),$=A.useRef(null),B=A.useRef(null),F=A.useRef(!1),W=A.useRef(!1),Y=A.useRef(!1),G=A.useRef(!1);A.useImperativeHandle(S,()=>$.current);const V=A.useMemo(()=>[{id:"",label:s,searchText:s},...n],[s,n]),L=A.useMemo(()=>{const ee=I.trim().toLowerCase();return ee?V.filter(se=>`${se.label} ${se.searchText??""}`.toLowerCase().includes(ee)):V},[V,I]),R=n.find(ee=>ee.id===t)??null,D=typeof window<"u"&&window.innerWidth<640?{top:16,right:16,bottom:88,left:16}:16;A.useEffect(()=>{if(!j)return;const ee=L.findIndex(se=>se.id===t);E(ee>=0?ee:0)},[L,j,t]),A.useEffect(()=>{if(!j||!_)return;const ee=requestAnimationFrame(()=>{var se;(se=B.current)==null||se.focus(),z(!1)});return()=>cancelAnimationFrame(ee)},[j,_]);const X=(ee,se,ne=!1)=>{const le=L[ee]??L[0];if(le&&l(le.id),ne){z(!0),N(""),C(!0);return}F.current=se,C(!1),N(""),se&&c&&requestAnimationFrame(()=>{c()})};return i.jsxs(bi,{open:j,onOpenChange:ee=>{C(ee),ee||N("")},children:[i.jsx(Hi,{asChild:!0,children:i.jsxs("button",{ref:$,type:"button","aria-label":u,className:q("inline-flex min-w-0 items-center gap-1 border border-border text-sm font-medium text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",k==="field"?"h-10 w-full justify-between rounded-md bg-background px-3 hover:bg-accent/30":"rounded-md bg-muted/40 px-2 py-1 hover:bg-accent/50",d),onPointerDown:()=>{W.current=!0},onFocus:()=>{Y.current?Y.current=!1:W.current||C(!0),W.current=!1},children:[i.jsx("span",{className:q("flex min-w-0 items-center gap-2",k==="field"&&"flex-1 overflow-hidden"),children:f?f(R):(R==null?void 0:R.label)??i.jsx("span",{className:"text-muted-foreground",children:r})}),k==="field"?i.jsx(rs,{className:"ml-2 h-4 w-4 shrink-0 text-muted-foreground"}):null]})}),i.jsxs(yi,{align:"start",side:b,sideOffset:y,collisionPadding:D,className:q("motion-inline-selector-pop z-[70] flex max-h-[min(18rem,var(--radix-popover-content-available-height))] flex-col overflow-hidden p-1",k==="field"?"w-[var(--radix-popover-trigger-width)] min-w-64 max-w-[calc(100vw-2rem)]":"w-[min(20rem,calc(100vw-2rem))]",w),disablePortal:x,onOpenAutoFocus:ee=>{var ne;ee.preventDefault(),window.matchMedia("(pointer: coarse)").matches||(ne=T.current)==null||ne.focus()},onCloseAutoFocus:ee=>{if(G.current){ee.preventDefault(),G.current=!1,requestAnimationFrame(()=>{var se;return(se=$.current)==null?void 0:se.focus()});return}F.current&&(ee.preventDefault(),F.current=!1)},onInteractOutside:ee=>{const se=ee.target;se instanceof Element&&se.closest("[data-issue-runtime-portal]")&&ee.preventDefault()},onEscapeKeyDown:ee=>{ee.preventDefault(),ee.stopPropagation(),C(!1),Y.current=!0,G.current=!0},children:[i.jsx("input",{ref:T,className:"w-full border-b border-border bg-transparent px-2 py-1.5 text-sm outline-none placeholder:text-muted-foreground/60",placeholder:a,value:I,onChange:ee=>{N(ee.target.value)},onKeyDown:ee=>{if(ee.key==="ArrowDown"){ee.preventDefault(),E(se=>L.length===0?0:(se+1)%L.length);return}if(ee.key==="ArrowUp"){ee.preventDefault(),E(se=>L.length===0?0:se<=0?L.length-1:se-1);return}if(ee.key==="Enter"){ee.preventDefault(),X(M,!1,p);return}if(ee.key==="Tab"&&!ee.shiftKey){ee.preventDefault(),X(M,!0);return}ee.key==="Escape"&&(ee.preventDefault(),ee.stopPropagation(),C(!1),Y.current=!0,G.current=!0)}}),i.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto overscroll-contain py-1 touch-pan-y",children:L.length===0?i.jsx("p",{className:"px-2 py-2 text-xs text-muted-foreground",children:o}):L.map((ee,se)=>{const ne=ee.id===t,le=se===M,ie=m?m(ee,ne):i.jsx("span",{className:"truncate",children:ee.label}),re=h==null?void 0:h(ee,ne);return re?i.jsxs("div",{"data-inline-entity-option":!0,className:q("flex w-full items-center gap-1 rounded text-left text-sm transition-colors",le&&"bg-accent"),onMouseEnter:()=>E(se),children:[i.jsxs("button",{type:"button",ref:ne?B:void 0,"aria-pressed":ne,className:"flex min-w-0 flex-1 items-center gap-2 rounded px-2 py-1.5 text-left transition-colors touch-manipulation hover:bg-accent/80",onClick:()=>X(se,!1,p),children:[ie,i.jsx(zi,{className:q("ml-auto h-3.5 w-3.5 shrink-0 text-muted-foreground",ne?"opacity-100":"opacity-0")})]}),i.jsx("div",{className:"min-w-0 max-w-[45%] shrink-0 overflow-hidden",children:re})]},ee.id||"__none__"):i.jsxs("button",{type:"button","data-inline-entity-option":!0,className:q("flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-sm transition-colors touch-manipulation hover:bg-accent/80",le&&"bg-accent"),onMouseEnter:()=>E(se),onClick:()=>X(se,!p,p),children:[ie,i.jsx(zi,{className:q("ml-auto h-3.5 w-3.5 text-muted-foreground",ne?"opacity-100":"opacity-0")})]},ee.id||"__none__")})})]})]})});function zG({text:e,className:t,...n}){return i.jsxs("span",{role:"status","aria-label":`${e}...`,className:q("rudder-text-dots inline-flex items-baseline whitespace-nowrap align-baseline",t),...n,children:[i.jsx("span",{children:e}),i.jsx("span",{className:"rudder-text-dots__dots","aria-hidden":"true",children:[0,1,2].map(r=>i.jsx("span",{className:"rudder-text-dots__dot",style:{"--rudder-text-dot-index":r},children:"."},r))})]})}function Cn({className:e,...t}){return i.jsx("div",{"data-slot":"skeleton",className:q("motion-skeleton rounded-[var(--radius-sm)] bg-[color:color-mix(in_oklab,var(--surface-active)_82%,transparent)]",e),...t})}function JP(e){if(!e)return null;const t=e instanceof Date?e.getTime():Date.parse(e);return Number.isFinite(t)?t:null}function dut(e){return QVe(e)}function uut(e){let t=0;for(const n of e){const r=Date.parse(n.ts);Number.isFinite(r)&&r>t&&(t=r)}return t>0?t:Date.now()}function uOn(e,t){for(const n of e){const r=Date.parse(n.ts);if(Number.isFinite(r))return new Date(r)}return t}function fOn(e,t,n){const r=JP(t.createdAt),a=(t.chatTurnId?e.filter(l=>{if(l.role!=="user"||l.chatTurnId!==t.chatTurnId||(l.turnVariant??0)!==(t.turnVariant??0))return!1;const c=JP(l.createdAt);return c!==null&&(r===null||c<=r)}):[]).reduce((l,c)=>{const d=JP(c.createdAt);return d===null?l:l===null||d>l?d:l},null);if(a!==null)return new Date(a);const o=e.reduce((l,c)=>{if(c.role!=="user")return l;const d=JP(c.createdAt);return d===null||r!==null&&d>r?l:l===null||d>l?d:l},null);return o!==null?new Date(o):uOn(n,new Date(t.createdAt))}function mOn(e,t){const n=t.length>0?uut(t):0,r=JP(e.createdAt)??0,s=Math.max(n,r);return new Date(s>0?s:Date.now())}const AOn=new Set(["pending","acceptance_unknown","accepted_current"]);function Zre(e,t){const n=e==null?void 0:e[t];return typeof n=="string"&&n.trim()?n:null}function wPe(e,t){const n=e==null?void 0:e[t];return typeof n=="number"&&Number.isInteger(n)&&n>=0?n:null}function fut(e){var s;if(e.role!=="user"||((s=e.structuredPayload)==null?void 0:s.source)!=="steer")return null;const t=Zre(e.structuredPayload,"deliveryDisposition");if(!t||!AOn.has(t))return null;const n=Zre(e.structuredPayload,"targetGenerationId"),r=wPe(e.structuredPayload,"afterTranscriptEntryCount");return!n||r===null?null:{message:e,targetGenerationId:n,afterTranscriptEntryCount:r,generationSeq:wPe(e.structuredPayload,"generationSeq")??0,controlActionId:Zre(e.structuredPayload,"controlActionId")}}function hOn(e,t){const n=t.map(fut).filter(a=>!!a).sort((a,o)=>a.afterTranscriptEntryCount-o.afterTranscriptEntryCount||a.generationSeq-o.generationSeq||new Date(a.message.createdAt).getTime()-new Date(o.message.createdAt).getTime()||a.message.id.localeCompare(o.message.id));if(n.length===0)return e;const r=new Map;for(const a of n){const o=Math.min(a.afterTranscriptEntryCount,e.length),l=r.get(o)??[];l.push(a),r.set(o,l)}const s=[];for(let a=0;a<=e.length;a+=1){a>0&&s.push(e[a-1]);for(const o of r.get(a)??[]){const l={kind:"user",source:"steer",ts:new Date(o.message.createdAt).toISOString(),text:o.message.body,messageId:o.message.id,controlActionId:o.controlActionId??void 0,steerMessage:o.message};s.push(l)}}return s}function pOn(e,t,n){if(n)return e[t]?e:{...e,[t]:!0};if(!e[t])return e;const{[t]:r,...s}=e;return s}function gOn(e,t,n){if(n===null){if(!(t in e))return e;const{[t]:r,...s}=e;return s}return{...e,[t]:n}}function xOn(e,t){return!!(t&&e[t])}function kPe(e,t){return t?e[t]??null:null}function bOn(e,t){return e.role==="user"?!0:t.chatTurnId&&e.chatTurnId===t.chatTurnId?!1:new Date(e.createdAt).getTime()<t.userCreatedAt.getTime()}function yOn(e,t){const n=t.userMessageId?e.findIndex(s=>s.id===t.userMessageId):-1;if(n>=0)return n+1;const r=e.findIndex(s=>new Date(s.createdAt).getTime()>=t.userCreatedAt.getTime());return r>=0?r:e.length}function vOn(e,t){if(!t.editedFromCreatedAt)return!0;const n=new Date(e.createdAt).getTime();return n<t.editedFromCreatedAt.getTime()?!0:e.role==="user"&&e.id!==t.userMessageId&&n>=t.userCreatedAt.getTime()}const mut={content:null,version:0},DW=new Map,GQ=new Map;function Aut(e){for(const t of GQ.get(e)??[])t()}function wOn(e,t){const n=DW.get(e);DW.set(e,{content:t,version:((n==null?void 0:n.version)??0)+1}),Aut(e)}function kOn(e){DW.delete(e)&&Aut(e)}function OOn(e,t){const n=GQ.get(e)??new Set;return n.add(t),GQ.set(e,n),()=>{n.delete(t),n.size===0&&GQ.delete(e)}}function SOn(e){return DW.get(e)??mut}function jOn({targetKey:e}){const t=A.useSyncExternalStore(n=>OOn(e,n),()=>SOn(e),()=>mut);return i.jsxs("div",{className:"h-full min-h-0","data-testid":"chat-side-panel-issue-proposal-content",children:[i.jsx("span",{className:"sr-only",role:"status",children:"Issue proposal opened in Side Panel."}),t.content]})}const COn="*";function Xre(e){const t=e.trim();return t?`${t[0]}${"*".repeat(Math.max(1,Array.from(t).length-1))}`:COn}const NOn=[{regex:/\/Users\/([^/\\\s]+)/g,replace:(e,t)=>`/Users/${Xre(t)}`},{regex:/\/home\/([^/\\\s]+)/g,replace:(e,t)=>`/home/${Xre(t)}`},{regex:/([A-Za-z]:\\Users\\)([^\\/\s]+)/g,replace:(e,t,n)=>`${t}${Xre(n)}`}];function IOn(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function dA(e,t){if((t==null?void 0:t.enabled)===!1)return e;let n=e;for(const r of NOn)n=n.replace(r.regex,r.replace);return n}function RW(e,t){if(typeof e=="string")return dA(e,t);if(Array.isArray(e))return e.map(r=>RW(r,t));if(!IOn(e))return e;const n={};for(const[r,s]of Object.entries(e))n[r]=RW(s,t);return n}function u2e(e,t){switch(e.kind){case"assistant":case"thinking":case"user":case"stderr":case"system":case"stdout":return{...e,text:dA(e.text,t)};case"tool_call":return{...e,name:dA(e.name,t),input:RW(e.input,t)};case"tool_result":return{...e,content:dA(e.content,t)};case"todo_list":return{...e,todoListId:e.todoListId?dA(e.todoListId,t):void 0,items:e.items.map(n=>({...n,text:dA(n.text,t)}))};case"init":return{...e,model:dA(e.model,t),sessionId:dA(e.sessionId,t)};case"result":return{...e,text:dA(e.text,t),subtype:dA(e.subtype,t),errors:e.errors.map(n=>dA(n,t))};default:return e}}function QI(e){return typeof e=="string"&&e.trim().length>0?e.trim():null}function Gre(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function z5(e,t){if(!Array.isArray(e))return[];const n=Gre(t),r={agentRuntimeType:QI(n==null?void 0:n.agentRuntimeType),model:QI((n==null?void 0:n.model)??t)},s=[],a=new Set;r.agentRuntimeType&&r.model&&a.add(`${r.agentRuntimeType}\0${r.model}`);for(const o of e){const l=Gre(o),c=l?QI(l.agentRuntimeType)??r.agentRuntimeType:r.agentRuntimeType,d=QI(l?l.model:o);if(!c||!d)continue;const u=`${c}\0${d}`;if(a.has(u))continue;a.add(u);const f=Gre(l==null?void 0:l.config),m=f?Object.fromEntries(Object.entries(f).filter(([x])=>!["agentRuntimeType","model","modelFallbacks","config"].includes(x))):{},p={...l?Object.fromEntries(Object.entries(l).filter(([x])=>!["agentRuntimeType","model","modelFallbacks","config"].includes(x))):{},...m};s.push({agentRuntimeType:c,model:d,...Object.keys(p).length>0?{config:p}:{}})}return s}const POn=[{capabilityId:"issue.comment",name:"rudder_issue_comment",description:"Add a comment to an issue, optionally uploading images and appending Markdown image links.",semanticDescription:"Add a comment to an issue, optionally uploading images and appending Markdown image links. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Add a comment to an issue, optionally uploading images and appending Markdown image links"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,anyOf:[{required:["body"]},{required:["comment"]}],properties:{body:{description:"Direct Markdown body.",maxLength:5e5,minLength:1,type:"string"},comment:{description:"Direct Markdown body.",maxLength:5e5,minLength:1,type:"string"},images:{description:"Local image paths to attach.",items:{description:"Local image paths to attach.",maxLength:8192,minLength:1,type:"string"},maxItems:20,type:"array"},issue:{description:"Issue UUID, identifier, or short reference.",maxLength:200,minLength:1,type:"string"},reopen:{description:"Reopen the issue while commenting.",type:"boolean"}},required:["issue"],type:"object"}},{capabilityId:"issue.comments.list",name:"rudder_issue_comments_list",description:"List issue comments, optionally only newer comments after a full comment id or cmt_<uuid-prefix> with --after.",semanticDescription:"List issue comments, optionally only newer comments after a full comment id or cmt_<uuid-prefix> with --after. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List issue comments, optionally only newer comments after a full comment id or cmt_<uuid-prefix> with --after"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{after:{description:"Return comments after this comment id or short reference.",maxLength:200,minLength:1,type:"string"},issue:{description:"Issue UUID, identifier, or short reference.",maxLength:200,minLength:1,type:"string"},order:{description:"Comment order.",enum:["asc","desc"],maxLength:10,minLength:1,type:"string"}},required:["issue"],type:"object"}},{capabilityId:"issue.comments.get",name:"rudder_issue_comments_get",description:"Read one issue comment by full id or cmt_<uuid-prefix> scoped to the issue.",semanticDescription:"Read one issue comment by full id or cmt_<uuid-prefix> scoped to the issue. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read one issue comment by full id or cmt_<uuid-prefix> scoped to the issue"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{comment:{description:"Comment id or short reference.",maxLength:200,minLength:1,type:"string"},issue:{description:"Issue UUID, identifier, or short reference.",maxLength:200,minLength:1,type:"string"}},required:["issue","comment"],type:"object"}},{capabilityId:"issue.update",name:"rudder_issue_update",description:"Apply generic issue updates when workflow commands are not enough, optionally uploading images for the update comment.",semanticDescription:"Apply generic issue updates when workflow commands are not enough, optionally uploading images for the update comment. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Apply generic issue updates when workflow commands are not enough, optionally uploading images for the update comment"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{assigneeAgentId:{description:"Assignee agent id or reference.",maxLength:200,minLength:1,type:"string"},billingCode:{description:"Billing code.",maxLength:200,minLength:1,type:"string"},body:{description:"Direct Markdown body.",maxLength:5e5,minLength:1,type:"string"},comment:{description:"Direct Markdown body.",maxLength:5e5,minLength:1,type:"string"},description:{description:"Issue description.",maxLength:5e5,minLength:1,type:"string"},goalId:{description:"Goal id or reference.",maxLength:200,minLength:1,type:"string"},hiddenAt:{description:"Hidden timestamp.",maxLength:100,minLength:1,type:"string"},images:{description:"Local image paths to attach.",items:{description:"Local image paths to attach.",maxLength:8192,minLength:1,type:"string"},maxItems:20,type:"array"},issue:{description:"Issue UUID, identifier, or short reference.",maxLength:200,minLength:1,type:"string"},parentId:{description:"Parent issue id or reference.",maxLength:200,minLength:1,type:"string"},priority:{description:"New issue priority.",maxLength:100,minLength:1,type:"string"},projectId:{description:"Project id or reference.",maxLength:200,minLength:1,type:"string"},requestDepth:{description:"Requested issue depth.",maxLength:30,minLength:1,type:"string"},status:{description:"New issue status.",maxLength:100,minLength:1,type:"string"},title:{description:"Issue title.",maxLength:500,minLength:1,type:"string"}},required:["issue"],type:"object"}},{capabilityId:"issue.review",name:"rudder_issue_review",description:"Record a structured reviewer decision with a required comment.",semanticDescription:"Record a structured reviewer decision with a required comment. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Record a structured reviewer decision with a required comment"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,anyOf:[{required:["comment"]},{required:["body"]}],properties:{body:{description:"Direct Markdown body.",maxLength:5e5,minLength:1,type:"string"},comment:{description:"Direct Markdown body.",maxLength:5e5,minLength:1,type:"string"},decision:{description:"Structured review decision.",enum:["approve","request_changes","needs_followup","blocked"],maxLength:30,minLength:1,type:"string"},issue:{description:"Issue UUID, identifier, or short reference.",maxLength:200,minLength:1,type:"string"}},required:["issue","decision"],type:"object"}},{capabilityId:"issue.commit",name:"rudder_issue_commit",description:"Report a code commit created during issue work as structured issue activity.",semanticDescription:"Report a code commit created during issue work as structured issue activity. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Report a code commit created during issue work as structured issue activity"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{branch:{description:"Git branch name.",maxLength:500,minLength:1,type:"string"},count:{description:"Number of commits represented.",maximum:1e4,minimum:1,type:"number"},issue:{description:"Issue UUID, identifier, or short reference.",maxLength:200,minLength:1,type:"string"},message:{description:"Commit subject or status message.",maxLength:2e3,minLength:1,type:"string"},repoPath:{description:"Repository path.",maxLength:8192,minLength:1,type:"string"},sha:{description:"Git commit SHA.",maxLength:100,minLength:1,type:"string"},workspacePath:{description:"Workspace path.",maxLength:8192,minLength:1,type:"string"}},required:["issue","sha","message"],type:"object"}},{capabilityId:"issue.done",name:"rudder_issue_done",description:"Mark an issue done with a required completion comment, optionally uploading images.",semanticDescription:"Mark an issue done with a required completion comment, optionally uploading images. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!0,idempotentHint:!1,readOnlyHint:!1,title:"Mark an issue done with a required completion comment, optionally uploading images"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,anyOf:[{required:["comment"]},{required:["body"]}],properties:{body:{description:"Direct Markdown body.",maxLength:5e5,minLength:1,type:"string"},comment:{description:"Direct Markdown body.",maxLength:5e5,minLength:1,type:"string"},images:{description:"Local image paths to attach.",items:{description:"Local image paths to attach.",maxLength:8192,minLength:1,type:"string"},maxItems:20,type:"array"},issue:{description:"Issue UUID, identifier, or short reference.",maxLength:200,minLength:1,type:"string"}},required:["issue"],type:"object"}},{capabilityId:"issue.block",name:"rudder_issue_block",description:"Request human assistance after bounded recovery attempts; repeated matching claims are audited before the Issue becomes blocked.",semanticDescription:"Request human assistance after bounded recovery attempts; repeated matching claims are audited before the Issue becomes blocked. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!0,idempotentHint:!1,readOnlyHint:!1,title:"Request human assistance after bounded recovery attempts"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,anyOf:[{required:["comment"]},{required:["body"]}],properties:{body:{description:"Direct Markdown body.",maxLength:5e5,minLength:1,type:"string"},comment:{description:"Direct Markdown body.",maxLength:5e5,minLength:1,type:"string"},images:{description:"Local image paths to attach.",items:{description:"Local image paths to attach.",maxLength:8192,minLength:1,type:"string"},maxItems:20,type:"array"},issue:{description:"Issue UUID, identifier, or short reference.",maxLength:200,minLength:1,type:"string"}},required:["issue"],type:"object"}},{capabilityId:"project.list",name:"rudder_project_list",description:"List projects in an organization.",semanticDescription:"List projects in an organization. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List projects in an organization"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{},type:"object"}},{capabilityId:"project.get",name:"rudder_project_get",description:"Read one project by ID or shortname.",semanticDescription:"Read one project by ID or shortname. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read one project by ID or shortname"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{project:{description:"Project UUID or shortname.",maxLength:200,minLength:1,type:"string"}},required:["project"],type:"object"}},{capabilityId:"project.create",name:"rudder_project_create",description:"Create a project in the organization.",semanticDescription:"Create a project in the organization. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Create a project in the organization"},mutating:!0,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{color:{description:"Display color.",maxLength:100,minLength:1,type:"string"},description:{description:"Project description.",maxLength:5e5,minLength:1,type:"string"},goalId:{description:"Goal id or reference.",maxLength:200,minLength:1,type:"string"},goalIds:{description:"Goal ids.",items:{description:"Goal ids.",maxLength:8192,minLength:1,type:"string"},maxItems:100,type:"array"},leadAgentId:{description:"Lead agent id or reference.",maxLength:200,minLength:1,type:"string"},name:{description:"Project name.",maxLength:300,minLength:1,type:"string"},status:{description:"Project status.",maxLength:100,minLength:1,type:"string"},targetDate:{description:"Target date.",maxLength:100,minLength:1,type:"string"}},required:["name"],type:"object"}},{capabilityId:"project.update",name:"rudder_project_update",description:"Update mutable project fields such as name, description, status, goals, lead agent, target date, color, or archivedAt.",semanticDescription:"Update mutable project fields such as name, description, status, goals, lead agent, target date, color, or archivedAt. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Update mutable project fields such as name, description, status, goals, lead agent, target date, color, or archivedAt"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{archivedAt:{description:"Archive timestamp.",maxLength:100,minLength:1,type:"string"},color:{description:"Display color.",maxLength:100,minLength:1,type:"string"},description:{description:"Project description.",maxLength:5e5,minLength:1,type:"string"},goalId:{description:"Goal id or reference.",maxLength:200,minLength:1,type:"string"},goalIds:{description:"Goal ids.",items:{description:"Goal ids.",maxLength:8192,minLength:1,type:"string"},maxItems:100,type:"array"},idempotencyKey:{description:"Stable key for retrying project updates; required when changing Project-Goal links.",maxLength:256,minLength:1,type:"string"},leadAgentId:{description:"Lead agent id or reference.",maxLength:200,minLength:1,type:"string"},name:{description:"Project name.",maxLength:300,minLength:1,type:"string"},project:{description:"Project UUID or shortname.",maxLength:200,minLength:1,type:"string"},status:{description:"Project status.",maxLength:100,minLength:1,type:"string"},targetDate:{description:"Target date.",maxLength:100,minLength:1,type:"string"}},required:["project"],type:"object"}},{capabilityId:"user.activity",name:"rudder_user_activity",description:"Read a user-centered activity ledger with safe excerpts and provenance across chats, issue comments, approval comments, and user actor activity.",semanticDescription:"Read a user-centered activity ledger with safe excerpts and provenance across chats, issue comments, approval comments, and user actor activity. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read a user-centered activity ledger with safe excerpts and provenance across chats, issue comments, approval comments, and user actor activity"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{cursor:{description:"Opaque pagination cursor.",maxLength:2e3,minLength:1,type:"string"},include:{description:"Comma-separated optional sections.",maxLength:500,minLength:1,type:"string"},issueId:{description:"Issue id.",maxLength:200,minLength:1,type:"string"},limit:{description:"Page size.",maximum:100,minimum:1,type:"number"},projectId:{description:"Project id.",maxLength:200,minLength:1,type:"string"},relatedAgentId:{description:"Related agent id.",maxLength:200,minLength:1,type:"string"},since:{description:"Activity start timestamp.",maxLength:100,minLength:1,type:"string"},until:{description:"Activity end timestamp.",maxLength:100,minLength:1,type:"string"},user:{description:"User id, reference, or self.",maxLength:200,minLength:1,type:"string"}},type:"object"}},{capabilityId:"library.file.list",name:"rudder_library_file_list",description:"List Library files and folders; file rows include `libraryEntryId` when a strong reference can be generated.",semanticDescription:"List Library files and folders; file rows include `libraryEntryId` when a strong reference can be generated. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List Library files and folders"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{directory:{description:"Library-relative directory path.",maxLength:8192,minLength:1,type:"string"},path:{description:"Compatibility alias for directory.",maxLength:8192,minLength:1,type:"string"}},type:"object"}},{capabilityId:"library.file.get",name:"rudder_library_file_get",description:"Fallback read when local filesystem access is unavailable; JSON includes `mentionHref` and `markdownLink`.",semanticDescription:"Fallback read when local filesystem access is unavailable; JSON includes `mentionHref` and `markdownLink`. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Fallback read when local filesystem access is unavailable"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{path:{description:"Library-relative file path.",maxLength:8192,minLength:1,type:"string"}},required:["path"],type:"object"}},{capabilityId:"library.file.ref",name:"rudder_library_file_ref",description:"Return the stable Markdown reference for one Library file without printing file content.",semanticDescription:"Return the stable Markdown reference for one Library file without printing file content. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Return the stable Markdown reference for one Library file without printing file content"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{path:{description:"Library-relative file path.",maxLength:8192,minLength:1,type:"string"}},required:["path"],type:"object"}},{capabilityId:"library.file.link",name:"rudder_library_file_link",description:"Compatibility alias for `rudder library file ref <path>`.",semanticDescription:"Compatibility alias for `rudder library file ref <path>`. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Compatibility alias for `rudder library file ref <path>`"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{path:{description:"Library-relative file path.",maxLength:8192,minLength:1,type:"string"}},required:["path"],type:"object"}},{capabilityId:"library.file.put",name:"rudder_library_file_put",description:"Fallback create/update when local filesystem access is unavailable; JSON includes `mentionHref` and `markdownLink`.",semanticDescription:"Fallback create/update when local filesystem access is unavailable; JSON includes `mentionHref` and `markdownLink`. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!0,idempotentHint:!1,readOnlyHint:!1,title:"Fallback create/update when local filesystem access is unavailable"},mutating:!0,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,anyOf:[{required:["body"]},{required:["content"]}],properties:{body:{description:"Direct file content.",maxLength:1e6,minLength:1,type:"string"},content:{description:"Compatibility alias for body.",maxLength:1e6,minLength:1,type:"string"},path:{description:"Library-relative file path.",maxLength:8192,minLength:1,type:"string"}},required:["path"],type:"object"}},{capabilityId:"issue.create",name:"rudder_issue_create",description:"Create a new issue or subtask with the generic issue surface; agent-created issues default to the creating agent when no assignee is supplied.",semanticDescription:"Create a new issue or subtask with the generic issue surface; agent-created issues default to the creating agent when no assignee is supplied. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Create a new issue or subtask with the generic issue surface"},mutating:!0,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{assigneeAgentId:{description:"Assignee agent id or reference.",maxLength:200,minLength:1,type:"string"},billingCode:{description:"Billing code.",maxLength:200,minLength:1,type:"string"},description:{description:"Issue description.",maxLength:5e5,minLength:1,type:"string"},goalId:{description:"Goal id or reference.",maxLength:200,minLength:1,type:"string"},labelIds:{description:"Issue label ids.",items:{description:"Issue label ids.",maxLength:8192,minLength:1,type:"string"},maxItems:100,type:"array"},parentId:{description:"Parent issue id or reference.",maxLength:200,minLength:1,type:"string"},priority:{description:"Issue priority.",maxLength:100,minLength:1,type:"string"},projectId:{description:"Project id or reference.",maxLength:200,minLength:1,type:"string"},requestDepth:{description:"Requested issue depth.",maximum:1e4,minimum:0,type:"number"},status:{description:"Issue status.",maxLength:100,minLength:1,type:"string"},title:{description:"Issue title.",maxLength:500,minLength:1,type:"string"}},required:["title"],type:"object"}},{capabilityId:"approval.get",name:"rudder_approval_get",description:"Read one approval request.",semanticDescription:"Read one approval request. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read one approval request"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{approval:{description:"Approval UUID or short reference.",maxLength:200,minLength:1,type:"string"}},required:["approval"],type:"object"}},{capabilityId:"approval.issues",name:"rudder_approval_issues",description:"List the issues linked to an approval.",semanticDescription:"List the issues linked to an approval. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List the issues linked to an approval"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{approval:{description:"Approval UUID or short reference.",maxLength:200,minLength:1,type:"string"}},required:["approval"],type:"object"}}],TOn=[{capabilityId:"approval.comment",name:"rudder_approval_comment",description:"Add a comment to an approval.",semanticDescription:"Add a comment to an approval. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Add a comment to an approval"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,anyOf:[{required:["body"]},{required:["comment"]}],properties:{approval:{description:"Approval UUID or short reference.",maxLength:200,minLength:1,type:"string"},body:{description:"Direct Markdown body.",maxLength:5e5,minLength:1,type:"string"},comment:{description:"Direct Markdown body.",maxLength:5e5,minLength:1,type:"string"}},required:["approval"],type:"object"}},{capabilityId:"skill.list",name:"rudder_skill_list",description:"List organization-visible skills.",semanticDescription:"List organization-visible skills. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List organization-visible skills"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{},type:"object"}},{capabilityId:"skill.search",name:"rudder_skill_search",description:"Search organization-visible skills by name, slug, description, or source.",semanticDescription:"Search organization-visible skills by name, slug, description, or source. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Search organization-visible skills by name, slug, description, or source"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{query:{description:"Skill name, slug, description, source, or selection key to search for.",maxLength:2e3,minLength:1,type:"string"}},required:["query"],type:"object"}},{capabilityId:"skill.get",name:"rudder_skill_get",description:"Read one organization skill detail.",semanticDescription:"Read one organization skill detail. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read one organization skill detail"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{skill:{description:"Organization skill id.",maxLength:200,minLength:1,type:"string"}},required:["skill"],type:"object"}},{capabilityId:"skill.file",name:"rudder_skill_file",description:"Read one file from an organization skill package.",semanticDescription:"Read one file from an organization skill package. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read one file from an organization skill package"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{path:{description:"Skill package file path.",maxLength:8192,minLength:1,type:"string"},skill:{description:"Organization skill id.",maxLength:200,minLength:1,type:"string"}},required:["skill"],type:"object"}},{capabilityId:"skill.import",name:"rudder_skill_import",description:"Import a skill package into the organization skill library.",semanticDescription:"Import a skill package into the organization skill library. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Import a skill package into the organization skill library"},mutating:!0,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{source:{description:"Local path, URL, or repository reference.",maxLength:8192,minLength:1,type:"string"}},required:["source"],type:"object"}},{capabilityId:"skill.scan-local",name:"rudder_skill_scan_local",description:"Scan local roots for skill packages and import new ones.",semanticDescription:"Scan local roots for skill packages and import new ones. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Scan local roots for skill packages and import new ones"},mutating:!0,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{roots:{description:"Comma-separated local roots.",maxLength:2e4,minLength:1,type:"string"}},type:"object"}},{capabilityId:"skill.scan-projects",name:"rudder_skill_scan_projects",description:"Scan the org workspace and any legacy project workspace records for skill packages and import new ones.",semanticDescription:"Scan the org workspace and any legacy project workspace records for skill packages and import new ones. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Scan the org workspace and any legacy project workspace records for skill packages and import new ones"},mutating:!0,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{projectIds:{description:"Comma-separated project ids.",maxLength:2e4,minLength:1,type:"string"},workspaceIds:{description:"Comma-separated workspace ids.",maxLength:2e4,minLength:1,type:"string"}},type:"object"}},{capabilityId:"plugin.search",name:"rudder_plugin_search",description:"Search installed, local, and discoverable Rudder plugins.",semanticDescription:"Search installed, local, and discoverable Rudder plugins. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Search installed, local, and discoverable Rudder plugins"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{query:{description:"Plugin name, description, publisher, source, or component to search for.",maxLength:2e3,minLength:1,type:"string"}},required:["query"],type:"object"}},{capabilityId:"plugin.get",name:"rudder_plugin_get",description:"Read an installed plugin, including its components and current setup state; use this to resolve plugin:// references.",semanticDescription:"Read an installed plugin, including its components and current setup state; use this to resolve plugin:// references. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read an installed plugin, including its components and current setup state"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{plugin:{description:"Installed plugin UUID from a plugin:// reference or plugin search result.",maxLength:200,minLength:1,type:"string"}},required:["plugin"],type:"object"}},{capabilityId:"browser.tabs",name:"rudder_browser_tabs",description:"List Browser tabs owned by the current Rudder agent run.",semanticDescription:"List Browser tabs owned by the current Rudder agent run. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List Browser tabs owned by the current Rudder agent run"},mutating:!1,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{},type:"object"}},{capabilityId:"browser.user-tabs",name:"rudder_browser_user_tabs",description:"List user-visible tabs currently open in Rudder's built-in Browser without taking control of them.",semanticDescription:"List user-visible tabs currently open in Rudder's built-in Browser without taking control of them. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List user-visible tabs currently open in Rudder's built-in Browser without taking control of them"},mutating:!1,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{},type:"object"}},{capabilityId:"browser.open",name:"rudder_browser_open",description:"Open a run-owned tab in the Rudder Browser.",semanticDescription:"Open a run-owned tab in the Rudder Browser. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1,title:"Open a run-owned tab in the Rudder Browser"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{url:{description:"HTTP or HTTPS URL.",maxLength:8192,minLength:1,type:"string"}},required:["url"],type:"object"}},{capabilityId:"browser.navigate",name:"rudder_browser_navigate",description:"Navigate a run-owned Rudder Browser tab.",semanticDescription:"Navigate a run-owned Rudder Browser tab. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1,title:"Navigate a run-owned Rudder Browser tab"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"},url:{description:"HTTP or HTTPS URL.",maxLength:8192,minLength:1,type:"string"}},required:["tabId","url"],type:"object"}},{capabilityId:"browser.back",name:"rudder_browser_back",description:"Navigate a run-owned Rudder Browser tab back in history.",semanticDescription:"Navigate a run-owned Rudder Browser tab back in history. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Navigate a run-owned Rudder Browser tab back in history"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId"],type:"object"}},{capabilityId:"browser.forward",name:"rudder_browser_forward",description:"Navigate a run-owned Rudder Browser tab forward in history.",semanticDescription:"Navigate a run-owned Rudder Browser tab forward in history. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Navigate a run-owned Rudder Browser tab forward in history"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId"],type:"object"}},{capabilityId:"browser.reload",name:"rudder_browser_reload",description:"Reload a run-owned Rudder Browser tab.",semanticDescription:"Reload a run-owned Rudder Browser tab. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!1,title:"Reload a run-owned Rudder Browser tab"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId"],type:"object"}},{capabilityId:"browser.viewport",name:"rudder_browser_viewport",description:"Inspect, set, or reset the responsive viewport for the current Rudder Browser run.",semanticDescription:"Inspect, set, or reset the responsive viewport for the current Rudder Browser run. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Inspect, set, or reset the responsive viewport for the current Rudder Browser run"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{action:{description:"Viewport action.",enum:["get","set","reset"],type:"string"},height:{description:"Viewport height in CSS pixels.",maximum:2160,minimum:240,type:"number"},width:{description:"Viewport width in CSS pixels.",maximum:3840,minimum:320,type:"number"}},required:["action"],type:"object"}},{capabilityId:"browser.visibility",name:"rudder_browser_visibility",description:"Inspect or change whether the current run's selected Rudder Browser tab is visible.",semanticDescription:"Inspect or change whether the current run's selected Rudder Browser tab is visible. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Inspect or change whether the current run's selected Rudder Browser tab is visible"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{visible:{description:"Whether the selected Agent Browser tab is visible.",type:"boolean"}},type:"object"}},{capabilityId:"browser.snapshot",name:"rudder_browser_snapshot",description:"Capture a bounded DOM and accessibility-oriented snapshot, including frame structure and ephemeral node ids.",semanticDescription:"Capture a bounded DOM and accessibility-oriented snapshot, including frame structure and ephemeral node ids. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Capture a bounded DOM and accessibility-oriented snapshot, including frame structure and ephemeral node ids"},mutating:!1,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{boxes:{description:"Include viewport-relative element boxes.",type:"boolean"},depth:{description:"Maximum snapshot tree depth.",maximum:30,minimum:1,type:"number"},maxNodes:{description:"Maximum snapshot nodes.",maximum:3e3,minimum:1,type:"number"},tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId"],type:"object"}},{capabilityId:"browser.locator",name:"rudder_browser_locator",description:"Perform read-only bounded Browser locator text, attribute, state, count, or wait operations.",semanticDescription:"Perform read-only bounded Browser locator text, attribute, state, count, or wait operations. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Perform read-only bounded Browser locator text, attribute, state, count, or wait operations"},mutating:!1,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{action:{description:"Read-only locator action.",enum:["count","allTextContents","textContent","innerText","attribute","visible","enabled","checked","selected","wait"],type:"string"},locator:{additionalProperties:!1,properties:{and:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},exact:{description:"Require an exact text or attribute match.",type:"boolean"},filter:{additionalProperties:!1,properties:{has:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},hasNot:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},hasNotText:{description:"Excluded descendant text.",maxLength:2e3,type:"string"},hasText:{description:"Required descendant text.",maxLength:2e3,type:"string"},visible:{description:"Filter by current visibility.",type:"boolean"}},type:"object"},frame:{items:{description:"CSS iframe selector.",maxLength:1e3,minLength:1,type:"string"},maxItems:8,type:"array"},index:{description:"Zero-based locator match index.",maximum:499,minimum:0,type:"number"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},or:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},position:{description:"Locator endpoint after an explicit count.",enum:["first","last"],type:"string"},scope:{additionalProperties:!1,properties:{and:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},exact:{description:"Require an exact text or attribute match.",type:"boolean"},filter:{additionalProperties:!1,properties:{has:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},hasNot:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},hasNotText:{description:"Excluded descendant text.",maxLength:2e3,type:"string"},hasText:{description:"Required descendant text.",maxLength:2e3,type:"string"},visible:{description:"Filter by current visibility.",type:"boolean"}},type:"object"},index:{description:"Zero-based locator match index.",maximum:499,minimum:0,type:"number"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},or:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},position:{description:"Locator endpoint after an explicit count.",enum:["first","last"],type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},name:{description:"Attribute name for attribute reads.",maxLength:200,type:"string"},state:{description:"Wait state.",enum:["attached","detached","visible","hidden"],type:"string"},tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"},timeoutMs:{description:"Wait timeout in milliseconds.",maximum:3e4,minimum:0,type:"number"}},required:["tabId","action","locator"],type:"object"}}],_On=[{capabilityId:"browser.cua",name:"rudder_browser_cua",description:"Perform trusted coordinate mouse, scroll, drag, keyboard, and text input in a run-owned Browser tab.",semanticDescription:"Perform trusted coordinate mouse, scroll, drag, keyboard, and text input in a run-owned Browser tab. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Perform trusted coordinate mouse, scroll, drag, keyboard, and text input in a run-owned Browser tab"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{action:{description:"Coordinate input or inspection action.",enum:["click","doubleClick","move","scroll","drag","keypress","type","elementInfo"],type:"string"},button:{oneOf:[{description:"Mouse button number.",maximum:5,minimum:1,type:"number"},{description:"Mouse button.",enum:["left","middle","right"],type:"string"}]},keys:{items:{description:"Keyboard key or modifier.",maxLength:100,minLength:1,type:"string"},maxItems:10,type:"array"},path:{items:{additionalProperties:!1,properties:{x:{description:"Path X coordinate.",type:"number"},y:{description:"Path Y coordinate.",type:"number"}},required:["x","y"],type:"object"},maxItems:200,minItems:2,type:"array"},scrollX:{description:"Horizontal scroll delta.",type:"number"},scrollY:{description:"Vertical scroll delta.",type:"number"},tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"},text:{description:"Text to type.",maxLength:1e5,type:"string"},x:{description:"Viewport X coordinate.",type:"number"},y:{description:"Viewport Y coordinate.",type:"number"}},required:["tabId","action"],type:"object"}},{capabilityId:"browser.dom-cua",name:"rudder_browser_dom_cua",description:"Inspect a bounded read-only DOM snapshot with ephemeral node ids.",semanticDescription:"Inspect a bounded read-only DOM snapshot with ephemeral node ids. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Inspect a bounded read-only DOM snapshot with ephemeral node ids"},mutating:!1,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{action:{description:"Read-only DOM snapshot action.",enum:["get"],type:"string"},depth:{description:"Maximum DOM depth.",maximum:30,minimum:1,type:"number"},maxNodes:{description:"Maximum DOM nodes.",maximum:3e3,minimum:1,type:"number"},tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId","action"],type:"object"}},{capabilityId:"browser.dialog",name:"rudder_browser_dialog",description:"Inspect, accept, or dismiss the active JavaScript dialog in a run-owned Browser tab.",semanticDescription:"Inspect, accept, or dismiss the active JavaScript dialog in a run-owned Browser tab. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Inspect, accept, or dismiss the active JavaScript dialog in a run-owned Browser tab"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{action:{description:"Dialog action.",enum:["get","accept","dismiss"],type:"string"},promptText:{description:"Prompt response text.",maxLength:1e4,type:"string"},tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId","action"],type:"object"}},{capabilityId:"browser.clipboard",name:"rudder_browser_clipboard",description:"Read or write the isolated virtual clipboard for the current Browser run without touching the OS clipboard.",semanticDescription:"Read or write the isolated virtual clipboard for the current Browser run without touching the OS clipboard. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!0,idempotentHint:!1,readOnlyHint:!1,title:"Read or write the isolated virtual clipboard for the current Browser run without touching the OS clipboard"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{action:{description:"Virtual clipboard action.",enum:["read","readText","write","writeText","clear"],type:"string"},items:{items:{additionalProperties:!1,properties:{entries:{items:{additionalProperties:!1,properties:{base64:{description:"Base64 clipboard payload.",maxLength:65e4,type:"string"},mimeType:{description:"Clipboard MIME type.",maxLength:200,minLength:1,type:"string"},text:{description:"Text clipboard payload.",maxLength:5e5,type:"string"}},required:["mimeType"],type:"object"},maxItems:20,type:"array"},presentationStyle:{description:"Clipboard presentation style.",enum:["unspecified","inline","attachment"],type:"string"}},required:["entries"],type:"object"},maxItems:20,type:"array"},text:{description:"Plain clipboard text.",maxLength:5e5,type:"string"}},required:["action"],type:"object"}},{capabilityId:"browser.logs",name:"rudder_browser_logs",description:"Read bounded console and runtime logs captured for a run-owned Browser tab.",semanticDescription:"Read bounded console and runtime logs captured for a run-owned Browser tab. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!0,idempotentHint:!1,readOnlyHint:!1,title:"Read bounded console and runtime logs captured for a run-owned Browser tab"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{clear:{description:"Clear the tab log buffer after reading.",type:"boolean"},filter:{description:"Case-insensitive log substring filter.",maxLength:2e3,type:"string"},levels:{items:{description:"Log level.",enum:["debug","info","log","warn","error"],type:"string"},maxItems:5,type:"array"},limit:{description:"Maximum log entries.",maximum:500,minimum:1,type:"number"},tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId"],type:"object"}},{capabilityId:"browser.download",name:"rudder_browser_download",description:"Download explicit locator media without dispatching page input into a bounded run-owned artifact.",semanticDescription:"Download explicit locator media without dispatching page input into a bounded run-owned artifact. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1,title:"Download explicit locator media without dispatching page input into a bounded run-owned artifact"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{locator:{additionalProperties:!1,properties:{and:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},exact:{description:"Require an exact text or attribute match.",type:"boolean"},filter:{additionalProperties:!1,properties:{has:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},hasNot:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},hasNotText:{description:"Excluded descendant text.",maxLength:2e3,type:"string"},hasText:{description:"Required descendant text.",maxLength:2e3,type:"string"},visible:{description:"Filter by current visibility.",type:"boolean"}},type:"object"},frame:{items:{description:"CSS iframe selector.",maxLength:1e3,minLength:1,type:"string"},maxItems:8,type:"array"},index:{description:"Zero-based locator match index.",maximum:499,minimum:0,type:"number"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},or:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},position:{description:"Locator endpoint after an explicit count.",enum:["first","last"],type:"string"},scope:{additionalProperties:!1,properties:{and:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},exact:{description:"Require an exact text or attribute match.",type:"boolean"},filter:{additionalProperties:!1,properties:{has:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},hasNot:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},hasNotText:{description:"Excluded descendant text.",maxLength:2e3,type:"string"},hasText:{description:"Required descendant text.",maxLength:2e3,type:"string"},visible:{description:"Filter by current visibility.",type:"boolean"}},type:"object"},index:{description:"Zero-based locator match index.",maximum:499,minimum:0,type:"number"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},or:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},position:{description:"Locator endpoint after an explicit count.",enum:["first","last"],type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},mode:{description:"Read-only media download mode.",enum:["media"],type:"string"},tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId","mode","locator"],type:"object"}},{capabilityId:"browser.assets",name:"rudder_browser_assets",description:"List page assets or bundle an explicit bounded selection into a run-owned temporary artifact.",semanticDescription:"List page assets or bundle an explicit bounded selection into a run-owned temporary artifact. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"List page assets or bundle an explicit bounded selection into a run-owned temporary artifact"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{action:{description:"Asset action.",enum:["list","bundle"],type:"string"},assetIds:{items:{description:"Asset id.",maxLength:160,type:"string"},maxItems:100,minItems:1,type:"array"},inventoryId:{description:"Prior asset inventory id.",maxLength:160,type:"string"},kinds:{items:{description:"Asset kind.",enum:["font","image","stylesheet","video"],type:"string"},maxItems:4,minItems:1,type:"array"},tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId","action"],type:"object"}},{capabilityId:"browser.content",name:"rudder_browser_content",description:"Export current page content or an eligible Google Workspace document into a bounded run-owned artifact.",semanticDescription:"Export current page content or an eligible Google Workspace document into a bounded run-owned artifact. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1,title:"Export current page content or an eligible Google Workspace document into a bounded run-owned artifact"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{format:{description:"Content export format.",enum:["text","pdf","md","docx","xlsx","csv","pptx"],type:"string"},tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId","format"],type:"object"}},{capabilityId:"browser.wait",name:"rudder_browser_wait",description:"Wait for bounded URL, text, disappearance, or time conditions in a run-owned Browser tab.",semanticDescription:"Wait for bounded URL, text, disappearance, or time conditions in a run-owned Browser tab. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Wait for bounded URL, text, disappearance, or time conditions in a run-owned Browser tab"},mutating:!1,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"},text:{description:"Text that must appear.",maxLength:1e4,type:"string"},textGone:{description:"Text that must disappear.",maxLength:1e4,type:"string"},timeMs:{description:"Fixed bounded delay in milliseconds.",maximum:3e4,minimum:0,type:"number"},timeoutMs:{description:"Wait timeout in milliseconds.",maximum:3e4,minimum:0,type:"number"},url:{description:"URL substring.",maxLength:8192,type:"string"}},required:["tabId"],type:"object"}},{capabilityId:"browser.read",name:"rudder_browser_read",description:"Read a structured snapshot from a run-owned Rudder Browser tab.",semanticDescription:"Read a structured snapshot from a run-owned Rudder Browser tab. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read a structured snapshot from a run-owned Rudder Browser tab"},mutating:!1,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId"],type:"object"}},{capabilityId:"browser.click",name:"rudder_browser_click",description:"Click an element reference returned by Rudder Browser read.",semanticDescription:"Click an element reference returned by Rudder Browser read. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Click an element reference returned by Rudder Browser read"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{ref:{description:"Element reference returned by rudder_browser_read.",maxLength:160,type:"string"},tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId","ref"],type:"object"}},{capabilityId:"browser.type",name:"rudder_browser_type",description:"Type into an element reference in a run-owned Rudder Browser tab.",semanticDescription:"Type into an element reference in a run-owned Rudder Browser tab. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Type into an element reference in a run-owned Rudder Browser tab"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{ref:{description:"Element reference returned by rudder_browser_read.",maxLength:160,type:"string"},submit:{description:"Submit the owning form after typing.",type:"boolean"},tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"},text:{description:"Text to enter.",maxLength:1e5,type:"string"}},required:["tabId","ref","text"],type:"object"}}],MOn=[{capabilityId:"browser.screenshot",name:"rudder_browser_screenshot",description:"Capture a screenshot of a run-owned Rudder Browser tab.",semanticDescription:"Capture a screenshot of a run-owned Rudder Browser tab. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Capture a screenshot of a run-owned Rudder Browser tab"},mutating:!1,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{clip:{additionalProperties:!1,properties:{height:{description:"Clip height.",minimum:1,type:"number"},width:{description:"Clip width.",minimum:1,type:"number"},x:{description:"Clip X coordinate.",type:"number"},y:{description:"Clip Y coordinate.",type:"number"}},required:["x","y","width","height"],type:"object"},format:{description:"Image format.",enum:["png","jpeg"],type:"string"},fullPage:{description:"Capture the full scrollable page.",type:"boolean"},locator:{additionalProperties:!1,properties:{and:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},exact:{description:"Require an exact text or attribute match.",type:"boolean"},filter:{additionalProperties:!1,properties:{has:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},hasNot:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},hasNotText:{description:"Excluded descendant text.",maxLength:2e3,type:"string"},hasText:{description:"Required descendant text.",maxLength:2e3,type:"string"},visible:{description:"Filter by current visibility.",type:"boolean"}},type:"object"},frame:{items:{description:"CSS iframe selector.",maxLength:1e3,minLength:1,type:"string"},maxItems:8,type:"array"},index:{description:"Zero-based locator match index.",maximum:499,minimum:0,type:"number"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},or:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},position:{description:"Locator endpoint after an explicit count.",enum:["first","last"],type:"string"},scope:{additionalProperties:!1,properties:{and:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},exact:{description:"Require an exact text or attribute match.",type:"boolean"},filter:{additionalProperties:!1,properties:{has:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},hasNot:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},hasNotText:{description:"Excluded descendant text.",maxLength:2e3,type:"string"},hasText:{description:"Required descendant text.",maxLength:2e3,type:"string"},visible:{description:"Filter by current visibility.",type:"boolean"}},type:"object"},index:{description:"Zero-based locator match index.",maximum:499,minimum:0,type:"number"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},or:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},position:{description:"Locator endpoint after an explicit count.",enum:["first","last"],type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},quality:{description:"JPEG quality.",maximum:100,minimum:1,type:"number"},tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId"],type:"object"}},{capabilityId:"browser.close",name:"rudder_browser_close",description:"Close a run-owned Rudder Browser tab.",semanticDescription:"Close a run-owned Rudder Browser tab. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!1,title:"Close a run-owned Rudder Browser tab"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId"],type:"object"}},{capabilityId:"automation.list",name:"rudder_automation_list",description:"List automations for an organization with compact local filters.",semanticDescription:"List automations for an organization with compact local filters. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List automations for an organization with compact local filters"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{assigneeAgentId:{description:"Assignee agent id.",maxLength:200,minLength:1,type:"string"},outputMode:{description:"Output mode filter.",maxLength:100,minLength:1,type:"string"},projectId:{description:"Project id.",maxLength:200,minLength:1,type:"string"},status:{description:"Automation status filter.",maxLength:100,minLength:1,type:"string"}},type:"object"}},{capabilityId:"automation.get",name:"rudder_automation_get",description:"Read one automation detail including triggers and recent runs.",semanticDescription:"Read one automation detail including triggers and recent runs. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read one automation detail including triggers and recent runs"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{automation:{description:"Automation UUID or short reference.",maxLength:200,minLength:1,type:"string"}},required:["automation"],type:"object"}},{capabilityId:"automation.runs",name:"rudder_automation_runs",description:"List recent runs for one automation.",semanticDescription:"List recent runs for one automation. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List recent runs for one automation"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{automation:{description:"Automation UUID or short reference.",maxLength:200,minLength:1,type:"string"},limit:{description:"Maximum run rows.",maximum:100,minimum:1,type:"number"}},required:["automation"],type:"object"}},{capabilityId:"automation.triggers.list",name:"rudder_automation_triggers_list",description:"List triggers configured for one automation.",semanticDescription:"List triggers configured for one automation. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List triggers configured for one automation"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{automation:{description:"Automation UUID or short reference.",maxLength:200,minLength:1,type:"string"}},required:["automation"],type:"object"}},{capabilityId:"automation.triggers.create",name:"rudder_automation_triggers_create",description:"Create a schedule, webhook, or API trigger through the governed automation API.",semanticDescription:"Create a schedule, webhook, or API trigger through the governed automation API. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Create a schedule, webhook, or API trigger through the governed automation API"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{automation:{description:"Automation UUID or short reference.",maxLength:200,minLength:1,type:"string"},cronExpression:{description:"Cron expression.",maxLength:500,minLength:1,type:"string"},disabled:{description:"Create the trigger disabled.",type:"boolean"},enabled:{description:"Create the trigger enabled.",type:"boolean"},kind:{description:"Trigger kind.",maxLength:100,minLength:1,type:"string"},label:{description:"Trigger label.",maxLength:300,minLength:1,type:"string"},payload:{description:"JSON payload object or JSON string.",type:["object","string"]},replayWindowSec:{description:"Webhook replay window in seconds.",maxLength:30,minLength:1,type:"string"},signingMode:{description:"Webhook signing mode.",maxLength:100,minLength:1,type:"string"},timezone:{description:"IANA timezone.",maxLength:200,minLength:1,type:"string"}},required:["automation"],type:"object"}},{capabilityId:"automation.triggers.update",name:"rudder_automation_triggers_update",description:"Update an automation trigger through the governed automation API.",semanticDescription:"Update an automation trigger through the governed automation API. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Update an automation trigger through the governed automation API"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{cronExpression:{description:"Cron expression.",maxLength:500,minLength:1,type:"string"},disabled:{description:"Disable the trigger.",type:"boolean"},enabled:{description:"Enable the trigger.",type:"boolean"},label:{description:"Trigger label.",maxLength:300,minLength:1,type:"string"},payload:{description:"JSON payload object or JSON string.",type:["object","string"]},replayWindowSec:{description:"Webhook replay window in seconds.",maxLength:30,minLength:1,type:"string"},signingMode:{description:"Webhook signing mode.",maxLength:100,minLength:1,type:"string"},timezone:{description:"IANA timezone.",maxLength:200,minLength:1,type:"string"},trigger:{description:"Automation trigger UUID or short reference.",maxLength:200,minLength:1,type:"string"}},required:["trigger"],type:"object"}},{capabilityId:"automation.triggers.delete",name:"rudder_automation_triggers_delete",description:"Delete an automation trigger through the governed automation API.",semanticDescription:"Delete an automation trigger through the governed automation API. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!0,idempotentHint:!1,readOnlyHint:!1,title:"Delete an automation trigger through the governed automation API"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{trigger:{description:"Automation trigger UUID or short reference.",maxLength:200,minLength:1,type:"string"}},required:["trigger"],type:"object"}},{capabilityId:"automation.triggers.rotate-secret",name:"rudder_automation_triggers_rotate_secret",description:"Rotate an automation webhook trigger secret through the governed automation API.",semanticDescription:"Rotate an automation webhook trigger secret through the governed automation API. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!0,idempotentHint:!1,readOnlyHint:!1,title:"Rotate an automation webhook trigger secret through the governed automation API"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{trigger:{description:"Automation trigger UUID or short reference.",maxLength:200,minLength:1,type:"string"}},required:["trigger"],type:"object"}},{capabilityId:"automation.create",name:"rudder_automation_create",description:"Create an automation through the governed automation API.",semanticDescription:"Create an automation through the governed automation API. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Create an automation through the governed automation API"},mutating:!0,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{assigneeAgentId:{description:"Assignee agent id.",maxLength:200,minLength:1,type:"string"},catchUpPolicy:{description:"Catch-up policy.",maxLength:100,minLength:1,type:"string"},concurrencyPolicy:{description:"Concurrency policy.",maxLength:100,minLength:1,type:"string"},description:{description:"Compatibility alias for instructions.",maxLength:5e5,minLength:1,type:"string"},goalId:{description:"Goal id.",maxLength:200,minLength:1,type:"string"},instructions:{description:"Automation instructions.",maxLength:5e5,minLength:1,type:"string"},notifyOnIssueCreated:{description:"Notify when an issue is created.",type:"boolean"},outputMode:{description:"Automation output mode.",maxLength:100,minLength:1,type:"string"},parentIssueId:{description:"Parent issue id.",maxLength:200,minLength:1,type:"string"},payload:{description:"JSON payload object or JSON string.",type:["object","string"]},priority:{description:"Issue priority.",maxLength:100,minLength:1,type:"string"},projectId:{description:"Project id.",maxLength:200,minLength:1,type:"string"},status:{description:"Automation status.",maxLength:100,minLength:1,type:"string"},title:{description:"Automation title.",maxLength:500,minLength:1,type:"string"}},type:"object"}},{capabilityId:"automation.update",name:"rudder_automation_update",description:"Update automation fields through the governed automation API.",semanticDescription:"Update automation fields through the governed automation API. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Update automation fields through the governed automation API"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{assigneeAgentId:{description:"Assignee agent id.",maxLength:200,minLength:1,type:"string"},automation:{description:"Automation UUID or short reference.",maxLength:200,minLength:1,type:"string"},catchUpPolicy:{description:"Catch-up policy.",maxLength:100,minLength:1,type:"string"},concurrencyPolicy:{description:"Concurrency policy.",maxLength:100,minLength:1,type:"string"},description:{description:"Compatibility alias for instructions.",maxLength:5e5,minLength:1,type:"string"},goalId:{description:"Goal id.",maxLength:200,minLength:1,type:"string"},instructions:{description:"Automation instructions.",maxLength:5e5,minLength:1,type:"string"},notifyOnIssueCreated:{description:"Notify when an issue is created.",type:"boolean"},outputMode:{description:"Automation output mode.",maxLength:100,minLength:1,type:"string"},parentIssueId:{description:"Parent issue id.",maxLength:200,minLength:1,type:"string"},payload:{description:"JSON payload object or JSON string.",type:["object","string"]},priority:{description:"Issue priority.",maxLength:100,minLength:1,type:"string"},projectId:{description:"Project id.",maxLength:200,minLength:1,type:"string"},status:{description:"Automation status.",maxLength:100,minLength:1,type:"string"},title:{description:"Automation title.",maxLength:500,minLength:1,type:"string"}},required:["automation"],type:"object"}},{capabilityId:"automation.enable",name:"rudder_automation_enable",description:"Enable an automation by setting status to active.",semanticDescription:"Enable an automation by setting status to active. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Enable an automation by setting status to active"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{automation:{description:"Automation UUID or short reference.",maxLength:200,minLength:1,type:"string"}},required:["automation"],type:"object"}}],EOn=[{capabilityId:"automation.disable",name:"rudder_automation_disable",description:"Disable an automation by setting status to paused.",semanticDescription:"Disable an automation by setting status to paused. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!0,idempotentHint:!1,readOnlyHint:!1,title:"Disable an automation by setting status to paused"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{automation:{description:"Automation UUID or short reference.",maxLength:200,minLength:1,type:"string"}},required:["automation"],type:"object"}},{capabilityId:"automation.run",name:"rudder_automation_run",description:"Trigger a manual automation run.",semanticDescription:"Trigger a manual automation run. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Trigger a manual automation run"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{automation:{description:"Automation UUID or short reference.",maxLength:200,minLength:1,type:"string"},idempotencyKey:{description:"Idempotency key.",maxLength:500,minLength:1,type:"string"},payload:{description:"JSON payload object or JSON string.",type:["object","string"]},source:{description:"Invocation source.",maxLength:500,minLength:1,type:"string"},triggerId:{description:"Trigger id.",maxLength:200,minLength:1,type:"string"}},required:["automation"],type:"object"}},{capabilityId:"chat.list",name:"rudder_chat_list",description:"List chat conversations without dumping full message history.",semanticDescription:"List chat conversations without dumping full message history. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List chat conversations without dumping full message history"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{limit:{description:"Maximum chat rows.",maximum:100,minimum:1,type:"number"},query:{description:"Optional chat query.",maxLength:2e3,minLength:1,type:"string"},status:{description:"Chat status filter.",maxLength:100,minLength:1,type:"string"}},type:"object"}},{capabilityId:"chat.search",name:"rudder_chat_search",description:"Search chats with bounded snippets and optional scope filtering.",semanticDescription:"Search chats with bounded snippets and optional scope filtering. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Search chats with bounded snippets and optional scope filtering"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{limit:{description:"Maximum matches.",maximum:100,minimum:1,type:"number"},query:{description:"Non-empty chat search query.",maxLength:2e3,minLength:1,type:"string"},scope:{description:"Search scope.",maxLength:100,minLength:1,type:"string"},snippetChars:{description:"Maximum snippet characters.",maximum:1e4,minimum:100,type:"number"},status:{description:"Chat status filter.",maxLength:100,minLength:1,type:"string"}},required:["query"],type:"object"}},{capabilityId:"chat.get",name:"rudder_chat_get",description:"Read one chat conversation record.",semanticDescription:"Read one chat conversation record. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read one chat conversation record"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{chat:{description:"Chat conversation UUID or short reference.",maxLength:200,minLength:1,type:"string"}},required:["chat"],type:"object"}},{capabilityId:"chat.messages",name:"rudder_chat_messages",description:"Read bounded chat messages with page cursors; transcript output is omitted unless requested.",semanticDescription:"Read bounded chat messages with page cursors; transcript output is omitted unless requested. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read bounded chat messages with page cursors"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{chat:{description:"Chat conversation UUID or short reference.",maxLength:200,minLength:1,type:"string"},cursor:{description:"Opaque pagination cursor.",maxLength:2e3,minLength:1,type:"string"},includeOutput:{description:"Compatibility alias for includeTranscript.",type:"boolean"},includeTranscript:{description:"Include bounded transcript data.",type:"boolean"},limit:{description:"Maximum message rows.",maximum:100,minimum:1,type:"number"},maxOutputChars:{description:"Maximum output characters per row.",maximum:2e4,minimum:100,type:"number"}},required:["chat"],type:"object"}},{capabilityId:"chat.transcript",name:"rudder_chat_transcript",description:"Read paginated chat messages with assistant transcript entries clipped in human output.",semanticDescription:"Read paginated chat messages with assistant transcript entries clipped in human output. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read paginated chat messages with assistant transcript entries clipped in human output"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{chat:{description:"Chat conversation UUID or short reference.",maxLength:200,minLength:1,type:"string"},cursor:{description:"Opaque pagination cursor.",maxLength:2e3,minLength:1,type:"string"},limit:{description:"Maximum transcript rows.",maximum:100,minimum:1,type:"number"},maxOutputChars:{description:"Maximum output characters per row.",maximum:2e4,minimum:100,type:"number"}},required:["chat"],type:"object"}},{capabilityId:"chat.read",name:"rudder_chat_read",description:"Read a bounded recent-message snapshot for one chat with page cursors.",semanticDescription:"Read a bounded recent-message snapshot for one chat with page cursors. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read a bounded recent-message snapshot for one chat with page cursors"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{chat:{description:"Chat conversation UUID or short reference.",maxLength:200,minLength:1,type:"string"},cursor:{description:"Opaque pagination cursor.",maxLength:2e3,minLength:1,type:"string"},includeOutput:{description:"Compatibility alias for includeTranscript.",type:"boolean"},includeTranscript:{description:"Include bounded transcript data.",type:"boolean"},limit:{description:"Maximum message rows.",maximum:100,minimum:1,type:"number"},maxOutputChars:{description:"Maximum output characters per row.",maximum:2e4,minimum:100,type:"number"},turnLimit:{description:"Maximum transcript turns.",maximum:100,minimum:1,type:"number"}},required:["chat"],type:"object"}},{capabilityId:"chat.create",name:"rudder_chat_create",description:"Create a chat conversation with its first message.",semanticDescription:"Create a chat conversation with its first message. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Create a chat conversation with its first message"},mutating:!0,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{body:{description:"Initial agent-authored chat message.",maxLength:5e5,minLength:1,type:"string"},issueCreationMode:{description:"Issue creation mode.",maxLength:100,minLength:1,type:"string"},payload:{description:"JSON payload object or JSON string.",type:["object","string"]},planMode:{description:"Start the chat in plan mode.",type:"boolean"},preferredAgentId:{description:"Preferred responding agent id.",maxLength:200,minLength:1,type:"string"},summary:{description:"Chat summary.",maxLength:1e4,minLength:1,type:"string"},title:{description:"Chat title.",maxLength:500,minLength:1,type:"string"}},required:["body"],type:"object"}},{capabilityId:"chat.send",name:"rudder_chat_send",description:"Send an agent-authored message directly to the operator in a chat.",semanticDescription:"Send an agent-authored message directly to the operator in a chat. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Send an agent-authored message directly to the operator in a chat"},mutating:!0,requiresOrgId:!1,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{body:{description:"Agent-authored chat message.",maxLength:5e5,minLength:1,type:"string"},chat:{description:"Chat conversation UUID or short reference.",maxLength:200,minLength:1,type:"string"},editUserMessageId:{description:"User message id to edit.",maxLength:200,minLength:1,type:"string"}},required:["chat","body"],type:"object"}},{capabilityId:"chat.archive",name:"rudder_chat_archive",description:"Archive a chat conversation without deleting it.",semanticDescription:"Archive a chat conversation without deleting it. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!0,idempotentHint:!1,readOnlyHint:!1,title:"Archive a chat conversation without deleting it"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{chat:{description:"Chat conversation UUID or short reference.",maxLength:200,minLength:1,type:"string"}},required:["chat"],type:"object"}},{capabilityId:"runs.list",name:"rudder_runs_list",description:"List lightweight run summaries with stable pagination and filters; use --full only for legacy full-row compatibility.",semanticDescription:"List lightweight run summaries with stable pagination and filters; use --full only for legacy full-row compatibility. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List lightweight run summaries with stable pagination and filters"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{createdBefore:{description:"Only runs created before this timestamp.",maxLength:100,minLength:1,type:"string"},cursor:{description:"Opaque pagination cursor.",maxLength:2e3,minLength:1,type:"string"},issueId:{description:"Linked issue id filter.",maxLength:200,minLength:1,type:"string"},limit:{description:"Summary page size.",maximum:100,minimum:1,type:"number"},loadedSkill:{description:"Loaded skill filter.",maxLength:500,minLength:1,type:"string"},relatedAgentId:{description:"Agent id filter.",maxLength:200,minLength:1,type:"string"},runIdPrefix:{description:"Run id prefix filter.",maxLength:200,minLength:1,type:"string"},runtime:{description:"Runtime type filter.",maxLength:100,minLength:1,type:"string"},status:{description:"Run status filter.",maxLength:100,minLength:1,type:"string"},updatedAfter:{description:"Only runs updated after this timestamp.",maxLength:100,minLength:1,type:"string"},usedSkill:{description:"Used skill filter.",maxLength:500,minLength:1,type:"string"}},type:"object"}},{capabilityId:"runs.by-skill",name:"rudder_runs_by_skill",description:"Build a paginated skill evidence packet from lightweight run summaries; use --full only for legacy full-row compatibility.",semanticDescription:"Build a paginated skill evidence packet from lightweight run summaries; use --full only for legacy full-row compatibility. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Build a paginated skill evidence packet from lightweight run summaries"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{createdBefore:{description:"Only runs created before this timestamp.",maxLength:100,minLength:1,type:"string"},cursor:{description:"Opaque pagination cursor.",maxLength:2e3,minLength:1,type:"string"},evidence:{description:"Skill evidence type.",enum:["used","loaded"],maxLength:20,minLength:1,type:"string"},issueId:{description:"Linked issue id filter.",maxLength:200,minLength:1,type:"string"},limit:{description:"Summary page size.",maximum:100,minimum:1,type:"number"},relatedAgentId:{description:"Agent id filter.",maxLength:200,minLength:1,type:"string"},runtime:{description:"Runtime type filter.",maxLength:100,minLength:1,type:"string"},skill:{description:"Skill key or display name.",maxLength:500,minLength:1,type:"string"},status:{description:"Run status filter.",maxLength:100,minLength:1,type:"string"}},required:["skill"],type:"object"}},{capabilityId:"runs.get",name:"rudder_runs_get",description:"Read one bounded run summary; use --full only from a direct trusted CLI for raw detail.",semanticDescription:"Read one bounded run summary; use --full only from a direct trusted CLI for raw detail. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read one bounded run summary"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{run:{description:"Run UUID, typed short reference (run_<prefix>), or legacy bare short prefix.",maxLength:200,minLength:1,type:"string"}},required:["run"],type:"object"}},{capabilityId:"runs.events",name:"rudder_runs_events",description:"List a bounded page of persisted run events with a lossless opaque cursor and clipped payload previews.",semanticDescription:"List a bounded page of persisted run events with a lossless opaque cursor and clipped payload previews. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List a bounded page of persisted run events with a lossless opaque cursor and clipped payload previews"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{afterSeq:{description:"Legacy sequence-only cursor.",maximum:1e7,minimum:0,type:"number"},cursor:{description:"Opaque pagination cursor.",maxLength:2e3,minLength:1,type:"string"},limit:{description:"Event page size.",maximum:500,minimum:1,type:"number"},maxChars:{description:"Maximum preview characters per event.",maximum:2e4,minimum:100,type:"number"},run:{description:"Run UUID, typed short reference (run_<prefix>), or legacy bare short prefix.",maxLength:200,minLength:1,type:"string"}},required:["run"],type:"object"}},{capabilityId:"runs.log",name:"rudder_runs_log",description:"Read a bounded byte range of stored run log content.",semanticDescription:"Read a bounded byte range of stored run log content. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read a bounded byte range of stored run log content"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{limitBytes:{description:"Maximum bytes for ranged read.",maximum:1e6,minimum:1,type:"number"},maxChars:{description:"Maximum displayed log characters.",maximum:1e5,minimum:100,type:"number"},offset:{description:"Byte offset for ranged read.",maximum:1e9,minimum:0,type:"number"},run:{description:"Run UUID, typed short reference (run_<prefix>), or legacy bare short prefix.",maxLength:200,minLength:1,type:"string"}},required:["run"],type:"object"}},{capabilityId:"runs.transcript",name:"rudder_runs_transcript",description:"Read a compact server-normalized transcript; --json changes encoding only and --full is direct-CLI-only raw access.",semanticDescription:"Read a compact server-normalized transcript; --json changes encoding only and --full is direct-CLI-only raw access. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read a compact server-normalized transcript"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{aroundError:{description:"Transcript error step id.",maxLength:200,minLength:1,type:"string"},chronological:{description:"Return oldest-first rows.",type:"boolean"},contextTurns:{description:"Turns around the selected error.",maximum:20,minimum:1,type:"number"},cursor:{description:"Opaque pagination cursor.",maxLength:2e3,minLength:1,type:"string"},errorsOnly:{description:"Return only error rows.",type:"boolean"},includeOutput:{description:"Include clipped row output.",type:"boolean"},maxChars:{description:"Maximum output characters per row.",maximum:2e4,minimum:100,type:"number"},narrative:{description:"Use narrative row formatting.",type:"boolean"},run:{description:"Run UUID, typed short reference (run_<prefix>), or legacy bare short prefix.",maxLength:200,minLength:1,type:"string"},turnLimit:{description:"Maximum turns.",maximum:100,minimum:1,type:"number"}},required:["run"],type:"object"}},{capabilityId:"runs.errors",name:"rudder_runs_errors",description:"List failed tool calls, stderr, runtime failures, and jump-to-context commands.",semanticDescription:"List failed tool calls, stderr, runtime failures, and jump-to-context commands. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List failed tool calls, stderr, runtime failures, and jump-to-context commands"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{cursor:{description:"Opaque pagination cursor.",maxLength:2e3,minLength:1,type:"string"},maxChars:{description:"Maximum output characters per error.",maximum:2e4,minimum:100,type:"number"},run:{description:"Run UUID, typed short reference (run_<prefix>), or legacy bare short prefix.",maxLength:200,minLength:1,type:"string"}},required:["run"],type:"object"}},{capabilityId:"runs.cancel",name:"rudder_runs_cancel",description:"Cancel a heartbeat run through the governed server route.",semanticDescription:"Cancel a heartbeat run through the governed server route. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!0,idempotentHint:!1,readOnlyHint:!1,title:"Cancel a heartbeat run through the governed server route"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{run:{description:"Run UUID, typed short reference (run_<prefix>), or legacy bare short prefix.",maxLength:200,minLength:1,type:"string"}},required:["run"],type:"object"}},{capabilityId:"runs.retry",name:"rudder_runs_retry",description:"Retry a failed, timed out, or cancelled run through the governed server route.",semanticDescription:"Retry a failed, timed out, or cancelled run through the governed server route. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Retry a failed, timed out, or cancelled run through the governed server route"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{run:{description:"Run UUID, typed short reference (run_<prefix>), or legacy bare short prefix.",maxLength:200,minLength:1,type:"string"}},required:["run"],type:"object"}},{capabilityId:"runs.create",name:"rudder_runs_create",description:"Create an independently governed Delegation Run for the current or another same-organization Agent.",semanticDescription:"Create an independently governed Delegation Run for the current or another same-organization Agent. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!1,title:"Create an independently governed Delegation Run"},mutating:!0,requiresOrgId:!1,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{idempotencyKey:{description:"Required stable key for safe replay.",maxLength:500,minLength:1,type:"string"},targetAgentId:{description:"Optional same-organization target Agent id.",maxLength:200,minLength:1,type:"string"},task:{description:"Delegation task to run independently.",maxLength:2e4,minLength:1,type:"string"}},required:["task","idempotencyKey"],type:"object"}}],DOn=[{capabilityId:"agent.me",name:"rudder_agent_me",description:"Show the authenticated agent identity and budget.",semanticDescription:"Show the authenticated agent identity and budget. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Show the authenticated agent identity and budget"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{},type:"object"}},{capabilityId:"agent.inbox",name:"rudder_agent_inbox",description:"List the compact assignee and reviewer work inbox for the authenticated agent.",semanticDescription:"List the compact assignee and reviewer work inbox for the authenticated agent. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List the compact assignee and reviewer work inbox for the authenticated agent"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{},type:"object"}},{capabilityId:"organization.members.list",name:"rudder_organization_members_list",description:"List active visible human and agent members in the authenticated organization.",semanticDescription:"List active visible human and agent members in the authenticated organization. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List active visible human and agent members in the authenticated organization"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{cursor:{description:"Opaque pagination cursor.",maxLength:2e3,minLength:1,type:"string"},limit:{description:"Page size.",maximum:100,minimum:1,type:"number"},query:{description:"Optional member name filter.",maxLength:2e3,minLength:1,type:"string"},type:{description:"Member type filter.",enum:["human","agent","all"],maxLength:10,minLength:1,type:"string"}},type:"object"}},{capabilityId:"organization.brand_color.update",name:"rudder_organization_brand_color_update",description:"Update the authenticated organization's brand color.",semanticDescription:"Update the authenticated organization's brand color. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!1,title:"Update the authenticated organization's brand color"},mutating:!0,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{brandColor:{description:"Hex brand color, for example #123456.",maxLength:7,minLength:7,type:"string"},idempotencyKey:{description:"Required stable key for safe replay.",maxLength:255,minLength:1,type:"string"}},required:["brandColor","idempotencyKey"],type:"object"}},{capabilityId:"agent.capabilities",name:"rudder_agent_capabilities",description:"List the stable Rudder agent command contract.",semanticDescription:"List the stable Rudder agent command contract. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List the stable Rudder agent command contract"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{},type:"object"}},{capabilityId:"agent.update",name:"rudder_agent_update",description:"Update an agent's identity fields; defaults to the authenticated agent.",semanticDescription:"Update an agent's identity fields; defaults to the authenticated agent. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Update an agent's identity fields"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{capabilities:{description:"Agent capability summary.",maxLength:1e5,minLength:1,type:"string"},clearCapabilities:{description:"Clear the current capability summary.",type:"boolean"},clearDescription:{description:"Compatibility alias for clearCapabilities.",type:"boolean"},clearTitle:{description:"Clear the current title.",type:"boolean"},description:{description:"Compatibility alias for capabilities.",maxLength:1e5,minLength:1,type:"string"},name:{description:"Agent name.",maxLength:200,minLength:1,type:"string"},role:{description:"Agent role.",maxLength:100,minLength:1,type:"string"},title:{description:"Agent title.",maxLength:300,minLength:1,type:"string"}},type:"object"}},{capabilityId:"agent.skills.create",name:"rudder_agent_skills_create",description:"Create an agent-private skill package under AGENT_HOME/skills.",semanticDescription:"Create an agent-private skill package under AGENT_HOME/skills. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Create an agent-private skill package under AGENT_HOME/skills"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{body:{description:"Compatibility alias for markdown.",maxLength:5e5,minLength:1,type:"string"},description:{description:"Skill description.",maxLength:1e5,minLength:1,type:"string"},enable:{description:"Enable the created skill for the runtime agent.",type:"boolean"},markdown:{description:"SKILL.md content.",maxLength:5e5,minLength:1,type:"string"},name:{description:"Skill display name.",maxLength:200,minLength:1,type:"string"},slug:{description:"Skill slug.",maxLength:200,minLength:1,type:"string"}},required:["name"],type:"object"}},{capabilityId:"agent.skills.enable",name:"rudder_agent_skills_enable",description:"Add skill selections to an agent without replacing existing enabled skills.",semanticDescription:"Add skill selections to an agent without replacing existing enabled skills. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Add skill selections to an agent without replacing existing enabled skills"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{selectionRefs:{description:"Skill selection references.",items:{description:"Skill selection references.",maxLength:8192,minLength:1,type:"string"},maxItems:100,type:"array"}},required:["selectionRefs"],type:"object"}},{capabilityId:"agent.skills.sync",name:"rudder_agent_skills_sync",description:"Sync the desired enabled skill set for an agent.",semanticDescription:"Sync the desired enabled skill set for an agent. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!0,idempotentHint:!1,readOnlyHint:!1,title:"Sync the desired enabled skill set for an agent"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{desiredSkills:{description:"Comma-separated desired skill references.",maxLength:2e4,minLength:1,type:"string"}},required:["desiredSkills"],type:"object"}},{capabilityId:"goal.list",name:"rudder_goal_list",description:"Discover Goals owned by the authenticated Agent; defaults to active Goals and returns current progress, next step, and attention state.",semanticDescription:"Discover Goals owned by the authenticated Agent; defaults to active Goals and returns current progress, next step, and attention state. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Discover Goals owned by the authenticated Agent"},mutating:!1,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{facet:{description:"Current Goal workspace facet.",enum:["agent_advancing","needs_attention","waiting_focus","waiting_external","ready_for_acceptance","closed"],maxLength:40,minLength:1,type:"string"},focus:{description:"Filter by whether the Goal is the organization Focus Goal.",type:"boolean"},lifecycle:{description:"Goal lifecycle filter; active is the safe default.",enum:["draft","active","closed","all"],maxLength:20,minLength:1,type:"string"},limit:{description:"Maximum owned Goals to return.",maximum:100,minimum:1,type:"number"}},type:"object"}},{capabilityId:"goal.context",name:"rudder_goal_context",description:"Read the owned Goal agreement and current operating context before acting: contract revision, criteria, boundaries, progress, next step, attention, proposals, and recent feedback.",semanticDescription:"Read the owned Goal agreement and current operating context before acting: contract revision, criteria, boundaries, progress, next step, attention, proposals, and recent feedback. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: required from runtime env. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read the owned Goal agreement and current operating context before acting: contract revision, criteria, boundaries, progress, next step, attention, proposals, and recent feedback"},mutating:!1,requiresOrgId:!1,requiresAgentId:!0,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{goal:{description:"Goal UUID returned by rudder_goal_list.",maxLength:200,minLength:1,type:"string"}},required:["goal"],type:"object"}},{capabilityId:"goal.progress",name:"rudder_goal_progress",description:"Record evidence-backed progress for a Goal owned by the authenticated Agent and attribute it to the current Run.",semanticDescription:"Record evidence-backed progress for a Goal owned by the authenticated Agent and attribute it to the current Run. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Record evidence-backed progress for a Goal owned by the authenticated Agent and attribute it to the current Run"},mutating:!0,requiresOrgId:!1,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{activityKind:{description:"Progress classification.",enum:["progress","evidence","bottleneck"],maxLength:30,minLength:1,type:"string"},evidenceRefs:{description:"URI-like references to artifacts, measurements, or other supporting evidence.",items:{description:"URI-like evidence reference.",maxLength:8192,minLength:1,type:"string"},maxItems:100,minItems:1,type:"array"},goal:{description:"Goal UUID or typed short reference (gol_<prefix>) from the current Goal Runtime Context.",maxLength:200,minLength:1,type:"string"},idempotencyKey:{description:"Stable key for safe retry.",maxLength:500,minLength:1,type:"string"},summary:{description:"Plain-language progress, observed change, or named blocker.",maxLength:1e5,minLength:1,type:"string"}},required:["goal","summary","evidenceRefs","idempotencyKey"],type:"object"}},{capabilityId:"goal.checkpoint",name:"rudder_goal_checkpoint",description:"Atomically persist a Goal checkpoint, optional Plan revision, continuation, checkpoint activity, and eligible automatic continuation wake.",semanticDescription:"Atomically persist a Goal checkpoint, optional Plan revision, continuation, checkpoint activity, and eligible automatic continuation wake. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Atomically persist a Goal checkpoint, optional Plan revision, continuation, checkpoint activity, and eligible automatic continuation wake"},mutating:!0,requiresOrgId:!1,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{continuation:{additionalProperties:!1,properties:{kind:{description:"Continuation policy.",enum:["commitment","wait","decision","verification"],maxLength:1e5,minLength:1,type:"string"},summary:{description:"What should happen next or what is awaited.",maxLength:1e5,minLength:1,type:"string"},wakeCondition:{oneOf:[{minLength:1,type:"string"},{type:"null"}]}},required:["kind","summary"],type:"object"},evidenceRefs:{description:"URI-like references to artifacts, measurements, or other supporting evidence.",items:{description:"URI-like evidence reference.",maxLength:8192,minLength:1,type:"string"},maxItems:100,type:"array"},expectedPlanRevision:{description:"Plan revision read before this checkpoint.",maximum:1e9,minimum:1,type:"number"},goal:{description:"Goal UUID or typed short reference (gol_<prefix>) from the current Goal Runtime Context.",maxLength:200,minLength:1,type:"string"},idempotencyKey:{description:"Stable key for safe retry.",maxLength:500,minLength:1,type:"string"},plan:{additionalProperties:!1,description:"Optional complete next Plan revision; omit when the current Plan remains valid.",properties:{budgetAllocations:{additionalProperties:!0,type:"object"},hypotheses:{items:{},maxItems:1e3,type:"array"},invalidationConditions:{items:{},maxItems:1e3,type:"array"},rejectedPaths:{items:{},maxItems:1e3,type:"array"},selectedPaths:{items:{},maxItems:1e3,type:"array"},sequencing:{items:{},maxItems:1e3,type:"array"},summary:{description:"Plan summary.",maxLength:1e5,minLength:1,type:"string"}},required:["summary"],type:"object"},summary:{description:"Plain-language bounded-run checkpoint summary.",maxLength:1e5,minLength:1,type:"string"}},required:["goal","summary","evidenceRefs","expectedPlanRevision","continuation","idempotencyKey"],type:"object"}},{capabilityId:"goal.change.propose",name:"rudder_goal_change_propose",description:"Propose a reviewable change to the current Goal contract when evidence shows its outcome, criteria, boundaries, or deadlines should change.",semanticDescription:"Propose a reviewable change to the current Goal contract when evidence shows its outcome, criteria, boundaries, or deadlines should change. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Propose a reviewable change to the current Goal contract when evidence shows its outcome, criteria, boundaries, or deadlines should change"},mutating:!0,requiresOrgId:!1,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{afterContract:{additionalProperties:!1,description:"Only the Goal contract fields that should change.",minProperties:1,properties:{actionDeadline:{description:"Proposed ISO-8601 action deadline, or null to clear it.",oneOf:[{format:"date-time",type:"string"},{type:"null"}]},autonomyEnvelope:{additionalProperties:!0,type:"object"},criteria:{items:{additionalProperties:!1,properties:{evaluator:{description:"Criterion evaluator.",enum:["artifact","metric","policy","human"],maxLength:20,minLength:1,type:"string"},evidenceRequirements:{items:{description:"URI-like required evidence reference.",maxLength:8192,minLength:1,type:"string"},maxItems:100,type:"array"},id:{description:"Stable criterion id.",maxLength:500,minLength:1,type:"string"},label:{description:"Plain-language success criterion.",maxLength:1e5,minLength:1,type:"string"}},required:["id","label","evaluator"],type:"object"},maxItems:100,minItems:1,type:"array"},evaluationDeadline:{description:"Proposed ISO-8601 evaluation deadline, or null to clear it.",oneOf:[{format:"date-time",type:"string"},{type:"null"}]},evaluationPolicy:{additionalProperties:!0,type:"object"},humanAuthorities:{additionalProperties:!0,type:"object"},objectiveMode:{description:"Proposed objective mode.",enum:["target","maximize","maintain","decide"],maxLength:20,minLength:1,type:"string"},outcomeStatement:{description:"Proposed result-oriented outcome.",maxLength:1e5,minLength:1,type:"string"}},type:"object"},contractRevision:{description:"Current Goal contract revision.",maximum:1e9,minimum:1,type:"number"},evidenceRefs:{description:"URI-like references supporting the proposed change.",items:{description:"URI-like evidence reference.",maxLength:8192,minLength:1,type:"string"},maxItems:100,type:"array"},goal:{description:"Goal UUID or typed short reference (gol_<prefix>) from the current Goal Runtime Context.",maxLength:200,minLength:1,type:"string"},idempotencyKey:{description:"Stable key for safe retry.",maxLength:500,minLength:1,type:"string"},rationale:{description:"Why the current contract should change and what evidence invalidated it.",maxLength:1e5,minLength:1,type:"string"}},required:["goal","contractRevision","afterContract","rationale","idempotencyKey"],type:"object"}},{capabilityId:"goal.result.propose",name:"rudder_goal_result_propose",description:"Submit an evidence-backed Goal result for mandatory human acceptance without closing the Goal.",semanticDescription:"Submit an evidence-backed Goal result for mandatory human acceptance without closing the Goal. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Submit an evidence-backed Goal result for mandatory human acceptance without closing the Goal"},mutating:!0,requiresOrgId:!1,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{contractRevision:{description:"Current Goal contract revision.",maximum:1e9,minimum:1,type:"number"},criteria:{description:"Criterion outcomes for the current contract revision.",items:{additionalProperties:!1,properties:{id:{description:"Criterion id from the Goal Runtime Context.",maxLength:500,minLength:1,type:"string"},status:{description:"Observed criterion status.",enum:["met","unmet","breached","unknown"],maxLength:20,minLength:1,type:"string"}},required:["id","status"],type:"object"},maxItems:100,minItems:1,type:"array"},decision:{description:"Optional decision reached for decide-mode Goals.",maxLength:1e5,minLength:1,type:"string"},evidenceRefs:{description:"URI-like references supporting the proposed result.",items:{description:"URI-like evidence reference.",maxLength:8192,minLength:1,type:"string"},maxItems:100,minItems:1,type:"array"},goal:{description:"Goal UUID or typed short reference (gol_<prefix>) from the current Goal Runtime Context.",maxLength:200,minLength:1,type:"string"},idempotencyKey:{description:"Stable key for safe retry.",maxLength:500,minLength:1,type:"string"},resultPayload:{additionalProperties:!0,description:"Optional structured result details.",type:"object"},resultValue:{description:"Optional measured result value.",oneOf:[{maxLength:1e5,type:"string"},{type:"number"},{type:"boolean"}]},riskSummary:{description:"Known risks, limitations, or remaining gaps.",maxLength:1e5,minLength:1,type:"string"}},required:["goal","contractRevision","criteria","evidenceRefs","riskSummary","idempotencyKey"],type:"object"}},{capabilityId:"issue.get",name:"rudder_issue_get",description:"Read a full issue by UUID or identifier.",semanticDescription:"Read a full issue by UUID or identifier. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read a full issue by UUID or identifier"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{issue:{description:"Issue UUID, identifier, or short reference.",maxLength:200,minLength:1,type:"string"}},required:["issue"],type:"object"}},{capabilityId:"issue.list",name:"rudder_issue_list",description:"List issues with optional status, assignee, and project filters without requiring a search query.",semanticDescription:"List issues with optional status, assignee, and project filters without requiring a search query. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List issues with optional status, assignee, and project filters without requiring a search query"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{assigneeAgentId:{description:"Assignee agent id or reference.",maxLength:200,minLength:1,type:"string"},projectId:{description:"Project id or reference.",maxLength:200,minLength:1,type:"string"},status:{description:"Comma-separated issue statuses.",maxLength:500,minLength:1,type:"string"}},type:"object"}},{capabilityId:"issue.search",name:"rudder_issue_search",description:"Search issues with the server-side issue index across title, identifier, description, and comments.",semanticDescription:"Search issues with the server-side issue index across title, identifier, description, and comments. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Search issues with the server-side issue index across title, identifier, description, and comments"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{assigneeAgentId:{description:"Assignee agent id or reference.",maxLength:200,minLength:1,type:"string"},projectId:{description:"Project id or reference.",maxLength:200,minLength:1,type:"string"},query:{description:"Non-empty server-side issue search query.",maxLength:2e3,minLength:1,type:"string"},status:{description:"Comma-separated issue statuses.",maxLength:500,minLength:1,type:"string"}},required:["query"],type:"object"}},{capabilityId:"issue.context",name:"rudder_issue_context",description:"Read the compact heartbeat context for an issue; wake comments may be addressed by full id or cmt_<uuid-prefix>.",semanticDescription:"Read the compact heartbeat context for an issue; wake comments may be addressed by full id or cmt_<uuid-prefix>. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read the compact heartbeat context for an issue"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{issue:{description:"Issue UUID, identifier, or short reference.",maxLength:200,minLength:1,type:"string"},wakeCommentId:{description:"Wake comment id or short reference.",maxLength:200,minLength:1,type:"string"}},required:["issue"],type:"object"}},{capabilityId:"issue.checkout",name:"rudder_issue_checkout",description:"Atomically checkout an issue for the current or specified agent.",semanticDescription:"Atomically checkout an issue for the current or specified agent. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Atomically checkout an issue for the current or specified agent"},mutating:!0,requiresOrgId:!1,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{expectedStatuses:{description:"Comma-separated allowed prior statuses.",maxLength:500,minLength:1,type:"string"},issue:{description:"Issue UUID, identifier, or short reference.",maxLength:200,minLength:1,type:"string"}},required:["issue"],type:"object"}},...POn,...TOn,..._On,...MOn,...EOn],ROn=DOn;function LOn(e){return{name:e.name,description:e.semanticDescription??e.description,inputSchema:e.inputSchema,annotations:e.annotations}}const hut=ROn.map(LOn),zOn=hut.filter(e=>!e.name.startsWith("rudder_browser_")),$On=hut.filter(e=>e.name.startsWith("rudder_browser_"));zOn.map(e=>e.name);$On.map(e=>e.name);function put(e,t){if((t.kind==="thinking"||t.kind==="assistant")&&t.delta){const n=e.length-1,r=e[n],s=(r==null?void 0:r.kind)!=="assistant"||t.kind!=="assistant"||r.phase===void 0||t.phase===void 0||r.phase===t.phase,a=r&&(r.kind==="thinking"||r.kind==="assistant")&&(r.segmentId||t.segmentId)?!!(r.segmentId&&t.segmentId&&r.segmentId===t.segmentId):!0;if(r&&r.kind===t.kind&&r.delta&&s&&a){e[n]={...r,text:r.text+t.text,ts:t.ts,...r.kind==="assistant"&&t.kind==="assistant"&&(r.phase??t.phase)?{phase:r.phase??t.phase}:{}};return}}e.push(t)}function gut(e,t){for(const n of t)put(e,n)}function xut(){return{stdoutBuffer:"",lastStdoutTs:null}}function but(e,t,n,r,s){const a={enabled:(s==null?void 0:s.censorUsernameInLogs)??!1};if(n.stream==="stderr"){e.push({kind:"stderr",ts:n.ts,text:dA(n.chunk,a)});return}if(n.stream==="system"){e.push({kind:"system",ts:n.ts,text:dA(n.chunk,a)});return}t.lastStdoutTs=n.ts;const l=(t.stdoutBuffer+n.chunk).split(/\r?\n/);t.stdoutBuffer=l.pop()??"";for(const c of l){const d=c.trim();d&&gut(e,r(d,n.ts).map(u=>u2e(u,a)))}}function yut(e,t,n,r){const s=t.stdoutBuffer.trim();if(!s)return;const a={enabled:(r==null?void 0:r.censorUsernameInLogs)??!1};gut(e,n(s,t.lastStdoutTs??new Date().toISOString()).map(o=>u2e(o,a))),t.stdoutBuffer=""}function FOn(e,t,n){const r=[],s=xut();for(const a of e)but(r,s,a,t,n);return yut(r,s,t,n),r}const BOn=250,vp="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",Yre=[250,500,1e3,2e3,5e3],Jre=5,QOn=10,nw=40,OPe=50,UOn=5,qOn=5*6e4,VOn=30*6e4;function WOn(e){const t=(e==null?void 0:e.trim())??"";return/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(t)?`local-app-recovery:${t}`:null}const HOn=new Set(["accepted_current","reconciled_current","continuation_pending","running_next","delivered","completed","steered"]),KOn=new Set(["accepted_current","reconciled_current","continuation_pending","running_next","delivered"]);function mfe(e,t=!1){return!!(e.sourceMessageId||e.deliveredMessageId||e.continuationMessageId)||HOn.has(e.status)||e.deliveryDisposition!==null&&KOn.has(e.deliveryDisposition)||e.status==="cancelled"?{state:"hidden"}:t?{state:"sending",label:"Sending…"}:e.status==="queued"?{state:"queued",label:"Queued"}:e.status==="failed_actionable"?{state:"failed",label:"Couldn't send"}:{state:"sending",label:"Sending…"}}const ZOn=new Set(["starting","active","running","tool_busy","closing","waiting_for_network","stop_requested","stopping"]),XOn=new Set(["queued","steer_pending","accepted_current","acceptance_unknown","reconciled_current","continuation_pending","running_next","dequeue_claimed","running","steered"]);function RC(e){return e!=null&&e.activeGenerationId&&(e.activeGenerationStatus===null||ZOn.has(e.activeGenerationStatus))?e.activeGenerationId:null}function GOn(e){return e?RC(e)!==null||e.items.some(t=>XOn.has(t.status)&&mfe(t).state!=="hidden"):!1}function SPe(e){return`${e.name.trim()}\0${e.type.trim().toLowerCase()}\0${e.size}`}function ese(e){return(e==null?void 0:e.mutability)==="external_bound_chat"}function LW(e,t,n){if(!e||e.streamKey!==t||!["streaming","tool_busy","finalizing","waiting_for_network"].includes(e.state))return e;const r="generationId"in n?n.generationId:void 0,s="attemptEpoch"in n?n.attemptEpoch:void 0,a="generationSeq"in n?n.generationSeq:void 0;if(e.generationId&&r&&e.generationId!==r||e.attemptEpoch!==null&&e.attemptEpoch!==void 0&&s!==void 0&&s<e.attemptEpoch||!(n.type==="assistant_state"||n.type==="waiting_for_network")&&a!==void 0&&e.lastCommittedRenderSeq!==void 0&&a<=e.lastCommittedRenderSeq)return e;if(n.type==="assistant_delta")return{...e,body:`${e.body}${n.delta}`,generationId:n.generationId??e.generationId??null,attemptEpoch:n.attemptEpoch??e.attemptEpoch??null,lastCommittedRenderSeq:n.generationSeq??e.lastCommittedRenderSeq??0,renderedBodyHash:n.bodyHash??e.renderedBodyHash??vp};if(n.type==="assistant_state"){const c=n.state==="tool_busy"?"tool_busy":n.state;return{...e,state:c,generationId:r??e.generationId??null,attemptEpoch:s??e.attemptEpoch??null,lastCommittedRenderSeq:a??e.lastCommittedRenderSeq??0}}if(n.type==="waiting_for_network")return{...e,state:"waiting_for_network",generationId:n.generationId??e.generationId??null,attemptEpoch:n.attemptEpoch??e.attemptEpoch??null,lastCommittedRenderSeq:n.generationSeq??e.lastCommittedRenderSeq??0,renderedBodyHash:n.bodyHash??e.renderedBodyHash??vp};const l=[...e.transcript];return put(l,n.entry),{...e,transcript:l,generationId:n.generationId??e.generationId??null,attemptEpoch:n.attemptEpoch??e.attemptEpoch??null,lastCommittedRenderSeq:n.generationSeq??e.lastCommittedRenderSeq??0,renderedBodyHash:n.bodyHash??e.renderedBodyHash??vp}}function YOn(e){return e.replace(/\\/g,"\\\\").replace(/]/g,"\\]")}function JOn(e){return`[${YOn(C6(e).trim()||"Chat")}](${aN(e.id)})`}function eSn(e){try{const t=new URL(e,"http://rudder.local");let n="";if(t.protocol==="chat:")n=`${t.hostname}${t.pathname}`.replace(/^\/+/,"").trim();else if(t.origin==="http://rudder.local"){const s=t.pathname.match(/^\/(?:(?:messenger\/)?chat\/([^/]+)|[^/]+\/messenger\/chat\/([^/]+))\/?$/),a=(s==null?void 0:s[1])??(s==null?void 0:s[2])??"";try{n=decodeURIComponent(a).trim()}catch{n=a.trim()}}const r=(t.searchParams.get("messageId")??t.searchParams.get("targetMessageId")??"").trim();return n?{conversationId:n,messageId:r||null}:null}catch{return null}}function tse(e,t,n){const r=n?{...n,...n.attachmentIds?{attachmentIds:[...n.attachmentIds]}:{},...n.attachmentFileIndexes?{attachmentFileIndexes:[...n.attachmentFileIndexes]}:{}}:null;return{kind:"side_chat",sourceConversationId:e.id,sourceMessageId:t.id,sourcePreview:(r==null?void 0:r.selectedText)??t.body,...r?{inlineAnnotations:[r]}:{},conversationId:null,clientMutationId:crypto.randomUUID(),label:"Side Chat"}}function nse(e,t){return Array.from(e.querySelectorAll("[data-message-id]")).find(n=>n.dataset.messageId===t)??null}function tSn(e){return e.querySelector("[data-message-highlight-target='true']")??e}function vut(){return typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth"}function wut(e){e.classList.remove("chat-message-jump-highlight"),e.offsetWidth,e.classList.add("chat-message-jump-highlight"),window.setTimeout(()=>e.classList.remove("chat-message-jump-highlight"),1800)}function rse(e){const t=tSn(e);e.scrollIntoView({block:"center",behavior:vut()}),e.classList.remove("chat-message-jump-highlight"),wut(t)}function nSn(e){e.scrollIntoView({block:"center",behavior:vut()}),wut(e)}function rSn(e){const t=Ve({queryKey:U.chats.listPreview(e.selectedOrganizationId??"__none__","active",nw,e.activeProjectId),queryFn:()=>Zn.list(e.selectedOrganizationId,"active",{limit:nw,projectId:e.activeProjectId===e.noProjectId?void 0:e.activeProjectId}),enabled:!!e.selectedOrganizationId&&e.activeProjectId!==e.noProjectId});return{draftPreflightQuery:Ve({queryKey:["chats",e.selectedOrganizationId??"__none__","draft-preflight",e.activeAgentId??"__none__",e.modelOverride??"__agent_default__",e.effortOverride??"__agent_default__",e.activeProjectId,e.issueContextId??"__none__",e.planMode],queryFn:()=>Zn.preflightDraft(e.selectedOrganizationId,{preferredAgentId:e.activeAgentId,modelOverride:e.modelOverride,effortOverride:e.effortOverride,issueCreationMode:"manual_approval",planMode:e.planMode,contextLinks:e.contextLinks}),enabled:!e.selectedConversation&&!!e.selectedOrganizationId&&!!e.activeAgentId,retry:!1,staleTime:r=>{var s;return(s=r.state.data)!=null&&s.available?qOn:0},gcTime:VOn}),projectConversationsQuery:t}}function sSn(e){return e.newConversationSendInFlight||e.activeSendInFlight&&!e.hasActiveStream?"sending":e.stopRequestPending||e.streamStopping?"stopping":e.canQueueDraft?"queue":e.activeSendInFlight?"stop":e.canContinueInterruptedConversation&&!e.hasSubmittableDraft&&e.pendingFileCount===0?"continue":"send"}function iSn(e){return e.selectedConversationExternalBound||e.composerUnavailable||e.sendButtonMode==="sending"||e.sendButtonMode==="stopping"?!0:e.sendButtonMode==="continue"?e.modelSelectionPending:e.sendButtonMode==="send"||e.sendButtonMode==="queue"?e.modelSelectionPending||!e.hasDraft:!1}async function aSn(e){var n;const t=await Zn.createQueuedMessage(e.conversation.id,{clientMutationId:`ui:${Date.now()}:${Math.random().toString(36).slice(2)}`,expectedGenerationId:e.serverActiveGenerationId,payload:{body:e.body,...(n=e.inlineAnnotations)!=null&&n.length?{inlineAnnotations:e.inlineAnnotations}:{},attachmentIds:[],skillRefs:[],projectId:e.projectId,accessMode:null,model:e.modelOverride,effort:e.effortOverride,metadata:{source:"chat_composer"}}},{files:e.files});return e.queryClient.setQueryData(U.chats.queue(e.orgId,e.conversation.id),r=>{var s,a,o;return{activeGenerationId:(r==null?void 0:r.activeGenerationId)??e.serverActiveGenerationId,activeAttemptEpoch:(r==null?void 0:r.activeAttemptEpoch)??((s=e.queueSnapshot)==null?void 0:s.activeAttemptEpoch)??null,activeControlVersion:(r==null?void 0:r.activeControlVersion)??((a=e.queueSnapshot)==null?void 0:a.activeControlVersion)??null,activeGenerationStatus:(r==null?void 0:r.activeGenerationStatus)??((o=e.queueSnapshot)==null?void 0:o.activeGenerationStatus)??null,items:[...(r==null?void 0:r.items)??[],t]}}),t}function oSn(e){return!!(e.activeReply&&!e.newConversationSendInFlight&&e.pendingRegularFileCount===0&&(e.body.trim().length>0||e.annotationCount>0))}function lSn(e,t){const{inlineAnnotations:n,...r}=e;return{...r,body:t}}function VF(e){const t=e.dataTransfer;return t.files.length>0||Array.from(t.types??[]).includes("Files")||Array.from(t.items??[]).some(n=>n.kind==="file")}function f2e(e){const[t,n]=A.useState(!1),r=A.useRef(0),s=A.useCallback(c=>{VF(c)&&(c.preventDefault(),c.stopPropagation(),r.current+=1,n(!0))},[]),a=A.useCallback(c=>{VF(c)&&(c.preventDefault(),c.stopPropagation(),c.dataTransfer.dropEffect="copy")},[]),o=A.useCallback(c=>{r.current===0&&!VF(c)||(c.preventDefault(),c.stopPropagation(),r.current=Math.max(0,r.current-1),r.current===0&&n(!1))},[]),l=A.useCallback(c=>{r.current===0&&!VF(c)||(c.preventDefault(),c.stopPropagation(),r.current=0,n(!1),e(c.dataTransfer.files))},[e]);return{active:t,targetProps:{onDragEnter:s,onDragOver:a,onDragLeave:o,onDrop:l}}}function kut(e){return A.useCallback(t=>{const n=t.clipboardData,r=Array.from((n==null?void 0:n.items)??[]).filter(l=>l.kind==="file").map(l=>l.getAsFile()).filter(l=>l instanceof File),s=new Map;for(const l of r){const c=SPe(l);s.set(c,(s.get(c)??0)+1)}const a=Array.from((n==null?void 0:n.files)??[]).filter(l=>{const c=SPe(l),d=s.get(c)??0;return d<=0?!0:(d===1?s.delete(c):s.set(c,d-1),!1)}),o=[...r,...a];o.length!==0&&(t.preventDefault(),t.stopPropagation(),e(o))},[e])}function m2e(){return i.jsx("div",{"data-testid":"chat-composer-file-drop-overlay",role:"status","aria-live":"polite",className:"pointer-events-none absolute inset-0 z-20 flex items-center justify-center rounded-[inherit] border border-[color:color-mix(in_oklab,var(--accent-base)_55%,transparent)] bg-[color:color-mix(in_oklab,var(--surface-elevated)_88%,transparent)] backdrop-blur-[2px]",children:i.jsxs("div",{className:"flex items-center gap-2 rounded-[var(--radius-md)] bg-[color:var(--accent-soft)] px-3 py-2 text-sm font-medium text-foreground shadow-[var(--shadow-sm)]",children:[i.jsx(df,{className:"h-4 w-4 text-[color:var(--accent-base)]","aria-hidden":!0}),"Drop files to attach"]})})}function cSn({message:e,conversation:t,agents:n,canRetry:r,onRetry:s}){const a=wmt(e,t),o=a?n==null?void 0:n.find(u=>u.id===a.agentId):null,l=o?uw(o):a==null?void 0:a.agentId,c=typeof window>"u"?null:Zf(window.location.pathname),d=a?rc(`/agents/${l}/runs/${a.runId}`,c):null;return!d&&!r?null:i.jsxs("div",{className:"flex basis-full shrink-0 flex-wrap items-center justify-end gap-2 pl-7 sm:basis-auto sm:pl-0",children:[d?i.jsx(gn,{to:d,className:"inline-flex h-7 items-center rounded-md border border-border bg-background/70 px-2 text-xs font-medium text-foreground transition-colors hover:bg-background",children:"Open run"}):null,r?i.jsxs("button",{type:"button",className:"inline-flex h-7 items-center gap-1.5 rounded-md border border-destructive/30 bg-background/70 px-2 text-xs font-medium text-destructive transition-colors hover:bg-background",onClick:()=>s==null?void 0:s(e),children:[i.jsx(tf,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Retry"]}):null]})}function f1(e,t){const n=e==null?void 0:e[t];return typeof n=="string"&&n.trim().length>0?n.trim():null}function Out(e,t){var s,a,o;const n=/\[([^\]]+)\]\(chat:\/\/([^)]+)\)/g;let r;for(;(r=n.exec(e))!==null;){const l=(s=r[1])==null?void 0:s.trim(),c=(o=(a=r[2])==null?void 0:a.split(/[?#]/)[0])==null?void 0:o.trim();if(l&&c===t)return l}return null}function dSn(e){const t=e.structuredPayload;if(!t||t.eventType!=="chat_fork"&&t.type!=="chat_fork")return null;const n=f1(t,"sourceConversationId"),r=f1(t,"sourceMessageId");if(!n)return null;const s=f1(t,"sourceConversationTitle")??Out(e.body,n)??"source chat";return{sourceConversationId:n,sourceConversationTitle:s,sourceMessageId:r}}function uSn(e){const t=e.structuredPayload;if(!t||t.eventType!=="side_chat_started")return null;const n=f1(t,"sourceConversationId");if(!n)return null;const r=f1(t,"sourceConversationTitle")??Out(e.body,n)??"source chat";return{sourceConversationId:n,sourceConversationTitle:r}}const x3=0,dr=1,pi=2,kd=3,Nl=4,W1=5,$G=6,Mf=7,fA=8,Oa=9,Us=10,yc=11,ka=12,Oc=13,xL=14,mA=15,Wf=16,Hf=17,BA=18,Uh=19,Wp=20,oo=21,Ds=22,Pu=23,zh=24,cf=25,fSn=0;function sf(e){return e>=48&&e<=57}function s5(e){return sf(e)||e>=65&&e<=70||e>=97&&e<=102}function A2e(e){return e>=65&&e<=90}function mSn(e){return e>=97&&e<=122}function ASn(e){return A2e(e)||mSn(e)}function hSn(e){return e>=128}function zW(e){return ASn(e)||hSn(e)||e===95}function Sut(e){return zW(e)||sf(e)||e===45}function pSn(e){return e>=0&&e<=8||e===11||e>=14&&e<=31||e===127}function $W(e){return e===10||e===13||e===12}function Y6(e){return $W(e)||e===32||e===9}function c0(e,t){return!(e!==92||$W(t)||t===fSn)}function YQ(e,t,n){return e===45?zW(t)||t===45||c0(t,n):zW(e)?!0:e===92?c0(e,t):!1}function sse(e,t,n){return e===43||e===45?sf(t)?2:t===46&&sf(n)?3:0:e===46?sf(t)?2:0:sf(e)?1:0}function jut(e){return e===65279||e===65534?1:0}const Afe=new Array(128),gSn=128,JQ=130,Cut=131,h2e=132,Nut=133;for(let e=0;e<Afe.length;e++)Afe[e]=Y6(e)&&JQ||sf(e)&&Cut||zW(e)&&h2e||pSn(e)&&Nut||e||gSn;function ise(e){return e<128?Afe[e]:h2e}function US(e,t){return t<e.length?e.charCodeAt(t):0}function hfe(e,t,n){return n===13&&US(e,t+1)===10?2:1}function qS(e,t,n){let r=e.charCodeAt(t);return A2e(r)&&(r=r|32),r===n}function kE(e,t,n,r){if(n-t!==r.length||t<0||n>e.length)return!1;for(let s=t;s<n;s++){const a=r.charCodeAt(s-t);let o=e.charCodeAt(s);if(A2e(o)&&(o=o|32),o!==a)return!1}return!0}function xSn(e,t){for(;t>=0&&Y6(e.charCodeAt(t));t--);return t+1}function WF(e,t){for(;t<e.length&&Y6(e.charCodeAt(t));t++);return t}function ase(e,t){for(;t<e.length&&sf(e.charCodeAt(t));t++);return t}function LC(e,t){if(t+=2,s5(US(e,t-1))){for(const r=Math.min(e.length,t+5);t<r&&s5(US(e,t));t++);const n=US(e,t);Y6(n)&&(t+=hfe(e,t,n))}return t}function HF(e,t){for(;t<e.length;t++){const n=e.charCodeAt(t);if(!Sut(n)){if(c0(n,US(e,t+1))){t=LC(e,t)-1;continue}break}}return t}function FG(e,t){let n=e.charCodeAt(t);if((n===43||n===45)&&(n=e.charCodeAt(t+=1)),sf(n)&&(t=ase(e,t+1),n=e.charCodeAt(t)),n===46&&sf(e.charCodeAt(t+1))&&(t+=2,t=ase(e,t)),qS(e,t,101)){let r=0;n=e.charCodeAt(t+1),(n===45||n===43)&&(r=1,n=e.charCodeAt(t+2)),sf(n)&&(t=ase(e,t+1+r+1))}return t}function ose(e,t){for(;t<e.length;t++){const n=e.charCodeAt(t);if(n===41){t++;break}c0(n,US(e,t+1))&&(t=LC(e,t))}return t}function Iut(e){if(e.length===1&&!s5(e.charCodeAt(0)))return e[0];let t=parseInt(e,16);return(t===0||t>=55296&&t<=57343||t>1114111)&&(t=65533),String.fromCodePoint(t)}const pfe=["EOF-token","ident-token","function-token","at-keyword-token","hash-token","string-token","bad-string-token","url-token","bad-url-token","delim-token","number-token","percentage-token","dimension-token","whitespace-token","CDO-token","CDC-token","colon-token","semicolon-token","comma-token","[-token","]-token","(-token",")-token","{-token","}-token","comment-token"],bSn=16*1024;function FW(e=null,t){return e===null||e.length<t?new Uint32Array(Math.max(t+1024,bSn)):e}const jPe=10,ySn=12,CPe=13;function NPe(e){const t=e.source,n=t.length,r=t.length>0?jut(t.charCodeAt(0)):0,s=FW(e.lines,n),a=FW(e.columns,n);let o=e.startLine,l=e.startColumn;for(let c=r;c<n;c++){const d=t.charCodeAt(c);s[c]=o,a[c]=l++,(d===jPe||d===CPe||d===ySn)&&(d===CPe&&c+1<n&&t.charCodeAt(c+1)===jPe&&(c++,s[c]=o,a[c]=l),o++,l=1)}s[n]=o,a[n]=l,e.lines=s,e.columns=a,e.computed=!0}class vSn{constructor(t,n,r,s){this.setSource(t,n,r,s),this.lines=null,this.columns=null}setSource(t="",n=0,r=1,s=1){this.source=t,this.startOffset=n,this.startLine=r,this.startColumn=s,this.computed=!1}getLocation(t,n){return this.computed||NPe(this),{source:n,offset:this.startOffset+t,line:this.lines[t],column:this.columns[t]}}getLocationRange(t,n,r){return this.computed||NPe(this),{source:r,start:{offset:this.startOffset+t,line:this.lines[t],column:this.columns[t]},end:{offset:this.startOffset+n,line:this.lines[n],column:this.columns[n]}}}}const wg=16777215,kg=24,bL=1,BG=2,rw=new Uint8Array(32);rw[pi]=Ds;rw[oo]=Ds;rw[Uh]=Wp;rw[Pu]=zh;const Yg=new Uint8Array(32);Yg[pi]=bL;Yg[oo]=bL;Yg[Uh]=bL;Yg[Pu]=bL;Yg[Ds]=BG;Yg[Wp]=BG;Yg[zh]=BG;function IPe(e,t,n){return e<t?t:e>n?n:e}class wSn{constructor(t,n){this.setSource(t,n)}reset(){this.eof=!1,this.tokenIndex=-1,this.tokenType=0,this.tokenStart=this.firstCharOffset,this.tokenEnd=this.firstCharOffset}setSource(t="",n=()=>{}){t=String(t||"");const r=t.length,s=FW(this.offsetAndType,t.length+1),a=FW(this.balance,t.length+1);let o=0,l=-1,c=0,d=t.length;this.offsetAndType=null,this.balance=null,a.fill(0),n(t,(u,f,m)=>{const h=o++;if(s[h]=u<<kg|m,l===-1&&(l=f),a[h]=d,u===c){const p=a[d];a[d]=h,d=p,c=rw[s[p]>>kg]}else this.isBlockOpenerTokenType(u)&&(d=h,c=rw[u])}),s[o]=x3<<kg|r,a[o]=o;for(let u=0;u<o;u++){const f=a[u];if(f<=u){const m=a[f];m!==u&&(a[u]=m)}else f>o&&(a[u]=o)}this.source=t,this.firstCharOffset=l===-1?0:l,this.tokenCount=o,this.offsetAndType=s,this.balance=a,this.reset(),this.next()}lookupType(t){return t+=this.tokenIndex,t<this.tokenCount?this.offsetAndType[t]>>kg:x3}lookupTypeNonSC(t){for(let n=this.tokenIndex;n<this.tokenCount;n++){const r=this.offsetAndType[n]>>kg;if(r!==Oc&&r!==cf&&t--===0)return r}return x3}lookupOffset(t){return t+=this.tokenIndex,t<this.tokenCount?this.offsetAndType[t-1]&wg:this.source.length}lookupOffsetNonSC(t){for(let n=this.tokenIndex;n<this.tokenCount;n++){const r=this.offsetAndType[n]>>kg;if(r!==Oc&&r!==cf&&t--===0)return n-this.tokenIndex}return x3}lookupValue(t,n){return t+=this.tokenIndex,t<this.tokenCount?kE(this.source,this.offsetAndType[t-1]&wg,this.offsetAndType[t]&wg,n):!1}getTokenStart(t){return t===this.tokenIndex?this.tokenStart:t>0?t<this.tokenCount?this.offsetAndType[t-1]&wg:this.offsetAndType[this.tokenCount]&wg:this.firstCharOffset}getTokenEnd(t){return t===this.tokenIndex?this.tokenEnd:this.offsetAndType[IPe(t,0,this.tokenCount)]&wg}getTokenType(t){return t===this.tokenIndex?this.tokenType:this.offsetAndType[IPe(t,0,this.tokenCount)]>>kg}substrToCursor(t){return this.source.substring(t,this.tokenStart)}isBlockOpenerTokenType(t){return Yg[t]===bL}isBlockCloserTokenType(t){return Yg[t]===BG}getBlockTokenPairIndex(t){const n=this.getTokenType(t);if(Yg[n]===1){const r=this.balance[t],s=this.getTokenType(r);return rw[n]===s?r:-1}else if(Yg[n]===2){const r=this.balance[t],s=this.getTokenType(r);return rw[s]===n?r:-1}return-1}isBalanceEdge(t){return this.balance[this.tokenIndex]<t}isDelim(t,n){return n?this.lookupType(n)===Oa&&this.source.charCodeAt(this.lookupOffset(n))===t:this.tokenType===Oa&&this.source.charCodeAt(this.tokenStart)===t}skip(t){let n=this.tokenIndex+t;n<this.tokenCount?(this.tokenIndex=n,this.tokenStart=this.offsetAndType[n-1]&wg,n=this.offsetAndType[n],this.tokenType=n>>kg,this.tokenEnd=n&wg):(this.tokenIndex=this.tokenCount,this.next())}next(){let t=this.tokenIndex+1;t<this.tokenCount?(this.tokenIndex=t,this.tokenStart=this.tokenEnd,t=this.offsetAndType[t],this.tokenType=t>>kg,this.tokenEnd=t&wg):(this.eof=!0,this.tokenIndex=this.tokenCount,this.tokenType=x3,this.tokenStart=this.tokenEnd=this.source.length)}skipSC(){for(;this.tokenType===Oc||this.tokenType===cf;)this.next()}skipUntilBalanced(t,n){let r=t,s=0,a=0;e:for(;r<this.tokenCount;r++){if(s=this.balance[r],s<t)break e;switch(a=r>0?this.offsetAndType[r-1]&wg:this.firstCharOffset,n(this.source.charCodeAt(a))){case 1:break e;case 2:r++;break e;default:this.isBlockOpenerTokenType(this.offsetAndType[r]>>kg)&&(r=s)}}this.skip(r-this.tokenIndex)}forEachToken(t){for(let n=0,r=this.firstCharOffset;n<this.tokenCount;n++){const s=r,a=this.offsetAndType[n],o=a&wg,l=a>>kg;r=o,t(l,s,o,n)}}dump(){const t=new Array(this.tokenCount);return this.forEachToken((n,r,s,a)=>{t[a]={idx:a,type:pfe[n],chunk:this.source.substring(r,s),balance:this.balance[a]}}),t}}function QG(e,t){function n(f){return f<l?e.charCodeAt(f):0}function r(){if(d=FG(e,d),YQ(n(d),n(d+1),n(d+2))){u=ka,d=HF(e,d);return}if(n(d)===37){u=yc,d++;return}u=Us}function s(){const f=d;if(d=HF(e,d),kE(e,f,d,"url")&&n(d)===40){if(d=WF(e,d+1),n(d)===34||n(d)===39){u=pi,d=f+4;return}o();return}if(n(d)===40){u=pi,d++;return}u=dr}function a(f){for(f||(f=n(d++)),u=W1;d<e.length;d++){const m=e.charCodeAt(d);switch(ise(m)){case f:d++;return;case JQ:if($W(m)){d+=hfe(e,d,m),u=$G;return}break;case 92:if(d===e.length-1)break;const h=n(d+1);$W(h)?d+=hfe(e,d+1,h):c0(m,h)&&(d=LC(e,d)-1);break}}}function o(){for(u=Mf,d=WF(e,d);d<e.length;d++){const f=e.charCodeAt(d);switch(ise(f)){case 41:d++;return;case JQ:if(d=WF(e,d),n(d)===41||d>=e.length){d<e.length&&d++;return}d=ose(e,d),u=fA;return;case 34:case 39:case 40:case Nut:d=ose(e,d),u=fA;return;case 92:if(c0(f,n(d+1))){d=LC(e,d)-1;break}d=ose(e,d),u=fA;return}}}e=String(e||"");const l=e.length;let c=jut(n(0)),d=c,u;for(;d<l;){const f=e.charCodeAt(d);switch(ise(f)){case JQ:u=Oc,d=WF(e,d+1);break;case 34:a();break;case 35:Sut(n(d+1))||c0(n(d+1),n(d+2))?(u=Nl,d=HF(e,d+1)):(u=Oa,d++);break;case 39:a();break;case 40:u=oo,d++;break;case 41:u=Ds,d++;break;case 43:sse(f,n(d+1),n(d+2))?r():(u=Oa,d++);break;case 44:u=BA,d++;break;case 45:sse(f,n(d+1),n(d+2))?r():n(d+1)===45&&n(d+2)===62?(u=mA,d=d+3):YQ(f,n(d+1),n(d+2))?s():(u=Oa,d++);break;case 46:sse(f,n(d+1),n(d+2))?r():(u=Oa,d++);break;case 47:n(d+1)===42?(u=cf,d=e.indexOf("*/",d+2),d=d===-1?e.length:d+2):(u=Oa,d++);break;case 58:u=Wf,d++;break;case 59:u=Hf,d++;break;case 60:n(d+1)===33&&n(d+2)===45&&n(d+3)===45?(u=xL,d=d+4):(u=Oa,d++);break;case 64:YQ(n(d+1),n(d+2),n(d+3))?(u=kd,d=HF(e,d+1)):(u=Oa,d++);break;case 91:u=Uh,d++;break;case 92:c0(f,n(d+1))?s():(u=Oa,d++);break;case 93:u=Wp,d++;break;case 123:u=Pu,d++;break;case 125:u=zh,d++;break;case Cut:r();break;case h2e:s();break;default:u=Oa,d++}t(u,c,c=d)}}let B7=null;class cu{static createItem(t){return{prev:null,next:null,data:t}}constructor(){this.head=null,this.tail=null,this.cursor=null}createItem(t){return cu.createItem(t)}allocateCursor(t,n){let r;return B7!==null?(r=B7,B7=B7.cursor,r.prev=t,r.next=n,r.cursor=this.cursor):r={prev:t,next:n,cursor:this.cursor},this.cursor=r,r}releaseCursor(){const{cursor:t}=this;this.cursor=t.cursor,t.prev=null,t.next=null,t.cursor=B7,B7=t}updateCursors(t,n,r,s){let{cursor:a}=this;for(;a!==null;)a.prev===t&&(a.prev=n),a.next===r&&(a.next=s),a=a.cursor}*[Symbol.iterator](){for(let t=this.head;t!==null;t=t.next)yield t.data}get size(){let t=0;for(let n=this.head;n!==null;n=n.next)t++;return t}get isEmpty(){return this.head===null}get first(){return this.head&&this.head.data}get last(){return this.tail&&this.tail.data}fromArray(t){let n=null;this.head=null;for(let r of t){const s=cu.createItem(r);n!==null?n.next=s:this.head=s,s.prev=n,n=s}return this.tail=n,this}toArray(){return[...this]}toJSON(){return[...this]}forEach(t,n=this){const r=this.allocateCursor(null,this.head);for(;r.next!==null;){const s=r.next;r.next=s.next,t.call(n,s.data,s,this)}this.releaseCursor()}forEachRight(t,n=this){const r=this.allocateCursor(this.tail,null);for(;r.prev!==null;){const s=r.prev;r.prev=s.prev,t.call(n,s.data,s,this)}this.releaseCursor()}reduce(t,n,r=this){let s=this.allocateCursor(null,this.head),a=n,o;for(;s.next!==null;)o=s.next,s.next=o.next,a=t.call(r,a,o.data,o,this);return this.releaseCursor(),a}reduceRight(t,n,r=this){let s=this.allocateCursor(this.tail,null),a=n,o;for(;s.prev!==null;)o=s.prev,s.prev=o.prev,a=t.call(r,a,o.data,o,this);return this.releaseCursor(),a}some(t,n=this){for(let r=this.head;r!==null;r=r.next)if(t.call(n,r.data,r,this))return!0;return!1}map(t,n=this){const r=new cu;for(let s=this.head;s!==null;s=s.next)r.appendData(t.call(n,s.data,s,this));return r}filter(t,n=this){const r=new cu;for(let s=this.head;s!==null;s=s.next)t.call(n,s.data,s,this)&&r.appendData(s.data);return r}nextUntil(t,n,r=this){if(t===null)return;const s=this.allocateCursor(null,t);for(;s.next!==null;){const a=s.next;if(s.next=a.next,n.call(r,a.data,a,this))break}this.releaseCursor()}prevUntil(t,n,r=this){if(t===null)return;const s=this.allocateCursor(t,null);for(;s.prev!==null;){const a=s.prev;if(s.prev=a.prev,n.call(r,a.data,a,this))break}this.releaseCursor()}clear(){this.head=null,this.tail=null}copy(){const t=new cu;for(let n of this)t.appendData(n);return t}prepend(t){return this.updateCursors(null,t,this.head,t),this.head!==null?(this.head.prev=t,t.next=this.head):this.tail=t,this.head=t,this}prependData(t){return this.prepend(cu.createItem(t))}append(t){return this.insert(t)}appendData(t){return this.insert(cu.createItem(t))}insert(t,n=null){if(n!==null)if(this.updateCursors(n.prev,t,n,t),n.prev===null){if(this.head!==n)throw new Error("before doesn't belong to list");this.head=t,n.prev=t,t.next=n,this.updateCursors(null,t)}else n.prev.next=t,t.prev=n.prev,n.prev=t,t.next=n;else this.updateCursors(this.tail,t,null,t),this.tail!==null?(this.tail.next=t,t.prev=this.tail):this.head=t,this.tail=t;return this}insertData(t,n){return this.insert(cu.createItem(t),n)}remove(t){if(this.updateCursors(t,t.prev,t,t.next),t.prev!==null)t.prev.next=t.next;else{if(this.head!==t)throw new Error("item doesn't belong to list");this.head=t.next}if(t.next!==null)t.next.prev=t.prev;else{if(this.tail!==t)throw new Error("item doesn't belong to list");this.tail=t.prev}return t.prev=null,t.next=null,t}push(t){this.insert(cu.createItem(t))}pop(){return this.tail!==null?this.remove(this.tail):null}unshift(t){this.prepend(cu.createItem(t))}shift(){return this.head!==null?this.remove(this.head):null}prependList(t){return this.insertList(t,this.head)}appendList(t){return this.insertList(t)}insertList(t,n){return t.head===null?this:(n!=null?(this.updateCursors(n.prev,t.tail,n,t.head),n.prev!==null?(n.prev.next=t.head,t.head.prev=n.prev):this.head=t.head,n.prev=t.tail,t.tail.next=n):(this.updateCursors(this.tail,t.tail,null,t.head),this.tail!==null?(this.tail.next=t.head,t.head.prev=this.tail):this.head=t.head,this.tail=t.tail),t.head=null,t.tail=null,this)}replace(t,n){"head"in n?this.insertList(n,t):this.insert(n,t),this.remove(t)}}function UG(e,t){const n=Object.create(SyntaxError.prototype),r=new Error;return Object.assign(n,{name:e,message:t,get stack(){return(r.stack||"").replace(/^(.+\n){1,3}/,`${e}: ${t}
1867
+ ${le}`:le)}}else if(p)for(const se of D)try{await p(se)}catch(ne){x==null||x(ne instanceof Error?ne:new Error("Attachment upload failed"),se)}}finally{B(!1),_.current&&(_.current.value=""),requestAnimationFrame(()=>{var se;return(se=z.current)==null?void 0:se.focus()})}}}return i.jsxs("div",{ref:T,"aria-label":l,className:"chat-composer grid min-w-0 grid-cols-[var(--control-height-sm)_minmax(0,1fr)_auto] items-end gap-x-1.5 rounded-[var(--radius-lg)] p-2 md:block md:p-3","data-composer-state":e.trim()?"composing":"empty","data-issue-detail-escape-back":C?e.trim()?"dirty":"empty":void 0,"data-detail-escape-layer":I?"true":void 0,"data-testid":N,onMouseDown:V,tabIndex:-1,children:[i.jsx("div",{className:"col-start-2 row-start-1 min-w-0 md:block",children:i.jsxs("div",{ref:W,"data-testid":"issue-comment-composer-editor-scroll",className:"motion-comment-composer-height scrollbar-auto-hide relative h-[var(--comment-composer-editor-height)] min-w-0 max-h-[min(24dvh,10rem)] overflow-y-auto overscroll-contain pr-1 md:h-auto md:max-h-[min(38dvh,22rem)]",style:{"--comment-composer-editor-height":"1.875rem"},children:[e.trim()?null:i.jsx("span",{"aria-hidden":"true",className:"pointer-events-none absolute inset-y-0 left-0 z-10 flex items-start pt-px text-sm text-muted-foreground md:hidden",children:d}),i.jsx(Cu,{ref:z,engine:"milkdown",value:e,onChange:t,ariaLabel:c,placeholder:d,mentions:f,agentMentionIntent:"wake",onMentionQueryChange:m,mentionMenuAnchorRef:T,mentionMenuPlacement:"container",onSubmit:n,imageUploadHandler:h,className:"rounded-[var(--radius-md)] bg-transparent",contentClassName:"min-h-7 bg-transparent text-sm leading-6 text-foreground md:min-h-16",bordered:!1})]})}),k?i.jsx("div",{className:"col-span-3 mt-2 md:mt-2",children:k}):null,i.jsxs("div",{"data-testid":"issue-comment-composer-toolbar",className:"contents md:mt-3 md:flex md:items-center md:justify-end md:gap-3",children:[h||p?i.jsxs("div",{className:`col-start-1 row-start-1 flex items-center self-end md:gap-3 ${G.length===0?"md:mr-auto":""}`,children:[i.jsx("input",{ref:_,type:"file",accept:b,"aria-label":y,multiple:w,className:"hidden",onChange:L}),i.jsx(oe,{type:"button",variant:"ghost",size:"icon-sm",onClick:()=>{var R;return(R=_.current)==null?void 0:R.click()},disabled:$||s,title:"Attach file",children:i.jsx(df,{className:"h-4 w-4"})})]}):null,G.length>0?i.jsxs("div",{"data-testid":"comment-agent-wake-status",className:"col-span-3 row-start-2 mt-2 flex min-w-0 flex-wrap items-center gap-2 md:mt-0 md:flex-1",children:[i.jsx("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-1.5",role:"status","aria-live":"polite",children:i.jsx(o7n,{mentionedAgents:G,onToggle:(R,D,X)=>{t(PNt(e,R,D?"reference":"wake")),X&&requestAnimationFrame(()=>{var ee;return(ee=z.current)==null?void 0:ee.focus()})}})}),S?i.jsx("div",{className:"ml-auto flex shrink-0 items-center",children:S}):null]}):S?i.jsx("div",{className:"col-span-3 row-start-2 mt-2 flex justify-end md:contents",children:S}):null,i.jsxs("div",{className:"col-start-3 row-start-1 flex items-center gap-1.5 self-end",children:[j,i.jsx(oe,{type:"button",size:"sm",disabled:!r||$,onClick:n,children:s?"Posting...":u})]})]})]})}function c7n(e,t){return e.map(n=>{var s,a;const r=t==null?void 0:t.get(n.agentId);return{id:n.runId,status:n.status,invocationSource:"issue_timeline",triggerDetail:null,startedAt:typeof n.startedAt=="string"?n.startedAt:((s=n.startedAt)==null?void 0:s.toISOString())??null,finishedAt:typeof n.finishedAt=="string"?n.finishedAt:((a=n.finishedAt)==null?void 0:a.toISOString())??null,createdAt:typeof n.createdAt=="string"?n.createdAt:n.createdAt.toISOString(),agentId:n.agentId,agentName:(r==null?void 0:r.name)??n.agentId.slice(0,8),agentRuntimeType:(r==null?void 0:r.agentRuntimeType)??"process",issueId:null,resultJson:n.resultJson??null}})}function Kdt(e){return e!=null&&e!=="paused"&&e!=="terminated"&&e!=="pending_approval"}function d7n(e,t=new Set,n=!1){return n?!1:!XUe(e).some(r=>{if(t.has(r))return!0;const s=yqe(r);if((s==null?void 0:s.kind)!=="agent")return!1;let a=0;for(const o of t)if(o.replace(/-/g,"").toLowerCase().startsWith(s.prefix)&&(a+=1),a>1)return!1;return a===1})}function u7n(e){try{localStorage.removeItem(e)}catch{}}function f7n({agentMap:e,body:t,canReopen:n,composerSurfaceRef:r,draftKey:s,editorRef:a,locale:o,onAdd:l,reopen:c,reopenWillWakeAgent:d,setReopen:u,updateBody:f}){const{confirm:m}=Bs(),[h,p]=A.useState(!1),[x,b]=A.useState(!1),y=A.useRef(!1),w=A.useRef(null),k=A.useRef(null),S=A.useMemo(()=>new Set((e==null?void 0:e.keys())??[]),[e]);A.useEffect(()=>()=>{w.current!==null&&window.cancelAnimationFrame(w.current),k.current!==null&&window.clearTimeout(k.current)},[]);function j(){var I;if((I=a.current)==null||I.focus(),typeof window<"u"){w.current!==null&&(window.cancelAnimationFrame(w.current),w.current=null),k.current!==null&&(window.clearTimeout(k.current),k.current=null);const N=()=>{var E;w.current=null;const M=document.activeElement;(!M||M===document.body||M instanceof HTMLElement&&M.closest('[role="dialog"]'))&&((E=a.current)==null||E.focus())};w.current=window.requestAnimationFrame(N),k.current=window.setTimeout(()=>{k.current=null,N()},250)}}async function C(I="comment"){var _,z;if(y.current)return;const M=(((z=(_=a.current)==null?void 0:_.getMarkdown)==null?void 0:z.call(_))??t).trim();if(!M)return;const E=n&&c?!0:void 0;y.current=!0;try{if(d7n(M,S,I==="steer"||!!(E&&d))){b(!0);const T=await m({title:RP(o,"comments.unmentionedConfirm.title"),description:RP(o,"comments.unmentionedConfirm.description"),cancelLabel:RP(o,"comments.unmentionedConfirm.cancel"),confirmLabel:RP(o,"comments.unmentionedConfirm.confirm"),restoreFocus:$=>{var B;$?(B=r.current)==null||B.focus({preventScroll:!0}):j()}});if(b(!1),!T){j();return}}p(!0),I==="steer"?await l(M,E,"steer"):await l(M,E),f(""),s&&u7n(s),u(n)}finally{p(!1),b(!1),y.current=!1}}return{canSubmit:!h&&!x&&!!t.trim(),handleSubmit:C,submitting:h}}function ZO(e){return`${e.kind}:${e.id}`}function m7n({activityItems:e,comments:t,linkedRuns:n}){const r=t.map(l=>({kind:"comment",id:l.id,createdAtMs:new Date(l.createdAt).getTime(),comment:l})),s=n.map(l=>({kind:"run",id:l.runId,createdAtMs:new Date(l.startedAt??l.createdAt).getTime(),run:l})),a=e.map(l=>({kind:"activity",id:l.id,createdAtMs:new Date(l.createdAt).getTime(),activity:l})),o={activity:0,comment:1,run:2};return[...r,...s,...a].sort((l,c)=>l.createdAtMs!==c.createdAtMs?l.createdAtMs-c.createdAtMs:l.kind!==c.kind?o[l.kind]-o[c.kind]:l.id.localeCompare(c.id))}function A7n(e){return e.map(t=>({key:ZO(t),kind:t.kind,createdAtMs:t.createdAtMs,...t.kind==="comment"?{commentBody:t.comment.body}:{},...t.kind==="run"?{runStatus:t.run.status}:{}}))}function h7n(e,t){var s;if(t.hidden.length===0)return e;const n=new Map(e.map(a=>[ZO(a),a])),r=a=>a.map(o=>n.get(o.key)).filter(o=>!!o);return[...r(t.visibleHead),{kind:"disclosure",id:"middle",createdAtMs:((s=t.hidden[0])==null?void 0:s.createdAtMs)??0,hiddenCount:t.hidden.length},...r(t.visibleTail)]}function p7n(e,t,n){const r=new Array(e);return new Proxy(r,{get(s,a,o){if(typeof a=="string"){const l=a.charCodeAt(0);if(l>=48&&l<=57){const c=+a;if(Number.isInteger(c)&&c>=0&&c<e){let d=s[c];if(!d){const u=t[c*2];d=s[c]={index:c,key:n(c),start:u,size:t[c*2+1],end:u+t[c*2+1],lane:0}}return d}}if(a==="length")return e}return Reflect.get(s,a,o)}})}function F7(e,t,n){let r=n.initialDeps??[],s,a=!0;function o(){const l=e();return(l.length!==r.length||l.some((d,u)=>r[u]!==d))&&(r=l,s=t(...l),n!=null&&n.onChange&&!(a&&n.skipInitialOnChange)&&n.onChange(s),a=!1),s}return o.updateDeps=l=>{r=l},o}function pPe(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const g7n=(e,t)=>Math.abs(e-t)<1.01,x7n=(e,t,n)=>{let r;return function(...s){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,s),n)}};let BI;const Wre=()=>{if(BI!==void 0)return BI;if(typeof navigator>"u")return BI=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return BI=!0;const e=navigator.maxTouchPoints;return BI=navigator.platform==="MacIntel"&&e!==void 0&&e>0},gPe=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},b7n=e=>e,y7n=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,s=new Array(r);for(let a=0;a<r;a++)s[a]=t+a;return s},v7n=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const s=o=>{const{width:l,height:c}=o;t({width:Math.round(l),height:Math.round(c)})};if(s(gPe(n)),!r.ResizeObserver)return()=>{};const a=new r.ResizeObserver(o=>{const l=()=>{const c=o[0];if(c!=null&&c.borderBoxSize){const d=c.borderBoxSize[0];if(d){s({width:d.inlineSize,height:d.blockSize});return}}s(gPe(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return a.observe(n,{box:"border-box"}),()=>{a.unobserve(n)}},vE={passive:!0},w7n=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=()=>{t({width:n.innerWidth,height:n.innerHeight})};return r(),n.addEventListener("resize",r,vE),()=>{n.removeEventListener("resize",r)}},k7n=typeof window>"u"?!0:"onscrollend"in window,Zdt=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const s=e.targetWindow;if(!s)return;const a=e.options.useScrollendEvent&&k7n;let o=0;const l=a?null:x7n(s,()=>t(o,!1),e.options.isScrollingResetDelay),c=f=>()=>{o=n(r),l==null||l(),t(o,f)},d=c(!0),u=c(!1);return r.addEventListener("scroll",d,vE),a&&r.addEventListener("scrollend",u,vE),()=>{r.removeEventListener("scroll",d),a&&r.removeEventListener("scrollend",u)}},O7n=(e,t)=>Zdt(e,t,n=>{const{horizontal:r,isRtl:s}=e.options;return r?n.scrollLeft*(s&&-1||1):n.scrollTop}),S7n=(e,t)=>Zdt(e,t,n=>e.options.horizontal?n.scrollX:n.scrollY),j7n=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),s=n.options.getItemKey(r);return n.itemSizeCache.get(s)??n.options.estimateSize(r)}if(t!=null&&t.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),s=n.options.getItemKey(r),a=n.itemSizeCache.get(s);if(a!==void 0)return a}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},Xdt=(e,{adjustments:t=0,behavior:n},r)=>{var s,a;(a=(s=r.scrollElement)==null?void 0:s.scrollTo)==null||a.call(s,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},C7n=Xdt,N7n=Xdt;class I7n{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this.elementsCache=new Map,this.now=()=>{var n,r,s;return((s=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:s.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(s=>{s.forEach(a=>{const o=()=>{const l=a.target,c=this.indexFromElement(l);if(!l.isConnected){this.observer.unobserve(l);for(const[d,u]of this.elementsCache)if(u===l){this.elementsCache.delete(d);break}return}this.shouldMeasureDuringScroll(c)&&this.resizeItem(c,this.options.measureElement(l,a,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(o):o()})}));return{disconnect:()=>{var s;(s=r())==null||s.disconnect(),n=null},observe:s=>{var a;return(a=r())==null?void 0:a.observe(s,{box:"border-box"})},unobserve:s=>{var a;return(a=r())==null?void 0:a.unobserve(s)}}})(),this.range=null,this.setOptions=n=>{var r,s;const a={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:b7n,rangeExtractor:y7n,onChange:()=>{},measureElement:j7n,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const m in n){const h=n[m];h!==void 0&&(a[m]=h)}const o=this.options;let l=null,c=null,d=!1;if(o!==void 0&&o.enabled&&a.enabled&&a.anchorTo==="end"&&this.scrollElement!==null){const m=o.count,h=a.count,p=this.getMeasurements(),x=m>0?((r=p[0])==null?void 0:r.key)??o.getItemKey(0):null,b=m>0?((s=p[m-1])==null?void 0:s.key)??o.getItemKey(m-1):null;if(h!==m||m>0&&h>0&&(a.getItemKey(0)!==x||a.getItemKey(h-1)!==b)){d=!0;const k=m>0?this.getVirtualItemForOffset(this.getScrollOffset())??p[0]:null;k&&(l=[k.key,this.getScrollOffset()-k.start]);const S=a.followOnAppend===!0?"auto":a.followOnAppend||null;S&&h>m&&this.isAtEnd(o.scrollEndThreshold)&&(m===0||a.getItemKey(h-1)!==b)&&(c=S)}}this.options=a,d&&(this.pendingMin=0,this.itemSizeCacheVersion++);let u=!1,f=0;if(l&&this.scrollOffset!==null){const[m,h]=l,p=this.getMeasurements(),{count:x,getItemKey:b}=this.options;let y=0;for(;y<x&&b(y)!==m;)y++;if(y<x){const w=p[y];if(w){const k=Math.max(0,w.start+h);k!==this.scrollOffset&&(f=k-this.scrollOffset,this.scrollOffset=k,u=!0)}}}(u||c)&&(this.pendingScrollAnchor=[u?l[0]:null,u?l[1]:0,c,f])},this.notify=n=>{var r,s;(s=(r=this.options).onChange)==null||s.call(r,this,n)},this.maybeNotify=F7(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(a=>{this.observer.observe(a)}),this.unsubs.push(this.options.observeElementRect(this,a=>{this.scrollRect=a,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(a,o)=>{if(o&&this._intendedScrollOffset===null&&a===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(a-this._intendedScrollOffset)<1.5&&(a=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const l=this.getScrollOffset();this.scrollDirection=o?l===a?this.scrollDirection:l<a?"forward":"backward":null,this.scrollOffset=a,this.isScrolling=o,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),"addEventListener"in this.scrollElement){const a=this.scrollElement,o=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},l=()=>{this._iosTouching=!1,!(!Wre()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};a.addEventListener("touchstart",o,vE),a.addEventListener("touchend",l,vE),this.unsubs.push(()=>{a.removeEventListener("touchstart",o),a.removeEventListener("touchend",l),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const s=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,s&&this.scrollElement&&this.options.enabled){const[a,o,l,c]=s;a!==null&&!l&&(Wre()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?c!==0&&(this._iosDeferredAdjustment+=c):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),l&&this.scrollToEnd({behavior:l})}},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;if(this._iosDeferredAdjustment<0&&n>=r-1){this._iosDeferredAdjustment=0;return}const s=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=s,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=F7(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,s,a,o,l,c,d)=>(this.prevLanes!==void 0&&this.prevLanes!==l&&(this.lanesChangedFlag=!0),this.prevLanes=l,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:s,getItemKey:a,enabled:o,lanes:l,laneAssignmentMode:c,gap:d}),{key:!1}),this.getMeasurements=F7(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:s,getItemKey:a,enabled:o,lanes:l,laneAssignmentMode:c,gap:d},u)=>{const f=this.itemSizeCache;if(!o)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const y of this.laneAssignments.keys())y>=n&&this.laneAssignments.delete(y);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(y=>{this.itemSizeCache.set(y.key,y.size)}));const m=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),l===1){const y=n*2;let w=this._flatMeasurements;if(!w||w.length<y){const j=new Float64Array(y);w&&m>0&&j.set(w.subarray(0,m*2)),w=j,this._flatMeasurements=w}let k;if(m===0)k=r+s;else{const j=m-1;k=w[j*2]+w[j*2+1]+d}for(let j=m;j<n;j++){const C=a(j),I=f.get(C),N=typeof I=="number"?I:this.options.estimateSize(j);w[j*2]=k,w[j*2+1]=N,k+=N+d}const S=p7n(n,w,a);return this.measurementsCache=S,S}const h=this.measurementsCache.slice(0,m),p=new Array(l).fill(void 0),x=new Float64Array(l);let b=0;for(let y=0;y<m;y++){const w=h[y];w&&(p[w.lane]===void 0&&b++,p[w.lane]=y,x[w.lane]=w.end)}for(let y=m;y<n;y++){const w=a(y),k=this.laneAssignments.get(y);let S,j;const C=c==="estimate"||f.has(w);if(k!==void 0&&this.options.lanes>1){S=k;const E=p[S],_=E!==void 0?h[E]:void 0;j=_?_.end+d:r+s}else if(b===l){let E=0,_=x[0],z=p[0];for(let T=1;T<l;T++){const $=x[T];($<_||$===_&&p[T]<z)&&(E=T,_=$,z=p[T])}S=E,j=_+d,C&&this.laneAssignments.set(y,S)}else S=y%this.options.lanes,j=r+s,C&&this.laneAssignments.set(y,S);const I=f.get(w),N=typeof I=="number"?I:this.options.estimateSize(y),M=j+N;h[y]={index:y,start:j,size:N,end:M,key:w,lane:S},p[S]===void 0&&b++,p[S]=y,x[S]=M}return this.measurementsCache=h,h},{key:!1,debug:()=>this.options.debug}),this.calculateRange=F7(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,a)=>n.length===0||r===0?(this.range=null,null):(this.range=T7n(n,r,s,a,a===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=F7(()=>{let n=null,r=null;const s=this.calculateRange();return s&&(n=s.startIndex,r=s.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,s,a,o)=>a===null||o===null?[]:n({startIndex:a,endIndex:o,overscan:r,count:s}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,s=n.getAttribute(r);return s?parseInt(s,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const s=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(s!==void 0&&this.range){const a=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),o=Math.max(0,s-a),l=Math.min(this.options.count-1,s+a);return n>=o&&n<=l}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((o,l)=>{o.isConnected||(this.observer.unobserve(o),this.elementsCache.delete(l))});return}const r=this.indexFromElement(n),s=this.options.getItemKey(r),a=this.elementsCache.get(s);a!==n&&(a&&this.observer.unobserve(a),this.observer.observe(n),this.elementsCache.set(s,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var s,a;if(n<0||n>=this.options.count)return;let o,l,c;const d=this._flatMeasurements;if(this.options.lanes===1&&d!==null)c=this.options.getItemKey(n),l=d[n*2],o=d[n*2+1];else{const m=this.measurementsCache[n];if(!m)return;c=m.key,l=m.start,o=m.size}const u=this.itemSizeCache.get(c)??o,f=r-u;if(f!==0){const m=this.options.anchorTo==="end"&&((s=this.scrollState)==null?void 0:s.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,h=m?this.getTotalSize():0,p=this.getScrollOffset()+this.scrollAdjustments,b=!this.itemSizeCache.has(c)?l<p:l+u<=p&&this.scrollDirection!=="backward",y=((a=this.scrollState)==null?void 0:a.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:c,start:l,size:o,end:l+o,lane:0},f,this):b);(this.pendingMin===null||n<this.pendingMin)&&(this.pendingMin=n),this.itemSizeCache.set(c,r),this.itemSizeCacheVersion++,m?this.applyScrollAdjustment(this.getTotalSize()-h):y&&this.applyScrollAdjustment(f),this.notify(!1)}},this.getVirtualItems=F7(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const s=[];for(let a=0,o=n.length;a<o;a++){const l=n[a],c=r[l];s.push(c)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const s=this._flatMeasurements,a=this.options.lanes===1&&s!=null,o=Gdt(0,r.length-1,a?l=>s[l*2]:l=>pPe(r[l]).start,n);return pPe(r[o])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,s=0)=>{if(!this.scrollElement)return 0;const a=this.getSize(),o=this.getScrollOffset();r==="auto"&&(r=n>=o+a?"end":"start"),r==="center"?n+=(s-a)/2:r==="end"&&(n-=a);const l=this.getMaxScrollOffset();return Math.max(Math.min(l,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const s=this.getSize(),a=this.getScrollOffset(),o=this.measurementsCache[n];if(!o)return;if(r==="auto")if(o.end>=a+s-this.options.scrollPaddingEnd)r="end";else if(o.start<=a+this.options.scrollPaddingStart)r="start";else return[a,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const l=r==="end"?o.end+this.options.scrollPaddingEnd:o.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(l,r,o.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:s="auto"}={})=>{this._iosDeferredAdjustment=0;const a=this.getOffsetForAlignment(n,r),o=this.now();this.scrollState={index:null,align:r,behavior:s,startedAt:o,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:s="auto"}={})=>{this._iosDeferredAdjustment=0,n=Math.max(0,Math.min(n,this.options.count-1));const a=this.getOffsetForIndex(n,r);if(!a)return;const[o,l]=a,c=this.now();this.scrollState={index:n,align:l,behavior:s,startedAt:c,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const s=this.getScrollOffset()+n,a=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:a,lastTargetOffset:s,stableFrames:0},this._scrollToOffset(s,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let s;if(r.length===0)s=this.options.paddingStart;else if(this.options.lanes===1){const a=r.length-1,o=this._flatMeasurements;o!=null?s=o[a*2]+o[a*2+1]:s=((n=r[a])==null?void 0:n.end)??0}else{const a=Array(this.options.lanes).fill(null);let o=r.length-1;for(;o>=0&&a.some(l=>l===null);){const l=r[o];a[l.lane]===null&&(a[l.lane]=l.end),o--}s=Math.max(...a.filter(l=>l!==null))}return Math.max(s-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const s of r)s&&this.itemSizeCache.has(s.key)&&n.push({index:s.index,key:s.key,start:s.start,size:s.size,end:s.end,lane:s.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:s})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:s,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){t!==0&&(Wre()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?this._iosDeferredAdjustment+=t:(this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollOffset<0&&(this.scrollOffset=0),this.scrollAdjustments=0)))}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,s=r?r[0]:this.scrollState.lastTargetOffset,a=1,o=s!==this.scrollState.lastTargetOffset;if(!o&&g7n(s,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=a){this.getScrollOffset()!==s&&this._scrollToOffset(s,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,o){const l=this.getSize()||600,c=Math.abs(s-this.getScrollOffset()),d=this.scrollState.behavior==="smooth"&&c>l;this.scrollState.lastTargetOffset=s,d||(this.scrollState.behavior="auto"),this._scrollToOffset(s,{adjustments:void 0,behavior:d?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Gdt=(e,t,n,r)=>{for(;e<=t;){const s=(e+t)/2|0,a=n(s);if(a<r)e=s+1;else if(a>r)t=s-1;else return s}return e>0?e-1:0};function P7n(e,t,n){let r=0;for(;r<=t;){const s=(r+t)/2|0,a=e[s*2];if(a<n)r=s+1;else if(a>n)t=s-1;else return s}return r>0?r-1:0}function T7n(e,t,n,r,s){const a=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:a};if(r===1&&s!==null){const d=P7n(s,a,n);let u=d;const f=n+t;for(;u<a&&s[u*2]+s[u*2+1]<f;)u++;return{startIndex:d,endIndex:u}}let l=Gdt(0,a,d=>e[d].start,n),c=l;if(r===1)for(;c<a&&e[c].end<n+t;)c++;else if(r>1){const d=Array(r).fill(0);for(;c<a&&d.some(f=>f<n+t);){const f=e[c];d[f.lane]=f.end,c++}const u=Array(r).fill(n+t);for(;l>=0&&u.some(f=>f>=n);){const f=e[l];u[f.lane]=f.start,l--}l=Math.max(0,l-l%r),c=Math.min(a,c+(r-1-c%r))}return{startIndex:l,endIndex:c}}const Hre=typeof document<"u"?A.useLayoutEffect:A.useEffect;function Ydt({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",directDomPrepaintRows:r=0,...s}){const a=A.useReducer(f=>f+1,0)[1],o=A.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});o.current.enabled=t,o.current.mode=n;const l=f=>{const m=o.current;if(!m.enabled||!m.container)return;const h=f.getTotalSize();if(h!==m.lastSize){m.lastSize=h;const p=f.options.horizontal?"width":"height";m.container.style[p]=`${h}px`}},c=f=>{const m=o.current;if(!m.enabled||!m.container)return;l(f);const h=!!f.options.horizontal,p=m.mode==="transform",x=h?"left":"top",b=f.options.scrollMargin,y=f.getVirtualItems();for(const w of y){const k=w.start-b,S=f.elementsCache.get(w.key);S&&m.lastPositions.get(S)!==k&&(m.lastPositions.set(S,k),p?S.style.transform=h?`translate3d(${k}px, 0, 0)`:`translate3d(0, ${k}px, 0)`:S.style[x]=`${k}px`)}},d={...s,onChange:(f,m)=>{var y,w;var h;const p=o.current;let x=!0,b=!1;if(p.enabled){c(f);const k=f.getVirtualItems(),S=(y=k[0])==null?void 0:y.index,j=(w=k[k.length-1])==null?void 0:w.index,C=p.prevRange;if(x=!C||C.isScrolling!==f.isScrolling||C.startIndex!==S||C.endIndex!==j,x){p.prevRange=k.length?{startIndex:S,endIndex:j,isScrolling:f.isScrolling}:null;const I=f.range,N=k.flatMap(B=>f.elementsCache.has(B.key)?[B.index]:[]),M=N[0],E=N[N.length-1],_=!I||M===void 0||E===void 0?0:f.scrollDirection==="backward"?I.startIndex-M:f.scrollDirection==="forward"?E-I.endIndex:Math.min(I.startIndex-M,E-I.endIndex),z=I?f.scrollDirection==="backward"?I.startIndex:f.scrollDirection==="forward"?f.options.count-1-I.endIndex:0:0,T=Math.min(r,Math.max(0,z)),$=!!I&&M!==void 0&&E!==void 0&&M<=I.startIndex&&E>=I.endIndex;b=r>0&&f.scrollDirection!==null&&(!$||_<T)}}x&&((e||b)&&m?ja.flushSync(a):a()),(h=s.onChange)==null||h.call(s,f,m)}},[u]=A.useState(()=>{const f=new I7n(d);return Object.assign(f,{containerRef:m=>{const h=o.current;if(h.container=m,h.lastSize=null,m&&h.enabled){const p=f.getTotalSize();h.lastSize=p;const x=f.options.horizontal?"width":"height";m.style[x]=`${p}px`}}})});return u.setOptions(d),Hre(()=>u._didMount(),[]),Hre(()=>(l(u),u._willUpdate())),Hre(()=>{c(u)}),u}function Jdt(e){return Ydt({observeElementRect:v7n,observeElementOffset:O7n,scrollToFn:N7n,...e})}function _7n(e){return Ydt({getScrollElement:()=>typeof document<"u"?window:null,observeElementRect:w7n,observeElementOffset:S7n,scrollToFn:C7n,initialOffset:()=>typeof document<"u"?window.scrollY:0,...e})}const qF=4,M7n=22;function xPe(e){if(!e||typeof window>"u")return e;let t=e;for(;t&&t!==document.body&&t!==document.documentElement;){const r=window.getComputedStyle(t),s=/(auto|scroll|overlay)/.test(`${r.overflow} ${r.overflowY}`),a=t.scrollHeight>t.clientHeight+1,o=t.clientHeight<=window.innerHeight+1;if(s&&(a||o))return t;t=t.parentElement}const n=document.scrollingElement;return n instanceof HTMLElement?n:e}function d2e({children:e,estimateSize:t,getItemKey:n,items:r,itemGap:s=20,leadingOverscan:a=0,overscan:o=3,preventScrollBlanking:l=!1,onTargetMounted:c,scrollElementRef:d,targetKey:u,testId:f}){const m=A.useRef(null),h=A.useRef(null),p=A.useRef(null),[x,b]=A.useState(0),[y,w]=A.useState(0),k=A.useMemo(()=>r.map((F,W)=>n(F,W)),[n,r]),S=A.useCallback(F=>k[F]??F,[k]),j=typeof window<"u"&&new URLSearchParams(window.location.search).get("perfBaseline")==="1",C=A.useCallback(F=>{var ee;const W=(ee=p.current)==null?void 0:ee.scrollDirection,Y=Math.max(8,Math.ceil(o/2)),G=Math.max(a,W==="backward"?o:Y),V=W==="backward"?Y:o,L=Math.max(0,F.startIndex-G),R=Math.min(F.count-1,F.endIndex+V),D=Math.floor(L/qF)*qF,X=Math.min(F.count-1,Math.ceil((R+1)/qF)*qF-1);return Array.from({length:X-D+1},(se,ne)=>D+ne)},[a,o]);A.useLayoutEffect(()=>{let F=null;const W=()=>{F!==null&&cancelAnimationFrame(F),F=requestAnimationFrame(()=>{F=null,b(Y=>Y+1)})};return b(Y=>Y+1),window.addEventListener("resize",W),()=>{F!==null&&cancelAnimationFrame(F),window.removeEventListener("resize",W)}},[]);const I=xPe(d.current),N=typeof document<"u"&&I===document.scrollingElement,M=A.useCallback(()=>xPe(d.current),[d,x]),E={count:r.length,estimateSize:t,getItemKey:S,...l?{overscan:0,rangeExtractor:C}:{overscan:o},scrollMargin:y,directDomUpdates:l&&!j,directDomUpdatesMode:"transform",directDomPrepaintRows:l&&!j?M7n:0,useFlushSync:!1},_=Jdt({...E,enabled:!j&&!N,getScrollElement:M}),z=_7n({...E,enabled:!j&&N}),T=N?z:_;p.current=T;const $=A.useCallback(F=>{m.current=F,l&&!j&&T.containerRef(F)},[j,l,T]),B=T.getVirtualItems();return A.useLayoutEffect(()=>{const F=m.current,W=I;if(!F||!W)return;const Y=()=>{const X=F.getBoundingClientRect(),ee=W===document.scrollingElement?Math.max(0,X.top+W.scrollTop):Math.max(0,X.top-W.getBoundingClientRect().top+W.scrollTop);w(se=>Math.abs(se-ee)<1?se:ee)};Y();const G=[];let V=F.parentElement;for(;V&&V!==W;)G.push(V),V=V.parentElement;const L=typeof ResizeObserver>"u"?null:new ResizeObserver(()=>Y());L==null||L.observe(F);for(const X of G)L==null||L.observe(X);let R=null;const D=typeof MutationObserver>"u"?null:new MutationObserver(()=>{var X;if(!((X=p.current)!=null&&X.isScrolling)){Y();return}R!==null&&clearTimeout(R),R=setTimeout(()=>{R=null,Y()},180)});for(const X of G)D==null||D.observe(X,{attributeFilter:["class","style"],attributes:!0});return()=>{R!==null&&clearTimeout(R),D==null||D.disconnect(),L==null||L.disconnect()}},[l,I]),A.useLayoutEffect(()=>{if(!u)return;const F=k.indexOf(u);F!==-1&&T.scrollToIndex(F,{align:"center"})},[k,u,T]),A.useLayoutEffect(()=>{if(!u||!c||h.current===u||!B.some(W=>k[W.index]===u))return;h.current=u;const F=requestAnimationFrame(()=>c(u));return()=>cancelAnimationFrame(F)},[k,c,u,B]),A.useLayoutEffect(()=>{u!==h.current&&(h.current=null)},[u]),j?i.jsx("div",{"data-testid":`${f}-baseline`,className:"flex w-full flex-col gap-5",children:r.map((F,W)=>i.jsx("div",{"data-virtualized-activity-key":k[W],children:e(F,W)},k[W]))}):i.jsx("div",{ref:$,"data-testid":f,"data-virtualized-scroll-root":N?"window":"element",style:{...l?{}:{height:`${T.getTotalSize()}px`},position:"relative",width:"100%"},children:B.map(F=>{const W=r[F.index];return W?i.jsx("div",{ref:T.measureElement,"data-index":F.index,"data-virtualized-activity-key":k[F.index],style:{left:0,paddingBottom:`${s}px`,position:"absolute",top:0,...l?{}:{transform:`translateY(${F.start-y}px)`},width:"100%"},children:e(W,F.index)},F.key):null})})}function E7n({announcement:e,children:t,mountAll:n,onTargetMounted:r,reserveHashScrollEndSpace:s,regionLabel:a,scrollElementRef:o,targetKey:l,timeline:c,timelineRegionId:d}){const u=!n&&!!o&&c.length>60;A.useLayoutEffect(()=>{u||!l||!r||c.some(h=>ZO(h)===l)&&r(l)},[r,l,c,u]);const f=h=>i.jsx("div",{"data-issue-timeline-key":ZO(h),tabIndex:h.kind==="disclosure"?void 0:-1,children:t(h)}),m=u&&o?i.jsx(d2e,{items:c,getItemKey:ZO,estimateSize:h=>{const p=c[h];return(p==null?void 0:p.kind)==="disclosure"?64:(p==null?void 0:p.kind)==="run"?p.run.status==="queued"||p.run.status==="running"?320:52:(p==null?void 0:p.kind)==="activity"?48:168},overscan:5,preventScrollBlanking:!0,scrollElementRef:o,targetKey:l,onTargetMounted:r,testId:"comment-thread-virtual-timeline",children:h=>f(h)}):c.map(h=>i.jsx("div",{children:f(h)},ZO(h)));return i.jsxs("div",{id:d,className:"space-y-3",role:a?"region":void 0,"aria-label":a,children:[m,i.jsx("span",{className:"sr-only","aria-live":"polite","aria-atomic":"true",children:e}),s?i.jsx("div",{"aria-hidden":"true",className:"h-[var(--comment-hash-scroll-end-space)]",style:{"--comment-hash-scroll-end-space":"min(6rem, 12vh)"},"data-testid":"comment-hash-scroll-end-space"}):null]})}function D7n(e){const t=e.replace(/\s*\([^)]*\)\s*/g," ").trim()||e.trim(),n=t.split(/\s+/);return n.length>=2?(n[0][0]+n[n.length-1][0]).toUpperCase():t.slice(0,2).toUpperCase()}const R7n={xs:"text-sm",sm:"text-xs",default:"text-sm",lg:"text-sm"};function Bd({name:e,avatarUrl:t,initials:n,size:r="default",className:s}){const a=n??D7n(e);return i.jsxs("span",{className:q("inline-flex gap-1.5",r==="xs"?"items-baseline gap-1":"items-center",r==="lg"&&"gap-2",s),children:[i.jsxs(uu,{size:r,className:r==="xs"?"relative -top-px":void 0,"data-avatar-url":t??void 0,children:[t&&i.jsx(gR,{src:t,alt:e}),i.jsx(fu,{children:a})]}),i.jsx("span",{className:q("truncate",R7n[r]),children:e})]})}const eut=12,L7n=4,bPe=24,z7n=640,$7n=900,F7n=144,B7n=720,Q7n=112,U7n=20,q7n=240,V7n=32,W7n=7,yPe={activity:0,comment:1,run:2};function tut(e,t,n){return Math.min(n,Math.max(t,e))}function XQ(e,t){return e.createdAtMs!==t.createdAtMs?e.createdAtMs-t.createdAtMs:e.kind!==t.kind?yPe[e.kind]-yPe[t.kind]:e.key.localeCompare(t.key)}function wE(e){return{key:e.key,kind:e.kind,createdAtMs:e.createdAtMs}}function nut(e){return tut(e*.8,z7n,$7n)}function H7n(e,t){const n=Math.max(1,t-V7n),r=Math.max(1,Math.floor(n/W7n)),s=e.split(/\r?\n/u);return Math.max(1,s.reduce((a,o)=>a+Math.max(1,Math.ceil(o.length/r)),0))}function K7n(e){var r,s;const t=((r=e.match(/!\[[^\]]*\]\([^\n)]+\)/gu))==null?void 0:r.length)??0,n=((s=e.match(/<img\b/giu))==null?void 0:s.length)??0;return t+n}function rut(e,t){if(e.kind==="activity")return 40;if(e.kind==="run")return e.runStatus==="queued"||e.runStatus==="running"?320:52;const n=e.commentBody??"",r=H7n(n,t);return tut(Q7n+r*U7n+K7n(n)*q7n,F7n,B7n)}function Z7n(e,t){return e.reduce((n,r,s)=>n+rut(r,t)+(s>0?eut:0),0)}function EW(e,t,n,r=!1){let s=0,a=0;const o=r?[...e].reverse():e;for(const l of o){const c=rut(l,n)+(a>0?eut:0);if(a>0&&s+c>t)break;s+=c,a+=1}return a}function sut(e,t,n){return e.length>=L7n&&Z7n(e,n)>=t*.5}function X7n(e,t,n){const r=[...e].sort(XQ);if(r.length===0||t<=0||n<=0)return{fullyExpanded:!0,prefixBoundary:null,suffixBoundary:null};const s=nut(t),a=EW(r,s*.4,n),o=r.slice(a),l=EW(o,s*.8,n,!0),c=Math.max(a,r.length-l),d=r.slice(a,c);return sut(d,s,n)?{fullyExpanded:!1,prefixBoundary:wE(r[Math.max(0,a-1)]),suffixBoundary:wE(r[c])}:{fullyExpanded:!0,prefixBoundary:null,suffixBoundary:null}}function DC(e,t){const n=[...e].sort(XQ);if(t.fullyExpanded||!t.prefixBoundary||!t.suffixBoundary)return{hidden:[],visibleHead:n,visibleTail:[]};const r=[],s=[],a=[];for(const o of n)XQ(o,t.prefixBoundary)<=0?r.push(o):XQ(o,t.suffixBoundary)>=0?a.push(o):s.push(o);return{hidden:s,visibleHead:r,visibleTail:a}}function G7n(e,t,n,r){const s=DC(e,t);if(s.hidden.length===0)return{fullyExpanded:!0,prefixBoundary:null,suffixBoundary:null};const a=nut(n),o=a*1.2,l=Math.min(bPe,EW(s.hidden,o,r)),c=Math.min(bPe,EW(s.hidden,o,r,!0));if(l+c>=s.hidden.length)return{fullyExpanded:!0,prefixBoundary:null,suffixBoundary:null};const d=s.hidden[Math.max(0,l-1)],u=s.hidden[Math.max(l,s.hidden.length-c)],f={...t,prefixBoundary:wE(d),suffixBoundary:wE(u)},m=DC(e,f).hidden;return sut(m,a,r)?f:{fullyExpanded:!0,prefixBoundary:null,suffixBoundary:null}}function Y7n(e,t,n){if(t.fullyExpanded)return t;const s=DC(e,t).hidden.find(o=>o.key===n);if(!s)return t;const a={...t,prefixBoundary:wE(s)};return DC(e,a).hidden.length===0?{fullyExpanded:!0,prefixBoundary:null,suffixBoundary:null}:a}const vPe={fullyExpanded:!0,prefixBoundary:null,suffixBoundary:null};function Kre(e){let t=e.parentElement;for(;t;){const n=window.getComputedStyle(t);if(/(auto|scroll|overlay)/.test(`${n.overflow} ${n.overflowY}`))return t;t=t.parentElement}return null}function J7n({hiddenCount:e,locale:t,onRevealMore:n,timelineRegionId:r}){const s=t==="zh-CN"?`已隐藏 ${e} 条动态`:`${e} hidden ${e===1?"item":"items"}`;return i.jsxs("div",{className:"flex min-h-16 items-center gap-3 py-1","data-testid":"issue-timeline-disclosure",children:[i.jsx("span",{"aria-hidden":"true",className:"h-px min-w-4 flex-1 border-t border-dashed border-border"}),i.jsxs("div",{className:"flex shrink-0 flex-col items-center gap-0.5 text-center",children:[i.jsx("span",{className:"text-xs tabular-nums text-muted-foreground",children:s}),i.jsxs(oe,{type:"button",variant:"outline",size:"sm",className:"group h-8 cursor-pointer !bg-[color:var(--surface-elevated)] px-3 text-xs !shadow-[var(--shadow-sm)] hover:border-[color:var(--border-strong)] hover:!bg-[color:var(--surface-active)]","aria-controls":r,"aria-expanded":"false",onClick:a=>{var o;return n==null?void 0:n(a.detail===0,((o=a.currentTarget.closest("[data-testid='issue-timeline-disclosure']"))==null?void 0:o.getBoundingClientRect().top)??a.currentTarget.getBoundingClientRect().top)},children:[t==="zh-CN"?"加载更多":"Load more",i.jsx(rs,{"aria-hidden":"true",className:"size-3.5 text-muted-foreground transition-transform duration-150 group-active:translate-y-0.5"})]})]}),i.jsx("span",{"aria-hidden":"true",className:"h-px min-w-4 flex-1 border-t border-dashed border-border"})]})}function eOn({config:e,items:t,locale:n}){const s=`issue-activity-timeline-${A.useId().replace(/:/gu,"")}`,[a,o]=A.useState({height:0,width:0}),[l,c]=A.useState(null),[d,u]=A.useState(""),f=A.useRef(null);A.useLayoutEffect(()=>{if(!e)return;const y=document.getElementById(s);if(!y)return;let w=null;const k=()=>{w!==null&&cancelAnimationFrame(w),w=requestAnimationFrame(()=>{const C=Kre(y),I={height:(C==null?void 0:C.clientHeight)??window.innerHeight,width:y.clientWidth};o(N=>N.height===I.height&&N.width===I.width?N:I),w=null})},S=typeof ResizeObserver>"u"?null:new ResizeObserver(k);S==null||S.observe(y);const j=Kre(y);return j&&(S==null||S.observe(j)),window.addEventListener("resize",k,{passive:!0}),k(),()=>{w!==null&&cancelAnimationFrame(w),S==null||S.disconnect(),window.removeEventListener("resize",k)}},[e,s]),A.useLayoutEffect(()=>{if(e){if(e.failOpen||e.forceExpanded){c(y=>(y==null?void 0:y.key)===e.key&&y.state.fullyExpanded?y:{key:e.key,state:vPe});return}!e.ready||a.height<=0||a.width<=0||c(y=>(y==null?void 0:y.key)===e.key?y:{key:e.key,state:X7n(t,a.height,a.width)})}},[e,a,t]);const m=A.useMemo(()=>!e||e.failOpen||e.forceExpanded||(l==null?void 0:l.key)!==e.key?vPe:l.state,[e,l]),h=A.useMemo(()=>DC(t,m),[m,t]),p=A.useCallback((y,w)=>{if(!e||h.hidden.length===0)return;f.current={dividerTop:w,focus:y,key:h.hidden[0].key};const k=G7n(t,m,a.height,a.width),S=DC(t,k).hidden.length;c({key:e.key,state:k}),u(S===0?n==="zh-CN"?"已显示全部动态":"All activity is shown":n==="zh-CN"?`仍有 ${S} 条动态被隐藏`:`${S} hidden ${S===1?"item remains":"items remain"}`)},[e,a,m,t,n,h.hidden]),x=A.useCallback(y=>{if(!e||m.fullyExpanded)return;const w=Y7n(t,m,y);w!==m&&c({key:e.key,state:w})},[e,m,t]);A.useLayoutEffect(()=>{const y=f.current;if(!y)return;const w=document.getElementById(s),k=Array.from((w==null?void 0:w.querySelectorAll("[data-issue-timeline-key]"))??[]).find(C=>C.dataset.issueTimelineKey===y.key);if(!k)return;const S=Kre(k),j=k.getBoundingClientRect().top-y.dividerTop;S?S.scrollTop+=j:window.scrollBy({top:j,behavior:"auto"}),y.focus&&k.focus({preventScroll:!0}),f.current=null},[h,s]);const b=e==null?void 0:e.onVisibilityChange;return A.useEffect(()=>{b==null||b()},[b,h.hidden.length]),{announcement:d,mountAll:e==null?void 0:e.mountAll,revealMore:p,revealTarget:x,selection:h,timelineRegionId:s}}function Oi({status:e}){return i.jsx("span",{className:q("inline-flex shrink-0 items-center rounded-[calc(var(--radius-sm)-1px)] border px-2.5 py-1 text-xs font-medium whitespace-nowrap shadow-[var(--shadow-sm)]",hR[e]??pR),children:e.replace("_"," ")})}function iut(e){const t=e==null?void 0:e.trim().replace(/\\/g,"/").replace(/\/+/g,"/");return(t==null?void 0:t.replace(/\/$/g,""))||null}function aut(e){var n;const t=e==null?void 0:e.trim().toLowerCase().replace(/^\$/,"");return t&&((n=t.replace(/^bundled:/,"").split("/").filter(Boolean).at(-1))==null?void 0:n.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,""))||null}function tOn(e){return[e.sourcePath,e.workspaceEditPath].flatMap(t=>{const n=iut(t);if(!n)return[];const r=n.toLowerCase();return r==="skill.md"||r.endsWith("/skill.md")?[n]:[`${n}/SKILL.md`]})}function nOn(e,t){return[e.slug,e.key,e.name].map(aut).some(n=>n===t)}function out(e,t){const n=iut(e.path),r=t??[];if(n){const a=r.filter(o=>tOn(o).some(l=>l===n));if(a.length===1){const o=a[0];return{kind:"organization_skill_file",skillId:o.id,filePath:"SKILL.md",label:o.slug||o.name}}}const s=aut(e.name);if(s){const a=r.filter(o=>nOn(o,s));if(a.length===1){const o=a[0];return{kind:"organization_skill_file",skillId:o.id,filePath:"SKILL.md",label:o.slug||o.name}}}return n?{kind:"local_file",filePath:n,label:e.name||n.split("/").at(-2)||"Skill"}:null}function rOn(e,t,n){const r=LA(e,t??"");if(!r)return null;try{const a=new URL(r.href);if(a.hostname==="org"){const o=decodeURIComponent(a.pathname.replace(/^\/+/u,"")).trim();if(o){const l=(n??[]).find(c=>c.id===o);return{kind:"organization_skill_file",skillId:o,filePath:"SKILL.md",label:(l==null?void 0:l.slug)||(l==null?void 0:l.name)||r.label}}}if(a.hostname==="agent")return null}catch{}const s=fge(r.href);return out({name:s?"":r.label,path:s},n)}function sOn({label:e,className:t,constrain:n=!0}){return i.jsx("span",{"data-slot":"agent-title-badge",className:q("inline-flex min-w-0 shrink items-center rounded-sm border border-border/70 bg-muted/50 px-1.5 py-0.5 text-[10px] font-medium leading-3 text-muted-foreground",n?"max-w-[9rem]":"max-w-full whitespace-normal",t),title:e,children:i.jsx("span",{className:q("min-w-0",n?"truncate":"whitespace-normal break-words text-left"),children:e})})}function Ro({kind:e,label:t,agentAvatarStyle:n="framed",badgeLabel:r,agentIcon:s,agentRole:a,avatarUrl:o,className:l,layout:c="inline",muted:d=!1}){const u=c==="stacked";return i.jsxs("span",{"data-slot":"assignee-label","data-kind":e,"data-layout":c,"data-agent-avatar-style":e==="agent"?n:void 0,className:q("inline-flex min-w-0 max-w-full items-center gap-1.5",u&&"w-full",l),children:[e==="agent"?n==="bare"?i.jsx(lc,{icon:s,role:a,className:"h-6 w-6 shrink-0 text-muted-foreground"}):i.jsx("span",{"data-slot":"assignee-agent-avatar-frame",className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-border/70 bg-muted/40 text-muted-foreground",children:i.jsx(lc,{icon:s,role:a,className:"h-3.5 w-3.5"})}):i.jsxs(uu,{size:"sm","data-avatar-url":e==="user"&&o?o:void 0,children:[e==="user"&&o?i.jsx(gR,{src:o,alt:t}):null,i.jsx(fu,{className:q(e==="unassigned"&&"border border-dashed border-muted-foreground/35 bg-muted/30"),children:e==="user"?i.jsx(zj,{className:"h-3 w-3"}):i.jsx(qAe,{className:"h-3 w-3"})})]}),i.jsxs("span",{className:q("inline-flex min-w-0 max-w-full flex-1 items-center gap-1.5 overflow-hidden",u&&"w-full flex-col items-start gap-1"),children:[i.jsx("span",{"data-slot":"assignee-label-text",className:q("block min-w-0 max-w-full truncate text-xs",d&&"text-muted-foreground"),title:t,children:t}),r?i.jsx(sOn,{label:r,constrain:!u}):null]})]})}function yh({agent:e,agentAvatarStyle:t="framed"}){const n=_q(e);return i.jsxs("span",{"data-slot":"agent-menu-label",className:"flex min-w-0 flex-1 items-center gap-2",children:[t==="bare"?i.jsx(lc,{icon:e.icon,role:e.role,className:"h-6 w-6 shrink-0 text-muted-foreground"}):i.jsx("span",{"data-slot":"agent-menu-avatar-frame",className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-border/70 bg-muted/40 text-muted-foreground",children:i.jsx(lc,{icon:e.icon,role:e.role,className:"h-3.5 w-3.5"})}),i.jsxs("span",{className:"flex min-w-0 flex-1 flex-col text-left",children:[i.jsx("span",{className:"truncate text-xs font-medium leading-4 text-foreground",children:e.name}),n?i.jsx("span",{"data-slot":"agent-menu-supporting-label",className:"truncate text-[11px] leading-3 text-muted-foreground",children:n}):null]})]})}function ufe({label:e="Assign to me",avatarUrl:t}){return i.jsxs("span",{"data-slot":"assignee-self-action-label",className:"flex min-w-0 flex-1 items-center gap-2",children:[i.jsxs(uu,{size:"sm","data-avatar-url":t??void 0,children:[t?i.jsx(gR,{src:t,alt:e}):null,i.jsx(fu,{className:"border border-border/70 bg-muted/40",children:i.jsx(zj,{className:"h-3.5 w-3.5"})})]}),i.jsx("span",{className:"truncate text-xs font-medium leading-4 text-foreground",children:e})]})}function lut({message:e,currentUserId:t=null,currentUserAvatarUrl:n=null}){const r=A.useMemo(()=>tTt(e.structuredPayload).filter(s=>s.display==="card"),[e.structuredPayload]);return r.length===0?null:i.jsx("div",{className:"mt-3 flex max-w-[72ch] flex-col gap-2","data-testid":"chat-rich-references",children:r.map((s,a)=>i.jsx(iOn,{reference:s,currentUserId:t,currentUserAvatarUrl:n},`${s.type}:${s.issueId??s.identifier??"issue"}:${s.type==="issue_comment"?s.commentId:a}`))})}function iOn({reference:e,currentUserId:t,currentUserAvatarUrl:n}){return e.type==="issue"?i.jsx(aOn,{reference:e,currentUserId:t,currentUserAvatarUrl:n}):i.jsx(oOn,{reference:e,currentUserId:t,currentUserAvatarUrl:n})}function aOn({reference:e,currentUserId:t,currentUserAvatarUrl:n}){const r=cut(e),s=Ve({queryKey:U.issues.detail(r),queryFn:()=>fr.get(r),retry:!1,enabled:!!r});return s.isLoading?i.jsx(Bk,{icon:"issue",title:"Loading issue",detail:r,tone:"loading"}):s.isError?i.jsx(ffe,{error:s.error,kind:"issue"}):s.data?i.jsx(lOn,{issue:s.data,currentUserId:t,currentUserAvatarUrl:n}):i.jsx(Bk,{icon:"issue",title:"Issue unavailable",detail:"The issue could not be loaded.",tone:"muted"})}function oOn({reference:e,currentUserId:t,currentUserAvatarUrl:n}){const r=cut(e),s=Ve({queryKey:U.issues.detail(r),queryFn:()=>fr.get(r),retry:!1,enabled:!!r}),a=Ve({queryKey:U.issues.comment(r,e.commentId),queryFn:()=>fr.getComment(r,e.commentId),retry:!1,enabled:!!r});return s.isLoading||a.isLoading?i.jsx(Bk,{icon:"comment",title:"Loading comment",detail:r,tone:"loading"}):s.isError?i.jsx(ffe,{error:s.error,kind:"issue"}):a.isError?i.jsx(ffe,{error:a.error,kind:"comment"}):!s.data||!a.data?i.jsx(Bk,{icon:"comment",title:"Comment unavailable",detail:"The comment could not be loaded.",tone:"muted"}):i.jsx(cOn,{issue:s.data,comment:a.data,currentUserId:t,currentUserAvatarUrl:n})}function lOn({issue:e,currentUserId:t,currentUserAvatarUrl:n}){const r=e.identifier??e.id.slice(0,8),s=e.assigneeAgentId?e.assigneeAgentId.slice(0,8):e.assigneeUserId?NA(e.assigneeUserId,null)??e.assigneeUserId.slice(0,8):"Unassigned";return i.jsx(gn,{to:`/issues/${e.identifier??e.id}`,className:"group block rounded-lg border border-border bg-card px-3 py-2.5 text-left shadow-[var(--shadow-sm)] transition-colors hover:border-[color:var(--accent-strong)]/40 hover:bg-[color:var(--surface-active)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":`Open issue ${r}`,children:i.jsxs("div",{className:"flex min-w-0 items-start gap-3",children:[i.jsx("div",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-border bg-background text-muted-foreground",children:i.jsx(Aa,{className:"h-4 w-4","aria-hidden":!0})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[i.jsx("span",{className:"font-mono text-[11px] font-medium text-foreground",children:r}),i.jsx(Oi,{status:e.status}),i.jsx("span",{children:Hd(e.priority)})]}),i.jsx("div",{className:"mt-1 truncate text-sm font-medium leading-5 text-foreground",children:e.title}),i.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground",children:[e.assigneeUserId?i.jsx(Bd,{name:s,avatarUrl:e.assigneeUserId===t?n:null,size:"xs"}):i.jsx("span",{children:s}),i.jsxs("span",{children:["Updated ",Ca(e.updatedAt)]})]})]})]})})}function cOn({issue:e,comment:t,currentUserId:n,currentUserAvatarUrl:r}){const s=e.identifier??e.id.slice(0,8),a=t.authorAgentId?t.authorAgentId.slice(0,8):t.authorUserId?NA(t.authorUserId,null)??t.authorUserId.slice(0,8):"System",o=dOn(t.body);return i.jsx(gn,{to:`/issues/${e.identifier??e.id}#comment-${t.id}`,className:"group block rounded-lg border border-border bg-card px-3 py-2.5 text-left shadow-[var(--shadow-sm)] transition-colors hover:border-[color:var(--accent-strong)]/40 hover:bg-[color:var(--surface-active)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":`Open comment on issue ${s}`,children:i.jsxs("div",{className:"flex min-w-0 items-start gap-3",children:[i.jsx("div",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-border bg-background text-muted-foreground",children:i.jsx(PD,{className:"h-4 w-4","aria-hidden":!0})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[i.jsx("span",{className:"font-mono text-[11px] font-medium text-foreground",children:s}),t.authorUserId?i.jsx(Bd,{name:a,avatarUrl:t.authorUserId===n?r:null,size:"xs"}):i.jsx("span",{children:a}),i.jsx("span",{children:Ca(t.createdAt)})]}),i.jsx("div",{className:"mt-1 truncate text-sm font-medium leading-5 text-foreground",children:e.title}),i.jsx("p",{className:"mt-1 max-h-[3.75rem] overflow-hidden text-sm leading-5 text-muted-foreground",children:o})]})]})})}function ffe({error:e,kind:t}){if(e instanceof $o){if(e.status===403)return i.jsx(Bk,{icon:t,title:"Permission denied",detail:"You do not have access to this reference.",tone:"warning"});if(e.status===404)return i.jsx(Bk,{icon:t,title:t==="issue"?"Issue not found":"Comment not found",detail:"The reference may have been deleted or moved.",tone:"muted"})}return i.jsx(Bk,{icon:t,title:"Reference unavailable",detail:"The reference could not be loaded.",tone:"warning"})}function Bk({icon:e,title:t,detail:n,tone:r}){const s=e==="issue"?Aa:Co;return i.jsx("div",{className:q("rounded-lg border border-dashed px-3 py-2.5 text-sm",r==="warning"?"border-amber-500/35 bg-amber-500/5 text-amber-800 dark:text-amber-200":"border-border bg-card text-muted-foreground"),children:i.jsxs("div",{className:"flex items-start gap-3",children:[i.jsx("div",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-current/15 bg-background/70",children:i.jsx(s,{className:"h-4 w-4","aria-hidden":!0})}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("div",{className:"font-medium text-foreground",children:t}),i.jsx("div",{className:"mt-0.5 break-words text-xs",children:n})]})]})})}function cut(e){return e.issueId??e.identifier??""}function dOn(e){return e.replace(/!\[[^\]]*]\([^)]*\)/g,"").replace(/\[([^\]]+)]\([^)]*\)/g,"$1").replace(/[`*_>#~-]+/g,"").replace(/\s+/g," ").trim()||"No comment body."}const vh=A.forwardRef(function({value:t,options:n,placeholder:r,noneLabel:s,searchPlaceholder:a,emptyMessage:o,onChange:l,onConfirm:c,className:d,ariaLabel:u,renderTriggerValue:f,renderOption:m,renderOptionAccessory:h,keepOpenOnOptionChange:p=!1,disablePortal:x,side:b="bottom",sideOffset:y,contentClassName:w,variant:k="inline"},S){const[j,C]=A.useState(!1),[I,N]=A.useState(""),[M,E]=A.useState(0),[_,z]=A.useState(!1),T=A.useRef(null),$=A.useRef(null),B=A.useRef(null),F=A.useRef(!1),W=A.useRef(!1),Y=A.useRef(!1),G=A.useRef(!1);A.useImperativeHandle(S,()=>$.current);const V=A.useMemo(()=>[{id:"",label:s,searchText:s},...n],[s,n]),L=A.useMemo(()=>{const ee=I.trim().toLowerCase();return ee?V.filter(se=>`${se.label} ${se.searchText??""}`.toLowerCase().includes(ee)):V},[V,I]),R=n.find(ee=>ee.id===t)??null,D=typeof window<"u"&&window.innerWidth<640?{top:16,right:16,bottom:88,left:16}:16;A.useEffect(()=>{if(!j)return;const ee=L.findIndex(se=>se.id===t);E(ee>=0?ee:0)},[L,j,t]),A.useEffect(()=>{if(!j||!_)return;const ee=requestAnimationFrame(()=>{var se;(se=B.current)==null||se.focus(),z(!1)});return()=>cancelAnimationFrame(ee)},[j,_]);const X=(ee,se,ne=!1)=>{const le=L[ee]??L[0];if(le&&l(le.id),ne){z(!0),N(""),C(!0);return}F.current=se,C(!1),N(""),se&&c&&requestAnimationFrame(()=>{c()})};return i.jsxs(bi,{open:j,onOpenChange:ee=>{C(ee),ee||N("")},children:[i.jsx(Hi,{asChild:!0,children:i.jsxs("button",{ref:$,type:"button","aria-label":u,className:q("inline-flex min-w-0 items-center gap-1 border border-border text-sm font-medium text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",k==="field"?"h-10 w-full justify-between rounded-md bg-background px-3 hover:bg-accent/30":"rounded-md bg-muted/40 px-2 py-1 hover:bg-accent/50",d),onPointerDown:()=>{W.current=!0},onFocus:()=>{Y.current?Y.current=!1:W.current||C(!0),W.current=!1},children:[i.jsx("span",{className:q("flex min-w-0 items-center gap-2",k==="field"&&"flex-1 overflow-hidden"),children:f?f(R):(R==null?void 0:R.label)??i.jsx("span",{className:"text-muted-foreground",children:r})}),k==="field"?i.jsx(rs,{className:"ml-2 h-4 w-4 shrink-0 text-muted-foreground"}):null]})}),i.jsxs(yi,{align:"start",side:b,sideOffset:y,collisionPadding:D,className:q("motion-inline-selector-pop z-[70] flex max-h-[min(18rem,var(--radix-popover-content-available-height))] flex-col overflow-hidden p-1",k==="field"?"w-[var(--radix-popover-trigger-width)] min-w-64 max-w-[calc(100vw-2rem)]":"w-[min(20rem,calc(100vw-2rem))]",w),disablePortal:x,onOpenAutoFocus:ee=>{var ne;ee.preventDefault(),window.matchMedia("(pointer: coarse)").matches||(ne=T.current)==null||ne.focus()},onCloseAutoFocus:ee=>{if(G.current){ee.preventDefault(),G.current=!1,requestAnimationFrame(()=>{var se;return(se=$.current)==null?void 0:se.focus()});return}F.current&&(ee.preventDefault(),F.current=!1)},onInteractOutside:ee=>{const se=ee.target;se instanceof Element&&se.closest("[data-issue-runtime-portal]")&&ee.preventDefault()},onEscapeKeyDown:ee=>{ee.preventDefault(),ee.stopPropagation(),C(!1),Y.current=!0,G.current=!0},children:[i.jsx("input",{ref:T,className:"w-full border-b border-border bg-transparent px-2 py-1.5 text-sm outline-none placeholder:text-muted-foreground/60",placeholder:a,value:I,onChange:ee=>{N(ee.target.value)},onKeyDown:ee=>{if(ee.key==="ArrowDown"){ee.preventDefault(),E(se=>L.length===0?0:(se+1)%L.length);return}if(ee.key==="ArrowUp"){ee.preventDefault(),E(se=>L.length===0?0:se<=0?L.length-1:se-1);return}if(ee.key==="Enter"){ee.preventDefault(),X(M,!1,p);return}if(ee.key==="Tab"&&!ee.shiftKey){ee.preventDefault(),X(M,!0);return}ee.key==="Escape"&&(ee.preventDefault(),ee.stopPropagation(),C(!1),Y.current=!0,G.current=!0)}}),i.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto overscroll-contain py-1 touch-pan-y",children:L.length===0?i.jsx("p",{className:"px-2 py-2 text-xs text-muted-foreground",children:o}):L.map((ee,se)=>{const ne=ee.id===t,le=se===M,ie=m?m(ee,ne):i.jsx("span",{className:"truncate",children:ee.label}),re=h==null?void 0:h(ee,ne);return re?i.jsxs("div",{"data-inline-entity-option":!0,className:q("flex w-full items-center gap-1 rounded text-left text-sm transition-colors",le&&"bg-accent"),onMouseEnter:()=>E(se),children:[i.jsxs("button",{type:"button",ref:ne?B:void 0,"aria-pressed":ne,className:"flex min-w-0 flex-1 items-center gap-2 rounded px-2 py-1.5 text-left transition-colors touch-manipulation hover:bg-accent/80",onClick:()=>X(se,!1,p),children:[ie,i.jsx(zi,{className:q("ml-auto h-3.5 w-3.5 shrink-0 text-muted-foreground",ne?"opacity-100":"opacity-0")})]}),i.jsx("div",{className:"min-w-0 max-w-[45%] shrink-0 overflow-hidden",children:re})]},ee.id||"__none__"):i.jsxs("button",{type:"button","data-inline-entity-option":!0,className:q("flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-sm transition-colors touch-manipulation hover:bg-accent/80",le&&"bg-accent"),onMouseEnter:()=>E(se),onClick:()=>X(se,!p,p),children:[ie,i.jsx(zi,{className:q("ml-auto h-3.5 w-3.5 text-muted-foreground",ne?"opacity-100":"opacity-0")})]},ee.id||"__none__")})})]})]})});function zG({text:e,className:t,...n}){return i.jsxs("span",{role:"status","aria-label":`${e}...`,className:q("rudder-text-dots inline-flex items-baseline whitespace-nowrap align-baseline",t),...n,children:[i.jsx("span",{children:e}),i.jsx("span",{className:"rudder-text-dots__dots","aria-hidden":"true",children:[0,1,2].map(r=>i.jsx("span",{className:"rudder-text-dots__dot",style:{"--rudder-text-dot-index":r},children:"."},r))})]})}function Cn({className:e,...t}){return i.jsx("div",{"data-slot":"skeleton",className:q("motion-skeleton rounded-[var(--radius-sm)] bg-[color:color-mix(in_oklab,var(--surface-active)_82%,transparent)]",e),...t})}function JP(e){if(!e)return null;const t=e instanceof Date?e.getTime():Date.parse(e);return Number.isFinite(t)?t:null}function dut(e){return QVe(e)}function uut(e){let t=0;for(const n of e){const r=Date.parse(n.ts);Number.isFinite(r)&&r>t&&(t=r)}return t>0?t:Date.now()}function uOn(e,t){for(const n of e){const r=Date.parse(n.ts);if(Number.isFinite(r))return new Date(r)}return t}function fOn(e,t,n){const r=JP(t.createdAt),a=(t.chatTurnId?e.filter(l=>{if(l.role!=="user"||l.chatTurnId!==t.chatTurnId||(l.turnVariant??0)!==(t.turnVariant??0))return!1;const c=JP(l.createdAt);return c!==null&&(r===null||c<=r)}):[]).reduce((l,c)=>{const d=JP(c.createdAt);return d===null?l:l===null||d>l?d:l},null);if(a!==null)return new Date(a);const o=e.reduce((l,c)=>{if(c.role!=="user")return l;const d=JP(c.createdAt);return d===null||r!==null&&d>r?l:l===null||d>l?d:l},null);return o!==null?new Date(o):uOn(n,new Date(t.createdAt))}function mOn(e,t){const n=t.length>0?uut(t):0,r=JP(e.createdAt)??0,s=Math.max(n,r);return new Date(s>0?s:Date.now())}const AOn=new Set(["pending","acceptance_unknown","accepted_current"]);function Zre(e,t){const n=e==null?void 0:e[t];return typeof n=="string"&&n.trim()?n:null}function wPe(e,t){const n=e==null?void 0:e[t];return typeof n=="number"&&Number.isInteger(n)&&n>=0?n:null}function fut(e){var s;if(e.role!=="user"||((s=e.structuredPayload)==null?void 0:s.source)!=="steer")return null;const t=Zre(e.structuredPayload,"deliveryDisposition");if(!t||!AOn.has(t))return null;const n=Zre(e.structuredPayload,"targetGenerationId"),r=wPe(e.structuredPayload,"afterTranscriptEntryCount");return!n||r===null?null:{message:e,targetGenerationId:n,afterTranscriptEntryCount:r,generationSeq:wPe(e.structuredPayload,"generationSeq")??0,controlActionId:Zre(e.structuredPayload,"controlActionId")}}function hOn(e,t){const n=t.map(fut).filter(a=>!!a).sort((a,o)=>a.afterTranscriptEntryCount-o.afterTranscriptEntryCount||a.generationSeq-o.generationSeq||new Date(a.message.createdAt).getTime()-new Date(o.message.createdAt).getTime()||a.message.id.localeCompare(o.message.id));if(n.length===0)return e;const r=new Map;for(const a of n){const o=Math.min(a.afterTranscriptEntryCount,e.length),l=r.get(o)??[];l.push(a),r.set(o,l)}const s=[];for(let a=0;a<=e.length;a+=1){a>0&&s.push(e[a-1]);for(const o of r.get(a)??[]){const l={kind:"user",source:"steer",ts:new Date(o.message.createdAt).toISOString(),text:o.message.body,messageId:o.message.id,controlActionId:o.controlActionId??void 0,steerMessage:o.message};s.push(l)}}return s}function pOn(e,t,n){if(n)return e[t]?e:{...e,[t]:!0};if(!e[t])return e;const{[t]:r,...s}=e;return s}function gOn(e,t,n){if(n===null){if(!(t in e))return e;const{[t]:r,...s}=e;return s}return{...e,[t]:n}}function xOn(e,t){return!!(t&&e[t])}function kPe(e,t){return t?e[t]??null:null}function bOn(e,t){return e.role==="user"?!0:t.chatTurnId&&e.chatTurnId===t.chatTurnId?!1:new Date(e.createdAt).getTime()<t.userCreatedAt.getTime()}function yOn(e,t){const n=t.userMessageId?e.findIndex(s=>s.id===t.userMessageId):-1;if(n>=0)return n+1;const r=e.findIndex(s=>new Date(s.createdAt).getTime()>=t.userCreatedAt.getTime());return r>=0?r:e.length}function vOn(e,t){if(!t.editedFromCreatedAt)return!0;const n=new Date(e.createdAt).getTime();return n<t.editedFromCreatedAt.getTime()?!0:e.role==="user"&&e.id!==t.userMessageId&&n>=t.userCreatedAt.getTime()}const mut={content:null,version:0},DW=new Map,GQ=new Map;function Aut(e){for(const t of GQ.get(e)??[])t()}function wOn(e,t){const n=DW.get(e);DW.set(e,{content:t,version:((n==null?void 0:n.version)??0)+1}),Aut(e)}function kOn(e){DW.delete(e)&&Aut(e)}function OOn(e,t){const n=GQ.get(e)??new Set;return n.add(t),GQ.set(e,n),()=>{n.delete(t),n.size===0&&GQ.delete(e)}}function SOn(e){return DW.get(e)??mut}function jOn({targetKey:e}){const t=A.useSyncExternalStore(n=>OOn(e,n),()=>SOn(e),()=>mut);return i.jsxs("div",{className:"h-full min-h-0","data-testid":"chat-side-panel-issue-proposal-content",children:[i.jsx("span",{className:"sr-only",role:"status",children:"Issue proposal opened in Side Panel."}),t.content]})}const COn="*";function Xre(e){const t=e.trim();return t?`${t[0]}${"*".repeat(Math.max(1,Array.from(t).length-1))}`:COn}const NOn=[{regex:/\/Users\/([^/\\\s]+)/g,replace:(e,t)=>`/Users/${Xre(t)}`},{regex:/\/home\/([^/\\\s]+)/g,replace:(e,t)=>`/home/${Xre(t)}`},{regex:/([A-Za-z]:\\Users\\)([^\\/\s]+)/g,replace:(e,t,n)=>`${t}${Xre(n)}`}];function IOn(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function dA(e,t){if((t==null?void 0:t.enabled)===!1)return e;let n=e;for(const r of NOn)n=n.replace(r.regex,r.replace);return n}function RW(e,t){if(typeof e=="string")return dA(e,t);if(Array.isArray(e))return e.map(r=>RW(r,t));if(!IOn(e))return e;const n={};for(const[r,s]of Object.entries(e))n[r]=RW(s,t);return n}function u2e(e,t){switch(e.kind){case"assistant":case"thinking":case"user":case"stderr":case"system":case"stdout":return{...e,text:dA(e.text,t)};case"tool_call":return{...e,name:dA(e.name,t),input:RW(e.input,t)};case"tool_result":return{...e,content:dA(e.content,t)};case"todo_list":return{...e,todoListId:e.todoListId?dA(e.todoListId,t):void 0,items:e.items.map(n=>({...n,text:dA(n.text,t)}))};case"init":return{...e,model:dA(e.model,t),sessionId:dA(e.sessionId,t)};case"result":return{...e,text:dA(e.text,t),subtype:dA(e.subtype,t),errors:e.errors.map(n=>dA(n,t))};default:return e}}function QI(e){return typeof e=="string"&&e.trim().length>0?e.trim():null}function Gre(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function z5(e,t){if(!Array.isArray(e))return[];const n=Gre(t),r={agentRuntimeType:QI(n==null?void 0:n.agentRuntimeType),model:QI((n==null?void 0:n.model)??t)},s=[],a=new Set;r.agentRuntimeType&&r.model&&a.add(`${r.agentRuntimeType}\0${r.model}`);for(const o of e){const l=Gre(o),c=l?QI(l.agentRuntimeType)??r.agentRuntimeType:r.agentRuntimeType,d=QI(l?l.model:o);if(!c||!d)continue;const u=`${c}\0${d}`;if(a.has(u))continue;a.add(u);const f=Gre(l==null?void 0:l.config),m=f?Object.fromEntries(Object.entries(f).filter(([x])=>!["agentRuntimeType","model","modelFallbacks","config"].includes(x))):{},p={...l?Object.fromEntries(Object.entries(l).filter(([x])=>!["agentRuntimeType","model","modelFallbacks","config"].includes(x))):{},...m};s.push({agentRuntimeType:c,model:d,...Object.keys(p).length>0?{config:p}:{}})}return s}const POn=[{capabilityId:"issue.comment",name:"rudder_issue_comment",description:"Add a comment to an issue, optionally uploading images and appending Markdown image links.",semanticDescription:"Add a comment to an issue, optionally uploading images and appending Markdown image links. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Add a comment to an issue, optionally uploading images and appending Markdown image links"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,anyOf:[{required:["body"]},{required:["comment"]}],properties:{body:{description:"Direct Markdown body.",maxLength:5e5,minLength:1,type:"string"},comment:{description:"Direct Markdown body.",maxLength:5e5,minLength:1,type:"string"},images:{description:"Local image paths to attach.",items:{description:"Local image paths to attach.",maxLength:8192,minLength:1,type:"string"},maxItems:20,type:"array"},issue:{description:"Issue UUID, identifier, or short reference.",maxLength:200,minLength:1,type:"string"},reopen:{description:"Reopen the issue while commenting.",type:"boolean"}},required:["issue"],type:"object"}},{capabilityId:"issue.comments.list",name:"rudder_issue_comments_list",description:"List issue comments, optionally only newer comments after a full comment id or cmt_<uuid-prefix> with --after.",semanticDescription:"List issue comments, optionally only newer comments after a full comment id or cmt_<uuid-prefix> with --after. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List issue comments, optionally only newer comments after a full comment id or cmt_<uuid-prefix> with --after"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{after:{description:"Return comments after this comment id or short reference.",maxLength:200,minLength:1,type:"string"},issue:{description:"Issue UUID, identifier, or short reference.",maxLength:200,minLength:1,type:"string"},order:{description:"Comment order.",enum:["asc","desc"],maxLength:10,minLength:1,type:"string"}},required:["issue"],type:"object"}},{capabilityId:"issue.comments.get",name:"rudder_issue_comments_get",description:"Read one issue comment by full id or cmt_<uuid-prefix> scoped to the issue.",semanticDescription:"Read one issue comment by full id or cmt_<uuid-prefix> scoped to the issue. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read one issue comment by full id or cmt_<uuid-prefix> scoped to the issue"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{comment:{description:"Comment id or short reference.",maxLength:200,minLength:1,type:"string"},issue:{description:"Issue UUID, identifier, or short reference.",maxLength:200,minLength:1,type:"string"}},required:["issue","comment"],type:"object"}},{capabilityId:"issue.update",name:"rudder_issue_update",description:"Apply generic issue updates when workflow commands are not enough, optionally uploading images for the update comment.",semanticDescription:"Apply generic issue updates when workflow commands are not enough, optionally uploading images for the update comment. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Apply generic issue updates when workflow commands are not enough, optionally uploading images for the update comment"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{assigneeAgentId:{description:"Assignee agent id or reference.",maxLength:200,minLength:1,type:"string"},billingCode:{description:"Billing code.",maxLength:200,minLength:1,type:"string"},body:{description:"Direct Markdown body.",maxLength:5e5,minLength:1,type:"string"},comment:{description:"Direct Markdown body.",maxLength:5e5,minLength:1,type:"string"},description:{description:"Issue description.",maxLength:5e5,minLength:1,type:"string"},goalId:{description:"Goal id or reference.",maxLength:200,minLength:1,type:"string"},hiddenAt:{description:"Hidden timestamp.",maxLength:100,minLength:1,type:"string"},images:{description:"Local image paths to attach.",items:{description:"Local image paths to attach.",maxLength:8192,minLength:1,type:"string"},maxItems:20,type:"array"},issue:{description:"Issue UUID, identifier, or short reference.",maxLength:200,minLength:1,type:"string"},parentId:{description:"Parent issue id or reference.",maxLength:200,minLength:1,type:"string"},priority:{description:"New issue priority.",maxLength:100,minLength:1,type:"string"},projectId:{description:"Project id or reference.",maxLength:200,minLength:1,type:"string"},requestDepth:{description:"Requested issue depth.",maxLength:30,minLength:1,type:"string"},status:{description:"New issue status.",maxLength:100,minLength:1,type:"string"},title:{description:"Issue title.",maxLength:500,minLength:1,type:"string"}},required:["issue"],type:"object"}},{capabilityId:"issue.review",name:"rudder_issue_review",description:"Record a structured reviewer decision with a required comment.",semanticDescription:"Record a structured reviewer decision with a required comment. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Record a structured reviewer decision with a required comment"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,anyOf:[{required:["comment"]},{required:["body"]}],properties:{body:{description:"Direct Markdown body.",maxLength:5e5,minLength:1,type:"string"},comment:{description:"Direct Markdown body.",maxLength:5e5,minLength:1,type:"string"},decision:{description:"Structured review decision.",enum:["approve","request_changes","needs_followup","blocked"],maxLength:30,minLength:1,type:"string"},issue:{description:"Issue UUID, identifier, or short reference.",maxLength:200,minLength:1,type:"string"}},required:["issue","decision"],type:"object"}},{capabilityId:"issue.commit",name:"rudder_issue_commit",description:"Report a code commit created during issue work as structured issue activity.",semanticDescription:"Report a code commit created during issue work as structured issue activity. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Report a code commit created during issue work as structured issue activity"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{branch:{description:"Git branch name.",maxLength:500,minLength:1,type:"string"},count:{description:"Number of commits represented.",maximum:1e4,minimum:1,type:"number"},issue:{description:"Issue UUID, identifier, or short reference.",maxLength:200,minLength:1,type:"string"},message:{description:"Commit subject or status message.",maxLength:2e3,minLength:1,type:"string"},repoPath:{description:"Repository path.",maxLength:8192,minLength:1,type:"string"},sha:{description:"Git commit SHA.",maxLength:100,minLength:1,type:"string"},workspacePath:{description:"Workspace path.",maxLength:8192,minLength:1,type:"string"}},required:["issue","sha","message"],type:"object"}},{capabilityId:"issue.done",name:"rudder_issue_done",description:"Mark an issue done with a required completion comment, optionally uploading images.",semanticDescription:"Mark an issue done with a required completion comment, optionally uploading images. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!0,idempotentHint:!1,readOnlyHint:!1,title:"Mark an issue done with a required completion comment, optionally uploading images"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,anyOf:[{required:["comment"]},{required:["body"]}],properties:{body:{description:"Direct Markdown body.",maxLength:5e5,minLength:1,type:"string"},comment:{description:"Direct Markdown body.",maxLength:5e5,minLength:1,type:"string"},images:{description:"Local image paths to attach.",items:{description:"Local image paths to attach.",maxLength:8192,minLength:1,type:"string"},maxItems:20,type:"array"},issue:{description:"Issue UUID, identifier, or short reference.",maxLength:200,minLength:1,type:"string"}},required:["issue"],type:"object"}},{capabilityId:"issue.block",name:"rudder_issue_block",description:"Request human assistance after bounded recovery attempts; repeated matching claims are audited before the Issue becomes blocked.",semanticDescription:"Request human assistance after bounded recovery attempts; repeated matching claims are audited before the Issue becomes blocked. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!0,idempotentHint:!1,readOnlyHint:!1,title:"Request human assistance after bounded recovery attempts"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,anyOf:[{required:["comment"]},{required:["body"]}],properties:{body:{description:"Direct Markdown body.",maxLength:5e5,minLength:1,type:"string"},comment:{description:"Direct Markdown body.",maxLength:5e5,minLength:1,type:"string"},images:{description:"Local image paths to attach.",items:{description:"Local image paths to attach.",maxLength:8192,minLength:1,type:"string"},maxItems:20,type:"array"},issue:{description:"Issue UUID, identifier, or short reference.",maxLength:200,minLength:1,type:"string"}},required:["issue"],type:"object"}},{capabilityId:"project.list",name:"rudder_project_list",description:"List projects in an organization.",semanticDescription:"List projects in an organization. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List projects in an organization"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{},type:"object"}},{capabilityId:"project.get",name:"rudder_project_get",description:"Read one project by ID or shortname.",semanticDescription:"Read one project by ID or shortname. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read one project by ID or shortname"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{project:{description:"Project UUID or shortname.",maxLength:200,minLength:1,type:"string"}},required:["project"],type:"object"}},{capabilityId:"project.create",name:"rudder_project_create",description:"Create a project in the organization.",semanticDescription:"Create a project in the organization. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Create a project in the organization"},mutating:!0,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{color:{description:"Display color.",maxLength:100,minLength:1,type:"string"},description:{description:"Project description.",maxLength:5e5,minLength:1,type:"string"},goalId:{description:"Goal id or reference.",maxLength:200,minLength:1,type:"string"},goalIds:{description:"Goal ids.",items:{description:"Goal ids.",maxLength:8192,minLength:1,type:"string"},maxItems:100,type:"array"},leadAgentId:{description:"Lead agent id or reference.",maxLength:200,minLength:1,type:"string"},name:{description:"Project name.",maxLength:300,minLength:1,type:"string"},status:{description:"Project status.",maxLength:100,minLength:1,type:"string"},targetDate:{description:"Target date.",maxLength:100,minLength:1,type:"string"}},required:["name"],type:"object"}},{capabilityId:"project.update",name:"rudder_project_update",description:"Update mutable project fields such as name, description, status, goals, lead agent, target date, color, or archivedAt.",semanticDescription:"Update mutable project fields such as name, description, status, goals, lead agent, target date, color, or archivedAt. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Update mutable project fields such as name, description, status, goals, lead agent, target date, color, or archivedAt"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{archivedAt:{description:"Archive timestamp.",maxLength:100,minLength:1,type:"string"},color:{description:"Display color.",maxLength:100,minLength:1,type:"string"},description:{description:"Project description.",maxLength:5e5,minLength:1,type:"string"},goalId:{description:"Goal id or reference.",maxLength:200,minLength:1,type:"string"},goalIds:{description:"Goal ids.",items:{description:"Goal ids.",maxLength:8192,minLength:1,type:"string"},maxItems:100,type:"array"},idempotencyKey:{description:"Stable key for retrying project updates; required when changing Project-Goal links.",maxLength:256,minLength:1,type:"string"},leadAgentId:{description:"Lead agent id or reference.",maxLength:200,minLength:1,type:"string"},name:{description:"Project name.",maxLength:300,minLength:1,type:"string"},project:{description:"Project UUID or shortname.",maxLength:200,minLength:1,type:"string"},status:{description:"Project status.",maxLength:100,minLength:1,type:"string"},targetDate:{description:"Target date.",maxLength:100,minLength:1,type:"string"}},required:["project"],type:"object"}},{capabilityId:"user.activity",name:"rudder_user_activity",description:"Read a user-centered activity ledger with safe excerpts and provenance across chats, issue comments, approval comments, and user actor activity.",semanticDescription:"Read a user-centered activity ledger with safe excerpts and provenance across chats, issue comments, approval comments, and user actor activity. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read a user-centered activity ledger with safe excerpts and provenance across chats, issue comments, approval comments, and user actor activity"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{cursor:{description:"Opaque pagination cursor.",maxLength:2e3,minLength:1,type:"string"},include:{description:"Comma-separated optional sections.",maxLength:500,minLength:1,type:"string"},issueId:{description:"Issue id.",maxLength:200,minLength:1,type:"string"},limit:{description:"Page size.",maximum:100,minimum:1,type:"number"},projectId:{description:"Project id.",maxLength:200,minLength:1,type:"string"},relatedAgentId:{description:"Related agent id.",maxLength:200,minLength:1,type:"string"},since:{description:"Activity start timestamp.",maxLength:100,minLength:1,type:"string"},until:{description:"Activity end timestamp.",maxLength:100,minLength:1,type:"string"},user:{description:"User id, reference, or self.",maxLength:200,minLength:1,type:"string"}},type:"object"}},{capabilityId:"library.file.list",name:"rudder_library_file_list",description:"List Library files and folders; file rows include `libraryEntryId` when a strong reference can be generated.",semanticDescription:"List Library files and folders; file rows include `libraryEntryId` when a strong reference can be generated. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List Library files and folders"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{directory:{description:"Library-relative directory path.",maxLength:8192,minLength:1,type:"string"},path:{description:"Compatibility alias for directory.",maxLength:8192,minLength:1,type:"string"}},type:"object"}},{capabilityId:"library.file.get",name:"rudder_library_file_get",description:"Fallback read when local filesystem access is unavailable; JSON includes `mentionHref` and `markdownLink`.",semanticDescription:"Fallback read when local filesystem access is unavailable; JSON includes `mentionHref` and `markdownLink`. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Fallback read when local filesystem access is unavailable"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{path:{description:"Library-relative file path.",maxLength:8192,minLength:1,type:"string"}},required:["path"],type:"object"}},{capabilityId:"library.file.ref",name:"rudder_library_file_ref",description:"Return the stable Markdown reference for one Library file without printing file content.",semanticDescription:"Return the stable Markdown reference for one Library file without printing file content. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Return the stable Markdown reference for one Library file without printing file content"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{path:{description:"Library-relative file path.",maxLength:8192,minLength:1,type:"string"}},required:["path"],type:"object"}},{capabilityId:"library.file.link",name:"rudder_library_file_link",description:"Compatibility alias for `rudder library file ref <path>`.",semanticDescription:"Compatibility alias for `rudder library file ref <path>`. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Compatibility alias for `rudder library file ref <path>`"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{path:{description:"Library-relative file path.",maxLength:8192,minLength:1,type:"string"}},required:["path"],type:"object"}},{capabilityId:"library.file.put",name:"rudder_library_file_put",description:"Fallback create/update when local filesystem access is unavailable; JSON includes `mentionHref` and `markdownLink`.",semanticDescription:"Fallback create/update when local filesystem access is unavailable; JSON includes `mentionHref` and `markdownLink`. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!0,idempotentHint:!1,readOnlyHint:!1,title:"Fallback create/update when local filesystem access is unavailable"},mutating:!0,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,anyOf:[{required:["body"]},{required:["content"]}],properties:{body:{description:"Direct file content.",maxLength:1e6,minLength:1,type:"string"},content:{description:"Compatibility alias for body.",maxLength:1e6,minLength:1,type:"string"},path:{description:"Library-relative file path.",maxLength:8192,minLength:1,type:"string"}},required:["path"],type:"object"}},{capabilityId:"issue.create",name:"rudder_issue_create",description:"Create a new issue or subtask with the generic issue surface; agent-created issues default to the creating agent when no assignee is supplied.",semanticDescription:"Create a new issue or subtask with the generic issue surface; agent-created issues default to the creating agent when no assignee is supplied. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Create a new issue or subtask with the generic issue surface"},mutating:!0,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{assigneeAgentId:{description:"Assignee agent id or reference.",maxLength:200,minLength:1,type:"string"},billingCode:{description:"Billing code.",maxLength:200,minLength:1,type:"string"},description:{description:"Issue description.",maxLength:5e5,minLength:1,type:"string"},goalId:{description:"Goal id or reference.",maxLength:200,minLength:1,type:"string"},labelIds:{description:"Issue label ids.",items:{description:"Issue label ids.",maxLength:8192,minLength:1,type:"string"},maxItems:100,type:"array"},parentId:{description:"Parent issue id or reference.",maxLength:200,minLength:1,type:"string"},priority:{description:"Issue priority.",maxLength:100,minLength:1,type:"string"},projectId:{description:"Project id or reference.",maxLength:200,minLength:1,type:"string"},requestDepth:{description:"Requested issue depth.",maximum:1e4,minimum:0,type:"number"},status:{description:"Issue status.",maxLength:100,minLength:1,type:"string"},title:{description:"Issue title.",maxLength:500,minLength:1,type:"string"}},required:["title"],type:"object"}},{capabilityId:"approval.get",name:"rudder_approval_get",description:"Read one approval request.",semanticDescription:"Read one approval request. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read one approval request"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{approval:{description:"Approval UUID or short reference.",maxLength:200,minLength:1,type:"string"}},required:["approval"],type:"object"}},{capabilityId:"approval.issues",name:"rudder_approval_issues",description:"List the issues linked to an approval.",semanticDescription:"List the issues linked to an approval. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List the issues linked to an approval"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{approval:{description:"Approval UUID or short reference.",maxLength:200,minLength:1,type:"string"}},required:["approval"],type:"object"}}],TOn=[{capabilityId:"approval.comment",name:"rudder_approval_comment",description:"Add a comment to an approval.",semanticDescription:"Add a comment to an approval. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Add a comment to an approval"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,anyOf:[{required:["body"]},{required:["comment"]}],properties:{approval:{description:"Approval UUID or short reference.",maxLength:200,minLength:1,type:"string"},body:{description:"Direct Markdown body.",maxLength:5e5,minLength:1,type:"string"},comment:{description:"Direct Markdown body.",maxLength:5e5,minLength:1,type:"string"}},required:["approval"],type:"object"}},{capabilityId:"skill.list",name:"rudder_skill_list",description:"List organization-visible skills.",semanticDescription:"List organization-visible skills. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List organization-visible skills"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{},type:"object"}},{capabilityId:"skill.search",name:"rudder_skill_search",description:"Search organization-visible skills by name, slug, description, or source.",semanticDescription:"Search organization-visible skills by name, slug, description, or source. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Search organization-visible skills by name, slug, description, or source"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{query:{description:"Skill name, slug, description, source, or selection key to search for.",maxLength:2e3,minLength:1,type:"string"}},required:["query"],type:"object"}},{capabilityId:"skill.get",name:"rudder_skill_get",description:"Read one organization skill detail.",semanticDescription:"Read one organization skill detail. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read one organization skill detail"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{skill:{description:"Organization skill id.",maxLength:200,minLength:1,type:"string"}},required:["skill"],type:"object"}},{capabilityId:"skill.file",name:"rudder_skill_file",description:"Read one file from an organization skill package.",semanticDescription:"Read one file from an organization skill package. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read one file from an organization skill package"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{path:{description:"Skill package file path.",maxLength:8192,minLength:1,type:"string"},skill:{description:"Organization skill id.",maxLength:200,minLength:1,type:"string"}},required:["skill"],type:"object"}},{capabilityId:"skill.import",name:"rudder_skill_import",description:"Import a skill package into the organization skill library.",semanticDescription:"Import a skill package into the organization skill library. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Import a skill package into the organization skill library"},mutating:!0,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{source:{description:"Local path, URL, or repository reference.",maxLength:8192,minLength:1,type:"string"}},required:["source"],type:"object"}},{capabilityId:"skill.scan-local",name:"rudder_skill_scan_local",description:"Scan local roots for skill packages and import new ones.",semanticDescription:"Scan local roots for skill packages and import new ones. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Scan local roots for skill packages and import new ones"},mutating:!0,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{roots:{description:"Comma-separated local roots.",maxLength:2e4,minLength:1,type:"string"}},type:"object"}},{capabilityId:"skill.scan-projects",name:"rudder_skill_scan_projects",description:"Scan the org workspace and any legacy project workspace records for skill packages and import new ones.",semanticDescription:"Scan the org workspace and any legacy project workspace records for skill packages and import new ones. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Scan the org workspace and any legacy project workspace records for skill packages and import new ones"},mutating:!0,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{projectIds:{description:"Comma-separated project ids.",maxLength:2e4,minLength:1,type:"string"},workspaceIds:{description:"Comma-separated workspace ids.",maxLength:2e4,minLength:1,type:"string"}},type:"object"}},{capabilityId:"plugin.search",name:"rudder_plugin_search",description:"Search installed, local, and discoverable Rudder plugins.",semanticDescription:"Search installed, local, and discoverable Rudder plugins. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Search installed, local, and discoverable Rudder plugins"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{query:{description:"Plugin name, description, publisher, source, or component to search for.",maxLength:2e3,minLength:1,type:"string"}},required:["query"],type:"object"}},{capabilityId:"plugin.get",name:"rudder_plugin_get",description:"Read an installed plugin, including its components and current setup state; use this to resolve plugin:// references.",semanticDescription:"Read an installed plugin, including its components and current setup state; use this to resolve plugin:// references. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read an installed plugin, including its components and current setup state"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{plugin:{description:"Installed plugin UUID from a plugin:// reference or plugin search result.",maxLength:200,minLength:1,type:"string"}},required:["plugin"],type:"object"}},{capabilityId:"browser.tabs",name:"rudder_browser_tabs",description:"List Browser tabs owned by the current Rudder agent run.",semanticDescription:"List Browser tabs owned by the current Rudder agent run. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List Browser tabs owned by the current Rudder agent run"},mutating:!1,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{},type:"object"}},{capabilityId:"browser.user-tabs",name:"rudder_browser_user_tabs",description:"List user-visible tabs currently open in Rudder's built-in Browser without taking control of them.",semanticDescription:"List user-visible tabs currently open in Rudder's built-in Browser without taking control of them. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List user-visible tabs currently open in Rudder's built-in Browser without taking control of them"},mutating:!1,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{},type:"object"}},{capabilityId:"browser.open",name:"rudder_browser_open",description:"Open a run-owned tab in the Rudder Browser.",semanticDescription:"Open a run-owned tab in the Rudder Browser. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1,title:"Open a run-owned tab in the Rudder Browser"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{url:{description:"HTTP or HTTPS URL.",maxLength:8192,minLength:1,type:"string"}},required:["url"],type:"object"}},{capabilityId:"browser.navigate",name:"rudder_browser_navigate",description:"Navigate a run-owned Rudder Browser tab.",semanticDescription:"Navigate a run-owned Rudder Browser tab. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1,title:"Navigate a run-owned Rudder Browser tab"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"},url:{description:"HTTP or HTTPS URL.",maxLength:8192,minLength:1,type:"string"}},required:["tabId","url"],type:"object"}},{capabilityId:"browser.back",name:"rudder_browser_back",description:"Navigate a run-owned Rudder Browser tab back in history.",semanticDescription:"Navigate a run-owned Rudder Browser tab back in history. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Navigate a run-owned Rudder Browser tab back in history"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId"],type:"object"}},{capabilityId:"browser.forward",name:"rudder_browser_forward",description:"Navigate a run-owned Rudder Browser tab forward in history.",semanticDescription:"Navigate a run-owned Rudder Browser tab forward in history. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Navigate a run-owned Rudder Browser tab forward in history"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId"],type:"object"}},{capabilityId:"browser.reload",name:"rudder_browser_reload",description:"Reload a run-owned Rudder Browser tab.",semanticDescription:"Reload a run-owned Rudder Browser tab. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!1,title:"Reload a run-owned Rudder Browser tab"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId"],type:"object"}},{capabilityId:"browser.viewport",name:"rudder_browser_viewport",description:"Inspect, set, or reset the responsive viewport for the current Rudder Browser run.",semanticDescription:"Inspect, set, or reset the responsive viewport for the current Rudder Browser run. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Inspect, set, or reset the responsive viewport for the current Rudder Browser run"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{action:{description:"Viewport action.",enum:["get","set","reset"],type:"string"},height:{description:"Viewport height in CSS pixels.",maximum:2160,minimum:240,type:"number"},width:{description:"Viewport width in CSS pixels.",maximum:3840,minimum:320,type:"number"}},required:["action"],type:"object"}},{capabilityId:"browser.visibility",name:"rudder_browser_visibility",description:"Inspect or change whether the current run's selected Rudder Browser tab is visible.",semanticDescription:"Inspect or change whether the current run's selected Rudder Browser tab is visible. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Inspect or change whether the current run's selected Rudder Browser tab is visible"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{visible:{description:"Whether the selected Agent Browser tab is visible.",type:"boolean"}},type:"object"}},{capabilityId:"browser.snapshot",name:"rudder_browser_snapshot",description:"Capture a bounded DOM and accessibility-oriented snapshot, including frame structure and ephemeral node ids.",semanticDescription:"Capture a bounded DOM and accessibility-oriented snapshot, including frame structure and ephemeral node ids. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Capture a bounded DOM and accessibility-oriented snapshot, including frame structure and ephemeral node ids"},mutating:!1,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{boxes:{description:"Include viewport-relative element boxes.",type:"boolean"},depth:{description:"Maximum snapshot tree depth.",maximum:30,minimum:1,type:"number"},maxNodes:{description:"Maximum snapshot nodes.",maximum:3e3,minimum:1,type:"number"},tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId"],type:"object"}},{capabilityId:"browser.locator",name:"rudder_browser_locator",description:"Perform read-only bounded Browser locator text, attribute, state, count, or wait operations.",semanticDescription:"Perform read-only bounded Browser locator text, attribute, state, count, or wait operations. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Perform read-only bounded Browser locator text, attribute, state, count, or wait operations"},mutating:!1,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{action:{description:"Read-only locator action.",enum:["count","allTextContents","textContent","innerText","attribute","visible","enabled","checked","selected","wait"],type:"string"},locator:{additionalProperties:!1,properties:{and:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},exact:{description:"Require an exact text or attribute match.",type:"boolean"},filter:{additionalProperties:!1,properties:{has:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},hasNot:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},hasNotText:{description:"Excluded descendant text.",maxLength:2e3,type:"string"},hasText:{description:"Required descendant text.",maxLength:2e3,type:"string"},visible:{description:"Filter by current visibility.",type:"boolean"}},type:"object"},frame:{items:{description:"CSS iframe selector.",maxLength:1e3,minLength:1,type:"string"},maxItems:8,type:"array"},index:{description:"Zero-based locator match index.",maximum:499,minimum:0,type:"number"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},or:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},position:{description:"Locator endpoint after an explicit count.",enum:["first","last"],type:"string"},scope:{additionalProperties:!1,properties:{and:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},exact:{description:"Require an exact text or attribute match.",type:"boolean"},filter:{additionalProperties:!1,properties:{has:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},hasNot:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},hasNotText:{description:"Excluded descendant text.",maxLength:2e3,type:"string"},hasText:{description:"Required descendant text.",maxLength:2e3,type:"string"},visible:{description:"Filter by current visibility.",type:"boolean"}},type:"object"},index:{description:"Zero-based locator match index.",maximum:499,minimum:0,type:"number"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},or:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},position:{description:"Locator endpoint after an explicit count.",enum:["first","last"],type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},name:{description:"Attribute name for attribute reads.",maxLength:200,type:"string"},state:{description:"Wait state.",enum:["attached","detached","visible","hidden"],type:"string"},tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"},timeoutMs:{description:"Wait timeout in milliseconds.",maximum:3e4,minimum:0,type:"number"}},required:["tabId","action","locator"],type:"object"}}],_On=[{capabilityId:"browser.cua",name:"rudder_browser_cua",description:"Perform trusted coordinate mouse, scroll, drag, keyboard, and text input in a run-owned Browser tab.",semanticDescription:"Perform trusted coordinate mouse, scroll, drag, keyboard, and text input in a run-owned Browser tab. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Perform trusted coordinate mouse, scroll, drag, keyboard, and text input in a run-owned Browser tab"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{action:{description:"Coordinate input or inspection action.",enum:["click","doubleClick","move","scroll","drag","keypress","type","elementInfo"],type:"string"},button:{oneOf:[{description:"Mouse button number.",maximum:5,minimum:1,type:"number"},{description:"Mouse button.",enum:["left","middle","right"],type:"string"}]},keys:{items:{description:"Keyboard key or modifier.",maxLength:100,minLength:1,type:"string"},maxItems:10,type:"array"},path:{items:{additionalProperties:!1,properties:{x:{description:"Path X coordinate.",type:"number"},y:{description:"Path Y coordinate.",type:"number"}},required:["x","y"],type:"object"},maxItems:200,minItems:2,type:"array"},scrollX:{description:"Horizontal scroll delta.",type:"number"},scrollY:{description:"Vertical scroll delta.",type:"number"},tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"},text:{description:"Text to type.",maxLength:1e5,type:"string"},x:{description:"Viewport X coordinate.",type:"number"},y:{description:"Viewport Y coordinate.",type:"number"}},required:["tabId","action"],type:"object"}},{capabilityId:"browser.dom-cua",name:"rudder_browser_dom_cua",description:"Inspect a bounded read-only DOM snapshot with ephemeral node ids.",semanticDescription:"Inspect a bounded read-only DOM snapshot with ephemeral node ids. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Inspect a bounded read-only DOM snapshot with ephemeral node ids"},mutating:!1,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{action:{description:"Read-only DOM snapshot action.",enum:["get"],type:"string"},depth:{description:"Maximum DOM depth.",maximum:30,minimum:1,type:"number"},maxNodes:{description:"Maximum DOM nodes.",maximum:3e3,minimum:1,type:"number"},tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId","action"],type:"object"}},{capabilityId:"browser.dialog",name:"rudder_browser_dialog",description:"Inspect, accept, or dismiss the active JavaScript dialog in a run-owned Browser tab.",semanticDescription:"Inspect, accept, or dismiss the active JavaScript dialog in a run-owned Browser tab. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Inspect, accept, or dismiss the active JavaScript dialog in a run-owned Browser tab"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{action:{description:"Dialog action.",enum:["get","accept","dismiss"],type:"string"},promptText:{description:"Prompt response text.",maxLength:1e4,type:"string"},tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId","action"],type:"object"}},{capabilityId:"browser.clipboard",name:"rudder_browser_clipboard",description:"Read or write the isolated virtual clipboard for the current Browser run without touching the OS clipboard.",semanticDescription:"Read or write the isolated virtual clipboard for the current Browser run without touching the OS clipboard. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!0,idempotentHint:!1,readOnlyHint:!1,title:"Read or write the isolated virtual clipboard for the current Browser run without touching the OS clipboard"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{action:{description:"Virtual clipboard action.",enum:["read","readText","write","writeText","clear"],type:"string"},items:{items:{additionalProperties:!1,properties:{entries:{items:{additionalProperties:!1,properties:{base64:{description:"Base64 clipboard payload.",maxLength:65e4,type:"string"},mimeType:{description:"Clipboard MIME type.",maxLength:200,minLength:1,type:"string"},text:{description:"Text clipboard payload.",maxLength:5e5,type:"string"}},required:["mimeType"],type:"object"},maxItems:20,type:"array"},presentationStyle:{description:"Clipboard presentation style.",enum:["unspecified","inline","attachment"],type:"string"}},required:["entries"],type:"object"},maxItems:20,type:"array"},text:{description:"Plain clipboard text.",maxLength:5e5,type:"string"}},required:["action"],type:"object"}},{capabilityId:"browser.logs",name:"rudder_browser_logs",description:"Read bounded console and runtime logs captured for a run-owned Browser tab.",semanticDescription:"Read bounded console and runtime logs captured for a run-owned Browser tab. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!0,idempotentHint:!1,readOnlyHint:!1,title:"Read bounded console and runtime logs captured for a run-owned Browser tab"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{clear:{description:"Clear the tab log buffer after reading.",type:"boolean"},filter:{description:"Case-insensitive log substring filter.",maxLength:2e3,type:"string"},levels:{items:{description:"Log level.",enum:["debug","info","log","warn","error"],type:"string"},maxItems:5,type:"array"},limit:{description:"Maximum log entries.",maximum:500,minimum:1,type:"number"},tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId"],type:"object"}},{capabilityId:"browser.download",name:"rudder_browser_download",description:"Download explicit locator media without dispatching page input into a bounded run-owned artifact.",semanticDescription:"Download explicit locator media without dispatching page input into a bounded run-owned artifact. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1,title:"Download explicit locator media without dispatching page input into a bounded run-owned artifact"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{locator:{additionalProperties:!1,properties:{and:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},exact:{description:"Require an exact text or attribute match.",type:"boolean"},filter:{additionalProperties:!1,properties:{has:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},hasNot:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},hasNotText:{description:"Excluded descendant text.",maxLength:2e3,type:"string"},hasText:{description:"Required descendant text.",maxLength:2e3,type:"string"},visible:{description:"Filter by current visibility.",type:"boolean"}},type:"object"},frame:{items:{description:"CSS iframe selector.",maxLength:1e3,minLength:1,type:"string"},maxItems:8,type:"array"},index:{description:"Zero-based locator match index.",maximum:499,minimum:0,type:"number"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},or:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},position:{description:"Locator endpoint after an explicit count.",enum:["first","last"],type:"string"},scope:{additionalProperties:!1,properties:{and:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},exact:{description:"Require an exact text or attribute match.",type:"boolean"},filter:{additionalProperties:!1,properties:{has:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},hasNot:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},hasNotText:{description:"Excluded descendant text.",maxLength:2e3,type:"string"},hasText:{description:"Required descendant text.",maxLength:2e3,type:"string"},visible:{description:"Filter by current visibility.",type:"boolean"}},type:"object"},index:{description:"Zero-based locator match index.",maximum:499,minimum:0,type:"number"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},or:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},position:{description:"Locator endpoint after an explicit count.",enum:["first","last"],type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},mode:{description:"Read-only media download mode.",enum:["media"],type:"string"},tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId","mode","locator"],type:"object"}},{capabilityId:"browser.assets",name:"rudder_browser_assets",description:"List page assets or bundle an explicit bounded selection into a run-owned temporary artifact.",semanticDescription:"List page assets or bundle an explicit bounded selection into a run-owned temporary artifact. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"List page assets or bundle an explicit bounded selection into a run-owned temporary artifact"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{action:{description:"Asset action.",enum:["list","bundle"],type:"string"},assetIds:{items:{description:"Asset id.",maxLength:160,type:"string"},maxItems:100,minItems:1,type:"array"},inventoryId:{description:"Prior asset inventory id.",maxLength:160,type:"string"},kinds:{items:{description:"Asset kind.",enum:["font","image","stylesheet","video"],type:"string"},maxItems:4,minItems:1,type:"array"},tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId","action"],type:"object"}},{capabilityId:"browser.content",name:"rudder_browser_content",description:"Export current page content or an eligible Google Workspace document into a bounded run-owned artifact.",semanticDescription:"Export current page content or an eligible Google Workspace document into a bounded run-owned artifact. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1,title:"Export current page content or an eligible Google Workspace document into a bounded run-owned artifact"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{format:{description:"Content export format.",enum:["text","pdf","md","docx","xlsx","csv","pptx"],type:"string"},tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId","format"],type:"object"}},{capabilityId:"browser.wait",name:"rudder_browser_wait",description:"Wait for bounded URL, text, disappearance, or time conditions in a run-owned Browser tab.",semanticDescription:"Wait for bounded URL, text, disappearance, or time conditions in a run-owned Browser tab. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Wait for bounded URL, text, disappearance, or time conditions in a run-owned Browser tab"},mutating:!1,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"},text:{description:"Text that must appear.",maxLength:1e4,type:"string"},textGone:{description:"Text that must disappear.",maxLength:1e4,type:"string"},timeMs:{description:"Fixed bounded delay in milliseconds.",maximum:3e4,minimum:0,type:"number"},timeoutMs:{description:"Wait timeout in milliseconds.",maximum:3e4,minimum:0,type:"number"},url:{description:"URL substring.",maxLength:8192,type:"string"}},required:["tabId"],type:"object"}},{capabilityId:"browser.read",name:"rudder_browser_read",description:"Read a structured snapshot from a run-owned Rudder Browser tab.",semanticDescription:"Read a structured snapshot from a run-owned Rudder Browser tab. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read a structured snapshot from a run-owned Rudder Browser tab"},mutating:!1,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId"],type:"object"}},{capabilityId:"browser.click",name:"rudder_browser_click",description:"Click an element reference returned by Rudder Browser read.",semanticDescription:"Click an element reference returned by Rudder Browser read. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Click an element reference returned by Rudder Browser read"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{ref:{description:"Element reference returned by rudder_browser_read.",maxLength:160,type:"string"},tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId","ref"],type:"object"}},{capabilityId:"browser.type",name:"rudder_browser_type",description:"Type into an element reference in a run-owned Rudder Browser tab.",semanticDescription:"Type into an element reference in a run-owned Rudder Browser tab. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Type into an element reference in a run-owned Rudder Browser tab"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{ref:{description:"Element reference returned by rudder_browser_read.",maxLength:160,type:"string"},submit:{description:"Submit the owning form after typing.",type:"boolean"},tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"},text:{description:"Text to enter.",maxLength:1e5,type:"string"}},required:["tabId","ref","text"],type:"object"}}],MOn=[{capabilityId:"browser.screenshot",name:"rudder_browser_screenshot",description:"Capture a screenshot of a run-owned Rudder Browser tab.",semanticDescription:"Capture a screenshot of a run-owned Rudder Browser tab. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Capture a screenshot of a run-owned Rudder Browser tab"},mutating:!1,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{clip:{additionalProperties:!1,properties:{height:{description:"Clip height.",minimum:1,type:"number"},width:{description:"Clip width.",minimum:1,type:"number"},x:{description:"Clip X coordinate.",type:"number"},y:{description:"Clip Y coordinate.",type:"number"}},required:["x","y","width","height"],type:"object"},format:{description:"Image format.",enum:["png","jpeg"],type:"string"},fullPage:{description:"Capture the full scrollable page.",type:"boolean"},locator:{additionalProperties:!1,properties:{and:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},exact:{description:"Require an exact text or attribute match.",type:"boolean"},filter:{additionalProperties:!1,properties:{has:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},hasNot:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},hasNotText:{description:"Excluded descendant text.",maxLength:2e3,type:"string"},hasText:{description:"Required descendant text.",maxLength:2e3,type:"string"},visible:{description:"Filter by current visibility.",type:"boolean"}},type:"object"},frame:{items:{description:"CSS iframe selector.",maxLength:1e3,minLength:1,type:"string"},maxItems:8,type:"array"},index:{description:"Zero-based locator match index.",maximum:499,minimum:0,type:"number"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},or:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},position:{description:"Locator endpoint after an explicit count.",enum:["first","last"],type:"string"},scope:{additionalProperties:!1,properties:{and:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},exact:{description:"Require an exact text or attribute match.",type:"boolean"},filter:{additionalProperties:!1,properties:{has:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},hasNot:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},hasNotText:{description:"Excluded descendant text.",maxLength:2e3,type:"string"},hasText:{description:"Required descendant text.",maxLength:2e3,type:"string"},visible:{description:"Filter by current visibility.",type:"boolean"}},type:"object"},index:{description:"Zero-based locator match index.",maximum:499,minimum:0,type:"number"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},or:{additionalProperties:!1,properties:{exact:{description:"Require an exact text or attribute match.",type:"boolean"},name:{description:"Accessible name used with the role strategy.",maxLength:2e3,type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},position:{description:"Locator endpoint after an explicit count.",enum:["first","last"],type:"string"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},strategy:{description:"Locator strategy.",enum:["css","testId","href","role","label","placeholder","text"],type:"string"},value:{description:"Selector, role, label, placeholder, href, test id, or text value.",maxLength:2e3,minLength:1,type:"string"}},required:["strategy","value"],type:"object"},quality:{description:"JPEG quality.",maximum:100,minimum:1,type:"number"},tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId"],type:"object"}},{capabilityId:"browser.close",name:"rudder_browser_close",description:"Close a run-owned Rudder Browser tab.",semanticDescription:"Close a run-owned Rudder Browser tab. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!1,title:"Close a run-owned Rudder Browser tab"},mutating:!0,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{tabId:{description:"Run-owned Rudder Browser tab id.",maxLength:160,minLength:1,type:"string"}},required:["tabId"],type:"object"}},{capabilityId:"automation.list",name:"rudder_automation_list",description:"List automations for an organization with compact local filters.",semanticDescription:"List automations for an organization with compact local filters. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List automations for an organization with compact local filters"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{assigneeAgentId:{description:"Assignee agent id.",maxLength:200,minLength:1,type:"string"},outputMode:{description:"Output mode filter.",maxLength:100,minLength:1,type:"string"},projectId:{description:"Project id.",maxLength:200,minLength:1,type:"string"},status:{description:"Automation status filter.",maxLength:100,minLength:1,type:"string"}},type:"object"}},{capabilityId:"automation.get",name:"rudder_automation_get",description:"Read one automation detail including triggers and recent runs.",semanticDescription:"Read one automation detail including triggers and recent runs. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read one automation detail including triggers and recent runs"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{automation:{description:"Automation UUID or short reference.",maxLength:200,minLength:1,type:"string"}},required:["automation"],type:"object"}},{capabilityId:"automation.runs",name:"rudder_automation_runs",description:"List recent runs for one automation.",semanticDescription:"List recent runs for one automation. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List recent runs for one automation"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{automation:{description:"Automation UUID or short reference.",maxLength:200,minLength:1,type:"string"},limit:{description:"Maximum run rows.",maximum:100,minimum:1,type:"number"}},required:["automation"],type:"object"}},{capabilityId:"automation.triggers.list",name:"rudder_automation_triggers_list",description:"List triggers configured for one automation.",semanticDescription:"List triggers configured for one automation. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List triggers configured for one automation"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{automation:{description:"Automation UUID or short reference.",maxLength:200,minLength:1,type:"string"}},required:["automation"],type:"object"}},{capabilityId:"automation.triggers.create",name:"rudder_automation_triggers_create",description:"Create a schedule, webhook, or API trigger through the governed automation API.",semanticDescription:"Create a schedule, webhook, or API trigger through the governed automation API. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Create a schedule, webhook, or API trigger through the governed automation API"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{automation:{description:"Automation UUID or short reference.",maxLength:200,minLength:1,type:"string"},cronExpression:{description:"Cron expression.",maxLength:500,minLength:1,type:"string"},disabled:{description:"Create the trigger disabled.",type:"boolean"},enabled:{description:"Create the trigger enabled.",type:"boolean"},kind:{description:"Trigger kind.",maxLength:100,minLength:1,type:"string"},label:{description:"Trigger label.",maxLength:300,minLength:1,type:"string"},payload:{description:"JSON payload object or JSON string.",type:["object","string"]},replayWindowSec:{description:"Webhook replay window in seconds.",maxLength:30,minLength:1,type:"string"},signingMode:{description:"Webhook signing mode.",maxLength:100,minLength:1,type:"string"},timezone:{description:"IANA timezone.",maxLength:200,minLength:1,type:"string"}},required:["automation"],type:"object"}},{capabilityId:"automation.triggers.update",name:"rudder_automation_triggers_update",description:"Update an automation trigger through the governed automation API.",semanticDescription:"Update an automation trigger through the governed automation API. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Update an automation trigger through the governed automation API"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{cronExpression:{description:"Cron expression.",maxLength:500,minLength:1,type:"string"},disabled:{description:"Disable the trigger.",type:"boolean"},enabled:{description:"Enable the trigger.",type:"boolean"},label:{description:"Trigger label.",maxLength:300,minLength:1,type:"string"},payload:{description:"JSON payload object or JSON string.",type:["object","string"]},replayWindowSec:{description:"Webhook replay window in seconds.",maxLength:30,minLength:1,type:"string"},signingMode:{description:"Webhook signing mode.",maxLength:100,minLength:1,type:"string"},timezone:{description:"IANA timezone.",maxLength:200,minLength:1,type:"string"},trigger:{description:"Automation trigger UUID or short reference.",maxLength:200,minLength:1,type:"string"}},required:["trigger"],type:"object"}},{capabilityId:"automation.triggers.delete",name:"rudder_automation_triggers_delete",description:"Delete an automation trigger through the governed automation API.",semanticDescription:"Delete an automation trigger through the governed automation API. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!0,idempotentHint:!1,readOnlyHint:!1,title:"Delete an automation trigger through the governed automation API"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{trigger:{description:"Automation trigger UUID or short reference.",maxLength:200,minLength:1,type:"string"}},required:["trigger"],type:"object"}},{capabilityId:"automation.triggers.rotate-secret",name:"rudder_automation_triggers_rotate_secret",description:"Rotate an automation webhook trigger secret through the governed automation API.",semanticDescription:"Rotate an automation webhook trigger secret through the governed automation API. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!0,idempotentHint:!1,readOnlyHint:!1,title:"Rotate an automation webhook trigger secret through the governed automation API"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{trigger:{description:"Automation trigger UUID or short reference.",maxLength:200,minLength:1,type:"string"}},required:["trigger"],type:"object"}},{capabilityId:"automation.create",name:"rudder_automation_create",description:"Create an automation through the governed automation API.",semanticDescription:"Create an automation through the governed automation API. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Create an automation through the governed automation API"},mutating:!0,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{assigneeAgentId:{description:"Assignee agent id.",maxLength:200,minLength:1,type:"string"},catchUpPolicy:{description:"Catch-up policy.",maxLength:100,minLength:1,type:"string"},concurrencyPolicy:{description:"Concurrency policy.",maxLength:100,minLength:1,type:"string"},description:{description:"Compatibility alias for instructions.",maxLength:5e5,minLength:1,type:"string"},goalId:{description:"Goal id.",maxLength:200,minLength:1,type:"string"},instructions:{description:"Automation instructions.",maxLength:5e5,minLength:1,type:"string"},notifyOnIssueCreated:{description:"Notify when an issue is created.",type:"boolean"},outputMode:{description:"Automation output mode.",maxLength:100,minLength:1,type:"string"},parentIssueId:{description:"Parent issue id.",maxLength:200,minLength:1,type:"string"},payload:{description:"JSON payload object or JSON string.",type:["object","string"]},priority:{description:"Issue priority.",maxLength:100,minLength:1,type:"string"},projectId:{description:"Project id.",maxLength:200,minLength:1,type:"string"},status:{description:"Automation status.",maxLength:100,minLength:1,type:"string"},title:{description:"Automation title.",maxLength:500,minLength:1,type:"string"}},type:"object"}},{capabilityId:"automation.update",name:"rudder_automation_update",description:"Update automation fields through the governed automation API.",semanticDescription:"Update automation fields through the governed automation API. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Update automation fields through the governed automation API"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{assigneeAgentId:{description:"Assignee agent id.",maxLength:200,minLength:1,type:"string"},automation:{description:"Automation UUID or short reference.",maxLength:200,minLength:1,type:"string"},catchUpPolicy:{description:"Catch-up policy.",maxLength:100,minLength:1,type:"string"},concurrencyPolicy:{description:"Concurrency policy.",maxLength:100,minLength:1,type:"string"},description:{description:"Compatibility alias for instructions.",maxLength:5e5,minLength:1,type:"string"},goalId:{description:"Goal id.",maxLength:200,minLength:1,type:"string"},instructions:{description:"Automation instructions.",maxLength:5e5,minLength:1,type:"string"},notifyOnIssueCreated:{description:"Notify when an issue is created.",type:"boolean"},outputMode:{description:"Automation output mode.",maxLength:100,minLength:1,type:"string"},parentIssueId:{description:"Parent issue id.",maxLength:200,minLength:1,type:"string"},payload:{description:"JSON payload object or JSON string.",type:["object","string"]},priority:{description:"Issue priority.",maxLength:100,minLength:1,type:"string"},projectId:{description:"Project id.",maxLength:200,minLength:1,type:"string"},status:{description:"Automation status.",maxLength:100,minLength:1,type:"string"},title:{description:"Automation title.",maxLength:500,minLength:1,type:"string"}},required:["automation"],type:"object"}},{capabilityId:"automation.enable",name:"rudder_automation_enable",description:"Enable an automation by setting status to active.",semanticDescription:"Enable an automation by setting status to active. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Enable an automation by setting status to active"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{automation:{description:"Automation UUID or short reference.",maxLength:200,minLength:1,type:"string"}},required:["automation"],type:"object"}}],EOn=[{capabilityId:"automation.disable",name:"rudder_automation_disable",description:"Disable an automation by setting status to paused.",semanticDescription:"Disable an automation by setting status to paused. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!0,idempotentHint:!1,readOnlyHint:!1,title:"Disable an automation by setting status to paused"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{automation:{description:"Automation UUID or short reference.",maxLength:200,minLength:1,type:"string"}},required:["automation"],type:"object"}},{capabilityId:"automation.run",name:"rudder_automation_run",description:"Trigger a manual automation run.",semanticDescription:"Trigger a manual automation run. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Trigger a manual automation run"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{automation:{description:"Automation UUID or short reference.",maxLength:200,minLength:1,type:"string"},idempotencyKey:{description:"Idempotency key.",maxLength:500,minLength:1,type:"string"},payload:{description:"JSON payload object or JSON string.",type:["object","string"]},source:{description:"Invocation source.",maxLength:500,minLength:1,type:"string"},triggerId:{description:"Trigger id.",maxLength:200,minLength:1,type:"string"}},required:["automation"],type:"object"}},{capabilityId:"chat.list",name:"rudder_chat_list",description:"List chat conversations without dumping full message history.",semanticDescription:"List chat conversations without dumping full message history. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List chat conversations without dumping full message history"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{limit:{description:"Maximum chat rows.",maximum:100,minimum:1,type:"number"},query:{description:"Optional chat query.",maxLength:2e3,minLength:1,type:"string"},status:{description:"Chat status filter.",maxLength:100,minLength:1,type:"string"}},type:"object"}},{capabilityId:"chat.search",name:"rudder_chat_search",description:"Search chats with bounded snippets and optional scope filtering.",semanticDescription:"Search chats with bounded snippets and optional scope filtering. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Search chats with bounded snippets and optional scope filtering"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{limit:{description:"Maximum matches.",maximum:100,minimum:1,type:"number"},query:{description:"Non-empty chat search query.",maxLength:2e3,minLength:1,type:"string"},scope:{description:"Search scope.",maxLength:100,minLength:1,type:"string"},snippetChars:{description:"Maximum snippet characters.",maximum:1e4,minimum:100,type:"number"},status:{description:"Chat status filter.",maxLength:100,minLength:1,type:"string"}},required:["query"],type:"object"}},{capabilityId:"chat.get",name:"rudder_chat_get",description:"Read one chat conversation record.",semanticDescription:"Read one chat conversation record. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read one chat conversation record"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{chat:{description:"Chat conversation UUID or short reference.",maxLength:200,minLength:1,type:"string"}},required:["chat"],type:"object"}},{capabilityId:"chat.messages",name:"rudder_chat_messages",description:"Read bounded chat messages with page cursors; transcript output is omitted unless requested.",semanticDescription:"Read bounded chat messages with page cursors; transcript output is omitted unless requested. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read bounded chat messages with page cursors"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{chat:{description:"Chat conversation UUID or short reference.",maxLength:200,minLength:1,type:"string"},cursor:{description:"Opaque pagination cursor.",maxLength:2e3,minLength:1,type:"string"},includeOutput:{description:"Compatibility alias for includeTranscript.",type:"boolean"},includeTranscript:{description:"Include bounded transcript data.",type:"boolean"},limit:{description:"Maximum message rows.",maximum:100,minimum:1,type:"number"},maxOutputChars:{description:"Maximum output characters per row.",maximum:2e4,minimum:100,type:"number"}},required:["chat"],type:"object"}},{capabilityId:"chat.transcript",name:"rudder_chat_transcript",description:"Read paginated chat messages with assistant transcript entries clipped in human output.",semanticDescription:"Read paginated chat messages with assistant transcript entries clipped in human output. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read paginated chat messages with assistant transcript entries clipped in human output"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{chat:{description:"Chat conversation UUID or short reference.",maxLength:200,minLength:1,type:"string"},cursor:{description:"Opaque pagination cursor.",maxLength:2e3,minLength:1,type:"string"},limit:{description:"Maximum transcript rows.",maximum:100,minimum:1,type:"number"},maxOutputChars:{description:"Maximum output characters per row.",maximum:2e4,minimum:100,type:"number"}},required:["chat"],type:"object"}},{capabilityId:"chat.read",name:"rudder_chat_read",description:"Read a bounded recent-message snapshot for one chat with page cursors.",semanticDescription:"Read a bounded recent-message snapshot for one chat with page cursors. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read a bounded recent-message snapshot for one chat with page cursors"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{chat:{description:"Chat conversation UUID or short reference.",maxLength:200,minLength:1,type:"string"},cursor:{description:"Opaque pagination cursor.",maxLength:2e3,minLength:1,type:"string"},includeOutput:{description:"Compatibility alias for includeTranscript.",type:"boolean"},includeTranscript:{description:"Include bounded transcript data.",type:"boolean"},limit:{description:"Maximum message rows.",maximum:100,minimum:1,type:"number"},maxOutputChars:{description:"Maximum output characters per row.",maximum:2e4,minimum:100,type:"number"},turnLimit:{description:"Maximum transcript turns.",maximum:100,minimum:1,type:"number"}},required:["chat"],type:"object"}},{capabilityId:"chat.create",name:"rudder_chat_create",description:"Create a chat conversation with its first message.",semanticDescription:"Create a chat conversation with its first message. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Create a chat conversation with its first message"},mutating:!0,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{body:{description:"Initial agent-authored chat message.",maxLength:5e5,minLength:1,type:"string"},issueCreationMode:{description:"Issue creation mode.",maxLength:100,minLength:1,type:"string"},payload:{description:"JSON payload object or JSON string.",type:["object","string"]},planMode:{description:"Start the chat in plan mode.",type:"boolean"},preferredAgentId:{description:"Preferred responding agent id.",maxLength:200,minLength:1,type:"string"},summary:{description:"Chat summary.",maxLength:1e4,minLength:1,type:"string"},title:{description:"Chat title.",maxLength:500,minLength:1,type:"string"}},required:["body"],type:"object"}},{capabilityId:"chat.send",name:"rudder_chat_send",description:"Send an agent-authored message directly to the operator in a chat.",semanticDescription:"Send an agent-authored message directly to the operator in a chat. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Send an agent-authored message directly to the operator in a chat"},mutating:!0,requiresOrgId:!1,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{body:{description:"Agent-authored chat message.",maxLength:5e5,minLength:1,type:"string"},chat:{description:"Chat conversation UUID or short reference.",maxLength:200,minLength:1,type:"string"},editUserMessageId:{description:"User message id to edit.",maxLength:200,minLength:1,type:"string"}},required:["chat","body"],type:"object"}},{capabilityId:"chat.archive",name:"rudder_chat_archive",description:"Archive a chat conversation without deleting it.",semanticDescription:"Archive a chat conversation without deleting it. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!0,idempotentHint:!1,readOnlyHint:!1,title:"Archive a chat conversation without deleting it"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{chat:{description:"Chat conversation UUID or short reference.",maxLength:200,minLength:1,type:"string"}},required:["chat"],type:"object"}},{capabilityId:"runs.list",name:"rudder_runs_list",description:"List lightweight run summaries with stable pagination and filters; use --full only for legacy full-row compatibility.",semanticDescription:"List lightweight run summaries with stable pagination and filters; use --full only for legacy full-row compatibility. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List lightweight run summaries with stable pagination and filters"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{createdBefore:{description:"Only runs created before this timestamp.",maxLength:100,minLength:1,type:"string"},cursor:{description:"Opaque pagination cursor.",maxLength:2e3,minLength:1,type:"string"},issueId:{description:"Linked issue id filter.",maxLength:200,minLength:1,type:"string"},limit:{description:"Summary page size.",maximum:100,minimum:1,type:"number"},loadedSkill:{description:"Loaded skill filter.",maxLength:500,minLength:1,type:"string"},relatedAgentId:{description:"Agent id filter.",maxLength:200,minLength:1,type:"string"},runIdPrefix:{description:"Run id prefix filter.",maxLength:200,minLength:1,type:"string"},runtime:{description:"Runtime type filter.",maxLength:100,minLength:1,type:"string"},status:{description:"Run status filter.",maxLength:100,minLength:1,type:"string"},updatedAfter:{description:"Only runs updated after this timestamp.",maxLength:100,minLength:1,type:"string"},usedSkill:{description:"Used skill filter.",maxLength:500,minLength:1,type:"string"}},type:"object"}},{capabilityId:"runs.by-skill",name:"rudder_runs_by_skill",description:"Build a paginated skill evidence packet from lightweight run summaries; use --full only for legacy full-row compatibility.",semanticDescription:"Build a paginated skill evidence packet from lightweight run summaries; use --full only for legacy full-row compatibility. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Build a paginated skill evidence packet from lightweight run summaries"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{createdBefore:{description:"Only runs created before this timestamp.",maxLength:100,minLength:1,type:"string"},cursor:{description:"Opaque pagination cursor.",maxLength:2e3,minLength:1,type:"string"},evidence:{description:"Skill evidence type.",enum:["used","loaded"],maxLength:20,minLength:1,type:"string"},issueId:{description:"Linked issue id filter.",maxLength:200,minLength:1,type:"string"},limit:{description:"Summary page size.",maximum:100,minimum:1,type:"number"},relatedAgentId:{description:"Agent id filter.",maxLength:200,minLength:1,type:"string"},runtime:{description:"Runtime type filter.",maxLength:100,minLength:1,type:"string"},skill:{description:"Skill key or display name.",maxLength:500,minLength:1,type:"string"},status:{description:"Run status filter.",maxLength:100,minLength:1,type:"string"}},required:["skill"],type:"object"}},{capabilityId:"runs.get",name:"rudder_runs_get",description:"Read one bounded run summary; use --full only from a direct trusted CLI for raw detail.",semanticDescription:"Read one bounded run summary; use --full only from a direct trusted CLI for raw detail. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read one bounded run summary"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{run:{description:"Run UUID, typed short reference (run_<prefix>), or legacy bare short prefix.",maxLength:200,minLength:1,type:"string"}},required:["run"],type:"object"}},{capabilityId:"runs.events",name:"rudder_runs_events",description:"List a bounded page of persisted run events with a lossless opaque cursor and clipped payload previews.",semanticDescription:"List a bounded page of persisted run events with a lossless opaque cursor and clipped payload previews. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List a bounded page of persisted run events with a lossless opaque cursor and clipped payload previews"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{afterSeq:{description:"Legacy sequence-only cursor.",maximum:1e7,minimum:0,type:"number"},cursor:{description:"Opaque pagination cursor.",maxLength:2e3,minLength:1,type:"string"},limit:{description:"Event page size.",maximum:500,minimum:1,type:"number"},maxChars:{description:"Maximum preview characters per event.",maximum:2e4,minimum:100,type:"number"},run:{description:"Run UUID, typed short reference (run_<prefix>), or legacy bare short prefix.",maxLength:200,minLength:1,type:"string"}},required:["run"],type:"object"}},{capabilityId:"runs.log",name:"rudder_runs_log",description:"Read a bounded byte range of stored run log content.",semanticDescription:"Read a bounded byte range of stored run log content. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read a bounded byte range of stored run log content"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{limitBytes:{description:"Maximum bytes for ranged read.",maximum:1e6,minimum:1,type:"number"},maxChars:{description:"Maximum displayed log characters.",maximum:1e5,minimum:100,type:"number"},offset:{description:"Byte offset for ranged read.",maximum:1e9,minimum:0,type:"number"},run:{description:"Run UUID, typed short reference (run_<prefix>), or legacy bare short prefix.",maxLength:200,minLength:1,type:"string"}},required:["run"],type:"object"}},{capabilityId:"runs.transcript",name:"rudder_runs_transcript",description:"Read a compact server-normalized transcript; --json changes encoding only and --full is direct-CLI-only raw access.",semanticDescription:"Read a compact server-normalized transcript; --json changes encoding only and --full is direct-CLI-only raw access. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read a compact server-normalized transcript"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{aroundError:{description:"Transcript error step id.",maxLength:200,minLength:1,type:"string"},chronological:{description:"Return oldest-first rows.",type:"boolean"},contextTurns:{description:"Turns around the selected error.",maximum:20,minimum:1,type:"number"},cursor:{description:"Opaque pagination cursor.",maxLength:2e3,minLength:1,type:"string"},errorsOnly:{description:"Return only error rows.",type:"boolean"},includeOutput:{description:"Include clipped row output.",type:"boolean"},maxChars:{description:"Maximum output characters per row.",maximum:2e4,minimum:100,type:"number"},narrative:{description:"Use narrative row formatting.",type:"boolean"},run:{description:"Run UUID, typed short reference (run_<prefix>), or legacy bare short prefix.",maxLength:200,minLength:1,type:"string"},turnLimit:{description:"Maximum turns.",maximum:100,minimum:1,type:"number"}},required:["run"],type:"object"}},{capabilityId:"runs.errors",name:"rudder_runs_errors",description:"List failed tool calls, stderr, runtime failures, and jump-to-context commands.",semanticDescription:"List failed tool calls, stderr, runtime failures, and jump-to-context commands. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List failed tool calls, stderr, runtime failures, and jump-to-context commands"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{cursor:{description:"Opaque pagination cursor.",maxLength:2e3,minLength:1,type:"string"},maxChars:{description:"Maximum output characters per error.",maximum:2e4,minimum:100,type:"number"},run:{description:"Run UUID, typed short reference (run_<prefix>), or legacy bare short prefix.",maxLength:200,minLength:1,type:"string"}},required:["run"],type:"object"}},{capabilityId:"runs.cancel",name:"rudder_runs_cancel",description:"Cancel a heartbeat run through the governed server route.",semanticDescription:"Cancel a heartbeat run through the governed server route. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!0,idempotentHint:!1,readOnlyHint:!1,title:"Cancel a heartbeat run through the governed server route"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{run:{description:"Run UUID, typed short reference (run_<prefix>), or legacy bare short prefix.",maxLength:200,minLength:1,type:"string"}},required:["run"],type:"object"}},{capabilityId:"runs.retry",name:"rudder_runs_retry",description:"Retry a failed, timed out, or cancelled run through the governed server route.",semanticDescription:"Retry a failed, timed out, or cancelled run through the governed server route. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Retry a failed, timed out, or cancelled run through the governed server route"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{run:{description:"Run UUID, typed short reference (run_<prefix>), or legacy bare short prefix.",maxLength:200,minLength:1,type:"string"}},required:["run"],type:"object"}},{capabilityId:"runs.create",name:"rudder_runs_create",description:"Create an independently governed Delegation Run for the current or another same-organization Agent.",semanticDescription:"Create an independently governed Delegation Run for the current or another same-organization Agent. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!1,title:"Create an independently governed Delegation Run"},mutating:!0,requiresOrgId:!1,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{idempotencyKey:{description:"Required stable key for safe replay.",maxLength:500,minLength:1,type:"string"},targetAgentId:{description:"Optional same-organization target Agent id.",maxLength:200,minLength:1,type:"string"},task:{description:"Delegation task to run independently.",maxLength:2e4,minLength:1,type:"string"}},required:["task","idempotencyKey"],type:"object"}}],DOn=[{capabilityId:"agent.me",name:"rudder_agent_me",description:"Show the authenticated agent identity and budget.",semanticDescription:"Show the authenticated agent identity and budget. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Show the authenticated agent identity and budget"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{},type:"object"}},{capabilityId:"agent.inbox",name:"rudder_agent_inbox",description:"List the compact assignee and reviewer work inbox for the authenticated agent.",semanticDescription:"List the compact assignee and reviewer work inbox for the authenticated agent. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List the compact assignee and reviewer work inbox for the authenticated agent"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{},type:"object"}},{capabilityId:"organization.members.list",name:"rudder_organization_members_list",description:"List active visible human and agent members in the authenticated organization.",semanticDescription:"List active visible human and agent members in the authenticated organization. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List active visible human and agent members in the authenticated organization"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{cursor:{description:"Opaque pagination cursor.",maxLength:2e3,minLength:1,type:"string"},limit:{description:"Page size.",maximum:100,minimum:1,type:"number"},query:{description:"Optional member name filter.",maxLength:2e3,minLength:1,type:"string"},type:{description:"Member type filter.",enum:["human","agent","all"],maxLength:10,minLength:1,type:"string"}},type:"object"}},{capabilityId:"organization.brand_color.update",name:"rudder_organization_brand_color_update",description:"Set or clear the authenticated organization's brand color and link or clear an existing same-organization logo asset.",semanticDescription:"Set or clear the authenticated organization's brand color and link or clear an existing same-organization logo asset. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!1,title:"Update organization branding"},mutating:!0,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,anyOf:[{required:["brandColor"]},{required:["logoAssetId"]}],properties:{brandColor:{description:"Hex brand color, for example #123456; null clears it. Omit to preserve it.",maxLength:7,minLength:7,pattern:"^#[0-9a-fA-F]{6}$",type:["string","null"]},idempotencyKey:{description:"Required stable key for safe replay.",maxLength:255,minLength:1,type:"string"},logoAssetId:{description:"Existing asset UUID from this organization; null clears the logo. Omit to preserve it.",format:"uuid",pattern:"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89aAbB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$",type:["string","null"]}},required:["idempotencyKey"],type:"object"}},{capabilityId:"agent.capabilities",name:"rudder_agent_capabilities",description:"List the stable Rudder agent command contract.",semanticDescription:"List the stable Rudder agent command contract. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List the stable Rudder agent command contract"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{},type:"object"}},{capabilityId:"agent.update",name:"rudder_agent_update",description:"Update an agent's identity fields; defaults to the authenticated agent.",semanticDescription:"Update an agent's identity fields; defaults to the authenticated agent. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Update an agent's identity fields"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{capabilities:{description:"Agent capability summary.",maxLength:1e5,minLength:1,type:"string"},clearCapabilities:{description:"Clear the current capability summary.",type:"boolean"},clearDescription:{description:"Compatibility alias for clearCapabilities.",type:"boolean"},clearTitle:{description:"Clear the current title.",type:"boolean"},description:{description:"Compatibility alias for capabilities.",maxLength:1e5,minLength:1,type:"string"},name:{description:"Agent name.",maxLength:200,minLength:1,type:"string"},role:{description:"Agent role.",maxLength:100,minLength:1,type:"string"},title:{description:"Agent title.",maxLength:300,minLength:1,type:"string"}},type:"object"}},{capabilityId:"agent.skills.create",name:"rudder_agent_skills_create",description:"Create an agent-private skill package under AGENT_HOME/skills.",semanticDescription:"Create an agent-private skill package under AGENT_HOME/skills. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Create an agent-private skill package under AGENT_HOME/skills"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{body:{description:"Compatibility alias for markdown.",maxLength:5e5,minLength:1,type:"string"},description:{description:"Skill description.",maxLength:1e5,minLength:1,type:"string"},enable:{description:"Enable the created skill for the runtime agent.",type:"boolean"},markdown:{description:"SKILL.md content.",maxLength:5e5,minLength:1,type:"string"},name:{description:"Skill display name.",maxLength:200,minLength:1,type:"string"},slug:{description:"Skill slug.",maxLength:200,minLength:1,type:"string"}},required:["name"],type:"object"}},{capabilityId:"agent.skills.enable",name:"rudder_agent_skills_enable",description:"Add skill selections to an agent without replacing existing enabled skills.",semanticDescription:"Add skill selections to an agent without replacing existing enabled skills. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Add skill selections to an agent without replacing existing enabled skills"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{selectionRefs:{description:"Skill selection references.",items:{description:"Skill selection references.",maxLength:8192,minLength:1,type:"string"},maxItems:100,type:"array"}},required:["selectionRefs"],type:"object"}},{capabilityId:"agent.skills.sync",name:"rudder_agent_skills_sync",description:"Sync the desired enabled skill set for an agent.",semanticDescription:"Sync the desired enabled skill set for an agent. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!0,idempotentHint:!1,readOnlyHint:!1,title:"Sync the desired enabled skill set for an agent"},mutating:!0,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{desiredSkills:{description:"Comma-separated desired skill references.",maxLength:2e4,minLength:1,type:"string"}},required:["desiredSkills"],type:"object"}},{capabilityId:"goal.list",name:"rudder_goal_list",description:"Discover Goals owned by the authenticated Agent; defaults to active Goals and returns current progress, next step, and attention state.",semanticDescription:"Discover Goals owned by the authenticated Agent; defaults to active Goals and returns current progress, next step, and attention state. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: required from runtime env. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Discover Goals owned by the authenticated Agent"},mutating:!1,requiresOrgId:!0,requiresAgentId:!0,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{facet:{description:"Current Goal workspace facet.",enum:["agent_advancing","needs_attention","waiting_focus","waiting_external","ready_for_acceptance","closed"],maxLength:40,minLength:1,type:"string"},focus:{description:"Filter by whether the Goal is the organization Focus Goal.",type:"boolean"},lifecycle:{description:"Goal lifecycle filter; active is the safe default.",enum:["draft","active","closed","all"],maxLength:20,minLength:1,type:"string"},limit:{description:"Maximum owned Goals to return.",maximum:100,minimum:1,type:"number"}},type:"object"}},{capabilityId:"goal.context",name:"rudder_goal_context",description:"Read the owned Goal agreement and current operating context before acting: contract revision, criteria, boundaries, progress, next step, attention, proposals, and recent feedback.",semanticDescription:"Read the owned Goal agreement and current operating context before acting: contract revision, criteria, boundaries, progress, next step, attention, proposals, and recent feedback. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: required from runtime env. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read the owned Goal agreement and current operating context before acting: contract revision, criteria, boundaries, progress, next step, attention, proposals, and recent feedback"},mutating:!1,requiresOrgId:!1,requiresAgentId:!0,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{goal:{description:"Goal UUID returned by rudder_goal_list.",maxLength:200,minLength:1,type:"string"}},required:["goal"],type:"object"}},{capabilityId:"goal.progress",name:"rudder_goal_progress",description:"Record evidence-backed progress for a Goal owned by the authenticated Agent and attribute it to the current Run.",semanticDescription:"Record evidence-backed progress for a Goal owned by the authenticated Agent and attribute it to the current Run. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Record evidence-backed progress for a Goal owned by the authenticated Agent and attribute it to the current Run"},mutating:!0,requiresOrgId:!1,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{activityKind:{description:"Progress classification.",enum:["progress","evidence","bottleneck"],maxLength:30,minLength:1,type:"string"},evidenceRefs:{description:"URI-like references to artifacts, measurements, or other supporting evidence.",items:{description:"URI-like evidence reference.",maxLength:8192,minLength:1,type:"string"},maxItems:100,minItems:1,type:"array"},goal:{description:"Goal UUID or typed short reference (gol_<prefix>) from the current Goal Runtime Context.",maxLength:200,minLength:1,type:"string"},idempotencyKey:{description:"Stable key for safe retry.",maxLength:500,minLength:1,type:"string"},summary:{description:"Plain-language progress, observed change, or named blocker.",maxLength:1e5,minLength:1,type:"string"}},required:["goal","summary","evidenceRefs","idempotencyKey"],type:"object"}},{capabilityId:"goal.checkpoint",name:"rudder_goal_checkpoint",description:"Atomically persist a Goal checkpoint, optional Plan revision, continuation, checkpoint activity, and eligible automatic continuation wake.",semanticDescription:"Atomically persist a Goal checkpoint, optional Plan revision, continuation, checkpoint activity, and eligible automatic continuation wake. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Atomically persist a Goal checkpoint, optional Plan revision, continuation, checkpoint activity, and eligible automatic continuation wake"},mutating:!0,requiresOrgId:!1,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{continuation:{additionalProperties:!1,properties:{kind:{description:"Continuation policy.",enum:["commitment","wait","decision","verification"],maxLength:1e5,minLength:1,type:"string"},summary:{description:"What should happen next or what is awaited.",maxLength:1e5,minLength:1,type:"string"},wakeCondition:{oneOf:[{minLength:1,type:"string"},{type:"null"}]}},required:["kind","summary"],type:"object"},evidenceRefs:{description:"URI-like references to artifacts, measurements, or other supporting evidence.",items:{description:"URI-like evidence reference.",maxLength:8192,minLength:1,type:"string"},maxItems:100,type:"array"},expectedPlanRevision:{description:"Plan revision read before this checkpoint.",maximum:1e9,minimum:1,type:"number"},goal:{description:"Goal UUID or typed short reference (gol_<prefix>) from the current Goal Runtime Context.",maxLength:200,minLength:1,type:"string"},idempotencyKey:{description:"Stable key for safe retry.",maxLength:500,minLength:1,type:"string"},plan:{additionalProperties:!1,description:"Optional complete next Plan revision; omit when the current Plan remains valid.",properties:{budgetAllocations:{additionalProperties:!0,type:"object"},hypotheses:{items:{},maxItems:1e3,type:"array"},invalidationConditions:{items:{},maxItems:1e3,type:"array"},rejectedPaths:{items:{},maxItems:1e3,type:"array"},selectedPaths:{items:{},maxItems:1e3,type:"array"},sequencing:{items:{},maxItems:1e3,type:"array"},summary:{description:"Plan summary.",maxLength:1e5,minLength:1,type:"string"}},required:["summary"],type:"object"},summary:{description:"Plain-language bounded-run checkpoint summary.",maxLength:1e5,minLength:1,type:"string"}},required:["goal","summary","evidenceRefs","expectedPlanRevision","continuation","idempotencyKey"],type:"object"}},{capabilityId:"goal.change.propose",name:"rudder_goal_change_propose",description:"Propose a reviewable change to the current Goal contract when evidence shows its outcome, criteria, boundaries, or deadlines should change.",semanticDescription:"Propose a reviewable change to the current Goal contract when evidence shows its outcome, criteria, boundaries, or deadlines should change. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Propose a reviewable change to the current Goal contract when evidence shows its outcome, criteria, boundaries, or deadlines should change"},mutating:!0,requiresOrgId:!1,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{afterContract:{additionalProperties:!1,description:"Only the Goal contract fields that should change.",minProperties:1,properties:{actionDeadline:{description:"Proposed ISO-8601 action deadline, or null to clear it.",oneOf:[{format:"date-time",type:"string"},{type:"null"}]},autonomyEnvelope:{additionalProperties:!0,type:"object"},criteria:{items:{additionalProperties:!1,properties:{evaluator:{description:"Criterion evaluator.",enum:["artifact","metric","policy","human"],maxLength:20,minLength:1,type:"string"},evidenceRequirements:{items:{description:"URI-like required evidence reference.",maxLength:8192,minLength:1,type:"string"},maxItems:100,type:"array"},id:{description:"Stable criterion id.",maxLength:500,minLength:1,type:"string"},label:{description:"Plain-language success criterion.",maxLength:1e5,minLength:1,type:"string"}},required:["id","label","evaluator"],type:"object"},maxItems:100,minItems:1,type:"array"},evaluationDeadline:{description:"Proposed ISO-8601 evaluation deadline, or null to clear it.",oneOf:[{format:"date-time",type:"string"},{type:"null"}]},evaluationPolicy:{additionalProperties:!0,type:"object"},humanAuthorities:{additionalProperties:!0,type:"object"},objectiveMode:{description:"Proposed objective mode.",enum:["target","maximize","maintain","decide"],maxLength:20,minLength:1,type:"string"},outcomeStatement:{description:"Proposed result-oriented outcome.",maxLength:1e5,minLength:1,type:"string"}},type:"object"},contractRevision:{description:"Current Goal contract revision.",maximum:1e9,minimum:1,type:"number"},evidenceRefs:{description:"URI-like references supporting the proposed change.",items:{description:"URI-like evidence reference.",maxLength:8192,minLength:1,type:"string"},maxItems:100,type:"array"},goal:{description:"Goal UUID or typed short reference (gol_<prefix>) from the current Goal Runtime Context.",maxLength:200,minLength:1,type:"string"},idempotencyKey:{description:"Stable key for safe retry.",maxLength:500,minLength:1,type:"string"},rationale:{description:"Why the current contract should change and what evidence invalidated it.",maxLength:1e5,minLength:1,type:"string"}},required:["goal","contractRevision","afterContract","rationale","idempotencyKey"],type:"object"}},{capabilityId:"goal.result.propose",name:"rudder_goal_result_propose",description:"Submit an evidence-backed Goal result for mandatory human acceptance without closing the Goal.",semanticDescription:"Submit an evidence-backed Goal result for mandatory human acceptance without closing the Goal. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Submit an evidence-backed Goal result for mandatory human acceptance without closing the Goal"},mutating:!0,requiresOrgId:!1,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{contractRevision:{description:"Current Goal contract revision.",maximum:1e9,minimum:1,type:"number"},criteria:{description:"Criterion outcomes for the current contract revision.",items:{additionalProperties:!1,properties:{id:{description:"Criterion id from the Goal Runtime Context.",maxLength:500,minLength:1,type:"string"},status:{description:"Observed criterion status.",enum:["met","unmet","breached","unknown"],maxLength:20,minLength:1,type:"string"}},required:["id","status"],type:"object"},maxItems:100,minItems:1,type:"array"},decision:{description:"Optional decision reached for decide-mode Goals.",maxLength:1e5,minLength:1,type:"string"},evidenceRefs:{description:"URI-like references supporting the proposed result.",items:{description:"URI-like evidence reference.",maxLength:8192,minLength:1,type:"string"},maxItems:100,minItems:1,type:"array"},goal:{description:"Goal UUID or typed short reference (gol_<prefix>) from the current Goal Runtime Context.",maxLength:200,minLength:1,type:"string"},idempotencyKey:{description:"Stable key for safe retry.",maxLength:500,minLength:1,type:"string"},resultPayload:{additionalProperties:!0,description:"Optional structured result details.",type:"object"},resultValue:{description:"Optional measured result value.",oneOf:[{maxLength:1e5,type:"string"},{type:"number"},{type:"boolean"}]},riskSummary:{description:"Known risks, limitations, or remaining gaps.",maxLength:1e5,minLength:1,type:"string"}},required:["goal","contractRevision","criteria","evidenceRefs","riskSummary","idempotencyKey"],type:"object"}},{capabilityId:"issue.get",name:"rudder_issue_get",description:"Read a full issue by UUID or identifier.",semanticDescription:"Read a full issue by UUID or identifier. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read a full issue by UUID or identifier"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{issue:{description:"Issue UUID, identifier, or short reference.",maxLength:200,minLength:1,type:"string"}},required:["issue"],type:"object"}},{capabilityId:"issue.list",name:"rudder_issue_list",description:"List issues with optional status, assignee, and project filters without requiring a search query.",semanticDescription:"List issues with optional status, assignee, and project filters without requiring a search query. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"List issues with optional status, assignee, and project filters without requiring a search query"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{assigneeAgentId:{description:"Assignee agent id or reference.",maxLength:200,minLength:1,type:"string"},projectId:{description:"Project id or reference.",maxLength:200,minLength:1,type:"string"},status:{description:"Comma-separated issue statuses.",maxLength:500,minLength:1,type:"string"}},type:"object"}},{capabilityId:"issue.search",name:"rudder_issue_search",description:"Search issues with the server-side issue index across title, identifier, description, and comments.",semanticDescription:"Search issues with the server-side issue index across title, identifier, description, and comments. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: required from runtime env. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Search issues with the server-side issue index across title, identifier, description, and comments"},mutating:!1,requiresOrgId:!0,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{assigneeAgentId:{description:"Assignee agent id or reference.",maxLength:200,minLength:1,type:"string"},projectId:{description:"Project id or reference.",maxLength:200,minLength:1,type:"string"},query:{description:"Non-empty server-side issue search query.",maxLength:2e3,minLength:1,type:"string"},status:{description:"Comma-separated issue statuses.",maxLength:500,minLength:1,type:"string"}},required:["query"],type:"object"}},{capabilityId:"issue.context",name:"rudder_issue_context",description:"Read the compact heartbeat context for an issue; wake comments may be addressed by full id or cmt_<uuid-prefix>.",semanticDescription:"Read the compact heartbeat context for an issue; wake comments may be addressed by full id or cmt_<uuid-prefix>. Mutating: no. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: runtime env when available. Run attribution: not attached.",annotations:{destructiveHint:!1,idempotentHint:!0,readOnlyHint:!0,title:"Read the compact heartbeat context for an issue"},mutating:!1,requiresOrgId:!1,requiresAgentId:!1,attachesRunIdWhenAvailable:!1,inputSchema:{additionalProperties:!1,properties:{issue:{description:"Issue UUID, identifier, or short reference.",maxLength:200,minLength:1,type:"string"},wakeCommentId:{description:"Wake comment id or short reference.",maxLength:200,minLength:1,type:"string"}},required:["issue"],type:"object"}},{capabilityId:"issue.checkout",name:"rudder_issue_checkout",description:"Atomically checkout an issue for the current or specified agent.",semanticDescription:"Atomically checkout an issue for the current or specified agent. Mutating: yes. Runtime identity and authorization are injected by the Rudder-managed MCP server and are not accepted as tool input. Org context: not required by this tool. Agent context: required from runtime env. Run attribution: attached from runtime env when available.",annotations:{destructiveHint:!1,idempotentHint:!1,readOnlyHint:!1,title:"Atomically checkout an issue for the current or specified agent"},mutating:!0,requiresOrgId:!1,requiresAgentId:!0,attachesRunIdWhenAvailable:!0,inputSchema:{additionalProperties:!1,properties:{expectedStatuses:{description:"Comma-separated allowed prior statuses.",maxLength:500,minLength:1,type:"string"},issue:{description:"Issue UUID, identifier, or short reference.",maxLength:200,minLength:1,type:"string"}},required:["issue"],type:"object"}},...POn,...TOn,..._On,...MOn,...EOn],ROn=DOn;function LOn(e){return{name:e.name,description:e.semanticDescription??e.description,inputSchema:e.inputSchema,annotations:e.annotations}}const hut=ROn.map(LOn),zOn=hut.filter(e=>!e.name.startsWith("rudder_browser_")),$On=hut.filter(e=>e.name.startsWith("rudder_browser_"));zOn.map(e=>e.name);$On.map(e=>e.name);function put(e,t){if((t.kind==="thinking"||t.kind==="assistant")&&t.delta){const n=e.length-1,r=e[n],s=(r==null?void 0:r.kind)!=="assistant"||t.kind!=="assistant"||r.phase===void 0||t.phase===void 0||r.phase===t.phase,a=r&&(r.kind==="thinking"||r.kind==="assistant")&&(r.segmentId||t.segmentId)?!!(r.segmentId&&t.segmentId&&r.segmentId===t.segmentId):!0;if(r&&r.kind===t.kind&&r.delta&&s&&a){e[n]={...r,text:r.text+t.text,ts:t.ts,...r.kind==="assistant"&&t.kind==="assistant"&&(r.phase??t.phase)?{phase:r.phase??t.phase}:{}};return}}e.push(t)}function gut(e,t){for(const n of t)put(e,n)}function xut(){return{stdoutBuffer:"",lastStdoutTs:null}}function but(e,t,n,r,s){const a={enabled:(s==null?void 0:s.censorUsernameInLogs)??!1};if(n.stream==="stderr"){e.push({kind:"stderr",ts:n.ts,text:dA(n.chunk,a)});return}if(n.stream==="system"){e.push({kind:"system",ts:n.ts,text:dA(n.chunk,a)});return}t.lastStdoutTs=n.ts;const l=(t.stdoutBuffer+n.chunk).split(/\r?\n/);t.stdoutBuffer=l.pop()??"";for(const c of l){const d=c.trim();d&&gut(e,r(d,n.ts).map(u=>u2e(u,a)))}}function yut(e,t,n,r){const s=t.stdoutBuffer.trim();if(!s)return;const a={enabled:(r==null?void 0:r.censorUsernameInLogs)??!1};gut(e,n(s,t.lastStdoutTs??new Date().toISOString()).map(o=>u2e(o,a))),t.stdoutBuffer=""}function FOn(e,t,n){const r=[],s=xut();for(const a of e)but(r,s,a,t,n);return yut(r,s,t,n),r}const BOn=250,vp="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",Yre=[250,500,1e3,2e3,5e3],Jre=5,QOn=10,nw=40,OPe=50,UOn=5,qOn=5*6e4,VOn=30*6e4;function WOn(e){const t=(e==null?void 0:e.trim())??"";return/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(t)?`local-app-recovery:${t}`:null}const HOn=new Set(["accepted_current","reconciled_current","continuation_pending","running_next","delivered","completed","steered"]),KOn=new Set(["accepted_current","reconciled_current","continuation_pending","running_next","delivered"]);function mfe(e,t=!1){return!!(e.sourceMessageId||e.deliveredMessageId||e.continuationMessageId)||HOn.has(e.status)||e.deliveryDisposition!==null&&KOn.has(e.deliveryDisposition)||e.status==="cancelled"?{state:"hidden"}:t?{state:"sending",label:"Sending…"}:e.status==="queued"?{state:"queued",label:"Queued"}:e.status==="failed_actionable"?{state:"failed",label:"Couldn't send"}:{state:"sending",label:"Sending…"}}const ZOn=new Set(["starting","active","running","tool_busy","closing","waiting_for_network","stop_requested","stopping"]),XOn=new Set(["queued","steer_pending","accepted_current","acceptance_unknown","reconciled_current","continuation_pending","running_next","dequeue_claimed","running","steered"]);function RC(e){return e!=null&&e.activeGenerationId&&(e.activeGenerationStatus===null||ZOn.has(e.activeGenerationStatus))?e.activeGenerationId:null}function GOn(e){return e?RC(e)!==null||e.items.some(t=>XOn.has(t.status)&&mfe(t).state!=="hidden"):!1}function SPe(e){return`${e.name.trim()}\0${e.type.trim().toLowerCase()}\0${e.size}`}function ese(e){return(e==null?void 0:e.mutability)==="external_bound_chat"}function LW(e,t,n){if(!e||e.streamKey!==t||!["streaming","tool_busy","finalizing","waiting_for_network"].includes(e.state))return e;const r="generationId"in n?n.generationId:void 0,s="attemptEpoch"in n?n.attemptEpoch:void 0,a="generationSeq"in n?n.generationSeq:void 0;if(e.generationId&&r&&e.generationId!==r||e.attemptEpoch!==null&&e.attemptEpoch!==void 0&&s!==void 0&&s<e.attemptEpoch||!(n.type==="assistant_state"||n.type==="waiting_for_network")&&a!==void 0&&e.lastCommittedRenderSeq!==void 0&&a<=e.lastCommittedRenderSeq)return e;if(n.type==="assistant_delta")return{...e,body:`${e.body}${n.delta}`,generationId:n.generationId??e.generationId??null,attemptEpoch:n.attemptEpoch??e.attemptEpoch??null,lastCommittedRenderSeq:n.generationSeq??e.lastCommittedRenderSeq??0,renderedBodyHash:n.bodyHash??e.renderedBodyHash??vp};if(n.type==="assistant_state"){const c=n.state==="tool_busy"?"tool_busy":n.state;return{...e,state:c,generationId:r??e.generationId??null,attemptEpoch:s??e.attemptEpoch??null,lastCommittedRenderSeq:a??e.lastCommittedRenderSeq??0}}if(n.type==="waiting_for_network")return{...e,state:"waiting_for_network",generationId:n.generationId??e.generationId??null,attemptEpoch:n.attemptEpoch??e.attemptEpoch??null,lastCommittedRenderSeq:n.generationSeq??e.lastCommittedRenderSeq??0,renderedBodyHash:n.bodyHash??e.renderedBodyHash??vp};const l=[...e.transcript];return put(l,n.entry),{...e,transcript:l,generationId:n.generationId??e.generationId??null,attemptEpoch:n.attemptEpoch??e.attemptEpoch??null,lastCommittedRenderSeq:n.generationSeq??e.lastCommittedRenderSeq??0,renderedBodyHash:n.bodyHash??e.renderedBodyHash??vp}}function YOn(e){return e.replace(/\\/g,"\\\\").replace(/]/g,"\\]")}function JOn(e){return`[${YOn(C6(e).trim()||"Chat")}](${aN(e.id)})`}function eSn(e){try{const t=new URL(e,"http://rudder.local");let n="";if(t.protocol==="chat:")n=`${t.hostname}${t.pathname}`.replace(/^\/+/,"").trim();else if(t.origin==="http://rudder.local"){const s=t.pathname.match(/^\/(?:(?:messenger\/)?chat\/([^/]+)|[^/]+\/messenger\/chat\/([^/]+))\/?$/),a=(s==null?void 0:s[1])??(s==null?void 0:s[2])??"";try{n=decodeURIComponent(a).trim()}catch{n=a.trim()}}const r=(t.searchParams.get("messageId")??t.searchParams.get("targetMessageId")??"").trim();return n?{conversationId:n,messageId:r||null}:null}catch{return null}}function tse(e,t,n){const r=n?{...n,...n.attachmentIds?{attachmentIds:[...n.attachmentIds]}:{},...n.attachmentFileIndexes?{attachmentFileIndexes:[...n.attachmentFileIndexes]}:{}}:null;return{kind:"side_chat",sourceConversationId:e.id,sourceMessageId:t.id,sourcePreview:(r==null?void 0:r.selectedText)??t.body,...r?{inlineAnnotations:[r]}:{},conversationId:null,clientMutationId:crypto.randomUUID(),label:"Side Chat"}}function nse(e,t){return Array.from(e.querySelectorAll("[data-message-id]")).find(n=>n.dataset.messageId===t)??null}function tSn(e){return e.querySelector("[data-message-highlight-target='true']")??e}function vut(){return typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth"}function wut(e){e.classList.remove("chat-message-jump-highlight"),e.offsetWidth,e.classList.add("chat-message-jump-highlight"),window.setTimeout(()=>e.classList.remove("chat-message-jump-highlight"),1800)}function rse(e){const t=tSn(e);e.scrollIntoView({block:"center",behavior:vut()}),e.classList.remove("chat-message-jump-highlight"),wut(t)}function nSn(e){e.scrollIntoView({block:"center",behavior:vut()}),wut(e)}function rSn(e){const t=Ve({queryKey:U.chats.listPreview(e.selectedOrganizationId??"__none__","active",nw,e.activeProjectId),queryFn:()=>Zn.list(e.selectedOrganizationId,"active",{limit:nw,projectId:e.activeProjectId===e.noProjectId?void 0:e.activeProjectId}),enabled:!!e.selectedOrganizationId&&e.activeProjectId!==e.noProjectId});return{draftPreflightQuery:Ve({queryKey:["chats",e.selectedOrganizationId??"__none__","draft-preflight",e.activeAgentId??"__none__",e.modelOverride??"__agent_default__",e.effortOverride??"__agent_default__",e.activeProjectId,e.issueContextId??"__none__",e.planMode],queryFn:()=>Zn.preflightDraft(e.selectedOrganizationId,{preferredAgentId:e.activeAgentId,modelOverride:e.modelOverride,effortOverride:e.effortOverride,issueCreationMode:"manual_approval",planMode:e.planMode,contextLinks:e.contextLinks}),enabled:!e.selectedConversation&&!!e.selectedOrganizationId&&!!e.activeAgentId,retry:!1,staleTime:r=>{var s;return(s=r.state.data)!=null&&s.available?qOn:0},gcTime:VOn}),projectConversationsQuery:t}}function sSn(e){return e.newConversationSendInFlight||e.activeSendInFlight&&!e.hasActiveStream?"sending":e.stopRequestPending||e.streamStopping?"stopping":e.canQueueDraft?"queue":e.activeSendInFlight?"stop":e.canContinueInterruptedConversation&&!e.hasSubmittableDraft&&e.pendingFileCount===0?"continue":"send"}function iSn(e){return e.selectedConversationExternalBound||e.composerUnavailable||e.sendButtonMode==="sending"||e.sendButtonMode==="stopping"?!0:e.sendButtonMode==="continue"?e.modelSelectionPending:e.sendButtonMode==="send"||e.sendButtonMode==="queue"?e.modelSelectionPending||!e.hasDraft:!1}async function aSn(e){var n;const t=await Zn.createQueuedMessage(e.conversation.id,{clientMutationId:`ui:${Date.now()}:${Math.random().toString(36).slice(2)}`,expectedGenerationId:e.serverActiveGenerationId,payload:{body:e.body,...(n=e.inlineAnnotations)!=null&&n.length?{inlineAnnotations:e.inlineAnnotations}:{},attachmentIds:[],skillRefs:[],projectId:e.projectId,accessMode:null,model:e.modelOverride,effort:e.effortOverride,metadata:{source:"chat_composer"}}},{files:e.files});return e.queryClient.setQueryData(U.chats.queue(e.orgId,e.conversation.id),r=>{var s,a,o;return{activeGenerationId:(r==null?void 0:r.activeGenerationId)??e.serverActiveGenerationId,activeAttemptEpoch:(r==null?void 0:r.activeAttemptEpoch)??((s=e.queueSnapshot)==null?void 0:s.activeAttemptEpoch)??null,activeControlVersion:(r==null?void 0:r.activeControlVersion)??((a=e.queueSnapshot)==null?void 0:a.activeControlVersion)??null,activeGenerationStatus:(r==null?void 0:r.activeGenerationStatus)??((o=e.queueSnapshot)==null?void 0:o.activeGenerationStatus)??null,items:[...(r==null?void 0:r.items)??[],t]}}),t}function oSn(e){return!!(e.activeReply&&!e.newConversationSendInFlight&&e.pendingRegularFileCount===0&&(e.body.trim().length>0||e.annotationCount>0))}function lSn(e,t){const{inlineAnnotations:n,...r}=e;return{...r,body:t}}function VF(e){const t=e.dataTransfer;return t.files.length>0||Array.from(t.types??[]).includes("Files")||Array.from(t.items??[]).some(n=>n.kind==="file")}function f2e(e){const[t,n]=A.useState(!1),r=A.useRef(0),s=A.useCallback(c=>{VF(c)&&(c.preventDefault(),c.stopPropagation(),r.current+=1,n(!0))},[]),a=A.useCallback(c=>{VF(c)&&(c.preventDefault(),c.stopPropagation(),c.dataTransfer.dropEffect="copy")},[]),o=A.useCallback(c=>{r.current===0&&!VF(c)||(c.preventDefault(),c.stopPropagation(),r.current=Math.max(0,r.current-1),r.current===0&&n(!1))},[]),l=A.useCallback(c=>{r.current===0&&!VF(c)||(c.preventDefault(),c.stopPropagation(),r.current=0,n(!1),e(c.dataTransfer.files))},[e]);return{active:t,targetProps:{onDragEnter:s,onDragOver:a,onDragLeave:o,onDrop:l}}}function kut(e){return A.useCallback(t=>{const n=t.clipboardData,r=Array.from((n==null?void 0:n.items)??[]).filter(l=>l.kind==="file").map(l=>l.getAsFile()).filter(l=>l instanceof File),s=new Map;for(const l of r){const c=SPe(l);s.set(c,(s.get(c)??0)+1)}const a=Array.from((n==null?void 0:n.files)??[]).filter(l=>{const c=SPe(l),d=s.get(c)??0;return d<=0?!0:(d===1?s.delete(c):s.set(c,d-1),!1)}),o=[...r,...a];o.length!==0&&(t.preventDefault(),t.stopPropagation(),e(o))},[e])}function m2e(){return i.jsx("div",{"data-testid":"chat-composer-file-drop-overlay",role:"status","aria-live":"polite",className:"pointer-events-none absolute inset-0 z-20 flex items-center justify-center rounded-[inherit] border border-[color:color-mix(in_oklab,var(--accent-base)_55%,transparent)] bg-[color:color-mix(in_oklab,var(--surface-elevated)_88%,transparent)] backdrop-blur-[2px]",children:i.jsxs("div",{className:"flex items-center gap-2 rounded-[var(--radius-md)] bg-[color:var(--accent-soft)] px-3 py-2 text-sm font-medium text-foreground shadow-[var(--shadow-sm)]",children:[i.jsx(df,{className:"h-4 w-4 text-[color:var(--accent-base)]","aria-hidden":!0}),"Drop files to attach"]})})}function cSn({message:e,conversation:t,agents:n,canRetry:r,onRetry:s}){const a=wmt(e,t),o=a?n==null?void 0:n.find(u=>u.id===a.agentId):null,l=o?uw(o):a==null?void 0:a.agentId,c=typeof window>"u"?null:Zf(window.location.pathname),d=a?rc(`/agents/${l}/runs/${a.runId}`,c):null;return!d&&!r?null:i.jsxs("div",{className:"flex basis-full shrink-0 flex-wrap items-center justify-end gap-2 pl-7 sm:basis-auto sm:pl-0",children:[d?i.jsx(gn,{to:d,className:"inline-flex h-7 items-center rounded-md border border-border bg-background/70 px-2 text-xs font-medium text-foreground transition-colors hover:bg-background",children:"Open run"}):null,r?i.jsxs("button",{type:"button",className:"inline-flex h-7 items-center gap-1.5 rounded-md border border-destructive/30 bg-background/70 px-2 text-xs font-medium text-destructive transition-colors hover:bg-background",onClick:()=>s==null?void 0:s(e),children:[i.jsx(tf,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Retry"]}):null]})}function f1(e,t){const n=e==null?void 0:e[t];return typeof n=="string"&&n.trim().length>0?n.trim():null}function Out(e,t){var s,a,o;const n=/\[([^\]]+)\]\(chat:\/\/([^)]+)\)/g;let r;for(;(r=n.exec(e))!==null;){const l=(s=r[1])==null?void 0:s.trim(),c=(o=(a=r[2])==null?void 0:a.split(/[?#]/)[0])==null?void 0:o.trim();if(l&&c===t)return l}return null}function dSn(e){const t=e.structuredPayload;if(!t||t.eventType!=="chat_fork"&&t.type!=="chat_fork")return null;const n=f1(t,"sourceConversationId"),r=f1(t,"sourceMessageId");if(!n)return null;const s=f1(t,"sourceConversationTitle")??Out(e.body,n)??"source chat";return{sourceConversationId:n,sourceConversationTitle:s,sourceMessageId:r}}function uSn(e){const t=e.structuredPayload;if(!t||t.eventType!=="side_chat_started")return null;const n=f1(t,"sourceConversationId");if(!n)return null;const r=f1(t,"sourceConversationTitle")??Out(e.body,n)??"source chat";return{sourceConversationId:n,sourceConversationTitle:r}}const x3=0,dr=1,pi=2,kd=3,Nl=4,W1=5,$G=6,Mf=7,fA=8,Oa=9,Us=10,yc=11,ka=12,Oc=13,xL=14,mA=15,Wf=16,Hf=17,BA=18,Uh=19,Wp=20,oo=21,Ds=22,Pu=23,zh=24,cf=25,fSn=0;function sf(e){return e>=48&&e<=57}function s5(e){return sf(e)||e>=65&&e<=70||e>=97&&e<=102}function A2e(e){return e>=65&&e<=90}function mSn(e){return e>=97&&e<=122}function ASn(e){return A2e(e)||mSn(e)}function hSn(e){return e>=128}function zW(e){return ASn(e)||hSn(e)||e===95}function Sut(e){return zW(e)||sf(e)||e===45}function pSn(e){return e>=0&&e<=8||e===11||e>=14&&e<=31||e===127}function $W(e){return e===10||e===13||e===12}function Y6(e){return $W(e)||e===32||e===9}function c0(e,t){return!(e!==92||$W(t)||t===fSn)}function YQ(e,t,n){return e===45?zW(t)||t===45||c0(t,n):zW(e)?!0:e===92?c0(e,t):!1}function sse(e,t,n){return e===43||e===45?sf(t)?2:t===46&&sf(n)?3:0:e===46?sf(t)?2:0:sf(e)?1:0}function jut(e){return e===65279||e===65534?1:0}const Afe=new Array(128),gSn=128,JQ=130,Cut=131,h2e=132,Nut=133;for(let e=0;e<Afe.length;e++)Afe[e]=Y6(e)&&JQ||sf(e)&&Cut||zW(e)&&h2e||pSn(e)&&Nut||e||gSn;function ise(e){return e<128?Afe[e]:h2e}function US(e,t){return t<e.length?e.charCodeAt(t):0}function hfe(e,t,n){return n===13&&US(e,t+1)===10?2:1}function qS(e,t,n){let r=e.charCodeAt(t);return A2e(r)&&(r=r|32),r===n}function kE(e,t,n,r){if(n-t!==r.length||t<0||n>e.length)return!1;for(let s=t;s<n;s++){const a=r.charCodeAt(s-t);let o=e.charCodeAt(s);if(A2e(o)&&(o=o|32),o!==a)return!1}return!0}function xSn(e,t){for(;t>=0&&Y6(e.charCodeAt(t));t--);return t+1}function WF(e,t){for(;t<e.length&&Y6(e.charCodeAt(t));t++);return t}function ase(e,t){for(;t<e.length&&sf(e.charCodeAt(t));t++);return t}function LC(e,t){if(t+=2,s5(US(e,t-1))){for(const r=Math.min(e.length,t+5);t<r&&s5(US(e,t));t++);const n=US(e,t);Y6(n)&&(t+=hfe(e,t,n))}return t}function HF(e,t){for(;t<e.length;t++){const n=e.charCodeAt(t);if(!Sut(n)){if(c0(n,US(e,t+1))){t=LC(e,t)-1;continue}break}}return t}function FG(e,t){let n=e.charCodeAt(t);if((n===43||n===45)&&(n=e.charCodeAt(t+=1)),sf(n)&&(t=ase(e,t+1),n=e.charCodeAt(t)),n===46&&sf(e.charCodeAt(t+1))&&(t+=2,t=ase(e,t)),qS(e,t,101)){let r=0;n=e.charCodeAt(t+1),(n===45||n===43)&&(r=1,n=e.charCodeAt(t+2)),sf(n)&&(t=ase(e,t+1+r+1))}return t}function ose(e,t){for(;t<e.length;t++){const n=e.charCodeAt(t);if(n===41){t++;break}c0(n,US(e,t+1))&&(t=LC(e,t))}return t}function Iut(e){if(e.length===1&&!s5(e.charCodeAt(0)))return e[0];let t=parseInt(e,16);return(t===0||t>=55296&&t<=57343||t>1114111)&&(t=65533),String.fromCodePoint(t)}const pfe=["EOF-token","ident-token","function-token","at-keyword-token","hash-token","string-token","bad-string-token","url-token","bad-url-token","delim-token","number-token","percentage-token","dimension-token","whitespace-token","CDO-token","CDC-token","colon-token","semicolon-token","comma-token","[-token","]-token","(-token",")-token","{-token","}-token","comment-token"],bSn=16*1024;function FW(e=null,t){return e===null||e.length<t?new Uint32Array(Math.max(t+1024,bSn)):e}const jPe=10,ySn=12,CPe=13;function NPe(e){const t=e.source,n=t.length,r=t.length>0?jut(t.charCodeAt(0)):0,s=FW(e.lines,n),a=FW(e.columns,n);let o=e.startLine,l=e.startColumn;for(let c=r;c<n;c++){const d=t.charCodeAt(c);s[c]=o,a[c]=l++,(d===jPe||d===CPe||d===ySn)&&(d===CPe&&c+1<n&&t.charCodeAt(c+1)===jPe&&(c++,s[c]=o,a[c]=l),o++,l=1)}s[n]=o,a[n]=l,e.lines=s,e.columns=a,e.computed=!0}class vSn{constructor(t,n,r,s){this.setSource(t,n,r,s),this.lines=null,this.columns=null}setSource(t="",n=0,r=1,s=1){this.source=t,this.startOffset=n,this.startLine=r,this.startColumn=s,this.computed=!1}getLocation(t,n){return this.computed||NPe(this),{source:n,offset:this.startOffset+t,line:this.lines[t],column:this.columns[t]}}getLocationRange(t,n,r){return this.computed||NPe(this),{source:r,start:{offset:this.startOffset+t,line:this.lines[t],column:this.columns[t]},end:{offset:this.startOffset+n,line:this.lines[n],column:this.columns[n]}}}}const wg=16777215,kg=24,bL=1,BG=2,rw=new Uint8Array(32);rw[pi]=Ds;rw[oo]=Ds;rw[Uh]=Wp;rw[Pu]=zh;const Yg=new Uint8Array(32);Yg[pi]=bL;Yg[oo]=bL;Yg[Uh]=bL;Yg[Pu]=bL;Yg[Ds]=BG;Yg[Wp]=BG;Yg[zh]=BG;function IPe(e,t,n){return e<t?t:e>n?n:e}class wSn{constructor(t,n){this.setSource(t,n)}reset(){this.eof=!1,this.tokenIndex=-1,this.tokenType=0,this.tokenStart=this.firstCharOffset,this.tokenEnd=this.firstCharOffset}setSource(t="",n=()=>{}){t=String(t||"");const r=t.length,s=FW(this.offsetAndType,t.length+1),a=FW(this.balance,t.length+1);let o=0,l=-1,c=0,d=t.length;this.offsetAndType=null,this.balance=null,a.fill(0),n(t,(u,f,m)=>{const h=o++;if(s[h]=u<<kg|m,l===-1&&(l=f),a[h]=d,u===c){const p=a[d];a[d]=h,d=p,c=rw[s[p]>>kg]}else this.isBlockOpenerTokenType(u)&&(d=h,c=rw[u])}),s[o]=x3<<kg|r,a[o]=o;for(let u=0;u<o;u++){const f=a[u];if(f<=u){const m=a[f];m!==u&&(a[u]=m)}else f>o&&(a[u]=o)}this.source=t,this.firstCharOffset=l===-1?0:l,this.tokenCount=o,this.offsetAndType=s,this.balance=a,this.reset(),this.next()}lookupType(t){return t+=this.tokenIndex,t<this.tokenCount?this.offsetAndType[t]>>kg:x3}lookupTypeNonSC(t){for(let n=this.tokenIndex;n<this.tokenCount;n++){const r=this.offsetAndType[n]>>kg;if(r!==Oc&&r!==cf&&t--===0)return r}return x3}lookupOffset(t){return t+=this.tokenIndex,t<this.tokenCount?this.offsetAndType[t-1]&wg:this.source.length}lookupOffsetNonSC(t){for(let n=this.tokenIndex;n<this.tokenCount;n++){const r=this.offsetAndType[n]>>kg;if(r!==Oc&&r!==cf&&t--===0)return n-this.tokenIndex}return x3}lookupValue(t,n){return t+=this.tokenIndex,t<this.tokenCount?kE(this.source,this.offsetAndType[t-1]&wg,this.offsetAndType[t]&wg,n):!1}getTokenStart(t){return t===this.tokenIndex?this.tokenStart:t>0?t<this.tokenCount?this.offsetAndType[t-1]&wg:this.offsetAndType[this.tokenCount]&wg:this.firstCharOffset}getTokenEnd(t){return t===this.tokenIndex?this.tokenEnd:this.offsetAndType[IPe(t,0,this.tokenCount)]&wg}getTokenType(t){return t===this.tokenIndex?this.tokenType:this.offsetAndType[IPe(t,0,this.tokenCount)]>>kg}substrToCursor(t){return this.source.substring(t,this.tokenStart)}isBlockOpenerTokenType(t){return Yg[t]===bL}isBlockCloserTokenType(t){return Yg[t]===BG}getBlockTokenPairIndex(t){const n=this.getTokenType(t);if(Yg[n]===1){const r=this.balance[t],s=this.getTokenType(r);return rw[n]===s?r:-1}else if(Yg[n]===2){const r=this.balance[t],s=this.getTokenType(r);return rw[s]===n?r:-1}return-1}isBalanceEdge(t){return this.balance[this.tokenIndex]<t}isDelim(t,n){return n?this.lookupType(n)===Oa&&this.source.charCodeAt(this.lookupOffset(n))===t:this.tokenType===Oa&&this.source.charCodeAt(this.tokenStart)===t}skip(t){let n=this.tokenIndex+t;n<this.tokenCount?(this.tokenIndex=n,this.tokenStart=this.offsetAndType[n-1]&wg,n=this.offsetAndType[n],this.tokenType=n>>kg,this.tokenEnd=n&wg):(this.tokenIndex=this.tokenCount,this.next())}next(){let t=this.tokenIndex+1;t<this.tokenCount?(this.tokenIndex=t,this.tokenStart=this.tokenEnd,t=this.offsetAndType[t],this.tokenType=t>>kg,this.tokenEnd=t&wg):(this.eof=!0,this.tokenIndex=this.tokenCount,this.tokenType=x3,this.tokenStart=this.tokenEnd=this.source.length)}skipSC(){for(;this.tokenType===Oc||this.tokenType===cf;)this.next()}skipUntilBalanced(t,n){let r=t,s=0,a=0;e:for(;r<this.tokenCount;r++){if(s=this.balance[r],s<t)break e;switch(a=r>0?this.offsetAndType[r-1]&wg:this.firstCharOffset,n(this.source.charCodeAt(a))){case 1:break e;case 2:r++;break e;default:this.isBlockOpenerTokenType(this.offsetAndType[r]>>kg)&&(r=s)}}this.skip(r-this.tokenIndex)}forEachToken(t){for(let n=0,r=this.firstCharOffset;n<this.tokenCount;n++){const s=r,a=this.offsetAndType[n],o=a&wg,l=a>>kg;r=o,t(l,s,o,n)}}dump(){const t=new Array(this.tokenCount);return this.forEachToken((n,r,s,a)=>{t[a]={idx:a,type:pfe[n],chunk:this.source.substring(r,s),balance:this.balance[a]}}),t}}function QG(e,t){function n(f){return f<l?e.charCodeAt(f):0}function r(){if(d=FG(e,d),YQ(n(d),n(d+1),n(d+2))){u=ka,d=HF(e,d);return}if(n(d)===37){u=yc,d++;return}u=Us}function s(){const f=d;if(d=HF(e,d),kE(e,f,d,"url")&&n(d)===40){if(d=WF(e,d+1),n(d)===34||n(d)===39){u=pi,d=f+4;return}o();return}if(n(d)===40){u=pi,d++;return}u=dr}function a(f){for(f||(f=n(d++)),u=W1;d<e.length;d++){const m=e.charCodeAt(d);switch(ise(m)){case f:d++;return;case JQ:if($W(m)){d+=hfe(e,d,m),u=$G;return}break;case 92:if(d===e.length-1)break;const h=n(d+1);$W(h)?d+=hfe(e,d+1,h):c0(m,h)&&(d=LC(e,d)-1);break}}}function o(){for(u=Mf,d=WF(e,d);d<e.length;d++){const f=e.charCodeAt(d);switch(ise(f)){case 41:d++;return;case JQ:if(d=WF(e,d),n(d)===41||d>=e.length){d<e.length&&d++;return}d=ose(e,d),u=fA;return;case 34:case 39:case 40:case Nut:d=ose(e,d),u=fA;return;case 92:if(c0(f,n(d+1))){d=LC(e,d)-1;break}d=ose(e,d),u=fA;return}}}e=String(e||"");const l=e.length;let c=jut(n(0)),d=c,u;for(;d<l;){const f=e.charCodeAt(d);switch(ise(f)){case JQ:u=Oc,d=WF(e,d+1);break;case 34:a();break;case 35:Sut(n(d+1))||c0(n(d+1),n(d+2))?(u=Nl,d=HF(e,d+1)):(u=Oa,d++);break;case 39:a();break;case 40:u=oo,d++;break;case 41:u=Ds,d++;break;case 43:sse(f,n(d+1),n(d+2))?r():(u=Oa,d++);break;case 44:u=BA,d++;break;case 45:sse(f,n(d+1),n(d+2))?r():n(d+1)===45&&n(d+2)===62?(u=mA,d=d+3):YQ(f,n(d+1),n(d+2))?s():(u=Oa,d++);break;case 46:sse(f,n(d+1),n(d+2))?r():(u=Oa,d++);break;case 47:n(d+1)===42?(u=cf,d=e.indexOf("*/",d+2),d=d===-1?e.length:d+2):(u=Oa,d++);break;case 58:u=Wf,d++;break;case 59:u=Hf,d++;break;case 60:n(d+1)===33&&n(d+2)===45&&n(d+3)===45?(u=xL,d=d+4):(u=Oa,d++);break;case 64:YQ(n(d+1),n(d+2),n(d+3))?(u=kd,d=HF(e,d+1)):(u=Oa,d++);break;case 91:u=Uh,d++;break;case 92:c0(f,n(d+1))?s():(u=Oa,d++);break;case 93:u=Wp,d++;break;case 123:u=Pu,d++;break;case 125:u=zh,d++;break;case Cut:r();break;case h2e:s();break;default:u=Oa,d++}t(u,c,c=d)}}let B7=null;class cu{static createItem(t){return{prev:null,next:null,data:t}}constructor(){this.head=null,this.tail=null,this.cursor=null}createItem(t){return cu.createItem(t)}allocateCursor(t,n){let r;return B7!==null?(r=B7,B7=B7.cursor,r.prev=t,r.next=n,r.cursor=this.cursor):r={prev:t,next:n,cursor:this.cursor},this.cursor=r,r}releaseCursor(){const{cursor:t}=this;this.cursor=t.cursor,t.prev=null,t.next=null,t.cursor=B7,B7=t}updateCursors(t,n,r,s){let{cursor:a}=this;for(;a!==null;)a.prev===t&&(a.prev=n),a.next===r&&(a.next=s),a=a.cursor}*[Symbol.iterator](){for(let t=this.head;t!==null;t=t.next)yield t.data}get size(){let t=0;for(let n=this.head;n!==null;n=n.next)t++;return t}get isEmpty(){return this.head===null}get first(){return this.head&&this.head.data}get last(){return this.tail&&this.tail.data}fromArray(t){let n=null;this.head=null;for(let r of t){const s=cu.createItem(r);n!==null?n.next=s:this.head=s,s.prev=n,n=s}return this.tail=n,this}toArray(){return[...this]}toJSON(){return[...this]}forEach(t,n=this){const r=this.allocateCursor(null,this.head);for(;r.next!==null;){const s=r.next;r.next=s.next,t.call(n,s.data,s,this)}this.releaseCursor()}forEachRight(t,n=this){const r=this.allocateCursor(this.tail,null);for(;r.prev!==null;){const s=r.prev;r.prev=s.prev,t.call(n,s.data,s,this)}this.releaseCursor()}reduce(t,n,r=this){let s=this.allocateCursor(null,this.head),a=n,o;for(;s.next!==null;)o=s.next,s.next=o.next,a=t.call(r,a,o.data,o,this);return this.releaseCursor(),a}reduceRight(t,n,r=this){let s=this.allocateCursor(this.tail,null),a=n,o;for(;s.prev!==null;)o=s.prev,s.prev=o.prev,a=t.call(r,a,o.data,o,this);return this.releaseCursor(),a}some(t,n=this){for(let r=this.head;r!==null;r=r.next)if(t.call(n,r.data,r,this))return!0;return!1}map(t,n=this){const r=new cu;for(let s=this.head;s!==null;s=s.next)r.appendData(t.call(n,s.data,s,this));return r}filter(t,n=this){const r=new cu;for(let s=this.head;s!==null;s=s.next)t.call(n,s.data,s,this)&&r.appendData(s.data);return r}nextUntil(t,n,r=this){if(t===null)return;const s=this.allocateCursor(null,t);for(;s.next!==null;){const a=s.next;if(s.next=a.next,n.call(r,a.data,a,this))break}this.releaseCursor()}prevUntil(t,n,r=this){if(t===null)return;const s=this.allocateCursor(t,null);for(;s.prev!==null;){const a=s.prev;if(s.prev=a.prev,n.call(r,a.data,a,this))break}this.releaseCursor()}clear(){this.head=null,this.tail=null}copy(){const t=new cu;for(let n of this)t.appendData(n);return t}prepend(t){return this.updateCursors(null,t,this.head,t),this.head!==null?(this.head.prev=t,t.next=this.head):this.tail=t,this.head=t,this}prependData(t){return this.prepend(cu.createItem(t))}append(t){return this.insert(t)}appendData(t){return this.insert(cu.createItem(t))}insert(t,n=null){if(n!==null)if(this.updateCursors(n.prev,t,n,t),n.prev===null){if(this.head!==n)throw new Error("before doesn't belong to list");this.head=t,n.prev=t,t.next=n,this.updateCursors(null,t)}else n.prev.next=t,t.prev=n.prev,n.prev=t,t.next=n;else this.updateCursors(this.tail,t,null,t),this.tail!==null?(this.tail.next=t,t.prev=this.tail):this.head=t,this.tail=t;return this}insertData(t,n){return this.insert(cu.createItem(t),n)}remove(t){if(this.updateCursors(t,t.prev,t,t.next),t.prev!==null)t.prev.next=t.next;else{if(this.head!==t)throw new Error("item doesn't belong to list");this.head=t.next}if(t.next!==null)t.next.prev=t.prev;else{if(this.tail!==t)throw new Error("item doesn't belong to list");this.tail=t.prev}return t.prev=null,t.next=null,t}push(t){this.insert(cu.createItem(t))}pop(){return this.tail!==null?this.remove(this.tail):null}unshift(t){this.prepend(cu.createItem(t))}shift(){return this.head!==null?this.remove(this.head):null}prependList(t){return this.insertList(t,this.head)}appendList(t){return this.insertList(t)}insertList(t,n){return t.head===null?this:(n!=null?(this.updateCursors(n.prev,t.tail,n,t.head),n.prev!==null?(n.prev.next=t.head,t.head.prev=n.prev):this.head=t.head,n.prev=t.tail,t.tail.next=n):(this.updateCursors(this.tail,t.tail,null,t.head),this.tail!==null?(this.tail.next=t.head,t.head.prev=this.tail):this.head=t.head,this.tail=t.tail),t.head=null,t.tail=null,this)}replace(t,n){"head"in n?this.insertList(n,t):this.insert(n,t),this.remove(t)}}function UG(e,t){const n=Object.create(SyntaxError.prototype),r=new Error;return Object.assign(n,{name:e,message:t,get stack(){return(r.stack||"").replace(/^(.+\n){1,3}/,`${e}: ${t}
1868
1868
  `)}})}const lse=100,PPe=60,TPe=" ";function _Pe({source:e,line:t,column:n,baseLine:r,baseColumn:s},a){function o(p,x){return d.slice(p,x).map((b,y)=>String(p+y+1).padStart(m)+" |"+b).join(`
1869
1869
  `)}const l=`
1870
1870
  `.repeat(Math.max(r-1,0)),c=" ".repeat(Math.max(s-1,0)),d=(l+c+e).split(/\r\n?|\n|\f/),u=Math.max(1,t-a)-1,f=Math.min(t+a,d.length+1),m=Math.max(4,String(f).length)+1;let h=0;n+=(TPe.length-1)*(d[t-1].substr(0,n-1).match(/\t/g)||[]).length,n>lse&&(h=n-PPe+3,n=PPe-2);for(let p=u;p<=f;p++)p>=0&&p<d.length&&(d[p]=d[p].replace(/\t/g,TPe),d[p]=(h>0&&d[p].length>h?"…":"")+d[p].substr(h,lse-2)+(d[p].length>h+lse-1?"…":""));return[o(u,t),new Array(n+m+2).join("-")+"^",o(t,f)].filter(Boolean).join(`
@@ -1951,7 +1951,7 @@ ${c}`.trim();return[o,{kind:"tool_result",ts:t,toolUseId:Hu(n.callID)||Hu(n.id,r
1951
1951
 
1952
1952
  `);D(Ie?`${Ie}
1953
1953
 
1954
- ${$e}`:$e)}finally{ne(!1),ie.current&&(ie.current.value="")}}}if(t.length===0)return i.jsx("p",{className:"text-sm text-muted-foreground",children:p});const de=Be=>{var ut,ge,Le;if(Be.kind==="disclosure")return i.jsx(J7n,{hiddenCount:Be.hiddenCount,locale:T,onRevealMore:E,timelineRegionId:_});if(Be.kind==="activity")return i.jsx("div",{children:Be.activity.node});if(Be.kind==="run"){const rt=Be.run,At=rt.status==="queued"||rt.status==="running",Ue=c.get(rt.runId)??[],Se=d(rt.runId),We=VFn(rt.contextSnapshot),Te=rt.startedAt??rt.createdAt,He=So(Te),fe=o[rt.runId]??lht(rt.status),je=fe?"Hide details":"Show details",ye=n==null?void 0:n.get(rt.agentId),tt=(ye==null?void 0:ye.name)??rt.agentId.slice(0,8),ze=(rt.finishedAt||TGe(rt)?_R(rt):null)??"Run",De=MR(rt),kt=rc(`/agents/${rt.agentId}/runs/${rt.runId}`,W),gt=()=>{$(kt)},Ke=Me=>{WFn(Me.target)||gt()},Je=Me=>{Me.target===Me.currentTarget&&(Me.key!=="Enter"&&Me.key!==" "||(Me.preventDefault(),gt()))},wt=i.jsx(vy,{to:kt,className:"inline-flex shrink-0 rounded-[calc(var(--radius-sm)-1px)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring","aria-label":`Open ${rt.status.replace("_"," ")} run details`,children:i.jsx(Oi,{status:rt.status})}),Z=i.jsx("button",{type:"button","aria-label":je,"aria-expanded":fe,"aria-controls":`run-output-${rt.runId}`,className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border bg-background/70 text-muted-foreground motion-safe:transition-colors hover:bg-accent hover:text-foreground motion-reduce:transition-none",onClick:()=>{l(rt.runId,!fe)},children:i.jsx(rs,{className:`h-3.5 w-3.5 motion-safe:transition-transform motion-reduce:transition-none ${fe?"rotate-180":""}`})});return i.jsxs("div",{"aria-label":"Agent run","data-run-id":rt.runId,role:"link",tabIndex:0,className:`overflow-hidden rounded-sm border border-dashed border-border bg-muted/35 motion-safe:transition-[padding,background-color,border-color] motion-safe:duration-200 motion-safe:ease-out hover:border-border/80 hover:bg-muted/50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring motion-reduce:transition-none ${fe?"p-3":"px-3 py-1"}`,onClick:Ke,onKeyDown:Je,children:[fe?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3",children:[i.jsx(vy,{to:`/agents/${rt.agentId}`,className:"hover:underline",children:i.jsx(zl,{name:tt,icon:ye==null?void 0:ye.icon,role:ye==null?void 0:ye.role,size:"sm"})}),i.jsx("div",{className:"shrink-0 text-right",children:i.jsx("time",{className:"block text-xs text-muted-foreground",dateTime:Zse(Te),title:He,children:Ca(Te)})})]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[i.jsxs("span",{className:"inline-flex h-7 shrink-0 items-center gap-1 font-medium text-muted-foreground",title:De||void 0,children:[i.jsx(Dh,{className:"h-3.5 w-3.5"}),ze]}),wt,We&&i.jsx("span",{className:"rounded-md border border-amber-500/30 bg-amber-500/10 px-2 py-1 text-[11px] font-medium text-amber-700 dark:text-amber-300",children:We}),i.jsx("span",{className:"ml-auto",children:Z})]})]}):i.jsxs("div",{className:"grid min-w-0 grid-cols-[minmax(0,1fr)_auto_auto] items-center gap-2 text-xs",children:[i.jsxs("div",{className:"flex h-7 min-w-0 items-center gap-2",children:[i.jsx(vy,{to:`/agents/${rt.agentId}`,className:"min-w-0 shrink overflow-hidden hover:underline",children:i.jsx(zl,{name:tt,icon:ye==null?void 0:ye.icon,role:ye==null?void 0:ye.role,size:"sm",className:"h-7 w-full min-w-0 max-w-[12rem] items-center"})}),i.jsxs("span",{className:"inline-flex h-7 shrink-0 items-center gap-1 font-medium text-muted-foreground",title:De||void 0,children:[i.jsx(Dh,{className:"h-3.5 w-3.5"}),ze]}),wt,We&&i.jsx("span",{className:"inline-flex h-7 shrink-0 items-center rounded-md border border-amber-500/30 bg-amber-500/10 px-2 text-[11px] font-medium text-amber-700 dark:text-amber-300",children:We})]}),i.jsx("time",{className:"hidden h-7 shrink-0 items-center text-muted-foreground sm:inline-flex",dateTime:Zse(Te),title:He,children:Ca(Te)}),Z]}),i.jsx(nBn,{expanded:fe,id:`run-output-${rt.runId}`,children:i.jsx(M1,{entries:Ue,density:"compact",limit:4,streaming:At,collapseStdout:!0,presentation:"chat",emptyMessage:Se?"Waiting for transcript parsing...":At?`Run ${rt.status}. Waiting for output...`:"No run output captured."})})]})}const ae=Be.comment,Ee=a===ae.id,he=So(ae.createdAt);if(!!ae.deletedAt)return null;const Ie=new Date(ae.updatedAt).getTime()>new Date(ae.createdAt).getTime()+1e3,$e=!!x&&!ae.authorAgentId&&ae.authorUserId===x,ce=!!x&&($e||!!ae.authorAgentId),Oe=V===ae.id,Ye=Y[ae.id]===!0&&!Oe,J=JFn(ae.body),qe=()=>{G(rt=>({...rt,[ae.id]:!Ye}))},be=()=>{G(rt=>({...rt,[ae.id]:!1})),L(ae.id),D(ae.body)},ot=()=>{L(null),D("")},ke=async()=>{var At,Ue;if(!y)return;const rt=(((Ue=(At=le.current)==null?void 0:At.getMarkdown)==null?void 0:Ue.call(At))??R).trim();if(rt){ee(!0);try{await y(ae.id,rt),ot()}finally{ee(!1)}}},Ce=async()=>{!w||!await F({title:"Delete this comment?",description:"This permanently removes the comment from the issue. This cannot be undone.",confirmLabel:"Delete comment",tone:"destructive"})||await w(ae.id)},ue=ae.authorAgentId?i.jsx(vy,{to:`/agents/${ae.authorAgentId}`,className:Ye?"block min-w-0 max-w-full overflow-hidden hover:underline":"min-w-0 hover:underline",children:i.jsx(zl,{name:((ut=n==null?void 0:n.get(ae.authorAgentId))==null?void 0:ut.name)??ae.authorAgentId.slice(0,8),icon:(ge=n==null?void 0:n.get(ae.authorAgentId))==null?void 0:ge.icon,role:(Le=n==null?void 0:n.get(ae.authorAgentId))==null?void 0:Le.role,size:"sm",className:Ye?"max-w-full min-w-0 overflow-hidden":void 0})}):i.jsx(Bd,{name:m1e(u),avatarUrl:ae.authorUserId===x?b:null,size:"sm",className:Ye?"max-w-full min-w-0 overflow-hidden":void 0}),mt=i.jsx("a",{href:`#comment-${ae.id}`,className:"text-xs text-muted-foreground transition-colors hover:text-foreground hover:underline",title:he,"aria-label":`Comment posted ${he}`,children:i.jsx("time",{dateTime:Zse(ae.createdAt),children:Ca(ae.createdAt)})});return i.jsxs("div",{id:`comment-${ae.id}`,"aria-label":Ye?"Collapsed comment":void 0,className:Oe?`overflow-hidden min-w-0 rounded-[var(--radius-lg)] border px-4 py-3 shadow-[var(--shadow-sm)] transition-colors duration-1000 ${Ee?"border-primary/50 bg-primary/5":"border-border/80 bg-card/80"}`:`border overflow-hidden min-w-0 rounded-sm transition-colors duration-1000 ${Ye?"border-dashed bg-muted/35 px-3 py-1 hover:bg-muted/50":"p-3"} ${Ee?"border-primary/50 bg-primary/5":"border-border"}`,children:[Oe?i.jsxs("div",{className:"mb-3 flex min-w-0 items-center gap-2",children:[i.jsx("div",{className:"min-w-0",children:ue}),i.jsx("span",{className:"shrink-0 text-sm text-muted-foreground",children:Ca(ae.createdAt)}),Ie?i.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",title:So(ae.updatedAt),children:"edited"}):null]}):i.jsxs("div",{"data-comment-collapsed-header":Ye?"true":void 0,className:Ye?"grid min-w-0 grid-cols-[minmax(0,1fr)_auto_auto] items-center gap-3 text-xs":"grid min-w-0 grid-cols-[minmax(0,1fr)_auto_auto] items-start gap-3",children:[i.jsxs("div",{className:Ye?"min-w-0 py-1":"min-w-0",children:[i.jsx("span",{className:Ye?"block min-w-0 max-w-[min(24rem,55vw)]":"min-w-0",children:ue}),Ye&&J?i.jsx("span",{className:"mt-1 block min-w-0 break-words line-clamp-2 text-sm leading-5 text-foreground",title:J,children:J}):null]}),i.jsxs("span",{className:Ye?"hidden h-7 shrink-0 items-center sm:inline-flex":"flex h-7 shrink-0 items-center gap-1.5",children:[mt,Ie?i.jsx("span",{className:"text-xs text-muted-foreground",title:So(ae.updatedAt),children:"edited"}):null]}),i.jsxs("span",{className:"flex h-7 shrink-0 items-center gap-1",children:[Ye?i.jsx("button",{type:"button",className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border bg-background/70 text-muted-foreground motion-safe:transition-[background-color,color,transform] hover:bg-accent hover:text-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring motion-reduce:transition-none","aria-label":"Expand comment","aria-expanded":"false",title:"Expand comment",onClick:qe,children:i.jsx(rs,{className:"h-3.5 w-3.5"})}):null,Ye?null:i.jsx(eBn,{comment:ae,orgId:r,projectId:s,location:B,collapsed:Ye,canEdit:$e,canDelete:ce,onToggleCollapsed:qe,onEdit:be,onDelete:Ce})]})]}),Oe?i.jsxs(i.Fragment,{children:[i.jsx(Cu,{ref:le,engine:"milkdown",value:R,onChange:D,placeholder:"Edit comment...",mentions:h,agentMentionIntent:"wake",imageUploadHandler:k,className:"rounded-[var(--radius-md)] bg-transparent",contentClassName:"min-h-[92px] bg-transparent text-[15px] leading-7 text-foreground",bordered:!1,onSubmit:ke}),i.jsxs("div",{className:"mt-5 flex items-center justify-between gap-3",children:[k?i.jsxs("div",{children:[i.jsx("input",{ref:ie,type:"file",accept:oht,multiple:!0,className:"hidden",onChange:re}),i.jsx(oe,{type:"button",variant:"ghost",size:"icon-sm",onClick:()=>{var rt;return(rt=ie.current)==null?void 0:rt.click()},disabled:se||X,title:"Attach file",children:i.jsx(df,{className:"h-4 w-4"})})]}):i.jsx("span",{"aria-hidden":"true"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(oe,{size:"sm",variant:"ghost",onClick:ot,disabled:X,children:"Cancel"}),i.jsx(oe,{size:"sm",onClick:ke,disabled:X||se||!R.trim(),children:X?"Saving...":"Save"})]})]})]}):i.jsxs(tBn,{collapsed:Ye,children:[i.jsx(Ya,{className:"text-sm",agentMentions:f,skillReferences:m,onLinkClick:S,children:ae.body}),ae.runId?i.jsx("div",{className:"mt-2 pt-2 border-t border-border/60",children:ae.runAgentId?i.jsxs(vy,{to:`/agents/${ae.runAgentId}/runs/${ae.runId}`,className:"inline-flex items-center rounded-md border border-border bg-accent/30 px-2 py-1 text-[10px] font-mono text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors",children:["run ",ae.runId.slice(0,8)]}):i.jsxs("span",{className:"inline-flex items-center rounded-md border border-border bg-accent/30 px-2 py-1 text-[10px] font-mono text-muted-foreground",children:["run ",ae.runId.slice(0,8)]})}):null]})]})};return i.jsx(E7n,{announcement:z,mountAll:M,onTargetMounted:N,reserveHashScrollEndSpace:j,regionLabel:C,scrollElementRef:I,targetKey:a?`comment:${a}`:null,timeline:t,timelineRegionId:_,children:Be=>de(Be)})});function ove({comments:e,linkedRuns:t=[],activityItems:n=[],orgId:r,projectId:s,onAdd:a,onUpdate:o,onDelete:l,currentUserId:c,currentUserAvatarUrl:d,issueStatus:u,locale:f="en",reopenWillWakeAgent:m=!1,steerRunId:h=null,agentMap:p,imageUploadHandler:x,onAttachImage:b,draftKey:y,liveRunSlot:w,mentions:k,onMentionQueryChange:S,operatorDisplayName:j,heading:C,hideHeading:I=!1,emptyMessage:N="No comments or runs yet.",escapeBackWhenEmpty:M=!1,fixedComposer:E=!1,fixedComposerTimelineScroll:_=!0,hideComposer:z=!1,composerReplacement:T,timelineScrollElementRef:$,progressiveDisclosure:B}){var ze;const[F,W]=A.useState(()=>y?B_e(y):""),Y=UFn(u),[G,V]=A.useState(Y),[L,R]=A.useState(null),[D,X]=A.useState({}),[ee,se]=A.useState(!1),ne=A.useRef(null),le=A.useRef(null),ie=A.useRef(null),re=$??(E&&_?ie:void 0),de=Ir(),Be=p8(),ae=A.useRef(null),Ee=A.useRef(null),he=A.useRef([]),_e=A.useRef([]),Ie=A.useRef(null),$e=A.useRef(null),ce=A.useMemo(()=>e.filter(De=>!De.deletedAt),[e]),Oe=((ze=ce[0])==null?void 0:ze.issueId)??null,Ye=b5(f,"Leave a comment..."),J=A.useMemo(()=>m7n({activityItems:n,comments:ce,linkedRuns:t}),[n,t,ce]),qe=A.useMemo(()=>A7n(J),[J]),be=eOn({config:B,items:qe,locale:f}),ot=A.useMemo(()=>h7n(J,be.selection),[J,be.selection]),ke=A.useMemo(()=>c7n(t,p),[p,t]),Ce=A.useMemo(()=>ke.filter(De=>lht(De.status)||D[De.id]===!0),[D,ke]),{transcriptByRun:ue,hasOutputForRun:mt}=OL({runs:Ce,orgId:r,maxChunksPerRun:120}),ut=A.useCallback((De,kt)=>{X(gt=>({...gt,[De]:kt}))},[]),ge=A.useMemo(()=>k||(p?Array.from(p.values()).filter(De=>De.status!=="terminated").map(De=>({id:`agent:${De.id}`,name:of(De),kind:"agent",agentId:De.id,agentIcon:De.icon,agentRole:De.role})):[]),[p,k]),Le=A.useMemo(()=>ge.filter(De=>De.kind==="skill"&&De.skillMarkdownTarget).map(De=>({href:De.skillMarkdownTarget,label:De.skillRefLabel??De.name,displayName:De.skillDisplayName??De.name,description:De.skillDescription,categoryLabel:De.skillCategoryLabel,locationLabel:De.skillLocationLabel,detailsHref:De.skillDetailsHref})),[ge]),rt=A.useCallback(De=>{W(De),y&&qFn(y,De)},[y]),{canSubmit:At,handleSubmit:Ue,submitting:Se}=f7n({agentMap:p,body:F,canReopen:Y,composerSurfaceRef:le,draftKey:y,editorRef:ne,locale:f,onAdd:a,reopen:G,reopenWillWakeAgent:m,setReopen:V,updateBody:rt}),We=A.useMemo(()=>ge.filter(De=>De.kind==="agent"&&De.agentId).map(De=>({name:De.name,agentId:De.agentId,agentIcon:De.agentIcon})),[ge]);A.useEffect(()=>{y&&W(B_e(y))},[y]);const Te=A.useCallback(()=>{var De;if(typeof window<"u"&&typeof window.cancelAnimationFrame=="function")for(const kt of he.current)window.cancelAnimationFrame(kt);he.current=[];for(const kt of _e.current)clearTimeout(kt);_e.current=[],(De=$e.current)==null||De.call($e),$e.current=null,Ie.current=null,se(!1)},[]);A.useEffect(()=>()=>{Te(),Ee.current&&clearTimeout(Ee.current)},[Te]),A.useEffect(()=>{V(Y)},[Y]);const He=A.useCallback((De,kt="smooth",gt={})=>{const Ke=document.getElementById(`comment-${De}`);if(!Ke)return!1;if(gt.retry&&KFn(Ke)<=QFn)return Te(),!0;Ee.current&&clearTimeout(Ee.current),R(De);const Je=HFn(Ke,kt);return Ie.current={container:Je.container,scrollTop:Je.scrollTop},ZFn(de.pathname,Je.scrollTop),Ee.current=setTimeout(()=>{R(null),Ee.current=null},3e3),!0},[Te,de.pathname]),fe=A.useCallback(({event:De,href:kt})=>{if(De.defaultPrevented||De.button!==0||De.metaKey||De.ctrlKey||De.shiftKey||De.altKey||typeof window>"u")return;const gt=XFn({href:kt,baseHref:window.location.href,currentPathname:de.pathname,currentIssueId:Oe,currentIssueRef:Yfe(de)});if(gt){De.preventDefault(),De.stopPropagation();const wt=`#comment-${encodeURIComponent(gt)}`;return de.hash===wt?He(gt):Be({pathname:de.pathname,search:de.search,hash:wt}),!0}const Ke=(()=>{try{const wt=new URL(kt,window.location.href);if(wt.origin!==window.location.origin||wt.hash===de.hash)return null;const Z=aU(wt.hash);if(!Z)return null;const Me=lH(wt.pathname);if(!Me)return null;const lt=Yfe(de);return lt&&Me===lt||Oe&&Me===Oe?Z:null}catch{return null}})();if(Ke)return De.preventDefault(),De.stopPropagation(),Be({pathname:de.pathname,search:de.search,hash:`#comment-${encodeURIComponent(Ke)}`}),!0;const Je=GFn({href:kt,baseHref:window.location.href});if(Je)return De.preventDefault(),De.stopPropagation(),Be(Je),!0},[Oe,de,Be,He]);A.useLayoutEffect(()=>{const De=aU(de.hash);De&&be.revealTarget(`comment:${De}`)},[de.hash,be.revealTarget]),A.useEffect(()=>{var Ke;const De=de.hash,kt=aU(De);if(!kt||ce.length===0||!ce.some(Je=>Je.id===kt))return;const gt=`${de.key}:${De}`;if(ae.current!==gt)if(Te(),se(!0),He(kt,"auto")){ae.current=gt;const Je=((Ke=Ie.current)==null?void 0:Ke.container)??window,wt=()=>{Te()};for(const Me of F_e)Je.addEventListener(Me,wt,{passive:!0});if($e.current=()=>{for(const Me of F_e)Je.removeEventListener(Me,wt)},typeof window<"u"&&typeof window.requestAnimationFrame=="function"){const Me=window.requestAnimationFrame(()=>{const lt=window.requestAnimationFrame(()=>{He(kt,"auto",{retry:!0}),he.current=he.current.filter(Pe=>Pe!==lt)});he.current.push(lt),he.current=he.current.filter(Pe=>Pe!==Me)});he.current.push(Me)}for(const Me of $_e){const lt=setTimeout(()=>{He(kt,"auto",{retry:!0}),_e.current=_e.current.filter(Pe=>Pe!==lt)},Me);_e.current.push(lt)}const Z=setTimeout(()=>{se(!1),_e.current=_e.current.filter(Me=>Me!==Z)},Math.max(...$_e)+120);_e.current.push(Z)}else R(kt)},[Te,de.hash,de.key,He,ce]);const je=A.useCallback(De=>{if(!De.startsWith("comment:"))return;const kt=`${de.key}:${de.hash}`;if(ae.current===kt)return;const gt=De.slice(8);!gt||!He(gt,"auto")||(ae.current=kt,se(!1))},[de.hash,de.key,He]),ye=i.jsx(rBn,{timeline:ot,agentMap:p,orgId:r,projectId:s,highlightCommentId:L,runExpandedOverrides:D,onToggleRunExpanded:ut,runTranscriptById:ue,runHasOutput:mt,operatorDisplayName:j,agentMentions:We,skillReferences:Le,mentions:ge,emptyMessage:N,currentUserId:c,currentUserAvatarUrl:d,onUpdate:o,onDelete:l,imageUploadHandler:x,onMarkdownLinkClick:fe,reserveHashScrollEndSpace:ee,timelineRegionLabel:B?f==="zh-CN"?"任务动态时间线":"Issue activity timeline":void 0,scrollElementRef:re,onTargetMounted:je,mountAll:be.mountAll,onRevealMore:be.revealMore,timelineRegionId:be.timelineRegionId,disclosureAnnouncement:be.announcement,locale:f}),me=T??i.jsx(Hdt,{body:F,onBodyChange:rt,onSubmit:()=>Ue(),canSubmit:At,submitting:Se,editorRef:ne,surfaceRef:le,placeholder:Ye,mentions:ge,onMentionQueryChange:S,imageUploadHandler:x,onAttachFile:b,attachmentAccept:oht,escapeBackWhenEmpty:M,beforeSubmit:Y?i.jsxs("label",{className:"flex cursor-pointer select-none items-center gap-1.5 text-xs text-muted-foreground",children:[i.jsx("input",{type:"checkbox",checked:G,onChange:De=>V(De.target.checked),className:"rounded border-border"}),"Re-open"]}):null,secondaryAction:h?i.jsxs(oe,{size:"sm",variant:"outline","data-testid":"issue-comment-steer",disabled:!At,onClick:()=>Ue("steer"),title:"Interrupt the active run and continue with this feedback",children:[i.jsx(b3t,{className:"mr-1.5 h-3.5 w-3.5"}),"Steer"]}):null});return E?_?i.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-4",children:[!I&&i.jsx("div",{className:"shrink-0",children:C??i.jsxs("h3",{className:"text-sm font-semibold",children:["Comments & Runs (",J.length,")"]})}),i.jsxs("div",{ref:ie,className:"scrollbar-auto-hide min-h-0 flex-1 overflow-y-auto overscroll-contain pr-1","data-testid":"comment-thread-timeline-scroll",children:[ye,w?i.jsx("div",{className:"mt-4",children:w}):null]}),i.jsx("div",{className:"comment-thread-fixed-composer sticky bottom-0 z-20 -mx-4 -mb-4 shrink-0 px-4 pb-4 pt-3","data-testid":"comment-thread-fixed-composer",children:z?null:me})]}):i.jsxs("div",{className:"flex min-h-0 flex-col gap-1",children:[!I&&i.jsx("div",{className:"shrink-0",children:C??i.jsxs("h3",{className:"text-sm font-semibold",children:["Comments & Runs (",J.length,")"]})}),i.jsxs("div",{"data-testid":"comment-thread-timeline-flow",children:[ye,w?i.jsx("div",{className:"mt-3",children:w}):null]}),i.jsx("div",{className:"comment-thread-fixed-composer sticky bottom-[calc(5rem+env(safe-area-inset-bottom))] z-20 -mx-4 shrink-0 px-4 pb-4 pt-1 md:bottom-0","data-testid":"comment-thread-fixed-composer",children:z?null:me})]}):i.jsxs("div",{className:"space-y-4",children:[!I&&(C??i.jsxs("h3",{className:"text-sm font-semibold",children:["Comments & Runs (",J.length,")"]})),ye,w,z?null:me]})}const sBn=250,iBn=1600;function aBn(){const[e,t]=A.useState("idle"),n=A.useRef(0),r=A.useRef(null),s=A.useRef(null),a=A.useCallback(()=>{r.current&&(clearTimeout(r.current),r.current=null),s.current&&(clearTimeout(s.current),s.current=null)},[]);A.useEffect(()=>a,[a]);const o=A.useCallback(()=>{n.current+=1,a(),t("idle")},[a]),l=A.useCallback(()=>{a(),t("idle")},[a]),c=A.useCallback(async d=>{const u=n.current+1;n.current=u,a(),r.current=setTimeout(()=>{n.current===u&&t("saving")},sBn);try{if(await d(),n.current!==u)return;a(),t("saved"),s.current=setTimeout(()=>{n.current===u&&t("idle")},iBn)}catch(f){throw n.current!==u||(a(),t("error")),f}},[a]);return{state:e,markDirty:l,reset:o,runSave:c}}function m3(e){return e.trim().length===0?"":e}function lve(e){const t=m3(e);return t.length===0?null:t}function j_(e){const t=m3(e);return t.length===0?void 0:t}const Jfe="px-1 -mx-1",oBn=Jfe,lBn=900;function cBn(e){return e instanceof HTMLElement?e:e instanceof Node?e.parentElement:null}function k4(e){e.catch(()=>{})}function p1({value:e,onSave:t,as:n="span",className:r,placeholder:s="Click to edit...",multiline:a=!1,imageUploadHandler:o,mentions:l,onMentionQueryChange:c,onLinkClick:d,editorEngine:u,documentIdentity:f,alwaysEdit:m=!1,variant:h="default"}){const[p,x]=A.useState(m),[b,y]=A.useState(!1),[w,k]=A.useState(e),S=A.useRef(null),j=A.useRef(null),C=A.useRef(null),I=A.useRef(Promise.resolve()),N=A.useRef(null),M=A.useRef(0),E=A.useRef(null),_=A.useRef(!1),z=A.useRef(e),T=A.useRef(!1),$=A.useRef(null),B=A.useRef(!1),[F,W]=A.useState(!1),{state:Y,markDirty:G,reset:V,runSave:L}=aBn(),R=A.useCallback(()=>{C.current&&(clearTimeout(C.current),C.current=null)},[]);A.useEffect(()=>R,[R]),A.useEffect(()=>{var ae,Ee;const re=z.current!==e;if(z.current=e,!re)return;const de=((Ee=(ae=j.current)==null?void 0:ae.getMarkdown)==null?void 0:Ee.call(ae))??w,Be=u==="codemirror"?m3(de):de.trim();if(u==="codemirror"&&a&&b&&T.current&&Be!==e){$.current=e,W(!0),R();return}T.current=!1,_.current=!1,$.current=null,W(!1),k(e)},[R,w,u,a,b,e]);const D=A.useCallback(re=>{re&&(re.style.height="auto",re.style.height=`${re.scrollHeight}px`)},[]),X=q("rudder-inline-markdown-surface rounded",h==="issue-description"&&"rudder-issue-description-surface"),ee=q("rudder-inline-markdown-body",h==="issue-description"&&"rudder-issue-description-markdown rudder-issue-description-markdown-read"),se=q("rudder-edit-in-place-content",h==="issue-description"&&"rudder-issue-description-markdown rudder-issue-description-markdown-edit",r);A.useEffect(()=>{p&&S.current&&(S.current.focus(),S.current.select(),S.current instanceof HTMLTextAreaElement&&D(S.current))},[p,D]),A.useEffect(()=>{if(!p||!a||u==="codemirror"&&m)return;const re=requestAnimationFrame(()=>{var de;(de=j.current)==null||de.focus()});return()=>cancelAnimationFrame(re)},[m,p,u,a]);const ne=A.useCallback(async(re=w)=>{const de=u==="codemirror"?m3(re):re.trim(),Be=M.current>0;if(de!==e||Be)if(Be&&N.current===de)await I.current;else{N.current=de,M.current+=1;const ae=I.current.catch(()=>{}).then(async()=>{await Promise.resolve(t(de))});I.current=ae;try{await ae}finally{M.current-=1,M.current===0&&N.current===de&&(N.current=null)}}else k(e);a||x(!1)},[w,u,a,t,e]);function le(re){re.key==="Enter"&&!a&&(re.preventDefault(),k4(ne())),re.key==="Escape"&&(R(),V(),B.current=!0,T.current=!1,_.current=!1,$.current=null,W(!1),k(e),a?(y(!1),m||x(!1),document.activeElement instanceof HTMLElement&&document.activeElement.blur()):x(!1))}if(A.useEffect(()=>{if(!a||!b)return;if($.current!==null){R();return}const re=u==="codemirror"?m3(w):w.trim();if(E.current===re){E.current=null;return}if(re===e){Y!=="saved"&&V();return}return G(),R(),C.current=setTimeout(()=>{C.current=null,k4(L(()=>ne(re)))},lBn),R},[Y,R,ne,w,u,G,a,b,V,L,e]),a&&(p||u==="codemirror"))return i.jsxs("div",{className:q(oBn,X),onFocusCapture:()=>y(!0),onBlurCapture:re=>{var ae,Ee;if(re.currentTarget.contains(re.relatedTarget))return;if(R(),y(!1),m||x(!1),B.current){B.current=!1;return}const de=_.current?((Ee=(ae=j.current)==null?void 0:ae.getMarkdown)==null?void 0:Ee.call(ae))??w:w,Be=u==="codemirror"?m3(de):de.trim();if($.current!==null){V();return}if(E.current=Be,Be===e){V(),k4(ne(de));return}k4(L(()=>ne(de)))},onKeyDown:le,children:[i.jsx(Cu,{ref:j,engine:u,value:w,onChange:re=>{E.current=null,_.current=!0;const de=u==="codemirror"?m3(re):re.trim();T.current=de!==e,T.current||($.current=null,W(!1)),k(re)},placeholder:s,bordered:!1,className:"bg-transparent",contentClassName:se,imageUploadHandler:o,mentions:l,onMentionQueryChange:c,onLinkClick:d,documentIdentity:f,activateInlineTokensOnPlainClick:h==="issue-description",submitShortcut:"mod-enter",onSubmit:()=>{var Be,ae;R();const re=((ae=(Be=j.current)==null?void 0:Be.getMarkdown)==null?void 0:ae.call(Be))??w,de=u==="codemirror"?m3(re):re.trim();if($.current=null,W(!1),E.current=de,de===e){V(),k4(ne(re));return}k4(L(()=>ne(re)))}}),i.jsx("div",{className:"flex min-h-4 items-center justify-end pr-1",children:i.jsx("span",{className:q("text-[11px] transition-opacity duration-150",Y==="error"?"text-destructive":"text-muted-foreground",Y==="idle"&&!F?"opacity-0":"opacity-100"),children:Y==="saving"?"Autosaving...":F?"Updated elsewhere — submit to overwrite":Y==="saved"?"Saved":Y==="error"?"Could not save":"Idle"})})]});if(p)return i.jsx("textarea",{ref:S,value:w,rows:1,onChange:re=>{k(re.target.value),D(re.target)},onBlur:()=>{k4(ne())},onKeyDown:le,className:q("w-full bg-transparent rounded outline-none resize-none overflow-hidden",Jfe,r)});const ie=e&&a?"div":n;return i.jsx(ie,{className:q(a?X:"rounded overflow-hidden",a?"cursor-text":"cursor-pointer transition-colors hover:bg-accent/50",Jfe,r,a&&!e&&"min-h-9 py-1 text-muted-foreground italic",!a&&!e&&"text-muted-foreground italic"),onClick:re=>{var de;(de=cBn(re.target))!=null&&de.closest("a")||x(!0)},children:e&&a?i.jsx(Ya,{className:ee,copyMarkdownOnCopy:!0,onLinkClick:({event:re,href:de,label:Be,sourceHref:ae})=>{const Ee=d==null?void 0:d({event:re.nativeEvent,href:de,label:Be,sourceHref:ae});return re.stopPropagation(),Ee},children:e}):e||s})}function g1({className:e,orientation:t="horizontal",decorative:n=!0,...r}){return i.jsx(qQe,{"data-slot":"separator",decorative:n,orientation:t,className:q("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",e),...r})}const Xse=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#6366f1","#a855f7","#ec4899"];function Iw(e){return e.trim().replace(/\s+/g," ")}function dht(e,t){const n=Iw(t).toLowerCase();return n?e.find(r=>Iw(r.name).toLowerCase()===n)??null:null}function cve(e){const t=Iw(e);if(!t)return Xse[0];let n=0;for(let r=0;r<t.length;r+=1)n=n*31+t.charCodeAt(r)>>>0;return Xse[n%Xse.length]}function ly(){return typeof window>"u"?null:window.desktopIdentity??null}let eme=null,KS=null,JI=0;const oU=new Set;function lU(e){eme!==e&&(eme=e,oU.forEach(t=>t()))}function dBn(){if(KS)return;const e=ly();if(!e)return;const t=++JI;let n=0;const r=o=>{n+=1,lU(o.status==="signed-in"?o.account.image:null)},s=e.onStateChanged(r);KS=()=>{JI+=1,KS=null,s()};const a=n;e.getState().then(async o=>{if(t!==JI||n!==a||(r(o),o.status!=="signed-in"))return;const l=n;try{const c=await e.getProfile();t===JI&&n===l&&lU(c.image)}catch{}}).catch(()=>{t===JI&&lU(null)})}function uBn(e){return oU.add(e),dBn(),()=>{oU.delete(e),!(oU.size>0)&&(KS==null||KS(),lU(null))}}function G0(){return A.useSyncExternalStore(uBn,()=>eme,()=>null)}const uht="rudder:recent-assignees",U_e=10;function SL(){try{const e=localStorage.getItem(uht);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function Kk(e){if(!e)return;const t=SL().filter(n=>n!==e);t.unshift(e),t.length>U_e&&(t.length=U_e),localStorage.setItem(uht,JSON.stringify(t))}function ZS(e,t){const n=new Map(t.map((r,s)=>[r,s]));return[...e].sort((r,s)=>{const a=n.get(r.id),o=n.get(s.id);return a!==void 0&&o!==void 0?a-o:a!==void 0?-1:o!==void 0?1:r.name.localeCompare(s.name)})}const tme=60,nme=60*tme,C_=24*nme,q_e=7*C_,V_e=30*C_;function Uf(e,t={}){const n=cN(),r=Date.now(),s=new Date(e).getTime(),a=Math.round((r-s)/1e3);if(t.absoluteAfterDays!==void 0&&a>=t.absoluteAfterDays*C_)return So(e);if(a<tme)return n==="zh-CN"?"刚刚":"just now";if(a<nme){const l=Math.floor(a/tme);return n==="zh-CN"?`${l} 分钟前`:`${l}m ago`}if(a<C_){const l=Math.floor(a/nme);return n==="zh-CN"?`${l} 小时前`:`${l}h ago`}if(a<q_e){const l=Math.floor(a/C_);return n==="zh-CN"?`${l} 天前`:`${l}d ago`}if(a<V_e){const l=Math.floor(a/q_e);return n==="zh-CN"?`${l} 周前`:`${l}w ago`}const o=Math.floor(a/V_e);return n==="zh-CN"?Pm(e):`${o}mo ago`}const fBn={xs:"gap-1 px-1.5 py-0.5 text-[10px]",sm:"gap-1.5 px-2 py-0.5 text-xs"},mBn={xs:"h-1.5 w-1.5",sm:"h-2 w-2"};function Zk({label:e,size:t="xs",className:n}){return i.jsxs("span",{"data-slot":"issue-label-chip",className:q("inline-flex max-w-full items-center rounded-[calc(var(--radius-sm)-2px)] border border-[color:var(--border-soft)] bg-[color:color-mix(in_oklab,var(--surface-elevated)_78%,transparent)] font-medium text-muted-foreground",fBn[t],n),title:e.name,children:[i.jsx("span",{className:q("shrink-0 rounded-full",mBn[t]),style:{backgroundColor:e.color},"aria-hidden":"true"}),i.jsx("span",{className:"truncate",children:e.name})]})}function fht(e){const[t,n]=A.useState(null),[r,s]=A.useState(null),a=A.useRef(null),o=A.useRef(null),l=A.useRef(null),c=A.useRef(null),d=is(),u=is(),f=e.disabled||e.pending,m=C=>{const I=window.innerHeight-C,N=document.querySelector("[data-mobile-bottom-navigation]");return!N||N.getClientRects().length===0?I:Math.min(I,N.getBoundingClientRect().top-C)};A.useEffect(()=>{if(!t)return;const C=I=>{I.key!=="Escape"&&I.key!=="ArrowLeft"||(I.preventDefault(),I.stopImmediatePropagation(),x(t))};return window.addEventListener("keydown",C,!0),()=>window.removeEventListener("keydown",C,!0)},[t]);const h=C=>{a.current=C,typeof e.modelSelectRef=="function"?e.modelSelectRef(C):e.modelSelectRef&&(e.modelSelectRef.current=C)},p=(C,I,N=!1)=>{if(f||!I)return;const M=I.getBoundingClientRect(),E=256,_=12,z=m(_),$=window.innerWidth-M.right>=E+_?M.right+8:Math.max(_,M.left-E-8),B=I.closest("[data-runtime-profile-panel]"),F=B==null?void 0:B.getBoundingClientRect(),W=F?$<F.right&&$+E>F.left:!1;if(F&&W){const D=Math.max(0,z-F.bottom-8),X=Math.max(0,F.top-_-8),ee=D>=X,se=Math.min(320,ee?D:X);s({left:Math.min(Math.max(_,M.left),window.innerWidth-_-E),top:ee?F.bottom+8:F.top-8-se,maxHeight:`${se}px`}),n(C),N&&requestAnimationFrame(()=>{var ne;(ne=(C==="model"?l:c).current)==null||ne.focus()});return}const Y=Math.max(0,z-M.top),G=Math.max(0,M.bottom-_),V=Y>=120,L=Math.min(320,V?Y:Math.max(G,Y));s({left:$,top:V?Math.max(_,M.top):Math.max(_,Math.min(M.bottom-L,z-L)),maxHeight:`${L}px`}),n(C),N&&requestAnimationFrame(()=>{var R;(R=(C==="model"?l:c).current)==null||R.focus()})},x=C=>{n(null),requestAnimationFrame(()=>{var I;(I=(C==="model"?a:o).current)==null||I.focus()})},b=(C,I)=>{C.key!=="ArrowLeft"&&C.key!=="Escape"||(C.preventDefault(),C.stopPropagation(),x(I))},y=(C,I)=>{const N=C==="model"?e.testIds.modelOption:e.testIds.effortOption,M=C==="model"?l:c,E=[I.defaultOption,...I.options];return i.jsxs(i.Fragment,{children:[E.map((_,z)=>{const T=I.selectedId===_.id;return i.jsxs("button",{ref:z===0?M:void 0,type:"button",role:"option","aria-selected":T,"data-testid":N(_.id),className:"chat-composer-menu-row",onClick:()=>{I.onSelect(_.id),n(null)},children:[i.jsx("span",{className:"min-w-0 flex-1 truncate",children:_.label}),T?i.jsx(zi,{className:"h-4 w-4 shrink-0","aria-hidden":"true"}):null]},_.id??"default")}),I.loading?i.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-2 text-xs text-muted-foreground",children:[i.jsx(fn,{className:"h-3.5 w-3.5 animate-spin","aria-hidden":"true"}),"Loading models..."]}):I.options.length===0?i.jsx("div",{className:"px-2.5 py-2 text-xs text-muted-foreground",children:I.emptyLabel??"No options found."}):null]})},w=q("pointer-events-auto surface-overlay scrollbar-auto-hide scrollbar-menu-inset fixed z-[80] w-64 overflow-y-auto rounded-[var(--radius-lg)] border p-1.5 shadow-lg"),k=q("chat-composer-menu-row grid min-h-10 grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto] gap-2",f&&"cursor-not-allowed opacity-60"),S=t==="model"&&r&&typeof document<"u"?ja.createPortal(i.jsx("div",{ref:d,"data-runtime-profile-submenu":!0,"data-chat-runtime-submenu":!0,"data-issue-runtime-portal":!0,"data-testid":e.testIds.modelOptions,role:"listbox","aria-label":`${e.ariaContext} model`,className:w,style:r,onKeyDown:C=>b(C,"model"),children:y("model",e.model)}),document.body):null,j=e.effort&&t==="effort"&&r&&typeof document<"u"?ja.createPortal(i.jsx("div",{ref:u,"data-runtime-profile-submenu":!0,"data-chat-runtime-submenu":!0,"data-issue-runtime-portal":!0,"data-testid":e.testIds.effortOptions,role:"listbox","aria-label":`${e.ariaContext} thinking`,className:w,style:r,onKeyDown:C=>b(C,"effort"),children:y("effort",e.effort)}),document.body):null;return i.jsxs("div",{className:"relative min-w-0",children:[i.jsxs("button",{ref:h,type:"button","data-testid":e.testIds.modelTrigger,"aria-label":`Model for ${e.ariaContext}`,"aria-haspopup":"listbox","aria-expanded":t==="model",className:k,disabled:f,title:e.errorMessage??void 0,"data-value":e.model.dataValue,onPointerMove:C=>{C.pointerType==="mouse"&&p("model",a.current)},onClick:()=>p("model",a.current,!0),onKeyDown:C=>{(C.key==="ArrowRight"||C.key==="ArrowDown")&&(C.preventDefault(),p("model",a.current,!0))},children:[i.jsx("span",{className:"font-medium text-foreground",children:"Model"}),i.jsx("span",{className:"min-w-0 truncate text-right text-muted-foreground",children:e.model.valueLabel}),e.model.loading||e.pending?i.jsx(fn,{className:"h-4 w-4 animate-spin text-muted-foreground","aria-hidden":"true"}):i.jsx(vi,{className:"h-4 w-4 text-muted-foreground","aria-hidden":"true"})]}),e.effort?i.jsxs("button",{ref:o,type:"button","data-testid":e.testIds.effortTrigger,"aria-label":`Thinking for ${e.ariaContext}`,"aria-haspopup":"listbox","aria-expanded":t==="effort",className:k,disabled:f,"data-value":e.effort.dataValue,onPointerMove:C=>{C.pointerType==="mouse"&&p("effort",o.current)},onClick:()=>p("effort",o.current,!0),onKeyDown:C=>{(C.key==="ArrowRight"||C.key==="ArrowDown")&&(C.preventDefault(),p("effort",o.current,!0))},children:[i.jsx("span",{className:"font-medium text-foreground",children:"Thinking"}),i.jsx("span",{className:"min-w-0 truncate text-right text-muted-foreground",children:e.effort.valueLabel}),e.pending?i.jsx(fn,{className:"h-4 w-4 animate-spin text-muted-foreground","aria-hidden":"true"}):i.jsx(vi,{className:"h-4 w-4 text-muted-foreground","aria-hidden":"true"})]}):null,e.errorMessage?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"mt-1 flex min-h-7 items-center gap-1.5 border-t border-[color:var(--border-soft)] px-2.5 pt-1.5 text-[11px] text-muted-foreground",children:i.jsx("span",{children:e.errorMessage})}),i.jsx("span",{className:"sr-only",role:"status",children:e.errorMessage})]}):null,S,j]})}const mht="deepseek-v4-pro[1m]",cU=[{id:mht,label:"DeepSeek V4 Pro (1M)"},{id:"deepseek-v4-flash",label:"DeepSeek V4 Flash"},{id:"claude-opus-4-6",label:"Claude Opus 4.6",variants:["low","medium","high","xhigh","max"]},{id:"claude-sonnet-4-6",label:"Claude Sonnet 4.6",variants:["low","medium","high","xhigh","max"]},{id:"claude-haiku-4-6",label:"Claude Haiku 4.6",variants:[]},{id:"claude-sonnet-4-5-20250929",label:"Claude Sonnet 4.5"},{id:"claude-haiku-4-5-20251001",label:"Claude Haiku 4.5",variants:[]}],ABn={claude_local:cU,codex_local:Azn,cursor:Gzn},hBn=["opencode_local","pi_local"];function dve(e){return e.trim().toLowerCase().startsWith("deepseek")}function l9(e){return hBn.includes(e)}function Aht(e){const[t,n]=e.split("/",2).map(r=>r.trim());return!!(t&&n)}function hht(e,t=!1){return l9(e)?"Select or enter provider/model":t?"Select model":"Default"}function pht(e){return l9(e)?"Search or enter provider/model...":"Search models..."}function ght(e,t=!1){return t?"Loading models...":e==="pi_local"?"No models discovered. Run `pi --list-models`, authenticate the provider, or enter provider/model such as deepseek/deepseek-chat and run Test now.":e==="opencode_local"?"No models discovered. Run `opencode models --verbose`, authenticate the provider, or enter provider/model and run Test now.":"No models found."}function xht(e){return e==="pi_local"?"Pi requires provider/model, for example kimi-coding/kimi-for-coding.":e==="opencode_local"?"OpenCode requires provider/model, for example opencode/deepseek-v4-flash-free.":"This runtime requires provider/model."}function dY(e){const t=e.indexOf("/");return(t>=0?e.slice(0,t).trim():e.trim())||null}function pBn(e){const t=e.indexOf("/");return(t>=0?e.slice(t+1).trim():"")||null}function gBn(e,t){const n=dY(t);return e==="claude_local"&&dve(t)?"For Claude Code + DeepSeek, use a DeepSeek model such as deepseek-v4-pro[1m]. Paste DEEPSEEK_API_KEY below or reference the existing organization secret, then use Test now as the source of truth.":e==="pi_local"?n==="deepseek"?"For Pi + DeepSeek, use provider/model such as deepseek/deepseek-chat. Paste DEEPSEEK_API_KEY below, or use pi /login if DeepSeek is already configured locally. If Pi routes through OpenRouter, use openrouter/deepseek/deepseek-chat and paste OPENROUTER_API_KEY. Test now is the source of truth.":n?`For Pi, authenticate provider "${n}" with pi /login, auth.json, or provider env, then use Test now to prove the selected model can answer.`:"Pi models use provider/model format. Use pi --list-models, or enter a custom provider/model and run Test now.":e==="opencode_local"?n?`For OpenCode, authenticate provider "${n}" with opencode auth login or provider env, then use Test now to prove the selected model can answer.`:"OpenCode models use provider/model format. Use opencode models, or enter a custom provider/model and run Test now.":null}function dU(e,t){const n=dY(t);if(e==="claude_local"&&dve(t))return"DEEPSEEK_API_KEY";if(e==="pi_local"){if(n==="deepseek")return"DEEPSEEK_API_KEY";if(n==="openrouter")return"OPENROUTER_API_KEY";if(n==="kimi-coding"||n==="kimi")return"KIMI_API_KEY"}return null}function xBn(e,t){const n=dU(e,t);return n?`${n} for ${t.trim()||"this provider"}`:null}function bBn(e,t,n){const r=t.trim();if(e==="cursor")return`${r} --trust -p --mode ask --output-format json "Respond with hello."`;if(e==="codex_local")return`${r} exec --dangerously-bypass-approvals-and-sandbox --json "Respond with hello."`;if(e==="opencode_local"){const s=n.trim()?` --model ${n.trim()}`:"";return`${r} run --format json${s} "Respond with hello."`}if(e==="pi_local"){const s=dY(n)??"<provider>",a=pBn(n)??"<model>";return`${r} -p "Respond with hello." --mode json --provider ${s} --model ${a} --tools read`}return`${r} -p "Respond with hello." --output-format json --no-session-persistence --permission-mode auto --bare --tools ""`}function yBn(e,t){const n=dY(t);return e==="claude_local"&&dve(t)?"If auth fails, set DEEPSEEK_API_KEY in the runtime env or organization secret binding, then retry Claude Code Test now.":e==="cursor"?"If auth fails, set CURSOR_API_KEY in env or run cursor-agent login.":e==="codex_local"?"If auth fails, run codex login or configure the OpenAI credentials Codex already uses locally.":e==="opencode_local"?"If auth fails, run opencode auth login or set the provider API key in env.":e==="pi_local"&&n==="deepseek"?"If auth fails, set DEEPSEEK_API_KEY for native Pi DeepSeek or run pi /login. If Pi asks for openrouter, set OPENROUTER_API_KEY or add a native DeepSeek provider/model in ~/.pi/agent/models.json.":e==="pi_local"&&n?`If auth fails, authenticate provider "${n}" with pi /login, ~/.pi/agent/auth.json, or provider env.`:"If login is required, run claude auth login and retry."}function rme(e){const t=e.checks.find(n=>n.level==="error"||/_hello_probe_(auth_required|model_unavailable|timed_out|unexpected_output|failed)$/.test(n.code));if(e.status==="fail"||t){const n=(t==null?void 0:t.hint)||(t==null?void 0:t.message);return n?`Runtime environment test is not ready: ${n}`:"Runtime environment test is not ready. Fix the runtime setup and run Test now again."}return null}function c9(e,...t){var a,o;const n=[...t.flatMap(l=>l??[]),...ABn[e]??[]],r=new Set,s=[];for(const l of n){const c=l.id.trim();if(!c||r.has(c))continue;r.add(c);const d=Array.isArray(l.variants)?[...new Set(l.variants.filter(f=>typeof f=="string"&&f.trim().length>0))]:void 0,u=(a=l.capabilities)==null?void 0:a.reasoning;s.push({id:c,label:((o=l.label)==null?void 0:o.trim())||c,...d?{variants:d}:{},...typeof u=="boolean"?{capabilities:{reasoning:u}}:{}})}return s}const bht=["off","minimal","low","medium","high","xhigh"];function E0(e){return{value:e,label:e==="xhigh"?"Extra High":e.charAt(0).toUpperCase()+e.slice(1)}}e3.map(E0);ive["gpt-5.6-sol"].map(E0);bht.map(E0);const vBn=bht.filter(e=>e!=="xhigh").map(E0);function d9(e){const t=new Set;return e.flatMap(n=>{const r=n.value.trim();return!r||t.has(r)?[]:(t.add(r),[{value:r,label:n.label}])})}function IE(e){return[{value:"",label:"Auto"},...d9(e)]}function uve(e,t){if((t==null?void 0:t.variants)!==void 0){const n=d9(t.variants.map(E0));return n.length===0?[]:IE(n)}return[]}function fve(e,t){return!t||!Array.isArray(t.variants)||t.variants.length===0?[]:IE(d9(t.variants.map(E0)))}function mve(e,t){if((t==null?void 0:t.variants)!==void 0)return t.variants.map(E0);if(t)return[];const n=ive[e.trim().toLowerCase()];return n?n.map(E0):[]}function Ave(e,t){var n,r;if(((n=t==null?void 0:t.capabilities)==null?void 0:n.reasoning)===!1)return[];if((t==null?void 0:t.variants)!==void 0){const s=d9(t.variants.map(E0));return s.length===0?[]:IE(s)}return((r=t==null?void 0:t.capabilities)==null?void 0:r.reasoning)===!0?IE(vBn):[]}function hve(e,t){if(!t)return[];if(Array.isArray(t.variants)){const n=d9(t.variants.map(E0));return n.length===0?[]:IE(n)}return[]}function yht(e,t){return[{value:"",label:e},...d9(t)]}const wBn=new Set(["claude_local","codex_local","opencode_local","pi_local","cursor"]);function pve(e){return!!(e&&wBn.has(e.agentRuntimeType))}function gve(e){return e==="codex_local"?"modelReasoningEffort":e==="opencode_local"?"variant":e==="claude_local"?"effort":e==="pi_local"?"thinking":e==="cursor"?"effort":null}function vht(e){return{...e.runtimeConfig,...e.agentRuntimeConfig}}function oT(e){const t=vht(e).model;return typeof t=="string"&&t.trim()?t.trim():"Default model"}function wht(e){const t=vht(e),n=gve(e.agentRuntimeType),r=n?t[n]??(n==="modelReasoningEffort"?t.reasoningEffort:null):null;return typeof r=="string"&&r.trim()?r.trim():null}function cH(e,t){var r;const n=(r=e==null?void 0:e.agentRuntimeConfig)==null?void 0:r[t];return typeof n=="string"&&n.trim()?n.trim():null}function sme(e,t){return cH(e,t)??(t==="modelReasoningEffort"?cH(e,"reasoningEffort"):null)}function ime(e){return!e||e.toLowerCase()==="auto"?"Auto":{minimal:"Minimal",light:"Light",low:"Low",medium:"Medium",high:"High",xhigh:"Extra High",max:"Max",ultra:"Ultra"}[e.toLowerCase()]??`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function kBn(e,t,n){const r=c9(e.agentRuntimeType,t);return!n||r.some(s=>s.id===n)?r:[...r,{id:n,label:n}]}function Gse(e,t,n){const r=e.agentRuntimeType==="claude_local"?uve(t,n):e.agentRuntimeType==="codex_local"?mve(t,n):e.agentRuntimeType==="opencode_local"?fve(t,n):e.agentRuntimeType==="pi_local"?Ave(t,n):e.agentRuntimeType==="cursor"?hve(t,n):[];return[{id:null,label:"Agent default"},...r.filter(s=>s.value.length>0).map(s=>({id:s.value,label:s.label}))]}function Yse(e,t,n,r){const s={...(e==null?void 0:e.agentRuntimeConfig)??{}};t?s.model=t:delete s.model,n?s[r]=n:delete s[r],r==="modelReasoningEffort"&&delete s.reasoningEffort;const a={...e??{}};return Object.keys(s).length>0?a.agentRuntimeConfig=s:delete a.agentRuntimeConfig,a.agentRuntimeConfig||a.useProjectWorkspace!==void 0?a:null}function OBn(e,t){var o;const n=cH(t,"model")??oT(e),r=gve(e.agentRuntimeType),s=r?sme(t,r)??wht(e):null,a=(o=t==null?void 0:t.agentRuntimeConfig)!=null&&o.model||r&&sme(t,r)?"Custom profile":"Agent default";return r?`${a} · ${n} · ${ime(s)}`:`${a} · ${n}`}function uY({agent:e,orgId:t,overrides:n,onApply:r,variant:s="compact",disabled:a=!1}){const o=pve(e),[l,c]=A.useState(!1),[d,u]=A.useState(!1),[f,m]=A.useState(null),[h,p]=A.useState(null),[x,b]=A.useState(null),[y,w]=A.useState(!1),k=A.useRef(null),S=A.useRef(null),j=gve(e.agentRuntimeType),C=Ve({queryKey:U.agents.adapterModels(t,e.agentRuntimeType),queryFn:()=>$n.adapterModels(t,e.agentRuntimeType),enabled:(l||d)&&o,retry:!1}),I=cH(n,"model"),N=sme(n,j),M=y?h:I,E=y?x:N,_=M??oT(e),z=kBn(e,C.data,M),T=z.find(le=>le.id===_),$=Gse(e,_,T),B=$.length>1,F=E,W=OBn(e,n),Y=()=>{u(!1),w(!1)},G=(le,ie,re)=>{const Be=document.querySelector("[data-mobile-bottom-navigation]"),ae=Be&&Be.getClientRects().length>0?Math.min(window.innerHeight-12,Be.getBoundingClientRect().top-12):window.innerHeight-12;return{left:window.innerWidth-le.right>=ie+12?le.right+8:Math.max(12,le.left-ie-8),top:Math.max(12,Math.min(le.top,ae-re))}},V=()=>{a||!S.current||(p(I),b(N),w(!0),m(G(S.current.getBoundingClientRect(),304,176)),u(!0))};if(A.useEffect(()=>{if(!d)return;const le=ie=>{var re,de;ie.target instanceof Node&&((re=k.current)!=null&&re.contains(ie.target)||ie.target instanceof Element&&ie.target.closest("[data-runtime-profile-submenu]")||(de=S.current)!=null&&de.contains(ie.target)||Y())};return document.addEventListener("pointerdown",le),()=>document.removeEventListener("pointerdown",le)},[d]),A.useEffect(()=>{if(!d)return;const le=ie=>{ie.key!=="Escape"&&ie.key!=="ArrowLeft"||document.querySelector("[data-runtime-profile-submenu]")||(ie.preventDefault(),ie.stopImmediatePropagation(),Y(),requestAnimationFrame(()=>{var re;return(re=S.current)==null?void 0:re.focus()}))};return window.addEventListener("keydown",le,!0),()=>window.removeEventListener("keydown",le,!0)},[d]),A.useEffect(()=>{if(!d)return;const le=()=>{S.current&&m(G(S.current.getBoundingClientRect(),304,176))};return window.addEventListener("resize",le),window.addEventListener("scroll",le,!0),()=>{window.removeEventListener("resize",le),window.removeEventListener("scroll",le,!0)}},[d]),!o)return null;const L=le=>{le?(p(I),b(N),w(!0)):w(!1),c(le)},R=()=>{r(Yse(n,h,x,j)),c(!1)},D=le=>{if(p(le),le==null){b(null);return}const ie=le??oT(e),re=Gse(e,ie,z.find(de=>de.id===ie));x&&!re.some(de=>de.id===x)&&b(null)},X=()=>{Y(),requestAnimationFrame(()=>{var le;return(le=S.current)==null?void 0:le.focus()})},ee=le=>{const ie=le??oT(e),re=Gse(e,ie,z.find(Be=>Be.id===ie)),de=x&&re.some(Be=>Be.id===x)?x:null;p(le),b(de),r(Yse(n,le,de,j)),X()},se=le=>{b(le),r(Yse(n,M,le,j)),X()},ne=le=>i.jsx(fht,{ariaContext:`${e.name} runtime`,disabled:a,errorMessage:C.error?"Models unavailable; showing built-in defaults.":null,testIds:{modelTrigger:"issue-runtime-model-trigger",modelOptions:"issue-runtime-model-options",modelOption:ie=>ie==null?"issue-runtime-option-default-model":`issue-runtime-option-model-${ie}`,effortTrigger:"issue-runtime-effort-trigger",effortOptions:"issue-runtime-effort-options",effortOption:ie=>`issue-runtime-option-effort-${ie??"default"}`},model:{valueLabel:_,selectedId:M,defaultOption:{id:null,label:`Agent default · ${oT(e)}`},options:z,loading:C.isPending,emptyLabel:C.error?"Models unavailable":"No models found.",onSelect:le==="menu"?ee:D},effort:B?{valueLabel:ime(F),selectedId:F,defaultOption:{id:null,label:`Agent default · ${ime(wht(e))}`},options:$.filter(ie=>ie.id!=null),onSelect:le==="menu"?se:b}:void 0});if(s==="menu"){const le=d&&f&&typeof document<"u"?ja.createPortal(i.jsxs("div",{ref:k,"data-issue-runtime-portal":!0,"data-runtime-profile-panel":!0,"data-testid":"issue-runtime-profile-panel",role:"dialog","aria-label":`Model and thinking for ${e.name}`,className:"pointer-events-auto surface-overlay fixed z-[75] w-[19rem] max-w-[calc(100vw-1.5rem)] rounded-[var(--radius-lg)] border p-1.5 shadow-lg",style:f,onKeyDownCapture:ie=>{ie.key==="Escape"?(ie.preventDefault(),ie.stopPropagation(),Y(),requestAnimationFrame(()=>{var re;return(re=S.current)==null?void 0:re.focus()})):ie.key==="ArrowLeft"&&(ie.preventDefault(),ie.stopPropagation(),Y(),requestAnimationFrame(()=>{var re;return(re=S.current)==null?void 0:re.focus()}))},children:[i.jsxs("button",{type:"button",className:"chat-composer-menu-row mb-1",onClick:()=>{Y(),requestAnimationFrame(()=>{var ie;return(ie=S.current)==null?void 0:ie.focus()})},children:[i.jsx(Tw,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),i.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:e.name})]}),i.jsx("div",{className:"border-t border-[color:var(--border-soft)] pt-1",children:ne("menu")})]}),document.body):null;return i.jsxs(i.Fragment,{children:[i.jsxs("button",{ref:S,type:"button","data-testid":"issue-runtime-selector","aria-label":`Configure model and thinking for ${e.name}`,"aria-haspopup":"dialog","aria-expanded":d,className:q("chat-composer-menu-row !w-auto min-w-0 max-w-full",a&&"cursor-not-allowed opacity-60"),disabled:a,title:W,onClick:()=>d?Y():V(),onKeyDown:ie=>{(ie.key==="ArrowRight"||ie.key==="Enter"||ie.key===" ")&&(ie.preventDefault(),V())},children:[i.jsx(f6,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),i.jsx("span",{className:"min-w-0 flex-1 truncate font-medium text-foreground",children:"Model"}),i.jsx("span",{className:"min-w-0 max-w-[14rem] truncate text-right text-muted-foreground",children:W}),i.jsx(vi,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"})]}),le]})}return i.jsxs(bi,{open:l,onOpenChange:L,children:[i.jsx(Hi,{asChild:!0,children:i.jsxs("button",{type:"button","data-testid":"issue-runtime-selector","aria-label":`Run profile for ${e.name}`,className:q(s==="icon"?"inline-flex h-6 w-6 shrink-0 items-center justify-center rounded text-muted-foreground opacity-100 transition-[color,background-color,opacity] hover:bg-accent/70 hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 md:pointer-events-none md:opacity-0 md:group-hover/issue-property:pointer-events-auto md:group-hover/issue-property:opacity-100 md:group-focus-within/issue-property:pointer-events-auto md:group-focus-within/issue-property:opacity-100 data-[state=open]:pointer-events-auto data-[state=open]:opacity-100":"inline-flex min-w-0 items-center gap-1 rounded px-1.5 py-1 text-[11px] text-muted-foreground transition-colors hover:bg-accent/70 hover:text-foreground",a&&"cursor-not-allowed opacity-60"),disabled:a,title:W,children:[i.jsx(f6,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":"true"}),s==="compact"?i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"min-w-0 truncate",children:W}),i.jsx(rs,{className:"h-3 w-3 shrink-0","aria-hidden":"true"})]}):null]})}),i.jsxs(yi,{"data-testid":"issue-runtime-profile-panel","data-runtime-profile-panel":!0,align:"end",side:"bottom",sideOffset:6,collisionPadding:12,className:"surface-overlay w-[19rem] max-w-[calc(100vw-1.5rem)] p-1.5",onInteractOutside:le=>{const ie=le.target;ie instanceof Element&&ie.closest("[data-runtime-profile-submenu]")&&le.preventDefault()},children:[i.jsxs("button",{type:"button",className:"chat-composer-menu-row mb-1",onClick:()=>c(!1),children:[i.jsx(Tw,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),i.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:e.name})]}),i.jsx("div",{className:"border-t border-[color:var(--border-soft)] pt-1",children:ne("staged")}),i.jsxs("div",{className:"mt-2 flex justify-end gap-2 border-t border-border pt-2",children:[i.jsx("button",{type:"button",className:"rounded px-2 py-1.5 text-xs text-muted-foreground hover:bg-accent/60",onClick:()=>c(!1),children:"Cancel"}),i.jsx("button",{type:"button","data-testid":"issue-runtime-apply",className:"rounded bg-primary px-2.5 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",onClick:R,children:"Apply"})]})]})]})}function SBn(e){var t,n,r,s,a,o,l,c;return e?((t=e.codebase)==null?void 0:t.scope)==="organization"||((n=e.codebase)==null?void 0:n.scope)==="none"?((r=e.executionWorkspacePolicy)==null?void 0:r.defaultProjectWorkspaceId)??null:((s=e.executionWorkspacePolicy)==null?void 0:s.defaultProjectWorkspaceId)??((o=(a=e.workspaces)==null?void 0:a.find(d=>d.isPrimary))==null?void 0:o.id)??((c=(l=e.workspaces)==null?void 0:l[0])==null?void 0:c.id)??null:null}function xm({label:e,children:t,align:n="center"}){return i.jsxs("div",{"data-slot":"issue-property-row","data-align":n,className:q("group/issue-property flex gap-3 py-1.5",n==="start"?"items-start":"items-center"),children:[i.jsx("span",{className:"text-xs text-muted-foreground shrink-0 w-20",children:e}),i.jsx("div",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:t})]})}function IO({inline:e,label:t,open:n,onOpenChange:r,triggerContent:s,triggerAriaLabel:a,triggerClassName:o,popoverClassName:l,popoverAlign:c="end",rowAlign:d="center",extra:u,children:f}){const m=q("inline-flex min-w-0 max-w-full items-center gap-1.5 cursor-pointer hover:bg-accent/50 rounded px-1 -mx-1 py-0.5 transition-colors",o);return e?i.jsxs("div",{children:[i.jsxs(xm,{label:t,align:d,children:[i.jsx("button",{type:"button",className:m,"aria-label":a,onClick:()=>r(!n),children:s}),u]}),n&&i.jsx("div",{className:q("rounded-md border border-border bg-popover p-1 mb-2",l),children:f})]}):i.jsxs(xm,{label:t,align:d,children:[i.jsxs(bi,{open:n,onOpenChange:r,children:[i.jsx(Hi,{asChild:!0,children:i.jsx("button",{type:"button",className:m,"aria-label":a,children:s})}),i.jsx(yi,{className:q("p-1",l),align:c,collisionPadding:16,children:f})]}),u]})}function dH({issue:e,onUpdate:t,inline:n,childIssues:r,showAuditFields:s=!0,showAuditSeparator:a=!0}){var Pe,Re,Nt,Wt,Jt,Ze,Mt;const{selectedOrganizationId:o}=Mr(),{openNewIssue:l}=Bs(),{pushToast:c}=ws(),d=er(),u=e.orgId??o,[f,m]=A.useState(!1),[h,p]=A.useState(""),[x,b]=A.useState(!1),[y,w]=A.useState(""),[k,S]=A.useState(!1),[j,C]=A.useState(""),[I,N]=A.useState(!1),[M,E]=A.useState(""),[_,z]=A.useState(!1),[T,$]=A.useState(!1),[B,F]=A.useState(""),[W,Y]=A.useState(!1),[G,V]=A.useState(""),L=is(),R=is(),{data:D}=Ve({queryKey:U.auth.session,queryFn:()=>Ll.getSession()}),X=((Pe=D==null?void 0:D.user)==null?void 0:Pe.id)??((Re=D==null?void 0:D.session)==null?void 0:Re.userId),ee=G0(),se=Ae=>Ae&&Ae===X?ee:null,{data:ne}=Ve({queryKey:U.agents.list(u),queryFn:()=>$n.list(u),enabled:!!u}),{data:le}=Ve({queryKey:U.projects.list(u),queryFn:()=>Wi.list(u),enabled:!!u}),ie=A.useMemo(()=>(le??[]).filter(Ae=>!Ae.archivedAt||Ae.id===e.projectId),[le,e.projectId]),{orderedProjects:re}=PR({projects:ie,orgId:u,userId:X}),{data:de}=Ve({queryKey:U.issues.labels(u),queryFn:()=>fr.listLabels(u),enabled:!!u}),{data:Be}=Ve({queryKey:U.issues.list(u),queryFn:()=>fr.list(u),enabled:!!u}),ae=xt({mutationFn:Ae=>fr.createLabel(u,Ae),onSuccess:async Ae=>{await d.invalidateQueries({queryKey:U.issues.labels(u)}),t({labelIds:[...e.labelIds??[],Ae.id]}),V("")}}),Ee=Ae=>{const ht=e.labelIds??[],Lt=ht.includes(Ae)?ht.filter(Mn=>Mn!==Ae):[...ht,Ae];t({labelIds:Lt})},he=Ae=>{if(!Ae||!ne)return null;const ht=ne.find(Lt=>Lt.id===Ae);return(ht==null?void 0:ht.name)??Ae.slice(0,8)},_e=A.useMemo(()=>new Map((ne??[]).map(Ae=>[Ae.id,Ae])),[ne]),Ie=Ae=>{if(!Ae)return(Ae==null?void 0:Ae.slice(0,8))??"None";const ht=re.find(Lt=>Lt.id===Ae);return(ht==null?void 0:ht.name)??Ae.slice(0,8)},$e=A.useMemo(()=>new Map((Be??[]).map(Ae=>[Ae.id,Ae])),[Be]),ce=A.useCallback(Ae=>{var ht;return((ht=Ae.project)==null?void 0:ht.name)??(Ae.projectId?Ie(Ae.projectId):null)},[re]),Oe=Ae=>Ae.identifier??Ae.id.slice(0,8),Ye=A.useCallback((Ae,ht)=>{const Lt=ht.trim().toLowerCase();return Lt?`${Ae.identifier??""} ${Ae.title}`.toLowerCase().includes(Lt):!0},[]),J=A.useCallback((Ae,ht)=>{var Ln;let Lt=Ae.parentId;const Mn=new Set;for(;Lt;){if(Lt===ht)return!0;if(Mn.has(Lt))return!1;Mn.add(Lt),Lt=((Ln=$e.get(Lt))==null?void 0:Ln.parentId)??null}return!1},[$e]),qe=e.parentId?((Nt=e.ancestors)==null?void 0:Nt[0])??$e.get(e.parentId)??null:null,be=A.useMemo(()=>(r??[]).slice(0,5),[r]),ot=()=>{z(!1),$(!1),l({parentId:e.id,parentIssue:{id:e.id,identifier:e.identifier,title:e.title},...e.projectId?{projectId:e.projectId}:{},...e.goalId?{goalId:e.goalId}:{}})},ke=xt({mutationFn:Ae=>fr.update(Ae.id,{parentId:e.id}),onSuccess:async(Ae,ht)=>{$(!1),F(""),await d.invalidateQueries({queryKey:U.issues.detail(e.id)}),await d.invalidateQueries({queryKey:U.issues.detail(Ae.id)}),Ae.identifier&&await d.invalidateQueries({queryKey:U.issues.detail(Ae.identifier)}),u&&(await d.invalidateQueries({queryKey:U.issues.list(u)}),await d.invalidateQueries({queryKey:U.issues.children(u,e.id)}),ht.parentId&&await d.invalidateQueries({queryKey:U.issues.children(u,ht.parentId)}))},onError:Ae=>{c({title:Ae instanceof Error?Ae.message:"Failed to add existing issue",tone:"error"})}}),Ce=A.useMemo(()=>(Be??[]).filter(Ae=>Ae.id!==e.id).filter(Ae=>!J(Ae,e.id)).filter(Ae=>Ye(Ae,M)).slice(0,12),[Be,e.id,Ye,J,M]),ue=A.useMemo(()=>(Be??[]).filter(Ae=>Ae.id!==e.id).filter(Ae=>Ae.parentId!==e.id).filter(Ae=>!(e.ancestors??[]).some(ht=>ht.id===Ae.id)).filter(Ae=>Ye(Ae,B)).slice(0,12),[Be,B,e.ancestors,e.id,Ye]),mt=Ae=>{if(!Ae)return null;const ht=(le==null?void 0:le.find(Lt=>Lt.id===Ae))??null;return ht?Gj(ht):`/projects/${Ae}`},ut=A.useMemo(()=>SL(),[f]),ge=A.useMemo(()=>ZS((ne??[]).filter(Ae=>Ae.status!=="terminated"),ut),[ne,ut]),Le=e.assigneeAgentId?ne==null?void 0:ne.find(Ae=>Ae.id===e.assigneeAgentId):null,rt=e.reviewerAgentId?ne==null?void 0:ne.find(Ae=>Ae.id===e.reviewerAgentId):null,At=Ae=>NA(Ae,X),Ue=At(e.assigneeUserId),Se=At(e.reviewerUserId),We=At(e.createdByUserId),Te=(e.labels??[]).length>0?i.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[(e.labels??[]).slice(0,3).map(Ae=>i.jsx(Zk,{label:Ae,size:"sm"},Ae.id)),(e.labels??[]).length>3&&i.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",(e.labels??[]).length-3]})]}):i.jsxs(i.Fragment,{children:[i.jsx(Hae,{className:"h-3.5 w-3.5 text-muted-foreground"}),i.jsx("span",{className:"text-sm text-muted-foreground",children:"No labels"})]}),He=Iw(G),fe=A.useMemo(()=>(de??[]).filter(Ae=>He?Ae.name.toLowerCase().includes(He.toLowerCase()):!0),[de,He]),je=A.useMemo(()=>dht(de??[],He),[de,He]),ye=He.length>0&&fe.length===0&&!je,tt=cve(He),me=A.useCallback(()=>{!ye||ae.isPending||ae.mutate({name:He,color:tt})},[ae,tt,He,ye]),ze=i.jsxs(i.Fragment,{children:[i.jsx("input",{className:"w-full px-2 py-1.5 text-xs bg-transparent outline-none border-b border-border mb-1 placeholder:text-muted-foreground/50",placeholder:"Search labels...",value:G,onChange:Ae=>V(Ae.target.value),onKeyDown:Ae=>{Ae.key!=="Enter"||!ye||(Ae.preventDefault(),me())},autoFocus:!n}),i.jsxs("div",{className:"max-h-44 overflow-y-auto overscroll-contain space-y-0.5",children:[fe.map(Ae=>{const ht=(e.labelIds??[]).includes(Ae.id);return i.jsxs("button",{className:q("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-left",ht&&"bg-accent"),onClick:()=>Ee(Ae.id),children:[i.jsx("span",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:Ae.color}}),i.jsx("span",{className:"truncate",children:Ae.name})]},Ae.id)}),ye&&i.jsxs(i.Fragment,{children:[fe.length>0?i.jsx("div",{className:"my-1 border-t border-border"}):null,i.jsxs("button",{className:"flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-left",disabled:ae.isPending,onClick:me,children:[i.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-sm border border-border/70 text-muted-foreground",children:i.jsx(ps,{className:"h-2.5 w-2.5"})}),i.jsx("span",{className:"truncate",children:ae.isPending?"Creating…":`Create label "${He}"`}),i.jsx("span",{className:"ml-auto h-2.5 w-2.5 shrink-0 rounded-full",style:{backgroundColor:tt},"aria-hidden":"true"})]})]})]})]}),De=Le?i.jsx(Ro,{kind:"agent",label:Le.name,agentAvatarStyle:"bare",agentIcon:Le.icon,agentRole:Le.role,className:"w-full"}):Ue?i.jsx(Ro,{kind:"user",label:Ue,avatarUrl:se(e.assigneeUserId)}):i.jsx(Ro,{kind:"unassigned",label:"Unassigned",muted:!0}),kt=i.jsxs(i.Fragment,{children:[i.jsx("input",{className:"w-full px-2 py-1.5 text-xs bg-transparent outline-none border-b border-border mb-1 placeholder:text-muted-foreground/50",placeholder:"Search assignees...",value:h,onChange:Ae=>p(Ae.target.value),autoFocus:!n}),i.jsxs("div",{ref:L,"data-testid":"issue-properties-assignee-scroll",className:"scrollbar-auto-hide max-h-60 overflow-y-auto overscroll-contain",children:[i.jsx("button",{className:q("flex min-w-0 items-center gap-2 w-full px-2 py-1.5 text-left text-xs rounded hover:bg-accent/50",!e.assigneeAgentId&&!e.assigneeUserId&&"bg-accent"),onClick:()=>{t({assigneeAgentId:null,assigneeUserId:null,assigneeAgentRuntimeOverrides:null}),m(!1)},children:i.jsx(Ro,{kind:"unassigned",label:"No assignee"})}),X&&i.jsx("button",{className:q("flex min-w-0 items-center gap-2 w-full px-2 py-2 text-left text-xs rounded hover:bg-accent/50",e.assigneeUserId===X&&"bg-accent"),onClick:()=>{t({assigneeAgentId:null,assigneeUserId:X,assigneeAgentRuntimeOverrides:null}),m(!1)},children:i.jsx(ufe,{avatarUrl:ee})}),e.createdByUserId&&e.createdByUserId!==X&&i.jsx("button",{className:q("flex min-w-0 items-center gap-2 w-full px-2 py-1.5 text-left text-xs rounded hover:bg-accent/50",e.assigneeUserId===e.createdByUserId&&"bg-accent"),onClick:()=>{t({assigneeAgentId:null,assigneeUserId:e.createdByUserId,assigneeAgentRuntimeOverrides:null}),m(!1)},children:i.jsx(Ro,{kind:"user",label:We?`Assign to ${We}`:"Assign to requester",avatarUrl:se(e.createdByUserId)})}),ge.filter(Ae=>{if(!h.trim())return!0;const ht=h.toLowerCase();return`${of(Ae)} ${Ae.name} ${Ae.role} ${Ae.title??""}`.toLowerCase().includes(ht)}).map(Ae=>i.jsx("div",{className:q("flex min-w-0 items-center gap-1 w-full rounded hover:bg-accent/50",Ae.id===e.assigneeAgentId&&"bg-accent"),children:i.jsx("button",{type:"button",className:"flex min-w-0 flex-1 items-center gap-2 px-2 py-2 text-left text-xs",onClick:()=>{if(Ae.id===e.assigneeAgentId){m(!1);return}Kk(Ae.id),t({assigneeAgentId:Ae.id,assigneeUserId:null,assigneeAgentRuntimeOverrides:null}),m(!1)},children:i.jsx(yh,{agent:Ae})})},Ae.id))]})]}),gt=rt?i.jsx(Ro,{kind:"agent",label:rt.name,agentAvatarStyle:"bare",agentIcon:rt.icon,agentRole:rt.role,className:"w-full"}):Se?i.jsx(Ro,{kind:"user",label:Se,avatarUrl:se(e.reviewerUserId)}):i.jsx(Ro,{kind:"unassigned",label:"No reviewer",muted:!0}),Ke=i.jsxs(i.Fragment,{children:[i.jsx("input",{className:"w-full px-2 py-1.5 text-xs bg-transparent outline-none border-b border-border mb-1 placeholder:text-muted-foreground/50",placeholder:"Search reviewers...",value:y,onChange:Ae=>w(Ae.target.value),autoFocus:!n}),i.jsxs("div",{ref:R,"data-testid":"issue-properties-reviewer-scroll",className:"scrollbar-auto-hide max-h-60 overflow-y-auto overscroll-contain",children:[i.jsx("button",{className:q("flex min-w-0 items-center gap-2 w-full px-2 py-1.5 text-left text-xs rounded hover:bg-accent/50",!e.reviewerAgentId&&!e.reviewerUserId&&"bg-accent"),onClick:()=>{t({reviewerAgentId:null,reviewerUserId:null}),b(!1)},children:i.jsx(Ro,{kind:"unassigned",label:"No reviewer"})}),X&&i.jsx("button",{className:q("flex min-w-0 items-center gap-2 w-full px-2 py-2 text-left text-xs rounded hover:bg-accent/50",e.reviewerUserId===X&&"bg-accent"),onClick:()=>{t({reviewerAgentId:null,reviewerUserId:X}),b(!1)},children:i.jsx(ufe,{avatarUrl:ee})}),ge.filter(Ae=>{if(!y.trim())return!0;const ht=y.toLowerCase();return`${of(Ae)} ${Ae.name} ${Ae.role} ${Ae.title??""}`.toLowerCase().includes(ht)}).map(Ae=>i.jsx("button",{className:q("flex min-w-0 items-center gap-2 w-full px-2 py-2 text-left text-xs rounded hover:bg-accent/50",Ae.id===e.reviewerAgentId&&"bg-accent"),onClick:()=>{Kk(Ae.id),t({reviewerAgentId:Ae.id,reviewerUserId:null}),b(!1)},children:i.jsx(yh,{agent:Ae})},Ae.id))]})]}),Je=e.projectId?i.jsxs(i.Fragment,{children:[i.jsx(Fo,{color:(Wt=re.find(Ae=>Ae.id===e.projectId))==null?void 0:Wt.color,icon:(Jt=re.find(Ae=>Ae.id===e.projectId))==null?void 0:Jt.icon,size:"xs"}),i.jsx("span",{className:"text-sm truncate",children:Ie(e.projectId)}),i.jsx(rs,{className:"h-3 w-3 shrink-0 text-muted-foreground/70","aria-hidden":"true"})]}):i.jsxs(i.Fragment,{children:[i.jsx(d6,{className:"h-3.5 w-3.5 text-muted-foreground"}),i.jsx("span",{className:"text-sm text-muted-foreground",children:"No project"}),i.jsx(rs,{className:"h-3 w-3 shrink-0 text-muted-foreground/70","aria-hidden":"true"})]}),wt=i.jsxs(i.Fragment,{children:[i.jsx("input",{className:"w-full px-2 py-1.5 text-xs bg-transparent outline-none border-b border-border mb-1 placeholder:text-muted-foreground/50",placeholder:"Search projects...",value:j,onChange:Ae=>C(Ae.target.value),autoFocus:!n}),i.jsxs("div",{className:"max-h-48 overflow-y-auto overscroll-contain",children:[i.jsx("button",{className:q("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 whitespace-nowrap",!e.projectId&&"bg-accent"),onClick:()=>{t({projectId:null,projectWorkspaceId:null,executionWorkspaceId:null}),S(!1)},children:"No project"}),re.filter(Ae=>{if(!j.trim())return!0;const ht=j.toLowerCase();return Ae.name.toLowerCase().includes(ht)}).map(Ae=>i.jsxs("button",{className:q("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 whitespace-nowrap",Ae.id===e.projectId&&"bg-accent"),onClick:()=>{t({projectId:Ae.id,projectWorkspaceId:SBn(Ae),executionWorkspaceId:null}),S(!1)},children:[i.jsx(Fo,{color:Ae.color,icon:Ae.icon,size:"xs"}),Ae.name]},Ae.id))]})]}),Z=qe?i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"max-w-20 shrink truncate font-mono text-[11px] text-muted-foreground",children:Oe(qe)}),i.jsx("span",{className:"min-w-0 truncate text-sm",children:qe.title})]}):i.jsxs(i.Fragment,{children:[i.jsx(kk,{className:"h-3.5 w-3.5 text-muted-foreground"}),i.jsx("span",{className:"text-sm text-muted-foreground",children:"No parent"})]}),Me=i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-center gap-1.5 border-b border-border px-2 py-1.5",children:[i.jsx(Al,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("input",{className:"min-w-0 flex-1 bg-transparent text-xs outline-none placeholder:text-muted-foreground/50",placeholder:"Search issues...",value:M,onChange:Ae=>E(Ae.target.value),autoFocus:!n})]}),i.jsxs("div",{className:"max-h-60 overflow-y-auto overscroll-contain p-1",children:[i.jsxs("button",{type:"button",className:q("flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs hover:bg-accent/50",!e.parentId&&"bg-accent"),onClick:()=>{t({parentId:null}),N(!1),E("")},children:[i.jsx(kk,{className:"h-3.5 w-3.5 text-muted-foreground"}),"No parent"]}),Ce.length>0?Ce.map(Ae=>{const ht=ce(Ae);return i.jsxs("button",{type:"button",className:q("grid w-full grid-cols-[auto_minmax(0,1fr)] items-center gap-x-2 rounded px-2 py-1.5 text-left text-xs hover:bg-accent/50",Ae.id===e.parentId&&"bg-accent"),onClick:()=>{t({parentId:Ae.id}),N(!1),E("")},children:[i.jsx("span",{className:"font-mono text-[11px] text-muted-foreground",children:Oe(Ae)}),i.jsx("span",{className:"min-w-0 truncate",children:Ae.title}),ht&&Ae.projectId!==e.projectId?i.jsx("span",{className:"col-start-2 min-w-0 truncate text-[11px] text-muted-foreground",children:ht}):null]},Ae.id)}):i.jsx("p",{className:"px-2 py-2 text-xs text-muted-foreground",children:"No matching issues."})]})]}),lt=T?i.jsxs("div",{className:q("shrink-0 rounded-md border border-border bg-popover p-1",n?"w-full":void 0),style:n?void 0:{width:"480px",maxWidth:"calc(100vw - 2rem)"},children:[i.jsxs("div",{className:"flex items-center gap-1.5 border-b border-border px-2 py-1.5",children:[i.jsx(Al,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("input",{className:"min-w-0 flex-1 bg-transparent text-xs outline-none placeholder:text-muted-foreground/50",placeholder:"Search existing issues...",value:B,onChange:Ae=>F(Ae.target.value),autoFocus:!n})]}),i.jsx("div",{className:"max-h-56 overflow-y-auto overscroll-contain py-1",children:ue.length>0?ue.map(Ae=>{const ht=ce(Ae),Lt=Ae.parentId?$e.get(Ae.parentId)??null:null;return i.jsxs("button",{type:"button",className:"grid w-full grid-cols-[auto_minmax(0,1fr)] items-center gap-x-2 rounded px-2 py-1.5 text-left text-xs hover:bg-accent/50 disabled:cursor-wait disabled:opacity-60",onClick:()=>ke.mutate(Ae),disabled:ke.isPending,children:[i.jsx("span",{className:"font-mono text-[11px] text-muted-foreground",children:Oe(Ae)}),i.jsx("span",{className:"min-w-0 truncate",children:Ae.title}),i.jsx("span",{className:"col-start-2 min-w-0 truncate text-[11px] text-muted-foreground",children:Lt?`Move from ${Oe(Lt)}`:ht&&Ae.projectId!==e.projectId?ht:"No parent"})]},Ae.id)}):i.jsx("p",{className:"px-2 py-2 text-xs text-muted-foreground",children:"No matching issues."})})]}):null;return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"space-y-1",children:[i.jsx(xm,{label:"Status",children:i.jsx(ki,{status:e.status,onChange:Ae=>t({status:Ae}),showLabel:!0})}),i.jsx(xm,{label:"Priority",children:i.jsx(Dc,{priority:e.priority,onChange:Ae=>t({priority:Ae}),showLabel:!0})}),i.jsx(IO,{inline:n,label:"Labels",open:W,onOpenChange:Ae=>{Y(Ae),Ae||V("")},triggerContent:Te,triggerClassName:"min-w-0 max-w-full",popoverClassName:"w-64",children:ze}),i.jsx(IO,{inline:n,label:"Assignee",open:f,onOpenChange:Ae=>{m(Ae),Ae||p("")},triggerContent:De,triggerClassName:"min-w-0 max-w-full flex-1 justify-start overflow-hidden",popoverClassName:"w-[19rem]",popoverAlign:"start",rowAlign:"start",extra:Le&&u&&pve(Le)?i.jsx(uY,{agent:Le,orgId:u,overrides:e.assigneeAgentRuntimeOverrides,variant:"icon",onApply:Ae=>t({assigneeAgentRuntimeOverrides:Ae})}):null,children:kt}),i.jsx(IO,{inline:n,label:"Reviewer",open:x,onOpenChange:Ae=>{b(Ae),Ae||w("")},triggerContent:gt,triggerClassName:"min-w-0 max-w-full flex-1 justify-start overflow-hidden",popoverClassName:"w-[19rem]",popoverAlign:"start",rowAlign:"start",children:Ke}),i.jsx(IO,{inline:n,label:"Project",open:k,onOpenChange:Ae=>{S(Ae),Ae||C("")},triggerContent:Je,triggerAriaLabel:`Change project: ${e.projectId?Ie(e.projectId):"No project"}`,triggerClassName:"min-w-0 max-w-full",popoverClassName:"w-fit min-w-[11rem]",extra:e.projectId?i.jsx(gn,{to:mt(e.projectId),"aria-label":"Open project",className:"inline-flex items-center justify-center h-5 w-5 rounded hover:bg-accent/50 transition-colors text-muted-foreground hover:text-foreground",onClick:Ae=>Ae.stopPropagation(),children:i.jsx(Jy,{className:"h-3 w-3"})}):void 0,children:wt}),i.jsx(IO,{inline:n,label:"Parent issue",open:I,onOpenChange:Ae=>{N(Ae),Ae||E("")},triggerContent:Z,triggerClassName:"min-w-0 max-w-full",popoverClassName:"w-72",extra:qe?i.jsx(gn,{to:dN(qe),"aria-label":"Open parent issue",className:"inline-flex h-5 w-5 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",onClick:Ae=>Ae.stopPropagation(),children:i.jsx(Jy,{className:"h-3 w-3"})}):void 0,children:Me}),r?i.jsxs("div",{className:"py-1.5",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("span",{className:"w-20 shrink-0 text-xs text-muted-foreground",children:"Sub-issues"}),i.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[i.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-center gap-1.5 rounded px-1 py-0.5 text-left transition-colors hover:bg-accent/50 disabled:pointer-events-none",onClick:()=>$(Ae=>!Ae),"aria-label":"Show sub-issue picker",children:[i.jsx(kk,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"rounded-sm border border-border px-1.5 py-0.5 text-[11px] leading-none text-muted-foreground",children:r.length})]}),i.jsxs(bi,{open:_,onOpenChange:z,children:[i.jsx(Hi,{asChild:!0,children:i.jsxs("button",{type:"button",className:"ml-auto inline-flex h-6 items-center gap-1 rounded border border-border px-1.5 text-[11px] text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:[i.jsx(ps,{className:"h-3 w-3"}),"Add"]})}),i.jsxs(yi,{className:"w-44 p-1",align:"end",collisionPadding:16,children:[i.jsx("button",{type:"button",className:"w-full rounded px-2 py-1.5 text-left text-xs hover:bg-accent/50",onClick:ot,children:"Create new sub-issue"}),i.jsx("button",{type:"button",className:"w-full rounded px-2 py-1.5 text-left text-xs hover:bg-accent/50",onClick:()=>{z(!1),$(!0)},children:"Add existing issue"})]})]})]})]}),i.jsxs("div",{className:"mt-1.5 min-w-0 space-y-1",children:[lt?i.jsx("div",{className:q(n?void 0:"flex justify-end"),children:lt}):null,i.jsxs("div",{className:q("min-w-0 space-y-1",n?"ml-0":"ml-[5.75rem]"),children:[be.length===0?i.jsx("button",{type:"button",className:"w-full rounded px-1 py-1 text-left text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",onClick:ot,children:"No sub-issues."}):be.map(Ae=>{const ht=Ae.identifier??Ae.id,Lt=Ae.identifier??Ae.id.slice(0,8);return i.jsxs(gn,{to:`/issues/${ht}`,className:"grid max-w-full min-w-0 grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-1.5 overflow-hidden rounded px-1 py-1 text-xs transition-colors hover:bg-accent/50",title:Ae.title,children:[i.jsx(ki,{status:Ae.status}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:Ae.title}),i.jsx("span",{className:"min-w-0 max-w-[5.5rem] truncate font-mono text-[11px] text-muted-foreground",children:Lt})]},Ae.id)}),r.length>be.length?i.jsxs("p",{className:"px-1 text-[11px] text-muted-foreground",children:["+",r.length-be.length," more"]}):null]})]})]}):null,e.requestDepth>0&&i.jsx(xm,{label:"Depth",children:i.jsx("span",{className:"text-sm font-mono",children:e.requestDepth})})]}),s?i.jsxs(i.Fragment,{children:[a?i.jsx(g1,{}):null,i.jsxs("div",{className:"space-y-1",children:[(e.createdByAgentId||e.createdByUserId)&&i.jsx(xm,{label:"Created by",children:e.createdByAgentId?i.jsx(gn,{to:`/agents/${e.createdByAgentId}`,className:"hover:underline",children:i.jsx(zl,{name:he(e.createdByAgentId)??e.createdByAgentId.slice(0,8),icon:e.createdByAgentId?(Ze=_e.get(e.createdByAgentId))==null?void 0:Ze.icon:null,role:e.createdByAgentId?(Mt=_e.get(e.createdByAgentId))==null?void 0:Mt.role:null,size:"sm"})}):i.jsx(Ro,{kind:"user",label:We??"User",avatarUrl:se(e.createdByUserId)})}),e.startedAt&&i.jsx(xm,{label:"Started",children:i.jsx("span",{className:"text-sm",children:Pm(e.startedAt)})}),e.completedAt&&i.jsx(xm,{label:"Completed",children:i.jsx("span",{className:"text-sm",children:Pm(e.completedAt)})}),i.jsx(xm,{label:"Created",children:i.jsx("span",{className:"text-sm",children:So(e.createdAt)})}),i.jsx(xm,{label:"Updated",children:i.jsx("span",{className:"text-sm",children:Uf(e.updatedAt)})})]})]}):null]})}const Jse={activeViewInstanceId:null,tabOrder:[],tabsByViewInstanceId:{},runtimesById:{},promotionsById:{}},kht=A.createContext(null);function Oht(){var e,t;return((t=(e=globalThis.crypto)==null?void 0:e.randomUUID)==null?void 0:t.call(e))??`view-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function jBn(e,t){if(e.kind!=="automation"&&e.kind!=="browser"&&e.kind!=="library_directory"&&e.kind!=="library_document"&&e.kind!=="library_entry"&&e.kind!=="library_file"&&e.kind!=="local_app")return null;const n=t??e.viewInstanceId??(e.kind==="browser"?e.tabId:Oht());return{...e,viewInstanceId:n}}function Sht(e,t){return JSON.stringify([e,t.kind,t.viewInstanceId])}function CBn({children:e,createId:t=Oht,initialState:n}){const[r,s]=A.useState(()=>n??AXt()),a=A.useRef(r);a.current=r;const o=A.useCallback(u=>{const f=$Xt(a.current,u);return a.current=f,s(f),f},[]),l=A.useCallback(()=>a.current,[]),c=A.useCallback((u,f,m)=>{o({type:"tab/unbind-saved-view",organizationId:u,viewInstanceId:f,savedViewId:m})},[o]),d=A.useMemo(()=>({createId:t,dispatch:o,getState:l,state:r,unbindSavedViewForOrganization:c}),[t,o,l,r,c]);return i.jsx(kht.Provider,{value:d,children:e})}function xve(){const e=A.useContext(kht);if(!e)throw new Error("useMainWorkbench must be used inside MainWorkbenchProvider");return e}function fY(e){const{createId:t,dispatch:n,getState:r,state:s}=xve(),a=Ege(),o=(e==null?void 0:e.trim())??"",l=o?s.organizations[o]??Jse:Jse,c=A.useCallback(()=>(o?r().organizations[o]:null)??Jse,[r,o]),d=A.useCallback(()=>{const I=r();if(!a)return hXt(I,o);const N=I.organizations[o],M=Object.values((N==null?void 0:N.runtimesById)??{}).filter(E=>E.targetKind==="browser"&&E.host.kind!=="crashed"&&E.host.kind!=="disposed"&&!a.hasSurface(E.id)).length;return a.getLiveBrowserCount(o)+M},[r,a,o]),u=A.useCallback(I=>{var _;return o?I.target.kind==="browser"&&!(a!=null&&a.hasSurface(I.runtimeId))&&d()>=xw?{admitted:!1,reason:"browser_capacity",viewInstanceId:null}:!!((_=n({type:"session-tab/create",organizationId:o,tab:I}).organizations[o])!=null&&_.tabsByViewInstanceId[I.viewInstanceId])?{admitted:!0,reason:null,viewInstanceId:I.viewInstanceId}:{admitted:!1,reason:"rejected",viewInstanceId:null}:{admitted:!1,reason:"rejected",viewInstanceId:null}},[n,d,a,o]),f=A.useCallback(I=>{const N=jBn(I??{...j6(),tabId:t()},(I==null?void 0:I.viewInstanceId)??(I==null?void 0:I.tabId)??t());return!N||N.kind!=="browser"||!o?{admitted:!1,reason:"rejected",viewInstanceId:null}:u({viewInstanceId:N.viewInstanceId,runtimeId:Sht(o,N),target:N,originContextKey:"messenger:workbench"})},[t,u,o]),m=A.useCallback((I,N)=>{var z;return!o||!I?{admitted:!1,reason:"rejected",viewInstanceId:null}:N.target.kind==="browser"&&!(a!=null&&a.hasSurface(N.runtimeId))&&d()>=xw?{admitted:!1,reason:"browser_capacity",viewInstanceId:null}:!!((z=n({type:"saved-tab/open",organizationId:o,savedViewId:I,tab:N}).organizations[o])!=null&&z.tabsByViewInstanceId[N.viewInstanceId])?{admitted:!0,reason:null,viewInstanceId:N.viewInstanceId}:{admitted:!1,reason:"rejected",viewInstanceId:null}},[n,d,a,o]),h=A.useCallback(I=>{o&&n({type:"tab/focus",organizationId:o,viewInstanceId:I})},[n,o]),p=A.useCallback((I,N)=>{o&&n({type:"tab/reorder",organizationId:o,viewInstanceId:I,toIndex:N})},[n,o]),x=A.useCallback(I=>{o&&n({type:"tab/close",organizationId:o,viewInstanceId:I})},[n,o]),b=A.useCallback((I,N)=>{o&&n({type:"tab/bind-saved-view",organizationId:o,viewInstanceId:I,savedViewId:N})},[n,o]),y=A.useCallback((I,N)=>{o&&n({type:"tab/unbind-saved-view",organizationId:o,viewInstanceId:I,savedViewId:N})},[n,o]),w=A.useCallback((I,N,M)=>{o&&(n({type:"runtime/update-target",organizationId:o,runtimeId:I,viewInstanceId:N,target:M}),n({type:"tab/update-target",organizationId:o,runtimeId:I,viewInstanceId:N,target:M}))},[n,o]),k=A.useCallback(I=>{o&&n({type:"runtime/admit",organizationId:o,runtime:I})},[n,o]),S=A.useCallback((I,N)=>{o&&n({type:"runtime/set-host",organizationId:o,runtimeId:I,host:N})},[n,o]),j=l.tabOrder.flatMap(I=>{const N=l.tabsByViewInstanceId[I];return N?[N]:[]}),C=l.activeViewInstanceId?l.tabsByViewInstanceId[l.activeViewInstanceId]??null:null;return A.useMemo(()=>({activeTab:C,activeViewInstanceId:l.activeViewInstanceId,admitRuntime:k,bindSavedView:b,canCreateBrowser:d()<xw,closeTab:x,createSessionBrowser:f,createSessionTab:u,dispatch:n,focusTab:h,getState:c,liveBrowserCount:d,openSavedTab:m,promotionsById:l.promotionsById,reorderTab:p,runtimesById:l.runtimesById,setRuntimeHost:S,tabOrder:l.tabOrder,tabs:j,tabsByViewInstanceId:l.tabsByViewInstanceId,unbindSavedView:y,updateTarget:w}),[C,k,b,x,f,u,n,h,c,o,m,l.activeViewInstanceId,l.promotionsById,l.runtimesById,l.tabOrder,l.tabsByViewInstanceId,p,S,s,j,y,w])}const jht=A.createContext(null);function NBn(e){var t,n;return((n=(t=globalThis.crypto)==null?void 0:t.randomUUID)==null?void 0:n.call(t))??`${e}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function ame(e){if(!jm(e)||e.kind!=="automation"&&e.kind!=="browser"&&e.kind!=="library_directory"&&e.kind!=="library_document"&&e.kind!=="library_entry"&&e.kind!=="library_file"&&e.kind!=="local_app")return null;const t=e.viewInstanceId??(e.kind==="browser"?e.tabId:null);return t?{...e,viewInstanceId:t}:null}function eP(e,t,n){const r=ame(n);return r?JSON.stringify([e,t,r.kind,r.viewInstanceId]):""}function eie(e,t){return JSON.stringify([e.trim(),t])}function IBn(e,t,n){const{group:r,savedView:s}=n;e.setQueryData(U.messenger.savedView(t,s.id),s);const a=U.messenger.customGroups(t);e.getQueryData(a)!==void 0&&e.setQueryData(a,o=>{const l=`saved-view:${s.id}`,c=(o==null?void 0:o.groups)??[];if(!r)return{groups:c.map(m=>({...m,entries:m.entries.filter(h=>h.item.type!=="saved_view"||h.item.savedView.id!==s.id)}))};const d=s.updatedAt??new Date,u={id:`optimistic:${l}`,orgId:s.orgId,userId:s.userId,groupId:r.id,itemKey:l,sortOrder:0,createdAt:s.createdAt??d,updatedAt:d,item:{type:"saved_view",itemKey:l,title:s.title,savedView:s}};return c.find(m=>m.id===r.id)?{groups:c.map(m=>{if(m.id!==r.id)return{...m,entries:m.entries.filter(p=>p.item.type!=="saved_view"||p.item.savedView.id!==s.id)};const h=m.entries.filter(p=>p.item.type!=="saved_view"||p.item.savedView.id!==s.id);return{...m,entries:[...h,{...u,sortOrder:h.length}]}})}:{groups:[...c.map(m=>({...m,entries:m.entries.filter(h=>h.item.type!=="saved_view"||h.item.savedView.id!==s.id)})),{id:r.id,orgId:s.orgId,userId:s.userId,name:r.name,icon:null,sortOrder:c.length,collapsed:!1,pinnedAt:null,createdAt:d,updatedAt:d,entries:[u]}]}})}function PBn(e){return e instanceof Error?e.message:"Could not move this view."}class TBn extends Error{constructor(){super("Keeping this view timed out. Retry to check whether it was saved."),this.name="PersistenceTimeoutError"}}function _Bn(e,t){return new Promise((n,r)=>{const s=globalThis.setTimeout(()=>r(new TBn),t);e.then(a=>{globalThis.clearTimeout(s),n(a)},a=>{globalThis.clearTimeout(s),r(a)})})}function MBn({children:e,claimTimeoutMs:t=5e3,persistenceTimeoutMs:n=15e3}){const r=Kr(),s=Ir(),a=er(),o=Qm(),l=xve(),c=mWe(),d=yR(),u=A.useRef(new Set),f=A.useRef(new Map),m=A.useRef(new Map),h=A.useRef(c==null?void 0:c.selectedOrganizationId);h.current=c==null?void 0:c.selectedOrganizationId;const[p,x]=A.useState(0),b=A.useCallback(()=>x(T=>T+1),[]),y=A.useCallback(T=>{d.setInteractionLocked(T.runtimeId,!1),u.current.delete(T.key),b()},[d,b]),w=A.useCallback(async(T,$)=>{var R,D;const B=T.request.organizationId.trim();if(h.current!==void 0&&h.current!==B)throw d.claimSurface(T.runtimeId,T.sideOwnerId),l.dispatch({type:"promotion/claim-fail",organizationId:B,promotionId:T.promotionId,savedViewId:$.savedView.id,expectedSourceRevision:T.sourceRevision,error:"organization_changed"}),y(T),new Error("Saved in Messenger. Return to the original organization to retry the move.");const F=()=>{var ee;if(!m.current.has(eie(B,$.savedView.id)))return!1;d.claimSurface(T.runtimeId,T.sideOwnerId);const X=(ee=l.getState().organizations[B])==null?void 0:ee.promotionsById[T.promotionId];return(X==null?void 0:X.status)==="claiming"?l.dispatch({type:"promotion/claim-fail",organizationId:B,promotionId:T.promotionId,savedViewId:$.savedView.id,expectedSourceRevision:T.sourceRevision,error:"saved_view_removal_pending"}):(X==null?void 0:X.status)==="detaching"&&l.dispatch({type:"promotion/detach-fail",organizationId:B,promotionId:T.promotionId,savedViewId:$.savedView.id,expectedSourceRevision:T.sourceRevision,error:"saved_view_removal_pending"}),y(T),!0};if(F())throw new Error("Saved View removal interrupted this move.");if(o.holdDisplayedContext(B,T.request.contextKey),((D=(R=l.dispatch({type:"promotion/claim",organizationId:B,promotionId:T.promotionId,savedViewId:$.savedView.id,expectedSourceRevision:T.sourceRevision}).organizations[B])==null?void 0:R.promotionsById[T.promotionId])==null?void 0:D.status)!=="detaching")throw y(T),new Error("The Saved View was kept, but Main could not stage it.");r(tC($.savedView.id));const Y=await d.waitForOwner(T.runtimeId,T.mainOwnerId,t);if(F())throw new Error("Saved View removal interrupted this move.");if(!(Y&&d.claimSurface(T.runtimeId,T.mainOwnerId)))throw d.claimSurface(T.runtimeId,T.sideOwnerId),l.dispatch({type:"promotion/detach-fail",organizationId:B,promotionId:T.promotionId,savedViewId:$.savedView.id,expectedSourceRevision:T.sourceRevision,error:"main_anchor_claim_failed"}),y(T),new Error("Saved in Messenger, but Main is not ready. Retry the move.");if(F())throw new Error("Saved View removal interrupted this move.");const V=o.detachTargetForContext(T.request.contextKey,T.exactKey,T.sourceRevision);if(!V.detached)throw d.claimSurface(T.runtimeId,T.sideOwnerId),l.dispatch({type:"promotion/detach-fail",organizationId:B,promotionId:T.promotionId,savedViewId:$.savedView.id,expectedSourceRevision:T.sourceRevision,error:V.reason}),y(T),new Error("Saved in Messenger, but the Side Panel changed. Retry the move.");l.dispatch({type:"promotion/detach-succeed",organizationId:B,promotionId:T.promotionId,savedViewId:$.savedView.id,expectedSourceRevision:T.sourceRevision});const L=d.getRuntimeTarget(T.runtimeId);return L&&L.kind===T.target.kind&&L.viewInstanceId===T.target.viewInstanceId&&(l.dispatch({type:"runtime/update-target",organizationId:B,runtimeId:T.runtimeId,viewInstanceId:T.target.viewInstanceId,target:L}),l.dispatch({type:"tab/update-target",organizationId:B,runtimeId:T.runtimeId,viewInstanceId:T.target.viewInstanceId,target:L})),f.current.delete(T.key),y(T),$},[t,d,r,o,y,l]),k=A.useCallback((T,$,B)=>{const F=eie(T,$),W=m.current.get(F);if(B){m.current.set(F,{pendingCount:((W==null?void 0:W.pendingCount)??0)+1,removed:(W==null?void 0:W.removed)??!1});return}if(W!=null&&W.removed)return;const Y=Math.max(0,((W==null?void 0:W.pendingCount)??0)-1);Y===0?m.current.delete(F):m.current.set(F,{pendingCount:Y,removed:!1})},[]),S=A.useCallback((T,$)=>{var F,W;const B=T.trim();m.current.set(eie(B,$),{pendingCount:0,removed:!0});for(const Y of Array.from(f.current.values())){if(Y.request.organizationId.trim()!==B)continue;const G=(F=l.getState().organizations[B])==null?void 0:F.promotionsById[Y.promotionId];(((W=Y.result)==null?void 0:W.savedView.id)??(G&&"savedViewId"in G?G.savedViewId:G==null?void 0:G.source.savedViewId))!==$||!G||(d.claimSurface(Y.runtimeId,Y.sideOwnerId),l.dispatch({type:"promotion/cancel-saved-view",organizationId:B,promotionId:Y.promotionId,savedViewId:$,expectedSourceRevision:G.source.sourceRevision}),f.current.delete(Y.key),y(Y))}},[d,y,l]),j=A.useCallback(async T=>{const $=T.request.organizationId.trim();let B;try{B=T.request.existingResult??await _Bn(_s.keepSavedView($,T.request.input),n)}catch(F){throw l.dispatch({type:F instanceof $o?"promotion/server-fail":"promotion/timeout",organizationId:$,promotionId:T.promotionId,expectedSourceRevision:T.sourceRevision,error:PBn(F)}),y(T),F}return T.result=B,IBn(a,$,B),l.dispatch({type:"promotion/server-commit",organizationId:$,promotionId:T.promotionId,savedViewId:B.savedView.id,expectedSourceRevision:T.sourceRevision}),a.invalidateQueries({queryKey:U.messenger.customGroups($)}).catch(()=>{}),w(T,B)},[w,n,a,y,l]),C=A.useCallback(async T=>{var ne,le,ie,re;const $=T.organizationId.trim(),B=ame(T.target);if(!$||!B)throw new Error("This Side Panel view cannot move to Messenger.");const F=fs(T.target),W=o.getTargetRevisionForContext(T.contextKey,F);if(W===null)throw new Error("This Side Panel view is no longer available.");const Y=uM($,B),G=ame(d.getRuntimeTarget(Y)??T.target),V=G&&G.kind===B.kind&&G.viewInstanceId===B.viewInstanceId?G:B,L=iX(V,{clientMutationId:T.input.clientMutationId,placement:T.input.placement})??T.input,R={...T,input:L,target:V},D=eP($,T.contextKey,T.target);if(!D||u.current.has(D))throw new Error("This view is already moving.");if(Array.from(f.current.values()).some(de=>de.runtimeId===Y)||Object.values(((ne=l.getState().organizations[$])==null?void 0:ne.promotionsById)??{}).some(de=>de.source.runtimeId===Y))throw new Error("This runtime is already moving.");if(f.current.has(D))throw new Error("This move has a retained attempt. Use Retry move.");const ee={exactKey:F,key:D,mainOwnerId:`main:${$}:${V.viewInstanceId}`,promotionId:NBn("promotion"),request:R,result:T.existingResult??null,runtimeId:Y,sideOwnerId:`side:${T.contextKey}:${Y}`,sourceRevision:W,target:V};if(f.current.set(D,ee),u.current.add(D),b(),d.setInteractionLocked(Y,!0),l.dispatch({type:"runtime/admit",organizationId:$,runtime:{id:Y,viewInstanceId:V.viewInstanceId,targetKind:V.kind,target:V,host:{kind:"side",contextKey:T.contextKey}}}),((re=(ie=l.dispatch({type:"promotion/start",organizationId:$,promotionId:ee.promotionId,clientMutationId:T.input.clientMutationId,source:{viewInstanceId:V.viewInstanceId,savedViewId:((le=T.existingResult)==null?void 0:le.savedView.id)??null,sourceRevision:W,target:V,originContextKey:T.contextKey,runtimeId:Y}}).organizations[$])==null?void 0:ie.promotionsById[ee.promotionId])==null?void 0:re.status)!=="pending")throw f.current.delete(D),y(ee),new Error("This view could not enter the move transaction.");return j(ee)},[d,j,o,b,y,l]),I=A.useCallback(T=>{var Y,G,V;const $=T.request.organizationId.trim(),B=(Y=l.getState().organizations[$])==null?void 0:Y.promotionsById[T.promotionId];if(!B||B.status!=="server_failed"&&B.status!=="commit_unknown"&&B.status!=="claim_failed")return!1;const F=((G=T.result)==null?void 0:G.savedView.id)??B.source.savedViewId;return F&&s.pathname.endsWith(tC(F))&&r("/messenger/workbench",{replace:!0}),(V=l.dispatch({type:"promotion/discard",organizationId:$,promotionId:T.promotionId,expectedSourceRevision:B.source.sourceRevision}).organizations[$])!=null&&V.promotionsById[T.promotionId]?!1:(f.current.delete(T.key),y(T),!0)},[s.pathname,r,y,l]),N=A.useCallback((T,$,B)=>{const F=f.current.get(eP(T,$,B));return F?I(F):!1},[I]);A.useEffect(()=>o.registerBrowserResetHandler((T,$)=>{var G;const B={...$,viewInstanceId:$.viewInstanceId??$.tabId},F=Array.from(f.current.values()).find(V=>V.request.contextKey===T&&V.runtimeId===uM(V.request.organizationId.trim(),B));if(!F)return"remove";const W=(G=l.getState().organizations[F.request.organizationId.trim()])==null?void 0:G.promotionsById[F.promotionId];return((W==null?void 0:W.status)==="server_failed"||(W==null?void 0:W.status)==="commit_unknown"||(W==null?void 0:W.status)==="claim_failed")&&I(F)?"remove":"preserve"}),[I,o,l]);const M=A.useCallback(async(T,$,B)=>{var se,ne,le;const F=T.trim(),W=eP(F,$,B),Y=f.current.get(W);if(!W||!Y)throw new Error("There is no retained move to retry.");if(u.current.has(W))throw new Error("This view is already moving.");const G=(se=l.getState().organizations[F])==null?void 0:se.promotionsById[Y.promotionId];if(!G||G.status!=="server_failed"&&G.status!=="commit_unknown"&&G.status!=="claim_failed")throw new Error("This move is not ready to retry.");if(o.getTargetRevisionForContext($,Y.exactKey)!==Y.sourceRevision)throw I(Y),new Error("The Side Panel view changed. Start a new move.");const L=o.replaceTargetForContext($,Y.exactKey,{...B}),R=o.getTargetRevisionForContext($,Y.exactKey);if(!L||R===null||R<=Y.sourceRevision)throw new Error("This Side Panel view could not enter retry.");const D=G.status==="server_failed"?"promotion/retry":G.status==="commit_unknown"?"promotion/reconcile":"promotion/claim-retry",X=l.dispatch({type:D,organizationId:F,promotionId:Y.promotionId,expectedSourceRevision:Y.sourceRevision,nextSourceRevision:R}),ee=D==="promotion/reconcile"?"reconciling":D==="promotion/claim-retry"?"claiming":"pending";if(((le=(ne=X.organizations[F])==null?void 0:ne.promotionsById[Y.promotionId])==null?void 0:le.status)!==ee)throw new Error("This move could not enter retry.");if(Y.sourceRevision=R,Y.request={...Y.request,target:{...B}},u.current.add(W),b(),d.setInteractionLocked(Y.runtimeId,!0),D==="promotion/claim-retry"){if(!Y.result)throw y(Y),new Error("The retained Saved View could not be recovered.");return w(Y,Y.result)}return j(Y)},[w,I,d,j,o,b,y,l]),E=A.useCallback((T,$,B)=>u.current.has(eP(T,$,B)),[]),_=A.useCallback((T,$,B)=>{var Y;const F=f.current.get(eP(T,$,B));if(!F)return{clientMutationId:null,error:null,promotionId:null,retryable:!1,status:"idle"};const W=(Y=l.state.organizations[T])==null?void 0:Y.promotionsById[F.promotionId];return W?{clientMutationId:W.clientMutationId,error:"error"in W?W.error:null,promotionId:W.id,retryable:W.status==="server_failed"||W.status==="commit_unknown"||W.status==="claim_failed",status:W.status}:{clientMutationId:F.request.input.clientMutationId,error:null,promotionId:F.promotionId,retryable:!1,status:"idle"}},[l.state]),z=A.useMemo(()=>({discard:N,finalizeSavedViewRemoval:S,getMoveState:_,isMoving:E,promote:C,retry:M,setSavedViewRemovalPending:k}),[N,S,_,E,C,M,p,k]);return i.jsx(jht.Provider,{value:z,children:e})}function bve(){return A.useContext(jht)}function EBn(){var e,t;return((t=(e=globalThis.crypto)==null?void 0:e.randomUUID)==null?void 0:t.call(e))??`00000000-0000-4000-8000-${Math.random().toString(16).slice(2,14).padEnd(12,"0")}`}const DBn=32,RBn="00000000-0000-4000-8000-000000000000",W_e="__messenger_sidebar__";function ome(e){return Array.isArray(e)?`[${e.map(ome).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,n])=>n!==void 0).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${ome(r)}`).join(",")}}`:JSON.stringify(e)}function LBn(e){const{clientMutationId:t,...n}=e;return ome(n)}function zBn(e,t){const n=e.get(t);if(n)return e.delete(t),e.set(t,n),n;const r=EBn();for(e.set(t,r);e.size>DBn;){const s=e.keys().next().value;if(s===void 0)break;e.delete(s)}return r}function $Bn(e,t,n){e.get(t)===n&&e.delete(t)}function FBn(e,t){for(const[n,r]of e)r===t&&e.delete(n)}function BBn({contextKey:e,organizationId:t,target:n}){var j;const{pushToast:r}=ws(),s=bve(),a=er(),o=A.useRef(new Map),l=!!(n&&jm(n)&&(n.kind!=="library_entry"||n.path)),c=e.startsWith("issue:")&&e.slice(6).trim()||null,d=e.startsWith("chat:")||!!c,u=Ve({queryKey:U.issues.detail(c??"__none__"),queryFn:()=>fr.get(c),enabled:l&&!!c}),f=Ve({queryKey:U.messenger.customGroups(t??"__none__"),queryFn:()=>_s.listCustomGroups(t),enabled:l&&!!t}),m=((j=f.data)==null?void 0:j.groups)??[],h=n&&jm(n)?n.kind==="browser"?n.viewInstanceId??n.tabId:n.viewInstanceId??null:null,p=h&&n&&jm(n)?m.flatMap(C=>C.entries).find(C=>C.item.type==="saved_view"&&C.item.savedView.targetPayload.kind===n.kind&&C.item.savedView.targetPayload.viewInstanceId===h)??null:null,x=p?m.find(C=>C.entries.some(I=>I.id===p.id))??null:null,b=s&&t&&n?s.getMoveState(t,e,n):null,y=xt({mutationFn:async C=>{var $;if(!t||!n)throw new Error("Organization and Side Panel target are required");if(s&&(b!=null&&b.retryable)){const B=await s.retry(t,e,n);return{clientMutationId:null,completedRetryMutationId:b.clientMutationId,intentKey:null,result:B}}const I=C===W_e?{kind:"loose"}:gZt(e,(($=u.data)==null?void 0:$.id)??null,C);if(!I)throw new Error(c?"Wait for the Issue to finish loading, then try again.":"Choose a Messenger group first.");const N=iX(n,{clientMutationId:RBn,placement:I});if(!N)throw new Error("This Side Panel view cannot be kept in Messenger.");const M=LBn(N),E=zBn(o.current,M),_={...N,clientMutationId:E},z=p&&x&&I.kind==="group"&&I.groupId===x.id?{savedView:p.item.savedView,group:{id:x.id,name:x.name}}:null,T=s?await s.promote({contextKey:e,input:_,organizationId:t,target:n,existingResult:z}):await _s.keepSavedView(t,_);return{clientMutationId:E,completedRetryMutationId:null,intentKey:M,result:T}},onSuccess:async({clientMutationId:C,completedRetryMutationId:I,intentKey:N,result:M})=>{N&&C&&$Bn(o.current,N,C),I&&FBn(o.current,I),await Promise.all([a.invalidateQueries({queryKey:U.messenger.customGroups(t??"__none__")}),a.invalidateQueries({queryKey:["messenger",t??"__none__","saved-views"]})]),r({title:"Moved to Messenger",body:M.group?`Moved to ${M.group.name}.`:"Moved to Messenger sidebar.",tone:"success"})},onError:C=>{r({title:"Could not move this view",body:C instanceof Error?C.message:"Try again.",tone:"error"})}});if(!l||!n)return null;const w=!!(c&&u.isPending),k="inline-flex h-7 items-center justify-center gap-1 rounded-[calc(var(--radius-sm)-1px)] px-2 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-[color:var(--surface-active)] hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40 disabled:cursor-not-allowed disabled:opacity-50",S=y.isPending||w?i.jsx(fn,{className:"h-3.5 w-3.5 animate-spin","aria-hidden":!0}):b!=null&&b.retryable?i.jsx(A0,{className:"h-3.5 w-3.5","aria-hidden":!0}):y.isSuccess?i.jsx(zi,{className:"h-3.5 w-3.5","aria-hidden":!0}):i.jsx(vze,{className:"h-3.5 w-3.5","aria-hidden":!0});return b!=null&&b.retryable?i.jsxs("button",{type:"button","data-testid":"chat-side-panel-keep-in-messenger","aria-label":"Retry move to Messenger",title:b.error??"Retry move to Messenger",className:k,disabled:y.isPending,onClick:()=>y.mutate(null),children:[S,i.jsx("span",{children:"Retry move"})]}):d?c&&u.isError?i.jsxs("div",{className:"flex items-center gap-1 text-[11px]",role:"alert",children:[i.jsx("span",{className:"text-destructive",children:"Could not load this Issue."}),i.jsx("button",{type:"button",className:k,onClick:()=>void u.refetch(),children:"Retry Issue lookup"})]}):i.jsxs("button",{type:"button","data-testid":"chat-side-panel-keep-in-messenger","aria-label":"Keep in Messenger",title:"Keep in Messenger",className:k,disabled:y.isPending||w||!!u.error,onClick:()=>y.mutate(null),children:[S,i.jsx("span",{className:b!=null&&b.retryable?"inline":"hidden min-[1180px]:inline",children:b!=null&&b.retryable?"Retry move":"Keep"})]}):i.jsxs(ui,{onOpenChange:C=>{C&&f.refetch()},children:[i.jsx(fi,{asChild:!0,children:i.jsxs("button",{type:"button","data-testid":"chat-side-panel-keep-in-messenger","aria-label":"Keep in Messenger",title:"Keep in Messenger",className:k,disabled:y.isPending||f.isPending||!t,children:[S,i.jsx("span",{className:"hidden min-[1180px]:inline",children:"Keep"})]})}),i.jsxs(mi,{align:"end",className:"surface-overlay w-64 text-foreground",children:[i.jsx(dM,{children:"Keep in Messenger"}),f.isError?i.jsxs(i.Fragment,{children:[i.jsx(Ht,{disabled:!0,className:"whitespace-normal text-xs leading-5",children:"Could not load Messenger groups."}),i.jsx(Ht,{onClick:()=>void f.refetch(),children:"Retry groups"})]}):i.jsxs(i.Fragment,{children:[i.jsx(Ht,{onClick:()=>y.mutate(W_e),children:"Messenger sidebar"}),x?i.jsxs(Ht,{className:"whitespace-normal text-xs leading-5",onClick:()=>y.mutate(x.id),children:["Move existing view from ",x.name," to Main"]}):m.length>0?m.map(C=>i.jsx(Ht,{onClick:()=>y.mutate(C.id),children:C.name},C.id)):i.jsx(Ht,{disabled:!0,className:"whitespace-normal text-xs leading-5",children:"No groups yet."})]})]})]})}const mY=A.forwardRef(function({children:t,centered:n=!1,streaming:r=!1,fileDragActive:s=!1,fileDropTargetProps:a,className:o,testId:l="chat-composer-file-drop-target"},c){return i.jsx("div",{ref:c,"data-testid":l,...a,className:q("chat-composer relative rounded-[var(--radius-lg)] p-3 transition-[border-color,box-shadow] duration-300",r&&"chat-composer--streaming",s&&"ring-2 ring-[color:var(--accent-base)] ring-offset-2 ring-offset-background",n?"mx-auto w-full max-w-3xl":"w-full",o),children:t})}),AY=A.forwardRef(function({scrollRef:t,onKeyDownCapture:n,onPasteCapture:r,scrollTestId:s="chat-composer-editor-scroll",className:a,contentClassName:o,...l},c){return i.jsx("div",{ref:t,"data-testid":s,className:"chat-composer-editor-scroll scrollbar-auto-hide overflow-y-auto overscroll-contain",onKeyDownCapture:n,onPasteCapture:r,children:i.jsx(Cu,{ref:c,...l,submitShortcut:"enter",plainText:!0,bordered:!1,className:q("rounded-[var(--radius-md)] bg-transparent",a),contentClassName:q("min-h-[88px] bg-transparent text-[15px] leading-7 text-foreground",o)})})});function hY({children:e,actions:t,testId:n="chat-composer-toolbar"}){return i.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-2.5","data-testid":n,children:[i.jsx("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-2",children:e}),t]})}function Cht({open:e,onOpenChange:t,onAddFiles:n,children:r}){return i.jsxs(ui,{open:e,onOpenChange:t,children:[i.jsx(fi,{type:"button",className:"control-hover inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full border border-[color:var(--border-soft)] bg-[color:color-mix(in_oklab,var(--surface-active)_52%,transparent)] text-sm font-medium text-foreground transition-[color,background-color,border-color,box-shadow,opacity,transform,scale] hover:bg-[color:var(--surface-active)] focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring/40","aria-label":"Add files and options",children:i.jsx(ps,{className:"h-4 w-4"})}),i.jsxs(mi,{align:"start",side:"top",sideOffset:8,className:"surface-overlay w-80 max-w-[calc(100vw-2rem)] rounded-[var(--radius-lg)] border p-1.5 text-foreground",children:[i.jsxs(Ht,{className:"rounded-[var(--radius-md)] px-3 py-2.5",onSelect:s=>{s.preventDefault(),t(!1),window.setTimeout(n,0)},children:[i.jsx(df,{className:"mr-2 h-4 w-4"}),"Add files"]}),r]})]})}function Nht({open:e,onClick:t,buttonRef:n}){return i.jsx("button",{ref:n,type:"button",className:q("chat-chip inline-flex max-w-[min(100%,16rem)] min-w-0 items-center gap-1.5 rounded-[var(--radius-md)] px-3 py-1.5 text-xs font-medium transition-colors hover:bg-[color:var(--surface-active)]",e&&"bg-[color:var(--surface-active)]"),"aria-label":"Skills","aria-expanded":e,"aria-haspopup":"menu",onClick:t,children:i.jsx("span",{className:"min-w-0 truncate",children:"Skills"})})}function Iht({pending:e,skills:t,filteredSkills:n,searchQuery:r,searchInputRef:s,onSearchQueryChange:a,onSelect:o}){return i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"px-3 py-1.5 text-xs font-medium text-muted-foreground",children:"Skills"}),e?i.jsxs("div",{className:"flex items-center gap-2 rounded-[var(--radius-md)] px-3 py-2 text-sm text-muted-foreground",children:[i.jsx(fn,{className:"h-4 w-4 animate-spin"}),i.jsx("span",{children:"Loading skills..."})]}):t.length===0?i.jsx("div",{className:"rounded-[var(--radius-md)] px-3 py-2 text-sm leading-6 text-muted-foreground",children:"This agent has no enabled skills."}):i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"px-2 pb-2",children:i.jsx("input",{ref:s,className:"w-full rounded-[var(--radius-md)] border border-border bg-transparent px-2.5 py-2 text-sm outline-none placeholder:text-muted-foreground/60 focus:border-ring",placeholder:"Search skills...",value:r,onChange:l=>a(l.target.value),onKeyDown:l=>{l.key!=="Escape"&&l.stopPropagation()}})}),i.jsx("div",{children:n.length===0?i.jsx("div",{className:"rounded-[var(--radius-md)] px-3 py-2 text-sm leading-6 text-muted-foreground",children:"No skills match search."}):n.map(l=>i.jsxs("button",{type:"button",role:"menuitem","data-chat-composer-menu-item":!0,className:"chat-composer-menu-row",onClick:()=>o(l),children:[i.jsx(nd,{className:"h-4 w-4 shrink-0 text-[#2f80ed]"}),i.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[i.jsx("span",{className:"min-w-0 shrink truncate font-medium text-foreground",children:l.skillDisplayName}),l.skillCategoryLabel?i.jsx("span",{className:"inline-flex shrink-0 items-center rounded-[var(--radius-sm)] border border-border/70 bg-muted/50 px-1.5 py-0.5 text-[11px] leading-none text-muted-foreground",children:l.skillCategoryLabel}):null,i.jsx("span",{className:"min-w-0 flex-1 truncate text-muted-foreground",children:l.skillDescription??l.skillLocationLabel??l.skillRefLabel})]})]},l.id))})]})]})}function yve({children:e,menuRef:t,testId:n,ariaLabel:r,position:s,onKeyDown:a}){const o=is(),l=A.useCallback(c=>{typeof t=="function"?t(c):t&&(t.current=c),o(c)},[t,o]);return i.jsx("div",{ref:l,"data-testid":n,role:"menu","aria-label":r,onKeyDown:a,className:"chat-composer-context-menu motion-chat-composer-menu-pop surface-overlay scrollbar-auto-hide fixed z-50 overflow-y-auto rounded-[var(--radius-lg)] border p-1.5 text-foreground",style:s,children:e})}function pY({mode:e,disabled:t,onClick:n,stoppingComplete:r=!1,ariaLabel:s}){const a=e==="sending"||e==="stopping"&&!r,o=s??(e==="sending"?"Sending":e==="stopping"?r?"Response stopped":"Stopping response":e==="stop"?"Stop streaming":e==="queue"?"Queue":e==="continue"?"Continue":"Send");return i.jsx(oe,{type:"button",variant:"ghost",size:"icon-sm",onClick:n,disabled:t,"aria-busy":a?!0:void 0,"aria-label":o,title:e==="continue"?o:void 0,className:q("shrink-0 rounded-full border-0 bg-white text-black shadow-sm","hover:bg-zinc-100 dark:bg-white dark:text-black dark:hover:bg-zinc-100","disabled:pointer-events-none disabled:opacity-35","focus-visible:ring-2 focus-visible:ring-white/40 focus-visible:ring-offset-2 focus-visible:ring-offset-[color:var(--surface-page)]",a&&"disabled:opacity-100"),children:a?i.jsx(fn,{className:"h-[18px] w-[18px] animate-spin",strokeWidth:2.25}):e==="stop"||e==="stopping"?i.jsx(z0,{className:"h-3.5 w-3.5 fill-current"}):i.jsx(_Ae,{className:"h-[18px] w-[18px]",strokeWidth:2.25})})}function Ox(e){switch(e){case"steer":return"Could not send steer";case"side-chat":return"Could not send Side Chat message";case"feedback":return"Could not send feedback";default:return"Could not send message"}}function uU(e,t="send"){if(e instanceof S6)return{title:Ox(t),body:"The request took too long. Check your connection and try again."};if(e instanceof $o){if(e.status===401||e.status===403)return{title:Ox(t),body:"You no longer have access to this chat. Refresh and try again."};if(e.status===404)return{title:Ox(t),body:"This chat is no longer available. Refresh and try again."};if(e.status===409)return{title:Ox(t),body:"This chat changed while the request was in progress. Refresh and try again."};if(e.status===429)return{title:Ox(t),body:"Rudder is busy right now. Wait a moment and try again."};if(e.status>=400&&e.status<500)return{title:Ox(t),body:"Check the message and try again."};if(e.status>=500)return{title:Ox(t),body:"Rudder could not process the request. Try again."}}return hDt(e)?{title:Ox(t),body:"The request was interrupted. Try again when you are ready."}:e instanceof TypeError||e instanceof Error&&/network|fetch|connection|load failed/iu.test(e.message)?{title:Ox(t),body:"Rudder could not be reached. Check your connection and try again."}:{title:Ox(t),body:"Something went wrong. Try again."}}function uH(e,t="send"){return uU(e,t).body}const QBn="rudder:chat-stop-recovery:v1",UBn=1440*60*1e3,qBn=[250,500,1e3,2e3,5e3];function vve(){try{return globalThis.localStorage??null}catch{return null}}function wve(e,t){return`${QBn}:${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function lme(e){return`${e.orgId}\0${e.chatId}\0${e.request.controlActionId}`}function gY(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function H_e(e){return e===void 0||typeof e=="string"}function tie(e){return e===void 0||typeof e=="number"&&Number.isFinite(e)}function Pht(e){return!gY(e)||typeof e.controlActionId!="string"||!e.controlActionId.trim()||!H_e(e.expectedGenerationId)||!tie(e.expectedAttemptEpoch)||!tie(e.expectedControlVersion)||!tie(e.lastCommittedRenderSeq)||!H_e(e.renderedBodyHash)?null:{controlActionId:e.controlActionId,...typeof e.expectedGenerationId=="string"?{expectedGenerationId:e.expectedGenerationId}:{},...typeof e.expectedAttemptEpoch=="number"?{expectedAttemptEpoch:e.expectedAttemptEpoch}:{},...typeof e.expectedControlVersion=="number"?{expectedControlVersion:e.expectedControlVersion}:{},...typeof e.lastCommittedRenderSeq=="number"?{lastCommittedRenderSeq:e.lastCommittedRenderSeq}:{},...typeof e.renderedBodyHash=="string"?{renderedBodyHash:e.renderedBodyHash}:{}}}const Tht=new Set(["streaming","tool_busy","finalizing","stopping","stopped","failed"]);function fU(e){if(typeof e!="string")return null;const t=new Date(e);return Number.isNaN(t.getTime())?null:t}function VBn(e,t){if(e===null||!gY(e))return null;const n=fU(e.userCreatedAt),r=fU(e.createdAt),s=e.editedFromCreatedAt===null?null:fU(e.editedFromCreatedAt);return e.chatId!==t||typeof e.streamKey!="string"||typeof e.userBody!="string"||!n||!(typeof e.userMessageId=="string"||e.userMessageId===null)||!(typeof e.chatTurnId=="string"||e.chatTurnId===null)||typeof e.turnVariant!="number"||e.editedFromCreatedAt!==null&&!s||typeof e.body!="string"||typeof e.state!="string"||!Tht.has(e.state)||!r||!Array.isArray(e.transcript)||!(typeof e.replyingAgentId=="string"||e.replyingAgentId===null)?null:{...e,chatId:t,userCreatedAt:n,editedFromCreatedAt:s,createdAt:r,state:e.state}}function WBn(e){var r;if(!e)return null;const{userFiles:t,...n}=e;return{...n,userCreatedAt:e.userCreatedAt.toISOString(),editedFromCreatedAt:((r=e.editedFromCreatedAt)==null?void 0:r.toISOString())??null,createdAt:e.createdAt.toISOString()}}function _ht(e){var t;return{version:1,orgId:e.orgId,chatId:e.chatId,request:e.request,frozenDraft:e.frozenDraft,previousStreamState:((t=e.frozenDraft)==null?void 0:t.state)??null,requestedAt:(e.now??new Date).toISOString()}}function Mht(e){var t;try{const n={...e,frozenDraft:WBn(e.frozenDraft)};(t=vve())==null||t.setItem(wve(e.orgId,e.chatId),JSON.stringify(n))}catch{}}function _g(e,t,n=new Date){var r;try{const s=(r=vve())==null?void 0:r.getItem(wve(e,t));if(!s)return null;const a=JSON.parse(s);if(!gY(a)||a.version!==1||a.orgId!==e||a.chatId!==t)return sw(e,t),null;const o=Pht(a.request),l=fU(a.requestedAt),c=a.previousStreamState===null?null:typeof a.previousStreamState=="string"&&Tht.has(a.previousStreamState)?a.previousStreamState:void 0;if(!o||!l||c===void 0||n.getTime()-l.getTime()>UBn)return sw(e,t),null;const d=VBn(a.frozenDraft,t);return a.frozenDraft!==null&&!d?(sw(e,t),null):{version:1,orgId:e,chatId:t,request:o,frozenDraft:d,previousStreamState:c,requestedAt:l.toISOString()}}catch{return sw(e,t),null}}function sw(e,t,n){try{const r=vve();if(!r)return!1;const s=wve(e,t);if(n){const a=r.getItem(s);if(!a)return!1;try{const o=JSON.parse(a),l=gY(o)?Pht(o.request):null;if(l&&l.controlActionId!==n)return!1}catch{}}return r.removeItem(s),!0}catch{return!1}}function Eht(e,t={}){var o;const n=(o=t.retryDelaysMs)!=null&&o.length?[...t.retryDelaysMs]:[...qBn],r=new Map,s=l=>{l.timer&&(clearTimeout(l.timer),l.timer=null)},a=l=>{const c=lme(l);let d=r.get(c);return d?d.recovery=l:(d={recovery:l,retryCount:0,timer:null},r.set(c,d)),{key:c,state:d}};return{schedule(l){const{key:c,state:d}=a(l);if(d.timer)return;const u=n[Math.min(d.retryCount,n.length-1)]??0;d.retryCount+=1,d.timer=setTimeout(()=>{const f=r.get(c);f&&(f.timer=null,e(f.recovery))},u)},retryNow(l){const{state:c}=a(l);s(c),e(c.recovery)},resolve(l){const c=lme(l),d=r.get(c);d&&s(d),r.delete(c)},dispose(){for(const l of r.values())s(l);r.clear()}}}function HBn(e){var t;return((t=e.body)==null?void 0:t.trim())||e.kind}function KBn(e){return e.transcript??[]}function K_e(){}function ZBn({target:e,onReplaceTarget:t}){const n=er(),r=Kr(),[s,a]=A.useState(e.body),[o,l]=A.useState([]),[c,d]=A.useState(""),[u,f]=A.useState(!1),[m,h]=A.useState(null),[p,x]=A.useState(0),[b,y]=A.useState(null),[w,k]=A.useState(null),[S,j]=A.useState(null),[C,I]=A.useState(!1),[N,M]=A.useState({}),E=A.useRef(e),_=A.useRef(!1),z=A.useRef(null),T=A.useRef(null),$=A.useRef(!1),B=A.useRef(()=>{}),F=A.useRef(null),W=A.useRef(null);F.current||(F.current=Eht(ae=>{B.current(ae)})),E.current=e;const Y=Ve({queryKey:U.agents.list(e.organizationId),queryFn:()=>$n.list(e.organizationId)}),G=Ve({queryKey:U.chats.detail(e.organizationId,e.conversationId??"__goal-chat-draft__"),queryFn:()=>Zn.get(e.conversationId),enabled:!!e.conversationId}),V=Ve({queryKey:U.chats.messages(e.organizationId,e.conversationId??"__goal-chat-draft__"),queryFn:()=>Zn.listMessages(e.organizationId,e.conversationId,{includeTranscript:!0}),enabled:!!e.conversationId}),L=Ve({queryKey:U.chats.queue(e.organizationId,e.conversationId??"__goal-chat-draft__"),queryFn:()=>Zn.listQueue(e.conversationId),enabled:!!e.conversationId,refetchInterval:u&&e.conversationId?2e3:!1}),R=A.useMemo(()=>{const ae=Y.data??[];return e.agentId?ae.find(Ee=>Ee.id===e.agentId)??null:null},[Y.data,e.agentId]),D=!Y.isPending&&!R,X=G.data,ee=G.error??V.error;A.useEffect(()=>{V.data&&!_.current&&l(V.data)},[V.data]),A.useEffect(()=>{a(e.body)},[e.body]),A.useEffect(()=>{try{window.localStorage.setItem(`rudder.goal-chat:${e.organizationId}:${e.goalId}`,JSON.stringify(e))}catch{}},[e]),A.useEffect(()=>{var ae;(ae=W.current)==null||ae.scrollIntoView({block:"end"})},[o,c]),A.useEffect(()=>()=>{var ae,Ee;(ae=z.current)==null||ae.abort(),(Ee=F.current)==null||Ee.dispose()},[]),A.useEffect(()=>{const ae=e.conversationId;if(!ae)return;const Ee=()=>{var _e;const he=_g(e.organizationId,ae);he&&((_e=F.current)==null||_e.retryNow(he))};return Ee(),window.addEventListener("online",Ee),()=>window.removeEventListener("online",Ee)},[e.conversationId,e.organizationId]),A.useEffect(()=>{if(m===null){x(0);return}const ae=()=>x(Math.floor((Date.now()-m)/1e3));ae();const Ee=window.setInterval(ae,1e3);return()=>window.clearInterval(Ee)},[m]);const se=A.useCallback(ae=>{const Ee=E.current,he={...Ee,...ae};E.current=he,t(fs(Ee),he)},[t]),ne=A.useCallback(()=>{const ae=E.current.conversationId;ae&&r(`/messenger/chat/${ae}`)},[r]),le=async ae=>{const Ee=(ae??s).trim(),he=E.current;if(!Ee||u||!R)return;const _e=new AbortController;z.current=_e,T.current=Ee,_.current=!0,f(!0),h(Date.now()),y(null),k(null),j(null),d("");let Ie=null;try{const $e=async ce=>{if(ce.type==="ack"){l(Ye=>[...Ye,ce.userMessage]);const Oe=E.current;se({conversationId:ce.userMessage.conversationId,body:Oe.body===Ee?"":Oe.body}),a(Ye=>Ye.trim()===Ee?"":Ye)}if(ce.type==="assistant_delta"&&d(Oe=>Oe+ce.delta),ce.type==="final"&&(d(""),l(Oe=>[...Oe,...ce.messages])),ce.type==="error")throw new Error(ce.error)};he.conversationId?await Zn.sendMessageStream(he.conversationId,Ee,{onEvent:$e,signal:_e.signal}):await Zn.sendFirstMessageStream(e.organizationId,Ee,{preferredAgentId:R.id,issueCreationMode:"manual_approval",planMode:!1,modelOverride:null,effortOverride:null,contextLinks:[{entityType:"goal",entityId:e.goalId}],clientMutationId:e.clientMutationId,signal:_e.signal,onEvent:$e}),Ie=E.current.conversationId??he.conversationId}catch($e){_e.signal.aborted||(j(Ee),y(uH($e,"side-chat")))}finally{z.current===_e&&(z.current=null),T.current=null,_.current=!1,f(!1),h(null)}Ie&&await Promise.all([n.invalidateQueries({queryKey:U.chats.detail(e.organizationId,Ie)}),n.invalidateQueries({queryKey:U.chats.messages(e.organizationId,Ie)}),n.invalidateQueries({queryKey:U.goals.detail(e.goalId)}),n.invalidateQueries({queryKey:U.goals.list(e.organizationId)}),n.invalidateQueries({queryKey:["goals","workspace",e.organizationId]})])},ie=A.useCallback(async(ae,Ee)=>{await Promise.allSettled([n.invalidateQueries({queryKey:U.chats.detail(ae,Ee)}),n.invalidateQueries({queryKey:U.chats.messages(ae,Ee)}),n.invalidateQueries({queryKey:U.chats.queue(ae,Ee)}),n.invalidateQueries({queryKey:U.goals.detail(e.goalId)})])},[n,e.goalId]),re=A.useCallback(ae=>{$.current||($.current=!0,I(!0),y(null),k("Stopping response..."),(async()=>{var Ee,he,_e,Ie,$e;try{const ce=await Zn.stopMessageStream(ae.chatId,ae.request);if((ce.controlActionId??ae.request.controlActionId)!==ae.request.controlActionId){k("Stop confirmation pending. Rudder will retry automatically."),(Ee=F.current)==null||Ee.schedule(ae);return}const Ye=ce.disposition??"",J=ce.stopped||["startup_cancelled","stopping","stop_requested","stopped","interrupted_unverified"].includes(Ye),qe=!ce.stopped&&Ye==="completion_committed";if(sw(ae.orgId,ae.chatId,ae.request.controlActionId),(he=F.current)==null||he.resolve(ae),J){const be=T.current;(_e=z.current)==null||_e.abort(),j(be),k(ce.stopped?"Response stopped. Retry when ready or continue in full chat.":"Response frozen. Runtime termination could not be independently confirmed.")}else qe?(j(null),k("Response completed before Stop reached the cutoff.")):k("No active response was available to stop.");await ie(ae.orgId,ae.chatId)}catch(ce){ce instanceof $o&&ce.status>=400&&ce.status<500?(sw(ae.orgId,ae.chatId,ae.request.controlActionId),(Ie=F.current)==null||Ie.resolve(ae),k(null),y(`Stop was rejected. ${ce.message}`)):(k("Stop confirmation pending. Rudder will retry automatically."),y(null),($e=F.current)==null||$e.schedule(ae))}finally{$.current=!1,I(!1)}})())},[ie]);B.current=re;const de=()=>{var ce,Oe,Ye,J,qe;if(!u||C)return;const ae=E.current,Ee=ae.conversationId;if(!Ee){k("Stop becomes available as soon as this Chat starts.");return}const he=_g(ae.organizationId,Ee);if(he){(ce=F.current)==null||ce.retryNow(he);return}const _e=RC(L.data),Ie=_e&&((Oe=L.data)==null?void 0:Oe.activeAttemptEpoch)!==null&&((Ye=L.data)==null?void 0:Ye.activeAttemptEpoch)!==void 0&&((J=L.data)==null?void 0:J.activeControlVersion)!==null&&((qe=L.data)==null?void 0:qe.activeControlVersion)!==void 0,$e=_ht({orgId:ae.organizationId,chatId:Ee,request:{controlActionId:globalThis.crypto.randomUUID(),...Ie?{expectedGenerationId:_e,expectedAttemptEpoch:L.data.activeAttemptEpoch,expectedControlVersion:L.data.activeControlVersion}:{}},frozenDraft:null});Mht($e),re($e)},Be=!!(s.trim()&&R&&!u);return i.jsxs("div",{className:"flex h-full min-h-0 flex-col","data-testid":"goal-chat-panel",children:[i.jsx("div",{className:"scrollbar-auto-hide min-h-0 flex-1 overflow-y-auto px-4 py-4",children:i.jsxs("div",{className:"mx-auto flex w-full max-w-3xl flex-col gap-4",children:[i.jsxs("div",{className:"flex min-w-0 items-center gap-2 border-b border-border/70 pb-3",children:[i.jsx(Si,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("div",{className:"truncate text-sm font-medium",children:"Chat about Goal"}),i.jsx("div",{className:"truncate text-xs text-muted-foreground",children:e.label})]}),e.conversationId?i.jsxs(oe,{type:"button",size:"sm",variant:"ghost","aria-label":"Open full chat",title:"Open full chat",onClick:()=>r(`/messenger/chat/${e.conversationId}`),children:[i.jsx(Ki,{className:"h-4 w-4"}),i.jsx("span",{className:"hidden sm:inline",children:"Open full chat"})]}):null]}),e.conversationId&&(G.isPending||V.isPending)?i.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading conversation..."}):null,ee?i.jsxs("div",{role:"alert",className:"flex flex-wrap items-center justify-between gap-2 text-sm text-destructive",children:[i.jsx("span",{children:ee instanceof Error?ee.message:"Could not load this conversation."}),i.jsx(oe,{type:"button",size:"sm",variant:"outline",onClick:()=>void Promise.all([G.refetch(),V.refetch()]),children:"Retry"})]}):null,!e.conversationId&&o.length===0?i.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No messages yet."}):null,X?o.map(ae=>{const Ee=KBn(ae);return i.jsxs("div",{"data-testid":"goal-chat-message",children:[ae.role==="assistant"&&Ee.length>0?i.jsx(J6,{entries:Ee,state:ae.status,generationTerminalReason:ae.generationTerminalReason,streamStartedAt:new Date(ae.createdAt),streamEndedAt:new Date(ae.updatedAt),assistantMessageBody:ae.body,showDeveloperDiagnostics:!1}):null,i.jsx(Qk,{conversation:X,message:ae,agents:Y.data,decisionNote:N[ae.id]??"",onDecisionNoteChange:he=>M(_e=>({..._e,[ae.id]:he})),decisionNoteMentions:[],onDecisionNoteMentionQueryChange:K_e,onDecisionNoteInlineTokenClick:K_e,onApprovalAction:ne,onIssueProposalChange:ne,onResolveOperationProposal:ne,onConvertToIssue:ne,actionPending:!1,onCopyMessageText:he=>{var _e;return(_e=navigator.clipboard)==null?void 0:_e.writeText(he)},onRetryFailedMessage:ne,onOpenFile:ne,onSelectResponseAnnotation:he=>{he.surface==="agent_run_transcript"&&r(`/agents/${he.sourceAgentId}/runs/${he.sourceRunId}`)},skillReferences:[]})]},ae.id)}):o.map(ae=>i.jsxs("div",{className:`rounded-md border px-3 py-2 text-sm ${ae.role==="user"?"ml-6 bg-muted/30":"mr-6"}`,children:[i.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:ae.role==="user"?"You":(R==null?void 0:R.name)??"Agent"}),i.jsx("div",{className:"whitespace-pre-wrap break-words",children:HBn(ae)})]},ae.id)),c?i.jsx("div",{"data-testid":"goal-chat-streaming",className:"mr-6 whitespace-pre-wrap break-words text-sm text-foreground",children:c}):null,u?i.jsxs("div",{role:"status","data-testid":"goal-chat-working",className:"mr-6 flex items-center gap-2 rounded-lg border border-border bg-muted/25 px-3 py-2.5",children:[i.jsx(fn,{className:"h-4 w-4 shrink-0 animate-spin text-muted-foreground","aria-hidden":"true"}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"truncate text-sm font-medium",children:p>=30?"Still working on this Goal...":`${(R==null?void 0:R.name)??"Agent"} is working...`}),E.current.conversationId?i.jsx("p",{className:"text-xs text-muted-foreground",children:"You can keep this panel open or continue in full chat."}):null]})]}):null,i.jsx("div",{ref:W})]})}),w?i.jsx("div",{role:"status",className:"px-4 pb-2 text-sm text-muted-foreground",children:w}):null,b||S?i.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 px-4 pb-2",children:[b?i.jsx("span",{role:"alert",className:"text-sm text-destructive",children:b}):i.jsx("span",{}),i.jsxs("div",{className:"flex items-center gap-2",children:[S?i.jsx(oe,{type:"button",size:"sm",variant:"outline",disabled:u,onClick:()=>void le(S),children:"Retry message"}):null,e.conversationId?i.jsx(oe,{type:"button",size:"sm",variant:"ghost",onClick:ne,children:"Open full chat"}):null]})]}):null,i.jsxs("div",{className:"shrink-0 px-4 pb-4",children:[D?i.jsx("p",{role:"alert",className:"mx-auto mb-2 max-w-3xl text-sm text-destructive",children:"The Goal Owner is unavailable. Reassign the Goal before starting a chat."}):null,i.jsxs(mY,{className:"mx-auto max-w-3xl",testId:"goal-chat-composer",children:[i.jsx(AY,{value:s,onChange:ae=>{u||(a(ae),se({body:ae}))},placeholder:"Message about this Goal...",onSubmit:()=>void le()}),i.jsx(hY,{actions:i.jsx(pY,{mode:u?C?"stopping":"stop":"send",ariaLabel:u?C?"Stopping response":e.conversationId?"Stop streaming":"Stop unavailable until chat starts":"Send message",disabled:u?C||!e.conversationId:!Be,onClick:()=>void(u?de():le())}),children:R?i.jsx(zl,{name:R.name,icon:R.icon,role:R.role,size:"sm",className:"min-w-0"}):i.jsx("span",{className:"min-w-0 truncate text-xs text-muted-foreground",children:Y.isPending?"Loading Agent...":D?"Owner unavailable":"No Agent available"})})]})]})]})}function Dht({project:e,label:t,expanded:n,disabled:r,buttonRef:s,testId:a="chat-project-selector",iconTestId:o="chat-project-icon",clearTestId:l="chat-project-clear",onClick:c,onClear:d}){return i.jsxs("div",{className:"group/project relative inline-flex max-w-[min(100%,15rem)] min-w-0",children:[i.jsxs("button",{ref:s,type:"button","data-testid":a,"aria-label":`Project context: ${t}`,"aria-expanded":r?!1:n,disabled:r,title:r?"Project context is locked after conversation starts.":void 0,className:q("chat-chip inline-flex w-full min-w-0 items-center gap-1.5 rounded-[var(--radius-md)] px-3 py-1.5 text-xs font-medium",r?"cursor-default":"transition-colors hover:bg-[color:var(--surface-active)]",n&&"bg-[color:var(--surface-active)]"),onClick:c,children:[e?i.jsx(Fo,{color:e.color,icon:e.icon,size:"xs",testId:o,className:q("transition-opacity",!r&&"group-focus-within/project:opacity-0 group-hover/project:opacity-0")}):null,i.jsx("span",{className:"min-w-0 truncate",children:t})]}),e&&!r?i.jsx("button",{type:"button","data-testid":l,"aria-label":`Clear project context: ${t}`,title:"Clear project context",className:"pointer-events-none absolute left-2 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-[var(--radius-sm)] text-muted-foreground opacity-0 transition-[color,background-color,opacity] hover:bg-[color:var(--surface-inset)] hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring/40 group-focus-within/project:pointer-events-auto group-focus-within/project:opacity-100 group-hover/project:pointer-events-auto group-hover/project:opacity-100",onClick:u=>{u.stopPropagation(),d()},children:i.jsx(Jr,{className:"h-4 w-4",strokeWidth:2.4})}):null]})}function Rht({projects:e,activeProjectId:t,onSelect:n,onCreateProject:r}){return i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"px-3 py-1.5 text-xs font-medium text-muted-foreground",children:"Project context"}),i.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":t===null,"data-chat-composer-menu-item":!0,className:"chat-composer-menu-row project-context-menu-item",onClick:()=>n(null),children:[i.jsx("span",{className:"project-context-empty-swatch h-3 w-3 shrink-0","aria-hidden":"true"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:"No project"})]}),e.length>0?i.jsx("div",{className:"my-1 border-t border-[color:var(--border-soft)] pt-1",children:e.map(s=>{var a;return i.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":t===s.id,"data-chat-composer-menu-item":!0,className:"chat-composer-menu-row project-context-menu-item",onClick:()=>n(s.id),children:[i.jsx(Fo,{color:s.color,icon:s.icon,size:"xs"}),i.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:((a=s.name)==null?void 0:a.trim())||"Unknown project"})]},s.id)})}):null,r&&t===null?i.jsx("div",{className:"mt-1 border-t border-[color:var(--border-soft)] pt-1",children:i.jsxs("button",{type:"button",role:"menuitem","data-testid":"chat-project-create","data-chat-composer-menu-item":!0,className:"chat-composer-menu-row project-context-menu-item",onClick:r,children:[i.jsx(e2,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:"Create project"})]})}):null]})}const ny="__none__",cme="rudder.chatLastAgentByOrg";function Lht(){try{return globalThis.localStorage??null}catch{return null}}function jL(e){return(e??[]).filter(t=>t.status!=="terminated")}function XBn(e){var t;try{const n=(t=Lht())==null?void 0:t.getItem(cme);if(!n)return;const r=JSON.parse(n);if(!r||typeof r!="object")return;const s=r[e];return typeof s=="string"&&s.trim().length>0?s:void 0}catch{return}}function tP(e,t){if(!(!t||t===ny))try{const n=Lht();if(!n)return;const r=n.getItem(cme),s=r?JSON.parse(r):{},a=s&&typeof s=="object"?s:{};a[e]=t,n.setItem(cme,JSON.stringify(a))}catch{return}}function nie(e,t){return!!(e&&jL(t).some(n=>n.id===e))}function GBn(e,t){const n=jL(t);if(n.length===0)return ny;const r=e?XBn(e):void 0;return r&&n.some(s=>s.id===r)?r:n[0].id}const PE="dev-restart-required";function Z_e({explicit:e,pendingFileCount:t}){return e??(t>0?"memory":"durable")}function fH({annotations:e,devServer:t,draftPersistence:n="durable",pushToast:r}){if(e.length===0||!(t!=null&&t.enabled)||!t.restartRequired)return!1;const s=_n(),a=n==="durable"&&s;return r({id:PE,dedupeKey:`${PE}:${Date.now()}:${Math.random()}`,title:"Restart Rudder to send annotations",body:n==="memory"?"Your draft is still open in this window. Copy it before restarting Rudder.":s?"Your message and annotations are saved. Rudder's local server is still running older code.":"Your message and annotations are saved. Restart pnpm dev, then send again.",tone:"warn",persistent:!0,...a?{action:{label:"Restart Rudder",onClick:async()=>{try{await s.restart()}catch(o){throw r({title:"Could not restart Rudder",body:o instanceof Error?o.message:"Try restarting Rudder manually.",tone:"error"}),o}}}}:{}}),!0}const mH=new Map;function YBn(e,t,n){if(n.length===0)return;const r=mH.get(e)??new Map;r.set(t,[...n]),mH.set(e,r)}function JBn(e){const t=mH.get(e);return t?(mH.delete(e),Object.fromEntries(Array.from(t.entries(),([n,r])=>[n,[...r]]))):{}}const e0={agentRuntimeType:"claude_local",cwd:"",instructionsFilePath:"",promptTemplate:"",model:"",modelFallbacks:[],thinkingEffort:"",mode:"",chrome:!1,dangerouslySkipPermissions:!1,permissionMode:"auto",search:!1,countSubscriptionUsageAsCost:!0,dangerouslyBypassSandbox:!1,command:"",args:"",extraArgs:"",envVars:"",envBindings:{},url:"",bootstrapPrompt:"",payloadTemplateJson:"",workspaceStrategyType:"project_primary",workspaceBaseRef:"",workspaceBranchTemplate:"",worktreeParentDir:"",runtimeServicesJson:"",maxTurnsPerRun:300,heartbeatEnabled:!1,intervalSec:300,preflightEnabled:!0,maxConcurrentRuns:Uhe},rie={identity:{},agentRuntimeConfig:{},heartbeat:{},runtime:{}},X_e={};function eQn(e){return Object.keys(e.identity).length>0||e.agentRuntimeType!==void 0||Object.keys(e.agentRuntimeConfig).length>0||Object.keys(e.heartbeat).length>0||Object.keys(e.runtime).length>0}const jh="w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40";function tQn(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}function nQn(e){return Array.isArray(e)?e.filter(t=>typeof t=="string").join(", "):typeof e=="string"?e:""}const xY={claude_local:{key:"effort",label:"Thinking effort"},codex_local:{key:"modelReasoningEffort",label:"Thinking effort"},opencode_local:{key:"variant",label:"Thinking effort"},pi_local:{key:"thinking",label:"Thinking effort"},cursor:{key:"effort",label:"Thinking effort"}},rQn=["claude_local","codex_local","opencode_local","pi_local","cursor"];function Jg(e){var t,n,r;return e==="claude_local"?((t=cU.find(s=>s.id===mht))==null?void 0:t.id)??((n=cU.find(s=>s.id.startsWith("deepseek")))==null?void 0:n.id)??((r=cU[0])==null?void 0:r.id)??"":e==="codex_local"?sY:e==="cursor"?cY:e==="opencode_local"?"opencode/deepseek-v4-flash-free":e==="pi_local"?"kimi-coding/kimi-for-coding":""}function zht(e){return e==="codex_local"?"codex":e==="pi_local"?"pi":e==="cursor"?"cursor-agent":e==="opencode_local"?"opencode":"claude"}function $ht(e){const t={...e0,agentRuntimeType:e,model:Jg(e),modelFallbacks:[],command:zht(e)};return e==="codex_local"&&(t.thinkingEffort=iY,t.search=oY,t.countSubscriptionUsageAsCost=iH,t.dangerouslyBypassSandbox=aY),e==="claude_local"&&(t.dangerouslySkipPermissions=!1,t.permissionMode="auto"),e==="opencode_local"&&(t.dangerouslySkipPermissions=!1),t}function UC(e){return F5(e).buildAdapterConfig($ht(e))}function Fht(e){return e==="claude_local"?"codex_local":"claude_local"}function sQn(e){const t=Fht(e),n=UC(t),r=typeof n.model=="string"?n.model:Jg(t);return{agentRuntimeType:t,model:r,config:n}}function Bht(e,t){const n=new Set(t.map(s=>`${s.agentRuntimeType}\0${s.model}`)),r=[Fht(e),"opencode_local","pi_local","cursor","codex_local","claude_local"];for(const s of r){const a=UC(s),o=typeof a.model=="string"?a.model:Jg(s);if(!n.has(`${s}\0${o}`))return{agentRuntimeType:s,model:o,config:a}}return sQn(e)}function AH(e){var t;return((t=xY[e])==null?void 0:t.key)??"effort"}function o5(e,t="",n){return xY[e]?e==="codex_local"?yht("Auto",mve(t,n)).map(s=>({id:s.value,label:s.label})):e==="claude_local"?uve(t,n).map(s=>({id:s.value,label:s.label})):e==="opencode_local"?fve(t,n).map(s=>({id:s.value,label:s.label})):e==="pi_local"?Ave(t,n).map(s=>({id:s.value,label:s.label})):e==="cursor"?hve(t,n).map(s=>({id:s.value,label:s.label})):[]:[]}function Qht(e){var t;return((t=xY[e])==null?void 0:t.label)??"Thinking effort"}function CL(e,t="",n){return e==="cursor"||e==="codex_local"||e==="claude_local"||e==="opencode_local"||e==="pi_local"?o5(e,t,n).length>1:e in xY}function iQn(e){return Object.values(e).some(t=>t===void 0)}function G_e(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Xk(e,t){return{agentRuntimeType:e,model:t}}function Gk(e,t){return z5(e,{agentRuntimeType:t.agentRuntimeType,model:""})}function Uht({primaryRuntimeType:e,primaryModel:t,primaryConfig:n}){const r={...n};delete r.modelFallbacks;const s=Gk(n.modelFallbacks??[],Xk(e,t));return[{id:"primary",agentRuntimeType:e,model:t,config:{...r,...t?{model:t}:{}}},...s.map((a,o)=>({id:`fallback-${o}`,agentRuntimeType:a.agentRuntimeType,model:a.model,config:{...a.config??{},...a.model?{model:a.model}:{}}}))]}function qht(e,t,n){const r=e.findIndex(a=>a.id===t),s=e.findIndex(a=>a.id===n);return r<0||s<0||r===s?Y_e(e):Y_e(Sy(e,r,s))}function Y_e(e){return{primary:e[0]??{id:"primary",agentRuntimeType:"codex_local",model:"",config:{}},fallbacks:e.slice(1).map(n=>({agentRuntimeType:n.agentRuntimeType,model:n.model,config:{...n.config,...n.model?{model:n.model}:{}}}))}}const Vht="flex gap-3 overflow-x-auto overscroll-x-contain pb-2 pr-2 [-webkit-overflow-scrolling:touch]",XS="basis-[60%] min-w-[420px] shrink-0 grow-0";function hH(e){const t=R8[e.runtimeType]??e.runtimeType;return e.model?`${e.title} · ${t} · ${e.model}`:`${e.title} · ${t}`}function Wht(e){return e.checks.filter(t=>t.level==="warn"||t.level==="error")}function Hht(e){var c;const[t,n]=A.useState({modelOverride:null,effortOverride:null}),r=A.useRef(null),s=A.useRef(null),a=A.useRef(null),o=t,l=Ve({queryKey:e.activeAgent&&e.selectedOrganizationId?U.agents.adapterModels(e.selectedOrganizationId,e.activeAgent.agentRuntimeType):U.agents.adapterModels("__none__","__none__"),queryFn:()=>$n.adapterModels(e.selectedOrganizationId,e.activeAgent.agentRuntimeType),enabled:!!e.selectedOrganizationId&&!!e.activeAgent,retry:!1});return A.useEffect(()=>{var u;const d=`${e.selectedOrganizationId??"__none__"}:${e.composerScopeKey??((u=e.selectedConversation)==null?void 0:u.id)??"new"}:${e.activeAgentId??"__none__"}`;r.current!==null&&r.current!==d&&n({modelOverride:null,effortOverride:null}),r.current=d},[e.activeAgentId,e.composerScopeKey,(c=e.selectedConversation)==null?void 0:c.id,e.selectedOrganizationId]),{activeRuntimeOverrides:o,adapterModelsQuery:l,draftRuntimeOverrides:t,runtimeModelSelectRef:a,runtimeSelectorRef:s,setDraftRuntimeOverrides:n}}function aQn(e){return{applyRuntimeOverrides:n=>{e.activeAgent&&e.setDraftRuntimeOverrides(n)},runtimeSelectionPending:!1}}function kve(e){const t=e.agentRuntimeConfig.model??e.runtimeConfig.model;return typeof t=="string"&&t.trim()?t.trim():"Default model"}function Kht(e){const t={...e.runtimeConfig,...e.agentRuntimeConfig},n=AH(e.agentRuntimeType),r=t[n]??(e.agentRuntimeType==="codex_local"?t.reasoningEffort:null);return typeof r=="string"&&r.trim()?r.trim():null}function dme(e){if(!e||e.toLowerCase()==="auto")return"Auto";const n={minimal:"Minimal",light:"Light",low:"Low",medium:"Medium",high:"High",xhigh:"Extra High",max:"Max",ultra:"Ultra"}[e.toLowerCase()];return n||e.charAt(0).toUpperCase()+e.slice(1)}function oQn(e,t,n){const r=c9(e.agentRuntimeType,t),s=(n==null?void 0:n.trim())??"";return!s||r.some(a=>a.id===s)?r:[...r,{id:s,label:s}]}function lQn(e,t,n,r){const s=n??kve(e);if(!CL(e.agentRuntimeType,s,r))return{modelOverride:n,effortOverride:null};const a=o5(e.agentRuntimeType,s,r);return{modelOverride:n,effortOverride:t.effortOverride&&a.some(o=>o.id===t.effortOverride)?t.effortOverride:null}}function Zht(e){var s;if(!e.agent)return"Loading runtime";const t=e.overrides.modelOverride??kve(e.agent),n=(s=e.adapterModels)==null?void 0:s.find(a=>a.id===t);if(!CL(e.agent.agentRuntimeType,t,n))return t;const r=e.overrides.effortOverride==null?Kht(e.agent):e.overrides.effortOverride;return`${t} · ${dme(r)}`}function cQn(e){const t=oQn(e.agent,e.adapterModels,e.overrides.modelOverride),n=kve(e.agent),r=Kht(e.agent),s=e.overrides.modelOverride??n,a=t.find(f=>f.id===s),o=CL(e.agent.agentRuntimeType,s,a),l=o5(e.agent.agentRuntimeType,s,a).map(f=>({id:f.id||"auto",label:f.label})),c=e.overrides.effortOverride,d=e.error instanceof Error?e.error.message:e.error?"Models are temporarily unavailable.":null,u=c??r;return i.jsx(fht,{ariaContext:`this conversation (${e.agent.name} runtime)`,disabled:e.disabled,pending:e.pending,errorMessage:d,modelSelectRef:e.modelSelectRef,testIds:{modelTrigger:"chat-model-selector",modelOptions:"chat-model-options",modelOption:f=>f==null?"chat-model-option-default":`chat-model-option-${f}`,effortTrigger:"chat-effort-selector",effortOptions:"chat-effort-options",effortOption:f=>f==null?"chat-effort-option-default":`chat-effort-option-${f}`},model:{valueLabel:s,dataValue:e.overrides.modelOverride??"",selectedId:e.overrides.modelOverride,defaultOption:{id:null,label:`Agent default · ${n}`},options:t,loading:e.isLoading,emptyLabel:d?"Models unavailable":"No models found.",onSelect:f=>e.onChange(lQn(e.agent,e.overrides,f,t.find(m=>m.id===(f??n))))},effort:o?{valueLabel:dme(u),dataValue:c??"",selectedId:c,defaultOption:{id:null,label:`Agent default · ${dme(r)}`},options:l,onSelect:f=>e.onChange({...e.overrides,effortOverride:f})}:void 0})}function dQn(e){var l;const[t,n]=A.useState(!1),[r,s]=A.useState(null),a=A.useRef(null),o=()=>{if(!e.agent||e.disabled||!a.current)return;const c=a.current.getBoundingClientRect(),d=304,u=12;if(e.panelPlacement==="above"){s({left:Math.max(u,Math.min(c.right-d,window.innerWidth-d-u)),bottom:Math.max(u,window.innerHeight-c.top+8)}),n(!0);return}const f=window.innerWidth-c.right;s({left:f>=d+u?c.right+8:Math.max(u,c.left-d-8),top:Math.max(u,Math.min(c.top,window.innerHeight-u-360))}),n(!0)};return A.useEffect(()=>{if(!t||!e.modelSelectRef||typeof e.modelSelectRef!="object")return;const c=e.modelSelectRef;requestAnimationFrame(()=>{var d;return(d=c.current)==null?void 0:d.focus()})},[t,e.modelSelectRef]),i.jsxs(i.Fragment,{children:[i.jsxs("button",{ref:a,type:"button",role:"menuitem","data-chat-composer-menu-item":!0,"data-testid":"chat-agent-runtime-selector","aria-label":`Configure model and thinking for ${((l=e.agent)==null?void 0:l.name)??"selected agent"}`,"aria-haspopup":"dialog","aria-expanded":t,disabled:!e.agent||e.disabled,className:q("inline-flex min-w-0 max-w-44 items-center gap-1 rounded-[var(--radius-sm)] px-2 py-1","text-[11px] text-muted-foreground transition-colors hover:bg-[color:var(--surface-active)] hover:text-foreground","disabled:cursor-not-allowed disabled:opacity-55"),onClick:c=>{if(c.stopPropagation(),t){n(!1);return}o()},onKeyDown:c=>{(c.key==="ArrowRight"||c.key==="Enter"||c.key===" ")&&(c.preventDefault(),c.stopPropagation(),o())},children:[i.jsx("span",{className:"min-w-0 truncate",children:e.label}),e.pending?i.jsx(fn,{className:"h-3.5 w-3.5 shrink-0 animate-spin","aria-hidden":"true"}):i.jsx(vi,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":"true"})]}),t&&r&&e.agent&&typeof document<"u"?ja.createPortal(i.jsxs("div",{"data-chat-runtime-submenu":!0,"data-runtime-profile-panel":!0,"data-testid":"chat-agent-runtime-panel",role:"dialog","aria-label":`Model and thinking for ${e.agent.name}`,className:"surface-overlay fixed z-[65] w-[19rem] max-w-[calc(100vw-1.5rem)] rounded-[var(--radius-lg)] border p-1.5 shadow-lg",style:r,onKeyDownCapture:c=>{c.key!=="Escape"&&c.key!=="ArrowLeft"||(c.preventDefault(),c.stopPropagation(),n(!1),requestAnimationFrame(()=>{var d;return(d=a.current)==null?void 0:d.focus()}))},children:[i.jsxs("button",{type:"button",className:"chat-composer-menu-row mb-1",onClick:()=>{n(!1),requestAnimationFrame(()=>{var c;return(c=a.current)==null?void 0:c.focus()})},children:[i.jsx(Tw,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),i.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:e.agent.name})]}),i.jsx("div",{className:"border-t border-[color:var(--border-soft)] pt-1",children:i.jsx(cQn,{agent:e.agent,adapterModels:e.adapterModels,overrides:e.overrides,disabled:e.disabled,isLoading:e.isLoading,error:e.error,pending:e.pending,modelSelectRef:e.modelSelectRef,onChange:e.onChange})})]}),document.body):null]})}function Ove(e){var s;if(!["ArrowDown","ArrowUp","Home","End"].includes(e.key)||e.target instanceof Element&&e.target.closest("[data-chat-runtime-submenu]"))return;const t=Array.from(e.currentTarget.querySelectorAll("[data-chat-composer-menu-item]:not(:disabled)"));if(t.length===0)return;e.preventDefault();const n=t.findIndex(a=>a===document.activeElement),r=e.key==="Home"?0:e.key==="End"?t.length-1:e.key==="ArrowUp"?n<=0?t.length-1:n-1:n<0||n===t.length-1?0:n+1;(s=t[r])==null||s.focus()}function Sve(e){return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-center justify-between gap-3 px-3 py-1.5 text-xs font-medium text-muted-foreground",children:[i.jsx("span",{children:"Agents"}),e.agentSelectionLocked?i.jsxs("span",{className:"inline-flex items-center gap-1","data-testid":"chat-agent-lock-state",children:[i.jsx(qae,{className:"h-3 w-3","aria-hidden":"true"}),"Bound to chat"]}):null]}),e.agents.length===0?i.jsxs("div",{className:"flex items-center gap-2 rounded-[var(--radius-md)] px-3 py-2 text-sm text-muted-foreground",children:[i.jsx(zo,{className:"h-4 w-4 shrink-0"}),i.jsx("span",{children:"Create or activate an agent before sending messages."})]}):e.agents.map(t=>{const n=e.activeAgentId===t.id,r=e.runtimeSelectionPending||e.newConversationSendInFlight||e.agentSelectionLocked&&!n||e.externalBound;return i.jsxs("div",{"data-testid":`chat-agent-option-${t.id}`,"data-selected":n?"true":void 0,className:q("flex min-h-10 items-center gap-1 rounded-[var(--radius-md)]",n&&"bg-[color:var(--surface-active)]"),children:[i.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":n,"aria-disabled":r||n,disabled:r&&!n,"data-chat-composer-menu-item":!0,className:"chat-composer-menu-row min-w-0 flex-1 disabled:cursor-default disabled:opacity-100",onClick:()=>e.onSelectAgent(t.id),children:[i.jsx(lc,{icon:t.icon,role:t.role,className:"h-4 w-4 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 flex-1 truncate text-left font-medium",children:of(t)}),e.agentSelectionLocked&&!n?i.jsx(qae,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground","aria-label":"Unavailable after chat starts"}):null]}),n&&e.showRuntimeControls!==!1?i.jsx(dQn,{agent:t,adapterModels:e.adapterModels,overrides:e.overrides,label:e.runtimeLabel,disabled:e.externalBound||e.newConversationSendInFlight,isLoading:e.isLoading,error:e.error,pending:e.runtimeSelectionPending,panelPlacement:e.runtimePanelPlacement,modelSelectRef:e.modelSelectRef,onChange:e.onChangeRuntime}):null]},t.id)})]})}function jve(e){return i.jsxs("button",{ref:e.buttonRef,type:"button","data-testid":"chat-agent-selector","aria-label":`Chat agent: ${e.label}`,"aria-expanded":e.expanded,disabled:e.disabled,className:q("chat-chip inline-flex max-w-[min(100%,16rem)] min-w-0 items-center gap-1.5 rounded-[var(--radius-md)] px-3 py-1.5 text-xs font-medium","transition-colors hover:bg-[color:var(--surface-active)] disabled:cursor-not-allowed disabled:opacity-60",e.expanded&&"bg-[color:var(--surface-active)]"),onClick:e.onClick,children:[e.agent?i.jsx(lc,{icon:e.agent.icon,role:e.agent.role,testId:"chat-agent-selector-icon",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):null,i.jsx("span",{className:"min-w-0 truncate",children:e.label})]})}const ume={sending:!1,stopping:!1,stopRequested:!1,stopAccepted:!1,conversationId:null},fme=new Map;function uQn(e,t){return`${e}:${t}`}function fQn(e,t){const n=uQn(e,t),r=fme.get(n);if(r)return r;const s={key:n,state:ume,listeners:new Set,abortController:null,streamFence:mme()};return fme.set(n,s),s}function Og(e,t){if(e){e.state={...e.state,...t};for(const n of e.listeners)n()}}function sie(e,t){return["run-debug-chat-session",e,t]}function iie(){var e,t;return((t=(e=globalThis.crypto)==null?void 0:e.randomUUID)==null?void 0:t.call(e))??`annotation-${Date.now()}-${Math.random().toString(36).slice(2)}`}function mQn(e){var t;return((t=e.body)==null?void 0:t.trim())||(e.role==="user"?"Annotation-only feedback":"")}function AQn(e){return e.transcript??[]}function $v(){}function aie(e,t){return e instanceof $o?e.status===t:!!(e&&typeof e=="object"&&"status"in e&&e.status===t)}const hQn="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",pQn=250,gQn=1e4;function mme(){return{generationId:null,attemptEpoch:null,lastCommittedRenderSeq:0,renderedBodyHash:hQn}}function oie(e,t){t.generationId&&(e.generationId=t.generationId),t.attemptEpoch!==void 0&&(e.attemptEpoch=t.attemptEpoch),t.generationSeq!==void 0&&(e.lastCommittedRenderSeq=t.generationSeq),t.bodyHash&&(e.renderedBodyHash=t.bodyHash)}function xQn(e,t){const n=RC(e);return t?n!==t:n===null}function J_e({organizationId:e,target:t,onReplaceTarget:n}){var Pe;const r=er(),{pushToast:s}=ws(),a=Kr(),o=t.kind==="run_debug_chat",l=t.kind==="run_debug_chat"&&t.autoSend,c=A.useMemo(()=>o?fQn(e,t.clientMutationId):null,[o,e,t.clientMutationId]),d=A.useSyncExternalStore(Re=>c?(c.listeners.add(Re),()=>{c.listeners.delete(Re),queueMicrotask(()=>{c.listeners.size===0&&!c.state.sending&&!c.abortController&&fme.delete(c.key)})}):()=>{},()=>(c==null?void 0:c.state)??ume,()=>(c==null?void 0:c.state)??ume),[u,f]=A.useState(t.body??""),[m,h]=A.useState(0),[p,x]=A.useState(t.projectId??null),[b,y]=A.useState(null),[w,k]=A.useState(null),[S,j]=A.useState(d.sending),[C,I]=A.useState(d.stopping),[N,M]=A.useState(!1),[E,_]=A.useState(null),[z,T]=A.useState([]),[$,B]=A.useState(""),[F,W]=A.useReducer(a1e,t.inlineAnnotations??[],N6),[Y,G]=A.useState(!1),[V,L]=A.useState(null),R=A.useRef(null),D=A.useRef(null),X=A.useRef(null),ee=A.useRef(null),se=A.useRef(null),ne=A.useRef(null),le=A.useRef(t.clientMutationId||iie()),ie=A.useRef(t),re=A.useRef(t.conversationId),de=A.useRef(null),Be=A.useRef(!1),ae=A.useRef(!1),Ee=A.useRef(mme()),he=A.useRef(null),_e=A.useRef(0),Ie=A.useRef([]),$e=A.useRef(null),ce=A.useRef(!1),Oe=A.useRef(null),Ye=A.useRef(t);ie.current=t,le.current=t.clientMutationId||le.current,A.useEffect(()=>{c&&(j(d.sending),I(d.stopping),d.conversationId&&(re.current=d.conversationId))},[c,d]),A.useEffect(()=>{var Wt;const Re=Ye.current;!(((Wt=he.current)==null?void 0:Wt.conversationId)===t.conversationId&&he.current.clientMutationId===t.clientMutationId&&Re.conversationId===null&&!!t.conversationId)&&(Re.conversationId!==t.conversationId||Re.clientMutationId!==t.clientMutationId)&&(T([]),B("")),Ye.current=t},[t.clientMutationId,t.conversationId]),A.useEffect(()=>{S||he.current||(re.current=t.conversationId??null)},[S,t.conversationId]),A.useEffect(()=>{if(t.kind==="run_feedback_chat"&&!(typeof window>"u"))try{window.localStorage.setItem(`rudder.run-feedback-draft:${e}:${t.agentId}`,JSON.stringify(t))}catch{}},[e,t]);const J=Ve({queryKey:U.agents.list(e),queryFn:()=>$n.list(e)}),qe=Ve({queryKey:U.projects.list(e),queryFn:()=>Wi.list(e)}),be=Ve({queryKey:U.health,queryFn:()=>EA.get()}),ot=Ve({queryKey:U.chats.detail(e,t.conversationId??"__run-feedback-draft__"),queryFn:()=>Zn.get(t.conversationId),enabled:!!t.conversationId,retry:(Re,Nt)=>!aie(Nt,404)&&Re<2}),ke=Ve({queryKey:U.chats.messages(e,t.conversationId??"__run-feedback-draft__"),queryFn:()=>Zn.listMessages(e,t.conversationId,{includeTranscript:!0}),enabled:!!t.conversationId}),Ce=Ve({queryKey:U.chats.queue(e,t.conversationId??"__run-feedback-draft__"),queryFn:()=>Zn.listQueue(t.conversationId),enabled:!!t.conversationId,refetchInterval:S?1e3:!1});A.useEffect(()=>{if(t.kind!=="run_debug_chat"||!t.conversationId||!Ce.data)return;if(RC(Ce.data)!==null){j(!0),Og(c,{sending:!0,conversationId:t.conversationId});return}d.sending&&(j(!1),Og(c,{sending:!1,stopping:!1}))},[c,d.sending,Ce.data,t.conversationId,t.kind]),A.useEffect(()=>{ke.data&&T(Re=>qk(Re,ke.data))},[ke.data]),A.useEffect(()=>{var Re;(Re=Oe.current)==null||Re.scrollIntoView({block:"end"})},[z,$]),A.useEffect(()=>{f(t.body??"")},[t.body]),A.useEffect(()=>{const Re=t.inlineAnnotations??[],Nt=DT(F),Wt=Re.map(ht=>{const{attachmentFileIndexes:Lt,ordinal:Mn,...Ln}=ht;return Ln}),Jt=JBn(t.clientMutationId),Ze=new Set(Re.map(ht=>ht.id)),Ae={...Object.fromEntries(Object.entries(F.pendingFilesByAnnotationId).filter(([ht])=>Ze.has(ht))),...Jt};JSON.stringify(Wt)===JSON.stringify(Nt)&&Object.keys(Jt).length===0||(W({type:"reset",annotations:Re,pendingFilesByAnnotationId:Ae}),G(Re.length>0))},[F,t.clientMutationId,t.inlineAnnotations]),A.useEffect(()=>{x(t.projectId??null)},[t.projectId]);const ue=ot.data,mt=A.useMemo(()=>jL(J.data),[J.data]),ut=t.conversationId?(ue==null?void 0:ue.preferredAgentId)??t.agentId:t.kind==="run_debug_chat"?t.preferredAgentId:t.agentId,ge=A.useMemo(()=>mt.find(Re=>Re.id===ut)??null,[ut,mt]),Le=A.useMemo(()=>(qe.data??[]).find(Re=>Re.id===p)??null,[p,qe.data]),rt=t.kind==="run_debug_chat"||!!(S||t.projectLocked||t.conversationId||z.some(Re=>Re.role==="user")),At=t.kind==="run_feedback_chat"||!!(S||t.conversationId||z.some(Re=>Re.role==="user")),Ue=F.annotations.length,Se=K4(F.annotations,Object.values(F.pendingFilesByAnnotationId).reduce((Re,Nt)=>Re+Nt.length,0)),Te=!F.annotations.some(Re=>Re.sourceHash==="pending")&&!Se&&bM(u,F),He=A.useCallback(Re=>{const Nt=ie.current,Wt=Nt.kind==="run_feedback_chat"?{...Nt,...Re,preferredAgentId:Nt.agentId}:{...Nt,...Re};ie.current=Wt,n(fs(Nt),Wt)},[n]);A.useEffect(()=>{t.kind==="run_feedback_chat"&&t.preferredAgentId&&t.preferredAgentId!==t.agentId&&He({preferredAgentId:t.agentId})},[t.agentId,t.kind,t.preferredAgentId,He]);const fe=A.useCallback(Re=>{const Nt=ie.current;if(Nt.conversationId!==Re)return!1;if(Nt.kind==="run_debug_chat")return _("This Debug Chat is no longer available. Open Ask agent again to retry."),!1;const Wt=iie();return le.current=Wt,re.current=null,T([]),B(""),y(null),k(null),He({conversationId:null,projectLocked:!1,clientMutationId:Wt,preferredAgentId:Nt.agentId,recoveryNotice:"The previous feedback chat is no longer available. Your draft was kept. Choose a project and send again."}),!0},[He]);A.useEffect(()=>{t.conversationId&&aie(ot.error,404)&&fe(t.conversationId)},[ot.error,fe,t.conversationId]);const je=A.useCallback(()=>{const Re=he.current;if(!Re)return!1;const Nt=ie.current;return Re.conversationId?Nt.conversationId===Re.conversationId:Nt.clientMutationId===Re.clientMutationId},[]),ye=A.useCallback(async()=>{const Re=Ie.current.splice(0),Nt=$e.current;if(Nt)for(const Wt of Re)await Nt(Wt)},[]),tt=A.useCallback(async(Re,Nt)=>{const Wt=Date.now()+gQn,Jt=U.chats.queue(e,Re);for(;Date.now()<Wt;){try{const Ze=await r.fetchQuery({queryKey:Jt,queryFn:()=>Zn.listQueue(Re),staleTime:0});if(r.setQueryData(Jt,Ze),xQn(Ze,Nt))return!0}catch{}await new Promise(Ze=>window.setTimeout(Ze,pQn))}return!1},[e,r]),me=A.useCallback(async()=>{var Ze;const Re=he.current,Nt=(Re==null?void 0:Re.conversationId)??re.current??d.conversationId,Wt=!!(c&&d.sending);if(!Nt||!S||C||!je()&&!Wt)return;const Jt=iie();Be.current=!0,I(!0),Og(c,{stopping:!0,stopRequested:!0,stopAccepted:!1}),M(!1),_(null);try{const Mt=await r.fetchQuery({queryKey:U.chats.queue(e,Nt),queryFn:()=>Zn.listQueue(Nt),staleTime:0});r.setQueryData(U.chats.queue(e,Nt),Mt);const Ae=(c==null?void 0:c.streamFence)??Ee.current,ht=Mt.activeGenerationId&&Mt.activeAttemptEpoch!==null&&Mt.activeAttemptEpoch!==void 0&&Mt.activeControlVersion!==null&&Mt.activeControlVersion!==void 0?{generationId:Mt.activeGenerationId,attemptEpoch:Mt.activeAttemptEpoch,controlVersion:Mt.activeControlVersion}:null,Lt={controlActionId:Jt,...ht?{expectedGenerationId:ht.generationId,expectedAttemptEpoch:ht.attemptEpoch,expectedControlVersion:ht.controlVersion}:{},lastCommittedRenderSeq:Ae.lastCommittedRenderSeq,renderedBodyHash:Ae.renderedBodyHash},Mn=await Zn.stopMessageStream(Nt,Lt);if(Mn.controlActionId!==Jt)throw new Error("Stop confirmation did not match this feedback stream.");Mn.stopped||["stopping","stop_requested","stopped","interrupted_unverified"].includes(Mn.disposition??"")?(ae.current=!0,Og(c,{stopAccepted:!0}),Ie.current=[],B(""),(Ze=(c==null?void 0:c.abortController)??de.current)==null||Ze.abort(),Mn.disposition==="stopped"||Mn.disposition==="interrupted_unverified"||await tt(Nt,Mn.generationId??(ht==null?void 0:ht.generationId)??null)?(I(!1),Og(c,{sending:!1,stopping:!1}),M(!1)):(I(!1),Og(c,{sending:!1,stopping:!1}),M(!0),_("Stop was accepted, but the final runtime state could not be confirmed yet."))):(Be.current=!1,await ye(),I(!1),Og(c,{stopping:!1,stopRequested:!1,stopAccepted:!1})),await Promise.allSettled([r.invalidateQueries({queryKey:U.chats.detail(e,Nt)}),r.invalidateQueries({queryKey:U.chats.messages(e,Nt)})])}catch(Mt){Be.current=!1,await ye(),I(!1),Og(c,{stopping:!1,stopRequested:!1,stopAccepted:!1}),M(!1),_(Mt instanceof Error?Mt.message:"Could not stop feedback.")}},[c,d,e,r,ye,S,C,je,tt]),ze=Re=>{if(rt)return;const Nt=Re||null;x(Nt),He({projectId:Nt})},De=A.useCallback(()=>{y(null),k(null)},[]),kt=A.useCallback(Re=>{const Nt=Re==="project"?ee.current:se.current;Nt&&k(Uk(Nt)),y(Re)},[]),gt=Re=>{At||!mt.some(Nt=>Nt.id===Re)||(He({preferredAgentId:Re}),De())};A.useEffect(()=>{if(!b)return;const Re=()=>{const Jt=b==="project"?ee.current:se.current;Jt&&k(Uk(Jt))},Nt=Jt=>{var Mt,Ae,ht;const Ze=Jt.target;Ze instanceof Node&&((Mt=X.current)!=null&&Mt.contains(Ze)||(Ae=ee.current)!=null&&Ae.contains(Ze)||(ht=se.current)!=null&&ht.contains(Ze)||De())},Wt=Jt=>{if(Jt.key!=="Escape")return;const Ze=b==="project"?ee.current:se.current;De(),requestAnimationFrame(()=>Ze==null?void 0:Ze.focus())};return Re(),window.addEventListener("resize",Re),window.addEventListener("scroll",Re,!0),document.addEventListener("pointerdown",Nt,!0),document.addEventListener("keydown",Wt),()=>{window.removeEventListener("resize",Re),window.removeEventListener("scroll",Re,!0),document.removeEventListener("pointerdown",Nt,!0),document.removeEventListener("keydown",Wt)}},[De,b]);const Ke=async()=>{var Ln;if(ce.current||S||C||N||!Te)return;const Re=ie.current,Nt=u.trim(),Wt=Gq(F),Jt=new Set(Wt.inlineAnnotations.map(Un=>Un.id));if(fH({annotations:Wt.inlineAnnotations,devServer:(Ln=be.data)==null?void 0:Ln.devServer,draftPersistence:"durable",pushToast:s}))return;ce.current=!0,Re.kind==="run_feedback_chat"&&Re.recoveryNotice&&He({recoveryNotice:null}),Re.kind==="run_debug_chat"&&Re.errorMessage&&He({errorMessage:null}),Re.kind==="run_debug_chat"&&f(""),j(!0),Og(c,{sending:!0,stopping:!1,stopRequested:!1,stopAccepted:!1}),I(!1),M(!1),Be.current=!1,ae.current=!1,Ee.current=mme(),_(null),B("");const Ze=_e.current+1;_e.current=Ze,he.current={conversationId:Re.conversationId??null,clientMutationId:Re.clientMutationId??le.current},Ie.current=[];const Mt=new AbortController;de.current=Mt,c&&(c.abortController=Mt,c.streamFence=Ee.current);const Ae=()=>_e.current===Ze&&je(),ht=async Un=>{if(!(!Ae()||ae.current)){if(Un.type==="ack"){oie(Ee.current,Un),re.current=Un.userMessage.conversationId,Og(c,{conversationId:Un.userMessage.conversationId,sending:!0}),!Re.conversationId&&he.current&&(he.current={...he.current,conversationId:Un.userMessage.conversationId}),T(Ct=>qk(Ct,[Un.userMessage]));for(const Ct of Jt)W({type:"delete",id:Ct});const mr=ie.current,bt=mr.inlineAnnotations.filter(Ct=>!Jt.has(Ct.id)),rn=Re.conversationId?{...mr,body:mr.body===Nt?"":mr.body,inlineAnnotations:bt}:mr.kind==="run_feedback_chat"?{...mr,conversationId:Un.userMessage.conversationId,projectLocked:!0,projectId:Re.projectId,body:mr.body===Nt?"":mr.body,inlineAnnotations:bt}:{...mr,conversationId:Un.userMessage.conversationId,body:mr.body===Nt?"":mr.body,inlineAnnotations:bt};if(He(rn),Re.kind==="run_debug_chat"&&(r.setQueryData(sie(e,Re.clientMutationId),{autoSendConsumed:!0,conversationId:Un.userMessage.conversationId}),f(""),h(Ct=>Ct+1)),G(bt.length>0),!Re.conversationId&&Re.kind==="run_feedback_chat")try{window.localStorage.setItem(`rudder.run-feedback-draft:${e}:${Re.agentId}`,JSON.stringify(rn))}catch{}}if(Un.type==="assistant_delta"&&(oie(Ee.current,Un),B(mr=>mr+Un.delta)),(Un.type==="assistant_state"||Un.type==="transcript_entry")&&oie(Ee.current,Un),Un.type==="final"&&(B(""),T(mr=>qk(mr,Un.messages))),Un.type==="error")throw new Error(Un.error)}};$e.current=ht;const Lt=async Un=>{if(!(!Ae()||ae.current)){if(Be.current&&!ae.current){Ie.current.push(Un);return}await ht(Un)}};let Mn=null;try{Re.conversationId?await Zn.sendMessageStream(Re.conversationId,Nt,{signal:Mt.signal,files:Wt.files,inlineAnnotations:Wt.inlineAnnotations,onEvent:Lt}):await Zn.sendFirstMessageStream(e,Nt,{signal:Mt.signal,preferredAgentId:Re.kind==="run_debug_chat"?Re.preferredAgentId:Re.agentId,issueCreationMode:"manual_approval",planMode:!1,modelOverride:null,effortOverride:null,contextLinks:Re.projectId?[{entityType:"project",entityId:Re.projectId}]:[],clientMutationId:le.current,files:Wt.files,inlineAnnotations:Wt.inlineAnnotations,onEvent:Lt}),Re.conversationId&&await Promise.all([r.invalidateQueries({queryKey:U.chats.detail(e,Re.conversationId)}),r.invalidateQueries({queryKey:U.chats.messages(e,Re.conversationId)})])}catch(Un){const mr=(Un instanceof DOMException||Un instanceof Error)&&Un.name==="AbortError";!(ae.current||(c==null?void 0:c.state.stopAccepted))&&(!mr||!Be.current)&&(Re.conversationId&&aie(Un,404)?fe(Re.conversationId):Mn=Re.kind==="run_debug_chat"?`${uH(Un)} Choose another agent or try again.`:uH(Un,"feedback"))}finally{const Un=ae.current;de.current=null,ce.current=!1,j(!1),Og(c,{sending:!1,stopping:!1,stopRequested:!1,stopAccepted:!1}),(c==null?void 0:c.abortController)===Mt&&(c.abortController=null),!Un&&!Be.current&&I(!1),(!Be.current||Un)&&($e.current=null,he.current=null,Ie.current=[],Be.current=!1),Mn&&(_(Mn),Re.kind==="run_debug_chat"&&(f(Nt),He({autoSend:!1,errorMessage:Mn})))}};A.useEffect(()=>{if(t.kind!=="run_debug_chat")return;const Re=r.getQueryData(sie(e,t.clientMutationId));!(Re!=null&&Re.conversationId)||t.conversationId===Re.conversationId&&!t.body&&!t.autoSend||(f(""),h(Nt=>Nt+1),He({conversationId:Re.conversationId,body:"",autoSend:!1}))},[l,e,r,t.body,t.clientMutationId,t.conversationId,t.kind,He]),A.useEffect(()=>{if(t.kind!=="run_debug_chat"||!l||J.isPending)return;const Re=sie(e,t.clientMutationId),Nt=r.getQueryData(Re);if(Nt!=null&&Nt.autoSendConsumed){const Wt=Nt.conversationId??re.current;He({autoSend:!1,conversationId:Wt??t.conversationId,body:Wt?"":t.body});return}if(r.setQueryData(Re,{autoSendConsumed:!0,conversationId:null}),He({autoSend:!1}),!ge){const Wt="The Run agent is unavailable. Choose another agent or try again.";_(Wt),He({autoSend:!1,errorMessage:Wt});return}Ke()},[J.isPending,l,ge,t.clientMutationId,t.kind]);const Je=z,wt=!!(o&&S&&t.conversationId&&RC(Ce.data)),Z=S&&!!re.current&&(je()||wt),Me=C||N?"stopping":Z?"stop":S?"sending":"send",lt=C||N||!S&&!Te||S&&!Z;return i.jsxs("div",{className:"flex h-full min-h-0 flex-col","data-testid":o?"run-debug-chat-panel":"run-feedback-chat-panel","data-debug-conversation-id":o?t.conversationId??"":void 0,"data-debug-runtime-sending":o?String(d.sending):void 0,"data-debug-queue-status":o?((Pe=Ce.data)==null?void 0:Pe.activeGenerationStatus)??"":void 0,children:[i.jsx("div",{className:"scrollbar-auto-hide min-h-0 flex-1 overflow-y-auto px-4 py-4","data-testid":"run-chat-messages-scroll",children:i.jsxs("div",{className:"mx-auto flex w-full max-w-3xl flex-col gap-4",children:[i.jsxs("div",{className:"flex items-center gap-2 border-b border-border/70 pb-3",children:[i.jsx(Si,{className:"h-4 w-4 text-muted-foreground","aria-hidden":"true"}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("div",{className:"truncate text-sm font-medium",children:o?"Debug Run":"Run feedback"}),i.jsx("div",{className:"truncate text-xs text-muted-foreground",children:(ge==null?void 0:ge.name)??t.agentId})]})]}),ue?i.jsx("div",{className:"text-xs text-muted-foreground",children:ue.title}):null,o&&S&&!t.conversationId&&t.body.trim()&&!z.some(Re=>Re.role==="user")?i.jsx("div",{className:"ml-6 rounded-lg border bg-muted/30 px-3 py-2 text-sm","data-testid":"run-chat-pending-message",children:i.jsx("div",{className:"whitespace-pre-wrap break-words",children:t.body})}):null,ue?Je.map(Re=>{const Nt=AQn(Re);return i.jsxs("div",{"data-testid":"run-feedback-chat-message",children:[Re.role==="assistant"&&Nt.length>0?i.jsx(J6,{entries:Nt,state:Re.status,generationTerminalReason:Re.generationTerminalReason,streamStartedAt:new Date(Re.createdAt),streamEndedAt:new Date(Re.updatedAt),assistantMessageBody:Re.body,showDeveloperDiagnostics:!1}):null,Re.role==="user"&&!Re.body.trim()?i.jsx("div",{className:"mb-2 text-xs text-muted-foreground",children:"Annotation-only feedback"}):null,i.jsx(Qk,{conversation:ue,message:Re,agents:J.data,decisionNote:"",onDecisionNoteChange:$v,decisionNoteMentions:[],onDecisionNoteMentionQueryChange:$v,onDecisionNoteInlineTokenClick:$v,onApprovalAction:$v,onIssueProposalChange:$v,onResolveOperationProposal:$v,onConvertToIssue:$v,actionPending:!1,onCopyMessageText:Wt=>{var Jt;return(Jt=navigator.clipboard)==null?void 0:Jt.writeText(Wt)},onOpenFile:$v,onSelectResponseAnnotation:Wt=>{Wt.surface==="agent_run_transcript"&&a(`/agents/${t.agentId}/runs/${Wt.sourceRunId}`)},skillReferences:[]})]},Re.id)}):Je.map(Re=>i.jsxs("div",{className:`rounded-lg border px-3 py-2 text-sm ${Re.role==="user"?"ml-6 bg-muted/30":"mr-6"}`,children:[i.jsx("div",{className:"mb-1 text-[10px] uppercase tracking-wide text-muted-foreground",children:Re.role}),i.jsx("div",{className:"whitespace-pre-wrap break-words",children:mQn(Re)})]},Re.id)),ue&&$?i.jsx("div",{"data-testid":"run-feedback-chat-streaming",children:i.jsx("div",{className:"max-w-3xl whitespace-pre-wrap break-words text-sm text-foreground",children:$})}):null,i.jsx("div",{ref:Oe,"data-testid":"run-chat-message-end"})]})}),E||(t.kind==="run_feedback_chat"?t.recoveryNotice:t.errorMessage)||Se?i.jsx("div",{role:"alert",className:"px-4 pb-2 text-sm text-destructive",children:E??(t.kind==="run_feedback_chat"?t.recoveryNotice:t.errorMessage)??Se}):null,i.jsxs("div",{className:"shrink-0 px-4 pb-4",children:[i.jsxs(mY,{ref:D,className:"mx-auto max-w-3xl",testId:"run-feedback-composer",children:[Ue>0?i.jsxs("div",{className:"mb-3 flex flex-col items-start gap-2",children:[i.jsx(Q2e,{annotations:F.annotations,pendingFilesByAnnotationId:F.pendingFilesByAnnotationId,open:Y,buttonRef:R,onOpenChange:Re=>{G(Re),Re&&L(null)},onClear:()=>{W({type:"clear"}),He({inlineAnnotations:[]})},onEdit:Re=>{ne.current=R.current,L(Re.id)},onDelete:Re=>{W({type:"delete",id:Re}),He({inlineAnnotations:F.annotations.filter(Nt=>Nt.id!==Re)})}}),V?(()=>{const Re=F.annotations.find(Wt=>Wt.id===V);if(!Re)return null;const Nt=ne.current;return i.jsx(ZG,{annotation:Re,ordinal:Re.ordinal,pendingFiles:F.pendingFilesByAnnotationId[Re.id]??[],showSelectedTextContext:!0,anchorRect:(Nt==null?void 0:Nt.getBoundingClientRect())??null,getAnchorRect:()=>(Nt==null?void 0:Nt.getBoundingClientRect())??null,boundaryRect:null,getBoundaryRect:()=>null,returnFocusRef:ne,validateSave:Wt=>i1e(F,Re.id,{comment:Wt.comment,attachmentIds:Wt.attachmentIds,files:Wt.pendingFiles}),onSave:({comment:Wt,pendingFiles:Jt,attachmentIds:Ze})=>{W({type:"replaceDraft",id:Re.id,comment:Wt,attachmentIds:Ze,files:Jt}),He({inlineAnnotations:F.annotations.map(Mt=>Mt.id===Re.id?{...Mt,comment:Wt,attachmentIds:Ze}:Mt)}),L(null)},onCancel:()=>L(null),onDelete:()=>{W({type:"delete",id:Re.id}),He({inlineAnnotations:F.annotations.filter(Wt=>Wt.id!==Re.id)}),L(null)}})})():null]}):null,i.jsx(AY,{value:u,onChange:Re=>{S||C||N||(f(Re),He({body:Re}))},placeholder:o?"Ask a follow-up…":"Add context for this feedback…",onSubmit:()=>void Ke()},o?m:void 0),i.jsxs(hY,{actions:i.jsx(pY,{mode:Me,stoppingComplete:N,ariaLabel:N?"Stop status pending":Me==="stop"?"Stop feedback":Me==="stopping"?"Stopping feedback":Me==="sending"?"Sending feedback":"Send feedback",disabled:lt,onClick:()=>{if(Me==="stop"){me();return}Me==="send"&&Ke()}}),children:[o?null:i.jsx(Dht,{project:Le,label:(Le==null?void 0:Le.name)??"No project",expanded:b==="project",disabled:rt||qe.isPending,buttonRef:ee,testId:"run-feedback-project-selector",iconTestId:"run-feedback-project-icon",clearTestId:"run-feedback-project-clear",onClick:()=>{b==="project"?De():kt("project")},onClear:()=>ze("")}),i.jsx(jve,{buttonRef:se,agent:ge,label:ge?of(ge):J.isPending?"Loading agents":"No agent",expanded:b==="agent",disabled:At||J.isPending,onClick:()=>{b==="agent"?De():kt("agent")}})]})]}),b&&w&&typeof document<"u"?ja.createPortal(i.jsx(yve,{menuRef:X,testId:`run-feedback-${b}-menu`,ariaLabel:b==="agent"?"Run feedback agent":"Run feedback project",position:w,onKeyDown:b==="agent"?Ove:void 0,children:b==="project"?i.jsxs(i.Fragment,{children:[i.jsx(Rht,{projects:qe.data??[],activeProjectId:p,onSelect:Re=>{ze(Re??""),De()}}),qe.isError?i.jsxs("div",{className:"mt-1 flex items-center justify-between gap-3 border-t border-[color:var(--border-soft)] px-3 py-2 text-xs",children:[i.jsx("span",{role:"alert",className:"text-destructive",children:"Projects could not be loaded."}),i.jsx("button",{type:"button","data-chat-composer-menu-item":!0,className:"font-medium text-foreground hover:underline disabled:text-muted-foreground disabled:no-underline",disabled:qe.isFetching,onClick:()=>void qe.refetch(),children:qe.isFetching?"Retrying...":"Retry"})]}):null]}):i.jsx(Sve,{agents:mt,activeAgentId:ut,agentSelectionLocked:At,runtimeSelectionPending:!1,newConversationSendInFlight:S&&!ue,externalBound:!1,adapterModels:null,overrides:{modelOverride:null,effortOverride:null},runtimeLabel:"",showRuntimeControls:!1,onSelectAgent:gt,onChangeRuntime:()=>{}})}),document.body):null]})]})}class lie extends Error{constructor(){super("Side Chat close was superseded by a newer generation."),this.name="ChatGenerationCloseSupersededError"}}class Xht{constructor(){ls(this,"activeByChatId",new Map);ls(this,"listenersByChatId",new Map);ls(this,"getSnapshot",t=>this.activeByChatId.get(t)===!0);ls(this,"subscribe",(t,n)=>{const r=this.listenersByChatId.get(t)??new Set;return r.add(n),this.listenersByChatId.set(t,r),()=>{r.delete(n),r.size===0&&this.listenersByChatId.delete(t)}})}setActive(t,n){if(this.getSnapshot(t)!==n){n?this.activeByChatId.set(t,!0):this.activeByChatId.delete(t);for(const r of this.listenersByChatId.get(t)??[])r()}}}const bQn=new Set,Ght={activeChatIds:bQn,streamDrafts:{},sendInFlightByChatId:{},isChatGenerationActive:()=>!1,setChatSendInFlight:()=>{},setStreamDraftForChat:()=>{},setStreamAbortController:()=>{},abortChatStream:()=>{},beginChatGeneration:()=>({epoch:0,conversationId:null}),tryBeginChatGeneration:()=>null,rememberChatGenerationConversation:()=>{},setChatGenerationConversation:()=>!1,isChatGenerationCurrent:()=>!1,isChatGenerationClosePending:()=>!1,releaseChatGenerationScope:()=>{},requestChatGenerationClose:()=>({epoch:0,conversationId:null}),resetChatGenerationClose:()=>{},clearChatGenerationConversation:()=>{},destroyChatGenerationConversation:async(e,t,n)=>{await n()}},Yht=A.createContext(Ght),Jht=A.createContext(Ght),yQn=new Xht,ept=A.createContext(yQn);function vQn({children:e}){const t=kL(),[n,r]=A.useState({}),[s,a]=A.useState({}),o=A.useRef(n),l=A.useRef(null);l.current||(l.current=new Xht);const c=l.current,d=A.useRef({}),u=A.useRef({}),f=A.useRef(0),m=A.useRef({}),h=A.useRef(null),p=A.useRef(null),x=A.useRef(0),b=A.useCallback(()=>{h.current!==null&&(window.clearTimeout(h.current),h.current=null),r(o.current)},[]),y=A.useCallback(R=>{if(R){b();return}if(h.current!==null)return;const D=Date.now()<x.current;h.current=window.setTimeout(()=>{h.current=null,D?A.startTransition(()=>r(o.current)):r(o.current)},D?200:50)},[b]);A.useEffect(()=>{const R=()=>{x.current=Date.now()+120,p.current!==null&&window.clearTimeout(p.current),p.current=window.setTimeout(()=>{p.current=null,b()},120)};return window.addEventListener("scroll",R,{capture:!0,passive:!0}),window.addEventListener("wheel",R,{capture:!0,passive:!0}),()=>{window.removeEventListener("scroll",R,!0),window.removeEventListener("wheel",R,!0),h.current!==null&&window.clearTimeout(h.current),p.current!==null&&window.clearTimeout(p.current)}},[b]);const w=A.useMemo(()=>new Set(Object.keys(n)),[n]),k=A.useCallback((R,D)=>{a(X=>pOn(X,R,D))},[]),S=A.useCallback((R,D)=>{const X=o.current,ee=X[R]??null,se=typeof D=="function"?D(ee):D,ne=gOn(X,R,se);if(ne===X)return;if(o.current=ne,c.setActive(R,se!==null),((ee==null?void 0:ee.state)!==(se==null?void 0:se.state)||ee===null!=(se===null))&&t.updateSummary(`chat:${R}`,{status:(se==null?void 0:se.state)??(ee?"completed":null)}),se===null&&ee){h.current!==null&&(window.clearTimeout(h.current),h.current=null),r(X),window.setTimeout(()=>r(o.current),0);return}const le=se===null||se.state==="failed"||se.state==="stopped";y(le)},[t,y,c]),j=A.useCallback((R,D)=>{if(D){d.current={...d.current,[R]:D};return}if(!(R in d.current))return;const{[R]:X,...ee}=d.current;d.current=ee},[]),C=A.useCallback(R=>{var D;(D=d.current[R])==null||D.abort()},[]),I=A.useCallback(R=>{const D=u.current[R];if(D)return D;const X={epoch:0,conversationId:null,closeRequested:!1,sendClaimed:!1};return u.current={...u.current,[R]:X},X},[]),N=A.useCallback((R,D)=>{const X=I(R),ee=X.closeRequested?null:X.conversationId;return X.epoch=++f.current,X.closeRequested=!1,X.sendClaimed=!0,X.conversationId=D??ee,{epoch:X.epoch,conversationId:X.conversationId}},[I]),M=A.useCallback((R,D)=>{const X=I(R);return X.sendClaimed&&!X.closeRequested?null:N(R,D)},[N,I]),E=A.useCallback((R,D)=>{const X=u.current[R];!X||X.closeRequested||(X.conversationId===null||X.conversationId===D)&&(X.conversationId=D)},[]),_=A.useCallback((R,D,X)=>{const ee=u.current[R];return!ee||ee.epoch!==D||ee.closeRequested?!1:(ee.conversationId=X,!0)},[]),z=A.useCallback((R,D)=>{const X=u.current[R];return!!(X&&X.epoch===D&&!X.closeRequested)},[]),T=A.useCallback((R,D)=>{const X=u.current[R];return!!(X!=null&&X.closeRequested&&(D===void 0||X.epoch===D))},[]),$=A.useCallback((R,D)=>{const X=u.current[R];if(!X||X.epoch!==D)return;const{[R]:ee,...se}=u.current;u.current=se},[]),B=A.useCallback((R,D)=>{const X=I(R);return D&&!X.conversationId&&(X.conversationId=D),X.epoch=++f.current,X.closeRequested=!0,X.sendClaimed=!1,{epoch:X.epoch,conversationId:X.conversationId}},[I]),F=A.useCallback((R,D)=>{const X=u.current[R];(X==null?void 0:X.epoch)===D&&(X.closeRequested=!1,X.sendClaimed=!1)},[]),W=A.useCallback((R,D)=>{const X=u.current[R];(X==null?void 0:X.conversationId)===D&&(X.conversationId=null)},[]),Y=A.useCallback((R,D,X)=>{const ee=m.current[R];if((ee==null?void 0:ee.conversationId)===D)return ee.promise;let se;return se=(async()=>{try{await X()}finally{const ne=m.current[R];if((ne==null?void 0:ne.promise)===se){const{[R]:le,...ie}=m.current;m.current=ie}}})(),m.current={...m.current,[R]:{conversationId:D,promise:se}},se},[]),G=A.useCallback(R=>!!(R&&c.getSnapshot(R)),[c]),V=A.useMemo(()=>({abortChatStream:C,beginChatGeneration:N,clearChatGenerationConversation:W,destroyChatGenerationConversation:Y,tryBeginChatGeneration:M,isChatGenerationActive:G,isChatGenerationCurrent:z,isChatGenerationClosePending:T,rememberChatGenerationConversation:E,releaseChatGenerationScope:$,requestChatGenerationClose:B,resetChatGenerationClose:F,setChatGenerationConversation:_,setChatSendInFlight:k,setStreamDraftForChat:S,setStreamAbortController:j}),[C,N,W,Y,M,G,z,T,E,$,B,F,_,k,j,S]),L=A.useMemo(()=>({activeChatIds:w,streamDrafts:n,sendInFlightByChatId:s,beginChatGeneration:N,tryBeginChatGeneration:M,clearChatGenerationConversation:W,destroyChatGenerationConversation:Y,isChatGenerationActive:G,isChatGenerationCurrent:z,isChatGenerationClosePending:T,rememberChatGenerationConversation:E,releaseChatGenerationScope:$,requestChatGenerationClose:B,resetChatGenerationClose:F,setChatGenerationConversation:_,setChatSendInFlight:k,setStreamDraftForChat:S,setStreamAbortController:j,abortChatStream:C}),[C,w,N,W,Y,G,z,T,E,$,s,B,F,_,k,j,S,n,M]);return i.jsx(ept.Provider,{value:c,children:i.jsx(Jht.Provider,{value:V,children:i.jsx(Yht.Provider,{value:L,children:i.jsx(aen,{children:e})})})})}function Cve(){return A.useContext(Yht)}function Nve(){return A.useContext(Jht)}function wQn(e){const t=A.useContext(ept);return A.useSyncExternalStore(n=>t.subscribe(e,n),()=>t.getSnapshot(e),()=>t.getSnapshot(e))}function tpt(e){return vN(e)}function kQn(e){const t=new Map;for(const n of xKe({orgUrlKey:e.orgUrlKey,organizationSkills:e.organizationSkills,pluginManagedSkillIds:e.pluginManagedSkillIds}))t.set(n.skillMarkdownTarget,n);for(const n of vN(e))t.set(n.skillMarkdownTarget,n);return[...t.values()]}function npt(e,t){const n=t.trim().toLowerCase();return n?e.filter(r=>r.searchText.includes(n)):e}function rpt(e){return[...e].reverse().find(t=>t.role==="assistant"&&t.kind==="message"&&t.status==="completed"&&!t.supersededAt)??null}function OQn(e){const t=e.findIndex(n=>{var r;return n.kind==="system_event"&&((r=n.structuredPayload)==null?void 0:r.eventType)==="side_chat_started"});return t>=0?e.slice(t+1):e}function spt(e,t=new Date){return(e==null?void 0:e.conversationKind)!=="side_chat"||e.sideChatState==="kept"?!1:e.sideChatState==="completed"||e.sideChatState==="expired"?!0:e.sideChatState!=="active"||!e.sideChatExpiresAt?!1:new Date(e.sideChatExpiresAt).getTime()<=t.getTime()}const cie=[];function SQn(e,t){if(!e)return null;const n=new Date(e).getTime()-t.getTime();if(n<=0)return"Expired · read-only";const r=Math.max(1,Math.ceil(n/6e4));return r<60?`${r}m left`:`${Math.floor(r/60)}h ${r%60}m left`}function jQn(e){return e.transcript??[]}function Fv(){}function CQn({organizationId:e,target:t,active:n=!0,onRegisterCloseHandler:r,onReplaceTarget:s,onSelectResponseAnnotation:a}){var Ls,Vt;const o=er(),{pushToast:l}=ws(),{sendInFlightByChatId:c,streamDrafts:d}=Cve(),{abortChatStream:u,clearChatGenerationConversation:f,destroyChatGenerationConversation:m,isChatGenerationClosePending:h,isChatGenerationCurrent:p,rememberChatGenerationConversation:x,requestChatGenerationClose:b,releaseChatGenerationScope:y,resetChatGenerationClose:w,setChatGenerationConversation:k,setChatSendInFlight:S,setStreamAbortController:j,setStreamDraftForChat:C,tryBeginChatGeneration:I}=Nve(),N=_ge(e,t),M=d[N]??null,E=!!c[N],[_,z]=A.useState(""),[T,$]=A.useState(null),[B,F]=A.useState(()=>new Date),[W,Y]=A.useState(null),[G,V]=A.useState(!1),[L,R]=A.useState(null),[D,X]=A.useState(!1),[ee,se]=A.useState(!1),[ne,le]=A.useState(""),[ie,re]=A.useState([]),[de,Be]=A.useReducer(a1e,t.inlineAnnotations??[],N6),[ae,Ee]=A.useState(!1),[he,_e]=A.useState(null),Ie=A.useRef(null),$e=A.useRef(null),ce=A.useRef(null),Oe=A.useRef(null),Ye=A.useRef(null),J=A.useRef(null),qe=A.useRef(null),be=A.useRef(!1),ot=A.useRef(t.conversationId),ke=A.useRef(N),Ce=A.useRef(null);ke.current!==N?(ke.current=N,ot.current=t.conversationId,Ce.current=null):ot.current=t.conversationId??ot.current;const ue=A.useCallback(()=>{Ce.current=null,j(N,null),S(N,!1),C(N,null)},[S,j,C,N]);A.useEffect(()=>{t.conversationId&&x(N,t.conversationId)},[x,N,t.conversationId]);const mt=A.useCallback(async()=>{const Pt=b(N,ot.current);u(N);const mn=Pt.conversationId;if(!mn){if(!h(N,Pt.epoch))throw new lie;return ue(),y(N,Pt.epoch),null}try{await m(N,mn,async()=>{await Zn.destroySideChat(mn)})}catch(Vn){throw h(N,Pt.epoch)?(ue(),Vn instanceof $o&&(Vn.status===404||Vn.status===409)?(f(N,mn),y(N,Pt.epoch),Vn):(w(N,Pt.epoch),Vn)):new lie}if(!h(N,Pt.epoch))throw new lie;return f(N,mn),ue(),y(N,Pt.epoch),mn},[u,f,ue,m,h,y,b,w,N]);A.useEffect(()=>(r(N,mt),()=>r(N,null)),[mt,r,N]),A.useEffect(()=>{if(!n&&!(M!==null))return;F(new Date);const mn=window.setInterval(()=>F(new Date),1e3);return()=>window.clearInterval(mn)},[n,M!==null]);const ut=Ve({queryKey:U.chats.detail(e,t.sourceConversationId),queryFn:()=>Zn.get(t.sourceConversationId)}),ge=Ve({queryKey:U.chats.messages(e,t.sourceConversationId),queryFn:()=>Zn.listMessages(e,t.sourceConversationId),enabled:!t.sourceMessageId||!t.sourcePreview}),Le=ge.data??[],rt=A.useMemo(()=>t.sourceMessageId?Le.find(Pt=>Pt.id===t.sourceMessageId)??null:rpt(Le),[Le,t.sourceMessageId]),At=t.sourceMessageId??(rt==null?void 0:rt.id)??null,Ue=t.sourcePreview??(rt==null?void 0:rt.body)??null,Se=Ve({queryKey:U.chats.detail(e,t.conversationId??"__side-chat-draft__"),queryFn:()=>Zn.get(t.conversationId),enabled:!!t.conversationId}),We=Ve({queryKey:U.chats.messages(e,t.conversationId??"__side-chat-draft__"),queryFn:()=>Zn.listMessages(e,t.conversationId,{includeTranscript:!0}),enabled:!!t.conversationId}),Te=Ve({queryKey:U.agents.list(e),queryFn:()=>$n.list(e)}),He=Ve({queryKey:U.organizations.detail(e),queryFn:()=>Hn.get(e)}),fe=Ve({queryKey:U.organizationSkills.list(e),queryFn:()=>qf.list(e)}),je=Se.data??null,ye=je??ut.data??null,tt=A.useMemo(()=>jL(Te.data),[Te.data]);A.useEffect(()=>{if(je||be.current||!ut.data)return;const Pt=ut.data.preferredAgentId,mn=tt.find(Vn=>Vn.id===Pt)??tt[0]??null;Y((mn==null?void 0:mn.id)??null),be.current=!0},[je,tt,ut.data]);const me=(je==null?void 0:je.preferredAgentId)??W??((Ls=ut.data)==null?void 0:Ls.preferredAgentId)??null,ze=me?tt.find(Pt=>Pt.id===me)??null:null,De=Ve({queryKey:U.agents.skills(me??"__none__"),queryFn:()=>$n.skills(me,e),enabled:!!me}),kt=A.useMemo(()=>{var Pt;return tpt({agent:ze,orgUrlKey:((Pt=He.data)==null?void 0:Pt.urlKey)??"organization",organizationSkills:fe.data,skillSnapshot:De.data})},[De.data,(Vt=He.data)==null?void 0:Vt.urlKey,fe.data,ze]),gt=A.useMemo(()=>npt(kt,ne),[kt,ne]),{activeRuntimeOverrides:Ke,adapterModelsQuery:Je,runtimeModelSelectRef:wt,runtimeSelectorRef:Z,setDraftRuntimeOverrides:Me}=Hht({selectedOrganizationId:e,selectedConversation:je,activeAgentId:me,activeAgent:ze,composerScopeKey:t.clientMutationId}),lt=OQn(We.data??[]),Re=(M!=null&&M.generationId?lt.find(Pt=>Pt.role==="assistant"&&Pt.generationId===M.generationId&&Pt.status!=="streaming")??null:null)?null:M,Nt=Re!=null&&Re.generationId?lt.filter(Pt=>Pt.role!=="assistant"||Pt.generationId!==Re.generationId):lt,Wt=!!(Re&&(!Re.userMessageId||!lt.some(Pt=>Pt.id===Re.userMessageId))),Jt=spt(je,B),Ze=Jt?"Expired · read-only":SQn(je==null?void 0:je.sideChatExpiresAt,B),Mt=Pt=>{o.setQueryData(U.chats.detail(e,Pt.id),Pt)},Ae=Pt=>{ze&&Me(Pt)},ht=Pt=>{je||Pt===me||tt.some(mn=>mn.id===Pt)&&(Me({modelOverride:null,effortOverride:null}),Y(Pt),se(!1),le(""))},Lt=A.useCallback(async Pt=>{const mn=Array.from(Pt).filter(Vn=>Vn.size>0);if(mn.length!==0)try{const Vn=await Promise.all(mn.map((lr,bs)=>bmt(lr,bs)));re(lr=>[...lr,...Vn]),$(null)}catch(Vn){$(Vn instanceof Error?Vn.message:"Could not stage this attachment.")}},[]),Mn=kut(Lt),{active:Ln,targetProps:Un}=f2e(Lt),mr=Pt=>{!Pt.skillRefLabel||!Pt.skillMarkdownTarget||(z(mn=>Age(mn,[`[${Pt.skillRefLabel}](${Pt.skillMarkdownTarget})`])),se(!1),le(""))},bt=(Pt,mn)=>{o.setQueryData(U.chats.messages(e,Pt),(Vn=[])=>qk(Vn,[mn]))},rn=async()=>{var nt;const Pt=_.trim();if(ie.length===0&&!bM(Pt,de)||E||h(N)||Jt||!At)return;const mn=[...ie],Vn=Gq(de,{fileIndexOffset:mn.length});if(fH({annotations:Vn.inlineAnnotations,devServer:(nt=o.getQueryData(U.health))==null?void 0:nt.devServer,draftPersistence:"memory",pushToast:l}))return;const lr=new Date,bs=Ce.current,Qs=(M==null?void 0:M.state)==="failed"?M:null,Pa=I(N,t.conversationId);if(!Pa)return;Ce.current=null;const Zi=Pa.epoch,na=`${N}:${lr.getTime()}:${Math.random().toString(36).slice(2)}`;let Xi=!1,Gi=!1,ra=bs,pt=!1;S(N,!0),$(null),z(""),C(N,{chatId:Pa.conversationId,streamKey:na,userBody:Pt,userFiles:mn,userCreatedAt:lr,userMessageId:bs,chatTurnId:(Qs==null?void 0:Qs.chatTurnId)??null,turnVariant:(Qs==null?void 0:Qs.turnVariant)??0,editedFromCreatedAt:(Qs==null?void 0:Qs.userCreatedAt)??null,body:"",generationId:null,attemptEpoch:null,lastCommittedRenderSeq:0,renderedBodyHash:vp,state:"streaming",createdAt:lr,transcript:[],replyingAgentId:me});let en=Pa.conversationId;const Kt=async Ot=>{await m(N,Ot,async()=>{await Zn.destroySideChat(Ot)}),f(N,Ot)};try{if(!en){const $t=await Zn.createSideChat(t.sourceConversationId,{sourceMessageId:At,clientMutationId:t.clientMutationId,preferredAgentId:me??void 0});if(!k(N,Zi,$t.id)||!p(N,Zi)){await Kt($t.id);return}en=$t.id,ot.current=$t.id,Mt($t),o.setQueryData(U.chats.messages(e,$t.id),[]),s(fs(t),{...t,sourceMessageId:At,sourcePreview:Ue,conversationId:$t.id})}if(!en||!p(N,Zi)){en&&await Kt(en);return}const Ot=new AbortController;if(j(N,Ot),await Zn.sendMessageStream(en,Pt,{signal:Ot.signal,editUserMessageId:bs,modelOverride:Ke.modelOverride,effortOverride:Ke.effortOverride,files:[...mn,...Vn.files],inlineAnnotations:Vn.inlineAnnotations,onEvent:async $t=>{if(p(N,Zi)){if($t.type==="ack"&&(Xi=!0,Me({modelOverride:null,effortOverride:null}),Gi=!0,ra=$t.userMessage.id,Ce.current=null,bt(en,$t.userMessage),C(N,Ut=>(Ut==null?void 0:Ut.streamKey)===na?{...Ut,chatId:en,generationId:$t.generationId??Ut.generationId,userBody:$t.userMessage.body,userCreatedAt:new Date($t.userMessage.createdAt),userMessageId:$t.userMessage.id,chatTurnId:$t.userMessage.chatTurnId??Ut.chatTurnId,turnVariant:$t.userMessage.turnVariant??Ut.turnVariant,attemptEpoch:$t.attemptEpoch??Ut.attemptEpoch??null,lastCommittedRenderSeq:$t.generationSeq??Ut.lastCommittedRenderSeq??0,renderedBodyHash:$t.bodyHash??Ut.renderedBodyHash??vp}:Ut),Be({type:"clear"}),re([]),Ee(!1),_e(null),s(fs({...t,conversationId:en}),{...t,sourceMessageId:At,sourcePreview:Ue,conversationId:en,inlineAnnotations:[]})),($t.type==="assistant_delta"||$t.type==="assistant_state"||$t.type==="transcript_entry")&&C(N,Ut=>LW(Ut,na,$t)),$t.type==="final"){pt=!0,Ce.current=null;for(const Ut of $t.messages)bt(en,Ut);C(N,Ut=>(Ut==null?void 0:Ut.streamKey)===na?null:Ut)}if($t.type==="error")throw!Xi&&$t.messageId&&(Xi=!0,ra=$t.messageId,Be({type:"clear"}),re([]),Ee(!1),_e(null),s(fs({...t,conversationId:en}),{...t,sourceMessageId:At,sourcePreview:Ue,conversationId:en,inlineAnnotations:[]})),new Error($t.error)}}}),!pt)throw new Error("Side Chat stream ended before a final response.");await Promise.all([o.invalidateQueries({queryKey:U.chats.detail(e,en)}),o.invalidateQueries({queryKey:U.chats.messages(e,en)})])}catch(Ot){if(!p(N,Zi))return;Xi?Gi&&en?(Ce.current=ra,z($t=>$t||Pt)):Ce.current=ra:(Ce.current=bs,z($t=>$t||Pt)),Xi&&en&&await Promise.all([o.invalidateQueries({queryKey:U.chats.detail(e,en)}),o.invalidateQueries({queryKey:U.chats.messages(e,en)})]).catch(()=>{}),C(N,$t=>($t==null?void 0:$t.streamKey)===na?{...$t,state:"failed"}:$t),$(uH(Ot,"side-chat"))}finally{p(N,Zi)&&(j(N,null),S(N,!1),y(N,Zi))}},sn=!((!t.sourceMessageId||!t.sourcePreview)&&ge.isPending)&&!At,St=Te.data,qt=Zht({agent:ze,runtime:(je==null?void 0:je.chatRuntime)??null,overrides:Ke,adapterModels:Je.data}),En=ze?of(ze):Te.isPending?"Loading agents":"No agent",Fn=G||ee,tn=A.useCallback(()=>{V(!1),se(!1),le("")},[]);A.useEffect(()=>{n||(tn(),R(null))},[n,tn]);const Is=A.useCallback(Pt=>{const mn=Pt==="agent"?Z.current??ce.current:ce.current;mn&&R(Uk(mn)),V(Pt==="agent"),se(Pt==="skill"),Pt!=="skill"&&le("")},[Z]);return A.useEffect(()=>{if(!Fn){R(null);return}const Pt=()=>{const mn=G?Z.current??ce.current:ce.current;mn&&R(Uk(mn))};return Pt(),window.addEventListener("resize",Pt),window.addEventListener("scroll",Pt,!0),()=>{window.removeEventListener("resize",Pt),window.removeEventListener("scroll",Pt,!0)}},[G,Fn,Z]),A.useEffect(()=>{if(!Fn)return;const Pt=Vn=>{var bs,Qs;const lr=Vn.target;lr instanceof Node&&(lr instanceof Element&&lr.closest("[data-chat-runtime-submenu]")||(bs=Oe.current)!=null&&bs.contains(lr)||(Qs=Z.current)!=null&&Qs.contains(lr)||tn())},mn=Vn=>{if(Vn.key!=="Escape")return;const lr=G,bs=ee;tn(),lr?requestAnimationFrame(()=>{var Qs;return(Qs=Z.current)==null?void 0:Qs.focus()}):bs&&requestAnimationFrame(()=>{var Qs;return(Qs=J.current)==null?void 0:Qs.focus()})};return document.addEventListener("pointerdown",Pt,!0),document.addEventListener("keydown",mn),()=>{document.removeEventListener("pointerdown",Pt,!0),document.removeEventListener("keydown",mn)}},[G,tn,Fn,Z,ee]),A.useEffect(()=>{G&&requestAnimationFrame(()=>{var Pt,mn;(mn=(Pt=Oe.current)==null?void 0:Pt.querySelector("[data-chat-composer-menu-item]"))==null||mn.focus()})},[G]),A.useEffect(()=>{ee&&requestAnimationFrame(()=>{var Pt;return(Pt=Ye.current)==null?void 0:Pt.focus()})},[ee]),i.jsxs("div",{className:"flex h-full min-h-0 flex-col","data-testid":"side-chat-panel-view",children:[i.jsx("div",{className:"scrollbar-auto-hide min-h-0 flex-1 overflow-y-auto px-4 py-4",children:i.jsxs("div",{className:"mx-auto flex w-full max-w-4xl flex-col gap-5",children:[Ze?i.jsx("div",{className:"flex justify-end",children:i.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground","data-testid":"side-chat-state",children:[i.jsx(y1,{className:"h-3 w-3"}),Ze]})}):null,sn?i.jsx("p",{className:"text-sm text-destructive",children:"The main chat needs a completed assistant response first."}):null,i.jsxs("div",{className:"flex min-h-[12rem] flex-col gap-5","data-testid":"side-chat-messages",children:[ye?Nt.map(Pt=>{const mn=jQn(Pt);return i.jsxs("div",{children:[Pt.role==="assistant"&&mn.length>0?i.jsx(J6,{entries:mn,state:Pt.status,generationTerminalReason:Pt.generationTerminalReason,streamStartedAt:new Date(Pt.createdAt),streamEndedAt:new Date(Pt.updatedAt),assistantMessageBody:Pt.body,showDeveloperDiagnostics:!1}):null,i.jsx(Qk,{conversation:ye,message:Pt,agents:St,decisionNote:"",onDecisionNoteChange:Fv,decisionNoteMentions:[],onDecisionNoteMentionQueryChange:Fv,onDecisionNoteInlineTokenClick:Fv,onApprovalAction:Fv,onIssueProposalChange:Fv,onResolveOperationProposal:Fv,onConvertToIssue:Fv,actionPending:!1,onCopyMessageText:Vn=>{var lr;return(lr=navigator.clipboard)==null?void 0:lr.writeText(Vn)},onOpenFile:Fv,onSelectResponseAnnotation:a,skillReferences:cie})]},Pt.id)}):null,Re&&ye?i.jsxs("div",{className:"flex flex-col gap-5","data-testid":"side-chat-streaming-reply",children:[Wt?i.jsx(WG,{body:Re.userBody,files:Re.userFiles,createdAt:Re.userCreatedAt,onCopyMessageText:Pt=>{var mn;return(mn=navigator.clipboard)==null?void 0:mn.writeText(Pt)},onEditDraftOnly:z,skillReferences:cie}):null,i.jsx(J6,{entries:Re.transcript,state:Re.state,streamStartedAt:Re.createdAt,assistantMessageBody:Re.body,showDeveloperDiagnostics:!1}),i.jsx(R2e,{body:Re.body,createdAt:Re.createdAt,state:Re.state,replyingAgentId:Re.replyingAgentId,conversation:ye,agents:St,onCopyMessageText:Pt=>{var mn;return(mn=navigator.clipboard)==null?void 0:mn.writeText(Pt)},skillReferences:cie})]}):null]})]})}),T?i.jsx("div",{role:"alert",className:"px-4 pb-2 text-sm text-destructive",children:T}):null,Jt?i.jsx("div",{className:"shrink-0 border-t border-[color:var(--border-soft)] px-4 py-3 text-sm text-muted-foreground","data-testid":"side-chat-read-only",children:"This Side Chat has expired and can no longer be edited. Close the tab to destroy it."}):i.jsxs("div",{className:"shrink-0 px-4 pb-4","data-testid":"side-chat-composer",children:[i.jsxs(mY,{ref:ce,fileDragActive:Ln,fileDropTargetProps:Un,className:"mx-auto max-w-4xl",testId:"side-chat-composer-file-drop-target",children:[Ln?i.jsx(m2e,{}):null,de.annotations.length>0?i.jsxs("div",{className:"mb-3 flex flex-col items-start gap-2",children:[i.jsx(Q2e,{annotations:de.annotations,pendingFilesByAnnotationId:de.pendingFilesByAnnotationId,open:ae,buttonRef:$e,onOpenChange:Pt=>{Ee(Pt),Pt&&_e(null)},onClear:()=>{Be({type:"clear"}),Ee(!1),_e(null)},onEdit:Pt=>{Ie.current=$e.current,_e(Pt.id)},onDelete:Pt=>{Be({type:"delete",id:Pt}),de.annotations.length===1&&Ee(!1),_e(mn=>mn===Pt?null:mn)}}),he?(()=>{const Pt=de.annotations.find(lr=>lr.id===he);if(!Pt)return null;const mn=Ie.current,Vn=(mn==null?void 0:mn.closest('[data-testid="side-chat-panel-view"]'))??null;return i.jsx(ZG,{annotation:Pt,ordinal:Pt.ordinal,pendingFiles:de.pendingFilesByAnnotationId[Pt.id]??[],showSelectedTextContext:!0,anchorRect:(mn==null?void 0:mn.getBoundingClientRect())??null,getAnchorRect:()=>mn!=null&&mn.isConnected?mn.getBoundingClientRect():null,boundaryRect:(Vn==null?void 0:Vn.getBoundingClientRect())??null,getBoundaryRect:()=>Vn!=null&&Vn.isConnected?Vn.getBoundingClientRect():null,returnFocusRef:Ie,validateSave:lr=>i1e(de,Pt.id,{comment:lr.comment,attachmentIds:lr.attachmentIds,files:lr.pendingFiles}),onSave:({comment:lr,pendingFiles:bs,attachmentIds:Qs})=>{Be({type:"replaceDraft",id:Pt.id,comment:lr,attachmentIds:Qs,files:bs}),_e(null)},onCancel:()=>_e(null),onDelete:()=>{Be({type:"delete",id:Pt.id}),_e(null)}})})():null]}):null,ie.length>0?i.jsx("div",{"data-testid":"side-chat-pending-attachments",className:"mb-2.5 flex flex-wrap gap-2 px-3",children:ie.map(Pt=>{const mn=e8(Pt);return i.jsx("div",{"data-testid":"side-chat-pending-attachment",className:"max-w-full",children:i.jsx(i5,{file:Pt,onRemove:()=>re(Vn=>Vn.filter(lr=>e8(lr)!==mn))})},mn)})}):null,i.jsx(AY,{value:_,onChange:z,onPasteCapture:Mn,scrollTestId:"side-chat-composer-editor-scroll",placeholder:"Ask a focused follow-up…",onSubmit:()=>void rn()}),i.jsxs(hY,{testId:"side-chat-composer-toolbar",actions:i.jsx(pY,{mode:E?"sending":"send",ariaLabel:E?"Sending Side Chat message":"Send Side Chat message",disabled:ie.length===0&&!bM(_,de)||E||!me||sn,onClick:()=>void rn()}),children:[i.jsx(Cht,{open:D,onOpenChange:X,onAddFiles:()=>{var Pt;return(Pt=qe.current)==null?void 0:Pt.click()}}),i.jsx(jve,{buttonRef:Z,agent:ze,label:En,expanded:G,disabled:Te.isPending,onClick:()=>{if(G){tn();return}Is("agent")}}),i.jsx(Nht,{open:ee,buttonRef:J,onClick:()=>{if(ee){tn();return}Is("skill")}})]})]}),Fn&&L&&typeof document<"u"?ja.createPortal(i.jsxs(yve,{menuRef:Oe,testId:G?"side-chat-agent-menu":"side-chat-skill-menu",ariaLabel:G?"Side Chat agent":"Side Chat skills",position:L,onKeyDown:G?Ove:void 0,children:[G?i.jsx(Sve,{agents:tt,activeAgentId:me??"",agentSelectionLocked:!!je,runtimeSelectionPending:!1,newConversationSendInFlight:E&&!je,externalBound:!1,adapterModels:Je.data,overrides:Ke,runtimeLabel:qt,isLoading:Je.isPending,error:Je.error,runtimePanelPlacement:"above",modelSelectRef:wt,onSelectAgent:ht,onChangeRuntime:Ae}):null,ee?i.jsx(Iht,{pending:De.isPending||fe.isPending,skills:kt,filteredSkills:gt,searchQuery:ne,searchInputRef:Ye,onSearchQueryChange:le,onSelect:mr}):null]}),document.body):null,i.jsx("input",{ref:qe,type:"file",multiple:!0,className:"hidden",onChange:Pt=>{Lt(Pt.currentTarget.files??[]),Pt.currentTarget.value=""}})]})]})}function Ive(e){return e.trim().replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()}function NQn(e){const t=Ive(e);return t==="failed"||t==="error"?"border-destructive/30 bg-destructive/10 text-destructive":t==="running"||t==="in_progress"?"border-cyan-500/25 bg-cyan-500/10 text-cyan-700 dark:text-cyan-300":"border-border/60 bg-[color:var(--surface-active)] text-muted-foreground"}function IQn(e){const t=Ive(e).replace(/_/g," ");return t?t.charAt(0).toUpperCase()+t.slice(1):"Unknown"}function PQn({entries:e,response:t,running:n,loading:r,error:s,onRetry:a}){return e.length>0?i.jsxs(i.Fragment,{children:[i.jsx(M1,{entries:e,mode:"nice",density:"compact",streaming:n,collapseStdout:!0,presentation:"chat",hiddenAssistantMessageText:t}),s?i.jsx("p",{role:"alert",className:"mt-2 text-xs text-destructive",children:"Could not refresh the transcript. Showing the last loaded content."}):null]}):r?i.jsxs("div",{className:"inline-flex items-center gap-2 py-2 text-sm text-muted-foreground",role:"status",children:[i.jsx(fn,{className:"size-4 animate-spin","aria-hidden":!0}),"Loading transcript..."]}):s?i.jsxs("div",{role:"alert",className:"rounded-[var(--radius-sm)] border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:[i.jsx("p",{children:"Could not load the sub-agent transcript."}),i.jsx(oe,{type:"button",variant:"ghost",size:"xs",className:"mt-1 h-7 px-0 text-destructive hover:bg-transparent hover:text-destructive",onClick:a,children:"Retry"})]}):i.jsx("p",{className:"py-2 text-sm leading-6 text-muted-foreground",children:"No transcript entries were captured for this sub-agent."})}function TQn({target:e}){var h,p,x;const t=Ve({queryKey:["chat-subagent-live-manifest",e.conversationId,e.threadId],queryFn:()=>Zn.getWorkManifest(e.conversationId),enabled:!!e.conversationId,refetchInterval:b=>{var k;const y=(k=b.state.data)==null?void 0:k.subagents,w=[...(y==null?void 0:y.active)??[],...(y==null?void 0:y.done)??[]].find(S=>S.threadId===e.threadId);return(w==null?void 0:w.state)==="active"?2e3:!1}}),n=[...((h=t.data)==null?void 0:h.subagents.active)??[],...((p=t.data)==null?void 0:p.subagents.done)??[]].find(b=>b.threadId===e.threadId),r=(n==null?void 0:n.sourceMessageId)??e.sourceMessageId,s=(n==null?void 0:n.runId)??e.runId??null,a=Ve({queryKey:["chat-subagent-live-transcript",e.conversationId,r,e.threadId,n==null?void 0:n.status,n==null?void 0:n.updatedAt],queryFn:()=>Zn.getMessageTranscript(e.conversationId,r),enabled:!!(e.conversationId&&r),refetchInterval:(n==null?void 0:n.state)==="active"?2e3:!1}),o=Ve({queryKey:s?U.runDetail(s):["agent-run","none"],queryFn:()=>xo.get(s),enabled:!!s}),l=a.data?zUe(a.data.transcript,{sourceMessageId:a.data.messageId,runId:(n==null?void 0:n.runId)??null,sourceActive:(n==null?void 0:n.state)==="active",senderLabel:n==null?void 0:n.senderLabel}).find(b=>b.threadId===e.threadId):null,c={...e,senderLabel:(n==null?void 0:n.senderLabel)??e.senderLabel,status:(n==null?void 0:n.status)??(l==null?void 0:l.status)??e.status,response:(l==null?void 0:l.response)??e.response,entries:(l==null?void 0:l.entries)??e.entries,sourceMessageId:(n==null?void 0:n.sourceMessageId)??e.sourceMessageId},d=c.response??((x=[...c.entries].reverse().find(b=>b.kind==="assistant"))==null?void 0:x.text)??null,u=(n==null?void 0:n.state)==="active"||["running","in_progress","pending","queued","started"].includes(Ive(c.status)),f=!!(e.conversationId&&r)&&a.isPending&&c.entries.length===0,m=o.data?`/agents/${o.data.agentId}/runs/${o.data.id}`:null;return i.jsxs("div",{className:"scrollbar-auto-hide h-full min-h-0 overflow-y-auto","data-testid":"chat-side-panel-subagent-view","data-subagent-thread-id":c.threadId,children:[i.jsxs("div",{className:"border-b border-border/45 px-4 py-3",children:[i.jsxs("div",{className:"flex items-center gap-2.5",children:[i.jsx("img",{src:CE(c.avatarSeed),alt:"",className:"h-8 w-8 shrink-0 rounded-full object-cover ring-1 ring-border/60"}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("div",{className:"truncate text-sm font-semibold text-foreground",children:c.label}),i.jsx("div",{className:"truncate text-xs text-muted-foreground",title:c.threadId,children:c.threadId})]}),i.jsx("span",{className:q("rounded-[var(--radius-sm)] border px-2 py-0.5 text-[11px]",NQn(c.status)),children:IQn(c.status)})]}),c.model||c.reasoningEffort?i.jsxs("div",{className:"mt-2 flex flex-wrap gap-x-3 gap-y-1 pl-[2.625rem] text-[11px] text-muted-foreground",children:[c.model?i.jsx("span",{children:c.model}):null,c.reasoningEffort?i.jsxs("span",{children:[c.reasoningEffort," reasoning"]}):null,i.jsx("span",{children:"Read only"})]}):i.jsx("div",{className:"mt-2 pl-[2.625rem] text-[11px] text-muted-foreground",children:"Read only"})]}),i.jsxs("div",{className:"space-y-5 px-4 py-4",children:[i.jsxs("section",{"aria-label":"Main agent message",children:[i.jsx("div",{className:"mb-1.5 text-right text-xs font-medium text-muted-foreground",children:c.senderLabel}),i.jsx("div",{className:"ml-auto w-fit max-w-[88%] rounded-[var(--radius-xl)] bg-[color:var(--surface-active)] px-3.5 py-2.5 text-sm leading-6 text-foreground shadow-[var(--shadow-sm)]",children:i.jsx(Ya,{copyMarkdownOnCopy:!0,children:c.prompt})})]}),i.jsxs("section",{"aria-label":"Sub-agent transcript",children:[i.jsxs("div",{className:"mb-2 flex min-h-7 items-center gap-2 text-[11px] text-muted-foreground",children:[i.jsx("span",{className:"h-px min-w-4 flex-1 bg-border/45","aria-hidden":!0}),i.jsx("span",{children:u?"Working":"Transcript"}),i.jsx("span",{className:"h-px min-w-4 flex-1 bg-border/45","aria-hidden":!0}),m?i.jsx(oe,{asChild:!0,variant:"ghost",size:"xs",className:"h-7 shrink-0 gap-1.5 px-2 text-xs",children:i.jsxs(gn,{to:m,children:[i.jsx(skt,{className:"size-3.5","aria-hidden":!0}),"View run"]})}):s&&o.isPending?i.jsxs("span",{className:"inline-flex h-7 shrink-0 items-center gap-1.5 px-2",role:"status",children:[i.jsx(fn,{className:"size-3.5 animate-spin","aria-hidden":!0}),"Loading run"]}):null]}),i.jsx(PQn,{entries:c.entries,response:d,running:u,loading:f,error:a.isError,onRetry:()=>void a.refetch()}),s&&o.isError?i.jsxs("div",{role:"alert",className:"mt-2 flex flex-wrap items-center gap-2 text-xs text-destructive",children:[i.jsx("span",{children:"Could not load the linked Agent Run."}),i.jsx(oe,{type:"button",variant:"ghost",size:"xs",className:"h-7 px-1.5 text-destructive hover:text-destructive",onClick:()=>void o.refetch(),children:"Retry"})]}):null]}),i.jsxs("section",{"aria-label":"Sub-agent response",children:[i.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[i.jsx("img",{src:CE(c.avatarSeed),alt:"",className:"h-6 w-6 shrink-0 rounded-full object-cover ring-1 ring-border/60"}),i.jsx("span",{className:"text-xs font-semibold text-foreground",children:c.label})]}),d?i.jsx("div",{className:"max-w-[72ch] text-sm leading-6 text-foreground",children:i.jsx(Ya,{copyMarkdownOnCopy:!0,enableCodeBlockCopy:!0,children:d})}):i.jsx("p",{className:"text-sm leading-6 text-muted-foreground",children:u?"The sub-agent is still working.":"No response was captured for this sub-agent."})]})]})]})}function _Qn(e){const t=Date.parse(e);if(!Number.isFinite(t))return"";const n=Math.max(0,Math.round((Date.now()-t)/1e3));if(n<60)return"now";const r=Math.round(n/60);if(r<60)return`${r}m ago`;const s=Math.round(r/60);return s<24?`${s}h ago`:`${Math.round(s/24)}d ago`}function MQn(e){return e==="failed"?"Failed":e==="interrupted"?"Interrupted":e==="cancelled"?"Cancelled":e==="stopped"?"Stopped":null}function EQn({item:e,loading:t,onOpen:n}){const r=MQn(e.status);return i.jsxs("button",{type:"button",className:"group flex min-h-12 w-full min-w-0 items-center gap-3 rounded-[var(--radius-sm)] px-1.5 py-2 text-left transition-colors hover:bg-[color:var(--surface-active)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/30",onClick:n,title:e.label,"data-testid":`chat-side-panel-subagent-row-${e.threadId}`,children:[i.jsxs("span",{className:"relative inline-flex size-8 shrink-0",children:[i.jsx("img",{src:CE(e.avatarSeed),alt:"",className:q("size-8 rounded-full object-cover ring-1 ring-border/60",e.status==="failed"||e.status==="interrupted"?"ring-destructive/50":e.state==="active"?"ring-cyan-500/45":"ring-border/60")}),e.state==="active"?i.jsx("span",{className:"absolute -bottom-px -right-px size-2 rounded-full bg-cyan-500 ring-2 ring-background","aria-label":"Active"}):null]}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"block truncate text-sm font-medium text-foreground",children:e.label}),r?i.jsx("span",{className:"block truncate text-[11px] leading-4 text-destructive",children:r}):null]}),t?i.jsx(fn,{className:"size-3.5 shrink-0 animate-spin text-muted-foreground","aria-label":"Loading subagent"}):i.jsx("time",{dateTime:e.updatedAt,title:new Date(e.updatedAt).toLocaleString(),className:"shrink-0 text-xs tabular-nums text-muted-foreground",children:_Qn(e.updatedAt)})]})}function eMe({label:e,items:t,empty:n,loadingThreadId:r,loadError:s,onOpen:a}){return i.jsxs("section",{"aria-label":e,children:[i.jsxs("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:[e," · ",t.length]}),t.length===0?i.jsx("p",{className:"py-2 text-sm text-muted-foreground",children:n}):i.jsx("div",{className:"space-y-0.5",role:"list",children:t.map(o=>i.jsxs("div",{role:"listitem",children:[i.jsx(EQn,{item:o,loading:r===o.threadId,onOpen:()=>a(o)}),(s==null?void 0:s.threadId)===o.threadId?i.jsxs("div",{role:"alert",className:"ml-11 rounded-[var(--radius-sm)] border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:[i.jsx("p",{children:"Could not load sub-agent details."}),i.jsx("p",{className:"mt-0.5 text-[11px] opacity-80",children:s.message}),i.jsx(oe,{type:"button",variant:"ghost",size:"xs",className:"mt-1 h-7 px-0 text-destructive hover:bg-transparent hover:text-destructive",onClick:()=>a(o),children:"Retry"})]}):null]},o.threadId))})]})}function DQn({organizationId:e,target:t}){var f;const n=Qm(),{pushToast:r}=ws(),[s,a]=A.useState(null),[o,l]=A.useState(null),c=Ve({queryKey:U.chats.workManifest(e,t.conversationId),queryFn:()=>Zn.getWorkManifest(t.conversationId),refetchInterval:m=>{var h;return(((h=m.state.data)==null?void 0:h.subagents.active.length)??0)>0?2e3:!1}}),d=((f=c.data)==null?void 0:f.subagents)??{active:[],done:[]},u=async m=>{if(!s){a(m.threadId),l(null);try{const h=await Zn.getMessageTranscript(t.conversationId,m.sourceMessageId),p=zUe(h.transcript,{sourceMessageId:m.sourceMessageId,runId:m.runId,sourceActive:m.state==="active"}).find(x=>x.threadId===m.threadId);if(!p)throw new Error("The latest subagent evidence is not available.");n.openTarget({kind:"subagent",callId:p.callId,threadId:p.threadId,avatarSeed:p.avatarSeed,label:m.label,senderLabel:m.senderLabel??"Main agent",prompt:p.prompt,model:p.model,reasoningEffort:p.reasoningEffort,status:m.status,response:p.response,entries:p.entries,conversationId:t.conversationId,sourceMessageId:m.sourceMessageId,runId:m.runId})}catch(h){const p=h instanceof Error?h.message:"Try again.";l({threadId:m.threadId,message:p}),r({title:"Failed to load subagent",body:p,tone:"error"})}finally{a(null)}}};return c.isPending?i.jsx("div",{className:"grid h-full place-items-center","data-testid":"chat-side-panel-subagents-view",children:i.jsx(fn,{className:"size-5 animate-spin text-muted-foreground","aria-label":"Loading subagents"})}):c.isError?i.jsx("div",{className:"p-4","data-testid":"chat-side-panel-subagents-view",children:i.jsx("div",{role:"alert",className:"rounded-[var(--radius-md)] border border-destructive/30 bg-destructive/10 px-3 py-3 text-sm text-destructive",children:c.error instanceof Error?c.error.message:"Could not load subagents."})}):i.jsx("div",{className:"scrollbar-auto-hide h-full min-h-0 overflow-y-auto px-4 py-4","data-testid":"chat-side-panel-subagents-view",children:i.jsxs("div",{className:"space-y-8",children:[i.jsx(eMe,{label:"Active",items:d.active,empty:"No active subagents",loadingThreadId:s,loadError:o,onOpen:m=>void u(m)}),i.jsx(eMe,{label:"Done",items:d.done,empty:"No completed subagents",loadingThreadId:s,loadError:o,onOpen:m=>void u(m)})]})})}function tMe(e){return e instanceof Error&&e.message.replace(/^Error invoking remote method '[^']+':\s*/u,"").replace(/^Error:\s*/u,"").trim()||"Terminal failed to start."}function RQn({active:e,target:t}){const n=A.useRef(null),r=A.useRef(null),s=A.useRef(null),a=A.useRef(0),o=A.useRef(!1),l=A.useRef(e),[c,d]=A.useState("starting"),[u,f]=A.useState(null),[m,h]=A.useState(0),p=A.useCallback(async()=>{var S;const x=(S=_n())==null?void 0:S.terminal,b=r.current,y=s.current;if(!(x!=null&&x.supported)){d("failed"),f("Terminal is available only in Rudder Desktop.");return}if(!b||!y)return;if(!t.agentId){d("failed"),f("Select an Agent for this Chat before starting a terminal.");return}if(!l.current||o.current)return;const w=y.proposeDimensions();if(!w||w.cols<=2||w.rows<=1)return;y.fit(),o.current=!0;const k=++a.current;d("starting"),f(null),b.reset();try{const j=await x.create({orgId:t.organizationId,agentId:t.agentId,sessionId:t.sessionId,cols:Math.max(2,b.cols),rows:Math.max(1,b.rows)});if(k!==a.current)return;j.replay&&b.write(j.replay),d(j.status==="running"?"running":"exited"),l.current&&b.focus()}catch(j){if(k!==a.current)return;d("failed"),f(tMe(j))}},[t.agentId,t.organizationId,t.sessionId]);return A.useEffect(()=>{var z;const x=n.current,b=(z=_n())==null?void 0:z.terminal;if(!x||!(b!=null&&b.supported)){d("failed"),f("Terminal is available only in Rudder Desktop.");return}d("starting"),f(null);let y=!1,w=null,k=null,S,j,C,I,N,M;const E=()=>{a.current+=1,M!==void 0&&cancelAnimationFrame(M),N==null||N.disconnect(),S==null||S.dispose(),j==null||j.dispose(),C==null||C(),I==null||I(),k==null||k.dispose(),w==null||w.dispose(),o.current=!1,r.current=null,s.current=null,M=void 0,N=void 0,S=void 0,j=void 0,C=void 0,I=void 0,k=null,w=null};return(async()=>{const[{Terminal:T},{FitAddon:$}]=await Promise.all([on(()=>import("./xterm-8vrqRuWm.js").then(W=>W.x),[]),on(()=>import("./addon-fit-DCRNyXYv.js").then(W=>W.a),[])]);if(y)return;w=new T({cursorBlink:!0,convertEol:!1,fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:13,lineHeight:1.25,scrollback:5e3,theme:{background:"#111315",foreground:"#e7e9ea",cursor:"#f4f4f5",selectionBackground:"#3f4650"}}),k=new $;const B=w,F=k;B.loadAddon(F),B.open(x),r.current=B,s.current=F,S=B.onData(W=>void b.input(t.sessionId,W).catch(()=>{})),j=B.onResize(({cols:W,rows:Y})=>void b.resize(t.sessionId,W,Y).catch(()=>{})),C=b.onOutput(W=>{W.sessionId===t.sessionId&&B.write(W.data)}),I=b.onExit(W=>{W.sessionId===t.sessionId&&(d(W.error?"failed":"exited"),f(W.error))}),N=new ResizeObserver(()=>{F.fit(),l.current&&!o.current&&p()}),N.observe(x),M=requestAnimationFrame(()=>{l.current&&p()})})().catch(T=>{y||(E(),d("failed"),f(tMe(T)))}),()=>{y=!0,E()}},[m,p,t.sessionId]),A.useEffect(()=>{if(l.current=e,!e)return;const x=requestAnimationFrame(()=>{var b,y;(b=s.current)==null||b.fit(),o.current||p(),(y=r.current)==null||y.focus()});return()=>cancelAnimationFrame(x)},[e,p]),i.jsxs("div",{className:"relative h-full min-h-0 bg-[#111315]","data-testid":"terminal-panel-view",children:[i.jsx("div",{className:"h-full min-h-0 min-w-0 p-2",children:i.jsx("div",{ref:n,className:"h-full min-h-0 min-w-0 w-full overflow-hidden","data-testid":"terminal-xterm-host"})}),c!=="running"?i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-[#111315]/95 px-6",children:i.jsxs("div",{className:"max-w-xs text-center text-zinc-200",children:[i.jsx(Dh,{className:"mx-auto h-7 w-7 text-zinc-500","aria-hidden":!0}),i.jsx("h3",{className:"mt-3 text-sm font-semibold",children:c==="starting"?"Starting terminal":c==="exited"?"Shell exited":"Terminal unavailable"}),u?i.jsx("p",{className:"mt-2 text-xs leading-5 text-zinc-400",children:u}):null,c!=="starting"?i.jsxs(oe,{type:"button",size:"sm",variant:"outline",className:"mt-4 border-zinc-700 bg-zinc-900 text-zinc-100 hover:bg-zinc-800",onClick:()=>{o.current=!1,h(x=>x+1)},children:[i.jsx(A0,{className:"h-3.5 w-3.5"}),"Restart terminal"]}):null]})}):null]})}function GS(e){const t=e.split("/").filter(Boolean),n=[];for(let r=0;r<t.length-1;r+=1)n.push(t.slice(0,r+1).join("/"));return new Set(n)}function ipt(e){const t=e.split("/").filter(Boolean),n=[];for(let r=0;r<t.length;r+=1)n.push(t.slice(0,r+1).join("/"));return new Set(n)}function Jl(e){const t=(e==null?void 0:e.trim())??"";return t.length>0?t:null}const apt="rudder.workspace.launchTargetId",opt="rudder.workspace.unsupportedFileLaunchTargetId",LQn="rudder.workspace.openFileTabs",zQn=["cursor","vscode","windsurf","zed","webstorm","intellij","xcode","terminal","warp","commandPrompt","powershell","finder"],$Qn={fileTarget:!0,id:"defaultApp",label:"Default app",kind:"app"};function Pve(e){return zQn.includes(e)}function FQn(e){return e.kind==="ide"&&e.id!=="xcode"}function iw(e){return"fileTarget"in e}function TE(e){return[$Qn,...e.filter(FQn).map(t=>({fileTarget:!0,id:t.id,label:t.label,kind:"ide",workspaceTarget:t}))]}function lpt(e,t){if(!t.canOpenFile)return[];const n=TE(e);return t.canOpenLocation?[...n,...e.filter(r=>r.kind==="folder"||r.kind==="terminal")]:n}function BQn(e,t){return e.find(n=>n.id===t)??e.find(n=>n.id==="defaultApp")??null}function QQn(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(opt);return e==="defaultApp"||Pve(e)?e:null}catch{return null}}function UQn(e){if(!(typeof window>"u"))try{window.localStorage.setItem(opt,e)}catch{}}function qQn(){if(typeof window>"u")return null;const e=window.localStorage.getItem(apt);return Pve(e)?e:null}function N_(e){typeof window>"u"||window.localStorage.setItem(apt,e)}function Ame(e){return e&&Pve(e)?e:null}function VQn(e){return e.defaultPrevented||e.altKey||e.shiftKey||!e.metaKey&&!e.ctrlKey?!1:e.key.toLowerCase()==="w"}function pH(e){const t=new Set,n=[];for(const r of e){const s=Jl(r??null);!s||t.has(s)||(t.add(s),n.push(s))}return n.slice(-24)}function cpt(e){return`${LQn}:${e}`}function PO(e,t){const n=pH([...e,t]),r=Jl(t??null);return{openFilePaths:n,selectedFilePath:r&&n.includes(r)?r:n[0]??null}}function hme(e){var t;if(!e||typeof window>"u")return PO([],null);try{const n=(t=window.sessionStorage)==null?void 0:t.getItem(cpt(e)),r=n?JSON.parse(n):null;if(Array.isArray(r))return PO(r,r[0]);if(r&&typeof r=="object"){const s=r;return PO(Array.isArray(s.openFilePaths)?s.openFilePaths:[],typeof s.selectedFilePath=="string"?s.selectedFilePath:null)}}catch{return PO([],null)}return PO([],null)}function WQn(e,t,n){var r;if(!(!e||typeof window>"u"))try{const s=PO(t,n);(r=window.sessionStorage)==null||r.setItem(cpt(e),JSON.stringify(s))}catch{}}function HQn(e,t){return e.includes(t)?e:pH([...e,t])}const KQn="rudder.chat-side-panel.markdown-draft.v1";function Tve(e,t){return`${KQn}:${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Yk(e,t){if(!(typeof window>"u"))try{window.sessionStorage.removeItem(Tve(e,t))}catch{}}function k3(e,t,n,r){if(!(typeof window>"u")){if(r===n){Yk(e,t);return}try{const s={organizationId:e,filePath:t,baseContent:n,content:r,updatedAt:new Date().toISOString()};window.sessionStorage.setItem(Tve(e,t),JSON.stringify(s))}catch{}}}function dpt(e,t,n){const r={baseContent:n,conflicted:!1,content:n};if(typeof window>"u")return r;try{const s=window.sessionStorage.getItem(Tve(e,t));if(!s)return r;const a=JSON.parse(s);return!(a.organizationId===e&&a.filePath===t&&typeof a.baseContent=="string"&&typeof a.content=="string")||a.content===n?(Yk(e,t),r):{baseContent:a.baseContent,conflicted:a.baseContent!==n,content:a.content}}catch{return Yk(e,t),r}}function _ve(e){const t=e.match(/^(---\r?\n[\s\S]*?\r?\n---)(\r?\n|$)/);return t?{frontmatter:t[1]??"",separator:t[2]??`
1954
+ ${$e}`:$e)}finally{ne(!1),ie.current&&(ie.current.value="")}}}if(t.length===0)return i.jsx("p",{className:"text-sm text-muted-foreground",children:p});const de=Be=>{var ut,ge,Le;if(Be.kind==="disclosure")return i.jsx(J7n,{hiddenCount:Be.hiddenCount,locale:T,onRevealMore:E,timelineRegionId:_});if(Be.kind==="activity")return i.jsx("div",{children:Be.activity.node});if(Be.kind==="run"){const rt=Be.run,At=rt.status==="queued"||rt.status==="running",Ue=c.get(rt.runId)??[],Se=d(rt.runId),We=VFn(rt.contextSnapshot),Te=rt.startedAt??rt.createdAt,He=So(Te),fe=o[rt.runId]??lht(rt.status),je=fe?"Hide details":"Show details",ye=n==null?void 0:n.get(rt.agentId),tt=(ye==null?void 0:ye.name)??rt.agentId.slice(0,8),ze=(rt.finishedAt||TGe(rt)?_R(rt):null)??"Run",De=MR(rt),kt=rc(`/agents/${rt.agentId}/runs/${rt.runId}`,W),gt=()=>{$(kt)},Ke=Me=>{WFn(Me.target)||gt()},Je=Me=>{Me.target===Me.currentTarget&&(Me.key!=="Enter"&&Me.key!==" "||(Me.preventDefault(),gt()))},wt=i.jsx(vy,{to:kt,className:"inline-flex shrink-0 rounded-[calc(var(--radius-sm)-1px)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring","aria-label":`Open ${rt.status.replace("_"," ")} run details`,children:i.jsx(Oi,{status:rt.status})}),Z=i.jsx("button",{type:"button","aria-label":je,"aria-expanded":fe,"aria-controls":`run-output-${rt.runId}`,className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border bg-background/70 text-muted-foreground motion-safe:transition-colors hover:bg-accent hover:text-foreground motion-reduce:transition-none",onClick:()=>{l(rt.runId,!fe)},children:i.jsx(rs,{className:`h-3.5 w-3.5 motion-safe:transition-transform motion-reduce:transition-none ${fe?"rotate-180":""}`})});return i.jsxs("div",{"aria-label":"Agent run","data-run-id":rt.runId,role:"link",tabIndex:0,className:`overflow-hidden rounded-sm border border-dashed border-border bg-muted/35 motion-safe:transition-[padding,background-color,border-color] motion-safe:duration-200 motion-safe:ease-out hover:border-border/80 hover:bg-muted/50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring motion-reduce:transition-none ${fe?"p-3":"px-3 py-1"}`,onClick:Ke,onKeyDown:Je,children:[fe?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3",children:[i.jsx(vy,{to:`/agents/${rt.agentId}`,className:"hover:underline",children:i.jsx(zl,{name:tt,icon:ye==null?void 0:ye.icon,role:ye==null?void 0:ye.role,size:"sm"})}),i.jsx("div",{className:"shrink-0 text-right",children:i.jsx("time",{className:"block text-xs text-muted-foreground",dateTime:Zse(Te),title:He,children:Ca(Te)})})]}),i.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[i.jsxs("span",{className:"inline-flex h-7 shrink-0 items-center gap-1 font-medium text-muted-foreground",title:De||void 0,children:[i.jsx(Dh,{className:"h-3.5 w-3.5"}),ze]}),wt,We&&i.jsx("span",{className:"rounded-md border border-amber-500/30 bg-amber-500/10 px-2 py-1 text-[11px] font-medium text-amber-700 dark:text-amber-300",children:We}),i.jsx("span",{className:"ml-auto",children:Z})]})]}):i.jsxs("div",{className:"grid min-w-0 grid-cols-[minmax(0,1fr)_auto_auto] items-center gap-2 text-xs",children:[i.jsxs("div",{className:"flex h-7 min-w-0 items-center gap-2",children:[i.jsx(vy,{to:`/agents/${rt.agentId}`,className:"min-w-0 shrink overflow-hidden hover:underline",children:i.jsx(zl,{name:tt,icon:ye==null?void 0:ye.icon,role:ye==null?void 0:ye.role,size:"sm",className:"h-7 w-full min-w-0 max-w-[12rem] items-center"})}),i.jsxs("span",{className:"inline-flex h-7 shrink-0 items-center gap-1 font-medium text-muted-foreground",title:De||void 0,children:[i.jsx(Dh,{className:"h-3.5 w-3.5"}),ze]}),wt,We&&i.jsx("span",{className:"inline-flex h-7 shrink-0 items-center rounded-md border border-amber-500/30 bg-amber-500/10 px-2 text-[11px] font-medium text-amber-700 dark:text-amber-300",children:We})]}),i.jsx("time",{className:"hidden h-7 shrink-0 items-center text-muted-foreground sm:inline-flex",dateTime:Zse(Te),title:He,children:Ca(Te)}),Z]}),i.jsx(nBn,{expanded:fe,id:`run-output-${rt.runId}`,children:i.jsx(M1,{entries:Ue,density:"compact",limit:4,streaming:At,collapseStdout:!0,presentation:"chat",emptyMessage:Se?"Waiting for transcript parsing...":At?`Run ${rt.status}. Waiting for output...`:"No run output captured."})})]})}const ae=Be.comment,Ee=a===ae.id,he=So(ae.createdAt);if(!!ae.deletedAt)return null;const Ie=new Date(ae.updatedAt).getTime()>new Date(ae.createdAt).getTime()+1e3,$e=!!x&&!ae.authorAgentId&&ae.authorUserId===x,ce=!!x&&($e||!!ae.authorAgentId),Oe=V===ae.id,Ye=Y[ae.id]===!0&&!Oe,J=JFn(ae.body),qe=()=>{G(rt=>({...rt,[ae.id]:!Ye}))},be=()=>{G(rt=>({...rt,[ae.id]:!1})),L(ae.id),D(ae.body)},ot=()=>{L(null),D("")},ke=async()=>{var At,Ue;if(!y)return;const rt=(((Ue=(At=le.current)==null?void 0:At.getMarkdown)==null?void 0:Ue.call(At))??R).trim();if(rt){ee(!0);try{await y(ae.id,rt),ot()}finally{ee(!1)}}},Ce=async()=>{!w||!await F({title:"Delete this comment?",description:"This permanently removes the comment from the issue. This cannot be undone.",confirmLabel:"Delete comment",tone:"destructive"})||await w(ae.id)},ue=ae.authorAgentId?i.jsx(vy,{to:`/agents/${ae.authorAgentId}`,className:Ye?"block min-w-0 max-w-full overflow-hidden hover:underline":"min-w-0 hover:underline",children:i.jsx(zl,{name:((ut=n==null?void 0:n.get(ae.authorAgentId))==null?void 0:ut.name)??ae.authorAgentId.slice(0,8),icon:(ge=n==null?void 0:n.get(ae.authorAgentId))==null?void 0:ge.icon,role:(Le=n==null?void 0:n.get(ae.authorAgentId))==null?void 0:Le.role,size:"sm",className:Ye?"max-w-full min-w-0 overflow-hidden":void 0})}):i.jsx(Bd,{name:m1e(u),avatarUrl:ae.authorUserId===x?b:null,size:"sm",className:Ye?"max-w-full min-w-0 overflow-hidden":void 0}),mt=i.jsx("a",{href:`#comment-${ae.id}`,className:"text-xs text-muted-foreground transition-colors hover:text-foreground hover:underline",title:he,"aria-label":`Comment posted ${he}`,children:i.jsx("time",{dateTime:Zse(ae.createdAt),children:Ca(ae.createdAt)})});return i.jsxs("div",{id:`comment-${ae.id}`,"aria-label":Ye?"Collapsed comment":void 0,className:Oe?`overflow-hidden min-w-0 rounded-[var(--radius-lg)] border px-4 py-3 shadow-[var(--shadow-sm)] transition-colors duration-1000 ${Ee?"border-primary/50 bg-primary/5":"border-border/80 bg-card/80"}`:`border overflow-hidden min-w-0 rounded-sm transition-colors duration-1000 ${Ye?"border-dashed bg-muted/35 px-3 py-1 hover:bg-muted/50":"p-3"} ${Ee?"border-primary/50 bg-primary/5":"border-border"}`,children:[Oe?i.jsxs("div",{className:"mb-3 flex min-w-0 items-center gap-2",children:[i.jsx("div",{className:"min-w-0",children:ue}),i.jsx("span",{className:"shrink-0 text-sm text-muted-foreground",children:Ca(ae.createdAt)}),Ie?i.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",title:So(ae.updatedAt),children:"edited"}):null]}):i.jsxs("div",{"data-comment-collapsed-header":Ye?"true":void 0,className:Ye?"grid min-w-0 grid-cols-[minmax(0,1fr)_auto_auto] items-center gap-3 text-xs":"grid min-w-0 grid-cols-[minmax(0,1fr)_auto_auto] items-start gap-3",children:[i.jsxs("div",{className:Ye?"min-w-0 py-1":"min-w-0",children:[i.jsx("span",{className:Ye?"block min-w-0 max-w-[min(24rem,55vw)]":"min-w-0",children:ue}),Ye&&J?i.jsx("span",{className:"mt-1 block min-w-0 break-words line-clamp-2 text-sm leading-5 text-foreground",title:J,children:J}):null]}),i.jsxs("span",{className:Ye?"hidden h-7 shrink-0 items-center sm:inline-flex":"flex h-7 shrink-0 items-center gap-1.5",children:[mt,Ie?i.jsx("span",{className:"text-xs text-muted-foreground",title:So(ae.updatedAt),children:"edited"}):null]}),i.jsxs("span",{className:"flex h-7 shrink-0 items-center gap-1",children:[Ye?i.jsx("button",{type:"button",className:"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border bg-background/70 text-muted-foreground motion-safe:transition-[background-color,color,transform] hover:bg-accent hover:text-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring motion-reduce:transition-none","aria-label":"Expand comment","aria-expanded":"false",title:"Expand comment",onClick:qe,children:i.jsx(rs,{className:"h-3.5 w-3.5"})}):null,Ye?null:i.jsx(eBn,{comment:ae,orgId:r,projectId:s,location:B,collapsed:Ye,canEdit:$e,canDelete:ce,onToggleCollapsed:qe,onEdit:be,onDelete:Ce})]})]}),Oe?i.jsxs(i.Fragment,{children:[i.jsx(Cu,{ref:le,engine:"milkdown",value:R,onChange:D,placeholder:"Edit comment...",mentions:h,agentMentionIntent:"wake",imageUploadHandler:k,className:"rounded-[var(--radius-md)] bg-transparent",contentClassName:"min-h-[92px] bg-transparent text-[15px] leading-7 text-foreground",bordered:!1,onSubmit:ke}),i.jsxs("div",{className:"mt-5 flex items-center justify-between gap-3",children:[k?i.jsxs("div",{children:[i.jsx("input",{ref:ie,type:"file",accept:oht,multiple:!0,className:"hidden",onChange:re}),i.jsx(oe,{type:"button",variant:"ghost",size:"icon-sm",onClick:()=>{var rt;return(rt=ie.current)==null?void 0:rt.click()},disabled:se||X,title:"Attach file",children:i.jsx(df,{className:"h-4 w-4"})})]}):i.jsx("span",{"aria-hidden":"true"}),i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(oe,{size:"sm",variant:"ghost",onClick:ot,disabled:X,children:"Cancel"}),i.jsx(oe,{size:"sm",onClick:ke,disabled:X||se||!R.trim(),children:X?"Saving...":"Save"})]})]})]}):i.jsxs(tBn,{collapsed:Ye,children:[i.jsx(Ya,{className:"text-sm",agentMentions:f,skillReferences:m,onLinkClick:S,children:ae.body}),ae.runId?i.jsx("div",{className:"mt-2 pt-2 border-t border-border/60",children:ae.runAgentId?i.jsxs(vy,{to:`/agents/${ae.runAgentId}/runs/${ae.runId}`,className:"inline-flex items-center rounded-md border border-border bg-accent/30 px-2 py-1 text-[10px] font-mono text-muted-foreground hover:text-foreground hover:bg-accent/50 transition-colors",children:["run ",ae.runId.slice(0,8)]}):i.jsxs("span",{className:"inline-flex items-center rounded-md border border-border bg-accent/30 px-2 py-1 text-[10px] font-mono text-muted-foreground",children:["run ",ae.runId.slice(0,8)]})}):null]})]})};return i.jsx(E7n,{announcement:z,mountAll:M,onTargetMounted:N,reserveHashScrollEndSpace:j,regionLabel:C,scrollElementRef:I,targetKey:a?`comment:${a}`:null,timeline:t,timelineRegionId:_,children:Be=>de(Be)})});function ove({comments:e,linkedRuns:t=[],activityItems:n=[],orgId:r,projectId:s,onAdd:a,onUpdate:o,onDelete:l,currentUserId:c,currentUserAvatarUrl:d,issueStatus:u,locale:f="en",reopenWillWakeAgent:m=!1,steerRunId:h=null,agentMap:p,imageUploadHandler:x,onAttachImage:b,draftKey:y,liveRunSlot:w,mentions:k,onMentionQueryChange:S,operatorDisplayName:j,heading:C,hideHeading:I=!1,emptyMessage:N="No comments or runs yet.",escapeBackWhenEmpty:M=!1,fixedComposer:E=!1,fixedComposerTimelineScroll:_=!0,hideComposer:z=!1,composerReplacement:T,timelineScrollElementRef:$,progressiveDisclosure:B}){var ze;const[F,W]=A.useState(()=>y?B_e(y):""),Y=UFn(u),[G,V]=A.useState(Y),[L,R]=A.useState(null),[D,X]=A.useState({}),[ee,se]=A.useState(!1),ne=A.useRef(null),le=A.useRef(null),ie=A.useRef(null),re=$??(E&&_?ie:void 0),de=Ir(),Be=p8(),ae=A.useRef(null),Ee=A.useRef(null),he=A.useRef([]),_e=A.useRef([]),Ie=A.useRef(null),$e=A.useRef(null),ce=A.useMemo(()=>e.filter(De=>!De.deletedAt),[e]),Oe=((ze=ce[0])==null?void 0:ze.issueId)??null,Ye=b5(f,"Leave a comment..."),J=A.useMemo(()=>m7n({activityItems:n,comments:ce,linkedRuns:t}),[n,t,ce]),qe=A.useMemo(()=>A7n(J),[J]),be=eOn({config:B,items:qe,locale:f}),ot=A.useMemo(()=>h7n(J,be.selection),[J,be.selection]),ke=A.useMemo(()=>c7n(t,p),[p,t]),Ce=A.useMemo(()=>ke.filter(De=>lht(De.status)||D[De.id]===!0),[D,ke]),{transcriptByRun:ue,hasOutputForRun:mt}=OL({runs:Ce,orgId:r,maxChunksPerRun:120}),ut=A.useCallback((De,kt)=>{X(gt=>({...gt,[De]:kt}))},[]),ge=A.useMemo(()=>k||(p?Array.from(p.values()).filter(De=>De.status!=="terminated").map(De=>({id:`agent:${De.id}`,name:of(De),kind:"agent",agentId:De.id,agentIcon:De.icon,agentRole:De.role})):[]),[p,k]),Le=A.useMemo(()=>ge.filter(De=>De.kind==="skill"&&De.skillMarkdownTarget).map(De=>({href:De.skillMarkdownTarget,label:De.skillRefLabel??De.name,displayName:De.skillDisplayName??De.name,description:De.skillDescription,categoryLabel:De.skillCategoryLabel,locationLabel:De.skillLocationLabel,detailsHref:De.skillDetailsHref})),[ge]),rt=A.useCallback(De=>{W(De),y&&qFn(y,De)},[y]),{canSubmit:At,handleSubmit:Ue,submitting:Se}=f7n({agentMap:p,body:F,canReopen:Y,composerSurfaceRef:le,draftKey:y,editorRef:ne,locale:f,onAdd:a,reopen:G,reopenWillWakeAgent:m,setReopen:V,updateBody:rt}),We=A.useMemo(()=>ge.filter(De=>De.kind==="agent"&&De.agentId).map(De=>({name:De.name,agentId:De.agentId,agentIcon:De.agentIcon})),[ge]);A.useEffect(()=>{y&&W(B_e(y))},[y]);const Te=A.useCallback(()=>{var De;if(typeof window<"u"&&typeof window.cancelAnimationFrame=="function")for(const kt of he.current)window.cancelAnimationFrame(kt);he.current=[];for(const kt of _e.current)clearTimeout(kt);_e.current=[],(De=$e.current)==null||De.call($e),$e.current=null,Ie.current=null,se(!1)},[]);A.useEffect(()=>()=>{Te(),Ee.current&&clearTimeout(Ee.current)},[Te]),A.useEffect(()=>{V(Y)},[Y]);const He=A.useCallback((De,kt="smooth",gt={})=>{const Ke=document.getElementById(`comment-${De}`);if(!Ke)return!1;if(gt.retry&&KFn(Ke)<=QFn)return Te(),!0;Ee.current&&clearTimeout(Ee.current),R(De);const Je=HFn(Ke,kt);return Ie.current={container:Je.container,scrollTop:Je.scrollTop},ZFn(de.pathname,Je.scrollTop),Ee.current=setTimeout(()=>{R(null),Ee.current=null},3e3),!0},[Te,de.pathname]),fe=A.useCallback(({event:De,href:kt})=>{if(De.defaultPrevented||De.button!==0||De.metaKey||De.ctrlKey||De.shiftKey||De.altKey||typeof window>"u")return;const gt=XFn({href:kt,baseHref:window.location.href,currentPathname:de.pathname,currentIssueId:Oe,currentIssueRef:Yfe(de)});if(gt){De.preventDefault(),De.stopPropagation();const wt=`#comment-${encodeURIComponent(gt)}`;return de.hash===wt?He(gt):Be({pathname:de.pathname,search:de.search,hash:wt}),!0}const Ke=(()=>{try{const wt=new URL(kt,window.location.href);if(wt.origin!==window.location.origin||wt.hash===de.hash)return null;const Z=aU(wt.hash);if(!Z)return null;const Me=lH(wt.pathname);if(!Me)return null;const lt=Yfe(de);return lt&&Me===lt||Oe&&Me===Oe?Z:null}catch{return null}})();if(Ke)return De.preventDefault(),De.stopPropagation(),Be({pathname:de.pathname,search:de.search,hash:`#comment-${encodeURIComponent(Ke)}`}),!0;const Je=GFn({href:kt,baseHref:window.location.href});if(Je)return De.preventDefault(),De.stopPropagation(),Be(Je),!0},[Oe,de,Be,He]);A.useLayoutEffect(()=>{const De=aU(de.hash);De&&be.revealTarget(`comment:${De}`)},[de.hash,be.revealTarget]),A.useEffect(()=>{var Ke;const De=de.hash,kt=aU(De);if(!kt||ce.length===0||!ce.some(Je=>Je.id===kt))return;const gt=`${de.key}:${De}`;if(ae.current!==gt)if(Te(),se(!0),He(kt,"auto")){ae.current=gt;const Je=((Ke=Ie.current)==null?void 0:Ke.container)??window,wt=()=>{Te()};for(const Me of F_e)Je.addEventListener(Me,wt,{passive:!0});if($e.current=()=>{for(const Me of F_e)Je.removeEventListener(Me,wt)},typeof window<"u"&&typeof window.requestAnimationFrame=="function"){const Me=window.requestAnimationFrame(()=>{const lt=window.requestAnimationFrame(()=>{He(kt,"auto",{retry:!0}),he.current=he.current.filter(Pe=>Pe!==lt)});he.current.push(lt),he.current=he.current.filter(Pe=>Pe!==Me)});he.current.push(Me)}for(const Me of $_e){const lt=setTimeout(()=>{He(kt,"auto",{retry:!0}),_e.current=_e.current.filter(Pe=>Pe!==lt)},Me);_e.current.push(lt)}const Z=setTimeout(()=>{se(!1),_e.current=_e.current.filter(Me=>Me!==Z)},Math.max(...$_e)+120);_e.current.push(Z)}else R(kt)},[Te,de.hash,de.key,He,ce]);const je=A.useCallback(De=>{if(!De.startsWith("comment:"))return;const kt=`${de.key}:${de.hash}`;if(ae.current===kt)return;const gt=De.slice(8);!gt||!He(gt,"auto")||(ae.current=kt,se(!1))},[de.hash,de.key,He]),ye=i.jsx(rBn,{timeline:ot,agentMap:p,orgId:r,projectId:s,highlightCommentId:L,runExpandedOverrides:D,onToggleRunExpanded:ut,runTranscriptById:ue,runHasOutput:mt,operatorDisplayName:j,agentMentions:We,skillReferences:Le,mentions:ge,emptyMessage:N,currentUserId:c,currentUserAvatarUrl:d,onUpdate:o,onDelete:l,imageUploadHandler:x,onMarkdownLinkClick:fe,reserveHashScrollEndSpace:ee,timelineRegionLabel:B?f==="zh-CN"?"任务动态时间线":"Issue activity timeline":void 0,scrollElementRef:re,onTargetMounted:je,mountAll:be.mountAll,onRevealMore:be.revealMore,timelineRegionId:be.timelineRegionId,disclosureAnnouncement:be.announcement,locale:f}),me=T??i.jsx(Hdt,{body:F,onBodyChange:rt,onSubmit:()=>Ue(),canSubmit:At,submitting:Se,editorRef:ne,surfaceRef:le,placeholder:Ye,mentions:ge,onMentionQueryChange:S,imageUploadHandler:x,onAttachFile:b,attachmentAccept:oht,escapeBackWhenEmpty:M,beforeSubmit:Y?i.jsxs("label",{className:"flex cursor-pointer select-none items-center gap-1.5 text-xs text-muted-foreground",children:[i.jsx("input",{type:"checkbox",checked:G,onChange:De=>V(De.target.checked),className:"rounded border-border"}),"Re-open"]}):null,secondaryAction:h?i.jsxs(oe,{size:"sm",variant:"outline","data-testid":"issue-comment-steer",disabled:!At,onClick:()=>Ue("steer"),title:"Interrupt the active run and continue with this feedback",children:[i.jsx(b3t,{className:"mr-1.5 h-3.5 w-3.5"}),"Steer"]}):null});return E?_?i.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-4",children:[!I&&i.jsx("div",{className:"shrink-0",children:C??i.jsxs("h3",{className:"text-sm font-semibold",children:["Comments & Runs (",J.length,")"]})}),i.jsxs("div",{ref:ie,className:"scrollbar-auto-hide min-h-0 flex-1 overflow-y-auto overscroll-contain pr-1","data-testid":"comment-thread-timeline-scroll",children:[ye,w?i.jsx("div",{className:"mt-4",children:w}):null]}),i.jsx("div",{className:"comment-thread-fixed-composer sticky bottom-0 z-20 -mx-4 -mb-4 shrink-0 px-4 pb-4 pt-3","data-testid":"comment-thread-fixed-composer",children:z?null:me})]}):i.jsxs("div",{className:"flex min-h-0 flex-col gap-1",children:[!I&&i.jsx("div",{className:"shrink-0",children:C??i.jsxs("h3",{className:"text-sm font-semibold",children:["Comments & Runs (",J.length,")"]})}),i.jsxs("div",{"data-testid":"comment-thread-timeline-flow",children:[ye,w?i.jsx("div",{className:"mt-3",children:w}):null]}),i.jsx("div",{className:"comment-thread-fixed-composer sticky bottom-[calc(5rem+env(safe-area-inset-bottom))] z-20 -mx-4 shrink-0 px-4 pb-4 pt-1 md:bottom-0","data-testid":"comment-thread-fixed-composer",children:z?null:me})]}):i.jsxs("div",{className:"space-y-4",children:[!I&&(C??i.jsxs("h3",{className:"text-sm font-semibold",children:["Comments & Runs (",J.length,")"]})),ye,w,z?null:me]})}const sBn=250,iBn=1600;function aBn(){const[e,t]=A.useState("idle"),n=A.useRef(0),r=A.useRef(null),s=A.useRef(null),a=A.useCallback(()=>{r.current&&(clearTimeout(r.current),r.current=null),s.current&&(clearTimeout(s.current),s.current=null)},[]);A.useEffect(()=>a,[a]);const o=A.useCallback(()=>{n.current+=1,a(),t("idle")},[a]),l=A.useCallback(()=>{a(),t("idle")},[a]),c=A.useCallback(async d=>{const u=n.current+1;n.current=u,a(),r.current=setTimeout(()=>{n.current===u&&t("saving")},sBn);try{if(await d(),n.current!==u)return;a(),t("saved"),s.current=setTimeout(()=>{n.current===u&&t("idle")},iBn)}catch(f){throw n.current!==u||(a(),t("error")),f}},[a]);return{state:e,markDirty:l,reset:o,runSave:c}}function m3(e){return e.trim().length===0?"":e}function lve(e){const t=m3(e);return t.length===0?null:t}function j_(e){const t=m3(e);return t.length===0?void 0:t}const Jfe="px-1 -mx-1",oBn=Jfe,lBn=900;function cBn(e){return e instanceof HTMLElement?e:e instanceof Node?e.parentElement:null}function k4(e){e.catch(()=>{})}function p1({value:e,onSave:t,as:n="span",className:r,placeholder:s="Click to edit...",multiline:a=!1,imageUploadHandler:o,mentions:l,onMentionQueryChange:c,onLinkClick:d,editorEngine:u,documentIdentity:f,alwaysEdit:m=!1,variant:h="default"}){const[p,x]=A.useState(m),[b,y]=A.useState(!1),[w,k]=A.useState(e),S=A.useRef(null),j=A.useRef(null),C=A.useRef(null),I=A.useRef(Promise.resolve()),N=A.useRef(null),M=A.useRef(0),E=A.useRef(null),_=A.useRef(!1),z=A.useRef(e),T=A.useRef(!1),$=A.useRef(null),B=A.useRef(!1),[F,W]=A.useState(!1),{state:Y,markDirty:G,reset:V,runSave:L}=aBn(),R=A.useCallback(()=>{C.current&&(clearTimeout(C.current),C.current=null)},[]);A.useEffect(()=>R,[R]),A.useEffect(()=>{var ae,Ee;const re=z.current!==e;if(z.current=e,!re)return;const de=((Ee=(ae=j.current)==null?void 0:ae.getMarkdown)==null?void 0:Ee.call(ae))??w,Be=u==="codemirror"?m3(de):de.trim();if(u==="codemirror"&&a&&b&&T.current&&Be!==e){$.current=e,W(!0),R();return}T.current=!1,_.current=!1,$.current=null,W(!1),k(e)},[R,w,u,a,b,e]);const D=A.useCallback(re=>{re&&(re.style.height="auto",re.style.height=`${re.scrollHeight}px`)},[]),X=q("rudder-inline-markdown-surface rounded",h==="issue-description"&&"rudder-issue-description-surface"),ee=q("rudder-inline-markdown-body",h==="issue-description"&&"rudder-issue-description-markdown rudder-issue-description-markdown-read"),se=q("rudder-edit-in-place-content",h==="issue-description"&&"rudder-issue-description-markdown rudder-issue-description-markdown-edit",r);A.useEffect(()=>{p&&S.current&&(S.current.focus(),S.current.select(),S.current instanceof HTMLTextAreaElement&&D(S.current))},[p,D]),A.useEffect(()=>{if(!p||!a||u==="codemirror"&&m)return;const re=requestAnimationFrame(()=>{var de;(de=j.current)==null||de.focus()});return()=>cancelAnimationFrame(re)},[m,p,u,a]);const ne=A.useCallback(async(re=w)=>{const de=u==="codemirror"?m3(re):re.trim(),Be=M.current>0;if(de!==e||Be)if(Be&&N.current===de)await I.current;else{N.current=de,M.current+=1;const ae=I.current.catch(()=>{}).then(async()=>{await Promise.resolve(t(de))});I.current=ae;try{await ae}finally{M.current-=1,M.current===0&&N.current===de&&(N.current=null)}}else k(e);a||x(!1)},[w,u,a,t,e]);function le(re){re.key==="Enter"&&!a&&(re.preventDefault(),k4(ne())),re.key==="Escape"&&(R(),V(),B.current=!0,T.current=!1,_.current=!1,$.current=null,W(!1),k(e),a?(y(!1),m||x(!1),document.activeElement instanceof HTMLElement&&document.activeElement.blur()):x(!1))}if(A.useEffect(()=>{if(!a||!b)return;if($.current!==null){R();return}const re=u==="codemirror"?m3(w):w.trim();if(E.current===re){E.current=null;return}if(re===e){Y!=="saved"&&V();return}return G(),R(),C.current=setTimeout(()=>{C.current=null,k4(L(()=>ne(re)))},lBn),R},[Y,R,ne,w,u,G,a,b,V,L,e]),a&&(p||u==="codemirror"))return i.jsxs("div",{className:q(oBn,X),onFocusCapture:()=>y(!0),onBlurCapture:re=>{var ae,Ee;if(re.currentTarget.contains(re.relatedTarget))return;if(R(),y(!1),m||x(!1),B.current){B.current=!1;return}const de=_.current?((Ee=(ae=j.current)==null?void 0:ae.getMarkdown)==null?void 0:Ee.call(ae))??w:w,Be=u==="codemirror"?m3(de):de.trim();if($.current!==null){V();return}if(E.current=Be,Be===e){V(),k4(ne(de));return}k4(L(()=>ne(de)))},onKeyDown:le,children:[i.jsx(Cu,{ref:j,engine:u,value:w,onChange:re=>{E.current=null,_.current=!0;const de=u==="codemirror"?m3(re):re.trim();T.current=de!==e,T.current||($.current=null,W(!1)),k(re)},placeholder:s,bordered:!1,className:"bg-transparent",contentClassName:se,imageUploadHandler:o,mentions:l,onMentionQueryChange:c,onLinkClick:d,documentIdentity:f,activateInlineTokensOnPlainClick:h==="issue-description",submitShortcut:"mod-enter",onSubmit:()=>{var Be,ae;R();const re=((ae=(Be=j.current)==null?void 0:Be.getMarkdown)==null?void 0:ae.call(Be))??w,de=u==="codemirror"?m3(re):re.trim();if($.current=null,W(!1),E.current=de,de===e){V(),k4(ne(re));return}k4(L(()=>ne(re)))}}),i.jsx("div",{className:"flex min-h-4 items-center justify-end pr-1",children:i.jsx("span",{className:q("text-[11px] transition-opacity duration-150",Y==="error"?"text-destructive":"text-muted-foreground",Y==="idle"&&!F?"opacity-0":"opacity-100"),children:Y==="saving"?"Autosaving...":F?"Updated elsewhere — submit to overwrite":Y==="saved"?"Saved":Y==="error"?"Could not save":"Idle"})})]});if(p)return i.jsx("textarea",{ref:S,value:w,rows:1,onChange:re=>{k(re.target.value),D(re.target)},onBlur:()=>{k4(ne())},onKeyDown:le,className:q("w-full bg-transparent rounded outline-none resize-none overflow-hidden",Jfe,r)});const ie=e&&a?"div":n;return i.jsx(ie,{className:q(a?X:"rounded overflow-hidden",a?"cursor-text":"cursor-pointer transition-colors hover:bg-accent/50",Jfe,r,a&&!e&&"min-h-9 py-1 text-muted-foreground italic",!a&&!e&&"text-muted-foreground italic"),onClick:re=>{var de;(de=cBn(re.target))!=null&&de.closest("a")||x(!0)},children:e&&a?i.jsx(Ya,{className:ee,copyMarkdownOnCopy:!0,onLinkClick:({event:re,href:de,label:Be,sourceHref:ae})=>{const Ee=d==null?void 0:d({event:re.nativeEvent,href:de,label:Be,sourceHref:ae});return re.stopPropagation(),Ee},children:e}):e||s})}function g1({className:e,orientation:t="horizontal",decorative:n=!0,...r}){return i.jsx(qQe,{"data-slot":"separator",decorative:n,orientation:t,className:q("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",e),...r})}const Xse=["#ef4444","#f97316","#eab308","#22c55e","#06b6d4","#3b82f6","#6366f1","#a855f7","#ec4899"];function Iw(e){return e.trim().replace(/\s+/g," ")}function dht(e,t){const n=Iw(t).toLowerCase();return n?e.find(r=>Iw(r.name).toLowerCase()===n)??null:null}function cve(e){const t=Iw(e);if(!t)return Xse[0];let n=0;for(let r=0;r<t.length;r+=1)n=n*31+t.charCodeAt(r)>>>0;return Xse[n%Xse.length]}function ly(){return typeof window>"u"?null:window.desktopIdentity??null}let eme=null,KS=null,JI=0;const oU=new Set;function lU(e){eme!==e&&(eme=e,oU.forEach(t=>t()))}function dBn(){if(KS)return;const e=ly();if(!e)return;const t=++JI;let n=0;const r=o=>{n+=1,lU(o.status==="signed-in"?o.account.image:null)},s=e.onStateChanged(r);KS=()=>{JI+=1,KS=null,s()};const a=n;e.getState().then(async o=>{if(t!==JI||n!==a||(r(o),o.status!=="signed-in"))return;const l=n;try{const c=await e.getProfile();t===JI&&n===l&&lU(c.image)}catch{}}).catch(()=>{t===JI&&lU(null)})}function uBn(e){return oU.add(e),dBn(),()=>{oU.delete(e),!(oU.size>0)&&(KS==null||KS(),lU(null))}}function G0(){return A.useSyncExternalStore(uBn,()=>eme,()=>null)}const uht="rudder:recent-assignees",U_e=10;function SL(){try{const e=localStorage.getItem(uht);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function Kk(e){if(!e)return;const t=SL().filter(n=>n!==e);t.unshift(e),t.length>U_e&&(t.length=U_e),localStorage.setItem(uht,JSON.stringify(t))}function ZS(e,t){const n=new Map(t.map((r,s)=>[r,s]));return[...e].sort((r,s)=>{const a=n.get(r.id),o=n.get(s.id);return a!==void 0&&o!==void 0?a-o:a!==void 0?-1:o!==void 0?1:r.name.localeCompare(s.name)})}const tme=60,nme=60*tme,C_=24*nme,q_e=7*C_,V_e=30*C_;function Uf(e,t={}){const n=cN(),r=Date.now(),s=new Date(e).getTime(),a=Math.round((r-s)/1e3);if(t.absoluteAfterDays!==void 0&&a>=t.absoluteAfterDays*C_)return So(e);if(a<tme)return n==="zh-CN"?"刚刚":"just now";if(a<nme){const l=Math.floor(a/tme);return n==="zh-CN"?`${l} 分钟前`:`${l}m ago`}if(a<C_){const l=Math.floor(a/nme);return n==="zh-CN"?`${l} 小时前`:`${l}h ago`}if(a<q_e){const l=Math.floor(a/C_);return n==="zh-CN"?`${l} 天前`:`${l}d ago`}if(a<V_e){const l=Math.floor(a/q_e);return n==="zh-CN"?`${l} 周前`:`${l}w ago`}const o=Math.floor(a/V_e);return n==="zh-CN"?Pm(e):`${o}mo ago`}const fBn={xs:"gap-1 px-1.5 py-0.5 text-[10px]",sm:"gap-1.5 px-2 py-0.5 text-xs"},mBn={xs:"h-1.5 w-1.5",sm:"h-2 w-2"};function Zk({label:e,size:t="xs",className:n}){return i.jsxs("span",{"data-slot":"issue-label-chip",className:q("inline-flex max-w-full items-center rounded-[calc(var(--radius-sm)-2px)] border border-[color:var(--border-soft)] bg-[color:color-mix(in_oklab,var(--surface-elevated)_78%,transparent)] font-medium text-muted-foreground",fBn[t],n),title:e.name,children:[i.jsx("span",{className:q("shrink-0 rounded-full",mBn[t]),style:{backgroundColor:e.color},"aria-hidden":"true"}),i.jsx("span",{className:"truncate",children:e.name})]})}function fht(e){const[t,n]=A.useState(null),[r,s]=A.useState(null),a=A.useRef(null),o=A.useRef(null),l=A.useRef(null),c=A.useRef(null),d=is(),u=is(),f=e.disabled||e.pending,m=C=>{const I=window.innerHeight-C,N=document.querySelector("[data-mobile-bottom-navigation]");return!N||N.getClientRects().length===0?I:Math.min(I,N.getBoundingClientRect().top-C)};A.useEffect(()=>{if(!t)return;const C=I=>{I.key!=="Escape"&&I.key!=="ArrowLeft"||(I.preventDefault(),I.stopImmediatePropagation(),x(t))};return window.addEventListener("keydown",C,!0),()=>window.removeEventListener("keydown",C,!0)},[t]);const h=C=>{a.current=C,typeof e.modelSelectRef=="function"?e.modelSelectRef(C):e.modelSelectRef&&(e.modelSelectRef.current=C)},p=(C,I,N=!1)=>{if(f||!I)return;const M=I.getBoundingClientRect(),E=256,_=12,z=m(_),$=window.innerWidth-M.right>=E+_?M.right+8:Math.max(_,M.left-E-8),B=I.closest("[data-runtime-profile-panel]"),F=B==null?void 0:B.getBoundingClientRect(),W=F?$<F.right&&$+E>F.left:!1;if(F&&W){const D=Math.max(0,z-F.bottom-8),X=Math.max(0,F.top-_-8),ee=D>=X,se=Math.min(320,ee?D:X);s({left:Math.min(Math.max(_,M.left),window.innerWidth-_-E),top:ee?F.bottom+8:F.top-8-se,maxHeight:`${se}px`}),n(C),N&&requestAnimationFrame(()=>{var ne;(ne=(C==="model"?l:c).current)==null||ne.focus()});return}const Y=Math.max(0,z-M.top),G=Math.max(0,M.bottom-_),V=Y>=120,L=Math.min(320,V?Y:Math.max(G,Y));s({left:$,top:V?Math.max(_,M.top):Math.max(_,Math.min(M.bottom-L,z-L)),maxHeight:`${L}px`}),n(C),N&&requestAnimationFrame(()=>{var R;(R=(C==="model"?l:c).current)==null||R.focus()})},x=C=>{n(null),requestAnimationFrame(()=>{var I;(I=(C==="model"?a:o).current)==null||I.focus()})},b=(C,I)=>{C.key!=="ArrowLeft"&&C.key!=="Escape"||(C.preventDefault(),C.stopPropagation(),x(I))},y=(C,I)=>{const N=C==="model"?e.testIds.modelOption:e.testIds.effortOption,M=C==="model"?l:c,E=[I.defaultOption,...I.options];return i.jsxs(i.Fragment,{children:[E.map((_,z)=>{const T=I.selectedId===_.id;return i.jsxs("button",{ref:z===0?M:void 0,type:"button",role:"option","aria-selected":T,"data-testid":N(_.id),className:"chat-composer-menu-row",onClick:()=>{I.onSelect(_.id),n(null)},children:[i.jsx("span",{className:"min-w-0 flex-1 truncate",children:_.label}),T?i.jsx(zi,{className:"h-4 w-4 shrink-0","aria-hidden":"true"}):null]},_.id??"default")}),I.loading?i.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-2 text-xs text-muted-foreground",children:[i.jsx(fn,{className:"h-3.5 w-3.5 animate-spin","aria-hidden":"true"}),"Loading models..."]}):I.options.length===0?i.jsx("div",{className:"px-2.5 py-2 text-xs text-muted-foreground",children:I.emptyLabel??"No options found."}):null]})},w=q("pointer-events-auto surface-overlay scrollbar-auto-hide scrollbar-menu-inset fixed z-[80] w-64 overflow-y-auto rounded-[var(--radius-lg)] border p-1.5 shadow-lg"),k=q("chat-composer-menu-row grid min-h-10 grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto] gap-2",f&&"cursor-not-allowed opacity-60"),S=t==="model"&&r&&typeof document<"u"?ja.createPortal(i.jsx("div",{ref:d,"data-runtime-profile-submenu":!0,"data-chat-runtime-submenu":!0,"data-issue-runtime-portal":!0,"data-testid":e.testIds.modelOptions,role:"listbox","aria-label":`${e.ariaContext} model`,className:w,style:r,onKeyDown:C=>b(C,"model"),children:y("model",e.model)}),document.body):null,j=e.effort&&t==="effort"&&r&&typeof document<"u"?ja.createPortal(i.jsx("div",{ref:u,"data-runtime-profile-submenu":!0,"data-chat-runtime-submenu":!0,"data-issue-runtime-portal":!0,"data-testid":e.testIds.effortOptions,role:"listbox","aria-label":`${e.ariaContext} thinking`,className:w,style:r,onKeyDown:C=>b(C,"effort"),children:y("effort",e.effort)}),document.body):null;return i.jsxs("div",{className:"relative min-w-0",children:[i.jsxs("button",{ref:h,type:"button","data-testid":e.testIds.modelTrigger,"aria-label":`Model for ${e.ariaContext}`,"aria-haspopup":"listbox","aria-expanded":t==="model",className:k,disabled:f,title:e.errorMessage??void 0,"data-value":e.model.dataValue,onPointerMove:C=>{C.pointerType==="mouse"&&p("model",a.current)},onClick:()=>p("model",a.current,!0),onKeyDown:C=>{(C.key==="ArrowRight"||C.key==="ArrowDown")&&(C.preventDefault(),p("model",a.current,!0))},children:[i.jsx("span",{className:"font-medium text-foreground",children:"Model"}),i.jsx("span",{className:"min-w-0 truncate text-right text-muted-foreground",children:e.model.valueLabel}),e.model.loading||e.pending?i.jsx(fn,{className:"h-4 w-4 animate-spin text-muted-foreground","aria-hidden":"true"}):i.jsx(vi,{className:"h-4 w-4 text-muted-foreground","aria-hidden":"true"})]}),e.effort?i.jsxs("button",{ref:o,type:"button","data-testid":e.testIds.effortTrigger,"aria-label":`Thinking for ${e.ariaContext}`,"aria-haspopup":"listbox","aria-expanded":t==="effort",className:k,disabled:f,"data-value":e.effort.dataValue,onPointerMove:C=>{C.pointerType==="mouse"&&p("effort",o.current)},onClick:()=>p("effort",o.current,!0),onKeyDown:C=>{(C.key==="ArrowRight"||C.key==="ArrowDown")&&(C.preventDefault(),p("effort",o.current,!0))},children:[i.jsx("span",{className:"font-medium text-foreground",children:"Thinking"}),i.jsx("span",{className:"min-w-0 truncate text-right text-muted-foreground",children:e.effort.valueLabel}),e.pending?i.jsx(fn,{className:"h-4 w-4 animate-spin text-muted-foreground","aria-hidden":"true"}):i.jsx(vi,{className:"h-4 w-4 text-muted-foreground","aria-hidden":"true"})]}):null,e.errorMessage?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"mt-1 flex min-h-7 items-center gap-1.5 border-t border-[color:var(--border-soft)] px-2.5 pt-1.5 text-[11px] text-muted-foreground",children:i.jsx("span",{children:e.errorMessage})}),i.jsx("span",{className:"sr-only",role:"status",children:e.errorMessage})]}):null,S,j]})}const mht="deepseek-v4-pro[1m]",cU=[{id:mht,label:"DeepSeek V4 Pro (1M)"},{id:"deepseek-v4-flash",label:"DeepSeek V4 Flash"},{id:"claude-opus-4-6",label:"Claude Opus 4.6",variants:["low","medium","high","xhigh","max"]},{id:"claude-sonnet-4-6",label:"Claude Sonnet 4.6",variants:["low","medium","high","xhigh","max"]},{id:"claude-haiku-4-6",label:"Claude Haiku 4.6",variants:[]},{id:"claude-sonnet-4-5-20250929",label:"Claude Sonnet 4.5"},{id:"claude-haiku-4-5-20251001",label:"Claude Haiku 4.5",variants:[]}],ABn={claude_local:cU,codex_local:Azn,cursor:Gzn},hBn=["opencode_local","pi_local"];function dve(e){return e.trim().toLowerCase().startsWith("deepseek")}function l9(e){return hBn.includes(e)}function Aht(e){const[t,n]=e.split("/",2).map(r=>r.trim());return!!(t&&n)}function hht(e,t=!1){return l9(e)?"Select or enter provider/model":t?"Select model":"Default"}function pht(e){return l9(e)?"Search or enter provider/model...":"Search models..."}function ght(e,t=!1){return t?"Loading models...":e==="pi_local"?"No models discovered. Run `pi --list-models`, authenticate the provider, or enter provider/model such as deepseek/deepseek-chat and run Test now.":e==="opencode_local"?"No models discovered. Run `opencode models --verbose`, authenticate the provider, or enter provider/model and run Test now.":"No models found."}function xht(e){return e==="pi_local"?"Pi requires provider/model, for example kimi-coding/kimi-for-coding.":e==="opencode_local"?"OpenCode requires provider/model, for example opencode/deepseek-v4-flash-free.":"This runtime requires provider/model."}function dY(e){const t=e.indexOf("/");return(t>=0?e.slice(0,t).trim():e.trim())||null}function pBn(e){const t=e.indexOf("/");return(t>=0?e.slice(t+1).trim():"")||null}function gBn(e,t){const n=dY(t);return e==="claude_local"&&dve(t)?"For Claude Code + DeepSeek, use a DeepSeek model such as deepseek-v4-pro[1m]. Paste DEEPSEEK_API_KEY below or reference the existing organization secret, then use Test now as the source of truth.":e==="pi_local"?n==="deepseek"?"For Pi + DeepSeek, use provider/model such as deepseek/deepseek-chat. Paste DEEPSEEK_API_KEY below, or use pi /login if DeepSeek is already configured locally. If Pi routes through OpenRouter, use openrouter/deepseek/deepseek-chat and paste OPENROUTER_API_KEY. Test now is the source of truth.":n?`For Pi, authenticate provider "${n}" with pi /login, auth.json, or provider env, then use Test now to prove the selected model can answer.`:"Pi models use provider/model format. Use pi --list-models, or enter a custom provider/model and run Test now.":e==="opencode_local"?n?`For OpenCode, authenticate provider "${n}" with opencode auth login or provider env, then use Test now to prove the selected model can answer.`:"OpenCode models use provider/model format. Use opencode models, or enter a custom provider/model and run Test now.":null}function dU(e,t){const n=dY(t);if(e==="claude_local"&&dve(t))return"DEEPSEEK_API_KEY";if(e==="pi_local"){if(n==="deepseek")return"DEEPSEEK_API_KEY";if(n==="openrouter")return"OPENROUTER_API_KEY";if(n==="kimi-coding"||n==="kimi")return"KIMI_API_KEY"}return null}function xBn(e,t){const n=dU(e,t);return n?`${n} for ${t.trim()||"this provider"}`:null}function bBn(e,t,n){const r=t.trim();if(e==="cursor")return`${r} --trust -p --mode ask --output-format json "Respond with hello."`;if(e==="codex_local")return`${r} exec --dangerously-bypass-approvals-and-sandbox --json "Respond with hello."`;if(e==="opencode_local"){const s=n.trim()?` --model ${n.trim()}`:"";return`${r} run --format json${s} "Respond with hello."`}if(e==="pi_local"){const s=dY(n)??"<provider>",a=pBn(n)??"<model>";return`${r} -p "Respond with hello." --mode json --provider ${s} --model ${a} --tools read`}return`${r} -p "Respond with hello." --output-format json --no-session-persistence --permission-mode auto --bare --tools ""`}function yBn(e,t){const n=dY(t);return e==="claude_local"&&dve(t)?"If auth fails, set DEEPSEEK_API_KEY in the runtime env or organization secret binding, then retry Claude Code Test now.":e==="cursor"?"If auth fails, set CURSOR_API_KEY in env or run cursor-agent login.":e==="codex_local"?"If auth fails, run codex login or configure the OpenAI credentials Codex already uses locally.":e==="opencode_local"?"If auth fails, run opencode auth login or set the provider API key in env.":e==="pi_local"&&n==="deepseek"?"If auth fails, set DEEPSEEK_API_KEY for native Pi DeepSeek or run pi /login. If Pi asks for openrouter, set OPENROUTER_API_KEY or add a native DeepSeek provider/model in ~/.pi/agent/models.json.":e==="pi_local"&&n?`If auth fails, authenticate provider "${n}" with pi /login, ~/.pi/agent/auth.json, or provider env.`:"If login is required, run claude auth login and retry."}function rme(e){const t=e.checks.find(n=>n.level==="error"||/_hello_probe_(auth_required|model_unavailable|timed_out|unexpected_output|failed)$/.test(n.code));if(e.status==="fail"||t){const n=(t==null?void 0:t.hint)||(t==null?void 0:t.message);return n?`Runtime environment test is not ready: ${n}`:"Runtime environment test is not ready. Fix the runtime setup and run Test now again."}return null}function c9(e,...t){var a,o;const n=[...t.flatMap(l=>l??[]),...ABn[e]??[]],r=new Set,s=[];for(const l of n){const c=l.id.trim();if(!c||r.has(c))continue;r.add(c);const d=Array.isArray(l.variants)?[...new Set(l.variants.filter(f=>typeof f=="string"&&f.trim().length>0))]:void 0,u=(a=l.capabilities)==null?void 0:a.reasoning;s.push({id:c,label:((o=l.label)==null?void 0:o.trim())||c,...d?{variants:d}:{},...typeof u=="boolean"?{capabilities:{reasoning:u}}:{}})}return s}const bht=["off","minimal","low","medium","high","xhigh"];function E0(e){return{value:e,label:e==="xhigh"?"Extra High":e.charAt(0).toUpperCase()+e.slice(1)}}e3.map(E0);ive["gpt-5.6-sol"].map(E0);bht.map(E0);const vBn=bht.filter(e=>e!=="xhigh").map(E0);function d9(e){const t=new Set;return e.flatMap(n=>{const r=n.value.trim();return!r||t.has(r)?[]:(t.add(r),[{value:r,label:n.label}])})}function IE(e){return[{value:"",label:"Auto"},...d9(e)]}function uve(e,t){if((t==null?void 0:t.variants)!==void 0){const n=d9(t.variants.map(E0));return n.length===0?[]:IE(n)}return[]}function fve(e,t){return!t||!Array.isArray(t.variants)||t.variants.length===0?[]:IE(d9(t.variants.map(E0)))}function mve(e,t){if((t==null?void 0:t.variants)!==void 0)return t.variants.map(E0);if(t)return[];const n=ive[e.trim().toLowerCase()];return n?n.map(E0):[]}function Ave(e,t){var n,r;if(((n=t==null?void 0:t.capabilities)==null?void 0:n.reasoning)===!1)return[];if((t==null?void 0:t.variants)!==void 0){const s=d9(t.variants.map(E0));return s.length===0?[]:IE(s)}return((r=t==null?void 0:t.capabilities)==null?void 0:r.reasoning)===!0?IE(vBn):[]}function hve(e,t){if(!t)return[];if(Array.isArray(t.variants)){const n=d9(t.variants.map(E0));return n.length===0?[]:IE(n)}return[]}function yht(e,t){return[{value:"",label:e},...d9(t)]}const wBn=new Set(["claude_local","codex_local","opencode_local","pi_local","cursor"]);function pve(e){return!!(e&&wBn.has(e.agentRuntimeType))}function gve(e){return e==="codex_local"?"modelReasoningEffort":e==="opencode_local"?"variant":e==="claude_local"?"effort":e==="pi_local"?"thinking":e==="cursor"?"effort":null}function vht(e){return{...e.runtimeConfig,...e.agentRuntimeConfig}}function oT(e){const t=vht(e).model;return typeof t=="string"&&t.trim()?t.trim():"Default model"}function wht(e){const t=vht(e),n=gve(e.agentRuntimeType),r=n?t[n]??(n==="modelReasoningEffort"?t.reasoningEffort:null):null;return typeof r=="string"&&r.trim()?r.trim():null}function cH(e,t){var r;const n=(r=e==null?void 0:e.agentRuntimeConfig)==null?void 0:r[t];return typeof n=="string"&&n.trim()?n.trim():null}function sme(e,t){return cH(e,t)??(t==="modelReasoningEffort"?cH(e,"reasoningEffort"):null)}function ime(e){return!e||e.toLowerCase()==="auto"?"Auto":{minimal:"Minimal",light:"Light",low:"Low",medium:"Medium",high:"High",xhigh:"Extra High",max:"Max",ultra:"Ultra"}[e.toLowerCase()]??`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function kBn(e,t,n){const r=c9(e.agentRuntimeType,t);return!n||r.some(s=>s.id===n)?r:[...r,{id:n,label:n}]}function Gse(e,t,n){const r=e.agentRuntimeType==="claude_local"?uve(t,n):e.agentRuntimeType==="codex_local"?mve(t,n):e.agentRuntimeType==="opencode_local"?fve(t,n):e.agentRuntimeType==="pi_local"?Ave(t,n):e.agentRuntimeType==="cursor"?hve(t,n):[];return[{id:null,label:"Agent default"},...r.filter(s=>s.value.length>0).map(s=>({id:s.value,label:s.label}))]}function Yse(e,t,n,r){const s={...(e==null?void 0:e.agentRuntimeConfig)??{}};t?s.model=t:delete s.model,n?s[r]=n:delete s[r],r==="modelReasoningEffort"&&delete s.reasoningEffort;const a={...e??{}};return Object.keys(s).length>0?a.agentRuntimeConfig=s:delete a.agentRuntimeConfig,a.agentRuntimeConfig||a.useProjectWorkspace!==void 0?a:null}function OBn(e,t){var o;const n=cH(t,"model")??oT(e),r=gve(e.agentRuntimeType),s=r?sme(t,r)??wht(e):null,a=(o=t==null?void 0:t.agentRuntimeConfig)!=null&&o.model||r&&sme(t,r)?"Custom profile":"Agent default";return r?`${a} · ${n} · ${ime(s)}`:`${a} · ${n}`}function uY({agent:e,orgId:t,overrides:n,onApply:r,variant:s="compact",disabled:a=!1}){const o=pve(e),[l,c]=A.useState(!1),[d,u]=A.useState(!1),[f,m]=A.useState(null),[h,p]=A.useState(null),[x,b]=A.useState(null),[y,w]=A.useState(!1),k=A.useRef(null),S=A.useRef(null),j=gve(e.agentRuntimeType),C=Ve({queryKey:U.agents.adapterModels(t,e.agentRuntimeType),queryFn:()=>$n.adapterModels(t,e.agentRuntimeType),enabled:(l||d)&&o,retry:!1}),I=cH(n,"model"),N=sme(n,j),M=y?h:I,E=y?x:N,_=M??oT(e),z=kBn(e,C.data,M),T=z.find(le=>le.id===_),$=Gse(e,_,T),B=$.length>1,F=E,W=OBn(e,n),Y=()=>{u(!1),w(!1)},G=(le,ie,re)=>{const Be=document.querySelector("[data-mobile-bottom-navigation]"),ae=Be&&Be.getClientRects().length>0?Math.min(window.innerHeight-12,Be.getBoundingClientRect().top-12):window.innerHeight-12;return{left:window.innerWidth-le.right>=ie+12?le.right+8:Math.max(12,le.left-ie-8),top:Math.max(12,Math.min(le.top,ae-re))}},V=()=>{a||!S.current||(p(I),b(N),w(!0),m(G(S.current.getBoundingClientRect(),304,176)),u(!0))};if(A.useEffect(()=>{if(!d)return;const le=ie=>{var re,de;ie.target instanceof Node&&((re=k.current)!=null&&re.contains(ie.target)||ie.target instanceof Element&&ie.target.closest("[data-runtime-profile-submenu]")||(de=S.current)!=null&&de.contains(ie.target)||Y())};return document.addEventListener("pointerdown",le),()=>document.removeEventListener("pointerdown",le)},[d]),A.useEffect(()=>{if(!d)return;const le=ie=>{ie.key!=="Escape"&&ie.key!=="ArrowLeft"||document.querySelector("[data-runtime-profile-submenu]")||(ie.preventDefault(),ie.stopImmediatePropagation(),Y(),requestAnimationFrame(()=>{var re;return(re=S.current)==null?void 0:re.focus()}))};return window.addEventListener("keydown",le,!0),()=>window.removeEventListener("keydown",le,!0)},[d]),A.useEffect(()=>{if(!d)return;const le=()=>{S.current&&m(G(S.current.getBoundingClientRect(),304,176))};return window.addEventListener("resize",le),window.addEventListener("scroll",le,!0),()=>{window.removeEventListener("resize",le),window.removeEventListener("scroll",le,!0)}},[d]),!o)return null;const L=le=>{le?(p(I),b(N),w(!0)):w(!1),c(le)},R=()=>{r(Yse(n,h,x,j)),c(!1)},D=le=>{if(p(le),le==null){b(null);return}const ie=le??oT(e),re=Gse(e,ie,z.find(de=>de.id===ie));x&&!re.some(de=>de.id===x)&&b(null)},X=()=>{Y(),requestAnimationFrame(()=>{var le;return(le=S.current)==null?void 0:le.focus()})},ee=le=>{const ie=le??oT(e),re=Gse(e,ie,z.find(Be=>Be.id===ie)),de=x&&re.some(Be=>Be.id===x)?x:null;p(le),b(de),r(Yse(n,le,de,j)),X()},se=le=>{b(le),r(Yse(n,M,le,j)),X()},ne=le=>i.jsx(fht,{ariaContext:`${e.name} runtime`,disabled:a,errorMessage:C.error?"Models unavailable; showing built-in defaults.":null,testIds:{modelTrigger:"issue-runtime-model-trigger",modelOptions:"issue-runtime-model-options",modelOption:ie=>ie==null?"issue-runtime-option-default-model":`issue-runtime-option-model-${ie}`,effortTrigger:"issue-runtime-effort-trigger",effortOptions:"issue-runtime-effort-options",effortOption:ie=>`issue-runtime-option-effort-${ie??"default"}`},model:{valueLabel:_,selectedId:M,defaultOption:{id:null,label:`Agent default · ${oT(e)}`},options:z,loading:C.isPending,emptyLabel:C.error?"Models unavailable":"No models found.",onSelect:le==="menu"?ee:D},effort:B?{valueLabel:ime(F),selectedId:F,defaultOption:{id:null,label:`Agent default · ${ime(wht(e))}`},options:$.filter(ie=>ie.id!=null),onSelect:le==="menu"?se:b}:void 0});if(s==="menu"){const le=d&&f&&typeof document<"u"?ja.createPortal(i.jsxs("div",{ref:k,"data-issue-runtime-portal":!0,"data-runtime-profile-panel":!0,"data-testid":"issue-runtime-profile-panel",role:"dialog","aria-label":`Model and thinking for ${e.name}`,className:"pointer-events-auto surface-overlay fixed z-[75] w-[19rem] max-w-[calc(100vw-1.5rem)] rounded-[var(--radius-lg)] border p-1.5 shadow-lg",style:f,onKeyDownCapture:ie=>{ie.key==="Escape"?(ie.preventDefault(),ie.stopPropagation(),Y(),requestAnimationFrame(()=>{var re;return(re=S.current)==null?void 0:re.focus()})):ie.key==="ArrowLeft"&&(ie.preventDefault(),ie.stopPropagation(),Y(),requestAnimationFrame(()=>{var re;return(re=S.current)==null?void 0:re.focus()}))},children:[i.jsxs("button",{type:"button",className:"chat-composer-menu-row mb-1",onClick:()=>{Y(),requestAnimationFrame(()=>{var ie;return(ie=S.current)==null?void 0:ie.focus()})},children:[i.jsx(Tw,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),i.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:e.name})]}),i.jsx("div",{className:"border-t border-[color:var(--border-soft)] pt-1",children:ne("menu")})]}),document.body):null;return i.jsxs(i.Fragment,{children:[i.jsxs("button",{ref:S,type:"button","data-testid":"issue-runtime-selector","aria-label":`Configure model and thinking for ${e.name}`,"aria-haspopup":"dialog","aria-expanded":d,className:q("chat-composer-menu-row !w-auto min-w-0 max-w-full",a&&"cursor-not-allowed opacity-60"),disabled:a,title:W,onClick:()=>d?Y():V(),onKeyDown:ie=>{(ie.key==="ArrowRight"||ie.key==="Enter"||ie.key===" ")&&(ie.preventDefault(),V())},children:[i.jsx(f6,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),i.jsx("span",{className:"min-w-0 flex-1 truncate font-medium text-foreground",children:"Model"}),i.jsx("span",{className:"min-w-0 max-w-[14rem] truncate text-right text-muted-foreground",children:W}),i.jsx(vi,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"})]}),le]})}return i.jsxs(bi,{open:l,onOpenChange:L,children:[i.jsx(Hi,{asChild:!0,children:i.jsxs("button",{type:"button","data-testid":"issue-runtime-selector","aria-label":`Run profile for ${e.name}`,className:q(s==="icon"?"inline-flex h-6 w-6 shrink-0 items-center justify-center rounded text-muted-foreground opacity-100 transition-[color,background-color,opacity] hover:bg-accent/70 hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 md:pointer-events-none md:opacity-0 md:group-hover/issue-property:pointer-events-auto md:group-hover/issue-property:opacity-100 md:group-focus-within/issue-property:pointer-events-auto md:group-focus-within/issue-property:opacity-100 data-[state=open]:pointer-events-auto data-[state=open]:opacity-100":"inline-flex min-w-0 items-center gap-1 rounded px-1.5 py-1 text-[11px] text-muted-foreground transition-colors hover:bg-accent/70 hover:text-foreground",a&&"cursor-not-allowed opacity-60"),disabled:a,title:W,children:[i.jsx(f6,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":"true"}),s==="compact"?i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"min-w-0 truncate",children:W}),i.jsx(rs,{className:"h-3 w-3 shrink-0","aria-hidden":"true"})]}):null]})}),i.jsxs(yi,{"data-testid":"issue-runtime-profile-panel","data-runtime-profile-panel":!0,align:"end",side:"bottom",sideOffset:6,collisionPadding:12,className:"surface-overlay w-[19rem] max-w-[calc(100vw-1.5rem)] p-1.5",onInteractOutside:le=>{const ie=le.target;ie instanceof Element&&ie.closest("[data-runtime-profile-submenu]")&&le.preventDefault()},children:[i.jsxs("button",{type:"button",className:"chat-composer-menu-row mb-1",onClick:()=>c(!1),children:[i.jsx(Tw,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),i.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:e.name})]}),i.jsx("div",{className:"border-t border-[color:var(--border-soft)] pt-1",children:ne("staged")}),i.jsxs("div",{className:"mt-2 flex justify-end gap-2 border-t border-border pt-2",children:[i.jsx("button",{type:"button",className:"rounded px-2 py-1.5 text-xs text-muted-foreground hover:bg-accent/60",onClick:()=>c(!1),children:"Cancel"}),i.jsx("button",{type:"button","data-testid":"issue-runtime-apply",className:"rounded bg-primary px-2.5 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",onClick:R,children:"Apply"})]})]})]})}function SBn(e){var t,n,r,s,a,o,l,c;return e?((t=e.codebase)==null?void 0:t.scope)==="organization"||((n=e.codebase)==null?void 0:n.scope)==="none"?((r=e.executionWorkspacePolicy)==null?void 0:r.defaultProjectWorkspaceId)??null:((s=e.executionWorkspacePolicy)==null?void 0:s.defaultProjectWorkspaceId)??((o=(a=e.workspaces)==null?void 0:a.find(d=>d.isPrimary))==null?void 0:o.id)??((c=(l=e.workspaces)==null?void 0:l[0])==null?void 0:c.id)??null:null}function xm({label:e,children:t,align:n="center"}){return i.jsxs("div",{"data-slot":"issue-property-row","data-align":n,className:q("group/issue-property flex gap-3 py-1.5",n==="start"?"items-start":"items-center"),children:[i.jsx("span",{className:"text-xs text-muted-foreground shrink-0 w-20",children:e}),i.jsx("div",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:t})]})}function IO({inline:e,label:t,open:n,onOpenChange:r,triggerContent:s,triggerAriaLabel:a,triggerClassName:o,popoverClassName:l,popoverAlign:c="end",rowAlign:d="center",extra:u,children:f}){const m=q("inline-flex min-w-0 max-w-full items-center gap-1.5 cursor-pointer hover:bg-accent/50 rounded px-1 -mx-1 py-0.5 transition-colors",o);return e?i.jsxs("div",{children:[i.jsxs(xm,{label:t,align:d,children:[i.jsx("button",{type:"button",className:m,"aria-label":a,onClick:()=>r(!n),children:s}),u]}),n&&i.jsx("div",{className:q("rounded-md border border-border bg-popover p-1 mb-2",l),children:f})]}):i.jsxs(xm,{label:t,align:d,children:[i.jsxs(bi,{open:n,onOpenChange:r,children:[i.jsx(Hi,{asChild:!0,children:i.jsx("button",{type:"button",className:m,"aria-label":a,children:s})}),i.jsx(yi,{className:q("p-1",l),align:c,collisionPadding:16,children:f})]}),u]})}function dH({issue:e,onUpdate:t,inline:n,childIssues:r,showAuditFields:s=!0,showAuditSeparator:a=!0}){var Pe,Re,Nt,Wt,Jt,Ze,Mt;const{selectedOrganizationId:o}=Mr(),{openNewIssue:l}=Bs(),{pushToast:c}=ws(),d=er(),u=e.orgId??o,[f,m]=A.useState(!1),[h,p]=A.useState(""),[x,b]=A.useState(!1),[y,w]=A.useState(""),[k,S]=A.useState(!1),[j,C]=A.useState(""),[I,N]=A.useState(!1),[M,E]=A.useState(""),[_,z]=A.useState(!1),[T,$]=A.useState(!1),[B,F]=A.useState(""),[W,Y]=A.useState(!1),[G,V]=A.useState(""),L=is(),R=is(),{data:D}=Ve({queryKey:U.auth.session,queryFn:()=>Ll.getSession()}),X=((Pe=D==null?void 0:D.user)==null?void 0:Pe.id)??((Re=D==null?void 0:D.session)==null?void 0:Re.userId),ee=G0(),se=Ae=>Ae&&Ae===X?ee:null,{data:ne}=Ve({queryKey:U.agents.list(u),queryFn:()=>$n.list(u),enabled:!!u}),{data:le}=Ve({queryKey:U.projects.list(u),queryFn:()=>Wi.list(u),enabled:!!u}),ie=A.useMemo(()=>(le??[]).filter(Ae=>!Ae.archivedAt||Ae.id===e.projectId),[le,e.projectId]),{orderedProjects:re}=PR({projects:ie,orgId:u,userId:X}),{data:de}=Ve({queryKey:U.issues.labels(u),queryFn:()=>fr.listLabels(u),enabled:!!u}),{data:Be}=Ve({queryKey:U.issues.list(u),queryFn:()=>fr.list(u),enabled:!!u}),ae=xt({mutationFn:Ae=>fr.createLabel(u,Ae),onSuccess:async Ae=>{await d.invalidateQueries({queryKey:U.issues.labels(u)}),t({labelIds:[...e.labelIds??[],Ae.id]}),V("")}}),Ee=Ae=>{const ht=e.labelIds??[],Lt=ht.includes(Ae)?ht.filter(Mn=>Mn!==Ae):[...ht,Ae];t({labelIds:Lt})},he=Ae=>{if(!Ae||!ne)return null;const ht=ne.find(Lt=>Lt.id===Ae);return(ht==null?void 0:ht.name)??Ae.slice(0,8)},_e=A.useMemo(()=>new Map((ne??[]).map(Ae=>[Ae.id,Ae])),[ne]),Ie=Ae=>{if(!Ae)return(Ae==null?void 0:Ae.slice(0,8))??"None";const ht=re.find(Lt=>Lt.id===Ae);return(ht==null?void 0:ht.name)??Ae.slice(0,8)},$e=A.useMemo(()=>new Map((Be??[]).map(Ae=>[Ae.id,Ae])),[Be]),ce=A.useCallback(Ae=>{var ht;return((ht=Ae.project)==null?void 0:ht.name)??(Ae.projectId?Ie(Ae.projectId):null)},[re]),Oe=Ae=>Ae.identifier??Ae.id.slice(0,8),Ye=A.useCallback((Ae,ht)=>{const Lt=ht.trim().toLowerCase();return Lt?`${Ae.identifier??""} ${Ae.title}`.toLowerCase().includes(Lt):!0},[]),J=A.useCallback((Ae,ht)=>{var Ln;let Lt=Ae.parentId;const Mn=new Set;for(;Lt;){if(Lt===ht)return!0;if(Mn.has(Lt))return!1;Mn.add(Lt),Lt=((Ln=$e.get(Lt))==null?void 0:Ln.parentId)??null}return!1},[$e]),qe=e.parentId?((Nt=e.ancestors)==null?void 0:Nt[0])??$e.get(e.parentId)??null:null,be=A.useMemo(()=>(r??[]).slice(0,5),[r]),ot=()=>{z(!1),$(!1),l({parentId:e.id,parentIssue:{id:e.id,identifier:e.identifier,title:e.title},...e.projectId?{projectId:e.projectId}:{},...e.goalId?{goalId:e.goalId}:{}})},ke=xt({mutationFn:Ae=>fr.update(Ae.id,{parentId:e.id}),onSuccess:async(Ae,ht)=>{$(!1),F(""),await d.invalidateQueries({queryKey:U.issues.detail(e.id)}),await d.invalidateQueries({queryKey:U.issues.detail(Ae.id)}),Ae.identifier&&await d.invalidateQueries({queryKey:U.issues.detail(Ae.identifier)}),u&&(await d.invalidateQueries({queryKey:U.issues.list(u)}),await d.invalidateQueries({queryKey:U.issues.children(u,e.id)}),ht.parentId&&await d.invalidateQueries({queryKey:U.issues.children(u,ht.parentId)}))},onError:Ae=>{c({title:Ae instanceof Error?Ae.message:"Failed to add existing issue",tone:"error"})}}),Ce=A.useMemo(()=>(Be??[]).filter(Ae=>Ae.id!==e.id).filter(Ae=>!J(Ae,e.id)).filter(Ae=>Ye(Ae,M)).slice(0,12),[Be,e.id,Ye,J,M]),ue=A.useMemo(()=>(Be??[]).filter(Ae=>Ae.id!==e.id).filter(Ae=>Ae.parentId!==e.id).filter(Ae=>!(e.ancestors??[]).some(ht=>ht.id===Ae.id)).filter(Ae=>Ye(Ae,B)).slice(0,12),[Be,B,e.ancestors,e.id,Ye]),mt=Ae=>{if(!Ae)return null;const ht=(le==null?void 0:le.find(Lt=>Lt.id===Ae))??null;return ht?Gj(ht):`/projects/${Ae}`},ut=A.useMemo(()=>SL(),[f]),ge=A.useMemo(()=>ZS((ne??[]).filter(Ae=>Ae.status!=="terminated"),ut),[ne,ut]),Le=e.assigneeAgentId?ne==null?void 0:ne.find(Ae=>Ae.id===e.assigneeAgentId):null,rt=e.reviewerAgentId?ne==null?void 0:ne.find(Ae=>Ae.id===e.reviewerAgentId):null,At=Ae=>NA(Ae,X),Ue=At(e.assigneeUserId),Se=At(e.reviewerUserId),We=At(e.createdByUserId),Te=(e.labels??[]).length>0?i.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[(e.labels??[]).slice(0,3).map(Ae=>i.jsx(Zk,{label:Ae,size:"sm"},Ae.id)),(e.labels??[]).length>3&&i.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",(e.labels??[]).length-3]})]}):i.jsxs(i.Fragment,{children:[i.jsx(Hae,{className:"h-3.5 w-3.5 text-muted-foreground"}),i.jsx("span",{className:"text-sm text-muted-foreground",children:"No labels"})]}),He=Iw(G),fe=A.useMemo(()=>(de??[]).filter(Ae=>He?Ae.name.toLowerCase().includes(He.toLowerCase()):!0),[de,He]),je=A.useMemo(()=>dht(de??[],He),[de,He]),ye=He.length>0&&fe.length===0&&!je,tt=cve(He),me=A.useCallback(()=>{!ye||ae.isPending||ae.mutate({name:He,color:tt})},[ae,tt,He,ye]),ze=i.jsxs(i.Fragment,{children:[i.jsx("input",{className:"w-full px-2 py-1.5 text-xs bg-transparent outline-none border-b border-border mb-1 placeholder:text-muted-foreground/50",placeholder:"Search labels...",value:G,onChange:Ae=>V(Ae.target.value),onKeyDown:Ae=>{Ae.key!=="Enter"||!ye||(Ae.preventDefault(),me())},autoFocus:!n}),i.jsxs("div",{className:"max-h-44 overflow-y-auto overscroll-contain space-y-0.5",children:[fe.map(Ae=>{const ht=(e.labelIds??[]).includes(Ae.id);return i.jsxs("button",{className:q("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-left",ht&&"bg-accent"),onClick:()=>Ee(Ae.id),children:[i.jsx("span",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:Ae.color}}),i.jsx("span",{className:"truncate",children:Ae.name})]},Ae.id)}),ye&&i.jsxs(i.Fragment,{children:[fe.length>0?i.jsx("div",{className:"my-1 border-t border-border"}):null,i.jsxs("button",{className:"flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 text-left",disabled:ae.isPending,onClick:me,children:[i.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-sm border border-border/70 text-muted-foreground",children:i.jsx(ps,{className:"h-2.5 w-2.5"})}),i.jsx("span",{className:"truncate",children:ae.isPending?"Creating…":`Create label "${He}"`}),i.jsx("span",{className:"ml-auto h-2.5 w-2.5 shrink-0 rounded-full",style:{backgroundColor:tt},"aria-hidden":"true"})]})]})]})]}),De=Le?i.jsx(Ro,{kind:"agent",label:Le.name,agentAvatarStyle:"bare",agentIcon:Le.icon,agentRole:Le.role,className:"w-full"}):Ue?i.jsx(Ro,{kind:"user",label:Ue,avatarUrl:se(e.assigneeUserId)}):i.jsx(Ro,{kind:"unassigned",label:"Unassigned",muted:!0}),kt=i.jsxs(i.Fragment,{children:[i.jsx("input",{className:"w-full px-2 py-1.5 text-xs bg-transparent outline-none border-b border-border mb-1 placeholder:text-muted-foreground/50",placeholder:"Search assignees...",value:h,onChange:Ae=>p(Ae.target.value),autoFocus:!n}),i.jsxs("div",{ref:L,"data-testid":"issue-properties-assignee-scroll",className:"scrollbar-auto-hide max-h-60 overflow-y-auto overscroll-contain",children:[i.jsx("button",{className:q("flex min-w-0 items-center gap-2 w-full px-2 py-1.5 text-left text-xs rounded hover:bg-accent/50",!e.assigneeAgentId&&!e.assigneeUserId&&"bg-accent"),onClick:()=>{t({assigneeAgentId:null,assigneeUserId:null,assigneeAgentRuntimeOverrides:null}),m(!1)},children:i.jsx(Ro,{kind:"unassigned",label:"No assignee"})}),X&&i.jsx("button",{className:q("flex min-w-0 items-center gap-2 w-full px-2 py-2 text-left text-xs rounded hover:bg-accent/50",e.assigneeUserId===X&&"bg-accent"),onClick:()=>{t({assigneeAgentId:null,assigneeUserId:X,assigneeAgentRuntimeOverrides:null}),m(!1)},children:i.jsx(ufe,{avatarUrl:ee})}),e.createdByUserId&&e.createdByUserId!==X&&i.jsx("button",{className:q("flex min-w-0 items-center gap-2 w-full px-2 py-1.5 text-left text-xs rounded hover:bg-accent/50",e.assigneeUserId===e.createdByUserId&&"bg-accent"),onClick:()=>{t({assigneeAgentId:null,assigneeUserId:e.createdByUserId,assigneeAgentRuntimeOverrides:null}),m(!1)},children:i.jsx(Ro,{kind:"user",label:We?`Assign to ${We}`:"Assign to requester",avatarUrl:se(e.createdByUserId)})}),ge.filter(Ae=>{if(!h.trim())return!0;const ht=h.toLowerCase();return`${of(Ae)} ${Ae.name} ${Ae.role} ${Ae.title??""}`.toLowerCase().includes(ht)}).map(Ae=>i.jsx("div",{className:q("flex min-w-0 items-center gap-1 w-full rounded hover:bg-accent/50",Ae.id===e.assigneeAgentId&&"bg-accent"),children:i.jsx("button",{type:"button",className:"flex min-w-0 flex-1 items-center gap-2 px-2 py-2 text-left text-xs",onClick:()=>{if(Ae.id===e.assigneeAgentId){m(!1);return}Kk(Ae.id),t({assigneeAgentId:Ae.id,assigneeUserId:null,assigneeAgentRuntimeOverrides:null}),m(!1)},children:i.jsx(yh,{agent:Ae})})},Ae.id))]})]}),gt=rt?i.jsx(Ro,{kind:"agent",label:rt.name,agentAvatarStyle:"bare",agentIcon:rt.icon,agentRole:rt.role,className:"w-full"}):Se?i.jsx(Ro,{kind:"user",label:Se,avatarUrl:se(e.reviewerUserId)}):i.jsx(Ro,{kind:"unassigned",label:"No reviewer",muted:!0}),Ke=i.jsxs(i.Fragment,{children:[i.jsx("input",{className:"w-full px-2 py-1.5 text-xs bg-transparent outline-none border-b border-border mb-1 placeholder:text-muted-foreground/50",placeholder:"Search reviewers...",value:y,onChange:Ae=>w(Ae.target.value),autoFocus:!n}),i.jsxs("div",{ref:R,"data-testid":"issue-properties-reviewer-scroll",className:"scrollbar-auto-hide max-h-60 overflow-y-auto overscroll-contain",children:[i.jsx("button",{className:q("flex min-w-0 items-center gap-2 w-full px-2 py-1.5 text-left text-xs rounded hover:bg-accent/50",!e.reviewerAgentId&&!e.reviewerUserId&&"bg-accent"),onClick:()=>{t({reviewerAgentId:null,reviewerUserId:null}),b(!1)},children:i.jsx(Ro,{kind:"unassigned",label:"No reviewer"})}),X&&i.jsx("button",{className:q("flex min-w-0 items-center gap-2 w-full px-2 py-2 text-left text-xs rounded hover:bg-accent/50",e.reviewerUserId===X&&"bg-accent"),onClick:()=>{t({reviewerAgentId:null,reviewerUserId:X}),b(!1)},children:i.jsx(ufe,{avatarUrl:ee})}),ge.filter(Ae=>{if(!y.trim())return!0;const ht=y.toLowerCase();return`${of(Ae)} ${Ae.name} ${Ae.role} ${Ae.title??""}`.toLowerCase().includes(ht)}).map(Ae=>i.jsx("button",{className:q("flex min-w-0 items-center gap-2 w-full px-2 py-2 text-left text-xs rounded hover:bg-accent/50",Ae.id===e.reviewerAgentId&&"bg-accent"),onClick:()=>{Kk(Ae.id),t({reviewerAgentId:Ae.id,reviewerUserId:null}),b(!1)},children:i.jsx(yh,{agent:Ae})},Ae.id))]})]}),Je=e.projectId?i.jsxs(i.Fragment,{children:[i.jsx(Fo,{color:(Wt=re.find(Ae=>Ae.id===e.projectId))==null?void 0:Wt.color,icon:(Jt=re.find(Ae=>Ae.id===e.projectId))==null?void 0:Jt.icon,size:"xs"}),i.jsx("span",{className:"text-sm truncate",children:Ie(e.projectId)}),i.jsx(rs,{className:"h-3 w-3 shrink-0 text-muted-foreground/70","aria-hidden":"true"})]}):i.jsxs(i.Fragment,{children:[i.jsx(d6,{className:"h-3.5 w-3.5 text-muted-foreground"}),i.jsx("span",{className:"text-sm text-muted-foreground",children:"No project"}),i.jsx(rs,{className:"h-3 w-3 shrink-0 text-muted-foreground/70","aria-hidden":"true"})]}),wt=i.jsxs(i.Fragment,{children:[i.jsx("input",{className:"w-full px-2 py-1.5 text-xs bg-transparent outline-none border-b border-border mb-1 placeholder:text-muted-foreground/50",placeholder:"Search projects...",value:j,onChange:Ae=>C(Ae.target.value),autoFocus:!n}),i.jsxs("div",{className:"max-h-48 overflow-y-auto overscroll-contain",children:[i.jsx("button",{className:q("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 whitespace-nowrap",!e.projectId&&"bg-accent"),onClick:()=>{t({projectId:null,projectWorkspaceId:null,executionWorkspaceId:null}),S(!1)},children:"No project"}),re.filter(Ae=>{if(!j.trim())return!0;const ht=j.toLowerCase();return Ae.name.toLowerCase().includes(ht)}).map(Ae=>i.jsxs("button",{className:q("flex items-center gap-2 w-full px-2 py-1.5 text-xs rounded hover:bg-accent/50 whitespace-nowrap",Ae.id===e.projectId&&"bg-accent"),onClick:()=>{t({projectId:Ae.id,projectWorkspaceId:SBn(Ae),executionWorkspaceId:null}),S(!1)},children:[i.jsx(Fo,{color:Ae.color,icon:Ae.icon,size:"xs"}),Ae.name]},Ae.id))]})]}),Z=qe?i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"max-w-20 shrink truncate font-mono text-[11px] text-muted-foreground",children:Oe(qe)}),i.jsx("span",{className:"min-w-0 truncate text-sm",children:qe.title})]}):i.jsxs(i.Fragment,{children:[i.jsx(kk,{className:"h-3.5 w-3.5 text-muted-foreground"}),i.jsx("span",{className:"text-sm text-muted-foreground",children:"No parent"})]}),Me=i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-center gap-1.5 border-b border-border px-2 py-1.5",children:[i.jsx(Al,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("input",{className:"min-w-0 flex-1 bg-transparent text-xs outline-none placeholder:text-muted-foreground/50",placeholder:"Search issues...",value:M,onChange:Ae=>E(Ae.target.value),autoFocus:!n})]}),i.jsxs("div",{className:"max-h-60 overflow-y-auto overscroll-contain p-1",children:[i.jsxs("button",{type:"button",className:q("flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs hover:bg-accent/50",!e.parentId&&"bg-accent"),onClick:()=>{t({parentId:null}),N(!1),E("")},children:[i.jsx(kk,{className:"h-3.5 w-3.5 text-muted-foreground"}),"No parent"]}),Ce.length>0?Ce.map(Ae=>{const ht=ce(Ae);return i.jsxs("button",{type:"button",className:q("grid w-full grid-cols-[auto_minmax(0,1fr)] items-center gap-x-2 rounded px-2 py-1.5 text-left text-xs hover:bg-accent/50",Ae.id===e.parentId&&"bg-accent"),onClick:()=>{t({parentId:Ae.id}),N(!1),E("")},children:[i.jsx("span",{className:"font-mono text-[11px] text-muted-foreground",children:Oe(Ae)}),i.jsx("span",{className:"min-w-0 truncate",children:Ae.title}),ht&&Ae.projectId!==e.projectId?i.jsx("span",{className:"col-start-2 min-w-0 truncate text-[11px] text-muted-foreground",children:ht}):null]},Ae.id)}):i.jsx("p",{className:"px-2 py-2 text-xs text-muted-foreground",children:"No matching issues."})]})]}),lt=T?i.jsxs("div",{className:q("shrink-0 rounded-md border border-border bg-popover p-1",n?"w-full":void 0),style:n?void 0:{width:"480px",maxWidth:"calc(100vw - 2rem)"},children:[i.jsxs("div",{className:"flex items-center gap-1.5 border-b border-border px-2 py-1.5",children:[i.jsx(Al,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("input",{className:"min-w-0 flex-1 bg-transparent text-xs outline-none placeholder:text-muted-foreground/50",placeholder:"Search existing issues...",value:B,onChange:Ae=>F(Ae.target.value),autoFocus:!n})]}),i.jsx("div",{className:"max-h-56 overflow-y-auto overscroll-contain py-1",children:ue.length>0?ue.map(Ae=>{const ht=ce(Ae),Lt=Ae.parentId?$e.get(Ae.parentId)??null:null;return i.jsxs("button",{type:"button",className:"grid w-full grid-cols-[auto_minmax(0,1fr)] items-center gap-x-2 rounded px-2 py-1.5 text-left text-xs hover:bg-accent/50 disabled:cursor-wait disabled:opacity-60",onClick:()=>ke.mutate(Ae),disabled:ke.isPending,children:[i.jsx("span",{className:"font-mono text-[11px] text-muted-foreground",children:Oe(Ae)}),i.jsx("span",{className:"min-w-0 truncate",children:Ae.title}),i.jsx("span",{className:"col-start-2 min-w-0 truncate text-[11px] text-muted-foreground",children:Lt?`Move from ${Oe(Lt)}`:ht&&Ae.projectId!==e.projectId?ht:"No parent"})]},Ae.id)}):i.jsx("p",{className:"px-2 py-2 text-xs text-muted-foreground",children:"No matching issues."})})]}):null;return i.jsxs("div",{className:"space-y-4",children:[i.jsxs("div",{className:"space-y-1",children:[i.jsx(xm,{label:"Status",children:i.jsx(ki,{status:e.status,onChange:Ae=>t({status:Ae}),showLabel:!0})}),i.jsx(xm,{label:"Priority",children:i.jsx(Dc,{priority:e.priority,onChange:Ae=>t({priority:Ae}),showLabel:!0})}),i.jsx(IO,{inline:n,label:"Labels",open:W,onOpenChange:Ae=>{Y(Ae),Ae||V("")},triggerContent:Te,triggerClassName:"min-w-0 max-w-full",popoverClassName:"w-64",children:ze}),i.jsx(IO,{inline:n,label:"Assignee",open:f,onOpenChange:Ae=>{m(Ae),Ae||p("")},triggerContent:De,triggerClassName:"min-w-0 max-w-full flex-1 justify-start overflow-hidden",popoverClassName:"w-[19rem]",popoverAlign:"start",rowAlign:"start",extra:Le&&u&&pve(Le)?i.jsx(uY,{agent:Le,orgId:u,overrides:e.assigneeAgentRuntimeOverrides,variant:"icon",onApply:Ae=>t({assigneeAgentRuntimeOverrides:Ae})}):null,children:kt}),i.jsx(IO,{inline:n,label:"Reviewer",open:x,onOpenChange:Ae=>{b(Ae),Ae||w("")},triggerContent:gt,triggerClassName:"min-w-0 max-w-full flex-1 justify-start overflow-hidden",popoverClassName:"w-[19rem]",popoverAlign:"start",rowAlign:"start",children:Ke}),i.jsx(IO,{inline:n,label:"Project",open:k,onOpenChange:Ae=>{S(Ae),Ae||C("")},triggerContent:Je,triggerAriaLabel:`Change project: ${e.projectId?Ie(e.projectId):"No project"}`,triggerClassName:"min-w-0 max-w-full",popoverClassName:"w-fit min-w-[11rem]",extra:e.projectId?i.jsx(gn,{to:mt(e.projectId),"aria-label":"Open project",className:"inline-flex items-center justify-center h-5 w-5 rounded hover:bg-accent/50 transition-colors text-muted-foreground hover:text-foreground",onClick:Ae=>Ae.stopPropagation(),children:i.jsx(Jy,{className:"h-3 w-3"})}):void 0,children:wt}),i.jsx(IO,{inline:n,label:"Parent issue",open:I,onOpenChange:Ae=>{N(Ae),Ae||E("")},triggerContent:Z,triggerClassName:"min-w-0 max-w-full",popoverClassName:"w-72",extra:qe?i.jsx(gn,{to:dN(qe),"aria-label":"Open parent issue",className:"inline-flex h-5 w-5 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",onClick:Ae=>Ae.stopPropagation(),children:i.jsx(Jy,{className:"h-3 w-3"})}):void 0,children:Me}),r?i.jsxs("div",{className:"py-1.5",children:[i.jsxs("div",{className:"flex items-center gap-3",children:[i.jsx("span",{className:"w-20 shrink-0 text-xs text-muted-foreground",children:"Sub-issues"}),i.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[i.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-center gap-1.5 rounded px-1 py-0.5 text-left transition-colors hover:bg-accent/50 disabled:pointer-events-none",onClick:()=>$(Ae=>!Ae),"aria-label":"Show sub-issue picker",children:[i.jsx(kk,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"rounded-sm border border-border px-1.5 py-0.5 text-[11px] leading-none text-muted-foreground",children:r.length})]}),i.jsxs(bi,{open:_,onOpenChange:z,children:[i.jsx(Hi,{asChild:!0,children:i.jsxs("button",{type:"button",className:"ml-auto inline-flex h-6 items-center gap-1 rounded border border-border px-1.5 text-[11px] text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:[i.jsx(ps,{className:"h-3 w-3"}),"Add"]})}),i.jsxs(yi,{className:"w-44 p-1",align:"end",collisionPadding:16,children:[i.jsx("button",{type:"button",className:"w-full rounded px-2 py-1.5 text-left text-xs hover:bg-accent/50",onClick:ot,children:"Create new sub-issue"}),i.jsx("button",{type:"button",className:"w-full rounded px-2 py-1.5 text-left text-xs hover:bg-accent/50",onClick:()=>{z(!1),$(!0)},children:"Add existing issue"})]})]})]})]}),i.jsxs("div",{className:"mt-1.5 min-w-0 space-y-1",children:[lt?i.jsx("div",{className:q(n?void 0:"flex justify-end"),children:lt}):null,i.jsxs("div",{className:q("min-w-0 space-y-1",n?"ml-0":"ml-[5.75rem]"),children:[be.length===0?i.jsx("button",{type:"button",className:"w-full rounded px-1 py-1 text-left text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",onClick:ot,children:"No sub-issues."}):be.map(Ae=>{const ht=Ae.identifier??Ae.id,Lt=Ae.identifier??Ae.id.slice(0,8);return i.jsxs(gn,{to:`/issues/${ht}`,className:"grid max-w-full min-w-0 grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-1.5 overflow-hidden rounded px-1 py-1 text-xs transition-colors hover:bg-accent/50",title:Ae.title,children:[i.jsx(ki,{status:Ae.status}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:Ae.title}),i.jsx("span",{className:"min-w-0 max-w-[5.5rem] truncate font-mono text-[11px] text-muted-foreground",children:Lt})]},Ae.id)}),r.length>be.length?i.jsxs("p",{className:"px-1 text-[11px] text-muted-foreground",children:["+",r.length-be.length," more"]}):null]})]})]}):null,e.requestDepth>0&&i.jsx(xm,{label:"Depth",children:i.jsx("span",{className:"text-sm font-mono",children:e.requestDepth})})]}),s?i.jsxs(i.Fragment,{children:[a?i.jsx(g1,{}):null,i.jsxs("div",{className:"space-y-1",children:[(e.createdByAgentId||e.createdByUserId)&&i.jsx(xm,{label:"Created by",children:e.createdByAgentId?i.jsx(gn,{to:`/agents/${e.createdByAgentId}`,className:"hover:underline",children:i.jsx(zl,{name:he(e.createdByAgentId)??e.createdByAgentId.slice(0,8),icon:e.createdByAgentId?(Ze=_e.get(e.createdByAgentId))==null?void 0:Ze.icon:null,role:e.createdByAgentId?(Mt=_e.get(e.createdByAgentId))==null?void 0:Mt.role:null,size:"sm"})}):i.jsx(Ro,{kind:"user",label:We??"User",avatarUrl:se(e.createdByUserId)})}),e.startedAt&&i.jsx(xm,{label:"Started",children:i.jsx("span",{className:"text-sm",children:Pm(e.startedAt)})}),e.completedAt&&i.jsx(xm,{label:"Completed",children:i.jsx("span",{className:"text-sm",children:Pm(e.completedAt)})}),i.jsx(xm,{label:"Created",children:i.jsx("span",{className:"text-sm",children:So(e.createdAt)})}),i.jsx(xm,{label:"Updated",children:i.jsx("span",{className:"text-sm",children:Uf(e.updatedAt)})})]})]}):null]})}const Jse={activeViewInstanceId:null,tabOrder:[],tabsByViewInstanceId:{},runtimesById:{},promotionsById:{}},kht=A.createContext(null);function Oht(){var e,t;return((t=(e=globalThis.crypto)==null?void 0:e.randomUUID)==null?void 0:t.call(e))??`view-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function jBn(e,t){if(e.kind!=="automation"&&e.kind!=="browser"&&e.kind!=="library_directory"&&e.kind!=="library_document"&&e.kind!=="library_entry"&&e.kind!=="library_file"&&e.kind!=="local_app")return null;const n=t??e.viewInstanceId??(e.kind==="browser"?e.tabId:Oht());return{...e,viewInstanceId:n}}function Sht(e,t){return JSON.stringify([e,t.kind,t.viewInstanceId])}function CBn({children:e,createId:t=Oht,initialState:n}){const[r,s]=A.useState(()=>n??AXt()),a=A.useRef(r);a.current=r;const o=A.useCallback(u=>{const f=$Xt(a.current,u);return a.current=f,s(f),f},[]),l=A.useCallback(()=>a.current,[]),c=A.useCallback((u,f,m)=>{o({type:"tab/unbind-saved-view",organizationId:u,viewInstanceId:f,savedViewId:m})},[o]),d=A.useMemo(()=>({createId:t,dispatch:o,getState:l,state:r,unbindSavedViewForOrganization:c}),[t,o,l,r,c]);return i.jsx(kht.Provider,{value:d,children:e})}function xve(){const e=A.useContext(kht);if(!e)throw new Error("useMainWorkbench must be used inside MainWorkbenchProvider");return e}function fY(e){const{createId:t,dispatch:n,getState:r,state:s}=xve(),a=Ege(),o=(e==null?void 0:e.trim())??"",l=o?s.organizations[o]??Jse:Jse,c=A.useCallback(()=>(o?r().organizations[o]:null)??Jse,[r,o]),d=A.useCallback(()=>{const I=r();if(!a)return hXt(I,o);const N=I.organizations[o],M=Object.values((N==null?void 0:N.runtimesById)??{}).filter(E=>E.targetKind==="browser"&&E.host.kind!=="crashed"&&E.host.kind!=="disposed"&&!a.hasSurface(E.id)).length;return a.getLiveBrowserCount(o)+M},[r,a,o]),u=A.useCallback(I=>{var _;return o?I.target.kind==="browser"&&!(a!=null&&a.hasSurface(I.runtimeId))&&d()>=xw?{admitted:!1,reason:"browser_capacity",viewInstanceId:null}:!!((_=n({type:"session-tab/create",organizationId:o,tab:I}).organizations[o])!=null&&_.tabsByViewInstanceId[I.viewInstanceId])?{admitted:!0,reason:null,viewInstanceId:I.viewInstanceId}:{admitted:!1,reason:"rejected",viewInstanceId:null}:{admitted:!1,reason:"rejected",viewInstanceId:null}},[n,d,a,o]),f=A.useCallback(I=>{const N=jBn(I??{...j6(),tabId:t()},(I==null?void 0:I.viewInstanceId)??(I==null?void 0:I.tabId)??t());return!N||N.kind!=="browser"||!o?{admitted:!1,reason:"rejected",viewInstanceId:null}:u({viewInstanceId:N.viewInstanceId,runtimeId:Sht(o,N),target:N,originContextKey:"messenger:workbench"})},[t,u,o]),m=A.useCallback((I,N)=>{var z;return!o||!I?{admitted:!1,reason:"rejected",viewInstanceId:null}:N.target.kind==="browser"&&!(a!=null&&a.hasSurface(N.runtimeId))&&d()>=xw?{admitted:!1,reason:"browser_capacity",viewInstanceId:null}:!!((z=n({type:"saved-tab/open",organizationId:o,savedViewId:I,tab:N}).organizations[o])!=null&&z.tabsByViewInstanceId[N.viewInstanceId])?{admitted:!0,reason:null,viewInstanceId:N.viewInstanceId}:{admitted:!1,reason:"rejected",viewInstanceId:null}},[n,d,a,o]),h=A.useCallback(I=>{o&&n({type:"tab/focus",organizationId:o,viewInstanceId:I})},[n,o]),p=A.useCallback((I,N)=>{o&&n({type:"tab/reorder",organizationId:o,viewInstanceId:I,toIndex:N})},[n,o]),x=A.useCallback(I=>{o&&n({type:"tab/close",organizationId:o,viewInstanceId:I})},[n,o]),b=A.useCallback((I,N)=>{o&&n({type:"tab/bind-saved-view",organizationId:o,viewInstanceId:I,savedViewId:N})},[n,o]),y=A.useCallback((I,N)=>{o&&n({type:"tab/unbind-saved-view",organizationId:o,viewInstanceId:I,savedViewId:N})},[n,o]),w=A.useCallback((I,N,M)=>{o&&(n({type:"runtime/update-target",organizationId:o,runtimeId:I,viewInstanceId:N,target:M}),n({type:"tab/update-target",organizationId:o,runtimeId:I,viewInstanceId:N,target:M}))},[n,o]),k=A.useCallback(I=>{o&&n({type:"runtime/admit",organizationId:o,runtime:I})},[n,o]),S=A.useCallback((I,N)=>{o&&n({type:"runtime/set-host",organizationId:o,runtimeId:I,host:N})},[n,o]),j=l.tabOrder.flatMap(I=>{const N=l.tabsByViewInstanceId[I];return N?[N]:[]}),C=l.activeViewInstanceId?l.tabsByViewInstanceId[l.activeViewInstanceId]??null:null;return A.useMemo(()=>({activeTab:C,activeViewInstanceId:l.activeViewInstanceId,admitRuntime:k,bindSavedView:b,canCreateBrowser:d()<xw,closeTab:x,createSessionBrowser:f,createSessionTab:u,dispatch:n,focusTab:h,getState:c,liveBrowserCount:d,openSavedTab:m,promotionsById:l.promotionsById,reorderTab:p,runtimesById:l.runtimesById,setRuntimeHost:S,tabOrder:l.tabOrder,tabs:j,tabsByViewInstanceId:l.tabsByViewInstanceId,unbindSavedView:y,updateTarget:w}),[C,k,b,x,f,u,n,h,c,o,m,l.activeViewInstanceId,l.promotionsById,l.runtimesById,l.tabOrder,l.tabsByViewInstanceId,p,S,s,j,y,w])}const jht=A.createContext(null);function NBn(e){var t,n;return((n=(t=globalThis.crypto)==null?void 0:t.randomUUID)==null?void 0:n.call(t))??`${e}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function ame(e){if(!jm(e)||e.kind!=="automation"&&e.kind!=="browser"&&e.kind!=="library_directory"&&e.kind!=="library_document"&&e.kind!=="library_entry"&&e.kind!=="library_file"&&e.kind!=="local_app")return null;const t=e.viewInstanceId??(e.kind==="browser"?e.tabId:null);return t?{...e,viewInstanceId:t}:null}function eP(e,t,n){const r=ame(n);return r?JSON.stringify([e,t,r.kind,r.viewInstanceId]):""}function eie(e,t){return JSON.stringify([e.trim(),t])}function IBn(e,t,n){const{group:r,savedView:s}=n;e.setQueryData(U.messenger.savedView(t,s.id),s);const a=U.messenger.customGroups(t);e.getQueryData(a)!==void 0&&e.setQueryData(a,o=>{const l=`saved-view:${s.id}`,c=(o==null?void 0:o.groups)??[];if(!r)return{groups:c.map(m=>({...m,entries:m.entries.filter(h=>h.item.type!=="saved_view"||h.item.savedView.id!==s.id)}))};const d=s.updatedAt??new Date,u={id:`optimistic:${l}`,orgId:s.orgId,userId:s.userId,groupId:r.id,itemKey:l,sortOrder:0,createdAt:s.createdAt??d,updatedAt:d,item:{type:"saved_view",itemKey:l,title:s.title,savedView:s}};return c.find(m=>m.id===r.id)?{groups:c.map(m=>{if(m.id!==r.id)return{...m,entries:m.entries.filter(p=>p.item.type!=="saved_view"||p.item.savedView.id!==s.id)};const h=m.entries.filter(p=>p.item.type!=="saved_view"||p.item.savedView.id!==s.id);return{...m,entries:[...h,{...u,sortOrder:h.length}]}})}:{groups:[...c.map(m=>({...m,entries:m.entries.filter(h=>h.item.type!=="saved_view"||h.item.savedView.id!==s.id)})),{id:r.id,orgId:s.orgId,userId:s.userId,name:r.name,icon:null,sortOrder:c.length,collapsed:!1,pinnedAt:null,createdAt:d,updatedAt:d,entries:[u]}]}})}function PBn(e){return e instanceof Error?e.message:"Could not move this view."}class TBn extends Error{constructor(){super("Keeping this view timed out. Retry to check whether it was saved."),this.name="PersistenceTimeoutError"}}function _Bn(e,t){return new Promise((n,r)=>{const s=globalThis.setTimeout(()=>r(new TBn),t);e.then(a=>{globalThis.clearTimeout(s),n(a)},a=>{globalThis.clearTimeout(s),r(a)})})}function MBn({children:e,claimTimeoutMs:t=5e3,persistenceTimeoutMs:n=15e3}){const r=Kr(),s=Ir(),a=er(),o=Qm(),l=xve(),c=mWe(),d=yR(),u=A.useRef(new Set),f=A.useRef(new Map),m=A.useRef(new Map),h=A.useRef(c==null?void 0:c.selectedOrganizationId);h.current=c==null?void 0:c.selectedOrganizationId;const[p,x]=A.useState(0),b=A.useCallback(()=>x(T=>T+1),[]),y=A.useCallback(T=>{d.setInteractionLocked(T.runtimeId,!1),u.current.delete(T.key),b()},[d,b]),w=A.useCallback(async(T,$)=>{var R,D;const B=T.request.organizationId.trim();if(h.current!==void 0&&h.current!==B)throw d.claimSurface(T.runtimeId,T.sideOwnerId),l.dispatch({type:"promotion/claim-fail",organizationId:B,promotionId:T.promotionId,savedViewId:$.savedView.id,expectedSourceRevision:T.sourceRevision,error:"organization_changed"}),y(T),new Error("Saved in Messenger. Return to the original organization to retry the move.");const F=()=>{var ee;if(!m.current.has(eie(B,$.savedView.id)))return!1;d.claimSurface(T.runtimeId,T.sideOwnerId);const X=(ee=l.getState().organizations[B])==null?void 0:ee.promotionsById[T.promotionId];return(X==null?void 0:X.status)==="claiming"?l.dispatch({type:"promotion/claim-fail",organizationId:B,promotionId:T.promotionId,savedViewId:$.savedView.id,expectedSourceRevision:T.sourceRevision,error:"saved_view_removal_pending"}):(X==null?void 0:X.status)==="detaching"&&l.dispatch({type:"promotion/detach-fail",organizationId:B,promotionId:T.promotionId,savedViewId:$.savedView.id,expectedSourceRevision:T.sourceRevision,error:"saved_view_removal_pending"}),y(T),!0};if(F())throw new Error("Saved View removal interrupted this move.");if(o.holdDisplayedContext(B,T.request.contextKey),((D=(R=l.dispatch({type:"promotion/claim",organizationId:B,promotionId:T.promotionId,savedViewId:$.savedView.id,expectedSourceRevision:T.sourceRevision}).organizations[B])==null?void 0:R.promotionsById[T.promotionId])==null?void 0:D.status)!=="detaching")throw y(T),new Error("The Saved View was kept, but Main could not stage it.");r(tC($.savedView.id));const Y=await d.waitForOwner(T.runtimeId,T.mainOwnerId,t);if(F())throw new Error("Saved View removal interrupted this move.");if(!(Y&&d.claimSurface(T.runtimeId,T.mainOwnerId)))throw d.claimSurface(T.runtimeId,T.sideOwnerId),l.dispatch({type:"promotion/detach-fail",organizationId:B,promotionId:T.promotionId,savedViewId:$.savedView.id,expectedSourceRevision:T.sourceRevision,error:"main_anchor_claim_failed"}),y(T),new Error("Saved in Messenger, but Main is not ready. Retry the move.");if(F())throw new Error("Saved View removal interrupted this move.");const V=o.detachTargetForContext(T.request.contextKey,T.exactKey,T.sourceRevision);if(!V.detached)throw d.claimSurface(T.runtimeId,T.sideOwnerId),l.dispatch({type:"promotion/detach-fail",organizationId:B,promotionId:T.promotionId,savedViewId:$.savedView.id,expectedSourceRevision:T.sourceRevision,error:V.reason}),y(T),new Error("Saved in Messenger, but the Side Panel changed. Retry the move.");l.dispatch({type:"promotion/detach-succeed",organizationId:B,promotionId:T.promotionId,savedViewId:$.savedView.id,expectedSourceRevision:T.sourceRevision});const L=d.getRuntimeTarget(T.runtimeId);return L&&L.kind===T.target.kind&&L.viewInstanceId===T.target.viewInstanceId&&(l.dispatch({type:"runtime/update-target",organizationId:B,runtimeId:T.runtimeId,viewInstanceId:T.target.viewInstanceId,target:L}),l.dispatch({type:"tab/update-target",organizationId:B,runtimeId:T.runtimeId,viewInstanceId:T.target.viewInstanceId,target:L})),f.current.delete(T.key),y(T),$},[t,d,r,o,y,l]),k=A.useCallback((T,$,B)=>{const F=eie(T,$),W=m.current.get(F);if(B){m.current.set(F,{pendingCount:((W==null?void 0:W.pendingCount)??0)+1,removed:(W==null?void 0:W.removed)??!1});return}if(W!=null&&W.removed)return;const Y=Math.max(0,((W==null?void 0:W.pendingCount)??0)-1);Y===0?m.current.delete(F):m.current.set(F,{pendingCount:Y,removed:!1})},[]),S=A.useCallback((T,$)=>{var F,W;const B=T.trim();m.current.set(eie(B,$),{pendingCount:0,removed:!0});for(const Y of Array.from(f.current.values())){if(Y.request.organizationId.trim()!==B)continue;const G=(F=l.getState().organizations[B])==null?void 0:F.promotionsById[Y.promotionId];(((W=Y.result)==null?void 0:W.savedView.id)??(G&&"savedViewId"in G?G.savedViewId:G==null?void 0:G.source.savedViewId))!==$||!G||(d.claimSurface(Y.runtimeId,Y.sideOwnerId),l.dispatch({type:"promotion/cancel-saved-view",organizationId:B,promotionId:Y.promotionId,savedViewId:$,expectedSourceRevision:G.source.sourceRevision}),f.current.delete(Y.key),y(Y))}},[d,y,l]),j=A.useCallback(async T=>{const $=T.request.organizationId.trim();let B;try{B=T.request.existingResult??await _Bn(_s.keepSavedView($,T.request.input),n)}catch(F){throw l.dispatch({type:F instanceof $o?"promotion/server-fail":"promotion/timeout",organizationId:$,promotionId:T.promotionId,expectedSourceRevision:T.sourceRevision,error:PBn(F)}),y(T),F}return T.result=B,IBn(a,$,B),l.dispatch({type:"promotion/server-commit",organizationId:$,promotionId:T.promotionId,savedViewId:B.savedView.id,expectedSourceRevision:T.sourceRevision}),a.invalidateQueries({queryKey:U.messenger.customGroups($)}).catch(()=>{}),w(T,B)},[w,n,a,y,l]),C=A.useCallback(async T=>{var ne,le,ie,re;const $=T.organizationId.trim(),B=ame(T.target);if(!$||!B)throw new Error("This Side Panel view cannot move to Messenger.");const F=fs(T.target),W=o.getTargetRevisionForContext(T.contextKey,F);if(W===null)throw new Error("This Side Panel view is no longer available.");const Y=uM($,B),G=ame(d.getRuntimeTarget(Y)??T.target),V=G&&G.kind===B.kind&&G.viewInstanceId===B.viewInstanceId?G:B,L=iX(V,{clientMutationId:T.input.clientMutationId,placement:T.input.placement})??T.input,R={...T,input:L,target:V},D=eP($,T.contextKey,T.target);if(!D||u.current.has(D))throw new Error("This view is already moving.");if(Array.from(f.current.values()).some(de=>de.runtimeId===Y)||Object.values(((ne=l.getState().organizations[$])==null?void 0:ne.promotionsById)??{}).some(de=>de.source.runtimeId===Y))throw new Error("This runtime is already moving.");if(f.current.has(D))throw new Error("This move has a retained attempt. Use Retry move.");const ee={exactKey:F,key:D,mainOwnerId:`main:${$}:${V.viewInstanceId}`,promotionId:NBn("promotion"),request:R,result:T.existingResult??null,runtimeId:Y,sideOwnerId:`side:${T.contextKey}:${Y}`,sourceRevision:W,target:V};if(f.current.set(D,ee),u.current.add(D),b(),d.setInteractionLocked(Y,!0),l.dispatch({type:"runtime/admit",organizationId:$,runtime:{id:Y,viewInstanceId:V.viewInstanceId,targetKind:V.kind,target:V,host:{kind:"side",contextKey:T.contextKey}}}),((re=(ie=l.dispatch({type:"promotion/start",organizationId:$,promotionId:ee.promotionId,clientMutationId:T.input.clientMutationId,source:{viewInstanceId:V.viewInstanceId,savedViewId:((le=T.existingResult)==null?void 0:le.savedView.id)??null,sourceRevision:W,target:V,originContextKey:T.contextKey,runtimeId:Y}}).organizations[$])==null?void 0:ie.promotionsById[ee.promotionId])==null?void 0:re.status)!=="pending")throw f.current.delete(D),y(ee),new Error("This view could not enter the move transaction.");return j(ee)},[d,j,o,b,y,l]),I=A.useCallback(T=>{var Y,G,V;const $=T.request.organizationId.trim(),B=(Y=l.getState().organizations[$])==null?void 0:Y.promotionsById[T.promotionId];if(!B||B.status!=="server_failed"&&B.status!=="commit_unknown"&&B.status!=="claim_failed")return!1;const F=((G=T.result)==null?void 0:G.savedView.id)??B.source.savedViewId;return F&&s.pathname.endsWith(tC(F))&&r("/messenger/workbench",{replace:!0}),(V=l.dispatch({type:"promotion/discard",organizationId:$,promotionId:T.promotionId,expectedSourceRevision:B.source.sourceRevision}).organizations[$])!=null&&V.promotionsById[T.promotionId]?!1:(f.current.delete(T.key),y(T),!0)},[s.pathname,r,y,l]),N=A.useCallback((T,$,B)=>{const F=f.current.get(eP(T,$,B));return F?I(F):!1},[I]);A.useEffect(()=>o.registerBrowserResetHandler((T,$)=>{var G;const B={...$,viewInstanceId:$.viewInstanceId??$.tabId},F=Array.from(f.current.values()).find(V=>V.request.contextKey===T&&V.runtimeId===uM(V.request.organizationId.trim(),B));if(!F)return"remove";const W=(G=l.getState().organizations[F.request.organizationId.trim()])==null?void 0:G.promotionsById[F.promotionId];return((W==null?void 0:W.status)==="server_failed"||(W==null?void 0:W.status)==="commit_unknown"||(W==null?void 0:W.status)==="claim_failed")&&I(F)?"remove":"preserve"}),[I,o,l]);const M=A.useCallback(async(T,$,B)=>{var se,ne,le;const F=T.trim(),W=eP(F,$,B),Y=f.current.get(W);if(!W||!Y)throw new Error("There is no retained move to retry.");if(u.current.has(W))throw new Error("This view is already moving.");const G=(se=l.getState().organizations[F])==null?void 0:se.promotionsById[Y.promotionId];if(!G||G.status!=="server_failed"&&G.status!=="commit_unknown"&&G.status!=="claim_failed")throw new Error("This move is not ready to retry.");if(o.getTargetRevisionForContext($,Y.exactKey)!==Y.sourceRevision)throw I(Y),new Error("The Side Panel view changed. Start a new move.");const L=o.replaceTargetForContext($,Y.exactKey,{...B}),R=o.getTargetRevisionForContext($,Y.exactKey);if(!L||R===null||R<=Y.sourceRevision)throw new Error("This Side Panel view could not enter retry.");const D=G.status==="server_failed"?"promotion/retry":G.status==="commit_unknown"?"promotion/reconcile":"promotion/claim-retry",X=l.dispatch({type:D,organizationId:F,promotionId:Y.promotionId,expectedSourceRevision:Y.sourceRevision,nextSourceRevision:R}),ee=D==="promotion/reconcile"?"reconciling":D==="promotion/claim-retry"?"claiming":"pending";if(((le=(ne=X.organizations[F])==null?void 0:ne.promotionsById[Y.promotionId])==null?void 0:le.status)!==ee)throw new Error("This move could not enter retry.");if(Y.sourceRevision=R,Y.request={...Y.request,target:{...B}},u.current.add(W),b(),d.setInteractionLocked(Y.runtimeId,!0),D==="promotion/claim-retry"){if(!Y.result)throw y(Y),new Error("The retained Saved View could not be recovered.");return w(Y,Y.result)}return j(Y)},[w,I,d,j,o,b,y,l]),E=A.useCallback((T,$,B)=>u.current.has(eP(T,$,B)),[]),_=A.useCallback((T,$,B)=>{var Y;const F=f.current.get(eP(T,$,B));if(!F)return{clientMutationId:null,error:null,promotionId:null,retryable:!1,status:"idle"};const W=(Y=l.state.organizations[T])==null?void 0:Y.promotionsById[F.promotionId];return W?{clientMutationId:W.clientMutationId,error:"error"in W?W.error:null,promotionId:W.id,retryable:W.status==="server_failed"||W.status==="commit_unknown"||W.status==="claim_failed",status:W.status}:{clientMutationId:F.request.input.clientMutationId,error:null,promotionId:F.promotionId,retryable:!1,status:"idle"}},[l.state]),z=A.useMemo(()=>({discard:N,finalizeSavedViewRemoval:S,getMoveState:_,isMoving:E,promote:C,retry:M,setSavedViewRemovalPending:k}),[N,S,_,E,C,M,p,k]);return i.jsx(jht.Provider,{value:z,children:e})}function bve(){return A.useContext(jht)}function EBn(){var e,t;return((t=(e=globalThis.crypto)==null?void 0:e.randomUUID)==null?void 0:t.call(e))??`00000000-0000-4000-8000-${Math.random().toString(16).slice(2,14).padEnd(12,"0")}`}const DBn=32,RBn="00000000-0000-4000-8000-000000000000",W_e="__messenger_sidebar__";function ome(e){return Array.isArray(e)?`[${e.map(ome).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,n])=>n!==void 0).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${ome(r)}`).join(",")}}`:JSON.stringify(e)}function LBn(e){const{clientMutationId:t,...n}=e;return ome(n)}function zBn(e,t){const n=e.get(t);if(n)return e.delete(t),e.set(t,n),n;const r=EBn();for(e.set(t,r);e.size>DBn;){const s=e.keys().next().value;if(s===void 0)break;e.delete(s)}return r}function $Bn(e,t,n){e.get(t)===n&&e.delete(t)}function FBn(e,t){for(const[n,r]of e)r===t&&e.delete(n)}function BBn({contextKey:e,organizationId:t,target:n}){var j;const{pushToast:r}=ws(),s=bve(),a=er(),o=A.useRef(new Map),l=!!(n&&jm(n)&&(n.kind!=="library_entry"||n.path)),c=e.startsWith("issue:")&&e.slice(6).trim()||null,d=e.startsWith("chat:")||!!c,u=Ve({queryKey:U.issues.detail(c??"__none__"),queryFn:()=>fr.get(c),enabled:l&&!!c}),f=Ve({queryKey:U.messenger.customGroups(t??"__none__"),queryFn:()=>_s.listCustomGroups(t),enabled:l&&!!t}),m=((j=f.data)==null?void 0:j.groups)??[],h=n&&jm(n)?n.kind==="browser"?n.viewInstanceId??n.tabId:n.viewInstanceId??null:null,p=h&&n&&jm(n)?m.flatMap(C=>C.entries).find(C=>C.item.type==="saved_view"&&C.item.savedView.targetPayload.kind===n.kind&&C.item.savedView.targetPayload.viewInstanceId===h)??null:null,x=p?m.find(C=>C.entries.some(I=>I.id===p.id))??null:null,b=s&&t&&n?s.getMoveState(t,e,n):null,y=xt({mutationFn:async C=>{var $;if(!t||!n)throw new Error("Organization and Side Panel target are required");if(s&&(b!=null&&b.retryable)){const B=await s.retry(t,e,n);return{clientMutationId:null,completedRetryMutationId:b.clientMutationId,intentKey:null,result:B}}const I=C===W_e?{kind:"loose"}:gZt(e,(($=u.data)==null?void 0:$.id)??null,C);if(!I)throw new Error(c?"Wait for the Issue to finish loading, then try again.":"Choose a Messenger group first.");const N=iX(n,{clientMutationId:RBn,placement:I});if(!N)throw new Error("This Side Panel view cannot be kept in Messenger.");const M=LBn(N),E=zBn(o.current,M),_={...N,clientMutationId:E},z=p&&x&&I.kind==="group"&&I.groupId===x.id?{savedView:p.item.savedView,group:{id:x.id,name:x.name}}:null,T=s?await s.promote({contextKey:e,input:_,organizationId:t,target:n,existingResult:z}):await _s.keepSavedView(t,_);return{clientMutationId:E,completedRetryMutationId:null,intentKey:M,result:T}},onSuccess:async({clientMutationId:C,completedRetryMutationId:I,intentKey:N,result:M})=>{N&&C&&$Bn(o.current,N,C),I&&FBn(o.current,I),await Promise.all([a.invalidateQueries({queryKey:U.messenger.customGroups(t??"__none__")}),a.invalidateQueries({queryKey:["messenger",t??"__none__","saved-views"]})]),r({title:"Moved to Messenger",body:M.group?`Moved to ${M.group.name}.`:"Moved to Messenger sidebar.",tone:"success"})},onError:C=>{r({title:"Could not move this view",body:C instanceof Error?C.message:"Try again.",tone:"error"})}});if(!l||!n)return null;const w=!!(c&&u.isPending),k="inline-flex h-7 items-center justify-center gap-1 rounded-[calc(var(--radius-sm)-1px)] px-2 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-[color:var(--surface-active)] hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40 disabled:cursor-not-allowed disabled:opacity-50",S=y.isPending||w?i.jsx(fn,{className:"h-3.5 w-3.5 animate-spin","aria-hidden":!0}):b!=null&&b.retryable?i.jsx(A0,{className:"h-3.5 w-3.5","aria-hidden":!0}):y.isSuccess?i.jsx(zi,{className:"h-3.5 w-3.5","aria-hidden":!0}):i.jsx(vze,{className:"h-3.5 w-3.5","aria-hidden":!0});return b!=null&&b.retryable?i.jsxs("button",{type:"button","data-testid":"chat-side-panel-keep-in-messenger","aria-label":"Retry move to Messenger",title:b.error??"Retry move to Messenger",className:k,disabled:y.isPending,onClick:()=>y.mutate(null),children:[S,i.jsx("span",{children:"Retry move"})]}):d?c&&u.isError?i.jsxs("div",{className:"flex items-center gap-1 text-[11px]",role:"alert",children:[i.jsx("span",{className:"text-destructive",children:"Could not load this Issue."}),i.jsx("button",{type:"button",className:k,onClick:()=>void u.refetch(),children:"Retry Issue lookup"})]}):i.jsxs("button",{type:"button","data-testid":"chat-side-panel-keep-in-messenger","aria-label":"Keep in Messenger",title:"Keep in Messenger",className:k,disabled:y.isPending||w||!!u.error,onClick:()=>y.mutate(null),children:[S,i.jsx("span",{className:b!=null&&b.retryable?"inline":"hidden min-[1180px]:inline",children:b!=null&&b.retryable?"Retry move":"Keep"})]}):i.jsxs(ui,{onOpenChange:C=>{C&&f.refetch()},children:[i.jsx(fi,{asChild:!0,children:i.jsxs("button",{type:"button","data-testid":"chat-side-panel-keep-in-messenger","aria-label":"Keep in Messenger",title:"Keep in Messenger",className:k,disabled:y.isPending||f.isPending||!t,children:[S,i.jsx("span",{className:"hidden min-[1180px]:inline",children:"Keep"})]})}),i.jsxs(mi,{align:"end",className:"surface-overlay w-64 text-foreground",children:[i.jsx(dM,{children:"Keep in Messenger"}),f.isError?i.jsxs(i.Fragment,{children:[i.jsx(Ht,{disabled:!0,className:"whitespace-normal text-xs leading-5",children:"Could not load Messenger groups."}),i.jsx(Ht,{onClick:()=>void f.refetch(),children:"Retry groups"})]}):i.jsxs(i.Fragment,{children:[i.jsx(Ht,{onClick:()=>y.mutate(W_e),children:"Messenger sidebar"}),x?i.jsxs(Ht,{className:"whitespace-normal text-xs leading-5",onClick:()=>y.mutate(x.id),children:["Move existing view from ",x.name," to Main"]}):m.length>0?m.map(C=>i.jsx(Ht,{onClick:()=>y.mutate(C.id),children:C.name},C.id)):i.jsx(Ht,{disabled:!0,className:"whitespace-normal text-xs leading-5",children:"No groups yet."})]})]})]})}const mY=A.forwardRef(function({children:t,centered:n=!1,streaming:r=!1,fileDragActive:s=!1,fileDropTargetProps:a,className:o,testId:l="chat-composer-file-drop-target"},c){return i.jsx("div",{ref:c,"data-testid":l,...a,className:q("chat-composer relative rounded-[var(--radius-lg)] p-3 transition-[border-color,box-shadow] duration-300",r&&"chat-composer--streaming",s&&"ring-2 ring-[color:var(--accent-base)] ring-offset-2 ring-offset-background",n?"mx-auto w-full max-w-3xl":"w-full",o),children:t})}),AY=A.forwardRef(function({scrollRef:t,onKeyDownCapture:n,onPasteCapture:r,scrollTestId:s="chat-composer-editor-scroll",className:a,contentClassName:o,...l},c){return i.jsx("div",{ref:t,"data-testid":s,className:"chat-composer-editor-scroll scrollbar-auto-hide overflow-y-auto overscroll-contain",onKeyDownCapture:n,onPasteCapture:r,children:i.jsx(Cu,{ref:c,...l,submitShortcut:"enter",plainText:!0,bordered:!1,className:q("rounded-[var(--radius-md)] bg-transparent",a),contentClassName:q("min-h-[88px] bg-transparent text-[15px] leading-7 text-foreground",o)})})});function hY({children:e,actions:t,testId:n="chat-composer-toolbar"}){return i.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-2.5","data-testid":n,children:[i.jsx("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-2",children:e}),t]})}function Cht({open:e,onOpenChange:t,onAddFiles:n,children:r}){return i.jsxs(ui,{open:e,onOpenChange:t,children:[i.jsx(fi,{type:"button",className:"control-hover inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full border border-[color:var(--border-soft)] bg-[color:color-mix(in_oklab,var(--surface-active)_52%,transparent)] text-sm font-medium text-foreground transition-[color,background-color,border-color,box-shadow,opacity,transform,scale] hover:bg-[color:var(--surface-active)] focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring/40","aria-label":"Add files and options",children:i.jsx(ps,{className:"h-4 w-4"})}),i.jsxs(mi,{align:"start",side:"top",sideOffset:8,className:"surface-overlay w-80 max-w-[calc(100vw-2rem)] rounded-[var(--radius-lg)] border p-1.5 text-foreground",children:[i.jsxs(Ht,{className:"rounded-[var(--radius-md)] px-3 py-2.5",onSelect:s=>{s.preventDefault(),t(!1),window.setTimeout(n,0)},children:[i.jsx(df,{className:"mr-2 h-4 w-4"}),"Add files"]}),r]})]})}function Nht({open:e,onClick:t,buttonRef:n}){return i.jsx("button",{ref:n,type:"button",className:q("chat-chip inline-flex max-w-[min(100%,16rem)] min-w-0 items-center gap-1.5 rounded-[var(--radius-md)] px-3 py-1.5 text-xs font-medium transition-colors hover:bg-[color:var(--surface-active)]",e&&"bg-[color:var(--surface-active)]"),"aria-label":"Skills","aria-expanded":e,"aria-haspopup":"menu",onClick:t,children:i.jsx("span",{className:"min-w-0 truncate",children:"Skills"})})}function Iht({pending:e,skills:t,filteredSkills:n,searchQuery:r,searchInputRef:s,onSearchQueryChange:a,onSelect:o}){return i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"px-3 py-1.5 text-xs font-medium text-muted-foreground",children:"Skills"}),e?i.jsxs("div",{className:"flex items-center gap-2 rounded-[var(--radius-md)] px-3 py-2 text-sm text-muted-foreground",children:[i.jsx(fn,{className:"h-4 w-4 animate-spin"}),i.jsx("span",{children:"Loading skills..."})]}):t.length===0?i.jsx("div",{className:"rounded-[var(--radius-md)] px-3 py-2 text-sm leading-6 text-muted-foreground",children:"This agent has no enabled skills."}):i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"px-2 pb-2",children:i.jsx("input",{ref:s,className:"w-full rounded-[var(--radius-md)] border border-border bg-transparent px-2.5 py-2 text-sm outline-none placeholder:text-muted-foreground/60 focus:border-ring",placeholder:"Search skills...",value:r,onChange:l=>a(l.target.value),onKeyDown:l=>{l.key!=="Escape"&&l.stopPropagation()}})}),i.jsx("div",{children:n.length===0?i.jsx("div",{className:"rounded-[var(--radius-md)] px-3 py-2 text-sm leading-6 text-muted-foreground",children:"No skills match search."}):n.map(l=>i.jsxs("button",{type:"button",role:"menuitem","data-chat-composer-menu-item":!0,className:"chat-composer-menu-row",onClick:()=>o(l),children:[i.jsx(nd,{className:"h-4 w-4 shrink-0 text-[#2f80ed]"}),i.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[i.jsx("span",{className:"min-w-0 shrink truncate font-medium text-foreground",children:l.skillDisplayName}),l.skillCategoryLabel?i.jsx("span",{className:"inline-flex shrink-0 items-center rounded-[var(--radius-sm)] border border-border/70 bg-muted/50 px-1.5 py-0.5 text-[11px] leading-none text-muted-foreground",children:l.skillCategoryLabel}):null,i.jsx("span",{className:"min-w-0 flex-1 truncate text-muted-foreground",children:l.skillDescription??l.skillLocationLabel??l.skillRefLabel})]})]},l.id))})]})]})}function yve({children:e,menuRef:t,testId:n,ariaLabel:r,position:s,onKeyDown:a}){const o=is(),l=A.useCallback(c=>{typeof t=="function"?t(c):t&&(t.current=c),o(c)},[t,o]);return i.jsx("div",{ref:l,"data-testid":n,role:"menu","aria-label":r,onKeyDown:a,className:"chat-composer-context-menu motion-chat-composer-menu-pop surface-overlay scrollbar-auto-hide fixed z-50 overflow-y-auto rounded-[var(--radius-lg)] border p-1.5 text-foreground",style:s,children:e})}function pY({mode:e,disabled:t,onClick:n,stoppingComplete:r=!1,ariaLabel:s}){const a=e==="sending"||e==="stopping"&&!r,o=s??(e==="sending"?"Sending":e==="stopping"?r?"Response stopped":"Stopping response":e==="stop"?"Stop streaming":e==="queue"?"Queue":e==="continue"?"Continue":"Send");return i.jsx(oe,{type:"button",variant:"ghost",size:"icon-sm",onClick:n,disabled:t,"aria-busy":a?!0:void 0,"aria-label":o,title:e==="continue"?o:void 0,className:q("shrink-0 rounded-full border-0 bg-white text-black shadow-sm","hover:bg-zinc-100 dark:bg-white dark:text-black dark:hover:bg-zinc-100","disabled:pointer-events-none disabled:opacity-35","focus-visible:ring-2 focus-visible:ring-white/40 focus-visible:ring-offset-2 focus-visible:ring-offset-[color:var(--surface-page)]",a&&"disabled:opacity-100"),children:a?i.jsx(fn,{className:"h-[18px] w-[18px] animate-spin",strokeWidth:2.25}):e==="stop"||e==="stopping"?i.jsx(z0,{className:"h-3.5 w-3.5 fill-current"}):i.jsx(_Ae,{className:"h-[18px] w-[18px]",strokeWidth:2.25})})}function Ox(e){switch(e){case"steer":return"Could not send steer";case"side-chat":return"Could not send Side Chat message";case"feedback":return"Could not send feedback";default:return"Could not send message"}}function uU(e,t="send"){if(e instanceof S6)return{title:Ox(t),body:"The request took too long. Check your connection and try again."};if(e instanceof $o){if(e.status===401||e.status===403)return{title:Ox(t),body:"You no longer have access to this chat. Refresh and try again."};if(e.status===404)return{title:Ox(t),body:"This chat is no longer available. Refresh and try again."};if(e.status===409)return{title:Ox(t),body:"This chat changed while the request was in progress. Refresh and try again."};if(e.status===429)return{title:Ox(t),body:"Rudder is busy right now. Wait a moment and try again."};if(e.status>=400&&e.status<500)return{title:Ox(t),body:"Check the message and try again."};if(e.status>=500)return{title:Ox(t),body:"Rudder could not process the request. Try again."}}return hDt(e)?{title:Ox(t),body:"The request was interrupted. Try again when you are ready."}:e instanceof TypeError||e instanceof Error&&/network|fetch|connection|load failed/iu.test(e.message)?{title:Ox(t),body:"Rudder could not be reached. Check your connection and try again."}:{title:Ox(t),body:"Something went wrong. Try again."}}function uH(e,t="send"){return uU(e,t).body}const QBn="rudder:chat-stop-recovery:v1",UBn=1440*60*1e3,qBn=[250,500,1e3,2e3,5e3];function vve(){try{return globalThis.localStorage??null}catch{return null}}function wve(e,t){return`${QBn}:${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function lme(e){return`${e.orgId}\0${e.chatId}\0${e.request.controlActionId}`}function gY(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function H_e(e){return e===void 0||typeof e=="string"}function tie(e){return e===void 0||typeof e=="number"&&Number.isFinite(e)}function Pht(e){return!gY(e)||typeof e.controlActionId!="string"||!e.controlActionId.trim()||!H_e(e.expectedGenerationId)||!tie(e.expectedAttemptEpoch)||!tie(e.expectedControlVersion)||!tie(e.lastCommittedRenderSeq)||!H_e(e.renderedBodyHash)?null:{controlActionId:e.controlActionId,...typeof e.expectedGenerationId=="string"?{expectedGenerationId:e.expectedGenerationId}:{},...typeof e.expectedAttemptEpoch=="number"?{expectedAttemptEpoch:e.expectedAttemptEpoch}:{},...typeof e.expectedControlVersion=="number"?{expectedControlVersion:e.expectedControlVersion}:{},...typeof e.lastCommittedRenderSeq=="number"?{lastCommittedRenderSeq:e.lastCommittedRenderSeq}:{},...typeof e.renderedBodyHash=="string"?{renderedBodyHash:e.renderedBodyHash}:{}}}const Tht=new Set(["streaming","tool_busy","finalizing","stopping","stopped","failed"]);function fU(e){if(typeof e!="string")return null;const t=new Date(e);return Number.isNaN(t.getTime())?null:t}function VBn(e,t){if(e===null||!gY(e))return null;const n=fU(e.userCreatedAt),r=fU(e.createdAt),s=e.editedFromCreatedAt===null?null:fU(e.editedFromCreatedAt);return e.chatId!==t||typeof e.streamKey!="string"||typeof e.userBody!="string"||!n||!(typeof e.userMessageId=="string"||e.userMessageId===null)||!(typeof e.chatTurnId=="string"||e.chatTurnId===null)||typeof e.turnVariant!="number"||e.editedFromCreatedAt!==null&&!s||typeof e.body!="string"||typeof e.state!="string"||!Tht.has(e.state)||!r||!Array.isArray(e.transcript)||!(typeof e.replyingAgentId=="string"||e.replyingAgentId===null)?null:{...e,chatId:t,userCreatedAt:n,editedFromCreatedAt:s,createdAt:r,state:e.state}}function WBn(e){var r;if(!e)return null;const{userFiles:t,...n}=e;return{...n,userCreatedAt:e.userCreatedAt.toISOString(),editedFromCreatedAt:((r=e.editedFromCreatedAt)==null?void 0:r.toISOString())??null,createdAt:e.createdAt.toISOString()}}function _ht(e){var t;return{version:1,orgId:e.orgId,chatId:e.chatId,request:e.request,frozenDraft:e.frozenDraft,previousStreamState:((t=e.frozenDraft)==null?void 0:t.state)??null,requestedAt:(e.now??new Date).toISOString()}}function Mht(e){var t;try{const n={...e,frozenDraft:WBn(e.frozenDraft)};(t=vve())==null||t.setItem(wve(e.orgId,e.chatId),JSON.stringify(n))}catch{}}function _g(e,t,n=new Date){var r;try{const s=(r=vve())==null?void 0:r.getItem(wve(e,t));if(!s)return null;const a=JSON.parse(s);if(!gY(a)||a.version!==1||a.orgId!==e||a.chatId!==t)return sw(e,t),null;const o=Pht(a.request),l=fU(a.requestedAt),c=a.previousStreamState===null?null:typeof a.previousStreamState=="string"&&Tht.has(a.previousStreamState)?a.previousStreamState:void 0;if(!o||!l||c===void 0||n.getTime()-l.getTime()>UBn)return sw(e,t),null;const d=VBn(a.frozenDraft,t);return a.frozenDraft!==null&&!d?(sw(e,t),null):{version:1,orgId:e,chatId:t,request:o,frozenDraft:d,previousStreamState:c,requestedAt:l.toISOString()}}catch{return sw(e,t),null}}function sw(e,t,n){try{const r=vve();if(!r)return!1;const s=wve(e,t);if(n){const a=r.getItem(s);if(!a)return!1;try{const o=JSON.parse(a),l=gY(o)?Pht(o.request):null;if(l&&l.controlActionId!==n)return!1}catch{}}return r.removeItem(s),!0}catch{return!1}}function Eht(e,t={}){var o;const n=(o=t.retryDelaysMs)!=null&&o.length?[...t.retryDelaysMs]:[...qBn],r=new Map,s=l=>{l.timer&&(clearTimeout(l.timer),l.timer=null)},a=l=>{const c=lme(l);let d=r.get(c);return d?d.recovery=l:(d={recovery:l,retryCount:0,timer:null},r.set(c,d)),{key:c,state:d}};return{schedule(l){const{key:c,state:d}=a(l);if(d.timer)return;const u=n[Math.min(d.retryCount,n.length-1)]??0;d.retryCount+=1,d.timer=setTimeout(()=>{const f=r.get(c);f&&(f.timer=null,e(f.recovery))},u)},retryNow(l){const{state:c}=a(l);s(c),e(c.recovery)},resolve(l){const c=lme(l),d=r.get(c);d&&s(d),r.delete(c)},dispose(){for(const l of r.values())s(l);r.clear()}}}function HBn(e){var t;return((t=e.body)==null?void 0:t.trim())||e.kind}function KBn(e){return e.transcript??[]}function K_e(){}function ZBn({target:e,onReplaceTarget:t}){const n=er(),r=Kr(),[s,a]=A.useState(e.body),[o,l]=A.useState([]),[c,d]=A.useState(""),[u,f]=A.useState(!1),[m,h]=A.useState(null),[p,x]=A.useState(0),[b,y]=A.useState(null),[w,k]=A.useState(null),[S,j]=A.useState(null),[C,I]=A.useState(!1),[N,M]=A.useState({}),E=A.useRef(e),_=A.useRef(!1),z=A.useRef(null),T=A.useRef(null),$=A.useRef(!1),B=A.useRef(()=>{}),F=A.useRef(null),W=A.useRef(null);F.current||(F.current=Eht(ae=>{B.current(ae)})),E.current=e;const Y=Ve({queryKey:U.agents.list(e.organizationId),queryFn:()=>$n.list(e.organizationId)}),G=Ve({queryKey:U.chats.detail(e.organizationId,e.conversationId??"__goal-chat-draft__"),queryFn:()=>Zn.get(e.conversationId),enabled:!!e.conversationId}),V=Ve({queryKey:U.chats.messages(e.organizationId,e.conversationId??"__goal-chat-draft__"),queryFn:()=>Zn.listMessages(e.organizationId,e.conversationId,{includeTranscript:!0}),enabled:!!e.conversationId}),L=Ve({queryKey:U.chats.queue(e.organizationId,e.conversationId??"__goal-chat-draft__"),queryFn:()=>Zn.listQueue(e.conversationId),enabled:!!e.conversationId,refetchInterval:u&&e.conversationId?2e3:!1}),R=A.useMemo(()=>{const ae=Y.data??[];return e.agentId?ae.find(Ee=>Ee.id===e.agentId)??null:null},[Y.data,e.agentId]),D=!Y.isPending&&!R,X=G.data,ee=G.error??V.error;A.useEffect(()=>{V.data&&!_.current&&l(V.data)},[V.data]),A.useEffect(()=>{a(e.body)},[e.body]),A.useEffect(()=>{try{window.localStorage.setItem(`rudder.goal-chat:${e.organizationId}:${e.goalId}`,JSON.stringify(e))}catch{}},[e]),A.useEffect(()=>{var ae;(ae=W.current)==null||ae.scrollIntoView({block:"end"})},[o,c]),A.useEffect(()=>()=>{var ae,Ee;(ae=z.current)==null||ae.abort(),(Ee=F.current)==null||Ee.dispose()},[]),A.useEffect(()=>{const ae=e.conversationId;if(!ae)return;const Ee=()=>{var _e;const he=_g(e.organizationId,ae);he&&((_e=F.current)==null||_e.retryNow(he))};return Ee(),window.addEventListener("online",Ee),()=>window.removeEventListener("online",Ee)},[e.conversationId,e.organizationId]),A.useEffect(()=>{if(m===null){x(0);return}const ae=()=>x(Math.floor((Date.now()-m)/1e3));ae();const Ee=window.setInterval(ae,1e3);return()=>window.clearInterval(Ee)},[m]);const se=A.useCallback(ae=>{const Ee=E.current,he={...Ee,...ae};E.current=he,t(fs(Ee),he)},[t]),ne=A.useCallback(()=>{const ae=E.current.conversationId;ae&&r(`/messenger/chat/${ae}`)},[r]),le=async ae=>{const Ee=(ae??s).trim(),he=E.current;if(!Ee||u||!R)return;const _e=new AbortController;z.current=_e,T.current=Ee,_.current=!0,f(!0),h(Date.now()),y(null),k(null),j(null),d("");let Ie=null;try{const $e=async ce=>{if(ce.type==="ack"){l(Ye=>[...Ye,ce.userMessage]);const Oe=E.current;se({conversationId:ce.userMessage.conversationId,body:Oe.body===Ee?"":Oe.body}),a(Ye=>Ye.trim()===Ee?"":Ye)}if(ce.type==="assistant_delta"&&d(Oe=>Oe+ce.delta),ce.type==="final"&&(d(""),l(Oe=>[...Oe,...ce.messages])),ce.type==="error")throw new Error(ce.error)};he.conversationId?await Zn.sendMessageStream(he.conversationId,Ee,{onEvent:$e,signal:_e.signal}):await Zn.sendFirstMessageStream(e.organizationId,Ee,{preferredAgentId:R.id,issueCreationMode:"manual_approval",planMode:!1,modelOverride:null,effortOverride:null,contextLinks:[{entityType:"goal",entityId:e.goalId}],clientMutationId:e.clientMutationId,signal:_e.signal,onEvent:$e}),Ie=E.current.conversationId??he.conversationId}catch($e){_e.signal.aborted||(j(Ee),y(uH($e,"side-chat")))}finally{z.current===_e&&(z.current=null),T.current=null,_.current=!1,f(!1),h(null)}Ie&&await Promise.all([n.invalidateQueries({queryKey:U.chats.detail(e.organizationId,Ie)}),n.invalidateQueries({queryKey:U.chats.messages(e.organizationId,Ie)}),n.invalidateQueries({queryKey:U.goals.detail(e.goalId)}),n.invalidateQueries({queryKey:U.goals.list(e.organizationId)}),n.invalidateQueries({queryKey:["goals","workspace",e.organizationId]})])},ie=A.useCallback(async(ae,Ee)=>{await Promise.allSettled([n.invalidateQueries({queryKey:U.chats.detail(ae,Ee)}),n.invalidateQueries({queryKey:U.chats.messages(ae,Ee)}),n.invalidateQueries({queryKey:U.chats.queue(ae,Ee)}),n.invalidateQueries({queryKey:U.goals.detail(e.goalId)})])},[n,e.goalId]),re=A.useCallback(ae=>{$.current||($.current=!0,I(!0),y(null),k("Stopping response..."),(async()=>{var Ee,he,_e,Ie,$e;try{const ce=await Zn.stopMessageStream(ae.chatId,ae.request);if((ce.controlActionId??ae.request.controlActionId)!==ae.request.controlActionId){k("Stop confirmation pending. Rudder will retry automatically."),(Ee=F.current)==null||Ee.schedule(ae);return}const Ye=ce.disposition??"",J=ce.stopped||["startup_cancelled","stopping","stop_requested","stopped","interrupted_unverified"].includes(Ye),qe=!ce.stopped&&Ye==="completion_committed";if(sw(ae.orgId,ae.chatId,ae.request.controlActionId),(he=F.current)==null||he.resolve(ae),J){const be=T.current;(_e=z.current)==null||_e.abort(),j(be),k(ce.stopped?"Response stopped. Retry when ready or continue in full chat.":"Response frozen. Runtime termination could not be independently confirmed.")}else qe?(j(null),k("Response completed before Stop reached the cutoff.")):k("No active response was available to stop.");await ie(ae.orgId,ae.chatId)}catch(ce){ce instanceof $o&&ce.status>=400&&ce.status<500?(sw(ae.orgId,ae.chatId,ae.request.controlActionId),(Ie=F.current)==null||Ie.resolve(ae),k(null),y(`Stop was rejected. ${ce.message}`)):(k("Stop confirmation pending. Rudder will retry automatically."),y(null),($e=F.current)==null||$e.schedule(ae))}finally{$.current=!1,I(!1)}})())},[ie]);B.current=re;const de=()=>{var ce,Oe,Ye,J,qe;if(!u||C)return;const ae=E.current,Ee=ae.conversationId;if(!Ee){k("Stop becomes available as soon as this Chat starts.");return}const he=_g(ae.organizationId,Ee);if(he){(ce=F.current)==null||ce.retryNow(he);return}const _e=RC(L.data),Ie=_e&&((Oe=L.data)==null?void 0:Oe.activeAttemptEpoch)!==null&&((Ye=L.data)==null?void 0:Ye.activeAttemptEpoch)!==void 0&&((J=L.data)==null?void 0:J.activeControlVersion)!==null&&((qe=L.data)==null?void 0:qe.activeControlVersion)!==void 0,$e=_ht({orgId:ae.organizationId,chatId:Ee,request:{controlActionId:globalThis.crypto.randomUUID(),...Ie?{expectedGenerationId:_e,expectedAttemptEpoch:L.data.activeAttemptEpoch,expectedControlVersion:L.data.activeControlVersion}:{}},frozenDraft:null});Mht($e),re($e)},Be=!!(s.trim()&&R&&!u);return i.jsxs("div",{className:"flex h-full min-h-0 flex-col","data-testid":"goal-chat-panel",children:[i.jsx("div",{className:"scrollbar-auto-hide min-h-0 flex-1 overflow-y-auto px-4 py-4",children:i.jsxs("div",{className:"mx-auto flex w-full max-w-3xl flex-col gap-4",children:[i.jsxs("div",{className:"flex min-w-0 items-center gap-2 border-b border-border/70 pb-3",children:[i.jsx(Si,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("div",{className:"truncate text-sm font-medium",children:"Chat about Goal"}),i.jsx("div",{className:"truncate text-xs text-muted-foreground",children:e.label})]}),e.conversationId?i.jsxs(oe,{type:"button",size:"sm",variant:"ghost","aria-label":"Open full chat",title:"Open full chat",onClick:()=>r(`/messenger/chat/${e.conversationId}`),children:[i.jsx(Ki,{className:"h-4 w-4"}),i.jsx("span",{className:"hidden sm:inline",children:"Open full chat"})]}):null]}),e.conversationId&&(G.isPending||V.isPending)?i.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading conversation..."}):null,ee?i.jsxs("div",{role:"alert",className:"flex flex-wrap items-center justify-between gap-2 text-sm text-destructive",children:[i.jsx("span",{children:ee instanceof Error?ee.message:"Could not load this conversation."}),i.jsx(oe,{type:"button",size:"sm",variant:"outline",onClick:()=>void Promise.all([G.refetch(),V.refetch()]),children:"Retry"})]}):null,!e.conversationId&&o.length===0?i.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No messages yet."}):null,X?o.map(ae=>{const Ee=KBn(ae);return i.jsxs("div",{"data-testid":"goal-chat-message",children:[ae.role==="assistant"&&Ee.length>0?i.jsx(J6,{entries:Ee,state:ae.status,generationTerminalReason:ae.generationTerminalReason,streamStartedAt:new Date(ae.createdAt),streamEndedAt:new Date(ae.updatedAt),assistantMessageBody:ae.body,showDeveloperDiagnostics:!1}):null,i.jsx(Qk,{conversation:X,message:ae,agents:Y.data,decisionNote:N[ae.id]??"",onDecisionNoteChange:he=>M(_e=>({..._e,[ae.id]:he})),decisionNoteMentions:[],onDecisionNoteMentionQueryChange:K_e,onDecisionNoteInlineTokenClick:K_e,onApprovalAction:ne,onIssueProposalChange:ne,onResolveOperationProposal:ne,onConvertToIssue:ne,actionPending:!1,onCopyMessageText:he=>{var _e;return(_e=navigator.clipboard)==null?void 0:_e.writeText(he)},onRetryFailedMessage:ne,onOpenFile:ne,onSelectResponseAnnotation:he=>{he.surface==="agent_run_transcript"&&r(`/agents/${he.sourceAgentId}/runs/${he.sourceRunId}`)},skillReferences:[]})]},ae.id)}):o.map(ae=>i.jsxs("div",{className:`rounded-md border px-3 py-2 text-sm ${ae.role==="user"?"ml-6 bg-muted/30":"mr-6"}`,children:[i.jsx("div",{className:"mb-1 text-xs text-muted-foreground",children:ae.role==="user"?"You":(R==null?void 0:R.name)??"Agent"}),i.jsx("div",{className:"whitespace-pre-wrap break-words",children:HBn(ae)})]},ae.id)),c?i.jsx("div",{"data-testid":"goal-chat-streaming",className:"mr-6 whitespace-pre-wrap break-words text-sm text-foreground",children:c}):null,u?i.jsxs("div",{role:"status","data-testid":"goal-chat-working",className:"mr-6 flex items-center gap-2 rounded-lg border border-border bg-muted/25 px-3 py-2.5",children:[i.jsx(fn,{className:"h-4 w-4 shrink-0 animate-spin text-muted-foreground","aria-hidden":"true"}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"truncate text-sm font-medium",children:p>=30?"Still working on this Goal...":`${(R==null?void 0:R.name)??"Agent"} is working...`}),E.current.conversationId?i.jsx("p",{className:"text-xs text-muted-foreground",children:"You can keep this panel open or continue in full chat."}):null]})]}):null,i.jsx("div",{ref:W})]})}),w?i.jsx("div",{role:"status",className:"px-4 pb-2 text-sm text-muted-foreground",children:w}):null,b||S?i.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 px-4 pb-2",children:[b?i.jsx("span",{role:"alert",className:"text-sm text-destructive",children:b}):i.jsx("span",{}),i.jsxs("div",{className:"flex items-center gap-2",children:[S?i.jsx(oe,{type:"button",size:"sm",variant:"outline",disabled:u,onClick:()=>void le(S),children:"Retry message"}):null,e.conversationId?i.jsx(oe,{type:"button",size:"sm",variant:"ghost",onClick:ne,children:"Open full chat"}):null]})]}):null,i.jsxs("div",{className:"shrink-0 px-4 pb-4",children:[D?i.jsx("p",{role:"alert",className:"mx-auto mb-2 max-w-3xl text-sm text-destructive",children:"The Goal Owner is unavailable. Reassign the Goal before starting a chat."}):null,i.jsxs(mY,{className:"mx-auto max-w-3xl",testId:"goal-chat-composer",children:[i.jsx(AY,{value:s,onChange:ae=>{u||(a(ae),se({body:ae}))},placeholder:"Message about this Goal...",onSubmit:()=>void le()}),i.jsx(hY,{actions:i.jsx(pY,{mode:u?C?"stopping":"stop":"send",ariaLabel:u?C?"Stopping response":e.conversationId?"Stop streaming":"Stop unavailable until chat starts":"Send message",disabled:u?C||!e.conversationId:!Be,onClick:()=>void(u?de():le())}),children:R?i.jsx(zl,{name:R.name,icon:R.icon,role:R.role,size:"sm",className:"min-w-0"}):i.jsx("span",{className:"min-w-0 truncate text-xs text-muted-foreground",children:Y.isPending?"Loading Agent...":D?"Owner unavailable":"No Agent available"})})]})]})]})}function Dht({project:e,label:t,expanded:n,disabled:r,buttonRef:s,testId:a="chat-project-selector",iconTestId:o="chat-project-icon",clearTestId:l="chat-project-clear",onClick:c,onClear:d}){return i.jsxs("div",{className:"group/project relative inline-flex max-w-[min(100%,15rem)] min-w-0",children:[i.jsxs("button",{ref:s,type:"button","data-testid":a,"aria-label":`Project context: ${t}`,"aria-expanded":r?!1:n,disabled:r,title:r?"Project context is locked after conversation starts.":void 0,className:q("chat-chip inline-flex w-full min-w-0 items-center gap-1.5 rounded-[var(--radius-md)] px-3 py-1.5 text-xs font-medium",r?"cursor-default":"transition-colors hover:bg-[color:var(--surface-active)]",n&&"bg-[color:var(--surface-active)]"),onClick:c,children:[e?i.jsx(Fo,{color:e.color,icon:e.icon,size:"xs",testId:o,className:q("transition-opacity",!r&&"group-focus-within/project:opacity-0 group-hover/project:opacity-0")}):null,i.jsx("span",{className:"min-w-0 truncate",children:t})]}),e&&!r?i.jsx("button",{type:"button","data-testid":l,"aria-label":`Clear project context: ${t}`,title:"Clear project context",className:"pointer-events-none absolute left-2 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-[var(--radius-sm)] text-muted-foreground opacity-0 transition-[color,background-color,opacity] hover:bg-[color:var(--surface-inset)] hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring/40 group-focus-within/project:pointer-events-auto group-focus-within/project:opacity-100 group-hover/project:pointer-events-auto group-hover/project:opacity-100",onClick:u=>{u.stopPropagation(),d()},children:i.jsx(Jr,{className:"h-4 w-4",strokeWidth:2.4})}):null]})}function Rht({projects:e,activeProjectId:t,onSelect:n,onCreateProject:r}){return i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"px-3 py-1.5 text-xs font-medium text-muted-foreground",children:"Project context"}),i.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":t===null,"data-chat-composer-menu-item":!0,className:"chat-composer-menu-row project-context-menu-item",onClick:()=>n(null),children:[i.jsx("span",{className:"project-context-empty-swatch h-3 w-3 shrink-0","aria-hidden":"true"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:"No project"})]}),e.length>0?i.jsx("div",{className:"my-1 border-t border-[color:var(--border-soft)] pt-1",children:e.map(s=>{var a;return i.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":t===s.id,"data-chat-composer-menu-item":!0,className:"chat-composer-menu-row project-context-menu-item",onClick:()=>n(s.id),children:[i.jsx(Fo,{color:s.color,icon:s.icon,size:"xs"}),i.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:((a=s.name)==null?void 0:a.trim())||"Unknown project"})]},s.id)})}):null,r&&t===null?i.jsx("div",{className:"mt-1 border-t border-[color:var(--border-soft)] pt-1",children:i.jsxs("button",{type:"button",role:"menuitem","data-testid":"chat-project-create","data-chat-composer-menu-item":!0,className:"chat-composer-menu-row project-context-menu-item",onClick:r,children:[i.jsx(e2,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:"Create project"})]})}):null]})}const ny="__none__",cme="rudder.chatLastAgentByOrg";function Lht(){try{return globalThis.localStorage??null}catch{return null}}function jL(e){return(e??[]).filter(t=>t.status!=="terminated")}function XBn(e){var t;try{const n=(t=Lht())==null?void 0:t.getItem(cme);if(!n)return;const r=JSON.parse(n);if(!r||typeof r!="object")return;const s=r[e];return typeof s=="string"&&s.trim().length>0?s:void 0}catch{return}}function tP(e,t){if(!(!t||t===ny))try{const n=Lht();if(!n)return;const r=n.getItem(cme),s=r?JSON.parse(r):{},a=s&&typeof s=="object"?s:{};a[e]=t,n.setItem(cme,JSON.stringify(a))}catch{return}}function nie(e,t){return!!(e&&jL(t).some(n=>n.id===e))}function GBn(e,t){const n=jL(t);if(n.length===0)return ny;const r=e?XBn(e):void 0;return r&&n.some(s=>s.id===r)?r:n[0].id}const PE="dev-restart-required";function Z_e({explicit:e,pendingFileCount:t}){return e??(t>0?"memory":"durable")}function fH({annotations:e,devServer:t,draftPersistence:n="durable",pushToast:r}){if(e.length===0||!(t!=null&&t.enabled)||!t.restartRequired)return!1;const s=_n(),a=n==="durable"&&s;return r({id:PE,dedupeKey:`${PE}:${Date.now()}:${Math.random()}`,title:"Restart Rudder to send annotations",body:n==="memory"?"Your draft is still open in this window. Copy it before restarting Rudder.":s?"Your message and annotations are saved. Rudder's local server is still running older code.":"Your message and annotations are saved. Restart pnpm dev, then send again.",tone:"warn",persistent:!0,...a?{action:{label:"Restart Rudder",onClick:async()=>{try{await s.restart()}catch(o){throw r({title:"Could not restart Rudder",body:o instanceof Error?o.message:"Try restarting Rudder manually.",tone:"error"}),o}}}}:{}}),!0}const mH=new Map;function YBn(e,t,n){if(n.length===0)return;const r=mH.get(e)??new Map;r.set(t,[...n]),mH.set(e,r)}function JBn(e){const t=mH.get(e);return t?(mH.delete(e),Object.fromEntries(Array.from(t.entries(),([n,r])=>[n,[...r]]))):{}}const e0={agentRuntimeType:"claude_local",cwd:"",instructionsFilePath:"",promptTemplate:"",model:"",modelFallbacks:[],thinkingEffort:"",mode:"",chrome:!1,dangerouslySkipPermissions:!1,permissionMode:"auto",search:!1,countSubscriptionUsageAsCost:!0,dangerouslyBypassSandbox:!1,command:"",args:"",extraArgs:"",envVars:"",envBindings:{},url:"",bootstrapPrompt:"",payloadTemplateJson:"",workspaceStrategyType:"project_primary",workspaceBaseRef:"",workspaceBranchTemplate:"",worktreeParentDir:"",runtimeServicesJson:"",maxTurnsPerRun:300,heartbeatEnabled:!1,intervalSec:300,preflightEnabled:!0,maxConcurrentRuns:Uhe},rie={identity:{},agentRuntimeConfig:{},heartbeat:{},runtime:{}},X_e={};function eQn(e){return Object.keys(e.identity).length>0||e.agentRuntimeType!==void 0||Object.keys(e.agentRuntimeConfig).length>0||Object.keys(e.heartbeat).length>0||Object.keys(e.runtime).length>0}const jh="w-full rounded-md border border-border px-2.5 py-1.5 bg-transparent outline-none text-sm font-mono placeholder:text-muted-foreground/40";function tQn(e){return e.split(",").map(t=>t.trim()).filter(Boolean)}function nQn(e){return Array.isArray(e)?e.filter(t=>typeof t=="string").join(", "):typeof e=="string"?e:""}const xY={claude_local:{key:"effort",label:"Thinking effort"},codex_local:{key:"modelReasoningEffort",label:"Thinking effort"},opencode_local:{key:"variant",label:"Thinking effort"},pi_local:{key:"thinking",label:"Thinking effort"},cursor:{key:"effort",label:"Thinking effort"}},rQn=["claude_local","codex_local","opencode_local","pi_local","cursor"];function Jg(e){var t,n,r;return e==="claude_local"?((t=cU.find(s=>s.id===mht))==null?void 0:t.id)??((n=cU.find(s=>s.id.startsWith("deepseek")))==null?void 0:n.id)??((r=cU[0])==null?void 0:r.id)??"":e==="codex_local"?sY:e==="cursor"?cY:e==="opencode_local"?"opencode/deepseek-v4-flash-free":e==="pi_local"?"kimi-coding/kimi-for-coding":""}function zht(e){return e==="codex_local"?"codex":e==="pi_local"?"pi":e==="cursor"?"cursor-agent":e==="opencode_local"?"opencode":"claude"}function $ht(e){const t={...e0,agentRuntimeType:e,model:Jg(e),modelFallbacks:[],command:zht(e)};return e==="codex_local"&&(t.thinkingEffort=iY,t.search=oY,t.countSubscriptionUsageAsCost=iH,t.dangerouslyBypassSandbox=aY),e==="claude_local"&&(t.dangerouslySkipPermissions=!1,t.permissionMode="auto"),e==="opencode_local"&&(t.dangerouslySkipPermissions=!1),t}function UC(e){return F5(e).buildAdapterConfig($ht(e))}function Fht(e){return e==="claude_local"?"codex_local":"claude_local"}function sQn(e){const t=Fht(e),n=UC(t),r=typeof n.model=="string"?n.model:Jg(t);return{agentRuntimeType:t,model:r,config:n}}function Bht(e,t){const n=new Set(t.map(s=>`${s.agentRuntimeType}\0${s.model}`)),r=[Fht(e),"opencode_local","pi_local","cursor","codex_local","claude_local"];for(const s of r){const a=UC(s),o=typeof a.model=="string"?a.model:Jg(s);if(!n.has(`${s}\0${o}`))return{agentRuntimeType:s,model:o,config:a}}return sQn(e)}function AH(e){var t;return((t=xY[e])==null?void 0:t.key)??"effort"}function o5(e,t="",n){return xY[e]?e==="codex_local"?yht("Auto",mve(t,n)).map(s=>({id:s.value,label:s.label})):e==="claude_local"?uve(t,n).map(s=>({id:s.value,label:s.label})):e==="opencode_local"?fve(t,n).map(s=>({id:s.value,label:s.label})):e==="pi_local"?Ave(t,n).map(s=>({id:s.value,label:s.label})):e==="cursor"?hve(t,n).map(s=>({id:s.value,label:s.label})):[]:[]}function Qht(e){var t;return((t=xY[e])==null?void 0:t.label)??"Thinking effort"}function CL(e,t="",n){return e==="cursor"||e==="codex_local"||e==="claude_local"||e==="opencode_local"||e==="pi_local"?o5(e,t,n).length>1:e in xY}function iQn(e){return Object.values(e).some(t=>t===void 0)}function G_e(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Xk(e,t){return{agentRuntimeType:e,model:t}}function Gk(e,t){return z5(e,{agentRuntimeType:t.agentRuntimeType,model:""})}function Uht({primaryRuntimeType:e,primaryModel:t,primaryConfig:n}){const r={...n};delete r.modelFallbacks;const s=Gk(n.modelFallbacks??[],Xk(e,t));return[{id:"primary",agentRuntimeType:e,model:t,config:{...r,...t?{model:t}:{}}},...s.map((a,o)=>({id:`fallback-${o}`,agentRuntimeType:a.agentRuntimeType,model:a.model,config:{...a.config??{},...a.model?{model:a.model}:{}}}))]}function qht(e,t,n){const r=e.findIndex(a=>a.id===t),s=e.findIndex(a=>a.id===n);return r<0||s<0||r===s?Y_e(e):Y_e(Sy(e,r,s))}function Y_e(e){return{primary:e[0]??{id:"primary",agentRuntimeType:"codex_local",model:"",config:{}},fallbacks:e.slice(1).map(n=>({agentRuntimeType:n.agentRuntimeType,model:n.model,config:{...n.config,...n.model?{model:n.model}:{}}}))}}const Vht="flex gap-3 overflow-x-auto overscroll-x-contain pb-2 pr-2 [-webkit-overflow-scrolling:touch]",XS="basis-[60%] min-w-[420px] shrink-0 grow-0";function hH(e){const t=R8[e.runtimeType]??e.runtimeType;return e.model?`${e.title} · ${t} · ${e.model}`:`${e.title} · ${t}`}function Wht(e){return e.checks.filter(t=>t.level==="warn"||t.level==="error")}function Hht(e){var c;const[t,n]=A.useState({modelOverride:null,effortOverride:null}),r=A.useRef(null),s=A.useRef(null),a=A.useRef(null),o=t,l=Ve({queryKey:e.activeAgent&&e.selectedOrganizationId?U.agents.adapterModels(e.selectedOrganizationId,e.activeAgent.agentRuntimeType):U.agents.adapterModels("__none__","__none__"),queryFn:()=>$n.adapterModels(e.selectedOrganizationId,e.activeAgent.agentRuntimeType),enabled:!!e.selectedOrganizationId&&!!e.activeAgent,retry:!1});return A.useEffect(()=>{var u;const d=`${e.selectedOrganizationId??"__none__"}:${e.composerScopeKey??((u=e.selectedConversation)==null?void 0:u.id)??"new"}:${e.activeAgentId??"__none__"}`;r.current!==null&&r.current!==d&&n({modelOverride:null,effortOverride:null}),r.current=d},[e.activeAgentId,e.composerScopeKey,(c=e.selectedConversation)==null?void 0:c.id,e.selectedOrganizationId]),{activeRuntimeOverrides:o,adapterModelsQuery:l,draftRuntimeOverrides:t,runtimeModelSelectRef:a,runtimeSelectorRef:s,setDraftRuntimeOverrides:n}}function aQn(e){return{applyRuntimeOverrides:n=>{e.activeAgent&&e.setDraftRuntimeOverrides(n)},runtimeSelectionPending:!1}}function kve(e){const t=e.agentRuntimeConfig.model??e.runtimeConfig.model;return typeof t=="string"&&t.trim()?t.trim():"Default model"}function Kht(e){const t={...e.runtimeConfig,...e.agentRuntimeConfig},n=AH(e.agentRuntimeType),r=t[n]??(e.agentRuntimeType==="codex_local"?t.reasoningEffort:null);return typeof r=="string"&&r.trim()?r.trim():null}function dme(e){if(!e||e.toLowerCase()==="auto")return"Auto";const n={minimal:"Minimal",light:"Light",low:"Low",medium:"Medium",high:"High",xhigh:"Extra High",max:"Max",ultra:"Ultra"}[e.toLowerCase()];return n||e.charAt(0).toUpperCase()+e.slice(1)}function oQn(e,t,n){const r=c9(e.agentRuntimeType,t),s=(n==null?void 0:n.trim())??"";return!s||r.some(a=>a.id===s)?r:[...r,{id:s,label:s}]}function lQn(e,t,n,r){const s=n??kve(e);if(!CL(e.agentRuntimeType,s,r))return{modelOverride:n,effortOverride:null};const a=o5(e.agentRuntimeType,s,r);return{modelOverride:n,effortOverride:t.effortOverride&&a.some(o=>o.id===t.effortOverride)?t.effortOverride:null}}function Zht(e){var s;if(!e.agent)return"Loading runtime";const t=e.overrides.modelOverride??kve(e.agent),n=(s=e.adapterModels)==null?void 0:s.find(a=>a.id===t);if(!CL(e.agent.agentRuntimeType,t,n))return t;const r=e.overrides.effortOverride==null?Kht(e.agent):e.overrides.effortOverride;return`${t} · ${dme(r)}`}function cQn(e){const t=oQn(e.agent,e.adapterModels,e.overrides.modelOverride),n=kve(e.agent),r=Kht(e.agent),s=e.overrides.modelOverride??n,a=t.find(f=>f.id===s),o=CL(e.agent.agentRuntimeType,s,a),l=o5(e.agent.agentRuntimeType,s,a).map(f=>({id:f.id||"auto",label:f.label})),c=e.overrides.effortOverride,d=e.error instanceof Error?e.error.message:e.error?"Models are temporarily unavailable.":null,u=c??r;return i.jsx(fht,{ariaContext:`this conversation (${e.agent.name} runtime)`,disabled:e.disabled,pending:e.pending,errorMessage:d,modelSelectRef:e.modelSelectRef,testIds:{modelTrigger:"chat-model-selector",modelOptions:"chat-model-options",modelOption:f=>f==null?"chat-model-option-default":`chat-model-option-${f}`,effortTrigger:"chat-effort-selector",effortOptions:"chat-effort-options",effortOption:f=>f==null?"chat-effort-option-default":`chat-effort-option-${f}`},model:{valueLabel:s,dataValue:e.overrides.modelOverride??"",selectedId:e.overrides.modelOverride,defaultOption:{id:null,label:`Agent default · ${n}`},options:t,loading:e.isLoading,emptyLabel:d?"Models unavailable":"No models found.",onSelect:f=>e.onChange(lQn(e.agent,e.overrides,f,t.find(m=>m.id===(f??n))))},effort:o?{valueLabel:dme(u),dataValue:c??"",selectedId:c,defaultOption:{id:null,label:`Agent default · ${dme(r)}`},options:l,onSelect:f=>e.onChange({...e.overrides,effortOverride:f})}:void 0})}function dQn(e){var l;const[t,n]=A.useState(!1),[r,s]=A.useState(null),a=A.useRef(null),o=()=>{if(!e.agent||e.disabled||!a.current)return;const c=a.current.getBoundingClientRect(),d=304,u=12;if(e.panelPlacement==="above"){s({left:Math.max(u,Math.min(c.right-d,window.innerWidth-d-u)),bottom:Math.max(u,window.innerHeight-c.top+8)}),n(!0);return}const f=window.innerWidth-c.right;s({left:f>=d+u?c.right+8:Math.max(u,c.left-d-8),top:Math.max(u,Math.min(c.top,window.innerHeight-u-360))}),n(!0)};return A.useEffect(()=>{if(!t||!e.modelSelectRef||typeof e.modelSelectRef!="object")return;const c=e.modelSelectRef;requestAnimationFrame(()=>{var d;return(d=c.current)==null?void 0:d.focus()})},[t,e.modelSelectRef]),i.jsxs(i.Fragment,{children:[i.jsxs("button",{ref:a,type:"button",role:"menuitem","data-chat-composer-menu-item":!0,"data-testid":"chat-agent-runtime-selector","aria-label":`Configure model and thinking for ${((l=e.agent)==null?void 0:l.name)??"selected agent"}`,"aria-haspopup":"dialog","aria-expanded":t,disabled:!e.agent||e.disabled,className:q("inline-flex min-w-0 max-w-44 items-center gap-1 rounded-[var(--radius-sm)] px-2 py-1","text-[11px] text-muted-foreground transition-colors hover:bg-[color:var(--surface-active)] hover:text-foreground","disabled:cursor-not-allowed disabled:opacity-55"),onClick:c=>{if(c.stopPropagation(),t){n(!1);return}o()},onKeyDown:c=>{(c.key==="ArrowRight"||c.key==="Enter"||c.key===" ")&&(c.preventDefault(),c.stopPropagation(),o())},children:[i.jsx("span",{className:"min-w-0 truncate",children:e.label}),e.pending?i.jsx(fn,{className:"h-3.5 w-3.5 shrink-0 animate-spin","aria-hidden":"true"}):i.jsx(vi,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":"true"})]}),t&&r&&e.agent&&typeof document<"u"?ja.createPortal(i.jsxs("div",{"data-chat-runtime-submenu":!0,"data-runtime-profile-panel":!0,"data-testid":"chat-agent-runtime-panel",role:"dialog","aria-label":`Model and thinking for ${e.agent.name}`,className:"surface-overlay fixed z-[65] w-[19rem] max-w-[calc(100vw-1.5rem)] rounded-[var(--radius-lg)] border p-1.5 shadow-lg",style:r,onKeyDownCapture:c=>{c.key!=="Escape"&&c.key!=="ArrowLeft"||(c.preventDefault(),c.stopPropagation(),n(!1),requestAnimationFrame(()=>{var d;return(d=a.current)==null?void 0:d.focus()}))},children:[i.jsxs("button",{type:"button",className:"chat-composer-menu-row mb-1",onClick:()=>{n(!1),requestAnimationFrame(()=>{var c;return(c=a.current)==null?void 0:c.focus()})},children:[i.jsx(Tw,{className:"h-4 w-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),i.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:e.agent.name})]}),i.jsx("div",{className:"border-t border-[color:var(--border-soft)] pt-1",children:i.jsx(cQn,{agent:e.agent,adapterModels:e.adapterModels,overrides:e.overrides,disabled:e.disabled,isLoading:e.isLoading,error:e.error,pending:e.pending,modelSelectRef:e.modelSelectRef,onChange:e.onChange})})]}),document.body):null]})}function Ove(e){var s;if(!["ArrowDown","ArrowUp","Home","End"].includes(e.key)||e.target instanceof Element&&e.target.closest("[data-chat-runtime-submenu]"))return;const t=Array.from(e.currentTarget.querySelectorAll("[data-chat-composer-menu-item]:not(:disabled)"));if(t.length===0)return;e.preventDefault();const n=t.findIndex(a=>a===document.activeElement),r=e.key==="Home"?0:e.key==="End"?t.length-1:e.key==="ArrowUp"?n<=0?t.length-1:n-1:n<0||n===t.length-1?0:n+1;(s=t[r])==null||s.focus()}function Sve(e){return i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-center justify-between gap-3 px-3 py-1.5 text-xs font-medium text-muted-foreground",children:[i.jsx("span",{children:"Agents"}),e.agentSelectionLocked?i.jsxs("span",{className:"inline-flex items-center gap-1","data-testid":"chat-agent-lock-state",children:[i.jsx(qae,{className:"h-3 w-3","aria-hidden":"true"}),"Bound to chat"]}):null]}),e.agents.length===0?i.jsxs("div",{className:"flex items-center gap-2 rounded-[var(--radius-md)] px-3 py-2 text-sm text-muted-foreground",children:[i.jsx(zo,{className:"h-4 w-4 shrink-0"}),i.jsx("span",{children:"Create or activate an agent before sending messages."})]}):e.agents.map(t=>{const n=e.activeAgentId===t.id,r=e.runtimeSelectionPending||e.newConversationSendInFlight||e.agentSelectionLocked&&!n||e.externalBound;return i.jsxs("div",{"data-testid":`chat-agent-option-${t.id}`,"data-selected":n?"true":void 0,className:q("flex min-h-10 items-center gap-1 rounded-[var(--radius-md)]",n&&"bg-[color:var(--surface-active)]"),children:[i.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":n,"aria-disabled":r||n,disabled:r&&!n,"data-chat-composer-menu-item":!0,className:"chat-composer-menu-row min-w-0 flex-1 disabled:cursor-default disabled:opacity-100",onClick:()=>e.onSelectAgent(t.id),children:[i.jsx(lc,{icon:t.icon,role:t.role,className:"h-4 w-4 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 flex-1 truncate text-left font-medium",children:of(t)}),e.agentSelectionLocked&&!n?i.jsx(qae,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground","aria-label":"Unavailable after chat starts"}):null]}),n&&e.showRuntimeControls!==!1?i.jsx(dQn,{agent:t,adapterModels:e.adapterModels,overrides:e.overrides,label:e.runtimeLabel,disabled:e.externalBound||e.newConversationSendInFlight,isLoading:e.isLoading,error:e.error,pending:e.runtimeSelectionPending,panelPlacement:e.runtimePanelPlacement,modelSelectRef:e.modelSelectRef,onChange:e.onChangeRuntime}):null]},t.id)})]})}function jve(e){return i.jsxs("button",{ref:e.buttonRef,type:"button","data-testid":"chat-agent-selector","aria-label":`Chat agent: ${e.label}`,"aria-expanded":e.expanded,disabled:e.disabled,className:q("chat-chip inline-flex max-w-[min(100%,16rem)] min-w-0 items-center gap-1.5 rounded-[var(--radius-md)] px-3 py-1.5 text-xs font-medium","transition-colors hover:bg-[color:var(--surface-active)] disabled:cursor-not-allowed disabled:opacity-60",e.expanded&&"bg-[color:var(--surface-active)]"),onClick:e.onClick,children:[e.agent?i.jsx(lc,{icon:e.agent.icon,role:e.agent.role,testId:"chat-agent-selector-icon",className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):null,i.jsx("span",{className:"min-w-0 truncate",children:e.label})]})}const ume={sending:!1,stopping:!1,stopRequested:!1,stopAccepted:!1,conversationId:null},fme=new Map;function uQn(e,t){return`${e}:${t}`}function fQn(e,t){const n=uQn(e,t),r=fme.get(n);if(r)return r;const s={key:n,state:ume,listeners:new Set,abortController:null,streamFence:mme()};return fme.set(n,s),s}function Og(e,t){if(e){e.state={...e.state,...t};for(const n of e.listeners)n()}}function sie(e,t){return["run-debug-chat-session",e,t]}function iie(){var e,t;return((t=(e=globalThis.crypto)==null?void 0:e.randomUUID)==null?void 0:t.call(e))??`annotation-${Date.now()}-${Math.random().toString(36).slice(2)}`}function mQn(e){var t;return((t=e.body)==null?void 0:t.trim())||(e.role==="user"?"Annotation-only feedback":"")}function AQn(e){return e.transcript??[]}function $v(){}function aie(e,t){return e instanceof $o?e.status===t:!!(e&&typeof e=="object"&&"status"in e&&e.status===t)}const hQn="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",pQn=250,gQn=1e4;function mme(){return{generationId:null,attemptEpoch:null,lastCommittedRenderSeq:0,renderedBodyHash:hQn}}function oie(e,t){t.generationId&&(e.generationId=t.generationId),t.attemptEpoch!==void 0&&(e.attemptEpoch=t.attemptEpoch),t.generationSeq!==void 0&&(e.lastCommittedRenderSeq=t.generationSeq),t.bodyHash&&(e.renderedBodyHash=t.bodyHash)}function xQn(e,t){const n=RC(e);return t?n!==t:n===null}function J_e({organizationId:e,target:t,onReplaceTarget:n}){var Pe;const r=er(),{pushToast:s}=ws(),a=Kr(),o=t.kind==="run_debug_chat",l=t.kind==="run_debug_chat"&&t.autoSend,c=A.useMemo(()=>o?fQn(e,t.clientMutationId):null,[o,e,t.clientMutationId]),d=A.useSyncExternalStore(Re=>c?(c.listeners.add(Re),()=>{c.listeners.delete(Re),queueMicrotask(()=>{c.listeners.size===0&&!c.state.sending&&!c.abortController&&fme.delete(c.key)})}):()=>{},()=>(c==null?void 0:c.state)??ume,()=>(c==null?void 0:c.state)??ume),[u,f]=A.useState(t.body??""),[m,h]=A.useState(0),[p,x]=A.useState(t.projectId??null),[b,y]=A.useState(null),[w,k]=A.useState(null),[S,j]=A.useState(d.sending),[C,I]=A.useState(d.stopping),[N,M]=A.useState(!1),[E,_]=A.useState(null),[z,T]=A.useState([]),[$,B]=A.useState(""),[F,W]=A.useReducer(a1e,t.inlineAnnotations??[],N6),[Y,G]=A.useState(!1),[V,L]=A.useState(null),R=A.useRef(null),D=A.useRef(null),X=A.useRef(null),ee=A.useRef(null),se=A.useRef(null),ne=A.useRef(null),le=A.useRef(t.clientMutationId||iie()),ie=A.useRef(t),re=A.useRef(t.conversationId),de=A.useRef(null),Be=A.useRef(!1),ae=A.useRef(!1),Ee=A.useRef(mme()),he=A.useRef(null),_e=A.useRef(0),Ie=A.useRef([]),$e=A.useRef(null),ce=A.useRef(!1),Oe=A.useRef(null),Ye=A.useRef(t);ie.current=t,le.current=t.clientMutationId||le.current,A.useEffect(()=>{c&&(j(d.sending),I(d.stopping),d.conversationId&&(re.current=d.conversationId))},[c,d]),A.useEffect(()=>{var Wt;const Re=Ye.current;!(((Wt=he.current)==null?void 0:Wt.conversationId)===t.conversationId&&he.current.clientMutationId===t.clientMutationId&&Re.conversationId===null&&!!t.conversationId)&&(Re.conversationId!==t.conversationId||Re.clientMutationId!==t.clientMutationId)&&(T([]),B("")),Ye.current=t},[t.clientMutationId,t.conversationId]),A.useEffect(()=>{S||he.current||(re.current=t.conversationId??null)},[S,t.conversationId]),A.useEffect(()=>{if(t.kind==="run_feedback_chat"&&!(typeof window>"u"))try{window.localStorage.setItem(`rudder.run-feedback-draft:${e}:${t.agentId}`,JSON.stringify(t))}catch{}},[e,t]);const J=Ve({queryKey:U.agents.list(e),queryFn:()=>$n.list(e)}),qe=Ve({queryKey:U.projects.list(e),queryFn:()=>Wi.list(e)}),be=Ve({queryKey:U.health,queryFn:()=>EA.get()}),ot=Ve({queryKey:U.chats.detail(e,t.conversationId??"__run-feedback-draft__"),queryFn:()=>Zn.get(t.conversationId),enabled:!!t.conversationId,retry:(Re,Nt)=>!aie(Nt,404)&&Re<2}),ke=Ve({queryKey:U.chats.messages(e,t.conversationId??"__run-feedback-draft__"),queryFn:()=>Zn.listMessages(e,t.conversationId,{includeTranscript:!0}),enabled:!!t.conversationId}),Ce=Ve({queryKey:U.chats.queue(e,t.conversationId??"__run-feedback-draft__"),queryFn:()=>Zn.listQueue(t.conversationId),enabled:!!t.conversationId,refetchInterval:S?1e3:!1});A.useEffect(()=>{if(t.kind!=="run_debug_chat"||!t.conversationId||!Ce.data)return;if(RC(Ce.data)!==null){j(!0),Og(c,{sending:!0,conversationId:t.conversationId});return}d.sending&&(j(!1),Og(c,{sending:!1,stopping:!1}))},[c,d.sending,Ce.data,t.conversationId,t.kind]),A.useEffect(()=>{ke.data&&T(Re=>qk(Re,ke.data))},[ke.data]),A.useEffect(()=>{var Re;(Re=Oe.current)==null||Re.scrollIntoView({block:"end"})},[z,$]),A.useEffect(()=>{f(t.body??"")},[t.body]),A.useEffect(()=>{const Re=t.inlineAnnotations??[],Nt=DT(F),Wt=Re.map(ht=>{const{attachmentFileIndexes:Lt,ordinal:Mn,...Ln}=ht;return Ln}),Jt=JBn(t.clientMutationId),Ze=new Set(Re.map(ht=>ht.id)),Ae={...Object.fromEntries(Object.entries(F.pendingFilesByAnnotationId).filter(([ht])=>Ze.has(ht))),...Jt};JSON.stringify(Wt)===JSON.stringify(Nt)&&Object.keys(Jt).length===0||(W({type:"reset",annotations:Re,pendingFilesByAnnotationId:Ae}),G(Re.length>0))},[F,t.clientMutationId,t.inlineAnnotations]),A.useEffect(()=>{x(t.projectId??null)},[t.projectId]);const ue=ot.data,mt=A.useMemo(()=>jL(J.data),[J.data]),ut=t.conversationId?(ue==null?void 0:ue.preferredAgentId)??t.agentId:t.kind==="run_debug_chat"?t.preferredAgentId:t.agentId,ge=A.useMemo(()=>mt.find(Re=>Re.id===ut)??null,[ut,mt]),Le=A.useMemo(()=>(qe.data??[]).find(Re=>Re.id===p)??null,[p,qe.data]),rt=t.kind==="run_debug_chat"||!!(S||t.projectLocked||t.conversationId||z.some(Re=>Re.role==="user")),At=t.kind==="run_feedback_chat"||!!(S||t.conversationId||z.some(Re=>Re.role==="user")),Ue=F.annotations.length,Se=K4(F.annotations,Object.values(F.pendingFilesByAnnotationId).reduce((Re,Nt)=>Re+Nt.length,0)),Te=!F.annotations.some(Re=>Re.sourceHash==="pending")&&!Se&&bM(u,F),He=A.useCallback(Re=>{const Nt=ie.current,Wt=Nt.kind==="run_feedback_chat"?{...Nt,...Re,preferredAgentId:Nt.agentId}:{...Nt,...Re};ie.current=Wt,n(fs(Nt),Wt)},[n]);A.useEffect(()=>{t.kind==="run_feedback_chat"&&t.preferredAgentId&&t.preferredAgentId!==t.agentId&&He({preferredAgentId:t.agentId})},[t.agentId,t.kind,t.preferredAgentId,He]);const fe=A.useCallback(Re=>{const Nt=ie.current;if(Nt.conversationId!==Re)return!1;if(Nt.kind==="run_debug_chat")return _("This Debug Chat is no longer available. Open Ask agent again to retry."),!1;const Wt=iie();return le.current=Wt,re.current=null,T([]),B(""),y(null),k(null),He({conversationId:null,projectLocked:!1,clientMutationId:Wt,preferredAgentId:Nt.agentId,recoveryNotice:"The previous feedback chat is no longer available. Your draft was kept. Choose a project and send again."}),!0},[He]);A.useEffect(()=>{t.conversationId&&aie(ot.error,404)&&fe(t.conversationId)},[ot.error,fe,t.conversationId]);const je=A.useCallback(()=>{const Re=he.current;if(!Re)return!1;const Nt=ie.current;return Re.conversationId?Nt.conversationId===Re.conversationId:Nt.clientMutationId===Re.clientMutationId},[]),ye=A.useCallback(async()=>{const Re=Ie.current.splice(0),Nt=$e.current;if(Nt)for(const Wt of Re)await Nt(Wt)},[]),tt=A.useCallback(async(Re,Nt)=>{const Wt=Date.now()+gQn,Jt=U.chats.queue(e,Re);for(;Date.now()<Wt;){try{const Ze=await r.fetchQuery({queryKey:Jt,queryFn:()=>Zn.listQueue(Re),staleTime:0});if(r.setQueryData(Jt,Ze),xQn(Ze,Nt))return!0}catch{}await new Promise(Ze=>window.setTimeout(Ze,pQn))}return!1},[e,r]),me=A.useCallback(async()=>{var Ze;const Re=he.current,Nt=(Re==null?void 0:Re.conversationId)??re.current??d.conversationId,Wt=!!(c&&d.sending);if(!Nt||!S||C||!je()&&!Wt)return;const Jt=iie();Be.current=!0,I(!0),Og(c,{stopping:!0,stopRequested:!0,stopAccepted:!1}),M(!1),_(null);try{const Mt=await r.fetchQuery({queryKey:U.chats.queue(e,Nt),queryFn:()=>Zn.listQueue(Nt),staleTime:0});r.setQueryData(U.chats.queue(e,Nt),Mt);const Ae=(c==null?void 0:c.streamFence)??Ee.current,ht=Mt.activeGenerationId&&Mt.activeAttemptEpoch!==null&&Mt.activeAttemptEpoch!==void 0&&Mt.activeControlVersion!==null&&Mt.activeControlVersion!==void 0?{generationId:Mt.activeGenerationId,attemptEpoch:Mt.activeAttemptEpoch,controlVersion:Mt.activeControlVersion}:null,Lt={controlActionId:Jt,...ht?{expectedGenerationId:ht.generationId,expectedAttemptEpoch:ht.attemptEpoch,expectedControlVersion:ht.controlVersion}:{},lastCommittedRenderSeq:Ae.lastCommittedRenderSeq,renderedBodyHash:Ae.renderedBodyHash},Mn=await Zn.stopMessageStream(Nt,Lt);if(Mn.controlActionId!==Jt)throw new Error("Stop confirmation did not match this feedback stream.");Mn.stopped||["stopping","stop_requested","stopped","interrupted_unverified"].includes(Mn.disposition??"")?(ae.current=!0,Og(c,{stopAccepted:!0}),Ie.current=[],B(""),(Ze=(c==null?void 0:c.abortController)??de.current)==null||Ze.abort(),Mn.disposition==="stopped"||Mn.disposition==="interrupted_unverified"||await tt(Nt,Mn.generationId??(ht==null?void 0:ht.generationId)??null)?(I(!1),Og(c,{sending:!1,stopping:!1}),M(!1)):(I(!1),Og(c,{sending:!1,stopping:!1}),M(!0),_("Stop was accepted, but the final runtime state could not be confirmed yet."))):(Be.current=!1,await ye(),I(!1),Og(c,{stopping:!1,stopRequested:!1,stopAccepted:!1})),await Promise.allSettled([r.invalidateQueries({queryKey:U.chats.detail(e,Nt)}),r.invalidateQueries({queryKey:U.chats.messages(e,Nt)})])}catch(Mt){Be.current=!1,await ye(),I(!1),Og(c,{stopping:!1,stopRequested:!1,stopAccepted:!1}),M(!1),_(Mt instanceof Error?Mt.message:"Could not stop feedback.")}},[c,d,e,r,ye,S,C,je,tt]),ze=Re=>{if(rt)return;const Nt=Re||null;x(Nt),He({projectId:Nt})},De=A.useCallback(()=>{y(null),k(null)},[]),kt=A.useCallback(Re=>{const Nt=Re==="project"?ee.current:se.current;Nt&&k(Uk(Nt)),y(Re)},[]),gt=Re=>{At||!mt.some(Nt=>Nt.id===Re)||(He({preferredAgentId:Re}),De())};A.useEffect(()=>{if(!b)return;const Re=()=>{const Jt=b==="project"?ee.current:se.current;Jt&&k(Uk(Jt))},Nt=Jt=>{var Mt,Ae,ht;const Ze=Jt.target;Ze instanceof Node&&((Mt=X.current)!=null&&Mt.contains(Ze)||(Ae=ee.current)!=null&&Ae.contains(Ze)||(ht=se.current)!=null&&ht.contains(Ze)||De())},Wt=Jt=>{if(Jt.key!=="Escape")return;const Ze=b==="project"?ee.current:se.current;De(),requestAnimationFrame(()=>Ze==null?void 0:Ze.focus())};return Re(),window.addEventListener("resize",Re),window.addEventListener("scroll",Re,!0),document.addEventListener("pointerdown",Nt,!0),document.addEventListener("keydown",Wt),()=>{window.removeEventListener("resize",Re),window.removeEventListener("scroll",Re,!0),document.removeEventListener("pointerdown",Nt,!0),document.removeEventListener("keydown",Wt)}},[De,b]);const Ke=async()=>{var Ln;if(ce.current||S||C||N||!Te)return;const Re=ie.current,Nt=u.trim(),Wt=Gq(F),Jt=new Set(Wt.inlineAnnotations.map(Un=>Un.id));if(fH({annotations:Wt.inlineAnnotations,devServer:(Ln=be.data)==null?void 0:Ln.devServer,draftPersistence:"durable",pushToast:s}))return;ce.current=!0,Re.kind==="run_feedback_chat"&&Re.recoveryNotice&&He({recoveryNotice:null}),Re.kind==="run_debug_chat"&&Re.errorMessage&&He({errorMessage:null}),Re.kind==="run_debug_chat"&&f(""),j(!0),Og(c,{sending:!0,stopping:!1,stopRequested:!1,stopAccepted:!1}),I(!1),M(!1),Be.current=!1,ae.current=!1,Ee.current=mme(),_(null),B("");const Ze=_e.current+1;_e.current=Ze,he.current={conversationId:Re.conversationId??null,clientMutationId:Re.clientMutationId??le.current},Ie.current=[];const Mt=new AbortController;de.current=Mt,c&&(c.abortController=Mt,c.streamFence=Ee.current);const Ae=()=>_e.current===Ze&&je(),ht=async Un=>{if(!(!Ae()||ae.current)){if(Un.type==="ack"){oie(Ee.current,Un),re.current=Un.userMessage.conversationId,Og(c,{conversationId:Un.userMessage.conversationId,sending:!0}),!Re.conversationId&&he.current&&(he.current={...he.current,conversationId:Un.userMessage.conversationId}),T(Ct=>qk(Ct,[Un.userMessage]));for(const Ct of Jt)W({type:"delete",id:Ct});const mr=ie.current,bt=mr.inlineAnnotations.filter(Ct=>!Jt.has(Ct.id)),rn=Re.conversationId?{...mr,body:mr.body===Nt?"":mr.body,inlineAnnotations:bt}:mr.kind==="run_feedback_chat"?{...mr,conversationId:Un.userMessage.conversationId,projectLocked:!0,projectId:Re.projectId,body:mr.body===Nt?"":mr.body,inlineAnnotations:bt}:{...mr,conversationId:Un.userMessage.conversationId,body:mr.body===Nt?"":mr.body,inlineAnnotations:bt};if(He(rn),Re.kind==="run_debug_chat"&&(r.setQueryData(sie(e,Re.clientMutationId),{autoSendConsumed:!0,conversationId:Un.userMessage.conversationId}),f(""),h(Ct=>Ct+1)),G(bt.length>0),!Re.conversationId&&Re.kind==="run_feedback_chat")try{window.localStorage.setItem(`rudder.run-feedback-draft:${e}:${Re.agentId}`,JSON.stringify(rn))}catch{}}if(Un.type==="assistant_delta"&&(oie(Ee.current,Un),B(mr=>mr+Un.delta)),(Un.type==="assistant_state"||Un.type==="transcript_entry")&&oie(Ee.current,Un),Un.type==="final"&&(B(""),T(mr=>qk(mr,Un.messages))),Un.type==="error")throw new Error(Un.error)}};$e.current=ht;const Lt=async Un=>{if(!(!Ae()||ae.current)){if(Be.current&&!ae.current){Ie.current.push(Un);return}await ht(Un)}};let Mn=null;try{Re.conversationId?await Zn.sendMessageStream(Re.conversationId,Nt,{signal:Mt.signal,files:Wt.files,inlineAnnotations:Wt.inlineAnnotations,onEvent:Lt}):await Zn.sendFirstMessageStream(e,Nt,{signal:Mt.signal,preferredAgentId:Re.kind==="run_debug_chat"?Re.preferredAgentId:Re.agentId,issueCreationMode:"manual_approval",planMode:!1,modelOverride:null,effortOverride:null,contextLinks:Re.projectId?[{entityType:"project",entityId:Re.projectId}]:[],clientMutationId:le.current,files:Wt.files,inlineAnnotations:Wt.inlineAnnotations,onEvent:Lt}),Re.conversationId&&await Promise.all([r.invalidateQueries({queryKey:U.chats.detail(e,Re.conversationId)}),r.invalidateQueries({queryKey:U.chats.messages(e,Re.conversationId)})])}catch(Un){const mr=(Un instanceof DOMException||Un instanceof Error)&&Un.name==="AbortError";!(ae.current||(c==null?void 0:c.state.stopAccepted))&&(!mr||!Be.current)&&(Re.conversationId&&aie(Un,404)?fe(Re.conversationId):Mn=Re.kind==="run_debug_chat"?`${uH(Un)} Choose another agent or try again.`:uH(Un,"feedback"))}finally{const Un=ae.current;de.current=null,ce.current=!1,j(!1),Og(c,{sending:!1,stopping:!1,stopRequested:!1,stopAccepted:!1}),(c==null?void 0:c.abortController)===Mt&&(c.abortController=null),!Un&&!Be.current&&I(!1),(!Be.current||Un)&&($e.current=null,he.current=null,Ie.current=[],Be.current=!1),Mn&&(_(Mn),Re.kind==="run_debug_chat"&&(f(Nt),He({autoSend:!1,errorMessage:Mn})))}};A.useEffect(()=>{if(t.kind!=="run_debug_chat")return;const Re=r.getQueryData(sie(e,t.clientMutationId));!(Re!=null&&Re.conversationId)||t.conversationId===Re.conversationId&&!t.body&&!t.autoSend||(f(""),h(Nt=>Nt+1),He({conversationId:Re.conversationId,body:"",autoSend:!1}))},[l,e,r,t.body,t.clientMutationId,t.conversationId,t.kind,He]),A.useEffect(()=>{if(t.kind!=="run_debug_chat"||!l||J.isPending)return;const Re=sie(e,t.clientMutationId),Nt=r.getQueryData(Re);if(Nt!=null&&Nt.autoSendConsumed){const Wt=Nt.conversationId??re.current;He({autoSend:!1,conversationId:Wt??t.conversationId,body:Wt?"":t.body});return}if(r.setQueryData(Re,{autoSendConsumed:!0,conversationId:null}),He({autoSend:!1}),!ge){const Wt="The Run agent is unavailable. Choose another agent or try again.";_(Wt),He({autoSend:!1,errorMessage:Wt});return}Ke()},[J.isPending,l,ge,t.clientMutationId,t.kind]);const Je=z,wt=!!(o&&S&&t.conversationId&&RC(Ce.data)),Z=S&&!!re.current&&(je()||wt),Me=C||N?"stopping":Z?"stop":S?"sending":"send",lt=C||N||!S&&!Te||S&&!Z;return i.jsxs("div",{className:"flex h-full min-h-0 flex-col","data-testid":o?"run-debug-chat-panel":"run-feedback-chat-panel","data-debug-conversation-id":o?t.conversationId??"":void 0,"data-debug-runtime-sending":o?String(d.sending):void 0,"data-debug-queue-status":o?((Pe=Ce.data)==null?void 0:Pe.activeGenerationStatus)??"":void 0,children:[i.jsx("div",{className:"scrollbar-auto-hide min-h-0 flex-1 overflow-y-auto px-4 py-4","data-testid":"run-chat-messages-scroll",children:i.jsxs("div",{className:"mx-auto flex w-full max-w-3xl flex-col gap-4",children:[i.jsxs("div",{className:"flex items-center gap-2 border-b border-border/70 pb-3",children:[i.jsx(Si,{className:"h-4 w-4 text-muted-foreground","aria-hidden":"true"}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("div",{className:"truncate text-sm font-medium",children:o?"Debug Run":"Run feedback"}),i.jsx("div",{className:"truncate text-xs text-muted-foreground",children:(ge==null?void 0:ge.name)??t.agentId})]})]}),ue?i.jsx("div",{className:"text-xs text-muted-foreground",children:ue.title}):null,o&&S&&!t.conversationId&&t.body.trim()&&!z.some(Re=>Re.role==="user")?i.jsx("div",{className:"ml-6 rounded-lg border bg-muted/30 px-3 py-2 text-sm","data-testid":"run-chat-pending-message",children:i.jsx("div",{className:"whitespace-pre-wrap break-words",children:t.body})}):null,ue?Je.map(Re=>{const Nt=AQn(Re);return i.jsxs("div",{"data-testid":"run-feedback-chat-message",children:[Re.role==="assistant"&&Nt.length>0?i.jsx(J6,{entries:Nt,state:Re.status,generationTerminalReason:Re.generationTerminalReason,streamStartedAt:new Date(Re.createdAt),streamEndedAt:new Date(Re.updatedAt),assistantMessageBody:Re.body,showDeveloperDiagnostics:!1}):null,Re.role==="user"&&!Re.body.trim()?i.jsx("div",{className:"mb-2 text-xs text-muted-foreground",children:"Annotation-only feedback"}):null,i.jsx(Qk,{conversation:ue,message:Re,agents:J.data,decisionNote:"",onDecisionNoteChange:$v,decisionNoteMentions:[],onDecisionNoteMentionQueryChange:$v,onDecisionNoteInlineTokenClick:$v,onApprovalAction:$v,onIssueProposalChange:$v,onResolveOperationProposal:$v,onConvertToIssue:$v,actionPending:!1,onCopyMessageText:Wt=>{var Jt;return(Jt=navigator.clipboard)==null?void 0:Jt.writeText(Wt)},onOpenFile:$v,onSelectResponseAnnotation:Wt=>{Wt.surface==="agent_run_transcript"&&a(`/agents/${t.agentId}/runs/${Wt.sourceRunId}`)},skillReferences:[]})]},Re.id)}):Je.map(Re=>i.jsxs("div",{className:`rounded-lg border px-3 py-2 text-sm ${Re.role==="user"?"ml-6 bg-muted/30":"mr-6"}`,children:[i.jsx("div",{className:"mb-1 text-[10px] uppercase tracking-wide text-muted-foreground",children:Re.role}),i.jsx("div",{className:"whitespace-pre-wrap break-words",children:mQn(Re)})]},Re.id)),ue&&$?i.jsx("div",{"data-testid":"run-feedback-chat-streaming",children:i.jsx("div",{className:"max-w-3xl whitespace-pre-wrap break-words text-sm text-foreground",children:$})}):null,i.jsx("div",{ref:Oe,"data-testid":"run-chat-message-end"})]})}),E||(t.kind==="run_feedback_chat"?t.recoveryNotice:t.errorMessage)||Se?i.jsx("div",{role:"alert",className:"px-4 pb-2 text-sm text-destructive",children:E??(t.kind==="run_feedback_chat"?t.recoveryNotice:t.errorMessage)??Se}):null,i.jsxs("div",{className:"shrink-0 px-4 pb-4",children:[i.jsxs(mY,{ref:D,className:"mx-auto max-w-3xl",testId:"run-feedback-composer",children:[Ue>0?i.jsxs("div",{className:"mb-3 flex flex-col items-start gap-2",children:[i.jsx(Q2e,{annotations:F.annotations,pendingFilesByAnnotationId:F.pendingFilesByAnnotationId,open:Y,buttonRef:R,onOpenChange:Re=>{G(Re),Re&&L(null)},onClear:()=>{W({type:"clear"}),He({inlineAnnotations:[]})},onEdit:Re=>{ne.current=R.current,L(Re.id)},onDelete:Re=>{W({type:"delete",id:Re}),He({inlineAnnotations:F.annotations.filter(Nt=>Nt.id!==Re)})}}),V?(()=>{const Re=F.annotations.find(Wt=>Wt.id===V);if(!Re)return null;const Nt=ne.current;return i.jsx(ZG,{annotation:Re,ordinal:Re.ordinal,pendingFiles:F.pendingFilesByAnnotationId[Re.id]??[],showSelectedTextContext:!0,anchorRect:(Nt==null?void 0:Nt.getBoundingClientRect())??null,getAnchorRect:()=>(Nt==null?void 0:Nt.getBoundingClientRect())??null,boundaryRect:null,getBoundaryRect:()=>null,returnFocusRef:ne,validateSave:Wt=>i1e(F,Re.id,{comment:Wt.comment,attachmentIds:Wt.attachmentIds,files:Wt.pendingFiles}),onSave:({comment:Wt,pendingFiles:Jt,attachmentIds:Ze})=>{W({type:"replaceDraft",id:Re.id,comment:Wt,attachmentIds:Ze,files:Jt}),He({inlineAnnotations:F.annotations.map(Mt=>Mt.id===Re.id?{...Mt,comment:Wt,attachmentIds:Ze}:Mt)}),L(null)},onCancel:()=>L(null),onDelete:()=>{W({type:"delete",id:Re.id}),He({inlineAnnotations:F.annotations.filter(Wt=>Wt.id!==Re.id)}),L(null)}})})():null]}):null,i.jsx(AY,{value:u,onChange:Re=>{S||C||N||(f(Re),He({body:Re}))},placeholder:o?"Ask a follow-up…":"Add context for this feedback…",onSubmit:()=>void Ke()},o?m:void 0),i.jsxs(hY,{actions:i.jsx(pY,{mode:Me,stoppingComplete:N,ariaLabel:N?"Stop status pending":Me==="stop"?"Stop feedback":Me==="stopping"?"Stopping feedback":Me==="sending"?"Sending feedback":"Send feedback",disabled:lt,onClick:()=>{if(Me==="stop"){me();return}Me==="send"&&Ke()}}),children:[o?null:i.jsx(Dht,{project:Le,label:(Le==null?void 0:Le.name)??"No project",expanded:b==="project",disabled:rt||qe.isPending,buttonRef:ee,testId:"run-feedback-project-selector",iconTestId:"run-feedback-project-icon",clearTestId:"run-feedback-project-clear",onClick:()=>{b==="project"?De():kt("project")},onClear:()=>ze("")}),i.jsx(jve,{buttonRef:se,agent:ge,label:ge?of(ge):J.isPending?"Loading agents":"No agent",expanded:b==="agent",disabled:At||J.isPending,onClick:()=>{b==="agent"?De():kt("agent")}})]})]}),b&&w&&typeof document<"u"?ja.createPortal(i.jsx(yve,{menuRef:X,testId:`run-feedback-${b}-menu`,ariaLabel:b==="agent"?"Run feedback agent":"Run feedback project",position:w,onKeyDown:b==="agent"?Ove:void 0,children:b==="project"?i.jsxs(i.Fragment,{children:[i.jsx(Rht,{projects:qe.data??[],activeProjectId:p,onSelect:Re=>{ze(Re??""),De()}}),qe.isError?i.jsxs("div",{className:"mt-1 flex items-center justify-between gap-3 border-t border-[color:var(--border-soft)] px-3 py-2 text-xs",children:[i.jsx("span",{role:"alert",className:"text-destructive",children:"Projects could not be loaded."}),i.jsx("button",{type:"button","data-chat-composer-menu-item":!0,className:"font-medium text-foreground hover:underline disabled:text-muted-foreground disabled:no-underline",disabled:qe.isFetching,onClick:()=>void qe.refetch(),children:qe.isFetching?"Retrying...":"Retry"})]}):null]}):i.jsx(Sve,{agents:mt,activeAgentId:ut,agentSelectionLocked:At,runtimeSelectionPending:!1,newConversationSendInFlight:S&&!ue,externalBound:!1,adapterModels:null,overrides:{modelOverride:null,effortOverride:null},runtimeLabel:"",showRuntimeControls:!1,onSelectAgent:gt,onChangeRuntime:()=>{}})}),document.body):null]})]})}class lie extends Error{constructor(){super("Side Chat close was superseded by a newer generation."),this.name="ChatGenerationCloseSupersededError"}}class Xht{constructor(){ls(this,"activeByChatId",new Map);ls(this,"listenersByChatId",new Map);ls(this,"getSnapshot",t=>this.activeByChatId.get(t)===!0);ls(this,"subscribe",(t,n)=>{const r=this.listenersByChatId.get(t)??new Set;return r.add(n),this.listenersByChatId.set(t,r),()=>{r.delete(n),r.size===0&&this.listenersByChatId.delete(t)}})}setActive(t,n){if(this.getSnapshot(t)!==n){n?this.activeByChatId.set(t,!0):this.activeByChatId.delete(t);for(const r of this.listenersByChatId.get(t)??[])r()}}}const bQn=new Set,Ght={activeChatIds:bQn,streamDrafts:{},sendInFlightByChatId:{},isChatGenerationActive:()=>!1,setChatSendInFlight:()=>{},setStreamDraftForChat:()=>{},setStreamAbortController:()=>{},abortChatStream:()=>{},beginChatGeneration:()=>({epoch:0,conversationId:null}),tryBeginChatGeneration:()=>null,rememberChatGenerationConversation:()=>{},setChatGenerationConversation:()=>!1,isChatGenerationCurrent:()=>!1,isChatGenerationClosePending:()=>!1,releaseChatGenerationScope:()=>{},requestChatGenerationClose:()=>({epoch:0,conversationId:null}),resetChatGenerationClose:()=>{},clearChatGenerationConversation:()=>{},destroyChatGenerationConversation:async(e,t,n)=>{await n()}},Yht=A.createContext(Ght),Jht=A.createContext(Ght),yQn=new Xht,ept=A.createContext(yQn);function vQn({children:e}){const t=kL(),[n,r]=A.useState({}),[s,a]=A.useState({}),o=A.useRef(n),l=A.useRef(null);l.current||(l.current=new Xht);const c=l.current,d=A.useRef({}),u=A.useRef({}),f=A.useRef(0),m=A.useRef({}),h=A.useRef(null),p=A.useRef(null),x=A.useRef(0),b=A.useCallback(()=>{h.current!==null&&(window.clearTimeout(h.current),h.current=null),r(o.current)},[]),y=A.useCallback(R=>{if(R){b();return}if(h.current!==null)return;const D=Date.now()<x.current;h.current=window.setTimeout(()=>{h.current=null,D?A.startTransition(()=>r(o.current)):r(o.current)},D?200:50)},[b]);A.useEffect(()=>{const R=()=>{x.current=Date.now()+120,p.current!==null&&window.clearTimeout(p.current),p.current=window.setTimeout(()=>{p.current=null,b()},120)};return window.addEventListener("scroll",R,{capture:!0,passive:!0}),window.addEventListener("wheel",R,{capture:!0,passive:!0}),()=>{window.removeEventListener("scroll",R,!0),window.removeEventListener("wheel",R,!0),h.current!==null&&window.clearTimeout(h.current),p.current!==null&&window.clearTimeout(p.current)}},[b]);const w=A.useMemo(()=>new Set(Object.keys(n)),[n]),k=A.useCallback((R,D)=>{a(X=>pOn(X,R,D))},[]),S=A.useCallback((R,D)=>{const X=o.current,ee=X[R]??null,se=typeof D=="function"?D(ee):D,ne=gOn(X,R,se);if(ne===X)return;if(o.current=ne,c.setActive(R,se!==null),((ee==null?void 0:ee.state)!==(se==null?void 0:se.state)||ee===null!=(se===null))&&t.updateSummary(`chat:${R}`,{status:(se==null?void 0:se.state)??(ee?"completed":null)}),se===null&&ee){h.current!==null&&(window.clearTimeout(h.current),h.current=null),r(X),window.setTimeout(()=>r(o.current),0);return}const le=se===null||se.state==="failed"||se.state==="stopped";y(le)},[t,y,c]),j=A.useCallback((R,D)=>{if(D){d.current={...d.current,[R]:D};return}if(!(R in d.current))return;const{[R]:X,...ee}=d.current;d.current=ee},[]),C=A.useCallback(R=>{var D;(D=d.current[R])==null||D.abort()},[]),I=A.useCallback(R=>{const D=u.current[R];if(D)return D;const X={epoch:0,conversationId:null,closeRequested:!1,sendClaimed:!1};return u.current={...u.current,[R]:X},X},[]),N=A.useCallback((R,D)=>{const X=I(R),ee=X.closeRequested?null:X.conversationId;return X.epoch=++f.current,X.closeRequested=!1,X.sendClaimed=!0,X.conversationId=D??ee,{epoch:X.epoch,conversationId:X.conversationId}},[I]),M=A.useCallback((R,D)=>{const X=I(R);return X.sendClaimed&&!X.closeRequested?null:N(R,D)},[N,I]),E=A.useCallback((R,D)=>{const X=u.current[R];!X||X.closeRequested||(X.conversationId===null||X.conversationId===D)&&(X.conversationId=D)},[]),_=A.useCallback((R,D,X)=>{const ee=u.current[R];return!ee||ee.epoch!==D||ee.closeRequested?!1:(ee.conversationId=X,!0)},[]),z=A.useCallback((R,D)=>{const X=u.current[R];return!!(X&&X.epoch===D&&!X.closeRequested)},[]),T=A.useCallback((R,D)=>{const X=u.current[R];return!!(X!=null&&X.closeRequested&&(D===void 0||X.epoch===D))},[]),$=A.useCallback((R,D)=>{const X=u.current[R];if(!X||X.epoch!==D)return;const{[R]:ee,...se}=u.current;u.current=se},[]),B=A.useCallback((R,D)=>{const X=I(R);return D&&!X.conversationId&&(X.conversationId=D),X.epoch=++f.current,X.closeRequested=!0,X.sendClaimed=!1,{epoch:X.epoch,conversationId:X.conversationId}},[I]),F=A.useCallback((R,D)=>{const X=u.current[R];(X==null?void 0:X.epoch)===D&&(X.closeRequested=!1,X.sendClaimed=!1)},[]),W=A.useCallback((R,D)=>{const X=u.current[R];(X==null?void 0:X.conversationId)===D&&(X.conversationId=null)},[]),Y=A.useCallback((R,D,X)=>{const ee=m.current[R];if((ee==null?void 0:ee.conversationId)===D)return ee.promise;let se;return se=(async()=>{try{await X()}finally{const ne=m.current[R];if((ne==null?void 0:ne.promise)===se){const{[R]:le,...ie}=m.current;m.current=ie}}})(),m.current={...m.current,[R]:{conversationId:D,promise:se}},se},[]),G=A.useCallback(R=>!!(R&&c.getSnapshot(R)),[c]),V=A.useMemo(()=>({abortChatStream:C,beginChatGeneration:N,clearChatGenerationConversation:W,destroyChatGenerationConversation:Y,tryBeginChatGeneration:M,isChatGenerationActive:G,isChatGenerationCurrent:z,isChatGenerationClosePending:T,rememberChatGenerationConversation:E,releaseChatGenerationScope:$,requestChatGenerationClose:B,resetChatGenerationClose:F,setChatGenerationConversation:_,setChatSendInFlight:k,setStreamDraftForChat:S,setStreamAbortController:j}),[C,N,W,Y,M,G,z,T,E,$,B,F,_,k,j,S]),L=A.useMemo(()=>({activeChatIds:w,streamDrafts:n,sendInFlightByChatId:s,beginChatGeneration:N,tryBeginChatGeneration:M,clearChatGenerationConversation:W,destroyChatGenerationConversation:Y,isChatGenerationActive:G,isChatGenerationCurrent:z,isChatGenerationClosePending:T,rememberChatGenerationConversation:E,releaseChatGenerationScope:$,requestChatGenerationClose:B,resetChatGenerationClose:F,setChatGenerationConversation:_,setChatSendInFlight:k,setStreamDraftForChat:S,setStreamAbortController:j,abortChatStream:C}),[C,w,N,W,Y,G,z,T,E,$,s,B,F,_,k,j,S,n,M]);return i.jsx(ept.Provider,{value:c,children:i.jsx(Jht.Provider,{value:V,children:i.jsx(Yht.Provider,{value:L,children:i.jsx(aen,{children:e})})})})}function Cve(){return A.useContext(Yht)}function Nve(){return A.useContext(Jht)}function wQn(e){const t=A.useContext(ept);return A.useSyncExternalStore(n=>t.subscribe(e,n),()=>t.getSnapshot(e),()=>t.getSnapshot(e))}function tpt(e){return vN(e)}function kQn(e){const t=new Map;for(const n of xKe({orgUrlKey:e.orgUrlKey,organizationSkills:e.organizationSkills,pluginManagedSkillIds:e.pluginManagedSkillIds}))t.set(n.skillMarkdownTarget,n);for(const n of vN(e))t.set(n.skillMarkdownTarget,n);return[...t.values()]}function npt(e,t){const n=t.trim().toLowerCase();return n?e.filter(r=>r.searchText.includes(n)):e}function rpt(e){return[...e].reverse().find(t=>t.role==="assistant"&&t.kind==="message"&&t.status==="completed"&&!t.supersededAt)??null}function OQn(e){const t=e.findIndex(n=>{var r;return n.kind==="system_event"&&((r=n.structuredPayload)==null?void 0:r.eventType)==="side_chat_started"});return t>=0?e.slice(t+1):e}function spt(e,t=new Date){return(e==null?void 0:e.conversationKind)!=="side_chat"||e.sideChatState==="kept"?!1:e.sideChatState==="completed"||e.sideChatState==="expired"?!0:e.sideChatState!=="active"||!e.sideChatExpiresAt?!1:new Date(e.sideChatExpiresAt).getTime()<=t.getTime()}const cie=[];function SQn(e,t){if(!e)return null;const n=new Date(e).getTime()-t.getTime();if(n<=0)return"Expired · read-only";const r=Math.max(1,Math.ceil(n/6e4));return r<60?`${r}m left`:`${Math.floor(r/60)}h ${r%60}m left`}function jQn(e){return e.transcript??[]}function Fv(){}function CQn({organizationId:e,target:t,active:n=!0,onRegisterCloseHandler:r,onReplaceTarget:s,onSelectResponseAnnotation:a}){var Ls,Vt;const o=er(),{pushToast:l}=ws(),{sendInFlightByChatId:c,streamDrafts:d}=Cve(),{abortChatStream:u,clearChatGenerationConversation:f,destroyChatGenerationConversation:m,isChatGenerationClosePending:h,isChatGenerationCurrent:p,rememberChatGenerationConversation:x,requestChatGenerationClose:b,releaseChatGenerationScope:y,resetChatGenerationClose:w,setChatGenerationConversation:k,setChatSendInFlight:S,setStreamAbortController:j,setStreamDraftForChat:C,tryBeginChatGeneration:I}=Nve(),N=_ge(e,t),M=d[N]??null,E=!!c[N],[_,z]=A.useState(""),[T,$]=A.useState(null),[B,F]=A.useState(()=>new Date),[W,Y]=A.useState(null),[G,V]=A.useState(!1),[L,R]=A.useState(null),[D,X]=A.useState(!1),[ee,se]=A.useState(!1),[ne,le]=A.useState(""),[ie,re]=A.useState([]),[de,Be]=A.useReducer(a1e,t.inlineAnnotations??[],N6),[ae,Ee]=A.useState(!1),[he,_e]=A.useState(null),Ie=A.useRef(null),$e=A.useRef(null),ce=A.useRef(null),Oe=A.useRef(null),Ye=A.useRef(null),J=A.useRef(null),qe=A.useRef(null),be=A.useRef(!1),ot=A.useRef(t.conversationId),ke=A.useRef(N),Ce=A.useRef(null);ke.current!==N?(ke.current=N,ot.current=t.conversationId,Ce.current=null):ot.current=t.conversationId??ot.current;const ue=A.useCallback(()=>{Ce.current=null,j(N,null),S(N,!1),C(N,null)},[S,j,C,N]);A.useEffect(()=>{t.conversationId&&x(N,t.conversationId)},[x,N,t.conversationId]);const mt=A.useCallback(async()=>{const Pt=b(N,ot.current);u(N);const mn=Pt.conversationId;if(!mn){if(!h(N,Pt.epoch))throw new lie;return ue(),y(N,Pt.epoch),null}try{await m(N,mn,async()=>{await Zn.destroySideChat(mn)})}catch(Vn){throw h(N,Pt.epoch)?(ue(),Vn instanceof $o&&(Vn.status===404||Vn.status===409)?(f(N,mn),y(N,Pt.epoch),Vn):(w(N,Pt.epoch),Vn)):new lie}if(!h(N,Pt.epoch))throw new lie;return f(N,mn),ue(),y(N,Pt.epoch),mn},[u,f,ue,m,h,y,b,w,N]);A.useEffect(()=>(r(N,mt),()=>r(N,null)),[mt,r,N]),A.useEffect(()=>{if(!n&&!(M!==null))return;F(new Date);const mn=window.setInterval(()=>F(new Date),1e3);return()=>window.clearInterval(mn)},[n,M!==null]);const ut=Ve({queryKey:U.chats.detail(e,t.sourceConversationId),queryFn:()=>Zn.get(t.sourceConversationId)}),ge=Ve({queryKey:U.chats.messages(e,t.sourceConversationId),queryFn:()=>Zn.listMessages(e,t.sourceConversationId),enabled:!t.sourceMessageId||!t.sourcePreview}),Le=ge.data??[],rt=A.useMemo(()=>t.sourceMessageId?Le.find(Pt=>Pt.id===t.sourceMessageId)??null:rpt(Le),[Le,t.sourceMessageId]),At=t.sourceMessageId??(rt==null?void 0:rt.id)??null,Ue=t.sourcePreview??(rt==null?void 0:rt.body)??null,Se=Ve({queryKey:U.chats.detail(e,t.conversationId??"__side-chat-draft__"),queryFn:()=>Zn.get(t.conversationId),enabled:!!t.conversationId}),We=Ve({queryKey:U.chats.messages(e,t.conversationId??"__side-chat-draft__"),queryFn:()=>Zn.listMessages(e,t.conversationId,{includeTranscript:!0}),enabled:!!t.conversationId}),Te=Ve({queryKey:U.agents.list(e),queryFn:()=>$n.list(e)}),He=Ve({queryKey:U.organizations.detail(e),queryFn:()=>Hn.get(e)}),fe=Ve({queryKey:U.organizationSkills.list(e),queryFn:()=>qf.list(e)}),je=Se.data??null,ye=je??ut.data??null,tt=A.useMemo(()=>jL(Te.data),[Te.data]);A.useEffect(()=>{if(je||be.current||!ut.data)return;const Pt=ut.data.preferredAgentId,mn=tt.find(Vn=>Vn.id===Pt)??tt[0]??null;Y((mn==null?void 0:mn.id)??null),be.current=!0},[je,tt,ut.data]);const me=(je==null?void 0:je.preferredAgentId)??W??((Ls=ut.data)==null?void 0:Ls.preferredAgentId)??null,ze=me?tt.find(Pt=>Pt.id===me)??null:null,De=Ve({queryKey:U.agents.skills(me??"__none__"),queryFn:()=>$n.skills(me,e),enabled:!!me}),kt=A.useMemo(()=>{var Pt;return tpt({agent:ze,orgUrlKey:((Pt=He.data)==null?void 0:Pt.urlKey)??"organization",organizationSkills:fe.data,skillSnapshot:De.data})},[De.data,(Vt=He.data)==null?void 0:Vt.urlKey,fe.data,ze]),gt=A.useMemo(()=>npt(kt,ne),[kt,ne]),{activeRuntimeOverrides:Ke,adapterModelsQuery:Je,runtimeModelSelectRef:wt,runtimeSelectorRef:Z,setDraftRuntimeOverrides:Me}=Hht({selectedOrganizationId:e,selectedConversation:je,activeAgentId:me,activeAgent:ze,composerScopeKey:t.clientMutationId}),lt=OQn(We.data??[]),Re=(M!=null&&M.generationId?lt.find(Pt=>Pt.role==="assistant"&&Pt.generationId===M.generationId&&Pt.status!=="streaming")??null:null)?null:M,Nt=Re!=null&&Re.generationId?lt.filter(Pt=>Pt.role!=="assistant"||Pt.generationId!==Re.generationId):lt,Wt=!!(Re&&(!Re.userMessageId||!lt.some(Pt=>Pt.id===Re.userMessageId))),Jt=spt(je,B),Ze=Jt?"Expired · read-only":SQn(je==null?void 0:je.sideChatExpiresAt,B),Mt=Pt=>{o.setQueryData(U.chats.detail(e,Pt.id),Pt)},Ae=Pt=>{ze&&Me(Pt)},ht=Pt=>{je||Pt===me||tt.some(mn=>mn.id===Pt)&&(Me({modelOverride:null,effortOverride:null}),Y(Pt),se(!1),le(""))},Lt=A.useCallback(async Pt=>{const mn=Array.from(Pt).filter(Vn=>Vn.size>0);if(mn.length!==0)try{const Vn=await Promise.all(mn.map((lr,bs)=>bmt(lr,bs)));re(lr=>[...lr,...Vn]),$(null)}catch(Vn){$(Vn instanceof Error?Vn.message:"Could not stage this attachment.")}},[]),Mn=kut(Lt),{active:Ln,targetProps:Un}=f2e(Lt),mr=Pt=>{!Pt.skillRefLabel||!Pt.skillMarkdownTarget||(z(mn=>Age(mn,[`[${Pt.skillRefLabel}](${Pt.skillMarkdownTarget})`])),se(!1),le(""))},bt=(Pt,mn)=>{o.setQueryData(U.chats.messages(e,Pt),(Vn=[])=>qk(Vn,[mn]))},rn=async()=>{var nt;const Pt=_.trim();if(ie.length===0&&!bM(Pt,de)||E||h(N)||Jt||!At)return;const mn=[...ie],Vn=Gq(de,{fileIndexOffset:mn.length});if(fH({annotations:Vn.inlineAnnotations,devServer:(nt=o.getQueryData(U.health))==null?void 0:nt.devServer,draftPersistence:"memory",pushToast:l}))return;const lr=new Date,bs=Ce.current,Qs=(M==null?void 0:M.state)==="failed"?M:null,Pa=I(N,t.conversationId);if(!Pa)return;Ce.current=null;const Zi=Pa.epoch,na=`${N}:${lr.getTime()}:${Math.random().toString(36).slice(2)}`;let Xi=!1,Gi=!1,ra=bs,pt=!1;S(N,!0),$(null),z(""),C(N,{chatId:Pa.conversationId,streamKey:na,userBody:Pt,userFiles:mn,userCreatedAt:lr,userMessageId:bs,chatTurnId:(Qs==null?void 0:Qs.chatTurnId)??null,turnVariant:(Qs==null?void 0:Qs.turnVariant)??0,editedFromCreatedAt:(Qs==null?void 0:Qs.userCreatedAt)??null,body:"",generationId:null,attemptEpoch:null,lastCommittedRenderSeq:0,renderedBodyHash:vp,state:"streaming",createdAt:lr,transcript:[],replyingAgentId:me});let en=Pa.conversationId;const Kt=async Ot=>{await m(N,Ot,async()=>{await Zn.destroySideChat(Ot)}),f(N,Ot)};try{if(!en){const $t=await Zn.createSideChat(t.sourceConversationId,{sourceMessageId:At,clientMutationId:t.clientMutationId,preferredAgentId:me??void 0});if(!k(N,Zi,$t.id)||!p(N,Zi)){await Kt($t.id);return}en=$t.id,ot.current=$t.id,Mt($t),o.setQueryData(U.chats.messages(e,$t.id),[]),s(fs(t),{...t,sourceMessageId:At,sourcePreview:Ue,conversationId:$t.id})}if(!en||!p(N,Zi)){en&&await Kt(en);return}const Ot=new AbortController;if(j(N,Ot),await Zn.sendMessageStream(en,Pt,{signal:Ot.signal,editUserMessageId:bs,modelOverride:Ke.modelOverride,effortOverride:Ke.effortOverride,files:[...mn,...Vn.files],inlineAnnotations:Vn.inlineAnnotations,onEvent:async $t=>{if(p(N,Zi)){if($t.type==="ack"&&(Xi=!0,Me({modelOverride:null,effortOverride:null}),Gi=!0,ra=$t.userMessage.id,Ce.current=null,bt(en,$t.userMessage),C(N,Ut=>(Ut==null?void 0:Ut.streamKey)===na?{...Ut,chatId:en,generationId:$t.generationId??Ut.generationId,userBody:$t.userMessage.body,userCreatedAt:new Date($t.userMessage.createdAt),userMessageId:$t.userMessage.id,chatTurnId:$t.userMessage.chatTurnId??Ut.chatTurnId,turnVariant:$t.userMessage.turnVariant??Ut.turnVariant,attemptEpoch:$t.attemptEpoch??Ut.attemptEpoch??null,lastCommittedRenderSeq:$t.generationSeq??Ut.lastCommittedRenderSeq??0,renderedBodyHash:$t.bodyHash??Ut.renderedBodyHash??vp}:Ut),Be({type:"clear"}),re([]),Ee(!1),_e(null),s(fs({...t,conversationId:en}),{...t,sourceMessageId:At,sourcePreview:Ue,conversationId:en,inlineAnnotations:[]})),($t.type==="assistant_delta"||$t.type==="assistant_state"||$t.type==="transcript_entry")&&C(N,Ut=>LW(Ut,na,$t)),$t.type==="final"){pt=!0,Ce.current=null;for(const Ut of $t.messages)bt(en,Ut);C(N,Ut=>(Ut==null?void 0:Ut.streamKey)===na?null:Ut)}if($t.type==="error")throw!Xi&&$t.messageId&&(Xi=!0,ra=$t.messageId,Be({type:"clear"}),re([]),Ee(!1),_e(null),s(fs({...t,conversationId:en}),{...t,sourceMessageId:At,sourcePreview:Ue,conversationId:en,inlineAnnotations:[]})),new Error($t.error)}}}),!pt)throw new Error("Side Chat stream ended before a final response.");await Promise.all([o.invalidateQueries({queryKey:U.chats.detail(e,en)}),o.invalidateQueries({queryKey:U.chats.messages(e,en)})])}catch(Ot){if(!p(N,Zi))return;Xi?Gi&&en?(Ce.current=ra,z($t=>$t||Pt)):Ce.current=ra:(Ce.current=bs,z($t=>$t||Pt)),Xi&&en&&await Promise.all([o.invalidateQueries({queryKey:U.chats.detail(e,en)}),o.invalidateQueries({queryKey:U.chats.messages(e,en)})]).catch(()=>{}),C(N,$t=>($t==null?void 0:$t.streamKey)===na?{...$t,state:"failed"}:$t),$(uH(Ot,"side-chat"))}finally{p(N,Zi)&&(j(N,null),S(N,!1),y(N,Zi))}},sn=!((!t.sourceMessageId||!t.sourcePreview)&&ge.isPending)&&!At,St=Te.data,qt=Zht({agent:ze,runtime:(je==null?void 0:je.chatRuntime)??null,overrides:Ke,adapterModels:Je.data}),En=ze?of(ze):Te.isPending?"Loading agents":"No agent",Fn=G||ee,tn=A.useCallback(()=>{V(!1),se(!1),le("")},[]);A.useEffect(()=>{n||(tn(),R(null))},[n,tn]);const Is=A.useCallback(Pt=>{const mn=Pt==="agent"?Z.current??ce.current:ce.current;mn&&R(Uk(mn)),V(Pt==="agent"),se(Pt==="skill"),Pt!=="skill"&&le("")},[Z]);return A.useEffect(()=>{if(!Fn){R(null);return}const Pt=()=>{const mn=G?Z.current??ce.current:ce.current;mn&&R(Uk(mn))};return Pt(),window.addEventListener("resize",Pt),window.addEventListener("scroll",Pt,!0),()=>{window.removeEventListener("resize",Pt),window.removeEventListener("scroll",Pt,!0)}},[G,Fn,Z]),A.useEffect(()=>{if(!Fn)return;const Pt=Vn=>{var bs,Qs;const lr=Vn.target;lr instanceof Node&&(lr instanceof Element&&lr.closest("[data-chat-runtime-submenu]")||(bs=Oe.current)!=null&&bs.contains(lr)||(Qs=Z.current)!=null&&Qs.contains(lr)||tn())},mn=Vn=>{if(Vn.key!=="Escape")return;const lr=G,bs=ee;tn(),lr?requestAnimationFrame(()=>{var Qs;return(Qs=Z.current)==null?void 0:Qs.focus()}):bs&&requestAnimationFrame(()=>{var Qs;return(Qs=J.current)==null?void 0:Qs.focus()})};return document.addEventListener("pointerdown",Pt,!0),document.addEventListener("keydown",mn),()=>{document.removeEventListener("pointerdown",Pt,!0),document.removeEventListener("keydown",mn)}},[G,tn,Fn,Z,ee]),A.useEffect(()=>{G&&requestAnimationFrame(()=>{var Pt,mn;(mn=(Pt=Oe.current)==null?void 0:Pt.querySelector("[data-chat-composer-menu-item]"))==null||mn.focus()})},[G]),A.useEffect(()=>{ee&&requestAnimationFrame(()=>{var Pt;return(Pt=Ye.current)==null?void 0:Pt.focus()})},[ee]),i.jsxs("div",{className:"flex h-full min-h-0 flex-col","data-testid":"side-chat-panel-view",children:[i.jsx("div",{className:"scrollbar-auto-hide min-h-0 flex-1 overflow-y-auto px-4 py-4",children:i.jsxs("div",{className:"mx-auto flex w-full max-w-4xl flex-col gap-5",children:[Ze?i.jsx("div",{className:"flex justify-end",children:i.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground","data-testid":"side-chat-state",children:[i.jsx(y1,{className:"h-3 w-3"}),Ze]})}):null,sn?i.jsx("p",{className:"text-sm text-destructive",children:"The main chat needs a completed assistant response first."}):null,i.jsxs("div",{className:"flex min-h-[12rem] flex-col gap-5","data-testid":"side-chat-messages",children:[ye?Nt.map(Pt=>{const mn=jQn(Pt);return i.jsxs("div",{children:[Pt.role==="assistant"&&mn.length>0?i.jsx(J6,{entries:mn,state:Pt.status,generationTerminalReason:Pt.generationTerminalReason,streamStartedAt:new Date(Pt.createdAt),streamEndedAt:new Date(Pt.updatedAt),assistantMessageBody:Pt.body,showDeveloperDiagnostics:!1}):null,i.jsx(Qk,{conversation:ye,message:Pt,agents:St,decisionNote:"",onDecisionNoteChange:Fv,decisionNoteMentions:[],onDecisionNoteMentionQueryChange:Fv,onDecisionNoteInlineTokenClick:Fv,onApprovalAction:Fv,onIssueProposalChange:Fv,onResolveOperationProposal:Fv,onConvertToIssue:Fv,actionPending:!1,onCopyMessageText:Vn=>{var lr;return(lr=navigator.clipboard)==null?void 0:lr.writeText(Vn)},onOpenFile:Fv,onSelectResponseAnnotation:a,skillReferences:cie})]},Pt.id)}):null,Re&&ye?i.jsxs("div",{className:"flex flex-col gap-5","data-testid":"side-chat-streaming-reply",children:[Wt?i.jsx(WG,{body:Re.userBody,files:Re.userFiles,createdAt:Re.userCreatedAt,onCopyMessageText:Pt=>{var mn;return(mn=navigator.clipboard)==null?void 0:mn.writeText(Pt)},onEditDraftOnly:z,skillReferences:cie}):null,i.jsx(J6,{entries:Re.transcript,state:Re.state,streamStartedAt:Re.createdAt,assistantMessageBody:Re.body,showDeveloperDiagnostics:!1}),i.jsx(R2e,{body:Re.body,createdAt:Re.createdAt,state:Re.state,replyingAgentId:Re.replyingAgentId,conversation:ye,agents:St,onCopyMessageText:Pt=>{var mn;return(mn=navigator.clipboard)==null?void 0:mn.writeText(Pt)},skillReferences:cie})]}):null]})]})}),T?i.jsx("div",{role:"alert",className:"px-4 pb-2 text-sm text-destructive",children:T}):null,Jt?i.jsx("div",{className:"shrink-0 border-t border-[color:var(--border-soft)] px-4 py-3 text-sm text-muted-foreground","data-testid":"side-chat-read-only",children:"This Side Chat has expired and can no longer be edited. Close the tab to destroy it."}):i.jsxs("div",{className:"shrink-0 px-4 pb-4","data-testid":"side-chat-composer",children:[i.jsxs(mY,{ref:ce,fileDragActive:Ln,fileDropTargetProps:Un,className:"mx-auto max-w-4xl",testId:"side-chat-composer-file-drop-target",children:[Ln?i.jsx(m2e,{}):null,de.annotations.length>0?i.jsxs("div",{className:"mb-3 flex flex-col items-start gap-2",children:[i.jsx(Q2e,{annotations:de.annotations,pendingFilesByAnnotationId:de.pendingFilesByAnnotationId,open:ae,buttonRef:$e,onOpenChange:Pt=>{Ee(Pt),Pt&&_e(null)},onClear:()=>{Be({type:"clear"}),Ee(!1),_e(null)},onEdit:Pt=>{Ie.current=$e.current,_e(Pt.id)},onDelete:Pt=>{Be({type:"delete",id:Pt}),de.annotations.length===1&&Ee(!1),_e(mn=>mn===Pt?null:mn)}}),he?(()=>{const Pt=de.annotations.find(lr=>lr.id===he);if(!Pt)return null;const mn=Ie.current,Vn=(mn==null?void 0:mn.closest('[data-testid="side-chat-panel-view"]'))??null;return i.jsx(ZG,{annotation:Pt,ordinal:Pt.ordinal,pendingFiles:de.pendingFilesByAnnotationId[Pt.id]??[],showSelectedTextContext:!0,anchorRect:(mn==null?void 0:mn.getBoundingClientRect())??null,getAnchorRect:()=>mn!=null&&mn.isConnected?mn.getBoundingClientRect():null,boundaryRect:(Vn==null?void 0:Vn.getBoundingClientRect())??null,getBoundaryRect:()=>Vn!=null&&Vn.isConnected?Vn.getBoundingClientRect():null,returnFocusRef:Ie,validateSave:lr=>i1e(de,Pt.id,{comment:lr.comment,attachmentIds:lr.attachmentIds,files:lr.pendingFiles}),onSave:({comment:lr,pendingFiles:bs,attachmentIds:Qs})=>{Be({type:"replaceDraft",id:Pt.id,comment:lr,attachmentIds:Qs,files:bs}),_e(null)},onCancel:()=>_e(null),onDelete:()=>{Be({type:"delete",id:Pt.id}),_e(null)}})})():null]}):null,ie.length>0?i.jsx("div",{"data-testid":"side-chat-pending-attachments",className:"mb-2.5 flex flex-wrap gap-2 px-3",children:ie.map(Pt=>{const mn=e8(Pt);return i.jsx("div",{"data-testid":"side-chat-pending-attachment",className:"max-w-full",children:i.jsx(i5,{file:Pt,onRemove:()=>re(Vn=>Vn.filter(lr=>e8(lr)!==mn))})},mn)})}):null,i.jsx(AY,{value:_,onChange:z,onPasteCapture:Mn,scrollTestId:"side-chat-composer-editor-scroll",placeholder:"Ask a focused follow-up…",onSubmit:()=>void rn()}),i.jsxs(hY,{testId:"side-chat-composer-toolbar",actions:i.jsx(pY,{mode:E?"sending":"send",ariaLabel:E?"Sending Side Chat message":"Send Side Chat message",disabled:ie.length===0&&!bM(_,de)||E||!me||sn,onClick:()=>void rn()}),children:[i.jsx(Cht,{open:D,onOpenChange:X,onAddFiles:()=>{var Pt;return(Pt=qe.current)==null?void 0:Pt.click()}}),i.jsx(jve,{buttonRef:Z,agent:ze,label:En,expanded:G,disabled:Te.isPending,onClick:()=>{if(G){tn();return}Is("agent")}}),i.jsx(Nht,{open:ee,buttonRef:J,onClick:()=>{if(ee){tn();return}Is("skill")}})]})]}),Fn&&L&&typeof document<"u"?ja.createPortal(i.jsxs(yve,{menuRef:Oe,testId:G?"side-chat-agent-menu":"side-chat-skill-menu",ariaLabel:G?"Side Chat agent":"Side Chat skills",position:L,onKeyDown:G?Ove:void 0,children:[G?i.jsx(Sve,{agents:tt,activeAgentId:me??"",agentSelectionLocked:!!je,runtimeSelectionPending:!1,newConversationSendInFlight:E&&!je,externalBound:!1,adapterModels:Je.data,overrides:Ke,runtimeLabel:qt,isLoading:Je.isPending,error:Je.error,runtimePanelPlacement:"above",modelSelectRef:wt,onSelectAgent:ht,onChangeRuntime:Ae}):null,ee?i.jsx(Iht,{pending:De.isPending||fe.isPending,skills:kt,filteredSkills:gt,searchQuery:ne,searchInputRef:Ye,onSearchQueryChange:le,onSelect:mr}):null]}),document.body):null,i.jsx("input",{ref:qe,type:"file",multiple:!0,className:"hidden",onChange:Pt=>{Lt(Pt.currentTarget.files??[]),Pt.currentTarget.value=""}})]})]})}function Ive(e){return e.trim().replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[\s-]+/g,"_").toLowerCase()}function NQn(e){const t=Ive(e);return t==="failed"||t==="error"?"border-destructive/30 bg-destructive/10 text-destructive":t==="running"||t==="in_progress"?"border-cyan-500/25 bg-cyan-500/10 text-cyan-700 dark:text-cyan-300":"border-border/60 bg-[color:var(--surface-active)] text-muted-foreground"}function IQn(e){const t=Ive(e).replace(/_/g," ");return t?t.charAt(0).toUpperCase()+t.slice(1):"Unknown"}function PQn({entries:e,response:t,running:n,loading:r,error:s,onRetry:a}){return e.length>0?i.jsxs(i.Fragment,{children:[i.jsx(M1,{entries:e,mode:"nice",density:"compact",streaming:n,collapseStdout:!0,presentation:"chat",hiddenAssistantMessageText:t}),s?i.jsx("p",{role:"alert",className:"mt-2 text-xs text-destructive",children:"Could not refresh the transcript. Showing the last loaded content."}):null]}):r?i.jsxs("div",{className:"inline-flex items-center gap-2 py-2 text-sm text-muted-foreground",role:"status",children:[i.jsx(fn,{className:"size-4 animate-spin","aria-hidden":!0}),"Loading transcript..."]}):s?i.jsxs("div",{role:"alert",className:"rounded-[var(--radius-sm)] border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:[i.jsx("p",{children:"Could not load the sub-agent transcript."}),i.jsx(oe,{type:"button",variant:"ghost",size:"xs",className:"mt-1 h-7 px-0 text-destructive hover:bg-transparent hover:text-destructive",onClick:a,children:"Retry"})]}):i.jsx("p",{className:"py-2 text-sm leading-6 text-muted-foreground",children:"No transcript entries were captured for this sub-agent."})}function TQn({target:e}){var h,p,x;const t=Ve({queryKey:["chat-subagent-live-manifest",e.conversationId,e.threadId],queryFn:()=>Zn.getWorkManifest(e.conversationId),enabled:!!e.conversationId,refetchInterval:b=>{var k;const y=(k=b.state.data)==null?void 0:k.subagents,w=[...(y==null?void 0:y.active)??[],...(y==null?void 0:y.done)??[]].find(S=>S.threadId===e.threadId);return(w==null?void 0:w.state)==="active"?2e3:!1}}),n=[...((h=t.data)==null?void 0:h.subagents.active)??[],...((p=t.data)==null?void 0:p.subagents.done)??[]].find(b=>b.threadId===e.threadId),r=(n==null?void 0:n.sourceMessageId)??e.sourceMessageId,s=(n==null?void 0:n.runId)??e.runId??null,a=Ve({queryKey:["chat-subagent-live-transcript",e.conversationId,r,e.threadId,n==null?void 0:n.status,n==null?void 0:n.updatedAt],queryFn:()=>Zn.getMessageTranscript(e.conversationId,r),enabled:!!(e.conversationId&&r),refetchInterval:(n==null?void 0:n.state)==="active"?2e3:!1}),o=Ve({queryKey:s?U.runDetail(s):["agent-run","none"],queryFn:()=>xo.get(s),enabled:!!s}),l=a.data?zUe(a.data.transcript,{sourceMessageId:a.data.messageId,runId:(n==null?void 0:n.runId)??null,sourceActive:(n==null?void 0:n.state)==="active",senderLabel:n==null?void 0:n.senderLabel}).find(b=>b.threadId===e.threadId):null,c={...e,senderLabel:(n==null?void 0:n.senderLabel)??e.senderLabel,status:(n==null?void 0:n.status)??(l==null?void 0:l.status)??e.status,response:(l==null?void 0:l.response)??e.response,entries:(l==null?void 0:l.entries)??e.entries,sourceMessageId:(n==null?void 0:n.sourceMessageId)??e.sourceMessageId},d=c.response??((x=[...c.entries].reverse().find(b=>b.kind==="assistant"))==null?void 0:x.text)??null,u=(n==null?void 0:n.state)==="active"||["running","in_progress","pending","queued","started"].includes(Ive(c.status)),f=!!(e.conversationId&&r)&&a.isPending&&c.entries.length===0,m=o.data?`/agents/${o.data.agentId}/runs/${o.data.id}`:null;return i.jsxs("div",{className:"scrollbar-auto-hide h-full min-h-0 overflow-y-auto","data-testid":"chat-side-panel-subagent-view","data-subagent-thread-id":c.threadId,children:[i.jsxs("div",{className:"border-b border-border/45 px-4 py-3",children:[i.jsxs("div",{className:"flex items-center gap-2.5",children:[i.jsx("img",{src:CE(c.avatarSeed),alt:"",className:"h-8 w-8 shrink-0 rounded-full object-cover ring-1 ring-border/60"}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("div",{className:"truncate text-sm font-semibold text-foreground",children:c.label}),i.jsx("div",{className:"truncate text-xs text-muted-foreground",title:c.threadId,children:c.threadId})]}),i.jsx("span",{className:q("rounded-[var(--radius-sm)] border px-2 py-0.5 text-[11px]",NQn(c.status)),children:IQn(c.status)})]}),c.model||c.reasoningEffort?i.jsxs("div",{className:"mt-2 flex flex-wrap gap-x-3 gap-y-1 pl-[2.625rem] text-[11px] text-muted-foreground",children:[c.model?i.jsx("span",{children:c.model}):null,c.reasoningEffort?i.jsxs("span",{children:[c.reasoningEffort," reasoning"]}):null,i.jsx("span",{children:"Read only"})]}):i.jsx("div",{className:"mt-2 pl-[2.625rem] text-[11px] text-muted-foreground",children:"Read only"})]}),i.jsxs("div",{className:"space-y-5 px-4 py-4",children:[i.jsxs("section",{"aria-label":"Main agent message",children:[i.jsx("div",{className:"mb-1.5 text-right text-xs font-medium text-muted-foreground",children:c.senderLabel}),i.jsx("div",{className:"ml-auto w-fit max-w-[88%] rounded-[var(--radius-xl)] bg-[color:var(--surface-active)] px-3.5 py-2.5 text-sm leading-6 text-foreground shadow-[var(--shadow-sm)]",children:i.jsx(Ya,{copyMarkdownOnCopy:!0,children:c.prompt})})]}),i.jsxs("section",{"aria-label":"Sub-agent transcript",children:[i.jsxs("div",{className:"mb-2 flex min-h-7 items-center gap-2 text-[11px] text-muted-foreground",children:[i.jsx("span",{className:"h-px min-w-4 flex-1 bg-border/45","aria-hidden":!0}),i.jsx("span",{children:u?"Working":"Transcript"}),i.jsx("span",{className:"h-px min-w-4 flex-1 bg-border/45","aria-hidden":!0}),m?i.jsx(oe,{asChild:!0,variant:"ghost",size:"xs",className:"h-7 shrink-0 gap-1.5 px-2 text-xs",children:i.jsxs(gn,{to:m,children:[i.jsx(skt,{className:"size-3.5","aria-hidden":!0}),"View run"]})}):s&&o.isPending?i.jsxs("span",{className:"inline-flex h-7 shrink-0 items-center gap-1.5 px-2",role:"status",children:[i.jsx(fn,{className:"size-3.5 animate-spin","aria-hidden":!0}),"Loading run"]}):null]}),i.jsx(PQn,{entries:c.entries,response:d,running:u,loading:f,error:a.isError,onRetry:()=>void a.refetch()}),s&&o.isError?i.jsxs("div",{role:"alert",className:"mt-2 flex flex-wrap items-center gap-2 text-xs text-destructive",children:[i.jsx("span",{children:"Could not load the linked Agent Run."}),i.jsx(oe,{type:"button",variant:"ghost",size:"xs",className:"h-7 px-1.5 text-destructive hover:text-destructive",onClick:()=>void o.refetch(),children:"Retry"})]}):null]}),i.jsxs("section",{"aria-label":"Sub-agent response",children:[i.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[i.jsx("img",{src:CE(c.avatarSeed),alt:"",className:"h-6 w-6 shrink-0 rounded-full object-cover ring-1 ring-border/60"}),i.jsx("span",{className:"text-xs font-semibold text-foreground",children:c.label})]}),d?i.jsx("div",{className:"max-w-[72ch] text-sm leading-6 text-foreground",children:i.jsx(Ya,{copyMarkdownOnCopy:!0,enableCodeBlockCopy:!0,children:d})}):i.jsx("p",{className:"text-sm leading-6 text-muted-foreground",children:u?"The sub-agent is still working.":"No response was captured for this sub-agent."})]})]})]})}function _Qn(e){const t=Date.parse(e);if(!Number.isFinite(t))return"";const n=Math.max(0,Math.round((Date.now()-t)/1e3));if(n<60)return"now";const r=Math.round(n/60);if(r<60)return`${r}m ago`;const s=Math.round(r/60);return s<24?`${s}h ago`:`${Math.round(s/24)}d ago`}function MQn(e){return e==="failed"?"Failed":e==="interrupted"?"Interrupted":e==="cancelled"?"Cancelled":e==="stopped"?"Stopped":null}function EQn({item:e,loading:t,onOpen:n}){const r=MQn(e.status);return i.jsxs("button",{type:"button",className:"group flex min-h-12 w-full min-w-0 items-center gap-3 rounded-[var(--radius-sm)] px-1.5 py-2 text-left transition-colors hover:bg-[color:var(--surface-active)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/30",onClick:n,title:e.label,"data-testid":`chat-side-panel-subagent-row-${e.threadId}`,children:[i.jsxs("span",{className:"relative inline-flex size-8 shrink-0",children:[i.jsx("img",{src:CE(e.avatarSeed),alt:"",className:q("size-8 rounded-full object-cover ring-1 ring-border/60",e.status==="failed"||e.status==="interrupted"?"ring-destructive/50":e.state==="active"?"ring-cyan-500/45":"ring-border/60")}),e.state==="active"?i.jsx("span",{className:"absolute -bottom-px -right-px size-2 rounded-full bg-cyan-500 ring-2 ring-background","aria-label":"Active"}):null]}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"block truncate text-sm font-medium text-foreground",children:e.label}),r?i.jsx("span",{className:"block truncate text-[11px] leading-4 text-destructive",children:r}):null]}),t?i.jsx(fn,{className:"size-3.5 shrink-0 animate-spin text-muted-foreground","aria-label":"Loading subagent"}):i.jsx("time",{dateTime:e.updatedAt,title:new Date(e.updatedAt).toLocaleString(),className:"shrink-0 text-xs tabular-nums text-muted-foreground",children:_Qn(e.updatedAt)})]})}function eMe({label:e,items:t,empty:n,loadingThreadId:r,loadError:s,onOpen:a}){return i.jsxs("section",{"aria-label":e,children:[i.jsxs("div",{className:"mb-2 text-xs font-medium text-muted-foreground",children:[e," · ",t.length]}),t.length===0?i.jsx("p",{className:"py-2 text-sm text-muted-foreground",children:n}):i.jsx("div",{className:"space-y-0.5",role:"list",children:t.map(o=>i.jsxs("div",{role:"listitem",children:[i.jsx(EQn,{item:o,loading:r===o.threadId,onOpen:()=>a(o)}),(s==null?void 0:s.threadId)===o.threadId?i.jsxs("div",{role:"alert",className:"ml-11 rounded-[var(--radius-sm)] border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:[i.jsx("p",{children:"Could not load sub-agent details."}),i.jsx("p",{className:"mt-0.5 text-[11px] opacity-80",children:s.message}),i.jsx(oe,{type:"button",variant:"ghost",size:"xs",className:"mt-1 h-7 px-0 text-destructive hover:bg-transparent hover:text-destructive",onClick:()=>a(o),children:"Retry"})]}):null]},o.threadId))})]})}function DQn({organizationId:e,target:t}){var f;const n=Qm(),{pushToast:r}=ws(),[s,a]=A.useState(null),[o,l]=A.useState(null),c=Ve({queryKey:U.chats.workManifest(e,t.conversationId),queryFn:()=>Zn.getWorkManifest(t.conversationId),refetchInterval:m=>{var h;return(((h=m.state.data)==null?void 0:h.subagents.active.length)??0)>0?2e3:!1}}),d=((f=c.data)==null?void 0:f.subagents)??{active:[],done:[]},u=async m=>{if(!s){a(m.threadId),l(null);try{const h=await Zn.getMessageTranscript(t.conversationId,m.sourceMessageId),p=zUe(h.transcript,{sourceMessageId:m.sourceMessageId,runId:m.runId,sourceActive:m.state==="active"}).find(x=>x.threadId===m.threadId);if(!p)throw new Error("The latest subagent evidence is not available.");n.openTarget({kind:"subagent",callId:p.callId,threadId:p.threadId,avatarSeed:p.avatarSeed,label:m.label,senderLabel:m.senderLabel??"Main agent",prompt:p.prompt,model:p.model,reasoningEffort:p.reasoningEffort,status:m.status,response:p.response,entries:p.entries,conversationId:t.conversationId,sourceMessageId:m.sourceMessageId,runId:m.runId})}catch(h){const p=h instanceof Error?h.message:"Try again.";l({threadId:m.threadId,message:p}),r({title:"Failed to load subagent",body:p,tone:"error"})}finally{a(null)}}};return c.isPending?i.jsx("div",{className:"grid h-full place-items-center","data-testid":"chat-side-panel-subagents-view",children:i.jsx(fn,{className:"size-5 animate-spin text-muted-foreground","aria-label":"Loading subagents"})}):c.isError?i.jsx("div",{className:"p-4","data-testid":"chat-side-panel-subagents-view",children:i.jsx("div",{role:"alert",className:"rounded-[var(--radius-md)] border border-destructive/30 bg-destructive/10 px-3 py-3 text-sm text-destructive",children:c.error instanceof Error?c.error.message:"Could not load subagents."})}):i.jsx("div",{className:"scrollbar-auto-hide h-full min-h-0 overflow-y-auto px-4 py-4","data-testid":"chat-side-panel-subagents-view",children:i.jsxs("div",{className:"space-y-8",children:[i.jsx(eMe,{label:"Active",items:d.active,empty:"No active subagents",loadingThreadId:s,loadError:o,onOpen:m=>void u(m)}),i.jsx(eMe,{label:"Done",items:d.done,empty:"No completed subagents",loadingThreadId:s,loadError:o,onOpen:m=>void u(m)})]})})}function tMe(e){return e instanceof Error&&e.message.replace(/^Error invoking remote method '[^']+':\s*/u,"").replace(/^Error:\s*/u,"").trim()||"Terminal failed to start."}function RQn({active:e,target:t}){const n=A.useRef(null),r=A.useRef(null),s=A.useRef(null),a=A.useRef(0),o=A.useRef(!1),l=A.useRef(e),[c,d]=A.useState("starting"),[u,f]=A.useState(null),[m,h]=A.useState(0),p=A.useCallback(async()=>{var S;const x=(S=_n())==null?void 0:S.terminal,b=r.current,y=s.current;if(!(x!=null&&x.supported)){d("failed"),f("Terminal is available only in Rudder Desktop.");return}if(!b||!y)return;if(!t.agentId){d("failed"),f("Select an Agent for this Chat before starting a terminal.");return}if(!l.current||o.current)return;const w=y.proposeDimensions();if(!w||w.cols<=2||w.rows<=1)return;y.fit(),o.current=!0;const k=++a.current;d("starting"),f(null),b.reset();try{const j=await x.create({orgId:t.organizationId,agentId:t.agentId,sessionId:t.sessionId,cols:Math.max(2,b.cols),rows:Math.max(1,b.rows)});if(k!==a.current)return;j.replay&&b.write(j.replay),d(j.status==="running"?"running":"exited"),l.current&&b.focus()}catch(j){if(k!==a.current)return;d("failed"),f(tMe(j))}},[t.agentId,t.organizationId,t.sessionId]);return A.useEffect(()=>{var z;const x=n.current,b=(z=_n())==null?void 0:z.terminal;if(!x||!(b!=null&&b.supported)){d("failed"),f("Terminal is available only in Rudder Desktop.");return}d("starting"),f(null);let y=!1,w=null,k=null,S,j,C,I,N,M;const E=()=>{a.current+=1,M!==void 0&&cancelAnimationFrame(M),N==null||N.disconnect(),S==null||S.dispose(),j==null||j.dispose(),C==null||C(),I==null||I(),k==null||k.dispose(),w==null||w.dispose(),o.current=!1,r.current=null,s.current=null,M=void 0,N=void 0,S=void 0,j=void 0,C=void 0,I=void 0,k=null,w=null};return(async()=>{const[{Terminal:T},{FitAddon:$}]=await Promise.all([on(()=>import("./xterm-Jvo0xPzf.js").then(W=>W.x),[]),on(()=>import("./addon-fit-DZOvRzIT.js").then(W=>W.a),[])]);if(y)return;w=new T({cursorBlink:!0,convertEol:!1,fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:13,lineHeight:1.25,scrollback:5e3,theme:{background:"#111315",foreground:"#e7e9ea",cursor:"#f4f4f5",selectionBackground:"#3f4650"}}),k=new $;const B=w,F=k;B.loadAddon(F),B.open(x),r.current=B,s.current=F,S=B.onData(W=>void b.input(t.sessionId,W).catch(()=>{})),j=B.onResize(({cols:W,rows:Y})=>void b.resize(t.sessionId,W,Y).catch(()=>{})),C=b.onOutput(W=>{W.sessionId===t.sessionId&&B.write(W.data)}),I=b.onExit(W=>{W.sessionId===t.sessionId&&(d(W.error?"failed":"exited"),f(W.error))}),N=new ResizeObserver(()=>{F.fit(),l.current&&!o.current&&p()}),N.observe(x),M=requestAnimationFrame(()=>{l.current&&p()})})().catch(T=>{y||(E(),d("failed"),f(tMe(T)))}),()=>{y=!0,E()}},[m,p,t.sessionId]),A.useEffect(()=>{if(l.current=e,!e)return;const x=requestAnimationFrame(()=>{var b,y;(b=s.current)==null||b.fit(),o.current||p(),(y=r.current)==null||y.focus()});return()=>cancelAnimationFrame(x)},[e,p]),i.jsxs("div",{className:"relative h-full min-h-0 bg-[#111315]","data-testid":"terminal-panel-view",children:[i.jsx("div",{className:"h-full min-h-0 min-w-0 p-2",children:i.jsx("div",{ref:n,className:"h-full min-h-0 min-w-0 w-full overflow-hidden","data-testid":"terminal-xterm-host"})}),c!=="running"?i.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-[#111315]/95 px-6",children:i.jsxs("div",{className:"max-w-xs text-center text-zinc-200",children:[i.jsx(Dh,{className:"mx-auto h-7 w-7 text-zinc-500","aria-hidden":!0}),i.jsx("h3",{className:"mt-3 text-sm font-semibold",children:c==="starting"?"Starting terminal":c==="exited"?"Shell exited":"Terminal unavailable"}),u?i.jsx("p",{className:"mt-2 text-xs leading-5 text-zinc-400",children:u}):null,c!=="starting"?i.jsxs(oe,{type:"button",size:"sm",variant:"outline",className:"mt-4 border-zinc-700 bg-zinc-900 text-zinc-100 hover:bg-zinc-800",onClick:()=>{o.current=!1,h(x=>x+1)},children:[i.jsx(A0,{className:"h-3.5 w-3.5"}),"Restart terminal"]}):null]})}):null]})}function GS(e){const t=e.split("/").filter(Boolean),n=[];for(let r=0;r<t.length-1;r+=1)n.push(t.slice(0,r+1).join("/"));return new Set(n)}function ipt(e){const t=e.split("/").filter(Boolean),n=[];for(let r=0;r<t.length;r+=1)n.push(t.slice(0,r+1).join("/"));return new Set(n)}function Jl(e){const t=(e==null?void 0:e.trim())??"";return t.length>0?t:null}const apt="rudder.workspace.launchTargetId",opt="rudder.workspace.unsupportedFileLaunchTargetId",LQn="rudder.workspace.openFileTabs",zQn=["cursor","vscode","windsurf","zed","webstorm","intellij","xcode","terminal","warp","commandPrompt","powershell","finder"],$Qn={fileTarget:!0,id:"defaultApp",label:"Default app",kind:"app"};function Pve(e){return zQn.includes(e)}function FQn(e){return e.kind==="ide"&&e.id!=="xcode"}function iw(e){return"fileTarget"in e}function TE(e){return[$Qn,...e.filter(FQn).map(t=>({fileTarget:!0,id:t.id,label:t.label,kind:"ide",workspaceTarget:t}))]}function lpt(e,t){if(!t.canOpenFile)return[];const n=TE(e);return t.canOpenLocation?[...n,...e.filter(r=>r.kind==="folder"||r.kind==="terminal")]:n}function BQn(e,t){return e.find(n=>n.id===t)??e.find(n=>n.id==="defaultApp")??null}function QQn(){if(typeof window>"u")return null;try{const e=window.localStorage.getItem(opt);return e==="defaultApp"||Pve(e)?e:null}catch{return null}}function UQn(e){if(!(typeof window>"u"))try{window.localStorage.setItem(opt,e)}catch{}}function qQn(){if(typeof window>"u")return null;const e=window.localStorage.getItem(apt);return Pve(e)?e:null}function N_(e){typeof window>"u"||window.localStorage.setItem(apt,e)}function Ame(e){return e&&Pve(e)?e:null}function VQn(e){return e.defaultPrevented||e.altKey||e.shiftKey||!e.metaKey&&!e.ctrlKey?!1:e.key.toLowerCase()==="w"}function pH(e){const t=new Set,n=[];for(const r of e){const s=Jl(r??null);!s||t.has(s)||(t.add(s),n.push(s))}return n.slice(-24)}function cpt(e){return`${LQn}:${e}`}function PO(e,t){const n=pH([...e,t]),r=Jl(t??null);return{openFilePaths:n,selectedFilePath:r&&n.includes(r)?r:n[0]??null}}function hme(e){var t;if(!e||typeof window>"u")return PO([],null);try{const n=(t=window.sessionStorage)==null?void 0:t.getItem(cpt(e)),r=n?JSON.parse(n):null;if(Array.isArray(r))return PO(r,r[0]);if(r&&typeof r=="object"){const s=r;return PO(Array.isArray(s.openFilePaths)?s.openFilePaths:[],typeof s.selectedFilePath=="string"?s.selectedFilePath:null)}}catch{return PO([],null)}return PO([],null)}function WQn(e,t,n){var r;if(!(!e||typeof window>"u"))try{const s=PO(t,n);(r=window.sessionStorage)==null||r.setItem(cpt(e),JSON.stringify(s))}catch{}}function HQn(e,t){return e.includes(t)?e:pH([...e,t])}const KQn="rudder.chat-side-panel.markdown-draft.v1";function Tve(e,t){return`${KQn}:${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function Yk(e,t){if(!(typeof window>"u"))try{window.sessionStorage.removeItem(Tve(e,t))}catch{}}function k3(e,t,n,r){if(!(typeof window>"u")){if(r===n){Yk(e,t);return}try{const s={organizationId:e,filePath:t,baseContent:n,content:r,updatedAt:new Date().toISOString()};window.sessionStorage.setItem(Tve(e,t),JSON.stringify(s))}catch{}}}function dpt(e,t,n){const r={baseContent:n,conflicted:!1,content:n};if(typeof window>"u")return r;try{const s=window.sessionStorage.getItem(Tve(e,t));if(!s)return r;const a=JSON.parse(s);return!(a.organizationId===e&&a.filePath===t&&typeof a.baseContent=="string"&&typeof a.content=="string")||a.content===n?(Yk(e,t),r):{baseContent:a.baseContent,conflicted:a.baseContent!==n,content:a.content}}catch{return Yk(e,t),r}}function _ve(e){const t=e.match(/^(---\r?\n[\s\S]*?\r?\n---)(\r?\n|$)/);return t?{frontmatter:t[1]??"",separator:t[2]??`
1955
1955
  `,body:e.slice(t[0].length)}:{frontmatter:null,separator:"",body:e}}function gH(e,t,n){return e===null?n:`${e}${t||`
1956
1956
  `}${n}`}function ZQn(e){var t;return((t=e.match(/[\p{L}\p{N}]+(?:[-'][\p{L}\p{N}]+)*/gu))==null?void 0:t.length)??0}const XQn=H0({String:Xe.string,Number:Xe.number,"True False":Xe.bool,PropertyName:Xe.propertyName,Null:Xe.null,", :":Xe.separator,"[ ]":Xe.squareBracket,"{ }":Xe.brace}),GQn=P0.deserialize({version:14,states:"$bOVQPOOOOQO'#Cb'#CbOnQPO'#CeOvQPO'#ClOOQO'#Cr'#CrQOQPOOOOQO'#Cg'#CgO}QPO'#CfO!SQPO'#CtOOQO,59P,59PO![QPO,59PO!aQPO'#CuOOQO,59W,59WO!iQPO,59WOVQPO,59QOqQPO'#CmO!nQPO,59`OOQO1G.k1G.kOVQPO'#CnO!vQPO,59aOOQO1G.r1G.rOOQO1G.l1G.lOOQO,59X,59XOOQO-E6k-E6kOOQO,59Y,59YOOQO-E6l-E6l",stateData:"#O~OeOS~OQSORSOSSOTSOWQO_ROgPO~OVXOgUO~O^[O~PVO[^O~O]_OVhX~OVaO~O]bO^iX~O^dO~O]_OVha~O]bO^ia~O",goto:"!kjPPPPPPkPPkqwPPPPk{!RPPP!XP!e!hXSOR^bQWQRf_TVQ_Q`WRg`QcZRicQTOQZRQe^RhbRYQR]R",nodeNames:"⚠ JsonText True False Null Number String } { Object Property PropertyName : , ] [ Array",maxTerm:25,nodeProps:[["isolate",-2,6,11,""],["openedBy",7,"{",14,"["],["closedBy",8,"}",15,"]"]],propSources:[XQn],skippedNodes:[0],repeatNodeCount:2,tokenData:"(|~RaXY!WYZ!W]^!Wpq!Wrs!]|}$u}!O$z!Q!R%T!R![&c![!]&t!}#O&y#P#Q'O#Y#Z'T#b#c'r#h#i(Z#o#p(r#q#r(w~!]Oe~~!`Wpq!]qr!]rs!xs#O!]#O#P!}#P;'S!];'S;=`$o<%lO!]~!}Og~~#QXrs!]!P!Q!]#O#P!]#U#V!]#Y#Z!]#b#c!]#f#g!]#h#i!]#i#j#m~#pR!Q![#y!c!i#y#T#Z#y~#|R!Q![$V!c!i$V#T#Z$V~$YR!Q![$c!c!i$c#T#Z$c~$fR!Q![!]!c!i!]#T#Z!]~$rP;=`<%l!]~$zO]~~$}Q!Q!R%T!R![&c~%YRT~!O!P%c!g!h%w#X#Y%w~%fP!Q![%i~%nRT~!Q![%i!g!h%w#X#Y%w~%zR{|&T}!O&T!Q![&Z~&WP!Q![&Z~&`PT~!Q![&Z~&hST~!O!P%c!Q![&c!g!h%w#X#Y%w~&yO[~~'OO_~~'TO^~~'WP#T#U'Z~'^P#`#a'a~'dP#g#h'g~'jP#X#Y'm~'rOR~~'uP#i#j'x~'{P#`#a(O~(RP#`#a(U~(ZOS~~(^P#f#g(a~(dP#i#j(g~(jP#X#Y(m~(rOQ~~(wOW~~(|OV~",tokenizers:[0],topRules:{JsonText:[0,1]},tokenPrec:0}),YQn=()=>e=>{try{JSON.parse(e.state.doc.toString())}catch(t){if(!(t instanceof SyntaxError))throw t;const n=JQn(t,e.state.doc);return[{from:n,message:t.message,severity:"error",to:n}]}return[]};function JQn(e,t){let n;return(n=e.message.match(/at position (\d+)/))?Math.min(+n[1],t.length):(n=e.message.match(/at line (\d+) column (\d+)/))?Math.min(t.line(+n[1]).from+ +n[2]-1,t.length):0}const upt=I0.define({name:"json",parser:GQn.configure({props:[Q2.add({Object:ES({except:/^\s*\}/}),Array:ES({except:/^\s*\]/})}),U2.add({"Object Array":YR})]}),languageData:{closeBrackets:{brackets:["[","{",'"']},indentOnInput:/^\s*[\}\]]$/}});function fpt(){return new _1(upt)}const eUn=Object.freeze(Object.defineProperty({__proto__:null,json:fpt,jsonLanguage:upt,jsonParseLinter:YQn},Symbol.toStringTag,{value:"Module"})),tUn=1,mpt=194,Apt=195,nUn=196,nMe=197,rUn=198,sUn=199,iUn=200,aUn=2,hpt=3,rMe=201,oUn=24,lUn=25,cUn=49,dUn=50,uUn=55,fUn=56,mUn=57,AUn=59,hUn=60,pUn=61,gUn=62,xUn=63,bUn=65,yUn=238,vUn=71,wUn=241,kUn=242,OUn=243,SUn=244,jUn=245,CUn=246,NUn=247,IUn=248,ppt=72,PUn=249,TUn=250,_Un=251,MUn=252,EUn=253,DUn=254,RUn=255,LUn=256,zUn=73,$Un=77,FUn=263,BUn=112,QUn=130,UUn=151,qUn=152,VUn=155,n8=10,_E=13,Mve=32,bY=9,Eve=35,WUn=40,HUn=46,pme=123,sMe=125,gpt=39,xpt=34,iMe=92,KUn=111,ZUn=120,XUn=78,GUn=117,YUn=85,JUn=new Set([lUn,cUn,dUn,FUn,bUn,QUn,fUn,mUn,yUn,gUn,xUn,ppt,zUn,$Un,hUn,pUn,UUn,qUn,VUn,BUn]);function die(e){return e==n8||e==_E}function uie(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}const eqn=new cd((e,t)=>{let n;if(e.next<0)e.acceptToken(sUn);else if(t.context.flags&mU)die(e.next)&&e.acceptToken(rUn,1);else if(((n=e.peek(-1))<0||die(n))&&t.canShift(nMe)){let r=0;for(;e.next==Mve||e.next==bY;)e.advance(),r++;(e.next==n8||e.next==_E||e.next==Eve)&&e.acceptToken(nMe,-r)}else die(e.next)&&e.acceptToken(nUn,1)},{contextual:!0}),tqn=new cd((e,t)=>{let n=t.context;if(n.flags)return;let r=e.peek(-1);if(r==n8||r==_E){let s=0,a=0;for(;;){if(e.next==Mve)s++;else if(e.next==bY)s+=8-s%8;else break;e.advance(),a++}s!=n.indent&&e.next!=n8&&e.next!=_E&&e.next!=Eve&&(s<n.indent?e.acceptToken(Apt,-a):e.acceptToken(mpt))}}),mU=1,bpt=2,Wb=4,Hb=8,Kb=16,Zb=32;function AU(e,t,n){this.parent=e,this.indent=t,this.flags=n,this.hash=(e?e.hash+e.hash<<8:0)+t+(t<<4)+n+(n<<6)}const nqn=new AU(null,0,0);function rqn(e){let t=0;for(let n=0;n<e.length;n++)t+=e.charCodeAt(n)==bY?8-t%8:1;return t}const aMe=new Map([[wUn,0],[kUn,Wb],[OUn,Hb],[SUn,Hb|Wb],[jUn,Kb],[CUn,Kb|Wb],[NUn,Kb|Hb],[IUn,Kb|Hb|Wb],[PUn,Zb],[TUn,Zb|Wb],[_Un,Zb|Hb],[MUn,Zb|Hb|Wb],[EUn,Zb|Kb],[DUn,Zb|Kb|Wb],[RUn,Zb|Kb|Hb],[LUn,Zb|Kb|Hb|Wb]].map(([e,t])=>[e,t|bpt])),sqn=new hG({start:nqn,reduce(e,t,n,r){return e.flags&mU&&JUn.has(t)||(t==vUn||t==ppt)&&e.flags&bpt?e.parent:e},shift(e,t,n,r){return t==mpt?new AU(e,rqn(r.read(r.pos,n.pos)),0):t==Apt?e.parent:t==oUn||t==uUn||t==AUn||t==hpt?new AU(e,0,mU):aMe.has(t)?new AU(e,0,aMe.get(t)|e.flags&mU):e},hash(e){return e.hash}}),iqn=new cd(e=>{for(let t=0;t<5;t++){if(e.next!="print".charCodeAt(t))return;e.advance()}if(!/\w/.test(String.fromCharCode(e.next)))for(let t=0;;t++){let n=e.peek(t);if(!(n==Mve||n==bY)){n!=WUn&&n!=HUn&&n!=n8&&n!=_E&&n!=Eve&&e.acceptToken(tUn);return}}}),aqn=new cd((e,t)=>{let{flags:n}=t.context,r=n&Wb?xpt:gpt,s=(n&Hb)>0,a=!(n&Kb),o=(n&Zb)>0,l=e.pos;for(;!(e.next<0);)if(o&&e.next==pme)if(e.peek(1)==pme)e.advance(2);else{if(e.pos==l){e.acceptToken(hpt,1);return}break}else if(a&&e.next==iMe){if(e.pos==l){e.advance();let c=e.next;c>=0&&(e.advance(),oqn(e,c)),e.acceptToken(aUn);return}break}else if(e.next==iMe&&!a&&e.peek(1)>-1)e.advance(2);else if(e.next==r&&(!s||e.peek(1)==r&&e.peek(2)==r)){if(e.pos==l){e.acceptToken(rMe,s?3:1);return}break}else if(e.next==n8){if(s)e.advance();else if(e.pos==l){e.acceptToken(rMe);return}break}else e.advance();e.pos>l&&e.acceptToken(iUn)});function oqn(e,t){if(t==KUn)for(let n=0;n<2&&e.next>=48&&e.next<=55;n++)e.advance();else if(t==ZUn)for(let n=0;n<2&&uie(e.next);n++)e.advance();else if(t==GUn)for(let n=0;n<4&&uie(e.next);n++)e.advance();else if(t==YUn)for(let n=0;n<8&&uie(e.next);n++)e.advance();else if(t==XUn&&e.next==pme){for(e.advance();e.next>=0&&e.next!=sMe&&e.next!=gpt&&e.next!=xpt&&e.next!=n8;)e.advance();e.next==sMe&&e.advance()}}const lqn=H0({'async "*" "**" FormatConversion FormatSpec':Xe.modifier,"for while if elif else try except finally return raise break continue with pass assert await yield match case":Xe.controlKeyword,"in not and or is del":Xe.operatorKeyword,"from def class global nonlocal lambda":Xe.definitionKeyword,import:Xe.moduleKeyword,"with as print":Xe.keyword,Boolean:Xe.bool,None:Xe.null,VariableName:Xe.variableName,"CallExpression/VariableName":Xe.function(Xe.variableName),"FunctionDefinition/VariableName":Xe.function(Xe.definition(Xe.variableName)),"ClassDefinition/VariableName":Xe.definition(Xe.className),PropertyName:Xe.propertyName,"CallExpression/MemberExpression/PropertyName":Xe.function(Xe.propertyName),Comment:Xe.lineComment,Number:Xe.number,String:Xe.string,FormatString:Xe.special(Xe.string),Escape:Xe.escape,UpdateOp:Xe.updateOperator,"ArithOp!":Xe.arithmeticOperator,BitOp:Xe.bitwiseOperator,CompareOp:Xe.compareOperator,AssignOp:Xe.definitionOperator,Ellipsis:Xe.punctuation,At:Xe.meta,"( )":Xe.paren,"[ ]":Xe.squareBracket,"{ }":Xe.brace,".":Xe.derefOperator,", ;":Xe.separator}),cqn={__proto__:null,await:44,or:54,and:56,in:60,not:62,is:64,if:70,else:72,lambda:76,yield:94,from:96,async:102,for:104,None:162,True:164,False:164,del:178,pass:182,break:186,continue:190,return:194,raise:202,import:206,as:208,global:212,nonlocal:214,assert:218,type:223,elif:236,while:240,try:246,except:248,finally:250,with:254,def:258,class:268,match:279,case:285},dqn=P0.deserialize({version:14,states:"##jO`QeOOP$}OSOOO&WQtO'#HUOOQS'#Co'#CoOOQS'#Cp'#CpO'vQdO'#CnO*UQtO'#HTOOQS'#HU'#HUOOQS'#DU'#DUOOQS'#HT'#HTO*rQdO'#D_O+VQdO'#DfO+gQdO'#DjO+zOWO'#DuO,VOWO'#DvO.[QtO'#GuOOQS'#Gu'#GuO'vQdO'#GtO0ZQtO'#GtOOQS'#Eb'#EbO0rQdO'#EcOOQS'#Gs'#GsO0|QdO'#GrOOQV'#Gr'#GrO1XQdO'#FYOOQS'#G^'#G^O1^QdO'#FXOOQV'#IS'#ISOOQV'#Gq'#GqOOQV'#Fq'#FqQ`QeOOO'vQdO'#CqO1lQdO'#C}O1sQdO'#DRO2RQdO'#HYO2cQtO'#EVO'vQdO'#EWOOQS'#EY'#EYOOQS'#E['#E[OOQS'#E^'#E^O2wQdO'#E`O3_QdO'#EdO3rQdO'#EfO3zQtO'#EfO1XQdO'#EiO0rQdO'#ElO1XQdO'#EnO0rQdO'#EtO0rQdO'#EwO4VQdO'#EyO4^QdO'#FOO4iQdO'#EzO0rQdO'#FOO1XQdO'#FQO1XQdO'#FVO4nQdO'#F[P4uOdO'#GpPOOO)CBd)CBdOOQS'#Ce'#CeOOQS'#Cf'#CfOOQS'#Cg'#CgOOQS'#Ch'#ChOOQS'#Ci'#CiOOQS'#Cj'#CjOOQS'#Cl'#ClO'vQdO,59OO'vQdO,59OO'vQdO,59OO'vQdO,59OO'vQdO,59OO'vQdO,59OO5TQdO'#DoOOQS,5:Y,5:YO5hQdO'#HdOOQS,5:],5:]O5uQ!fO,5:]O5zQtO,59YO1lQdO,59bO1lQdO,59bO1lQdO,59bO8jQdO,59bO8oQdO,59bO8vQdO,59jO8}QdO'#HTO:TQdO'#HSOOQS'#HS'#HSOOQS'#D['#D[O:lQdO,59aO'vQdO,59aO:zQdO,59aOOQS,59y,59yO;PQdO,5:RO'vQdO,5:ROOQS,5:Q,5:QO;_QdO,5:QO;dQdO,5:XO'vQdO,5:XO'vQdO,5:VOOQS,5:U,5:UO;uQdO,5:UO;zQdO,5:WOOOW'#Fy'#FyO<POWO,5:aOOQS,5:a,5:aO<[QdO'#HwOOOW'#Dw'#DwOOOW'#Fz'#FzO<lOWO,5:bOOQS,5:b,5:bOOQS'#F}'#F}O<zQtO,5:iO?lQtO,5=`O@VQ#xO,5=`O@vQtO,5=`OOQS,5:},5:}OA_QeO'#GWOBqQdO,5;^OOQV,5=^,5=^OB|QtO'#IPOCkQdO,5;tOOQS-E:[-E:[OOQV,5;s,5;sO4dQdO'#FQOOQV-E9o-E9oOCsQtO,59]OEzQtO,59iOFeQdO'#HVOFpQdO'#HVO1XQdO'#HVOF{QdO'#DTOGTQdO,59mOGYQdO'#HZO'vQdO'#HZO0rQdO,5=tOOQS,5=t,5=tO0rQdO'#EROOQS'#ES'#ESOGwQdO'#GPOHXQdO,58|OHXQdO,58|O*xQdO,5:oOHgQtO'#H]OOQS,5:r,5:rOOQS,5:z,5:zOHzQdO,5;OOI]QdO'#IOO1XQdO'#H}OOQS,5;Q,5;QOOQS'#GT'#GTOIqQtO,5;QOJPQdO,5;QOJUQdO'#IQOOQS,5;T,5;TOJdQdO'#H|OOQS,5;W,5;WOJuQdO,5;YO4iQdO,5;`O4iQdO,5;cOJ}QtO'#ITO'vQdO'#ITOKXQdO,5;eO4VQdO,5;eO0rQdO,5;jO1XQdO,5;lOK^QeO'#EuOLjQgO,5;fO!!kQdO'#IUO4iQdO,5;jO!!vQdO,5;lO!#OQdO,5;qO!#ZQtO,5;vO'vQdO,5;vPOOO,5=[,5=[P!#bOSO,5=[P!#jOdO,5=[O!&bQtO1G.jO!&iQtO1G.jO!)YQtO1G.jO!)dQtO1G.jO!+}QtO1G.jO!,bQtO1G.jO!,uQdO'#HcO!-TQtO'#GuO0rQdO'#HcO!-_QdO'#HbOOQS,5:Z,5:ZO!-gQdO,5:ZO!-lQdO'#HeO!-wQdO'#HeO!.[QdO,5>OOOQS'#Ds'#DsOOQS1G/w1G/wOOQS1G.|1G.|O!/[QtO1G.|O!/cQtO1G.|O1lQdO1G.|O!0OQdO1G/UOOQS'#DZ'#DZO0rQdO,59tOOQS1G.{1G.{O!0VQdO1G/eO!0gQdO1G/eO!0oQdO1G/fO'vQdO'#H[O!0tQdO'#H[O!0yQtO1G.{O!1ZQdO,59iO!2aQdO,5=zO!2qQdO,5=zO!2yQdO1G/mO!3OQtO1G/mOOQS1G/l1G/lO!3`QdO,5=uO!4VQdO,5=uO0rQdO1G/qO!4tQdO1G/sO!4yQtO1G/sO!5ZQtO1G/qOOQS1G/p1G/pOOQS1G/r1G/rOOOW-E9w-E9wOOQS1G/{1G/{O!5kQdO'#HxO0rQdO'#HxO!5|QdO,5>cOOOW-E9x-E9xOOQS1G/|1G/|OOQS-E9{-E9{O!6[Q#xO1G2zO!6{QtO1G2zO'vQdO,5<jOOQS,5<j,5<jOOQS-E9|-E9|OOQS,5<r,5<rOOQS-E:U-E:UOOQV1G0x1G0xO1XQdO'#GRO!7dQtO,5>kOOQS1G1`1G1`O!8RQdO1G1`OOQS'#DV'#DVO0rQdO,5=qOOQS,5=q,5=qO!8WQdO'#FrO!8cQdO,59oO!8kQdO1G/XO!8uQtO,5=uOOQS1G3`1G3`OOQS,5:m,5:mO!9fQdO'#GtOOQS,5<k,5<kOOQS-E9}-E9}O!9wQdO1G.hOOQS1G0Z1G0ZO!:VQdO,5=wO!:gQdO,5=wO0rQdO1G0jO0rQdO1G0jO!:xQdO,5>jO!;ZQdO,5>jO1XQdO,5>jO!;lQdO,5>iOOQS-E:R-E:RO!;qQdO1G0lO!;|QdO1G0lO!<RQdO,5>lO!<aQdO,5>lO!<oQdO,5>hO!=VQdO,5>hO!=hQdO'#EpO0rQdO1G0tO!=sQdO1G0tO!=xQgO1G0zO!AvQgO1G0}O!EqQdO,5>oO!E{QdO,5>oO!FTQtO,5>oO0rQdO1G1PO!F_QdO1G1PO4iQdO1G1UO!!vQdO1G1WOOQV,5;a,5;aO!FdQfO,5;aO!FiQgO1G1QO!JjQdO'#GZO4iQdO1G1QO4iQdO1G1QO!JzQdO,5>pO!KXQdO,5>pO1XQdO,5>pOOQV1G1U1G1UO!KaQdO'#FSO!KrQ!fO1G1WO!KzQdO1G1WOOQV1G1]1G1]O4iQdO1G1]O!LPQdO1G1]O!LXQdO'#F^OOQV1G1b1G1bO!#ZQtO1G1bPOOO1G2v1G2vP!L^OSO1G2vOOQS,5=},5=}OOQS'#Dp'#DpO0rQdO,5=}O!LfQdO,5=|O!LyQdO,5=|OOQS1G/u1G/uO!MRQdO,5>PO!McQdO,5>PO!MkQdO,5>PO!NOQdO,5>PO!N`QdO,5>POOQS1G3j1G3jOOQS7+$h7+$hO!8kQdO7+$pO#!RQdO1G.|O#!YQdO1G.|OOQS1G/`1G/`OOQS,5<`,5<`O'vQdO,5<`OOQS7+%P7+%PO#!aQdO7+%POOQS-E9r-E9rOOQS7+%Q7+%QO#!qQdO,5=vO'vQdO,5=vOOQS7+$g7+$gO#!vQdO7+%PO##OQdO7+%QO##TQdO1G3fOOQS7+%X7+%XO##eQdO1G3fO##mQdO7+%XOOQS,5<_,5<_O'vQdO,5<_O##rQdO1G3aOOQS-E9q-E9qO#$iQdO7+%]OOQS7+%_7+%_O#$wQdO1G3aO#%fQdO7+%_O#%kQdO1G3gO#%{QdO1G3gO#&TQdO7+%]O#&YQdO,5>dO#&sQdO,5>dO#&sQdO,5>dOOQS'#Dx'#DxO#'UO&jO'#DzO#'aO`O'#HyOOOW1G3}1G3}O#'fQdO1G3}O#'nQdO1G3}O#'yQ#xO7+(fO#(jQtO1G2UP#)TQdO'#GOOOQS,5<m,5<mOOQS-E:P-E:POOQS7+&z7+&zOOQS1G3]1G3]OOQS,5<^,5<^OOQS-E9p-E9pOOQS7+$s7+$sO#)bQdO,5=`O#){QdO,5=`O#*^QtO,5<aO#*qQdO1G3cOOQS-E9s-E9sOOQS7+&U7+&UO#+RQdO7+&UO#+aQdO,5<nO#+uQdO1G4UOOQS-E:Q-E:QO#,WQdO1G4UOOQS1G4T1G4TOOQS7+&W7+&WO#,iQdO7+&WOOQS,5<p,5<pO#,tQdO1G4WOOQS-E:S-E:SOOQS,5<l,5<lO#-SQdO1G4SOOQS-E:O-E:OO1XQdO'#EqO#-jQdO'#EqO#-uQdO'#IRO#-}QdO,5;[OOQS7+&`7+&`O0rQdO7+&`O#.SQgO7+&fO!JmQdO'#GXO4iQdO7+&fO4iQdO7+&iO#2QQtO,5<tO'vQdO,5<tO#2[QdO1G4ZOOQS-E:W-E:WO#2fQdO1G4ZO4iQdO7+&kO0rQdO7+&kOOQV7+&p7+&pO!KrQ!fO7+&rO!KzQdO7+&rO`QeO1G0{OOQV-E:X-E:XO4iQdO7+&lO4iQdO7+&lOOQV,5<u,5<uO#2nQdO,5<uO!JmQdO,5<uOOQV7+&l7+&lO#2yQgO7+&lO#6tQdO,5<vO#7PQdO1G4[OOQS-E:Y-E:YO#7^QdO1G4[O#7fQdO'#IWO#7tQdO'#IWO1XQdO'#IWOOQS'#IW'#IWO#8PQdO'#IVOOQS,5;n,5;nO#8XQdO,5;nO0rQdO'#FUOOQV7+&r7+&rO4iQdO7+&rOOQV7+&w7+&wO4iQdO7+&wO#8^QfO,5;xOOQV7+&|7+&|POOO7+(b7+(bO#8cQdO1G3iOOQS,5<c,5<cO#8qQdO1G3hOOQS-E9u-E9uO#9UQdO,5<dO#9aQdO,5<dO#9tQdO1G3kOOQS-E9v-E9vO#:UQdO1G3kO#:^QdO1G3kO#:nQdO1G3kO#:UQdO1G3kOOQS<<H[<<H[O#:yQtO1G1zOOQS<<Hk<<HkP#;WQdO'#FtO8vQdO1G3bO#;eQdO1G3bO#;jQdO<<HkOOQS<<Hl<<HlO#;zQdO7+)QOOQS<<Hs<<HsO#<[QtO1G1yP#<{QdO'#FsO#=YQdO7+)RO#=jQdO7+)RO#=rQdO<<HwO#=wQdO7+({OOQS<<Hy<<HyO#>nQdO,5<bO'vQdO,5<bOOQS-E9t-E9tOOQS<<Hw<<HwOOQS,5<g,5<gO0rQdO,5<gO#>sQdO1G4OOOQS-E9y-E9yO#?^QdO1G4OO<[QdO'#H{OOOO'#D{'#D{OOOO'#F|'#F|O#?oO&jO,5:fOOOW,5>e,5>eOOOW7+)i7+)iO#?zQdO7+)iO#@SQdO1G2zO#@mQdO1G2zP'vQdO'#FuO0rQdO<<IpO1XQdO1G2YP1XQdO'#GSO#AOQdO7+)pO#AaQdO7+)pOOQS<<Ir<<IrP1XQdO'#GUP0rQdO'#GQOOQS,5;],5;]O#ArQdO,5>mO#BQQdO,5>mOOQS1G0v1G0vOOQS<<Iz<<IzOOQV-E:V-E:VO4iQdO<<JQOOQV,5<s,5<sO4iQdO,5<sOOQV<<JQ<<JQOOQV<<JT<<JTO#BYQtO1G2`P#BdQdO'#GYO#BkQdO7+)uO#BuQgO<<JVO4iQdO<<JVOOQV<<J^<<J^O4iQdO<<J^O!KrQ!fO<<J^O#FpQgO7+&gOOQV<<JW<<JWO#FzQgO<<JWOOQV1G2a1G2aO1XQdO1G2aO#JuQdO1G2aO4iQdO<<JWO1XQdO1G2bP0rQdO'#G[O#KQQdO7+)vO#K_QdO7+)vOOQS'#FT'#FTO0rQdO,5>rO#KgQdO,5>rO#KrQdO,5>rO#K}QdO,5>qO#L`QdO,5>qOOQS1G1Y1G1YOOQS,5;p,5;pOOQV<<Jc<<JcO#LhQdO1G1dOOQS7+)T7+)TP#LmQdO'#FwO#L}QdO1G2OO#MbQdO1G2OO#MrQdO1G2OP#M}QdO'#FxO#N[QdO7+)VO#NlQdO7+)VO#NlQdO7+)VO#NtQdO7+)VO$ UQdO7+(|O8vQdO7+(|OOQSAN>VAN>VO$ oQdO<<LmOOQSAN>cAN>cO0rQdO1G1|O$!PQtO1G1|P$!ZQdO'#FvOOQS1G2R1G2RP$!hQdO'#F{O$!uQdO7+)jO$#`QdO,5>gOOOO-E9z-E9zOOOW<<MT<<MTO$#nQdO7+(fOOQSAN?[AN?[OOQS7+'t7+'tO$$XQdO<<M[OOQS,5<q,5<qO$$jQdO1G4XOOQS-E:T-E:TOOQVAN?lAN?lOOQV1G2_1G2_O4iQdOAN?qO$$xQgOAN?qOOQVAN?xAN?xO4iQdOAN?xOOQV<<JR<<JRO4iQdOAN?rO4iQdO7+'{OOQV7+'{7+'{O1XQdO7+'{OOQVAN?rAN?rOOQS7+'|7+'|O$(sQdO<<MbOOQS1G4^1G4^O0rQdO1G4^OOQS,5<w,5<wO$)QQdO1G4]OOQS-E:Z-E:ZOOQU'#G_'#G_O$)cQfO7+'OO$)nQdO'#F_O$*uQdO7+'jO$+VQdO7+'jOOQS7+'j7+'jO$+bQdO<<LqO$+rQdO<<LqO$+rQdO<<LqO$+zQdO'#H^OOQS<<Lh<<LhO$,UQdO<<LhOOQS7+'h7+'hOOQS'#D|'#D|OOOO1G4R1G4RO$,oQdO1G4RO$,wQdO1G4RP!=hQdO'#GVOOQVG25]G25]O4iQdOG25]OOQVG25dG25dOOQVG25^G25^OOQV<<Kg<<KgO4iQdO<<KgOOQS7+)x7+)xP$-SQdO'#G]OOQU-E:]-E:]OOQV<<Jj<<JjO$-vQtO'#FaOOQS'#Fc'#FcO$.WQdO'#FbO$.xQdO'#FbOOQS'#Fb'#FbO$.}QdO'#IYO$)nQdO'#FiO$)nQdO'#FiO$/fQdO'#FjO$)nQdO'#FkO$/mQdO'#IZOOQS'#IZ'#IZO$0[QdO,5;yOOQS<<KU<<KUO$0dQdO<<KUO$0tQdOANB]O$1UQdOANB]O$1^QdO'#H_OOQS'#H_'#H_O1sQdO'#DcO$1wQdO,5=xOOQSANBSANBSOOOO7+)m7+)mO$2`QdO7+)mOOQVLD*wLD*wOOQVANARANARO5uQ!fO'#GaO$2hQtO,5<SO$)nQdO'#FmOOQS,5<W,5<WOOQS'#Fd'#FdO$3YQdO,5;|O$3_QdO,5;|OOQS'#Fg'#FgO$)nQdO'#G`O$4PQdO,5<QO$4kQdO,5>tO$4{QdO,5>tO1XQdO,5<PO$5^QdO,5<TO$5cQdO,5<TO$)nQdO'#I[O$5hQdO'#I[O$5mQdO,5<UOOQS,5<V,5<VO0rQdO'#FpOOQU1G1e1G1eO4iQdO1G1eOOQSAN@pAN@pO$5rQdOG27wO$6SQdO,59}OOQS1G3d1G3dOOOO<<MX<<MXOOQS,5<{,5<{OOQS-E:_-E:_O$6XQtO'#FaO$6`QdO'#I]O$6nQdO'#I]O$6vQdO,5<XOOQS1G1h1G1hO$6{QdO1G1hO$7QQdO,5<zOOQS-E:^-E:^O$7lQdO,5=OO$8TQdO1G4`OOQS-E:b-E:bOOQS1G1k1G1kOOQS1G1o1G1oO$8eQdO,5>vO$)nQdO,5>vOOQS1G1p1G1pOOQS,5<[,5<[OOQU7+'P7+'PO$+zQdO1G/iO$)nQdO,5<YO$8sQdO,5>wO$8zQdO,5>wOOQS1G1s1G1sOOQS7+'S7+'SP$)nQdO'#GdO$9SQdO1G4bO$9^QdO1G4bO$9fQdO1G4bOOQS7+%T7+%TO$9tQdO1G1tO$:SQtO'#FaO$:ZQdO,5<}OOQS,5<},5<}O$:iQdO1G4cOOQS-E:a-E:aO$)nQdO,5<|O$:pQdO,5<|O$:uQdO7+)|OOQS-E:`-E:`O$;PQdO7+)|O$)nQdO,5<ZP$)nQdO'#GcO$;XQdO1G2hO$)nQdO1G2hP$;gQdO'#GbO$;nQdO<<MhO$;xQdO1G1uO$<WQdO7+(SO8vQdO'#C}O8vQdO,59bO8vQdO,59bO8vQdO,59bO$<fQtO,5=`O8vQdO1G.|O0rQdO1G/XO0rQdO7+$pP$<yQdO'#GOO'vQdO'#GtO$=WQdO,59bO$=]QdO,59bO$=dQdO,59mO$=iQdO1G/UO1sQdO'#DRO8vQdO,59j",stateData:"$>S~O%cOS%^OSSOS%]PQ~OPdOVaOfoOhYOopOs!POvqO!PrO!Q{O!T!SO!U!RO!XZO!][O!h`O!r`O!s`O!t`O!{tO!}uO#PvO#RwO#TxO#XyO#ZzO#^|O#_|O#a}O#c!OO#l!QO#o!TO#s!UO#u!VO#z!WO#}hO$P!XO%oRO%pRO%tSO%uWO&Z]O&[]O&]]O&^]O&_]O&`]O&a]O&b]O&c^O&d^O&e^O&f^O&g^O&h^O&i^O&j^O~O%]!YO~OV!aO_!aOa!bOh!iO!X!kO!f!mO%j![O%k!]O%l!^O%m!_O%n!_O%o!`O%p!`O%q!aO%r!aO%s!aO~Ok%xXl%xXm%xXn%xXo%xXp%xXs%xXz%xX{%xX!x%xX#g%xX%[%xX%_%xX%z%xXg%xX!T%xX!U%xX%{%xX!W%xX![%xX!Q%xX#[%xXt%xX!m%xX~P%SOfoOhYO!XZO!][O!h`O!r`O!s`O!t`O%oRO%pRO%tSO%uWO&Z]O&[]O&]]O&^]O&_]O&`]O&a]O&b]O&c^O&d^O&e^O&f^O&g^O&h^O&i^O&j^O~Oz%wX{%wX#g%wX%[%wX%_%wX%z%wX~Ok!pOl!qOm!oOn!oOo!rOp!sOs!tO!x%wX~P)pOV!zOg!|Oo0cOv0qO!PrO~P'vOV#OOo0cOv0qO!W#PO~P'vOV#SOa#TOo0cOv0qO![#UO~P'vOQ#XO%`#XO%a#ZO~OQ#^OR#[O%`#^O%a#`O~OV%iX_%iXa%iXh%iXk%iXl%iXm%iXn%iXo%iXp%iXs%iXz%iX!X%iX!f%iX%j%iX%k%iX%l%iX%m%iX%n%iX%o%iX%p%iX%q%iX%r%iX%s%iXg%iX!T%iX!U%iX~O&Z]O&[]O&]]O&^]O&_]O&`]O&a]O&b]O&c^O&d^O&e^O&f^O&g^O&h^O&i^O&j^O{%iX!x%iX#g%iX%[%iX%_%iX%z%iX%{%iX!W%iX![%iX!Q%iX#[%iXt%iX!m%iX~P,eOz#dO{%hX!x%hX#g%hX%[%hX%_%hX%z%hX~Oo0cOv0qO~P'vO#g#gO%[#iO%_#iO~O%uWO~O!T#nO#u!VO#z!WO#}hO~OopO~P'vOV#sOa#tO%uWO{wP~OV#xOo0cOv0qO!Q#yO~P'vO{#{O!x$QO%z#|O#g!yX%[!yX%_!yX~OV#xOo0cOv0qO#g#SX%[#SX%_#SX~P'vOo0cOv0qO#g#WX%[#WX%_#WX~P'vOh$WO%uWO~O!f$YO!r$YO%uWO~OV$eO~P'vO!U$gO#s$hO#u$iO~O{$jO~OV$qO~P'vOS$sO%[$rO%_$rO%c$tO~OV$}Oa$}Og%POo0cOv0qO~P'vOo0cOv0qO{%SO~P'vO&Y%UO~Oa!bOh!iO!X!kO!f!mOVba_bakbalbambanbaobapbasbazba{ba!xba#gba%[ba%_ba%jba%kba%lba%mba%nba%oba%pba%qba%rba%sba%zbagba!Tba!Uba%{ba!Wba![ba!Qba#[batba!mba~On%ZO~Oo%ZO~P'vOo0cO~P'vOk0eOl0fOm0dOn0dOo0mOp0nOs0rOg%wX!T%wX!U%wX%{%wX!W%wX![%wX!Q%wX#[%wX!m%wX~P)pO%{%]Og%vXz%vX!T%vX!U%vX!W%vX{%vX~Og%_Oz%`O!T%dO!U%cO~Og%_O~Oz%gO!T%dO!U%cO!W&SX~O!W%kO~Oz%lO{%nO!T%dO!U%cO![%}X~O![%rO~O![%sO~OQ#XO%`#XO%a%uO~OV%wOo0cOv0qO!PrO~P'vOQ#^OR#[O%`#^O%a%zO~OV!qa_!qaa!qah!qak!qal!qam!qan!qao!qap!qas!qaz!qa{!qa!X!qa!f!qa!x!qa#g!qa%[!qa%_!qa%j!qa%k!qa%l!qa%m!qa%n!qa%o!qa%p!qa%q!qa%r!qa%s!qa%z!qag!qa!T!qa!U!qa%{!qa!W!qa![!qa!Q!qa#[!qat!qa!m!qa~P#yOz%|O{%ha!x%ha#g%ha%[%ha%_%ha%z%ha~P%SOV&OOopOvqO{%ha!x%ha#g%ha%[%ha%_%ha%z%ha~P'vOz%|O{%ha!x%ha#g%ha%[%ha%_%ha%z%ha~OPdOVaOopOvqO!PrO!Q{O!{tO!}uO#PvO#RwO#TxO#XyO#ZzO#^|O#_|O#a}O#c!OO#g$zX%[$zX%_$zX~P'vO#g#gO%[&TO%_&TO~O!f&UOh&sX%[&sXz&sX#[&sX#g&sX%_&sX#Z&sXg&sX~Oh!iO%[&WO~Okealeameaneaoeapeaseazea{ea!xea#gea%[ea%_ea%zeagea!Tea!Uea%{ea!Wea![ea!Qea#[eatea!mea~P%SOsqazqa{qa#gqa%[qa%_qa%zqa~Ok!pOl!qOm!oOn!oOo!rOp!sO!xqa~PEcO%z&YOz%yX{%yX~O%uWOz%yX{%yX~Oz&]O{wX~O{&_O~Oz%lO#g%}X%[%}X%_%}Xg%}X{%}X![%}X!m%}X%z%}X~OV0lOo0cOv0qO!PrO~P'vO%z#|O#gUa%[Ua%_Ua~Oz&hO#g&PX%[&PX%_&PXn&PX~P%SOz&kO!Q&jO#g#Wa%[#Wa%_#Wa~Oz&lO#[&nO#g&rX%[&rX%_&rXg&rX~O!f$YO!r$YO#Z&qO%uWO~O#Z&qO~Oz&sO#g&tX%[&tX%_&tX~Oz&uO#g&pX%[&pX%_&pX{&pX~O!X&wO%z&xO~Oz&|On&wX~P%SOn'PO~OPdOVaOopOvqO!PrO!Q{O!{tO!}uO#PvO#RwO#TxO#XyO#ZzO#^|O#_|O#a}O#c!OO%['UO~P'vOt'YO#p'WO#q'XOP#naV#naf#nah#nao#nas#nav#na!P#na!Q#na!T#na!U#na!X#na!]#na!h#na!r#na!s#na!t#na!{#na!}#na#P#na#R#na#T#na#X#na#Z#na#^#na#_#na#a#na#c#na#l#na#o#na#s#na#u#na#z#na#}#na$P#na%X#na%o#na%p#na%t#na%u#na&Z#na&[#na&]#na&^#na&_#na&`#na&a#na&b#na&c#na&d#na&e#na&f#na&g#na&h#na&i#na&j#na%Z#na%_#na~Oz'ZO#[']O{&xX~Oh'_O!X&wO~Oh!iO{$jO!X&wO~O{'eO~P%SO%['hO%_'hO~OS'iO%['hO%_'hO~OV!aO_!aOa!bOh!iO!X!kO!f!mO%l!^O%m!_O%n!_O%o!`O%p!`O%q!aO%r!aO%s!aOkWilWimWinWioWipWisWizWi{Wi!xWi#gWi%[Wi%_Wi%jWi%zWigWi!TWi!UWi%{Wi!WWi![Wi!QWi#[WitWi!mWi~O%k!]O~P!#uO%kWi~P!#uOV!aO_!aOa!bOh!iO!X!kO!f!mO%o!`O%p!`O%q!aO%r!aO%s!aOkWilWimWinWioWipWisWizWi{Wi!xWi#gWi%[Wi%_Wi%jWi%kWi%lWi%zWigWi!TWi!UWi%{Wi!WWi![Wi!QWi#[WitWi!mWi~O%m!_O%n!_O~P!&pO%mWi%nWi~P!&pOa!bOh!iO!X!kO!f!mOkWilWimWinWioWipWisWizWi{Wi!xWi#gWi%[Wi%_Wi%jWi%kWi%lWi%mWi%nWi%oWi%pWi%zWigWi!TWi!UWi%{Wi!WWi![Wi!QWi#[WitWi!mWi~OV!aO_!aO%q!aO%r!aO%s!aO~P!)nOVWi_Wi%qWi%rWi%sWi~P!)nO!T%dO!U%cOg&VXz&VX~O%z'kO%{'kO~P,eOz'mOg&UX~Og'oO~Oz'pO{'rO!W&XX~Oo0cOv0qOz'pO{'sO!W&XX~P'vO!W'uO~Om!oOn!oOo!rOp!sOkjisjizji{ji!xji#gji%[ji%_ji%zji~Ol!qO~P!.aOlji~P!.aOk0eOl0fOm0dOn0dOo0mOp0nO~Ot'wO~P!/jOV'|Og'}Oo0cOv0qO~P'vOg'}Oz(OO~Og(QO~O!U(SO~Og(TOz(OO!T%dO!U%cO~P%SOk0eOl0fOm0dOn0dOo0mOp0nOgqa!Tqa!Uqa%{qa!Wqa![qa!Qqa#[qatqa!mqa~PEcOV'|Oo0cOv0qO!W&Sa~P'vOz(WO!W&Sa~O!W(XO~Oz(WO!T%dO!U%cO!W&Sa~P%SOV(]Oo0cOv0qO![%}a#g%}a%[%}a%_%}ag%}a{%}a!m%}a%z%}a~P'vOz(^O![%}a#g%}a%[%}a%_%}ag%}a{%}a!m%}a%z%}a~O![(aO~Oz(^O!T%dO!U%cO![%}a~P%SOz(dO!T%dO!U%cO![&Ta~P%SOz(gO{&lX![&lX!m&lX%z&lX~O{(kO![(mO!m(nO%z(jO~OV&OOopOvqO{%hi!x%hi#g%hi%[%hi%_%hi%z%hi~P'vOz(pO{%hi!x%hi#g%hi%[%hi%_%hi%z%hi~O!f&UOh&sa%[&saz&sa#[&sa#g&sa%_&sa#Z&sag&sa~O%[(uO~OV#sOa#tO%uWO~Oz&]O{wa~OopOvqO~P'vOz(^O#g%}a%[%}a%_%}ag%}a{%}a![%}a!m%}a%z%}a~P%SOz(zO#g%hX%[%hX%_%hX%z%hX~O%z#|O#gUi%[Ui%_Ui~O#g&Pa%[&Pa%_&Pan&Pa~P'vOz(}O#g&Pa%[&Pa%_&Pan&Pa~O%uWO#g&ra%[&ra%_&rag&ra~Oz)SO#g&ra%[&ra%_&rag&ra~Og)VO~OV)WOh$WO%uWO~O#Z)XO~O%uWO#g&ta%[&ta%_&ta~Oz)ZO#g&ta%[&ta%_&ta~Oo0cOv0qO#g&pa%[&pa%_&pa{&pa~P'vOz)^O#g&pa%[&pa%_&pa{&pa~OV)`Oa)`O%uWO~O%z)eO~Ot)hO#j)gOP#hiV#hif#hih#hio#his#hiv#hi!P#hi!Q#hi!T#hi!U#hi!X#hi!]#hi!h#hi!r#hi!s#hi!t#hi!{#hi!}#hi#P#hi#R#hi#T#hi#X#hi#Z#hi#^#hi#_#hi#a#hi#c#hi#l#hi#o#hi#s#hi#u#hi#z#hi#}#hi$P#hi%X#hi%o#hi%p#hi%t#hi%u#hi&Z#hi&[#hi&]#hi&^#hi&_#hi&`#hi&a#hi&b#hi&c#hi&d#hi&e#hi&f#hi&g#hi&h#hi&i#hi&j#hi%Z#hi%_#hi~Ot)iOP#kiV#kif#kih#kio#kis#kiv#ki!P#ki!Q#ki!T#ki!U#ki!X#ki!]#ki!h#ki!r#ki!s#ki!t#ki!{#ki!}#ki#P#ki#R#ki#T#ki#X#ki#Z#ki#^#ki#_#ki#a#ki#c#ki#l#ki#o#ki#s#ki#u#ki#z#ki#}#ki$P#ki%X#ki%o#ki%p#ki%t#ki%u#ki&Z#ki&[#ki&]#ki&^#ki&_#ki&`#ki&a#ki&b#ki&c#ki&d#ki&e#ki&f#ki&g#ki&h#ki&i#ki&j#ki%Z#ki%_#ki~OV)kOn&wa~P'vOz)lOn&wa~Oz)lOn&wa~P%SOn)pO~O%Y)tO~Ot)wO#p'WO#q)vOP#niV#nif#nih#nio#nis#niv#ni!P#ni!Q#ni!T#ni!U#ni!X#ni!]#ni!h#ni!r#ni!s#ni!t#ni!{#ni!}#ni#P#ni#R#ni#T#ni#X#ni#Z#ni#^#ni#_#ni#a#ni#c#ni#l#ni#o#ni#s#ni#u#ni#z#ni#}#ni$P#ni%X#ni%o#ni%p#ni%t#ni%u#ni&Z#ni&[#ni&]#ni&^#ni&_#ni&`#ni&a#ni&b#ni&c#ni&d#ni&e#ni&f#ni&g#ni&h#ni&i#ni&j#ni%Z#ni%_#ni~OV)zOo0cOv0qO{$jO~P'vOo0cOv0qO{&xa~P'vOz*OO{&xa~OV*SOa*TOg*WO%q*UO%uWO~O{$jO&{*YO~Oh'_O~Oh!iO{$jO~O%[*_O~O%[*aO%_*aO~OV$}Oa$}Oo0cOv0qOg&Ua~P'vOz*dOg&Ua~Oo0cOv0qO{*gO!W&Xa~P'vOz*hO!W&Xa~Oo0cOv0qOz*hO{*kO!W&Xa~P'vOo0cOv0qOz*hO!W&Xa~P'vOz*hO{*kO!W&Xa~Om0dOn0dOo0mOp0nOgjikjisjizji!Tji!Uji%{ji!Wji{ji![ji#gji%[ji%_ji!Qji#[jitji!mji%zji~Ol0fO~P!NkOlji~P!NkOV'|Og*pOo0cOv0qO~P'vOn*rO~Og*pOz*tO~Og*uO~OV'|Oo0cOv0qO!W&Si~P'vOz*vO!W&Si~O!W*wO~OV(]Oo0cOv0qO![%}i#g%}i%[%}i%_%}ig%}i{%}i!m%}i%z%}i~P'vOz*zO!T%dO!U%cO![&Ti~Oz*}O![%}i#g%}i%[%}i%_%}ig%}i{%}i!m%}i%z%}i~O![+OO~Oa+QOo0cOv0qO![&Ti~P'vOz*zO![&Ti~O![+SO~OV+UOo0cOv0qO{&la![&la!m&la%z&la~P'vOz+VO{&la![&la!m&la%z&la~O!]+YO&n+[O![!nX~O![+^O~O{(kO![+_O~O{(kO![+_O!m+`O~OV&OOopOvqO{%hq!x%hq#g%hq%[%hq%_%hq%z%hq~P'vOz$ri{$ri!x$ri#g$ri%[$ri%_$ri%z$ri~P%SOV&OOopOvqO~P'vOV&OOo0cOv0qO#g%ha%[%ha%_%ha%z%ha~P'vOz+aO#g%ha%[%ha%_%ha%z%ha~Oz$ia#g$ia%[$ia%_$ian$ia~P%SO#g&Pi%[&Pi%_&Pin&Pi~P'vOz+dO#g#Wq%[#Wq%_#Wq~O#[+eOz$va#g$va%[$va%_$vag$va~O%uWO#g&ri%[&ri%_&rig&ri~Oz+gO#g&ri%[&ri%_&rig&ri~OV+iOh$WO%uWO~O%uWO#g&ti%[&ti%_&ti~Oo0cOv0qO#g&pi%[&pi%_&pi{&pi~P'vO{#{Oz#eX!W#eX~Oz+mO!W&uX~O!W+oO~Ot+rO#j)gOP#hqV#hqf#hqh#hqo#hqs#hqv#hq!P#hq!Q#hq!T#hq!U#hq!X#hq!]#hq!h#hq!r#hq!s#hq!t#hq!{#hq!}#hq#P#hq#R#hq#T#hq#X#hq#Z#hq#^#hq#_#hq#a#hq#c#hq#l#hq#o#hq#s#hq#u#hq#z#hq#}#hq$P#hq%X#hq%o#hq%p#hq%t#hq%u#hq&Z#hq&[#hq&]#hq&^#hq&_#hq&`#hq&a#hq&b#hq&c#hq&d#hq&e#hq&f#hq&g#hq&h#hq&i#hq&j#hq%Z#hq%_#hq~On$|az$|a~P%SOV)kOn&wi~P'vOz+yOn&wi~Oz,TO{$jO#[,TO~O#q,VOP#nqV#nqf#nqh#nqo#nqs#nqv#nq!P#nq!Q#nq!T#nq!U#nq!X#nq!]#nq!h#nq!r#nq!s#nq!t#nq!{#nq!}#nq#P#nq#R#nq#T#nq#X#nq#Z#nq#^#nq#_#nq#a#nq#c#nq#l#nq#o#nq#s#nq#u#nq#z#nq#}#nq$P#nq%X#nq%o#nq%p#nq%t#nq%u#nq&Z#nq&[#nq&]#nq&^#nq&_#nq&`#nq&a#nq&b#nq&c#nq&d#nq&e#nq&f#nq&g#nq&h#nq&i#nq&j#nq%Z#nq%_#nq~O#[,WOz%Oa{%Oa~Oo0cOv0qO{&xi~P'vOz,YO{&xi~O{#{O%z,[Og&zXz&zX~O%uWOg&zXz&zX~Oz,`Og&yX~Og,bO~O%Y,eO~O!T%dO!U%cOg&Viz&Vi~OV$}Oa$}Oo0cOv0qOg&Ui~P'vO{,hOz$la!W$la~Oo0cOv0qO{,iOz$la!W$la~P'vOo0cOv0qO{*gO!W&Xi~P'vOz,lO!W&Xi~Oo0cOv0qOz,lO!W&Xi~P'vOz,lO{,oO!W&Xi~Og$hiz$hi!W$hi~P%SOV'|Oo0cOv0qO~P'vOn,qO~OV'|Og,rOo0cOv0qO~P'vOV'|Oo0cOv0qO!W&Sq~P'vOz$gi![$gi#g$gi%[$gi%_$gig$gi{$gi!m$gi%z$gi~P%SOV(]Oo0cOv0qO~P'vOa+QOo0cOv0qO![&Tq~P'vOz,sO![&Tq~O![,tO~OV(]Oo0cOv0qO![%}q#g%}q%[%}q%_%}qg%}q{%}q!m%}q%z%}q~P'vO{,uO~OV+UOo0cOv0qO{&li![&li!m&li%z&li~P'vOz,zO{&li![&li!m&li%z&li~O!]+YO&n+[O![!na~O{(kO![,}O~OV&OOo0cOv0qO#g%hi%[%hi%_%hi%z%hi~P'vOz-OO#g%hi%[%hi%_%hi%z%hi~O%uWO#g&rq%[&rq%_&rqg&rq~Oz-RO#g&rq%[&rq%_&rqg&rq~OV)`Oa)`O%uWO!W&ua~Oz-TO!W&ua~On$|iz$|i~P%SOV)kO~P'vOV)kOn&wq~P'vOt-XOP#myV#myf#myh#myo#mys#myv#my!P#my!Q#my!T#my!U#my!X#my!]#my!h#my!r#my!s#my!t#my!{#my!}#my#P#my#R#my#T#my#X#my#Z#my#^#my#_#my#a#my#c#my#l#my#o#my#s#my#u#my#z#my#}#my$P#my%X#my%o#my%p#my%t#my%u#my&Z#my&[#my&]#my&^#my&_#my&`#my&a#my&b#my&c#my&d#my&e#my&f#my&g#my&h#my&i#my&j#my%Z#my%_#my~O%Z-]O%_-]O~P`O#q-^OP#nyV#nyf#nyh#nyo#nys#nyv#ny!P#ny!Q#ny!T#ny!U#ny!X#ny!]#ny!h#ny!r#ny!s#ny!t#ny!{#ny!}#ny#P#ny#R#ny#T#ny#X#ny#Z#ny#^#ny#_#ny#a#ny#c#ny#l#ny#o#ny#s#ny#u#ny#z#ny#}#ny$P#ny%X#ny%o#ny%p#ny%t#ny%u#ny&Z#ny&[#ny&]#ny&^#ny&_#ny&`#ny&a#ny&b#ny&c#ny&d#ny&e#ny&f#ny&g#ny&h#ny&i#ny&j#ny%Z#ny%_#ny~Oz-aO{$jO#[-aO~Oo0cOv0qO{&xq~P'vOz-dO{&xq~O%z,[Og&zaz&za~O{#{Og&zaz&za~OV*SOa*TO%q*UO%uWOg&ya~Oz-hOg&ya~O$S-lO~OV$}Oa$}Oo0cOv0qO~P'vOo0cOv0qO{-mOz$li!W$li~P'vOo0cOv0qOz$li!W$li~P'vO{-mOz$li!W$li~Oo0cOv0qO{*gO~P'vOo0cOv0qO{*gO!W&Xq~P'vOz-pO!W&Xq~Oo0cOv0qOz-pO!W&Xq~P'vOs-sO!T%dO!U%cOg&Oq!W&Oq![&Oqz&Oq~P!/jOa+QOo0cOv0qO![&Ty~P'vOz$ji![$ji~P%SOa+QOo0cOv0qO~P'vOV+UOo0cOv0qO~P'vOV+UOo0cOv0qO{&lq![&lq!m&lq%z&lq~P'vO{(kO![-xO!m-yO%z-wO~OV&OOo0cOv0qO#g%hq%[%hq%_%hq%z%hq~P'vO%uWO#g&ry%[&ry%_&ryg&ry~OV)`Oa)`O%uWO!W&ui~Ot-}OP#m!RV#m!Rf#m!Rh#m!Ro#m!Rs#m!Rv#m!R!P#m!R!Q#m!R!T#m!R!U#m!R!X#m!R!]#m!R!h#m!R!r#m!R!s#m!R!t#m!R!{#m!R!}#m!R#P#m!R#R#m!R#T#m!R#X#m!R#Z#m!R#^#m!R#_#m!R#a#m!R#c#m!R#l#m!R#o#m!R#s#m!R#u#m!R#z#m!R#}#m!R$P#m!R%X#m!R%o#m!R%p#m!R%t#m!R%u#m!R&Z#m!R&[#m!R&]#m!R&^#m!R&_#m!R&`#m!R&a#m!R&b#m!R&c#m!R&d#m!R&e#m!R&f#m!R&g#m!R&h#m!R&i#m!R&j#m!R%Z#m!R%_#m!R~Oo0cOv0qO{&xy~P'vOV*SOa*TO%q*UO%uWOg&yi~O$S-lO%Z.VO%_.VO~OV.aOh._O!X.^O!].`O!h.YO!s.[O!t.[O%p.XO%uWO&Z]O&[]O&]]O&^]O&_]O&`]O&a]O&b]O~Oo0cOv0qOz$lq!W$lq~P'vO{.fOz$lq!W$lq~Oo0cOv0qO{*gO!W&Xy~P'vOz.gO!W&Xy~Oo0cOv.kO~P'vOs-sO!T%dO!U%cOg&Oy!W&Oy![&Oyz&Oy~P!/jO{(kO![.nO~O{(kO![.nO!m.oO~OV*SOa*TO%q*UO%uWO~Oh.tO!f.rOz$TX#[$TX%j$TXg$TX~Os$TX{$TX!W$TX![$TX~P$-bO%o.vO%p.vOs$UXz$UX{$UX#[$UX%j$UX!W$UXg$UX![$UX~O!h.xO~Oz.|O#[/OO%j.yOs&|X{&|X!W&|Xg&|X~Oa/RO~P$)zOh.tOs&}Xz&}X{&}X#[&}X%j&}X!W&}Xg&}X![&}X~Os/VO{$jO~Oo0cOv0qOz$ly!W$ly~P'vOo0cOv0qO{*gO!W&X!R~P'vOz/ZO!W&X!R~Og&RXs&RX!T&RX!U&RX!W&RX![&RXz&RX~P!/jOs-sO!T%dO!U%cOg&Qa!W&Qa![&Qaz&Qa~O{(kO![/^O~O!f.rOh$[as$[az$[a{$[a#[$[a%j$[a!W$[ag$[a![$[a~O!h/eO~O%o.vO%p.vOs$Uaz$Ua{$Ua#[$Ua%j$Ua!W$Uag$Ua![$Ua~O%j.yOs$Yaz$Ya{$Ya#[$Ya!W$Yag$Ya![$Ya~Os&|a{&|a!W&|ag&|a~P$)nOz/jOs&|a{&|a!W&|ag&|a~O!W/mO~Og/mO~O{/oO~O![/pO~Oo0cOv0qO{*gO!W&X!Z~P'vO{/sO~O%z/tO~P$-bOz/uO#[/OO%j.yOg'PX~Oz/uOg'PX~Og/wO~O!h/xO~O#[/OOs%Saz%Sa{%Sa%j%Sa!W%Sag%Sa![%Sa~O#[/OO%j.yOs%Waz%Wa{%Wa!W%Wag%Wa~Os&|i{&|i!W&|ig&|i~P$)nOz/zO#[/OO%j.yO!['Oa~Og'Pa~P$)nOz0SOg'Pa~Oa0UO!['Oi~P$)zOz0WO!['Oi~Oz0WO#[/OO%j.yO!['Oi~O#[/OO%j.yOg$biz$bi~O%z0ZO~P$-bO#[/OO%j.yOg%Vaz%Va~Og'Pi~P$)nO{0^O~Oa0UO!['Oq~P$)zOz0`O!['Oq~O#[/OO%j.yOz%Ui![%Ui~Oa0UO~P$)zOa0UO!['Oy~P$)zO#[/OO%j.yOg$ciz$ci~O#[/OO%j.yOz%Uq![%Uq~Oz+aO#g%ha%[%ha%_%ha%z%ha~P%SOV&OOo0cOv0qO~P'vOn0hO~Oo0hO~P'vO{0iO~Ot0jO~P!/jO&]&Z&j&h&i&g&f&d&e&c&b&`&a&_&^&[%u~",goto:"!=j'QPPPPPP'RP'Z*s+[+t,_,y-fP.SP'Z.r.r'ZPPP'Z2[PPPPPP2[5PPP5PP7b7k=sPP=v>h>kPP'Z'ZPP>zPP'Z'ZPP'Z'Z'Z'Z'Z?O?w'ZP?zP@QDXGuGyPG|HWH['ZPPPH_Hk'RP'R'RP'RP'RP'RP'RP'R'R'RP'RPP'RPP'RP'RPHqH}IVPI^IdPI^PI^I^PPPI^PKrPK{LVL]KrPI^LfPI^PLmLsPLwM]MzNeLwLwNkNxLwLwLwLw! ^! d! g! l! o! y!!P!!]!!o!!u!#P!#V!#s!#y!$P!$Z!$a!$g!$y!%T!%Z!%a!%k!%q!%w!%}!&T!&Z!&e!&k!&u!&{!'U!'[!'k!'s!'}!(UPPPPPPPPPPP!([!(_!(e!(n!(x!)TPPPPPPPPPPPP!-u!/Z!3^!6oPP!6w!7W!7a!8Y!8P!8c!8i!8l!8o!8r!8z!9jPPPPPPPPPPPPPPPPP!9m!9q!9wP!:]!:a!:m!:v!;S!;j!;m!;p!;v!;|!<S!<VP!<_!<h!=d!=g]eOn#g$j)t,P'}`OTYZ[adnoprtxy}!P!Q!R!U!X!c!d!e!f!g!h!i!k!o!p!q!s!t!z#O#S#T#[#d#g#x#y#{#}$Q$e$g$h$j$q$}%S%Z%^%`%c%g%l%n%w%|&O&Z&_&h&j&k&u&x&|'P'W'Z'l'm'p'r's'w'|(O(S(W(](^(d(g(p(r(z(})^)e)g)k)l)p)t)z*O*Y*d*g*h*k*q*r*t*v*y*z*}+Q+U+V+Y+a+c+d+k+x+y,P,X,Y,],g,h,i,k,l,o,q,s,u,w,y,z-O-d-f-m-p-s.f.g/V/Z/s0c0d0e0f0h0i0j0k0l0n0r{!cQ#c#p$R$d$p%e%j%p%q&`'O'g(q(|)j*o*x+w,v0g}!dQ#c#p$R$d$p$u%e%j%p%q&`'O'g(q(|)j*o*x+w,v0g!P!eQ#c#p$R$d$p$u$v%e%j%p%q&`'O'g(q(|)j*o*x+w,v0g!R!fQ#c#p$R$d$p$u$v$w%e%j%p%q&`'O'g(q(|)j*o*x+w,v0g!T!gQ#c#p$R$d$p$u$v$w$x%e%j%p%q&`'O'g(q(|)j*o*x+w,v0g!V!hQ#c#p$R$d$p$u$v$w$x$y%e%j%p%q&`'O'g(q(|)j*o*x+w,v0g!Z!hQ!n#c#p$R$d$p$u$v$w$x$y$z%e%j%p%q&`'O'g(q(|)j*o*x+w,v0g'}TOTYZ[adnoprtxy}!P!Q!R!U!X!c!d!e!f!g!h!i!k!o!p!q!s!t!z#O#S#T#[#d#g#x#y#{#}$Q$e$g$h$j$q$}%S%Z%^%`%c%g%l%n%w%|&O&Z&_&h&j&k&u&x&|'P'W'Z'l'm'p'r's'w'|(O(S(W(](^(d(g(p(r(z(})^)e)g)k)l)p)t)z*O*Y*d*g*h*k*q*r*t*v*y*z*}+Q+U+V+Y+a+c+d+k+x+y,P,X,Y,],g,h,i,k,l,o,q,s,u,w,y,z-O-d-f-m-p-s.f.g/V/Z/s0c0d0e0f0h0i0j0k0l0n0r&eVOYZ[dnprxy}!P!Q!U!i!k!o!p!q!s!t#[#d#g#y#{#}$Q$h$j$}%S%Z%^%`%g%l%n%w%|&Z&_&j&k&u&x'P'W'Z'l'm'p'r's'w(O(W(^(d(g(p(r(z)^)e)g)p)t)z*O*Y*d*g*h*k*q*r*t*v*y*z*}+U+V+Y+a+d+k,P,X,Y,],g,h,i,k,l,o,q,s,u,w,y,z-O-d-f-m-p-s.f.g/V/Z/s0c0d0e0f0h0i0j0k0n0r%oXOYZ[dnrxy}!P!Q!U!i!k#[#d#g#y#{#}$Q$h$j$}%S%^%`%g%l%n%w%|&Z&_&j&k&u&x'P'W'Z'l'm'p'r's'w(O(W(^(d(g(p(r(z)^)e)g)p)t)z*O*Y*d*g*h*k*q*t*v*y*z*}+U+V+Y+a+d+k,P,X,Y,],g,h,i,k,l,o,s,u,w,y,z-O-d-f-m-p.f.g/V/Z0i0j0kQ#vqQ/[.kR0o0q't`OTYZ[adnoprtxy}!P!Q!R!U!X!c!d!e!f!g!h!k!o!p!q!s!t!z#O#S#T#[#d#g#x#y#{#}$Q$e$g$h$j$q$}%S%Z%^%`%c%g%l%n%w%|&O&Z&_&h&j&k&u&x&|'P'W'Z'l'p'r's'w'|(O(S(W(](^(d(g(p(r(z(})^)e)g)k)l)p)t)z*O*Y*g*h*k*q*r*t*v*y*z*}+Q+U+V+Y+a+c+d+k+x+y,P,X,Y,],h,i,k,l,o,q,s,u,w,y,z-O-d-f-m-p-s.f.g/V/Z/s0c0d0e0f0h0i0j0k0l0n0rh#jhz{$W$Z&l&q)S)X+f+g-RW#rq&].k0qQ$]|Q$a!OQ$n!VQ$o!WW$|!i'm*d,gS&[#s#tQ'S$iQ(s&UQ)U&nU)Y&s)Z+jW)a&w+m-T-{Q*Q']W*R'_,`-h.TQ+l)`S,_*S*TQ-Q+eQ-_,TQ-c,WQ.R-al.W-l.^._.a.z.|/R/j/o/t/y0U0Z0^Q/S.`Q/a.tQ/l/OU0P/u0S0[X0V/z0W0_0`R&Z#r!_!wYZ!P!Q!k%S%`%g'p'r's(O(W)g*g*h*k*q*t*v,h,i,k,l,o-m-p.f.g/ZR%^!vQ!{YQ%x#[Q&d#}Q&g$QR,{+YT.j-s/s!Y!jQ!n#c#p$R$d$p$u$v$w$x$y$z%e%j%p%q&`'O'g(q(|)j*o*x+w,v0gQ&X#kQ'c$oR*^'dR'l$|Q%V!mR/_.r'|_OTYZ[adnoprtxy}!P!Q!R!U!X!c!d!e!f!g!h!i!k!o!p!q!s!t!z#O#S#T#[#d#g#x#y#{#}$Q$e$g$h$j$q$}%S%Z%^%`%c%g%l%n%w%|&O&Z&_&h&j&k&u&x&|'P'W'Z'l'm'p'r's'w'|(O(S(W(](^(d(g(p(r(z(})^)e)g)k)l)p)t)z*O*Y*d*g*h*k*q*r*t*v*y*z*}+Q+U+V+Y+a+c+d+k+x+y,P,X,Y,],g,h,i,k,l,o,q,s,u,w,y,z-O-d-f-m-p-s.f.g/V/Z/s0c0d0e0f0h0i0j0k0l0n0rS#a_#b!P.[-l.^._.`.a.t.z.|/R/j/o/t/u/y/z0S0U0W0Z0[0^0_0`'|_OTYZ[adnoprtxy}!P!Q!R!U!X!c!d!e!f!g!h!i!k!o!p!q!s!t!z#O#S#T#[#d#g#x#y#{#}$Q$e$g$h$j$q$}%S%Z%^%`%c%g%l%n%w%|&O&Z&_&h&j&k&u&x&|'P'W'Z'l'm'p'r's'w'|(O(S(W(](^(d(g(p(r(z(})^)e)g)k)l)p)t)z*O*Y*d*g*h*k*q*r*t*v*y*z*}+Q+U+V+Y+a+c+d+k+x+y,P,X,Y,],g,h,i,k,l,o,q,s,u,w,y,z-O-d-f-m-p-s.f.g/V/Z/s0c0d0e0f0h0i0j0k0l0n0rT#a_#bT#^^#_R(o%xa(l%x(n(o+`,{-y-z.oT+[(k+]R-z,{Q$PsQ+l)aQ,^*RR-e,_X#}s$O$P&fQ&y$aQ'a$nQ'd$oR)s'SQ)b&wV-S+m-T-{ZgOn$j)t,PXkOn)t,PQ$k!TQ&z$bQ&{$cQ'^$mQ'b$oQ)q'RQ)x'WQ){'XQ)|'YQ*Z'`S*]'c'dQ+s)gQ+u)hQ+v)iQ+z)oS+|)r*[Q,Q)vQ,R)wS,S)y)zQ,d*^Q-V+rQ-W+tQ-Y+{S-Z+},OQ-`,UQ-b,VQ-|-XQ.O-[Q.P-^Q.Q-_Q.p-}Q.q.RQ/W.dR/r/XWkOn)t,PR#mjQ'`$nS)r'S'aR,O)sQ,]*RR-f,^Q*['`Q+})rR-[,OZiOjn)t,PQ'f$pR*`'gT-j,e-ku.c-l.^._.a.t.z.|/R/j/o/t/u/y0S0U0Z0[0^t.c-l.^._.a.t.z.|/R/j/o/t/u/y0S0U0Z0[0^Q/S.`X0V/z0W0_0`!P.Z-l.^._.`.a.t.z.|/R/j/o/t/u/y/z0S0U0W0Z0[0^0_0`Q.w.YR/f.xg.z.].{/b/i/n/|0O0Q0]0a0bu.b-l.^._.a.t.z.|/R/j/o/t/u/y0S0U0Z0[0^X.u.W.b/a0PR/c.tV0R/u0S0[R/X.dQnOS#on,PR,P)tQ&^#uR(x&^S%m#R#wS(_%m(bT(b%p&`Q%a!yQ%h!}W(P%a%h(U(YQ(U%eR(Y%jQ&i$RR)O&iQ(e%qQ*{(`T+R(e*{Q'n%OR*e'nS'q%R%SY*i'q*j,m-q.hU*j'r's'tU,m*k*l*mS-q,n,oR.h-rQ#Y]R%t#YQ#_^R%y#_Q(h%vS+W(h+XR+X(iQ+](kR,|+]Q#b_R%{#bQ#ebQ%}#cW&Q#e%}({+bQ({&cR+b0gQ$OsS&e$O&fR&f$PQ&v$_R)_&vQ&V#jR(t&VQ&m$VS)T&m+hR+h)UQ$Z{R&p$ZQ&t$]R)[&tQ+n)bR-U+nQ#hfR&S#hQ)f&zR+q)fQ&}$dS)m&})nR)n'OQ'V$kR)u'VQ'[$lS*P'[,ZR,Z*QQ,a*VR-i,aWjOn)t,PR#ljQ-k,eR.U-kd.{.]/b/i/n/|0O0Q0]0a0bR/h.{U.s.W/a0PR/`.sQ/{/nS0X/{0YR0Y/|S/v/b/cR0T/vQ.}.]R/k.}R!ZPXmOn)t,PWlOn)t,PR'T$jYfOn$j)t,PR&R#g[sOn#g$j)t,PR&d#}&dQOYZ[dnprxy}!P!Q!U!i!k!o!p!q!s!t#[#d#g#y#{#}$Q$h$j$}%S%Z%^%`%g%l%n%w%|&Z&_&j&k&u&x'P'W'Z'l'm'p'r's'w(O(W(^(d(g(p(r(z)^)e)g)p)t)z*O*Y*d*g*h*k*q*r*t*v*y*z*}+U+V+Y+a+d+k,P,X,Y,],g,h,i,k,l,o,q,s,u,w,y,z-O-d-f-m-p-s.f.g/V/Z/s0c0d0e0f0h0i0j0k0n0rQ!nTQ#caQ#poU$Rt%c(SS$d!R$gQ$p!XQ$u!cQ$v!dQ$w!eQ$x!fQ$y!gQ$z!hQ%e!zQ%j#OQ%p#SQ%q#TQ&`#xQ'O$eQ'g$qQ(q&OU(|&h(}+cW)j&|)l+x+yQ*o'|Q*x(]Q+w)kQ,v+QR0g0lQ!yYQ!}ZQ$b!PQ$c!QQ%R!kQ't%S^'{%`%g(O(W*q*t*v^*f'p*h,k,l-p.g/ZQ*l'rQ*m'sQ+t)gQ,j*gQ,n*kQ-n,hQ-o,iQ-r,oQ.e-mR/Y.f[bOn#g$j)t,P!^!vYZ!P!Q!k%S%`%g'p'r's(O(W)g*g*h*k*q*t*v,h,i,k,l,o-m-p.f.g/ZQ#R[Q#fdS#wrxQ$UyW$_}$Q'P)pS$l!U$hW${!i'm*d,gS%v#[+Y`&P#d%|(p(r(z+a-O0kQ&a#yQ&b#{Q&c#}Q'j$}Q'z%^W([%l(^*y*}Q(`%nQ(i%wQ(v&ZS(y&_0iQ)P&jQ)Q&kU)]&u)^+kQ)d&xQ)y'WY)}'Z*O,X,Y-dQ*b'lS*n'w0jW+P(d*z,s,wW+T(g+V,y,zQ+p)eQ,U)zQ,c*YQ,x+UQ-P+dQ-e,]Q-v,uQ.S-fR/q/VhUOn#d#g$j%|&_'w(p(r)t,P%U!uYZ[drxy}!P!Q!U!i!k#[#y#{#}$Q$h$}%S%^%`%g%l%n%w&Z&j&k&u&x'P'W'Z'l'm'p'r's(O(W(^(d(g(z)^)e)g)p)z*O*Y*d*g*h*k*q*t*v*y*z*}+U+V+Y+a+d+k,X,Y,],g,h,i,k,l,o,s,u,w,y,z-O-d-f-m-p.f.g/V/Z0i0j0kQ#qpW%W!o!s0d0nQ%X!pQ%Y!qQ%[!tQ%f0cS'v%Z0hQ'x0eQ'y0fQ,p*rQ-u,qS.i-s/sR0p0rU#uq.k0qR(w&][cOn#g$j)t,PZ!xY#[#}$Q+YQ#W[Q#zrR$TxQ%b!yQ%i!}Q%o#RQ'j${Q(V%eQ(Z%jQ(c%pQ(f%qQ*|(`Q,f*bQ-t,pQ.m-uR/].lQ$StQ(R%cR*s(SQ.l-sR/}/sR#QZR#V[R%Q!iQ%O!iV*c'm*d,g!Z!lQ!n#c#p$R$d$p$u$v$w$x$y$z%e%j%p%q&`'O'g(q(|)j*o*x+w,v0gR%T!kT#]^#_Q%x#[R,{+YQ(m%xS+_(n(oQ,}+`Q-x,{S.n-y-zR/^.oT+Z(k+]Q$`}Q&g$QQ)o'PR+{)pQ$XzQ)W&qR+i)XQ$XzQ&o$WQ)W&qR+i)XQ#khW$Vz$W&q)XQ$[{Q&r$ZZ)R&l)S+f+g-RR$^|R)c&wXlOn)t,PQ$f!RR'Q$gQ$m!UR'R$hR*X'_Q*V'_V-g,`-h.TQ.d-lQ/P.^R/Q._U.]-l.^._Q/U.aQ/b.tQ/g.zU/i.|/j/yQ/n/RQ/|/oQ0O/tU0Q/u0S0[Q0]0UQ0a0ZR0b0^R/T.`R/d.t",nodeNames:"⚠ print Escape { Comment Script AssignStatement * BinaryExpression BitOp BitOp BitOp BitOp ArithOp ArithOp @ ArithOp ** UnaryExpression ArithOp BitOp AwaitExpression await ) ( ParenthesizedExpression BinaryExpression or and CompareOp in not is UnaryExpression ConditionalExpression if else LambdaExpression lambda ParamList VariableName AssignOp , : NamedExpression AssignOp YieldExpression yield from TupleExpression ComprehensionExpression async for LambdaExpression ] [ ArrayExpression ArrayComprehensionExpression } { DictionaryExpression DictionaryComprehensionExpression SetExpression SetComprehensionExpression CallExpression ArgList AssignOp MemberExpression . PropertyName Number String FormatString FormatReplacement FormatSelfDoc FormatConversion FormatSpec FormatReplacement FormatSelfDoc ContinuedString Ellipsis None Boolean TypeDef AssignOp UpdateStatement UpdateOp ExpressionStatement DeleteStatement del PassStatement pass BreakStatement break ContinueStatement continue ReturnStatement return YieldStatement PrintStatement RaiseStatement raise ImportStatement import as ScopeStatement global nonlocal AssertStatement assert TypeDefinition type TypeParamList TypeParam StatementGroup ; IfStatement Body elif WhileStatement while ForStatement TryStatement try except finally WithStatement with FunctionDefinition def ParamList AssignOp TypeDef ClassDefinition class DecoratedStatement Decorator At MatchStatement match MatchBody MatchClause case CapturePattern LiteralPattern ArithOp ArithOp AsPattern OrPattern LogicOp AttributePattern SequencePattern MappingPattern StarPattern ClassPattern PatternArgList KeywordPattern KeywordPattern Guard",maxTerm:277,context:sqn,nodeProps:[["isolate",-5,4,71,72,73,77,""],["group",-15,6,85,87,88,90,92,94,96,98,99,100,102,105,108,110,"Statement Statement",-22,8,18,21,25,40,49,50,56,57,60,61,62,63,64,67,70,71,72,79,80,81,82,"Expression",-10,114,116,119,121,122,126,128,133,135,138,"Statement",-9,143,144,147,148,150,151,152,153,154,"Pattern"],["openedBy",23,"(",54,"[",58,"{"],["closedBy",24,")",55,"]",59,"}"]],propSources:[lqn],skippedNodes:[0,4],repeatNodeCount:34,tokenData:"!2|~R!`OX%TXY%oY[%T[]%o]p%Tpq%oqr'ars)Yst*xtu%Tuv,dvw-hwx.Uxy/tyz0[z{0r{|2S|}2p}!O3W!O!P4_!P!Q:Z!Q!R;k!R![>_![!]Do!]!^Es!^!_FZ!_!`Gk!`!aHX!a!b%T!b!cIf!c!dJU!d!eK^!e!hJU!h!i!#f!i!tJU!t!u!,|!u!wJU!w!x!.t!x!}JU!}#O!0S#O#P&o#P#Q!0j#Q#R!1Q#R#SJU#S#T%T#T#UJU#U#VK^#V#YJU#Y#Z!#f#Z#fJU#f#g!,|#g#iJU#i#j!.t#j#oJU#o#p!1n#p#q!1s#q#r!2a#r#s!2f#s$g%T$g;'SJU;'S;=`KW<%lOJU`%YT&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%T`%lP;=`<%l%To%v]&n`%c_OX%TXY%oY[%T[]%o]p%Tpq%oq#O%T#O#P&o#P#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%To&tX&n`OY%TYZ%oZ]%T]^%o^#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tc'f[&n`O!_%T!_!`([!`#T%T#T#U(r#U#f%T#f#g(r#g#h(r#h#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tc(cTmR&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tc(yT!mR&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk)aV&n`&[ZOr%Trs)vs#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk){V&n`Or%Trs*bs#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk*iT&n`&^ZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%To+PZS_&n`OY*xYZ%TZ]*x]^%T^#o*x#o#p+r#p#q*x#q#r+r#r;'S*x;'S;=`,^<%lO*x_+wTS_OY+rZ]+r^;'S+r;'S;=`,W<%lO+r_,ZP;=`<%l+ro,aP;=`<%l*xj,kV%rQ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tj-XT!xY&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tj-oV%lQ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk.]V&n`&ZZOw%Twx.rx#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk.wV&n`Ow%Twx/^x#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk/eT&n`&]ZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk/{ThZ&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tc0cTgR&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk0yXVZ&n`Oz%Tz{1f{!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk1mVaR&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk2ZV%oZ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tc2wTzR&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%To3_W%pZ&n`O!_%T!_!`-Q!`!a3w!a#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Td4OT&{S&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk4fX!fQ&n`O!O%T!O!P5R!P!Q%T!Q![6T![#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk5WV&n`O!O%T!O!P5m!P#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk5tT!rZ&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti6[a!hX&n`O!Q%T!Q![6T![!g%T!g!h7a!h!l%T!l!m9s!m#R%T#R#S6T#S#X%T#X#Y7a#Y#^%T#^#_9s#_#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti7fZ&n`O{%T{|8X|}%T}!O8X!O!Q%T!Q![8s![#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti8^V&n`O!Q%T!Q![8s![#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti8z]!hX&n`O!Q%T!Q![8s![!l%T!l!m9s!m#R%T#R#S8s#S#^%T#^#_9s#_#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti9zT!hX&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk:bX%qR&n`O!P%T!P!Q:}!Q!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tj;UV%sQ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti;ro!hX&n`O!O%T!O!P=s!P!Q%T!Q![>_![!d%T!d!e?q!e!g%T!g!h7a!h!l%T!l!m9s!m!q%T!q!rA]!r!z%T!z!{Bq!{#R%T#R#S>_#S#U%T#U#V?q#V#X%T#X#Y7a#Y#^%T#^#_9s#_#c%T#c#dA]#d#l%T#l#mBq#m#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti=xV&n`O!Q%T!Q![6T![#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti>fc!hX&n`O!O%T!O!P=s!P!Q%T!Q![>_![!g%T!g!h7a!h!l%T!l!m9s!m#R%T#R#S>_#S#X%T#X#Y7a#Y#^%T#^#_9s#_#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti?vY&n`O!Q%T!Q!R@f!R!S@f!S#R%T#R#S@f#S#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Ti@mY!hX&n`O!Q%T!Q!R@f!R!S@f!S#R%T#R#S@f#S#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TiAbX&n`O!Q%T!Q!YA}!Y#R%T#R#SA}#S#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TiBUX!hX&n`O!Q%T!Q!YA}!Y#R%T#R#SA}#S#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TiBv]&n`O!Q%T!Q![Co![!c%T!c!iCo!i#R%T#R#SCo#S#T%T#T#ZCo#Z#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TiCv]!hX&n`O!Q%T!Q![Co![!c%T!c!iCo!i#R%T#R#SCo#S#T%T#T#ZCo#Z#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%ToDvV{_&n`O!_%T!_!`E]!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TcEdT%{R&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TkEzT#gZ&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TkFbXmR&n`O!^%T!^!_F}!_!`([!`!a([!a#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TjGUV%mQ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TkGrV%zZ&n`O!_%T!_!`([!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TkH`WmR&n`O!_%T!_!`([!`!aHx!a#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TjIPV%nQ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TkIoV_Q#}P&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%ToJ_]&n`&YS%uZO!Q%T!Q![JU![!c%T!c!}JU!}#R%T#R#SJU#S#T%T#T#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUoKZP;=`<%lJUoKge&n`&YS%uZOr%Trs)Ysw%Twx.Ux!Q%T!Q![JU![!c%T!c!tJU!t!uLx!u!}JU!}#R%T#R#SJU#S#T%T#T#fJU#f#gLx#g#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUoMRa&n`&YS%uZOr%TrsNWsw%Twx! vx!Q%T!Q![JU![!c%T!c!}JU!}#R%T#R#SJU#S#T%T#T#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUkN_V&n`&`ZOr%TrsNts#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%TkNyV&n`Or%Trs! `s#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk! gT&n`&bZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk! }V&n`&_ZOw%Twx!!dx#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!!iV&n`Ow%Twx!#Ox#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!#VT&n`&aZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%To!#oe&n`&YS%uZOr%Trs!%Qsw%Twx!&px!Q%T!Q![JU![!c%T!c!tJU!t!u!(`!u!}JU!}#R%T#R#SJU#S#T%T#T#fJU#f#g!(`#g#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUk!%XV&n`&dZOr%Trs!%ns#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!%sV&n`Or%Trs!&Ys#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!&aT&n`&fZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!&wV&n`&cZOw%Twx!'^x#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!'cV&n`Ow%Twx!'xx#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!(PT&n`&eZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%To!(ia&n`&YS%uZOr%Trs!)nsw%Twx!+^x!Q%T!Q![JU![!c%T!c!}JU!}#R%T#R#SJU#S#T%T#T#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUk!)uV&n`&hZOr%Trs!*[s#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!*aV&n`Or%Trs!*vs#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!*}T&n`&jZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!+eV&n`&gZOw%Twx!+zx#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!,PV&n`Ow%Twx!,fx#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tk!,mT&n`&iZO#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%To!-Vi&n`&YS%uZOr%TrsNWsw%Twx! vx!Q%T!Q![JU![!c%T!c!dJU!d!eLx!e!hJU!h!i!(`!i!}JU!}#R%T#R#SJU#S#T%T#T#UJU#U#VLx#V#YJU#Y#Z!(`#Z#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUo!.}a&n`&YS%uZOr%Trs)Ysw%Twx.Ux!Q%T!Q![JU![!c%T!c!}JU!}#R%T#R#SJU#S#T%T#T#oJU#p#q%T#r$g%T$g;'SJU;'S;=`KW<%lOJUk!0ZT!XZ&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tc!0qT!WR&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%Tj!1XV%kQ&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%T~!1sO!]~k!1zV%jR&n`O!_%T!_!`-Q!`#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%T~!2fO![~i!2mT%tX&n`O#o%T#p#q%T#r;'S%T;'S;=`%i<%lO%T",tokenizers:[iqn,tqn,eqn,aqn,0,1,2,3,4],topRules:{Script:[0,5]},specialized:[{term:221,get:e=>cqn[e]||-1}],tokenPrec:7668}),oMe=new b0e,ypt=new Set(["Script","Body","FunctionDefinition","ClassDefinition","LambdaExpression","ForStatement","MatchClause"]);function fB(e){return(t,n,r)=>{if(r)return!1;let s=t.node.getChild("VariableName");return s&&n(s,e),!0}}const uqn={FunctionDefinition:fB("function"),ClassDefinition:fB("class"),ForStatement(e,t,n){if(n){for(let r=e.node.firstChild;r;r=r.nextSibling)if(r.name=="VariableName")t(r,"variable");else if(r.name=="in")break}},ImportStatement(e,t){var n,r;let{node:s}=e,a=((n=s.firstChild)===null||n===void 0?void 0:n.name)=="from";for(let o=s.getChild("import");o;o=o.nextSibling)o.name=="VariableName"&&((r=o.nextSibling)===null||r===void 0?void 0:r.name)!="as"&&t(o,a?"variable":"namespace")},AssignStatement(e,t){for(let n=e.node.firstChild;n;n=n.nextSibling)if(n.name=="VariableName")t(n,"variable");else if(n.name==":"||n.name=="AssignOp")break},ParamList(e,t){for(let n=null,r=e.node.firstChild;r;r=r.nextSibling)r.name=="VariableName"&&(!n||!/\*|AssignOp/.test(n.name))&&t(r,"variable"),n=r},CapturePattern:fB("variable"),AsPattern:fB("variable"),__proto__:null};function vpt(e,t){let n=oMe.get(t);if(n)return n;let r=[],s=!0;function a(o,l){let c=e.sliceString(o.from,o.to);r.push({label:c,type:l})}return t.cursor(Ao.IncludeAnonymous).iterate(o=>{if(o.name){let l=uqn[o.name];if(l&&l(o,a,s)||!s&&ypt.has(o.name))return!1;s=!1}else if(o.to-o.from>8192){for(let l of vpt(e,o.node))r.push(l);return!1}}),oMe.set(t,r),r}const lMe=/^[\w\xa1-\uffff][\w\d\xa1-\uffff]*$/,wpt=["String","FormatString","Comment","PropertyName"];function kpt(e){let t=Ha(e.state).resolveInner(e.pos,-1);if(wpt.indexOf(t.name)>-1)return null;let n=t.name=="VariableName"||t.to-t.from<20&&lMe.test(e.state.sliceDoc(t.from,t.to));if(!n&&!e.explicit)return null;let r=[];for(let s=t;s;s=s.parent)ypt.has(s.name)&&(r=r.concat(vpt(e.state.doc,s)));return{options:r,from:n?t.from:e.pos,validFor:lMe}}const fqn=["__annotations__","__builtins__","__debug__","__doc__","__import__","__name__","__loader__","__package__","__spec__","False","None","True"].map(e=>({label:e,type:"constant"})).concat(["ArithmeticError","AssertionError","AttributeError","BaseException","BlockingIOError","BrokenPipeError","BufferError","BytesWarning","ChildProcessError","ConnectionAbortedError","ConnectionError","ConnectionRefusedError","ConnectionResetError","DeprecationWarning","EOFError","Ellipsis","EncodingWarning","EnvironmentError","Exception","FileExistsError","FileNotFoundError","FloatingPointError","FutureWarning","GeneratorExit","IOError","ImportError","ImportWarning","IndentationError","IndexError","InterruptedError","IsADirectoryError","KeyError","KeyboardInterrupt","LookupError","MemoryError","ModuleNotFoundError","NameError","NotADirectoryError","NotImplemented","NotImplementedError","OSError","OverflowError","PendingDeprecationWarning","PermissionError","ProcessLookupError","RecursionError","ReferenceError","ResourceWarning","RuntimeError","RuntimeWarning","StopAsyncIteration","StopIteration","SyntaxError","SyntaxWarning","SystemError","SystemExit","TabError","TimeoutError","TypeError","UnboundLocalError","UnicodeDecodeError","UnicodeEncodeError","UnicodeError","UnicodeTranslateError","UnicodeWarning","UserWarning","ValueError","Warning","ZeroDivisionError"].map(e=>({label:e,type:"type"}))).concat(["bool","bytearray","bytes","classmethod","complex","float","frozenset","int","list","map","memoryview","object","range","set","staticmethod","str","super","tuple","type"].map(e=>({label:e,type:"class"}))).concat(["abs","aiter","all","anext","any","ascii","bin","breakpoint","callable","chr","compile","delattr","dict","dir","divmod","enumerate","eval","exec","exit","filter","format","getattr","globals","hasattr","hash","help","hex","id","input","isinstance","issubclass","iter","len","license","locals","max","min","next","oct","open","ord","pow","print","property","quit","repr","reversed","round","setattr","slice","sorted","sum","vars","zip"].map(e=>({label:e,type:"function"}))),mqn=[xc("def ${name}(${params}):\n ${}",{label:"def",detail:"function",type:"keyword"}),xc("for ${name} in ${collection}:\n ${}",{label:"for",detail:"loop",type:"keyword"}),xc("while ${}:\n ${}",{label:"while",detail:"loop",type:"keyword"}),xc("try:\n ${}\nexcept ${error}:\n ${}",{label:"try",detail:"/ except block",type:"keyword"}),xc(`if \${}:
1957
1957