@researai/deepscientist 1.5.15 → 1.5.17

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 (202) hide show
  1. package/README.md +385 -104
  2. package/bin/ds.js +1241 -110
  3. package/docs/en/00_QUICK_START.md +100 -19
  4. package/docs/en/01_SETTINGS_REFERENCE.md +34 -1
  5. package/docs/en/02_START_RESEARCH_GUIDE.md +7 -0
  6. package/docs/en/05_TUI_GUIDE.md +6 -0
  7. package/docs/en/06_RUNTIME_AND_CANVAS.md +4 -3
  8. package/docs/en/09_DOCTOR.md +25 -8
  9. package/docs/en/14_PROMPT_SKILLS_AND_MCP_GUIDE.md +63 -13
  10. package/docs/en/15_CODEX_PROVIDER_SETUP.md +37 -11
  11. package/docs/en/19_EXTERNAL_CONTROLLER_GUIDE.md +226 -0
  12. package/docs/en/19_LOCAL_BROWSER_AUTH.md +70 -0
  13. package/docs/en/20_WORKSPACE_MODES_GUIDE.md +250 -0
  14. package/docs/en/21_LOCAL_MODEL_BACKENDS_GUIDE.md +283 -0
  15. package/docs/en/91_DEVELOPMENT.md +237 -0
  16. package/docs/en/README.md +24 -2
  17. package/docs/zh/00_QUICK_START.md +89 -19
  18. package/docs/zh/01_SETTINGS_REFERENCE.md +34 -1
  19. package/docs/zh/02_START_RESEARCH_GUIDE.md +7 -0
  20. package/docs/zh/05_TUI_GUIDE.md +6 -0
  21. package/docs/zh/09_DOCTOR.md +26 -9
  22. package/docs/zh/14_PROMPT_SKILLS_AND_MCP_GUIDE.md +63 -13
  23. package/docs/zh/15_CODEX_PROVIDER_SETUP.md +37 -11
  24. package/docs/zh/19_EXTERNAL_CONTROLLER_GUIDE.md +226 -0
  25. package/docs/zh/19_LOCAL_BROWSER_AUTH.md +68 -0
  26. package/docs/zh/20_WORKSPACE_MODES_GUIDE.md +251 -0
  27. package/docs/zh/21_LOCAL_MODEL_BACKENDS_GUIDE.md +281 -0
  28. package/docs/zh/README.md +24 -2
  29. package/install.sh +46 -4
  30. package/package.json +2 -1
  31. package/pyproject.toml +1 -1
  32. package/src/deepscientist/__init__.py +1 -1
  33. package/src/deepscientist/acp/envelope.py +6 -0
  34. package/src/deepscientist/artifact/service.py +647 -22
  35. package/src/deepscientist/bash_exec/service.py +234 -9
  36. package/src/deepscientist/bridges/connectors.py +8 -2
  37. package/src/deepscientist/cli.py +115 -19
  38. package/src/deepscientist/codex_cli_compat.py +367 -22
  39. package/src/deepscientist/config/models.py +2 -1
  40. package/src/deepscientist/config/service.py +183 -13
  41. package/src/deepscientist/daemon/api/handlers.py +255 -31
  42. package/src/deepscientist/daemon/api/router.py +9 -0
  43. package/src/deepscientist/daemon/app.py +1146 -105
  44. package/src/deepscientist/diagnostics/__init__.py +6 -0
  45. package/src/deepscientist/diagnostics/runner_failures.py +130 -0
  46. package/src/deepscientist/doctor.py +207 -3
  47. package/src/deepscientist/gitops/__init__.py +10 -1
  48. package/src/deepscientist/gitops/diff.py +129 -0
  49. package/src/deepscientist/gitops/service.py +4 -1
  50. package/src/deepscientist/mcp/server.py +39 -0
  51. package/src/deepscientist/prompts/builder.py +275 -34
  52. package/src/deepscientist/quest/layout.py +15 -2
  53. package/src/deepscientist/quest/service.py +707 -55
  54. package/src/deepscientist/quest/stage_views.py +6 -1
  55. package/src/deepscientist/runners/codex.py +143 -43
  56. package/src/deepscientist/shared.py +19 -0
  57. package/src/deepscientist/skills/__init__.py +2 -2
  58. package/src/deepscientist/skills/installer.py +196 -5
  59. package/src/deepscientist/skills/registry.py +66 -0
  60. package/src/prompts/connectors/qq.md +18 -8
  61. package/src/prompts/connectors/weixin.md +16 -6
  62. package/src/prompts/contracts/shared_interaction.md +14 -2
  63. package/src/prompts/system.md +23 -5
  64. package/src/prompts/system_copilot.md +56 -0
  65. package/src/skills/analysis-campaign/SKILL.md +1 -0
  66. package/src/skills/baseline/SKILL.md +8 -0
  67. package/src/skills/decision/SKILL.md +8 -0
  68. package/src/skills/experiment/SKILL.md +8 -0
  69. package/src/skills/figure-polish/SKILL.md +1 -0
  70. package/src/skills/finalize/SKILL.md +1 -0
  71. package/src/skills/idea/SKILL.md +1 -0
  72. package/src/skills/intake-audit/SKILL.md +8 -0
  73. package/src/skills/mentor/SKILL.md +217 -0
  74. package/src/skills/mentor/references/correction-rules.md +210 -0
  75. package/src/skills/mentor/references/knowledge-profile.md +91 -0
  76. package/src/skills/mentor/references/persona-profile.md +138 -0
  77. package/src/skills/mentor/references/taste-profile.md +128 -0
  78. package/src/skills/mentor/references/thought-style-profile.md +138 -0
  79. package/src/skills/mentor/references/work-profile.md +289 -0
  80. package/src/skills/mentor/references/workflow-profile.md +240 -0
  81. package/src/skills/optimize/SKILL.md +1 -0
  82. package/src/skills/rebuttal/SKILL.md +1 -0
  83. package/src/skills/review/SKILL.md +1 -0
  84. package/src/skills/scout/SKILL.md +8 -0
  85. package/src/skills/write/SKILL.md +1 -0
  86. package/src/tui/dist/app/AppContainer.js +19 -11
  87. package/src/tui/dist/index.js +4 -1
  88. package/src/tui/dist/lib/api.js +33 -3
  89. package/src/tui/package.json +1 -1
  90. package/src/ui/dist/assets/AiManusChatView-Bv-Z8YpU.js +204 -0
  91. package/src/ui/dist/assets/AnalysisPlugin-BCKAfjba.js +1 -0
  92. package/src/ui/dist/assets/CliPlugin-BCKcpc35.js +109 -0
  93. package/src/ui/dist/assets/CodeEditorPlugin-DbOfSJ8K.js +2 -0
  94. package/src/ui/dist/assets/CodeViewerPlugin-CbaFRrUU.js +270 -0
  95. package/src/ui/dist/assets/DocViewerPlugin-DAjLVeQD.js +7 -0
  96. package/src/ui/dist/assets/GitCommitViewerPlugin-CIUqbUDO.js +1 -0
  97. package/src/ui/dist/assets/GitDiffViewerPlugin-CQACjoAA.js +6 -0
  98. package/src/ui/dist/assets/GitSnapshotViewer-0r4nLPke.js +30 -0
  99. package/src/ui/dist/assets/ImageViewerPlugin-nBOmI2v_.js +26 -0
  100. package/src/ui/dist/assets/LabCopilotPanel-BHxOxF4z.js +14 -0
  101. package/src/ui/dist/assets/LabPlugin-BKoZGs95.js +22 -0
  102. package/src/ui/dist/assets/LatexPlugin-ZwtV8pIp.js +25 -0
  103. package/src/ui/dist/assets/MarkdownViewerPlugin-DKqVfKyW.js +128 -0
  104. package/src/ui/dist/assets/MarketplacePlugin-BwxStZ9D.js +13 -0
  105. package/src/ui/dist/assets/NotebookEditor-BEQhaQbt.js +81 -0
  106. package/src/ui/dist/assets/{NotebookEditor-CccQYZjX.css → NotebookEditor-BHH8rdGj.css} +1 -1
  107. package/src/ui/dist/assets/NotebookEditor-BOr3x3Ej.css +1 -0
  108. package/src/ui/dist/assets/NotebookEditor-DB9N_T9q.js +361 -0
  109. package/src/ui/dist/assets/PdfLoader-Cy5jtWrr.css +1 -0
  110. package/src/ui/dist/assets/PdfLoader-eWBONbQP.js +16 -0
  111. package/src/ui/dist/assets/PdfMarkdownPlugin-D22YOZL3.js +1 -0
  112. package/src/ui/dist/assets/PdfViewerPlugin-c-RK9DLM.js +17 -0
  113. package/src/ui/dist/assets/PdfViewerPlugin-nwwE-fjJ.css +1 -0
  114. package/src/ui/dist/assets/SearchPlugin-CxF9ytAx.js +16 -0
  115. package/src/ui/dist/assets/SearchPlugin-DA4en4hK.css +1 -0
  116. package/src/ui/dist/assets/TextViewerPlugin-C5xqeeUH.js +54 -0
  117. package/src/ui/dist/assets/VNCViewer-BoLGLnHz.js +11 -0
  118. package/src/ui/dist/assets/bot-DREQOxzP.js +6 -0
  119. package/src/ui/dist/assets/browser-CTB2jwNe.js +8 -0
  120. package/src/ui/dist/assets/chevron-up-C9Qpx4DE.js +6 -0
  121. package/src/ui/dist/assets/code-WlFHE7z_.js +6 -0
  122. package/src/ui/dist/assets/file-content-BZMz3RYp.js +1 -0
  123. package/src/ui/dist/assets/file-diff-panel-CQhw0jS2.js +1 -0
  124. package/src/ui/dist/assets/file-jump-queue-DA-SdG__.js +1 -0
  125. package/src/ui/dist/assets/file-socket-CfQPKQKj.js +1 -0
  126. package/src/ui/dist/assets/git-commit-horizontal-DxZ8DCZh.js +6 -0
  127. package/src/ui/dist/assets/image-Bgl4VIyx.js +6 -0
  128. package/src/ui/dist/assets/index-BpV6lusQ.css +33 -0
  129. package/src/ui/dist/assets/index-CBNVuWcP.js +2496 -0
  130. package/src/ui/dist/assets/index-CwNu1aH4.js +11 -0
  131. package/src/ui/dist/assets/index-DrUnlf6K.js +1 -0
  132. package/src/ui/dist/assets/index-NW-h8VzN.js +1 -0
  133. package/src/ui/dist/assets/monaco-CiHMMNH_.js +1 -0
  134. package/src/ui/dist/assets/pdf-effect-queue-J8OnM0jE.js +6 -0
  135. package/src/ui/dist/assets/plugin-monaco-C8UgLomw.js +19 -0
  136. package/src/ui/dist/assets/plugin-notebook-HbW2K-1c.js +169 -0
  137. package/src/ui/dist/assets/plugin-pdf-CR8hgQBV.js +357 -0
  138. package/src/ui/dist/assets/plugin-terminal-MXFIPun8.js +227 -0
  139. package/src/ui/dist/assets/popover-CLc0pPP8.js +1 -0
  140. package/src/ui/dist/assets/project-sync-C9IdzdZW.js +1 -0
  141. package/src/ui/dist/assets/select-Cs2PmzwL.js +11 -0
  142. package/src/ui/dist/assets/sigma-ClKcHAXm.js +6 -0
  143. package/src/ui/dist/assets/trash-DwpbFr3w.js +11 -0
  144. package/src/ui/dist/assets/useCliAccess-NQ8m0Let.js +1 -0
  145. package/src/ui/dist/assets/useFileDiffOverlay-FuhcnKiw.js +1 -0
  146. package/src/ui/dist/assets/wrap-text-BC-Hltpd.js +11 -0
  147. package/src/ui/dist/assets/zoom-out-E_gaeAxL.js +11 -0
  148. package/src/ui/dist/index.html +5 -2
  149. package/src/ui/dist/assets/AiManusChatView-DDjbFnbt.js +0 -26597
  150. package/src/ui/dist/assets/AnalysisPlugin-Yb5IdmaU.js +0 -123
  151. package/src/ui/dist/assets/CliPlugin-e64sreyu.js +0 -31037
  152. package/src/ui/dist/assets/CodeEditorPlugin-C4D2TIkU.js +0 -427
  153. package/src/ui/dist/assets/CodeViewerPlugin-BVoNZIvC.js +0 -905
  154. package/src/ui/dist/assets/DocViewerPlugin-CLChbllo.js +0 -278
  155. package/src/ui/dist/assets/GitDiffViewerPlugin-C4xeFyFQ.js +0 -2661
  156. package/src/ui/dist/assets/ImageViewerPlugin-OiMUAcLi.js +0 -500
  157. package/src/ui/dist/assets/LabCopilotPanel-BjD2ThQF.js +0 -4104
  158. package/src/ui/dist/assets/LabPlugin-DQPg-NrB.js +0 -2677
  159. package/src/ui/dist/assets/LatexPlugin-CI05XAV9.js +0 -1792
  160. package/src/ui/dist/assets/MarkdownViewerPlugin-DpeBLYZf.js +0 -308
  161. package/src/ui/dist/assets/MarketplacePlugin-DolE58Q2.js +0 -413
  162. package/src/ui/dist/assets/NotebookEditor-7Qm2rSWD.js +0 -4214
  163. package/src/ui/dist/assets/NotebookEditor-C1kWaxKi.js +0 -84873
  164. package/src/ui/dist/assets/NotebookEditor-C3VQ7ylN.css +0 -1405
  165. package/src/ui/dist/assets/PdfLoader-BfOHw8Zw.js +0 -25468
  166. package/src/ui/dist/assets/PdfLoader-C-Y707R3.css +0 -49
  167. package/src/ui/dist/assets/PdfMarkdownPlugin-BulDREv1.js +0 -409
  168. package/src/ui/dist/assets/PdfViewerPlugin-C-daaOaL.js +0 -3095
  169. package/src/ui/dist/assets/PdfViewerPlugin-DQ11QcSf.css +0 -3627
  170. package/src/ui/dist/assets/SearchPlugin-CjpaiJ3A.js +0 -741
  171. package/src/ui/dist/assets/SearchPlugin-DDMrGDkh.css +0 -379
  172. package/src/ui/dist/assets/TextViewerPlugin-BxIyqPQC.js +0 -472
  173. package/src/ui/dist/assets/VNCViewer-HAg9mF7M.js +0 -18821
  174. package/src/ui/dist/assets/awareness-C0NPR2Dj.js +0 -292
  175. package/src/ui/dist/assets/bot-0DYntytV.js +0 -21
  176. package/src/ui/dist/assets/browser-BAcuE0Xj.js +0 -2895
  177. package/src/ui/dist/assets/code-B20Slj_w.js +0 -17
  178. package/src/ui/dist/assets/file-content-DT24KFma.js +0 -377
  179. package/src/ui/dist/assets/file-diff-panel-DK13YPql.js +0 -92
  180. package/src/ui/dist/assets/file-jump-queue-r5XKgJEV.js +0 -16
  181. package/src/ui/dist/assets/file-socket-B4T2o4nR.js +0 -58
  182. package/src/ui/dist/assets/function-B5QZkkHC.js +0 -1895
  183. package/src/ui/dist/assets/image-DSeR_sDS.js +0 -18
  184. package/src/ui/dist/assets/index-BrFje2Uk.js +0 -120
  185. package/src/ui/dist/assets/index-BwRJaoTl.js +0 -25
  186. package/src/ui/dist/assets/index-D_E4281X.js +0 -221322
  187. package/src/ui/dist/assets/index-DnYB3xb1.js +0 -159
  188. package/src/ui/dist/assets/index-G7AcWcMu.css +0 -12594
  189. package/src/ui/dist/assets/monaco-LExaAN3Y.js +0 -623
  190. package/src/ui/dist/assets/pdf-effect-queue-BJk5okWJ.js +0 -47
  191. package/src/ui/dist/assets/pdf_viewer-e0g1is2C.js +0 -8206
  192. package/src/ui/dist/assets/popover-D3Gg_FoV.js +0 -476
  193. package/src/ui/dist/assets/project-sync-C_ygLlVU.js +0 -297
  194. package/src/ui/dist/assets/select-CpAK6uWm.js +0 -1690
  195. package/src/ui/dist/assets/sigma-DEccaSgk.js +0 -22
  196. package/src/ui/dist/assets/square-check-big-uUfyVsbD.js +0 -17
  197. package/src/ui/dist/assets/trash-CXvwwSe8.js +0 -32
  198. package/src/ui/dist/assets/useCliAccess-Bnop4mgR.js +0 -957
  199. package/src/ui/dist/assets/useFileDiffOverlay-B8eUAX0I.js +0 -53
  200. package/src/ui/dist/assets/wrap-text-9vbOBpkW.js +0 -35
  201. package/src/ui/dist/assets/yjs-DncrqiZ8.js +0 -11243
  202. package/src/ui/dist/assets/zoom-out-BgVMmOW4.js +0 -34
@@ -0,0 +1,204 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-DrUnlf6K.js","assets/index-CBNVuWcP.js","assets/plugin-monaco-C8UgLomw.js","assets/plugin-terminal-MXFIPun8.js","assets/plugin-notebook-HbW2K-1c.js","assets/index-BpV6lusQ.css","assets/useCliAccess-NQ8m0Let.js","assets/VNCViewer-BoLGLnHz.js","assets/file-content-BZMz3RYp.js","assets/select-Cs2PmzwL.js","assets/chevron-up-C9Qpx4DE.js","assets/file-jump-queue-DA-SdG__.js","assets/pdf-effect-queue-J8OnM0jE.js","assets/file-diff-panel-CQhw0jS2.js","assets/bot-DREQOxzP.js","assets/git-commit-horizontal-DxZ8DCZh.js","assets/NotebookEditor-DB9N_T9q.js","assets/NotebookEditor-BOr3x3Ej.css","assets/trash-DwpbFr3w.js"])))=>i.map(i=>d[i]);
2
+ import{y as In,cb as Yy,cc as Zy,cd as Xp,ce as Yp,j as s,cf as Jy,r as An,bB as pa,cg as eb,bC as er,ch as tb,ci as nb,cj as oo,ck as sb,cl as Zp,cm as ni,cn as oi,co as si,cp as Ul,aS as Vn,cq as Zh,cr as rb,cs as Jh,aa as ab,ao as ib,bE as Ur,ct as ob,m as li,cu as ex,cv as lb,cw as ma,al as tx,s as Qs,b as z,cx as nx,f as nn,U as Ks,ak as cb,T as Tn,cy as sx,cz as rx,cA as ax,cB as ix,cC as ox,cD as K,cE as Tt,cF as tc,cG as nc,cH as ub,cI as db,cJ as Wl,cK as fb,k as Ou,cL as pb,cM as mb,O as sc,h as No,bv as lx,cN as pi,cO as hb,cP as xb,H as gb,bo as yb,cQ as bb,bq as cx,cR as uo,cS as vb,cT as _b,ah as Hl,cU as wb,u as nr,cV as ux,cW as Sb,cX as kb,cY as Nb,Q as jb,g as dx,_ as fx,cZ as Tb,ae as Vl,n as px,c_ as ri,c$ as Ab,b$ as Cb,c as mx,d0 as Eb,d1 as ud,l as mi,X as fo,L as dd,ax as hx,d2 as ai,E as Rb,e as Ib,b7 as fd,b8 as pd,d3 as Mb,d4 as xx,d5 as Lb,d as jo,aP as rc,d6 as pl,d7 as Pb,d8 as Db,d9 as $b,da as Fb,db as zb,dc as Ob,aZ as ks,ba as gx,dd as yx,bQ as Bb,bR as qb,b5 as Ub,bS as Wb,bU as ml,de as Hb,df as Vb,dg as bx,dh as Kb,b6 as Gb,an as Qb,a2 as Xb,di as Yb,aY as Zb,ad as Jb,a as fr,x as ev,dj as tv,dk as Jp,dl as Bu,dm as hl,bZ as nv,bI as sv,dn as rv,dp as xu,a0 as av,a6 as iv,$ as ov,dq as em,dr as lv,ds as cv,bp as uv,dt as dv,b9 as fv,bb as pv}from"./index-CBNVuWcP.js";import{r as c}from"./plugin-monaco-C8UgLomw.js";import{r as tm}from"./plugin-notebook-HbW2K-1c.js";import{u as qu}from"./file-content-BZMz3RYp.js";import{n as bo,j as vx,s as Kl,e as Uu,L as mv,S as hv,a as xv,c as gv,d as gu}from"./select-Cs2PmzwL.js";import{q as yv}from"./file-jump-queue-DA-SdG__.js";import{q as bv,M as _x}from"./pdf-effect-queue-J8OnM0jE.js";import{F as Wu}from"./file-diff-panel-CQhw0jS2.js";import{B as vv}from"./bot-DREQOxzP.js";import{G as _v}from"./git-commit-horizontal-DxZ8DCZh.js";import{C as wx}from"./chevron-up-C9Qpx4DE.js";import{v as wv,d as Sv,g as nm,s as sm,U as kv,I as Nv}from"./NotebookEditor-DB9N_T9q.js";import{T as jv,A as Tv}from"./trash-DwpbFr3w.js";/**
3
+ * @license lucide-react v0.511.0 - ISC
4
+ *
5
+ * This source code is licensed under the ISC license.
6
+ * See the LICENSE file in the root directory of this source tree.
7
+ */const Av=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],rm=In("archive",Av);/**
8
+ * @license lucide-react v0.511.0 - ISC
9
+ *
10
+ * This source code is licensed under the ISC license.
11
+ * See the LICENSE file in the root directory of this source tree.
12
+ */const Cv=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],Ev=In("circle-check-big",Cv);/**
13
+ * @license lucide-react v0.511.0 - ISC
14
+ *
15
+ * This source code is licensed under the ISC license.
16
+ * See the LICENSE file in the root directory of this source tree.
17
+ */const Rv=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"10",x2:"10",y1:"15",y2:"9",key:"c1nkhi"}],["line",{x1:"14",x2:"14",y1:"15",y2:"9",key:"h65svq"}]],Iv=In("circle-pause",Rv);/**
18
+ * @license lucide-react v0.511.0 - ISC
19
+ *
20
+ * This source code is licensed under the ISC license.
21
+ * See the LICENSE file in the root directory of this source tree.
22
+ */const Mv=[["path",{d:"M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3",key:"11bfej"}]],Lv=In("command",Mv);/**
23
+ * @license lucide-react v0.511.0 - ISC
24
+ *
25
+ * This source code is licensed under the ISC license.
26
+ * See the LICENSE file in the root directory of this source tree.
27
+ */const Pv=[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4.268 21a2 2 0 0 0 1.727 1H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"ms7g94"}],["path",{d:"m9 18-1.5-1.5",key:"1j6qii"}],["circle",{cx:"5",cy:"14",r:"3",key:"ufru5t"}]],Dv=In("file-search",Pv);/**
28
+ * @license lucide-react v0.511.0 - ISC
29
+ *
30
+ * This source code is licensed under the ISC license.
31
+ * See the LICENSE file in the root directory of this source tree.
32
+ */const $v=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],md=In("globe",$v);/**
33
+ * @license lucide-react v0.511.0 - ISC
34
+ *
35
+ * This source code is licensed under the ISC license.
36
+ * See the LICENSE file in the root directory of this source tree.
37
+ */const Fv=[["path",{d:"M10 17H7l-4 4v-7",key:"1r71xu"}],["path",{d:"M14 17h1",key:"nufu4t"}],["path",{d:"M14 3h1",key:"1ec4yj"}],["path",{d:"M19 3a2 2 0 0 1 2 2",key:"18rm91"}],["path",{d:"M21 14v1a2 2 0 0 1-2 2",key:"29akq3"}],["path",{d:"M21 9v1",key:"mxsmne"}],["path",{d:"M3 9v1",key:"1r0deq"}],["path",{d:"M5 3a2 2 0 0 0-2 2",key:"y57alp"}],["path",{d:"M9 3h1",key:"1yesri"}]],zv=In("message-square-dashed",Fv);/**
38
+ * @license lucide-react v0.511.0 - ISC
39
+ *
40
+ * This source code is licensed under the ISC license.
41
+ * See the LICENSE file in the root directory of this source tree.
42
+ */const Ov=[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M12 3v3",key:"1n5kay"}],["path",{d:"M4 6a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1h13a2 2 0 0 0 1.152-.365l3.424-2.317a1 1 0 0 0 0-1.635l-3.424-2.318A2 2 0 0 0 17 6z",key:"1btarq"}]],Bv=In("milestone",Ov);/**
43
+ * @license lucide-react v0.511.0 - ISC
44
+ *
45
+ * This source code is licensed under the ISC license.
46
+ * See the LICENSE file in the root directory of this source tree.
47
+ */const qv=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],Uv=In("minimize-2",qv);/**
48
+ * @license lucide-react v0.511.0 - ISC
49
+ *
50
+ * This source code is licensed under the ISC license.
51
+ * See the LICENSE file in the root directory of this source tree.
52
+ */const Wv=[["path",{d:"M13.234 20.252 21 12.3",key:"1cbrk9"}],["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 0 2.828 2 2 0 0 0 2.828 0l8.414-8.586a4 4 0 0 0 0-5.656 4 4 0 0 0-5.656 0l-8.415 8.585a6 6 0 1 0 8.486 8.486",key:"1pkts6"}]],Sx=In("paperclip",Wv);/**
53
+ * @license lucide-react v0.511.0 - ISC
54
+ *
55
+ * This source code is licensed under the ISC license.
56
+ * See the LICENSE file in the root directory of this source tree.
57
+ */const Hv=[["path",{d:"M12 20h9",key:"t2du7b"}],["path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z",key:"1ykcvy"}],["path",{d:"m15 5 3 3",key:"1w25hb"}]],Vv=In("pencil-line",Hv);/**
58
+ * @license lucide-react v0.511.0 - ISC
59
+ *
60
+ * This source code is licensed under the ISC license.
61
+ * See the LICENSE file in the root directory of this source tree.
62
+ */const Kv=[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M15 9.34V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H7.89",key:"znwnzq"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M9 9v1.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h11",key:"c9qhm2"}]],Gv=In("pin-off",Kv);/**
63
+ * @license lucide-react v0.511.0 - ISC
64
+ *
65
+ * This source code is licensed under the ISC license.
66
+ * See the LICENSE file in the root directory of this source tree.
67
+ */const Qv=[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z",key:"1nkz8b"}]],am=In("pin",Qv);/**
68
+ * @license lucide-react v0.511.0 - ISC
69
+ *
70
+ * This source code is licensed under the ISC license.
71
+ * See the LICENSE file in the root directory of this source tree.
72
+ */const Xv=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M9 8V2",key:"14iosj"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z",key:"osxo6l"}]],Yv=In("plug",Xv);/**
73
+ * @license lucide-react v0.511.0 - ISC
74
+ *
75
+ * This source code is licensed under the ISC license.
76
+ * See the LICENSE file in the root directory of this source tree.
77
+ */const Zv=[["path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"14sxne"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16",key:"1hlbsb"}],["path",{d:"M16 16h5v5",key:"ccwih5"}]],Jv=In("refresh-ccw",Zv);/**
78
+ * @license lucide-react v0.511.0 - ISC
79
+ *
80
+ * This source code is licensed under the ISC license.
81
+ * See the LICENSE file in the root directory of this source tree.
82
+ */const e_=[["circle",{cx:"6",cy:"19",r:"3",key:"1kj8tv"}],["path",{d:"M9 19h8.5a3.5 3.5 0 0 0 0-7h-11a3.5 3.5 0 0 1 0-7H15",key:"1d8sl"}],["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}]],t_=In("route",e_);/**
83
+ * @license lucide-react v0.511.0 - ISC
84
+ *
85
+ * This source code is licensed under the ISC license.
86
+ * See the LICENSE file in the root directory of this source tree.
87
+ */const n_=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],kx=In("send",n_);/**
88
+ * @license lucide-react v0.511.0 - ISC
89
+ *
90
+ * This source code is licensed under the ISC license.
91
+ * See the LICENSE file in the root directory of this source tree.
92
+ */const s_=[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]],r_=In("share-2",s_);/**
93
+ * @license lucide-react v0.511.0 - ISC
94
+ *
95
+ * This source code is licensed under the ISC license.
96
+ * See the LICENSE file in the root directory of this source tree.
97
+ */const a_=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"19",x2:"19",y1:"8",y2:"14",key:"1bvyxn"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]],i_=In("user-plus",a_),o_=c.createContext(null);function l_(){const e=c.useRef(!1);return Yy(()=>(e.current=!0,()=>{e.current=!1}),[]),e}function c_(){const e=l_(),[t,n]=c.useState(0),r=c.useCallback(()=>{e.current&&n(t+1)},[t]);return[c.useCallback(()=>Zy.postRender(r),[r]),t]}const Nx=e=>e===!0,u_=e=>Nx(e===!0)||e==="id",d_=({children:e,id:t,inherit:n=!0})=>{const r=c.useContext(Xp),a=c.useContext(o_),[i,o]=c_(),u=c.useRef(null),d=r.id||a;u.current===null&&(u_(n)&&d&&(t=t?d+"-"+t:d),u.current={id:t,group:Nx(n)?r.group||Yp():Yp()});const f=c.useMemo(()=>({...u.current,forceRender:i}),[o]);return s.jsx(Xp.Provider,{value:f,children:e})};class f_{constructor(){this.componentControls=new Set}subscribe(t){return this.componentControls.add(t),()=>this.componentControls.delete(t)}start(t,n){this.componentControls.forEach(r=>{r.start(t.nativeEvent||t,n)})}cancel(){this.componentControls.forEach(t=>{t.cancel()})}stop(){this.componentControls.forEach(t=>{t.stop()})}}const p_=()=>new f_;function m_(){return Jy(p_)}async function h_(e,t){return(await An.post(`/api/v1/pdf/parse/${e}`,null,{params:void 0})).data}async function x_(e,t){return(await An.get(`/api/v1/pdf/markdown/${e}`,{params:{max_chars:t},responseType:"text"})).data}const g_=24,im=6e3,tr=new Map,y_=e=>{let t=0;for(let n=0;n<e.length;n+=1)t=t*31+e.charCodeAt(n)|0;return t},om=e=>{const t=e?.data,n=typeof t?.event_id=="string"?t.event_id:"",r=typeof t?.timestamp=="number"?t.timestamp:0,a=typeof t?.tool_call_id=="string"?t.tool_call_id:"",i=typeof t?.status=="string"?t.status:"",o=typeof t?.delta=="string"?t.delta:"",u=o.length,d=o?y_(o):0;return`${e.event}|${n}|${r}|${a}|${i}|${u}|${d}`},po=e=>{const t=tr.get(e);t&&(tr.delete(e),tr.set(e,t))},jx=()=>{for(;tr.size>g_;){const e=tr.keys().next().value;if(!e)return;tr.delete(e)}},Tx=e=>{const t=tr.get(e);t&&(t.length<=im||t.splice(0,t.length-im))},b_=e=>{if(!e)return null;const t=tr.get(e);return t?(po(e),t):null},xl=(e,t)=>{e&&(tr.set(e,[...t]),po(e),Tx(e),jx())},v_=(e,t)=>{if(!e)return;const n=tr.get(e);if(n){const r=n.length>0?n[n.length-1]:null;if(r)try{if(om(r)===om(t)){po(e);return}}catch{}n.push(t),Tx(e),po(e);return}tr.set(e,[t]),po(e),jx()},hd="quest:",__=200,w_=25,xd=400,Ax=18e4;function Kn(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Rt(e){return typeof e=="string"&&e.trim().length>0?e:null}function gl(e){return typeof e=="string"?e.trim().toLowerCase():""}function Cx(e){if(typeof e=="number"&&Number.isFinite(e))return e>1e12?Math.floor(e/1e3):Math.floor(e);if(typeof e=="string"){const t=Number(e);if(Number.isFinite(t))return t>1e12?Math.floor(t/1e3):Math.floor(t);const n=Date.parse(e);if(!Number.isNaN(n))return Math.floor(n/1e3)}return Math.floor(Date.now()/1e3)}function Qi(e){return e?e.trim().toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,""):""}function Ex(e){if(typeof e=="string"&&e.trim())try{return JSON.parse(e)}catch{return null}return e&&typeof e=="object"?e:null}function Hr(e){return`${hd}${e}`}function S_(e,t,n){if(t&&n)return`mcp__${Qi(t)}__${Qi(n)}`;const r=Qi(e);if(e){const a=e.trim().toLowerCase();for(const i of["memory","artifact","bash_exec"])if(a.startsWith(`${i}.`)){const o=a.slice(i.length+1);return`mcp__${Qi(i)}__${Qi(o)}`}}return r==="shell_command"?"shell_exec":r==="web_fetch"?"webfetch":r==="web_search"||r==="websearch"?"web_search":r||e||"tool"}function k_(e){const n=Kn(e.counts)?.bash_running_count;if(typeof n=="number"&&Number.isFinite(n))return Math.max(0,Math.floor(n));if(typeof n=="string"){const r=Number(n);if(Number.isFinite(r))return Math.max(0,Math.floor(r))}return 0}function Rx(e){const t=gl(e.workspace_mode),n=gl(e.continuation_policy),r=Rt(e.active_run_id),a=gl(e.runtime_status)||gl(e.status);return!(t!=="copilot"||n!=="wait_for_user_or_resume"||r||k_(e)>0||a==="failed"||a==="error")}function Wr(e,t,n){return{surface:"copilot",quest_id:e,session_id:t,sender_type:"agent",sender_label:"DeepScientist",sender_name:"DeepScientist",...n}}function N_(e,t,n){const r=Ex(t),a=Kn(r);if(a)return a;const i=typeof t=="string"?t:"";if(!i){if(e==="web_search"){const o=Kn(n.search),u=Array.isArray(o?.queries)?o?.queries.filter(d=>typeof d=="string"&&d.trim().length>0):[];if(u.length>0)return{query:u[0],queries:u}}return{}}if(e==="shell_exec")return{command:i,raw:i};if(e==="web_search"){const o=Kn(n.search),u=Array.isArray(o?.queries)?o?.queries.filter(d=>typeof d=="string"&&d.trim().length>0):[];return{query:u[0]??i,...u.length>0?{queries:u}:{},raw:i}}return{raw:i}}function j_(e,t,n,r){const a=Ex(n),i=Kn(a);if(e==="web_search"){const u=Kn(r.search)??i,d={status:t||"completed"};return u?Object.assign(d,u):typeof n=="string"&&n.trim()&&(d.output=n),{status:t||"completed",result:d}}if(i){const u={...i};return t&&typeof u.status!="string"&&(u.status=t),{status:t||(typeof u.status=="string"?u.status:"completed"),result:u}}const o={};if(t&&(o.status=t),typeof n=="string"&&n.trim()&&(o.output=n),r.mcp_server==="bash_exec"&&r.mcp_tool==="bash_exec")for(const u of["bash_id","status","started_at","finished_at","exit_code","stop_reason","last_progress","log_path"])r[u]!=null&&o[u]==null&&(o[u]=r[u]);return{status:t||"completed",result:o}}function T_(e,t,n,r,a,i){const o=Rt(e.event_type)||"",u=Kn(e.message),d=Rt(u?.content)??"";if(o==="runner.reasoning")return{event:"reasoning",data:{event_id:r,timestamp:a,...typeof i=="number"?{seq:i}:{},created_at:typeof e.created_at=="string"?e.created_at:void 0,reasoning_id:Rt(u?.run_id)||r,status:"completed",content:d,kind:"full",metadata:Wr(t,n)}};const f=u?.role==="user"?"user":"assistant",p=Wr(t,n,f==="user"?{sender_type:"user",sender_label:"You",sender_name:"You",delivery_state:typeof u?.delivery_state=="string"?u.delivery_state:void 0}:{sender_type:"agent",sender_label:"DeepScientist",sender_name:"DeepScientist",agent_label:"DeepScientist"});if(f==="assistant"){const y=typeof u?.run_id=="string"&&u.run_id.trim().length>0?u.run_id:null,g=typeof u?.skill_id=="string"&&u.skill_id.trim().length>0?u.skill_id:null;p.quest_event_type=o||void 0,p.quest_run_id=y??void 0,p.quest_skill_id=g??void 0}return{event:"message",data:{event_id:r,timestamp:a,...typeof i=="number"?{seq:i}:{},created_at:typeof e.created_at=="string"?e.created_at:void 0,role:f,...o==="runner.delta"?{delta:d}:{content:d},metadata:p}}}function A_(e,t,n,r,a,i){const o=Kn(e.data),u=Rt(o?.tool_name),d=tb(u,Rt(o?.mcp_server),Rt(o?.mcp_tool)),f=d.server,p=d.tool,h=Kn(o?.metadata)??{},y=Wr(t,n,{...h,...f?{mcp_server:f}:{},...p?{mcp_tool:p}:{},bash_id:typeof h.bash_id=="string"?h.bash_id:typeof h.bashId=="string"?h.bashId:void 0,bash_status:typeof h.status=="string"?h.status:typeof o?.status=="string"?o.status:void 0,bash_mode:typeof h.mode=="string"?h.mode:typeof h.bash_mode=="string"?h.bash_mode:void 0,bash_command:typeof h.command=="string"?h.command:typeof h.bash_command=="string"?h.bash_command:void 0,bash_workdir:typeof h.workdir=="string"?h.workdir:typeof h.bash_workdir=="string"?h.bash_workdir:void 0}),g=S_(u,f,p);return{event:"tool",data:{event_id:r,timestamp:a,...typeof i=="number"?{seq:i}:{},created_at:typeof e.created_at=="string"?e.created_at:void 0,tool_call_id:Rt(o?.tool_call_id)||r,name:p||u||f||"tool",function:g,status:Rt(e.event_type)==="runner.tool_call"?"calling":"called",args:N_(g,o?.args,h),metadata:y,...Rt(e.event_type)==="runner.tool_result"?{content:j_(g,Rt(o?.status),o?.output,h)}:{}}}}function yu(e,t,n,r,a,i){const o=Rt(e.event_type)||"",u=Kn(e.data);if(o==="runner.turn_finish")return{event:"done",data:{event_id:r,timestamp:a,...typeof i=="number"?{seq:i}:{},created_at:typeof e.created_at=="string"?e.created_at:void 0,metadata:Wr(t,n)}};if(o==="runner.turn_error")return{event:"error",data:{event_id:r,timestamp:a,...typeof i=="number"?{seq:i}:{},created_at:typeof e.created_at=="string"?e.created_at:void 0,error:Rt(u?.summary)||"Quest run failed.",metadata:Wr(t,n)}};if(o==="quest.control"){const h=Rt(u?.action)||Rt(e.action)||"";if(h==="pause"||h==="stop")return{event:"wait",data:{event_id:r,timestamp:a,...typeof i=="number"?{seq:i}:{},created_at:typeof e.created_at=="string"?e.created_at:void 0,metadata:Wr(t,n)}}}if(o==="artifact.recorded"){const h=Kn(e.artifact),y=Kn(h?.paths)??{},g=Object.values(y).filter(_=>typeof _=="string"&&_.trim().length>0),T=Rt(h?.summary)||Rt(h?.guidance)||Rt(h?.reason)||`Artifact recorded: ${Rt(h?.kind)||"artifact"}`;return{event:"status",data:{event_id:r,timestamp:a,...typeof i=="number"?{seq:i}:{},created_at:typeof e.created_at=="string"?e.created_at:void 0,message:T,status:"artifact",event_type:o,...g.length>0?{related_files:g}:{},...Rt(h?.artifact_path)?{artifacts:[String(h?.artifact_path)]}:{},metadata:Wr(t,n)}}}const d=Rt(u?.label)||o||"event",f=Rt(u?.summary)||Rt(u?.message)||Rt(u?.text)||d.replace(/_/g," ");return{event:"status",data:{event_id:r,timestamp:a,...typeof i=="number"?{seq:i}:{},created_at:typeof e.created_at=="string"?e.created_at:void 0,message:f,status:d==="run_started"?"running":d==="run_failed"?"failed":d==="run_finished"?"completed":d,event_type:o,metadata:Wr(t,n)}}}function Ix(e){const t=Kn(e.params??Kn(e)?.params),n=Kn(t?.update),r=Rt(t?.sessionId)||Rt(n?.session_id)||Hr(Rt(n?.quest_id)||""),a=Rt(n?.quest_id)||To(r)||"";if(!n||!r||!a)return[];const i=Rt(n.event_id)||`quest-${a}-${String(n.cursor??Date.now())}`,o=Cx(n.created_at),u=typeof n.cursor=="number"?n.cursor:void 0,d=Rt(n.event_type)||"";if(n.kind==="message"||d==="conversation.message"||d.startsWith("runner.")){if(d==="conversation.message"||d==="runner.delta"||d==="runner.agent_message"||d==="runner.reasoning"){const h=T_(n,a,r,i,o,u);return h?[h]:[]}if(d==="runner.tool_call"||d==="runner.tool_result"){const h=A_(n,a,r,i,o,u);return h?[h]:[]}const p=yu(n,a,r,i,o,u);return p?[p]:[]}if(n.kind==="artifact"||d==="artifact.recorded"||d==="quest.control"){const p=yu(n,a,r,i,o,u);return p?[p]:[]}const f=yu(n,a,r,i,o,u);return f?[f]:[]}function C_(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n.event==="message"){const r=n.data,a=typeof r.content=="string"&&r.content.trim().length>0?r.content.trim():typeof r.delta=="string"&&r.delta.trim().length>0?r.delta.trim():"";if(a)return{text:a,timestamp:typeof r.timestamp=="number"?r.timestamp:null}}if(n.event==="status"){const r=n.data,a=typeof r.message=="string"&&r.message.trim().length>0?r.message.trim():typeof r.text=="string"&&r.text.trim().length>0?r.text.trim():"";if(a)return{text:a,timestamp:typeof r.timestamp=="number"?r.timestamp:null}}}return{text:null,timestamp:null}}function Mx(e,t){if(Rx(e))return!1;if(e.active_run_id)return!0;for(let n=t.length-1;n>=0;n-=1){const r=t[n];if(r.event==="done"||r.event==="wait"||r.event==="error")return!1;if(r.event==="tool"&&r.data.status==="calling"||r.event==="reasoning"&&r.data.status==="in_progress")return!0;if(r.event==="message"){const a=r.data;if(a.role==="assistant"&&typeof a.delta=="string"&&a.delta.length>0)return!0}}return!1}function E_(e,t){if(Rx(e))return t.length>0?"completed":"pending";if(Mx(e,t))return"running";for(let a=t.length-1;a>=0;a-=1){const i=t[a];if(i.event==="error")return"failed";if(i.event==="wait")return"waiting";if(i.event==="done")return"completed"}const r=Rt(e.runtime_status)||Rt(e.status)||"";return r==="failed"||r==="error"?"failed":r==="paused"||r==="waiting"?"waiting":r==="running"?"running":e.stop_reason||t.length>0?"completed":"pending"}async function gd(e){return(await An.get(`/api/quests/${e}/session`,{timeout:Ax})).data}async function R_(e,t){return(await An.get(`/api/quests/${e}/events`,{params:{after:t,limit:__,format:"acp",session_id:Hr(e)},timeout:Ax})).data}async function yd(e,t){const n=t?.full===!0,r=typeof t?.limit=="number"&&Number.isFinite(t.limit)&&t.limit>0?Math.floor(t.limit):xd,a=[];let i=0,o=0,u=!0;for(;u&&o<w_;){const d=await R_(e,i),f=(d.acp_updates??[]).flatMap(p=>Ix(p));a.push(...f),!n&&a.length>r&&a.splice(0,a.length-r),i=typeof d.cursor=="number"?d.cursor:i,u=!!d.has_more,o+=1}return{events:a,cursor:i,fetchedAll:!u,requestedLimit:r}}function bd(e,t,n){const r=e.snapshot,a=E_(r,t),i=Mx(r,t),o=C_(t),u=Cx(r.updated_at),d=typeof r.history_count=="number"&&Number.isFinite(r.history_count)?r.history_count:null,f=typeof n?.limit=="number"&&Number.isFinite(n.limit)&&n.limit>0?Math.floor(n.limit):xd;return{session_id:Hr(e.quest_id),status:a,title:Rt(r.title)||e.quest_id,is_active:i,is_shared:!1,latest_message:o.text||Rt(Kn(r.summary)?.status_line)||null,latest_message_at:o.timestamp??u,updated_at:u,events:t,events_truncated:n?.full===!0?!1:d!=null?d>t.length:!n?.fetchedAll,event_limit:n?.full===!0?null:f,plan_history:[],execution_target:"sandbox",cli_server_id:null,session_metadata:{quest_id:e.quest_id,quest_root:r.quest_root,active_anchor:r.active_anchor,runner:r.runner,workspace_mode:r.workspace_mode,continuation_policy:typeof r.continuation_policy=="string"?r.continuation_policy:null,active_run_id:r.active_run_id,runtime_status:r.runtime_status,stop_reason:r.stop_reason,updated_at:r.updated_at,bound_conversations:r.bound_conversations},agents:[{agent_id:"deepscientist",agent_label:"DeepScientist",agent_display_name:"DeepScientist",agent_source:r.runner??"codex",agent_engine:r.runner??"codex"}],event_metadata_mode:"full"}}function ya(e){return typeof e=="string"&&e.startsWith(hd)}function To(e){return ya(e)&&e.slice(hd.length).trim()||null}async function vo(e){return!e||e.trim().length===0?!1:pa()?!0:eb(e)}async function I_(e){const t=await gd(e);return bd(t,[],{limit:xd,fetchedAll:!1})}async function M_(e,t){const n=To(e);if(!n)throw new Error(`Invalid quest session id: ${e}`);const[r,a]=await Promise.all([gd(n),yd(n,t)]);return bd(r,a.events,{full:t?.full,limit:a.requestedLimit,fetchedAll:a.fetchedAll})}async function L_(e,t){const n=To(e);if(!n)throw new Error(`Invalid quest session id: ${e}`);return(await yd(n,t)).events}async function vd(e,t){const n=await gd(e),r=await yd(e,{limit:t});return bd(n,r.events,{limit:r.requestedLimit,fetchedAll:r.fetchedAll})}async function P_(e){const t=await vd(e,80);return{sessions:[{session_id:t.session_id,status:t.status??null,title:t.title??null,latest_message:t.latest_message??null,latest_message_at:t.latest_message_at??null,updated_at:t.updated_at??null,is_shared:!1,is_active:t.is_active??!1,agent_engine:typeof t.session_metadata?.runner=="string"?t.session_metadata.runner:"codex",execution_target:"sandbox",cli_server_id:null}]}}function D_(e){const t=new URLSearchParams({format:"acp",session_id:Hr(e),stream:"1"});return`${er()}/api/quests/${e}/events?${t.toString()}`}function Pl(e){for(let t=e.length-1;t>=0;t-=1){const r=e[t].data?.seq;if(typeof r=="number"&&Number.isFinite(r))return String(r)}return null}async function lm(e){if(e&&await vo(e)){const n=await I_(e);return{session_id:n.session_id,status:n.status??void 0,title:n.title??null,is_active:n.is_active??!1}}return(await An.put("/api/v1/sessions",e?{project_id:e}:void 0)).data}async function _d(e,t){if(ya(e))return await M_(e,t);const n={};return t?.full===!0?n.full=!0:typeof t?.limit=="number"&&(n.limit=t.limit),t?.metadata&&(n.metadata=t.metadata),(await An.get(`/api/v1/sessions/${e}`,{params:n})).data}async function $_(e){const t=`ds:session-summaries:${e??"all"}`,n=sb(t);if(n)return n;if(e&&await vo(e)){const i=await P_(e);return Zp(t,i,3e4),i}const a=(await An.get("/api/v1/sessions/summary",{params:e?{project_id:e}:void 0})).data;return Zp(t,a,3e4),a}async function Xi(e,t,n,r){if(await vo(e))return await vd(e,t);if(!nb())return null;try{return(await An.get("/api/v1/sessions/latest",{params:{project_id:e,...n?{surface:n}:{},...typeof t=="number"?{limit:t}:{},...r?.metadata?{metadata:r.metadata}:{}}})).data}catch(a){if(oo.isAxiosError(a)&&a.response?.status===404)return null;throw a}}async function F_(e){if(ya(e)){const t=e.slice(6);await An.post(`/api/quests/${t}/commands`,{command:"/stop",source:"web-react"});return}await An.post(`/api/v1/sessions/${e}/stop`)}async function z_(e){await An.delete(`/api/v1/sessions/${e}`)}async function O_(e,t,n,r){return(await An.post(`/api/v1/sessions/${e}/shell/write`,{session_id:t,input:n,press_enter:r})).data}async function B_(e,t){return(await An.post(`/api/v1/sessions/${e}/file`,{file:t})).data}async function q_(e){return(await An.get(`/api/v1/sessions/${e}/files`)).data}async function cm(e,t,n){return(await An.post(`/api/v1/sessions/${e}/tools/${t}`,{output:n})).data}async function U_(e,t){const n={};if(typeof window<"u"){const a=window.localStorage.getItem("ds_owner_token")||window.localStorage.getItem("deepscientist_api_token");a&&(n["X-DS-Owner-Token"]=a)}return(await An.post(`/api/v1/sessions/${e}/apply_patch`,t,{headers:n})).data}async function W_(e,t,n){return(await An.post(`/api/v1/sessions/${e}/clarify`,{tool_call_id:t,selections:n})).data}async function H_(e,t=15){return(await An.post(`/api/v1/sessions/${e}/vnc/signed-url`,{expire_minutes:t})).data}async function nj(e,t=15){const n=er().replace(/^http/,"ws");try{const r=await H_(e,t);return`${n}${r.signed_url}`}catch(r){if(typeof window>"u")throw r;const i=window.localStorage.getItem("ds_access_token")||null,o=i?`?token=${encodeURIComponent(i)}`:"";return`${n}/api/v1/sessions/${e}/vnc${o}`}}const Gl=()=>typeof window>"u"?!1:window.localStorage.getItem("ds_debug_copilot")==="1",_o=new Map,bu=e=>_o.get(e)??null,um=e=>{const t=_o.get(e);if(t)return t;const n={sessionId:e,projectId:null,connection:{status:"idle"},isStreaming:!1,abortController:null,runId:0,abortedRunId:null,eventSeq:0,listeners:new Set,eventSubscribers:new Set,connectionSubscribers:new Set};return _o.set(e,n),n},wd=e=>{const t=_o.get(e);t&&(t.isStreaming||t.abortController||t.listeners.size>0||t.eventSubscribers.size>0||t.connectionSubscribers.size>0||_o.delete(e))},V_=e=>e.listeners.size>0||e.eventSubscribers.size>0||e.connectionSubscribers.size>0;let yl=null,Yi=null;const Lx=async e=>{if(e!=="user"||typeof window>"u")return null;if(yl)return yl;const t=window.localStorage.getItem("ds_owner_token")||window.localStorage.getItem("deepscientist_api_token");return t?(yl=t,t):Yi||(Yi=(async()=>{try{const r=(await rb())?.api_token;return r&&typeof window<"u"&&(window.localStorage.setItem("ds_owner_token",r),yl=r),r||null}catch{return null}finally{Yi=null}})(),Yi)},Px=()=>{const e={"Content-Type":"application/json"},{token:t,mode:n}=Zh();return t&&(e.Authorization=`Bearer ${t}`),{headers:e,authMode:n}},Hu=e=>{Jh(e,"session_expired")},dm=e=>{const t=e.split(/\n/);let n="",r="";const a=[];for(const i of t)if(i){if(i.startsWith("event:")){n=i.slice(6).trim();continue}if(i.startsWith("data:")){a.push(i.slice(5).trimStart());continue}i.startsWith("id:")&&(r=i.slice(3).trim())}return a.length===0?null:{event:n||"message",data:a.join(`
98
+ `),id:r||void 0}},Vu=async e=>{let t="";try{if((e.headers.get("content-type")||"").toLowerCase().includes("application/json")){const a=await e.json(),i=a?.detail;if(typeof i=="string")t=i;else if(i&&typeof i=="object"){const o=i,u=o.message,d=Number(o.required_minimum??0),f=Number(o.balance??0);typeof u=="string"&&u.trim()?(t=u,d>0&&(t+=` Required: ${d}, balance: ${f}.`)):d>0&&(t=`Insufficient points. Required: ${d}, balance: ${f}.`)}else typeof a?.message=="string"&&a.message.trim()&&(t=a.message)}else{const a=(await e.text()).trim();a&&(t=a)}}catch{}const n=`HTTP ${e.status}: ${e.statusText}`;return new Error(t||n)},fm=e=>{const t=e.data,n=typeof t.delta=="string"?t.delta:"",r=typeof t.status=="string"?t.status:void 0,a=typeof t.event_id=="string"?t.event_id:void 0,i=typeof t.tool_call_id=="string"?t.tool_call_id:void 0,o=typeof t.timestamp=="number"?t.timestamp:void 0,u=typeof t.seq=="number"?t.seq:typeof t._seq=="number"?t._seq:void 0;let d=e.event;return e.event==="message"&&n?d="text_delta":e.event==="reasoning"&&n?d="reasoning_delta":e.event==="tool"&&(d=r==="calling"?"tool_call":"tool_result"),{event:e.event,kind:d,eventId:a,toolCallId:i,status:r,timestamp:o,seq:u,deltaLen:n.length}},Xs=(e,t,n)=>{if(!Gl())return;const r={projectId:e.projectId??null,sessionId:e.sessionId??null};if(n){console.info(`[SSE][${t}]`,{...r,...n});return}console.info(`[SSE][${t}]`,r)},Sd=e=>{for(const t of e.listeners)try{t()}catch{}},Br=(e,t,n)=>{if(!(typeof n=="number"&&e.runId!==n)){e.connection=t;for(const r of e.connectionSubscribers)try{r(t)}catch{}Xs(e,"connection",t),Sd(e)}},qr=(e,t,n)=>{typeof n=="number"&&e.runId!==n||(e.isStreaming=t,Sd(e))},K_=e=>{const t=e.data;if(!t)return null;const n=t.seq??t.sequence??t._seq;if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"){const r=Number(n);if(Number.isFinite(r))return r}return null},G_=(e,t)=>{const n=t.data;if(!n||typeof n!="object")return;const r=K_(t);if(r!=null){r>e.eventSeq&&(e.eventSeq=r),typeof n.seq!="number"&&(n.seq=r);return}e.eventSeq+=1,n.seq=e.eventSeq},pm=(e,t,n)=>{if(!(e.runId!==n||e.abortedRunId===n)){G_(e,t),v_(e.sessionId,t);for(const r of e.eventSubscribers)try{r(t,{runId:n,sessionId:e.sessionId})}catch{}}},Dx=e=>({surface:e.surface,execution_target:e.executionTarget,cli_server_id:e.cliServerId??null,...e.metadata??{}}),Ql=async(e,t,n=0)=>{const r=e.sessionId;if(!r)return;const a=To(r),{headers:i,authMode:o}=Px(),u=await Lx(o);if(u&&(i["X-DS-Owner-Token"]=u),a){const g=e.message??"";if(Gl()&&console.info("[CopilotAudit][stream] quest postChat",{projectId:t,sessionId:r,questId:a,messageLength:g.length,attempt:n}),!g.trim())return;const T=`${er()}/api/quests/${a}/chat`,w="POST",_=Date.now();let b;try{b=await fetch(T,{method:w,headers:i,body:JSON.stringify({text:g,source:"web-react"})})}catch(E){throw ni({method:w,url:si(T),duration_ms:Date.now()-_,error:oi(E instanceof Error?E.message:"request_failed")}),E}if(ni({method:w,url:si(T),status:b.status,duration_ms:Date.now()-_}),b.status===401){if(o==="user"&&n<1&&await Ul()){await Ql(e,t,n+1);return}Hu(o);return}if(!b.ok)throw await Vu(b);return}const d={message:e.message??"",timestamp:Math.floor(Date.now()/1e3),attachments:e.attachments??[],...e.attachmentsSelected&&e.attachmentsSelected.length>0?{attachments_selected:e.attachmentsSelected}:{},...e.attachmentsAll&&e.attachmentsAll.length>0?{attachments_all:e.attachmentsAll}:{},...e.mentionTargets&&e.mentionTargets.length>0?{mention_targets:e.mentionTargets}:{},metadata:Dx(e)},f=`${er()}/api/v1/sessions/${r}/chat`,p="POST",h=Date.now();let y;try{y=await fetch(f,{method:p,headers:i,body:JSON.stringify(d)})}catch(g){throw ni({method:p,url:si(f),duration_ms:Date.now()-h,error:oi(g instanceof Error?g.message:"request_failed")}),g}if(ni({method:p,url:si(f),status:y.status,duration_ms:Date.now()-h}),y.status===401){if(o==="user"&&n<1&&await Ul()){await Ql(e,t,n+1);return}Hu(o);return}if(!y.ok)throw await Vu(y)},Dl=async(e,t,n,r=0)=>{const a=t.sessionId;if(!a||e.runId!==n)return;const i=To(a),o=!!i,u=!!(t.replayFromLastEvent||r>0),d=new AbortController;e.abortController=d,qr(e,!0,n),Br(e,{status:r>0?"reconnecting":"connecting"},n);const{headers:f,authMode:p}=Px(),h=await Lx(p);h&&(f["X-DS-Owner-Token"]=h);const y=t.message??"",g=y.trim().length>0,T=(t.attachments??[]).length>0,w=!g&&!T;w&&delete f["Content-Type"];let _=Vn.getState().getLastEventId(a);if(o&&!_&&(u||w))try{const M=await _d(a,{limit:1}),U=Pl(M.events??[]);U&&(_=U,Vn.getState().setLastEventId(a,U))}catch{}!!_&&(u||o&&(g||T))&&_&&(f["Last-Event-ID"]=_);const R=w?void 0:{message:y,timestamp:Math.floor(Date.now()/1e3),event_id:u&&_||void 0,attachments:t.attachments??[],...t.attachmentsSelected&&t.attachmentsSelected.length>0?{attachments_selected:t.attachmentsSelected}:{},...t.attachmentsAll&&t.attachmentsAll.length>0?{attachments_all:t.attachmentsAll}:{},...t.mentionTargets&&t.mentionTargets.length>0?{mention_targets:t.mentionTargets}:{},...t.recentFiles&&t.recentFiles.length>0?{recent_files:t.recentFiles}:{},metadata:Dx(t)};let A=null,C=null;try{let M=w?"stream":"chat",U=`${er()}/api/v1/sessions/${a}/${M}`,Q=w?"GET":"POST",ae=R;o&&i&&(M="quest_stream",U=D_(i),Q="GET",ae=void 0,delete f["Content-Type"],!w&&(g||T)&&!t.questMessagePosted&&(await Ql(t,e.projectId??projectId??null,r),t.questMessagePosted=!0)),Xs(e,"start",{activeSessionId:a,endpoint:M,attempt:r,streamOnly:w,shouldReplay:u,hasMessage:g,hasAttachments:T,lastEventId:_});const ye=Date.now();let V;try{V=await fetch(U,{method:Q,headers:f,body:ae?JSON.stringify(ae):void 0,signal:d.signal})}catch($){throw ni({method:Q,url:si(U),duration_ms:Date.now()-ye,error:oi($ instanceof Error?$.message:"request_failed")}),$}if(ni({method:Q,url:si(U),status:V.status,duration_ms:Date.now()-ye}),e.runId!==n)return;if(V.status===429){const $=Number(V.headers.get("Retry-After")??"3"),I=Number.isFinite($)?$*1e3:3e3,O=Date.now()+I;Br(e,{status:"rate_limited",retryAt:O,error:"rate_limited"},n),qr(e,!1,n),r<3&&window.setTimeout(()=>{e.runId===n&&(e.abortController?.signal.aborted||Dl(e,t,n,r+1))},I);return}if(V.status===401){if(p==="user"&&r<1&&await Ul()){qr(e,!1,n),Dl(e,t,n,r+1);return}Br(e,{status:"error",error:"unauthorized"},n),qr(e,!1,n),Hu(p);return}if(!V.ok)throw await Vu(V);if((V.headers.get("content-type")||"").includes("application/json")){Xs(e,"closed",{activeSessionId:a,endpoint:M,reason:"json_response"}),await V.json(),qr(e,!1,n),Br(e,{status:"closed"},n);return}Br(e,{status:"open"},n);const Z=V.body?.getReader();if(!Z)throw new Error("No response body");const Se=new TextDecoder;let $e="",Ne=!1;A=()=>{Ne||(Ne=!0,Z.cancel().catch(()=>{}))},C=()=>{A?.()},d.signal.aborted?C():d.signal.addEventListener("abort",C,{once:!0});const G=$=>{const I=JSON.parse($.data);if(o){if($.event==="cursor"){const Oe=(I&&typeof I=="object"&&!Array.isArray(I)?I:null)?.cursor;a&&(typeof Oe=="number"||typeof Oe=="string"&&Oe.trim().length>0)&&Vn.getState().setLastEventId(a,String(Oe));return}const de=Ix(I);$.id&&a&&Vn.getState().setLastEventId(a,$.id);for(const Te of de)Xs(e,"event",fm(Te)),pm(e,Te,n);return}const O=I,X={event:$.event,data:O};Xs(e,"event",fm(X));const ne=(X.event==="message"||X.event==="reasoning")&&typeof O?.delta=="string"&&!!O.delta,ke=typeof $.id=="string"&&$.id.trim().length>0?$.id.trim():O?.event_id&&!ne?O.event_id:null;ke&&a&&Vn.getState().setLastEventId(a,ke),pm(e,X,n)};for(;!(d.signal.aborted||e.runId!==n||e.abortedRunId===n);){const{done:$,value:I}=await Z.read();if($||d.signal.aborted||e.runId!==n||e.abortedRunId===n)break;$e+=Se.decode(I,{stream:!0}),I&&I.length>0&&Xs(e,"chunk",{bytes:I.length,bufferSize:$e.length}),$e.includes("\r")&&($e=$e.replace(/\r\n/g,`
99
+ `));let O=$e.indexOf(`
100
+
101
+ `);for(;O!==-1&&e.runId===n;){const X=$e.slice(0,O);$e=$e.slice(O+2);const ne=X.replace(/\r\n/g,`
102
+ `).trim(),ke=dm(ne),de=e.runId===n&&e.abortedRunId!==n&&!d.signal.aborted;if(ke&&de)try{G(ke)}catch(Te){console.warn("[SSE] Failed to parse event data",Te)}O=$e.indexOf(`
103
+
104
+ `)}}const J=$e.replace(/\r\n/g,`
105
+ `).trim();if(J&&e.runId===n&&e.abortedRunId!==n&&!d.signal.aborted){const $=dm(J);if($)try{G($)}catch(I){console.warn("[SSE] Failed to parse trailing event data",I)}}qr(e,!1,n),Xs(e,"closed",{activeSessionId:a,reason:"eof"}),Br(e,{status:"closed"},n)}catch(M){if(d.signal.aborted){qr(e,!1,n),Xs(e,"closed",{activeSessionId:a,reason:"aborted"}),Br(e,{status:"closed"},n);return}const U=M instanceof Error?M.message:"SSE error";Xs(e,"error",{activeSessionId:a,message:U,attempt:r}),Br(e,{status:"error",error:U},n),qr(e,!1,n),r<1&&e.runId===n&&Dl(e,t,n,r+1)}finally{A&&!d.signal.aborted&&e.abortedRunId===n&&A(),C&&d.signal.removeEventListener("abort",C),e.abortController===d&&(e.abortController=null),wd(e.sessionId)}},Q_=e=>{e.runId+=1,e.abortedRunId=null;const t=e.runId;return e.abortController&&(Xs(e,"abort",{reason:"new_stream",runId:t}),e.abortController.abort(),e.abortController=null),t},mm=e=>{const t=e.runId;e.runId+=1,e.abortedRunId=t,e.abortController&&(Xs(e,"stop",{reason:"user_or_caller"}),e.abortController.abort(),e.abortController=null),e.isStreaming=!1,e.connection={status:"closed"},Sd(e);for(const n of e.connectionSubscribers)try{n(e.connection)}catch{}return wd(e.sessionId),t};function X_(e){const{sessionId:t,projectId:n,onEvent:r,onConnectionChange:a,autoStopWhenUnobserved:i=!1}=e,o=c.useRef(r),u=c.useRef(a);c.useEffect(()=>{o.current=r},[r]),c.useEffect(()=>{u.current=a},[a]);const d=c.useMemo(()=>{if(!t)return{connection:{status:"idle"},isStreaming:!1,runId:0};const E=bu(t);return E?{connection:E.connection,isStreaming:E.isStreaming,runId:E.runId}:{connection:{status:"idle"},isStreaming:!1,runId:0}},[t]),[f,p]=c.useState(d.connection),[h,y]=c.useState(d.isStreaming),[g,T]=c.useState(d.runId);c.useEffect(()=>{if(!t){p({status:"idle"}),y(!1),T(0);return}const E=um(t);n&&(E.projectId=n);const R=()=>{const U=bu(t);U&&(p(U.connection),y(U.isStreaming),T(U.runId))};R();const A=()=>{R()};E.listeners.add(A);const C=(U,Q)=>{o.current?.(U,Q)};E.eventSubscribers.add(C);const M=U=>{u.current?.(U)};return E.connectionSubscribers.add(M),()=>{if(E.listeners.delete(A),E.eventSubscribers.delete(C),E.connectionSubscribers.delete(M),i&&!V_(E)&&(E.isStreaming||E.abortController)){mm(E);return}wd(t)}},[i,n,t]);const w=c.useCallback(async E=>{const R=E.sessionId??t;if(!R)return;Gl()&&console.info("[CopilotAudit][stream] sendMessage",{targetSessionId:R,projectId:n,hasMessage:(E.message??"").trim().length>0,attachmentCount:(E.attachments??[]).length,replayFromLastEvent:!!E.replayFromLastEvent});const A=um(R);n&&!A.projectId&&(A.projectId=n);const M=(E.message??"").trim().length>0,U=(E.attachments??[]).length>0,Q=!M&&!U;if(Q){const V=A.connection.status;if(A.isStreaming||A.abortController!=null||V==="connecting"||V==="open"||V==="reconnecting"||V==="rate_limited")return}const ae={...E,sessionId:R};if(A.isStreaming){if(Gl()&&console.info("[CopilotAudit][stream] runtime already streaming",{targetSessionId:R,streamOnly:Q}),Q)return;await Ql(ae,n??null,0);return}const ye=Q_(A);await Dl(A,ae,ye,0)},[n,t]),_=c.useCallback(E=>{const R=E??t;if(!R)return null;const A=bu(R);return A?mm(A):null},[t]),b=c.useCallback(async E=>t?_d(t,E):null,[t]);return{sendMessage:w,stop:_,restoreSession:b,connection:f,isStreaming:h,runId:g}}async function Y_({projectId:e,sessionId:t,file:n,onProgress:r}){const a=new FormData;return a.append("file",n),a.append("project_id",e),a.append("session_id",t),(await An.post("/api/copilot/files",a,{headers:{"Content-Type":void 0},onUploadProgress:o=>{if(!r||!o.total)return;const u=Math.round(o.loaded*100/o.total);r(u)}})).data}async function Z_(e,t){const n=await An.post(`/api/v1/projects/${e}/copilot/actions/fix-with-ai`,t);return Array.isArray(n.data)?n.data:[]}const J_=3500,ew=3e3,tw=3e3,vu=new Map,_u=new Map,wu=new Map,nw=(e,t)=>{const n=bo(t);return`${e}:${n}`},sw=ab((e,t)=>({highlightedKey:null,readingKeys:new Set,writingKeys:new Set,movedKeys:new Set,renamedKeys:new Set,highlight:n=>{e({highlightedKey:n}),window.setTimeout(()=>{t().highlightedKey===n&&e({highlightedKey:null})},3e3)},markRead:n=>{e(i=>{const o=new Set(i.readingKeys);return o.add(n),{readingKeys:o}});const r=vu.get(n);r&&window.clearTimeout(r);const a=window.setTimeout(()=>{vu.delete(n),e(i=>{if(!i.readingKeys.has(n))return i;const o=new Set(i.readingKeys);return o.delete(n),{readingKeys:o}})},J_);vu.set(n,a)},markWrite:n=>{e(r=>{const a=new Set(r.writingKeys);return a.add(n),{writingKeys:a}})},clearWrite:n=>{e(r=>{if(!r.writingKeys.has(n))return r;const a=new Set(r.writingKeys);return a.delete(n),{writingKeys:a}})},markMove:n=>{e(i=>{const o=new Set(i.movedKeys);return o.add(n),{movedKeys:o}});const r=_u.get(n);r&&window.clearTimeout(r);const a=window.setTimeout(()=>{_u.delete(n),e(i=>{if(!i.movedKeys.has(n))return i;const o=new Set(i.movedKeys);return o.delete(n),{movedKeys:o}})},ew);_u.set(n,a)},clearMove:n=>{e(r=>{if(!r.movedKeys.has(n))return r;const a=new Set(r.movedKeys);return a.delete(n),{movedKeys:a}})},markRename:n=>{e(i=>{const o=new Set(i.renamedKeys);return o.add(n),{renamedKeys:o}});const r=wu.get(n);r&&window.clearTimeout(r);const a=window.setTimeout(()=>{wu.delete(n),e(i=>{if(!i.renamedKeys.has(n))return i;const o=new Set(i.renamedKeys);return o.delete(n),{renamedKeys:o}})},tw);wu.set(n,a)},clearRename:n=>{e(r=>{if(!r.renamedKeys.has(n))return r;const a=new Set(r.renamedKeys);return a.delete(n),{renamedKeys:a}})}})),Fn={read_file:"ds_system_read_file",append_file:"ds_system_append_file",write_task_plan:"mcp_write_task_plan",pull_file:"ds_system_pull_file",list_file:"ds_system_list_file",list_dir:"ds_system_list_dir",grep_text:"ds_system_grep_text",grep_files:"ds_system_grep_files",glob_files:"ds_system_glob_files",write_memory:"mcp_write_memory",request_patch:"ds_system_request_patch",bash_exec:"bash_exec",status_update:"mcp_status_update",write_question:"mcp_write_question",lab_quests:"lab_quests",lab_pi_sleep:"lab_pi_sleep",lab_baseline:"lab_baseline"};function rw(e){const t=e.trim();if(!t)return"";const n=t.toLowerCase();if(!n.startsWith("mcp__"))return n;const r=n.split("__");return r[r.length-1]||n}function yr(e){const t=e.trim().toLowerCase(),n=rw(e),r=t.startsWith("mcp__");return n?n===Fn.read_file?"read_file":n===Fn.append_file?"append_file":n===Fn.write_task_plan?"write_task_plan":n===Fn.pull_file?"pull_file":n===Fn.list_file?"list_file":n===Fn.list_dir?"list_dir":n===Fn.grep_text?"grep_text":n===Fn.grep_files?"grep_files":n===Fn.glob_files?"glob_files":n===Fn.write_memory?"write_memory":n===Fn.request_patch?"request_patch":n===Fn.status_update?"status_update":n===Fn.write_question?"write_question":n===Fn.lab_quests?"lab_quests":n===Fn.lab_pi_sleep?"lab_pi_sleep":n===Fn.lab_baseline?"lab_baseline":n===Fn.bash_exec&&r?"bash_exec":null:null}function wo(e){if(!e)return"";const t=e.path??e.file_path??e.filePath??e.file??e.dir_path??e.target_path??e.targetPath;return typeof t=="string"?t:""}function $x(e){if(e==null)return{text:"",message:""};if(typeof e=="string")return{text:e,message:""};if(typeof e!="object")return{text:String(e),message:""};const t=e,n=typeof t.message=="string"?t.message:"";let r="";const a=t.content_line_numbered;if(typeof a=="string"&&a.trim())return{text:a,message:n};const i=t.content;if(Array.isArray(i))for(let o=i.length-1;o>=0;o-=1){const u=i[o];if(typeof u=="string"&&u.trim()){r=u;break}if(u&&typeof u=="object"){const d=u.text;if(typeof d=="string"&&d.trim()){r=d;break}}}else if(typeof i=="string")r=i;else if(i&&typeof i=="object"){const o=i,u=o.content_line_numbered;if(typeof u=="string"&&u.trim())r=u;else{const d=o.text;typeof d=="string"&&(r=d)}}return!r&&typeof t.text=="string"&&(r=t.text),{text:r,message:n}}const Fx=e=>{const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n))return n}catch{return null}return null},Ku=e=>{if(e==null)return[];if(typeof e=="string")return e.trim()?[e]:[];if(Array.isArray(e))return e.flatMap(t=>Ku(t));if(typeof e=="object"){const t=e,n=t.text;if(typeof n=="string"&&n.trim())return[n];const r=t.content;if(r!=null)return Ku(r)}return[]},aw=e=>{let t=[],n="",r,a="";for(const i of e){const o=Fx(i);if(o){!t.length&&Array.isArray(o.items)&&(t=o.items),!n&&typeof o.content=="string"&&(n=o.content),r==null&&typeof o.truncated=="boolean"&&(r=o.truncated);continue}!a&&i.trim()&&(a=i)}return!n&&a&&(n=a),{items:t,content:n,truncated:r}};function Xl(e){if(e==null)return{items:[],content:"",truncated:!1};if(typeof e=="string"){const u=Fx(e);return u?{items:Array.isArray(u.items)?u.items:[],content:typeof u.content=="string"?u.content:"",truncated:typeof u.truncated=="boolean"?u.truncated:!1}:{items:[],content:e,truncated:!1}}if(typeof e!="object")return{items:[],content:String(e),truncated:!1};const t=e;let n=Array.isArray(t.items)?t.items:[],r="",a=!!t.truncated;const i=t.structured_content;if(i&&typeof i=="object"&&!Array.isArray(i)){const u=i;!n.length&&Array.isArray(u.items)&&(n=u.items),!r&&typeof u.content=="string"&&(r=u.content),!a&&typeof u.truncated=="boolean"&&(a=u.truncated)}const o=Ku(t.content);if(o.length>0){const u=aw(o);!n.length&&u.items.length>0&&(n=u.items),!r&&u.content&&(r=u.content),!a&&typeof u.truncated=="boolean"&&(a=u.truncated)}if(!n.length&&!r){const u=t.result;if(u&&u!==e){const f=Xl(u);if(f.items.length>0||f.content)return f}const d=t.content;if(d&&d!==e&&typeof d=="object"&&!Array.isArray(d)){const f=Xl(d);if(f.items.length>0||f.content)return f}}return{items:n,content:r,truncated:a}}function zx(e){if(e==null||typeof e!="object")return"";const t=e;if(typeof t.message=="string"&&t.message.trim())return t.message;if(typeof t.error=="string"&&t.error.trim())return t.error;const n=t.errors;if(Array.isArray(n)){const r=n.map(a=>String(a).trim()).filter(Boolean);if(r.length>0)return r.join(", ")}return""}const iw="ds:file:reload",ow=1500,lw=e=>e.trim().startsWith("/"),cw=(e,t)=>{const n=e.trim();return n?lw(n)?bo(n):t?vx([...Kl(t),...Kl(n)]):bo(n):""},uw=e=>{const t=Ur.getState();return e||(t.activeServerId?t.activeServerId:t.servers.length===1?t.servers[0].id:null)},Ox=e=>Ur.getState().servers.find(n=>n.id===e)?.server_root??"/",dw=e=>tx(e)??Qs.CODE_EDITOR,fw=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e),pw=e=>{const t=[e.metadata?.task_id,e.metadata?.taskId,e.metadata?.agent_kernel_task_id,e.metadata?.session_id,e.metadata?.lab_session_id,e.metadata?.resume_task_id,e.args?.task_id,e.args?.taskId,e.sessionId];for(const n of t){if(typeof n!="string")continue;const r=n.trim();if(!(!r||r.startsWith("draft-")))return r}return null},mw=(e,t)=>{if(!e)return e;const n=bo(e),r="/.core/memory/working",a=n.indexOf(r);if(a===-1)return e;const i=n.slice(0,a),o=n.slice(a+r.length);let u=Kl(o),d=t;return!d&&u.length>0&&fw(u[0])&&(d=u[0],u=u.slice(1)),d?(u.length>0&&u[0]===d&&(u=u.slice(1)),vx([...Kl(i),".core","planning",d,...u])):e},Bx=e=>{const t=bo(e);return t.includes("/.core/memory/working")||t.includes("/.core/planning/")?"planning":"cli"},hw=e=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("ds:explorer:focus",{detail:e}))},xw=e=>{typeof window>"u"||window.dispatchEvent(new CustomEvent(iw,{detail:e}))},gw=e=>typeof window>"u"?Promise.resolve():new Promise(t=>{let n=!1;const r=()=>{n||(n=!0,window.clearTimeout(a),t())},a=window.setTimeout(r,ow),i={target:e.target,projectId:e.projectId,onComplete:r};window.dispatchEvent(new CustomEvent(ob,{detail:i}))}),yw=e=>{const t=li.getState(),n=Ox(e.serverId),r=ex({projectId:e.projectId,serverId:e.serverId,path:e.path}),a=lb(e.path),i=dw(e.path);t.openTab({pluginId:i,context:{type:"file",resourceId:r,resourcePath:ma({serverId:e.serverId,path:e.path,serverRoot:n}),resourceName:a,customData:{projectId:e.projectId,fileSource:"cli",cliServerId:e.serverId,cliPath:e.path,cliRoot:n,readOnly:e.readOnly??!1,readonly:e.readOnly??!1,lab_context:!0,lab_session_id:e.sessionId??null}},title:a})},bw=e=>{const t=ex({projectId:e.projectId,serverId:e.serverId,path:e.path}),n=qu.getState();n.getEntry(e.projectId,t)&&n.reload({projectId:e.projectId,fileId:t}).catch(r=>{console.warn("[LabCliEffect] Reload failed:",r)}),xw({projectId:e.projectId,fileId:t,filePath:e.path,source:"lab-cli"})},vw=e=>{const t=sw.getState(),n=nw(e.serverId,e.path);t.highlight(n),e.kind==="read"?t.markRead(n):e.kind==="write"&&t.markWrite(n);const r=Bx(e.path);hw({target:r,projectId:e.projectId,path:e.path}),e.kind==="write"&&yw(e)},_w=new Set(["append_file","write_task_plan","write_memory","request_patch","pull_file"]),ww=new Set(["file_read","file_info"]),Sw=new Set(["file_write","file_str_replace","file_patch","ds_system_write_file","ds_system_append_file"]),Su=new Map,kw=e=>{const t=e.tool_call_id;return typeof t=="string"&&t.trim()?t.trim():""},Nw=e=>{const t=e.content;return!t||typeof t!="object"||Array.isArray(t)?null:t},jw=e=>{const t=Nw(e);if(!t)return"";const n=wo(t);if(n)return n;const r=typeof t.written_path=="string"?t.written_path:"";if(r)return r;const a=t.result;if(a&&typeof a=="object"&&!Array.isArray(a)){const i=wo(a);if(i)return i;if(typeof a.written_path=="string")return a.written_path}return""},Tw=e=>{if(!ib.getState().followEffects||!e.projectId)return!1;const n=e.functionName.trim().toLowerCase(),r=n.startsWith("mcp__")?n.split("__").slice(-1)[0]??n:n,a=yr(e.functionName);let i=null;if(a)if(a==="read_file")i="read";else if(_w.has(a))i="write";else return!1;else if(r)if(ww.has(r))i="read";else if(Sw.has(r))i="write";else return!1;else return!1;const o=a==="request_patch"||r==="file_patch"||r==="ds_system_request_patch",u=e.toolData.args&&typeof e.toolData.args=="object"&&!Array.isArray(e.toolData.args)?e.toolData.args:{},d=e.toolData.metadata&&typeof e.toolData.metadata=="object"?e.toolData.metadata:null,f=wo(u)||jw(e.toolData),p=kw(e.toolData),h=uw(e.cliServerId);if(!h)return!1;const y=Ox(h),g=pw({metadata:d,args:u,sessionId:e.sessionId??null}),T=f?cw(f,y):"",_=(T?mw(T,g):"")||T;if(e.status==="calling")return p&&_&&Su.set(p,{serverId:h,path:_}),!1;if(e.status!=="called")return!1;let b=h,E=_;if(!E&&p){const M=Su.get(p);M&&(b=M.serverId,E=M.path)}if(p&&Su.delete(p),!E)return!1;const R={projectId:e.projectId,sessionId:e.sessionId??null,serverId:b,path:E,kind:i,readOnly:e.readOnly},A=Bx(E),C=()=>{vw(R),i==="write"&&o&&bw(R)};return gw({target:A,projectId:e.projectId}).then(C),!0};function Aw(e,t){const n=getComputedStyle(e),r=parseFloat(n.fontSize);return t*r}function Cw(e,t){const n=getComputedStyle(e.ownerDocument.body),r=parseFloat(n.fontSize);return t*r}function Ew(e){return e/100*window.innerHeight}function Rw(e){return e/100*window.innerWidth}function Iw(e){switch(typeof e){case"number":return[e,"px"];case"string":{const t=parseFloat(e);return e.endsWith("%")?[t,"%"]:e.endsWith("px")?[t,"px"]:e.endsWith("rem")?[t,"rem"]:e.endsWith("em")?[t,"em"]:e.endsWith("vh")?[t,"vh"]:e.endsWith("vw")?[t,"vw"]:[t,"%"]}}}function bl({groupSize:e,panelElement:t,styleProp:n}){let r;const[a,i]=Iw(n);switch(i){case"%":{r=a/100*e;break}case"px":{r=a;break}case"rem":{r=Cw(t,a);break}case"em":{r=Aw(t,a);break}case"vh":{r=Ew(a);break}case"vw":{r=Rw(a);break}}return r}function xs(e){return parseFloat(e.toFixed(3))}function hi({group:e}){const{orientation:t,panels:n}=e;return n.reduce((r,a)=>(r+=t==="horizontal"?a.element.offsetWidth:a.element.offsetHeight,r),0)}function Gu(e){const{panels:t}=e,n=hi({group:e});return n===0?t.map(r=>({groupResizeBehavior:r.panelConstraints.groupResizeBehavior,collapsedSize:0,collapsible:r.panelConstraints.collapsible===!0,defaultSize:void 0,disabled:r.panelConstraints.disabled,minSize:0,maxSize:100,panelId:r.id})):t.map(r=>{const{element:a,panelConstraints:i}=r;let o=0;if(i.collapsedSize!==void 0){const p=bl({groupSize:n,panelElement:a,styleProp:i.collapsedSize});o=xs(p/n*100)}let u;if(i.defaultSize!==void 0){const p=bl({groupSize:n,panelElement:a,styleProp:i.defaultSize});u=xs(p/n*100)}let d=0;if(i.minSize!==void 0){const p=bl({groupSize:n,panelElement:a,styleProp:i.minSize});d=xs(p/n*100)}let f=100;if(i.maxSize!==void 0){const p=bl({groupSize:n,panelElement:a,styleProp:i.maxSize});f=xs(p/n*100)}return{groupResizeBehavior:i.groupResizeBehavior,collapsedSize:o,collapsible:i.collapsible===!0,defaultSize:u,disabled:i.disabled,minSize:d,maxSize:f,panelId:r.id}})}function Qt(e,t="Assertion error"){if(!e)throw Error(t)}function Qu(e,t){return Array.from(t).sort(e==="horizontal"?Mw:Lw)}function Mw(e,t){const n=e.element.offsetLeft-t.element.offsetLeft;return n!==0?n:e.element.offsetWidth-t.element.offsetWidth}function Lw(e,t){const n=e.element.offsetTop-t.element.offsetTop;return n!==0?n:e.element.offsetHeight-t.element.offsetHeight}function qx(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&e.nodeType===Node.ELEMENT_NODE}function Ux(e,t){return{x:e.x>=t.left&&e.x<=t.right?0:Math.min(Math.abs(e.x-t.left),Math.abs(e.x-t.right)),y:e.y>=t.top&&e.y<=t.bottom?0:Math.min(Math.abs(e.y-t.top),Math.abs(e.y-t.bottom))}}function Pw({orientation:e,rects:t,targetRect:n}){const r={x:n.x+n.width/2,y:n.y+n.height/2};let a,i=Number.MAX_VALUE;for(const o of t){const{x:u,y:d}=Ux(r,o),f=e==="horizontal"?u:d;f<i&&(i=f,a=o)}return Qt(a,"No rect found"),a}let vl;function Dw(){return vl===void 0&&(typeof matchMedia=="function"?vl=!!matchMedia("(pointer:coarse)").matches:vl=!1),vl}function Wx(e){const{element:t,orientation:n,panels:r,separators:a}=e,i=Qu(n,Array.from(t.children).filter(qx).map(T=>({element:T}))).map(({element:T})=>T),o=[];let u=!1,d=!1,f=-1,p=-1,h=0,y,g=[];{let T=-1;for(const w of i)w.hasAttribute("data-panel")&&(T++,w.ariaDisabled===null&&(h++,f===-1&&(f=T),p=T))}if(h>1){let T=-1;for(const w of i)if(w.hasAttribute("data-panel")){T++;const _=r.find(b=>b.element===w);if(_){if(y){const b=y.element.getBoundingClientRect(),E=w.getBoundingClientRect();let R;if(d){const A=n==="horizontal"?new DOMRect(b.right,b.top,0,b.height):new DOMRect(b.left,b.bottom,b.width,0),C=n==="horizontal"?new DOMRect(E.left,E.top,0,E.height):new DOMRect(E.left,E.top,E.width,0);switch(g.length){case 0:{R=[A,C];break}case 1:{const M=g[0],U=Pw({orientation:n,rects:[b,E],targetRect:M.element.getBoundingClientRect()});R=[M,U===b?C:A];break}default:{R=g;break}}}else g.length?R=g:R=[n==="horizontal"?new DOMRect(b.right,E.top,E.left-b.right,E.height):new DOMRect(E.left,b.bottom,E.width,E.top-b.bottom)];for(const A of R){let C="width"in A?A:A.element.getBoundingClientRect();const M=Dw()?e.resizeTargetMinimumSize.coarse:e.resizeTargetMinimumSize.fine;if(C.width<M){const Q=M-C.width;C=new DOMRect(C.x-Q/2,C.y,C.width+Q,C.height)}if(C.height<M){const Q=M-C.height;C=new DOMRect(C.x,C.y-Q/2,C.width,C.height+Q)}const U=T<=f||T>p;!u&&!U&&o.push({group:e,groupSize:hi({group:e}),panels:[y,_],separator:"width"in A?void 0:A,rect:C}),u=!1}}d=!1,y=_,g=[]}}else if(w.hasAttribute("data-separator")){w.ariaDisabled!==null&&(u=!0);const _=a.find(b=>b.element===w);_?g.push(_):(y=void 0,g=[])}else d=!0}return o}let Hx=class{#e={};addListener(t,n){const r=this.#e[t];return r===void 0?this.#e[t]=[n]:r.includes(n)||r.push(n),()=>{this.removeListener(t,n)}}emit(t,n){const r=this.#e[t];if(r!==void 0)if(r.length===1)r[0].call(null,n);else{let a=!1,i=null;const o=Array.from(r);for(let u=0;u<o.length;u++){const d=o[u];try{d.call(null,n)}catch(f){i===null&&(a=!0,i=f)}}if(a)throw i}}removeAllListeners(){this.#e={}}removeListener(t,n){const r=this.#e[t];if(r!==void 0){const a=r.indexOf(n);a>=0&&r.splice(a,1)}}},gr=new Map;const Vx=new Hx;function $w(e){gr=new Map(gr),gr.delete(e)}function hm(e,t){for(const[n]of gr)if(n.id===e)return n}function Kr(e,t){for(const[n,r]of gr)if(n.id===e)return r;if(t)throw Error(`Could not find data for Group with id ${e}`)}function Sa(){return gr}function kd(e,t){return Vx.addListener("groupChange",n=>{n.group.id===e&&t(n)})}function jr(e,t){const n=gr.get(e);gr=new Map(gr),gr.set(e,t),Vx.emit("groupChange",{group:e,prev:n,next:t})}function Fw(e,t,n){let r,a={x:1/0,y:1/0};for(const i of t){const o=Ux(n,i.rect);switch(e){case"horizontal":{o.x<=a.x&&(r=i,a=o);break}case"vertical":{o.y<=a.y&&(r=i,a=o);break}}}return r?{distance:a,hitRegion:r}:void 0}function zw(e){return e!==null&&typeof e=="object"&&"nodeType"in e&&e.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function Ow(e,t){if(e===t)throw new Error("Cannot compare node with itself");const n={a:ym(e),b:ym(t)};let r;for(;n.a.at(-1)===n.b.at(-1);)r=n.a.pop(),n.b.pop();Qt(r,"Stacking order can only be calculated for elements with a common ancestor");const a={a:gm(xm(n.a)),b:gm(xm(n.b))};if(a.a===a.b){const i=r.childNodes,o={a:n.a.at(-1),b:n.b.at(-1)};let u=i.length;for(;u--;){const d=i[u];if(d===o.a)return 1;if(d===o.b)return-1}}return Math.sign(a.a-a.b)}const Bw=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function qw(e){const t=getComputedStyle(Kx(e)??e).display;return t==="flex"||t==="inline-flex"}function Uw(e){const t=getComputedStyle(e);return!!(t.position==="fixed"||t.zIndex!=="auto"&&(t.position!=="static"||qw(e))||+t.opacity<1||"transform"in t&&t.transform!=="none"||"webkitTransform"in t&&t.webkitTransform!=="none"||"mixBlendMode"in t&&t.mixBlendMode!=="normal"||"filter"in t&&t.filter!=="none"||"webkitFilter"in t&&t.webkitFilter!=="none"||"isolation"in t&&t.isolation==="isolate"||Bw.test(t.willChange)||t.webkitOverflowScrolling==="touch")}function xm(e){let t=e.length;for(;t--;){const n=e[t];if(Qt(n,"Missing node"),Uw(n))return n}return null}function gm(e){return e&&Number(getComputedStyle(e).zIndex)||0}function ym(e){const t=[];for(;e;)t.push(e),e=Kx(e);return t}function Kx(e){const{parentNode:t}=e;return zw(t)?t.host:t}function Ww(e,t){return e.x<t.x+t.width&&e.x+e.width>t.x&&e.y<t.y+t.height&&e.y+e.height>t.y}function Hw({groupElement:e,hitRegion:t,pointerEventTarget:n}){if(!qx(n)||n.contains(e)||e.contains(n))return!0;if(Ow(n,e)>0){let r=n;for(;r;){if(r.contains(e))return!0;if(Ww(r.getBoundingClientRect(),t))return!1;r=r.parentElement}}return!0}function Nd(e,t){const n=[];return t.forEach((r,a)=>{if(a.disabled)return;const i=Wx(a),o=Fw(a.orientation,i,{x:e.clientX,y:e.clientY});o&&o.distance.x<=0&&o.distance.y<=0&&Hw({groupElement:a.element,hitRegion:o.hitRegion.rect,pointerEventTarget:e.target})&&n.push(o.hitRegion)}),n}function Vw(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!=t[n])return!1;return!0}function rs(e,t,n=0){return Math.abs(xs(e)-xs(t))<=n}function hr(e,t){return rs(e,t)?0:e>t?1:-1}function ii({overrideDisabledPanels:e,panelConstraints:t,prevSize:n,size:r}){const{collapsedSize:a=0,collapsible:i,disabled:o,maxSize:u=100,minSize:d=0}=t;if(o&&!e)return n;if(hr(r,d)<0)if(i){const f=(a+d)/2;hr(r,f)<0?r=a:r=d}else r=d;return r=Math.min(u,r),r=xs(r),r}function So({delta:e,initialLayout:t,panelConstraints:n,pivotIndices:r,prevLayout:a,trigger:i}){if(rs(e,0))return t;const o=i==="imperative-api",u=Object.values(t),d=Object.values(a),f=[...u],[p,h]=r;Qt(p!=null,"Invalid first pivot index"),Qt(h!=null,"Invalid second pivot index");let y=0;switch(i){case"keyboard":{{const w=e<0?h:p,_=n[w];Qt(_,`Panel constraints not found for index ${w}`);const{collapsedSize:b=0,collapsible:E,minSize:R=0}=_;if(E){const A=u[w];if(Qt(A!=null,`Previous layout not found for panel index ${w}`),rs(A,b)){const C=R-A;hr(C,Math.abs(e))>0&&(e=e<0?0-C:C)}}}{const w=e<0?p:h,_=n[w];Qt(_,`No panel constraints found for index ${w}`);const{collapsedSize:b=0,collapsible:E,minSize:R=0}=_;if(E){const A=u[w];if(Qt(A!=null,`Previous layout not found for panel index ${w}`),rs(A,R)){const C=A-b;hr(C,Math.abs(e))>0&&(e=e<0?0-C:C)}}}break}default:{const w=e<0?h:p,_=n[w];Qt(_,`Panel constraints not found for index ${w}`);const b=u[w],{collapsible:E,collapsedSize:R,minSize:A}=_;if(E&&hr(b,A)<0)if(e>0){const C=A-R,M=C/2,U=b+e;hr(U,A)<0&&(e=hr(e,M)<=0?0:C)}else{const C=A-R,M=100-C/2,U=b-e;hr(U,A)<0&&(e=hr(100+e,M)>0?0:-C)}break}}{const w=e<0?1:-1;let _=e<0?h:p,b=0;for(;;){const R=u[_];Qt(R!=null,`Previous layout not found for panel index ${_}`);const A=ii({overrideDisabledPanels:o,panelConstraints:n[_],prevSize:R,size:100})-R;if(b+=A,_+=w,_<0||_>=n.length)break}const E=Math.min(Math.abs(e),Math.abs(b));e=e<0?0-E:E}{let w=e<0?p:h;for(;w>=0&&w<n.length;){const _=Math.abs(e)-Math.abs(y),b=u[w];Qt(b!=null,`Previous layout not found for panel index ${w}`);const E=b-_,R=ii({overrideDisabledPanels:o,panelConstraints:n[w],prevSize:b,size:E});if(!rs(b,R)&&(y+=b-R,f[w]=R,y.toFixed(3).localeCompare(Math.abs(e).toFixed(3),void 0,{numeric:!0})>=0))break;e<0?w--:w++}}if(Vw(d,f))return a;{const w=e<0?h:p,_=u[w];Qt(_!=null,`Previous layout not found for panel index ${w}`);const b=_+y,E=ii({overrideDisabledPanels:o,panelConstraints:n[w],prevSize:_,size:b});if(f[w]=E,!rs(E,b)){let R=b-E,A=e<0?h:p;for(;A>=0&&A<n.length;){const C=f[A];Qt(C!=null,`Previous layout not found for panel index ${A}`);const M=C+R,U=ii({overrideDisabledPanels:o,panelConstraints:n[A],prevSize:C,size:M});if(rs(C,U)||(R-=U-C,f[A]=U),rs(R,0))break;e>0?A--:A++}}}const g=Object.values(f).reduce((w,_)=>_+w,0);if(!rs(g,100,.1))return a;const T=Object.keys(a);return f.reduce((w,_,b)=>(w[T[b]]=_,w),{})}function ba(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(t[n]===void 0||hr(e[n],t[n])!==0)return!1;return!0}function va({layout:e,panelConstraints:t}){const n=Object.values(e),r=[...n],a=r.reduce((u,d)=>u+d,0);if(r.length!==t.length)throw Error(`Invalid ${t.length} panel layout: ${r.map(u=>`${u}%`).join(", ")}`);if(!rs(a,100)&&r.length>0)for(let u=0;u<t.length;u++){const d=r[u];Qt(d!=null,`No layout data found for index ${u}`);const f=100/a*d;r[u]=f}let i=0;for(let u=0;u<t.length;u++){const d=n[u];Qt(d!=null,`No layout data found for index ${u}`);const f=r[u];Qt(f!=null,`No layout data found for index ${u}`);const p=ii({overrideDisabledPanels:!0,panelConstraints:t[u],prevSize:d,size:f});f!=p&&(i+=f-p,r[u]=p)}if(!rs(i,0))for(let u=0;u<t.length;u++){const d=r[u];Qt(d!=null,`No layout data found for index ${u}`);const f=d+i,p=ii({overrideDisabledPanels:!0,panelConstraints:t[u],prevSize:d,size:f});if(d!==p&&(i-=p-d,r[u]=p,rs(i,0)))break}const o=Object.keys(e);return r.reduce((u,d,f)=>(u[o[f]]=d,u),{})}function Gx({groupId:e,panelId:t}){const n=()=>{const u=Sa();for(const[d,{defaultLayoutDeferred:f,derivedPanelConstraints:p,layout:h,groupSize:y,separatorToPanels:g}]of u)if(d.id===e)return{defaultLayoutDeferred:f,derivedPanelConstraints:p,group:d,groupSize:y,layout:h,separatorToPanels:g};throw Error(`Group ${e} not found`)},r=()=>{const u=n().derivedPanelConstraints.find(d=>d.panelId===t);if(u!==void 0)return u;throw Error(`Panel constraints not found for Panel ${t}`)},a=()=>{const u=n().group.panels.find(d=>d.id===t);if(u!==void 0)return u;throw Error(`Layout not found for Panel ${t}`)},i=()=>{const u=n().layout[t];if(u!==void 0)return u;throw Error(`Layout not found for Panel ${t}`)},o=u=>{const d=i();if(u===d)return;const{defaultLayoutDeferred:f,derivedPanelConstraints:p,group:h,groupSize:y,layout:g,separatorToPanels:T}=n(),w=h.panels.findIndex(R=>R.id===t),_=w===h.panels.length-1,b=So({delta:_?d-u:u-d,initialLayout:g,panelConstraints:p,pivotIndices:_?[w-1,w]:[w,w+1],prevLayout:g,trigger:"imperative-api"}),E=va({layout:b,panelConstraints:p});ba(g,E)||jr(h,{defaultLayoutDeferred:f,derivedPanelConstraints:p,groupSize:y,layout:E,separatorToPanels:T})};return{collapse:()=>{const{collapsible:u,collapsedSize:d}=r(),{mutableValues:f}=a(),p=i();u&&p!==d&&(f.expandToSize=p,o(d))},expand:()=>{const{collapsible:u,collapsedSize:d,minSize:f}=r(),{mutableValues:p}=a(),h=i();if(u&&h===d){let y=p.expandToSize??f;y===0&&(y=1),o(y)}},getSize:()=>{const{group:u}=n(),d=i(),{element:f}=a(),p=u.orientation==="horizontal"?f.offsetWidth:f.offsetHeight;return{asPercentage:d,inPixels:p}},isCollapsed:()=>{const{collapsible:u,collapsedSize:d}=r(),f=i();return u&&rs(d,f)},resize:u=>{if(i()!==u){let d;switch(typeof u){case"number":{const{group:f}=n(),p=hi({group:f});d=xs(u/p*100);break}case"string":{d=parseFloat(u);break}}o(d)}}}}function bm(e){if(e.defaultPrevented)return;const t=Sa();Nd(e,t).forEach(n=>{if(n.separator){const r=n.panels.find(a=>a.panelConstraints.defaultSize!==void 0);if(r){const a=r.panelConstraints.defaultSize,i=Gx({groupId:n.group.id,panelId:r.id});i&&a!==void 0&&(i.resize(a),e.preventDefault())}}})}function $l(e){const t=Sa();for(const[n]of t)if(n.separators.some(r=>r.element===e))return n;throw Error("Could not find parent Group for separator element")}function Qx({groupId:e}){const t=()=>{const n=Sa();for(const[r,a]of n)if(r.id===e)return{group:r,...a};throw Error(`Could not find Group with id "${e}"`)};return{getLayout(){const{defaultLayoutDeferred:n,layout:r}=t();return n?{}:r},setLayout(n){const{defaultLayoutDeferred:r,derivedPanelConstraints:a,group:i,groupSize:o,layout:u,separatorToPanels:d}=t(),f=va({layout:n,panelConstraints:a});return r?u:(ba(u,f)||jr(i,{defaultLayoutDeferred:r,derivedPanelConstraints:a,groupSize:o,layout:f,separatorToPanels:d}),f)}}}function fa(e,t){const n=$l(e),r=Kr(n.id,!0),a=n.separators.find(p=>p.element===e);Qt(a,"Matching separator not found");const i=r.separatorToPanels.get(a);Qt(i,"Matching panels not found");const o=i.map(p=>n.panels.indexOf(p)),u=Qx({groupId:n.id}).getLayout(),d=So({delta:t,initialLayout:u,panelConstraints:r.derivedPanelConstraints,pivotIndices:o,prevLayout:u,trigger:"keyboard"}),f=va({layout:d,panelConstraints:r.derivedPanelConstraints});ba(u,f)||jr(n,{defaultLayoutDeferred:r.defaultLayoutDeferred,derivedPanelConstraints:r.derivedPanelConstraints,groupSize:r.groupSize,layout:f,separatorToPanels:r.separatorToPanels})}function vm(e){if(e.defaultPrevented)return;const t=e.currentTarget,n=$l(t);if(!n.disabled)switch(e.key){case"ArrowDown":{e.preventDefault(),n.orientation==="vertical"&&fa(t,5);break}case"ArrowLeft":{e.preventDefault(),n.orientation==="horizontal"&&fa(t,-5);break}case"ArrowRight":{e.preventDefault(),n.orientation==="horizontal"&&fa(t,5);break}case"ArrowUp":{e.preventDefault(),n.orientation==="vertical"&&fa(t,-5);break}case"End":{e.preventDefault(),fa(t,100);break}case"Enter":{e.preventDefault();const r=$l(t),a=Kr(r.id,!0),{derivedPanelConstraints:i,layout:o,separatorToPanels:u}=a,d=r.separators.find(y=>y.element===t);Qt(d,"Matching separator not found");const f=u.get(d);Qt(f,"Matching panels not found");const p=f[0],h=i.find(y=>y.panelId===p.id);if(Qt(h,"Panel metadata not found"),h.collapsible){const y=o[p.id],g=h.collapsedSize===y?r.mutableState.expandedPanelSizes[p.id]??h.minSize:h.collapsedSize;fa(t,g-y)}break}case"F6":{e.preventDefault();const r=$l(t).separators.map(o=>o.element),a=Array.from(r).findIndex(o=>o===e.currentTarget);Qt(a!==null,"Index not found");const i=e.shiftKey?a>0?a-1:r.length-1:a+1<r.length?a+1:0;r[i].focus({preventScroll:!0});break}case"Home":{e.preventDefault(),fa(t,-100);break}}}let ci={cursorFlags:0,state:"inactive"};const jd=new Hx;function _a(){return ci}function Kw(e){return jd.addListener("change",e)}function Gw(e){const t=ci,n={...ci};n.cursorFlags=e,ci=n,jd.emit("change",{prev:t,next:n})}function ui(e){const t=ci;ci=e,jd.emit("change",{prev:t,next:e})}function _m(e){if(e.defaultPrevented||e.pointerType==="mouse"&&e.button>0)return;const t=Sa(),n=Nd(e,t),r=new Map;let a=!1;n.forEach(i=>{i.separator&&(a||(a=!0,i.separator.element.focus({preventScroll:!0})));const o=t.get(i.group);o&&r.set(i.group,o.layout)}),ui({cursorFlags:0,hitRegions:n,initialLayoutMap:r,pointerDownAtPoint:{x:e.clientX,y:e.clientY},state:"active"}),n.length&&e.preventDefault()}const Qw=e=>e,ku=()=>{},Xx=1,Yx=2,Zx=4,Jx=8,wm=3,Sm=12;let _l;function km(){return _l===void 0&&(_l=!1,typeof window<"u"&&(window.navigator.userAgent.includes("Chrome")||window.navigator.userAgent.includes("Firefox"))&&(_l=!0)),_l}function Xw({cursorFlags:e,groups:t,state:n}){let r=0,a=0;switch(n){case"active":case"hover":t.forEach(i=>{if(!i.mutableState.disableCursor)switch(i.orientation){case"horizontal":{r++;break}case"vertical":{a++;break}}})}if(!(r===0&&a===0)){switch(n){case"active":{if(e&&km()){const i=(e&Xx)!==0,o=(e&Yx)!==0,u=(e&Zx)!==0,d=(e&Jx)!==0;if(i)return u?"se-resize":d?"ne-resize":"e-resize";if(o)return u?"sw-resize":d?"nw-resize":"w-resize";if(u)return"s-resize";if(d)return"n-resize"}break}}return km()?r>0&&a>0?"move":r>0?"ew-resize":"ns-resize":r>0&&a>0?"grab":r>0?"col-resize":"row-resize"}}const Nm=new WeakMap;function Td(e){if(e.defaultView===null||e.defaultView===void 0)return;let{prevStyle:t,styleSheet:n}=Nm.get(e)??{};n===void 0&&(n=new e.defaultView.CSSStyleSheet,e.adoptedStyleSheets&&e.adoptedStyleSheets.push(n));const r=_a();switch(r.state){case"active":case"hover":{const a=Xw({cursorFlags:r.cursorFlags,groups:r.hitRegions.map(o=>o.group),state:r.state}),i=`*, *:hover {cursor: ${a} !important; }`;if(t===i)return;t=i,a?n.cssRules.length===0?n.insertRule(i):n.replaceSync(i):n.cssRules.length===1&&n.deleteRule(0);break}case"inactive":{t=void 0,n.cssRules.length===1&&n.deleteRule(0);break}}Nm.set(e,{prevStyle:t,styleSheet:n})}function eg({document:e,event:t,hitRegions:n,initialLayoutMap:r,mountedGroups:a,pointerDownAtPoint:i,prevCursorFlags:o}){let u=0;n.forEach(f=>{const{group:p,groupSize:h}=f,{orientation:y,panels:g}=p,{disableCursor:T}=p.mutableState;let w=0;i?y==="horizontal"?w=(t.clientX-i.x)/h*100:w=(t.clientY-i.y)/h*100:y==="horizontal"?w=t.clientX<0?-100:100:w=t.clientY<0?-100:100;const _=r.get(p),b=a.get(p);if(!_||!b)return;const{defaultLayoutDeferred:E,derivedPanelConstraints:R,groupSize:A,layout:C,separatorToPanels:M}=b;if(R&&C&&M){const U=So({delta:w,initialLayout:_,panelConstraints:R,pivotIndices:f.panels.map(Q=>g.indexOf(Q)),prevLayout:C,trigger:"mouse-or-touch"});if(ba(U,C)){if(w!==0&&!T)switch(y){case"horizontal":{u|=w<0?Xx:Yx;break}case"vertical":{u|=w<0?Zx:Jx;break}}}else jr(f.group,{defaultLayoutDeferred:E,derivedPanelConstraints:R,groupSize:A,layout:U,separatorToPanels:M})}});let d=0;t.movementX===0?d|=o&wm:d|=u&wm,t.movementY===0?d|=o&Sm:d|=u&Sm,Gw(d),Td(e)}function jm(e){const t=Sa(),n=_a();switch(n.state){case"active":eg({document:e.currentTarget,event:e,hitRegions:n.hitRegions,initialLayoutMap:n.initialLayoutMap,mountedGroups:t,prevCursorFlags:n.cursorFlags})}}function Tm(e){if(e.defaultPrevented)return;const t=_a(),n=Sa();switch(t.state){case"active":{if(e.buttons===0){ui({cursorFlags:0,state:"inactive"}),t.hitRegions.forEach(r=>{const a=Kr(r.group.id,!0);jr(r.group,a)});return}eg({document:e.currentTarget,event:e,hitRegions:t.hitRegions,initialLayoutMap:t.initialLayoutMap,mountedGroups:n,pointerDownAtPoint:t.pointerDownAtPoint,prevCursorFlags:t.cursorFlags});break}default:{const r=Nd(e,n);r.length===0?t.state!=="inactive"&&ui({cursorFlags:0,state:"inactive"}):ui({cursorFlags:0,hitRegions:r,state:"hover"}),Td(e.currentTarget);break}}}function Am(e){if(e.relatedTarget instanceof HTMLIFrameElement)switch(_a().state){case"hover":ui({cursorFlags:0,state:"inactive"})}}function Cm(e){if(e.defaultPrevented||e.pointerType==="mouse"&&e.button>0)return;const t=_a();switch(t.state){case"active":ui({cursorFlags:0,state:"inactive"}),t.hitRegions.length>0&&(Td(e.currentTarget),t.hitRegions.forEach(n=>{const r=Kr(n.group.id,!0);jr(n.group,r)}),e.preventDefault())}}function Em(e){let t=0,n=0;const r={};for(const i of e)if(i.defaultSize!==void 0){t++;const o=xs(i.defaultSize);n+=o,r[i.panelId]=o}else r[i.panelId]=void 0;const a=e.length-t;if(a!==0){const i=xs((100-n)/a);for(const o of e)o.defaultSize===void 0&&(r[o.panelId]=i)}return r}function Yw(e,t,n){if(!n[0])return;const r=e.panels.find(d=>d.element===t);if(!r||!r.onResize)return;const a=hi({group:e}),i=e.orientation==="horizontal"?r.element.offsetWidth:r.element.offsetHeight,o=r.mutableValues.prevSize,u={asPercentage:xs(i/a*100),inPixels:i};r.mutableValues.prevSize=u,r.onResize(u,r.id,o)}function Zw(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const n in e)if(e[n]!==t[n])return!1;return!0}function Jw({group:e,nextGroupSize:t,prevGroupSize:n,prevLayout:r}){if(n<=0||t<=0||n===t)return r;let a=0,i=0,o=!1;const u=new Map,d=[];for(const h of e.panels){const y=r[h.id]??0;switch(h.panelConstraints.groupResizeBehavior){case"preserve-pixel-size":{o=!0;const g=y/100*n,T=xs(g/t*100);u.set(h.id,T),a+=T;break}case"preserve-relative-size":default:{d.push(h.id),i+=y;break}}}if(!o||d.length===0)return r;const f=100-a,p={...r};if(u.forEach((h,y)=>{p[y]=h}),i>0)for(const h of d){const y=r[h]??0;p[h]=xs(y/i*f)}else{const h=xs(f/d.length);for(const y of d)p[y]=h}return p}function e0(e,t){const n=e.map(a=>a.id),r=Object.keys(t);if(n.length!==r.length)return!1;for(const a of n)if(!r.includes(a))return!1;return!0}const ei=new Map;function t0(e){let t=!0;Qt(e.element.ownerDocument.defaultView,"Cannot register an unmounted Group");const n=e.element.ownerDocument.defaultView.ResizeObserver,r=new Set,a=new Set,i=new n(T=>{for(const w of T){const{borderBoxSize:_,target:b}=w;if(b===e.element){if(t){const E=hi({group:e});if(E===0)return;const R=Kr(e.id);if(!R)return;const A=Gu(e),C=R.defaultLayoutDeferred?Em(A):R.layout,M=Jw({group:e,nextGroupSize:E,prevGroupSize:R.groupSize,prevLayout:C}),U=va({layout:M,panelConstraints:A});if(!R.defaultLayoutDeferred&&ba(R.layout,U)&&Zw(R.derivedPanelConstraints,A)&&R.groupSize===E)return;jr(e,{defaultLayoutDeferred:!1,derivedPanelConstraints:A,groupSize:E,layout:U,separatorToPanels:R.separatorToPanels})}}else Yw(e,b,_)}});i.observe(e.element),e.panels.forEach(T=>{Qt(!r.has(T.id),`Panel ids must be unique; id "${T.id}" was used more than once`),r.add(T.id),T.onResize&&i.observe(T.element)});const o=hi({group:e}),u=Gu(e),d=e.panels.map(({id:T})=>T).join(",");let f=e.mutableState.defaultLayout;f&&(e0(e.panels,f)||(f=void 0));const p=e.mutableState.layouts[d]??f??Em(u),h=va({layout:p,panelConstraints:u}),y=e.element.ownerDocument;ei.set(y,(ei.get(y)??0)+1);const g=new Map;return Wx(e).forEach(T=>{T.separator&&g.set(T.separator,T.panels)}),jr(e,{defaultLayoutDeferred:o===0,derivedPanelConstraints:u,groupSize:o,layout:h,separatorToPanels:g}),e.separators.forEach(T=>{Qt(!a.has(T.id),`Separator ids must be unique; id "${T.id}" was used more than once`),a.add(T.id),T.element.addEventListener("keydown",vm)}),ei.get(y)===1&&(y.addEventListener("dblclick",bm,!0),y.addEventListener("pointerdown",_m,!0),y.addEventListener("pointerleave",jm),y.addEventListener("pointermove",Tm),y.addEventListener("pointerout",Am),y.addEventListener("pointerup",Cm,!0)),function(){t=!1,ei.set(y,Math.max(0,(ei.get(y)??0)-1)),$w(e),e.separators.forEach(T=>{T.element.removeEventListener("keydown",vm)}),ei.get(y)||(y.removeEventListener("dblclick",bm,!0),y.removeEventListener("pointerdown",_m,!0),y.removeEventListener("pointerleave",jm),y.removeEventListener("pointermove",Tm),y.removeEventListener("pointerout",Am),y.removeEventListener("pointerup",Cm,!0)),i.disconnect()}}function n0(){const[e,t]=c.useState({}),n=c.useCallback(()=>t({}),[]);return[e,n]}function Ad(e){const t=c.useId();return`${e??t}`}const ka=typeof window<"u"?c.useLayoutEffect:c.useEffect;function mo(e){const t=c.useRef(e);return ka(()=>{t.current=e},[e]),c.useCallback((...n)=>t.current?.(...n),[t])}function Cd(...e){return mo(t=>{e.forEach(n=>{if(n)switch(typeof n){case"function":{n(t);break}case"object":{n.current=t;break}}})})}function Ed(e){const t=c.useRef({...e});return ka(()=>{for(const n in e)t.current[n]=e[n]},[e]),t.current}const tg=c.createContext(null);function s0(e,t){const n=c.useRef({getLayout:()=>({}),setLayout:Qw});c.useImperativeHandle(t,()=>n.current,[]),ka(()=>{Object.assign(n.current,Qx({groupId:e}))})}function ng({children:e,className:t,defaultLayout:n,disableCursor:r,disabled:a,elementRef:i,groupRef:o,id:u,onLayoutChange:d,onLayoutChanged:f,orientation:p="horizontal",resizeTargetMinimumSize:h={coarse:20,fine:10},style:y,...g}){const T=c.useRef({onLayoutChange:{},onLayoutChanged:{}}),w=mo(V=>{ba(T.current.onLayoutChange,V)||(T.current.onLayoutChange=V,d?.(V))}),_=mo(V=>{ba(T.current.onLayoutChanged,V)||(T.current.onLayoutChanged=V,f?.(V))}),b=Ad(u),E=c.useRef(null),[R,A]=n0(),C=c.useRef({lastExpandedPanelSizes:{},layouts:{},panels:[],resizeTargetMinimumSize:h,separators:[]}),M=Cd(E,i);s0(b,o);const U=mo((V,W)=>{const Z=_a(),Se=hm(V),$e=Kr(V);if($e){let Ne=!1;switch(Z.state){case"active":{Ne=Z.hitRegions.some(G=>G.group===Se);break}}return{flexGrow:$e.layout[W]??1,pointerEvents:Ne?"none":void 0}}return{flexGrow:n?.[W]??1}}),Q=Ed({defaultLayout:n,disableCursor:r}),ae=c.useMemo(()=>({get disableCursor(){return!!Q.disableCursor},getPanelStyles:U,id:b,orientation:p,registerPanel:V=>{const W=C.current;return W.panels=Qu(p,[...W.panels,V]),A(),()=>{W.panels=W.panels.filter(Z=>Z!==V),A()}},registerSeparator:V=>{const W=C.current;return W.separators=Qu(p,[...W.separators,V]),A(),()=>{W.separators=W.separators.filter(Z=>Z!==V),A()}},togglePanelDisabled:(V,W)=>{const Z=C.current.panels.find(Ne=>Ne.id===V);Z&&(Z.panelConstraints.disabled=W);const Se=hm(b),$e=Kr(b);Se&&$e&&jr(Se,{...$e,derivedPanelConstraints:Gu(Se)})},toggleSeparatorDisabled:(V,W)=>{const Z=C.current.separators.find(Se=>Se.id===V);Z&&(Z.disabled=W)}}),[U,b,A,p,Q]),ye=c.useRef(null);return ka(()=>{const V=E.current;if(V===null)return;const W=C.current;let Z;if(Q.defaultLayout!==void 0&&Object.keys(Q.defaultLayout).length===W.panels.length){Z={};for(const I of W.panels){const O=Q.defaultLayout[I.id];O!==void 0&&(Z[I.id]=O)}}const Se={disabled:!!a,element:V,id:b,mutableState:{defaultLayout:Z,disableCursor:!!Q.disableCursor,expandedPanelSizes:C.current.lastExpandedPanelSizes,layouts:C.current.layouts},orientation:p,panels:W.panels,resizeTargetMinimumSize:W.resizeTargetMinimumSize,separators:W.separators};ye.current=Se;const $e=t0(Se),{defaultLayoutDeferred:Ne,derivedPanelConstraints:G,layout:J}=Kr(Se.id,!0);!Ne&&G.length>0&&(w(J),_(J));const $=kd(b,I=>{const{defaultLayoutDeferred:O,derivedPanelConstraints:X,layout:ne}=I.next;if(O||X.length===0)return;const ke=Se.panels.map(({id:Te})=>Te).join(",");Se.mutableState.layouts[ke]=ne,X.forEach(Te=>{if(Te.collapsible){const{layout:Oe}=I.prev??{};if(Oe){const He=rs(Te.collapsedSize,ne[Te.panelId]),ut=rs(Te.collapsedSize,Oe[Te.panelId]);He&&!ut&&(Se.mutableState.expandedPanelSizes[Te.panelId]=Oe[Te.panelId])}}});const de=_a().state!=="active";w(ne),de&&_(ne)});return()=>{ye.current=null,$e(),$()}},[a,b,_,w,p,R,Q]),c.useEffect(()=>{const V=ye.current;V&&(V.mutableState.defaultLayout=n,V.mutableState.disableCursor=!!r)}),s.jsx(tg.Provider,{value:ae,children:s.jsx("div",{...g,className:t,"data-group":!0,"data-testid":b,id:b,ref:M,style:{height:"100%",width:"100%",overflow:"hidden",...y,display:"flex",flexDirection:p==="horizontal"?"row":"column",flexWrap:"nowrap",touchAction:p==="horizontal"?"pan-y":"pan-x"},children:e})})}ng.displayName="Group";function Rd(){const e=c.useContext(tg);return Qt(e,"Group Context not found; did you render a Panel or Separator outside of a Group?"),e}function r0(e,t){const{id:n}=Rd(),r=c.useRef({collapse:ku,expand:ku,getSize:()=>({asPercentage:0,inPixels:0}),isCollapsed:()=>!1,resize:ku});c.useImperativeHandle(t,()=>r.current,[]),ka(()=>{Object.assign(r.current,Gx({groupId:n,panelId:e}))})}function sg({children:e,className:t,collapsedSize:n="0%",collapsible:r=!1,defaultSize:a,disabled:i,elementRef:o,groupResizeBehavior:u="preserve-relative-size",id:d,maxSize:f="100%",minSize:p="0%",onResize:h,panelRef:y,style:g,...T}){const w=!!d,_=Ad(d),b=Ed({disabled:i}),E=c.useRef(null),R=Cd(E,o),{getPanelStyles:A,id:C,orientation:M,registerPanel:U,togglePanelDisabled:Q}=Rd(),ae=h!==null,ye=mo((W,Z,Se)=>{h?.(W,d,Se)});ka(()=>{const W=E.current;if(W!==null){const Z={element:W,id:_,idIsStable:w,mutableValues:{expandToSize:void 0,prevSize:void 0},onResize:ae?ye:void 0,panelConstraints:{groupResizeBehavior:u,collapsedSize:n,collapsible:r,defaultSize:a,disabled:b.disabled,maxSize:f,minSize:p}};return U(Z)}},[u,n,r,a,ae,_,w,f,p,ye,U,b]),c.useEffect(()=>{Q(_,!!i)},[i,_,Q]),r0(_,y);const V=c.useSyncExternalStore(W=>kd(C,W),()=>JSON.stringify(A(C,_)),()=>JSON.stringify(A(C,_)));return s.jsx("div",{...T,"aria-disabled":i||void 0,"data-panel":!0,"data-testid":_,id:_,ref:R,style:{...a0,display:"flex",flexBasis:0,flexShrink:1,overflow:"visible",...JSON.parse(V)},children:s.jsx("div",{className:t,style:{maxHeight:"100%",maxWidth:"100%",flexGrow:1,overflow:"auto",...g,touchAction:M==="horizontal"?"pan-y":"pan-x"},children:e})})}sg.displayName="Panel";const a0={minHeight:0,maxHeight:"100%",height:"auto",minWidth:0,maxWidth:"100%",width:"auto",border:"none",borderWidth:0,padding:0,margin:0};function i0({layout:e,panelConstraints:t,panelId:n,panelIndex:r}){let a,i;const o=e[n],u=t.find(d=>d.panelId===n);if(u){const d=u.maxSize,f=u.collapsible?u.collapsedSize:u.minSize,p=[r,r+1];i=va({layout:So({delta:f-o,initialLayout:e,panelConstraints:t,pivotIndices:p,prevLayout:e}),panelConstraints:t})[n],a=va({layout:So({delta:d-o,initialLayout:e,panelConstraints:t,pivotIndices:p,prevLayout:e}),panelConstraints:t})[n]}return{valueControls:n,valueMax:a,valueMin:i,valueNow:o}}function rg({children:e,className:t,disabled:n,elementRef:r,id:a,style:i,...o}){const u=Ad(a),d=Ed({disabled:n}),[f,p]=c.useState({}),[h,y]=c.useState("inactive"),g=c.useRef(null),T=Cd(g,r),{disableCursor:w,id:_,orientation:b,registerSeparator:E,toggleSeparatorDisabled:R}=Rd(),A=b==="horizontal"?"vertical":"horizontal";ka(()=>{const M=g.current;if(M!==null){const U={disabled:d.disabled,element:M,id:u},Q=E(U),ae=Kw(V=>{y(V.next.state!=="inactive"&&V.next.hitRegions.some(W=>W.separator===U)?V.next.state:"inactive")}),ye=kd(_,V=>{const{derivedPanelConstraints:W,layout:Z,separatorToPanels:Se}=V.next,$e=Se.get(U);if($e){const Ne=$e[0],G=$e.indexOf(Ne);p(i0({layout:Z,panelConstraints:W,panelId:Ne.id,panelIndex:G}))}});return()=>{ae(),ye(),Q()}}},[_,u,E,d]),c.useEffect(()=>{R(u,!!n)},[n,u,R]);let C;return n&&!w&&(C="not-allowed"),s.jsx("div",{...o,"aria-controls":f.valueControls,"aria-disabled":n||void 0,"aria-orientation":A,"aria-valuemax":f.valueMax,"aria-valuemin":f.valueMin,"aria-valuenow":f.valueNow,children:e,className:t,"data-separator":n?"disabled":h,"data-testid":u,id:u,ref:T,role:"separator",style:{flexBasis:"auto",cursor:C,...i,flexGrow:0,flexShrink:0,touchAction:"none"},tabIndex:n?void 0:0})}rg.displayName="Separator";const o0=({className:e,orientation:t="horizontal",...n})=>s.jsx(ng,{orientation:t,className:z("flex h-full w-full",t==="vertical"&&"flex-col",e),...n}),Rm=sg,l0=({withHandle:e,className:t,...n})=>s.jsx(rg,{className:z("relative flex w-px items-center justify-center bg-soft-border","focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-soft-accent focus-visible:ring-offset-1","hover:bg-soft-accent/50 hover:w-1 transition-all duration-150 cursor-col-resize","data-[resize-handle-active]:bg-soft-accent data-[resize-handle-active]:w-1 data-[resize-handle-active]:shadow-lg data-[resize-handle-active]:shadow-soft-accent/30",t),...n,children:e&&s.jsx("div",{className:z("z-10 flex h-4 w-3 items-center justify-center rounded-sm border border-soft-border bg-soft-bg-elevated","transition-all duration-150","group-data-[resize-handle-active]:scale-110 group-data-[resize-handle-active]:border-soft-accent group-data-[resize-handle-active]:bg-soft-accent/10"),children:s.jsx(nx,{className:z("h-2.5 w-2.5 text-soft-text-tertiary transition-colors","group-data-[resize-handle-active]:text-soft-accent")})})}),Im=e=>typeof e=="string"?e.trim():"",c0=(e,t)=>{const n=Im(t.title),r=Im(t.latest_message);return{...e,...t,title:n?t.title:e.title??t.title??null,latest_message:r?t.latest_message:e.latest_message??t.latest_message??null,latest_message_at:t.latest_message_at??e.latest_message_at??null,updated_at:t.updated_at??e.updated_at??null,status:t.status??e.status??null,is_shared:t.is_shared??e.is_shared??!1,is_active:t.is_active??e.is_active??!1}},Nu=(e,t)=>{if(t.length===0)return[];const n=new Map(t.map(a=>[a.session_id,a])),r=[];return e.forEach(a=>{const i=n.get(a.session_id);i&&(r.push(c0(a,i)),n.delete(a.session_id))}),t.forEach(a=>{n.has(a.session_id)&&(r.push(a),n.delete(a.session_id))}),r},wl=()=>typeof window>"u"?!1:window.localStorage.getItem("ds_debug_copilot")==="1";function u0(e){const{projectId:t,enabled:n=!0,stream:r=!1}=e,[a,i]=c.useState([]),[o,u]=c.useState({status:"idle"}),d=c.useRef(null),f=c.useCallback(w=>{u(w)},[]),p=c.useCallback(()=>{const w={"Content-Type":"application/json"},{token:_,mode:b}=Zh();return _&&(w.Authorization=`Bearer ${_}`),{headers:w,authMode:b}},[]),h=c.useCallback(w=>{Jh(w,"session_expired")},[]),y=w=>{const _=w.split(/\n/);let b="";const E=[];for(const R of _)if(R){if(R.startsWith("event:")){b=R.slice(6).trim();continue}R.startsWith("data:")&&E.push(R.slice(5).trimStart())}return E.length===0?null:{event:b||"message",data:E.join(`
106
+ `)}},g=c.useCallback(async()=>{if(!n){wl()&&console.info("[Sessions] reload skipped (disabled)"),i([]);return}try{const w=typeof t=="string"&&t.trim().length>0?t:void 0;wl()&&console.info("[Sessions] reload start",{projectId:w??null});const _=await $_(w);wl()&&console.info("[Sessions] reload success",{count:_.sessions?.length??0}),i(b=>Nu(b,_.sessions??[]))}catch(w){wl()&&console.warn("[Sessions] reload failed",w),f({status:"error",error:"fetch_failed"})}},[n,t,f]),T=c.useCallback(async(w=0)=>{if(!n)return;d.current&&(d.current.abort(),d.current=null);const _=new AbortController;d.current=_,f({status:w>0?"reconnecting":"connecting"});const{headers:b,authMode:E}=p();delete b["Content-Type"];const R=new URLSearchParams,A=typeof t=="string"&&t.trim().length>0?t:void 0;A&&R.set("project_id",A);try{const C=await fetch(`${er()}/api/v1/sessions/stream?${R.toString()}`,{method:"GET",headers:b,signal:_.signal});if(C.status===401){if(E==="user"&&w<1&&await Ul()){f({status:"reconnecting"}),await T(w+1);return}f({status:"error",error:"unauthorized"}),h(E);return}if(!C.ok)throw new Error(`HTTP ${C.status}: ${C.statusText}`);f({status:"open"});const M=C.body?.getReader();if(!M)throw new Error("No response body");const U=new TextDecoder;let Q="";for(;;){const{done:ye,value:V}=await M.read();if(ye)break;Q+=U.decode(V,{stream:!0}),Q.includes("\r")&&(Q=Q.replace(/\r\n/g,`
107
+ `));let W=Q.indexOf(`
108
+
109
+ `);for(;W!==-1;){const Z=Q.slice(0,W);Q=Q.slice(W+2);const Se=Z.replace(/\r\n/g,`
110
+ `).trim(),$e=y(Se);if($e&&$e.event==="sessions")try{const Ne=JSON.parse($e.data);Array.isArray(Ne.sessions)&&i(G=>Nu(G,Ne.sessions??[]))}catch(Ne){console.warn("[Sessions SSE] Failed to parse event data",Ne)}W=Q.indexOf(`
111
+
112
+ `)}}const ae=Q.replace(/\r\n/g,`
113
+ `).trim();if(ae){const ye=y(ae);if(ye&&ye.event==="sessions")try{const V=JSON.parse(ye.data);Array.isArray(V.sessions)&&i(W=>Nu(W,V.sessions??[]))}catch(V){console.warn("[Sessions SSE] Failed to parse trailing event data",V)}}f({status:"closed"})}catch(C){if(_.signal.aborted){f({status:"closed"});return}f({status:"error",error:C instanceof Error?C.message:"stream_failed"}),w<1&&T(w+1)}finally{d.current===_&&(d.current=null)}},[p,n,h,t,f]);return c.useEffect(()=>{if(!n){f({status:"idle"}),i([]);return}return g(),r&&T(0),()=>{d.current&&(d.current.abort(),d.current=null)}},[n,t,g,T,r,f]),{sessions:a,setSessions:i,reload:g,connection:o}}const d0="ds:pdf:queue",f0="ds:file:queue",Mm="ds:file:jump";function gs(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(e,{detail:t}))}function Id(){gs("ds:copilot:open",{source:"ui-effect"})}function p0(e){if(!e.parentId)return null;const t=nn.getState().findNode;let n=e.parentId;for(;n;){const r=t(n);if(!r)return null;if(r.type==="folder"&&r.folderKind==="latex")return r;n=r.parentId}return null}function m0(e){const t=e.toLowerCase();return t.endsWith(".tex")||t.endsWith(".bib")}function h0(e){const t=e.toLowerCase();return t.endsWith(".md")||t.endsWith(".markdown")||t.endsWith(".mdx")}function x0(e,t){if(e.type==="notebook")return Qs.NOTEBOOK;const n=tx(e.name);if(n===Qs.NOTEBOOK&&h0(e.name))return n;if(e.mimeType){const r=cb(e.mimeType);if(r)return r===Qs.TEXT_VIEWER&&n?t?.preferEditor&&n===Qs.CODE_VIEWER?Qs.CODE_EDITOR:n:t?.preferEditor&&r===Qs.CODE_VIEWER?Qs.CODE_EDITOR:r}return t?.preferEditor&&n===Qs.CODE_VIEWER?Qs.CODE_EDITOR:n??null}function Qr(e,t,n){const r=li.getState(),a=t.projectId??nn.getState().projectId??void 0;if(a&&m0(e.name)){const d=p0(e);if(d)return r.openTab({pluginId:Qs.LATEX,context:{type:"custom",resourceId:d.id,resourceName:d.name,customData:{projectId:a,latexFolderId:d.id,mainFileId:d.latex?.mainFileId??null,openFileId:e.id}},title:d.name})}const i=x0(e,n);if(!i)return null;const o={type:e.type==="notebook"?"notebook":"file",resourceId:e.id,resourcePath:e.path?Ks(e.path):void 0,resourceName:e.name,mimeType:e.mimeType,customData:a?{projectId:a}:void 0},u=r.findTabByContext(o);return u?(u.pluginId!==i&&r.updateTabPlugin(u.id,i,o),r.setActiveTab(u.id),u.id):r.openTab({pluginId:i,context:o,title:e.name})}function is(e){const t=nn.getState();if(e.fileId){const n=t.findNode(e.fileId);if(n)return n}if(e.filePath){const n=t.findNodeByPath(e.filePath);if(n)return n}return null}function xi(e){return e?e.replace(/^\/FILES\/?/,"").replace(/^\/+/,"").replace(/\/+$/,""):""}function ag(){return typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`pdf-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function g0(e){const t=ag();return{...e,__dsEffectId:t}}function y0(){return ag()}function Fl(e){if(e.type!=="file")return!1;const t=e.name.toLowerCase(),n=(e.mimeType??"").toLowerCase();return t.endsWith(".pdf")||n==="application/pdf"}function b0(e){const t=e.trim().toLowerCase();if(!t)return null;const r=[...nn.getState().nodes];for(;r.length>0;){const a=r.shift();if(a){if(Fl(a)&&a.name.toLowerCase()===t)return a;a.children?.length&&r.push(...a.children)}}return null}function Lm(e){const t=nn.getState();if(e.fileId){const n=t.findNode(e.fileId);if(n&&Fl(n))return n}if(e.filePath){const n=t.findNodeByPath(xi(e.filePath));if(n&&Fl(n))return n}if(e.fileName){const n=xi(e.fileName);if(n.includes("/")){const r=t.findNodeByPath(n);if(r&&Fl(r))return r}return b0(e.fileName)}return null}function ho(e,t){const n=i=>{nn.getState().expandToFile(i.id),Qr(i,{fileId:i.id,filePath:i.path,fileName:i.name}),t?.(i)},r=Lm(e);if(r)return n(r),r;const a=nn.getState();return typeof a.refresh=="function"&&a.refresh().then(()=>{const i=Lm(e);i&&n(i)}),null}function Yl(e,t){if(!t.fileId)return null;const n=g0(t);return bv({id:n.__dsEffectId,name:e,data:n}),gs(d0,{fileId:n.fileId}),n}function v0(e){if(!e.fileId)return null;const t={...e,__dsEffectId:y0()};return yv({id:t.__dsEffectId,data:t}),gs(f0,{fileId:t.fileId}),t}function ig(e){const t=is(e);if(!t)return;const n=nn.getState();n.highlightFile(t.id),n.expandToFile(t.id)}function Xu(e){e.diff&&gs("ds:file:diff",{...e,changeType:e.changeType??(e.created?"create":"update")})}function Ao(e){return e?.surface!=="welcome"}function _0(e,t){const n=i=>{const o=nn.getState();o.markFileRead(i.id),o.highlightFile(i.id),o.expandToFile(i.id),Ao(t)&&i.type!=="folder"&&(Id(),Qr(i,e,{preferEditor:!0}))},r=is(e);if(r){n(r);return}const a=nn.getState();typeof a.refresh=="function"&&a.refresh().then(()=>{const i=is(e);i&&n(i)})}function w0(e,t){const n=i=>{const o=nn.getState();o.markFileWrite(i.id),o.highlightFile(i.id),o.expandToFile(i.id);const u=Ao(t);if(u&&(Id(),Qr(i,e,{preferEditor:!0})),e.diff)if(typeof window>"u")Xu(e);else{const d=u?180:0;window.setTimeout(()=>Xu(e),d)}},r=is(e);if(r){n(r);return}const a=nn.getState();typeof a.refresh=="function"&&a.refresh().then(()=>{const i=is(e);i&&n(i)})}function S0(e){const t=is(e);t&&(Id(),Qr(t,e),ig({...e,fileId:t.id,filePath:t.path}))}function og(e){const t=a=>{const i=e.lineStart??e.line??e.lineEnd,o=e.lineEnd??e.line??e.lineStart;Qr(a,e,{preferEditor:!0});const u=v0({...e,fileId:a.id,fileName:a.name,filePath:a.path??e.filePath,lineStart:i,lineEnd:o});u?gs(Mm,u):gs(Mm,{...e,fileId:a.id,fileName:a.name,filePath:a.path??e.filePath,lineStart:i,lineEnd:o})},n=is(e);if(n){t(n);return}const r=nn.getState();typeof r.refresh=="function"&&r.refresh().then(()=>{const a=is(e);a&&t(a)})}function k0(e,t){const n=nn.getState();typeof n.refresh=="function"&&n.refresh(),Xu({...e,changeType:e.changeType??"delete"}),Ao(t)&&(e.fileId||e.filePath)&&gs("ds:file:deleted",e)}function N0(e,t){const n=nn.getState(),r=e.filePath||e.targetPath,a=o=>{n.markFileMove(o.id),n.highlightFile(o.id),n.expandToFile(o.id),Ao(t)&&o.type!=="folder"&&Qr(o,e,{preferEditor:!0})},i=is(e);if(i&&r&&xi(i.path)!==xi(r)&&typeof n.refresh=="function"){n.refresh().then(()=>{const o=is(e);o&&a(o)});return}if(i){a(i);return}typeof n.refresh=="function"&&n.refresh().then(()=>{const o=is(e);o&&a(o)})}function j0(e,t){const n=nn.getState(),r=e.filePath||e.targetPath,a=o=>{n.markFileRename(o.id),n.highlightFile(o.id),n.expandToFile(o.id),Ao(t)&&o.type!=="folder"&&Qr(o,e,{preferEditor:!0})},i=is(e);if(i&&r&&xi(i.path)!==xi(r)&&typeof n.refresh=="function"){n.refresh().then(()=>{const o=is(e);o&&a(o)});return}if(i){a(i);return}typeof n.refresh=="function"&&n.refresh().then(()=>{const o=is(e);o&&a(o)})}function T0(e){const t=ho({fileId:e.fileId,fileName:e.fileName}),n=Yl("pdf:jump",{...e,fileId:t?.id??e.fileId,fileName:e.fileName??t?.name});n?gs("pdf:navigate",n):gs("pdf:navigate",e)}function A0(e){const t=ho({fileId:e.fileId,fileName:e.fileName}),n=Yl("pdf:annotation_created",{...e,fileId:t?.id??e.fileId,fileName:e.fileName??t?.name});n?gs("pdf:annotation_created",n):gs("pdf:annotation_created",e)}function Md(e){if(!e.fileId&&!e.filePath&&!e.fileName)return;const t=e.page!==void 0||e.annotationId;if(e.fileId&&t){const n=Yl("pdf:jump",{fileId:e.fileId,fileName:e.fileName,page:e.page,annotationId:e.annotationId,mode:e.mode});n&&gs("pdf:navigate",n),ho(e);return}if(t){ho(e,n=>{const r=Yl("pdf:jump",{fileId:n.id,fileName:n.name,page:e.page,annotationId:e.annotationId,mode:e.mode});r&&gs("pdf:navigate",r)});return}ho(e)}function C0(e){if(!e)return;const t={fileId:e.fileId,filePath:e.filePath,fileName:e.fileName};if(e.page){Md({...t,page:e.page});return}const n=e.lineStart??e.lineEnd,r=e.lineEnd??e.lineStart;if(n||r){og({...t,lineStart:n,lineEnd:r});return}const a=is({fileId:e.fileId,filePath:e.filePath});a&&Qr(a,{fileId:a.id,filePath:a.path,fileName:a.name},{preferEditor:!0})}function Pm(e,t){const{name:n,data:r}=e;switch(n){case"file:highlight":ig(r);return;case"file:read":_0(r,t);return;case"file:write":w0(r,t);return;case"file:delete":k0(r,t);return;case"file:move":N0(r,t);return;case"file:rename":j0(r,t);return;case"file:open":S0(r);return;case"file:jump":og(r);return;case"pdf:jump":T0(r);return;case"annotation:created":case"pdf:annotation_created":A0(r);return;case"notebook:focus":case"notebook:block_inserted":gs(n,r);return}}function Ld(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Na=Ld();function lg(e){Na=e}var ha={exec:()=>null};function It(e,t=""){let n=typeof e=="string"?e:e.source,r={replace:(a,i)=>{let o=typeof i=="string"?i:i.source;return o=o.replace(as.caret,"$1"),n=n.replace(a,o),r},getRegex:()=>new RegExp(n,t)};return r}var E0=(()=>{try{return!!new RegExp("(?<=1)(?<!1)")}catch{return!1}})(),as={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}>`)},R0=/^(?:[ \t]*(?:\n|$))+/,I0=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,M0=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Co=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,L0=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Pd=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,cg=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ug=It(cg).replace(/bull/g,Pd).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),P0=It(cg).replace(/bull/g,Pd).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Dd=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,D0=/^[^\n]+/,$d=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,$0=It(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",$d).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),F0=It(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Pd).getRegex(),ac="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|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Fd=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,z0=It("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Fd).replace("tag",ac).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),dg=It(Dd).replace("hr",Co).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ac).getRegex(),O0=It(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",dg).getRegex(),zd={blockquote:O0,code:I0,def:$0,fences:M0,heading:L0,hr:Co,html:z0,lheading:ug,list:F0,newline:R0,paragraph:dg,table:ha,text:D0},Dm=It("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Co).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ac).getRegex(),B0={...zd,lheading:P0,table:Dm,paragraph:It(Dd).replace("hr",Co).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Dm).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ac).getRegex()},q0={...zd,html:It(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Fd).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:ha,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:It(Dd).replace("hr",Co).replace("heading",` *#{1,6} *[^
114
+ ]`).replace("lheading",ug).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},U0=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,W0=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,fg=/^( {2,}|\\)\n(?!\s*$)/,H0=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,ic=/[\p{P}\p{S}]/u,Od=/[\s\p{P}\p{S}]/u,pg=/[^\s\p{P}\p{S}]/u,V0=It(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Od).getRegex(),mg=/(?!~)[\p{P}\p{S}]/u,K0=/(?!~)[\s\p{P}\p{S}]/u,G0=/(?:[^\s\p{P}\p{S}]|~)/u,hg=/(?![*_])[\p{P}\p{S}]/u,Q0=/(?![*_])[\s\p{P}\p{S}]/u,X0=/(?:[^\s\p{P}\p{S}]|[*_])/u,Y0=It(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",E0?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),xg=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,Z0=It(xg,"u").replace(/punct/g,ic).getRegex(),J0=It(xg,"u").replace(/punct/g,mg).getRegex(),gg="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",e1=It(gg,"gu").replace(/notPunctSpace/g,pg).replace(/punctSpace/g,Od).replace(/punct/g,ic).getRegex(),t1=It(gg,"gu").replace(/notPunctSpace/g,G0).replace(/punctSpace/g,K0).replace(/punct/g,mg).getRegex(),n1=It("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,pg).replace(/punctSpace/g,Od).replace(/punct/g,ic).getRegex(),s1=It(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,hg).getRegex(),r1="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",a1=It(r1,"gu").replace(/notPunctSpace/g,X0).replace(/punctSpace/g,Q0).replace(/punct/g,hg).getRegex(),i1=It(/\\(punct)/,"gu").replace(/punct/g,ic).getRegex(),o1=It(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),l1=It(Fd).replace("(?:-->|$)","-->").getRegex(),c1=It("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",l1).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Zl=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,u1=It(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Zl).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),yg=It(/^!?\[(label)\]\[(ref)\]/).replace("label",Zl).replace("ref",$d).getRegex(),bg=It(/^!?\[(ref)\](?:\[\])?/).replace("ref",$d).getRegex(),d1=It("reflink|nolink(?!\\()","g").replace("reflink",yg).replace("nolink",bg).getRegex(),$m=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Bd={_backpedal:ha,anyPunctuation:i1,autolink:o1,blockSkip:Y0,br:fg,code:W0,del:ha,delLDelim:ha,delRDelim:ha,emStrongLDelim:Z0,emStrongRDelimAst:e1,emStrongRDelimUnd:n1,escape:U0,link:u1,nolink:bg,punctuation:V0,reflink:yg,reflinkSearch:d1,tag:c1,text:H0,url:ha},f1={...Bd,link:It(/^!?\[(label)\]\((.*?)\)/).replace("label",Zl).getRegex(),reflink:It(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Zl).getRegex()},Yu={...Bd,emStrongRDelimAst:t1,emStrongLDelim:J0,delLDelim:s1,delRDelim:a1,url:It(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",$m).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:It(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",$m).getRegex()},p1={...Yu,br:It(fg).replace("{2,}","*").getRegex(),text:It(Yu.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Sl={normal:zd,gfm:B0,pedantic:q0},Zi={normal:Bd,gfm:Yu,breaks:p1,pedantic:f1},m1={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Fm=e=>m1[e];function pr(e,t){if(t){if(as.escapeTest.test(e))return e.replace(as.escapeReplace,Fm)}else if(as.escapeTestNoEncode.test(e))return e.replace(as.escapeReplaceNoEncode,Fm);return e}function zm(e){try{e=encodeURI(e).replace(as.percentDecode,"%")}catch{return null}return e}function Om(e,t){let n=e.replace(as.findPipe,(i,o,u)=>{let d=!1,f=o;for(;--f>=0&&u[f]==="\\";)d=!d;return d?"|":" |"}),r=n.split(as.splitPipe),a=0;if(r[0].trim()||r.shift(),r.length>0&&!r.at(-1)?.trim()&&r.pop(),t)if(r.length>t)r.splice(t);else for(;r.length<t;)r.push("");for(;a<r.length;a++)r[a]=r[a].trim().replace(as.slashPipe,"|");return r}function Ji(e,t,n){let r=e.length;if(r===0)return"";let a=0;for(;a<r&&e.charAt(r-a-1)===t;)a++;return e.slice(0,r-a)}function h1(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let r=0;r<e.length;r++)if(e[r]==="\\")r++;else if(e[r]===t[0])n++;else if(e[r]===t[1]&&(n--,n<0))return r;return n>0?-2:-1}function x1(e,t=0){let n=t,r="";for(let a of e)if(a===" "){let i=4-n%4;r+=" ".repeat(i),n+=i}else r+=a,n++;return r}function Bm(e,t,n,r,a){let i=t.href,o=t.title||null,u=e[1].replace(a.other.outputLinkReplace,"$1");r.state.inLink=!0;let d={type:e[0].charAt(0)==="!"?"image":"link",raw:n,href:i,title:o,text:u,tokens:r.inlineTokens(u)};return r.state.inLink=!1,d}function g1(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let a=r[1];return t.split(`
115
+ `).map(i=>{let o=i.match(n.other.beginningSpace);if(o===null)return i;let[u]=o;return u.length>=a.length?i.slice(a.length):i}).join(`
116
+ `)}var Jl=class{options;rules;lexer;constructor(e){this.options=e||Na}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=t[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?n:Ji(n,`
117
+ `)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],r=g1(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:r}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let r=Ji(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:Ji(t[0],`
118
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=Ji(t[0],`
119
+ `).split(`
120
+ `),r="",a="",i=[];for(;n.length>0;){let o=!1,u=[],d;for(d=0;d<n.length;d++)if(this.rules.other.blockquoteStart.test(n[d]))u.push(n[d]),o=!0;else if(!o)u.push(n[d]);else break;n=n.slice(d);let f=u.join(`
121
+ `),p=f.replace(this.rules.other.blockquoteSetextReplace,`
122
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,"");r=r?`${r}
123
+ ${f}`:f,a=a?`${a}
124
+ ${p}`:p;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(p,i,!0),this.lexer.state.top=h,n.length===0)break;let y=i.at(-1);if(y?.type==="code")break;if(y?.type==="blockquote"){let g=y,T=g.raw+`
125
+ `+n.join(`
126
+ `),w=this.blockquote(T);i[i.length-1]=w,r=r.substring(0,r.length-g.raw.length)+w.raw,a=a.substring(0,a.length-g.text.length)+w.text;break}else if(y?.type==="list"){let g=y,T=g.raw+`
127
+ `+n.join(`
128
+ `),w=this.list(T);i[i.length-1]=w,r=r.substring(0,r.length-y.raw.length)+w.raw,a=a.substring(0,a.length-g.raw.length)+w.raw,n=T.substring(i.at(-1).raw.length).split(`
129
+ `);continue}}return{type:"blockquote",raw:r,tokens:i,text:a}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),r=n.length>1,a={type:"list",raw:"",ordered:r,start:r?+n.slice(0,-1):"",loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:"[*+-]");let i=this.rules.other.listItemRegex(n),o=!1;for(;e;){let d=!1,f="",p="";if(!(t=i.exec(e))||this.rules.block.hr.test(e))break;f=t[0],e=e.substring(f.length);let h=x1(t[2].split(`
130
+ `,1)[0],t[1].length),y=e.split(`
131
+ `,1)[0],g=!h.trim(),T=0;if(this.options.pedantic?(T=2,p=h.trimStart()):g?T=t[1].length+1:(T=h.search(this.rules.other.nonSpaceChar),T=T>4?1:T,p=h.slice(T),T+=t[1].length),g&&this.rules.other.blankLine.test(y)&&(f+=y+`
132
+ `,e=e.substring(y.length+1),d=!0),!d){let w=this.rules.other.nextBulletRegex(T),_=this.rules.other.hrRegex(T),b=this.rules.other.fencesBeginRegex(T),E=this.rules.other.headingBeginRegex(T),R=this.rules.other.htmlBeginRegex(T),A=this.rules.other.blockquoteBeginRegex(T);for(;e;){let C=e.split(`
133
+ `,1)[0],M;if(y=C,this.options.pedantic?(y=y.replace(this.rules.other.listReplaceNesting," "),M=y):M=y.replace(this.rules.other.tabCharGlobal," "),b.test(y)||E.test(y)||R.test(y)||A.test(y)||w.test(y)||_.test(y))break;if(M.search(this.rules.other.nonSpaceChar)>=T||!y.trim())p+=`
134
+ `+M.slice(T);else{if(g||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||b.test(h)||E.test(h)||_.test(h))break;p+=`
135
+ `+y}g=!y.trim(),f+=C+`
136
+ `,e=e.substring(C.length+1),h=M.slice(T)}}a.loose||(o?a.loose=!0:this.rules.other.doubleBlankLine.test(f)&&(o=!0)),a.items.push({type:"list_item",raw:f,task:!!this.options.gfm&&this.rules.other.listIsTask.test(p),loose:!1,text:p,tokens:[]}),a.raw+=f}let u=a.items.at(-1);if(u)u.raw=u.raw.trimEnd(),u.text=u.text.trimEnd();else return;a.raw=a.raw.trimEnd();for(let d of a.items){if(this.lexer.state.top=!1,d.tokens=this.lexer.blockTokens(d.text,[]),d.task){if(d.text=d.text.replace(this.rules.other.listReplaceTask,""),d.tokens[0]?.type==="text"||d.tokens[0]?.type==="paragraph"){d.tokens[0].raw=d.tokens[0].raw.replace(this.rules.other.listReplaceTask,""),d.tokens[0].text=d.tokens[0].text.replace(this.rules.other.listReplaceTask,"");for(let p=this.lexer.inlineQueue.length-1;p>=0;p--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[p].src)){this.lexer.inlineQueue[p].src=this.lexer.inlineQueue[p].src.replace(this.rules.other.listReplaceTask,"");break}}let f=this.rules.other.listTaskCheckbox.exec(d.raw);if(f){let p={type:"checkbox",raw:f[0]+" ",checked:f[0]!=="[ ]"};d.checked=p.checked,a.loose?d.tokens[0]&&["paragraph","text"].includes(d.tokens[0].type)&&"tokens"in d.tokens[0]&&d.tokens[0].tokens?(d.tokens[0].raw=p.raw+d.tokens[0].raw,d.tokens[0].text=p.raw+d.tokens[0].text,d.tokens[0].tokens.unshift(p)):d.tokens.unshift({type:"paragraph",raw:p.raw,text:p.raw,tokens:[p]}):d.tokens.unshift(p)}}if(!a.loose){let f=d.tokens.filter(h=>h.type==="space"),p=f.length>0&&f.some(h=>this.rules.other.anyLine.test(h.raw));a.loose=p}}if(a.loose)for(let d of a.items){d.loose=!0;for(let f of d.tokens)f.type==="text"&&(f.type="paragraph")}return a}}html(e){let t=this.rules.block.html.exec(e);if(t)return{type:"html",block:!0,raw:t[0],pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:t[0]}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),r=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",a=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:t[0],href:r,title:a}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=Om(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),a=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
137
+ `):[],i={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length===r.length){for(let o of r)this.rules.other.tableAlignRight.test(o)?i.align.push("right"):this.rules.other.tableAlignCenter.test(o)?i.align.push("center"):this.rules.other.tableAlignLeft.test(o)?i.align.push("left"):i.align.push(null);for(let o=0;o<n.length;o++)i.header.push({text:n[o],tokens:this.lexer.inline(n[o]),header:!0,align:i.align[o]});for(let o of a)i.rows.push(Om(o,i.header.length).map((u,d)=>({text:u,tokens:this.lexer.inline(u),header:!1,align:i.align[d]})));return i}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:t[2].charAt(0)==="="?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===`
138
+ `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let i=Ji(n.slice(0,-1),"\\");if((n.length-i.length)%2===0)return}else{let i=h1(t[2],"()");if(i===-2)return;if(i>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+i;t[2]=t[2].substring(0,i),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let r=t[2],a="";if(this.options.pedantic){let i=this.rules.other.pedanticHrefTitle.exec(r);i&&(r=i[1],a=i[3])}else a=t[3]?t[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?r=r.slice(1):r=r.slice(1,-1)),Bm(t,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:a&&a.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),a=t[r.toLowerCase()];if(!a){let i=n[0].charAt(0);return{type:"text",raw:i,text:i}}return Bm(n,a,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let r=this.rules.inline.emStrongLDelim.exec(e);if(!(!r||r[3]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[2])||!n||this.rules.inline.punctuation.exec(n))){let a=[...r[0]].length-1,i,o,u=a,d=0,f=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(f.lastIndex=0,t=t.slice(-1*e.length+a);(r=f.exec(t))!=null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i)continue;if(o=[...i].length,r[3]||r[4]){u+=o;continue}else if((r[5]||r[6])&&a%3&&!((a+o)%3)){d+=o;continue}if(u-=o,u>0)continue;o=Math.min(o,o+u+d);let p=[...r[0]][0].length,h=e.slice(0,a+r.index+p+o);if(Math.min(a,o)%2){let g=h.slice(1,-1);return{type:"em",raw:h,text:g,tokens:this.lexer.inlineTokens(g)}}let y=h.slice(2,-2);return{type:"strong",raw:h,text:y,tokens:this.lexer.inlineTokens(y)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(n),a=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&a&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,n=""){let r=this.rules.inline.delLDelim.exec(e);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let a=[...r[0]].length-1,i,o,u=a,d=this.rules.inline.delRDelim;for(d.lastIndex=0,t=t.slice(-1*e.length+a);(r=d.exec(t))!=null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i||(o=[...i].length,o!==a))continue;if(r[3]||r[4]){u+=o;continue}if(u-=o,u>0)continue;o=Math.min(o,o+u);let f=[...r[0]][0].length,p=e.slice(0,a+r.index+f+o),h=p.slice(a,-a);return{type:"del",raw:p,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,r;return t[2]==="@"?(n=t[1],r="mailto:"+n):(n=t[1],r=n),{type:"link",raw:t[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,r;if(t[2]==="@")n=t[0],r="mailto:"+n;else{let a;do a=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(a!==t[0]);n=t[0],t[1]==="www."?r="http://"+t[0]:r=t[0]}return{type:"link",raw:t[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:n}}}},Ys=class Zu{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Na,this.options.tokenizer=this.options.tokenizer||new Jl,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:as,block:Sl.normal,inline:Zi.normal};this.options.pedantic?(n.block=Sl.pedantic,n.inline=Zi.pedantic):this.options.gfm&&(n.block=Sl.gfm,this.options.breaks?n.inline=Zi.breaks:n.inline=Zi.gfm),this.tokenizer.rules=n}static get rules(){return{block:Sl,inline:Zi}}static lex(t,n){return new Zu(n).lex(t)}static lexInline(t,n){return new Zu(n).inlineTokens(t)}lex(t){t=t.replace(as.carriageReturn,`
139
+ `),this.blockTokens(t,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let r=this.inlineQueue[n];this.inlineTokens(r.src,r.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,n=[],r=!1){for(this.options.pedantic&&(t=t.replace(as.tabCharGlobal," ").replace(as.spaceLine,""));t;){let a;if(this.options.extensions?.block?.some(o=>(a=o.call({lexer:this},t,n))?(t=t.substring(a.raw.length),n.push(a),!0):!1))continue;if(a=this.tokenizer.space(t)){t=t.substring(a.raw.length);let o=n.at(-1);a.raw.length===1&&o!==void 0?o.raw+=`
140
+ `:n.push(a);continue}if(a=this.tokenizer.code(t)){t=t.substring(a.raw.length);let o=n.at(-1);o?.type==="paragraph"||o?.type==="text"?(o.raw+=(o.raw.endsWith(`
141
+ `)?"":`
142
+ `)+a.raw,o.text+=`
143
+ `+a.text,this.inlineQueue.at(-1).src=o.text):n.push(a);continue}if(a=this.tokenizer.fences(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.heading(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.hr(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.blockquote(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.list(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.html(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.def(t)){t=t.substring(a.raw.length);let o=n.at(-1);o?.type==="paragraph"||o?.type==="text"?(o.raw+=(o.raw.endsWith(`
144
+ `)?"":`
145
+ `)+a.raw,o.text+=`
146
+ `+a.raw,this.inlineQueue.at(-1).src=o.text):this.tokens.links[a.tag]||(this.tokens.links[a.tag]={href:a.href,title:a.title},n.push(a));continue}if(a=this.tokenizer.table(t)){t=t.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.lheading(t)){t=t.substring(a.raw.length),n.push(a);continue}let i=t;if(this.options.extensions?.startBlock){let o=1/0,u=t.slice(1),d;this.options.extensions.startBlock.forEach(f=>{d=f.call({lexer:this},u),typeof d=="number"&&d>=0&&(o=Math.min(o,d))}),o<1/0&&o>=0&&(i=t.substring(0,o+1))}if(this.state.top&&(a=this.tokenizer.paragraph(i))){let o=n.at(-1);r&&o?.type==="paragraph"?(o.raw+=(o.raw.endsWith(`
147
+ `)?"":`
148
+ `)+a.raw,o.text+=`
149
+ `+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):n.push(a),r=i.length!==t.length,t=t.substring(a.raw.length);continue}if(a=this.tokenizer.text(t)){t=t.substring(a.raw.length);let o=n.at(-1);o?.type==="text"?(o.raw+=(o.raw.endsWith(`
150
+ `)?"":`
151
+ `)+a.raw,o.text+=`
152
+ `+a.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):n.push(a);continue}if(t){let o="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(o);break}else throw new Error(o)}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}inlineTokens(t,n=[]){let r=t,a=null;if(this.tokens.links){let d=Object.keys(this.tokens.links);if(d.length>0)for(;(a=this.tokenizer.rules.inline.reflinkSearch.exec(r))!=null;)d.includes(a[0].slice(a[0].lastIndexOf("[")+1,-1))&&(r=r.slice(0,a.index)+"["+"a".repeat(a[0].length-2)+"]"+r.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(a=this.tokenizer.rules.inline.anyPunctuation.exec(r))!=null;)r=r.slice(0,a.index)+"++"+r.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(a=this.tokenizer.rules.inline.blockSkip.exec(r))!=null;)i=a[2]?a[2].length:0,r=r.slice(0,a.index+i)+"["+"a".repeat(a[0].length-i-2)+"]"+r.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);r=this.options.hooks?.emStrongMask?.call({lexer:this},r)??r;let o=!1,u="";for(;t;){o||(u=""),o=!1;let d;if(this.options.extensions?.inline?.some(p=>(d=p.call({lexer:this},t,n))?(t=t.substring(d.raw.length),n.push(d),!0):!1))continue;if(d=this.tokenizer.escape(t)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.tag(t)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.link(t)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(d.raw.length);let p=n.at(-1);d.type==="text"&&p?.type==="text"?(p.raw+=d.raw,p.text+=d.text):n.push(d);continue}if(d=this.tokenizer.emStrong(t,r,u)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.codespan(t)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.br(t)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.del(t,r,u)){t=t.substring(d.raw.length),n.push(d);continue}if(d=this.tokenizer.autolink(t)){t=t.substring(d.raw.length),n.push(d);continue}if(!this.state.inLink&&(d=this.tokenizer.url(t))){t=t.substring(d.raw.length),n.push(d);continue}let f=t;if(this.options.extensions?.startInline){let p=1/0,h=t.slice(1),y;this.options.extensions.startInline.forEach(g=>{y=g.call({lexer:this},h),typeof y=="number"&&y>=0&&(p=Math.min(p,y))}),p<1/0&&p>=0&&(f=t.substring(0,p+1))}if(d=this.tokenizer.inlineText(f)){t=t.substring(d.raw.length),d.raw.slice(-1)!=="_"&&(u=d.raw.slice(-1)),o=!0;let p=n.at(-1);p?.type==="text"?(p.raw+=d.raw,p.text+=d.text):n.push(d);continue}if(t){let p="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(p);break}else throw new Error(p)}}return n}},ec=class{options;parser;constructor(e){this.options=e||Na}space(e){return""}code({text:e,lang:t,escaped:n}){let r=(t||"").match(as.notSpaceStart)?.[0],a=e.replace(as.endingNewline,"")+`
153
+ `;return r?'<pre><code class="language-'+pr(r)+'">'+(n?a:pr(a,!0))+`</code></pre>
154
+ `:"<pre><code>"+(n?a:pr(a,!0))+`</code></pre>
155
+ `}blockquote({tokens:e}){return`<blockquote>
156
+ ${this.parser.parse(e)}</blockquote>
157
+ `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
158
+ `}hr(e){return`<hr>
159
+ `}list(e){let t=e.ordered,n=e.start,r="";for(let o=0;o<e.items.length;o++){let u=e.items[o];r+=this.listitem(u)}let a=t?"ol":"ul",i=t&&n!==1?' start="'+n+'"':"";return"<"+a+i+`>
160
+ `+r+"</"+a+`>
161
+ `}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
162
+ `}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
163
+ `}table(e){let t="",n="";for(let a=0;a<e.header.length;a++)n+=this.tablecell(e.header[a]);t+=this.tablerow({text:n});let r="";for(let a=0;a<e.rows.length;a++){let i=e.rows[a];n="";for(let o=0;o<i.length;o++)n+=this.tablecell(i[o]);r+=this.tablerow({text:n})}return r&&(r=`<tbody>${r}</tbody>`),`<table>
164
+ <thead>
165
+ `+t+`</thead>
166
+ `+r+`</table>
167
+ `}tablerow({text:e}){return`<tr>
168
+ ${e}</tr>
169
+ `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
170
+ `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${pr(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),a=zm(e);if(a===null)return r;e=a;let i='<a href="'+e+'"';return t&&(i+=' title="'+pr(t)+'"'),i+=">"+r+"</a>",i}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let a=zm(e);if(a===null)return pr(n);e=a;let i=`<img src="${e}" alt="${pr(n)}"`;return t&&(i+=` title="${pr(t)}"`),i+=">",i}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:pr(e.text)}},qd=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}},Zs=class Ju{options;renderer;textRenderer;constructor(t){this.options=t||Na,this.options.renderer=this.options.renderer||new ec,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new qd}static parse(t,n){return new Ju(n).parse(t)}static parseInline(t,n){return new Ju(n).parseInline(t)}parse(t){let n="";for(let r=0;r<t.length;r++){let a=t[r];if(this.options.extensions?.renderers?.[a.type]){let o=a,u=this.options.extensions.renderers[o.type].call({parser:this},o);if(u!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(o.type)){n+=u||"";continue}}let i=a;switch(i.type){case"space":{n+=this.renderer.space(i);break}case"hr":{n+=this.renderer.hr(i);break}case"heading":{n+=this.renderer.heading(i);break}case"code":{n+=this.renderer.code(i);break}case"table":{n+=this.renderer.table(i);break}case"blockquote":{n+=this.renderer.blockquote(i);break}case"list":{n+=this.renderer.list(i);break}case"checkbox":{n+=this.renderer.checkbox(i);break}case"html":{n+=this.renderer.html(i);break}case"def":{n+=this.renderer.def(i);break}case"paragraph":{n+=this.renderer.paragraph(i);break}case"text":{n+=this.renderer.text(i);break}default:{let o='Token with "'+i.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return n}parseInline(t,n=this.renderer){let r="";for(let a=0;a<t.length;a++){let i=t[a];if(this.options.extensions?.renderers?.[i.type]){let u=this.options.extensions.renderers[i.type].call({parser:this},i);if(u!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(i.type)){r+=u||"";continue}}let o=i;switch(o.type){case"escape":{r+=n.text(o);break}case"html":{r+=n.html(o);break}case"link":{r+=n.link(o);break}case"image":{r+=n.image(o);break}case"checkbox":{r+=n.checkbox(o);break}case"strong":{r+=n.strong(o);break}case"em":{r+=n.em(o);break}case"codespan":{r+=n.codespan(o);break}case"br":{r+=n.br(o);break}case"del":{r+=n.del(o);break}case"text":{r+=n.text(o);break}default:{let u='Token with "'+o.type+'" type was not found.';if(this.options.silent)return console.error(u),"";throw new Error(u)}}}return r}},lo=class{options;block;constructor(e){this.options=e||Na}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(){return this.block?Ys.lex:Ys.lexInline}provideParser(){return this.block?Zs.parse:Zs.parseInline}},y1=class{defaults=Ld();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Zs;Renderer=ec;TextRenderer=qd;Lexer=Ys;Tokenizer=Jl;Hooks=lo;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case"table":{let a=r;for(let i of a.header)n=n.concat(this.walkTokens(i.tokens,t));for(let i of a.rows)for(let o of i)n=n.concat(this.walkTokens(o.tokens,t));break}case"list":{let a=r;n=n.concat(this.walkTokens(a.items,t));break}default:{let a=r;this.defaults.extensions?.childTokens?.[a.type]?this.defaults.extensions.childTokens[a.type].forEach(i=>{let o=a[i].flat(1/0);n=n.concat(this.walkTokens(o,t))}):a.tokens&&(n=n.concat(this.walkTokens(a.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(a=>{if(!a.name)throw new Error("extension name required");if("renderer"in a){let i=t.renderers[a.name];i?t.renderers[a.name]=function(...o){let u=a.renderer.apply(this,o);return u===!1&&(u=i.apply(this,o)),u}:t.renderers[a.name]=a.renderer}if("tokenizer"in a){if(!a.level||a.level!=="block"&&a.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let i=t[a.level];i?i.unshift(a.tokenizer):t[a.level]=[a.tokenizer],a.start&&(a.level==="block"?t.startBlock?t.startBlock.push(a.start):t.startBlock=[a.start]:a.level==="inline"&&(t.startInline?t.startInline.push(a.start):t.startInline=[a.start]))}"childTokens"in a&&a.childTokens&&(t.childTokens[a.name]=a.childTokens)}),r.extensions=t),n.renderer){let a=this.defaults.renderer||new ec(this.defaults);for(let i in n.renderer){if(!(i in a))throw new Error(`renderer '${i}' does not exist`);if(["options","parser"].includes(i))continue;let o=i,u=n.renderer[o],d=a[o];a[o]=(...f)=>{let p=u.apply(a,f);return p===!1&&(p=d.apply(a,f)),p||""}}r.renderer=a}if(n.tokenizer){let a=this.defaults.tokenizer||new Jl(this.defaults);for(let i in n.tokenizer){if(!(i in a))throw new Error(`tokenizer '${i}' does not exist`);if(["options","rules","lexer"].includes(i))continue;let o=i,u=n.tokenizer[o],d=a[o];a[o]=(...f)=>{let p=u.apply(a,f);return p===!1&&(p=d.apply(a,f)),p}}r.tokenizer=a}if(n.hooks){let a=this.defaults.hooks||new lo;for(let i in n.hooks){if(!(i in a))throw new Error(`hook '${i}' does not exist`);if(["options","block"].includes(i))continue;let o=i,u=n.hooks[o],d=a[o];lo.passThroughHooks.has(i)?a[o]=f=>{if(this.defaults.async&&lo.passThroughHooksRespectAsync.has(i))return(async()=>{let h=await u.call(a,f);return d.call(a,h)})();let p=u.call(a,f);return d.call(a,p)}:a[o]=(...f)=>{if(this.defaults.async)return(async()=>{let h=await u.apply(a,f);return h===!1&&(h=await d.apply(a,f)),h})();let p=u.apply(a,f);return p===!1&&(p=d.apply(a,f)),p}}r.hooks=a}if(n.walkTokens){let a=this.defaults.walkTokens,i=n.walkTokens;r.walkTokens=function(o){let u=[];return u.push(i.call(this,o)),a&&(u=u.concat(a.call(this,o))),u}}this.defaults={...this.defaults,...r}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Ys.lex(e,t??this.defaults)}parser(e,t){return Zs.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},a={...this.defaults,...r},i=this.onError(!!a.silent,!!a.async);if(this.defaults.async===!0&&r.async===!1)return i(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||t===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(a.hooks&&(a.hooks.options=a,a.hooks.block=e),a.async)return(async()=>{let o=a.hooks?await a.hooks.preprocess(t):t,u=await(a.hooks?await a.hooks.provideLexer():e?Ys.lex:Ys.lexInline)(o,a),d=a.hooks?await a.hooks.processAllTokens(u):u;a.walkTokens&&await Promise.all(this.walkTokens(d,a.walkTokens));let f=await(a.hooks?await a.hooks.provideParser():e?Zs.parse:Zs.parseInline)(d,a);return a.hooks?await a.hooks.postprocess(f):f})().catch(i);try{a.hooks&&(t=a.hooks.preprocess(t));let o=(a.hooks?a.hooks.provideLexer():e?Ys.lex:Ys.lexInline)(t,a);a.hooks&&(o=a.hooks.processAllTokens(o)),a.walkTokens&&this.walkTokens(o,a.walkTokens);let u=(a.hooks?a.hooks.provideParser():e?Zs.parse:Zs.parseInline)(o,a);return a.hooks&&(u=a.hooks.postprocess(u)),u}catch(o){return i(o)}}}onError(e,t){return n=>{if(n.message+=`
171
+ Please report this to https://github.com/markedjs/marked.`,e){let r="<p>An error occurred:</p><pre>"+pr(n.message+"",!0)+"</pre>";return t?Promise.resolve(r):r}if(t)return Promise.reject(n);throw n}}},wa=new y1;function Bt(e,t){return wa.parse(e,t)}Bt.options=Bt.setOptions=function(e){return wa.setOptions(e),Bt.defaults=wa.defaults,lg(Bt.defaults),Bt};Bt.getDefaults=Ld;Bt.defaults=Na;Bt.use=function(...e){return wa.use(...e),Bt.defaults=wa.defaults,lg(Bt.defaults),Bt};Bt.walkTokens=function(e,t){return wa.walkTokens(e,t)};Bt.parseInline=wa.parseInline;Bt.Parser=Zs;Bt.parser=Zs.parse;Bt.Renderer=ec;Bt.TextRenderer=qd;Bt.Lexer=Ys;Bt.lexer=Ys.lex;Bt.Tokenizer=Jl;Bt.Hooks=lo;Bt.parse=Bt;Bt.options;Bt.setOptions;Bt.use;Bt.walkTokens;Bt.parseInline;Zs.parse;Ys.lex;/*! @license DOMPurify 3.3.2 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.3.2/LICENSE */const{entries:vg,setPrototypeOf:qm,isFrozen:b1,getPrototypeOf:v1,getOwnPropertyDescriptor:_1}=Object;let{freeze:os,seal:Rs,create:zl}=Object,{apply:ed,construct:td}=typeof Reflect<"u"&&Reflect;os||(os=function(t){return t});Rs||(Rs=function(t){return t});ed||(ed=function(t,n){for(var r=arguments.length,a=new Array(r>2?r-2:0),i=2;i<r;i++)a[i-2]=arguments[i];return t.apply(n,a)});td||(td=function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),a=1;a<n;a++)r[a-1]=arguments[a];return new t(...r)});const kl=ls(Array.prototype.forEach),w1=ls(Array.prototype.lastIndexOf),Um=ls(Array.prototype.pop),eo=ls(Array.prototype.push),S1=ls(Array.prototype.splice),Ol=ls(String.prototype.toLowerCase),ju=ls(String.prototype.toString),Tu=ls(String.prototype.match),to=ls(String.prototype.replace),k1=ls(String.prototype.indexOf),N1=ls(String.prototype.trim),ws=ls(Object.prototype.hasOwnProperty),ns=ls(RegExp.prototype.test),no=j1(TypeError);function ls(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),a=1;a<n;a++)r[a-1]=arguments[a];return ed(e,t,r)}}function j1(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return td(e,n)}}function gt(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ol;qm&&qm(e,null);let r=t.length;for(;r--;){let a=t[r];if(typeof a=="string"){const i=n(a);i!==a&&(b1(t)||(t[r]=i),a=i)}e[a]=!0}return e}function T1(e){for(let t=0;t<e.length;t++)ws(e,t)||(e[t]=null);return e}function mr(e){const t=zl(null);for(const[n,r]of vg(e))ws(e,n)&&(Array.isArray(r)?t[n]=T1(r):r&&typeof r=="object"&&r.constructor===Object?t[n]=mr(r):t[n]=r);return t}function so(e,t){for(;e!==null;){const r=_1(e,t);if(r){if(r.get)return ls(r.get);if(typeof r.value=="function")return ls(r.value)}e=v1(e)}function n(){return null}return n}const Wm=os(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Au=os(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Cu=os(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),A1=os(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Eu=os(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),C1=os(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Hm=os(["#text"]),Vm=os(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),Ru=os(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Km=os(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Nl=os(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),E1=Rs(/\{\{[\w\W]*|[\w\W]*\}\}/gm),R1=Rs(/<%[\w\W]*|[\w\W]*%>/gm),I1=Rs(/\$\{[\w\W]*/gm),M1=Rs(/^data-[\-\w.\u00B7-\uFFFF]+$/),L1=Rs(/^aria-[\-\w]+$/),_g=Rs(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),P1=Rs(/^(?:\w+script|data):/i),D1=Rs(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),wg=Rs(/^html$/i),$1=Rs(/^[a-z][.\w]*(-[.\w]+)+$/i);var Gm=Object.freeze({__proto__:null,ARIA_ATTR:L1,ATTR_WHITESPACE:D1,CUSTOM_ELEMENT:$1,DATA_ATTR:M1,DOCTYPE_NAME:wg,ERB_EXPR:R1,IS_ALLOWED_URI:_g,IS_SCRIPT_OR_DATA:P1,MUSTACHE_EXPR:E1,TMPLIT_EXPR:I1});const ro={element:1,text:3,progressingInstruction:7,comment:8,document:9},F1=function(){return typeof window>"u"?null:window},z1=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let r=null;const a="data-tt-policy-suffix";n&&n.hasAttribute(a)&&(r=n.getAttribute(a));const i="dompurify"+(r?"#"+r:"");try{return t.createPolicy(i,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return console.warn("TrustedTypes policy "+i+" could not be created."),null}},Qm=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Sg(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:F1();const t=we=>Sg(we);if(t.version="3.3.2",t.removed=[],!e||!e.document||e.document.nodeType!==ro.document||!e.Element)return t.isSupported=!1,t;let{document:n}=e;const r=n,a=r.currentScript,{DocumentFragment:i,HTMLTemplateElement:o,Node:u,Element:d,NodeFilter:f,NamedNodeMap:p=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:h,DOMParser:y,trustedTypes:g}=e,T=d.prototype,w=so(T,"cloneNode"),_=so(T,"remove"),b=so(T,"nextSibling"),E=so(T,"childNodes"),R=so(T,"parentNode");if(typeof o=="function"){const we=n.createElement("template");we.content&&we.content.ownerDocument&&(n=we.content.ownerDocument)}let A,C="";const{implementation:M,createNodeIterator:U,createDocumentFragment:Q,getElementsByTagName:ae}=n,{importNode:ye}=r;let V=Qm();t.isSupported=typeof vg=="function"&&typeof R=="function"&&M&&M.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:W,ERB_EXPR:Z,TMPLIT_EXPR:Se,DATA_ATTR:$e,ARIA_ATTR:Ne,IS_SCRIPT_OR_DATA:G,ATTR_WHITESPACE:J,CUSTOM_ELEMENT:$}=Gm;let{IS_ALLOWED_URI:I}=Gm,O=null;const X=gt({},[...Wm,...Au,...Cu,...Eu,...Hm]);let ne=null;const ke=gt({},[...Vm,...Ru,...Km,...Nl]);let de=Object.seal(zl(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Te=null,Oe=null;const He=Object.seal(zl(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let ut=!0,oe=!0,Ae=!1,Ce=!0,ie=!1,Ee=!0,fe=!1,Fe=!1,We=!1,Me=!1,yt=!1,bt=!1,ct=!0,qt=!1;const wt="user-content-";let jt=!0,Ye=!1,ft={},St=null;const Kt=gt({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Gt=null;const he=gt({},["audio","video","img","source","image","track"]);let kt=null;const $t=gt({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),ht="http://www.w3.org/1998/Math/MathML",an="http://www.w3.org/2000/svg",At="http://www.w3.org/1999/xhtml";let fn=At,Ze=!1,ot=null;const j=gt({},[ht,an,At],ju);let P=gt({},["mi","mo","mn","ms","mtext"]),B=gt({},["annotation-xml"]);const Le=gt({},["title","style","font","a","script"]);let Je=null;const Re=["application/xhtml+xml","text/html"],Ft="text/html";let at=null,Xt=null;const pt=n.createElement("form"),pn=function(k){return k instanceof RegExp||k instanceof Function},ln=function(){let k=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Xt&&Xt===k)){if((!k||typeof k!="object")&&(k={}),k=mr(k),Je=Re.indexOf(k.PARSER_MEDIA_TYPE)===-1?Ft:k.PARSER_MEDIA_TYPE,at=Je==="application/xhtml+xml"?ju:Ol,O=ws(k,"ALLOWED_TAGS")?gt({},k.ALLOWED_TAGS,at):X,ne=ws(k,"ALLOWED_ATTR")?gt({},k.ALLOWED_ATTR,at):ke,ot=ws(k,"ALLOWED_NAMESPACES")?gt({},k.ALLOWED_NAMESPACES,ju):j,kt=ws(k,"ADD_URI_SAFE_ATTR")?gt(mr($t),k.ADD_URI_SAFE_ATTR,at):$t,Gt=ws(k,"ADD_DATA_URI_TAGS")?gt(mr(he),k.ADD_DATA_URI_TAGS,at):he,St=ws(k,"FORBID_CONTENTS")?gt({},k.FORBID_CONTENTS,at):Kt,Te=ws(k,"FORBID_TAGS")?gt({},k.FORBID_TAGS,at):mr({}),Oe=ws(k,"FORBID_ATTR")?gt({},k.FORBID_ATTR,at):mr({}),ft=ws(k,"USE_PROFILES")?k.USE_PROFILES:!1,ut=k.ALLOW_ARIA_ATTR!==!1,oe=k.ALLOW_DATA_ATTR!==!1,Ae=k.ALLOW_UNKNOWN_PROTOCOLS||!1,Ce=k.ALLOW_SELF_CLOSE_IN_ATTR!==!1,ie=k.SAFE_FOR_TEMPLATES||!1,Ee=k.SAFE_FOR_XML!==!1,fe=k.WHOLE_DOCUMENT||!1,Me=k.RETURN_DOM||!1,yt=k.RETURN_DOM_FRAGMENT||!1,bt=k.RETURN_TRUSTED_TYPE||!1,We=k.FORCE_BODY||!1,ct=k.SANITIZE_DOM!==!1,qt=k.SANITIZE_NAMED_PROPS||!1,jt=k.KEEP_CONTENT!==!1,Ye=k.IN_PLACE||!1,I=k.ALLOWED_URI_REGEXP||_g,fn=k.NAMESPACE||At,P=k.MATHML_TEXT_INTEGRATION_POINTS||P,B=k.HTML_INTEGRATION_POINTS||B,de=k.CUSTOM_ELEMENT_HANDLING||{},k.CUSTOM_ELEMENT_HANDLING&&pn(k.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(de.tagNameCheck=k.CUSTOM_ELEMENT_HANDLING.tagNameCheck),k.CUSTOM_ELEMENT_HANDLING&&pn(k.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(de.attributeNameCheck=k.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),k.CUSTOM_ELEMENT_HANDLING&&typeof k.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(de.allowCustomizedBuiltInElements=k.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),ie&&(oe=!1),yt&&(Me=!0),ft&&(O=gt({},Hm),ne=zl(null),ft.html===!0&&(gt(O,Wm),gt(ne,Vm)),ft.svg===!0&&(gt(O,Au),gt(ne,Ru),gt(ne,Nl)),ft.svgFilters===!0&&(gt(O,Cu),gt(ne,Ru),gt(ne,Nl)),ft.mathMl===!0&&(gt(O,Eu),gt(ne,Km),gt(ne,Nl))),ws(k,"ADD_TAGS")||(He.tagCheck=null),ws(k,"ADD_ATTR")||(He.attributeCheck=null),k.ADD_TAGS&&(typeof k.ADD_TAGS=="function"?He.tagCheck=k.ADD_TAGS:(O===X&&(O=mr(O)),gt(O,k.ADD_TAGS,at))),k.ADD_ATTR&&(typeof k.ADD_ATTR=="function"?He.attributeCheck=k.ADD_ATTR:(ne===ke&&(ne=mr(ne)),gt(ne,k.ADD_ATTR,at))),k.ADD_URI_SAFE_ATTR&&gt(kt,k.ADD_URI_SAFE_ATTR,at),k.FORBID_CONTENTS&&(St===Kt&&(St=mr(St)),gt(St,k.FORBID_CONTENTS,at)),k.ADD_FORBID_CONTENTS&&(St===Kt&&(St=mr(St)),gt(St,k.ADD_FORBID_CONTENTS,at)),jt&&(O["#text"]=!0),fe&&gt(O,["html","head","body"]),O.table&&(gt(O,["tbody"]),delete Te.tbody),k.TRUSTED_TYPES_POLICY){if(typeof k.TRUSTED_TYPES_POLICY.createHTML!="function")throw no('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof k.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw no('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');A=k.TRUSTED_TYPES_POLICY,C=A.createHTML("")}else A===void 0&&(A=z1(g,a)),A!==null&&typeof C=="string"&&(C=A.createHTML(""));os&&os(k),Xt=k}},Pe=gt({},[...Au,...Cu,...A1]),te=gt({},[...Eu,...C1]),Yt=function(k){let se=R(k);(!se||!se.tagName)&&(se={namespaceURI:fn,tagName:"template"});const me=Ol(k.tagName),Nt=Ol(se.tagName);return ot[k.namespaceURI]?k.namespaceURI===an?se.namespaceURI===At?me==="svg":se.namespaceURI===ht?me==="svg"&&(Nt==="annotation-xml"||P[Nt]):!!Pe[me]:k.namespaceURI===ht?se.namespaceURI===At?me==="math":se.namespaceURI===an?me==="math"&&B[Nt]:!!te[me]:k.namespaceURI===At?se.namespaceURI===an&&!B[Nt]||se.namespaceURI===ht&&!P[Nt]?!1:!te[me]&&(Le[me]||!Pe[me]):!!(Je==="application/xhtml+xml"&&ot[k.namespaceURI]):!1},Ct=function(k){eo(t.removed,{element:k});try{R(k).removeChild(k)}catch{_(k)}},mt=function(k,se){try{eo(t.removed,{attribute:se.getAttributeNode(k),from:se})}catch{eo(t.removed,{attribute:null,from:se})}if(se.removeAttribute(k),k==="is")if(Me||yt)try{Ct(se)}catch{}else try{se.setAttribute(k,"")}catch{}},vt=function(k){let se=null,me=null;if(We)k="<remove></remove>"+k;else{const lt=Tu(k,/^[\r\n\t ]+/);me=lt&&lt[0]}Je==="application/xhtml+xml"&&fn===At&&(k='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+k+"</body></html>");const Nt=A?A.createHTML(k):k;if(fn===At)try{se=new y().parseFromString(Nt,Je)}catch{}if(!se||!se.documentElement){se=M.createDocument(fn,"template",null);try{se.documentElement.innerHTML=Ze?C:Nt}catch{}}const xe=se.body||se.documentElement;return k&&me&&xe.insertBefore(n.createTextNode(me),xe.childNodes[0]||null),fn===At?ae.call(se,fe?"html":"body")[0]:fe?se.documentElement:xe},mn=function(k){return U.call(k.ownerDocument||k,k,f.SHOW_ELEMENT|f.SHOW_COMMENT|f.SHOW_TEXT|f.SHOW_PROCESSING_INSTRUCTION|f.SHOW_CDATA_SECTION,null)},Gn=function(k){return k instanceof h&&(typeof k.nodeName!="string"||typeof k.textContent!="string"||typeof k.removeChild!="function"||!(k.attributes instanceof p)||typeof k.removeAttribute!="function"||typeof k.setAttribute!="function"||typeof k.namespaceURI!="string"||typeof k.insertBefore!="function"||typeof k.hasChildNodes!="function")},Cn=function(k){return typeof u=="function"&&k instanceof u};function sn(we,k,se){kl(we,me=>{me.call(t,k,se,Xt)})}const ys=function(k){let se=null;if(sn(V.beforeSanitizeElements,k,null),Gn(k))return Ct(k),!0;const me=at(k.nodeName);if(sn(V.uponSanitizeElement,k,{tagName:me,allowedTags:O}),Ee&&k.hasChildNodes()&&!Cn(k.firstElementChild)&&ns(/<[/\w!]/g,k.innerHTML)&&ns(/<[/\w!]/g,k.textContent)||k.nodeType===ro.progressingInstruction||Ee&&k.nodeType===ro.comment&&ns(/<[/\w]/g,k.data))return Ct(k),!0;if(!(He.tagCheck instanceof Function&&He.tagCheck(me))&&(!O[me]||Te[me])){if(!Te[me]&&Be(me)&&(de.tagNameCheck instanceof RegExp&&ns(de.tagNameCheck,me)||de.tagNameCheck instanceof Function&&de.tagNameCheck(me)))return!1;if(jt&&!St[me]){const Nt=R(k)||k.parentNode,xe=E(k)||k.childNodes;if(xe&&Nt){const lt=xe.length;for(let Mt=lt-1;Mt>=0;--Mt){const En=w(xe[Mt],!0);En.__removalCount=(k.__removalCount||0)+1,Nt.insertBefore(En,b(k))}}}return Ct(k),!0}return k instanceof d&&!Yt(k)||(me==="noscript"||me==="noembed"||me==="noframes")&&ns(/<\/no(script|embed|frames)/i,k.innerHTML)?(Ct(k),!0):(ie&&k.nodeType===ro.text&&(se=k.textContent,kl([W,Z,Se],Nt=>{se=to(se,Nt," ")}),k.textContent!==se&&(eo(t.removed,{element:k.cloneNode()}),k.textContent=se)),sn(V.afterSanitizeElements,k,null),!1)},Dn=function(k,se,me){if(Oe[se]||ct&&(se==="id"||se==="name")&&(me in n||me in pt))return!1;if(!(oe&&!Oe[se]&&ns($e,se))){if(!(ut&&ns(Ne,se))){if(!(He.attributeCheck instanceof Function&&He.attributeCheck(se,k))){if(!ne[se]||Oe[se]){if(!(Be(k)&&(de.tagNameCheck instanceof RegExp&&ns(de.tagNameCheck,k)||de.tagNameCheck instanceof Function&&de.tagNameCheck(k))&&(de.attributeNameCheck instanceof RegExp&&ns(de.attributeNameCheck,se)||de.attributeNameCheck instanceof Function&&de.attributeNameCheck(se,k))||se==="is"&&de.allowCustomizedBuiltInElements&&(de.tagNameCheck instanceof RegExp&&ns(de.tagNameCheck,me)||de.tagNameCheck instanceof Function&&de.tagNameCheck(me))))return!1}else if(!kt[se]){if(!ns(I,to(me,J,""))){if(!((se==="src"||se==="xlink:href"||se==="href")&&k!=="script"&&k1(me,"data:")===0&&Gt[k])){if(!(Ae&&!ns(G,to(me,J,"")))){if(me)return!1}}}}}}}return!0},Be=function(k){return k!=="annotation-xml"&&Tu(k,$)},Wt=function(k){sn(V.beforeSanitizeAttributes,k,null);const{attributes:se}=k;if(!se||Gn(k))return;const me={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ne,forceKeepAttr:void 0};let Nt=se.length;for(;Nt--;){const xe=se[Nt],{name:lt,namespaceURI:Mt,value:En}=xe,Mn=at(lt),Is=En;let en=lt==="value"?Is:N1(Is);if(me.attrName=Mn,me.attrValue=en,me.keepAttr=!0,me.forceKeepAttr=void 0,sn(V.uponSanitizeAttribute,k,me),en=me.attrValue,qt&&(Mn==="id"||Mn==="name")&&(mt(lt,k),en=wt+en),Ee&&ns(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,en)){mt(lt,k);continue}if(Mn==="attributename"&&Tu(en,"href")){mt(lt,k);continue}if(me.forceKeepAttr)continue;if(!me.keepAttr){mt(lt,k);continue}if(!Ce&&ns(/\/>/i,en)){mt(lt,k);continue}ie&&kl([W,Z,Se],le=>{en=to(en,le," ")});const F=at(k.nodeName);if(!Dn(F,Mn,en)){mt(lt,k);continue}if(A&&typeof g=="object"&&typeof g.getAttributeType=="function"&&!Mt)switch(g.getAttributeType(F,Mn)){case"TrustedHTML":{en=A.createHTML(en);break}case"TrustedScriptURL":{en=A.createScriptURL(en);break}}if(en!==Is)try{Mt?k.setAttributeNS(Mt,lt,en):k.setAttribute(lt,en),Gn(k)?Ct(k):Um(t.removed)}catch{mt(lt,k)}}sn(V.afterSanitizeAttributes,k,null)},zt=function we(k){let se=null;const me=mn(k);for(sn(V.beforeSanitizeShadowDOM,k,null);se=me.nextNode();)sn(V.uponSanitizeShadowNode,se,null),ys(se),Wt(se),se.content instanceof i&&we(se.content);sn(V.afterSanitizeShadowDOM,k,null)};return t.sanitize=function(we){let k=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},se=null,me=null,Nt=null,xe=null;if(Ze=!we,Ze&&(we="<!-->"),typeof we!="string"&&!Cn(we))if(typeof we.toString=="function"){if(we=we.toString(),typeof we!="string")throw no("dirty is not a string, aborting")}else throw no("toString is not a function");if(!t.isSupported)return we;if(Fe||ln(k),t.removed=[],typeof we=="string"&&(Ye=!1),Ye){if(we.nodeName){const En=at(we.nodeName);if(!O[En]||Te[En])throw no("root node is forbidden and cannot be sanitized in-place")}}else if(we instanceof u)se=vt("<!---->"),me=se.ownerDocument.importNode(we,!0),me.nodeType===ro.element&&me.nodeName==="BODY"||me.nodeName==="HTML"?se=me:se.appendChild(me);else{if(!Me&&!ie&&!fe&&we.indexOf("<")===-1)return A&&bt?A.createHTML(we):we;if(se=vt(we),!se)return Me?null:bt?C:""}se&&We&&Ct(se.firstChild);const lt=mn(Ye?we:se);for(;Nt=lt.nextNode();)ys(Nt),Wt(Nt),Nt.content instanceof i&&zt(Nt.content);if(Ye)return we;if(Me){if(yt)for(xe=Q.call(se.ownerDocument);se.firstChild;)xe.appendChild(se.firstChild);else xe=se;return(ne.shadowroot||ne.shadowrootmode)&&(xe=ye.call(r,xe,!0)),xe}let Mt=fe?se.outerHTML:se.innerHTML;return fe&&O["!doctype"]&&se.ownerDocument&&se.ownerDocument.doctype&&se.ownerDocument.doctype.name&&ns(wg,se.ownerDocument.doctype.name)&&(Mt="<!DOCTYPE "+se.ownerDocument.doctype.name+`>
172
+ `+Mt),ie&&kl([W,Z,Se],En=>{Mt=to(Mt,En," ")}),A&&bt?A.createHTML(Mt):Mt},t.setConfig=function(){let we=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};ln(we),Fe=!0},t.clearConfig=function(){Xt=null,Fe=!1},t.isValidAttribute=function(we,k,se){Xt||ln({});const me=at(we),Nt=at(k);return Dn(me,Nt,se)},t.addHook=function(we,k){typeof k=="function"&&eo(V[we],k)},t.removeHook=function(we,k){if(k!==void 0){const se=w1(V[we],k);return se===-1?void 0:S1(V[we],se,1)[0]}return Um(V[we])},t.removeHooks=function(we){V[we]=[]},t.removeAllHooks=function(){V=Qm()},t}var O1=Sg();const B1=["p","br","strong","em","code","pre","ul","ol","li","a","h1","h2","h3","span","div","button"],q1=["href","class","target","rel","title","data-cite-key","data-cite-index","data-cite-resolved","data-code-lines","type","aria-label"],U1={"&quot;":'"',"&apos;":"'","&amp;":"&","&nbsp;":" "},W1=/&#(x?[0-9a-fA-F]+);/g,H1=/\((cite:\s*[^)]+)\)/gi,V1=/\[(\d+)\]/g,K1=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Gr(e){if(typeof e!="string")return e==null?"":String(e);if(!e||!e.includes("&"))return e;const t=a=>a.replace(W1,(i,o)=>{const u=String(o).toLowerCase(),d=u.startsWith("x"),f=Number.parseInt(d?u.slice(1):u,d?16:10);return Number.isFinite(f)?f===10||f===13?`
173
+ `:f===9?" ":f===34?'"':f===39?"'":f===38?"&":f===160?" ":i:i}),n=a=>a.replace(/&(quot|apos|amp|nbsp);/g,i=>U1[i]??i);let r=t(n(e));return r=t(n(r)),r}const co=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"&quot;").replace(/'/g,"&#39;"),Es=e=>{if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()){const t=Number.parseInt(e,10);if(Number.isFinite(t))return t}},Xm=e=>!!(e&&K1.test(e));function nd(e){const t=e.match(/(\d+)(?:\s*(?:-|–|~|:|\.\.)\s*(\d+))?/);if(!t)return{};const n=Es(t[1]),r=Es(t[2]);return n?{start:n,end:r??n}:{}}const G1=(e,t)=>{if(!e||typeof e!="object")return null;const n=Es(e.index)??(typeof e.id=="string"?Es(e.id):void 0)??t,r=typeof n=="number"?n:t,a=Es(e.line_start??e.line),i=Es(e.line_end??e.line),o=typeof e.range=="string"?e.range:void 0,u=o?nd(o):{},d=a??u.start,f=i??u.end??(d||void 0),p=e.file_path;let h=e.file_name;if(!h&&typeof p=="string"){const g=p.split("/");h=g[g.length-1]||void 0}const y={key:`c${r}`,index:r,source:e.source,fileId:e.file_id,filePath:p,fileName:h,page:Es(e.page),lineStart:d,lineEnd:f,range:o??e.range,quote:e.quote,bbox:e.bbox};return y.label=Ud(y),y},Ud=e=>{const t=[],n=e.fileName||e.filePath||e.fileId;if(n&&t.push(n),e.page&&t.push(`p.${e.page}`),e.lineStart){const r=e.lineEnd&&e.lineEnd!==e.lineStart?`-${e.lineEnd}`:"";t.push(`L${e.lineStart}${r}`)}else e.range&&t.push(String(e.range));return t.join(" · ")},Q1=e=>{if(!e)return null;const n=Gr(e).replace(/^cite:\s*/i,"").trim();if(!n)return null;let r,a,i,o,u;const d=n.split(",").map(p=>p.trim()).filter(Boolean);for(const p of d){const h=p.match(/^([a-zA-Z_]+)\s*[:=]\s*(.+)$/);if(h){const g=h[1].toLowerCase(),T=h[2].trim();if(g==="file"||g==="file_id"||g==="fileid"||g==="id")r=T;else if(g==="path"||g==="file_path"||g==="filepath")r=T;else if(g==="page"||g==="p")a=Es(T);else if(g==="line"||g==="lines"||g==="range"){const w=nd(T);i=w.start,o=w.end,u=T}else g==="line_start"||g==="start_line"?i=Es(T):(g==="line_end"||g==="end_line")&&(o=Es(T));continue}if(!r){r=p;continue}const y=Es(p.replace(/^p/i,""));if(y&&a===void 0){a=y;continue}if(!i){const g=nd(p);g.start&&(i=g.start,o=g.end,u=p)}}if(!r)return null;const f={source:"inline",fileId:Xm(r)?r:void 0,filePath:Xm(r)?void 0:r,fileName:void 0,page:a,lineStart:i,lineEnd:o,range:u,quote:void 0,bbox:void 0,label:void 0,index:void 0};if(f.filePath&&f.filePath.includes("/")){const p=f.filePath.split("/");f.fileName=p[p.length-1]||void 0}return f.label=Ud({...f}),f},Iu=(e,t,n,r,a=!0)=>{const i=n?` title="${co(n)}"`:"",o=r?` data-cite-index="${r}"`:"";return`<span class="ds-citation" data-cite-key="${t}"${o}${` data-cite-resolved="${a?"true":"false"}"`}${i}>${e}</span>`},X1=(e,t)=>{let n=e.replace(V1,(r,a)=>{const i=Es(a);if(!i)return r;const o=t.byIndex.get(i);return o?Iu(r,o.key,o.label,o.index??i,!0):Iu(r,`c${i}`,void 0,i,!1)});return n=n.replace(H1,(r,a)=>{const i=Q1(a);if(!i)return r;t.inlineCounter+=1;const o=`i${t.inlineCounter}`,u={key:o,index:i.index,source:i.source,fileId:i.fileId,filePath:i.filePath,fileName:i.fileName,page:i.page,lineStart:i.lineStart,lineEnd:i.lineEnd,range:i.range,quote:i.quote,bbox:i.bbox,label:i.label??Ud({...i})};return t.lookup[o]=u,Iu(r,o,u.label,u.index,!0)}),n},Y1=e=>e.replace(/(^|[\s({])(@[A-Za-z0-9_-]+)/g,'$1<span class="ai-manus-mention">$2</span>'),Ym=e=>{const t=new Bt.Renderer;return t.code=({text:n,lang:r})=>{const a=typeof n=="string"?n:"",i=typeof r=="string"&&r.trim().length>0?r.trim().split(/\s+/)[0]:"",o=i?co(i):"",u=co(a),d=a?a.split(/\r?\n/).length:0,f=o||"Code",p=o?` class="language-${o}"`:"";return`
174
+ <div class="ai-manus-codeblock" data-code-lines="${d}">
175
+ <div class="ai-manus-codeblock-bar">
176
+ <span class="ai-manus-code-lang">${f}</span>
177
+ <div class="ai-manus-code-actions">
178
+ <button type="button" class="ai-manus-code-copy" aria-label="Copy code block">Copy</button>
179
+ </div>
180
+ </div>
181
+ <pre><code${p}>${u}</code></pre>
182
+ </div>
183
+ `},t.link=({href:n,title:r,text:a})=>{const i=n??"",o=r?` title="${r}"`:"";return`<a href="${i}" target="_blank" rel="noopener noreferrer"${o}>${a}</a>`},t.text=n=>{const r=typeof n=="string"?n:typeof n.text=="string"?n.text:typeof n.raw=="string"?n.raw:"";if(!r)return"";const a=typeof n!="string"?n.escaped:!1,i=typeof n=="string"?co(r):a?r:co(r),o=e?X1(i,e):i;return Y1(o)},t},Wd=(e,t,n=!1,r=!1)=>{if(!e)return{html:"",citationLookup:{}};const a=Gr(e);let i={},o=null;if(n){i={};const f=new Map;o={lookup:i,byIndex:f,inlineCounter:0},Array.isArray(t)&&t.forEach((p,h)=>{const y=G1(p,h+1);y&&(i[y.key]=y,y.index&&f.set(y.index,y))})}const u=r?Bt.parseInline(a,{renderer:Ym(o)}):Bt.parse(a,{renderer:Ym(o)});return{html:O1.sanitize(u,{ALLOWED_TAGS:B1,ALLOWED_ATTR:q1,ALLOW_DATA_ATTR:!0}),citationLookup:i}};function xo(e){return Wd(e,void 0,!1).html}function Vr(e){return Wd(e,void 0,!1,!0).html}function Z1(e,t){return Wd(e,t,!0)}const Zm="ds:lab:question-answered",J1="Copilot";function Bl(e,t){return`/FILES/${J1}/${e}/${t}`}function _n(e){return typeof crypto<"u"&&crypto.randomUUID?`${e}-${crypto.randomUUID()}`:`${e}-${Date.now()}-${Math.random().toString(16).slice(2)}`}function Hd(e){return e==="assistant"?"assistant":"user"}function Cs(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Number(e);if(Number.isFinite(t))return t;const n=Date.parse(e);if(!Number.isNaN(n))return Math.floor(n/1e3)}return Math.floor(Date.now()/1e3)}function xr(e){const t=e.data,n=t.seq;if(typeof n=="number"&&Number.isFinite(n))return n;const r=t._seq;return typeof r=="number"&&Number.isFinite(r)?r:null}function Vd(e,t){return!Array.isArray(e)||e.length===0?[]:e.map(n=>({...n,status:n.status??"success",file_path:n.file_path||(t?Bl(t,n.filename):n.file_path)}))}function kg(e,t,n){const r=n.map(a=>a.file_id||a.filename).filter(Boolean).sort().join("|");return`${e}:${t}:${r}`}const eS=e=>typeof e.content=="string"?e.content:typeof e.message=="string"?e.message:typeof e.text=="string"?e.text:e.content!=null?String(e.content):"",tS=(e,t,n)=>{const r=t.metadata;if((typeof r?.quest_event_type=="string"?r.quest_event_type:"")!=="conversation.message")return-1;const i=typeof r?.quest_run_id=="string"?r.quest_run_id:"",o=typeof r?.quest_skill_id=="string"?r.quest_skill_id:"",u=e.trim();if(!u||!i)return-1;for(let d=n.length-1;d>=0;d-=1){const f=n[d];if(f.type!=="text_delta")continue;const p=f.content;if(p.role!=="assistant")continue;const h=p.metadata;if((p.content||"").trim()===u&&(h?.quest_event_type||"")==="runner.agent_message"&&(h?.quest_run_id||"")===i&&!(o&&(h?.quest_skill_id||"")!==o))return d}return-1},nS=(e,t)=>{const n=e.data,r=Hd(n.role),a=typeof n.delta=="string"?n.delta:"",i=Cs(n.timestamp),u=(typeof n.event_id=="string"?n.event_id:"")||_n(r),d=t.resolveTimelineSeq(xr(e)),f=t.queueMessages??t.updateMessages;if(r==="user"&&n.metadata&&typeof n.metadata=="object"&&n.metadata.question_tool)return!0;if(r==="assistant"&&a){const g=t.assistantMessageIndexRef.current.get(u);if(g){const w=t.messagesRef.current.findIndex(_=>_.id===g);if(w>=0){const _=t.messagesRef.current[w];if(_.type==="text_delta"){const b=_.content;if(b.status==="in_progress"){const E=[...t.messagesRef.current];return E[w]={..._,content:{...b,role:r,timestamp:i,metadata:n.metadata??b.metadata,content:`${b.content}${a}`,status:"in_progress"}},f(E),t.lastAssistantSegmentIdRef&&(t.lastAssistantSegmentIdRef.current=g),t.startDisplayLock&&t.startDisplayLock(g),t.setCopilotStatus&&t.setCopilotStatus(null),!0}}}}t.closeAssistantSegment&&t.closeAssistantSegment();const T=t.buildTextDeltaId(u,d);return t.appendMessage({id:T,type:"text_delta",seq:d,ts:i,content:{...n,role:r,content:a,timestamp:i,status:"in_progress"}}),t.assistantMessageIndexRef.current.set(u,T),t.lastAssistantSegmentIdRef&&(t.lastAssistantSegmentIdRef.current=T),t.startDisplayLock&&t.startDisplayLock(T),t.setCopilotStatus&&t.setCopilotStatus(null),!0}const p=eS(n),h=Vd(Array.isArray(n.attachments)?n.attachments:void 0,t.sessionId);if(r==="assistant"&&n.metadata&&typeof n.metadata=="object"&&typeof n.metadata.moment_id=="string"){const g=String(n.metadata.moment_id||"");if(g){const T=t.messagesRef.current.findIndex(w=>{if(w.type!=="text_delta")return!1;const b=w.content.metadata;return typeof b?.moment_id=="string"&&b.moment_id===g});if(T>=0){const w=[...t.messagesRef.current],_=w[T],b=_.content,E={...b.metadata??{},...n.metadata};return w[T]={..._,content:{...b,role:r,timestamp:i,content:p||b.content,status:b.status??"completed",metadata:E}},t.updateMessages(w),u&&t.assistantMessageIndexRef.current.set(u,_.id),t.lastAssistantSegmentIdRef&&(t.lastAssistantSegmentIdRef.current=_.id),t.startDisplayLock&&t.startDisplayLock(_.id),t.setCopilotStatus&&t.setCopilotStatus(null),!0}}}if(r==="user"&&t.pendingUserRef?.current){const g=t.pendingUserRef.current;if(p.trim()===g.content.trim()&&h.length===g.attachments.length&&h.every(w=>g.attachments.some(_=>_.filename===w.filename)))return t.pendingUserRef.current=null,!0}r==="assistant"&&t.closeAssistantSegment&&t.closeAssistantSegment();let y=!1;if(r==="assistant"){const g=tS(p,n,t.messagesRef.current);if(g>=0){const T=[...t.messagesRef.current],w=T[g];if(w.type==="text_delta"){const _=w.content,b={..._,role:r,timestamp:i,status:"completed",metadata:{..._.metadata??{},...n.metadata??{}},content:p||_.content};T[g]={...w,seq:d,ts:i,content:b},t.updateMessages(T),u&&t.assistantMessageIndexRef.current.set(u,w.id),t.lastAssistantSegmentIdRef&&(t.lastAssistantSegmentIdRef.current=w.id),t.startDisplayLock&&t.startDisplayLock(w.id),y=!0}}}if(r==="assistant"&&!y){const g=t.assistantMessageIndexRef.current.get(u);if(g){const T=t.messagesRef.current.findIndex(w=>w.id===g);if(T>=0){const w=[...t.messagesRef.current],_=w[T];if(_.type==="text_delta"){const b=_.content,E={...b,role:r,timestamp:i,status:"completed",metadata:n.metadata??b.metadata,content:p||b.content};w[T]={..._,content:E},t.updateMessages(w),t.lastAssistantSegmentIdRef&&(t.lastAssistantSegmentIdRef.current=g),t.startDisplayLock&&t.startDisplayLock(g),y=!0}}}}if(!y){const g=t.buildTextDeltaId(u,d);t.appendMessage({id:g,type:"text_delta",seq:d,ts:i,content:{...n,role:r,content:p,timestamp:i,...r==="assistant"?{status:"completed"}:{}}}),r==="assistant"&&(t.assistantMessageIndexRef.current.set(u,g),t.lastAssistantSegmentIdRef&&(t.lastAssistantSegmentIdRef.current=g),t.startDisplayLock&&t.startDisplayLock(g))}if(t.onSessionUpdate&&t.onSessionUpdate(p,i),h.length>0){const g=kg(r,i,h);if(!t.attachmentsSeenRef.current.has(g))if(t.attachmentsSeenRef.current.add(g),(t.shouldDeferAttachments?.()??!1)&&t.onDeferAttachments)t.onDeferAttachments({event:"attachments",data:{event_id:_n("attachments"),timestamp:i,role:r,attachments:h,metadata:{context:{__deferred:!0}}}});else{const w=t.resolveTimelineSeq(null);t.appendMessage({id:_n("attachments"),type:"attachments",seq:w,ts:i,content:{role:r,attachments:h,timestamp:i}})}}return t.setCopilotStatus&&t.setCopilotStatus(null),!0},sS=(e,t)=>{const n=e.data,r=Hd(n.role),a=Cs(n.timestamp),i=t.resolveTimelineSeq(xr(e)),o=Vd(Array.isArray(n.attachments)?n.attachments:void 0,t.sessionId);if(o.length===0)return!0;const u=kg(r,a,o),d=!!n.metadata?.context?.__deferred;return t.attachmentsSeenRef.current.has(u)&&!d||(t.attachmentsSeenRef.current.add(u),t.appendMessage({id:_n("attachments"),type:"attachments",seq:i,ts:a,content:{role:r,attachments:o,timestamp:a}})),!0},rS=(e,t)=>{const n=e.data,r=typeof n.message_ref=="string"?n.message_ref:"",a=typeof n.delivery_state=="string"?n.delivery_state:"";if(!r||!a)return!0;const i=[...t.messagesRef.current],o=i.findIndex(p=>{if(p.type!=="text_delta"&&p.type!=="user")return!1;const h=p.content;return typeof h.event_id=="string"&&h.event_id===r||h.metadata?.group_message_id===r});if(o<0)return!0;const u=i[o],d=u.content,f={...d.metadata??{}};return f.delivery_state=a,typeof n.target_count=="number"&&(f.delivery_target_count=n.target_count),typeof n.delivered_count=="number"&&(f.delivery_delivered_count=n.delivered_count),typeof n.reply_state=="string"&&n.reply_state.trim()&&(f.reply_state=n.reply_state.trim()),i[o]={...u,content:{...d,metadata:f}},t.updateMessages(i),!0},aS=(e,t)=>!e?.data||typeof e.data!="object"?!1:e.event==="message"?nS(e,t):e.event==="attachments"?sS(e,t):e.event==="receipt"?rS(e,t):!1;function Ng(e){if(e.type!=="text_delta")return null;const t=e.content.metadata;return typeof t?.agent_label=="string"&&t.agent_label.trim()?t.agent_label:typeof t?.agent_id=="string"&&t.agent_id.trim()?`@${t.agent_id}`:null}function jg(e,t){if(!e)return t;if(!t)return e;const n=e.endsWith(`
184
+
185
+ `)?"":e.endsWith(`
186
+ `)?`
187
+ `:`
188
+
189
+ `;return`${e}${n}${t}`}function iS(e,t){const n=e.content,r=t.content,a=jg(n.content,r.content),i=r.metadata??n.metadata,o={...n,...r,content:a,metadata:i,role:r.role??n.role},u=n.status==="in_progress"||r.status==="in_progress"?"in_progress":r.status??n.status;return u&&(o.status=u),{...e,content:o}}function oS(e,t){const n=e.content,r=t.content,a=jg(n.content,r.content),i=n.status==="in_progress"||r.status==="in_progress"?"in_progress":r.status??n.status,o={...n,...r,content:a,status:i,kind:n.kind??r.kind,reasoning_id:n.reasoning_id};return{...e,content:o}}function Jm(e){const t=e.content;return{id:e.id,kind:"text",role:t.role,message:e,sourceIds:[e.id],agentLabel:t.role==="assistant"?Ng(e):null}}function eh(e){return{id:e.id,kind:e.type,message:e,sourceIds:[e.id]}}function lS(e,t){const n=e.content,r=t.content,a={...n,...r,args:r.args&&Object.keys(r.args).length>0?r.args:n.args,content:r.content??n.content,metadata:r.metadata??n.metadata,error:r.error??n.error};return{...t,id:e.id,content:a}}function cS(e){const t=[];let n=null;const r=a=>{const i={id:a,blocks:[]};return n=i,t.push(i),i};for(const a of e){if(a.type==="text_delta"&&a.content.role==="user"){r(a.id).blocks.push(Jm(a));continue}if(a.type==="attachments"||a.type==="attachment"){const i=a.content;if((!n||i.role==="user"&&n.blocks.length>0&&n.blocks[n.blocks.length-1].role!=="user")&&(n=r(a.id)),!n)continue;n.blocks.push(eh(a));continue}if(n||(n=r(a.id)),!!n){if(a.type==="text_delta"){const i=Ng(a),o=n.blocks[n.blocks.length-1],u=o?.role??null;o?.kind==="text"&&u==="assistant"&&o.agentLabel===i?(o.message=iS(o.message,a),o.sourceIds.push(a.id)):n.blocks.push(Jm(a));continue}if(a.type==="reasoning"){const i=n.blocks[n.blocks.length-1];if(i?.kind==="reasoning"){const o=i.message.content,u=a.content,d=o.kind??"full",f=u.kind??"full";if(d===f){i.message=oS(i.message,a),i.sourceIds.push(a.id);continue}}}if(a.type==="tool_call"||a.type==="tool_result"){const i=a.content;if(i.tool_call_id){let o=!1;for(let u=n.blocks.length-1;u>=0;u-=1){const d=n.blocks[u];if(d?.kind!=="tool_call"&&d?.kind!=="tool_result")continue;const f=d.message.content;if(f.tool_call_id&&f.tool_call_id===i.tool_call_id){d.kind=a.type,d.message=lS(d.message,a),d.sourceIds.push(a.id),o=!0;break}}if(o)continue}}n.blocks.push(eh(a))}}return t}const sd="*** Begin Patch",rd="*** End Patch",th="*** Add File: ",nh="*** Delete File: ",sh="*** Update File: ",rh="*** Move to: ",uS="*** End of File",ah=e=>e.startsWith("*** "),ih=(e,t)=>{const n=[];for(;e.index<e.lines.length;){const r=e.lines[e.index];if(!t(r))break;n.push(r),e.index+=1}return n},jl=e=>e.trim().replace(/^\/+/,""),oh=e=>e.filter(t=>{if(!t)return!0;const n=t[0];return n==="@"||n==="+"||n==="-"||n===" "});function dS(e){if(!Array.isArray(e)||e.length===0)return"";const t=[];return e.forEach(n=>{const r=typeof n?.patch=="string"?n.patch:"";r.trim()&&r.split(/\r?\n/).forEach(a=>{const i=a.trim();i===sd||i===rd||t.push(a)})}),t.length===0?"":[sd,...t,rd].join(`
190
+ `)}function Tg(e){const n={index:0,lines:e?e.split(/\r?\n/):[]};if(n.lines.length===0)return[];const r=[];for(;n.index<n.lines.length;){const a=n.lines[n.index];if(!a){n.index+=1;continue}const i=a.trim();if(i===sd||i===rd){n.index+=1;continue}if(a.startsWith(th)){const o=jl(a.slice(th.length));n.index+=1;const u=ih(n,f=>!ah(f)),d=oh(u.map(f=>f.startsWith("+")?f:`+${f}`));r.push({path:o,changeType:"create",diffLines:d});continue}if(a.startsWith(nh)){const o=jl(a.slice(nh.length));n.index+=1,r.push({path:o,changeType:"delete",diffLines:[]});continue}if(a.startsWith(sh)){const o=jl(a.slice(sh.length));n.index+=1;let u;n.lines[n.index]?.startsWith(rh)&&(u=jl(n.lines[n.index].slice(rh.length)),n.index+=1);const d=ih(n,p=>!ah(p)),f=oh(d.filter(p=>p!==uS));r.push({path:o,changeType:u?"move":"update",diffLines:f,moveTo:u});continue}n.index+=1}return r}function fS({toolContent:e,panelMode:t}){const n=t==null,r=c.useMemo(()=>{const h=e.args;return typeof h?.url=="string"?h.url:typeof e.content?.current_url=="string"?e.content.current_url:"Browser"},[e]),a=c.useMemo(()=>{const h=e.args;return typeof h?.url=="string"&&h.url.trim()?h.url.trim():typeof e.content?.current_url=="string"&&e.content.current_url.trim()?e.content.current_url.trim():typeof e.content?.url=="string"&&e.content.url.trim()?e.content.url.trim():""},[e]),i=c.useMemo(()=>a?/^https?:\/\//i.test(a)?a:`https://${a}`:"",[a]),o=c.useMemo(()=>i?`${er()}/api/v1/web/preview?url=${encodeURIComponent(i)}`:"",[i]),u=e.content?.error,d=c.useMemo(()=>typeof e.content?.text=="string"?e.content.text:"",[e]),f=.92,p=c.useMemo(()=>({transform:`scale(${f})`,transformOrigin:"top left",width:`${100/f}%`,height:`${140/f}%`}),[f]);return s.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[n?s.jsx("div",{className:"flex h-[36px] items-center border-b border-[var(--border-main)] bg-[var(--background-gray-main)] px-3 shadow-[inset_0px_1px_0px_0px_#FFFFFF]",children:s.jsx("div",{className:"flex-1 truncate text-center text-xs font-medium text-[var(--text-tertiary)]",children:r})}):null,s.jsxs("div",{className:"relative flex-1 overflow-hidden bg-[var(--fill-white)]",children:[u?s.jsxs("div",{className:"ds-tool-error-banner",role:"status",children:[s.jsx(Tn,{className:"ds-tool-error-icon"}),s.jsx("span",{children:u})]}):null,o?s.jsx("div",{className:"relative h-full w-full overflow-auto bg-[var(--background-white-main)]",children:s.jsx("div",{className:"relative min-h-full min-w-full",children:s.jsx("div",{style:p,children:s.jsx("iframe",{src:o,title:"Website preview",className:"h-full w-full border-0 pointer-events-none",referrerPolicy:"no-referrer",sandbox:"allow-same-origin",loading:"lazy"})})})}):d?s.jsx("div",{className:"flex h-full flex-col overflow-auto p-4",children:s.jsx("pre",{className:"whitespace-pre-wrap break-words text-xs leading-relaxed text-[var(--text-primary)]",children:d})}):s.jsx("div",{className:"flex h-full items-center justify-center text-xs text-[var(--text-tertiary)]",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(md,{className:"h-4 w-4"}),"No URL available."]})})]})]})}function pS(e){const t=e.lastIndexOf(".");if(!(t<0))return e.slice(t).toLowerCase()}function mS(e,t){return sx.findPluginForFile(e,t)?.id}function hS(e){const t=pS(e);return t?{".pdf":"file-text",".md":"book-open",".markdown":"book-open",".mdx":"book-open",".txt":"file-text",".json":"file-json",".js":"file-code",".ts":"file-code",".tsx":"file-code",".jsx":"file-code",".py":"file-code",".html":"file-code",".css":"file-code",".png":"image",".jpg":"image",".jpeg":"image",".gif":"image",".svg":"image",".webp":"image"}[t]:void 0}function Ag(e){const{file:t,projectId:n,forcePluginId:r,title:a,icon:i,customData:o}=e;let u=r;if(u||(u=mS(t.name,t.mimeType)),!u)return{success:!1,error:`No plugin available to open file: ${t.name}`};if(!sx.hasPlugin(u))return{success:!1,error:`Plugin not registered: ${u}`};const d={type:"file",resourceId:t.id,resourceName:t.name,customData:{...o,path:t.path,mimeType:t.mimeType,size:t.size,lastModified:t.lastModified,projectId:n}},f={pluginId:u,context:d,title:a||t.name,icon:i||hS(t.name)};return{success:!0,tabId:li.getState().openTab(f),pluginId:u}}const xS={create:"Created",update:"Updated",delete:"Deleted"};function gS({sessionId:e,toolContent:t,live:n,panelMode:r}){const[a,i]=c.useState(""),[o,u]=c.useState(null),d=c.useRef(!1),f=nn($=>$.findNodeByPath),p=c.useMemo(()=>{const $=t.args;return typeof $?.file=="string"?$.file:typeof $?.path=="string"?$.path:typeof t.content?.file=="string"?t.content.file:typeof t.content?.file_path=="string"?t.content.file_path:""},[t]),h=p.startsWith("/FILES/Copilot/"),y=p.startsWith("/FILES/")&&!h,g=c.useMemo(()=>{if(!p)return"File";const $=p.split("/");return $[$.length-1]||p},[p]),T=c.useMemo(()=>t.args??{},[t.args]),w=c.useMemo(()=>{const $=t.content,I=typeof T.file_id=="string"?T.file_id:typeof T.fileId=="string"?T.fileId:null;if(I)return I;if($){if(typeof $.file_id=="string")return $.file_id;if(typeof $.fileId=="string")return $.fileId}return null},[T,t.content]),_=c.useMemo(()=>p?f(p):null,[p,f]),b=w??_?.id??null,E=_?.name||g,R=_?.path||p,A=c.useCallback(()=>{b&&(Ag({file:{id:b,name:E||"File",path:R||void 0}}),nn.getState().expandToFile(b),nn.getState().select(b))},[b,E,R]),C=c.useMemo(()=>{const $=t.content?.diff;if(!$||typeof $!="object")return null;const I=$.lines;return Array.isArray(I)?$:null},[t]),M=c.useMemo(()=>{if(typeof t.content?.content=="string")return t.content.content;if(typeof t.content?.text=="string")return t.content.text},[t]),U=typeof M=="string",Q=typeof t.content?.changeType=="string"?t.content.changeType:void 0,ae=c.useMemo(()=>{const $=t.content?.diffs;if(!Array.isArray($))return null;const I=$.map(O=>{if(!O||typeof O!="object")return null;const X=O.diff;return!X||!Array.isArray(X.lines)?null:{path:O.path,changeType:O.changeType,diff:X}}).filter(Boolean);return I.length>0?I:null},[t]),ye=!!(C||ae),V=r==null||ye,W=!!b,Z=c.useMemo(()=>{const $=t.content,I=Array.isArray($?.lines)?$?.lines:null,O=Array.isArray($?.matches)?$?.matches:null,X=Array.isArray($?.results)?$?.results:null;if(I||O||X)return{lines:I,matches:O,results:X,page:$?.page};const ne=(t.function||"").toLowerCase();if(!new Set(["file_grep","pdf_search","pdf_read_lines","rebuttal_pdf_search","rebuttal_pdf_read_lines","file_read_lines"]).has(ne))return{lines:null,matches:null,results:null,page:null};const de=typeof $?.content=="string"?$.content.trim():"";if(!de||!de.startsWith("{")&&!de.startsWith("["))return{lines:null,matches:null,results:null,page:null};try{const Te=JSON.parse(de);if(Array.isArray(Te))return{lines:null,matches:null,results:Te,page:null};if(Te&&typeof Te=="object")return{lines:Array.isArray(Te.lines)?Te.lines:null,matches:Array.isArray(Te.matches)?Te.matches:null,results:Array.isArray(Te.results)?Te.results:null,page:Te.page??null}}catch{return{lines:null,matches:null,results:null,page:null}}return{lines:null,matches:null,results:null,page:null}},[t]),Se=c.useMemo(()=>{const $=[];return Z.lines&&Z.lines.forEach((I,O)=>{const X=typeof I.line=="number"?I.line:null,ne=typeof I.text=="string"?I.text:"",ke=typeof I.page=="number"?I.page:typeof Z.page=="number"?Z.page:null;!X&&!ke||$.push({key:`line-${X??O}`,label:ke?`p${ke} l${X??"-"}`:`l${X??"-"}`,line:X??void 0,page:ke??void 0,text:ne,fileId:w??void 0,filePath:p})}),Z.matches&&Z.matches.forEach((I,O)=>{const X=typeof I.line=="number"?I.line:null,ne=typeof I.text=="string"?I.text:"",ke=typeof I.file_id=="string"?I.file_id:w,de=typeof I.file_path=="string"?I.file_path:typeof I.path=="string"?I.path:p;!X&&!ne||$.push({key:`match-${X??O}`,label:X?`l${X}`:"match",line:X??void 0,text:ne,fileId:ke??void 0,filePath:de})}),Z.results&&Z.results.forEach((I,O)=>{const X=typeof I.page=="number"?I.page:null,ne=typeof I.line=="number"?I.line:null,ke=typeof I.text=="string"?I.text:"";!X&&!ne||$.push({key:`result-${X??ne??O}`,label:X?`p${X} l${ne??"-"}`:`l${ne??"-"}`,line:ne??void 0,page:X??void 0,text:ke,fileId:w??void 0,filePath:p})}),$.slice(0,40)},[p,Z,w]),$e=c.useCallback($=>{const I=$.fileId??w??void 0;if($.page&&I){Md({fileId:I,page:$.page});return}!I||!$.line||(nn.getState().expandToFile(I),nn.getState().select(I),window.dispatchEvent(new CustomEvent("ds:file-preview:jump",{detail:{fileId:I,line:$.line}})))},[w]),Ne=c.useMemo(()=>ye?ae?"File changes":p?`File changes · ${g}`:"File changes":g,[ae,g,p,ye]),G=c.useMemo(()=>{if(!ye)return null;const $=new Set;if(Q&&$.add(Q),ae&&ae.forEach(I=>{I.changeType&&$.add(I.changeType)}),$.size===1){const I=Array.from($)[0];return xS[I]??"Updated"}return"Updated"},[Q,ae,ye]);c.useEffect(()=>{let $=!0;d.current=!1;const I=ne=>{$&&(i(ne),u(null))},O=async()=>{if(!d.current){if(C||ae){I("");return}if(U){I(M??"");return}if(Q==="delete"){I("File deleted.");return}if(y){I("");return}if(!n){I("");return}if(!(!e||!p))try{const ne=await B_(e,p);I(ne.content??"")}catch(ne){const ke=ne.response?.status,de=typeof ne=="string"?ne:ne.message??"Failed to load file content.";if($&&u(de),ke===400||ke===404){d.current=!0;return}console.error("[FileToolView] Failed to load file",ne)}}};if(O(),!n||!e||!p)return()=>{$=!1};const X=window.setInterval(O,5e3);return()=>{$=!1,window.clearInterval(X)}},[Q,ae,C,p,U,M,n,e,t]);const J=!!(o&&!C&&!ae);return s.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[V?s.jsxs("div",{className:"flex h-[36px] items-center border-b border-[var(--border-main)] bg-[var(--background-gray-main)] px-3 shadow-[inset_0px_1px_0px_0px_#FFFFFF]",children:[s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[s.jsx("div",{className:"truncate text-xs font-medium text-[var(--text-tertiary)]",children:Ne}),G?s.jsx("span",{className:"rounded-full border border-[var(--border-light)] bg-[var(--fill-tsp-gray-main)] px-2 py-[2px] text-[10px] font-semibold text-[var(--text-secondary)]",children:G}):null]}),W?s.jsx("button",{type:"button",onClick:A,className:"inline-flex items-center rounded-md border border-[var(--border-light)] bg-[var(--background-white-main)] px-2 py-[2px] text-[10px] font-semibold text-[var(--text-secondary)] hover:bg-[var(--fill-tsp-white-light)]",children:"Open file"}):null]}):null,s.jsxs("div",{className:"relative flex-1 min-h-0",children:[s.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-2 overflow-auto px-3 py-2",children:[Se.length?s.jsxs("div",{className:"rounded-lg border border-[var(--border-light)] bg-[var(--fill-tsp-white-light)] p-2",children:[s.jsx("div",{className:"text-[11px] font-semibold text-[var(--text-secondary)]",children:"Evidence anchors"}),s.jsx("div",{className:"mt-2 flex flex-col gap-1",children:Se.map($=>s.jsxs("button",{type:"button",onClick:()=>$e($),className:"flex items-start gap-2 rounded-md border border-transparent px-2 py-1 text-left text-[11px] text-[var(--text-secondary)] hover:border-[var(--border-light)] hover:bg-[var(--fill-tsp-gray-main)]",children:[s.jsx("span",{className:"shrink-0 rounded-full border border-[var(--border-light)] bg-[var(--fill-tsp-gray-main)] px-2 py-[2px] text-[10px] font-semibold text-[var(--text-tertiary)]",children:$.label}),s.jsx("span",{className:"line-clamp-2",children:$.text||$.filePath||"Open location"})]},$.key))})]}):null,ae?ae.map(($,I)=>s.jsx(Wu,{diff:$.diff,changeType:$.changeType,title:$.path??"File changes",compact:!0,showHeader:!1},`${$.path??I}`)):C?s.jsx(Wu,{diff:C,changeType:Q,title:"File changes",compact:!0,className:"ai-manus-file-diff-full",showHeader:!1}):null,!C&&!ae?s.jsx("pre",{className:"whitespace-pre-wrap break-words text-xs leading-relaxed text-[var(--text-primary)]",children:a||"No content available."}):null]}),J?s.jsxs("div",{className:"ds-tool-error-banner",role:"status",children:[s.jsx(Tn,{className:"ds-tool-error-icon"}),s.jsx("span",{children:o})]}):null]})]})}function yS(e){const t=e.startsWith("@@")||e.startsWith("***")||e.startsWith("+++")||e.startsWith("---"),n=e.startsWith("+")&&!e.startsWith("+++"),r=e.startsWith("-")&&!e.startsWith("---");return{isHunk:t,isAdd:n,isDel:r,isContext:!t&&!n&&!r}}function bS(e){let t=0,n=0;return e.forEach(r=>{r.startsWith("+")&&!r.startsWith("+++")&&(t+=1),r.startsWith("-")&&!r.startsWith("---")&&(n+=1)}),{added:t,removed:n}}function Cg({patch:e,title:t="Patch preview",subtitle:n,compact:r,showHeader:a=!0,className:i}){const o=c.useMemo(()=>e?e.split(/\r?\n/):[""],[e]),u=c.useMemo(()=>bS(o),[o]),d=Math.max(String(o.length).length,2);return s.jsxs("div",{className:z("ds-patch-preview",r&&"is-compact",i),children:[a?s.jsx("div",{className:"ds-patch-preview-header",children:s.jsxs("div",{className:"ds-patch-preview-header-text",children:[s.jsx("div",{className:"ds-patch-preview-title",children:t}),s.jsxs("div",{className:"ds-patch-preview-subtitle",children:[s.jsxs("span",{className:"ds-patch-preview-meta",children:["+",u.added]}),s.jsxs("span",{className:"ds-patch-preview-meta",children:["-",u.removed]}),n?s.jsx("span",{className:"ds-patch-preview-muted",children:n}):null]})]})}):null,s.jsx("div",{className:"ds-patch-preview-body",children:o.map((f,p)=>{const{isHunk:h,isAdd:y,isDel:g,isContext:T}=yS(f);return s.jsxs("div",{className:z("ds-patch-preview-line",h&&"is-hunk",y&&"is-add",g&&"is-del",T&&"is-context"),children:[s.jsx("span",{className:"ds-patch-preview-gutter",children:String(p+1).padStart(d," ")}),s.jsx("span",{className:"ds-patch-preview-text",children:f||" "})]},`${p}-${f}`)})})]})}const vS={blue:{frame:"border-[rgba(121,145,182,0.22)] bg-[linear-gradient(180deg,rgba(237,243,250,0.96),rgba(255,255,255,0.98))]",title:"text-[#6382ad]",soft:"bg-[rgba(121,145,182,0.10)] text-[#58779f]"},sage:{frame:"border-[rgba(139,164,149,0.22)] bg-[linear-gradient(180deg,rgba(239,245,241,0.96),rgba(255,255,255,0.98))]",title:"text-[#6e8a79]",soft:"bg-[rgba(139,164,149,0.10)] text-[#66816f]"},violet:{frame:"border-[rgba(146,138,172,0.22)] bg-[linear-gradient(180deg,rgba(242,240,247,0.96),rgba(255,255,255,0.98))]",title:"text-[#7a7297]",soft:"bg-[rgba(146,138,172,0.10)] text-[#72698f]"},amber:{frame:"border-[rgba(189,164,120,0.22)] bg-[linear-gradient(180deg,rgba(248,243,233,0.96),rgba(255,255,255,0.98))]",title:"text-[#977a42]",soft:"bg-[rgba(189,164,120,0.12)] text-[#8c7240]"},rose:{frame:"border-[rgba(176,136,136,0.22)] bg-[linear-gradient(180deg,rgba(247,240,240,0.96),rgba(255,255,255,0.98))]",title:"text-[#976b6b]",soft:"bg-[rgba(176,136,136,0.12)] text-[#8a6262]"}},_S={default:"bg-[rgba(99,130,173,0.10)] text-[#5d79a0]",success:"bg-[rgba(110,138,121,0.12)] text-[#5f7a68]",warning:"bg-[rgba(189,164,120,0.14)] text-[#8f733d]",danger:"bg-[rgba(176,136,136,0.14)] text-[#8a5f5f]",muted:"bg-[rgba(117,118,125,0.10)] text-[var(--text-tertiary)]"};function Kd({title:e,subtitle:t,accent:n="blue",badge:r,meta:a,footer:i,className:o,children:u}){const d=vS[n];return s.jsxs("div",{className:z("overflow-hidden rounded-[18px] border px-4 py-4 shadow-[0_14px_34px_-28px_rgba(15,23,42,0.28)]",d.frame,o),children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:z("text-[13px] font-semibold tracking-[0.01em]",d.title),children:e}),t?s.jsx("div",{className:"mt-1 whitespace-pre-wrap text-[12px] leading-6 text-[var(--text-secondary)]",children:t}):null]}),r?s.jsx("div",{className:"shrink-0",children:r}):null]}),a?s.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:a}):null,s.jsx("div",{className:"mt-4 flex flex-col gap-3",children:u}),i?s.jsx("div",{className:"mt-4 border-t border-[var(--border-light)] pt-3",children:i}):null]})}function Vt({children:e,tone:t="default",className:n}){return s.jsx("span",{className:z("inline-flex items-center rounded-full px-2.5 py-1 text-[10px] font-medium tracking-[0.02em]",_S[t],n),children:e})}function Lt({title:e,children:t,compact:n=!1}){return s.jsxs("div",{className:z("rounded-[14px] border border-[var(--border-light)] bg-[rgba(255,255,255,0.74)]",n?"px-3 py-2.5":"px-3.5 py-3"),children:[s.jsx("div",{className:"mb-2 text-[10px] font-semibold uppercase tracking-[0.08em] text-[var(--text-tertiary)]",children:e}),s.jsx("div",{className:"text-[12px] leading-6 text-[var(--text-primary)]",children:t})]})}function Eg(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function wS(e){return e.length===0?null:s.jsx(Lt,{title:"Paths",compact:!0,children:s.jsx("div",{className:"space-y-2",children:e.map(t=>s.jsxs("div",{className:"rounded-[10px] bg-[rgba(255,255,255,0.72)] px-3 py-2",children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-[0.08em] text-[var(--text-tertiary)]",children:t.label}),s.jsx("div",{className:"mt-1 break-all font-mono text-[11px] text-[var(--text-primary)]",children:t.path})]},`${t.label}:${t.path}`))})})}function SS(e){const t=e.map(n=>Tt(n)).filter(n=>!!n);return t.length===0?s.jsx(Lt,{title:"Results",children:s.jsx("div",{className:"text-[12px] text-[var(--text-secondary)]",children:"No memory cards matched this request."})}):s.jsx(Lt,{title:`Results (${t.length})`,children:s.jsx("div",{className:"space-y-2.5",children:t.map((n,r)=>{const a=K(n.title)||K(n.id)||`Memory ${r+1}`,i=K(n.type)||K(n.kind),o=K(n.scope),u=K(n.updated_at),d=K(n.excerpt),f=K(n.path);return s.jsxs("div",{className:"rounded-[12px] border border-[var(--border-light)] bg-[rgba(255,255,255,0.78)] px-3 py-3",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"truncate text-[12px] font-semibold text-[var(--text-primary)]",children:a}),s.jsxs("div",{className:"mt-1 flex flex-wrap gap-1.5",children:[i?s.jsx(Vt,{tone:"muted",children:i}):null,o?s.jsx(Vt,{tone:"muted",children:o}):null]})]}),u?s.jsx("div",{className:"text-[10px] text-[var(--text-tertiary)]",children:Eg(u)}):null]}),d?s.jsx("div",{className:"mt-2 text-[12px] leading-6 text-[var(--text-secondary)]",children:Wl(d,220)}):null,f?s.jsx("div",{className:"mt-2 break-all font-mono text-[10px] text-[var(--text-tertiary)]",children:f}):null]},`${a}:${f??r}`)})})})}function kS(e){if(e==null)return null;let t="";if(typeof e=="string")t=e;else try{t=JSON.stringify(e,null,2)}catch{t=String(e)}return t.trim()?s.jsxs("details",{className:"rounded-[12px] border border-[var(--border-light)] bg-[rgba(255,255,255,0.62)] px-3 py-2",children:[s.jsx("summary",{className:"cursor-pointer text-[11px] font-medium text-[var(--text-secondary)]",children:"Raw payload"}),s.jsx("pre",{className:"mt-3 overflow-x-hidden overflow-y-auto whitespace-pre-wrap break-words text-[11px] leading-6 text-[var(--text-primary)]",children:t})]}):null}function NS({toolContent:e}){const{tool:t}=rx(e),n=ax(e),r=ix(e),a=ox(e),i=K(e.content?.error)||K(r?.error),o=e.status==="calling",d={write:o?"DeepScientist is saving memory...":"DeepScientist saved memory.",read:o?"DeepScientist is reading memory...":"DeepScientist loaded memory.",search:o?"DeepScientist is searching memory...":"DeepScientist searched memory.",list_recent:o?"DeepScientist is loading recent memory...":"DeepScientist loaded recent memory.",promote_to_global:o?"DeepScientist is promoting memory...":"DeepScientist promoted memory."}[t??""]||(o?"DeepScientist is updating memory...":"DeepScientist updated memory."),f=Tt(a),p=Tt(f?.record)??f,h=K(p?.title)||K(n.title),y=K(p?.type)||K(p?.kind)||K(n.kind),g=K(p?.scope)||K(n.scope),T=tc(p?.metadata?.tags??n.tags),w=K(p?.excerpt)||K(p?.body)||K(n.body),_=K(p?.updated_at),b=K(p?.id),E=K(n.query)||K(r?.query),R=Array.isArray(r?.items)?r?.items:[],A=typeof r?.count=="number"?r.count:R.length,C=nc(r??p??n),M=Tt(p?.metadata?.promoted_from);return s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs(Kd,{title:d,subtitle:t==="search"?E?`Query: ${E}`:"Searching quest-scoped or global memory cards.":t==="list_recent"?"Showing the most recently touched memory cards.":h?`Card: ${h}`:"Memory operations are stored as durable Markdown cards.",accent:"sage",meta:s.jsxs(s.Fragment,{children:[t?s.jsx(Vt,{children:t}):null,y?s.jsx(Vt,{tone:"muted",children:y}):null,g?s.jsx(Vt,{tone:"muted",children:g}):null,typeof A=="number"&&(t==="search"||t==="list_recent")?s.jsxs(Vt,{tone:"success",children:[A," results"]}):null]}),children:[i?s.jsxs("div",{className:"ds-tool-error-banner",role:"status",children:[s.jsx(Tn,{className:"ds-tool-error-icon"}),s.jsx("span",{children:i})]}):null,t==="search"||t==="list_recent"?SS(R):null,t==="write"||t==="read"||t==="promote_to_global"?s.jsx(Lt,{title:"Card",children:s.jsxs("div",{className:"space-y-2.5",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[12px] font-semibold text-[var(--text-primary)]",children:[s.jsx(ub,{className:"h-4 w-4 text-[#6e8a79]"}),s.jsx("span",{className:"truncate",children:h||"Untitled memory card"})]}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[y?s.jsx(Vt,{tone:"muted",children:y}):null,g?s.jsx(Vt,{tone:"muted",children:g}):null,b?s.jsx(Vt,{tone:"muted",children:b}):null]})]}),_?s.jsxs("div",{className:"flex items-center gap-1 text-[10px] text-[var(--text-tertiary)]",children:[s.jsx(db,{className:"h-3 w-3"}),s.jsx("span",{children:Eg(_)})]}):null]}),T.length>0?s.jsx("div",{className:"flex flex-wrap gap-1.5",children:T.map(U=>s.jsxs(Vt,{tone:"default",children:["#",U]},U))}):null,w?s.jsx("div",{className:"rounded-[12px] bg-[rgba(255,255,255,0.68)] px-3 py-3 text-[12px] leading-6 text-[var(--text-secondary)]",children:Wl(w,560)}):null,M?s.jsxs("div",{className:"flex items-start gap-2 rounded-[12px] border border-[var(--border-light)] bg-[rgba(255,255,255,0.68)] px-3 py-3 text-[12px] text-[var(--text-secondary)]",children:[s.jsx(fb,{className:"mt-0.5 h-4 w-4 text-[#6e8a79]"}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"font-medium text-[var(--text-primary)]",children:"Promoted from quest memory"}),K(M.path)?s.jsx("div",{className:"break-all font-mono text-[11px]",children:K(M.path)}):null,K(M.quest_root)?s.jsx("div",{className:"break-all font-mono text-[11px]",children:K(M.quest_root)}):null]})]}):null]})}):null,t==="search"&&E?s.jsx(Lt,{title:"Search context",compact:!0,children:s.jsxs("div",{className:"flex items-center gap-2 text-[12px] text-[var(--text-primary)]",children:[s.jsx(Ou,{className:"h-4 w-4 text-[#6e8a79]"}),s.jsx("span",{children:E})]})}):null,t==="list_recent"?s.jsx(Lt,{title:"What this means",compact:!0,children:s.jsxs("div",{className:"flex items-center gap-2 text-[12px] text-[var(--text-secondary)]",children:[s.jsx(pb,{className:"h-4 w-4 text-[#6e8a79]"}),s.jsx("span",{children:"These are the latest durable notes available to reuse without re-searching."})]})}):null,wS(C),kS(a)]})})}function jS(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function TS(e){if(e==null)return null;let t="";if(typeof e=="string")t=e;else try{t=JSON.stringify(e,null,2)}catch{t=String(e)}return t.trim()?s.jsxs("details",{className:"rounded-[12px] border border-[var(--border-light)] bg-[rgba(255,255,255,0.62)] px-3 py-2",children:[s.jsx("summary",{className:"cursor-pointer text-[11px] font-medium text-[var(--text-secondary)]",children:"Raw payload"}),s.jsx("pre",{className:"mt-3 overflow-x-hidden overflow-y-auto whitespace-pre-wrap break-words text-[11px] leading-6 text-[var(--text-primary)]",children:t})]}):null}function Eo(e){return e.length===0?null:s.jsx(Lt,{title:"Paths",compact:!0,children:s.jsx("div",{className:"space-y-2",children:e.map(t=>s.jsxs("div",{className:"rounded-[10px] bg-[rgba(255,255,255,0.72)] px-3 py-2",children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-[0.08em] text-[var(--text-tertiary)]",children:t.label}),s.jsx("div",{className:"mt-1 break-all font-mono text-[11px] text-[var(--text-primary)]",children:t.path})]},`${t.label}:${t.path}`))})})}function go(e){return e.length===0?null:s.jsx("div",{className:"space-y-1.5",children:e.map(t=>s.jsxs("div",{className:"flex items-start gap-2 text-[12px] leading-6 text-[var(--text-secondary)]",children:[s.jsx("span",{className:"mt-[7px] h-1.5 w-1.5 rounded-full bg-[rgba(122,114,151,0.65)]"}),s.jsx("span",{children:t})]},t))})}function lh(e,t,n){const r=Tt(t?.record)??Tt(n.payload)??t;if(!r)return null;const a=K(r.kind)||K(t?.recorded)||"artifact",i=K(r.summary)||K(r.message)||K(r.reason),o=K(r.reason),u=K(t?.guidance)||K(r.guidance),d=tc(t?.recommended_skill_reads),f=Array.isArray(t?.suggested_artifact_calls)?t?.suggested_artifact_calls.map(b=>Tt(b)).filter(b=>!!b).map(b=>{const E=K(b.name),R=K(b.purpose);return[E,R].filter(Boolean).join(" — ")}):[],p=K(r.status),h=K(r.artifact_id)||K(r.id),y=Tt(r.metrics_summary),g=y?Object.entries(y).map(([b,E])=>`${b}: ${typeof E=="number"?E.toFixed(4):String(E)}`).slice(0,6):[],T=Array.isArray(r.options)?r.options.map(b=>Tt(b)).filter(b=>!!b).map(b=>{const E=K(b.label)||K(b.id),R=K(b.description);return[E,R].filter(Boolean).join(" — ")}):[],w=nc(r),_=Tt(t?.baseline_registry_entry);return s.jsxs(s.Fragment,{children:[s.jsx(Lt,{title:"Artifact",children:s.jsxs("div",{className:"space-y-2.5",children:[s.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[s.jsx(Vt,{children:e==="publish_baseline"?"publish_baseline":"record"}),s.jsx(Vt,{tone:"muted",children:a}),p?s.jsx(Vt,{tone:p==="completed"||p==="generated"?"success":"default",children:p}):null,h?s.jsx(Vt,{tone:"muted",children:h}):null]}),i?s.jsx("div",{className:"text-[12px] leading-6 text-[var(--text-primary)]",children:i}):null,o?s.jsx("div",{className:"rounded-[12px] bg-[rgba(255,255,255,0.68)] px-3 py-3 text-[12px] leading-6 text-[var(--text-secondary)]",children:o}):null,u?s.jsxs("div",{className:"flex items-start gap-2 rounded-[12px] border border-[var(--border-light)] bg-[rgba(255,255,255,0.68)] px-3 py-3 text-[12px] text-[var(--text-secondary)]",children:[s.jsx(t_,{className:"mt-0.5 h-4 w-4 text-[#7a7297]"}),s.jsx("span",{children:u})]}):null,d.length>0||f.length>0?s.jsx("div",{className:"rounded-[12px] bg-[rgba(255,255,255,0.62)] px-3 py-3 text-[12px] leading-6 text-[var(--text-secondary)]",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(sc,{className:"mt-0.5 h-4 w-4 text-[#7a7297]"}),s.jsxs("div",{className:"space-y-2",children:[d.length>0?s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx("span",{className:"text-[11px] font-medium text-[var(--text-tertiary)]",children:"Read:"}),d.map(b=>s.jsx(Vt,{tone:"muted",children:b},b))]}):null,f.length>0?s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-medium text-[var(--text-tertiary)]",children:"Suggested calls:"}),s.jsx("div",{className:"mt-2",children:go(f)})]}):null]})]})}):null]})}),g.length>0?s.jsx(Lt,{title:"Metrics",children:go(g)}):null,T.length>0?s.jsx(Lt,{title:"Options",children:go(T)}):null,_?s.jsx(Lt,{title:"Registry entry",children:s.jsxs("div",{className:"space-y-2 text-[12px] leading-6 text-[var(--text-secondary)]",children:[K(_.baseline_id)?s.jsxs("div",{children:["Baseline: ",s.jsx("span",{className:"font-medium text-[var(--text-primary)]",children:K(_.baseline_id)})]}):null,K(_.default_variant_id)?s.jsxs("div",{children:["Default variant:"," ",s.jsx("span",{className:"font-medium text-[var(--text-primary)]",children:K(_.default_variant_id)})]}):null,K(_.summary)?s.jsx("div",{children:K(_.summary)}):null]})}):null,Eo(w)]})}function AS(e,t){const n=K(e?.message)||K(t.message),r=K(e?.branch),a=K(e?.head)||K(e?.commit);return s.jsx(s.Fragment,{children:s.jsx(Lt,{title:"Checkpoint",children:s.jsxs("div",{className:"space-y-2 text-[12px] leading-6 text-[var(--text-secondary)]",children:[n?s.jsx("div",{className:"font-medium text-[var(--text-primary)]",children:n}):null,r?s.jsxs("div",{children:["Branch: ",s.jsx("span",{className:"font-mono text-[11px] text-[var(--text-primary)]",children:r})]}):null,a?s.jsxs("div",{children:["Head: ",s.jsx("span",{className:"font-mono text-[11px] text-[var(--text-primary)]",children:a})]}):null]})})})}function CS(e){const t=K(e?.branch),n=K(e?.parent_branch),r=K(e?.start_point),a=K(e?.worktree_root);return s.jsxs(s.Fragment,{children:[s.jsx(Lt,{title:"Branch plan",children:s.jsxs("div",{className:"space-y-2 text-[12px] leading-6 text-[var(--text-secondary)]",children:[t?s.jsxs("div",{className:"flex items-center gap-2 text-[var(--text-primary)]",children:[s.jsx(lx,{className:"h-4 w-4 text-[#7a7297]"}),s.jsx("span",{className:"font-medium",children:t})]}):null,n?s.jsxs("div",{children:["Parent: ",s.jsx("span",{className:"font-mono text-[11px] text-[var(--text-primary)]",children:n})]}):null,r?s.jsxs("div",{children:["Start point: ",s.jsx("span",{className:"font-mono text-[11px] text-[var(--text-primary)]",children:r})]}):null,a?s.jsxs("div",{children:["Worktree: ",s.jsx("span",{className:"break-all font-mono text-[11px] text-[var(--text-primary)]",children:a})]}):null]})}),Eo(a?[{label:"worktree_root",path:a}]:[])]})}function ES(e){const t=K(e?.branch),n=K(e?.worktree_root),r=K(e?.idea_id),a=K(e?.latest_main_run_id),i=K(e?.next_anchor),o=K(e?.workspace_mode),u=pi(e?.promote_to_head),d=pi(e?.worktree_created),f=Tt(Tt(e?.artifact)?.record)??Tt(e?.artifact),p=K(f?.summary),h=K(f?.reason),y=nc({paths:{worktree_root:n,idea_md:K(e?.idea_md_path),idea_draft_md:K(e?.idea_draft_path)}});return s.jsxs(s.Fragment,{children:[s.jsx(Lt,{title:"Active workspace",children:s.jsxs("div",{className:"space-y-2.5 text-[12px] leading-6 text-[var(--text-secondary)]",children:[t?s.jsxs("div",{className:"flex items-center gap-2 text-[var(--text-primary)]",children:[s.jsx(lx,{className:"h-4 w-4 text-[#7a7297]"}),s.jsx("span",{className:"font-medium",children:t})]}):null,s.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[o?s.jsxs(Vt,{children:[o," workspace"]}):null,i?s.jsxs(Vt,{tone:"muted",children:["next: ",i]}):null,u!=null?s.jsx(Vt,{tone:u?"success":"muted",children:u?"promoted to head":"head unchanged"}):null,d!=null?s.jsx(Vt,{tone:d?"success":"muted",children:d?"created worktree":"reused worktree"}):null]}),p?s.jsx("div",{className:"text-[var(--text-primary)]",children:p}):null,h?s.jsx("div",{className:"rounded-[12px] bg-[rgba(255,255,255,0.68)] px-3 py-3",children:h}):null,r?s.jsxs("div",{children:["Active idea: ",s.jsx("span",{className:"font-medium text-[var(--text-primary)]",children:r})]}):null,a?s.jsxs("div",{children:["Latest main run: ",s.jsx("span",{className:"font-medium text-[var(--text-primary)]",children:a})]}):null,n?s.jsxs("div",{children:["Worktree: ",s.jsx("span",{className:"break-all font-mono text-[11px] text-[var(--text-primary)]",children:n})]}):null]})}),Eo(y)]})}function RS(e){const t=Tt(e?.attachment);if(!t)return null;const n=Tt(t.entry),r=Tt(t.selected_variant),a=K(t.source_baseline_id)||K(n?.baseline_id),i=K(t.source_variant_id)||K(r?.variant_id),o=K(n?.summary);return s.jsx(Lt,{title:"Attached baseline",children:s.jsxs("div",{className:"space-y-2 text-[12px] leading-6 text-[var(--text-secondary)]",children:[a?s.jsxs("div",{children:["Baseline: ",s.jsx("span",{className:"font-medium text-[var(--text-primary)]",children:a})]}):null,i?s.jsxs("div",{children:["Variant: ",s.jsx("span",{className:"font-medium text-[var(--text-primary)]",children:i})]}):null,o?s.jsx("div",{children:o}):null]})})}function IS(e,t){if((K(e?.mode)||K(t.mode)||"read")==="list"){const h=Array.isArray(e?.items)?e.items.map(g=>Tt(g)).filter(g=>!!g):[],y=typeof e?.count=="number"?e.count:h.length;return s.jsx(s.Fragment,{children:s.jsx(Lt,{title:"Saved arXiv papers",children:s.jsxs("div",{className:"space-y-2 text-[12px] leading-6 text-[var(--text-secondary)]",children:[s.jsxs("div",{children:["Count: ",s.jsx("span",{className:"font-medium text-[var(--text-primary)]",children:y})]}),h.length===0?s.jsx("div",{children:"No saved arXiv papers yet."}):s.jsx("div",{className:"space-y-2",children:h.map((g,T)=>s.jsxs("div",{className:"rounded-[12px] border border-[var(--border-light)] bg-[rgba(255,255,255,0.76)] px-3 py-3",children:[s.jsx("div",{className:"text-[12px] font-medium text-[var(--text-primary)]",children:K(g.title)||K(g.arxiv_id)||`Paper ${T+1}`}),K(g.arxiv_id)?s.jsx("div",{className:"mt-1 text-[11px] font-mono text-[var(--text-tertiary)]",children:K(g.arxiv_id)}):null,K(g.abstract)?s.jsx("div",{className:"mt-2 text-[12px] leading-6 text-[var(--text-secondary)]",children:Wl(K(g.abstract),320)}):null]},`${K(g.arxiv_id)||T}`))})]})})})}const r=K(e?.paper_id)||K(t.paper_id),a=K(e?.title)||r||"arXiv paper",i=K(e?.source),o=K(e?.content_mode),u=K(e?.content),d=K(e?.source_url),f=Array.isArray(e?.authors)?e?.authors.map(h=>String(h)).filter(Boolean):[],p=Array.isArray(e?.attempts)?e?.attempts.map(h=>Tt(h)).filter(h=>!!h).map(h=>{const y=K(h.source),g=pi(h.ok)===!1?"failed":pi(h.ok)===!0?"ok":void 0,T=K(h.error);return[y,g,T].filter(Boolean).join(" — ")}):[];return s.jsxs(s.Fragment,{children:[s.jsx(Lt,{title:"Paper",children:s.jsxs("div",{className:"space-y-2 text-[12px] leading-6 text-[var(--text-secondary)]",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[var(--text-primary)]",children:[s.jsx(md,{className:"h-4 w-4 text-[#6382ad]"}),s.jsx("span",{className:"font-medium",children:a})]}),r?s.jsxs("div",{children:["Paper id: ",s.jsx("span",{className:"font-mono text-[11px] text-[var(--text-primary)]",children:r})]}):null,o?s.jsxs("div",{children:["Mode: ",s.jsx("span",{className:"font-medium text-[var(--text-primary)]",children:o})]}):null,i?s.jsxs("div",{children:["Source: ",s.jsx("span",{className:"font-medium text-[var(--text-primary)]",children:i})]}):null,d?s.jsx("div",{className:"break-all text-[11px] text-[var(--text-primary)]",children:d}):null,f.length>0?s.jsx("div",{children:f.join(", ")}):null]})}),u?s.jsx(Lt,{title:"Preview",children:s.jsx("div",{className:"whitespace-pre-wrap text-[12px] leading-6 text-[var(--text-secondary)]",children:Wl(u,1400)})}):null,p.length>0?s.jsx(Lt,{title:"Fetch attempts",children:go(p)}):null]})}function MS(e,t){const n=K(e?.summary_path),r=K(t.reason);return s.jsxs(s.Fragment,{children:[s.jsx(Lt,{title:"Summary refresh",children:s.jsxs("div",{className:"space-y-2 text-[12px] leading-6 text-[var(--text-secondary)]",children:[r?s.jsxs("div",{children:["Reason: ",r]}):null,n?s.jsx("div",{className:"break-all font-mono text-[11px] text-[var(--text-primary)]",children:n}):null]})}),Eo(n?[{label:"summary_md",path:n}]:[])]})}function LS(e){const t=Tt(e?.graph);if(!t)return null;const n=K(t.branch),r=K(t.head),a=PS(t.lines),i=nc({paths:{json:K(t.json_path),svg:K(t.svg_path),png:K(t.png_path)}});return s.jsxs(s.Fragment,{children:[s.jsx(Lt,{title:"Graph export",children:s.jsxs("div",{className:"space-y-2 text-[12px] leading-6 text-[var(--text-secondary)]",children:[n?s.jsxs("div",{children:["Branch: ",s.jsx("span",{className:"font-medium text-[var(--text-primary)]",children:n})]}):null,r?s.jsxs("div",{children:["Head: ",s.jsx("span",{className:"font-mono text-[11px] text-[var(--text-primary)]",children:r})]}):null,a!=null?s.jsxs("div",{children:["Commits rendered: ",s.jsx("span",{className:"font-medium text-[var(--text-primary)]",children:a})]}):null]})}),Eo(i)]})}function PS(e){return Array.isArray(e)?e.length:void 0}function DS(e){const t=tc(e?.delivery_targets),n=K(e?.delivery_policy),r=K(e?.preferred_connector),a=pi(e?.delivered),i=hb(e?.open_request_count),o=Array.isArray(e?.normalized_attachments)?e.normalized_attachments.map(u=>Tt(u)).filter(u=>!!u).map(u=>K(u.kind)).filter(Boolean):[];return t.length===0&&!n&&!r&&a==null&&i==null&&o.length===0?null:s.jsx(Lt,{title:"Connector delivery",children:s.jsxs("div",{className:"space-y-2 text-[12px] leading-6 text-[var(--text-secondary)]",children:[s.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[a!=null?s.jsx(Vt,{tone:a?"success":"warning",children:a?"delivered":"not delivered"}):null,n?s.jsx(Vt,{tone:"muted",children:n}):null,r?s.jsx(Vt,{tone:"muted",children:r}):null,i!=null?s.jsxs(Vt,{tone:"muted",children:[i," open requests"]}):null]}),t.length>0?s.jsxs("div",{children:["Delivered to: ",t.join(", ")]}):null,o.length>0?s.jsxs("div",{children:["Attachments: ",o.join(", ")]}):null]})})}function $S(e,t){const n=K(e?.agent_instruction)||K(t.message),r=K(e?.reply_mode)||K(t.reply_mode),a=pi(e?.expects_reply),i=tc(e?.delivery_targets),o=Array.isArray(e?.recent_inbound_messages)?e?.recent_inbound_messages.map(d=>Tt(d)).filter(d=>!!d):[],u=Array.isArray(t.options)?t.options.map(d=>Tt(d)).filter(d=>!!d):[];return s.jsxs(s.Fragment,{children:[s.jsx(Lt,{title:"Interaction",children:s.jsxs("div",{className:"space-y-2 text-[12px] leading-6 text-[var(--text-secondary)]",children:[n?s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(vv,{className:"mt-0.5 h-4 w-4 text-[#7a7297]"}),s.jsx("span",{children:n})]}):null,s.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[r?s.jsx(Vt,{children:r}):null,a!=null?s.jsx(Vt,{tone:a?"warning":"success",children:a?"expects reply":"no reply needed"}):null,typeof e?.open_request_count=="number"?s.jsxs(Vt,{tone:"muted",children:[e.open_request_count," open requests"]}):null]}),i.length>0?s.jsxs("div",{children:["Delivered to: ",i.join(", ")]}):null]})}),u.length>0?s.jsx(Lt,{title:"Options",children:go(u.map(d=>{const f=K(d.label)||K(d.id),p=K(d.description);return[f,p].filter(Boolean).join(" — ")}))}):null,o.length>0?s.jsx(Lt,{title:"Recent inbound",children:s.jsx("div",{className:"space-y-2.5",children:o.map((d,f)=>s.jsxs("div",{className:"rounded-[12px] border border-[var(--border-light)] bg-[rgba(255,255,255,0.76)] px-3 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 text-[10px] text-[var(--text-tertiary)]",children:[s.jsx("span",{children:K(d.conversation_id)||"conversation"}),K(d.created_at)?s.jsx("span",{children:jS(K(d.created_at))}):null]}),s.jsx("div",{className:"mt-2 text-[12px] leading-6 text-[var(--text-primary)]",children:K(d.text)||K(d.content)||"No text provided."})]},`${K(d.message_id)??f}`))})}):null]})}function FS({toolContent:e}){const{tool:t}=rx(e),n=ax(e),r=ix(e),a=ox(e),i=K(e.content?.error)||K(r?.error),o=e.status==="calling",u=K(r?.mode)||K(n.mode)||"read",d={record:o?"DeepScientist is recording artifact...":"DeepScientist recorded artifact.",checkpoint:o?"DeepScientist is creating checkpoint...":"DeepScientist created checkpoint.",prepare_branch:o?"DeepScientist is preparing branch...":"DeepScientist prepared branch.",activate_branch:o?"DeepScientist is activating branch...":"DeepScientist activated branch.",publish_baseline:o?"DeepScientist is publishing baseline...":"DeepScientist published baseline.",attach_baseline:o?"DeepScientist is attaching baseline...":"DeepScientist attached baseline.",confirm_baseline:o?"DeepScientist is confirming baseline...":"DeepScientist confirmed baseline.",waive_baseline:o?"DeepScientist is waiving baseline...":"DeepScientist waived baseline.",submit_idea:o?"DeepScientist is submitting idea...":"DeepScientist submitted idea.",record_main_experiment:o?"DeepScientist is recording main experiment...":"DeepScientist recorded main experiment.",create_analysis_campaign:o?"DeepScientist is creating analysis campaign...":"DeepScientist created analysis campaign.",record_analysis_slice:o?"DeepScientist is recording analysis slice...":"DeepScientist recorded analysis slice.",arxiv:o?"DeepScientist is reading arXiv paper...":"DeepScientist read arXiv paper.",refresh_summary:o?"DeepScientist is refreshing summary...":"DeepScientist refreshed summary.",render_git_graph:o?"DeepScientist is rendering git graph...":"DeepScientist rendered git graph.",interact:o?"DeepScientist is sending interaction...":"DeepScientist sent interaction."},f=t==="arxiv"?"blue":t==="publish_baseline"||t==="attach_baseline"?"amber":t==="interact"?"sage":"violet",p={checkpoint:"Git-backed checkpoints keep quest state durable and reviewable.",prepare_branch:"Branches and worktrees isolate experiment routes without losing context.",activate_branch:"Returning to a durable research branch should also sync the active workspace and connector context.",render_git_graph:"Graph exports make quest lineage visible across branches and runs."},h=t||"artifact",y=Tt(Tt(r?.artifact)?.record)??Tt(r?.artifact),g=K(r?.guidance)||K((Tt(r?.record)??y??r)?.summary),T=h==="interact"?null:Tt(r?.interaction);return s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs(Kd,{title:h==="arxiv"&&u==="list"?o?"DeepScientist is listing saved arXiv papers...":"DeepScientist listed the saved arXiv papers.":d[h]||(o?"DeepScientist is updating artifact...":"DeepScientist updated artifact."),subtitle:g||p[h]||"Artifact tools persist branch, report, baseline, and interaction state.",accent:f,meta:s.jsxs(s.Fragment,{children:[s.jsx(Vt,{children:h}),K(r?.status)?s.jsx(Vt,{tone:"muted",children:K(r?.status)}):null,K((Tt(r?.record)??r)?.kind)?s.jsx(Vt,{tone:"muted",children:K((Tt(r?.record)??r)?.kind)}):null]}),children:[i?s.jsxs("div",{className:"ds-tool-error-banner",role:"status",children:[s.jsx(Tn,{className:"ds-tool-error-icon"}),s.jsx("span",{children:i})]}):null,t==="record"||t==="publish_baseline"?lh(t,r,n):null,t==="checkpoint"?AS(r,n):null,t==="prepare_branch"?CS(r):null,t==="activate_branch"?ES(r):null,t==="attach_baseline"?RS(r):null,t==="arxiv"?IS(r,n):null,t==="refresh_summary"?MS(r,n):null,t==="render_git_graph"?LS(r):null,t==="interact"?$S(r,n):null,t&&["submit_idea","record_main_experiment","create_analysis_campaign","confirm_baseline","waive_baseline","record_analysis_slice"].includes(t)&&Tt(r?.artifact)?lh("record",Tt(r?.artifact),n):null,t==="attach_baseline"&&r?.artifact?s.jsx(Lt,{title:"Follow-up artifact",children:s.jsxs("div",{className:"flex items-start gap-2 text-[12px] leading-6 text-[var(--text-secondary)]",children:[s.jsx(mb,{className:"mt-0.5 h-4 w-4 text-[#977a42]"}),s.jsx("span",{children:K(Tt(Tt(r.artifact)?.record)?.summary)||"Baseline attachment created a durable report artifact."})]})}):null,T?DS(T):null,t==="render_git_graph"&&r?.guidance?s.jsx(Lt,{title:"Why this helps",compact:!0,children:s.jsxs("div",{className:"flex items-start gap-2 text-[12px] leading-6 text-[var(--text-secondary)]",children:[s.jsx(Bv,{className:"mt-0.5 h-4 w-4 text-[#7a7297]"}),s.jsx("span",{children:K(r?.guidance)})]})}):null,t==="checkpoint"&&K(r?.guidance)?s.jsx(Lt,{title:"Next step",compact:!0,children:s.jsxs("div",{className:"flex items-start gap-2 text-[12px] leading-6 text-[var(--text-secondary)]",children:[s.jsx(sc,{className:"mt-0.5 h-4 w-4 text-[#7a7297]"}),s.jsx("span",{children:K(r?.guidance)})]})}):null,t==="prepare_branch"&&r?.artifact?s.jsx(Lt,{title:"Decision artifact",compact:!0,children:s.jsxs("div",{className:"flex items-start gap-2 text-[12px] leading-6 text-[var(--text-secondary)]",children:[s.jsx(No,{className:"mt-0.5 h-4 w-4 text-[#7a7297]"}),s.jsx("span",{children:K(Tt(Tt(r.artifact)?.record)?.reason)||"The branch preparation is also persisted as a decision artifact."})]})}):null,TS(a)]})})}const ss="mt-1 max-w-full break-words [overflow-wrap:anywhere] text-xs text-[var(--text-secondary)]",Hn="mt-2 max-w-full overflow-x-hidden whitespace-pre-wrap break-words [overflow-wrap:anywhere] rounded-lg bg-[var(--fill-tsp-gray-main)] p-3 text-xs";function zS({toolContent:e,panelMode:t}){const n=t==null,r=nn(Pe=>Pe.findNodeByPath),a=e.metadata&&typeof e.metadata=="object"&&!Array.isArray(e.metadata)?e.metadata:{},i=(e.function||"").trim().toLowerCase(),o=i.startsWith("mcp__")?i.split("__").filter(Boolean):[],u=typeof a.mcp_server=="string"&&a.mcp_server.trim()||o[1]||"";if(typeof a.mcp_tool=="string"&&a.mcp_tool.trim()||o[2],u==="memory")return s.jsx(NS,{toolContent:e,panelMode:t,live:e.status==="calling"});if(u==="artifact")return s.jsx(FS,{toolContent:e,panelMode:t,live:e.status==="calling"});const d=e.args&&typeof e.args=="object"&&!Array.isArray(e.args)?e.args:{},f=Object.keys(d).length>0,p=e.content?.result,h=e.content?.error,y=Pe=>{if(Pe==null)return"";if(typeof Pe=="string")return Pe;try{return JSON.stringify(Pe,null,2)}catch{return String(Pe)}},g=(Pe,te=50)=>{if(Pe.length===0)return"";const Yt=Pe.slice(0,te),Ct=Pe.length>te?`
191
+ ... (${Pe.length-te} more)`:"";return Yt.join(`
192
+ `)+Ct},T=yr(e.function),w=T==="read_file",_=T==="append_file",b=T==="write_task_plan",E=T==="pull_file",R=T==="list_file",A=T==="list_dir",C=T==="grep_text",M=T==="grep_files",U=T==="glob_files",Q=T==="write_memory",ae=T==="request_patch",ye=T==="bash_exec",V=wo(d),W=V||"a file",Z=V||"Unknown file",Se=typeof d.reason=="string"?d.reason:"",$e=y(d.content),Ne=e.content?.result,G=Ne&&typeof Ne=="object"&&!Array.isArray(Ne)?Ne:null,J=$x(Ne??e.content),$=J.text,I=J.message,O=G&&typeof G.message=="string"?G.message:"",X=I||h,ne=O||h,ke=zx(G??Ne)||h,de=typeof Ne=="string"?Ne:G&&typeof G.content=="string"?G.content:"",Te=Xl(Ne??e.content),Oe=Te.items,He=g(Oe.map(Pe=>{if(!Pe||typeof Pe!="object")return String(Pe);const te=Pe,Yt=typeof te.path=="string"?te.path:typeof te.name=="string"?te.name:"Unknown",Ct=typeof te.type=="string"?te.type:"",mt=typeof te.size=="number"?`${te.size}b`:"",vt=[Ct,mt].filter(Boolean).join(" · ");return vt?`${Yt} (${vt})`:Yt})),ut=Te.content,oe=Te.truncated,Ae=typeof d.query=="string"?d.query:G&&typeof G.query=="string"?G.query:"",Ce=typeof d.pattern=="string"?d.pattern:G&&typeof G.pattern=="string"?G.pattern:"",ie=Array.isArray(G?.matches)?G?.matches:[],Ee=G&&typeof G.content=="string"?G.content:typeof Ne=="string"?Ne:"",fe=g(Ee?Ee.split(/\r?\n/).filter(Boolean):[]),Fe=g(ie.map(Pe=>{if(!Pe||typeof Pe!="object")return String(Pe);const te=Pe,Yt=typeof te.file_path=="string"?te.file_path:"Unknown",Ct=typeof te.line=="number"?te.line:void 0,mt=typeof te.text=="string"?te.text:"",vt=Ct?`${Yt}:${Ct}`:Yt;return mt?`${vt} ${mt}`:vt})),We=g(ie.map(Pe=>{if(!Pe||typeof Pe!="object")return String(Pe);const te=Pe,Yt=typeof te.path=="string"?te.path:typeof te.file_path=="string"?te.file_path:"Unknown",Ct=typeof te.score=="number"||typeof te.score=="string"?String(te.score):"",mt=Ct?`score ${Ct}`:"",vt=typeof te.size=="number"?`${te.size}b`:"",mn=[mt,vt].filter(Boolean).join(" · ");return mn?`${Yt} (${mn})`:Yt})),Me=!!G?.truncated,yt=typeof d.title=="string"?d.title:"",bt=typeof d.kind=="string"?d.kind:G&&typeof G.kind=="string"?G.kind:"",ct=Array.isArray(d.tags)?d.tags.map(Pe=>String(Pe)):[],qt=typeof d.confidence=="number"?d.confidence:void 0,wt=G&&typeof G.id=="string"?G.id:"",jt=G&&typeof G.path=="string"?G.path:"",Ye=G&&typeof G.index_path=="string"?G.index_path:"",ft=Array.isArray(G?.warnings)?(G?.warnings).map(Pe=>String(Pe)):[],St=Array.isArray(G?.errors)?(G?.errors).map(Pe=>String(Pe)):[],Kt=typeof d.target_path=="string"?d.target_path:V||"Unknown target",Gt=typeof d.rationale=="string"?d.rationale:"",he=typeof d.patch=="string"?d.patch:"",kt=Array.isArray(d.evidence_refs)?d.evidence_refs.map(Pe=>String(Pe)):[],$t=Array.isArray(G?.applied)?(G?.applied).map(Pe=>String(Pe)):[],ht=g($t),an=typeof d.command=="string"?d.command:typeof d.cmd=="string"?d.cmd:"",At=typeof d.workdir=="string"?d.workdir:"",fn=typeof d.mode=="string"?d.mode.trim().toLowerCase():"",Ze=typeof d.timeout_seconds=="number"?`${d.timeout_seconds}s`:typeof d.timeout=="number"?`${d.timeout}ms`:"",ot=c.useMemo(()=>{if(!ye)return null;const Pe=G??Ne??e.content;if(!Pe||typeof Pe!="object"||Array.isArray(Pe))return null;const te=Pe;if(typeof te.success=="boolean"||typeof te.error=="string"){const Ct=te.result&&typeof te.result=="object"&&!Array.isArray(te.result)?te.result:te.data&&typeof te.data=="object"&&!Array.isArray(te.data)?te.data:null;if(Ct)return Ct}return te},[ye,G,Ne,e.content]),j=ot&&typeof ot.log=="string"?ot.log:ot&&typeof ot.output=="string"?String(ot.output):ot&&typeof ot.content=="string"?String(ot.content):typeof Ne=="string"?Ne:"",P=fn||(ot&&typeof ot.mode=="string"?ot.mode.trim().toLowerCase():""),B=ot&&typeof ot.status=="string"?ot.status:"",Je=j?(Pe=>Pe.split(/\r?\n/).filter(te=>!te.startsWith("__DS_PROGRESS__")&&!te.startsWith("__DS_BASH_STATUS__")&&!te.startsWith(xb)).join(`
193
+ `))(j):"",Re=G&&typeof G.file_id=="string"?G.file_id:G&&typeof G.fileId=="string"?G.fileId:e.content&&typeof e.content.file_id=="string"?e.content.file_id:e.content&&typeof e.content.fileId=="string"?e.content.fileId:null,Ft=c.useMemo(()=>V?r(V):null,[V,r]),at=Re??Ft?.id??null,Xt=Ft?.name||(V?V.split("/").pop():"File")||"File",pt=Ft?.path||V,pn=!!at&&(w||_||E||R||ae),ln=c.useCallback(()=>{at&&(Ag({file:{id:at,name:Xt,path:pt||void 0}}),nn.getState().expandToFile(at),nn.getState().select(at))},[at,Xt,pt]);if(w||_||b||E||R||A||C||M||U||Q||ae||ye){const Pe=w?`DeepScientist is reading ${W}...`:_?`DeepScientist is writing ${W}`:E?`DeepScientist is pulling ${W}...`:R||A?`DeepScientist is listing ${W}...`:C?`DeepScientist is grepping for "${Ae||"..."}"...`:M?`DeepScientist is finding files for "${Ce||"..."}"...`:U?`DeepScientist is matching files for "${Ce||"..."}"...`:Q?`DeepScientist is saving memory "${yt||"Untitled"}"...`:ae?`DeepScientist is applying a patch to ${Kt}...`:ye?"DeepScientist is executing a bash command...":"DeepScientist is planning...";return s.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[n?s.jsxs("div",{className:"flex h-[36px] items-center border-b border-[var(--border-main)] bg-[var(--background-gray-main)] px-3 shadow-[inset_0px_1px_0px_0px_#FFFFFF]",children:[s.jsx("div",{className:"flex-1 text-center text-xs font-medium text-[var(--text-tertiary)]",children:"MCP Tool"}),pn?s.jsx("button",{type:"button",onClick:ln,className:"inline-flex items-center rounded-md border border-[var(--border-light)] bg-[var(--background-white-main)] px-2 py-[2px] text-[10px] font-semibold text-[var(--text-secondary)] hover:bg-[var(--fill-tsp-white-light)]",children:"Open file"}):null]}):null,s.jsx("div",{className:"relative flex-1 overflow-x-hidden overflow-y-auto",children:s.jsxs("div",{className:"mx-auto flex min-w-0 max-w-[640px] flex-col gap-4 px-4 py-3 text-xs text-[var(--text-secondary)]",children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:Pe}),w||_||E||R||A?s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Title"}),s.jsx("div",{className:ss,children:Z})]}):null,C?s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Query"}),s.jsx("div",{className:ss,children:Ae||"—"})]}):null,U||M?s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Pattern"}),s.jsx("div",{className:ss,children:Ce||"—"})]}):null,Q?s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Memory title"}),s.jsx("div",{className:ss,children:yt||"—"})]}):null,ae?s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Target path"}),s.jsx("div",{className:ss,children:Kt})]}):null,ye?s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Command"}),s.jsx("pre",{className:Hn,children:an||"—"})]}):null,ye&&At?s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Workdir"}),s.jsx("div",{className:ss,children:At})]}):null,ye&&P?s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Mode"}),s.jsx("div",{className:ss,children:P})]}):null,ye&&Ze?s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Timeout"}),s.jsx("div",{className:ss,children:Ze})]}):null,ye&&P==="read"?s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Log"}),s.jsx("pre",{className:Hn,children:Je||"No log output returned."})]}):null,ye&&P==="kill"?s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Status"}),s.jsx("div",{className:ss,children:B||(e.status==="calling"?"Terminating…":"Termination requested.")})]}):null,w?X?s.jsxs("div",{className:"ds-tool-error-banner",role:"status",children:[s.jsx(Tn,{className:"ds-tool-error-icon"}),s.jsx("span",{children:X})]}):s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Content"}),s.jsx("pre",{className:Hn,children:$})]}):null,_?s.jsxs(s.Fragment,{children:[ne?s.jsxs("div",{className:"ds-tool-error-banner",role:"status",children:[s.jsx(Tn,{className:"ds-tool-error-icon"}),s.jsx("span",{children:ne})]}):null,s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Reason"}),s.jsx("pre",{className:Hn,children:Se})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Content"}),s.jsx("pre",{className:Hn,children:$e})]})]}):null,E?ke?s.jsxs("div",{className:"ds-tool-error-banner",role:"status",children:[s.jsx(Tn,{className:"ds-tool-error-icon"}),s.jsx("span",{children:ke})]}):s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Content"}),s.jsx("pre",{className:Hn,children:de})]}):null,R||A?s.jsxs(s.Fragment,{children:[ke?s.jsxs("div",{className:"ds-tool-error-banner",role:"status",children:[s.jsx(Tn,{className:"ds-tool-error-icon"}),s.jsx("span",{children:ke})]}):null,s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Items"}),s.jsx("pre",{className:Hn,children:ut||He||"No items returned."})]}),oe?s.jsx("div",{className:"text-xs text-[var(--text-tertiary)]",children:"Truncated results."}):null]}):null,C||M||U?s.jsxs(s.Fragment,{children:[ke?s.jsxs("div",{className:"ds-tool-error-banner",role:"status",children:[s.jsx(Tn,{className:"ds-tool-error-icon"}),s.jsx("span",{children:ke})]}):null,s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Matches"}),s.jsx("pre",{className:Hn,children:(C?Fe:M?fe:We)||"No matches returned."})]}),Me?s.jsx("div",{className:"text-xs text-[var(--text-tertiary)]",children:"Truncated results."}):null]}):null,Q?s.jsxs(s.Fragment,{children:[ke?s.jsxs("div",{className:"ds-tool-error-banner",role:"status",children:[s.jsx(Tn,{className:"ds-tool-error-icon"}),s.jsx("span",{children:ke})]}):null,bt?s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Kind"}),s.jsx("div",{className:ss,children:bt})]}):null,ct.length>0?s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Tags"}),s.jsx("pre",{className:Hn,children:ct.join(", ")})]}):null,qt!=null?s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Confidence"}),s.jsx("div",{className:ss,children:qt})]}):null,wt?s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Memory ID"}),s.jsx("div",{className:ss,children:wt})]}):null,jt?s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Path"}),s.jsx("div",{className:ss,children:jt})]}):null,Ye?s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Index path"}),s.jsx("div",{className:ss,children:Ye})]}):null,ft.length>0?s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Warnings"}),s.jsx("pre",{className:Hn,children:ft.join(", ")})]}):null,St.length>0?s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Errors"}),s.jsx("pre",{className:Hn,children:St.join(", ")})]}):null]}):null,ae?s.jsxs(s.Fragment,{children:[ke?s.jsxs("div",{className:"ds-tool-error-banner",role:"status",children:[s.jsx(Tn,{className:"ds-tool-error-icon"}),s.jsx("span",{children:ke})]}):null,Gt?s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Rationale"}),s.jsx("pre",{className:Hn,children:Gt})]}):null,he?s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Patch"}),s.jsx(Cg,{patch:he,showHeader:!1,className:"mt-2"})]}):null,kt.length>0?s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Evidence refs"}),s.jsx("pre",{className:Hn,children:kt.join(", ")})]}):null,ht?s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Applied"}),s.jsx("pre",{className:Hn,children:ht})]}):null]}):null,ye&&ke?s.jsxs("div",{className:"ds-tool-error-banner",role:"status",children:[s.jsx(Tn,{className:"ds-tool-error-icon"}),s.jsx("span",{children:ke})]}):null]})})]})}return s.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[n?s.jsx("div",{className:"flex h-[36px] items-center border-b border-[var(--border-main)] bg-[var(--background-gray-main)] px-3 shadow-[inset_0px_1px_0px_0px_#FFFFFF]",children:s.jsx("div",{className:"flex-1 text-center text-xs font-medium text-[var(--text-tertiary)]",children:"MCP Tool"})}):null,s.jsx("div",{className:"relative flex-1 overflow-x-hidden overflow-y-auto",children:s.jsxs("div",{className:"mx-auto flex min-w-0 max-w-[640px] flex-col gap-4 px-4 py-3 text-xs text-[var(--text-secondary)]",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Tool"}),s.jsx("div",{className:ss,children:e.function})]}),f?s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Arguments"}),s.jsx("pre",{className:Hn,children:JSON.stringify(d,null,2)})]}):null,p?s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:"Result"}),s.jsx("div",{className:Hn,children:String(p)})]}):h?s.jsxs("div",{className:"ds-tool-error-banner",role:"status",children:[s.jsx(Tn,{className:"ds-tool-error-icon"}),s.jsx("span",{children:h})]}):s.jsx("div",{className:"text-xs text-[var(--text-tertiary)]",children:e.status==="calling"?"Tool is executing…":"Waiting for result…"})]})})]})}function Nr(e){if(!Number.isFinite(e))return"";const t=e<1e12?e*1e3:e,n=Date.now(),r=Math.max(0,n-t),a=Math.floor(r/6e4),i=Math.floor(a/60),o=Math.floor(i/24);return a<1?"Just now":a<60?`${a}m ago`:i<24?`${i}h ago`:o===1?"Yesterday":o<7?`${o}d ago`:new Date(t).toLocaleDateString()}function Tl(e){return String(e).padStart(2,"0")}function OS(e){if(!Number.isFinite(e))return"";const t=e<1e12?e*1e3:e,n=new Date(t),r=new Date,a=n.getFullYear()===r.getFullYear(),i=a&&n.toDateString()===r.toDateString();return a?i?`${Tl(n.getHours())}:${Tl(n.getMinutes())}`:`${Tl(n.getMonth()+1)}-${Tl(n.getDate())}`:String(n.getFullYear())}function ad(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e!==0;if(typeof e=="string"){const t=e.trim().toLowerCase();return t==="true"||t==="1"||t==="yes"||t==="y"}return!1}function BS(e,t){if(typeof e=="string"){const n=e.trim();return n?{label:n,value:n}:null}if(typeof e=="number"){const n=String(e);return{label:n,value:n}}if(e&&typeof e=="object"){const n=String(e.label||e.name||e.value||"").trim();if(!n)return null;const a=String(e.value||e.label||e.name||"").trim()||`option-${t}`;return{label:n,value:a}}return null}function ko(e,t){const n=t.length;if(n===0)return null;if(typeof e=="number")return e>=1&&e<=n?e-1:e>=0&&e<n?e:null;const r=e.trim();if(!r)return null;if(/^\\d+$/.test(r))return ko(Number(r),t);const a=r.toLowerCase(),i=t.findIndex(o=>o.label===r||o.value===r||o.label.toLowerCase()===a);return i>=0?i:null}function Rg(e){const t=o=>{const u=o.trim();if(!u)return null;try{return JSON.parse(u)}catch{return null}},n=o=>{if(Array.isArray(o))return o;if(o&&typeof o=="object")return[o];if(typeof o=="string"){const u=t(o);if(Array.isArray(u))return u;if(u&&typeof u=="object")return[u]}return[]},r=o=>{if(Array.isArray(o))return o;if(typeof o=="string"){const u=t(o);if(Array.isArray(u))return u;const d=o.split("\\n").map(f=>f.trim()).filter(Boolean);return d.length===1&&d[0].includes(",")?d[0].split(",").map(f=>f.trim()).filter(Boolean):d.length>0?d:void 0}},a=n(e.questions),i=e.additional_question??e.additionalQuestion;if(a.length===0&&e.question){const o=r(e.options);o&&o.length>0&&a.push({question:e.question,options:o,multiple:ad(e.multiple),default:e.default})}return i&&typeof i=="object"&&a.push(i),a}function Ig(e){return Rg(e).map((n,r)=>{const a=n.id||n.key||n.name||n.qid||`q${r+1}`,i=String(a),o=String(n.question||n.prompt||n.text||n.title||n.label||i).trim(),u=String(n.description||n.help||n.hint||"").trim(),d=n.options||n.choices||n.values,p=(Array.isArray(d)?d:typeof d=="string"||typeof d=="number"?[d]:d&&typeof d=="object"?Object.values(d):[]).map((g,T)=>BS(g,T)).filter(Boolean),h=ad(n.multiple),y=ad(n.allow_free_text??n.allowFreeText??n.allow_custom_input??n.allowCustomInput??n.free_text??n.freeText);return{id:i,text:o,description:u,options:p,multiple:h,allowFreeText:y}}).filter(n=>n.options.length>0)}function qS(e,t){const n=Rg(e),r={};return t.forEach((a,i)=>{const o=n[i]??{},u=o.answer??o.default??o.default_value??o.defaultValue??o.value??o.defaults??o.selected??void 0;u!==void 0&&(r[a.id]=u)}),r}function US(e,t){const n={},r={},a={};return!e||typeof e!="object"?{choices:n,freeText:r,freeTextActive:a}:(t.forEach(i=>{const o=e[i.id];if(o==null)return;const u=i.allowFreeText,d=p=>{if(!u)return;const h=p.trim();h&&(r[i.id]=h)};if(i.multiple){const p=Array.isArray(o)?o:[o],h=[];p.forEach(y=>{if(typeof y!="string"&&typeof y!="number")return;const g=ko(y,i.options);if(g!==null){h.includes(g)||h.push(g);return}u&&typeof y=="string"&&d(y)}),h.length>0&&(n[i.id]=h),r[i.id]&&(a[i.id]=!0);return}const f=Array.isArray(o)?o:[o];for(const p of f){if(typeof p!="string"&&typeof p!="number")continue;const h=ko(p,i.options);if(h!==null){n[i.id]=h;return}if(u&&typeof p=="string"){d(p),r[i.id]&&(a[i.id]=!0);return}}}),{choices:n,freeText:r,freeTextActive:a})}function ch(e,t,n,r){const a=t[e.id],i=!!r[e.id];if(e.allowFreeText&&i){const o=n[e.id];return!!(o&&o.trim())}if(e.multiple){if(Array.isArray(a)&&a.length>0)return!0;if(!e.allowFreeText)return!1;const o=n[e.id];return!!(o&&o.trim())}return typeof a=="number"}function WS(e,t){if(t==null)return[];const n=Array.isArray(t)?t:[t],r=[];return n.forEach(a=>{if(typeof a!="string"&&typeof a!="number")return;const i=ko(a,e.options);if(i!==null){const o=e.options[i]?.label;o&&r.push(o);return}if(typeof a=="string"){const o=a.trim();if(!o)return;r.push(o)}}),r}function uh(e,t,n,r){const a={};return t.forEach(i=>{const o=e[i.id];if(i.multiple){const u=Array.isArray(o)?o:[],d=[];if(u.forEach(f=>{if(typeof f=="number"){const h=f>=0&&f<i.options.length?f:f>=1&&f<=i.options.length?f-1:null;if(h===null||d.includes(h))return;d.push(h);return}if(typeof f!="string")return;const p=ko(f,i.options);p===null||d.includes(p)||d.push(p)}),d.length>0){const f=d.map(h=>i.options[h]?.label||i.options[h]?.value||String(h+1)).filter(Boolean),p=i.allowFreeText?n[i.id]?.trim():"";if(p){const h=p.toLowerCase();f.some(y=>y.toLowerCase()===h)||f.push(p)}a[i.id]=f}else if(i.allowFreeText){const f=n[i.id]?.trim();f&&(a[i.id]=[f])}return}if(i.allowFreeText&&r[i.id]){const u=n[i.id]?.trim();u&&(a[i.id]=u);return}if(typeof o=="number"){const u=i.options[o],d=u?.label||u?.value||String(o+1);a[i.id]=d}}),a}const Al={lab_quests:i_,lab_pi_sleep:cx,status_update:bb,write_question:yb,write_memory:rm,lab_baseline:rm,default:_v},HS=e=>{const t=e.metadata?.surface;return typeof t=="string"&&t.startsWith("lab-")},_e=e=>typeof e=="string"&&e.trim()?e.trim():"",Cl=e=>_e(e).toLowerCase(),El=e=>Array.isArray(e)?e.map(t=>String(t)).map(t=>t.trim()).filter(Boolean):typeof e=="string"?e.split(",").map(t=>t.trim()).filter(Boolean):[],VS=e=>{const t=e.trim();return t?t.startsWith("@")?t:`@${t}`:""},KS=(e,t=120)=>uo(e.replace(/\s+/g," ").trim(),t),GS=(e,t=160)=>{if(!e)return"";const n=e.split(/\r?\n/).find(r=>r.trim())||"";return uo(n.replace(/\s+/g," ").trim(),t)},QS=e=>e?e.split(/\r?\n/).map(r=>r.trim()).filter(r=>r&&r!=="[PI-LAUNCHED]").join(`
194
+ `).trim():"",XS=e=>{const t=e.trim().toLowerCase();if(!t)return"updated quest";const n={"idea.created":"created idea","idea.review_ready":"reviewed idea","experiment.started":"started experiment","experiment.finished":"finished experiment","write.started":"started writing","write.completed":"completed draft","write.revision_ready":"revision ready","write.review_ready":"reviewed draft","write.self_review_ready":"self-review ready","baseline.ready":"prepared baseline","pi.question":"asked PI","pi.answer":"answered PI","agent.spawned":"spawned agent","error.reported":"reported error"};return n[t]?n[t]:t.startsWith("write.")?`write ${t.replace("write.","").replace(/_/g," ")}`:t.replace(/[._]/g," ")},YS=e=>{if(!e||typeof e!="object")return"";const t=e,n=_e(t.title);if(n)return n;const r=_e(t.question);if(r)return r;const a=_e(t.description);return a||""},ZS=e=>{const t=e.content&&typeof e.content=="object"&&!Array.isArray(e.content)?e.content:null;return(t?.result&&typeof t.result=="object"&&!Array.isArray(t.result)?t.result:null)??t??null},JS=(e,t,n)=>_e(t.quest_id)||_e(n?.quest_id)||_e(e.metadata?.quest_id),ek=(e,t)=>_e(e.branch)||_e(t?.branch),tk=(e,t)=>_e(e.stage_key)||_e(t?.stage_key),nk=(e,t)=>_e(e.event_id)||_e(t?.event_id);function Mg({tool:e,compact:t,projectId:n}){const r=HS(e),a=e.args&&typeof e.args=="object"&&!Array.isArray(e.args)?e.args:{},o=(e.metadata&&typeof e.metadata=="object"?e.metadata.hydrate_phase:void 0)==="skeleton",u=ZS(e),d=yr(e.function||"")??"lab_quests",f=Cl(a.mode),p=[],h=[],y=_e(u?.error)||_e(e.content?.error),g=typeof u?.success=="boolean"?!!u.success:null,T=!!y||g===!1,w=JS(e,a,u),_=ek(a,u),b=tk(a,u),E=nk(a,u),R=oe=>{typeof window>"u"||window.dispatchEvent(new CustomEvent("ds:lab:focus",{detail:oe}))};let A="Tool",C="",M=e.status==="calling"?"Running":"Done",U=!1;const Q=_e(a.question_id)||_e(a.questionId)||_e(u?.question_id)||_e(u?.questionId),ae=_e(a.question)||_e(u?.question)||_e(a.context_md),V=gb({queryKey:["lab-question-lookup",n],queryFn:async()=>{if(!n)return{pending:[],history:[]};const[oe,Ae]=await Promise.all([vb(n),_b(n)]);return{pending:oe.items??[],history:Ae.items??[]}},enabled:r&&d==="lab_quests"&&(f==="pi_ask"||f==="pi_answer")&&!!(n&&Q&&!ae),staleTime:3e4}),W=c.useCallback((oe,Ae)=>{if(!oe||typeof oe!="object"||Array.isArray(oe))return"";const Ce=oe,ie=Ig(Ce),Ee=Ae?String(Ae).trim():"";if(Ee){const Fe=ie.find(We=>We.id===Ee);if(Fe?.text)return Fe.text}return ie.length===1&&ie[0]?.text?ie[0].text:_e(Ce.question)||_e(Ce.title)||_e(Ce.prompt)||_e(Ce.text)},[]),Z=c.useMemo(()=>{if(!Q||!V.data)return"";const oe=[...V.data.pending??[],...V.data.history??[]];for(const Ae of oe){const Ce=W(Ae.question_set,Q);if(Ce)return Ce}return""},[Q,V.data,W]);if(d==="lab_quests")if(f==="agent"){A="Recruiting";const oe=_e(a.template_key)||_e(u?.template_key),Ae=_e(a.initial_instruction)||_e(u?.initial_instruction),Ce=QS(Ae);C=oe?`DeepScientist is recruiting @${oe}`:"DeepScientist is recruiting an agent";const ie=_e(u?.agent_instance_id)||_e(a.agent_instance_id),Ee=_e(u?.agent_id)||_e(a.agent_id);ie&&(h.push({id:"open-agent",label:"Open Agent",onClick:()=>R({focusType:"agent",focusId:ie})}),h.push({id:"open-team",label:"Open TEAM",onClick:()=>R({focusType:"agent",focusId:ie})})),Ee&&p.push({label:"agent_id",value:Ee}),ie&&p.push({label:"instance_id",value:ie}),Ce&&p.push({label:"instruction",value:Ce}),p.push(...[{label:"branch",value:_},{label:"stage",value:b}].filter(fe=>fe.value))}else if(f==="event"){A="Quest Event";const oe=_e(a.event_type)||_e(u?.event_type),Ae=_e(e.metadata?.agent_label)||_e(e.metadata?.agent_id)||_e(e.metadata?.agent_role);C=`${VS(Ae)||"Agent"} ${XS(oe)}`,w&&h.push({id:"open-quest",label:"Open Quest",onClick:()=>R({focusType:"quest",focusId:w})}),w&&_&&h.push({id:"open-branch",label:"Open Branch",onClick:()=>R({focusType:"quest-branch",focusId:w,branch:_})}),E&&p.push({label:"event_id",value:E});const ie=_e(u?.commit_hash);ie&&p.push({label:"commit",value:ie});const Ee=_e(u?.sync_status);Ee&&p.push({label:"sync",value:Ee});const fe=_e(u?.payload_summary);fe&&p.push({label:"summary",value:fe})}else if(f==="pi_ask"){A="Ask PI";const oe=_e(a.question)||_e(u?.question)||_e(a.context_md)||Z;C="DeepScientist is asking PI",U=e.status==="calling",M=U?"Waiting":"Done",w&&h.push({id:"open-pi",label:"Open PI",onClick:()=>R({focusType:"quest",focusId:w})});const Ae=El(a.options);Ae.length&&p.push({label:"options",value:Ae.slice(0,3).join(", ")});const Ce=_e(a.reply_deadline_hint);Ce&&p.push({label:"deadline",value:Ce});const ie=Q;ie&&p.push({label:"question_id",value:ie});const Ee=_e(u?.answer);oe&&p.push({label:"question",value:oe}),Ee&&p.push({label:"answer",value:Ee})}else if(f==="pi_answer"){A="PI Answer";const oe=_e(a.answer)||_e(u?.answer),Ae=_e(a.question)||_e(u?.question)||_e(a.context_md)||Z;C="DeepScientist received PI response",w&&h.push({id:"open-quest",label:"Open Quest",onClick:()=>R({focusType:"quest",focusId:w})});const Ce=_e(a.decision);Ce&&p.push({label:"decision",value:Ce});const ie=El(a.next_actions);ie.length&&p.push({label:"next",value:ie.slice(0,3).join(", ")});const Ee=Q;Ee&&p.push({label:"question_id",value:Ee}),Ae&&p.push({label:"question",value:Ae}),oe&&p.push({label:"answer",value:oe})}else if(f==="events")A="Events",C=`${(Array.isArray(u?.items)?u?.items:[]).length||0} events${_?` · ${_}`:""}`,w&&h.push({id:"view-all",label:"View All",onClick:()=>R({focusType:"quest",focusId:w})});else if(f==="audit"){A="Audit";const oe=Array.isArray(u?.errors)?(u?.errors).length:0,Ae=Array.isArray(u?.warnings)?(u?.warnings).length:0;C=`errors ${oe} · warnings ${Ae}`,w&&h.push({id:"open-report",label:"Open Report",onClick:()=>R({focusType:"quest",focusId:w})})}else if(f==="inbox"||f==="inbox_wait"){A="Inbox";const oe=Array.isArray(u?.items)?u?.items:[];U=e.status==="calling"&&f==="inbox_wait",M=U?"Waiting":"Done",C=U?"Waiting":`${oe.length||0} new`,w&&h.push({id:"open-quest",label:"Open",onClick:()=>R({focusType:"quest",focusId:w})})}else if(f==="baseline_bind"){A="Baseline",C=_e(u?.baseline_rel_path)||_e(a.target_path)||"Bound";const Ae=_e(u?.baseline_root_id)||_e(a.baseline_root_id);Ae&&p.push({label:"baseline_id",value:Ae})}else if(f==="create"){A="Creating Quest";const oe=_e(a.title)||_e(u?.title),Ae=_e(a.summary)||_e(u?.summary);C=oe?`DeepScientist is creating "${oe}"`:"DeepScientist is creating a quest",oe&&p.push({label:"title",value:oe}),Ae&&p.push({label:"summary",value:Ae});const Ce=_e(u?.quest_id);Ce&&p.push({label:"quest_id",value:Ce})}else f==="read"&&(A="Quest",C="Reading quests");else if(d==="lab_pi_sleep"){A="PI Waiting";const oe=Cl(a.mode);if(oe==="snapshot")A="Snapshot",C="Quest snapshot",w&&h.push({id:"open-quest",label:"Open Quest",onClick:()=>R({focusType:"quest",focusId:w})});else if(oe==="control"){A="PI Control";const Ae=_e(a.action),Ce=_e(u?.pi_state);C=[Ae,Ce?`→ ${Ce}`:""].filter(Boolean).join(" ")}else U=e.status==="calling",M=U?"Waiting":"Done",C=U?"Polling for events…":"Wait complete",w&&h.push({id:"open-latest",label:"Open Latest",onClick:()=>{const Ce=(Array.isArray(u?.events)?u?.events:[])[0],ie=_e(Ce?.event_id),Ee=_e(Ce?.branch);if(ie){R({focusType:"quest-event",focusId:w,branch:Ee||_,eventId:ie});return}R({focusType:"quest",focusId:w})}})}else if(d==="status_update"){A="Status",C=_e(a.message)||_e(a.text)||"Status update";const Ae=_e(a.phase),Ce=_e(a.step),ie=El(a.next);Ae&&p.push({label:"phase",value:Ae}),Ce&&p.push({label:"step",value:Ce}),ie.length&&p.push({label:"next",value:ie.slice(0,3).join(", ")})}else if(d==="write_question"){A="Question";const oe=a.question_set;C=YS(oe)||"Awaiting answer",U=e.status==="calling",M=U?"Waiting":"Done"}else if(d==="write_memory"){A="Memory";const oe=Cl(a.mode),Ae=_e(a.kind),Ce=_e(a.title),ie=_e(a.content_md)||_e(u?.content_md)||_e(a.content)||"",Ee=Ce||GS(ie)||[oe,Ae].filter(Boolean).join(" · ");C=Ce?`DeepScientist is saving memory "${Ce}"`:"DeepScientist is saving memory";const fe=_e(u?.id)||_e(a.id),Fe=El(a.tags),We=_e(a.confidence);fe&&p.push({label:"id",value:fe}),oe&&p.push({label:"mode",value:oe}),Ae&&p.push({label:"kind",value:Ae}),We&&p.push({label:"confidence",value:We}),Fe.length&&p.push({label:"tags",value:Fe.slice(0,3).join(", ")}),Ee&&Ee!==Ce&&p.push({label:"summary",value:Ee})}else if(d==="lab_baseline"){A="Baseline";const oe=Cl(a.mode),Ae=_e(a.target_path)||_e(a.source_path),Ce=oe||"processing";C=Ae?`DeepScientist is ${Ce.replace(/_/g," ")} ${Ae}`:`DeepScientist is ${Ce.replace(/_/g," ")} baseline`;const ie=_e(a.baseline_root_id)||_e(u?.baseline_root_id);ie&&p.push({label:"baseline_id",value:ie})}T&&(M="Error"),C||(C=o?"":"—"),C=KS(C);const Se=M==="Error"?"ds-lab-status-error":M==="Done"?"ds-lab-status-done":M==="Waiting"?"ds-lab-status-waiting":"ds-lab-status-running",$e=Al[d]||Al.default,Ne=Nr(e.timestamp),G=oe=>{if(!Number.isFinite(oe)||oe<0)return"";const Ae=Math.floor(oe),Ce=Math.floor(Ae/60),ie=Ae%60;return Ce>0?`${Ce}:${ie.toString().padStart(2,"0")}`:`0:${ie.toString().padStart(2,"0")}`},[J,$]=c.useState(()=>U?G(Date.now()/1e3-(e.timestamp||Date.now()/1e3)):"");c.useEffect(()=>{if(!U)return;const oe=()=>$(G(Date.now()/1e3-(e.timestamp||Date.now()/1e3)));oe();const Ae=window.setInterval(oe,1e3);return()=>window.clearInterval(Ae)},[U,e.timestamp]);const[I,O]=c.useState(!1),[X,ne]=c.useState(!1),ke=c.useRef(e.status);c.useEffect(()=>{if(ke.current!==e.status&&e.status==="called"){ne(!0);const oe=window.setTimeout(()=>ne(!1),180);return()=>window.clearTimeout(oe)}ke.current=e.status},[e.status]);const de=p.filter(oe=>oe.value).slice(0,6),Te=Math.max(p.filter(oe=>oe.value).length-de.length,0),Oe=d==="lab_quests"&&f==="read",He=_e(d==="lab_quests"&&(f==="pi_ask"||f==="pi_answer")?_e(a.question)||_e(u?.question)||_e(a.context_md):""),ut=_e(d==="lab_quests"&&(f==="pi_ask"||f==="pi_answer")?_e(u?.answer)||_e(a.answer):"");if(!r)return null;if(Oe){const oe=Al[d]||Al.default,Ae=Nr(e.timestamp);return s.jsxs("div",{className:"group flex items-start gap-2","data-tool-status":e.status==="calling"?"calling":void 0,children:[s.jsx("div",{className:"min-w-0 flex-1",children:s.jsxs("div",{className:z("ai-manus-tool-chip flex w-full items-start gap-2 rounded-[12px] border border-[var(--border-light)] px-3 py-2 text-left",t?"text-[10px]":"text-[11px]","bg-[var(--fill-tsp-white-light)] text-[var(--text-secondary)]"),children:[s.jsx("span",{className:"mt-[2px] inline-flex h-4 w-4 items-center justify-center text-[var(--icon-primary)]",children:s.jsx(oe,{className:"h-4 w-4"})}),s.jsx("span",{className:"min-w-0 flex-1 break-words",children:s.jsx("span",{className:z("block break-words font-medium text-[var(--text-secondary)]",t?"text-[10px]":"text-[11px]"),children:"DeepScientist is reading quests..."})})]})}),t?null:s.jsx("div",{className:"text-[9px] text-[var(--text-tertiary)] opacity-0 transition group-hover:opacity-100",children:Ae})]})}return s.jsxs("div",{className:z("ds-lab-tool-card",t&&"ds-lab-tool-card--compact",X&&"is-updated"),"data-status":M.toLowerCase(),children:[s.jsxs("div",{className:"ds-lab-tool-card__header",children:[s.jsxs("div",{className:"ds-lab-tool-card__title",children:[s.jsx($e,{className:"ds-lab-tool-card__icon"}),s.jsx("span",{className:"ds-lab-tool-card__label",children:A})]}),s.jsxs("div",{className:"ds-lab-tool-card__meta",children:[s.jsxs("span",{className:z("ds-lab-tool-card__status",Se),children:[s.jsx("span",{className:z("ds-lab-tool-card__dot",U?"is-pulse-slow":e.status==="calling"?"is-pulse-fast":"")}),M,U&&J?` ${J}`:""]}),s.jsx("span",{className:"ds-lab-tool-card__time",children:Ne})]})]}),o?s.jsxs("div",{className:"ds-lab-tool-card__skeleton","aria-hidden":"true",children:[s.jsx("span",{className:"ds-lab-tool-card__skeleton-line"}),s.jsx("span",{className:"ds-lab-tool-card__skeleton-line is-short"})]}):d==="lab_pi_sleep"&&U?s.jsxs("div",{className:"ds-lab-tool-card__summary ds-lab-terminal-line",children:["waiting for events",s.jsx("span",{className:"ds-lab-terminal-cursor","aria-hidden":"true"})]}):s.jsx("div",{className:"ds-lab-tool-card__summary",children:C}),!o&&(He||ut)?s.jsxs("div",{className:"ds-lab-qa",children:[He?s.jsxs("div",{className:"ds-lab-qa__row",children:[s.jsx("span",{className:"ds-lab-qa__label ds-lab-qa__label--q",children:"Q"}),s.jsx("span",{className:"ds-lab-qa__text",children:He})]}):null,ut?s.jsxs("div",{className:"ds-lab-qa__row",children:[s.jsx("span",{className:"ds-lab-qa__label ds-lab-qa__label--a",children:"A"}),s.jsx("span",{className:"ds-lab-qa__text",children:ut})]}):null]}):null,!o&&h.length>0?s.jsx("div",{className:"ds-lab-tool-card__actions",children:h.map(oe=>s.jsx("button",{type:"button",className:"ds-lab-tool-card__action",onClick:oe.onClick,children:oe.label},oe.id))}):null,!o&&de.length>0?s.jsxs("div",{className:"ds-lab-tool-card__details",children:[s.jsxs("button",{type:"button",className:"ds-lab-tool-card__details-toggle",onClick:()=>O(oe=>!oe),children:["Details",s.jsx("span",{className:z("ds-lab-tool-card__chevron",I&&"is-open")})]}),I?s.jsxs("div",{className:"ds-lab-tool-card__details-body",children:[de.map(oe=>s.jsxs("div",{className:"ds-lab-tool-card__detail-row",children:[s.jsx("span",{className:"ds-lab-tool-card__detail-label",children:oe.label}),s.jsx("span",{className:z("ds-lab-tool-card__detail-value",oe.label==="instruction"&&"ds-lab-tool-card__detail-value--multiline"),children:oe.value})]},oe.label)),Te>0?s.jsxs("div",{className:"ds-lab-tool-card__detail-row",children:[s.jsx("span",{className:"ds-lab-tool-card__detail-label",children:"more"}),s.jsxs("span",{className:"ds-lab-tool-card__detail-value",children:["+",Te," more"]})]}):null]}):null]}):null]})}function Gd({toolContent:e}){return s.jsx("div",{className:"flex h-full min-h-0 flex-col bg-[var(--background-surface)]",children:s.jsx("div",{className:"flex-1 overflow-y-auto px-4 py-4",children:s.jsx("div",{className:"mx-auto w-full max-w-[560px]",children:s.jsx(Mg,{tool:e})})})})}function sk(e){return s.jsx(Gd,{...e})}function rk(e){return s.jsx(Gd,{...e})}function ak(e){return s.jsx(Gd,{...e})}function xa(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Ss(...e){for(const t of e){if(typeof t!="string")continue;const n=t.trim();if(n)return n}return""}function Lg(e){const t=xa(e),n=Ss(t.arxiv_id,t.link,t.id),r=Ss(t.abs_url,n?`https://arxiv.org/abs/${n}`:""),a=Ss(t.pdf_url,n?`https://arxiv.org/pdf/${n}.pdf`:""),i=Ss(t.url,r,a),o={title:Ss(t.title,t.name,"Untitled"),abstract:Ss(t.abstract,t.snippet,t.summary,t.description),url:i,absUrl:r,arxivId:n,pdfUrl:a,source:Ss(t.source,"arxiv")};return!o.title&&!o.url&&!o.abstract?null:o}function ik(e){const t=xa(e),n=Ss(t.question,t.query);if(!n)return null;const a=(Array.isArray(t.papers)?t.papers:[]).map(Lg).filter(u=>u!=null),i=typeof t.count=="number"?t.count:a.length,o=Ss(t.error)||void 0;return{question:n,count:i,papers:a,error:o}}function ok(e){if(!e)return"";try{return`${(e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(`https://${e}`)).origin}/favicon.ico`}catch{return""}}function lk({toolContent:e,panelMode:t}){const n=t==null,r=xa(e),a=xa(e.content),i=xa(a.result),o=Object.keys(i).length>0?i:a,u=Ss(o.error,a.error,r.error)||void 0,f=(Array.isArray(o.papers)?o.papers:[]).map(Lg).filter(W=>W!=null),h=(Array.isArray(o.question_results)?o.question_results:[]).map(ik).filter(W=>W!=null),y=h.length>0,g=Ss(o.query,o.question,a.query,a.question),T=typeof o.count=="number"?o.count:void 0,w=xa(e.args),_=g||y&&h[0]?.question||""||Ss(w.query,w.question,w.q,w.text),b=T??(y?h.reduce((W,Z)=>W+Z.papers.length,0):f.length),E=xa(o.paper_search_usage),R=typeof E.total_calls=="number"&&Number.isFinite(E.total_calls)?E.total_calls:void 0,A=typeof o.required_paper_search_calls_for_pdf_annotate=="number"&&Number.isFinite(o.required_paper_search_calls_for_pdf_annotate)?o.required_paper_search_calls_for_pdf_annotate:void 0,C=Ss(o.annotation_gate_hint,o.message),M=e.status==="calling",U=!M&&!u,Q=y&&h.some(W=>W.papers.length>0),ae=U&&(y?!Q:b<=0),ye=M?"Searching arXiv papers...":ae?"Search completed, but no papers were returned. Try a narrower question.":"No papers found.",V=(W,Z,Se="global")=>{const $e=W.absUrl||W.url||W.pdfUrl,Ne=ok($e);return s.jsx("div",{className:"rounded-lg border border-[var(--border-light)] bg-[var(--background-main)] p-4 transition-colors hover:border-[var(--border-main)]",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx("div",{className:"mt-[2px] flex h-4 w-4 items-center justify-center rounded-[4px] bg-[var(--background-gray-subtle)]",children:Ne?s.jsx("img",{src:Ne,alt:"",className:"h-4 w-4 rounded-[4px]",onError:G=>{G.currentTarget.style.display="none"}}):null}),s.jsxs("div",{className:"min-w-0 flex-1",children:[$e?s.jsxs("a",{href:$e,target:"_blank",rel:"noopener noreferrer",className:"group flex items-start gap-2 text-xs font-medium text-[var(--text-primary)] hover:text-[var(--accent-primary)]",children:[s.jsx("span",{className:"flex-1",children:W.title||"Untitled"}),s.jsx(wb,{className:"h-4 w-4 flex-shrink-0 opacity-0 transition-opacity group-hover:opacity-100"})]}):s.jsx("div",{className:"text-xs font-medium text-[var(--text-primary)]",children:W.title||"Untitled"}),s.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-xs text-[var(--text-tertiary)]",children:[W.arxivId&&s.jsxs("span",{className:"rounded bg-[var(--background-gray-subtle)] px-1.5 py-0.5 font-mono",children:["arXiv:",W.arxivId]}),W.source&&s.jsx("span",{className:"rounded bg-[var(--background-gray-subtle)] px-1.5 py-0.5 uppercase",children:W.source}),W.absUrl&&s.jsxs("a",{href:W.absUrl,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 text-[var(--accent-primary)] hover:underline",children:[s.jsx(Hl,{className:"h-3 w-3"}),"arXiv"]}),W.pdfUrl&&s.jsxs("a",{href:W.pdfUrl,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 text-[var(--accent-primary)] hover:underline",children:[s.jsx(No,{className:"h-3 w-3"}),"PDF"]})]}),W.abstract&&s.jsx("p",{className:"mt-2 line-clamp-3 text-xs text-[var(--text-secondary)]",children:W.abstract})]})]})},`${Se}-${W.arxivId||Z}`)};return s.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[n?s.jsxs("div",{className:"flex h-[36px] items-center border-b border-[var(--border-main)] bg-[var(--background-gray-main)] px-3 shadow-[inset_0px_1px_0px_0px_#FFFFFF]",children:[s.jsx(Hl,{className:"mr-2 h-4 w-4 text-[var(--text-tertiary)]"}),s.jsx("div",{className:"flex-1 text-center text-xs font-medium text-[var(--text-tertiary)]",children:"Paper Search"})]}):null,s.jsx("div",{className:"relative flex-1 overflow-y-auto",children:s.jsxs("div",{className:"mx-auto flex max-w-[720px] flex-col gap-4 px-4 py-3",children:[!y&&_&&s.jsxs("div",{className:"text-xs text-[var(--text-tertiary)]",children:['Question: "',_,'"'," ",b!==void 0&&`• ${b} papers found`]}),y&&s.jsxs("div",{className:"text-xs text-[var(--text-tertiary)]",children:["Parallel questions: ",h.length,b!==void 0&&` • ${b} merged papers found`]}),R!==void 0||C?s.jsxs("div",{className:"rounded-lg border border-[var(--border-light)] bg-[var(--background-gray-main)]/40 px-3 py-2 text-xs text-[var(--text-secondary)]",children:[R!==void 0?s.jsxs("div",{children:["paper_search calls: ",R,A!==void 0?` (>=${A} to start PDF annotations)`:null]}):null,C?s.jsx("div",{className:R!==void 0?"mt-1":"",children:C}):null]}):null,u?s.jsxs("div",{className:"ds-tool-error-banner",role:"status",children:[s.jsx(Tn,{className:"ds-tool-error-icon"}),s.jsx("span",{children:u})]}):!y&&f.length===0||y&&!Q?s.jsx("div",{className:"text-xs text-[var(--text-tertiary)]",children:ye}):y?s.jsx("div",{className:"space-y-4",children:h.map((W,Z)=>s.jsxs("section",{className:"rounded-lg border border-[var(--border-light)] bg-[var(--background-gray-main)]/50 p-3",children:[s.jsxs("div",{className:"mb-3 text-xs font-medium text-[var(--text-secondary)]",children:["Q",Z+1,': "',W.question,'" • ',W.papers.length," papers found"]}),W.error?s.jsx("div",{className:"mb-3 text-xs text-[var(--status-error)]",children:W.error}):null,W.papers.length===0?s.jsx("div",{className:"text-xs text-[var(--text-tertiary)]",children:"No papers returned for this question."}):s.jsx("div",{className:"space-y-3",children:W.papers.map((Se,$e)=>V(Se,$e,`q${Z}`))})]},`question-group-${Z}`))}):f.map((W,Z)=>V(W,Z))]})})]})}function di(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Js(...e){for(const t of e){if(typeof t!="string")continue;const n=t.trim();if(n)return n}return""}function fi(e){if(typeof e=="number"&&Number.isFinite(e))return Math.max(0,Math.floor(e));if(typeof e=="string"&&e.trim()){const t=Number(e);if(Number.isFinite(t))return Math.max(0,Math.floor(t))}return 0}function Pg(e){const t=di(e),n=fi(t.input_tokens),r=fi(t.output_tokens),a=fi(t.total_tokens)||n+r;return{inputTokens:n,outputTokens:r,totalTokens:a}}function ck(e,t=""){const n=di(e),r=Js(n.arxiv_id,t),a=Js(n.abs_url,r?`https://arxiv.org/abs/${r}`:""),i=Js(n.pdf_url,r?`https://arxiv.org/pdf/${r}.pdf`:"");return{arxivId:r,absUrl:a,pdfUrl:i}}function uk(e){const t=di(e),n=Js(t.id),r=Js(t.question),a=Js(t.status).toLowerCase()||"failed",i=Js(t.answer),o=Js(t.error)||void 0,u=Array.isArray(t.next_steps)?t.next_steps.map(p=>Js(p)).filter(p=>!!p):[],d=ck(t.arxiv,n),f=Pg(t.usage);return!n&&!r&&!i&&!o?null:{id:n,question:r,status:a,answer:i,error:o,nextSteps:u,arxiv:d,usage:f}}function dk({toolContent:e,panelMode:t}){const{t:n}=nr("workspace"),r=t==null,a=di(e),i=di(e.content),o=di(i.result),u=Object.keys(o).length>0?o:i,d=(Array.isArray(u.results)?u.results:[]).map(uk).filter(b=>b!=null),f=Pg(u.usage),p=fi(u.success_count)||d.filter(b=>b.status==="ok").length,h=fi(u.failed_count)||Math.max(0,d.length-p),y=fi(u.count)||d.length,g=Js(u.message),T=Js(u.error,i.error,a.error),w=e.status==="calling",_=g||n("tool_read_paper_summary",{count:y,success:p,failed:h},"Processed {count} item(s): {success} succeeded, {failed} failed.");return s.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[r?s.jsxs("div",{className:"flex h-[36px] items-center border-b border-[var(--border-main)] bg-[var(--background-gray-main)] px-3 shadow-[inset_0px_1px_0px_0px_#FFFFFF]",children:[s.jsx(ux,{className:"mr-2 h-4 w-4 text-[var(--text-tertiary)]"}),s.jsx("div",{className:"flex-1 text-center text-xs font-medium text-[var(--text-tertiary)]",children:n("tool_read_paper_title",{},"Read Paper")})]}):null,s.jsx("div",{className:"relative flex-1 overflow-y-auto",children:s.jsxs("div",{className:"mx-auto flex max-w-[760px] flex-col gap-3 px-4 py-3",children:[w?s.jsx("div",{className:"text-xs text-[var(--text-tertiary)]",children:n("tool_read_paper_running",{},"Reading papers...")}):null,w?null:s.jsxs("div",{className:"text-xs text-[var(--text-tertiary)]",children:[_,f.totalTokens>0?` · ${n("tool_read_paper_usage",{input:f.inputTokens,output:f.outputTokens,total:f.totalTokens},"Input {input} · Output {output} · Total {total}")}`:""]}),T?s.jsxs("div",{className:"ds-tool-error-banner",role:"status",children:[s.jsx(Tn,{className:"ds-tool-error-icon"}),s.jsx("span",{children:T})]}):null,!w&&d.length===0?s.jsx("div",{className:"text-xs text-[var(--text-tertiary)]",children:n("tool_read_paper_empty",{},"No read_paper results yet.")}):null,d.map((b,E)=>s.jsxs("article",{className:"rounded-xl border border-[var(--border-light)] bg-[var(--background-main)] p-4",children:[s.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2 text-xs text-[var(--text-tertiary)]",children:[s.jsx("span",{className:"rounded bg-[var(--background-gray-subtle)] px-1.5 py-0.5 font-mono",children:b.arxiv.arxivId||b.id||`#${E+1}`}),b.arxiv.absUrl?s.jsxs("a",{href:b.arxiv.absUrl,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-[var(--accent-primary)] hover:underline",children:[s.jsx(Hl,{className:"h-3 w-3"}),"arXiv"]}):null,b.arxiv.pdfUrl?s.jsxs("a",{href:b.arxiv.pdfUrl,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-[var(--accent-primary)] hover:underline",children:[s.jsx(No,{className:"h-3 w-3"}),"PDF"]}):null]}),s.jsx("div",{className:"mb-2 text-[11px] font-semibold text-[var(--text-secondary)]",children:n("tool_read_paper_question_label",{},"Question")}),s.jsx("p",{className:"mb-3 whitespace-pre-wrap text-xs text-[var(--text-primary)]",children:b.question}),b.status==="ok"?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mb-2 text-[11px] font-semibold text-[var(--text-secondary)]",children:n("tool_read_paper_answer_label",{},"Answer")}),s.jsx("p",{className:"whitespace-pre-wrap text-xs leading-relaxed text-[var(--text-primary)]",children:b.answer})]}):s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"mb-1 text-[11px] font-semibold text-[var(--text-secondary)]",children:n("tool_read_paper_failed_label",{},"Failed")}),s.jsx("p",{className:"text-xs text-[var(--text-primary)]",children:b.error||n("tool_read_paper_failed_generic",{},"Read paper failed.")}),b.nextSteps.length>0?s.jsxs("div",{className:"rounded-lg bg-[var(--background-gray-subtle)] px-3 py-2 text-xs text-[var(--text-secondary)]",children:[s.jsx("div",{className:"mb-1 font-semibold",children:n("tool_read_paper_next_steps_label",{},"Next steps")}),s.jsx("ul",{className:"list-disc space-y-1 pl-4",children:b.nextSteps.map((R,A)=>s.jsx("li",{children:R},`${b.id||E}-step-${A}`))})]}):null]})]},`${b.id||"item"}-${E}`))]})})]})}function fk({toolContent:e,panelMode:t}){const n=t==null,r=!n,[a,i]=c.useState(r),o=Sb({args:e.args,content:e.content,metadataSearch:e.metadata&&typeof e.metadata=="object"?e.metadata.search:void 0,output:e.content&&typeof e.content=="object"?e.content.result??e.content.output:void 0}),u=o.error,d=o.results,f=o.query,p=o.count,h=e.status==="calling",y=o.queries;return c.useEffect(()=>{i(r)},[r,e.tool_call_id]),s.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[n?s.jsx("div",{className:"flex h-[36px] items-center border-b border-[var(--border-main)] bg-[var(--background-gray-main)] px-3 shadow-[inset_0px_1px_0px_0px_#FFFFFF]",children:s.jsx("div",{className:"flex-1 text-center text-xs font-medium text-[var(--text-tertiary)]",children:"Search"})}):null,s.jsx("div",{className:"relative flex-1 overflow-y-auto",children:s.jsx("div",{className:"mx-auto flex max-w-[720px] flex-col gap-3 px-4 py-3",children:s.jsxs(Kd,{title:h?"DeepScientist is searching the web...":"DeepScientist searched the web.",subtitle:f?`Primary query: ${f}`:"This run records the exact search queries that Codex issued.",accent:"blue",meta:s.jsxs(s.Fragment,{children:[s.jsx(DsToolPill,{children:h?"running":"completed"}),p>0?s.jsxs(DsToolPill,{tone:"success",children:[p," results"]}):null,y.length>0?s.jsxs(DsToolPill,{tone:"muted",children:[y.length," queries"]}):null]}),children:[u?s.jsxs("div",{className:"ds-tool-error-banner",role:"status",children:[s.jsx(Tn,{className:"ds-tool-error-icon"}),s.jsx("span",{children:u})]}):null,y.length>0?s.jsx(Lt,{title:"Issued queries",children:s.jsx(kb,{queries:y,activeQuery:f})}):null,p>0&&!r?s.jsx("button",{type:"button",onClick:()=>i(g=>!g),className:"inline-flex w-fit items-center gap-2 rounded-full border border-[var(--border-light)] bg-[rgba(255,255,255,0.82)] px-3 py-1.5 text-[11px] font-medium text-[var(--text-secondary)] transition hover:bg-[var(--background-white-main)]",children:a?"Hide results":`Show results (${p})`}):null,o.summary?s.jsx(Lt,{title:"Search summary",children:s.jsx("div",{className:"text-[12px] leading-6 text-[var(--text-secondary)]",children:o.summary})}):null,d.length>0&&a?s.jsx(Lt,{title:`Results (${p})`,children:s.jsx(Nb,{payload:o})}):null,!u&&d.length===0?s.jsxs(Lt,{title:"Search trace",children:[s.jsxs("div",{className:"flex items-start gap-2 text-[12px] leading-6 text-[var(--text-secondary)]",children:[s.jsx(sc,{className:"mt-0.5 h-4 w-4 text-[#6382ad]"}),s.jsx("span",{children:h?"Codex is still issuing search queries.":y.length>0?"This run preserved the search trace, but the upstream runtime did not return result cards for this call.":"No structured search results were returned for this call."})]}),o.summary?s.jsx("div",{className:"mt-3 rounded-[12px] bg-[rgba(255,255,255,0.72)] px-3 py-3 text-[12px] leading-6 text-[var(--text-secondary)]",children:o.summary}):null]}):null]})})})]})}const pk=dx(()=>fx(()=>import("./index-DrUnlf6K.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(e=>e.CliToolTerminal),{loading:()=>s.jsx("div",{className:"flex h-full items-center justify-center text-xs text-[var(--text-tertiary)]",children:"Loading terminal..."})});function dh(e){return e?typeof e=="string"?e:!Array.isArray(e)||e.length===0?"":e.map(t=>{const n=t.ps1?`${t.ps1} `:"",r=t.command??"",a=t.output??"";return`${n}${r}
195
+ ${a}`}).join(`
196
+ `):""}function mk(e){const t="Sandbox is starting or unavailable. Retrying...";if(!e)return t;if(typeof e=="string")return e;if(typeof e!="object")return t;if(e.response?.status===429)return"Too many requests. Retrying...";const a=e.response?.data?.detail;if(typeof a=="string"){const o=a.toLowerCase();return o.includes("docker_not_available")?"Sandbox is unavailable (Docker not available).":o.includes("sandbox_quota_exceeded")?"Sandbox quota exceeded. Stop another sandbox session to continue.":o.includes("sandbox_global_limit")?"Sandbox capacity reached. Please retry shortly.":o.includes("sandbox_starting")?"Sandbox is starting. Retrying...":o.includes("session id does not exist")||o.includes("session_not_found")||o.includes("session not found")?"Shell session not found. Run a shell command first.":o.includes("process has ended")?"Shell process ended. Run a new command to create a session.":o.includes("timeout")||o.includes("timed out")?t:a}const i=e.message;if(typeof i=="string"){const o=i.toLowerCase();if(o.includes("timeout")||o.includes("timed out"))return t;if(o.includes("connection refused")||o.includes("connect"))return"Sandbox service is unavailable. Retrying..."}return t}function hk(e){if(!e||typeof e!="object")return!1;if(e.response?.status===429)return!0;const n=e.response?.data?.detail;if(typeof n=="string"&&n.toLowerCase().includes("rate"))return!0;const r=e.message;if(typeof r=="string"){const a=r.toLowerCase();return a.includes("429")||a.includes("rate limit")}return!1}function xk(e){if(!e)return[];const t=[];let n="";for(let r=0;r<e.length;r+=1){const a=e[r];if(a==="\r"){e[r+1]===`
197
+ `&&(r+=1),t.push({input:n,pressEnter:!0}),n="";continue}if(a===`
198
+ `){t.push({input:n,pressEnter:!0}),n="";continue}n+=a}return n&&t.push({input:n,pressEnter:!1}),t}function gk({sessionId:e,toolContent:t,live:n,projectId:r,executionTarget:a,cliServerId:i,readOnly:o,active:u,panelMode:d}){const f=t.content?.runtime??t.content?.execution_target??a??"sandbox",p=d==="terminal",h=c.useMemo(()=>{const O=t.args;return typeof O?.id=="string"?O.id:typeof t.content?.session_id=="string"?t.content.session_id:typeof t.content?.shell_session_id=="string"?t.content.shell_session_id:""},[t]),y=!!(f==="cli"&&r&&i&&e&&u&&p),g=!1,[T,w]=c.useState(""),[_,b]=c.useState(null),E=_??"",R=E.length>0,A=c.useRef(""),C=c.useRef(()=>{}),M=c.useRef(()=>{}),U=c.useRef(()=>{}),Q=c.useRef(()=>!1),ae=c.useRef(!1),ye=c.useRef(null),V=c.useRef([]),W=c.useRef(!1),Z=c.useRef({until:0,delay:0}),Se=c.useMemo(()=>{const O=t.content?.console,X=t.content?.output;return dh(O)||X||""},[t]),$e=c.useMemo(()=>{if(n)return null;const O=t.args;return typeof O?.command=="string"&&O.command.trim()?O.command.trim():typeof O?.input=="string"&&O.input.trim()?O.input.trim():null},[n,t]);c.useEffect(()=>{ye.current=$e},[$e,t.tool_call_id]);const Ne=c.useCallback(()=>{const O=Date.now(),X=Z.current.delay,ne=Math.min(X?X*2:1500,15e3);Z.current={until:O+ne,delay:ne},b("Too many requests. Retrying...")},[]),G=c.useCallback(O=>{if(!ae.current){A.current=O;return}const X=A.current;if(O!==X){if(O.startsWith(X)?C.current?.(O.slice(X.length)):(M.current?.(),C.current?.(O)),A.current=O,ye.current){Q.current?.(ye.current)&&(ye.current=null);return}(u||n)&&U.current?.()}},[u,n]),J=c.useCallback(()=>{w(Se),b(null)},[Se]);c.useEffect(()=>{J()},[J,t.tool_call_id]),c.useEffect(()=>{G(T)},[G,T]);const $=c.useCallback(async()=>{if(!W.current){if(!e||!h||o){V.current=[];return}for(W.current=!0;V.current.length>0;){const O=V.current.shift();if(!O)break;const{input:X,pressEnter:ne}=O;if(!(!X&&!ne))try{const ke=await O_(e,h,X,ne),Te=dh(ke.console)||ke.output;Te&&w(Te),b(null),Z.current={until:0,delay:0}}catch(ke){if(hk(ke)){Ne();continue}b(mk(ke)),console.error("[ShellToolView] Failed to write to shell",ke)}}W.current=!1,J()}},[Ne,o,J,e,h]),I=c.useCallback((O,X)=>{if(!O&&!X)return;const ne=V.current,ke=ne[ne.length-1];ke&&!ke.pressEnter&&!X?ke.input+=O:ne.push({input:O,pressEnter:X}),$()},[$]);return c.useCallback(O=>{const X=xk(O);X.length!==0&&X.forEach(ne=>I(ne.input,ne.pressEnter))},[I]),s.jsxs("div",{className:z("flex h-full min-h-0 flex-col",p&&"ds-terminal-shell"),children:[p?null:s.jsx("div",{className:"flex h-[36px] items-center border-b border-[var(--border-main)] bg-[var(--background-gray-main)] px-3 shadow-[inset_0px_1px_0px_0px_#FFFFFF]",children:s.jsx("div",{className:"flex-1 truncate text-center text-xs font-medium text-[var(--text-tertiary)]",children:h||"Shell"})}),s.jsx("div",{className:z("flex-1 overflow-auto bg-[var(--background-white-main)]",p&&"ds-terminal-shell-body"),children:y?s.jsxs("div",{className:z("relative h-full p-3",p&&"p-2"),children:[s.jsx(pk,{projectId:r??"",serverId:i??"",chatSessionId:e??"",shellSessionId:h||void 0,operationId:t.content?.operation_id,readOnly:o,showHeader:!p}),R?s.jsxs("div",{className:"ds-tool-error-banner",role:"status",children:[s.jsx(Tn,{className:"ds-tool-error-icon"}),s.jsx("span",{children:E})]}):null]}):s.jsxs("div",{className:z("flex h-full min-h-0 flex-col p-3",p&&"p-2"),children:[s.jsxs("div",{className:"relative flex min-h-0 flex-1",children:[s.jsx("div",{className:"cli-root flex min-h-0 flex-1 flex-col",children:s.jsx(jb,{onInput:()=>{},onResize:()=>{},searchOpen:!1,onSearchOpenChange:()=>{},appearance:"terminal",autoFocus:g,showHeader:!p,onReady:({write:O,clear:X,scrollToBottom:ne,focus:ke,search:de})=>{C.current=O,M.current=X,U.current=ne,Q.current=de,ae.current=!0,G(A.current)}})}),R?s.jsxs("div",{className:"ds-tool-error-banner",role:"status",children:[s.jsx(Tn,{className:"ds-tool-error-icon"}),s.jsx("span",{children:E})]}):null]}),s.jsx("div",{className:"mt-2 text-xs text-[var(--text-tertiary)]",children:o?"View only. Input is disabled.":e?p?f==="cli"?"Connect a CLI server to enable terminal input.":"Sandbox shell output is view-only. Run a shell tool to execute commands.":"Switch to terminal view to enter commands.":"Start a task to run shell commands."})]})})]})}const fh={shell_exec:"Executing command",shell_view:"Viewing command output",shell_wait:"Waiting for command completion",shell_write_to_process:"Writing data to process",shell_kill_process:"Terminating process",bash_exec:"Executing bash command",read:"Reading file",write:"Writing file",edit:"Editing file",grep:"Searching file content",glob:"Finding file",file_read:"Reading file",file_read_lines:"Reading file lines",file_list:"Listing files",file_write:"Writing file",file_str_replace:"Replacing file content",file_find_in_content:"Searching file content",file_find_by_name:"Finding file",browser_view:"Viewing webpage",browser_navigate:"Navigating to webpage",browser_restart:"Restarting browser",browser_click:"Clicking element",browser_input:"Entering text",browser_move_mouse:"Moving mouse",browser_press_key:"Pressing key",browser_select_option:"Selecting option",browser_scroll_up:"Scrolling up",browser_scroll_down:"Scrolling down",browser_console_exec:"Executing JS code",browser_console_view:"Viewing console output",info_search_web:"Searching web",web_search:"Searching web",websearch:"Searching web",webfetch:"Fetching URL",web_news:"Searching news",paper_search:"Searching papers",read_paper:"Reading papers",message_notify_user:"Sending notification",message_ask_user:"Asking question",pdf_search:"Searching PDF",pdf_read_lines:"Reading PDF lines",pdf_annotate:"Annotating PDF",pdf_jump:"Jumping in PDF",rebuttal_pdf_search:"Searching PDF",rebuttal_pdf_read_lines:"Reading PDF lines",rebuttal_pdf_annotate:"Annotating PDF",rebuttal_pdf_jump:"Jumping in PDF",review_final_markdown_write:"Writing final report",rebuttal_final_markdown_write:"Writing final report",context_read:"Reading context",ds_system_read_file:"Reading file",ds_system_pull_file:"Reading file",ds_system_list_file:"Listing files",ds_system_list_dir:"Listing directory",ds_system_write_file:"Writing file",ds_system_append_file:"Writing file",ds_system_push_file:"Writing file",ds_system_grep_text:"Searching file content",ds_system_grep_files:"Finding files",ds_system_glob_files:"Finding file",ds_system_request_patch:"Applying patch",ds_system_log_event:"Logging event"},ph={shell_exec:"command",shell_view:"shell",shell_wait:"shell",shell_write_to_process:"input",shell_kill_process:"shell",bash_exec:"command",read:"file",write:"file",edit:"file",grep:"pattern",glob:"pattern",file_read:"file",file_read_lines:"file",file_list:"path",file_write:"file",file_str_replace:"file",file_find_in_content:"file",file_find_by_name:"path",browser_view:"page",browser_navigate:"url",browser_restart:"url",browser_click:"element",browser_input:"text",browser_move_mouse:"position",browser_press_key:"key",browser_select_option:"option",browser_scroll_up:"page",browser_scroll_down:"page",browser_console_exec:"code",browser_console_view:"console",info_search_web:"query",web_search:"query",websearch:"query",webfetch:"url",web_news:"query",paper_search:"query",read_paper:"items",message_notify_user:"message",message_ask_user:"question",pdf_search:"query",pdf_read_lines:"line",pdf_annotate:"comment",pdf_jump:"page",rebuttal_pdf_search:"query",rebuttal_pdf_read_lines:"line",rebuttal_pdf_annotate:"comment",rebuttal_pdf_jump:"page",review_final_markdown_write:"section_id",rebuttal_final_markdown_write:"section_id",context_read:"surface",ds_system_read_file:"path",ds_system_pull_file:"path",ds_system_list_file:"path",ds_system_list_dir:"path",ds_system_write_file:"path",ds_system_append_file:"path",ds_system_push_file:"path",ds_system_grep_text:"query",ds_system_grep_files:"pattern",ds_system_glob_files:"pattern",ds_system_request_patch:"target_path",ds_system_log_event:"event_type"},yk={shell:"Terminal",bash:"Terminal",file:"File",browser:"Browser",search:"Search",paper_search:"Paper Search",read_paper:"Read Paper",info:"Search",message:"Message",mcp:"MCP Tool"},bk={shell:Vl,bash:Vl,file:No,browser:md,search:Ou,paper_search:Hl,read_paper:ux,info:Ou,message:_x,mcp:Yv},vk={shell:gk,bash:Tb,file:gS,browser:fS,search:fk,paper_search:lk,read_paper:dk,mcp:zS},mh={lab_quests:sk,lab_pi_sleep:rk,lab_baseline:ak};function Dg(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function _k(e){const t=typeof e=="string"?e.trim():"";return t?t.startsWith("@")?t:`@${t}`:""}function $g(e){const t=e.metadata??{},n=typeof t.agent_label=="string"&&t.agent_label||typeof t.agent_id=="string"&&t.agent_id||typeof t.agent_role=="string"&&t.agent_role||"";return _k(n)||"@assistant"}function hh(e,t){for(const n of t){const r=e[n];if(r==null)continue;const a=Dg(r);if(a)return a}return""}function id(e){const t=(e.name||"").toLowerCase(),n=(e.function||"").toLowerCase();return n==="bash_exec"||t.includes("bash")?"bash":t.includes("mcp")||n.startsWith("mcp_")?"mcp":t.includes("message")?"message":n==="paper_search"||t.includes("paper_search")?"paper_search":n==="read_paper"||t.includes("read_paper")?"read_paper":n==="grep"||n==="glob"||t.includes("grep")||t.includes("glob")||t.includes("search")||n.startsWith("info_")||n.startsWith("web_")||n==="websearch"||n==="webfetch"?"search":n.startsWith("ds_system_")||n.startsWith("mcp_")||n.startsWith("lab_")||n.startsWith("mcp__")||n.includes("__mcp_")||n.includes("__lab_")?"mcp":t.includes("browser")||n.startsWith("browser_")?"browser":n==="read"||n==="write"||n==="edit"||t==="read"||t==="write"||t==="edit"||t.includes("file")||n.startsWith("file_")?"file":t.includes("shell")||n.startsWith("shell_")?"shell":"message"}function Qd(e){const t=id(e),n=(e.function||"").toLowerCase(),r=fh[e.function]??fh[n]??e.function,a=e.args&&typeof e.args=="object"&&!Array.isArray(e.args)?e.args:{},i=e.content&&typeof e.content=="object"&&!Array.isArray(e.content)?e.content:{},o=(e.function||"").toLowerCase();let u="";if((o.startsWith("file_")||o.startsWith("ds_system_"))&&(u=hh(a,["file","file_path","path","filePath"]),u||(u=hh(i,["file","file_path","filePath"]))),!u){const h=ph[e.function]??ph[n];u=h?Dg(a[h]):""}const d=yk[t]??e.name,f=bk[t]??_x;let p=vk[t];if(t==="mcp"){const h=yr(e.function||"");h&&mh[h]&&(p=mh[h])}return{category:t,name:d,icon:f,function:r,functionArg:u,view:p}}const Xd="chat-worker",wk=/^@([^\s]+)(?:\s+|$)/,Fg=()=>({id:Xd,label:"@chat-worker",description:"Default chat agent",role:"chat-worker",source:"backend",execution_target:"sandbox"}),zg=e=>{const t=typeof e.label=="string"?e.label.trim():"";return t?t.startsWith("@")?t:`@${t}`:`@${e.id}`},Sk=(e,t)=>{const n=t.trim().toLowerCase();if(!n)return null;const r=e.find(a=>a.id.toLowerCase()===n);return r||(e.find(a=>zg(a).slice(1).toLowerCase()===n)??null)},kk=e=>{const t=new Set,n=[];return e.forEach(r=>{const a=zg(r),i=`@${r.id}`;[a,i].forEach(u=>{const d=u.toLowerCase();t.has(d)||(t.add(d),n.push({agent:r,label:u}))})}),n},Yd=e=>{const t=Array.isArray(e)?e:[];return t.some(r=>r.id===Xd)?t:[Fg(),...t]},Nk=(e,t,n)=>{const r=e||"",a=r.trim(),i=Yd(t),o=n?.defaultAgent,u=o&&!i.some(b=>b.id===o.id)?[o,...i]:i,d=o??u.find(b=>b.id===Xd)??Fg(),f=n?.enabled??!0;if(!a)return{agent:d,displayMessage:"",agentMessage:"",matched:!1};if(!f||!r.startsWith("@"))return{agent:d,displayMessage:a,agentMessage:a,matched:!1};const p=kk(u),h=a.toLowerCase(),y=p.filter(b=>{if(!h.startsWith(b.label.toLowerCase()))return!1;const E=a[b.label.length];return E==null||/\s/.test(E)}).sort((b,E)=>E.label.length-b.label.length),T=(y.length>0?y:p.filter(b=>h.startsWith(b.label.toLowerCase())).sort((b,E)=>E.label.length-b.label.length))[0]??null;if(!T){const b=a.match(wk);if(!b)return{agent:d,displayMessage:a,agentMessage:a,matched:!1};const E=b[1]??"",R=Sk(u,E)??d,A=a.slice(b[0].length).trim();return!R||R.id===d.id&&E.toLowerCase()!==d.id?{agent:d,displayMessage:a,agentMessage:a,matched:!1}:{agent:R,displayMessage:a,agentMessage:A,matched:!0}}const w=T.agent,_=a.slice(T.label.length).trimStart();return!w||w.id===d.id?{agent:d,displayMessage:a,agentMessage:a,matched:!1}:{agent:w,displayMessage:a,agentMessage:_,matched:!0}},xh=10,Og=20,Bg=200,jk=3,Tk=Og*1024*1024,Ak=Bg*1024*1024,Mu=2e3,Ck=20*1024,Ek=new Set([".txt",".md",".json",".csv"]),gh=new Set(["application/json","application/pdf","image/png","image/jpeg","image/webp"]),Rk=new Set([".md",".txt",".csv",".json",".pdf",".png",".jpg",".jpeg",".webp"]),yh="text/*,application/json,application/pdf,image/png,image/jpeg,image/webp,.md,.txt,.csv",bh=e=>e.trim().replace(/\\/g,"/").replace(/\/+$/,""),qg=e=>{const t=e.lastIndexOf(".");return t<=0?"":e.slice(t).toLowerCase()},Zd=(e,t)=>(t||ri(e)||"").toLowerCase(),od=(e,t)=>{const n=qg(e);if(n&&Ek.has(n))return!0;const r=Zd(e,t);return r.startsWith("text/")||r==="application/json"||r==="text/csv"},vh=(e,t)=>Zd(e,t).startsWith("image/"),_h=(e,t)=>Zd(e,t)==="application/pdf"?!0:e.toLowerCase().endsWith(".pdf"),Ik=(e,t,n)=>{if(!od(e,t))return!1;const r=typeof n=="number"?n:0;return r>0&&r<=Ck},Jd=c.forwardRef(({projectId:e,sessionId:t,attachments:n,onAttachmentsChange:r,recentFiles:a,activeRecentFile:i,showRecentFiles:o,onRecentFilesRemove:u,onRecentFileOpen:d,ensureSession:f,readOnly:p,inputDisabled:h,compact:y},g)=>{const T=c.useRef(null),w=c.useRef(null),_=c.useRef([]),b=c.useRef([]),E=c.useRef(0),R=c.useRef(new Set),A=c.useRef(t??null),C=c.useRef(null),{addToast:M}=px(),U=!!y,[Q,ae]=c.useState(!1),[ye,V]=c.useState(!1),[W,Z]=c.useState(!1),[Se,$e]=c.useState(null),[Ne,G]=c.useState({}),[J,$]=c.useState({}),[I,O]=c.useState({}),[X,ne]=c.useState(!0),[ke,de]=c.useState(null),Te=c.useRef({}),{t:Oe}=nr("ai_manus"),He=c.useMemo(()=>n,[n]),ut=c.useMemo(()=>a??[],[a]),oe=c.useMemo(()=>i?bh(i):"",[i]),Ae=!!(o&&ut.length>0),Ce=!!d,ie=c.useMemo(()=>He.find(j=>j.file_id===Se)??null,[He,Se]),Ee=c.useMemo(()=>!ie||ie.status!=="success"?null:od(ie.filename,ie.content_type)?"text":vh(ie.filename,ie.content_type)?"image":_h(ie.filename,ie.content_type)?"pdf":"unknown",[ie]),fe=c.useMemo(()=>ie?Ne[ie.file_id]??null:null,[ie,Ne]),Fe=c.useMemo(()=>ie?J[ie.file_id]??null:null,[ie,J]),We=c.useMemo(()=>ie?I[ie.file_id]??null:null,[ie,I]),Me=j=>{const P=j(_.current);_.current=P,r(P)};c.useEffect(()=>{_.current=He},[He]),c.useEffect(()=>{Te.current=I},[I]),c.useEffect(()=>{const j=new Set(He.map(P=>P.file_id));O(P=>{const B={...P};for(const[Le,Je]of Object.entries(P))j.has(Le)||(URL.revokeObjectURL(Je),delete B[Le]);return B})},[He]),c.useEffect(()=>()=>{Object.values(Te.current).forEach(j=>{URL.revokeObjectURL(j)})},[]),c.useEffect(()=>{t&&(A.current=t)},[t]);const yt=()=>{const j=w.current;if(!j)return;const{scrollLeft:P,scrollWidth:B,clientWidth:Le}=j;ae(P>0),V(P<B-Le-4)},bt=()=>{w.current?.scrollBy({left:-280,behavior:"smooth"})},ct=()=>{w.current?.scrollBy({left:280,behavior:"smooth"})};c.useEffect(()=>{yt()},[n.length,Ae,ut.length]),c.useEffect(()=>{o||Z(!1)},[o]),c.useEffect(()=>{Se&&(He.some(j=>j.file_id===Se)||$e(null))},[Se,He]),c.useEffect(()=>{Se&&ne(!0)},[Se]);const qt=c.useCallback(async()=>{if(t)return t;if(A.current)return A.current;if(!f)return null;C.current||(C.current=f().finally(()=>{C.current=null}));const j=await C.current;return A.current=j,j},[f,t]),wt=j=>{if(j instanceof Error&&j.message)return j.message;if(typeof j=="string")return j;if(j&&typeof j=="object"){const P=j,B=P.response?.data?.detail||P.response?.data?.message;if(typeof B=="string"&&B.trim())return B}return"Upload failed"},jt=j=>{const P=j.type||"";if(P&&(P.startsWith("text/")||gh.has(P)))return!0;const B=qg(j.name);if(B&&Rk.has(B))return!0;const Le=ri(j.name);return!!(Le.startsWith("text/")||gh.has(Le))},Ye=async j=>{if(R.current.has(j.tempId))return;if(!e){M({type:"error",title:"Upload failed",description:"Open a project before uploading files."}),Me(B=>B.map(Le=>Le.file_id===j.tempId?{...Le,status:"failed",error:"No active project."}:Le));return}const P=await qt();if(!P){M({type:"error",title:"Upload failed",description:"Unable to create a session for uploads."}),Me(B=>B.map(Le=>Le.file_id===j.tempId?{...Le,status:"failed",error:"No active session."}:Le));return}Me(B=>B.map(Le=>Le.file_id===j.tempId?{...Le,status:"uploading",progress:typeof Le.progress=="number"?Le.progress:0,error:void 0,file_path:Le.file_path||Bl(P,Le.filename)}:Le));try{const B=await Y_({projectId:e,sessionId:P,file:j.file,onProgress:Le=>{R.current.has(j.tempId)||Me(Je=>Je.map(Re=>Re.file_id===j.tempId?{...Re,status:"uploading",progress:Math.max(0,Math.min(100,Le))}:Re))}});if(R.current.has(j.tempId))return;Me(Le=>Le.map(Je=>Je.file_id===j.tempId?{...Je,file_id:B.file_id,filename:B.name,content_type:B.mime??j.file.type,size:B.size??j.file.size,upload_date:new Date().toISOString(),status:"success",progress:100,file:null,error:void 0,file_path:Bl(P,B.name)}:Je))}catch(B){if(R.current.has(j.tempId))return;const Le=wt(B);console.error("[AiManus] Upload failed",B),Me(Je=>Je.map(Re=>Re.file_id===j.tempId?{...Re,status:"failed",error:Le}:Re))}},ft=()=>{for(;E.current<jk&&b.current.length>0;){const j=b.current.shift();if(!j)break;E.current+=1,Ye(j).finally(()=>{E.current=Math.max(0,E.current-1),ft()})}},St=c.useCallback(j=>{if(p||h||!j.length)return;let P=_.current.length,B=_.current.reduce((Re,Ft)=>Re+(Ft.size||0),0);const Le=t??A.current,Je=[];for(const Re of j){if(P>=xh){M({type:"warning",title:"Attachment limit reached",description:`You can attach up to ${xh} files per session.`});break}if(Re.size>Tk){M({type:"warning",title:"File too large",description:`Each file must be under ${Og} MB.`});continue}if(!jt(Re)){M({type:"warning",title:"Unsupported file type",description:"Allowed: text, JSON, PDF, PNG, JPEG, or WebP."});continue}if(B+Re.size>Ak){M({type:"warning",title:"Attachment quota reached",description:`Total attachments must stay under ${Bg} MB.`});continue}const Ft=`temp-${Date.now()}-${Math.random().toString(16).slice(2)}`,at=Re.type||ri(Re.name);Je.push({file_id:Ft,filename:Re.name,content_type:at,size:Re.size,upload_date:new Date().toISOString(),status:"queued",progress:0,file:Re,file_path:Le?Bl(Le,Re.name):void 0,include_in_context:Ik(Re.name,at,Re.size),metadata:{client_id:Ft}}),b.current.push({file:Re,tempId:Ft}),P+=1,B+=Re.size}Je.length>0&&(Me(Re=>[...Re,...Je]),ft())},[M,h,p,ft,t,Me]),Kt=c.useCallback(j=>{h||(R.current.add(j),b.current=b.current.filter(P=>P.tempId!==j),Me(P=>P.filter(B=>B.file_id!==j)))},[h,Me]);c.useImperativeHandle(g,()=>({openPicker:()=>{p||h||T.current?.click()},queueFiles:St,cancelAttachment:Kt}),[Kt,h,St,p]);const Gt=j=>{const P=Array.from(j.target.files??[]);St(P),j.target.value=""},he=j=>{Kt(j)},kt=c.useCallback(j=>{h||j.file&&(R.current.delete(j.file_id),Me(P=>P.map(B=>B.file_id===j.file_id?{...B,status:"queued",progress:0,error:void 0}:B)),b.current.push({file:j.file,tempId:j.file_id}),ft())},[h,ft,Me]),$t=c.useCallback((j,P)=>{h||Me(B=>B.map(Le=>Le.file_id===j?{...Le,include_in_context:P}:Le))},[h,Me]),ht=c.useCallback(j=>{$e(P=>P===j?null:j)},[]),an=c.useCallback(async j=>{const P=j.file_id;if(!P)return;const B=Ne[P];if(!(B&&(B.status==="loading"||B.status==="ready"))){G(Le=>({...Le,[P]:{status:"loading"}}));try{const Le=await Ab(P,{maxChars:Mu});G(Je=>({...Je,[P]:{status:"ready",content:Le.content,truncated:Le.truncated}}))}catch(Le){const Je=wt(Le);G(Re=>({...Re,[P]:{status:"error",error:Je}}))}}},[Ne]),At=c.useCallback(async j=>{if(j&&!Te.current[j])try{const P=await Cb(j);O(B=>({...B,[j]:P}))}catch(P){console.error("[AiManus] Failed to load image preview",P)}},[]);c.useEffect(()=>{!ie||ie.status!=="success"||(Ee==="text"&&an(ie),Ee==="image"&&At(ie.file_id))},[ie,Ee,At,an]);const fn=c.useCallback(async j=>{const P=j.file_id;if(P){$(B=>({...B,[P]:{...B[P]||{status:"idle"},status:"loading"}}));try{const B=await h_(P);if(B.status==="ready"){const Je=await x_(P,Mu);$(Re=>({...Re,[P]:{status:"ready",content:Je,truncated:Je.length>=Mu,pageCount:B.page_count,phase:B.phase,progress:B.progress}}));return}const Le=B.status==="processing"?"processing":"error";$(Je=>({...Je,[P]:{...Je[P]||{status:"idle"},status:Le,pageCount:B.page_count,phase:B.phase,progress:B.progress,error:B.error}}))}catch(B){const Le=wt(B);$(Je=>({...Je,[P]:{status:"error",error:Le}}))}}},[]),Ze=c.useCallback(async j=>{if(!j)return;const P=await mx(j);M({type:P?"success":"error",title:Oe(P?"copied_preview_title":"copy_failed_title"),description:Oe(P?"copied_preview_desc":"copy_failed_desc")})},[M,Oe]),ot=j=>{const P=j.split(".").pop();return P?P.toUpperCase():"FILE"};return He.length===0&&!Ae?s.jsx("input",{ref:T,type:"file",multiple:!0,accept:yh,className:"hidden",onChange:Gt}):s.jsxs("div",{className:z("relative w-full flex-shrink-0 overflow-hidden",U?"pb-2":"pb-3"),children:[He.length>0?s.jsxs("div",{className:z("px-3 pb-2 text-[10px] text-[var(--text-tertiary)]",U&&"px-2 text-[11px]"),children:["已附加 ",He.length," 个文件"]}):null,Q?s.jsx("button",{type:"button",onClick:bt,className:"absolute left-0 top-0 z-10 flex h-full items-center gap-2 px-3",style:{backgroundImage:"linear-gradient(270deg, var(--gradual-white-0) 0%, var(--fill-input-chat) 100%)"},children:s.jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded-full border border-[var(--border-white)] bg-[var(--background-menu-white)] shadow-[0_0_1.25px_0_var(--shadow-M),0_5px_16px_0_var(--shadow-M)]",children:s.jsx(Eb,{size:14})})}):null,s.jsx("div",{ref:w,onScroll:yt,className:"flex overflow-x-auto overflow-y-hidden pb-[10px] pl-[10px] pr-2 scrollbar-hide",children:s.jsxs("div",{className:"flex gap-3",children:[Ae?s.jsxs("div",{role:"button",tabIndex:0,onClick:()=>Z(j=>!j),onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),Z(P=>!P))},className:"group/attach relative flex w-[240px] max-w-full cursor-pointer items-center gap-2 rounded-[10px] bg-[var(--fill-tsp-white-main)] p-2 pr-2.5 transition hover:bg-[var(--fill-tsp-white-dark)] animate-in fade-in-0 zoom-in-95 duration-200",children:[s.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md",children:s.jsx(ud,{className:"h-4 w-4 text-[var(--icon-primary)]"})}),s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[s.jsx("div",{className:U?"flex-1 truncate text-[12px] text-[var(--text-primary)]":"flex-1 truncate text-[10px] text-[var(--text-primary)]",children:"Recent files"}),s.jsxs("div",{className:U?"text-[11px] text-[var(--text-tertiary)]":"text-[9px] text-[var(--text-tertiary)]",children:[ut.length," files"]})]}),s.jsxs("div",{className:"flex items-center gap-1",children:[W?s.jsx(wx,{size:14,className:"text-[var(--icon-tertiary)]"}):s.jsx(mi,{size:14,className:"text-[var(--icon-tertiary)]"}),u?s.jsx("button",{type:"button",onClick:j=>{j.stopPropagation(),u()},className:"hidden rounded-full bg-[var(--icon-tertiary)] p-[2px] text-white group-hover/attach:flex",children:s.jsx(fo,{size:10})}):null]})]}):null,He.map(j=>{const P=j.content_type||ri(j.filename),B=j.status==="queued",Le=j.status==="uploading",Je=j.status==="failed",Re=od(j.filename,j.content_type),Ft=_h(j.filename,j.content_type),at=vh(j.filename,j.content_type),Xt=j.status==="success"&&(Re||Ft||at),pt=Re||Ft,pn=Se===j.file_id,ln=typeof j.progress=="number"?j.progress:j.status==="success"?100:0,Pe=Math.max(0,Math.min(100,ln));return s.jsxs("div",{onClick:()=>{Xt&&ht(j.file_id)},className:z("group/attach relative flex w-[280px] max-w-full items-center gap-2 rounded-[10px] bg-[var(--fill-tsp-white-main)] p-2 pr-2.5 hover:bg-[var(--fill-tsp-white-dark)]",Xt?"cursor-pointer":"cursor-default",pn&&"border border-[var(--border-input-active)]"),children:[s.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-md",children:Le||B?s.jsx(dd,{className:z("h-4 w-4 text-[var(--icon-tertiary)]",Le&&"animate-spin")}):s.jsx(hx,{type:"file",mimeType:P,name:j.filename,className:"h-4 w-4"})}),s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[s.jsxs("div",{className:"flex min-w-0 items-center",children:[s.jsx("div",{className:U?"flex-1 truncate text-[12px] text-[var(--text-primary)]":"flex-1 truncate text-[10px] text-[var(--text-primary)]",children:j.filename}),s.jsx("button",{type:"button",onClick:te=>{te.stopPropagation(),he(j.file_id)},className:"hidden rounded-full bg-[var(--icon-tertiary)] p-[2px] text-white group-hover/attach:flex",children:s.jsx(fo,{size:10})})]}),!U||j.status!=="success"?s.jsxs("div",{className:U?"text-[11px] text-[var(--text-tertiary)]":"text-[9px] text-[var(--text-tertiary)]",children:[Je?s.jsxs("span",{className:"flex items-center gap-1 text-[var(--function-error)]",children:[s.jsx("span",{className:"truncate",title:j.error||"Upload failed",children:j.error||"Upload failed"}),s.jsxs("button",{type:"button",onClick:te=>{te.stopPropagation(),kt(j)},className:"flex items-center gap-1 rounded-full px-1 text-[var(--function-error)] hover:opacity-80",children:[s.jsx(Jv,{size:12}),s.jsx("span",{className:"text-[10px]",children:Oe("retry")})]})]}):Le?`Uploading ${Pe}% · ${ai(j.size)}`:B?`Queued · ${ai(j.size)}`:`${ot(j.filename)} · ${ai(j.size)}`,B||Le||Je?s.jsx("div",{className:"mt-1 h-1 w-full rounded-full bg-[var(--fill-tsp-gray-main)]",children:s.jsx("div",{className:z("h-1 rounded-full transition-[width] duration-200",Je?"bg-[var(--function-error)]":Le?"bg-[var(--fill-blue)]":"bg-[var(--fill-tsp-white-dark)]"),style:{width:`${Pe}%`}})}):null]}):null,pt?s.jsxs("label",{className:"mt-1 flex items-center gap-1 text-[9px] text-[var(--text-tertiary)]",onClick:te=>te.stopPropagation(),children:[s.jsx("input",{type:"checkbox",checked:!!j.include_in_context,onChange:te=>$t(j.file_id,te.target.checked),className:"h-3 w-3 rounded border border-[var(--border-light)] text-[var(--text-brand)]"}),s.jsx("span",{children:Oe("context")})]}):null]})]},j.file_id)})]})}),Ae&&W?s.jsxs("div",{className:z("mt-1 rounded-[10px] border border-[var(--border-light)] bg-[var(--fill-tsp-white-main)] px-3 py-2 text-[var(--text-secondary)] animate-in fade-in-0 slide-in-from-top-2 duration-200",U?"mx-2 text-[11px]":"mx-3 text-[10px]"),children:[s.jsx("div",{className:z("text-[var(--text-tertiary)]",U?"text-[11px]":"text-[10px]"),children:"Currently reading"}),s.jsx("div",{className:"mt-1 max-h-[120px] space-y-1 overflow-y-auto pr-1",children:ut.map(j=>{const P=bh(j),B=oe&&P===oe;return s.jsx("button",{type:"button",onClick:()=>d?.(j),disabled:!Ce,title:j,className:z("w-full text-left transition",U?"text-[11px]":"text-[10px]",Ce?"cursor-pointer text-[var(--text-secondary)] hover:text-[var(--text-primary)]":"cursor-default text-[var(--text-tertiary)]"),children:s.jsxs("span",{className:"flex min-w-0 items-center gap-1",children:[B?s.jsx(Rb,{size:12,className:"shrink-0 text-[var(--icon-primary)]"}):null,s.jsx("span",{className:"min-w-0 truncate",children:j})]})},j)})})]}):null,ie&&ie.status==="success"?s.jsxs("div",{className:z("mt-1 rounded-[10px] border border-[var(--border-light)] bg-[var(--fill-tsp-white-main)] px-3 py-2 text-[var(--text-secondary)] animate-in fade-in-0 slide-in-from-top-2 duration-200",U?"mx-2 text-[11px]":"mx-3 text-[10px]"),children:[(()=>{const j=ie.content_type||ri(ie.filename),P=ie.size?ai(ie.size):"",B=ie.filename.split(".").pop(),Le=B?B.toUpperCase():j;return s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[9px] text-[var(--text-tertiary)]",children:Oe("attachment_preview")}),s.jsx("div",{className:"truncate text-[11px] font-medium text-[var(--text-primary)]",children:ie.filename}),s.jsx("div",{className:"text-[9px] text-[var(--text-tertiary)]",children:[Le,P].filter(Boolean).join(" · ")})]}),s.jsx("button",{type:"button",onClick:()=>$e(null),className:"rounded-full bg-[var(--icon-tertiary)] p-[2px] text-white","aria-label":Oe("close_preview"),children:s.jsx(fo,{size:10})})]})})(),Ee==="text"?s.jsxs("div",{className:"mt-2 rounded-[8px] border border-[var(--border-light)] bg-[var(--background-white-main)] px-2 py-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("button",{type:"button",onClick:()=>ne(j=>!j),className:"flex items-center gap-2 text-[9px] text-[var(--text-tertiary)] hover:text-[var(--text-primary)]",children:[s.jsx(mi,{size:12,className:z("transition-transform",X&&"rotate-180")}),s.jsx("span",{children:Oe("text_preview")}),fe?.truncated?s.jsx("span",{className:"rounded-full bg-[var(--fill-tsp-gray-main)] px-2 py-0.5 text-[8px] text-[var(--text-tertiary)]",children:Oe("truncated")}):null]}),fe?.status==="ready"?s.jsxs("button",{type:"button",onClick:()=>Ze(fe.content||""),className:"flex items-center gap-1 rounded-full border border-[var(--border-light)] px-2 py-0.5 text-[8px] text-[var(--text-tertiary)] hover:text-[var(--text-primary)]",children:[s.jsx(Ib,{size:12}),Oe("copy")]}):null]}),X?s.jsx("div",{className:"mt-2 max-h-[160px] overflow-y-auto whitespace-pre-wrap text-[10px] text-[var(--text-primary)]",children:fe?.status==="loading"?s.jsx("span",{className:"text-[var(--text-tertiary)]",children:Oe("loading_preview")}):fe?.status==="error"?s.jsx("span",{className:"text-[var(--function-error)]",children:fe.error||Oe("preview_unavailable")}):fe?.content||s.jsx("span",{className:"text-[var(--text-tertiary)]",children:Oe("no_preview_available")})}):null]}):null,Ee==="image"?s.jsxs("div",{className:"mt-2 flex items-center gap-3",children:[We?s.jsx("button",{type:"button",onClick:()=>de(ie.file_id),className:"overflow-hidden rounded-[8px] border border-[var(--border-light)]",children:s.jsx("img",{src:We,alt:ie.filename,className:"h-[88px] w-[88px] object-cover"})}):s.jsx("span",{className:"text-[9px] text-[var(--text-tertiary)]",children:Oe("loading_image")}),s.jsx("div",{className:"text-[9px] text-[var(--text-tertiary)]",children:Oe("click_thumbnail_to_enlarge")}),s.jsx(fd,{open:ke===ie.file_id,onOpenChange:j=>de(j?ie.file_id:null),children:s.jsx(pd,{className:"max-w-[90vw]",children:We?s.jsx("img",{src:We,alt:ie.filename,className:"max-h-[80vh] w-auto"}):null})})]}):null,Ee==="pdf"?s.jsxs("div",{className:"mt-2 rounded-[8px] border border-[var(--border-light)] bg-[var(--background-white-main)] px-2 py-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"text-[9px] text-[var(--text-tertiary)]",children:["PDF preview",Fe?.pageCount?` · ${Fe.pageCount} pages`:""]}),s.jsx("button",{type:"button",onClick:()=>fn(ie),disabled:Fe?.status==="loading",className:"rounded-full border border-[var(--border-light)] px-2 py-0.5 text-[8px] text-[var(--text-tertiary)] hover:text-[var(--text-primary)] disabled:cursor-not-allowed disabled:opacity-60",children:"Extract text"})]}),s.jsx("div",{className:"mt-2 text-[9px] text-[var(--text-tertiary)]",children:Fe?.status==="loading"?"Requesting parser...":Fe?.status==="processing"?`Processing${Fe.progress!=null?` · ${Fe.progress}%`:""}`:Fe?.status==="error"?Fe.error||"PDF parse failed.":Fe?.content?"PDF text ready.":"Extract text to preview a snippet."}),Fe?.status==="ready"&&Fe.content?s.jsx("div",{className:"mt-2 max-h-[160px] overflow-y-auto whitespace-pre-wrap text-[10px] text-[var(--text-primary)]",children:Fe.content}):null]}):null,Ee==="unknown"?s.jsx("div",{className:"mt-2 text-[9px] text-[var(--text-tertiary)]",children:"Preview not available for this file type."}):null]}):null,ye?s.jsx("button",{type:"button",onClick:ct,className:"absolute right-0 top-0 z-10 flex h-full items-center gap-2 px-3",style:{backgroundImage:"linear-gradient(90deg, var(--gradual-white-0) 0%, var(--fill-input-chat) 100%)"},children:s.jsx("div",{className:"flex h-7 w-7 items-center justify-center rounded-full border border-[var(--border-white)] bg-[var(--background-menu-white)] shadow-[0_0_1.25px_0_var(--shadow-M),0_5px_16px_0_var(--shadow-M)]",children:s.jsx(Mb,{size:14})})}):null,s.jsx("input",{ref:T,type:"file",multiple:!0,accept:yh,className:"hidden",onChange:Gt})]})});Jd.displayName="ChatBoxFiles";const ga="application/x-ds-copilot-attachment";function Mk({value:e,onChange:t,onSubmit:n,onStop:r,isRunning:a,mentionables:i,mentionEnabled:o,includeDefaultAgent:u=!0,lockedPrefix:d,lockLeadingMentionSpace:f,attachments:p,onAttachmentsChange:h,attachmentsEnabled:y,recentFiles:g,recentFilesActivePath:T,recentFilesEnabled:w,onRecentFilesToggle:_,onRecentFilesRemove:b,onRecentFileOpen:E,showTerminalToggle:R,terminalActive:A,terminalLabel:C,onTerminalToggle:M,terminalToggleDisabled:U,recentFilesDisabled:Q,projectId:ae,sessionId:ye,ensureSession:V,readOnly:W,inputDisabled:Z,compact:Se,rows:$e=1,placeholder:Ne="Give DeepScientist a task to work on...",inputRef:G,containerClassName:J,panelClassName:$,inputClassName:I,onSessionAttachmentDrop:O}){const{t:X}=nr("ai_manus"),ne=!!Se,ke=!!(W||Z),de=o??!0,Te=y??!0,[Oe,He]=c.useState(!1),[ut,oe]=c.useState(!1),[Ae,Ce]=c.useState(!1),[ie,Ee]=c.useState(!1),fe=c.useRef(null),Fe=c.useRef(0),We=c.useRef(null),Me=c.useCallback(F=>{We.current=F,G&&(typeof G=="function"?G(F):"current"in G&&(G.current=F))},[G]),yt=c.useRef(null),bt=c.useRef(null),[ct,qt]=c.useState(""),[wt,jt]=c.useState(0),[Ye,ft]=c.useState(!1),[St,Kt]=c.useState(!1),Gt=c.useRef(null),he=c.useMemo(()=>{const F=typeof d=="string"?d.trim():"";return F?F.startsWith("@")?F:`@${F}`:null},[d]),kt=c.useMemo(()=>he?`${he} `:null,[he]),$t=kt?.length??0,ht=c.useMemo(()=>{if(!de)return[];const F=i??[];return u?Yd(F):F},[u,i,de]),an=c.useMemo(()=>{const F=new Set;return ht.forEach(le=>{if(le.label){const De=le.label.trim();De&&F.add(De.startsWith("@")?De:`@${De}`)}le.id&&F.add(`@${le.id}`)}),he&&F.add(he),Array.from(F).sort((le,De)=>De.length-le.length)},[ht,he]),At=c.useCallback(F=>{const le=F??"";if(!le.startsWith("@"))return null;const De=le.toLowerCase();for(const tt of an){const it=tt.toLowerCase();if(De.startsWith(it))return tt.length}const Qe=le.match(/^@([^\s]+)/);return Qe?Qe[0].length:null},[an]),fn=c.useCallback(F=>{const le=At(F);if(!le)return null;const De=F.slice(1,le).trim();return De?{token:De.toLowerCase(),end:le}:null},[At]);c.useEffect(()=>{oe(e.trim().length>0)},[e]),c.useEffect(()=>{de||(bt.current=null,ft(!1),qt(""))},[de]);const Ze=c.useCallback(F=>{if(!he||!kt)return F;const le=he,De=le.toLowerCase(),tt=(F??"").replace(/^\s+/,"");if(tt.toLowerCase().startsWith(De)){const wn=tt.slice(le.length);if(!wn)return kt;if(/^\s/.test(wn)){const Qn=wn.trimStart();return Qn?`${kt}${Qn}`:kt}}let it=tt;if(tt.startsWith("@")){const wn=tt.match(/^@([^\s]+)(?:\s+|$)/);wn&&(it=tt.slice(wn[0].length).trimStart())}return it?`${kt}${it}`:kt},[kt,he]);c.useEffect(()=>{if(!f){Gt.current=null;return}const F=fn(e);if(!F){Gt.current=null;return}Gt.current=F.token},[fn,f,e]);const ot=c.useCallback((F,le,De)=>{if(!f)return{value:F,selectionStart:le,selectionEnd:De,changed:!1};const Qe=At(F);if(!Qe)return{value:F,selectionStart:le,selectionEnd:De,changed:!1};if(F[Qe]===" ")return{value:F,selectionStart:le,selectionEnd:De,changed:!1};const tt=`${F.slice(0,Qe)} ${F.slice(Qe)}`,it=Qe,wn=le!=null&&le>=it?le+1:le,Qn=De!=null&&De>=it?De+1:De;return{value:tt,selectionStart:wn,selectionEnd:Qn,changed:!0}},[f,At]),j=c.useCallback((F,le,De)=>{const Qe=he?Ze(F):F,tt=ot(Qe,le,De);return{value:tt.value,selectionStart:tt.selectionStart,selectionEnd:tt.selectionEnd}},[ot,Ze,he]);c.useEffect(()=>{if(!he&&!f)return;const F=j(e).value;F!==e&&t(F)},[f,j,he,t,e]);const P=Te?p:[],B=c.useMemo(()=>P.filter(F=>F.status==="queued"||F.status==="uploading"),[P]),Le=B.length>0,Je=c.useMemo(()=>P.some(F=>F.status==="failed"),[P]),Re=B[0]??null,Ft=ut&&!ke&&!Je,at=!!(r&&!W),Xt=!!_,pt=!!w,pn=!!(ke||Q),ln=!!R,Pe=!!A,te=!!(ke||U),Yt=C||(Pe?"CLI Server":"Copilot"),Ct=Pe?"bg-[var(--ai-manus-input-runtime-bg)]":"bg-[var(--fill-input-chat)]",mt=z("w-full flex-1 resize-none rounded-md border-0 bg-transparent p-0 pt-[1px] focus-visible:outline-none focus-visible:ring-0 disabled:cursor-not-allowed disabled:opacity-50",ne?"min-h-[36px] text-[11px]":"min-h-[44px] text-[13px]",I),vt=c.useCallback((F,le)=>{if(!F.startsWith("@"))return null;const De=Math.max(0,Math.min(le,F.length)),Qe=F.search(/\s/),tt=Qe===-1?F.length:Qe;if(De>tt)return null;const it=F.slice(1,De);return/^[^\s]*$/.test(it)?{query:it,start:0,end:De}:null},[]),mn=c.useCallback(F=>{if(!F.startsWith("@"))return null;const le=F.search(/\s/);let Qe=le===-1?F.length:le;return F[Qe]===" "&&(Qe+=1),Math.min(Qe,F.length)},[]),Gn=c.useCallback((F,le)=>{const De=vt(F,le);if(!De){bt.current=null,ft(!1),qt("");return}bt.current={start:De.start,end:De.end},qt(De.query),jt(0),ft(!0)},[vt]),Cn=c.useMemo(()=>{if(!Ye)return[];const F=typeof ct=="string"?ct.toLowerCase():String(ct??"").toLowerCase();return ht.filter(le=>{const De=typeof le.id=="string"?le.id:le.id!=null?String(le.id):"",Qe=typeof le.label=="string"?le.label:le.label!=null?String(le.label):De?`@${De}`:"@agent",tt=De.toLowerCase(),it=Qe.toLowerCase();return tt.includes(F)||it.includes(F)})},[ht,Ye,ct]),sn=Ye&&Cn.length>0&&!ke&&de;c.useEffect(()=>{sn&&wt>=Cn.length&&jt(0)},[Cn.length,wt,sn]);const ys=c.useCallback(F=>{const le=bt.current;if(!le)return;const De=typeof F.label=="string"?F.label.trim():"",Qe=De?De.startsWith("@")?De:`@${De}`:`@${F.id}`,tt=e.slice(0,le.start),it=e.slice(le.end),wn=it.startsWith(" ")?"":" ",Qn=`${tt}${Qe}${wn}${it}`;t(Qn),ft(!1),qt(""),bt.current=null,requestAnimationFrame(()=>{if(!We.current)return;const On=tt.length+Qe.length+wn.length;We.current.setSelectionRange(On,On),We.current.focus()})},[t,e]),Dn=c.useCallback((F,le,De)=>{const Qe=j(F,le,De);t(Qe.value),(Qe.selectionStart!=null||Qe.selectionEnd!=null)&&(Qe.selectionStart!==le||Qe.selectionEnd!==De)&&requestAnimationFrame(()=>{if(!We.current)return;const tt=Qe.selectionStart??le,it=Qe.selectionEnd??tt;We.current.setSelectionRange(tt,it)}),!(ke||!de)&&Gn(Qe.value,Qe.selectionStart??le)},[ke,de,j,t,Gn]),Be=c.useCallback(F=>{yt.current&&(yt.current.scrollTop=F.currentTarget.scrollTop)},[]),Wt=c.useMemo(()=>{const F=e||"",le=F.length>0?F:Ne,De=[];if(F.length>0&&de){const Qe=F.match(/^@[^\s]+/);if(Qe){const tt=Qe[0];De.push(s.jsx("span",{className:"ai-manus-mention",children:tt},"mention-leading")),tt.length<F.length&&De.push(F.slice(tt.length))}else De.push(le)}else De.push(le);return le.endsWith("\\n")&&De.push("\\n"),{nodes:De,isPlaceholder:F.length===0}},[de,Ne,e]),zt=F=>{F.key!=="Enter"||F.shiftKey||Oe||Ft&&(F.preventDefault(),k())},we=F=>{if(he&&We.current){const le=$t||he.length,De=We.current.selectionStart??0,Qe=We.current.selectionEnd??De;if((De<le||De===le&&F.key==="Backspace")&&(F.key==="Backspace"||F.key==="Delete")){F.preventDefault(),requestAnimationFrame(()=>{We.current?.setSelectionRange(le,le)});return}De<le&&De!==Qe&&requestAnimationFrame(()=>{We.current?.setSelectionRange(le,le)})}if((F.metaKey||F.ctrlKey)&&F.key==="Enter"){if(Oe||!Ft)return;F.preventDefault(),k();return}if(F.key==="Backspace"&&de&&We.current){const le=We.current.selectionStart??0,De=We.current.selectionEnd??le;if(le===De){const Qe=mn(e);if(Qe&&le>0&&le<=Qe){F.preventDefault();const tt=e.slice(Qe);t(tt),bt.current=null,ft(!1),qt(""),requestAnimationFrame(()=>{We.current&&We.current.setSelectionRange(0,0)});return}}}if(sn){if(F.key==="ArrowDown"){F.preventDefault(),jt(le=>(le+1)%Cn.length);return}if(F.key==="ArrowUp"){F.preventDefault(),jt(le=>le-1<0?Cn.length-1:le-1);return}if(F.key==="Enter"||F.key==="Tab"){F.preventDefault();const le=Cn[wt];le&&ys(le);return}if(F.key==="Escape"){F.preventDefault(),ft(!1);return}}zt(F)},k=()=>{if(Ft){if(Le){Ee(!0);return}n()}},se=()=>{at&&r?.()},me=()=>{!Te||ke||fe.current?.openPicker()},Nt=()=>{Re&&(fe.current?.cancelAttachment?fe.current.cancelAttachment(Re.file_id):h(P.filter(F=>F.file_id!==Re.file_id)),Ee(!1))},xe=F=>Array.from(F.dataTransfer?.types??[]).includes("Files"),lt=F=>Array.from(F.dataTransfer?.types??[]).includes(ga),Mt=F=>{if(lt(F)&&O){Kt(!0);return}!Te||ke||xe(F)&&(Fe.current+=1,Ce(!0))},En=F=>{if(lt(F)&&O){F.preventDefault(),F.dataTransfer.dropEffect="copy",Kt(!0);return}!Te||ke||xe(F)&&(F.preventDefault(),F.dataTransfer.dropEffect="copy")},Mn=F=>{if(lt(F)&&O){const le=F.relatedTarget;if(le&&F.currentTarget.contains(le))return;Kt(!1);return}!Te||ke||xe(F)&&(Fe.current=Math.max(0,Fe.current-1),Fe.current===0&&Ce(!1))},Is=F=>{if(lt(F)&&O){const De=F.dataTransfer?.getData(ga);if(!De)return;F.preventDefault(),Kt(!1),O(De);return}if(!Te||ke||!xe(F))return;F.preventDefault(),Fe.current=0,Ce(!1);const le=Array.from(F.dataTransfer?.files??[]);le.length>0&&fe.current?.queueFiles(le)},en=F=>{if(!Te||ke)return;const De=Array.from(F.clipboardData?.items??[]).filter(it=>it.type.startsWith("image/")).map(it=>it.getAsFile()).filter(it=>!!it);if(De.length===0)return;const Qe=new Date().toISOString().replace(/[:.]/g,"-"),tt=De.map((it,wn)=>{const Qn=it.type.split("/")[1]||"png",On=`pasted-${Qe}-${wn+1}.${Qn}`,Ms=it.name&&it.name!=="image.png"?it.name:On;return it.name===Ms?it:new File([it],Ms,{type:it.type})});fe.current?.queueFiles(tt),F.preventDefault()};return s.jsxs("div",{className:z("relative bg-transparent",ne?"pb-1":"pb-3",J),children:[s.jsxs("div",{className:z("relative flex max-h-[320px] flex-col rounded-[12px] border border-[var(--border-light)] shadow-[0px_0px_1px_0px_var(--shadow-XS),0px_12px_28px_-20px_var(--shadow-S)] focus-within:border-[var(--border-input-active)] focus-within:ring-1 focus-within:ring-[var(--border-input-active)] transition-colors duration-200",Ct,ne?"gap-1.5 py-1.5":"gap-3 py-3",Ae&&"border-[var(--border-input-active)] ring-2 ring-[var(--border-input-active)]",St&&"border-[var(--border-input-active)] ring-2 ring-[var(--border-input-active)]",$),onDragEnter:Mt,onDragOver:En,onDragLeave:Mn,onDrop:Is,onPasteCapture:en,children:[Te||Xt||pt?s.jsx(Jd,{ref:fe,projectId:ae,sessionId:ye,attachments:P,onAttachmentsChange:h,recentFiles:g,activeRecentFile:T,showRecentFiles:pt,onRecentFilesRemove:b,onRecentFileOpen:E,ensureSession:V,readOnly:W,inputDisabled:Z,compact:ne}):null,s.jsxs("div",{className:z("relative pr-2",ne?"pl-3":"pl-4"),children:[sn?s.jsx("div",{className:"ai-manus-mention-popover absolute bottom-full left-0 z-20 mb-2 max-h-56 overflow-auto rounded-[14px]",children:Cn.map((F,le)=>{const De=le===wt,Qe=F.label?.trim()||`@${F.id}`;return s.jsx("button",{type:"button",onClick:()=>ys(F),className:z("ai-manus-mention-option flex w-full items-center gap-3 px-3 py-2 text-left text-[12px]",De&&"ai-manus-mention-option-active"),children:s.jsxs("span",{className:"flex flex-col",children:[s.jsx("span",{className:"text-[12px] font-semibold text-[var(--text-mention)]",children:Qe}),F.description?s.jsx("span",{className:"text-[10px] text-[var(--text-tertiary)]",children:F.description}):null]})},F.id)})}):null,s.jsxs("div",{className:"relative overflow-y-auto",children:[s.jsx("div",{ref:yt,"aria-hidden":!0,className:z("pointer-events-none absolute inset-0 overflow-hidden whitespace-pre-wrap break-words",Wt.isPlaceholder?"text-[var(--text-disable)]":"text-[var(--text-primary)]"),children:s.jsx("div",{className:z(mt,"whitespace-pre-wrap break-words"),children:Wt.nodes})}),s.jsx("textarea",{ref:Me,className:z(mt,"text-transparent caret-[var(--text-primary)] placeholder:text-transparent"),style:{color:"transparent",WebkitTextFillColor:"transparent"},rows:$e,value:e,onChange:F=>Dn(F.target.value,F.target.selectionStart??F.target.value.length,F.target.selectionEnd??F.target.selectionStart??F.target.value.length),onSelect:F=>de?Gn(F.currentTarget.value,F.currentTarget.selectionStart??F.currentTarget.value.length):void 0,onCompositionStart:()=>He(!0),onCompositionEnd:()=>He(!1),onKeyDown:we,onScroll:Be,placeholder:Ne,disabled:ke})]})]}),s.jsxs("footer",{className:z("flex w-full flex-row justify-between",ne?"px-2":"px-3"),children:[s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2 pr-2",children:[Te?s.jsx("button",{type:"button",onClick:me,disabled:ke,className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-[var(--border-main)] text-[11px] text-[var(--text-secondary)] hover:bg-[var(--fill-tsp-gray-main)] disabled:cursor-not-allowed disabled:opacity-60",children:s.jsx(Sx,{size:16})}):null,Xt?s.jsx("button",{type:"button",onClick:()=>_?.(),disabled:pn,"aria-pressed":pt,className:z("inline-flex h-8 w-8 items-center justify-center rounded-full border border-[var(--border-main)] text-[11px] text-[var(--text-secondary)] transition disabled:cursor-not-allowed disabled:opacity-60",pt?"bg-[var(--fill-tsp-gray-main)] text-[var(--text-primary)]":"hover:bg-[var(--fill-tsp-gray-main)]"),title:X("recent_files"),children:s.jsx(ud,{size:16})}):null,ln?s.jsxs("button",{type:"button",onClick:()=>M?.(),disabled:te,"aria-pressed":Pe,className:z("inline-flex h-8 min-w-0 max-w-[200px] items-center gap-2 rounded-full border px-3 text-[10px] font-semibold transition",Pe?"border-[var(--border-input-active)] bg-[var(--fill-blue)] text-[var(--text-primary)]":"border-[var(--border-main)] text-[var(--text-tertiary)] hover:bg-[var(--fill-tsp-gray-main)]",te&&"cursor-not-allowed opacity-60"),title:Yt,"aria-label":Yt,children:[s.jsx("span",{className:z("h-1.5 w-1.5 rounded-full",Pe?"bg-[var(--text-primary)]":"bg-[var(--text-tertiary)]")}),s.jsx("span",{className:"min-w-0 truncate",children:Yt})]}):null]}),s.jsxs("div",{className:"flex shrink-0 gap-2",children:[a?s.jsx("button",{type:"button",onClick:se,disabled:!at,"aria-label":X("pause"),title:X("pause"),className:at?"flex h-8 w-8 items-center justify-center rounded-full bg-[var(--Button-primary-black)] text-[var(--text-onblack)]":"flex h-8 w-8 cursor-not-allowed items-center justify-center rounded-full bg-[var(--fill-tsp-white-dark)] text-[var(--text-tertiary)]",children:s.jsx("span",{className:"h-[10px] w-[10px] rounded-[2px] bg-[var(--icon-onblack)]"})}):null,s.jsx("button",{type:"button",onClick:k,className:Ft?"flex h-8 w-8 items-center justify-center rounded-full bg-[var(--Button-primary-black)] text-[var(--text-onblack)] transition hover:opacity-90":"flex h-8 w-8 cursor-not-allowed items-center justify-center rounded-full bg-[var(--fill-tsp-white-dark)] text-[var(--text-tertiary)]",children:s.jsx(kx,{size:17})})]})]})]}),s.jsx(xx,{open:ie,onClose:()=>Ee(!1),onConfirm:Nt,title:"仍有文件上传中",description:Re?`还有 ${B.length} 个文件上传中,当前上传:${Re.filename}。`:"仍有文件上传中,请等待上传完成或取消该文件。",confirmText:"取消该文件",cancelText:"等待",variant:"warning"})]})}const Lk={type:"doc",content:[{type:"paragraph"}]};function Pk({value:e,onChange:t,onSubmit:n,onStop:r,isRunning:a,attachments:i,onAttachmentsChange:o,attachmentsEnabled:u,recentFiles:d,recentFilesActivePath:f,recentFilesEnabled:p,onRecentFilesToggle:h,onRecentFilesRemove:y,onRecentFileOpen:g,showTerminalToggle:T,terminalActive:w,terminalLabel:_,onTerminalToggle:b,terminalToggleDisabled:E,recentFilesDisabled:R,projectId:A,sessionId:C,ensureSession:M,readOnly:U,inputDisabled:Q,compact:ae,placeholder:ye="Draft a response...",containerClassName:V,panelClassName:W,inputClassName:Z,focusRef:Se,onSessionAttachmentDrop:$e}){const{t:Ne}=nr("ai_manus"),G=!!ae,J=!!(U||Q),$=u??!0,I=$?i:[],[O,X]=c.useState(!1),[ne,ke]=c.useState(!1),[de,Te]=c.useState(!1),Oe=c.useMemo(()=>I.filter(j=>j.status==="queued"||j.status==="uploading"),[I]),He=Oe.length>0,ut=c.useMemo(()=>I.some(j=>j.status==="failed"),[I]),oe=Oe[0]??null,Ce=e.trim().length>0&&!J&&!ut,ie=!!(r&&!U),Ee=!!h,fe=!!p,Fe=!!(J||R),We=!!T,Me=!!w,yt=!!(J||E),bt=_||(Me?"CLI Server":"Copilot"),ct=Me?"bg-[var(--ai-manus-input-runtime-bg)]":"bg-[var(--fill-input-chat)]",qt=c.useRef(null),wt=c.useRef(null),jt=c.useRef(!1),Ye=c.useRef(0),ft=c.useMemo(()=>{const j=wv.configure({placeholder:ye,includeChildren:!0}),P=Sv.filter(B=>B.name!=="placeholder");return[j,...P]},[ye]);c.useEffect(()=>{if(Se)return Se.current=()=>wt.current?.commands?.focus?.(),()=>{Se.current=null}},[Se]),c.useEffect(()=>{wt.current&&wt.current.setEditable(!J)},[J]),c.useEffect(()=>{if(!wt.current)return;const j=e||"";nm(wt.current).trim()!==j.trim()&&(jt.current=!0,sm(wt.current,j))},[e]);const St=c.useCallback(j=>{if(jt.current){jt.current=!1;return}const P=nm(j);t(P)},[t]),Kt=c.useCallback(()=>{if(Ce){if(He){Te(!0);return}n()}},[He,n,Ce]),Gt=c.useCallback(()=>{ie&&r?.()},[r,ie]),he=c.useCallback(j=>!Ce||J?!1:(j.metaKey||j.ctrlKey)&&j.key==="Enter"?(j.preventDefault(),Kt(),!0):!1,[Kt,J,Ce]),kt=c.useCallback(()=>{!$||J||qt.current?.openPicker()},[$,J]),$t=c.useCallback(()=>{oe&&(qt.current?.cancelAttachment?qt.current.cancelAttachment(oe.file_id):o(I.filter(j=>j.file_id!==oe.file_id)),Te(!1))},[I,o,oe]),ht=j=>Array.from(j.dataTransfer?.types??[]).includes("Files"),an=j=>{if(Array.from(j.dataTransfer?.types??[]).includes(ga)){$e&&ke(!0);return}!$||J||ht(j)&&(Ye.current+=1,X(!0))},At=j=>{if(Array.from(j.dataTransfer?.types??[]).includes(ga)){$e&&(j.preventDefault(),j.dataTransfer.dropEffect="copy",ke(!0));return}!$||J||ht(j)&&(j.preventDefault(),j.dataTransfer.dropEffect="copy")},fn=j=>{if(Array.from(j.dataTransfer?.types??[]).includes(ga)){if(!$e)return;const P=j.relatedTarget;if(P&&j.currentTarget.contains(P))return;ke(!1);return}!$||J||ht(j)&&(Ye.current=Math.max(0,Ye.current-1),Ye.current===0&&X(!1))},Ze=j=>{if(Array.from(j.dataTransfer?.types??[]).includes(ga)){if(!$e)return;const B=j.dataTransfer?.getData(ga);if(!B)return;j.preventDefault(),ke(!1),$e(B);return}if(!$||J||!ht(j))return;j.preventDefault(),Ye.current=0,X(!1);const P=Array.from(j.dataTransfer?.files??[]);P.length>0&&qt.current?.queueFiles(P)},ot=j=>{if(!$||J)return;const B=Array.from(j.clipboardData?.items??[]).filter(Re=>Re.type.startsWith("image/")).map(Re=>Re.getAsFile()).filter(Re=>!!Re);if(B.length===0)return;const Le=new Date().toISOString().replace(/[:.]/g,"-"),Je=B.map((Re,Ft)=>{const at=Re.type.split("/")[1]||"png",Xt=`pasted-${Le}-${Ft+1}.${at}`,pt=Re.name&&Re.name!=="image.png"?Re.name:Xt;return Re.name===pt?Re:new File([Re],pt,{type:Re.type})});qt.current?.queueFiles(Je),j.preventDefault()};return s.jsxs("div",{className:z("relative bg-transparent",G?"pb-1":"pb-3",V),children:[s.jsxs("div",{className:z("relative flex max-h-[320px] flex-col rounded-[12px] border border-[var(--border-light)] shadow-[0px_0px_1px_0px_var(--shadow-XS),0px_12px_28px_-20px_var(--shadow-S)] focus-within:border-[var(--border-input-active)] focus-within:ring-1 focus-within:ring-[var(--border-input-active)] transition-colors duration-200",ct,G?"gap-1.5 py-1.5":"gap-3 py-3",O&&"border-[var(--border-input-active)] ring-2 ring-[var(--border-input-active)]",ne&&"border-[var(--border-input-active)] ring-2 ring-[var(--border-input-active)]",W),onDragEnter:an,onDragOver:At,onDragLeave:fn,onDrop:Ze,onPasteCapture:ot,children:[$||Ee||fe?s.jsx(Jd,{ref:qt,projectId:A,sessionId:C,attachments:I,onAttachmentsChange:o,recentFiles:d,activeRecentFile:f,showRecentFiles:fe,onRecentFilesRemove:y,onRecentFileOpen:g,ensureSession:M,readOnly:U,inputDisabled:Q,compact:G}):null,s.jsx("div",{className:z("relative pr-2",G?"pl-3":"pl-4"),children:s.jsx("div",{className:"relative overflow-y-auto",children:s.jsx("div",{className:z("notebook-editor-container",Z),children:s.jsx(kv,{children:s.jsx(Nv,{extensions:ft,className:z("notebook-doc-editor relative w-full overflow-y-auto",G?"max-h-[180px]":"max-h-[240px]"),editorProps:{handleDOMEvents:{keydown:(j,P)=>he(P)},attributes:{class:z("prose prose-sm max-w-full font-default focus:outline-none",G?"text-[12px]":"text-[13px]"),style:"padding: 0; min-height: 44px;"}},onCreate:({editor:j})=>{wt.current=j,e.trim()?sm(j,e):j.commands.setContent(Lk),j.setEditable(!J)},onUpdate:({editor:j})=>St(j)})})})})}),s.jsxs("footer",{className:z("flex w-full flex-row justify-between",G?"px-2":"px-3"),children:[s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2 pr-2",children:[$?s.jsx("button",{type:"button",onClick:kt,disabled:J,className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-[var(--border-main)] text-[11px] text-[var(--text-secondary)] hover:bg-[var(--fill-tsp-gray-main)] disabled:cursor-not-allowed disabled:opacity-60",children:s.jsx(Sx,{size:16})}):null,Ee?s.jsx("button",{type:"button",onClick:()=>h?.(),disabled:Fe,"aria-pressed":fe,className:z("inline-flex h-8 w-8 items-center justify-center rounded-full border border-[var(--border-main)] text-[11px] text-[var(--text-secondary)] transition disabled:cursor-not-allowed disabled:opacity-60",fe?"bg-[var(--fill-tsp-gray-main)] text-[var(--text-primary)]":"hover:bg-[var(--fill-tsp-gray-main)]"),title:Ne("recent_files"),children:s.jsx(ud,{size:16})}):null,We?s.jsxs("button",{type:"button",onClick:()=>b?.(),disabled:yt,"aria-pressed":Me,className:z("inline-flex h-8 min-w-0 max-w-[200px] items-center gap-2 rounded-full border px-3 text-[10px] font-semibold transition",Me?"border-[var(--border-input-active)] bg-[var(--fill-blue)] text-[var(--text-primary)]":"border-[var(--border-main)] text-[var(--text-tertiary)] hover:bg-[var(--fill-tsp-gray-main)]",yt&&"cursor-not-allowed opacity-60"),title:bt,"aria-label":bt,children:[s.jsx("span",{className:z("h-1.5 w-1.5 rounded-full",Me?"bg-[var(--text-primary)]":"bg-[var(--text-tertiary)]")}),s.jsx("span",{className:"min-w-0 truncate",children:bt})]}):null]}),s.jsxs("div",{className:"flex shrink-0 gap-2",children:[a?s.jsx("button",{type:"button",onClick:Gt,disabled:!ie,"aria-label":Ne("pause"),title:Ne("pause"),className:ie?"flex h-8 w-8 items-center justify-center rounded-full bg-[var(--Button-primary-black)] text-[var(--text-onblack)]":"flex h-8 w-8 cursor-not-allowed items-center justify-center rounded-full bg-[var(--fill-tsp-white-dark)] text-[var(--text-tertiary)]",children:s.jsx("span",{className:"h-[10px] w-[10px] rounded-[2px] bg-[var(--icon-onblack)]"})}):null,s.jsx("button",{type:"button",onClick:Kt,className:Ce?"flex h-8 w-8 items-center justify-center rounded-full bg-[var(--Button-primary-black)] text-[var(--text-onblack)] transition hover:opacity-90":"flex h-8 w-8 cursor-not-allowed items-center justify-center rounded-full bg-[var(--fill-tsp-white-dark)] text-[var(--text-tertiary)]",children:s.jsx(kx,{size:17})})]})]})]}),s.jsx(xx,{open:de,onClose:()=>Te(!1),onConfirm:$t,title:"仍有文件上传中",description:oe?`还有 ${Oe.length} 个文件上传中,当前上传:${oe.filename}。`:"仍有文件上传中,请等待上传完成或取消该文件。",confirmText:"取消该文件",cancelText:"等待",variant:"warning"})]})}function oc({text:e,compact:t}){const n=!!t;return s.jsxs("div",{className:"flex items-center gap-1 text-[10px] text-[var(--text-tertiary)]",children:[e?s.jsx("span",{children:e}):null,s.jsx("span",{className:"relative top-[4px] flex gap-1",children:[0,1,2].map(r=>s.jsx("span",{className:"h-[3px] w-[3px] rounded bg-[var(--icon-tertiary)] animate-bounce-dot",style:{animationDelay:`${r*200}ms`}},r))})]})}const Dk=new Set(["a","e","i","o","u"]),wh={summary:"detail_final_report_section_summary",strengths:"detail_final_report_section_strengths",weaknesses:"detail_final_report_section_weaknesses",key_issues:"detail_final_report_section_key_issues",actionable_suggestions:"detail_final_report_section_actionable_suggestions",storyline_options_writing_outlines:"detail_final_report_section_storyline_options_writing_outlines",priority_revision_plan:"detail_final_report_section_priority_revision_plan",experiment_inventory_research_experiment_plan:"detail_final_report_section_experiment_inventory_research_experiment_plan",novelty_verification_related_work_matrix:"detail_final_report_section_novelty_verification_related_work_matrix",scores:"detail_final_report_section_scores",overview_revision_strategy:"detail_final_report_section_overview_revision_strategy",point_to_point_triage_table:"detail_final_report_section_point_to_point_triage_table",evidence_mapping_table:"detail_final_report_section_evidence_mapping_table",draft_responses_to_reviewers:"detail_final_report_section_draft_responses_to_reviewers",manuscript_revision_suggestions:"detail_final_report_section_manuscript_revision_suggestions",optional_experiment_plans:"detail_final_report_section_optional_experiment_plans",unresolved_items_risk_notes:"detail_final_report_section_unresolved_items_risk_notes",references:"detail_final_report_section_references"};function ld(e){return!e||typeof e!="object"||Array.isArray(e)?{}:e}function zn(e){return typeof e=="string"?e:""}function ao(e,t){if(typeof e=="string"){const o=e.trim().toLowerCase();if(!o)return null;const u=wh[o];return u?t(u,void 0,e):e.trim()}const n=ld(e),r=zn(n.id)||"",a=r.trim().toLowerCase();if(a){const o=wh[a];if(o)return t(o,void 0,zn(n.title)||a)}const i=zn(n.title);return i||r||null}function $k(e){if(!e)return null;const t=e.replace(/\s+/g," ");return t?t.length<=220?t:`${t.slice(0,217).trimEnd()}...`:null}const Fk=e=>{const t=e.trim().toLowerCase();return t?t.startsWith("ds_system_")?!0:t.includes("__ds_system_"):!1},zk=e=>{const t=e.trim();if(!t)return{verb:"",rest:""};const[n,...r]=t.split(/\s+/);return{verb:n,rest:r.join(" ")}},Ok=e=>{if(!e)return e;const t=e.toLowerCase();if(!t.endsWith("ing"))return e;const n=t.slice(0,-3);if(!n)return e;let r="";if(n.endsWith("y")){const a=n[n.length-2];a&&!Dk.has(a)?r=`${n.slice(0,-1)}ied`:r=`${n}ed`}else r=`${n}ed`;return e[0]===e[0].toUpperCase()&&(r=r.charAt(0).toUpperCase()+r.slice(1)),r};function Sh({tool:e,onClick:t,compact:n,collapsible:r,projectId:a}){const i=yr(e.function||""),o=typeof e.metadata?.surface=="string"&&e.metadata.surface.startsWith("lab-");return(i==="lab_quests"||i==="lab_pi_sleep"||i==="lab_baseline"||i==="write_memory")&&o?s.jsx(Mg,{tool:e,compact:n,projectId:a}):s.jsx(Bk,{tool:e,onClick:t,compact:n,collapsible:r,projectId:a})}function Bk({tool:e,onClick:t,compact:n,collapsible:r,projectId:a}){const i=c.useMemo(()=>Qd(e),[e]),o=c.useMemo(()=>$g(e),[e]),{t:u}=nr("workspace"),d=i.icon,f=!!n,[p,h]=c.useState(!1),y=ve=>{if(typeof ve!="number"||!Number.isFinite(ve)||ve<=0)return"";if(ve<1e3)return`${Math.round(ve)}ms`;const Ie=ve/1e3;if(Ie>=60){const rn=Math.floor(Ie/60),Ut=Math.round(Ie%60);return`${rn}m${Ut.toString().padStart(2,"0")}s`}const Pt=Ie>=10?0:1;return`${Ie.toFixed(Pt)}s`},g=(ve,Ie=1800)=>{if(ve==null)return"";try{return uo(oi(JSON.stringify(ve,null,2)),Ie)}catch{return uo(oi(String(ve)),Ie)}},T=ve=>{if(ve==null)return"";if(typeof ve=="string")return ve;try{return JSON.stringify(ve,null,2)}catch{return String(ve)}},w=(ve,Ie=40)=>{if(ve.length===0)return"";const Pt=ve.slice(0,Ie),rn=ve.length>Ie?`
199
+ ... (${ve.length-Ie} more)`:"";return Pt.join(`
200
+ `)+rn},_=e.args&&typeof e.args=="object"&&!Array.isArray(e.args)?e.args:{},b=e.content,E=b?.result,R=E&&typeof E=="object"?typeof E.status=="string"?String(E.status):"":typeof b?.status=="string"?String(b.status):"";typeof b?.success=="boolean"&&b.success,typeof b?.error=="string"&&b.error.trim().length>0,R.trim().length>0&&["ok","success","completed"].includes(R.trim().toLowerCase());const A="text-[var(--ds-morandi-red)]",C=y(e.duration_ms),M=i.category==="shell"||i.category==="bash"||i.category==="search"||i.category==="paper_search"||i.category==="file"||i.category==="mcp",U=e.function==="mcp_status_update"?typeof _.message=="string"?_.message:typeof _.text=="string"?_.text:"":"",Q=Gr(U),ae=e.function==="mcp_status_update"?_.todo??_.next:void 0,V=(Array.isArray(ae)?ae:typeof ae=="string"?[ae]:[]).map(ve=>Gr(String(ve)).trim()).filter(Boolean).join(" / "),W=V?`TODO: ${V}`:"",Z=i.category==="file",Se=e.function==="mcp_status_update"?"Status":i.name,$e=e.function==="mcp_status_update"&&Q?Q:i.function,Ne=Z?o:Se,G=Z?i.function:$e,J=Fk(e.function||""),$=c.useMemo(()=>{if(!J||!G)return null;const{verb:ve,rest:Ie}=zk(G);if(!ve||!/ing$/i.test(ve))return null;const Pt=Ok(ve);return!Pt||Pt===ve?null:{verbIng:ve,verbEd:Pt,rest:Ie}},[G,J]),[I,O]=c.useState(!1),X=c.useRef(null),ne=!!$&&e.status==="called"&&X.current==="calling";c.useEffect(()=>{if(!$)return;const ve=e.status;ve&&(ne?O(!0):ve==="calling"&&O(!1),X.current=ve)},[ne,e.status,$]);const ke=!!$&&(I||ne),de=$?e.status==="called"?$.verbEd:$.verbIng:"",Te=$?ke?s.jsx(Lb,{texts:[$.verbIng,$.verbEd],auto:!0,loop:!1,rotationInterval:1200,staggerFrom:"last",staggerDuration:.02,initial:{y:"90%",opacity:0},animate:{y:0,opacity:1},exit:{y:"-120%",opacity:0},animatePresenceInitial:!0,maxWords:14,mainClassName:"ds-copilot-status-text",splitLevelClassName:"ds-copilot-status-text-split",elementLevelClassName:"ds-copilot-status-text-element",style:{color:"inherit",fontWeight:"inherit"}}):de:G,Oe=$?s.jsxs(s.Fragment,{children:[Te,$.rest?` ${$.rest}`:""]}):G,He=typeof e.error=="string"&&e.error.trim().length>0?e.error:typeof b?.error=="string"&&b.error.trim().length>0?b.error:"",ut=He?uo(oi(He),240):"",oe=Object.keys(_).length===0?"":g(_),Ae=(()=>{if(!b)return"";const ve=b?.result??b;return typeof ve=="object"&&ve&&!Array.isArray(ve)&&Object.keys(ve).length===0?"":g(ve)})(),Ce=r!==!1&&!!(oe||Ae||ut),ie=p&&Ce,Ee=ve=>{ve.preventDefault(),ve.stopPropagation(),Ce&&h(Ie=>!Ie)},fe=e.status==="calling"?s.jsx(oc,{text:"Running",compact:f}):C?s.jsx("span",{className:`text-[10px] ${A}`,children:C}):null,Fe=s.jsx("div",{onClick:Ce?Ee:void 0,className:z("mt-1 inline-flex min-w-0 max-w-full items-center gap-2 text-[10px] text-[var(--ds-morandi-red)]",Ce&&"cursor-pointer text-left transition hover:text-[var(--ds-morandi-red-strong)]"),"aria-label":Ce?p?"Hide details":"Show details":void 0,"aria-expanded":Ce?ie:void 0,children:fe}),We=ie?s.jsxs("div",{className:"ai-manus-tool-details mt-2 rounded-[10px] border border-[var(--border-light)] bg-[var(--fill-tsp-white-light)] p-2",children:[ut?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--soft-danger)]",children:"Error"}),s.jsx("pre",{className:"ai-manus-tool-detail-body",children:ut})]}):null,oe?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Args"}),s.jsx("pre",{className:"ai-manus-tool-detail-body",children:oe})]}):null,Ae?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Result"}),s.jsx("pre",{className:"ai-manus-tool-detail-body",children:Ae})]}):null]}):null,Me=yr(e.function),yt=Me==="read_file",bt=Me==="append_file",ct=Me==="write_task_plan",qt=Me==="pull_file",wt=Me==="list_file",jt=Me==="list_dir",Ye=Me==="grep_text",ft=Me==="grep_files",St=Me==="glob_files",Kt=Me==="write_memory",Gt=Me==="request_patch",he=Me==="bash_exec",kt=yt||bt||ct||qt||wt||jt||Ye||ft||St||Kt||Gt||he,$t=!ct&&(yt||bt||qt||wt||jt||Ye||ft||St||Kt||Gt||he),ht=$t&&r!==!1,an=wo(_),At=an||"a file",fn=an||"Unknown file",Ze=typeof _.reason=="string"?_.reason:"",ot=T(_.content),j=b?.result,P=j&&typeof j=="object"&&!Array.isArray(j)?j:null,B=zx(P??j)||He,Le=$x(j??b),Je=Le.text,Re=Le.message,Ft=(()=>{if(!P)return"";const ve=P.message;return typeof ve=="string"?ve:""})(),at=Re||He,Xt=Ft||He,pt=ht&&!fe?s.jsx("span",{className:"text-[10px] text-[var(--text-tertiary)]",children:"Details"}):null,pn=typeof j=="string"?j:P&&typeof P.content=="string"?P.content:"",ln=Xl(j??b),Pe=ln.items,te=w(Pe.map(ve=>{if(!ve||typeof ve!="object")return String(ve);const Ie=ve,Pt=typeof Ie.path=="string"?Ie.path:typeof Ie.name=="string"?Ie.name:"Unknown",rn=typeof Ie.type=="string"?Ie.type:"",Ut=typeof Ie.size=="number"?`${Ie.size}b`:"",Xn=[rn,Ut].filter(Boolean).join(" · ");return Xn?`${Pt} (${Xn})`:Pt})),Yt=ln.content,Ct=ln.truncated,mt=typeof _.query=="string"?_.query:P&&typeof P.query=="string"?P.query:"",vt=Array.isArray(P?.matches)?P?.matches:[],mn=P&&typeof P.content=="string"?P.content:typeof j=="string"?j:"",Gn=w(mn?mn.split(/\r?\n/).filter(Boolean):[]),Cn=w(vt.map(ve=>{if(!ve||typeof ve!="object")return String(ve);const Ie=ve,Pt=typeof Ie.file_path=="string"?Ie.file_path:"Unknown",rn=typeof Ie.line=="number"?Ie.line:void 0,Ut=typeof Ie.text=="string"?Ie.text:"",Xn=rn?`${Pt}:${rn}`:Pt;return Ut?`${Xn} ${Ut}`:Xn})),sn=w(vt.map(ve=>{if(!ve||typeof ve!="object")return String(ve);const Ie=ve,Pt=typeof Ie.path=="string"?Ie.path:typeof Ie.file_path=="string"?Ie.file_path:"Unknown",rn=typeof Ie.score=="number"||typeof Ie.score=="string"?String(Ie.score):"",Ut=rn?`score ${rn}`:"",Xn=typeof Ie.size=="number"?`${Ie.size}b`:"",Ns=[Ut,Xn].filter(Boolean).join(" · ");return Ns?`${Pt} (${Ns})`:Pt})),ys=!!P?.truncated,Dn=typeof _.pattern=="string"?_.pattern:P&&typeof P.pattern=="string"?P.pattern:"",Be=typeof _.title=="string"?_.title:"",Wt=typeof _.kind=="string"?_.kind:P&&typeof P.kind=="string"?P.kind:"",zt=Array.isArray(_.tags)?_.tags.map(ve=>String(ve)):[],we=typeof _.confidence=="number"?_.confidence:void 0,k=P&&typeof P.id=="string"?P.id:"",se=P&&typeof P.path=="string"?P.path:"",me=P&&typeof P.index_path=="string"?P.index_path:"",Nt=Array.isArray(P?.warnings)?(P?.warnings).map(ve=>String(ve)):[],xe=Array.isArray(P?.errors)?(P?.errors).map(ve=>String(ve)):[],lt=typeof _.target_path=="string"?_.target_path:an||"Unknown target",Mt=typeof _.rationale=="string"?_.rationale:"",En=typeof _.patch=="string"?_.patch:"",Mn=Array.isArray(_.evidence_refs)?_.evidence_refs.map(ve=>String(ve)):[],Is=Array.isArray(P?.applied)?(P?.applied).map(ve=>String(ve)):[],en=w(Is),F=typeof _.command=="string"?_.command:typeof _.cmd=="string"?_.cmd:"",le=typeof _.workdir=="string"?_.workdir:"",De=typeof _.mode=="string"?_.mode:"",Qe=typeof _.timeout_seconds=="number"?`${_.timeout_seconds}s`:typeof _.timeout=="number"?`${_.timeout}ms`:"",tt=p&&ht,it=ve=>{ve.preventDefault(),ve.stopPropagation(),ht&&h(Ie=>!Ie)},wn=ve=>{ve.preventDefault(),ve.stopPropagation(),ht&&(h(Ie=>!Ie),t&&t())},Qn=tt?s.jsxs("div",{className:"ai-manus-tool-details mt-2 rounded-[10px] border border-[var(--border-light)] bg-[var(--fill-tsp-white-light)] p-2",children:[yt||bt||qt||wt||jt?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Title"}),s.jsx("div",{className:"mt-1 text-[11px] text-[var(--text-secondary)]",children:fn})]}):null,Ye?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Query"}),s.jsx("div",{className:"mt-1 text-[11px] text-[var(--text-secondary)]",children:mt||"—"})]}):null,St||ft?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Pattern"}),s.jsx("div",{className:"mt-1 text-[11px] text-[var(--text-secondary)]",children:Dn||"—"})]}):null,Kt?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Memory title"}),s.jsx("div",{className:"mt-1 text-[11px] text-[var(--text-secondary)]",children:Be||"—"})]}):null,he?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Command"}),s.jsx("pre",{className:"ai-manus-tool-detail-body",children:F||"—"})]}):null,he&&le?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Workdir"}),s.jsx("div",{className:"mt-1 text-[11px] text-[var(--text-secondary)]",children:le})]}):null,he&&De?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Mode"}),s.jsx("div",{className:"mt-1 text-[11px] text-[var(--text-secondary)]",children:De})]}):null,he&&Qe?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Timeout"}),s.jsx("div",{className:"mt-1 text-[11px] text-[var(--text-secondary)]",children:Qe})]}):null,Gt?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Target path"}),s.jsx("div",{className:"mt-1 text-[11px] text-[var(--text-secondary)]",children:lt})]}):null,yt?at?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--soft-danger)]",children:"Error"}),s.jsx("pre",{className:"ai-manus-tool-detail-body text-[var(--soft-danger)]",children:at})]}):s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Content"}),s.jsx("pre",{className:"ai-manus-tool-detail-body",children:Je})]}):null,bt?s.jsxs(s.Fragment,{children:[Xt?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--soft-danger)]",children:"Error"}),s.jsx("pre",{className:"ai-manus-tool-detail-body text-[var(--soft-danger)]",children:Xt})]}):null,s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Reason"}),s.jsx("pre",{className:"ai-manus-tool-detail-body",children:Ze})]}),s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Content"}),s.jsx("pre",{className:"ai-manus-tool-detail-body",children:ot})]})]}):null,qt?B?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--soft-danger)]",children:"Error"}),s.jsx("pre",{className:"ai-manus-tool-detail-body text-[var(--soft-danger)]",children:B})]}):s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Content"}),s.jsx("pre",{className:"ai-manus-tool-detail-body",children:pn})]}):null,wt||jt?s.jsxs(s.Fragment,{children:[B?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--soft-danger)]",children:"Error"}),s.jsx("pre",{className:"ai-manus-tool-detail-body text-[var(--soft-danger)]",children:B})]}):null,s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Items"}),s.jsx("pre",{className:"ai-manus-tool-detail-body",children:Yt||te||"No items returned."})]}),Ct?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Truncated"}),s.jsx("div",{className:"mt-1 text-[11px] text-[var(--text-secondary)]",children:"Yes"})]}):null]}):null,Ye||ft||St?s.jsxs(s.Fragment,{children:[B?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--soft-danger)]",children:"Error"}),s.jsx("pre",{className:"ai-manus-tool-detail-body text-[var(--soft-danger)]",children:B})]}):null,s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Matches"}),s.jsx("pre",{className:"ai-manus-tool-detail-body",children:(Ye?Cn:ft?Gn:sn)||"No matches returned."})]}),ys?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Truncated"}),s.jsx("div",{className:"mt-1 text-[11px] text-[var(--text-secondary)]",children:"Yes"})]}):null]}):null,Kt?s.jsxs(s.Fragment,{children:[B?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--soft-danger)]",children:"Error"}),s.jsx("pre",{className:"ai-manus-tool-detail-body text-[var(--soft-danger)]",children:B})]}):null,Wt?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Kind"}),s.jsx("div",{className:"mt-1 text-[11px] text-[var(--text-secondary)]",children:Wt})]}):null,zt.length>0?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Tags"}),s.jsx("pre",{className:"ai-manus-tool-detail-body",children:zt.join(", ")})]}):null,we!=null?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Confidence"}),s.jsx("div",{className:"mt-1 text-[11px] text-[var(--text-secondary)]",children:we})]}):null,k?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Memory ID"}),s.jsx("div",{className:"mt-1 text-[11px] text-[var(--text-secondary)]",children:k})]}):null,se?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Path"}),s.jsx("div",{className:"mt-1 text-[11px] text-[var(--text-secondary)]",children:se})]}):null,me?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Index path"}),s.jsx("div",{className:"mt-1 text-[11px] text-[var(--text-secondary)]",children:me})]}):null,Nt.length>0?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Warnings"}),s.jsx("pre",{className:"ai-manus-tool-detail-body",children:Nt.join(", ")})]}):null,xe.length>0?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--soft-danger)]",children:"Errors"}),s.jsx("pre",{className:"ai-manus-tool-detail-body text-[var(--soft-danger)]",children:xe.join(", ")})]}):null]}):null,Gt?s.jsxs(s.Fragment,{children:[B?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--soft-danger)]",children:"Error"}),s.jsx("pre",{className:"ai-manus-tool-detail-body text-[var(--soft-danger)]",children:B})]}):null,Mt?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Rationale"}),s.jsx("pre",{className:"ai-manus-tool-detail-body",children:Mt})]}):null,En?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Patch"}),s.jsx(Cg,{patch:En,showHeader:!1,compact:!0,className:"mt-1"})]}):null,Mn.length>0?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Evidence refs"}),s.jsx("pre",{className:"ai-manus-tool-detail-body",children:Mn.join(", ")})]}):null,en?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--text-tertiary)]",children:"Applied"}),s.jsx("pre",{className:"ai-manus-tool-detail-body",children:en})]}):null]}):null,he&&B?s.jsxs("div",{className:"ai-manus-tool-detail",children:[s.jsx("div",{className:"ai-manus-tool-detail-label text-[10px] text-[var(--soft-danger)]",children:"Error"}),s.jsx("pre",{className:"ai-manus-tool-detail-body text-[var(--soft-danger)]",children:B})]}):null]}):null,On=yt?`DeepScientist is reading ${At}...`:bt?`DeepScientist is writing ${At}`:qt?`DeepScientist is pulling ${At}...`:wt||jt?`DeepScientist is listing ${At}...`:Ye?`DeepScientist is grepping for "${mt||"..."}"...`:ft?`DeepScientist is finding files for "${Dn||"..."}"...`:St?`DeepScientist is matching files for "${Dn||"..."}"...`:Kt?`DeepScientist is saving memory "${Be||"Untitled"}"...`:Gt?`DeepScientist is applying a patch to ${lt}...`:he?"DeepScientist is executing a bash command...":"DeepScientist is planning...",Ms=bt?Ze:he?F:"",lc=s.jsxs("div",{onClick:ht?it:void 0,className:z("mt-1 inline-flex min-w-0 max-w-full items-center gap-2 text-[10px] text-[var(--text-tertiary)]",ht&&"cursor-pointer text-left transition hover:text-[var(--text-secondary)]"),"aria-label":ht?p?"Hide details":"Show details":void 0,"aria-expanded":ht?tt:void 0,children:[fe,pt]}),Ro=String(e.function||"").trim().toLowerCase(),ja=String(e.name||"").trim().toLowerCase(),gi=Ro==="review_final_markdown_write"||ja==="review_final_markdown_write"||Ro==="rebuttal_final_markdown_write"||ja==="rebuttal_final_markdown_write",Ls=c.useMemo(()=>{if(!gi)return null;const ve=String(e.status||"").trim().toLowerCase(),Ie=ld(b),Pt=ld(Ie.result),rn=Object.keys(Pt).length>0?Pt:Ie,Ut=String(zn(rn.status)||zn(Ie.status)||"").trim().toLowerCase(),Xn=String(zn(rn.reason)||zn(Ie.reason)||"").trim().toLowerCase(),Ns=rn.retry_required===!0||Ie.retry_required===!0,js=ao(rn.current_section,u)||ao(Ie.current_section,u)||ao(zn(_.section_id)||zn(_.section),u),yn=ao(rn.next_required_section,u)||ao(Ie.next_required_section,u),Ta=(Array.isArray(rn.missing_sections)?rn.missing_sections:Array.isArray(Ie.missing_sections)?Ie.missing_sections:[]).length,bs=$k(zn(rn.message)||zn(Ie.message)||zn(rn.details)||zn(Ie.details)||zn(rn.error)||zn(Ie.error)||(typeof Ie.result=="string"?String(Ie.result):""));return ve==="calling"?{headline:js?u("detail_final_report_tool_writing_section",{section:js}):u("detail_final_report_tool_writing_generic"),detail:null,tone:"active"}:["ok","success","completed"].includes(Ut)?{headline:u("detail_final_report_tool_completed"),detail:bs,tone:"success"}:Ut==="partial"||Xn==="required_sections_missing"?{headline:yn?u("detail_final_report_tool_partial_next",{section:yn}):Ta>0?u("detail_final_report_tool_partial_generic"):u("detail_final_report_tool_writing_generic"),detail:bs,tone:"active"}:Ut==="error"||Ns||(zn(rn.error)||zn(Ie.error))?{headline:u(Xn==="paper_search_calls_not_met"||Xn==="paper_search_distinct_queries_not_met"?"detail_final_report_tool_gate_paper_search":Xn==="annotation_count_not_met"?"detail_final_report_tool_gate_annotation":"detail_final_report_tool_retry_required"),detail:bs,tone:"warning"}:bs?{headline:bs,detail:null,tone:"active"}:{headline:js?u("detail_final_report_tool_writing_section",{section:js}):u("detail_final_report_tool_writing_generic"),detail:null,tone:"active"}},[gi,u,e.status,_.section,_.section_id,b]);if(kt){const ve=z("ai-manus-tool-chip flex w-full items-start gap-2 rounded-[12px] border border-[var(--border-light)] px-3 py-2 text-left",f?"text-[10px]":"text-[11px]",$t?"bg-[var(--fill-tsp-white-light)] text-[var(--text-secondary)] transition hover:bg-[var(--fill-tsp-gray-dark)]":"bg-[var(--fill-tsp-white-light)] text-[var(--text-secondary)]"),Ie=s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mt-[2px] inline-flex h-4 w-4 items-center justify-center text-[var(--icon-primary)]",children:s.jsx(d,{className:"h-4 w-4"})}),s.jsxs("span",{className:"min-w-0 flex-1 break-words",children:[s.jsx("span",{className:z("block break-words font-medium text-[var(--text-secondary)]",f?"text-[10px]":"text-[11px]"),children:On}),Ms?s.jsx("span",{className:z("mt-0.5 block break-words text-[var(--text-tertiary)]",f?"text-[9px]":"text-[10px]"),children:Ms}):null]}),$t?s.jsx(mi,{size:14,className:z("mt-0.5 text-[var(--icon-tertiary)] transition-transform",p&&"rotate-180")}):null]});return s.jsxs("div",{className:"group flex items-start gap-2","data-tool-status":e.status==="calling"?"calling":void 0,children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[ht?s.jsx("div",{onClick:wn,className:z(ve,"cursor-pointer"),"aria-label":p?"Hide details":"Show details","aria-expanded":tt,children:Ie}):s.jsx("div",{className:z(ve,"cursor-default"),children:Ie}),lc,Qn]}),f?null:s.jsx("div",{className:"text-[9px] text-[var(--text-tertiary)] opacity-0 transition group-hover:opacity-100",children:Nr(e.timestamp)})]})}if(Ls){const ve=z("ai-manus-tool-chip flex w-full items-start gap-2 rounded-[12px] border px-3 py-2 text-left",f?"text-[10px]":"text-[11px]",Ls.tone==="warning"?"border-[#B86B77]/35 bg-[#B86B77]/10 text-[#8D4C58]":Ls.tone==="success"?"border-[#4F6B5A]/35 bg-[#4F6B5A]/10 text-[#4F6B5A]":"border-[var(--border-light)] bg-[var(--fill-tsp-white-light)] text-[var(--text-secondary)]");return s.jsxs("div",{className:"group flex items-start gap-2","data-tool-status":e.status==="calling"?"calling":void 0,children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:ve,children:[s.jsx("span",{className:"mt-[2px] inline-flex h-4 w-4 items-center justify-center text-[currentColor]",children:s.jsx(d,{className:"h-4 w-4"})}),s.jsxs("span",{className:"min-w-0 flex-1 break-words",children:[s.jsx("span",{className:z("block break-words font-medium",f?"text-[10px]":"text-[11px]"),children:Ls.headline}),Ls.detail?s.jsx("span",{className:z("mt-0.5 block break-words opacity-90",f?"text-[9px]":"text-[10px]"),children:Ls.detail}):null]})]}),Fe,We]}),f?null:s.jsx("div",{className:"text-[9px] text-[var(--text-tertiary)] opacity-0 transition group-hover:opacity-100",children:Nr(e.timestamp)})]})}if(e.name==="message"&&typeof e.args?.text=="string"){const ve=Gr(e.args.text);return s.jsx("p",{className:"text-[11px] text-[var(--text-secondary)]",children:ve})}return M?s.jsxs("div",{className:"group flex items-start gap-2","data-tool-status":e.status==="calling"?"calling":void 0,children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("button",{type:"button",onClick:t,className:"ai-manus-tool-chip inline-flex max-w-full items-center gap-2 rounded-[10px] border border-[var(--border-light)] bg-[var(--fill-tsp-white-light)] px-[10px] py-[3px] text-[11px] text-[var(--text-secondary)] hover:bg-[var(--fill-tsp-gray-dark)]",children:[s.jsx("span",{className:"inline-flex w-[16px] items-center text-[var(--text-primary)]",children:s.jsx(d,{className:"h-4 w-4"})}),s.jsxs("span",{className:"flex min-w-0 items-center gap-1",children:[Z?s.jsxs("span",{className:"truncate text-[10px]",children:[o," ",i.function]}):s.jsx("span",{className:"truncate text-[10px]",children:i.function}),i.functionArg?s.jsx("code",{className:f?"truncate rounded-[6px] bg-[var(--fill-tsp-gray-main)] px-1 text-[10px] text-[var(--text-tertiary)]":"truncate rounded-[6px] bg-[var(--fill-tsp-gray-main)] px-1 text-[9px] text-[var(--text-tertiary)]",children:i.functionArg}):null]})]}),Fe,We]}),f?null:s.jsx("div",{className:"text-[9px] text-[var(--text-tertiary)] opacity-0 transition group-hover:opacity-100",children:Nr(e.timestamp)})]}):s.jsx("div",{className:"group flex items-start gap-2","data-tool-status":e.status==="calling"?"calling":void 0,children:s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:f?"ai-manus-tool-chip inline-flex max-w-full items-center gap-2 text-[10px] text-[var(--text-tertiary)]":"ai-manus-tool-chip inline-flex max-w-full items-center gap-2 text-[11px] text-[var(--text-tertiary)]",children:[s.jsx("span",{className:Z?"shrink-0 text-[9px] font-semibold text-[var(--text-secondary)]":"shrink-0 text-[9px] uppercase tracking-wide text-[var(--text-disable)]",children:Ne}),s.jsx("span",{className:e.function==="mcp_status_update"?"min-w-0 break-words":"min-w-0 truncate",children:Oe})]}),W?s.jsx("div",{className:"mt-1 break-words text-[10px] text-[var(--text-tertiary)]",children:W}):null,Fe,We]})})}function qk({content:e,onFileClick:t,compact:n}){if(!e.attachments.length)return null;const r=!!n;return s.jsxs("div",{className:"mt-3 flex flex-col gap-2",children:[r?null:s.jsx("div",{className:"text-[9px] font-medium text-[var(--text-tertiary)]",children:"Attachments"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:e.attachments.map(a=>{const i=a.content_type||ri(a.filename),o=a.status??"success",u=a.filename.split(".").pop(),d=u?u.toUpperCase():i.split("/").pop()?.toUpperCase(),f=a.size?ai(a.size):"",p=typeof a.progress=="number"?a.progress:o==="success"?100:0,h=Math.max(0,Math.min(100,p)),y=o==="failed"?a.error?`Upload failed · ${a.error}`:"Upload failed":o==="uploading"?`Uploading${typeof a.progress=="number"?` ${Math.round(h)}%`:"..."}`:o==="queued"?"Queued":[d,f].filter(Boolean).join(" · ");return s.jsxs("button",{type:"button",onClick:()=>t?.(a.file_id),className:r?"flex min-w-[min(200px,100%)] items-center gap-2 rounded-[10px] border border-[var(--border-light)] bg-[var(--fill-tsp-white-main)] px-3 py-2 text-left text-[11px] text-[var(--text-primary)] hover:bg-[var(--fill-tsp-white-dark)]":"flex min-w-[min(200px,100%)] items-center gap-2 rounded-[10px] border border-[var(--border-light)] bg-[var(--fill-tsp-white-main)] px-3 py-2 text-left text-[9px] text-[var(--text-primary)] hover:bg-[var(--fill-tsp-white-dark)]",children:[s.jsx(hx,{type:"file",mimeType:i,name:a.filename,className:"h-4 w-4"}),s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[s.jsx("span",{className:r?"truncate text-[11px] font-medium":"truncate text-[9px] font-medium",children:a.filename}),s.jsx("span",{className:z(r?"text-[10px]":"text-[8px]",o==="failed"?"text-[var(--function-error)]":"text-[var(--text-tertiary)]"),children:y}),o!=="success"?s.jsx("div",{className:"mt-1 h-1 w-full rounded-full bg-[var(--fill-tsp-gray-main)]",children:s.jsx("div",{className:z("h-1 rounded-full transition-[width] duration-200",o==="failed"?"bg-[var(--function-error)]":o==="uploading"?"bg-[var(--fill-blue)]":"bg-[var(--fill-tsp-white-dark)]"),style:{width:`${h}%`}})}):null]})]},a.file_id)})})]})}function Uk({toolCallId:e,args:t,status:n,answers:r,error:a,compact:i,submitLabel:o,submittingLabel:u,onSubmit:d}){const f=t,p=c.useMemo(()=>Ig(f),[f]),h=String(f.description||"").trim(),y=c.useMemo(()=>h?xo(h):"",[h]),g=c.useMemo(()=>{const fe={};return p.forEach(Fe=>{Fe.description&&(fe[Fe.id]=xo(Fe.description))}),fe},[p]),T=c.useMemo(()=>{const fe=qS(f,p);return US(fe,p)},[f,p]),w=T.choices,_=T.freeText,b=T.freeTextActive,E=n==="called"&&!a,R=n==="calling"&&!a&&!!d,A=!!i,C=o?.trim()||"Next",M=u?.trim()||"Submitting...",U=z("prose max-w-none text-[var(--text-tertiary)] [&_p]:my-1 [&_ul]:my-1 [&_ol]:my-1",A?"prose-sm text-[11px] [&_p]:text-[11px] [&_li]:text-[11px]":"prose-sm text-[12px] [&_p]:text-[12px] [&_li]:text-[12px]"),[Q,ae]=c.useState(w),[ye,V]=c.useState(_),[W,Z]=c.useState(b),[Se,$e]=c.useState(0),[Ne,G]=c.useState(!1);if(c.useEffect(()=>{ae(w),V(_),Z(b),$e(0),G(!1)},[w,_,b,e]),a)return null;const $=String(f.title||"").trim()||"User Request",I=p.length>0,O=p[Se],X=!!(O?.multiple&&O.allowFreeText),ne=p.some(fe=>fe.multiple)?"Multiple Choice":"Single Choice",ke=O?ch(O,Q,ye,W):!1,de=!O||Se>=p.length-1,Te=de?C:"Next",Oe=de?M:"Submitting...",He=(fe,Fe)=>{R&&(fe.allowFreeText&&!fe.multiple&&Z(We=>We[fe.id]?{...We,[fe.id]:!1}:We),ae(We=>{const Me={...We};if(fe.multiple){const yt=Array.isArray(Me[fe.id])?Me[fe.id]:[];Me[fe.id]=yt.includes(Fe)?yt.filter(bt=>bt!==Fe):[...yt,Fe]}else Me[fe.id]===Fe?delete Me[fe.id]:Me[fe.id]=Fe;return Me}))},ut=fe=>{R&&(Z(Fe=>({...Fe,[fe.id]:!0})),fe.multiple||ae(Fe=>{if(!(fe.id in Fe))return Fe;const We={...Fe};return delete We[fe.id],We}))},oe=(fe,Fe)=>{R&&(ut(fe),V(We=>({...We,[fe.id]:Fe})))},Ae=()=>{!R||Ne||Se<=0||$e(Se-1)},Ce=async()=>{if(!R||Ne)return;const fe=Se+1;if(fe<p.length){$e(fe);return}G(!0);try{await d?.(uh(Q,p,ye,W))}finally{G(!1)}},ie=async()=>{if(!R||Ne||!O||!ch(O,Q,ye,W))return;const fe=Se+1;if(fe<p.length){$e(fe);return}G(!0);try{await d?.(uh(Q,p,ye,W))}finally{G(!1)}},Ee=()=>s.jsx("div",{className:"mt-4 space-y-3",children:p.map(fe=>{const Fe=WS(fe,r?.[fe.id]);return s.jsxs("div",{className:"rounded-[16px] border border-[var(--border-light)] bg-[var(--fill-tsp-white-light)] px-4 py-3",children:[s.jsx("div",{className:z("font-medium text-[var(--text-primary)]","text-[12px]"),dangerouslySetInnerHTML:{__html:Vr(fe.text)}}),g[fe.id]?s.jsx("div",{className:z("mt-1",U),dangerouslySetInnerHTML:{__html:g[fe.id]}}):null,s.jsx("div",{className:"mt-2 flex flex-col gap-2",children:Fe.length>0?Fe.map(We=>s.jsx("span",{className:z("w-full rounded-[12px] border border-[var(--border-input-active)] bg-[var(--fill-blue)] px-3 py-2 font-medium text-[var(--text-primary)]","text-[11px]","whitespace-normal break-words"),dangerouslySetInnerHTML:{__html:Vr(We)}},`${fe.id}-${We}`)):s.jsx("span",{className:z("text-[var(--text-tertiary)]","text-[11px]"),children:"(no answer)"})})]},fe.id)})});return s.jsx("div",{className:"ai-manus-question-prompt w-full",children:s.jsxs("div",{className:z("ai-manus-question-prompt__card rounded-[22px] border border-[var(--border-light)] bg-[var(--background-white-main)]",A?"px-4 py-4":"px-6 py-5"),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2 text-[var(--text-secondary)]",children:[s.jsxs("span",{className:z("truncate","text-[12px]"),children:["Considering ",s.jsx("span",{className:"text-[var(--text-brand)]",children:$})]}),s.jsx(jo,{size:14,className:"shrink-0 text-[var(--text-brand)]"})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:z("rounded-full bg-[var(--fill-tsp-white-light)] px-3 py-1 text-[var(--text-secondary)]","text-[11px]"),children:ne}),R?s.jsx("button",{type:"button",onClick:Ce,className:z("text-[var(--text-tertiary)] hover:text-[var(--text-primary)]","text-[11px]"),children:"Skip"}):null]})]}),y?s.jsx("div",{className:z("mt-2",U),dangerouslySetInnerHTML:{__html:y}}):null,!I&&!a?s.jsx("div",{className:z("mt-3 text-[var(--text-tertiary)]","text-[12px]"),children:"No selectable options were provided."}):null,I&&!E?s.jsxs("div",{className:"mt-4",children:[s.jsx("div",{className:z("font-medium text-[var(--text-primary)]",A?"text-[15px]":"text-[16px]"),dangerouslySetInnerHTML:{__html:Vr(O?.text??"")}}),O&&g[O.id]?s.jsx("div",{className:z("mt-1",U),dangerouslySetInnerHTML:{__html:g[O.id]}}):null,O?s.jsxs("div",{className:"mt-4 flex flex-col gap-3",children:[O.options.map((fe,Fe)=>{const We=O.multiple?Array.isArray(Q[O.id])&&Q[O.id].includes(Fe):Q[O.id]===Fe;return s.jsx("button",{type:"button",onClick:Me=>{Me.target?.closest("a")||He(O,Fe)},disabled:!R,className:z("w-full rounded-[14px] border px-4 py-3 text-left leading-relaxed transition-all",We?"border-[var(--border-input-active)] bg-[var(--fill-blue)] text-[var(--text-primary)]":"border-[var(--border-dark)] text-[var(--text-secondary)] hover:bg-[var(--fill-tsp-white-light)]",!R&&"opacity-60","text-[12px]","whitespace-normal break-words"),"aria-pressed":We,children:s.jsx("span",{dangerouslySetInnerHTML:{__html:Vr(fe.label)}})},`${O.id}-${fe.value}`)}),O.allowFreeText?s.jsxs("div",{className:"w-full",children:[s.jsx("textarea",{value:ye[O.id]??"",onFocus:()=>ut(O),onChange:fe=>oe(O,fe.target.value),placeholder:X?"Add a custom answer (kept with selections)":"Add a custom answer",disabled:!R,rows:2,className:z("w-full resize-none break-words rounded-[14px] border bg-[var(--fill-tsp-white-light)] px-4 py-2 text-[12px] text-[var(--text-primary)] outline-none transition-colors",W[O.id]?"border-[var(--border-input-gold)]":"border-[var(--border-dark)]",!R&&"opacity-60"),"aria-label":"Custom answer"}),X?s.jsx("div",{className:"mt-2 text-[11px] text-[var(--text-tertiary)]",children:"Custom answer will be sent together with selected options."}):null]}):null]}):null,s.jsxs("div",{className:"mt-5 flex items-center justify-end gap-3",children:[Se>0?s.jsx("button",{type:"button",onClick:Ae,disabled:!R||Ne,className:z("mr-auto text-[var(--text-tertiary)] transition-colors hover:text-[var(--text-primary)]","text-[11px]",(!R||Ne)&&"opacity-60"),children:"Back"}):null,s.jsx("button",{type:"button",onClick:ie,disabled:!R||Ne||!ke,className:z("rounded-full px-6 py-2 font-semibold transition-all","text-[12px]",!R||Ne||!ke?"bg-[var(--fill-tsp-gray-dark)] text-[var(--text-tertiary)]":"bg-[var(--Button-primary-black)] text-[var(--text-onblack)] hover:brightness-110"),children:Ne?Oe:Te})]})]}):null,E?Ee():null]})})}const Wk=[];function Hk(e,t){return e&&e.length>0?e:t&&t.length>0?t:Wk}function Vk(e,t){if(t.length===0)return[];const n=new Map(e.map(r=>[r.id,r.label]));return t.map(r=>n.get(r)).filter(r=>!!r)}function Kk({question:e,options:t,multi:n,status:r,defaultSelected:a,selections:i,missingFields:o,error:u,compact:d,onSubmit:f}){const p=!!d,h=r==="calling"&&!u&&!!f,y=r!=="calling",g=c.useMemo(()=>Hk(i,a),[a,i]),T=g.join("|"),[w,_]=c.useState(g),[b,E]=c.useState(!1);if(c.useEffect(()=>{_(g),E(!1)},[T,e]),u)return null;const R=n?"Multiple Choice":"Single Choice",A=w.length>0,C=Vk(t,i??w),M=(o??[]).filter(Boolean).join(", "),U=ae=>{h&&_(ye=>n?ye.includes(ae)?ye.filter(V=>V!==ae):[...ye,ae]:ye[0]===ae?[]:[ae])},Q=async()=>{if(!h||b||!A)return;E(!0);const ae=n?w:w.slice(0,1);try{await f?.(ae)}finally{E(!1)}};return s.jsx("div",{className:"ai-manus-question-prompt ai-manus-clarify-question w-full",children:s.jsxs("div",{className:z("ai-manus-question-prompt__card rounded-[22px] border border-[var(--border-light)] bg-[var(--background-white-main)]",p?"px-4 py-4":"px-6 py-5"),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2 text-[var(--text-secondary)]",children:[s.jsx("span",{className:z("truncate","text-[12px]"),children:"Clarify request"}),s.jsx(jo,{size:14,className:"shrink-0 text-[var(--text-brand)]"})]}),s.jsx("span",{className:z("rounded-full bg-[var(--fill-tsp-white-light)] px-3 py-1 text-[var(--text-secondary)]","text-[11px]"),children:R})]}),M?s.jsxs("div",{className:z("mt-2 text-[var(--text-tertiary)]","text-[11px]"),children:["Missing: ",M]}):null,y?s.jsx("div",{className:"mt-4 space-y-3",children:s.jsxs("div",{className:"rounded-[16px] border border-[var(--border-light)] bg-[var(--fill-tsp-white-light)] px-4 py-3",children:[s.jsx("div",{className:z("font-medium text-[var(--text-primary)]","text-[12px]"),dangerouslySetInnerHTML:{__html:Vr(e)}}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:C.length>0?C.map(ae=>s.jsx("span",{className:z("rounded-full border border-[var(--border-input-active)] bg-[var(--fill-blue)] px-3 py-1 font-medium text-[var(--text-primary)]","text-[11px]"),dangerouslySetInnerHTML:{__html:Vr(ae)}},ae)):s.jsx("span",{className:z("text-[var(--text-tertiary)]","text-[11px]"),children:"(no answer)"})})]})}):s.jsxs("div",{className:"mt-4",children:[s.jsx("div",{className:z("font-medium text-[var(--text-primary)]",p?"text-[15px]":"text-[16px]"),dangerouslySetInnerHTML:{__html:Vr(e)}}),t.length===0?s.jsx("div",{className:z("mt-3 text-[var(--text-tertiary)]","text-[12px]"),children:"No selectable options were provided."}):s.jsx("div",{className:"mt-4 flex flex-wrap gap-3",children:t.map(ae=>{const ye=w.includes(ae.id);return s.jsx("button",{type:"button",onClick:V=>{V.target?.closest("a")||U(ae.id)},disabled:!h,className:z("rounded-full border px-4 py-2 text-left transition-all",ye?"border-[var(--border-input-active)] bg-[var(--fill-blue)] text-[var(--text-primary)]":"border-[var(--border-dark)] text-[var(--text-secondary)] hover:bg-[var(--fill-tsp-white-light)]",!h&&"opacity-60","text-[12px]"),"aria-pressed":ye,children:s.jsx("span",{dangerouslySetInnerHTML:{__html:Vr(ae.label)}})},ae.id)})}),s.jsx("div",{className:"mt-5 flex items-center justify-end",children:s.jsx("button",{type:"button",onClick:Q,disabled:!h||b||!A,className:z("rounded-full px-6 py-2 font-semibold transition-all","text-[12px]",!h||b||!A?"bg-[var(--fill-tsp-gray-dark)] text-[var(--text-tertiary)]":"bg-[var(--Button-primary-black)] text-[var(--text-onblack)] hover:brightness-110"),children:b?"Submitting...":"Confirm"})})]})]})})}const kh={pending:"Pending review",applying:"Applying patch",accepted:"Applied",rejected:"Rejected",failed:"Failed"},Nh={pending:"text-[var(--text-tertiary)]",applying:"text-[var(--text-secondary)]",accepted:"text-[var(--soft-success)]",rejected:"text-[var(--soft-danger)]",failed:"text-[var(--soft-danger)]"},Gk={create:"Created",update:"Updated",delete:"Deleted",move:"Moved"};function Qk(e){let t=0,n=0;return e.forEach(r=>{r.startsWith("+")&&!r.startsWith("+++")&&(t+=1),r.startsWith("-")&&!r.startsWith("---")&&(n+=1)}),{added:t,removed:n}}function Xk({content:e,compact:t,readOnly:n,onAccept:r,onReject:a}){const i=!!t,o=e.status==="applying",u=e.status==="accepted",d=e.status==="rejected",f=e.status==="failed",p=!n&&(e.status==="pending"||f)&&!o,h=!n&&e.status==="pending"&&!o,y=c.useMemo(()=>{const g={added:0,removed:0};return e.files.forEach(T=>{const w=Qk(T.diffLines);g.added+=w.added,g.removed+=w.removed}),g},[e.files]);return s.jsxs("div",{className:z("ai-manus-fade-in flex w-full flex-col gap-3 rounded-[12px] border border-[var(--border-light)]","bg-[var(--fill-tsp-white-light)] px-3 py-3 shadow-[0px_0px_1px_0px_var(--shadow-XS)]"),children:[s.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[s.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[s.jsx("div",{className:z("text-[12px] font-semibold text-[var(--text-primary)]",i&&"text-[11px]"),children:"Patch Review"}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[10px] text-[var(--text-tertiary)]",children:[s.jsxs("span",{children:[e.files.length," files"]}),s.jsxs("span",{children:["+",y.added]}),s.jsxs("span",{children:["-",y.removed]}),s.jsx("span",{className:Nh[e.status],children:kh[e.status]})]})]}),s.jsx("div",{className:"flex items-center gap-2",children:!u&&!d?s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",onClick:a,disabled:!h,className:z("inline-flex items-center gap-1 rounded-full border px-3 py-1 text-[10px] font-semibold","border-[var(--border-light)] text-[var(--text-tertiary)] transition hover:text-[var(--text-primary)]","disabled:cursor-not-allowed disabled:opacity-50"),children:[s.jsx(fo,{size:12}),"Reject"]}),s.jsxs("button",{type:"button",onClick:r,disabled:!p,className:z("inline-flex items-center gap-1 rounded-full border px-3 py-1 text-[10px] font-semibold","border-[var(--border-light)] bg-[var(--fill-tsp-gray-dark)] text-[var(--text-primary)]","transition hover:bg-[var(--fill-tsp-gray-mid)] disabled:cursor-not-allowed disabled:opacity-50"),children:[o?s.jsx(oc,{compact:!0,text:"Applying"}):s.jsx(jo,{size:12}),f?"Retry":"Accept"]})]}):s.jsx("div",{className:z("text-[10px] font-semibold",Nh[e.status]),children:kh[e.status]})})]}),e.rationale?s.jsx("div",{className:z("text-[11px] text-[var(--text-secondary)]",i&&"text-[10px]"),children:e.rationale}):null,e.error?s.jsxs("div",{className:"flex items-center gap-2 rounded-[10px] border border-[var(--border-light)] bg-[var(--fill-tsp-white)] px-2 py-1 text-[10px] text-[var(--soft-danger)]",children:[s.jsx(Tn,{size:12}),s.jsx("span",{className:"truncate",children:e.error})]}):null,s.jsx("div",{className:"flex flex-col gap-3",children:e.files.map(g=>s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 text-[10px] text-[var(--text-tertiary)]",children:[s.jsx("span",{className:"font-medium text-[var(--text-secondary)]",children:g.path}),s.jsxs("span",{children:[Gk[g.changeType],g.moveTo?` → ${g.moveTo}`:""]})]}),g.diffLines.length>0?s.jsx(Wu,{diff:{lines:g.diffLines},changeType:g.changeType==="move"?"update":g.changeType,showHeader:!1,compact:!0}):s.jsx("div",{className:"rounded-[10px] border border-dashed border-[var(--border-light)] px-3 py-2 text-[10px] text-[var(--text-tertiary)]",children:"No diff available."})]},`${g.path}-${g.changeType}`))})]})}const Yk=220,jh=3500;function Th({content:e,active:t,streamKey:n,allowComplete:r,reducedMotion:a,onComplete:i}){const[o,u]=c.useState(null),d=c.useRef(null),f=c.useRef(null),p=c.useRef([]),h=c.useRef(0),y=c.useRef(!1),g=c.useRef(null),T=c.useRef(i),w=c.useRef(n);return c.useEffect(()=>{T.current=i},[i]),c.useEffect(()=>{w.current!==n&&(w.current=n,h.current=0,y.current=!1,g.current=null,f.current&&(window.clearTimeout(f.current),f.current=null),u(t?"":null))},[t,n]),c.useEffect(()=>{p.current=e.split(/\r?\n/);const _=p.current.length,b=()=>{d.current&&(window.clearInterval(d.current),d.current=null)},E=()=>{f.current&&(window.clearTimeout(f.current),f.current=null)},R=()=>{y.current||(y.current=!0,T.current?.())},A=()=>{if(!r||y.current)return;if(a){R();return}const C=g.current??Date.now();g.current=C;const M=Date.now()-C,U=Math.max(0,Yk-M);if(U===0){R();return}E(),f.current=window.setTimeout(()=>{f.current=null,R()},U)};if(!t){b(),E(),y.current=!1,g.current=null,h.current=_,u(null);return}if(a){b(),E(),h.current=_,u(e),A();return}if(g.current||(g.current=Date.now()),h.current>_&&(h.current=_),h.current<_&&(y.current=!1),h.current===0&&_>0&&(h.current=1),u(p.current.slice(0,h.current).join(`
201
+ `)),h.current>=_){b(),A();return}if(!d.current)return d.current=window.setInterval(()=>{const C=p.current,M=C.length-h.current;if(M<=0){b(),A();return}const U=Math.max(1,Math.ceil(M/12));h.current=Math.min(C.length,h.current+U),u(C.slice(0,h.current).join(`
202
+ `)),h.current>=C.length&&(b(),A())},64),()=>{b(),E()}},[t,r,e,a]),o}function Zk({state:e}){return!e||e==="delivered"||e==="sent"?s.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-full text-[var(--text-tertiary)]","aria-label":"Sent",title:"Sent",children:s.jsx(jo,{className:"h-3.5 w-3.5",strokeWidth:2.4})}):e==="sending"?s.jsx("span",{className:"block h-2.5 w-2.5 rounded-full bg-[rgba(148,163,184,0.55)]","aria-label":"Queued",title:"Queued"}):e==="failed"?s.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-full text-[rgba(185,28,28,0.72)]","aria-label":"Failed",title:"Failed",children:"!"}):null}function Jk({message:e,sessionId:t,projectId:n,readOnly:r,onToolClick:a,onFileClick:i,onQuestionPromptSubmit:o,onClarifyQuestionSubmit:u,onPatchAccept:d,onPatchReject:f,onAvatarContextMenu:p,displayStreaming:h,onDisplayComplete:y,streamActive:g,compact:T,showAssistantHeader:w,preferInlineToolView:_,inlineToolOpen:b,onInlineToolOpenChange:E}){const R=!!T,A=w??!0,C=e.type==="tool"||e.type==="tool_call"||e.type==="tool_result",M=c.useMemo(()=>e.content,[e]),U=C&&typeof M.function=="string"?M.function:"",Q=U.toLowerCase(),ae=C&&M.args&&typeof M.args=="object"&&!Array.isArray(M.args)?M.args:{},ye=typeof ae.mode=="string"?ae.mode.trim().toLowerCase():"",V=ye==="read"||ye==="kill",W=R&&C&&(yr(U)==="bash_exec"||Q==="bash_exec"||Q==="paper_search"||Q==="read_paper"),[Z,Se]=c.useState(!0),[$e,Ne]=c.useState(W),G=rc(),J=c.useRef(null),$=c.useRef(null),I=c.useRef(null),O=c.useRef(null),X=!!h,ne=g??X,ke=e.type==="text_delta",de=c.useMemo(()=>e.content,[e]),Te=e.type==="user"||de.role==="user"?"user":"assistant",Oe=e.type==="user"||ke&&Te==="user",He=ke&&Te==="assistant",ut=c.useMemo(()=>e.content,[e]),oe=c.useMemo(()=>e.content,[e]),Ae=c.useMemo(()=>e.content,[e]),Ce=c.useMemo(()=>e.content,[e]),ie=c.useMemo(()=>e.content,[e]),Ee=c.useMemo(()=>e.content,[e]),fe=c.useMemo(()=>e.content,[e]),Fe=typeof de.content=="string"?de.content:"",We=e.type==="reasoning"&&typeof Ae.content=="string"?Ae.content:"",Me=c.useMemo(()=>Gr(Ce.content??""),[Ce.content]),yt=He&&de.status==="in_progress",bt=e.type==="reasoning"&&Ae.status==="in_progress",ct=C&&M.status==="calling",qt=e.type==="status"&&Ce.status==="in_progress",wt=He&&X,jt=e.type==="reasoning"&&X,Ye=X&&ne&&!(G??!1),ft=de.metadata?.ai_usage,St=typeof de.metadata?.sender_type=="string"?de.metadata.sender_type:null,Kt=typeof de.metadata?.agent_label=="string"?de.metadata.agent_label:typeof de.metadata?.agent_id=="string"?`@${de.metadata.agent_id}`:null,Gt=typeof de.metadata?.agent_display_name=="string"?de.metadata.agent_display_name:null,he=typeof de.metadata?.agent_logo=="string"?de.metadata.agent_logo:null,kt=St==="agent"&&typeof de.metadata?.sender_label=="string"?de.metadata.sender_label:Kt,$t=St==="agent"&&typeof de.metadata?.sender_name=="string"?de.metadata.sender_name:Gt,ht=St==="agent"&&typeof de.metadata?.sender_avatar_url=="string"?de.metadata.sender_avatar_url:he,an=$t||"DeepScientist",At=typeof de.metadata?.delivery_state=="string"?de.metadata.delivery_state.toLowerCase():null,fn=ft&&Number.isFinite(ft.total_tokens)?`Tokens: ${ft.total_tokens} (in ${ft.input_tokens}, out ${ft.output_tokens})${ft.estimated?" ~":""}`:null,Ze=c.useRef(!1),ot=!Ye,j=He&&!yt&&ot,P=e.type==="reasoning"&&!bt&&ot,B=C&&!ct&&ot,Le=e.type==="status"&&!qt&&ot,Je=He&&!yt,Re=e.type==="reasoning"&&!bt,Ft=C&&!ct,at=e.type==="status"&&!qt;c.useEffect(()=>{W&&Ne(!0)},[W]);const Xt=c.useCallback(Be=>{b==null&&Ne(Be),E?.(Be)},[b,E]);c.useEffect(()=>{Ze.current=!1},[e.id]);const pt=c.useCallback(Be=>{!y||Ze.current||(Ze.current=!0,y({id:e.id,kind:Be}))},[e.id,y]),pn=(Be,Wt=!1)=>{const zt=p?se=>{se.preventDefault(),p(se,e)}:void 0,we=z("shrink-0",R?"h-[22px] w-[22px]":"h-6 w-6"),k=ht?s.jsx("img",{src:ht,alt:an,className:we,draggable:!1}):s.jsxs(s.Fragment,{children:[s.jsx("img",{src:Fb,alt:"DeepScientist logo",className:z(we,"dark:hidden"),draggable:!1}),s.jsx("img",{src:zb,alt:"DeepScientist logo",className:z(we,"hidden dark:block"),draggable:!1})]});return s.jsxs("div",{className:"flex h-7 items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-[6px] text-[var(--text-primary)]",children:[s.jsx("div",{className:z("flex items-center",p&&"cursor-context-menu"),onContextMenu:zt,children:k}),s.jsx("span",{className:z("font-semibold","text-[10px]"),children:an}),kt?s.jsx("span",{className:"ai-manus-mention-label text-[10px] font-semibold",children:kt}):null]}),!R&&(Wt||Number.isFinite(Be))?s.jsxs("div",{className:"flex flex-col items-end gap-[2px] text-[9px] text-[var(--text-tertiary)]",children:[Wt&&fn?s.jsx("div",{className:"opacity-80",children:fn}):null,Number.isFinite(Be)?s.jsx("div",{className:"opacity-0 transition group-hover:opacity-100",children:Nr(Be)}):null]}):null]})},ln=c.useCallback(Be=>{const Wt=Be.target;if(!Wt)return!1;const zt=Wt.closest("button.ai-manus-code-copy");if(zt){Be.preventDefault(),Be.stopPropagation();const k=zt.closest(".ai-manus-codeblock")?.querySelector("pre code")?.textContent??"";if(!k)return!0;const se=zt.textContent??"Copy",me=lt=>{zt.textContent=lt},Nt=()=>{me("Copied"),window.setTimeout(()=>me(se),1400)};if(navigator.clipboard?.writeText)return navigator.clipboard.writeText(k).then(Nt).catch(()=>{}),!0;const xe=document.createElement("textarea");xe.value=k,xe.style.position="fixed",xe.style.top="-9999px",xe.style.left="-9999px",document.body.appendChild(xe),xe.select();try{document.execCommand("copy"),Nt()}catch{}finally{xe.remove()}return!0}return!1},[]),Pe=Th({content:Fe,active:He&&X&&!yt&&!Ye,streamKey:e.id,allowComplete:He,reducedMotion:G??!1,onComplete:j?()=>pt("assistant"):void 0}),Yt=Th({content:We,active:e.type==="reasoning"&&X&&!bt&&!Ye,streamKey:e.id,allowComplete:e.type==="reasoning"&&Ae.status==="completed",reducedMotion:G??!1,onComplete:P?()=>pt("reasoning"):void 0})??We,Ct=c.useMemo(()=>Oe?xo(Fe):"",[Fe,Oe]),mt=c.useMemo(()=>He?Z1(Pe!==null?Pe:Fe,de.metadata?.citations):{html:"",citationLookup:{}},[Fe,He,de.metadata?.citations,Pe]),vt=mt.html,mn=c.useRef({});c.useEffect(()=>{mn.current=mt.citationLookup},[mt.citationLookup]);const Gn=c.useMemo(()=>e.type!=="reasoning"?"":xo(Yt),[e.type,Yt]),Cn=c.useMemo(()=>e.type!=="step"?"":xo(ut.description||""),[e.type,ut.description]),sn=c.useMemo(()=>{if(!C)return"";const Be=M.args&&typeof M.args=="object"&&!Array.isArray(M.args)?M.args:{},Wt=typeof Be.message=="string"?Be.message:typeof Be.text=="string"?Be.text:"",zt=Gr(Wt),we=typeof M.error=="string"?M.error:"",k=M.content&&typeof M.content=="object"&&typeof M.content.error=="string"?String(M.content.error):"";return[M.tool_call_id,M.status,M.name,M.function,M.duration_ms??"",zt,we,k].join("|")},[C,M]),ys=c.useCallback(Be=>{const Wt=Be.target;if(!Wt)return;const zt=Wt.closest("[data-cite-key]");if(!zt)return;const we=zt.getAttribute("data-cite-key");if(!we)return;const k=mn.current[we];k&&(Be.preventDefault(),Be.stopPropagation(),C0(k))},[]),Dn=c.useCallback(Be=>{ln(Be)||ys(Be)},[ys,ln]);if(c.useEffect(()=>{if(!(!X||!y||Ze.current)){if(j){pt("assistant");return}if(P){pt("reasoning");return}Le&&pt("status")}},[pt,y,j,P,Le,X]),c.useEffect(()=>{if(!C||!X||!y||Ze.current||!B)return;const Be=G?0:220,Wt=window.setTimeout(()=>{pt("tool")},Be);return()=>window.clearTimeout(Wt)},[pt,C,y,G,B,X]),c.useEffect(()=>{if(!(!X||!y))return()=>{Ze.current||(He?pt("assistant"):e.type==="reasoning"?pt("reasoning"):e.type==="status"?pt("status"):C&&pt("tool"))}},[pt,He,C,e.id,e.type,y,X]),pl({ref:J,active:Ye&&He,contentKey:vt,mode:"assistant",maxChars:jh,reducedMotion:G??!1,onComplete:X&&Je?()=>pt("assistant"):void 0}),pl({ref:$,active:Ye&&e.type==="reasoning",contentKey:`${Gn}::${Ae.status??""}`,mode:"reasoning",maxChars:jh,reducedMotion:G??!1,onComplete:X&&Re?()=>pt("reasoning"):void 0}),pl({ref:O,active:Ye&&C,contentKey:sn,mode:"status",reducedMotion:G??!1,onComplete:X&&Ft?()=>pt("tool"):void 0}),pl({ref:I,active:Ye&&e.type==="status",contentKey:Me,mode:"status",reducedMotion:G??!1,onComplete:X&&at?()=>pt("status"):void 0}),c.useEffect(()=>{e.type==="reasoning"&&Ae.collapsed&&Se(!1)},[e.type,Ae.collapsed]),Oe)return s.jsxs("div",{className:"ai-manus-fade-in group mt-3 flex w-full flex-col items-end justify-end gap-1",children:[s.jsx("div",{className:"flex items-end",children:R?null:s.jsx("div",{className:"flex items-center gap-[2px] text-[9px] text-[var(--text-tertiary)] opacity-0 transition group-hover:opacity-100",children:Nr(de.timestamp)})}),s.jsxs("div",{className:"flex max-w-[90%] items-end gap-2",children:[s.jsx("div",{className:"mb-2 shrink-0",children:s.jsx(Zk,{state:At})}),s.jsx("div",{className:z("relative rounded-[10px] border border-[var(--border-main)] bg-[var(--fill-white)] p-3 text-[var(--text-primary)]",R?"text-[11px] leading-relaxed":"text-[12px] leading-relaxed"),onClick:ln,dangerouslySetInnerHTML:{__html:Ct}})]})]});if(ke)return s.jsxs("div",{className:"ai-manus-fade-in group mt-3 flex w-full flex-col gap-2",children:[A?pn(de.timestamp,!0):null,s.jsx("div",{ref:J,"data-content-streaming":wt?"true":void 0,"data-stream-caret":yt&&ne?"true":void 0,className:z("prose max-w-none text-[var(--text-primary)] dark:prose-invert [&_pre:not(.shiki)]:!bg-[var(--fill-tsp-white-light)] [&_code]:text-[var(--text-primary)] [&_pre:not(.shiki)_code]:text-[var(--text-primary)]",R?"prose-sm text-[11px] [&_p]:text-[11px] [&_li]:text-[11px]":"prose-sm text-[12px] [&_p]:text-[12px] [&_li]:text-[12px]"),onClick:Dn,dangerouslySetInnerHTML:{__html:vt}})]});if(C){const Be=Qd(M),zt=yr(M.function)==="bash_exec",we=zt?Pb:Be.view,k=Be.category==="paper_search",se=Be.category==="read_paper",me=Be.category==="bash"&&R&&!V,xe=!!_&&R&&!!we&&new Set(["shell","bash","file","browser","search","paper_search","read_paper","mcp"]).has(Be.category),lt=!!we&&(xe||k||se||me||zt),Mt=b??$e,En=we&&lt&&Mt,Mn=me||zt||Be.category==="shell"?"overflow-hidden rounded-[12px]":"overflow-hidden rounded-[12px] border border-[var(--border-light)] bg-[var(--background-main)]",Is=()=>{if(lt){Xt(!Mt);return}if(a){a(M);return}};return s.jsxs("div",{className:z("ai-manus-fade-in group flex flex-col gap-2",X&&"ai-manus-slide-in"),"data-content-streaming":X?"true":void 0,ref:O,children:[A?pn(M.timestamp):null,s.jsx(Sh,{tool:M,compact:R,collapsible:!0,projectId:n,onClick:lt||a?Is:void 0}),En?s.jsx("div",{className:Mn,children:s.jsx(we,{toolContent:M,live:M.status==="calling",sessionId:t,projectId:n,readOnly:r,panelMode:"inline"})}):null]})}if(e.type==="status")return Me?s.jsx("div",{ref:I,"data-content-streaming":X?"true":void 0,className:"ai-manus-fade-in text-center text-[11px] text-[var(--text-tertiary)]",children:Me}):null;if(e.type==="reasoning"){const Wt=Ae.kind==="summary"?"Reasoning summary":"Reasoning";if(!Yt.trim())return null;const zt=Ae.status==="in_progress"&&ne;return s.jsxs("div",{className:"ai-manus-fade-in group flex flex-col gap-2",children:[A?pn(Ae.timestamp):null,s.jsxs("button",{type:"button",onClick:()=>Se(we=>!we),className:z("group/header flex w-full items-center justify-between gap-2 text-[var(--text-primary)]",R?"text-[11px]":"text-[10px]"),children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[s.jsx(Db,{name:"Brain",alt:"",size:R?22:24,className:"shrink-0",fallback:s.jsx($b,{className:z("text-[var(--text-primary)]",R?"h-4 w-4":"h-5 w-5")})}),s.jsx("span",{className:"truncate font-medium",children:Wt}),zt?s.jsx(oc,{text:"Thinking",compact:R}):null,s.jsx(mi,{size:R?14:16,className:`transition-transform ${Z?"rotate-180":""}`})]}),R?null:s.jsx("div",{className:"text-[9px] text-[var(--text-tertiary)] opacity-0 transition group-hover/header:opacity-100",children:Nr(Ae.timestamp)})]}),s.jsx("div",{className:z("overflow-hidden rounded-[10px] border border-[var(--border-light)] bg-[var(--fill-tsp-white-light)] px-3 py-2",Z?"max-h-[100000px] opacity-100":"max-h-0 opacity-0","transition-[max-height,opacity] duration-150 ease-in-out"),children:s.jsx("div",{ref:$,"data-content-streaming":jt?"true":void 0,className:z("prose max-w-none text-[var(--text-primary)] dark:prose-invert [&_code]:text-[var(--text-primary)] [&_pre:not(.shiki)_code]:text-[var(--text-primary)]",R?"prose-sm text-[11px] [&_p]:text-[11px] [&_li]:text-[11px]":"prose-sm text-[12px] [&_p]:text-[12px] [&_li]:text-[12px]"),onClick:ln,dangerouslySetInnerHTML:{__html:Gn}})})]})}if(e.type==="step")return s.jsxs("div",{className:"ai-manus-fade-in group flex flex-col",children:[A?pn(ut.timestamp):null,s.jsxs("button",{type:"button",onClick:()=>Se(Be=>!Be),className:z("group/header flex w-full items-center justify-between gap-2 text-[var(--text-primary)]",R?"text-[11px]":"text-[10px]"),children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[ut.status==="completed"?s.jsx("span",{className:"flex h-4 w-4 items-center justify-center rounded-full bg-[var(--text-disable)] text-[var(--icon-white)]",children:s.jsx(jo,{size:10})}):s.jsx("span",{className:"flex h-4 w-4 items-center justify-center rounded-full border border-[var(--border-dark)]"}),s.jsx("div",{className:"truncate font-medium",onClick:ln,dangerouslySetInnerHTML:{__html:Cn}}),s.jsx(mi,{size:R?14:16,className:`transition-transform ${Z?"rotate-180":""}`})]}),R?null:s.jsx("div",{className:"text-[9px] text-[var(--text-tertiary)] opacity-0 transition group-hover/header:opacity-100",children:Nr(ut.timestamp)})]}),s.jsxs("div",{className:"flex",children:[s.jsx("div",{className:"relative w-[24px]",children:s.jsx("div",{className:"absolute left-[8px] top-0 bottom-0 border-l border-dashed border-[var(--border-dark)]",style:{height:"calc(100% + 14px)"}})}),s.jsx("div",{className:`flex flex-1 flex-col gap-3 overflow-hidden pt-2 transition-[max-height,opacity] duration-150 ease-in-out ${Z?"max-h-[100000px] opacity-100":"max-h-0 opacity-0"}`,children:ut.tools.map(Be=>s.jsx(Sh,{tool:Be,compact:R,collapsible:!0,projectId:n,onClick:()=>a?.(Be)},Be.tool_call_id))})]})]});if(e.type==="attachments"||e.type==="attachment"){const Be=A&&oe.role==="assistant";return s.jsxs("div",{className:"ai-manus-fade-in group flex flex-col gap-2",children:[Be?pn(oe.timestamp):null,s.jsx(qk,{content:oe,compact:R,onFileClick:i})]})}return e.type==="question_prompt"?s.jsxs("div",{className:"ai-manus-fade-in group flex flex-col gap-2",children:[A?pn(ie.timestamp):null,s.jsx(Uk,{toolCallId:ie.toolCallId,args:ie.args,status:ie.status,answers:ie.answers,error:ie.error,compact:R,onSubmit:o?Be=>o(ie.toolCallId,Be):void 0})]}):e.type==="clarify_question"?s.jsxs("div",{className:"ai-manus-fade-in group flex flex-col gap-2",children:[A?pn(Ee.timestamp):null,s.jsx(Kk,{question:Ee.question,options:Ee.options,multi:Ee.multi,status:Ee.status,defaultSelected:Ee.defaultSelected,selections:Ee.selections,missingFields:Ee.missingFields,error:Ee.error,compact:R,onSubmit:u?Be=>u(Ee.toolCallId,Be):void 0})]}):e.type==="patch_review"?s.jsxs("div",{className:"ai-manus-fade-in group flex flex-col gap-2",children:[A?pn(fe.timestamp):null,s.jsx(Xk,{content:fe,compact:R,readOnly:r,onAccept:d?()=>d(e.id):void 0,onReject:f?()=>f(e.id):void 0})]}):null}const Ug=c.memo(Jk,(e,t)=>!(e.message!==t.message||e.sessionId!==t.sessionId||e.projectId!==t.projectId||e.readOnly!==t.readOnly||e.compact!==t.compact||e.showAssistantHeader!==t.showAssistantHeader||e.preferInlineToolView!==t.preferInlineToolView||e.inlineToolOpen!==t.inlineToolOpen||e.onInlineToolOpenChange!==t.onInlineToolOpenChange||e.displayStreaming!==t.displayStreaming||e.onToolClick!==t.onToolClick||e.onFileClick!==t.onFileClick||e.onQuestionPromptSubmit!==t.onQuestionPromptSubmit||e.onClarifyQuestionSubmit!==t.onClarifyQuestionSubmit||e.onPatchAccept!==t.onPatchAccept||e.onPatchReject!==t.onPatchReject||e.onDisplayComplete!==t.onDisplayComplete||e.streamActive!==t.streamActive&&(e.message.type==="reasoning"||t.message.type==="reasoning")));Ug.displayName="ChatMessage";const ef=c.createContext(null),eN=({children:e,delayDuration:t,skipDelayDuration:n})=>s.jsx(s.Fragment,{children:e}),tN=({children:e,delayDuration:t=200})=>{const[n,r]=c.useState(!1),a=c.useRef(),i=c.useCallback(()=>{a.current=setTimeout(()=>{r(!0)},t)},[t]),o=c.useCallback(()=>{a.current&&clearTimeout(a.current),r(!1)},[]);return c.useEffect(()=>()=>{a.current&&clearTimeout(a.current)},[]),s.jsx(ef.Provider,{value:{open:n,setOpen:u=>{u?i():o()}},children:e})},Wg=c.forwardRef(({className:e,children:t,asChild:n,...r},a)=>{const i=c.useContext(ef);return s.jsx("div",{ref:a,className:z("inline-flex",e),onMouseEnter:()=>i?.setOpen(!0),onMouseLeave:()=>i?.setOpen(!1),onFocus:()=>i?.setOpen(!0),onBlur:()=>i?.setOpen(!1),...r,children:t})});Wg.displayName="TooltipTrigger";const Hg=c.forwardRef(({className:e,side:t="top",sideOffset:n=4,children:r,...a},i)=>c.useContext(ef)?.open?s.jsx("div",{ref:i,className:z("absolute z-[10002] overflow-hidden rounded-soft-sm px-3 py-1.5","bg-soft-bg-elevated text-soft-text-primary text-sm","shadow-soft-sm border border-soft-border","animate-in fade-in-0 zoom-in-95",t==="top"&&"bottom-full mb-2",t==="bottom"&&"top-full mt-2",t==="left"&&"right-full mr-2",t==="right"&&"left-full ml-2",e),style:{marginTop:t==="bottom"?n:void 0,marginBottom:t==="top"?n:void 0,marginLeft:t==="right"?n:void 0,marginRight:t==="left"?n:void 0},...a,children:r}):null);Hg.displayName="TooltipContent";function nN({plan:e,sessionId:t,compact:n,history:r}){const a=t?`ds:ai-manus:plan:${t}`:"ds:ai-manus:plan",[i,o]=c.useState(!1),[u,d]=c.useState({}),[f,p]=c.useState("current"),h=rc(),y=!!n,g="max-w-full",T="w-[90%] max-w-full",w=[.4,0,.2,1],_=[0,0,.2,1],b=[0,0,1,1],E=J=>{if(!J)return"Unknown";try{return new Date(J*1e3).toLocaleString()}catch{return"Unknown"}};c.useEffect(()=>{if(typeof window>"u")return;const J=window.localStorage.getItem(a);J!==null&&o(J==="1")},[a]),c.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(a,i?"1":"0")},[i,a]);const R=c.useCallback(J=>{d($=>({...$,[J]:!$[J]}))},[]),A=c.useMemo(()=>!r||r.length===0?[]:r.filter(J=>J?.task_plan?.tasks?.length||J?.steps?.length),[r]);c.useEffect(()=>{A.length||p("current")},[A.length]);const C=c.useMemo(()=>!A.length||f==="current"?e:A.find(J=>J.event_id===f)||e,[e,A,f]),M=c.useMemo(()=>C.task_plan?.tasks||[],[C]),U=c.useMemo(()=>M.length?[]:C.steps||[],[M.length,C.steps]);c.useEffect(()=>{d({})},[f,M.length]);const Q=c.useMemo(()=>{const J=typeof e.event_id=="string"?e.event_id:void 0;return[...A.filter(I=>I?.event_id&&I.event_id!==J).map(I=>({id:I.event_id,timestamp:I.timestamp,kind:"history"})),{id:"current",timestamp:e.timestamp,kind:"current"}]},[e.event_id,e.timestamp,A]),ae=c.useMemo(()=>{const J=Q.findIndex($=>$.id===f);return J>=0?J:Math.max(0,Q.length-1)},[Q,f]),ye=c.useMemo(()=>Q.length<=1?0:Math.min(100,Math.max(0,ae/(Q.length-1)*100)),[ae,Q.length]),V=c.useMemo(()=>A.length?f==="current"?"Current snapshot":"Historical snapshot":"Current snapshot",[A.length,f]),W=c.useMemo(()=>M.length?`${M.filter(I=>(I.status||"").toLowerCase()==="completed").length} / ${M.length||1}`:`${U.filter($=>$.status==="completed").length} / ${U.length||1}`,[U,M]);c.useMemo(()=>{if(M.length){for(const J of M){const $=(J.status||"").toLowerCase();if(!$||$!=="completed")return J.task}return M[0]?.task||"Task Progress"}for(const J of U)if(!J.status||J.status!=="completed")return J.description;return"Task Progress"},[U,M]);const Z=c.useMemo(()=>M.length?M.find($=>{const I=($.status||"").toLowerCase();return!I||I!=="completed"})?.status||(M.length?"completed":"pending"):U.length?U.find($=>$.status!=="completed")?.status||(U.length?"completed":"pending"):"pending",[U,M]),Se=c.useMemo(()=>({completed:{label:"Completed",className:"ai-manus-plan-badge ai-manus-plan-badge--completed",iconClass:"ai-manus-plan-status-icon ai-manus-plan-status-icon--completed",Icon:Ev,motion:h?void 0:{animate:{scale:[1,1.06,1],opacity:[.82,1,.82]},transition:{duration:2.6,repeat:1/0,ease:w}}},running:{label:"Running",className:"ai-manus-plan-badge ai-manus-plan-badge--running",iconClass:"ai-manus-plan-status-icon ai-manus-plan-status-icon--running",Icon:dd,motion:h?void 0:{animate:{rotate:360},transition:{duration:1.1,repeat:1/0,ease:b}}},pending:{label:"Pending",className:"ai-manus-plan-badge ai-manus-plan-badge--pending",iconClass:"ai-manus-plan-status-icon ai-manus-plan-status-icon--pending",Icon:cx,motion:h?void 0:{animate:{opacity:[.55,1,.55]},transition:{duration:1.9,repeat:1/0,ease:w}}},blocked:{label:"Blocked",className:"ai-manus-plan-badge ai-manus-plan-badge--blocked",iconClass:"ai-manus-plan-status-icon ai-manus-plan-status-icon--blocked",Icon:Tn,motion:h?void 0:{animate:{x:[0,-2,2,-1,1,0]},transition:{duration:.8,repeat:1/0,repeatDelay:1.2}}},paused:{label:"Paused",className:"ai-manus-plan-badge ai-manus-plan-badge--paused",iconClass:"ai-manus-plan-status-icon ai-manus-plan-status-icon--paused",Icon:Iv,motion:h?void 0:{animate:{scale:[1,.94,1]},transition:{duration:2.4,repeat:1/0,ease:w}}},failed:{label:"Failed",className:"ai-manus-plan-badge ai-manus-plan-badge--failed",iconClass:"ai-manus-plan-status-icon ai-manus-plan-status-icon--failed",Icon:Ob,motion:h?void 0:{animate:{rotate:[0,-6,6,-3,3,0]},transition:{duration:.9,repeat:1/0,repeatDelay:1.4}}}}),[h]),$e=J=>{const $=(J||"pending").toLowerCase();return Se[$]||Se.pending},Ne=({status:J,size:$=14})=>{const I=$e(J),O=I.Icon;return s.jsx(ks.span,{className:"flex h-4 w-4 items-center justify-center",...I.motion||{},children:s.jsx(O,{size:$,className:I.iconClass})})},G=({status:J})=>{const $=$e(J);return s.jsxs("span",{className:`inline-flex items-center gap-1.5 rounded-full border px-2 py-0.5 text-[9px] uppercase tracking-[0.08em] ${$.className}`,children:[s.jsx(Ne,{status:J,size:12}),$.label]})};return s.jsx("div",{className:`ai-manus-plan-panel relative inline-flex w-[90%] ${g} [&:not(:empty)]:pb-2`,children:i?s.jsx("div",{className:`flex ${T} min-w-0 flex-col`,children:s.jsx("div",{className:"ai-manus-plan-frame rounded-[14px] p-[1px]",children:s.jsxs("div",{className:"ai-manus-plan-surface flex max-h-[40vh] min-w-0 flex-col overflow-hidden rounded-[13px] py-4 backdrop-blur-[6px]",children:[s.jsxs("div",{className:"flex w-full items-center px-4 pb-4",children:[s.jsxs("div",{className:"flex flex-col",children:[s.jsx("span",{className:y?"ai-manus-plan-title text-[13px] font-bold":"ai-manus-plan-title text-[11px] font-bold",children:"Task Progress"}),s.jsx("span",{className:"ai-manus-plan-muted text-[10px]",children:V})]}),s.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[s.jsx("span",{className:"ai-manus-plan-muted text-[10px]",children:W}),s.jsx("button",{type:"button",onClick:()=>o(!1),className:"ai-manus-plan-icon-btn flex h-7 w-7 items-center justify-center rounded-md",children:s.jsx(mi,{size:16,className:"ai-manus-plan-muted"})})]})]}),s.jsx("div",{className:"px-4 pb-4",children:s.jsx(eN,{children:s.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[s.jsx("span",{className:"ai-manus-plan-label text-[9px] uppercase tracking-[0.22em]",children:"Timeline"}),s.jsx("div",{className:"flex-1 min-w-0",children:s.jsxs("div",{className:"relative flex w-full min-w-0 items-center justify-between gap-1.5 py-2 sm:gap-2",children:[s.jsx("div",{"aria-hidden":!0,className:"ai-manus-plan-timeline-line absolute left-0 right-0 top-1/2 h-px -translate-y-1/2"}),s.jsx(ks.span,{"aria-hidden":!0,className:"ai-manus-plan-timeline-progress absolute left-0 top-1/2 h-px -translate-y-1/2",animate:h?void 0:{width:`${ye}%`},style:h?{width:`${ye}%`}:void 0,transition:h?void 0:{duration:.5,ease:_}}),Q.map((J,$)=>{const I=$===ae,O=I?y?12:14:y?7:8,X=J.kind==="current"?`Current · ${E(J.timestamp)}`:E(J.timestamp);return s.jsx("div",{className:"relative flex min-w-0 items-center",children:s.jsxs(tN,{children:[s.jsx(Wg,{children:s.jsx(ks.button,{type:"button",onClick:()=>p(J.id),className:"ai-manus-plan-dot relative z-10 flex items-center justify-center rounded-full",style:{width:O,height:O},whileHover:h?void 0:{scale:I?1.06:1.18},animate:h?void 0:I?{scale:[1,1.08,1]}:{scale:1},transition:h?void 0:{duration:I?2.2:.2,repeat:I?1/0:0,ease:w},"aria-pressed":I,"aria-label":X,children:I&&!h?s.jsx(ks.span,{"aria-hidden":!0,className:"ai-manus-plan-dot-ring absolute inset-0 rounded-full border",animate:{scale:[1,1.6],opacity:[.5,0]},transition:{duration:1.8,repeat:1/0,ease:_}}):null})}),s.jsx(Hg,{side:"top",className:"left-1/2 -translate-x-1/2 whitespace-nowrap text-[11px]",children:X})]})},J.id)})]})})]})})}),s.jsx("div",{className:"flex min-h-0 flex-1 flex-col px-3",children:s.jsx("div",{className:"ai-manus-plan-body flex min-h-0 flex-1 flex-col rounded-[12px] pt-3 pb-2",children:s.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:M.length?s.jsx("div",{className:"flex flex-col gap-2 px-2 pb-2",children:M.map((J,$)=>{const I=`${J.task}-${$}`,O=!!u[I];return s.jsxs(ks.div,{className:"ai-manus-plan-task",animate:h?void 0:{scale:O?1:.98},transition:h?void 0:{duration:.2,ease:_},children:[s.jsxs("button",{type:"button",onClick:()=>R(I),className:"ai-manus-plan-task-title flex w-full items-start justify-between gap-2 text-left","aria-expanded":O,children:[s.jsx("span",{className:"ai-manus-plan-title text-[12px] font-semibold",children:J.task}),s.jsx(G,{status:J.status})]}),O?s.jsxs("div",{className:"ai-manus-plan-task-details mt-2",children:[J.detail?s.jsx("div",{className:"ai-manus-plan-muted text-[11px]",children:J.detail}):null,J.change_reason?s.jsx("div",{className:"ai-manus-plan-note mt-1 text-[10px]",children:J.change_reason}):null,J.sub_tasks.length?s.jsx("div",{className:"ai-manus-plan-subtext mt-2 flex flex-col gap-1 text-[10px]",children:J.sub_tasks.map((X,ne)=>s.jsxs("div",{className:"flex gap-2",children:[s.jsx("span",{className:"ai-manus-plan-bullet",children:"•"}),s.jsx("span",{children:X})]},`${I}-sub-${ne}`))}):null]}):null]},I)})}):U.map(J=>s.jsxs("div",{className:"flex items-start gap-2.5 px-4 py-2",children:[s.jsx(Ne,{status:J.status,size:14}),s.jsx("div",{className:y?"ai-manus-plan-title flex-1 truncate text-[12px]":"ai-manus-plan-title flex-1 truncate text-[10px]",title:J.description,children:J.description})]},J.id))})})})]})})}):s.jsx("button",{type:"button",onClick:()=>o(!0),className:`inline-flex w-auto min-w-[min(260px,100%)] ${g} items-start justify-between gap-2 text-left`,children:s.jsx("div",{className:"ai-manus-plan-frame ai-manus-plan-frame--collapsed rounded-[14px] p-[1px]",children:s.jsxs("div",{className:"ai-manus-plan-summary inline-flex w-auto min-w-[min(260px,100%)] items-start justify-between gap-2 rounded-[13px] px-3 py-2",children:[s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2.5",children:[s.jsx(Ne,{status:Z,size:14}),s.jsx("div",{className:y?"ai-manus-plan-muted truncate text-[12px]":"ai-manus-plan-muted truncate text-[10px]",title:"Task Progress",children:"Task Progress"})]}),s.jsxs("div",{className:y?"ai-manus-plan-muted flex items-center gap-2 text-[11px]":"ai-manus-plan-muted flex items-center gap-2 text-[9px]",children:[y?null:s.jsx("span",{className:"hidden sm:inline",children:W}),s.jsx(wx,{size:16,className:"ai-manus-plan-muted"})]})]})})})})}function sN({open:e,onOpenChange:t,files:n,loading:r,onOpenFile:a}){const{t:i}=nr("ai_manus");return s.jsx(fd,{open:e,onOpenChange:t,children:s.jsxs(pd,{className:"max-w-md rounded-[12px] border border-[var(--border-light)] bg-[var(--background-card)] p-5 text-[var(--text-primary)] shadow-[0px_18px_40px_-30px_var(--shadow-M)]",showCloseButton:!0,children:[s.jsx(gx,{className:"text-[11px] font-semibold text-[var(--text-primary)]",children:i("session_files")}),s.jsx(yx,{className:"text-[9px] text-[var(--text-tertiary)]",children:i("session_files_desc")}),s.jsx("div",{className:"mt-4 flex flex-col gap-2",children:r?s.jsx("div",{className:"text-[10px] text-[var(--text-tertiary)]",children:i("loading_files_short")}):n.length===0?s.jsx("div",{className:"text-[10px] text-[var(--text-tertiary)]",children:i("no_files_yet")}):n.map(o=>s.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-[10px] border border-[var(--border-light)] bg-[var(--fill-tsp-white-light)] px-3 py-2",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[s.jsx(No,{className:"h-4 w-4 text-[var(--icon-secondary)]"}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"truncate text-[10px] text-[var(--text-primary)]",children:o.filename}),s.jsx("div",{className:"text-[9px] text-[var(--text-tertiary)]",children:ai(o.size??void 0)})]})]}),o.file_id?s.jsx("button",{type:"button",onClick:()=>a(o.file_id),className:"rounded-[8px] border border-[var(--border-light)] px-2 py-1 text-[9px] font-medium text-[var(--text-secondary)] hover:bg-[var(--background-white-main)]",children:i("open")}):null]},o.file_id??o.file_path??o.filename))})]})})}function Ah({className:e,size:t=38}){const n=c.useId(),r=c.useId();return s.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:t,height:t,viewBox:"0 0 38 38",fill:"none",className:z("ai-manus-spin",e),children:[s.jsx("mask",{id:n,fill:"white",children:s.jsx("path",{d:"M38 19C38 29.4934 29.4934 38 19 38C8.50659 38 0 29.4934 0 19C0 8.50659 8.50659 0 19 0C29.4934 0 38 8.50659 38 19Z"})}),s.jsx("g",{clipPath:`url(#${r})`,mask:`url(#${n})`,children:s.jsx("g",{transform:"matrix(0 0.019 -0.019 0 19 19)",children:s.jsx("foreignObject",{x:"-1105.26",y:"-1105.26",width:"2210.53",height:"2210.53",children:s.jsx("div",{style:{background:"conic-gradient(from 90deg, #C7AD7A 0deg, #D6C2A1 75deg, #B18C55 150deg, #9A7B4B 225deg, #C1A26A 300deg, rgba(201, 179, 122, 0) 360deg)",height:"100%",width:"100%",opacity:1}})})})}),s.jsx("path",{d:"M36 19C36 28.3888 28.3888 36 19 36V40C30.598 40 40 30.598 40 19H36ZM19 36C9.61116 36 2 28.3888 2 19H-2C-2 30.598 7.40202 40 19 40V36ZM2 19C2 9.61116 9.61116 2 19 2V-2C7.40202 -2 -2 7.40202 -2 19H2ZM19 2C28.3888 2 36 9.61116 36 19H40C40 7.40202 30.598 -2 19 -2V2Z",mask:`url(#${n})`}),s.jsx("defs",{children:s.jsx("clipPath",{id:r,children:s.jsx("path",{d:"M36 19C36 28.3888 28.3888 36 19 36V40C30.598 40 40 30.598 40 19H36ZM19 36C9.61116 36 2 28.3888 2 19H-2C-2 30.598 7.40202 40 19 40V36ZM2 19C2 9.61116 9.61116 2 19 2V-2C7.40202 -2 -2 7.40202 -2 19H2ZM19 2C28.3888 2 36 9.61116 36 19H40C40 7.40202 30.598 -2 19 -2V2Z",mask:`url(#${n})`})})})]})}function rN({session:e,active:t,highlight:n,condensed:r,pinned:a,displayTitle:i,onSelect:o,onDelete:u,onTogglePin:d,onRename:f,onShare:p,readOnly:h}){const y=e.latest_message_at??e.updated_at,g=c.useMemo(()=>y?OS(y):"",[y]),T=typeof e.is_active=="boolean"?e.is_active:e.status==="running"||e.status==="pending",w=!!(e.agent_engine&&["claude_code","codex"].includes(e.agent_engine)||e.execution_target&&e.execution_target==="cli"||e.cli_server_id),_=e.session_id.startsWith("draft-"),b=typeof i=="string"&&i.trim()?i.trim():e.title||"New Chat",E=g?`${b} · ${g}`:b,R=!!(u&&!h&&!_),A=!!(d&&!h&&!_),C=!!(f&&!h&&!_),M=!!(p&&!h&&!_),U=R||A||C||M,Q=()=>{o(e.session_id)},ae=async Z=>{Z.stopPropagation(),!(!R||!u)&&u(e.session_id)},ye=Z=>{Z.stopPropagation(),!(!A||!d)&&d(e.session_id)},V=Z=>{Z.stopPropagation(),!(!C||!f)&&f(e.session_id)},W=Z=>{Z.stopPropagation(),!(!M||!p)&&p(e.session_id)};return r?s.jsx("div",{className:"px-1",children:s.jsx("div",{role:"button",tabIndex:0,onClick:Q,onKeyDown:Z=>{(Z.key==="Enter"||Z.key===" ")&&(Z.preventDefault(),Q())},title:E,"aria-label":b,className:z("group flex h-12 flex-col items-center justify-center gap-1 rounded-[10px] px-1 py-1 transition-colors",t?"bg-[var(--background-white-main)]":"hover:bg-[var(--fill-tsp-gray-main)]",n&&"ai-manus-slide-in"),children:s.jsxs("div",{className:"relative",children:[s.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-full bg-[var(--fill-tsp-white-dark)]",children:s.jsx("img",{alt:"Session",className:"h-4 w-4 object-cover opacity-80",src:"/chatting.svg"})}),T?s.jsx("div",{className:"absolute -left-[5px] -top-[3px] h-[calc(100%+8px)] w-[calc(100%+8px)]",children:s.jsx(Ah,{className:"h-full w-full"})}):null,w?s.jsx("div",{className:"absolute -right-1 -top-1 flex h-4 w-4 items-center justify-center rounded-full border border-[var(--border-main)] bg-[var(--background-white-main)] text-[var(--text-secondary)] shadow-[0px_2px_6px_-4px_rgba(0,0,0,0.3)]",children:s.jsx(Uu,{size:10})}):null]})})}):s.jsx("div",{className:"px-2",children:s.jsxs("div",{role:"button",tabIndex:0,onClick:Q,onKeyDown:Z=>{(Z.key==="Enter"||Z.key===" ")&&(Z.preventDefault(),Q())},className:z("group flex h-14 items-center gap-2 rounded-[10px] px-2 transition-colors",t?"bg-[var(--background-white-main)]":"hover:bg-[var(--fill-tsp-gray-main)]",n&&"ai-manus-slide-in"),children:[s.jsxs("div",{className:"relative",children:[s.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-full bg-[var(--fill-tsp-white-dark)]",children:s.jsx("img",{alt:"Session",className:"h-4 w-4 object-cover opacity-80",src:"/chatting.svg"})}),T?s.jsx("div",{className:"absolute -left-[5px] -top-[3px] h-[calc(100%+8px)] w-[calc(100%+8px)]",children:s.jsx(Ah,{className:"h-full w-full"})}):null,w?s.jsx("div",{className:"absolute -right-1 -top-1 flex h-4 w-4 items-center justify-center rounded-full border border-[var(--border-main)] bg-[var(--background-white-main)] text-[var(--text-secondary)] shadow-[0px_2px_6px_-4px_rgba(0,0,0,0.3)]",children:s.jsx(Uu,{size:10})}):null]}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-1 overflow-hidden",children:[s.jsx("span",{className:"flex-1 truncate text-sm font-medium text-[var(--text-primary)]",title:b,children:b}),a?s.jsx(am,{className:"h-3 w-3 shrink-0 text-[var(--text-tertiary)]","aria-label":"Pinned"}):null,s.jsx("span",{className:"text-xs text-[var(--text-tertiary)]",children:g})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"flex-1 truncate text-xs text-[var(--text-tertiary)]",title:e.latest_message||"",children:e.latest_message||""}),U?s.jsxs(Bb,{children:[s.jsx(qb,{asChild:!0,children:s.jsx("button",{type:"button",className:z("flex h-6 w-6 items-center justify-center rounded-[6px] border border-[var(--border-main)]","bg-[var(--background-menu-white)] text-[var(--icon-secondary)]","opacity-0 transition-opacity group-hover:opacity-100"),onClick:Z=>Z.stopPropagation(),"aria-label":"Session menu",children:s.jsx(Ub,{size:14})})}),s.jsxs(Wb,{className:z("!border-[var(--soft-border)] !bg-[var(--soft-bg-surface)] !text-[var(--soft-text-primary)]","shadow-[0px_16px_36px_-20px_rgba(0,0,0,0.2)]"),align:"end","data-ai-manus-history-overlay":"true",children:[A?s.jsxs(ml,{className:"cursor-pointer !focus:bg-[var(--soft-bg-inset)]",onClick:ye,children:[a?s.jsx(Gv,{className:"mr-2 h-3.5 w-3.5"}):s.jsx(am,{className:"mr-2 h-3.5 w-3.5"}),a?"Unpin":"Pin to top"]}):null,C?s.jsxs(ml,{className:"cursor-pointer !focus:bg-[var(--soft-bg-inset)]",onClick:V,children:[s.jsx(Vv,{className:"mr-2 h-3.5 w-3.5"}),"Rename"]}):null,M?s.jsxs(ml,{className:"cursor-pointer !focus:bg-[var(--soft-bg-inset)]",onClick:W,children:[s.jsx(r_,{className:"mr-2 h-3.5 w-3.5"}),"Copy link"]}):null,R&&(A||C||M)?s.jsx(Hb,{className:"bg-[var(--soft-border)]"}):null,s.jsxs(ml,{className:"cursor-pointer text-[hsl(var(--destructive))] !focus:bg-[hsl(var(--destructive)/0.12)]",onClick:ae,children:[s.jsx(jv,{className:"mr-2 h-3.5 w-3.5"}),"Delete"]})]})]}):null]})]})]})})}function aN({open:e,sessions:t,activeSessionId:n,highlightSessionId:r,onToggle:a,onSelect:i,onNew:o,onDelete:u,onTogglePin:d,onRename:f,onShare:p,readOnly:h,floating:y,draggable:g,dragConstraintsRef:T,pinnedSessionIds:w,renamedSessions:_,panelId:b}){const{t:E}=nr("ai_manus"),R=m_(),A=!!y,C=!!g,M=c.useRef(null),U=c.useMemo(()=>new Set(w??[]),[w]),Q=c.useMemo(()=>typeof window>"u"?!1:window.localStorage.getItem("ds_debug_copilot")==="1",[]);return c.useEffect(()=>{Q&&console.info("[AiManus][history:panel]",{open:e,floating:A,draggable:C,panelId:b??null})},[Q,C,A,e,b]),c.useEffect(()=>{if(!A||!e)return;const ae=ye=>{if(typeof ye.button=="number"&&ye.button!==0)return;const V=ye.target,W=M.current;if(W&&V&&W.contains(V))return;const Z=typeof ye.composedPath=="function"?ye.composedPath():null;if(Z){for(const Se of Z)if(Se instanceof Element&&(Se.hasAttribute("data-ai-manus-history-toggle")||Se.closest?.("[data-ai-manus-history-toggle]")||Se.hasAttribute("data-ai-manus-history-overlay")||Se.closest?.("[data-ai-manus-history-overlay]")))return}a(!1)};return document.addEventListener("pointerdown",ae,!0),()=>document.removeEventListener("pointerdown",ae,!0)},[A,a,e]),e?s.jsx(ks.div,{ref:M,id:b,role:"region","aria-label":E("history"),"data-ai-manus-history-overlay":"true",drag:C,dragControls:R,dragListener:!1,dragMomentum:!1,dragElastic:.08,dragConstraints:C?T:void 0,whileDrag:C?{scale:1.01}:void 0,className:z("relative min-w-0 overflow-visible pointer-events-auto",A?"m-3 h-[calc(100%-24px)] max-w-[calc(100%-24px)]":"h-full max-w-full","w-[min(300px,100%)]"),children:s.jsx(Vb,{className:"ai-manus-session-glass relative flex h-full w-full rounded-[18px]",strength:.28,children:s.jsxs(bx,{spotlightColor:"rgba(159, 177, 194, 0.24)",hoverOnly:!0,className:"flex h-full w-full flex-col bg-transparent",children:[s.jsx(Kb,{size:240,className:"ai-manus-session-noise opacity-[0.055]"}),s.jsxs("div",{className:"relative flex h-full flex-col",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-3",children:[s.jsx("div",{className:"h-7 w-7","aria-hidden":!0}),s.jsxs("div",{role:C?"button":void 0,tabIndex:C?0:void 0,"aria-label":C?E("drag_history_panel"):void 0,title:C?E("drag_to_move"):void 0,onPointerDown:C?ae=>{ae.preventDefault(),R.start(ae.nativeEvent)}:void 0,className:z("flex min-w-0 flex-1 items-center justify-center gap-2 rounded-[999px] px-2 py-1 text-[11px] font-semibold text-[var(--text-tertiary)]",C&&"touch-none cursor-grab select-none border border-[var(--border-light)] bg-[var(--fill-tsp-white-light)]/70 active:cursor-grabbing"),children:[s.jsx(nx,{className:"h-4 w-4 shrink-0 opacity-70"}),s.jsx("span",{className:"truncate",children:E("history")})]}),s.jsx("div",{className:"h-7 w-7","aria-hidden":!0})]}),s.jsx("div",{className:"px-3 pb-2",children:s.jsxs("button",{type:"button",onClick:o,disabled:h,className:z("flex h-9 w-full items-center justify-center gap-2 rounded-xl","bg-[var(--Button-primary-white)] text-sm font-medium text-[var(--text-primary)]","shadow-[0px_8px_28px_-24px_var(--shadow-L)] hover:bg-white/20","transition-[transform,box-shadow] duration-150 ease-out hover:-translate-y-[0.5px]",h&&"cursor-not-allowed opacity-50"),children:[s.jsx(Gb,{className:"h-4 w-4 text-[var(--icon-primary)]"}),s.jsx("span",{className:"truncate",children:E("new_chat")}),s.jsxs("span",{className:"flex items-center gap-1 text-[var(--text-tertiary)]",children:[s.jsx("span",{className:"flex h-5 min-w-5 items-center justify-center rounded-[6px] border border-[var(--border-light)] bg-[var(--fill-tsp-white-light)]",children:s.jsx(Lv,{size:14})}),s.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-[6px] border border-[var(--border-light)] bg-[var(--fill-tsp-white-light)] text-sm",children:"K"})]})]})}),t.length>0?s.jsx("div",{className:"ai-manus-scrollbar flex flex-1 flex-col overflow-y-auto pb-5",children:t.map(ae=>s.jsx(rN,{session:ae,active:ae.session_id===n,highlight:ae.session_id===r,pinned:U.has(ae.session_id),displayTitle:_?.[ae.session_id],onSelect:i,onDelete:u,onTogglePin:d,onRename:f,onShare:p,readOnly:h},ae.session_id))}):s.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-3 text-[var(--text-tertiary)]",children:[s.jsx(zv,{size:36}),s.jsx("span",{className:"text-sm font-medium",children:E("create_chat_to_get_started")})]})]})]})})}):null}function Ch({sessionId:e,toolContent:t,live:n,realTime:r,isShare:a,projectId:i,executionTarget:o,cliServerId:u,readOnly:d,active:f,viewMode:p,onViewModeChange:h,onHide:y,onJumpToRealTime:g,hideClose:T}){const{t:w}=nr("ai_manus"),_=c.useMemo(()=>Qd(t),[t]),b=c.useMemo(()=>$g(t),[t]),E=_.view,R=_.icon,A=_.category==="shell",C=p==="terminal",M=A&&C,U=c.useMemo(()=>o==="cli"?u?`CLI ${u.slice(0,6)}`:"CLI":o==="sandbox"?"Sandbox":"Runtime",[u,o]),Q=t.status==="calling"?w("running"):w("succeeded"),ae=_.category==="file",ye=_.functionArg?`${_.function}: ${_.functionArg}`:_.function,V=ae?`${b} ${ye}`:ye,[W,Z]=c.useState(!1),Se=c.useRef(null),$e=c.useMemo(()=>{const G=t.args;return typeof G?.id=="string"?G.id:typeof t.content?.session_id=="string"?t.content.session_id:typeof t.content?.shell_session_id=="string"?t.content.shell_session_id:""},[t]),Ne=o==="sandbox"?"Terminal Sandbox (view-only)":o==="cli"?"Terminal CLI (interactive)":"Terminal Ready";return c.useEffect(()=>{if(!W)return;const G=J=>{const $=J.target;!$||!Se.current||Se.current.contains($)||Z(!1)};return window.addEventListener("mousedown",G),()=>window.removeEventListener("mousedown",G)},[W]),s.jsxs("div",{className:z("ai-manus-tool-panel flex h-full min-w-0 w-full flex-col overflow-hidden rounded-[10px] border border-[var(--border-light)] shadow-[0px_0px_1px_0px_var(--shadow-XS),0px_16px_32px_-24px_var(--shadow-S)]",M&&"is-terminal"),children:[s.jsxs("div",{className:"ai-manus-tool-header relative flex items-center gap-2 border-b border-[var(--border-light)] px-4 py-2",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[s.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-[8px] border border-[var(--border-light)] bg-[var(--fill-tsp-gray-main)]",children:s.jsx(R,{className:"h-4 w-4 text-[var(--icon-primary)]"})}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-semibold text-[var(--text-primary)]",children:M?"Terminal":"Tool Panel"}),M?s.jsxs("div",{className:"mt-0.5 flex items-center gap-2 text-[10px] text-[var(--text-tertiary)]",children:[s.jsx("span",{className:"truncate",children:U}),s.jsx("span",{className:"text-[10px] text-[var(--text-disable)]",children:"•"}),s.jsx("span",{className:"truncate",children:Q})]}):null]})]}),s.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[M?s.jsxs("div",{ref:Se,className:"relative",children:[s.jsx("button",{type:"button",onClick:()=>Z(G=>!G),className:z("inline-flex h-6 w-6 items-center justify-center rounded-md border border-transparent transition",W?"border-[var(--border-light)] bg-[var(--fill-tsp-white-light)] text-[var(--icon-primary)]":"text-[var(--icon-tertiary)] hover:bg-[var(--fill-tsp-gray-main)]"),"aria-label":w("about_terminal_session"),title:w("about_terminal_session"),children:s.jsx(Qb,{className:"h-4 w-4"})}),W?s.jsxs("div",{className:"ds-tool-about-panel",children:[s.jsx("div",{className:"text-[12px] font-semibold text-[var(--text-primary)]",children:Ne}),s.jsxs("div",{className:"mt-1 text-[10px] text-[var(--text-tertiary)]",children:[w("session"),": ",$e||w("unknown")]}),s.jsxs("div",{className:"text-[10px] text-[var(--text-tertiary)]",children:[w("tool_call"),": ",t.tool_call_id||w("unknown")]})]}):null]}):null,h?s.jsx("button",{type:"button",onClick:()=>{if(C){h("tool");return}h("terminal")},"aria-pressed":C,"aria-label":w(C?"show_tool_output":"open_terminal"),title:w(C?"show_tool_output":"open_terminal"),className:z("inline-flex h-6 w-6 items-center justify-center rounded-md border border-transparent transition",C?"border-[var(--border-light)] bg-[var(--fill-tsp-white-light)] text-[var(--icon-primary)]":"text-[var(--icon-tertiary)] hover:bg-[var(--fill-tsp-gray-main)]"),children:s.jsx(Vl,{className:"h-4 w-4"})}):null,T?null:s.jsx("button",{type:"button",onClick:y,className:"inline-flex h-6 w-6 items-center justify-center rounded-md hover:bg-[var(--fill-tsp-gray-main)]",children:s.jsx(Uv,{className:"h-4 w-4 text-[var(--icon-tertiary)]"})})]})]}),M?null:s.jsxs("div",{className:"ai-manus-tool-meta flex items-center justify-between gap-3 px-4 py-2",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2 text-[11px] text-[var(--text-tertiary)]",children:[s.jsx("span",{className:"truncate text-[12px] font-medium text-[var(--text-secondary)]",children:ae?b:_.name}),s.jsx("span",{className:"text-[10px] text-[var(--text-disable)]",children:"•"}),s.jsx("span",{className:"truncate",children:U}),s.jsx("span",{className:"text-[10px] text-[var(--text-disable)]",children:"•"}),s.jsx("span",{className:"truncate",children:Q})]}),t.status==="calling"?s.jsx(oc,{text:w("running"),compact:!0}):null]}),s.jsx("div",{className:"ai-manus-tool-view flex-1 min-h-0 overflow-hidden rounded-[8px]",children:E?s.jsx(E,{sessionId:e,toolContent:t,live:n,isShare:a,projectId:i,executionTarget:o,cliServerId:u,readOnly:d,active:f,panelMode:p}):s.jsx("div",{className:"flex h-full items-center justify-center text-sm text-[var(--text-tertiary)]",children:w("tool_output_unavailable")})}),M?null:s.jsxs("div",{className:"ai-manus-tool-footer flex items-center gap-2 border-t border-[var(--border-light)] px-4 py-2 text-[11px] text-[var(--text-tertiary)]",children:[s.jsx("span",{className:"shrink-0 text-[11px] text-[var(--text-disable)]",children:w("task")}),s.jsx("span",{className:"truncate text-[11px] text-[var(--text-secondary)]",title:V,children:V})]}),r?null:s.jsx("div",{className:"relative flex w-full items-center gap-2 px-4 pb-4 pt-3",children:s.jsxs("button",{type:"button",onClick:g,className:"absolute left-1/2 top-[-44px] flex h-10 -translate-x-1/2 items-center gap-1 rounded-[10px] border border-[var(--border-main)] bg-[var(--background-white-main)] px-3 shadow-[0px_5px_16px_0px_var(--shadow-S),0px_0px_1.25px_0px_var(--shadow-S)] hover:bg-[var(--background-gray-main)]",children:[s.jsx(Xb,{size:16}),s.jsx("span",{className:"text-sm font-medium text-[var(--text-primary)]",children:w("jump_to_live")})]})})]})}function Eh({open:e,toolContent:t,live:n,sessionId:r,realTime:a,isShare:i,projectId:o,executionTarget:u,cliServerId:d,readOnly:f,viewMode:p,onViewModeChange:h,onClose:y,onJumpToRealTime:g,variant:T="floating",hideClose:w}){return c.useEffect(()=>{if(!e||w)return;const _=b=>{b.key==="Escape"&&y()};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[w,y,e]),!e||!t?null:T==="docked"?s.jsx(Ch,{sessionId:r,toolContent:t,live:n,realTime:a,isShare:i,projectId:o,executionTarget:u,cliServerId:d,readOnly:f,active:e,viewMode:p,onViewModeChange:h,onHide:y,onJumpToRealTime:g,hideClose:w}):s.jsxs("div",{className:"fixed inset-0 z-50 sm:inset-auto sm:bottom-6 sm:right-4 sm:top-[72px] sm:w-[min(540px,45vw)]",children:[s.jsx("div",{className:"absolute inset-0 bg-[var(--background-mask)] sm:hidden",role:"button",tabIndex:-1,onClick:y,onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&y()}}),s.jsx("div",{className:"relative h-full w-full p-4 sm:p-0",children:s.jsx(Ch,{sessionId:r,toolContent:t,live:n,realTime:a,isShare:i,projectId:o,executionTarget:u,cliServerId:d,readOnly:f,active:e,viewMode:p,onViewModeChange:h,onHide:y,onJumpToRealTime:g,hideClose:w})})]})}function cd(e,t){switch(e){case"pdf":return t?"border-[#8FA3B8]/45 bg-[#8FA3B8]/18 text-[#495f75]":"border-[#8FA3B8]/32 bg-[#8FA3B8]/12 text-[#55697d]";case"latex":return t?"border-[#A99EBE]/45 bg-[#A99EBE]/18 text-[#5a5170]":"border-[#A99EBE]/32 bg-[#A99EBE]/12 text-[#665d7b]";case"markdown":return t?"border-[#9CB0A7]/45 bg-[#9CB0A7]/18 text-[#4e625b]":"border-[#9CB0A7]/32 bg-[#9CB0A7]/12 text-[#5b6f68]";case"html":return t?"border-[#B49B88]/45 bg-[#B49B88]/18 text-[#725d50]":"border-[#B49B88]/32 bg-[#B49B88]/12 text-[#7d695d]";case"attention":return t?"border-[#C1A2A0]/48 bg-[#C1A2A0]/18 text-[#7a5957]":"border-[#C1A2A0]/34 bg-[#C1A2A0]/12 text-[#8b6766]";default:return t?"border-black/12 bg-black/[0.06] text-[var(--text-secondary)] dark:border-white/14 dark:bg-white/[0.08]":"border-black/10 bg-black/[0.04] text-[var(--text-secondary)] dark:border-white/10 dark:bg-white/[0.05]"}}function iN(e,t){switch(e){case"pdf":return t("context_kind_pdf");case"markdown":return t("context_kind_markdown");case"mdx":return t("context_kind_mdx");case"html":return t("context_kind_html");case"latex":return t("context_kind_latex");case"notebook":return t("context_kind_notebook");case"lab":return t("context_kind_lab");case"cli":return t("context_kind_cli");default:return t("context_kind_file")}}function Rh(e,t){switch(e){case"rendered":return t("context_mode_rendered");case"source":return t("context_mode_source");case"preview":return t("context_mode_preview");case"snapshot":return t("context_mode_snapshot",void 0,"Snapshot");case"diff":return t("context_mode_diff",void 0,"Diff");default:return null}}function Ih(e,t,n){if(e?.trim())return e.trim();if(t?.trim()){const r=t.split("/").filter(Boolean);return r[r.length-1]||t}return n}function oN({card:e}){const{t}=nr("ai_manus");return s.jsxs("div",{"data-testid":e.testId,className:z("rounded-[20px] border px-3.5 py-3","bg-[linear-gradient(180deg,rgba(252,251,249,0.96),rgba(246,243,240,0.92))]","shadow-[0_16px_36px_-30px_rgba(45,42,38,0.34)] backdrop-blur-[6px]",cd(e.tone,e.isActive)),children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:z("inline-flex h-6 items-center rounded-full border px-2.5 text-[10px] font-semibold tracking-[0.01em]",cd(e.tone,e.isActive)),children:e.typeLabel}),e.resourceLabel?s.jsx("span",{className:"truncate text-[12px] font-semibold text-[var(--text-primary)]",children:e.resourceLabel}):null,e.locationLabel?s.jsx("span",{className:"inline-flex h-6 items-center rounded-full border border-black/10 bg-black/[0.04] px-2.5 text-[10px] font-medium text-[var(--text-tertiary)] dark:border-white/10 dark:bg-white/[0.05]",children:e.locationLabel}):null]}),e.resourcePath?s.jsx("div",{className:"mt-1 truncate font-mono text-[10px] text-[var(--text-quaternary)]",children:e.resourcePath}):null]}),e.onRemove?s.jsx("button",{type:"button",onClick:e.onRemove,className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-[var(--text-tertiary)] transition-colors hover:bg-black/5 hover:text-[var(--text-primary)] dark:hover:bg-white/[0.06]","aria-label":t("reference_remove"),title:t("reference_remove"),children:s.jsx(fo,{className:"h-3.5 w-3.5"})}):null]}),s.jsx("div",{className:"mt-2.5 line-clamp-4 text-[12px] leading-5 text-[var(--text-primary)]",children:e.body}),e.detail?s.jsx("div",{className:"mt-1 text-[10px] text-[var(--text-tertiary)]",children:e.detail}):null,s.jsxs("div",{className:"mt-2 flex items-center gap-1.5 text-[10px] font-medium text-[var(--text-secondary)]",children:[s.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-current/60"}),s.jsx("span",{children:e.helper})]})]})}function lN({contentKind:e,documentMode:t,openTabCount:n,references:r,activeReferenceId:a,focusedIssue:i,onRemoveReference:o}){const{t:u}=nr("ai_manus"),d=rc(),f=c.useMemo(()=>{const _=[...r];return _.sort((b,E)=>b.id===a?-1:E.id===a?1:new Date(E.createdAt).getTime()-new Date(b.createdAt).getTime()),_},[a,r]),p=c.useMemo(()=>f.slice(0,i?2:3),[i,f]),h=c.useMemo(()=>{const _=[];return i&&_.push({id:`issue-${i.tabId}-${i.line||i.createdAt}`,testId:"copilot-context-card-latex-error",typeLabel:u("context_card_latex_error"),resourceLabel:Ih(i.resourceName,i.resourcePath,u("context_kind_file")),resourcePath:i.resourcePath,locationLabel:typeof i.line=="number"&&i.line>0?u("context_card_line",{line:i.line}):void 0,body:i.message,detail:i.excerpt?.trim()||u("context_issue_helper"),helper:u("context_included_next_message"),tone:"attention",isActive:!0}),p.forEach(b=>{const E=b.markdownExcerpt?.trim()||b.selectedText?.trim()||"";_.push({id:b.id,testId:"copilot-context-card-pdf",typeLabel:u("context_card_pdf_quote"),resourceLabel:Ih(b.resourceName,b.resourcePath,u("context_kind_pdf")),resourcePath:b.resourcePath,locationLabel:typeof b.pageNumber=="number"&&b.pageNumber>0?u("reference_page",{page:b.pageNumber}):void 0,body:E,detail:b.excerptStatus==="loading"?u("reference_loading_excerpt"):b.markdownExcerpt&&b.markdownExcerpt!==b.selectedText?u("reference_markdown_excerpt"):u("context_quote_helper"),helper:u("context_included_next_message"),tone:"pdf",isActive:b.id===a,onRemove:()=>o(b.id)})}),_},[a,i,o,u,p]);if(!h.length)return null;const y=Math.max(0,r.length-p.length),g=[{id:"kind",label:iN(e,u),tone:Yb(e)},...Rh(t,u)?[{id:"mode",label:Rh(t,u),tone:"neutral"}]:[],{id:"tabs",label:u("context_open_tabs",{count:n}),tone:"neutral"},{id:"quotes",label:u("context_quotes",{count:r.length}),tone:"neutral"},...i?[{id:"focused-issue",label:u("context_focused_issue"),tone:"attention"}]:[]],T=d?{}:{initial:{opacity:0,y:6},animate:{opacity:1,y:0},transition:{duration:.2,ease:[.22,1,.36,1]}},w=d?{}:{initial:{opacity:0,y:8,scale:.99},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-6,scale:.99},transition:{duration:.18,ease:[.22,1,.36,1]}};return s.jsxs(ks.section,{"data-testid":"copilot-context-tray",className:"mb-3 space-y-2.5",...T,children:[s.jsxs("div",{"data-testid":"copilot-context-summary",className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"inline-flex items-center gap-1.5 pr-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-[var(--text-tertiary)]",children:[s.jsx(mv,{className:"h-3.5 w-3.5"}),u("context_tray_title")]}),g.map(_=>s.jsx("span",{className:z("inline-flex h-6 items-center rounded-full border px-2.5 text-[10px] font-medium",cd(_.tone)),children:_.label},_.id)),y>0?s.jsx("span",{className:"inline-flex h-6 items-center rounded-full border border-black/8 bg-black/[0.03] px-2.5 text-[10px] font-medium text-[var(--text-tertiary)] dark:border-white/10 dark:bg-white/[0.04]",children:u("context_more_items",{count:y})}):null]}),s.jsx("div",{className:"space-y-2",children:s.jsx(Zb,{initial:!1,children:h.map(_=>s.jsx(ks.div,{layout:!0,...w,children:s.jsx(oN,{card:_})},_.id))})})]})}const Mh=120,cN=Number.MAX_SAFE_INTEGER,uN=120,dN=120,fN=50,pN=6,mN=1024,hN=40,Rl=26,Lu=62,xN=8e3,gN=6e4,Lh=8e3,yN=26,Pu=64,Ph="__thinking__",Dh="__load_full_history__",bN="CLI server offline. Please ensure the CLI is running.",Vg=c.memo(function({index:t,style:n,data:r}){const a=c.useRef(null),{items:i,render:o,setSize:u,messageMaxWidthClass:d}=r,f=i[t];return c.useEffect(()=>{const p=a.current;if(!p)return;const h=()=>u(t,p.getBoundingClientRect().height);if(h(),typeof ResizeObserver>"u")return;const y=new ResizeObserver(h);return y.observe(p),()=>y.disconnect()},[t,u,f.id]),s.jsx("div",{style:n,children:s.jsx("div",{ref:a,className:z("mx-auto w-full pb-3",d),children:o(f)})})});Vg.displayName="VirtualTurnRow";const $h=e=>{const t=e.toLowerCase();return t.includes("cli server")&&(t.includes("not connected")||t.includes("offline"))||t.includes("cli_server_not_connected")||t.includes("cli_server_offline")?bN:e};function Du(e,t,n){const r=t?.trim();if(r)return`mcp-status-${r}`;const a=e?.trim();return a?`mcp-status-${a}`:typeof n=="number"&&!Number.isNaN(n)?`mcp-status-${n}`:`mcp-status-${_n("status")}`}const vN=new Set(["recovery","wait","title","done","attachments","plan","step","receipt","status"]),Fh=[{title:"Plan",icon:sc},{title:"Terminal",icon:Vl},{title:"Sessions",icon:Bu}],zh=["Hello, {name}","{name} is thinking...","Welcome back, {name}","Good to see you, {name}","Ready when you are, {name}","Let's explore, {name}","What should we build, {name}?","Your lab is ready, {name}","Tell me your idea, {name}","New task? I am listening, {name}"],yo={pinned:[],renamed:{}};function _N(e){if(!e||typeof e!="object")return yo;const t=e,n=Array.isArray(t.pinned)&&t.pinned.length>0?t.pinned.filter(a=>typeof a=="string"&&a.trim()):[],r={};return t.renamed&&typeof t.renamed=="object"&&Object.entries(t.renamed).forEach(([a,i])=>{if(typeof i!="string")return;const o=i.trim();o&&(r[a]=o)}),{pinned:Array.from(new Set(n)),renamed:r}}function Oh(e){if(!e||typeof window>"u")return yo;const t=window.localStorage.getItem(e);if(!t)return yo;try{return _N(JSON.parse(t))}catch{return yo}}function wN(e,t){!e||typeof window>"u"||window.localStorage.setItem(e,JSON.stringify(t))}function Bh(){const e=Math.floor(Math.random()*zh.length);return zh[e]}const SN=dx(()=>fx(()=>import("./VNCViewer-BoLGLnHz.js"),__vite__mapDeps([7,1,2,3,4,5,8,9,10,11,12,13,14,15,16,17,18])).then(e=>e.VNCViewer),{loading:()=>s.jsx("div",{className:"flex h-full w-full items-center justify-center text-sm text-[var(--text-tertiary)]",children:"Loading sandbox view..."})});function kN(e){return e?e<1e12?e*1e3:e:0}function Gs(e){return e?e.trim().replace(/\\/g,"/").replace(/\/+$/,""):""}function Kg(e,t){if(!e)return null;for(const n of t){const r=e[n];if(typeof r!="string")continue;const a=r.trim();if(a)return a}return null}function $u(e){return Kg(e,["fileId","file_id","openFileId","mainFileId"])}function Fu(e){return Kg(e,["filePath","file_path","path","resourcePath"])}function Il(e){const t=Gs(e??"");return!!t&&t!=="/FILES"&&t!=="/CLIFILES"}function Vs(e){return e&&(e==="pending"||e==="running"||e==="waiting"||e==="completed"||e==="failed")?e:null}function ti(e){return e==="running"}function Ml(e){return ti(e)||e==="waiting"}function Ll(e){const t=e.trim().toLowerCase();if(!t)return"";if(!t.startsWith("mcp__"))return t;const n=t.split("__");return n[n.length-1]||t}function NN(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e!==0;if(typeof e=="string"){const t=e.trim().toLowerCase();if(["true","1","yes","y"].includes(t))return!0;if(["false","0","no","n"].includes(t))return!1}return!1}function qh(e){if(Array.isArray(e))return e.map(n=>String(n).trim()).filter(n=>n.length>0);if(typeof e=="string"){const n=e.trim();if(!n)return[];try{const r=JSON.parse(n);if(Array.isArray(r))return r.map(a=>String(a).trim()).filter(a=>a.length>0)}catch{}return n.includes(",")?n.split(",").map(r=>r.trim()).filter(r=>r.length>0):[n]}if(e==null)return[];const t=String(e).trim();return t?[t]:[]}function jN(e){if(!Array.isArray(e))return[];const t=[];return e.forEach((n,r)=>{if(typeof n=="string"||typeof n=="number"){const f=String(n).trim();if(!f)return;t.push({id:String(r+1),label:f});return}if(!n||typeof n!="object")return;const a=n,i=a.id??a.value??a.name??a.label??r+1,o=a.label??a.name??a.value??a.id??i,u=String(i??r+1).trim(),d=String(o??u).trim();!u||!d||t.push({id:u,label:d})}),t}function TN(e,t){const n=Array.isArray(e)?e:e!=null?[e]:[],r=new Set(t.map(f=>f.id)),a=new Map(t.map(f=>[f.label.toLowerCase(),f.id])),i=new Set,o=[];n.forEach(f=>{const p=typeof f=="string"?f.trim():String(f).trim();if(!p)return;if(r.has(p)){i.has(p)||(i.add(p),o.push(p));return}const h=Number(p);if(!Number.isNaN(h)&&Number.isFinite(h)){const g=Math.max(0,Math.floor(h)-1),T=t[g];T&&!i.has(T.id)&&(i.add(T.id),o.push(T.id));return}const y=a.get(p.toLowerCase());y&&!i.has(y)&&(i.add(y),o.push(y))});const u=new Map(t.map(f=>[f.id,f.label])),d=o.map(f=>u.get(f)).filter(f=>!!f);return{selections:o,selectedLabels:d}}function AN(e){const t=e.data;return typeof t.timestamp=="number"&&Number.isFinite(t.timestamp)?t.timestamp:typeof t.created_at=="string"&&t.created_at?Cs(t.created_at):null}function io(e){const t=e.map((a,i)=>({event:a,index:i,seq:xr(a),timestamp:AN(a)})),n=t.some(a=>a.seq!=null),r=t.some(a=>a.timestamp!=null);return!n&&!r?e:(t.sort((a,i)=>{if(n){if(a.seq!=null&&i.seq!=null&&a.seq!==i.seq)return a.seq-i.seq;if(a.seq!=null&&i.seq==null)return-1;if(a.seq==null&&i.seq!=null)return 1}return a.timestamp!=null&&i.timestamp!=null&&a.timestamp!==i.timestamp?a.timestamp-i.timestamp:a.timestamp!=null&&i.timestamp==null?-1:a.timestamp==null&&i.timestamp!=null?1:a.index-i.index}),t.map(a=>a.event))}function Uh(e){return e==="summary"?"summary":"full"}const CN=new Set(["pending","running","completed","failed","blocked","paused"]);function EN(e){if(typeof e=="string"){const t=e.trim().toLowerCase();if(CN.has(t))return t}return"pending"}function RN(e,t){return`${e}:${t}`}function Wh(e,t,n){const r=typeof n=="string"?n.trim():"";return r?`stream:${r}`:`reasoning:${RN(e,t)}`}function Gg(e){const t=e.args&&typeof e.args=="object"&&!Array.isArray(e.args)?e.args:{},n=e.content&&typeof e.content=="object"&&!Array.isArray(e.content)?e.content:{},r=typeof t.file_id=="string"&&t.file_id||typeof t.fileId=="string"&&t.fileId||typeof n.file_id=="string"&&n.file_id||typeof n.fileId=="string"&&n.fileId||void 0,a=typeof t.file=="string"&&t.file||typeof t.file_path=="string"&&t.file_path||typeof t.path=="string"&&t.path||typeof t.filePath=="string"&&t.filePath||typeof n.file=="string"&&n.file||typeof n.file_path=="string"&&n.file_path||typeof n.filePath=="string"&&n.filePath||void 0,i=typeof t.file_name=="string"&&t.file_name||typeof t.fileName=="string"&&t.fileName||typeof n.file_name=="string"&&n.file_name||typeof n.fileName=="string"&&n.fileName||void 0,o=typeof n.diff=="object"&&n.diff?n.diff:void 0,u=typeof n.changeType=="string"?n.changeType:void 0;return{fileId:r,filePath:a,fileName:i,content:n,diff:o,changeType:u}}function zu(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()){const t=Number(e);if(Number.isFinite(t))return t}}function IN(e){const t=typeof e.function=="string"?e.function:"",n=t.startsWith("rebuttal_pdf_")?`pdf_${t.slice(13)}`:t;if(!n.startsWith("pdf_"))return null;const r=e.args&&typeof e.args=="object"&&!Array.isArray(e.args)?e.args:{},{fileId:a,filePath:i,fileName:o}=Gg(e);if(!a&&!i&&!o)return null;const u=zu(r.page)??zu(r.page_number)??zu(r.pageNumber),d=u&&u>0?Math.floor(u):void 0,f=typeof r.annotation_id=="string"?r.annotation_id:typeof r.annotationId=="string"?r.annotationId:void 0;return{fileId:a,filePath:i,fileName:o,page:d,annotationId:f,mode:n==="pdf_guide"?"guide":n==="pdf_annotate"?"annotate":void 0}}function MN(e,t){if(t!=="called")return[];const n=typeof e.function=="string"?e.function:"",{fileId:r,filePath:a,fileName:i,content:o,diff:u,changeType:d}=Gg(e);if(!r&&!a)return[];if(n==="file_read"||n==="file_info")return[{name:"file:read",data:{fileId:r,filePath:a,fileName:i}}];if(n==="file_write"||n==="file_patch"){const f=typeof o?.created=="boolean"?o.created:void 0,p=d??(f?"create":"update");return[{name:"file:write",data:{fileId:r,filePath:a,fileName:i,...f!==void 0?{created:f}:{},...p?{changeType:p}:{},...u?{diff:u}:{}}}]}return n==="file_delete"?[{name:"file:delete",data:{fileId:r,filePath:a,fileName:i,changeType:d??"delete",...u?{diff:u}:{}}}]:[]}function Hh(e){if((typeof e.function=="string"?e.function.toLowerCase():"")!=="file_write")return!1;const n=e.args&&typeof e.args=="object"&&!Array.isArray(e.args)?e.args:{},r=n.source_path??n.sourcePath;return typeof r=="string"&&r.trim().length>0}function LN(e,t){const n=e.args&&typeof e.args=="object"&&!Array.isArray(e.args)?e.args:{},r=typeof n.patch=="string"?n.patch:typeof e.content?.patch=="string"?e.content.patch:"";if(!r.trim())return null;const a=Tg(r),i=typeof n.target_path=="string"?n.target_path:typeof n.targetPath=="string"?n.targetPath:void 0,o=typeof n.rationale=="string"?n.rationale:void 0;return{timestamp:Cs(e.timestamp),metadata:e.metadata,patch:r,files:a,status:"pending",toolCallId:t,targetPath:i,rationale:o}}function PN(e,t,n){const r=Array.isArray(e?.changes)?e.changes:[],a=dS(r);if(!a.trim())return null;const i=Tg(a);if(i.length===0)return null;const o=[];typeof e.title=="string"&&e.title.trim()&&o.push(e.title.trim()),Array.isArray(e.explanations)&&e.explanations.forEach(d=>{typeof d=="string"&&d.trim()&&o.push(d.trim())});const u=o.length>0?o.join(" · "):void 0;return{timestamp:t,patch:a,files:i,status:"pending",toolCallId:n,rationale:u}}const ql=new Set(["message","tool","step","status","reasoning","plan","recovery","error","done","title","wait","attachments","receipt"]);function Vh(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.event=="string"?t.event:typeof t.event_type=="string"?t.event_type:typeof t.type=="string"?t.type:null;if(!n||!ql.has(n))return null;let r=t.data??t.event_json??t.payload??{};if(typeof r=="string")try{r=JSON.parse(r)}catch{r={}}(!r||typeof r!="object"||Array.isArray(r))&&(r={});const a={...r};return!("event_id"in a)&&typeof t.event_id=="string"&&(a.event_id=t.event_id),!("timestamp"in a)&&t.timestamp!=null&&(a.timestamp=t.timestamp),!("seq"in a)&&typeof t.seq=="number"&&(a.seq=t.seq),!("created_at"in a)&&t.created_at!=null&&(a.created_at=String(t.created_at)),{event:n,data:a}}function Kh(e){const t=Vh(e);if(t)return t;if(typeof e=="string")try{const i=JSON.parse(e);return Vh(i)}catch{return null}if(!e||typeof e!="object")return null;const n=e,r=typeof n.event=="string"?n.event:typeof n.event_type=="string"?n.event_type:typeof n.type=="string"?n.type:null,a=n.data??n.event_json??n.payload??null;if(r&&ql.has(r)&&a&&typeof a=="object"&&!Array.isArray(a))return{event:r,data:a};if(a&&typeof a=="string")try{const i=JSON.parse(a);if(i&&typeof i=="object"&&!Array.isArray(i)&&r&&ql.has(r))return{event:r,data:i}}catch{return null}if(n.data&&typeof n.data=="object"&&!Array.isArray(n.data)){const i=n.data,o=typeof i.event=="string"?i.event:typeof i.event_type=="string"?i.event_type:typeof i.type=="string"?i.type:null,u=i.data??i.event_json??i.payload??null;if(o&&ql.has(o)&&u&&typeof u=="object"&&!Array.isArray(u))return{event:o,data:u}}return null}const DN=["surface","reply_to_surface","execution_target","cli_server_id","lab_mode","quest_id","quest_node_id"],Gh=e=>{const t=new Map,n=new Map,r=Array.isArray(e)?e:[];return r.forEach(a=>{a?.agent_instance_id&&t.set(String(a.agent_instance_id),a),a?.agent_id&&n.set(String(a.agent_id),a)}),{byInstanceId:t,byAgentId:n,fallback:r.length===1?r[0]:null}},Qh=(e,t,n)=>{if(!e?.data||typeof e.data!="object")return e;const r={...e.data},a=r.metadata,i=a&&typeof a=="object"&&!Array.isArray(a)?{...a}:{},o=typeof r.role=="string"?String(r.role):"",u=typeof i.sender_type=="string"?i.sender_type.toLowerCase():"",d=e.event==="message"||e.event==="attachments",f=o.toLowerCase(),p=u==="agent"||!!(i.agent_id||i.agent_instance_id)||(d?f==="assistant":!0);if(t&&typeof t=="object"&&DN.forEach(h=>{if(i[h]!=null)return;const y=t[h];y!=null&&(i[h]=y)}),p&&n){const h=typeof i.agent_instance_id=="string"?i.agent_instance_id:null,y=typeof i.agent_id=="string"?i.agent_id:null,g=(h?n.byInstanceId.get(h):null)||(y?n.byAgentId.get(y):null)||n.fallback;g&&(i.agent_instance_id==null&&g.agent_instance_id&&(i.agent_instance_id=g.agent_instance_id),i.agent_id==null&&g.agent_id&&(i.agent_id=g.agent_id),i.agent_label==null&&g.agent_label&&(i.agent_label=g.agent_label),i.agent_display_name==null&&g.agent_display_name&&(i.agent_display_name=g.agent_display_name),i.agent_logo==null&&g.agent_logo&&(i.agent_logo=g.agent_logo),i.agent_avatar_color==null&&g.agent_avatar_color&&(i.agent_avatar_color=g.agent_avatar_color),i.agent_role==null&&g.agent_role&&(i.agent_role=g.agent_role),i.agent_source==null&&g.agent_source&&(i.agent_source=g.agent_source),i.agent_engine==null&&g.agent_engine&&(i.agent_engine=g.agent_engine))}return Object.keys(i).length>0?r.metadata=i:delete r.metadata,{...e,data:r}};function Xh(e){let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{t=null}return Array.isArray(t)?t.map(n=>Qg(n)).filter(n=>!!n):[]}function Qg(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n=typeof t.event_id=="string"&&t.event_id?t.event_id:_n("plan"),r=$N(t.steps),a=FN(t.task_plan),i=r.length>0,o=!!a?.tasks?.length;return!i&&!o?null:{...t,event_id:n,steps:r,timestamp:Cs(t.timestamp),...a?{task_plan:a}:{}}}function $N(e){let t=e;return t&&typeof t=="object"&&!Array.isArray(t)&&(t=Object.values(t)),Array.isArray(t)?t.map((n,r)=>{if(!n)return null;if(typeof n=="string"){const f=n.trim();return f?{id:`step-${r+1}`,status:"pending",description:f}:null}if(typeof n!="object"||Array.isArray(n))return null;const a=n,o=(typeof a.description=="string"?a.description:typeof a.task=="string"?a.task:typeof a.title=="string"?a.title:typeof a.label=="string"?a.label:typeof a.text=="string"?a.text:"").trim();if(!o)return null;const u=typeof a.id=="string"&&a.id.trim()?a.id.trim():typeof a.step_id=="string"&&a.step_id.trim()?a.step_id.trim():`step-${r+1}`,d=EN(a.status);return{...a,id:u,status:d,description:o}}).filter(n=>!!n):[]}function FN(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e;if(!t)return;let n=t.tasks;if(n&&typeof n=="object"&&!Array.isArray(n)&&(n=Object.values(n)),typeof n=="string")try{n=JSON.parse(n)}catch{n=[]}const a=(Array.isArray(n)?n:[]).map(i=>{if(!i||typeof i!="object")return null;const o=i,d=(typeof o.task=="string"?o.task:typeof o.title=="string"?o.title:typeof o.name=="string"?o.name:"").trim();if(!d)return null;const f=typeof o.change_reason=="string"?o.change_reason:typeof o.changeReason=="string"?o.changeReason:typeof o.reason=="string"?o.reason:"",p=typeof o.detail=="string"?o.detail:typeof o.description=="string"?o.description:typeof o.details=="string"?o.details:"",y=(Array.isArray(o.sub_tasks)?o.sub_tasks:Array.isArray(o.subtasks)?o.subtasks:Array.isArray(o.subTasks)?o.subTasks:[]).filter(g=>typeof g=="string"&&g.trim().length>0).map(g=>g.trim());return{...i,task:d,change_reason:f??"",detail:p??"",sub_tasks:y}}).filter(i=>!!(i&&typeof i.task=="string"));return{...t,tasks:a}}function Yh({mode:e,projectId:t,readOnly:n,visible:r,prefill:a,suggestions:i,suggestionsDisabled:o,onSuggestionSelect:u,onActionsChange:d,onMetaChange:f,openToolPanel:p,hideCopilotGreeting:h,embedded:y,toolPanelMountId:g,sessionListMountId:T,sessionListEnabled:w,deferSessionList:_,uiMode:b,historyMode:E,historyPanelId:R,historyOpenOverride:A,onHistoryOpenChange:C,mentionablesOverride:M,defaultAgentOverride:U,mentionsEnabledOverride:Q,enforcedMentionPrefix:ae,lockedMentionPrefix:ye,lockLeadingMentionSpace:V,messageMetadata:W,runtimeToggleEnabled:Z,composerMode:Se,composerFooter:$e,leadMessage:Ne,onUserSubmit:G,layoutPadding:J,busyOverride:$}){const{addToast:I}=px(),{t:O}=nr("ai_manus"),{openFileInTab:X}=Jb(),ne=nn(l=>l.findNode),ke=nn(l=>l.findNodeByPath),de=qu(l=>l.entries),Te=li(l=>l.tabs),Oe=li(l=>l.tabs.find(m=>m.id===l.activeTabId)),He=li(l=>l.setActiveTab),ut=fr(l=>l.tabState),oe=fr(l=>{if(!Oe?.id)return null;const m=l.activeReferenceByTabId[Oe.id];return m&&l.references[m]||null}),Ae=fr(l=>Oe?.id?(l.referencesByTabId[Oe.id]||[]).map(x=>l.references[x]).filter(x=>!!x):[]),Ce=fr(l=>l.activeIssueByTabId),ie=fr(l=>l.removeReference),Ee=Ur(l=>l.servers),fe=Ur(l=>l.loadServers),Fe=Ur(l=>l.refreshServers),We=Ur(l=>l.activeServerId),Me=Ur(l=>l.projectId),yt=Ur(l=>l.isLoading),bt=ev(l=>l.user),ct=c.useMemo(()=>Ee.filter(l=>l.status!=="offline"&&l.status!=="error"),[Ee]),wt=tv()?.get("copilotSession")??null,jt=c.useMemo(()=>typeof window>"u"?!1:window.localStorage.getItem("ds_debug_copilot")==="1",[]),Ye=b??e,ft=c.useId(),St=R??ft,Gt=(J??"default")==="flush",he=e==="welcome"&&Ye==="copilot"?"copilot":e,kt=he==="welcome"||he==="copilot",$t=Vn(l=>t?l.sessionIdsByProjectSurface[t]?.[he]??null:null),ht=Vn(l=>t?l.sessionIdsByProjectSurface[t]?.welcome??null:null),an=Vn(l=>t?l.sessionIdsByProjectSurface[t]?.copilot??null:null),At=Vn(l=>t?l.sessionIdsByProject[t]??null:null),fn=kt?$t??(he==="welcome"?null:ht)??At:$t,Ze=Vn(l=>l.setSessionIdForSurface),ot=Vn(l=>l.clearSessionIdForSurface),j=Vn(l=>l.setLastEventId),P=Vn(l=>t?l.executionTargetsByProject[t]??"sandbox":"sandbox"),B=Vn(l=>t?l.cliServerIdsByProject[t]??null:null),Le=c.useRef(P),Je=c.useRef(B),Re=Vn(l=>l.setExecutionTarget),Ft=Vn(l=>l.setCliServerId),at=Jp(l=>l.setAgentsForProject),Xt=Jp(l=>t?l.agentsByProject[t]??[]:[]),pt=c.useMemo(()=>Yd(M??Xt),[M,Xt]),pn=c.useMemo(()=>Xt.some(l=>{const m=l.source?.toLowerCase(),x=l.execution_target?.toLowerCase();return m==="cli"||x==="cli"}),[Xt]);c.useEffect(()=>{Le.current=P},[P]),c.useEffect(()=>{Je.current=B},[B]);const ln=c.useMemo(()=>typeof Q=="boolean"?Q:ct.length>0,[Q,ct.length]),Pe=c.useCallback(l=>{if(!t||!l)return;const m=typeof l.execution_target=="string"?l.execution_target.trim().toLowerCase():"",x=m==="cli"||m==="cli_server"?"cli":m==="sandbox"?"sandbox":"",S=(typeof l.cli_server_id=="string"?l.cli_server_id.trim():"")||null;if(x==="cli"){Re(t,"cli",S??void 0);return}if(x==="sandbox"){Re(t,"sandbox"),S&&Ft(t,S);return}S&&Ft(t,S)},[t,Ft,Re]),te=!!n,Yt=(w??!0)&&!_,Ct=E??"inline",mt=Yt&&(e==="welcome"||Ct==="overlay"),vt=mt&&Ct!=="overlay"&&e==="welcome",mn=mt&&Ct==="overlay",Gn=te||!t,Cn=t?`ds:ai-manus:tool-panel-size:${t}`:"ds:ai-manus:tool-panel-size",sn=t?`ds:ai-manus:session-preferences:${bt?.id??"anon"}:${t}:${he}`:null,ys=c.useMemo(()=>{if(P==="cli"&&B){const l=Ee.find(m=>m.id===B);return`CLI: ${l?.name||l?.hostname||B.slice(0,6)}`}return"Backend Sandbox"},[B,Ee,P]),Dn=c.useMemo(()=>{if(!W||typeof W!="object")return!1;const l=W;return!!(l.agent_instance_id||l.lab_mode||l.agent_source==="lab")},[W]),{sessions:Be,setSessions:Wt,reload:zt}=u0({projectId:t,enabled:mt,stream:!1}),we=c.useRef([]),[k,se]=c.useState(()=>Oh(sn)),[me,Nt]=c.useState([]),xe=c.useRef([]),lt=c.useRef(new Map),Mt=c.useRef(new Set),[En,Mn]=c.useState(null),[Is,en]=c.useState([]),[F,le]=c.useState("New Chat"),[De,Qe]=c.useState(null),[tt,it]=c.useState(""),[wn,Qn]=c.useState([]),[On,Ms]=c.useState(!1),[lc,Ro]=c.useState(0),ja=c.useRef(!1),gi=c.useRef(!1),Ls=c.useRef(null),[ve,Ie]=c.useState(!0),Pt=c.useRef(!0),[rn,Ut]=c.useState(!1),[Xn,Ns]=c.useState(!1),[js,yn]=c.useState(()=>e==="welcome"?"terminal":"tool"),[Yn,Ta]=c.useState(null),[bs,cc]=c.useState(hN),[tf,yi]=c.useState(null),[nf,bi]=c.useState(null),[sf,Io]=c.useState(0),Xr=c.useRef(null),[rf,af]=c.useState(0),[vi,of]=c.useState(!1),[lf,cn]=c.useState(null),[Aa,uc]=c.useState(null),Tr=c.useRef(null),Ca=c.useRef(null),[Ar,cs]=c.useState(!1),[cf,Mo]=c.useState(!1),[dc,bn]=c.useState(!1),[Lo,uf]=c.useState(null),Cr=c.useRef(null),Ea=c.useRef(null),fc=c.useRef(!1),df=c.useRef(null),ff=c.useRef(null),[Xg,pf]=c.useState(()=>typeof A=="boolean"?A:Ct==="overlay"||y?!1:e==="welcome"&&Yt),[pc,mf]=c.useState(!1),[Yg,Zg]=c.useState([]),[Jg,hf]=c.useState(!1),[mc,ey]=c.useState(!1),[xf,gf]=c.useState(null),[Sn,Ra]=c.useState(!1),Ps=c.useRef(!1),[ty,ny]=c.useState(()=>Bh()),[kn,us]=c.useState(null),[hc,xc]=c.useState(!1),[Ia,yf]=c.useState(null),[gc,yc]=c.useState(""),bf=c.useRef(null),q=kn?null:fn,sr=c.useRef(kn),Ma=c.useRef(null),Po=c.useRef(!1),vf=c.useRef(null),[Er,Yr]=c.useState(null),Ds=c.useRef(null),[Rr,Zr]=c.useState(null),$s=c.useRef(null),Do=c.useCallback(()=>{if(Lc.current){Lc.current();return}Vo.current?.focus()},[]),[sy,_f]=c.useState(!1),[wf,bc]=c.useState(""),Ir=c.useRef(!1),vc=c.useRef(null),hn=c.useRef(q),$o=c.useRef(null),La=c.useRef(null),Sf=c.useRef(!0),_i=typeof A=="boolean",vn=mt?_i?A:Xg:!1,Fs=c.useCallback(l=>{if(mt){if(_i){C?.(l);return}pf(l)}},[_i,mt,C]);c.useEffect(()=>{if(!sn){se(yo);return}se(Oh(sn))},[sn]),c.useEffect(()=>{wN(sn,k)},[k,sn]),c.useEffect(()=>{mt&&(!_i||typeof A!="boolean"||pf(A))},[_i,A,mt]);const Zn=r??!0,Xe=c.useCallback((l,m)=>{if(!jt)return;const x={projectId:t??null,mode:e,uiSurface:Ye,visible:Zn,sessionId:hn.current,draftSessionId:sr.current};if(m){console.info(`[AiManus][${l}]`,{...x,...m});return}console.info(`[AiManus][${l}]`,x)},[jt,Zn,e,t,Ye]),kf=c.useMemo(()=>typeof window>"u"?!1:window.localStorage.getItem("ds_debug_copilot")==="1",[]),wi=c.useCallback((l,m)=>{if(!kf)return;const x={projectId:t??null,mode:e,uiSurface:Ye,sessionId:hn.current};console.warn(`[AiManusTrace][${l}]`,m?{...x,...m}:x)},[e,t,kf,Ye]);c.useEffect(()=>{Xe("history:state",{open:vn,enabled:mt,overlay:mn,inline:vt})},[Xe,vn,mt,vt,mn]);const Si=c.useRef(null),Ln=c.useRef(null),Bn=c.useRef(null),Jr=c.useRef(null),rr=c.useRef(new Map),ds=c.useRef(new Set),Fo=c.useRef(new Map),zs=c.useRef(null),Pa=c.useRef(null),vs=c.useRef(null);c.useRef(new Map),c.useRef(new Set),c.useRef(new Set),c.useRef(null);const Mr=c.useRef(0),Nf=c.useRef(new Map),ry=c.useRef(new Map),ay=c.useRef(new Map),zo=c.useRef(null);c.useRef(new Set);const un=c.useRef(null),xn=c.useRef(null),[ea,Lr]=c.useState(null),Ts=c.useRef(new Map),Jn=c.useRef([]),Da=c.useRef([]),_c=c.useRef(new Set),ki=c.useRef(!1),jf=c.useRef(new Set),wc=c.useRef(new Set),Ni=c.useRef(new Set),ji=c.useRef(new Map),Ti=c.useRef(!1),Sc=c.useRef(null),Tf=c.useRef(new Set),Ht=c.useRef(!1),Os=c.useRef(null),Pr=c.useRef(null),kc=c.useRef(null),ta=c.useRef(null),Oo=c.useRef(!1),na=c.useRef(!1),ar=c.useRef(null),br=c.useRef(!1),Ai=c.useRef(null),Bs=c.useRef(null),[ir,Dr]=c.useState("center"),Nc=c.useRef(null),Ci=c.useRef(!1),Bo=c.useRef(null),Ei=c.useRef(null),qo=c.useRef(null),Af=c.useRef(null),Ri=c.useRef(null),Uo=c.useRef(new Map),sa=c.useRef(null),vr=c.useRef(null),[$a,iy]=c.useState(0),[jc,Cf]=c.useState(!1),[oy,Tc]=c.useState(!1),[Wo,Ac]=c.useState(null),[Ii,Ho]=c.useState(!1),[Ef,Cc]=c.useState(!1),Ec=c.useRef(!1),[Rc,Rf]=c.useState(!1),[ly,cy]=c.useState(!1),If=c.useRef(!1),[Mf,ra]=c.useState(!0),aa=c.useRef(!0),Ic=c.useRef(!1),Mc=c.useRef(null),Vo=c.useRef(null),Lc=c.useRef(null),Lf=c.useRef(null),Pc=c.useRef(null),[Dc,$c]=c.useState(null),[Fc,zc]=c.useState(null),Pf=vt?"welcome":Ye,Df=e==="welcome"&&!!g,uy=vt&&!!T,Fa=Df&&!!Dc,$f=uy&&!!Fc,gn=e==="welcome"&&(Df||!mc),es=Fa?!0:rn,Ko=c.useMemo(()=>Yn&&id(Yn)==="shell"?Yn:null,[Yn]),Mi=q?`terminal-${q}`:"",Oc=c.useMemo(()=>{if(P==="cli"&&B&&q){const l=Mi||"terminal-new";return{event_id:l,timestamp:Math.floor(Date.now()/1e3),tool_call_id:l,name:"shell",status:"called",function:"shell_view",args:Mi?{id:Mi}:{},content:{session_id:Mi||void 0,runtime:P,execution_target:P,cli_server_id:B??void 0}}}return Ko},[B,P,q,Ko,Mi]),Go=c.useMemo(()=>P==="cli"?!!B:!!Ko,[B,P,Ko]),Li=js==="terminal"?Oc:Yn,za=gn&&!Fa&&es&&!!Li,Bc=gn&&es&&!!Li,dy=!!Ln.current,Qo=gn&&(Bc||dy),Xo=za?"max-w-[680px] xl:max-w-[720px]":"max-w-[768px]",Ve=Ye==="copilot",Yo=cN,Ff=Gt?"px-0":Ve?"px-4":"px-5",fy=Gt?"pt-0":"pt-[12px]",py=Gt?"mt-auto px-0 pb-0 pt-0":Ve?"mt-auto px-3 pb-1 pt-3":"mt-auto px-5 pb-5 pt-4",my=Gt?"px-0":Ve?"px-3":"px-5",hy=Gt?"right-0":Ve?"right-3":"right-5",Zo=c.useRef({projectId:t??null,mode:e,uiSurface:Ye});c.useEffect(()=>{Zo.current={projectId:t??null,mode:e,uiSurface:Ye}},[e,t,Ye]),c.useEffect(()=>(console.info("[CopilotAudit][lifecycle] mount",Zo.current),()=>{console.info("[CopilotAudit][lifecycle] unmount",Zo.current)}),[]),c.useEffect(()=>{console.info("[CopilotAudit][visibility] changed",{projectId:Zo.current.projectId,visible:Zn}),Xe("visibility:changed",{visible:Zn})},[Xe,Zn]),c.useEffect(()=>{if(!t||pa()||!kt||kn||$t)return;const l=he==="welcome"?At:ht??At;l&&Ze(t,he,l)},[kt,kn,At,t,he,Ze,$t,ht]),c.useEffect(()=>{if(!t||kn||$t)return;let l=!1;return(async()=>{await vo(t)&&(l||Ze(t,he,Hr(t)))})(),()=>{l=!0}},[kn,t,he,Ze,$t]),c.useEffect(()=>{t&&(pa()||e==="welcome"&&(!$t||$t===an||Ze(t,"copilot",$t)))},[an,e,t,Ze,$t]),c.useEffect(()=>{t&&(pa()||e!=="welcome"||Ye!=="copilot"||!$t||$t===ht||Ze(t,"welcome",$t))},[e,t,Ze,$t,Ye,ht]);const Oa=Ve||mc,xy=(Se??"text")==="notebook",Jo=rc(),zf=c.useId(),gy=`ai-manus-layout-${zf}`,Of=`ai-manus-composer-${zf}`;me.length;const yy=Sn&&me.length===0,$r=Ye==="welcome"||Ye==="copilot"&&!h,by=$r&&ir!=="done",Pi=mn&&vn,vy=$r&&ir==="center"&&!Pi,qs=$r&&ir==="center",[Bf,qf]=c.useState(null),Uf=Yt?Fh:Fh.filter(l=>l.title!=="Sessions"),_y=bt?.username?.trim()?bt.username.trim():"there",wy=ty.replace("{name}",_y),Sy="What can I do for you?",Di=e==="welcome",ky=Di&&Uf.length>0&&Ye!=="copilot",Ny=Di?{width:"61.8%"}:void 0,jy=Di?"min-w-[min(260px,100%)]":"w-[80%] max-w-[820px] min-w-[min(260px,100%)]",Wf=Di?{width:"61.8%"}:void 0,Hf=Di?"mx-auto min-w-[min(260px,100%)]":"w-full",Vf=c.useMemo(()=>{const l=new Set;if(pt.forEach(m=>{if(m.label){const x=m.label.trim();x&&l.add(x.startsWith("@")?x:`@${x}`)}m.id&&l.add(`@${m.id}`)}),ye){const m=ye.trim();m&&l.add(m.startsWith("@")?m:`@${m}`)}return Array.from(l).sort((m,x)=>x.length-m.length)},[ye,pt]),el=c.useCallback(l=>{if(!V)return l;const m=l??"";if(!m.startsWith("@"))return m;const x=m.toLowerCase();let v=null;for(const S of Vf){const L=S.toLowerCase();if(x.startsWith(L)){v=S.length;break}}if(v==null){const S=m.match(/^@([^\s]+)/);if(!S)return m;v=S[0].length}return m[v]===" "?m:`${m.slice(0,v)} ${m.slice(v)}`},[V,Vf]),Kf=Jo?{duration:0}:{type:"spring",stiffness:220,damping:20,mass:.9},qc=Jo?{duration:0}:{duration:.5,ease:[.16,1,.3,1]},Uc=c.useMemo(()=>Ve?120:144,[Ve]),Ty=c.useMemo(()=>c.forwardRef(function(m,x){return s.jsx("div",{ref:x,...m,style:{...m.style,paddingBottom:Uc}})}),[Uc]);c.useEffect(()=>{if(!V)return;const l=el(tt);l!==tt&&it(l)},[el,tt,V]),c.useLayoutEffect(()=>{if(!Pi){qf(null);return}if(typeof window>"u")return;const l=Pc.current;if(!l)return;let m=null;const x=()=>{m||(m=window.requestAnimationFrame(()=>{m=null;const S=l.querySelector('[data-ai-manus-history-overlay="true"]');if(!S)return;const L=S.getBoundingClientRect(),H=window.getComputedStyle(S),N=Number.parseFloat(H.marginLeft)||0,D=Number.parseFloat(H.marginRight)||0,be=Math.ceil(L.width+N+D);qf(Y=>Y===be?Y:be)}))};if(x(),typeof ResizeObserver>"u")return()=>{m&&window.cancelAnimationFrame(m)};const v=new ResizeObserver(()=>x());return v.observe(l),()=>{v.disconnect(),m&&window.cancelAnimationFrame(m)}},[Pi]),c.useEffect(()=>{js==="terminal"&&!Oc&&yn("tool")},[yn,Oc,js]);const ia=c.useRef(null),fs=c.useRef(null),tl=c.useCallback(l=>{const m=xe.current;if(l.length===0?(lt.current.clear(),Mt.current.clear()):l.length>m.length?m.length===0||l[m.length-1]?.id===m[m.length-1]?.id?!Ht.current&&Pt.current&&l.slice(m.length).forEach((L,H)=>{Mt.current.has(L.id)||(Mt.current.add(L.id),lt.current.set(L.id,H))}):(lt.current.clear(),Mt.current.clear()):(l.length<m.length||l.length===m.length&&l.length>0&&l[0]?.id!==m[0]?.id)&&(lt.current.clear(),Mt.current.clear()),xe.current=l,Nt(l),!jt)return;const x=l.slice(-6).map(v=>{const S=v.content,L=typeof S?.timestamp=="number"?S.timestamp:"na",H=v.id.length>8?v.id.slice(0,8):v.id;return`${v.type}:${H}:${L}`});Xe("state:messages",{count:l.length,tail:x})},[jt,Xe]),Gf=c.useCallback(()=>{fs.current&&(window.clearTimeout(fs.current),fs.current=null),ia.current=null},[]),Ba=c.useCallback(()=>{if(!ia.current)return;const l=ia.current;ia.current=null,fs.current&&(window.clearTimeout(fs.current),fs.current=null),tl(l)},[tl]),Wc=c.useCallback(l=>{xe.current=l,ia.current=l,!fs.current&&(fs.current=window.setTimeout(()=>{Ba()},yN))},[Ba]),Et=c.useCallback((l,m)=>{if(typeof m?.throttle=="boolean"?m.throttle:Ht.current||br.current){Wc(l);return}Gf(),tl(l)},[Gf,tl,Wc]),Qf=c.useCallback(l=>{Mt.current.has(l)&&(Mt.current.delete(l),lt.current.delete(l))},[]),Rn=c.useCallback(l=>{const m=xe.current.findIndex(x=>x.id===l.id);if(m>=0){const x=[...xe.current];x[m]=l,Et(x);return}Et([...xe.current,l])},[Et]),nl=c.useCallback((l,m)=>{const x=xe.current.findIndex(S=>S.id===l.id);if(x<0)return!1;const v=[...xe.current];return v[x]=l,Et(v,m),!0},[Et]),sl=c.useCallback(l=>{if(!nl(l))return!1;for(const[x,v]of rr.current.entries())if(v.id===l.id){rr.current.set(x,l);break}return!0},[nl]),qa=c.useCallback(l=>{if(!l||l.trim().length===0){Xr.current=null,yi(null),bi(null);return}Xr.current!==l&&(bi(Xr.current),Xr.current=l,yi(l),Io(m=>m+1))},[Io]),Hc=c.useCallback((l,m)=>{const x=l??m;return(Array.isArray(x)?x:typeof x=="string"?[x]:[]).map(L=>Gr(String(L))).map(L=>L.trim()).filter(L=>L.length>0).join(" / ")||null},[]),$i=c.useCallback(l=>{const m=Fo.current.get(l)??0;return`${l}::${m}`},[]),Ua=c.useCallback((l=!1)=>{const m=vs.current;if(!m||!l&&ds.current.has(m))return;const x=Fo.current.get(m)??0;Fo.current.set(m,x+1),vs.current=null},[]),Vc=c.useCallback(()=>{const l=vs.current;let m=!1;const x=v=>{if(!v||v.type!=="reasoning")return!1;const S=v.content;if(S.status!=="in_progress")return!1;const L={...S,status:"completed"},H={...v,content:L};return sl(H),Jr.current=L,!0};if(l){const v=$i(l),S=rr.current.get(v);m=x(S),ds.current.delete(l)}if(!m){const v=un.current?.id;if(v){const S=xe.current.findIndex(L=>L.id===v);S>=0&&(m=x(xe.current[S]))}}Ua(!0),wi("reasoning:seal",{activeStream:l,updated:m,lock:un.current,buffered:Jn.current.length})},[Ua,$i,sl,wi]),$n=c.useCallback(()=>{ja.current=!0,Ro(l=>l+1)},[]);c.useEffect(()=>{if(!t||te||typeof window>"u")return;let l=!1;const m=er();return(async()=>{const v=hn.current,S=sr.current;if(pa()){const L=Hr(t);v!==L?(console.info("[CopilotAudit][entry] adopt quest session",{projectId:t,sessionId:L}),Ze(t,he,L)):xe.current.length===0&&(console.info("[CopilotAudit][entry] restore quest session",{projectId:t,sessionId:L}),$n());return}if(console.info("[CopilotAudit][entry]",{projectId:t,apiBaseUrl:m,storedSessionId:v,draftSessionId:S}),S){console.info("[CopilotAudit][entry] skip restore (draft session active)",{projectId:t,draftSessionId:S});return}if(v){xe.current.length===0&&(console.info("[CopilotAudit][entry] restore stored session",{projectId:t,sessionId:v,url:`${m}/api/v1/sessions/${v}`}),$n());return}if(kt){console.info("[CopilotAudit][entry] request product latest session",{projectId:t,url:`${m}/api/v1/sessions/latest`});try{let L=await Xi(t,void 0,he),H=L?.session_id??null,N=!1;if(H||(L=await Xi(t),H=L?.session_id??null,N=!!H),l)return;if(Pe(L??void 0),console.info("[CopilotAudit][entry] latest session resolved",{projectId:t,sessionId:H,events:L?.events?.length??0,usedFallback:N}),!H){const D=v??hn.current;D&&xe.current.length===0&&(console.info("[CopilotAudit][entry] restore stored session",{projectId:t,sessionId:D,url:`${m}/api/v1/sessions/${D}`}),$n());return}if(v&&v===H){xe.current.length===0&&(console.info("[CopilotAudit][entry] restore latest session",{projectId:t,sessionId:H,url:`${m}/api/v1/sessions/${H}`}),$n());return}(L?.events?.length??0)===0&&(Ir.current=!0),Ze(t,he,H),console.info("[CopilotAudit][entry] adopt latest session",{projectId:t,sessionId:H,url:`${m}/api/v1/sessions/${H}`})}catch(L){if(l)return;console.warn("[CopilotAudit][entry] latest session request failed",L),v&&xe.current.length===0&&(console.info("[CopilotAudit][entry] restore stored session",{projectId:t,sessionId:v,url:`${m}/api/v1/sessions/${v}`}),$n())}}})(),()=>{l=!0}},[Ve,t,te,$n,he,Ze,Pe,kt]);const Us=c.useCallback(l=>{xe.current=[],Nt([]),lt.current=new Map,Mt.current=new Set,Ni.current=new Set,ji.current=new Map,Ti.current=!1,Mo(!1),Mn(null),en([]),le(l?.title??"New Chat"),Qe(null),it(""),Qn([]),Ms(!1),cn(null),uc(null),Tr.current=null,Ca.current=null,cs(!1),bn(!1),Ta(null),Ns(!1),yi(null),bi(null),Io(0),Xr.current=null,Yr(null),Ds.current=null,Zr(null),$s.current=null,Si.current=null,Ln.current=null,Bn.current=null,Jr.current=null,Mr.current=0,Nf.current=new Map,ry.current=new Map,ay.current=new Map,zo.current=null,rr.current=new Map,ds.current=new Set,Fo.current=new Map,zs.current&&(window.clearTimeout(zs.current),zs.current=null,Pa.current=null),vs.current=null,un.current=null,Ts.current.clear(),xn.current&&(window.clearTimeout(xn.current),xn.current=null),Lr(null),Jn.current=[],Da.current=[],_c.current.clear(),ki.current=!1,Sc.current=null,Tf.current=new Set,Uo.current.clear(),sa.current=null,vr.current&&(window.cancelAnimationFrame(vr.current),vr.current=null),Ci.current=!1,ia.current=null,fs.current&&(window.clearTimeout(fs.current),fs.current=null),Bs.current&&(window.clearTimeout(Bs.current),Bs.current=null),ny(Bh()),Dr("center"),Ie(!0),Pt.current=!0},[]);c.useEffect(()=>()=>{Ai.current&&window.clearTimeout(Ai.current),vr.current&&(window.cancelAnimationFrame(vr.current),vr.current=null,sa.current=null),fs.current&&(window.clearTimeout(fs.current),fs.current=null,ia.current=null)},[]),c.useEffect(()=>{we.current=Be},[Be]),c.useEffect(()=>{if(!q)return;const l=Be.find(v=>v.session_id===q);if(!l)return;const m=Vs(l.status??null),x=!!l.is_active||ti(m);bn(x),Qe(m),m==="completed"&&(yi(null),bi(null),Xr.current=null)},[q,Be]),c.useEffect(()=>{hn.current=q??null,La.current=null},[q]),c.useEffect(()=>{Ec.current=!1,Cf(!1),Rf(!1),Oo.current=!1,na.current=!1,Tc(!1),Ac(null),Ho(!1),Cc(!1)},[q]),c.useEffect(()=>{me.length===0||Ec.current||(Ec.current=!0,Cf(!0))},[me]),c.useEffect(()=>{Ps.current=Sn},[Sn]),c.useEffect(()=>{Xr.current=null,yi(null),bi(null),Io(0)},[q]),c.useEffect(()=>{Ds.current=Er},[Er]),c.useEffect(()=>{$s.current=Rr},[Rr]);const Xf=c.useCallback(l=>{if(!l)return;const m=hn.current??q??null;if(!m||l.sessionId!==m)return;const x=l.toolCallId?.trim();if(!x)return;const v=[...xe.current];let S=!1;const L=`question_prompt-${x}`,H=v.findIndex(D=>D.id===L);if(H>=0){const D=v[H];if(D.type==="question_prompt"){const be={...D.content,status:"called"};l.answers&&(be.answers=l.answers),v[H]={...D,content:be},S=!0}}else{const D=`clarify_question-${x}`,be=v.findIndex(Y=>Y.id===D?!0:Y.type!=="clarify_question"?!1:Y.content.toolCallId===x);if(be>=0){const Y=v[be];if(Y.type==="clarify_question"){const ce=Y.content,ue={...ce,status:"answered"};if(l.answers&&ce.options?.length){const re=[],ee=new Map(ce.options.map(qe=>[qe.label.toLowerCase(),qe.id])),ze=new Map(ce.options.map(qe=>[qe.id,qe.id])),je=[];Object.values(l.answers).forEach(qe=>{if(Array.isArray(qe)){qe.forEach(ge=>{(typeof ge=="string"||typeof ge=="number")&&je.push(ge)});return}(typeof qe=="string"||typeof qe=="number")&&je.push(qe)}),je.forEach(qe=>{if(typeof qe=="number"){const xt=qe>=1&&qe<=ce.options.length?qe-1:qe>=0?qe:null,Ue=xt!=null?ce.options[xt]:null;Ue&&!re.includes(Ue.id)&&re.push(Ue.id);return}const ge=qe.trim().toLowerCase();if(!ge)return;const Ke=ze.get(qe)||ee.get(ge)||ee.get(qe.toLowerCase());Ke&&!re.includes(Ke)&&re.push(Ke)}),re.length&&(ue.selections=re)}v[be]={...Y,content:ue},S=!0}}}S&&Et(v);let N=!1;Ds.current?.toolCallId===x&&(Yr(null),Ds.current=null,N=!0),$s.current?.toolCallId===x&&(Zr(null),$s.current=null,N=!0),N&&Ve&&cn(null)},[Ve,q,Et]);c.useEffect(()=>{if(typeof window>"u")return;const l=m=>{const x=m.detail;Xf(x)};return window.addEventListener(Zm,l),()=>window.removeEventListener(Zm,l)},[Xf]),c.useEffect(()=>{sr.current=kn},[kn]),c.useEffect(()=>{Po.current=!1},[t]),c.useEffect(()=>{!t||!wt||vf.current!==wt&&(vf.current=wt,hn.current!==wt&&(Po.current=!0,us(null),Ze(t,he,wt)))},[t,wt,he,us,Ze]);const on=c.useCallback((l,m,x)=>{Wt(v=>{const S=[...v],L=S.findIndex(D=>D.session_id===l),H=L>=0?S[L]:null,N={...H??{},session_id:l,title:m.title??H?.title??null,latest_message:m.latest_message??H?.latest_message??null,latest_message_at:m.latest_message_at??H?.latest_message_at??null,updated_at:m.updated_at??H?.updated_at??null,status:m.status??H?.status??null,is_shared:m.is_shared??H?.is_shared??!1,is_active:m.is_active??H?.is_active??!1,...m};return L>=0?(S[L]=N,x?.forceTop?(S.splice(L,1),S.unshift(N),we.current=S,S):(we.current=S,S)):x?.forceTop?(S.unshift(N),we.current=S,S):(S.push(N),we.current=S,S)})},[Wt]),or=c.useCallback(l=>{const m=k.renamed[l];return typeof m=="string"?m.trim():""},[k.renamed]),Kc=c.useCallback((l,m)=>{if(m){const v=or(m);if(v)return v}return(typeof l?.title=="string"?l.title.trim():"")||"New Chat"},[or]),Gc=c.useMemo(()=>{const l=new Map;return k.pinned.forEach((m,x)=>{l.set(m,x)}),l},[k.pinned]),Qc=c.useMemo(()=>new Set(k.pinned),[k.pinned]),Fi=c.useCallback(async l=>{if(Xe("latest:request",{force:!!l?.force,limit:typeof l?.limit=="number"?l.limit:null,adopt:!!l?.adopt,loadedProjectId:kc.current}),!t||te)return Xe("latest:skip",{reason:"no_project_or_readonly"}),null;if(!kt)return Xe("latest:skip",{reason:"surface_managed_externally"}),null;const m=`${t}:${he}`;if(!l?.force&&kc.current===m)return Xe("latest:skip",{reason:"already_loaded"}),null;try{let x=null,v=!1;if(pa()?x=await vd(t,l?.limit):(x=await Xi(t,l?.limit,he),x?.session_id||(x=await Xi(t,l?.limit),v=!!x?.session_id)),!x?.session_id)return Xe("latest:none",{usedFallback:v}),null;kc.current=m,Pe(x);const S=x.session_id,L=Vs(x.status??null),H=!!x.is_active||ti(L);on(S,{title:x.title??"New Chat",status:L,latest_message:x.latest_message??null,latest_message_at:x.latest_message_at??null,updated_at:x.updated_at??null,is_active:H},{forceTop:!0}),hn.current===S&&bn(H);const N=[],D=Gh(x.agents),be=x.session_metadata&&typeof x.session_metadata=="object"?x.session_metadata:null;for(const ze of x.events??[]){const je=Kh(ze);je&&N.push(Qh(je,be,D))}const Y=io(N);if(xl(S,Y),Y.length>0){const je=Y[Y.length-1].data.event_id;typeof je=="string"&&j(S,je)}else j(S,null);const ce=!!sr.current,ue=hn.current,re=!!l?.adopt&&!ce,ee=Y.length===0;return re?(ee&&(Ir.current=!0),ue!==S?Ze(t,he,S):Sn||$n()):!ue&&!ce&&(ee&&(Ir.current=!0),Ze(t,he,S)),Xe("latest:loaded",{sessionId:S,events:N.length,title:x.title??null,status:x.status??null,usedFallback:v}),S}catch(x){return Xe("latest:error",{message:x instanceof Error?x.message:String(x)}),null}},[Xe,sr,kt,Sn,he,t,te,$n,j,Ze,Pe,on]);c.useEffect(()=>{const l=gi.current,m=Ls.current!=null&&Ls.current!==e,x=!l&&Ls.current===null;gi.current=Zn,Ls.current=e;const v=hn.current,S=kt&&!!t&&!te&&!sr.current&&Ve&&!Po.current&&!v;if(Zn&&(!l||m)){if(Xe("visibility:enter",{wasVisible:l,modeChanged:m,isFirstMount:x}),e==="welcome"&&(Xe("sessions:reload",{reason:"visible_or_mode_changed"}),zt()),!t||te||sr.current)return;if(v&&xe.current.length===0&&!Sn){Xe("restore:request",{reason:"visible_restore_existing_session"}),$n();return}const L=S||e==="welcome"&&!v;Xe("latest:trigger",{reason:L?"visible_enter_adopt_latest":"visible_enter_load_latest"}),(!v||L)&&kt&&Fi({force:!0,adopt:L}).then(H=>{!H&&hn.current&&!Sn&&(Xe("restore:request",{reason:"visible_latest_failed_restore_stored"}),$n())});return}if(x&&!v&&!sr.current){if(!t||te)return;Xe("latest:trigger",{reason:"first_mount_no_session"}),kt&&Fi({force:!0,adopt:S});return}if(x&&v&&xe.current.length===0){if(!t||te)return;Sn||(Xe("restore:request",{reason:"first_mount_session_no_messages"}),$n())}},[Xe,kt,Sn,Fi,e,t,te,zt,$n,r,Ve]),c.useEffect(()=>{if(e!=="welcome")return;const l=!hn.current&&!sr.current;Xe("latest:trigger",{reason:"welcome_mode_effect",force:l}),Fi({force:l})},[Xe,Fi,e]),c.useEffect(()=>{if(!q)return;const l=or(q);if(l){F!==l&&le(l);return}if(F!=="New Chat")return;const m=Be.find(x=>x.session_id===q);m?.title&&le(m.title)},[or,q,Be,F]);const Yf=c.useCallback(l=>{if(or(l.session_id))return!1;const x=typeof l.title=="string"?l.title.trim():"",v=typeof l.latest_message=="string"?l.latest_message.trim():"",S=x.toLowerCase();return!v&&(!x||(S==="new chat"||S==="new task"))},[or]),rl=c.useMemo(()=>Be.filter(l=>Yf(l)?l.session_id===q:!0),[Yf,q,Be]),zi=c.useMemo(()=>kn?{session_id:kn,title:"New Chat",latest_message:null,latest_message_at:null,updated_at:Math.floor(Date.now()/1e3),status:null,is_shared:!1}:null,[kn]),Zf=c.useMemo(()=>{if(Qc.size===0)return zi?[zi,...rl]:rl;const l=[],m=[];rl.forEach(v=>{Qc.has(v.session_id)?l.push(v):m.push(v)}),l.sort((v,S)=>{const L=Gc.get(v.session_id)??0,H=Gc.get(S.session_id)??0;return L-H});const x=[...l,...m];return zi?[zi,...x]:x},[zi,rl,Gc,Qc]),Jf=q??kn??null,Oi=c.useCallback(l=>{gf(l),Ai.current&&window.clearTimeout(Ai.current),Ai.current=window.setTimeout(()=>{gf(m=>m===l?null:m)},900)},[]),ep=c.useCallback(()=>{vt&&(console.info("[CopilotAudit][welcome] open sessions list + reload summaries",{projectId:t??null}),Xe("welcome:sessions:open"),Fs(!0),zt())},[Xe,vt,zt,Fs]);c.useEffect(()=>{vt&&(Sf.current=vn)},[vn,vt]),c.useEffect(()=>{hc&&window.setTimeout(()=>bf.current?.focus(),0)},[hc]),c.useEffect(()=>{if(!mt){vn&&Fs(!1);return}if(!vt)return;const l=Sf.current;vn!==l&&Fs(l)},[vn,mt,vt,Fs]),c.useEffect(()=>{!mn||!vn||zt()},[vn,mn,zt]),c.useEffect(()=>{if(!$r){ir!=="done"&&Dr("done");return}if(ir!=="dropping"){if(!Sn&&me.length===0){ir!=="center"&&Dr("center");return}ir!=="done"&&Dr("done")}},[$r,Sn,me.length,ir]),c.useEffect(()=>()=>{Bs.current&&(window.clearTimeout(Bs.current),Bs.current=null)},[]),c.useEffect(()=>{jf.current=new Set,wc.current=new Set,af(0)},[q]),c.useEffect(()=>{if(typeof window>"u")return;const l=window.localStorage.getItem(Cn);if(!l)return;const m=Number(l);if(!Number.isFinite(m))return;const x=Math.min(Lu,Math.max(Rl,m));cc(x)},[Cn]),c.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(Cn,String(bs))},[bs,Cn]),c.useEffect(()=>{if(typeof window>"u")return;const l=window.matchMedia(`(max-width: ${mN}px)`),m=()=>ey(l.matches);return m(),l.addEventListener?(l.addEventListener("change",m),()=>l.removeEventListener("change",m)):(l.addListener(m),()=>l.removeListener(m))},[]),c.useLayoutEffect(()=>{if(typeof document>"u")return;if(!g){$c(null),Xe("portal:toolpanel:disabled");return}let l=!1;const m=S=>{const L=document.getElementById(g);return L?(l||$c(L),Xe("portal:toolpanel:found",{mountId:g,source:S}),!0):!1};if(m("initial"))return()=>{l=!0};$c(null),Xe("portal:toolpanel:waiting",{mountId:g});const x=new MutationObserver(()=>{m("observer")&&x.disconnect()});x.observe(document.body,{childList:!0,subtree:!0});const v=typeof window<"u"?window.setTimeout(()=>x.disconnect(),5e3):null;return()=>{l=!0,x.disconnect(),v&&typeof window<"u"&&window.clearTimeout(v)}},[Xe,g]),c.useLayoutEffect(()=>{if(typeof document>"u")return;if(!T){zc(null),Xe("portal:sessions:disabled");return}let l=!1;const m=S=>{const L=document.getElementById(T);return L?(l||zc(L),Xe("portal:sessions:found",{mountId:T,source:S}),!0):!1};if(m("initial"))return()=>{l=!0};zc(null),Xe("portal:sessions:waiting",{mountId:T});const x=new MutationObserver(()=>{m("observer")&&x.disconnect()});x.observe(document.body,{childList:!0,subtree:!0});const v=typeof window<"u"?window.setTimeout(()=>x.disconnect(),5e3):null;return()=>{l=!0,x.disconnect(),v&&typeof window<"u"&&window.clearTimeout(v)}},[Xe,T]),c.useEffect(()=>{const l=m=>{const v=m.detail||{};typeof v.active=="boolean"&&(_f(v.active),v.active||bc("")),typeof v.sessionId=="string"&&bc(v.sessionId)};return window.addEventListener("takeover",l),window.addEventListener("ai-manus:browser:takeover",l),()=>{window.removeEventListener("takeover",l),window.removeEventListener("ai-manus:browser:takeover",l)}},[]);const Wa=c.useCallback(async()=>{if(!t||te||Ma.current)return;const l=`draft-${Date.now()}`;Ma.current=l,ot(t,he),us(l),yn("tool"),Ut(!0),Us(),Re(t,"sandbox");try{const m=await lm(t);if(!m?.session_id)throw new Error("session_create_failed");if(Ma.current!==l||sr.current!==l)return;Ir.current=!0,us(null),Ze(t,he,m.session_id),j(m.session_id,null),on(m.session_id,{title:m.title??"New Chat",status:Vs(m.status)??"pending",latest_message:null,latest_message_at:Math.floor(Date.now()/1e3),updated_at:Math.floor(Date.now()/1e3),is_active:typeof m.is_active=="boolean"?m.is_active:!1},{forceTop:!0}),Oi(m.session_id)}catch{Ma.current===l&&I({type:"error",title:"Unable to create session",description:"Please try again in a moment."})}finally{Ma.current===l&&(Ma.current=null)}},[I,ot,t,te,Us,he,us,Re,j,Ze,Ut,yn,Oi,on]);c.useEffect(()=>{if(!vt||te)return;const l=m=>{(m.metaKey||m.ctrlKey)&&m.key.toLowerCase()==="k"&&(m.preventDefault(),Wa())};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[vt,te,Wa]);const nt=c.useMemo(()=>{if(!Oe)return null;const l=Oe.context,m=ut[Oe.id],x=$u(l.customData),v=Fu(l.customData),S=l.resourceId,L=l.type==="custom"?x??S:S??x,H=l.resourcePath?.trim()||v||m?.resourcePath||"",N=Il(H),D=L?hl(L):null,be=L?ne(L):null,Y=be?.type==="file"||be?.type==="notebook",ce=l.type==="file"||l.type==="notebook"||N||!!x||Y||!!D,ue=D!=null?Ee.find(ze=>ze.id===D.serverId)?.server_root??void 0:void 0;let re=H,ee=l.resourceName||m?.resourceName;return!D&&Y&&be?.path&&(re=Ks(be.path),!ee&&be?.name&&(ee=be.name)),!re&&ce&&L&&(D?re=ma({serverId:D.serverId,path:D.path,serverRoot:ue}):(Y&&be?.path&&(re=Ks(be.path)),!ee&&Y&&be?.name&&(ee=be.name))),re&&ce&&(D?re.startsWith("/CLIFILES")||(re=ma({serverId:D.serverId,path:D.path,serverRoot:ue})):re.startsWith("/FILES")||(re=Ks(re))),{tabId:Oe.id,type:Oe.context.type,resourceId:L,resourcePath:re,resourceName:ee,mimeType:Oe.context.mimeType,title:Oe.title,pluginId:Oe.pluginId}},[Oe,Ee,ne,ut]),[Ws,Ay]=c.useState({}),Fr=c.useMemo(()=>{if(!nt)return"";const l=nt.resourcePath??"";if(!(nt.type==="file"||nt.type==="notebook"||l.startsWith("/FILES")||l.startsWith("/CLIFILES")||!!(nt.resourceId&&Ws[nt.resourceId])))return"";const x=nt.resourceId&&Ws[nt.resourceId]?Ws[nt.resourceId]:"",v=Gs(l),S=Il(v)?v:x?Gs(x):"";return!S||S==="/FILES"||S==="/CLIFILES"?"":S},[nt,Ws]),Xc=c.useMemo(()=>{if(!t)return[];const l=Object.values(de).filter(x=>x.projectId===t);if(l.length===0)return[];l.sort((x,v)=>v.lastAccessedAt-x.lastAccessedAt);const m=[];for(const x of l){const v=ne(x.fileId);if(!v?.path)continue;const S=Gs(Ks(v.path));if(!(!S||S==="/FILES")&&(m.push(S),m.length>=Pu))break}return m},[de,ne,t]);c.useEffect(()=>{if(!On||Te.length===0)return;const l=new Set;for(const v of Te){const S=v.context,L=$u(S.customData),H=Fu(S.customData),N=S.resourceId,D=S.type==="custom"?L??N:N??L;if(!D||hl(D)||Ws[D])continue;const be=S.resourcePath?.trim()||H||"",Y=Il(be),ce=ne(D),ue=ce?.type==="file"||ce?.type==="notebook";if(!(ce&&!ue)&&!(Y||ue&&ce?.path)&&(l.add(D),l.size>=Pu))break}if(l.size===0)return;let m=!0;const x=Array.from(l);return Promise.allSettled(x.map(v=>nv(v))).then(v=>{if(!m)return;const S={};v.forEach((L,H)=>{if(L.status!=="fulfilled")return;const N=L.value;if(!N?.path)return;const D=Gs(Ks(N.path));!D||D==="/FILES"||(S[x[H]]=D)}),Object.keys(S).length!==0&&Ay(L=>({...L,...S}))}),()=>{m=!1}},[ne,Ws,On,Te]);const lr=c.useMemo(()=>{const l=new Set,m=[],x=Fr?Gs(Fr):"";for(const S of Te){const L=S.context,H=$u(L.customData),N=Fu(L.customData),D=L.resourceId,be=L.type==="custom"?H??D:D??H,Y=L.resourcePath?.trim()||N||"",ce=Il(Y),ue=be?ne(be):null,re=ue?.type==="file"||ue?.type==="notebook",ee=L.type==="file"||L.type==="notebook"||ce||!!H||re;let ze=Y;const je=be?hl(be):null;if(!ee&&!je)continue;const qe=je?Ee.find(ge=>ge.id===je.serverId)?.server_root??void 0:void 0;if(!ze&&be&&!ce?je?ze=ma({serverId:je.serverId,path:je.path,serverRoot:qe}):re&&ue?.path?ze=Ks(ue.path):be&&Ws[be]&&(ze=Ws[be]):!ze&&be&&Ws[be]&&(ze=Ws[be]),ze){const ge=ze.startsWith("/CLIFILES");je||ge?!ze.startsWith("/CLIFILES")&&je&&(ze=ma({serverId:je.serverId,path:je.path,serverRoot:qe})):ze.startsWith("/FILES")||(ze=Ks(ze))}ze=Gs(ze),ze&&(ze==="/FILES"||ze==="/CLIFILES"||l.has(ze)||(l.add(ze),m.push(ze)))}if(!m.some(S=>S.startsWith("/FILES"))&&Xc.length>0){for(const S of Xc)if(!l.has(S)&&(l.add(S),m.push(S),m.length>=Pu))break}if(x){const S=m.indexOf(x);S===-1?m.unshift(x):S>0&&(m.splice(S,1),m.unshift(x))}return m},[Fr,Xc,Ee,ne,Ws,Te]),Yc=c.useMemo(()=>lr.length===0?"":`Recent files (active first):
203
+ ${lr.map(m=>{const x=Gs(m);return Fr&&Gs(Fr)===x?`- [active] ${m}`:`- ${m}`}).join(`
204
+ `)}`,[Fr,lr]),Ha=c.useMemo(()=>{if(!Te.length)return[];const l=[],m=Oe?.id??null;for(const x of Te){const v=x.context,S=ut[x.id],L=v.type==="file"||v.type==="notebook",H=v.resourceId,N=L&&H?hl(H):null,D=L&&H?ne(H):null,be=N!=null?Ee.find(ee=>ee.id===N.serverId)?.server_root??void 0:void 0;let Y=v.resourcePath?.trim()||S?.resourcePath||"",ce=v.resourceName||S?.resourceName;!N&&D?.path&&(Y=Ks(D.path),!ce&&D?.name&&(ce=D.name)),!Y&&L&&H&&(N?Y=ma({serverId:N.serverId,path:N.path,serverRoot:be}):(D?.path&&(Y=Ks(D.path)),!ce&&D?.name&&(ce=D.name))),Y&&L&&(N?Y.startsWith("/CLIFILES")||(Y=ma({serverId:N.serverId,path:N.path,serverRoot:be})):Y.startsWith("/FILES")||(Y=Ks(Y))),(Y==="/FILES"||Y==="/CLIFILES")&&(Y="");const ue=Ce[x.id],re=[];S?.documentMode&&re.push(S.documentMode),S?.isReadOnly&&re.push("read_only"),S?.compileState==="compiling"&&re.push("compiling"),(S?.selectionCount||0)>0&&re.push("quote"),(S?.diagnostics?.errors||0)>0?re.push("error"):(S?.diagnostics?.warnings||0)>0&&re.push("warning"),ue?.kind==="latex_error"&&re.push(ue.severity==="warning"?"focused_warning":"focused_error"),l.push({tabId:x.id,title:x.title,type:v.type,pluginId:x.pluginId,resourceId:H,resourcePath:Y||void 0,resourceName:ce||void 0,mimeType:v.mimeType,isActive:x.id===m,contentKind:S?.contentKind,documentMode:S?.documentMode,pageNumber:S?.pageNumber,status:re.length>0?re:void 0,focusedIssue:ue?.kind==="latex_error"?{kind:ue.kind,resourcePath:ue.resourcePath,resourceName:ue.resourceName,line:ue.line,message:ue.message,severity:ue.severity}:void 0})}return l},[Oe?.id,Ee,ne,Te,Ce,ut]),Va=lr.length>0,tp=c.useMemo(()=>{if(!B)return"";const l=Ee.find(m=>m.id===B);return l?.name||l?.hostname||B.slice(0,6)},[B,Ee])||B?.slice(0,6)||"",np=P==="cli"?tp?`CLI Server: ${tp}`:"CLI Server":"Copilot",zr=e==="welcome"&&me.length>0,Zc=Ee.length>0||!!B,Cy=ct.length>0,al=!!((Z??!0)&&t&&Zc),sp=vi||zr||!Cy&&P!=="cli"||Dn&&P==="cli";c.useEffect(()=>{On&&!Va&&Ms(!1)},[Va,On]);const rp=c.useCallback(()=>{!Va||te||Ms(l=>!l)},[te,Va]),ap=c.useCallback(()=>{Ms(!1)},[]),Ka=c.useCallback(()=>{const l=typeof window<"u"?window.location.href:null,m=typeof window<"u"?window.location.pathname:null,x=typeof document<"u"?document.title:null,v=nt?.pluginId??null,S=fr.getState(),L=nt?.tabId!=null?S.tabState[nt.tabId]??ut[nt.tabId]:void 0,H=nt?.tabId!=null?S.referencesByTabId[nt.tabId]||[]:[],N=nt?.tabId!=null?S.activeReferenceByTabId[nt.tabId]:null,D=N&&S.references[N]||null,be=H.length>0?H.map(ge=>S.references[ge]).filter(ge=>!!ge):[],Y=nt?.tabId!=null?S.activeIssueByTabId[nt.tabId]:null,ce=D?{id:D.id,kind:D.kind,fileId:D.fileId,resourceId:D.resourceId,resourcePath:D.resourcePath,resourceName:D.resourceName,pageNumber:D.pageNumber,selectedText:D.selectedText,markdownExcerpt:D.markdownExcerpt,excerptStatus:D.excerptStatus,rects:D.rects,createdAt:D.createdAt}:null,ue=be.length>0?be.map(ge=>({id:ge.id,kind:ge.kind,resourcePath:ge.resourcePath,resourceName:ge.resourceName,pageNumber:ge.pageNumber,selectedText:ge.selectedText,markdownExcerpt:ge.markdownExcerpt})):void 0,re=Y?.kind==="latex_error"?{kind:Y.kind,fileId:Y.fileId,resourceId:Y.resourceId,resourcePath:Y.resourcePath,resourceName:Y.resourceName,line:Y.line,message:Y.message,severity:Y.severity,excerpt:Y.excerpt,createdAt:Y.createdAt}:null,ee=Ha.length>0?[...Ha].sort((ge,Ke)=>{const xt=ge.isActive?1:0;return(Ke.isActive?1:0)-xt}).map((ge,Ke)=>({docIndex:Ke+1,tabId:ge.tabId,title:ge.title,resourceId:ge.resourceId,resourcePath:ge.resourcePath,resourceName:ge.resourceName,mimeType:ge.mimeType,pluginId:ge.pluginId,type:ge.type,contentKind:ge.contentKind,documentMode:ge.documentMode,pageNumber:ge.pageNumber,status:Array.isArray(ge.status)?ge.status:void 0,isActive:!!ge.isActive,focusedIssue:ge.focusedIssue&&typeof ge.focusedIssue=="object"?ge.focusedIssue:void 0})):[],ze=ee.find(ge=>ge.isActive)||(nt?{docIndex:1,tabId:nt.tabId,title:nt.title,resourceId:nt.resourceId,resourcePath:nt.resourcePath,resourceName:nt.resourceName,mimeType:nt.mimeType,pluginId:nt.pluginId,type:nt.type,contentKind:L?.contentKind,documentMode:L?.documentMode,pageNumber:L?.pageNumber,isActive:!0}:null),je=[];if(ce){const ge=ee.find(Ke=>Ke.tabId===nt?.tabId)?.docIndex??ze?.docIndex;je.push({type:"pdf_selection",docIndex:ge,tabId:nt?.tabId,resourceId:ce.resourceId,resourcePath:ce.resourcePath,resourceName:ce.resourceName,pageNumber:ce.pageNumber,selectedText:ce.selectedText,markdownExcerpt:ce.markdownExcerpt})}if(re){const ge=ee.find(Ke=>Ke.tabId===nt?.tabId)?.docIndex??ze?.docIndex;je.push({type:"latex_error",docIndex:ge,tabId:nt?.tabId,fileId:re.fileId,resourceId:re.resourceId,resourcePath:re.resourcePath,resourceName:re.resourceName,line:re.line,message:re.message,severity:re.severity,excerpt:re.excerpt})}const qe=ze||ee.length>0||je.length>0?{activeDocument:ze||void 0,tabIndex:ee.length>0?ee:void 0,focusItems:je.length>0?je:void 0}:void 0;return!nt&&!l&&!m&&!x&&Ha.length===0?null:{activeTabId:nt?.tabId,selection:ce,resourceId:nt?.resourceId,resourcePath:nt?.resourcePath,resourceName:nt?.resourceName,mimeType:nt?.mimeType,title:nt?.title,pluginId:nt?.pluginId,pluginName:v||void 0,type:nt?.type,contentKind:L?.contentKind,documentMode:L?.documentMode,pageNumber:L?.pageNumber,anchors:ue,focusedIssue:re||void 0,memoryLayers:qe,pageUrl:l||void 0,pagePath:m||void 0,pageTitle:x||void 0,openTabs:Ha.length>0?Ha:void 0}},[nt,Ha,ut]),ip=c.useCallback(async(l,m=1600)=>{if(l.length===0)return;const x=Date.now()+m;for(;Date.now()<x;){const v=fr.getState().references;if(!l.some(L=>v[L]?.excerptStatus==="loading"))return;await new Promise(L=>window.setTimeout(L,40))}},[]),oa=c.useRef(null),Ey=c.useCallback((l,m)=>{const x=Tr.current;if(!(x&&m.runId===x.runId)&&!(Ca.current!=null&&m.runId===Ca.current)){if(Ps.current){Da.current.push(l);return}oa.current?.(l)}},[]),{sendMessage:cr,stop:Jc,connection:ps,isStreaming:eu,runId:Bi}=X_({sessionId:q,projectId:t,onEvent:Ey}),il=c.useRef(Bi);c.useEffect(()=>{il.current=Bi},[Bi]);const la=!!Aa,op=!la&&(eu||!!ea&&!la),tu=c.useMemo(()=>me.some(l=>{if(l.type==="text_delta"){const m=l.content;return m.role==="assistant"&&m.status==="in_progress"}return l.type==="reasoning"?l.content.status==="in_progress":l.type==="tool_call"?l.content.status==="calling":l.type==="step"?l.content.status==="running":!1}),[me]),Ga=!la&&(!!$||tu||!!Er||!!Rr||Ar||dc),nu=Ga&&!Er&&!Rr,lp=!1;c.useEffect(()=>{Tr.current=Aa},[Aa]),c.useEffect(()=>{Ar&&qa(null)},[Ar,qa]),c.useEffect(()=>{e!=="welcome"||!p||(ki.current=!0,Ut(!0),yn("tool"))},[e,p,q]);const ts=c.useCallback(l=>typeof l=="number"&&Number.isFinite(l)?(l>Mr.current&&(Mr.current=l),l):(Mr.current+=1,Mr.current),[]),Ry=c.useCallback((l,m)=>`text-${l.trim()?l.trim():"text"}-${m}`,[]),su=c.useCallback(()=>{const l=zo.current;if(!l)return;const m=xe.current.findIndex(L=>L.id===l);if(m<0){zo.current=null;return}const x=xe.current[m];if(x.type!=="text_delta")return;const v=x.content;if(v.role!=="assistant"||v.status!=="in_progress")return;const S=[...xe.current];S[m]={...x,content:{...v,status:"completed"}},Et(S)},[Et]);c.useCallback(l=>{let m=Mr.current;for(const x of l){const v=xr(x);if(v!=null){v>m&&(m=v);continue}m+=1;const S=x.data;S&&typeof S=="object"&&(S.seq=m)}Mr.current=m},[]);const ol=c.useCallback(l=>{if(Ht.current)return!1;const m=un.current;if(!m||l.event==="error"||vN.has(l.event)||l.event==="message")return!1;if(l.event==="reasoning"){if(m.kind!=="reasoning")return!1;const x=l.data,v=typeof x.reasoning_id=="string"?x.reasoning_id:"",S=Uh(x.kind),L=Wh(v,S,x.reasoning_stream_id),H=$i(L),N=rr.current.get(H);return!(m.kind==="reasoning"&&N?.id===m.id)}if(l.event==="tool"){const x=l.data,v=Ll(typeof x.function=="string"?x.function:"");if(v==="question_prompt"||v==="clarify_question"||m.kind!=="tool")return!1;const S=typeof x.tool_call_id=="string"?x.tool_call_id:"";let L=S;if(v==="mcp_status_update"){const H=typeof x.event_id=="string"?x.event_id:"",N=Cs(x.timestamp);L=Du(H,S,N)}return L&&L===m.id,!1}return!0},[]),_s=c.useCallback(()=>{if(Tr.current){Jn.current=[];return}if(Jn.current.length===0)return;const l=Jn.current;Jn.current=[],window.setTimeout(()=>{if(Tr.current){l.length=0;return}const m=oa.current;if(!m)return;const x=()=>{if(l.length===0)return;if(Tr.current){l.length=0;return}const v=l[0];if(ol(v)){Jn.current=l.concat(Jn.current);return}l.shift(),m(v),l.length>0&&window.setTimeout(x,0)};x()},0)},[ol]),Qa=c.useCallback(()=>{if(Ps.current||Da.current.length===0)return;const l=oa.current;if(!l){Da.current=[];return}const m=Da.current;Da.current=[];const x=Mr.current,v=_c.current,S=m.filter(H=>{const N=H.data,D=N&&typeof N.event_id=="string"?N.event_id:null;if(D&&v.has(D))return!1;const be=xr(H);return!(x!=null&&be!=null&&be<=x)});if(S.length===0)return;io(S).forEach(H=>{l(H)})},[]);c.useEffect(()=>{Pt.current=ve},[ve]),c.useEffect(()=>{t&&fe(t)},[fe,t]),c.useEffect(()=>{if(!t||!Zn||typeof window>"u")return;const l=window.setInterval(()=>{if(!document.hidden&&!yt){if(Me&&Me===t){Fe();return}fe(t)}},15e3);return()=>{window.clearInterval(l)}},[yt,Me,Zn,fe,t,Fe]);const qi=c.useCallback(async()=>{if(!(!t||fc.current)){fc.current=!0;try{const l=await sv(t);at(l.id,l.agents??[])}finally{fc.current=!1}}},[t,at]),cp=c.useCallback(async l=>{if(t){try{await rv(t,l)}catch{}Me&&Me===t?await Fe():await fe(t),typeof window<"u"?window.setTimeout(()=>{qi()},700):qi()}},[Me,fe,t,Fe,qi]),ll=c.useMemo(()=>ct.map(l=>l.id).sort().join("|"),[ct]);c.useEffect(()=>{t&&(!Me||Me!==t||ll!==df.current&&(df.current=ll,!(!ll&&!pn)&&qi()))},[Me,pn,ll,t,qi]);const Ui=B??We??null;c.useEffect(()=>{!t||!Ui||!Me||Me!==t||ff.current!==Ui&&(ff.current=Ui,cp(Ui))},[Me,t,cp,Ui]),c.useEffect(()=>{if(!t||!Me||Me!==t||yt)return;const l=!!(B&&Ee.some(m=>m.id===B));P==="cli"&&ct.length>0&&(!B||!ct.some(m=>m.id===B))&&Ft(t,ct[0].id),P==="cli"&&ct.length===0&&!l&&Re(t,"sandbox")},[yt,B,Ee,Me,P,ct,t,Ft,Re]);const qn=c.useCallback(async l=>{if(!t)return Xe("ensure:skip",{reason:"no_project"}),I({type:"error",title:"No project selected",description:"Open a project before starting a conversation."}),null;if(hn.current)return Xe("ensure:reuse",{sessionId:hn.current}),hn.current;if($o.current?.projectId===t)return Xe("ensure:inflight"),$o.current.promise;const m=l?.openToolPanel!==!1;if(await vo(t)){const v=Hr(t);return Xe("ensure:quest:adopt",{sessionId:v}),Ir.current=!0,us(null),Ze(t,he,v),j(v,null),on(v,{title:"New Chat",status:"pending",latest_message:null,latest_message_at:Math.floor(Date.now()/1e3),updated_at:Math.floor(Date.now()/1e3),is_active:!1},{forceTop:!0}),Oi(v),m&&Ut(!0),v}Xe("ensure:create:start");const x=lm(t).then(v=>{const S=hn.current,L=!S;return Xe("ensure:create:done",{sessionId:v.session_id,adopted:L}),L&&(Ir.current=!0,us(null),Ze(t,he,v.session_id),j(v.session_id,null)),on(v.session_id,{title:v.title??"New Chat",status:Vs(v.status)??"pending",latest_message:null,latest_message_at:Math.floor(Date.now()/1e3),updated_at:Math.floor(Date.now()/1e3),is_active:typeof v.is_active=="boolean"?v.is_active:!1},{forceTop:!0}),L&&(Oi(v.session_id),m&&Ut(!0)),S??v.session_id}).catch(v=>(Xe("ensure:create:error",{message:v instanceof Error?v.message:String(v)}),I({type:"error",title:"Unable to create session",description:"Please try again in a moment."}),null)).finally(()=>{$o.current=null});return $o.current={projectId:t,promise:x},x},[I,Xe,t,us,j,Ze,Ut,he,Oi,on]);c.useEffect(()=>{if(e!=="welcome"||!gn||te)return;if(!t){La.current=null;return}if(!es||js!=="terminal"){La.current=null;return}if(q){La.current=null;return}const l=`${t??"project"}:${kn??"draft"}`;La.current!==l&&(La.current=l,qn())},[kn,qn,e,t,te,q,gn,es,js]);function cl(){Tr.current=null,uc(null),Ca.current=null,cn(l=>l==="Paused"||l==="Cancelled"?null:l)}const ul=c.useCallback(async()=>{const l=(dt,dn)=>{const Ot=dn.trim();if(!Ot)return dt;const Un=Ot.startsWith("@")?Ot:`@${Ot}`,pe=(dt||"").trim();if(!pe)return pe;const Ge=Un.toLowerCase();if(pe.toLowerCase().startsWith(Ge)){const _t=pe.slice(Un.length);return _t?/^\s/.test(_t)?pe:`${Un} ${_t}`:Un}let rt=pe;if(pe.startsWith("@")){const _t=pe.match(/^@([^\s]+)(?:\s+|$)/);_t&&(rt=pe.slice(_t[0].length).trim())}return rt?`${Un} ${rt}`:Un};cl();const m=ae?l(tt,ae):tt,x=Nk(m,pt,{enabled:ln,defaultAgent:U}),v=x.displayMessage.trim();if(jt&&console.info("[CopilotAudit][submit] start",{projectId:t,sessionId:hn.current,inputLength:tt.length,displayLength:v.length,readOnlyMode:te,isRestoring:Ps.current,pendingRun:Ar}),!v||te)return;const S=x.agentMessage.trim();if(x.matched&&!S){I({type:"warning",title:"Add a message",description:"Provide a message after the agent mention."});return}const L=x.matched?S:v,H=x.agent.label?.trim(),N=H?H.startsWith("@")?H:`@${H}`:`@${x.agent.id}`,D={agent_id:x.agent.id,agent_label:N,agent_role:x.agent.role??x.agent.id,agent_source:x.agent.source??"backend"};x.agent.agent_engine&&(D.agent_engine=x.agent.agent_engine);const be=W?{...D,...W}:D,Y=On&&Yc?{...be,recent_files_prompt:Yc}:be;let ue=(typeof x.agent.execution_target=="string"?x.agent.execution_target.toLowerCase():"")==="cli"?"cli":P,re=ue==="cli"?B??ct[0]?.id??null:null;if(ue==="cli"&&!re)if(I({type:"warning",title:"CLI unavailable",description:"No online CLI server is available for this agent."}),t&&!Dn)ue="sandbox",re=null,Re(t,"sandbox");else return;ue==="cli"&&t&&P!=="cli"&&Re(t,"cli",re??void 0),$r&&ir==="center"&&(Bs.current&&(window.clearTimeout(Bs.current),Bs.current=null),Jo?Dr("done"):(Dr("dropping"),Bs.current=window.setTimeout(()=>{Dr("done"),Bs.current=null},520))),cs(!0),bn(!0);const ee=await qn();if(jt&&console.info("[CopilotAudit][submit] ensureSession resolved",{projectId:t,requestedSessionId:hn.current,resolvedSessionId:ee}),!ee){cs(!1),bn(!1);return}const ze=Vd(wn,ee).filter(dt=>dt.status==="success"),je=Math.floor(Date.now()/1e3);on(ee,{latest_message:v,latest_message_at:je,updated_at:je,status:"running",is_active:!0}),Sc.current={content:L,attachments:ze};const qe=ts();if(Rn({id:_n("user"),type:"user",seq:qe,ts:je,content:{content:v,timestamp:je,role:"user",metadata:Y}}),ze.length>0){const dt=ts();Rn({id:_n("attachments"),type:"attachments",seq:dt,ts:je,content:{role:"user",attachments:ze,timestamp:je}})}G?.(L),it(""),Qn([]),Ms(!1);const ge=nt?.tabId,Ke=ge!=null?(fr.getState().referencesByTabId[ge]||[]).filter(dt=>fr.getState().references[dt]?.excerptStatus==="loading"):[];Ke.length>0&&await ip(Ke);const xt=Ka(),Ue=xt?{context:xt,...Y}:Y;try{jt&&console.info("[CopilotAudit][submit] sendMessage",{projectId:t,sessionId:ee,messageLength:L.length,attachmentCount:ze.length}),await cr({sessionId:ee,message:L,attachments:ze,recentFiles:On?lr:void 0,surface:he,executionTarget:ue,cliServerId:re,metadata:Ue})}catch(dt){cs(!1),bn(!1);const dn=dt instanceof Error&&dt.message?dt.message:"Unable to send message. Please try again.",Ot=/insufficient points|required:\s*\d+/i.test(dn);I({type:"error",title:Ot?"Insufficient points":"Message failed",description:dn})}},[I,Rn,wn,Ka,cl,B,qn,P,tt,ae,pt,ln,U,W,ct,t,he,Jo,te,lr,On,Yc,ts,G,cs,Re,Dr,cr,on,$r,nt?.tabId,ip,ir]),up=async()=>{const l=q??hn.current;if(!l)return;cs(!1),bn(!1);const m=Bi>0?Bi:il.current;Jc(l),My("paused",m),on(l,{status:"waiting",updated_at:Math.floor(Date.now()/1e3),is_active:!1});try{await F_(l)}catch(x){console.warn("[AiManus] stopSession failed",x)}},Iy=c.useCallback(async()=>{const l=q??hn.current;if(!(!l||te)){cl(),cs(!0),bn(!0),on(l,{is_active:!0});try{await cr({sessionId:l,message:"",surface:he,executionTarget:P,cliServerId:B,replayFromLastEvent:!0})}catch{cs(!1),bn(!1),I({type:"error",title:"Resume failed",description:"Unable to resume the session. Please try again."})}}},[I,cl,B,P,te,cr,q,he,on]),dp=c.useCallback(l=>{if(!t||kn&&l===kn)return;Po.current=!0;const m=we.current.find(x=>x.session_id===l);m&&Pe(m),us(null),Ze(t,he,l)},[kn,t,he,us,Ze,Pe]),fp=c.useCallback(l=>{se(m=>{const v=m.pinned.includes(l)?m.pinned.filter(S=>S!==l):[l,...m.pinned.filter(S=>S!==l)];return{...m,pinned:v}})},[]),pp=c.useCallback(l=>{const m=we.current.find(v=>v.session_id===l),x=Kc(m??null,l);yf(l),yc(x),xc(!0)},[Kc]),Wi=c.useCallback(()=>{xc(!1),yf(null),yc("")},[]),mp=c.useCallback(()=>{if(!Ia)return;const l=gc.trim(),m=we.current.find(x=>x.session_id===Ia);if(se(x=>{const v={...x.renamed};return l?v[Ia]=l:delete v[Ia],{...x,renamed:v}}),hn.current===Ia){const x=typeof m?.title=="string"&&m.title.trim()?m.title.trim():"New Chat";le(l||x)}Wi()},[Wi,gc,Ia]),hp=c.useCallback(l=>{pp(l)},[pp]),xp=c.useCallback(l=>{if(!t||typeof window>"u")return"";const m=new URL(window.location.origin);return m.pathname=`/projects/${t}`,m.searchParams.set("copilotSession",l),m.toString()},[t]),gp=c.useCallback(async l=>{const m=xp(l);if(!m)return;const x=await mx(m);I({type:x?"success":"error",title:x?"Link copied":"Unable to copy link",description:x?"Share this session with teammates.":"Please try again."})},[I,xp]),yp=c.useCallback(async l=>{if(!t||te)return;if(kn&&l===kn){us(null),Us();return}if(window.confirm("Delete this session? This cannot be undone."))try{await z_(l),Wt(x=>x.filter(v=>v.session_id!==l)),se(x=>{const{[l]:v,...S}=x.renamed;return{...x,pinned:x.pinned.filter(L=>L!==l),renamed:S}}),q===l&&(ot(t,he),j(l,null),Us())}catch{I({type:"error",title:"Unable to delete session",description:"Please try again in a moment."})}},[I,ot,kn,t,te,Us,he,q,j,us,Wt]);c.useEffect(()=>{if(!xu||!pc||!q)return;let l=!0;return hf(!0),q_(q).then(m=>{l&&Zg(m)}).catch(()=>{l&&I({type:"error",title:"Unable to load session files",description:"Please try again later."})}).finally(()=>{l&&hf(!1)}),()=>{l=!1}},[I,pc,q]);const bp=c.useRef(null),vp=c.useCallback(()=>{const l={threadId:q??null,historyOpen:vn,isResponding:Ga,toolCount:rf,ready:!!q,isRestoring:Sn,restoreAttempted:Rc,hasHistory:jc,error:ps.error??null,title:F,statusText:tf,statusPrevText:nf,statusKey:sf,toolPanelVisible:Bc,toolToggleVisible:Qo,fixWithAiRunning:cf},m=bp.current;m&&m.threadId===l.threadId&&m.historyOpen===l.historyOpen&&m.isResponding===l.isResponding&&m.toolCount===l.toolCount&&m.ready===l.ready&&m.isRestoring===l.isRestoring&&m.restoreAttempted===l.restoreAttempted&&m.hasHistory===l.hasHistory&&m.error===l.error&&m.title===l.title&&m.statusText===l.statusText&&m.statusPrevText===l.statusPrevText&&m.statusKey===l.statusKey&&m.toolPanelVisible===l.toolPanelVisible&&m.toolToggleVisible===l.toolToggleVisible&&m.attachmentsDrawerOpen===l.attachmentsDrawerOpen&&m.fixWithAiRunning===l.fixWithAiRunning||(bp.current=l,f?.(l))},[ps.error,cf,vn,jc,Ga,Sn,f,Rc,q,sf,nf,tf,F,Bc,Qo]);c.useEffect(()=>{vp()},[vp]);const Hi=c.useRef({historyPanelEnabled:mt,historyOpenValue:vn,toolPanelEnabled:gn,toolPanelOpenValue:es,mode:e,projectId:t,sessionSurface:he,activeTool:Yn}),_p=c.useRef(()=>{}),ru=c.useRef(async()=>{}),Dt=c.useRef({setHistoryOpenValue:()=>{},startNewSession:()=>{},clearSessionIdForSurface:()=>{},resetConversation:()=>{},setSessionIdForSurface:()=>{},setDraftSessionId:()=>{},focusComposer:()=>{},setInputMessage:()=>{},handleSubmit:()=>{},ensureSession:async()=>null,setToolPanelView:()=>{},setToolPanelOpen:()=>{},setActiveTool:()=>{},setToolPanelLive:()=>{},runFixWithAi:l=>ru.current(l)});c.useEffect(()=>{Hi.current={historyPanelEnabled:mt,historyOpenValue:vn,toolPanelEnabled:gn,toolPanelOpenValue:es,mode:e,projectId:t,sessionSurface:he,activeTool:Yn}},[Yn,vn,mt,e,t,he,gn,es]),c.useEffect(()=>{Dt.current={setHistoryOpenValue:Fs,startNewSession:Wa,clearSessionIdForSurface:ot,resetConversation:Us,setSessionIdForSurface:Ze,setDraftSessionId:us,focusComposer:Do,setInputMessage:it,handleSubmit:ul,ensureSession:qn,setToolPanelView:yn,setToolPanelOpen:Ut,setActiveTool:Ta,setToolPanelLive:Ns,runFixWithAi:l=>ru.current(l)}},[ot,qn,Do,ul,Us,Ta,us,Fs,it,Ze,Ns,Ut,yn,Wa]);const au=c.useRef(null);au.current||(au.current={toggleHistory:()=>{const{historyPanelEnabled:l,historyOpenValue:m}=Hi.current;l&&Dt.current.setHistoryOpenValue(!m)},startNewThread:()=>{Dt.current.startNewSession()},setThreadId:l=>{const{projectId:m,sessionSurface:x}=Hi.current;if(m){if(Dt.current.setDraftSessionId(null),!l){Dt.current.clearSessionIdForSurface(m,x),Dt.current.resetConversation();return}Dt.current.setSessionIdForSurface(m,x,l)}},clearThread:()=>{Dt.current.resetConversation()},focusComposer:()=>{Dt.current.focusComposer()},setComposerValue:(l,m=!1)=>{Dt.current.setInputMessage(l),m&&window.setTimeout(()=>Dt.current.focusComposer(),0)},submitComposer:()=>{Dt.current.handleSubmit()},runFixWithAi:l=>{Dt.current.runFixWithAi(l)},openToolPanel:()=>{const{mode:l,toolPanelEnabled:m,activeTool:x}=Hi.current;if(l!=="welcome"||!m)return;if(x){Dt.current.setToolPanelView("tool"),Dt.current.setToolPanelOpen(!0);return}const v=Ln.current;if(v){Dt.current.setActiveTool(v),Dt.current.setToolPanelLive(v.status==="calling"),Dt.current.setToolPanelView("tool"),Dt.current.setToolPanelOpen(!0);return}(async()=>{await Dt.current.ensureSession()&&(Dt.current.setToolPanelView("terminal"),Dt.current.setToolPanelOpen(!0))})()},toggleToolPanel:()=>{const{mode:l,toolPanelEnabled:m,toolPanelOpenValue:x,activeTool:v}=Hi.current;if(l!=="welcome"||!m)return;if(x){Dt.current.setToolPanelOpen(!1);return}if(v){Dt.current.setToolPanelView("tool"),Dt.current.setToolPanelOpen(!0);return}const S=Ln.current;if(S){Dt.current.setActiveTool(S),Dt.current.setToolPanelLive(S.status==="calling"),Dt.current.setToolPanelView("tool"),Dt.current.setToolPanelOpen(!0);return}(async()=>{await Dt.current.ensureSession()&&(Dt.current.setToolPanelView("terminal"),Dt.current.setToolPanelOpen(!0))})()}}),c.useEffect(()=>{if(d)return d(au.current),()=>{d(null)}},[d]),c.useEffect(()=>{a&&(it(el(a.text)),a.focus&&window.setTimeout(()=>Do(),0))},[el,Do,a]),c.useEffect(()=>{gn||Ns(!1)},[gn]);const wp=c.useCallback(l=>l.tool_call_id===Ln.current?.tool_call_id,[]),ca=c.useCallback(l=>{if(Hh(l))return!1;const m=id(l);return m==="shell"||m==="bash"||m==="search"||m==="file"},[]),ms=c.useCallback(l=>{if(l.status==="calling")return!0;if(!wp(l))return!1;const m=kN(l.timestamp);return m?m>Date.now()-5*60*1e3:!1},[wp]),As=c.useCallback((l,m,x=!1)=>{Ta(l),Ns(m),yn("tool"),gn&&x&&Ut(!0)},[gn,yn]);c.useEffect(()=>{if(e!=="welcome"||!p||!ki.current||Ht.current)return;const l=Ln.current;if(l){ca(l)&&As(l,ms(l),!0),ki.current=!1;return}(async()=>{(q??await qn({openToolPanel:e!=="welcome"}))&&(yn("terminal"),Ut(!0))})(),ki.current=!1},[ca,qn,As,ms,e,p,q]);const iu=c.useCallback(()=>{if(Ve)return;const l=Jr.current;if(!l||l.collapsed)return;const m=xe.current.findIndex(L=>L.type==="reasoning"&&L.content===l);if(m<0)return;const x=xe.current[m],v={...l,collapsed:!0},S={...x,content:v};sl(S),Jr.current=v},[Ve,sl]),Sp=c.useCallback(async(l,m)=>{if(!q){I({type:"error",title:"Session unavailable",description:"Unable to submit answers. Please try again."});return}const x=Math.floor(Date.now()/1e3);cs(!0),bn(!0),on(q,{status:"running",updated_at:x,is_active:!0});try{const S=!!(await cm(q,l,{answers:m}))?.queued,L=`question_prompt-${l}`,H=xe.current.findIndex(N=>N.id===L);if(H>=0){const N=[...xe.current],D=N[H];D.type==="question_prompt"&&(N[H]={...D,content:{...D.content,status:"called",answers:m}},Et(N))}Yr(null),Ds.current=null,Ve&&cn(null),S&&I({type:"info",title:"Answer saved",description:"Agent is offline. Your answer will be delivered once it reconnects."})}catch{cs(!1),bn(!1),on(q,{is_active:!1}),I({type:"error",title:"Failed to submit answers",description:"Please try again."})}},[I,Ve,q,Et,on]),kp=c.useCallback(async(l,m)=>{if(!q||!l){I({type:"error",title:"Session unavailable",description:"Unable to submit answers. Please try again."});return}const x=Math.floor(Date.now()/1e3),v=m.map(S=>String(S).trim()).filter(Boolean);cs(!0),bn(!0),on(q,{status:"running",updated_at:x,is_active:!0});try{const S=await W_(q,l,v),L=`clarify_question-${l}`,H=xe.current.findIndex(N=>N.id===L?!0:N.type!=="clarify_question"?!1:N.content.toolCallId===l);if(H>=0){const N=[...xe.current],D=N[H];D.type==="clarify_question"&&(N[H]={...D,content:{...D.content,status:"answered",selections:v,selectedLabels:S?.selected??[]}},Et(N))}Zr(null),$s.current=null,Ve&&cn(null)}catch{cs(!1),bn(!1),on(q,{is_active:!1}),I({type:"error",title:"Failed to submit answers",description:"Please try again."})}},[I,Ve,q,Et,on]),ur=c.useCallback(l=>{const m=Math.floor(Date.now()/1e3);Rn({id:_n("status"),type:"status",seq:ts(),ts:m,content:{content:l,timestamp:m}})},[Rn,ts]),Xa=c.useCallback((l,m)=>{const x=xe.current.findIndex(N=>N.type!=="tool"?!1:N.content.tool_call_id===l),v=x>=0?xe.current[x]:null,S=v&&typeof v.seq=="number"?v.seq:ts(),L=v&&typeof v.ts=="number"?v.ts:m.timestamp??Math.floor(Date.now()/1e3),H={id:l||_n("tool"),type:"tool",seq:S,ts:L,content:m};if(x>=0){const N=[...xe.current];N[x]=H,Et(N)}else Rn(H);Si.current=m,m.name!=="message"&&(Ln.current=m)},[Rn,ts,Et]),Np=c.useCallback(async l=>{const m=l?.folderId?.trim();if(!t){I({type:"error",title:O("fix_with_ai_project_unavailable_title"),description:O("fix_with_ai_project_unavailable_desc")});return}if(!m){I({type:"warning",title:O("fix_with_ai_open_latex_title"),description:O("fix_with_ai_open_latex_desc")});return}if(te||Ti.current)return;if(Ti.current=!0,Mo(!0),!await qn()){Ti.current=!1,Mo(!1),I({type:"error",title:O("fix_with_ai_session_unavailable_title"),description:O("fix_with_ai_session_unavailable_desc")});return}const v=`fix-with-ai-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,S=Math.floor(Date.now()/1e3),L={project_id:t,folder_id:m},H=fr.getState(),N=nt?.tabId!=null?H.activeIssueByTabId[nt.tabId]:null,D=l.focusedError&&l.focusedError.kind==="latex_error"?l.focusedError:N?.kind==="latex_error"?{kind:N.kind,tabId:N.tabId,fileId:N.fileId,resourceId:N.resourceId,resourcePath:N.resourcePath,resourceName:N.resourceName,line:N.line,message:N.message,severity:N.severity,excerpt:N.excerpt}:null,be=D?`Fix the current LaTeX ${D.severity} in ${D.resourceName||D.resourcePath||"the active document"}${D.line?`:${D.line}`:""}. Focused issue: ${D.message}`:"Fix the current LaTeX compile issues in the active project with the smallest safe patch.";let Y=l.buildId??null,ce=[],ue=null;if(!Y)try{const ge=(await av(t,m,1))?.[0];if(ge?.build_id){if(Y=ge.build_id,Array.isArray(ge.errors)&&ge.errors.length>0)ce=ge.errors.map(Ke=>({path:Ke.path??null,line:typeof Ke.line=="number"?Ke.line:null,message:Ke.message,severity:Ke.severity==="warning"?"warning":"error"}));else if(ge.log_ready)try{ue=await iv(t,m,ge.build_id)}catch(Ke){console.warn("[CopilotAudit][fix-with-ai] Failed to load LaTeX log text",Ke)}}}catch(qe){console.warn("[CopilotAudit][fix-with-ai] Failed to load latest LaTeX build",qe)}Y&&(L.build_id=Y),D&&(L.focused_error=D),ce.length>0?L.log_items=ce:ue&&(L.log_text=ue);const re=Ka(),ee=D?"focused_error":"compile_log",ze=re?{context:re,task_intent:"latex_fix",repair_mode:ee}:{task_intent:"latex_fix",repair_mode:ee},je={event_id:v||_n("tool"),tool_call_id:v,name:"copilot_fix_with_ai",status:"calling",function:"fix_with_ai",args:L,timestamp:S};Xa(v,je),_p.current(v,"tool");try{const qe=await Z_(t,{folder_id:m,...Y?{build_id:Y}:{},...ce.length>0?{log_items:ce}:{},...ce.length===0&&ue?{log_text:ue}:{},...D?{focused_error:D}:{},message:l.promptText?.trim()||be,metadata:ze,recent_files:lr}),ge=Array.isArray(qe)?qe:[];if(ge.length===0){Xa(v,{...je,status:"called",error:"no_timeline_events"}),ur("Fix with AI returned no patch.");return}let Ke=!1;ge.forEach(xt=>{if(!(!xt||typeof xt!="object")){if(xt.type==="tool_call"||xt.type==="tool_result"){const Ue=xt.data,dt=Ue.status==="calling"||Ue.status==="called"?Ue.status:xt.type==="tool_call"?"calling":"called",dn=Ue.args&&typeof Ue.args=="object"&&!Array.isArray(Ue.args)?Ue.args:je.args,Ot={...je,tool_call_id:v,name:typeof Ue.name=="string"&&Ue.name?Ue.name:je.name,function:typeof Ue.function=="string"&&Ue.function?Ue.function:je.function,status:dt,args:dn,content:Ue.content&&typeof Ue.content=="object"&&!Array.isArray(Ue.content)?Ue.content:je.content};Xa(v,Ot),Ke=!0;return}if(xt.type==="patch"){const Ue=xt.data,dt=Math.floor(Date.now()/1e3),dn=PN(Ue,dt,v);if(!dn){const pe=[];typeof Ue.title=="string"&&Ue.title.trim()&&pe.push(Ue.title.trim()),Array.isArray(Ue.explanations)&&Ue.explanations.forEach(Ge=>{typeof Ge=="string"&&Ge.trim()&&pe.push(Ge.trim())}),pe.length>0&&ur(pe.join(" · "));return}const Ot=`patch-review-${Ue.patch_id||v}`,Un=xe.current.findIndex(pe=>pe.id===Ot);if(Un>=0){const pe=[...xe.current],Ge=pe[Un];Ge.type==="patch_review"&&(pe[Un]={...Ge,content:dn},Et(pe))}else Ni.current.has(Ot)||(Ni.current.add(Ot),Rn({id:Ot,type:"patch_review",seq:ts(),ts:dt,content:dn}));ji.current.set(Ot,{projectId:t,folderId:m})}}}),Ke||Xa(v,{...je,status:"called"})}catch(qe){const ge=oo.isAxiosError(qe)&&qe.response?.data?.ok===!1?qe.response?.data:null,Ke=ge?.message||(qe instanceof Error?qe.message:"fix_with_ai_failed"),xt=ge?.request_id,Ue=ge?.suggestion,dt=xt?`${Ke} (request_id: ${xt})`:Ke;Xa(v,{...je,status:"called",error:ge?.code||Ke,content:{error:ge?.code||Ke,message:Ke,request_id:xt,suggestion:Ue}}),ur(dt),I({type:"error",title:"Fix with AI failed",description:[Ke,Ue,xt?`request_id: ${xt}`:null].filter(Boolean).join(" ")})}finally{Ti.current=!1,Mo(!1)}},[nt?.tabId,I,Rn,ur,Ka,qn,t,te,lr,ts,O,Et,Xa]);c.useEffect(()=>{ru.current=Np},[Np]);const Ya=c.useCallback((l,m)=>{const x=xe.current.findIndex(D=>D.id===l);if(x<0)return null;const v=xe.current[x];if(v.type!=="patch_review")return null;const S=v.content,L=typeof m=="function"?m(S):m,H={...v,content:L},N=[...xe.current];return N[x]=H,Et(N),L},[Et]),ou=c.useCallback(async(l,m)=>{const x=xe.current.find(S=>S.id===l);if(!x||x.type!=="patch_review")return;const v=x.content;if(v.status!=="applying"){if(m==="reject"){Ya(l,{...v,status:"rejected"}),ur("Patch rejected."),ji.current.delete(l);return}if(!q){Ya(l,{...v,status:"failed",error:"Session unavailable."}),ur("Patch failed: session unavailable.");return}Ya(l,{...v,status:"applying",error:void 0});try{const S=ji.current.get(l),L=!!S,H=await U_(q,{patch:v.patch,recompile:L});if(!H?.success)throw new Error(H?.error||"apply_patch_failed");const N=Array.isArray(H.effects)?H.effects:[];if(N.forEach(Y=>{!Y||typeof Y!="object"||Y.name&&Pm(Y,{surface:he})}),t){const Y=qu.getState();N.forEach(ce=>{const ue=ce.data||{},re=typeof ue.fileId=="string"?ue.fileId:void 0;re&&(Y.reload({projectId:t,fileId:re}).catch(()=>{}),typeof window<"u"&&window.dispatchEvent(new CustomEvent("ds:file:reload",{detail:{projectId:t,fileId:re,filePath:typeof ue.filePath=="string"?ue.filePath:void 0,source:"patch-review"}})))})}Ya(l,Y=>({...Y,status:"accepted",summary:H.summary??Y.summary}));let D=!1,be=null;if(S)try{const Y=await ov(S.projectId,S.folderId,{auto:!1,stop_on_first_error:!1});D=!0,typeof window<"u"&&window.dispatchEvent(new CustomEvent("ds:latex-build",{detail:{projectId:S.projectId,folderId:S.folderId,buildId:Y.build_id,status:Y.status,errorMessage:Y.error_message??null}}))}catch(Y){be=Y instanceof Error?Y.message:"recompile_failed"}S?(ur(D?"Patch applied. Recompile started.":"Patch applied. Recompile failed to start."),be&&I({type:"error",title:"Recompile failed",description:"Unable to start a new LaTeX build. Please retry."})):ur("Patch applied."),ji.current.delete(l)}catch(S){const H=(oo.isAxiosError(S)&&S.response?.data?.detail?String(S.response.data.detail):null)||(S instanceof Error?S.message:"apply_patch_failed");Ya(l,N=>({...N,status:"failed",error:H})),ur(`Patch failed to apply: ${H}`),I({type:"error",title:"Patch failed",description:H})}}},[I,ur,t,q,he,Ya]),jp=c.useCallback(l=>{const m=xe.current.find(x=>x.id===l.id);return m?l.kind==="assistant"?m.type!=="text_delta"?!1:m.content.status==="in_progress":l.kind==="reasoning"?m.type!=="reasoning"?!1:m.content.status==="in_progress":l.kind==="tool"?m.type!=="tool"&&m.type!=="tool_call"&&m.type!=="tool_result"?!1:m.content.status==="calling":l.kind==="status"?m.type!=="status"?!1:m.content.status==="in_progress":!1:!1},[]),_r=c.useCallback((l,m)=>{if(Ht.current)return;const x=un.current;if(x&&x.id===l&&x.kind===m){Ts.current.set(l,Date.now());return}x&&x.id!==l&&Ts.current.delete(x.id),Ts.current.set(l,Date.now()),un.current={id:l,kind:m},Lr({id:l,kind:m}),wi("display:lock:start",{id:l,kind:m,activeStream:vs.current,buffered:Jn.current.length}),xn.current&&window.clearTimeout(xn.current);const v=()=>{xn.current=window.setTimeout(()=>{const S=un.current;if(!S||S.id!==l||S.kind!==m)return;const L=Ts.current.get(l);if(L!=null){if(Date.now()-L<gN){v();return}Ts.current.delete(l)}if(jp(S)){v();return}un.current=null,Ts.current.delete(l),Lr(null),xn.current=null,_s()},xN)};v()},[_s,jp]);c.useEffect(()=>{_p.current=_r},[_r]);const wr=c.useCallback(l=>{const{id:m,kind:x}=l,v=un.current;!v||v.id!==m||v.kind!==x||(un.current=null,x==="reasoning"&&zs.current&&(window.clearTimeout(zs.current),zs.current=null,Pa.current=null),Ts.current.delete(m),Lr(null),xn.current&&(window.clearTimeout(xn.current),xn.current=null),wi("display:lock:end",{id:m,kind:x,activeStream:vs.current,buffered:Jn.current.length}),_s())},[Xe,_s]);c.useEffect(()=>{if(la||eu||ps.status!=="closed"&&ps.status!=="error")return;const l=un.current;if(l){wr(l);return}Jn.current.length>0&&_s()},[ps.status,wr,_s,la,eu]),c.useEffect(()=>{te||!q||la||Ps.current||ps.status!=="closed"&&ps.status!=="error"||!(dc||Ar||tu||Ml(De))||Ea.current||(Ea.current=window.setTimeout(()=>{Ea.current=null,cr({sessionId:q,message:"",surface:he,executionTarget:Le.current,cliServerId:Je.current,replayFromLastEvent:!0}).catch(m=>{console.warn("[AiManus] Auto-resume stream failed",m)})},800))},[ps.status,tu,la,Ar,te,cr,dc,q,De,he]);const lu=c.useCallback(()=>{zs.current&&window.clearTimeout(zs.current),zs.current=window.setTimeout(()=>{const l=un.current,m=Pa.current;if(!l||l.kind!=="reasoning"||!m){zs.current=null;return}if(Date.now()-m<Lh){lu();return}Vc();const x=un.current;x?.kind==="reasoning"&&wr({id:x.id,kind:"reasoning"}),Pa.current=null,zs.current=null},Lh)},[wr,Vc]),Za=c.useCallback((l,m)=>{const x=l==="failed"?"failed":l==="paused"?"paused":"completed";let v=!1;const S=xe.current.map(L=>{if(L.type==="text_delta"){const H=L.content;if(H.role==="assistant"&&H.status==="in_progress")return v=!0,{...L,content:{...H,status:"completed"}}}else if(L.type==="reasoning"){const H=L.content;if(H.status==="in_progress")return v=!0,{...L,content:{...H,status:"completed"}}}else if(L.type==="tool_call"){const H=L.content;if(H.status==="calling")return v=!0,{...L,content:{...H,status:"called"}}}else if(L.type==="step"){const H=L.content;if(H.status==="running")return v=!0,{...L,content:{...H,status:x}}}else if(L.type==="question_prompt"){const H=L.content;if(H.status==="calling")return v=!0,{...L,content:{...H,status:"called"}}}else if(L.type==="clarify_question"){const H=L.content;if(H.status==="calling")return v=!0,{...L,content:{...H,status:"called"}}}return L});if(v){Et(S);for(const[L,H]of rr.current.entries()){const N=S.find(D=>D.id===H.id);N&&N!==H&&rr.current.set(L,N)}for(let L=S.length-1;L>=0;L-=1){const H=S[L];if(H.type==="reasoning"){Jr.current=H.content;break}}}Ds.current&&(Yr(null),Ds.current=null),$s.current&&(Zr(null),$s.current=null),Bn.current?.status==="running"&&(Bn.current.status=x),Si.current?.status==="calling"&&(Si.current.status="called"),Ln.current?.status==="calling"&&(Ln.current.status="called"),Ns(!1),un.current&&(un.current=null,Ts.current.clear(),Lr(null)),xn.current&&(window.clearTimeout(xn.current),xn.current=null),m?.flushBuffered===!1?Jn.current=[]:_s()},[_s,Et,Ns]),My=c.useCallback((l,m)=>{const x=m??il.current,v={runId:x,reason:l};Tr.current=v,uc(v),x>0&&(Ca.current=x),cn(l==="paused"?"Paused":"Cancelled"),Za("paused",{flushBuffered:!1}),ds.current.clear(),vs.current=null,xn.current&&(window.clearTimeout(xn.current),xn.current=null),un.current=null,Ts.current.clear(),Lr(null)},[Za]);c.useCallback(()=>{const l=il.current;l>0&&(Ca.current=l),Jc(),Za("paused",{flushBuffered:!1}),ds.current.clear(),vs.current=null,xn.current&&(window.clearTimeout(xn.current),xn.current=null),un.current=null,Ts.current.clear(),Lr(null)},[Za,Jc]);const Vi=c.useCallback(l=>{if(!l?.data||typeof l.data!="object")return;if(Ht.current){const N=l.data,D=typeof N.event_id=="string"?N.event_id:null;D&&_c.current.add(D)}const m=l.data?.metadata;if(!Ht.current&&Ve&&(m?.surface||m?.reply_to_surface)&&(l.event==="message"||l.event==="attachments")){const D=l.data.role==="assistant"?m.reply_to_surface??m.surface:m.surface??m.reply_to_surface;if((D==="welcome"||D==="copilot")&&!(D===he||he==="copilot"&&D==="welcome"||he==="welcome"&&D==="copilot"))return}const x=!!Ds.current,v=!!$s.current;if((x||v)&&!Ht.current){if(l.event==="reasoning")return;if(l.event==="message"){const N=l.data;if(Hd(N.role)==="assistant")return}if(l.event==="tool"){const N=l.data,D=Ll(typeof N.function=="string"?N.function:"");if(D!=="question_prompt"&&D!=="clarify_question")return}if(l.event==="plan"||l.event==="step")return}const S=l.event==="message"||l.event==="tool"||l.event==="step"||l.event==="status"||l.event==="reasoning"||l.event==="attachments"||l.event==="plan"||l.event==="wait"||l.event==="error"||l.event==="done";Ar&&S&&cs(!1),un.current?.kind==="reasoning"&&l.event!=="reasoning"&&Vc();const L=l.data?.event_id,H=(l.event==="message"||l.event==="reasoning")&&typeof l.data?.delta=="string"&&!!l.data.delta;if(L&&q&&!H&&j(q,L),ol(l)){const N=Jn.current.length===0;Jn.current.push(l),N&&wi("buffer:start",{event:l.event,eventId:l.data?.event_id??null,lock:un.current,activeStream:vs.current});return}if(l.event==="message"||l.event==="tool"||l.event==="step"||l.event==="attachments"?Ua(!0):l.event!=="reasoning"&&Ua(),!((l.event==="message"||l.event==="attachments"||l.event==="receipt")&&aS(l,{sessionId:q,messagesRef:xe,assistantMessageIndexRef:Nf,lastAssistantSegmentIdRef:zo,attachmentsSeenRef:Tf,pendingUserRef:Sc,resolveTimelineSeq:ts,buildTextDeltaId:Ry,appendMessage:Rn,updateMessages:Et,queueMessages:Wc,closeAssistantSegment:()=>{su(),iu()},startDisplayLock:D=>_r(D,"assistant"),setCopilotStatus:Ve?cn:void 0,onSessionUpdate:q?(D,be)=>{on(q,{latest_message:D,latest_message_at:be,updated_at:be,status:ar.current??null})}:void 0,shouldDeferAttachments:()=>!!un.current&&!Ht.current,onDeferAttachments:D=>{Jn.current.push(D)}}))){if(l.event==="reasoning"){const N=l.data,D=typeof N.reasoning_id=="string"&&N.reasoning_id?N.reasoning_id:"";if(!D)return;const be=ts(xr(l)),Y=N.status==="completed"?"completed":"in_progress",ce=typeof N.delta=="string"?N.delta:"",ue=typeof N.content=="string"?N.content:"";(!!(ue||ce)||Pa.current==null)&&(Pa.current=Date.now(),lu());const ee=Uh(N.kind),ze=Cs(N.timestamp),je=Wh(D,ee,N.reasoning_stream_id);vs.current&&vs.current!==je&&Ua(!0);const qe=$i(je),ge=rr.current.get(qe);if(ge&&ge.type==="reasoning"){const xt=ge.content,Ue=typeof xt.content=="string"?xt.content:"";let dt=Ue;ue?dt=ue:ce&&(dt=`${Ue}${ce}`);const dn={...xt,content:dt,status:Y,kind:ee,timestamp:ze},Ot={...ge,content:dn};nl(Ot,{throttle:Y==="in_progress"&&!!ce})||Et([...xe.current,Ot]),rr.current.set(qe,Ot),Jr.current=dn,vs.current=je,_r(ge.id,"reasoning"),Y==="completed"?(ds.current.delete(je),!Ht.current&&ds.current.size===0&&_s()):ds.current.add(je);return}if(!ue&&!ce)return;const Ke={id:typeof N.event_id=="string"?N.event_id:_n("reasoning"),type:"reasoning",seq:be,ts:ze,content:{reasoning_id:D,status:Y,content:ue||ce,kind:ee,timestamp:ze,collapsed:!1}};Rn(Ke),rr.current.set(qe,Ke),Jr.current=Ke.content,vs.current=je,_r(Ke.id,"reasoning"),Y==="completed"?(ds.current.delete(je),!Ht.current&&ds.current.size===0&&_s()):ds.current.add(je);return}if(l.event==="tool"){const N=l.data,D=ts(xr(l)),be=Cs(N.timestamp),Y=typeof N.function=="string"?N.function:"",ce=Ll(Y),ue=typeof N.tool_call_id=="string"&&N.tool_call_id?N.tool_call_id:_n("tool"),re=N.status==="calling"||N.status==="called"?N.status:"called",ee=typeof N.name=="string"?N.name:"",ze=un.current;if(su(),ze?.kind==="assistant"&&wr(ze),!Ht.current&&re==="calling"&&ee!=="message"){const pe=jf.current;pe.has(ue)||(pe.add(ue),af(Ge=>Ge+1))}if(re==="calling"&&(iu(),!Ht.current&&typeof window<"u"&&window.dispatchEvent(new CustomEvent("ds:tool:call",{detail:{toolCallId:ue,function:ce,name:ee,status:re}}))),!Ht.current&&re==="calling"){const pe=IN(N);pe&&Md(pe)}if(ce==="context_read"&&re==="calling"&&q){if(!Ht.current){const pe=Ka();pe&&cm(q,ue,{context:pe})}return}if(ce==="question_prompt"){const pe=be,Ge=`question_prompt-${ue}`,Zt=xe.current.findIndex(et=>et.id===Ge),rt=N.args&&typeof N.args=="object"&&!Array.isArray(N.args)?N.args:{},_t={timestamp:pe,metadata:N.metadata,toolCallId:ue,args:rt,status:re};if(re==="called"){const et=N.content&&typeof N.content=="object"&&!Array.isArray(N.content)?N.content:{},Jt=typeof et.error=="string"?et.error:"",tn=et.result&&typeof et.result=="object"&&!Array.isArray(et.result)?et.result:null,Pn=typeof tn?.status=="string"?tn.status.toLowerCase():"",Nn=tn&&typeof tn.answers=="object"&&tn.answers&&!Array.isArray(tn.answers)?tn.answers:void 0,kr=tn&&typeof tn.reason=="string"?tn.reason:"",jn=Array.isArray(tn?.errors)?tn?.errors:[],Hs=Jt||(Pn&&Pn!=="ok"&&Pn!=="success"?[kr||"Tool error",jn.length?`(${jn.join(", ")})`:""].filter(Boolean).join(" "):"")||"";Nn&&(_t.answers=Nn),Hs&&(_t.error=Hs)}if(Zt>=0){const et=[...xe.current],Jt=et[Zt];Jt.type==="question_prompt"&&(et[Zt]={...Jt,content:{...Jt.content,..._t}},Et(et))}else Rn({id:Ge,type:"question_prompt",seq:D,ts:pe,content:_t});const st=ar.current;if(te){Yr(null),Ds.current=null;return}if(re==="calling"){if(!br.current||st==="waiting"){const et={toolCallId:ue,args:rt};Yr(et),Ds.current=et}Ve&&cn("Waiting for your input")}else re==="called"&&(Yr(null),Ds.current=null,Ve&&cn(null));return}if(ce==="clarify_question"){const pe=be,Ge=`clarify_question-${ue}`,Zt=xe.current.findIndex(jn=>jn.id===Ge),rt=N.args&&typeof N.args=="object"&&!Array.isArray(N.args)?N.args:{},_t=typeof rt.question=="string"?rt.question:typeof rt.title=="string"?rt.title:"Clarify request",st=jN(rt.options??rt.choices??rt.values),et=NN(rt.multi??rt.multiple),Jt=qh(rt.default_selected??rt.defaultSelected),tn=qh(rt.missing_fields??rt.missingFields),Pn=typeof rt.question_id=="string"?rt.question_id:typeof rt.questionId=="string"?rt.questionId:typeof rt.id=="string"?rt.id:"",Nn={timestamp:pe,metadata:N.metadata,toolCallId:ue,question:_t,options:st,multi:et,status:re==="calling"?"calling":"called",defaultSelected:Jt,missingFields:tn,source:"backend"};if(re==="called"){const jn=N.content&&typeof N.content=="object"&&!Array.isArray(N.content)?N.content:{},Hs=typeof jn.error=="string"?jn.error:"",Wn=jn.result&&typeof jn.result=="object"&&!Array.isArray(jn.result)?jn.result:null,Gi=typeof Wn?.status=="string"?Wn.status.toLowerCase():"",fl=Wn&&typeof Wn.answers=="object"&&Wn.answers&&!Array.isArray(Wn.answers)?Wn.answers:void 0,Qy=Wn&&typeof Wn.reason=="string"?Wn.reason:"",Gp=Array.isArray(Wn?.errors)?Wn?.errors:[],Qp=Hs||(Gi&&Gi!=="ok"&&Gi!=="success"?[Qy||"Tool error",Gp.length?`(${Gp.join(", ")})`:""].filter(Boolean).join(" "):"")||"";if(fl){const Xy=Pn&&fl[Pn]!==void 0?fl[Pn]:Object.values(fl)[0],hu=TN(Xy,st);hu.selections.length>0&&(Nn.selections=hu.selections,Nn.selectedLabels=hu.selectedLabels)}Qp&&(Nn.error=Qp)}if(Zt>=0){const jn=[...xe.current],Hs=jn[Zt];Hs.type==="clarify_question"&&(jn[Zt]={...Hs,content:{...Hs.content,...Nn}},Et(jn))}else Rn({id:Ge,type:"clarify_question",seq:D,ts:pe,content:Nn});const kr=ar.current;if(te){Zr(null),$s.current=null;return}if(re==="calling"){if(!br.current||kr==="waiting"){const jn={messageId:Ge,toolCallId:ue,source:"backend",question:_t,options:st,multi:et,defaultSelected:Jt,missingFields:tn};Zr(jn),$s.current=jn}Ve&&cn("Waiting for your input")}else re==="called"&&(Zr(null),$s.current=null,Ve&&cn(null));return}if(ce==="mcp_status_update"){const pe=N.args&&typeof N.args=="object"&&!Array.isArray(N.args)?N.args:{};qa(Hc(pe.todo,pe.next));const Ge=typeof pe.message=="string"?pe.message:typeof pe.text=="string"?pe.text:"";if(!((N.status==="calling"||N.status==="called"?N.status:"called")==="calling"||N.status==null)||!Ge){Ve&&cn(null);return}const _t=be,st=typeof N.event_id=="string"&&N.event_id?N.event_id:"",et=Du(st,ue,_t),Jt=wc.current,tn={...N,event_id:st||_n("tool"),tool_call_id:ue,function:Y||ce,name:typeof N.name=="string"&&N.name?N.name:"message",status:"called",args:{...pe,message:Ge},timestamp:_t},Pn=xe.current.findIndex(Nn=>Nn.id===et);if(Pn>=0){const Nn=[...xe.current],kr=Nn[Pn];kr.type==="tool"&&(Nn[Pn]={...kr,content:tn},Et(Nn))}else Jt.has(et)||Rn({id:et,type:"tool",seq:D,ts:_t,content:tn});_r(et,"tool"),Ve&&cn(null),Jt.add(et);return}const je=N.metadata,qe=typeof je?.execution_target=="string"?je.execution_target.trim().toLowerCase():"",ge=qe==="cli"||qe==="cli_server"||!!je?.cli_server_id||!qe&&P==="cli",Ke=he.startsWith("lab-"),xt=[...N.ui_effect?[N.ui_effect]:[],...N.ui_effects??[]],Ue=xt.length>0?xt:MN(N,re);if(Ue.length>0&&!Ht.current){const pe=Ke&&ge;Ue.forEach(Ge=>{const Zt=typeof Ge?.name=="string"&&Ge.name.startsWith("file:");pe&&Zt||Pm(Ge,{surface:he})})}if(Ke&&ge&&!Ht.current&&Tw({toolData:N,functionName:Y||ce,status:re,projectId:t??null,sessionId:q,cliServerId:typeof je?.cli_server_id=="string"?je.cli_server_id:B,readOnly:te}),Ve)if(ge&&re==="calling")cn(null);else{const pe=`${N.name??"tool"} · ${ce}`;cn(re==="calling"?pe:null)}const dt={...N,event_id:typeof N.event_id=="string"&&N.event_id?N.event_id:_n("tool"),tool_call_id:ue,function:Y||ce,name:typeof N.name=="string"&&N.name?N.name:"tool",status:re,args:N.args&&typeof N.args=="object"&&!Array.isArray(N.args)?N.args:{},timestamp:be};if(yr(Y||ce)==="request_patch"&&re==="called"){const pe=LN(N,ue);if(pe){const Ge=`patch-review-${ue}`,Zt=xe.current.findIndex(rt=>rt.id===Ge);if(Zt>=0){const rt=[...xe.current],_t=rt[Zt];if(_t.type==="patch_review"){const st=_t.content,et={...pe,status:st.status??pe.status,error:st.error??pe.error,summary:st.summary??pe.summary};rt[Zt]={..._t,content:et},Et(rt)}}else Ni.current.has(Ge)||(Ni.current.add(Ge),Rn({id:Ge,type:"patch_review",seq:D,ts:pe.timestamp??be,content:pe}))}}if(ce==="sandbox_switch"&&re==="called"&&!Ht.current){const pe=dt.args,Ge=typeof pe?.target=="string"?pe.target.toLowerCase():"",Zt=typeof dt.content?.result=="object"&&dt.content?.result?String((dt.content?.result).provider_type??""):"",rt=typeof pe?.cli_server_id=="string"?pe.cli_server_id:"",_t=dt.content?.error,st=_t?$h(_t):void 0,et=st?"Runtime switch failed":"Runtime switched",Jt=Ge==="cli"||Ge==="cli_server"||Zt==="cli"?"CLI":"Sandbox",tn=st||(Jt==="CLI"&&rt?`Now using CLI server ${rt.slice(0,6)}`:`Now using ${Jt}`);I({type:st?"error":"info",title:et,description:tn,duration:6e3})}const Ot=pe=>{const Ge=pe.tool_call_id;if(!Ge)return!1;const Zt=xe.current,rt=Zt.findIndex(st=>st.type!=="tool"?!1:st.content.tool_call_id===Ge);if(rt>=0){const st=[...Zt],et=st[rt];if(et.type==="tool")return st[rt]={...et,content:pe},Et(st),!0}const _t=Zt.findIndex(st=>st.type!=="step"?!1:st.content.tools.some(Jt=>Jt.tool_call_id===Ge));if(_t>=0){const st=[...Zt],et=st[_t];if(et.type==="step"){const Jt=et.content,tn=Jt.tools.map(Nn=>Nn.tool_call_id===Ge?pe:Nn),Pn={...Jt,tools:tn};return st[_t]={...et,content:Pn},Et(st),Bn.current?.id===Jt.id&&(Bn.current=Pn),!0}}return!1};((pe,Ge)=>{if(!Ot(pe)){let rt=!1;if(!Ve&&Bn.current&&Bn.current.status==="running"){const _t=Bn.current.id,st=[...xe.current],et=st.findIndex(Jt=>Jt.type!=="step"?!1:Jt.content.id===_t);if(et>=0){const Jt=st[et];if(Jt.type==="step"){const tn=Jt.content,Pn=Array.isArray(tn.tools)?tn.tools:[],Nn=pe.tool_call_id,kr=Nn?Pn.findIndex(Wn=>Wn.tool_call_id===Nn):-1,jn=kr>=0?Pn.map((Wn,Gi)=>Gi===kr?pe:Wn):[...Pn,pe],Hs={...tn,tools:jn};st[et]={...Jt,content:Hs},Et(st),Bn.current=Hs,rt=!0}}}rt||Rn({id:pe.tool_call_id||_n("tool"),type:"tool",seq:D,ts:pe.timestamp??be,content:pe})}Si.current=pe,pe.name!=="message"&&_r(pe.tool_call_id,"tool"),pe.name!=="message"&&(Ln.current=pe,!Ht.current&&(Pt.current||pe.status==="calling")&&ca(pe)&&As(pe,ms(pe)))})(dt);return}if(l.event==="status"){const N=l.data,D=typeof N.message=="string"?N.message:typeof N.text=="string"?N.text:"";if(!D)return;const be=Cs(N.timestamp),Y=ts(xr(l)),ce=typeof N.event_id=="string"?N.event_id:"",ue=typeof N.tool_call_id=="string"?N.tool_call_id:"",re=Du(ce,ue,be);qa(Hc(N.todo,N.next));const ee=wc.current,{metadata:ze,event_id:je,timestamp:qe,seq:ge,created_at:Ke,tool_call_id:xt,...Ue}=N,dt={event_id:ce||_n("tool"),tool_call_id:ue||_n("tool"),name:"message",status:"called",function:"mcp_status_update",args:{...Ue,message:D},timestamp:be,metadata:ze},dn=xe.current.findIndex(Ot=>Ot.id===re);if(dn>=0){const Ot=[...xe.current],Un=Ot[dn];Un.type==="tool"&&(Ot[dn]={...Un,content:dt},Et(Ot))}else ee.has(re)||Rn({id:re,type:"tool",seq:Y,ts:be,content:dt});_r(re,"tool"),Ve&&cn(null),ee.add(re);return}if(l.event==="step"){const N=l.data,D=N.status;if(!D)return;const be=typeof N.description=="string"?N.description:"",Y=Cs(N.timestamp),ce=ts(xr(l)),ue=typeof N.id=="string"&&N.id?N.id:_n("step");if(Ve&&cn(D==="completed"?null:D==="failed"?"Step failed":`Step ${D}: ${be}`),D==="running"){const re=ue.startsWith("step-")?ue.slice(5):null;let ee=null;const ze=[...xe.current];if(re){const qe=ze.findIndex(ge=>ge.type!=="tool"?!1:ge.content.tool_call_id===re);if(qe>=0){const ge=ze[qe];ge.type==="tool"&&(ee=ge.content,ze.splice(qe,1))}}const je={...N,id:ue,status:D,description:be,timestamp:Y,tools:ee?[ee]:[]};ze.push({id:ue,type:"step",seq:ce,ts:Y,content:je}),Et(ze),Bn.current=je}else if(D==="completed"){if(Bn.current){const re=Bn.current.id,ee=[...xe.current],ze=ee.findIndex(je=>je.type!=="step"?!1:je.content.id===re);if(ze>=0){const je=ee[ze];if(je.type==="step"){const ge={...je.content,status:D};ee[ze]={...je,content:ge},Et(ee),Bn.current=ge}}else Bn.current={...Bn.current,status:D}}}else D==="failed"&&Ve&&cn("Step failed");Mn(re=>{if(re?.task_plan?.tasks?.length)return re;const ee=re?.steps?[...re.steps]:[],ze=ee.findIndex(je=>je.id===ue);return ze>=0?ee[ze]={...ee[ze],...N,id:ue,status:D,description:be,timestamp:Y}:ee.push({...N,id:ue,status:D,description:be,timestamp:Y}),{event_id:re?.event_id||N.event_id||_n("plan"),timestamp:Y,metadata:N.metadata,steps:ee}});return}if(l.event==="error"){const N=l.data,D=typeof N.error=="string"&&N.error?N.error:"Unexpected error",be=$h(D),Y=Cs(N.timestamp),ce=ts(xr(l));Rn({id:_n("error"),type:"assistant",seq:ce,ts:Y,content:{content:be,timestamp:Y,role:"assistant"}}),cn("Error"),bn(!1),q&&on(q,{status:"failed",updated_at:Y,is_active:!1}),ds.current.clear(),Ht.current||(un.current&&(un.current=null,Ts.current.clear(),Lr(null)),xn.current&&(window.clearTimeout(xn.current),xn.current=null),_s());return}if(l.event==="title"){const N=l.data,D=typeof N.title=="string"?N.title:"";if(!D)return;(q?or(q):"")||le(D),q&&on(q,{title:D});return}if(l.event==="plan"){const N=l.data,D=Qg(N);if(!D)return;const be=D.steps.length>0,Y=!!D.task_plan?.tasks?.length;Mn(D),en(ce=>{if(!be&&!Y)return ce;const ue=[...ce],re=ue.findIndex(qe=>qe.event_id===D.event_id);if(re>=0)return ue[re]=D,ue;const ze=ue[ue.length-1]?.task_plan?.hash,je=D.task_plan?.hash;return ze&&je&&ze===je?(ue.length>0&&(ue[ue.length-1]=D),ue):(ue.push(D),ue)});return}if(l.event==="wait"){Ve&&cn("Waiting for your input"),bn(!1),q&&on(q,{status:"waiting",updated_at:Cs(l.data?.timestamp),is_active:!1});return}if(l.event==="recovery"){if(Ht.current)return;const N=l.data,D=N.status==="recovered"||N.status==="failed"?N.status:"recovering",be=typeof N.missed_event_count=="number"?N.missed_event_count:null,Y=D==="recovering"?"Recovering CLI stream...":D==="recovered"?be!=null?`Recovered ${be} events`:"Recovery completed":"Recovery failed. Please retry.";uf({status:D,message:Y}),Cr.current&&(window.clearTimeout(Cr.current),Cr.current=null),D!=="recovering"&&(Cr.current=window.setTimeout(()=>{uf(null),Cr.current=null},4e3));return}l.event==="done"&&(Ve&&cn(null),Qe("completed"),qa(null),bn(!1),Za("completed"),q&&on(q,{status:"completed",updated_at:Math.floor(Date.now()/1e3),is_active:!1}),ds.current.size>0&&(ds.current.clear(),Ht.current||_s()))}},[Rn,Ka,ca,Za,su,Ua,iu,wr,_s,or,$i,As,ms,e,Ar,he,te,nl,q,lu,ol,cs,_r,j,on,Et,qa,Hc]);c.useEffect(()=>{oa.current=Vi},[Vi]),c.useEffect(()=>()=>{Cr.current&&(window.clearTimeout(Cr.current),Cr.current=null),Ea.current&&(window.clearTimeout(Ea.current),Ea.current=null)},[]),c.useEffect(()=>{vc.current&&vc.current!==q&&(Pr.current=null,ta.current=null,Os.current=null),vc.current=q??null},[q]),c.useEffect(()=>{if(!q){Pr.current=null,ta.current=null,Os.current=null,Ra(!1),Ps.current=!1,bn(!1);return}if(Sn&&Os.current===q)return;const l=ja.current;l&&(ja.current=!1);const m=we.current.find(ce=>ce.session_id===q),x=xe.current.length>0,v=!x&&ta.current!==q;if(Pr.current===q&&!v&&!l)return;ta.current=v?q:null,Pr.current=q,Rf(!0);let S=!0;const L=Ir.current;if(Ir.current=!1,L)return Xe("restore:skip",{sessionId:q,reason:"skip_restore_ref"}),Os.current=null,Ra(!1),Ps.current=!1,na.current&&(na.current=!1,Ho(!1)),Qa(),()=>{S=!1};Os.current=q;const H=Kc(m??null,q),N=b_(q),D=N?io([...N]):null;if(D&&(xl(q,D),ya(q))){const ce=Pl(D);ce&&j(q,ce)}const be=!!(D&&D.length>0);if(Xe("restore:start",{sessionId:q,forceRestore:l,shouldRetry:v,hasMessages:x,hasCachedEvents:be,hasSessionMeta:!!m,cachedEvents:D?.length??0}),Us({title:H}),Ra(!0),Ps.current=!0,m){const ce=Vs(m.status??null),ue=!!m.is_active||ti(ce);bn(ue)}if(be){Ie(!1),Pt.current=!1,Ht.current=!0,ar.current=Vs(m?.status??null),br.current=!0;try{const Ue=oa.current??Vi;if(Ue)for(const dt of D??[])try{Ue(dt)}catch(dn){console.warn("[AiManus] Failed to replay cached event",dn)}}finally{br.current=!1,Ht.current=!1,ar.current=null,Ba(),Qa()}Ie(!0),Pt.current=!0;const ce=we.current.find(Ue=>Ue.session_id===q),ue=typeof ce?.is_active=="boolean"?ce.is_active:typeof m?.is_active=="boolean"?m.is_active:null,re=ce?.status??m?.status??null,ee=Vs(re),ze=!!ue||Ml(ee),je=!!ue||ti(ee),qe=xe.current.some(Ue=>Ue.type!=="assistant"?!1:Ue.content.status==="in_progress"),ge=Ln.current?.status==="calling",Ke=Bn.current?.status==="running",xt=ze||qe||ge||Ke;if(je&&bn(!0),xt){cr({sessionId:q,message:"",surface:he,executionTarget:Le.current,cliServerId:Je.current,replayFromLastEvent:!0}).catch(dt=>{console.warn("[AiManus] Failed to resume stream",dt)});const Ue=Ln.current;Ue&&(Ue.status==="calling"||ms(Ue))&&ca(Ue)&&As(Ue,ms(Ue))}if(ya(q)&&!l&&!na.current)return Xe("restore:skip",{sessionId:q,reason:"quest_cache_replay"}),Ra(!1),Ps.current=!1,Os.current===q&&(Os.current=null),()=>{S=!1}}return(async()=>{Ci.current=!1;const ce=typeof performance<"u"?performance.now():Date.now();let ue=!1,re=!1;try{if(Xe("restore:fetch",{sessionId:q}),typeof window<"u"){const pe=er(),Ge=!!window.localStorage.getItem("ds_access_token");console.info("[CopilotAudit][restore] GET /api/v1/sessions/{id}",{sessionId:q,url:`${pe}/api/v1/sessions/${q}`,hasUserToken:Ge})}if(ue=na.current,re=Oo.current||ue,ue&&(na.current=!1),ya(q)&&!be){const pe=await L_(q,re?{full:!0}:void 0);if(!S)return;const Ge=io(pe);Ci.current=Ge.length>=Yo,Tc(!1),Ac(re?null:Ge.length||null);const Zt=or(q);Us({title:Zt||H}),Ie(!1),Pt.current=!1,Ht.current=!0,ar.current=Vs(m?.status??null);try{if(xl(q,Ge),Ge.length===0)j(q,null);else{const et=Pl(Ge);et&&j(q,et)}const st=oa.current??Vi;if(st){br.current=!0;try{for(const et of Ge)st(et)}finally{br.current=!1}}}finally{Ht.current=!1,ar.current=null,Ba(),Qa(),Ie(!0),Pt.current=!0}const rt=Vs(m?.status??null);(!!m?.is_active||Ml(rt))&&cr({sessionId:q,message:"",surface:he,executionTarget:Le.current,cliServerId:Je.current,replayFromLastEvent:!0}).catch(st=>{console.warn("[AiManus] Failed to resume quest stream",st)});return}const ee=await _d(q,re?{full:!0}:void 0);if(!S||!ee){S&&(Pr.current=null,!ee&&xe.current.length===0&&(ta.current=null));return}const ze=Array.isArray(ee.events)?ee.events.length:0;Ci.current=ze>=Yo;const je=!!ee.events_truncated,qe=typeof ee.event_limit=="number"?ee.event_limit:null;Tc(je),Ac(qe),re&&(je?(Oo.current=!1,Cc(!1)):(Oo.current=!0,Cc(!0))),Pe(ee);const ge=Vs(ee.status??null),Ke=!!ee.is_active||ti(ge);Ke&&bn(!0),console.info("[CopilotAudit][restore] session fetched",{sessionId:q,title:ee.title??null,status:ee.status??null,events:ee.events?.length??0,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-ce)}),Xe("restore:fetched",{sessionId:q,title:ee.title??null,status:ee.status??null,events:ee.events?.length??0});const xt=ee.title&&ee.title.trim().length>0?ee.title:H,Ue=or(q);be?Us({title:Ue||xt}):ee.title&&le(Ue||ee.title);const dt=Xh(ee.plan_history);let dn=[];if(dt.length===0&&Array.isArray(ee.events)){const pe=ee.events.filter(Ge=>Ge?.event==="plan").map(Ge=>Ge.data);dn=Xh(pe)}const Ot=dt.length>0?dt:dn;Ot.length>0&&(en(Ot),Mn(Ot[Ot.length-1])),Ie(!1),Pt.current=!1,Ht.current=!0,ar.current=Vs(ee.status??null);try{const pe=oa.current??Vi;if(pe){const Ge=[],Zt=Gh(ee.agents),rt=ee.session_metadata&&typeof ee.session_metadata=="object"?ee.session_metadata:null;for(const st of ee.events??[]){const et=Kh(st);et&&Ge.push(Qh(et,rt,Zt))}const _t=io(Ge);if(xl(q,_t),_t.length===0)j(q,null);else if(ya(q)){const st=Pl(_t);st&&j(q,st)}br.current=!0;try{for(const st of _t)try{pe(st)}catch(et){console.warn("[AiManus] Failed to restore event",et)}}finally{br.current=!1}}}finally{Ht.current=!1,ar.current=null,Ba(),Qa()}if(Ke&&bn(!0),Ie(!0),Pt.current=!0,!!ee.is_active||Ml(ge)){cr({sessionId:q,message:"",surface:he,executionTarget:Le.current,cliServerId:Je.current,replayFromLastEvent:!0}).catch(Ge=>{console.warn("[AiManus] Failed to resume stream",Ge)});const pe=Ln.current;pe&&(pe.status==="calling"||ms(pe))&&ca(pe)&&As(pe,ms(pe))}}catch(ee){const ze=Math.round((typeof performance<"u"?performance.now():Date.now())-ce),je=typeof window<"u"?er():null,qe=oo.isAxiosError(ee)?{status:ee.response?.status??null,statusText:ee.response?.statusText??null,url:typeof ee.config?.url=="string"?ee.config.url:null}:null;if(console.warn("[CopilotAudit][restore] failed",{sessionId:q,apiBaseUrl:je,durationMs:ze,axios:qe,message:ee instanceof Error?ee.message:String(ee)}),console.error("[AiManus] Failed to restore session",ee),Xe("restore:error",{sessionId:q,message:ee instanceof Error?ee.message:String(ee)}),S&&(Pr.current=null,ta.current=null),S&&t&&oo.isAxiosError(ee)&&(ee.response?.status===404||ee.response?.status===403)&&!(Nc.current?.projectId===t&&Nc.current?.sessionId===q))if(Nc.current={projectId:t,sessionId:q},pa()){const Ke=Hr(t);console.info("[CopilotAudit][restore] switch to quest session",{projectId:t,failedSessionId:q,sessionId:Ke,status:ee.response?.status??null}),ot(t,he),Ze(t,he,Ke),hn.current===Ke&&$n()}else{console.info("[CopilotAudit][restore] fallback to product latest session",{projectId:t,failedSessionId:q,status:ee.response?.status??null,url:`${er()}/api/v1/sessions/latest`}),ot(t,he);try{const Ke=await Xi(t,void 0,he);Pe(Ke??void 0);const xt=Ke?.session_id??null;console.info("[CopilotAudit][restore] fallback latest resolved",{projectId:t,sessionId:xt,events:Ke?.events?.length??0}),xt&&(Ze(t,he,xt),$n())}catch(Ke){console.warn("[CopilotAudit][restore] fallback latest failed",Ke)}}}finally{S&&(Ra(!1),Ps.current=!1,ue&&Ho(!1),Qa(),Os.current===q&&(Os.current=null),console.info("[CopilotAudit][restore] done",{sessionId:q,messages:xe.current.length}),Xe("restore:done",{sessionId:q}))}})(),()=>{S=!1,Os.current===q&&(Os.current=null,Pr.current===q&&(Pr.current=null),ta.current=null,Ht.current=!1,ar.current=null,Ra(!1),Ps.current=!1)}},[ca,ot,Xe,Ba,Qa,As,ms,e,t,Us,lc,$n,cr,he,q,Ze,Pe,Yo]);const Tp=l=>{e==="welcome"&&(Ie(!1),Pt.current=!1,As(l,ms(l),!0))},Ap=()=>{Ie(!0),Pt.current=!0,Ln.current&&!Hh(Ln.current)&&As(Ln.current,ms(Ln.current))},cu=c.useCallback(async l=>{const m=ne(l);if(!m){I({type:"error",title:"File not found",description:"The attachment could not be opened."});return}await X(m,{customData:t?{projectId:t}:void 0})},[I,ne,X,t]),Cp=c.useCallback(async l=>{const m=Gs(l);if(!m)return;const x=Te.find(S=>{if(S.context?.type!=="file"&&S.context?.type!=="notebook")return!1;const L=S.context.resourcePath;return L?Gs(L)===m:!1});if(x){He(x.id);return}const v=ke(m);if(!v){I({type:"error",title:"File not found",description:"The recent file could not be opened."});return}await X(v,{customData:t?{projectId:t}:void 0})},[I,ke,X,t,He,Te]),Ep=c.useMemo(()=>ps.status==="rate_limited"?"Rate limited. Retrying…":ps.status==="reconnecting"?"Reconnecting…":ps.status==="error"?ps.error||"Connection error":null,[ps.error,ps.status]),Ly=Aa?.reason==="cancelled"?"Cancelled":"Paused",Py=!!Aa,Dy=!!lf&&!Aa&&(!Oa||Ve),$y=Lo?.status==="failed"?"border-[var(--function-error)] bg-[var(--function-error-tsp)] text-[var(--function-error)]":Lo?.status==="recovering"?"border-[var(--function-warning)] bg-[var(--function-warning-tsp)] text-[var(--function-warning)]":"border-[var(--border-light)] bg-[var(--background-tsp-menu-white)] text-[var(--text-secondary)]",Fy=!!Ep&&(!Oa||Ve),uu=Er?"Answer the questions above to continue...":Rr?"Confirm the clarification above to continue...":"Give DeepScientist a task to work on...",du=c.useMemo(()=>me.length===0?me:me.filter(l=>{if(l.type!=="tool")return!0;const m=l.content;if(m.status!=="calling")return!0;const x=m.metadata,v=typeof x?.execution_target=="string"?x.execution_target.trim().toLowerCase():"";if(!(v==="cli"||v==="cli_server"||!!x?.cli_server_id||!v&&P==="cli"))return!0;const L=typeof m.function=="string"?m.function:"",H=Ll(L);return!!yr(L)||H==="mcp_status_update"}),[P,me]),Rp=!!Ne&&Rc&&!Sn&&!jc,ua=c.useMemo(()=>Rp&&Ne?[Ne,...du]:du,[du,Ne,Rp]),hs=Ci.current||ua.length>=Yo,Or=c.useMemo(()=>hs||Ef||ua.length<=Mh?ua:ua.slice(-Mh),[ua,hs,Ef]),Ki=c.useMemo(()=>cS(Or),[Or]),Ip=c.useMemo(()=>({id:Ph,blocks:[]}),[]),Mp=c.useMemo(()=>!hs||!nu?Ki:[...Ki,Ip],[Ki,hs,nu,Ip]),fu=oy&&!!q,Lp=c.useMemo(()=>({id:Dh,blocks:[]}),[]),da=c.useMemo(()=>{const l=hs?Mp:Ki;return fu?[Lp,...l]:l},[Ki,hs,Lp,fu,Mp]);c.useEffect(()=>{if(!jt)return;const l=Or.slice(-6).map(m=>{const x=m.content,v=typeof x?.timestamp=="number"?x.timestamp:"na",S=m.id.length>8?m.id.slice(0,8):m.id;return`${m.type}:${S}:${v}`});Xe("ui:order",{count:Or.length,tail:l})},[jt,Xe,Or]);const zy=hs?0:ua.length-Or.length,Pp=sy&&!!wf,Dp=c.useCallback(l=>{(sa.current==null||l<sa.current)&&(sa.current=l),vr.current==null&&(vr.current=window.requestAnimationFrame(()=>{vr.current=null;const m=sa.current??0;sa.current=null,Ri.current?.resetAfterIndex(m)}))},[]),Oy=c.useCallback((l,m)=>{const x=Uo.current.get(l);x!=null&&Math.abs(x-m)<1||(Uo.current.set(l,m),Dp(l))},[Dp]),By=c.useCallback(l=>Uo.current.get(l)??uN,[]);c.useLayoutEffect(()=>{if(!hs||!Ei.current)return;const l=()=>{Ei.current&&iy(Ei.current.clientHeight)};l();const m=new ResizeObserver(l);return m.observe(Ei.current),()=>m.disconnect()},[hs]);const Sr=c.useCallback(l=>{If.current!==l&&(If.current=l,cy(l))},[]),dl=c.useCallback(l=>{if(!l)return;const x=l.scrollHeight-l.scrollTop-l.clientHeight<=dN;x!==aa.current&&(aa.current=x,ra(x)),x&&Sr(!1)},[Sr,ra]),qy=c.useCallback(()=>{dl(Bo.current)},[dl]),Uy=c.useCallback(()=>{dl(qo.current)},[dl]),Ja=c.useCallback((l="auto")=>{if(me.length===0)return;if(hs){if(!Ri.current||!qo.current||$a<=0||da.length===0)return;Ri.current.scrollToItem(da.length-1,"end");return}const m=Bo.current;m&&m.scrollTo({top:m.scrollHeight,behavior:l})},[da.length,hs,$a,me.length]),Wy=c.useCallback(()=>{Ja("smooth"),aa.current=!0,ra(!0),Sr(!1)},[Ja,Sr,ra]),$p=c.useCallback(()=>{!q||Ii||Sn||(na.current=!0,Ho(!0),$n())},[Ii,Sn,$n,q]);c.useLayoutEffect(()=>{if(!Zn)return;if(me.length===0){Ic.current=!1,Mc.current=null,Sr(!1),aa.current=!0,ra(!0);return}Ic.current||!(hs?Ri.current&&qo.current&&$a>0:Bo.current)||(Ja("auto"),aa.current=!0,ra(!0),Sr(!1),Ic.current=!0)},[Zn,hs,$a,me.length,Ja,Sr,ra]),c.useEffect(()=>{Zn&&aa.current&&me.length!==0&&Ja("auto")},[da.length,Zn,me,Ja]),c.useEffect(()=>{if(me.length===0)return;const l=me[me.length-1]?.id??null;!l||l===Mc.current||(Mc.current=l,(!Zn||!aa.current)&&Sr(!0))},[Zn,me,Sr]);const Fp=c.useCallback(l=>{if(l.role==="assistant")return!0;if(l.role==="user")return!1;const m=l.message;if(m.type==="text_delta"||m.type==="attachments"||m.type==="attachment")return m.content.role==="assistant";switch(m.type){case"assistant":case"tool":case"tool_call":case"tool_result":case"reasoning":case"step":case"question_prompt":case"clarify_question":case"patch_review":return!0;default:return!1}},[]),zp=c.useCallback((l,m=!1)=>{const x=l.message,v=x.type==="assistant"||x.type==="text_delta"&&x.content.role==="assistant"?"assistant":x.type==="tool"||x.type==="tool_call"||x.type==="tool_result"?"tool":x.type==="reasoning"?"reasoning":x.type==="status"?"status":null,S=Mt.current.has(l.id),L=S?lt.current.get(l.id)??0:0,H=S?Math.min(L,pN)*fN:0,N=S?{"--ds-append-delay":`${H}ms`}:void 0,D=ea?.id,be=!!(D&&v&&ea?.kind===v&&l.sourceIds.includes(D)),Y=ce=>{if(ea&&be&&ea.kind===ce.kind){wr({id:ea.id,kind:ce.kind});return}wr(ce)};return s.jsx("div",{className:z(S&&"ai-manus-append"),"data-append":S?"pending":void 0,style:N,onAnimationEnd:S?ce=>{ce.target instanceof HTMLElement&&ce.animationName==="aiManusFadeIn"&&ce.target.classList.contains("ai-manus-fade-in")&&Qf(l.id)}:void 0,children:s.jsx(Ug,{message:x,sessionId:q??void 0,projectId:t??void 0,readOnly:te,showAssistantHeader:m,compact:Ve,onToolClick:gn?Tp:void 0,onFileClick:cu,onQuestionPromptSubmit:te?void 0:Sp,onClarifyQuestionSubmit:te?void 0:kp,onPatchAccept:te?void 0:ce=>ou(ce,"accept"),onPatchReject:te?void 0:ce=>ou(ce,"reject"),displayStreaming:be,streamActive:op,onDisplayComplete:Y})},l.id)},[cu,kp,ou,Tp,Sp,Ve,ea,wr,Qf,te,gn,op]),Op=c.useCallback(l=>{if(l.id===Dh){const x=typeof Wo=="number"&&Wo>0?`Showing latest ${Wo} messages.`:"Showing recent messages.",v=Ii?"Loading full history...":"Load full history";return s.jsx("div",{className:"flex w-full justify-center",children:s.jsxs("div",{className:z("inline-flex max-w-full items-center gap-2 rounded-full border px-3 py-1 font-medium","border-[var(--border-light)] bg-[var(--background-tsp-menu-white)] text-[var(--text-secondary)]",Ve?"text-[12px]":"text-[11px]"),children:[s.jsx("span",{children:x}),s.jsx("button",{type:"button",onClick:$p,disabled:Ii,className:"text-[var(--text-primary)] underline decoration-dotted underline-offset-4 disabled:cursor-not-allowed disabled:opacity-50",children:v})]})},l.id)}if(l.id===Ph)return s.jsx("div",{className:"flex w-full",children:s.jsx(em,{compact:Ve})},l.id);const m=l.blocks.findIndex(x=>Fp(x));return s.jsx("div",{className:"flex w-full flex-col gap-[12px]",children:l.blocks.map((x,v)=>zp(x,v===m))},l.id)},[$p,Wo,Ii,Ve,Fp,zp]),Bp=c.useCallback(()=>B&&ct.some(l=>l.id===B)?B:ct[0]?.id??null,[B,ct]),dr=c.useCallback((l,m)=>{if(!t||vi||zr)return;if(Dn&&l!=="cli"){I({type:"info",title:"Lab runtime locked",description:"Lab sessions require a CLI server. Switch to Copilot for sandbox mode.",duration:3500});return}if(l==="cli"&&ct.length===0){I({type:"warning",title:"No CLI server online",description:"Connect a CLI server to switch runtime."});return}if(l==="cli"&&m&&!ct.some(S=>S.id===m)){I({type:"warning",title:"CLI server offline",description:"Select an online CLI server to switch runtime."});return}const x=l==="cli"?m??Bp():null;if(l==="cli"&&!x){I({type:"error",title:"No CLI server available",description:"Bind and connect a CLI server before switching to CLI."});return}of(!0);const v=e!=="welcome";l==="cli"?(Re(t,"cli",x),v&&yn("terminal"),I({type:"info",title:"Connected to CLI",description:"Codex will run on the controlled server with real-time streaming.",duration:4e3})):(Re(t,"sandbox"),v&&yn("terminal"),I({type:"info",title:"Switched to Sandbox",description:"Terminal is in read-only preview mode.",duration:3e3})),of(!1)},[I,Dn,e,ct,t,Bp,zr,vi,Re,yn]),qp=c.useCallback(()=>{if(zr||vi)return;if(ct.length===0){P==="cli"&&dr("sandbox");return}const l=ct.map(S=>S.id),m=P==="cli"?B:null;if(!m){dr("cli",l[0]);return}const x=l.indexOf(m);if(x<0){dr("cli",l[0]);return}if(l.length===1){dr("sandbox");return}const v=x+1;if(v>=l.length){dr("sandbox");return}dr("cli",l[v])},[B,P,dr,ct,zr,vi]),Up=c.useCallback(()=>!t||!Zc||al&&e!=="welcome"?null:s.jsxs(hv,{value:P==="cli"&&B?`cli:${B}`:"sandbox",onValueChange:l=>{if(t&&!zr){if(l==="sandbox"){dr("sandbox");return}if(l.startsWith("cli:")){const m=l.replace("cli:","");dr("cli",m)}}},children:[s.jsx(xv,{className:"ds-copilot-icon-btn justify-center p-0 [&>svg]:hidden","aria-label":"Runtime","data-tooltip":ys,disabled:zr,children:s.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-current",children:s.jsx(Uu,{size:16})})}),s.jsxs(gv,{children:[s.jsx(gu,{value:"sandbox",disabled:Dn,children:"Sandbox (view-only)"}),Ee.length===0?s.jsx(gu,{value:"cli:none",disabled:!0,children:"CLI (bind server)"}):Ee.map(l=>{const m=l.status!=="offline"&&l.status!=="error";return s.jsxs(gu,{value:`cli:${l.id}`,disabled:!m,children:["CLI (interactive): ",l.name||l.hostname||l.id.slice(0,6),m?"":" (offline)"]},l.id)})]})]}),[B,Ee,P,dr,Zc,Dn,e,t,ys,zr,al]),Wp=c.useCallback(async l=>{if(l==="terminal"){if(!gn||!Go||!(q??await qn()))return;yn("terminal"),Ut(!0);return}Yn&&yn("tool")},[Yn,Go,qn,q,Ut,yn,gn]),Hy=c.useCallback(l=>{if(!Number.isFinite(l.asPercentage)||l.asPercentage<Rl)return;const m=Math.round(l.asPercentage),x=Math.min(Lu,Math.max(Rl,m));x!==bs&&cc(x)},[bs]),Hp=c.useCallback(async()=>{if(!gn)return;if(Yn){As(Yn,ms(Yn),!0);return}const l=Ln.current;if(l){As(l,ms(l),!0);return}(q??await qn())&&(yn("terminal"),Ut(!0))},[Yn,qn,As,ms,q,Ut,yn,gn]);c.useEffect(()=>{if(!gn||Fa)return;const l=Lf.current;if(!l)return;const m=window.requestAnimationFrame(()=>{try{if(za){l.expand(),l.resize(`${bs}%`);return}l.collapse()}catch{}});return()=>window.cancelAnimationFrame(m)},[za,gn,Fa,bs]);const Vp=c.useCallback(()=>{if(e!=="welcome"||!Qo)return null;const l=es?"Hide Tool":"Open Tool";return s.jsx("button",{type:"button",onClick:()=>{if(es){Ut(!1);return}Hp()},"aria-label":l,"data-tooltip":l,className:z("ai-manus-tool-btn",es&&"is-active"),children:es?"Hide Tool":"Open Tool"})},[Hp,e,Ut,es,Qo]),pu=c.useCallback(l=>s.jsx(aN,{open:l,panelId:St,sessions:Zf,activeSessionId:Jf,highlightSessionId:xf,readOnly:Gn,pinnedSessionIds:k.pinned,renamedSessions:k.renamed,onToggle:Fs,onSelect:dp,onNew:Wa,onDelete:yp,onTogglePin:fp,onRename:hp,onShare:gp,floating:mn,draggable:mn,dragConstraintsRef:Pc}),[Jf,yp,dp,hp,gp,fp,mn,St,xf,Gn,k.pinned,k.renamed,Fs,Wa,Zf]),mu=l=>{const m=Oe?.id?ut[Oe.id]:void 0,x=Oe?.id?Ce[Oe.id]:null,v=s.jsx(lN,{contentKind:m?.contentKind,documentMode:m?.documentMode,openTabCount:Te.length,references:Ae,activeReferenceId:oe?.id,focusedIssue:x,onRemoveReference:ie});return xy?s.jsxs("div",{children:[v,s.jsx(Pk,{value:tt,onChange:it,onSubmit:ul,onStop:up,isRunning:Ga,attachments:wn,onAttachmentsChange:Qn,recentFiles:lr,recentFilesActivePath:Fr,recentFilesEnabled:On,onRecentFilesToggle:rp,onRecentFilesRemove:ap,showTerminalToggle:al,terminalActive:P==="cli",terminalLabel:np,onTerminalToggle:qp,terminalToggleDisabled:sp,onRecentFileOpen:Cp,recentFilesDisabled:!Va,projectId:t,sessionId:q,ensureSession:qn,readOnly:te,inputDisabled:Sn||!!Er||!!Rr||lp,compact:l.compact,placeholder:l.placeholder,containerClassName:l.containerClassName,panelClassName:l.panelClassName,inputClassName:l.inputClassName,focusRef:Lc})]}):s.jsxs("div",{children:[v,s.jsx(Mk,{value:tt,onChange:it,onSubmit:ul,onStop:up,isRunning:Ga,mentionables:pt,mentionEnabled:ln,lockedPrefix:ye,lockLeadingMentionSpace:V,attachments:wn,onAttachmentsChange:Qn,recentFiles:lr,recentFilesActivePath:Fr,recentFilesEnabled:On,onRecentFilesToggle:rp,onRecentFilesRemove:ap,showTerminalToggle:al,terminalActive:P==="cli",terminalLabel:np,onTerminalToggle:qp,terminalToggleDisabled:sp,onRecentFileOpen:Cp,recentFilesDisabled:!Va,projectId:t,sessionId:q,ensureSession:qn,readOnly:te,inputDisabled:Sn||!!Er||!!Rr||lp,compact:l.compact,rows:l.rows,placeholder:l.placeholder,inputRef:l.inputRef,containerClassName:l.containerClassName,panelClassName:l.panelClassName,inputClassName:l.inputClassName})]})},Kp=s.jsxs("div",{className:"relative flex h-full min-w-0 flex-1 min-h-0 flex-col overflow-hidden",children:[e==="welcome"&&!y?qs?s.jsxs("div",{className:"ai-manus-surface sticky top-0 z-10 flex items-center justify-between border-b border-[var(--border-light)] px-5 py-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[vt&&!vn?s.jsx("button",{type:"button",onClick:()=>Fs(!0),"aria-expanded":vn,"aria-controls":St,className:"flex h-7 w-7 items-center justify-center rounded-md hover:bg-[var(--fill-tsp-gray-main)]",children:s.jsx(Bu,{className:"h-4 w-4 text-[var(--icon-secondary)]"})}):null,s.jsx("img",{src:lv("icons/welcome/copilot-badge.png"),alt:"Agent logo",className:"h-6 w-6"}),s.jsx("span",{className:"text-[11px] font-semibold text-[var(--text-primary)]",children:"Agent"})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[Up(),Vp()]})]}):s.jsx("div",{className:"ai-manus-surface sticky top-0 z-10 border-b border-[var(--border-light)] px-5 py-1.5",children:s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("div",{className:"flex flex-1 items-center",children:vt&&!vn?s.jsx("button",{type:"button",onClick:()=>Fs(!0),"aria-expanded":vn,"aria-controls":St,className:"flex h-7 w-7 items-center justify-center rounded-md hover:bg-[var(--fill-tsp-gray-main)]",children:s.jsx(Bu,{className:"h-4 w-4 text-[var(--icon-secondary)]"})}):null}),s.jsxs("div",{className:z("flex w-full min-w-0 items-center gap-2",Xo),children:[s.jsx("div",{className:z("min-w-0 flex-1 truncate whitespace-nowrap font-medium text-[var(--text-primary)]",Ve?"text-[12px]":"text-[13px]"),children:F}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e==="welcome"&&t?Up():null,Vp(),xu&&e==="welcome"&&q?s.jsx("button",{type:"button",onClick:()=>mf(!0),className:"ds-copilot-icon-btn","aria-label":"Session files","data-tooltip":"Session files",children:s.jsx(Dv,{size:16,className:"text-current"})}):null]})]}),s.jsx("div",{className:"flex flex-1"})]})}):null,s.jsx(d_,{id:gy,children:s.jsxs("div",{className:"relative flex h-full min-h-0 flex-col",children:[s.jsxs("div",{className:z("relative flex flex-1 min-h-0 flex-col overflow-hidden transition-opacity duration-300 ease-out motion-reduce:transition-none",e==="welcome"&&"bg-transparent",vy&&"opacity-0 pointer-events-none"),children:[Pi?s.jsx("div",{ref:Pc,className:"absolute inset-0 z-30 pointer-events-none",children:pu(!0)}):null,yy?s.jsx("div",{className:"absolute inset-0 z-20 flex items-center justify-center pointer-events-none",children:s.jsxs("div",{className:z("flex items-center gap-2 rounded-full border px-3 py-1.5 text-[11px] font-medium shadow-sm","border-[var(--border-light)] bg-[var(--background-white-main)] text-[var(--text-tertiary)]"),children:[s.jsx(dd,{className:"h-4 w-4 animate-spin"}),s.jsx("span",{children:"Loading..."})]})}):null,hs?s.jsx("div",{ref:Ei,className:z("relative flex-1 min-h-0 overflow-hidden",Ff),children:$a>0?s.jsx(cv,{ref:Ri,outerRef:qo,innerRef:Af,className:"ai-manus-scrollbar",height:$a,width:"100%",itemCount:da.length,itemSize:By,innerElementType:Ty,overscanCount:6,onScroll:Uy,itemData:{items:da,setSize:Oy,render:Op,messageMaxWidthClass:Xo},children:Vg}):null}):s.jsx("div",{ref:Bo,className:z("ai-manus-scrollbar flex-1 min-h-0 overflow-y-auto",Ff),onScroll:qy,children:s.jsxs("div",{ref:Af,className:z("mx-auto flex w-full flex-col gap-[12px]",fy,Xo),style:{paddingBottom:Uc},children:[zy>0&&!Oa&&!fu?s.jsxs("div",{className:"text-center text-[11px] text-[var(--text-tertiary)]",children:["Showing the latest ",Or.length," messages"]}):null,i&&!o&&Or.length===0?s.jsxs("div",{className:"rounded-[12px] border border-[var(--border-light)] bg-[var(--background-white-main)] p-4",children:[s.jsx("div",{className:z("font-medium text-[var(--text-primary)]","text-[11px]"),children:i.title}),i.subtitle&&!Oa?s.jsx("div",{className:z("text-[var(--text-tertiary)]","text-[10px]"),children:i.subtitle}):null,s.jsx("div",{className:"mt-3 grid gap-2",children:i.items.map(l=>s.jsx("button",{type:"button",className:z("rounded-[8px] border border-[var(--border-light)] px-3 py-2 text-left text-[var(--text-secondary)] hover:bg-[var(--fill-tsp-white-light)]","text-[11px]"),onClick:()=>u?.(l),children:l.label},l.label))})]}):null,da.map(l=>Op(l)),nu?s.jsx(em,{compact:Ve}):null]})}),ly?s.jsx("div",{className:"pointer-events-none absolute bottom-4 left-1/2 z-10 -translate-x-1/2",children:s.jsxs("button",{type:"button",onClick:Wy,className:z("pointer-events-auto inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-[11px] font-medium","border-[var(--border-main)] bg-[var(--background-white-main)] text-[var(--text-primary)]","shadow-[0px_8px_20px_-12px_rgba(0,0,0,0.28)] hover:bg-[var(--background-gray-main)]"),children:["New messages",s.jsx(Tv,{className:"h-3.5 w-3.5"})]})}):null]}),by?s.jsx(ks.div,{className:z("absolute inset-0 z-20 flex items-center justify-center pr-5 transition-opacity duration-300 ease-out motion-reduce:transition-none","pl-5",qs?"pointer-events-auto":"pointer-events-none"),style:Pi&&Bf!==null?{paddingLeft:Bf}:void 0,initial:!1,animate:{opacity:qs?1:0,y:qs?0:12},transition:qc,children:s.jsxs("div",{className:z("mx-auto flex w-full flex-col items-center",Xo),children:[s.jsxs(ks.div,{className:"pb-6 text-center",initial:!1,animate:{opacity:qs?1:0,y:qs?0:-6},transition:qc,children:[s.jsx("div",{className:z("ai-manus-greeting font-serif text-[var(--text-primary)]",e==="copilot"?"text-[70px] leading-[85px]":Ve?"text-[28px] leading-[34px]":"text-[34px] leading-[42px]"),children:wy}),s.jsx("div",{className:z("mt-1 text-[var(--text-tertiary)]",Ve?"text-[13px]":"text-[15px]"),children:Sy})]}),qs?s.jsx(ks.div,{layoutId:Of,transition:Kf,style:Ny,className:jy,children:mu({rows:3,placeholder:uu,inputRef:Vo,containerClassName:"pb-0",inputClassName:z("min-h-[56px]",Ve?"text-[14px]":"text-[15px]")})}):null,ky?s.jsx(ks.div,{className:"mt-5 w-[80%] max-w-[820px] min-w-[min(260px,100%)]",initial:!1,animate:{opacity:qs?1:0},transition:qc,children:s.jsx("div",{className:"grid gap-3 sm:grid-cols-3",children:Uf.map(l=>{const m=l.icon,v=l.title==="Sessions"&&vt;return s.jsxs(bx,{role:v?"button":void 0,tabIndex:v?0:void 0,onClick:v?ep:void 0,onKeyDown:v?S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),ep())}:void 0,className:z("ai-manus-surface flex h-full min-h-[68px] items-center gap-3 rounded-xl border border-[var(--border-light)] px-3 py-3","shadow-[0_14px_30px_-28px_rgba(45,42,38,0.45)]",v&&"cursor-pointer hover:border-[var(--border-main)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-black/10"),children:[s.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-[var(--fill-tsp-gray-main)]",children:s.jsx(m,{className:"h-4 w-4 text-[var(--icon-primary)]"})}),s.jsx("div",{className:"text-[12px] font-semibold text-[var(--text-primary)]",children:l.title})]},l.title)})})}):null]})}):null,s.jsxs("div",{className:z("relative sticky bottom-0 z-10 flex-shrink-0 overflow-visible",e==="welcome"&&"bg-transparent",py),children:[En?s.jsx("div",{className:z("pointer-events-none absolute inset-x-0 bottom-full flex justify-center",my),children:s.jsx("div",{className:z(Hf,"pointer-events-auto flex justify-center -translate-y-2"),style:Wf,children:s.jsx(nN,{plan:En,sessionId:q,compact:Ve,history:Is})})}):null,qs?null:e!=="welcome"?s.jsx("div",{"aria-hidden":!0,className:"pointer-events-none absolute -top-8 left-0 right-0 h-8 bg-gradient-to-t from-[var(--background-gray-main)] to-transparent"}):null,Ga&&!Er&&!Rr?s.jsx("div",{className:z("pointer-events-none absolute top-0 z-10 -translate-y-1/2",hy),children:s.jsx(uv,{toolCount:rf,resetKey:q??"new",className:"shrink-0",size:"lg",compact:Ve||mc})}):null,Py?s.jsxs("div",{className:z("mb-2 inline-flex max-w-full items-center gap-2 rounded-full border px-3 py-1 text-[11px] font-medium shadow-[inset_0px_1px_0px_0px_#FFFFFF]","border-[var(--border-light)] bg-[var(--background-tsp-menu-white)] text-[var(--text-secondary)]",Ve?"text-[12px]":"text-[11px]"),children:[s.jsx("span",{children:Ly}),te?null:s.jsx("button",{type:"button",onClick:Iy,className:"text-[var(--text-primary)] underline decoration-dotted underline-offset-4",children:"Resume"})]}):null,Dy&&!Oa?s.jsx("div",{className:z("pb-2 text-[var(--text-tertiary)]",Ve?"text-[12px]":"text-[11px]"),children:lf}):null,Lo?s.jsx("div",{className:z("mb-2 inline-flex max-w-full items-center gap-2 rounded-full border px-3 py-1 text-[11px] font-medium shadow-[inset_0px_1px_0px_0px_#FFFFFF]",$y,Ve?"text-[12px]":"text-[11px]"),children:Lo.message}):null,qs?null:$r?s.jsx(ks.div,{layoutId:Of,transition:Kf,style:Wf,className:Hf,children:mu({compact:Ve,placeholder:uu,inputRef:Vo})}):mu({compact:Ve,placeholder:uu,inputRef:Vo}),!qs&&$e?s.jsx("div",{className:"mt-2 flex items-center justify-end",children:$e}):null,Fy?s.jsx("div",{className:z("mt-2 text-[var(--text-tertiary)]",Ve?"text-[12px]":"text-[11px]"),children:Ep}):null,te&&!Oa?s.jsx("div",{className:"mt-1 text-[11px] text-[var(--text-tertiary)]",children:"View only"}):null]})]})})]}),Vy=gn&&Fa&&Dc&&es&&Li?tm.createPortal(s.jsx("div",{className:"ai-manus-tool-portal",children:s.jsx(Eh,{variant:"docked",open:es,toolContent:Li??void 0,live:Xn,sessionId:q??void 0,realTime:ve,isShare:te,projectId:t??void 0,executionTarget:P,cliServerId:B,readOnly:te,viewMode:js,onViewModeChange:Go?Wp:void 0,onClose:()=>{},onJumpToRealTime:Ap,hideClose:!0})}),Dc):null,Ky=vt&&$f&&Fc?tm.createPortal(s.jsx("div",{className:"ai-manus-session-portal",children:pu(vn)}),Fc):null,Gy=c.useMemo(()=>({isNearBottom:Mf}),[Mf]);return s.jsx(dv,{value:Gy,children:s.jsxs("div",{className:z("ai-manus-root flex h-full w-full min-h-0 min-w-0",y&&"ai-manus-embedded",y&&"flex-1",e==="welcome"?"ai-manus-mode-welcome":"ai-manus-mode-copilot",Ye==="copilot"?"ai-manus-copilot":"ai-manus-welcome",Pf==="welcome"?"flex-row":"flex-col"),children:[e==="welcome"&&vt&&!$f?pu(vn):null,s.jsx("div",{className:z("flex min-w-0 flex-1 min-h-0",Pf==="welcome"?"flex-row":"flex-col"),children:e==="welcome"&&gn&&!Fa&&za?s.jsxs(o0,{className:"flex-1 min-h-0 min-w-0",children:[s.jsx(Rm,{minSize:"38%",className:"min-w-0 min-h-0",children:Kp}),s.jsx(l0,{className:z("ai-manus-tool-divider pointer-events-none",za?"is-visible":"is-hidden")}),s.jsx(Rm,{panelRef:Lf,defaultSize:`${bs}%`,minSize:`${Rl}%`,maxSize:`${Lu}%`,collapsible:!0,collapsedSize:0,onResize:Hy,className:"min-w-0 min-h-0",children:s.jsx("div",{className:z("ai-manus-tool-dock relative flex h-full min-w-0 flex-1 flex-col overflow-hidden rounded-[10px]",za?"ai-manus-fade-in":"pointer-events-none opacity-0"),children:s.jsx(Eh,{variant:"docked",open:es,toolContent:Li??void 0,live:Xn,sessionId:q??void 0,realTime:ve,isShare:te,projectId:t??void 0,executionTarget:P,cliServerId:B,readOnly:te,viewMode:js,onViewModeChange:Go?Wp:void 0,onClose:()=>Ut(!1),onJumpToRealTime:Ap})})})]}):Kp}),s.jsx(fd,{open:hc,onOpenChange:l=>{if(l){xc(!0);return}Wi()},children:s.jsxs(pd,{showCloseButton:!1,className:"w-[min(420px,90vw)] !rounded-[18px] !border-[var(--soft-border)] !bg-[var(--soft-bg-surface)] !p-5 text-[var(--soft-text-primary)] shadow-[0px_30px_80px_-40px_rgba(0,0,0,0.32)]",children:[s.jsxs(fv,{className:"space-y-1",children:[s.jsx(gx,{className:"text-[15px] font-semibold text-[var(--soft-text-primary)]",children:"Rename chat"}),s.jsx(yx,{className:"text-xs text-[var(--soft-text-tertiary)]",children:"Only visible to you."})]}),s.jsx("div",{className:"pt-3",children:s.jsx("input",{ref:bf,value:gc,onChange:l=>yc(l.target.value),onKeyDown:l=>{l.key==="Enter"?(l.preventDefault(),mp()):l.key==="Escape"&&(l.preventDefault(),Wi())},maxLength:80,className:z("h-10 w-full rounded-xl border border-[var(--border-light)] px-3 text-sm","border-[var(--soft-border)] bg-[var(--soft-bg-base)] text-[var(--soft-text-primary)]","shadow-[0px_0px_1px_0px_rgba(0,0,0,0.08)]","focus:outline-none focus:ring-2 focus:ring-[hsl(var(--primary)/0.25)]"),placeholder:"New chat name"})}),s.jsxs(pv,{className:"mt-4 flex flex-row justify-end gap-2",children:[s.jsx("button",{type:"button",onClick:Wi,className:z("inline-flex h-9 items-center justify-center rounded-[10px] px-3 text-sm","border border-[var(--soft-border)] bg-[var(--soft-bg-surface)] text-[var(--soft-text-primary)]","hover:bg-[var(--soft-bg-inset)] transition-colors"),children:"Cancel"}),s.jsx("button",{type:"button",onClick:mp,className:z("inline-flex h-9 items-center justify-center rounded-[10px] px-3 text-sm font-medium","bg-[hsl(var(--primary))] text-[hsl(var(--primary-foreground))]","shadow-[0px_10px_24px_-16px_rgba(0,0,0,0.24)] hover:opacity-90 transition"),children:"Save"})]})]})}),xu?s.jsx(sN,{open:pc,onOpenChange:mf,files:Yg,loading:Jg,onOpenFile:cu}):null,Vy,Ky,Pp?s.jsxs("div",{className:"fixed inset-0 z-[60] bg-[var(--background-gray-main)]",children:[s.jsx("div",{className:"h-full w-full",children:s.jsx(SN,{sessionId:wf,enabled:Pp,viewOnly:!1})}),s.jsx("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2",children:s.jsx("button",{type:"button",onClick:()=>{_f(!1),bc("")},className:"inline-flex h-[36px] items-center justify-center gap-[6px] rounded-full border-2 border-[var(--border-dark)] bg-[var(--Button-primary-black)] px-[12px] text-sm font-medium text-[var(--text-onblack)] shadow-[0px_8px_32px_0px_rgba(0,0,0,0.32)] transition hover:opacity-90 active:opacity-80",children:"Exit Takeover"})})]}):null]})})}const rj=Object.freeze(Object.defineProperty({__proto__:null,AiManusChatView:Yh,default:Yh},Symbol.toStringTag,{value:"Module"}));export{Yh as A,Mk as C,Xd as D,aS as a,Ug as b,rj as c,nj as g,xo as r,X_ as u};