@intent-hq/web 2.361.2 → 2.361.4

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 (176) hide show
  1. package/package.json +1 -1
  2. package/web/app/immutable/assets/{MarkdownViewer.CmMrjGND.css → MarkdownViewer.D2MexjjT.css} +1 -1
  3. package/web/app/immutable/chunks/-5BGDZDk.js +32 -0
  4. package/web/app/immutable/chunks/{CrLichOk.js → 1P8JUNrt.js} +1 -1
  5. package/web/app/immutable/chunks/{BKw6wLyE.js → 8p81B4Fd.js} +1 -1
  6. package/web/app/immutable/chunks/{B1Tr5BPZ.js → B-nCPlyy.js} +1 -1
  7. package/web/app/immutable/chunks/{D9H2UCuG.js → B5G8dQJa.js} +1 -1
  8. package/web/app/immutable/chunks/{DOjUJ8i8.js → B61qyrBq.js} +1 -1
  9. package/web/app/immutable/chunks/{CytLF-ur.js → B6iZl_wM.js} +6 -6
  10. package/web/app/immutable/chunks/{B9tRD7MQ.js → B71-bXIU.js} +1 -1
  11. package/web/app/immutable/chunks/{Bhx5E4sN.js → B7wYsi9q.js} +1 -1
  12. package/web/app/immutable/chunks/{Bgk8kfr8.js → BALMGKKv.js} +1 -1
  13. package/web/app/immutable/chunks/{c1DCm8IK.js → BCyX6y2H.js} +1 -1
  14. package/web/app/immutable/chunks/{DkgfeEA0.js → BCykELTT.js} +1 -1
  15. package/web/app/immutable/chunks/{BMYcVUUM.js → BFvvXNf5.js} +8 -8
  16. package/web/app/immutable/chunks/{aokikQw5.js → BGdv1uWf.js} +13 -13
  17. package/web/app/immutable/chunks/{7tcI69cn.js → BIPMq18e.js} +1 -1
  18. package/web/app/immutable/chunks/{C9otdzZM.js → BPeXyR5m.js} +4 -4
  19. package/web/app/immutable/chunks/{DyIRpoZq.js → BQO2-pKG.js} +1 -1
  20. package/web/app/immutable/chunks/{OiHDtgNp.js → BS6UmzgC.js} +1 -1
  21. package/web/app/immutable/chunks/{CpY-WDD9.js → BTvnh9qa.js} +1 -1
  22. package/web/app/immutable/chunks/{BGOuxFsr.js → BVz2MGVx.js} +1 -1
  23. package/web/app/immutable/chunks/{Tqm9-f9l.js → BWtgKffi.js} +1 -1
  24. package/web/app/immutable/chunks/{CmVyGqNV.js → BYDNdw_J.js} +2 -2
  25. package/web/app/immutable/chunks/BaGrEyO7.js +1 -0
  26. package/web/app/immutable/chunks/BeF36lmB.js +3 -0
  27. package/web/app/immutable/chunks/{BD9wTbmm.js → BfOb5kjD.js} +1 -1
  28. package/web/app/immutable/chunks/{B5Pg9_MZ.js → BiLbb6HG.js} +1 -1
  29. package/web/app/immutable/chunks/{CVOsommd.js → BjGths7V.js} +2 -2
  30. package/web/app/immutable/chunks/{CuGN_Lgy.js → Bm01ytIS.js} +1 -1
  31. package/web/app/immutable/chunks/{Byj6QL5F.js → BmqyXExt.js} +1 -1
  32. package/web/app/immutable/chunks/{DjKDfA1m.js → BrBAfQ57.js} +2 -2
  33. package/web/app/immutable/chunks/{BOSMtVmb.js → BsloAXs5.js} +1 -1
  34. package/web/app/immutable/chunks/{Vfi0Dmt8.js → BuV8a8sz.js} +1 -1
  35. package/web/app/immutable/chunks/{BeLtysng.js → BuoVynwM.js} +1 -1
  36. package/web/app/immutable/chunks/{P-joxIX5.js → BuqbrxB1.js} +1 -1
  37. package/web/app/immutable/chunks/{Bl2aLOn5.js → C2GygP-d.js} +1 -1
  38. package/web/app/immutable/chunks/{dGnsWF4N.js → C4YDKHOI.js} +1 -1
  39. package/web/app/immutable/chunks/{CvH6beJr.js → C4rZWprN.js} +2 -2
  40. package/web/app/immutable/chunks/C7GN5GMc.js +3 -0
  41. package/web/app/immutable/chunks/{D5kZvSPC.js → C8__WGAb.js} +1 -1
  42. package/web/app/immutable/chunks/{DC3pczce.js → C8xHhbCK.js} +1 -1
  43. package/web/app/immutable/chunks/{Bt_RDNlI.js → C9idh8Ua.js} +1 -1
  44. package/web/app/immutable/chunks/{1EW4b83o.js → CBYFxd4u.js} +1 -1
  45. package/web/app/immutable/chunks/{DlBKZ9jQ.js → CGhO7uI2.js} +2 -2
  46. package/web/app/immutable/chunks/CIWs30wy.js +1 -0
  47. package/web/app/immutable/chunks/{DaHbZjgp.js → CK3bnTgZ.js} +1 -1
  48. package/web/app/immutable/chunks/{C-Qm3bfA.js → CKnHTDAw.js} +1 -1
  49. package/web/app/immutable/chunks/{CsqD9xz6.js → CLtHxjHo.js} +2 -2
  50. package/web/app/immutable/chunks/{QWfAA7k-.js → CN6piAaf.js} +1 -1
  51. package/web/app/immutable/chunks/{D3rVaYU0.js → CNmxox94.js} +2 -2
  52. package/web/app/immutable/chunks/{8HLudOb-.js → CNo8m56L.js} +1 -1
  53. package/web/app/immutable/chunks/{R1d5Y9eD.js → CP5zM-2z.js} +1 -1
  54. package/web/app/immutable/chunks/{DHbwKi-E.js → CQILQHaF.js} +2 -2
  55. package/web/app/immutable/chunks/{Bx_nP_MK.js → CQJgY6fB.js} +1 -1
  56. package/web/app/immutable/chunks/{aCDFJfWo.js → CRBbB4Mw.js} +1 -1
  57. package/web/app/immutable/chunks/{BG8JSmc7.js → CTU9yjO5.js} +1 -1
  58. package/web/app/immutable/chunks/{Bya2sQrR.js → CVGUPwtj.js} +1 -1
  59. package/web/app/immutable/chunks/{DD4-FHBp.js → CVig8fcR.js} +1 -1
  60. package/web/app/immutable/chunks/{dxPehZVa.js → CWVUBnHm.js} +2 -2
  61. package/web/app/immutable/chunks/{D0g6v2_u.js → CXe2ucrR.js} +1 -1
  62. package/web/app/immutable/chunks/{CNUg0Cs8.js → CZYViob1.js} +6 -6
  63. package/web/app/immutable/chunks/{CvPVdUUZ.js → CaOJIXi2.js} +1 -1
  64. package/web/app/immutable/chunks/{CGINFMqT.js → CdpHTR0L.js} +1 -1
  65. package/web/app/immutable/chunks/CffWzOD9.js +1 -0
  66. package/web/app/immutable/chunks/{-7du9lfn.js → CgCxS7G9.js} +1 -1
  67. package/web/app/immutable/chunks/{Cq8fk3CH.js → CiBGAwnh.js} +1 -1
  68. package/web/app/immutable/chunks/{CuoerPJp.js → Cket6Weo.js} +3 -3
  69. package/web/app/immutable/chunks/{Wz08guGa.js → Cl9ySU-o.js} +1 -1
  70. package/web/app/immutable/chunks/{DPfWnZYT.js → ClV-2Tgv.js} +1 -1
  71. package/web/app/immutable/chunks/{BXId-8a9.js → Clj6cYni.js} +1 -1
  72. package/web/app/immutable/chunks/{DXcrfgZH.js → Cobx8hVY.js} +2 -2
  73. package/web/app/immutable/chunks/{Bl0Adq86.js → CpxaxzA8.js} +1 -1
  74. package/web/app/immutable/chunks/{DHBQy6St.js → CtUkyckm.js} +1 -1
  75. package/web/app/immutable/chunks/{DwHEsGP4.js → CvCk2zex.js} +1 -1
  76. package/web/app/immutable/chunks/{6d4Jv8Hz.js → CxyAwsTu.js} +2 -2
  77. package/web/app/immutable/chunks/{CcZqxMtd.js → Cyj5BnLo.js} +1 -1
  78. package/web/app/immutable/chunks/{CyQJi5fM.js → CyloLyza.js} +1 -1
  79. package/web/app/immutable/chunks/{DzmdzUVi.js → Cz4zW21_.js} +1 -1
  80. package/web/app/immutable/chunks/{5NiJCy7J.js → CzwZgSIh.js} +1 -1
  81. package/web/app/immutable/chunks/{buVzC4lf.js → D-joLTU5.js} +1 -1
  82. package/web/app/immutable/chunks/{CssvkQD7.js → D-xbpOd2.js} +1 -1
  83. package/web/app/immutable/chunks/{As8lK70V.js → D0rtAmW8.js} +1 -1
  84. package/web/app/immutable/chunks/{C5cRG0yV.js → D1mB5Biz.js} +3 -3
  85. package/web/app/immutable/chunks/{B2ns9OTA.js → D47LEQTi.js} +1 -1
  86. package/web/app/immutable/chunks/{BbIMIfqX.js → D4Qdu3Ph.js} +1 -1
  87. package/web/app/immutable/chunks/{Cb4s3Dt_.js → D5-Qkhrf.js} +4 -4
  88. package/web/app/immutable/chunks/{BAgFsuQz.js → D65NcKrS.js} +1 -1
  89. package/web/app/immutable/chunks/{BpL3mTkL.js → D6YJZGmY.js} +1 -1
  90. package/web/app/immutable/chunks/{D4LnecGU.js → D8Pj7OSy.js} +2 -2
  91. package/web/app/immutable/chunks/{CJHViisg.js → DC2f25QV.js} +5 -5
  92. package/web/app/immutable/chunks/{cU6Fqv3g.js → DJ0zWgRW.js} +1 -1
  93. package/web/app/immutable/chunks/{Ds8ezw9K.js → DKfGiH_H.js} +1 -1
  94. package/web/app/immutable/chunks/{yTlZ1Sih.js → DLwNAutM.js} +1 -1
  95. package/web/app/immutable/chunks/{CpHAR9_T.js → DTXj0Rgw.js} +1 -1
  96. package/web/app/immutable/chunks/{B07OdpUU.js → DVhvsf4B.js} +3 -3
  97. package/web/app/immutable/chunks/{BG4tBRsm.js → DY8ddh3S.js} +1 -1
  98. package/web/app/immutable/chunks/{DsCJG1hb.js → D_pi05yD.js} +1 -1
  99. package/web/app/immutable/chunks/{BskEvHZa.js → Dagg0ZW1.js} +1 -1
  100. package/web/app/immutable/chunks/{DXXjnBc_.js → DbaAc_-Q.js} +1 -1
  101. package/web/app/immutable/chunks/{DkNdI_Wp.js → DcNzEJkC.js} +1 -1
  102. package/web/app/immutable/chunks/{C_z20mJT.js → DdNipNbw.js} +1 -1
  103. package/web/app/immutable/chunks/{CjorBqRt.js → DfVuwPvT.js} +1 -1
  104. package/web/app/immutable/chunks/{B4kCZd9W.js → Dh4zlY8h.js} +1 -1
  105. package/web/app/immutable/chunks/{BKHUH54N.js → DhEKpkr8.js} +1 -1
  106. package/web/app/immutable/chunks/{D0VMf2Fp.js → DihoaAJc.js} +3 -3
  107. package/web/app/immutable/chunks/DkBcuECQ.js +176 -0
  108. package/web/app/immutable/chunks/{rUCEwUE_.js → DlrcSqxf.js} +1 -1
  109. package/web/app/immutable/chunks/{sLpI8Vr2.js → DuAq2d-z.js} +1 -1
  110. package/web/app/immutable/chunks/{W67SWYQh.js → DuU6k7P3.js} +1 -1
  111. package/web/app/immutable/chunks/{ivBdCvd6.js → Dwa7mF5q.js} +7 -7
  112. package/web/app/immutable/chunks/{Dtqu7Pxg.js → Dxi1HqSj.js} +1 -1
  113. package/web/app/immutable/chunks/{BTR14c-t.js → DyHNI41j.js} +3 -3
  114. package/web/app/immutable/chunks/{D1FSU9Gk.js → E53OBtIE.js} +1 -1
  115. package/web/app/immutable/chunks/{Db7PzaF_.js → F7k6DTn_.js} +1 -1
  116. package/web/app/immutable/chunks/{YhYmjxML.js → FvRoXWri.js} +1 -1
  117. package/web/app/immutable/chunks/{BLFlTVjy.js → GvAc6kd4.js} +4 -4
  118. package/web/app/immutable/chunks/{CgS1Dv_8.js → I6IukSJg.js} +1 -1
  119. package/web/app/immutable/chunks/{DAwOD17b.js → JWLuWIPn.js} +1 -1
  120. package/web/app/immutable/chunks/{BQKRBk9B.js → KEUh5hD5.js} +1 -1
  121. package/web/app/immutable/chunks/{CO15VKbw.js → L325nzu4.js} +6 -6
  122. package/web/app/immutable/chunks/{52-_4pXR.js → Lar8kBUq.js} +1 -1
  123. package/web/app/immutable/chunks/{tSlfPnTD.js → LbWlLIDM.js} +1 -1
  124. package/web/app/immutable/chunks/{TaZ6zGN1.js → QsxxF2f1.js} +1 -1
  125. package/web/app/immutable/chunks/{C3L3GwMq.js → RZZC2VMk.js} +1 -1
  126. package/web/app/immutable/chunks/{B0JbhmMb.js → SFGrktzA.js} +1 -1
  127. package/web/app/immutable/chunks/{kbpbXlKS.js → SXIguSgd.js} +1 -1
  128. package/web/app/immutable/chunks/{BPRz9VyT.js → T4Vy0gCu.js} +1 -1
  129. package/web/app/immutable/chunks/{AxCVH26S.js → TXWL9W0o.js} +1 -1
  130. package/web/app/immutable/chunks/{5u3dQlae.js → XlJ5hhYy.js} +1 -1
  131. package/web/app/immutable/chunks/{D00mCTUs.js → _z8Ra-Dv.js} +2 -2
  132. package/web/app/immutable/chunks/{DVlYg0SZ.js → adKwpenO.js} +4 -4
  133. package/web/app/immutable/chunks/{CkVsI2Jc.js → aj6BVewJ.js} +1 -1
  134. package/web/app/immutable/chunks/{C1wjuTFV.js → bCGgAomG.js} +1 -1
  135. package/web/app/immutable/chunks/{C4qqiNcA.js → irvHhhJ8.js} +6 -6
  136. package/web/app/immutable/chunks/{Big1YQpq.js → lNKbWlW4.js} +1 -1
  137. package/web/app/immutable/chunks/{96DwTK9j.js → n9HBJb8W.js} +2 -2
  138. package/web/app/immutable/chunks/{B9pYL5w0.js → rG-lrv5J.js} +3 -3
  139. package/web/app/immutable/chunks/{Ch9oF0ek.js → sqDmXMOe.js} +1 -1
  140. package/web/app/immutable/chunks/{CkuFMgpI.js → sr1p2voA.js} +1 -1
  141. package/web/app/immutable/chunks/{DQTzZEWU.js → srjzsbo_.js} +2 -2
  142. package/web/app/immutable/chunks/{BSM5O6JV.js → tOoxsTJG.js} +1 -1
  143. package/web/app/immutable/chunks/{CpBPE3-0.js → tc8BXJjE.js} +1 -1
  144. package/web/app/immutable/chunks/{MzfVdJbX.js → u8xausOt.js} +1 -1
  145. package/web/app/immutable/chunks/{t94_2IkW.js → veeA223Q.js} +1 -1
  146. package/web/app/immutable/chunks/{DuTju9rc.js → w0ZX4RW-.js} +1 -1
  147. package/web/app/immutable/chunks/xFrJrsZA.js +4 -0
  148. package/web/app/immutable/chunks/{T_1hfFnC.js → xUNvQVfC.js} +2 -2
  149. package/web/app/immutable/entry/{app.CYYj7JvH.js → app.CblwGXso.js} +2 -2
  150. package/web/app/immutable/entry/start.q08osiX3.js +1 -0
  151. package/web/app/immutable/nodes/{0.vJoG8nTo.js → 0.Dj38UZF2.js} +1 -1
  152. package/web/app/immutable/nodes/{1.Di6AbyQm.js → 1.COOUD58l.js} +1 -1
  153. package/web/app/immutable/nodes/{10.BkazfxT8.js → 10.DWYTu71C.js} +4 -4
  154. package/web/app/immutable/nodes/{11.Ck_7PTgk.js → 11.dUTFxK_f.js} +1 -1
  155. package/web/app/immutable/nodes/{15.DWwqZzAg.js → 15.BVFZbc0c.js} +1 -1
  156. package/web/app/immutable/nodes/{19.CjDPuA-n.js → 19.BW6AKD4N.js} +2 -2
  157. package/web/app/immutable/nodes/{2.B7bl9OWL.js → 2.DG3n2WCl.js} +12 -12
  158. package/web/app/immutable/nodes/{20.tmuZaULh.js → 20.BztXJVwA.js} +1 -1
  159. package/web/app/immutable/nodes/{3.CY1Mye6q.js → 3.Ce1vN9CA.js} +1 -1
  160. package/web/app/immutable/nodes/{4.sNrk6dxf.js → 4.Ch2uLuDy.js} +1 -1
  161. package/web/app/immutable/nodes/{5.BrOibHKo.js → 5.DrcqOekH.js} +1 -1
  162. package/web/app/immutable/nodes/{6.BVYLHxv3.js → 6.BIHEeJJU.js} +1 -1
  163. package/web/app/immutable/nodes/{7.BZ0ZLzU_.js → 7.Bbv7Zz5A.js} +1 -1
  164. package/web/app/immutable/nodes/{8.BNlg4qDc.js → 8.ClCyEWtu.js} +1 -1
  165. package/web/app/immutable/nodes/{9.C8X38wWW.js → 9.kP1jiSrK.js} +4 -4
  166. package/web/app/version.json +1 -1
  167. package/web/index.html +9 -9
  168. package/web/app/immutable/chunks/0_7FQkiC.js +0 -1
  169. package/web/app/immutable/chunks/BEyxbMng.js +0 -18
  170. package/web/app/immutable/chunks/CeFme0q3.js +0 -1
  171. package/web/app/immutable/chunks/Cq0xvhw9.js +0 -3
  172. package/web/app/immutable/chunks/DWWTsFh-.js +0 -190
  173. package/web/app/immutable/chunks/DvCS4TTw.js +0 -1
  174. package/web/app/immutable/chunks/lZNvj_WH.js +0 -4
  175. package/web/app/immutable/chunks/yAiwGS7g.js +0 -3
  176. package/web/app/immutable/entry/start.BH_-Ros5.js +0 -1
@@ -1 +1 @@
1
- import{b as a,aW as o}from"./C9otdzZM.js";var g=a((t,e)=>{let n;return e==="sandbox"&&(n=o("#i"+t)),(e==="sandbox"?o(n.nodes()[0].contentDocument.body):o("body")).select(`[id="${t}"]`)},"getDiagramElement");export{g};
1
+ import{b as a,aW as o}from"./BPeXyR5m.js";var g=a((t,e)=>{let n;return e==="sandbox"&&(n=o("#i"+t)),(e==="sandbox"?o(n.nodes()[0].contentDocument.body):o("body")).select(`[id="${t}"]`)},"getDiagramElement");export{g};
@@ -1 +1 @@
1
- import{b as i}from"./C9otdzZM.js";function t(c,e){c.accDescr&&e.setAccDescription?.(c.accDescr),c.accTitle&&e.setAccTitle?.(c.accTitle),c.title&&e.setDiagramTitle?.(c.title)}i(t,"populateCommonDb");export{t as p};
1
+ import{b as i}from"./BPeXyR5m.js";function t(c,e){c.accDescr&&e.setAccDescription?.(c.accDescr),c.accTitle&&e.setAccTitle?.(c.accTitle),c.title&&e.setDiagramTitle?.(c.title)}i(t,"populateCommonDb");export{t as p};
@@ -1 +1 @@
1
- import{vI as V,vG as R,hf as q,hg as K,e as W,IA as z,IX as i,a7 as H,nK as P}from"./BkzMrEqG.js";import{bm as s}from"./AeC4KVgG.js";import{ax as G,l as X,G as $,az as S,f as v}from"./R1d5Y9eD.js";import{w as J}from"./Dz2z231n.js";import{cj as A,cL as Q,cK as Y,cP as Z}from"./BEyxbMng.js";import{y as b}from"./DWPd-rzt.js";const ee=["connected","disconnected","unreachable","revoked","update-required"],m=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),d=e=>typeof e=="string"&&e.length>0,h=e=>typeof e=="string"&&e.length>0?e:void 0,N=e=>Number.isSafeInteger(e)&&e>=0?e:0;function te(e){if(!m(e))return;const t=Array.isArray(e.providers)?e.providers.flatMap(r=>m(r)&&d(r.id)?[{id:r.id,...r.visible===!1?{visible:!1}:{},status:typeof r.status=="string"?r.status:"unknown",models:Array.isArray(r.models)?r.models.filter(o=>d(o)):[],...r.modelsStale===!0?{modelsStale:!0}:{}}]:[]):[],n=h(e.intentdVersion);return{...n?{intentdVersion:n}:{},providers:t}}function Ne(e){if(!m(e)||!d(e.id)||!d(e.name)||!d(e.fingerprint)||!ee.includes(e.state)||!Number.isInteger(e.port)||!d(e.addedAt))return null;const t=m(e.platform)&&d(e.platform.os)&&d(e.platform.arch)?{os:e.platform.os,arch:e.platform.arch}:void 0,n=te(e.capabilities),r=h(e.tcAddress),o=h(e.observedAt),c=h(e.lastConnectedAt),a=V(e.cloud),l=Number.isInteger(e.nodeProtocol)&&e.nodeProtocol>=0?e.nodeProtocol:void 0;return{id:e.id,name:e.name,...t?{platform:t}:{},hosts:Array.isArray(e.hosts)?e.hosts.filter(p=>d(p)):[],port:e.port,...r?{tcAddress:r}:{},fingerprint:e.fingerprint,state:e.state,runningAgents:N(e.runningAgents),...n?{capabilities:n}:{},...l!==void 0?{nodeProtocol:l}:{},...o?{observedAt:o}:{},addedAt:e.addedAt,...c?{lastConnectedAt:c}:{},...a?{cloud:a}:{}}}function Te(e){if(!m(e)||!d(e.credentialId)||!d(e.backendId)||!d(e.backendName)||!d(e.createdAt))return null;const t=h(e.lastUsedAt);return{credentialId:e.credentialId,backendId:e.backendId,backendName:e.backendName,createdAt:e.createdAt,...t?{lastUsedAt:t}:{},connected:e.connected===!0,runningAgents:N(e.runningAgents)}}function xe(e){const t=(typeof e=="string"?e:"").trim().toUpperCase();return t===""?null:t}function ne(e){if(!m(e)||typeof e.name!="string")return null;const t=e.name;return e.kind==="local"?{kind:"local",name:t}:e.kind==="machine"&&d(e.nodeId)?{kind:"machine",nodeId:e.nodeId,name:t}:e.kind==="cloud"&&d(e.cloudMachineId)?{kind:"cloud",cloudMachineId:e.cloudMachineId,name:t}:null}function we(e){if(!Array.isArray(e))return null;const t=[];for(const n of e){const r=ne(n);if(!r)return null;t.push(r)}return t}function re(e){return e.kind==="local"?{kind:"local"}:e.kind==="machine"?{kind:"machine",nodeId:e.nodeId}:{kind:"cloud",cloudMachineId:e.cloudMachineId}}function g(e){return e.kind==="local"?"local":e.kind==="machine"?`machine:${e.nodeId}`:`cloud:${e.cloudMachineId}`}const oe={macos:"macOS",linux:"Linux",windows:"Windows"},ae={aarch64:"arm64",arm64:"arm64",x86_64:"x64",x64:"x64"};function f(e,t){const n=[e&&(oe[e]??e),t&&(ae[t]??t)].filter(r=>!!r);return n.length?n.join(" "):null}function ce(e){return e?.placement?.target==="remote"||b(e?.placement?.target)}const se=new Set(["running","paused","resuming","pausing","stopping"]);function ie(e,t){if(e.placementError)return null;if(e.cloudStart)return"starting";if(!e.nodeId)return e.effectiveIsolation==="pending"?"starting":null;const n=t?.cloud?.state;return n&&se.has(n)?n:e.effectiveIsolation==="pending"?"starting":null}function T(e,t){if(!e||!ce(e))return null;const n=e.nodeId??e.placement?.nodeId??"",r=t&&t.id===n?t:null;if(b(e.placement?.target))return{nodeId:n,name:e.nodeName?.trim()||q(r?.cloud?.provider??K(e.placement?.cloudMachineId)),platform:f(r?.platform?.os,r?.platform?.arch),state:"ready",cloud:{state:ie(e,r)}};const o=f(e.placement?.os,e.placement?.arch)??f(r?.platform?.os,r?.platform?.arch),c=r?.state==="revoked"?"revoked":r?.state==="unreachable"||e.nodeState==="offline"?"unreachable":"ready";return{nodeId:n,name:e.nodeName?.trim()||r?.name||s.remoteAgent_location_unknownMachine(),platform:o,state:c}}function Be(e,t){if(!e)return null;const n=t&&t.id===e?t:null;return{nodeId:e,name:n?.name||s.remoteAgent_location_unknownMachine(),platform:f(n?.platform?.os,n?.platform?.arch),state:n?.state==="revoked"?"revoked":n?.state==="unreachable"?"unreachable":"ready"}}function x(e){switch(e){case"starting":return s.cloudMachines_agent_starting();case"running":return s.cloudMachines_agent_running();case"paused":return s.cloudMachines_agent_paused();case"resuming":return s.cloudMachines_agent_resuming();case"pausing":return s.cloudMachines_agent_pausing();case"stopping":return s.cloudMachines_agent_stopping();default:return null}}function De(e){const t=x(e.cloud?.state);return t?s.cloudMachines_agent_chip({machine:e.name,state:t}):e.name}function Fe(e){if(e.cloud){const n=x(e.cloud.state),r=s.remoteAgent_location_tooltipNoPlatform({machine:e.name});return n?s.remoteAgent_location_tooltipWithState({location:r,state:n}):r}const t=e.platform?s.remoteAgent_location_tooltip({machine:e.name,platform:e.platform}):s.remoteAgent_location_tooltipNoPlatform({machine:e.name});switch(e.state){case"unreachable":return s.remoteAgent_location_tooltipWithState({location:t,state:s.remoteMachines_state_unreachable_label()});case"revoked":return s.remoteAgent_location_tooltipWithState({location:t,state:s.remoteMachines_state_revoked_label()});default:return t}}function w(e,t){return!e||!t?null:e.placementError?"failed":t.state==="revoked"?"revoked":t.state==="unreachable"?"unreachable":e.effectiveIsolation==="pending"||e.cloudStart?"starting":e.setup?.state==="failed"?"setup-failed":null}function B(e){if(!e.endsWith("}"))return null;for(let t=e.indexOf(" {");t>=0;t=e.indexOf(" {",t+1))try{const n=JSON.parse(e.slice(t+1));if(n&&typeof n=="object"&&typeof n.code=="string")return{message:e.slice(0,t).trim(),data:n}}catch{}return null}function le(e,t){const n=e.detail??"",r=B(n),o=e.code==="machine-update-required"||r?.data.code==="machine-update-required";if(o&&r?.data.reason==="prepared-checkout")return{updateRequired:o,message:s.remoteAgent_updateRequired_preparedCheckout({machine:t})};const c=R(r?.data),a=c??(e.code?R({code:e.code}):null);return a?{updateRequired:o,message:r?.message||n,cloud:a,cloudDetailKnown:!!c}:{updateRequired:o,message:r?.message||n}}function Ue(e){if(!b(e?.placement?.target)||!e.placementError||e.status!==W.Error)return null;const t=le(e.placementError,"");return t.cloud?t:null}const de=["attachments-too-large-for-machine:","node-prompt-too-large:"],ue="remote-agent-unsupported:";function C(e){return new Intl.NumberFormat(void 0,{maximumFractionDigits:1}).format(e/1048576)}function je(e){const t=B(e)?.message??e;for(const r of de){const o=t.indexOf(r);if(o<0)continue;const c=t.slice(o+r.length).trim().replace(/^[a-z][\w]*(?:\.[\w]+)+:\s*/i,""),a=/come to (\d+) bytes\b.*?over its (\d+)-byte limit/.exec(c);return a?s.remoteAgent_attachmentsTooLargeSized_error({size:C(Number(a[1])),limit:C(Number(a[2]))}):c?s.remoteAgent_attachmentsTooLarge_error({detail:c}):s.remoteAgent_attachmentsTooLargeNoDetail_error()}const n=t.indexOf(ue);return n>=0&&/attachment/i.test(t.slice(n))?s.remoteAgent_attachmentsUnsupported_error():null}function Ve(e){return b(e?.placement?.target)&&w(e,T(e))==="starting"}function qe(e,t){if(!b(e?.placement?.target))return!1;const n=T(e,t);return n?.cloud?.state==="resuming"&&w(e,n)===null}const u="",M="cloud:";function O(e){return`${M}${e}`}function _(e){return e?.startsWith(M)&&e.slice(M.length)||null}const Ke=O("e2b");function fe(e,t){return e?.find(n=>O(n.cloudMachineId)===t&&n.unavailableReason===null)}const me=new Set(["connected","disconnected"]);function pe(e){switch(e){case"unreachable":return s.remoteMachines_state_unreachable_label();case"revoked":return s.remoteMachines_state_revoked_label();case"update-required":return s.remoteMachines_state_updateRequired_label();default:return}}function k(e){return me.has(e.state)}function he({backendLabel:e,backendPlatform:t,machines:n,cloud:r,orchestrator:o=!1}){const c=[o?{id:u,label:s.remoteMachines_startOn_firstAvailable_label(),platform:null,disabled:!1,hint:s.remoteMachines_startOn_firstAvailable_hint()}:{id:u,label:e,platform:f(t?.os,t?.arch),disabled:!1},...n.map(a=>{const l=f(a.platform?.os,a.platform?.arch);return k(a)?{id:a.id,label:a.name,platform:l,disabled:!1}:{id:a.id,label:a.name,platform:l,disabled:!0,reason:pe(a.state)}})];for(const a of r??[])c.push({id:O(a.cloudMachineId),label:a.label,platform:null,kind:"cloud",disabled:a.unavailableReason!==null,...a.unavailableReason?{reason:a.unavailableReason}:a.needsProfile?{hint:s.cloudMachines_startOn_hint()}:{}});return c}function We(e){return e.find(t=>t.id===u)?.label??""}function ze(e,t,n){if(e!==u)return _(e)?void 0:e;if(n)return t.find(r=>r.id!==u&&r.kind!=="cloud"&&!r.disabled)?.id}function ge({remoteMachinesVisible:e,supported:t,machines:n,cloud:r}){return e&&t&&(n.some(k)||(r??[]).some(o=>o.unavailableReason===null))}function be(e,t,n){if(!e)return u;if(_(e))return fe(n,e)?e:u;const r=t.find(o=>o.id===e);return r&&k(r)?r.id:u}function He(e,{cloudEntries:t=!1,providerOf:n}={}){const r=_(e);if(r){const o=n?.(r);return t&&o&&o!=="e2b"?{target:"cloud",checkout:"isolated",cloudMachineId:r}:t?{target:"e2b",checkout:"isolated",cloudMachineId:r}:{target:"e2b",checkout:"isolated"}}return e?{target:"remote",checkout:"isolated",nodeId:e}:void 0}function Ge({groups:e,providerRef:t,model:n}){const r=a=>a.options.filter(l=>!l.disabled),o=e.find(a=>a.key===t),c=o?r(o):[];if(n){const a=z(n).modelId;if(c.some(l=>l.value===a))return null}else if(c.length>0)return null;if(o&&c.length>0)return{providerId:o.key,modelId:c[0].value};for(const a of e){if(a.key==="default")continue;const l=r(a);if(l.length>0)return{providerId:a.key,modelId:l[0].value}}return null}function _e(e,t,n,r){const o=e.map(g),c=o.indexOf(t),a=o.indexOf(n);if(c<0||a<0||c===a)return null;let l=a+(r==="after"?1:0);if(c<l&&(l-=1),l===c)return null;const p=[...e],[j]=p.splice(c,1);return p.splice(l,0,j),p.map(re)}function Xe(e,t,n){const r=e.findIndex(c=>g(c)===t),o=e[r+n];return r<0||!o?null:_e(e,t,g(o),n===-1?"before":"after")}function Me(e,t){if(e===u)return"local";const n=t==="cloud"?_(e):null;return g(n?{kind:"cloud",cloudMachineId:n}:{kind:"machine",nodeId:e})}function E(e,t){const n=new Map(t.map((o,c)=>[g(o),c])),r=o=>n.get(Me(o.id,o.kind))??t.length;return e.map((o,c)=>({option:o,index:c})).sort((o,c)=>r(o.option)-r(c.option)||o.index-c.index).map(({option:o})=>o)}const Se=i.createSelector(e=>J.select(e)||A.select(e)),I=i.createSelector(e=>Se.select(e)&&e.remoteMachines?.supported===!0),$e=i.createSelector(e=>I.select(e)&&G.select(e)&&!A.select(e)),D=i.createSelector(e=>I.select(e)&&e.remoteMachines.machineOrder===!0&&e.remoteMachines.order!==null),L=i.createSelector(e=>D.select(e)?e.remoteMachines.order??[]:[]),ve=i.createSelector(e=>e.remoteMachines.orderSaving!==null),y=i.createSelector(e=>Object.values(e.remoteMachines?.machines??{}).sort((t,n)=>t.name.localeCompare(n.name))),Je=i.createSelector(e=>e.remoteMachines.localFingerprint),Qe=i.createSelector(e=>e.remoteMachines.pending),Ye=i.createSelector(e=>e.remoteMachines.failures),Ze=i.createSelector(e=>e.remoteMachines.executorBackends??[]),Ae=i.createSelector((e,t)=>{if(t===H)return s.layout_daemonStatus_localConnection_label();const n=P(e.connections.connections,t);return n?X(n):t}),Oe=i.createSelector(e=>Ae.select(e,e.connections.windowBackendId)),et=i.createSelector((e,t)=>(t?e.remoteMachines.machines[t]??e.cloudMachines?.machines[t]:void 0)??null),tt=i.createSelector((e,t)=>{const n=e.providerSettings?.profiles;return $({catalogProfiles:Z.select(e,t),defaultRemoteIncompatibility:Y.select(e,t),defaultRemoteLaunch:Q.select(e,t),profileDefaults:Object.values(n?.defaults??{}),profilesLoadStatus:n?.loadStatus??"idle"})}),nt=i.createSelector(e=>Object.fromEntries(Object.values(e.providerSettings?.profiles?.defaults??{}).map(t=>[t.baseProviderId,t.env.length>0]))),F=i.createSelector(e=>ge({remoteMachinesVisible:I.select(e),supported:e.remoteMachines?.initialAgentPlacement===!0,machines:y.select(e),cloud:S(e)}));function ke(e){const t=P(e.connections.connections,e.connections.windowBackendId);return t?.hostOs?{os:t.hostOs,arch:t.hostArch}:void 0}const Ie=i.createSelector(e=>{const t=A.select(e),n=he({backendLabel:Oe.select(e),backendPlatform:ke(e),machines:y.select(e),cloud:S(e),orchestrator:t});if(!D.select(e))return n;if(!t)return E(n,L.select(e));const[r,...o]=n;return[r,...E(o,L.select(e))]}),rt=i.createSelector(e=>F.select(e)?Ie.select(e):[]),ot=i.createSelector(e=>e.remoteMachines?.initialAgentPlacement===!0),at=i.createSelector((e,t,n)=>F.select(e)?be(t,y.select(e),U(e,n)):u);function U(e,t){const n=S(e);if(!n||!t)return n;const r=e.cloudMachines?.providers??{};return n.map(o=>{if(o.unavailableReason)return o;const c=v(e,t,r[o.cloudMachineId]??null);return c?{...o,unavailableReason:c}:o})}const ct=i.createSelector((e,t)=>U(e,t));export{ot as A,Je as B,L as C,ve as D,D as E,et as F,Ye as G,Qe as H,y as I,Se as J,I as K,tt as L,$e as M,ct as N,rt as O,Ie as P,F as Q,We as R,u as S,O as T,_ as U,ze as V,Xe as W,Ke as a,Ue as b,Ve as c,qe as d,De as e,T as f,Fe as g,w as h,xe as i,He as j,Ge as k,g as l,Be as m,f as n,_e as o,Te as p,we as q,Ne as r,le as s,je as t,be as u,Ae as v,Oe as w,nt as x,at as y,Ze as z};
1
+ import{vI as W,vG as R,hf as j,hg as q,e as K,IA as z,IX as i,a7 as H,nK as P}from"./BkzMrEqG.js";import{bm as s}from"./AeC4KVgG.js";import{ax as G,l as X,G as $,az as S,f as v}from"./CP5zM-2z.js";import{w as J}from"./Dz2z231n.js";import{cu as A,cW as Q,cV as Y,c_ as Z}from"./-5BGDZDk.js";import{y as b}from"./DWPd-rzt.js";const ee=["connected","disconnected","unreachable","revoked","update-required"],m=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),d=e=>typeof e=="string"&&e.length>0,h=e=>typeof e=="string"&&e.length>0?e:void 0,N=e=>Number.isSafeInteger(e)&&e>=0?e:0;function te(e){if(!m(e))return;const t=Array.isArray(e.providers)?e.providers.flatMap(r=>m(r)&&d(r.id)?[{id:r.id,...r.visible===!1?{visible:!1}:{},status:typeof r.status=="string"?r.status:"unknown",models:Array.isArray(r.models)?r.models.filter(o=>d(o)):[],...r.modelsStale===!0?{modelsStale:!0}:{}}]:[]):[],n=h(e.intentdVersion);return{...n?{intentdVersion:n}:{},providers:t}}function Ne(e){if(!m(e)||!d(e.id)||!d(e.name)||!d(e.fingerprint)||!ee.includes(e.state)||!Number.isInteger(e.port)||!d(e.addedAt))return null;const t=m(e.platform)&&d(e.platform.os)&&d(e.platform.arch)?{os:e.platform.os,arch:e.platform.arch}:void 0,n=te(e.capabilities),r=h(e.tcAddress),o=h(e.observedAt),c=h(e.lastConnectedAt),a=W(e.cloud),l=Number.isInteger(e.nodeProtocol)&&e.nodeProtocol>=0?e.nodeProtocol:void 0;return{id:e.id,name:e.name,...t?{platform:t}:{},hosts:Array.isArray(e.hosts)?e.hosts.filter(p=>d(p)):[],port:e.port,...r?{tcAddress:r}:{},fingerprint:e.fingerprint,state:e.state,runningAgents:N(e.runningAgents),...n?{capabilities:n}:{},...l!==void 0?{nodeProtocol:l}:{},...o?{observedAt:o}:{},addedAt:e.addedAt,...c?{lastConnectedAt:c}:{},...a?{cloud:a}:{}}}function Te(e){if(!m(e)||!d(e.credentialId)||!d(e.backendId)||!d(e.backendName)||!d(e.createdAt))return null;const t=h(e.lastUsedAt);return{credentialId:e.credentialId,backendId:e.backendId,backendName:e.backendName,createdAt:e.createdAt,...t?{lastUsedAt:t}:{},connected:e.connected===!0,runningAgents:N(e.runningAgents)}}function xe(e){const t=(typeof e=="string"?e:"").trim().toUpperCase();return t===""?null:t}function ne(e){if(!m(e)||typeof e.name!="string")return null;const t=e.name;return e.kind==="local"?{kind:"local",name:t}:e.kind==="machine"&&d(e.nodeId)?{kind:"machine",nodeId:e.nodeId,name:t}:e.kind==="cloud"&&d(e.cloudMachineId)?{kind:"cloud",cloudMachineId:e.cloudMachineId,name:t}:null}function we(e){if(!Array.isArray(e))return null;const t=[];for(const n of e){const r=ne(n);if(!r)return null;t.push(r)}return t}function re(e){return e.kind==="local"?{kind:"local"}:e.kind==="machine"?{kind:"machine",nodeId:e.nodeId}:{kind:"cloud",cloudMachineId:e.cloudMachineId}}function g(e){return e.kind==="local"?"local":e.kind==="machine"?`machine:${e.nodeId}`:`cloud:${e.cloudMachineId}`}const oe={macos:"macOS",linux:"Linux",windows:"Windows"},ae={aarch64:"arm64",arm64:"arm64",x86_64:"x64",x64:"x64"};function f(e,t){const n=[e&&(oe[e]??e),t&&(ae[t]??t)].filter(r=>!!r);return n.length?n.join(" "):null}function ce(e){return e?.placement?.target==="remote"||b(e?.placement?.target)}const se=new Set(["running","paused","resuming","pausing","stopping"]);function ie(e,t){if(e.placementError)return null;if(e.cloudStart)return"starting";if(!e.nodeId)return e.effectiveIsolation==="pending"?"starting":null;const n=t?.cloud?.state;return n&&se.has(n)?n:e.effectiveIsolation==="pending"?"starting":null}function T(e,t){if(!e||!ce(e))return null;const n=e.nodeId??e.placement?.nodeId??"",r=t&&t.id===n?t:null;if(b(e.placement?.target))return{nodeId:n,name:e.nodeName?.trim()||j(r?.cloud?.provider??q(e.placement?.cloudMachineId)),platform:f(r?.platform?.os,r?.platform?.arch),state:"ready",cloud:{state:ie(e,r)}};const o=f(e.placement?.os,e.placement?.arch)??f(r?.platform?.os,r?.platform?.arch),c=r?.state==="revoked"?"revoked":r?.state==="unreachable"||e.nodeState==="offline"?"unreachable":"ready";return{nodeId:n,name:e.nodeName?.trim()||r?.name||s.remoteAgent_location_unknownMachine(),platform:o,state:c}}function Be(e,t){if(!e)return null;const n=t&&t.id===e?t:null;return{nodeId:e,name:n?.name||s.remoteAgent_location_unknownMachine(),platform:f(n?.platform?.os,n?.platform?.arch),state:n?.state==="revoked"?"revoked":n?.state==="unreachable"?"unreachable":"ready"}}function x(e){switch(e){case"starting":return s.cloudMachines_agent_starting();case"running":return s.cloudMachines_agent_running();case"paused":return s.cloudMachines_agent_paused();case"resuming":return s.cloudMachines_agent_resuming();case"pausing":return s.cloudMachines_agent_pausing();case"stopping":return s.cloudMachines_agent_stopping();default:return null}}function De(e){const t=x(e.cloud?.state);return t?s.cloudMachines_agent_chip({machine:e.name,state:t}):e.name}function Fe(e){if(e.cloud){const n=x(e.cloud.state),r=s.remoteAgent_location_tooltipNoPlatform({machine:e.name});return n?s.remoteAgent_location_tooltipWithState({location:r,state:n}):r}const t=e.platform?s.remoteAgent_location_tooltip({machine:e.name,platform:e.platform}):s.remoteAgent_location_tooltipNoPlatform({machine:e.name});switch(e.state){case"unreachable":return s.remoteAgent_location_tooltipWithState({location:t,state:s.remoteMachines_state_unreachable_label()});case"revoked":return s.remoteAgent_location_tooltipWithState({location:t,state:s.remoteMachines_state_revoked_label()});default:return t}}function w(e,t){return!e||!t?null:e.placementError?"failed":t.state==="revoked"?"revoked":t.state==="unreachable"?"unreachable":e.effectiveIsolation==="pending"||e.cloudStart?"starting":e.setup?.state==="failed"?"setup-failed":null}function B(e){if(!e.endsWith("}"))return null;for(let t=e.indexOf(" {");t>=0;t=e.indexOf(" {",t+1))try{const n=JSON.parse(e.slice(t+1));if(n&&typeof n=="object"&&typeof n.code=="string")return{message:e.slice(0,t).trim(),data:n}}catch{}return null}function le(e,t){const n=e.detail??"",r=B(n),o=e.code==="machine-update-required"||r?.data.code==="machine-update-required";if(o&&r?.data.reason==="prepared-checkout")return{updateRequired:o,message:s.remoteAgent_updateRequired_preparedCheckout({machine:t})};const c=R(r?.data),a=c??(e.code?R({code:e.code}):null);return a?{updateRequired:o,message:r?.message||n,cloud:a,cloudDetailKnown:!!c}:{updateRequired:o,message:r?.message||n}}function Ue(e){if(!b(e?.placement?.target)||!e.placementError||e.status!==K.Error)return null;const t=le(e.placementError,"");return t.cloud?t:null}const de=["attachments-too-large-for-machine:","node-prompt-too-large:"],ue="remote-agent-unsupported:";function C(e){return new Intl.NumberFormat(void 0,{maximumFractionDigits:1}).format(e/1048576)}function Ve(e){const t=B(e)?.message??e;for(const r of de){const o=t.indexOf(r);if(o<0)continue;const c=t.slice(o+r.length).trim().replace(/^[a-z][\w]*(?:\.[\w]+)+:\s*/i,""),a=/come to (\d+) bytes\b.*?over its (\d+)-byte limit/.exec(c);return a?s.remoteAgent_attachmentsTooLargeSized_error({size:C(Number(a[1])),limit:C(Number(a[2]))}):c?s.remoteAgent_attachmentsTooLarge_error({detail:c}):s.remoteAgent_attachmentsTooLargeNoDetail_error()}const n=t.indexOf(ue);return n>=0&&/attachment/i.test(t.slice(n))?s.remoteAgent_attachmentsUnsupported_error():null}function We(e){return b(e?.placement?.target)&&w(e,T(e))==="starting"}function je(e,t){if(!b(e?.placement?.target))return!1;const n=T(e,t);return n?.cloud?.state==="resuming"&&w(e,n)===null}const u="",M="cloud:";function O(e){return`${M}${e}`}function _(e){return e?.startsWith(M)&&e.slice(M.length)||null}const qe=O("e2b");function fe(e,t){return e?.find(n=>O(n.cloudMachineId)===t&&n.unavailableReason===null)}const me=new Set(["connected","disconnected"]);function pe(e){switch(e){case"unreachable":return s.remoteMachines_state_unreachable_label();case"revoked":return s.remoteMachines_state_revoked_label();case"update-required":return s.remoteMachines_state_updateRequired_label();default:return}}function k(e){return me.has(e.state)}function he({backendLabel:e,backendPlatform:t,machines:n,cloud:r,orchestrator:o=!1}){const c=[o?{id:u,label:s.remoteMachines_startOn_firstAvailable_label(),platform:null,disabled:!1,hint:s.remoteMachines_startOn_firstAvailable_hint()}:{id:u,label:e,platform:f(t?.os,t?.arch),disabled:!1},...n.map(a=>{const l=f(a.platform?.os,a.platform?.arch);return k(a)?{id:a.id,label:a.name,platform:l,disabled:!1}:{id:a.id,label:a.name,platform:l,disabled:!0,reason:pe(a.state)}})];for(const a of r??[])c.push({id:O(a.cloudMachineId),label:a.label,platform:null,kind:"cloud",disabled:a.unavailableReason!==null,...a.unavailableReason?{reason:a.unavailableReason}:a.needsProfile?{hint:s.cloudMachines_startOn_hint()}:{}});return c}function Ke(e){return e.find(t=>t.id===u)?.label??""}function ze(e,t,n){if(e!==u)return _(e)?void 0:e;if(n)return t.find(r=>r.id!==u&&r.kind!=="cloud"&&!r.disabled)?.id}function ge({remoteMachinesVisible:e,supported:t,machines:n,cloud:r}){return e&&t&&(n.some(k)||(r??[]).some(o=>o.unavailableReason===null))}function be(e,t,n){if(!e)return u;if(_(e))return fe(n,e)?e:u;const r=t.find(o=>o.id===e);return r&&k(r)?r.id:u}function He(e,{cloudEntries:t=!1,providerOf:n}={}){const r=_(e);if(r){const o=n?.(r);return t&&o&&o!=="e2b"?{target:"cloud",checkout:"isolated",cloudMachineId:r}:t?{target:"e2b",checkout:"isolated",cloudMachineId:r}:{target:"e2b",checkout:"isolated"}}return e?{target:"remote",checkout:"isolated",nodeId:e}:void 0}function Ge({groups:e,providerRef:t,model:n}){const r=a=>a.options.filter(l=>!l.disabled),o=e.find(a=>a.key===t),c=o?r(o):[];if(n){const a=z(n).modelId;if(c.some(l=>l.value===a))return null}else if(c.length>0)return null;if(o&&c.length>0)return{providerId:o.key,modelId:c[0].value};for(const a of e){if(a.key==="default")continue;const l=r(a);if(l.length>0)return{providerId:a.key,modelId:l[0].value}}return null}function _e(e,t,n,r){const o=e.map(g),c=o.indexOf(t),a=o.indexOf(n);if(c<0||a<0||c===a)return null;let l=a+(r==="after"?1:0);if(c<l&&(l-=1),l===c)return null;const p=[...e],[V]=p.splice(c,1);return p.splice(l,0,V),p.map(re)}function Xe(e,t,n){const r=e.findIndex(c=>g(c)===t),o=e[r+n];return r<0||!o?null:_e(e,t,g(o),n===-1?"before":"after")}function Me(e,t){if(e===u)return"local";const n=t==="cloud"?_(e):null;return g(n?{kind:"cloud",cloudMachineId:n}:{kind:"machine",nodeId:e})}function E(e,t){const n=new Map(t.map((o,c)=>[g(o),c])),r=o=>n.get(Me(o.id,o.kind))??t.length;return e.map((o,c)=>({option:o,index:c})).sort((o,c)=>r(o.option)-r(c.option)||o.index-c.index).map(({option:o})=>o)}const Se=i.createSelector(e=>J.select(e)||A.select(e)),I=i.createSelector(e=>Se.select(e)&&e.remoteMachines?.supported===!0),$e=i.createSelector(e=>I.select(e)&&G.select(e)&&!A.select(e)),D=i.createSelector(e=>I.select(e)&&e.remoteMachines.machineOrder===!0&&e.remoteMachines.order!==null),L=i.createSelector(e=>D.select(e)?e.remoteMachines.order??[]:[]),ve=i.createSelector(e=>e.remoteMachines.orderSaving!==null),y=i.createSelector(e=>Object.values(e.remoteMachines?.machines??{}).sort((t,n)=>t.name.localeCompare(n.name))),Je=i.createSelector(e=>e.remoteMachines.localFingerprint),Qe=i.createSelector(e=>e.remoteMachines.pending),Ye=i.createSelector(e=>e.remoteMachines.failures),Ze=i.createSelector(e=>e.remoteMachines.executorBackends??[]),Ae=i.createSelector((e,t)=>{if(t===H)return s.layout_daemonStatus_localConnection_label();const n=P(e.connections.connections,t);return n?X(n):t}),Oe=i.createSelector(e=>Ae.select(e,e.connections.windowBackendId)),et=i.createSelector((e,t)=>(t?e.remoteMachines.machines[t]??e.cloudMachines?.machines[t]:void 0)??null),tt=i.createSelector((e,t)=>{const n=e.providerSettings?.profiles;return $({catalogProfiles:Z.select(e,t),defaultRemoteIncompatibility:Y.select(e,t),defaultRemoteLaunch:Q.select(e,t),profileDefaults:Object.values(n?.defaults??{}),profilesLoadStatus:n?.loadStatus??"idle"})}),nt=i.createSelector(e=>Object.fromEntries(Object.values(e.providerSettings?.profiles?.defaults??{}).map(t=>[t.baseProviderId,t.env.length>0]))),F=i.createSelector(e=>ge({remoteMachinesVisible:I.select(e),supported:e.remoteMachines?.initialAgentPlacement===!0,machines:y.select(e),cloud:S(e)}));function ke(e){const t=P(e.connections.connections,e.connections.windowBackendId);return t?.hostOs?{os:t.hostOs,arch:t.hostArch}:void 0}const Ie=i.createSelector(e=>{const t=A.select(e),n=he({backendLabel:Oe.select(e),backendPlatform:ke(e),machines:y.select(e),cloud:S(e),orchestrator:t});if(!D.select(e))return n;if(!t)return E(n,L.select(e));const[r,...o]=n;return[r,...E(o,L.select(e))]}),rt=i.createSelector(e=>F.select(e)?Ie.select(e):[]),ot=i.createSelector(e=>e.remoteMachines?.initialAgentPlacement===!0),at=i.createSelector((e,t,n)=>F.select(e)?be(t,y.select(e),U(e,n)):u);function U(e,t){const n=S(e);if(!n||!t)return n;const r=e.cloudMachines?.providers??{};return n.map(o=>{if(o.unavailableReason)return o;const c=v(e,t,r[o.cloudMachineId]??null);return c?{...o,unavailableReason:c}:o})}const ct=i.createSelector((e,t)=>U(e,t));export{ot as A,Je as B,L as C,ve as D,D as E,et as F,Ye as G,Qe as H,y as I,Se as J,I as K,tt as L,$e as M,ct as N,rt as O,Ie as P,F as Q,Ke as R,u as S,O as T,_ as U,ze as V,Xe as W,qe as a,Ue as b,We as c,je as d,De as e,T as f,Fe as g,w as h,xe as i,He as j,Ge as k,g as l,Be as m,f as n,_e as o,Te as p,we as q,Ne as r,le as s,Ve as t,be as u,Ae as v,Oe as w,nt as x,at as y,Ze as z};
@@ -1,14 +1,14 @@
1
- import{t as oe,bo as st,bm as Q,bw as ie,bs as $t,bq as Me,b as ce}from"./AeC4KVgG.js";import{bs as le,a5 as L,bS as C,ay as Yt,aD as t,bA as $,bl as K,b_ as k,bO as D,W as _,bn as de,c9 as y,aA as rt,aB as F,bV as Mt,br as _a,aw as De,aj as Se,bH as V,ai as ya,be as Ia,b$ as xa,bf as wa,aC as he,a7 as Be}from"./CJxGDkBm.js";import{i as at}from"./k2awEenT.js";import{I as ea,g as jt,i as Ne}from"./CswzK9Go.js";import{f as Xt,g as ne,s as gt,c as se}from"./DrHJ7oPv.js";import{b as ba}from"./NtFyWdpR.js";import{f as Ut}from"./DJM6amHV.js";import"./jhNNYE0v.js";import{A as aa,b as na,a as sa}from"./DwHEsGP4.js";import"./Dp2nUoTL.js";import{al as ra,aC as oa,an as Aa,ao as ka,ap as We,ag as ia,a as $a,p as Ta,dx as Ca,aO as Sa,aq as Na}from"./BEyxbMng.js";import{R as Oa}from"./BbV7MtxC.js";import{F as pe,bA as Fa,bf as Ra,aB as Ma,aV as Wa,cD as Da}from"./Ci7mS1ie.js";import{H as Ba}from"./CCnGCUBh.js";import{A as La}from"./gJtrDJPm.js";import{L as Ea}from"./CJHViisg.js";import{f as Pa}from"./W67SWYQh.js";import{e as Nt,IX as Fe,nL as Ga,fM as za,c1 as ja,sm as Ka,uJ as Ha}from"./BkzMrEqG.js";function qa(e){return e.type==="agent"}const Xa=180,Ya=180;var Le=F('<div class="activity-pill shrink-0 text-xs px-3 py-1.5 bg-muted/60 border border-border rounded-lg text-subtle max-w-32 truncate"><!> </div>'),Ua=F('<div class="text-ui text-subtle line-clamp-2 leading-tight px-1"> </div>'),Va=F('<div><div class="flex items-center justify-center gap-1"><!> <span class="truncate"> </span></div> <!> <!></div>'),Qa=F('<div class="text-sm text-primary-ink flex items-center justify-center gap-1"><!> <span class="truncate"> </span></div>'),Oe=F('<span class="text-xs text-subtle"> </span>'),Za=F('<span class="status-pill text-xs px-1.5 py-0.5 bg-muted/80 rounded-md text-subtle truncate max-w-[130px]"> </span>'),Ja=F('<div class="text-ui text-subtle truncate w-full px-1 leading-tight"> </div>'),tn=F('<div class="flex flex-col items-center gap-1"><div class="flex items-center justify-center gap-1.5"><!> <!></div> <!></div>'),en=F('<div class="text-sm text-subtle line-clamp-3 leading-tight"> </div>'),an=F('<div class="avatar-wrapper h-9 w-12 flex items-center justify-center bg-background rounded-full"><!></div> <span class="font-semibold text-center leading-tight line-clamp-2"> </span> <div class="status-footer mt-auto pt-2 w-full text-center"><!></div>',1),nn=F('<div class="agent-card-wrapper flex items-center gap-3 shadow"><!> <!> <!></div>');function ca(e,a){if(new.target)return oe({component:ca,...e});le(a,!0);const s=()=>$t(_t,"$attentionRequest$",o),g=()=>$t(it,"$agentSession$",o),u=()=>$t(x,"$agentIsResponding$",o),c=()=>$t(ct,"$agentIsWaitingForOtherAgents$",o),d=()=>$t(P,"$agentIsWaiting$",o),i=()=>$t(I,"$agentIsThinking$",o),[o,l]=Me();let n=st(a,"agent",7),p=st(a,"activeFile",7),R=st(a,"activeNote",7),h=st(a,"agentNames",7),v=st(a,"onclick",7),b=st(a,"onmouseenter",7),S=st(a,"onmouseleave",7);const x=ra(n().agentId),it=oa(n().agentId),E=y(()=>!n().waitingForAgentIds||n().waitingForAgentIds.length===0?[]:n().waitingForAgentIds.map(A=>h()?.get(A)||Q.agentOverview_hierarchyCard_agent_fallback()).slice(0,2)),I=Aa(n().agentId),P=ka(n().agentId),ct=We(n().agentId),_t=ia(n().agentId),Ot=y(()=>{const A={attentionKind:s()?.kind??null};return g()?na(g(),A):sa({status:n().status,isResponding:u(),isWaitingForOtherAgents:c()},{...A,isCompleted:n().status==="completed",isFailed:n().status==="failed"})});var Dt={get agent(){return n()},set agent(A){n(A),rt()},get activeFile(){return p()},set activeFile(A){p(A),rt()},get activeNote(){return R()},set activeNote(A){R(A),rt()},get agentNames(){return h()},set agentNames(A){h(A),rt()},get onclick(){return v()},set onclick(A){v(A),rt()},get onmouseenter(){return b()},set onmouseenter(A){b(A),rt()},get onmouseleave(){return S()},set onmouseleave(A){S(A),rt()},$set:ie,$on:(A,B)=>ce(a,A,B)},ht=nn(),bt=L(ht);{var Kt=A=>{var B=Le(),Tt=L(B);pe(Tt,{get icon(){return Ra},size:"xs",class:"inline"});var Rt=C(Tt);$(B),k(()=>D(Rt,` ${p()??""}`)),_(A,B)};at(bt,A=>{p()&&u()&&A(Kt)})}var Ft=C(bt,2);{let A=y(()=>d()?"border-primary-ink border-2":"");Ut(Ft,{variant:"ghost",type:"button",get class(){return`agent-card flex flex-col items-center px-2.5 py-4 bg-card border border-border
2
- hover:shadow transition-all cursor-pointer ${t(A)??""}`},get style(){return`width: 180px; height: 180px; anchor-name: --agent-hierarchy-${n().agentId??""};`},get onclick(){return v()},get onmouseenter(){return b()},get onmouseleave(){return S()},children:(B,Tt)=>{var Rt=an(),Lt=Yt(Rt),me=L(Lt);aa(me,{get agentId(){return n().agentId},variant:"emphasized",get state(){return t(Ot)},get specialist(){return n().specialist}}),$(Lt);var Zt=C(Lt,2),_e=K(Zt,!0),Jt=C(Zt,2),te=L(Jt);{var ye=ft=>{var r=Va(),f=L(r),M=L(f);{let z=y(()=>s().kind==="blocker"?Ma:Wa);pe(M,{get icon(){return t(z)},size:"xs"})}var W=C(M,2),m=K(W,!0);$(f);var H=C(f,2);{var nt=z=>{var It=Ua(),ot=K(It,!0);k(()=>D(ot,s().reason)),_(z,It)};at(H,z=>{s().reason&&z(nt)})}var N=C(H,2);{var G=z=>{Oa(z,{get date(){return s().timestamp},class:"text-ui text-ghost"})};at(N,z=>{s().timestamp&&z(G)})}$(r),k(z=>{Xt(r,1,`text-sm flex flex-col items-center gap-0.5 ${s().kind==="blocker"?"text-red-500":"text-warning-ink"}`),D(m,z)},[()=>s().kind==="blocker"?Q.chat_agentCard_attentionBlocker_label():Q.chat_agentCard_attentionDiscussion_label()]),_(ft,r)},yt=ft=>{var r=Qa(),f=L(r);pe(f,{get icon(){return Fa},size:"xs",class:"animate-pulse"});var M=C(f,2),W=K(M,!0);$(r),k(m=>D(W,m),[()=>Q.agentOverview_hierarchyCard_waitingFor_label({names:t(E).join(", ")})]),_(ft,r)},Ie=ft=>{const r=y(()=>n().activeToolName?$a(n().activeToolName,n().activeToolInput||{}):null),f=y(()=>t(r)&&!t(r).hidden?t(r):null);var M=tn(),W=L(M),m=L(W);ea(m,{size:14});var H=C(m,2);{var nt=Y=>{var Z=Oe(),pt=K(Z,!0);k(Et=>D(pt,Et),[()=>Q.agentOverview_hierarchyCard_thinking_label()]),_(Y,Z)},N=Y=>{var Z=Za(),pt=K(Z);k(()=>D(pt,`${t(f).verb??""}
3
- ${t(f).subject??""}`)),_(Y,Z)},G=Y=>{var Z=Oe(),pt=K(Z);k(()=>D(pt,`${t(f).verb??""}...`)),_(Y,Z)},z=Y=>{var Z=Oe(),pt=K(Z,!0);k(Et=>D(pt,Et),[()=>Q.agentOverview_hierarchyCard_responding_label()]),_(Y,Z)};at(H,Y=>{i()?Y(nt):t(f)&&t(f).subject?Y(N,1):t(f)?Y(G,2):Y(z,-1)})}$(W);var It=C(W,2);{var ot=Y=>{var Z=Ja(),pt=K(Z,!0);k(()=>D(pt,n().lastResponse)),_(Y,Z)};at(It,Y=>{!t(f)&&n().lastResponse&&Y(ot)})}$(M),_(ft,M)},xe=ft=>{var r=en(),f=K(r,!0);k(()=>D(f,n().lastResponse)),_(ft,r)};at(te,ft=>{s()?ft(ye):c()?ft(yt,1):u()||i()?ft(Ie,2):n().lastResponse&&ft(xe,3)})}$(Jt),k(()=>D(_e,n().name)),_(B,Rt)},$$slots:{default:!0}})}var ge=C(Ft,2);{var Bt=A=>{var B=Le(),Tt=L(B);pe(Tt,{get icon(){return Da},size:"xs",class:"inline"});var Rt=C(Tt);$(B),k(Lt=>D(Rt,` ${Lt??""}`),[()=>Q.agentOverview_hierarchyCard_note_label()]),_(A,B)};at(ge,A=>{R()&&u()&&A(Bt)})}$(ht),_(e,ht);var Qt=de(Dt);return l(),Qt}const sn=50;var rn=F('<span class="sr-only"> </span> <!>',1);function Re(e,a){if(new.target)return oe({component:Re,...e});le(a,!0);const s=()=>$t(R,"$attentionRequest$",c),g=()=>$t(h,"$agentSession$",c),u=()=>$t(p,"$agentIsWaitingForOtherAgents$",c),[c,d]=Me();let i=st(a,"agent",7),o=st(a,"onclick",7),l=st(a,"onmouseenter",7),n=st(a,"onmouseleave",7);const p=We(i().agentId),R=ia(i().agentId),h=oa(i().agentId),v=y(()=>{const x={attentionKind:s()?.kind??null};return g()?na(g(),x):sa({status:i().status,isResponding:i().status==="responding",isWaitingForOtherAgents:u()},{...x,isCompleted:i().status==="completed",isFailed:i().status==="failed"})});var b={get agent(){return i()},set agent(x){i(x),rt()},get onclick(){return o()},set onclick(x){o(x),rt()},get onmouseenter(){return l()},set onmouseenter(x){l(x),rt()},get onmouseleave(){return n()},set onmouseleave(x){n(x),rt()},$set:ie,$on:(x,it)=>ce(a,x,it)};Ut(e,{variant:"ghost",type:"button",class:"background-agent-card relative flex flex-col items-center justify-center gap-1 rounded-full bg-sidebar hover:bg-muted/70 transition-colors cursor-pointer p-2",get style(){return`width: 50px; min-height: 50px; anchor-name: --agent-hierarchy-${i().agentId??""};`},get onclick(){return o()},get onmouseenter(){return l()},get onmouseleave(){return n()},children:(x,it)=>{var E=rn(),I=Yt(E),P=K(I,!0),ct=C(I,2);aa(ct,{get agentId(){return i().agentId},size:32,get state(){return t(v)},get specialist(){return i().specialist}}),k(()=>D(P,i().name)),_(x,E)},$$slots:{default:!0}});var S=de(b);return d(),S}var re=he('<path fill="none"></path>'),on=F('<div class="batch-group-box relative z-10 bg-background border border-border rounded-xl"></div>'),cn=F('<svg class="connector-svg" style="overflow: visible; display: block;"><!><!></svg> <div class="children-items-row flex items-start justify-center"></div>',1),ln=F('<div class="children-wrapper flex flex-col items-center"></div>'),dn=F('<div class="agent-tree-node flex flex-col items-center"><div class="agent-card-wrapper relative z-10"><!></div> <!></div>'),gn=F('<div class="absolute inset-0 flex items-center justify-center"><div class="text-center text-subtle"><p class="text-lg font-medium"> </p> <p class="text-sm mt-1"> </p></div></div>'),un=F('<div class="utility-corral border border-dashed border-border rounded-lg p-3 min-w-20"><div class="corral-label text-xs text-subtle font-medium mb-2 text-center"> </div> <div class="corral-agents flex flex-col items-center gap-2"></div></div>'),fn=F('<div class="utility-corrals flex flex-col gap-4"></div>'),pn=F('<div class="text-xs text-subtle capitalize"> </div>'),vn=F('<span class="px-1.5 py-0.5 text-ui font-medium bg-muted text-subtle rounded"> </span>'),hn=F('<span class="text-warning-ink"> </span>'),mn=F('<span class="text-primary-ink"> </span>'),_n=F('<span class="text-green-500"> </span>'),yn=F('<span class="text-red-500"> </span>'),In=F("<span> </span>"),xn=F('<div class="text-xs text-subtle line-clamp-3 border-t border-border pt-2 mt-2"> </div>'),wn=F('<div class="text-xs text-subtle flex items-center gap-1"><!> <span> </span></div>'),bn=F('<div class="p-3 space-y-2"><div class="flex items-center gap-2"><!> <div class="flex-1 min-w-0"><div class="font-medium text-sm truncate"> </div> <!></div> <!></div> <div class="text-xs text-subtle"><!></div> <div class="text-xs text-subtle"> </div> <!> <!></div>'),An=he('<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="5" y1="12" x2="19" y2="12"></line></svg>'),kn=he('<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>'),$n=he('<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"></path></svg>'),Tn=F('<div class="canvas-content absolute inset-0 flex items-center justify-center p-8 svelte-13q5gm4"><div class="hierarchy-wrapper flex items-start gap-8"><!> <div class="main-hierarchy flex flex-col items-center gap-4"><div class="hierarchy-container flex flex-col items-center gap-4"><div class="roots-row flex justify-center"></div></div></div></div> <!></div> <div class="zoom-controls absolute bottom-4 right-4 flex items-center gap-1 bg-card border border-border rounded-lg shadow-sm p-1"><!> <!> <!> <div class="w-px h-6 bg-border mx-1"></div> <!></div> <div class="absolute bottom-4 left-4 text-xs text-subtle"> </div>',1),Cn=F('<div class="agent-hierarchy-graph relative w-full h-full overflow-hidden bg-background svelte-13q5gm4"><!></div>');function la(e,a){if(new.target)return oe({component:la,...e});le(a,!0);const s=(r,f=wa,M)=>{const W=y(()=>f().agent.isBackground),m=y(()=>f().children.length>0),H=y(()=>t(m)&&f().children[0]?.agent.isBackground?sn:Xa),nt=y(()=>16),N=y(()=>60),G=y(()=>t(m)?Rt(f().children,t(H),i):[]),z=y(()=>(()=>{const O=[];for(let q=0;q<t(G).length;q+=Tt)O.push(t(G).slice(q,q+Tt));return O})()),It=y(()=>t(z).map(O=>O.reduce((q,J)=>q+J.width,0)+Math.max(0,O.length-1)*i)),ot=y(()=>Math.max(...t(It),0));var Y=dn(),Z=L(Y),pt=L(Z);{var Et=O=>{Re(O,{get agent(){return f().agent},onclick:q=>te(f().agent,q),onmouseenter:()=>x(f().agent.agentId),onmouseleave:it})},we=O=>{ca(O,{get agent(){return f().agent},get activeFile(){return f().activeFile},get activeNote(){return f().activeNote},get agentNames(){return t(Lt)},onclick:q=>te(f().agent,q),onmouseenter:()=>x(f().agent.agentId),onmouseleave:it})};at(pt,O=>{t(W)?O(Et):O(we,-1)})}$(Z);var be=C(Z,2);{var U=O=>{const q=y(()=>f().agent.status==="waiting"?f().agent.waitingForAgentIds||[]:[]),J=y(()=>t(q).length>0),et=y(()=>t(N)/2);var xt=ln();jt(xt,21,()=>t(z),Ne,(Ht,At,Ct)=>{const Pt=y(()=>t(It)[Ct]),ee=y(()=>(t(ot)-t(Pt))/2),Ae=y(()=>(()=>{let ut=0;return t(At).map(j=>{const St=ut+j.width/2;return ut+=j.width+i,St})})());var ue=cn(),Gt=Yt(ue);gt(Gt,"height",t(N));var qt=L(Gt);{var ke=ut=>{var j=re();k(()=>{gt(j,"d",`M ${t(ot)/2} -${Ya} L ${t(ot)/2} ${t(N)/3}`),gt(j,"stroke",t(J)?"var(--primary-ink)":"currentColor"),Xt(j,0,se(t(J)?"":"text-border")),gt(j,"stroke-width",t(J)?2:1)}),_(ut,j)},$e=ut=>{var j=re();k(()=>{gt(j,"d",`M ${t(ot)/2} 0 L ${t(ot)/2} ${t(N)/3}`),gt(j,"stroke",t(J)?"var(--primary-ink)":"currentColor"),Xt(j,0,se(t(J)?"":"text-border")),gt(j,"stroke-width",t(J)?2:1)}),_(ut,j)};at(qt,ut=>{Ct>0?ut(ke):ut($e,-1)})}var Te=C(qt);jt(Te,17,()=>t(At),Ne,(ut,j,St)=>{const vt=y(()=>t(ee)+t(Ae)[St]),lt=y(()=>t(ot)/2),zt=y(()=>t(j).type==="batch"?t(j).children.some(wt=>t(q).includes(wt.agent.agentId)):t(q).includes(t(j).child.agent.agentId)),mt=y(()=>t(zt)?"var(--color-primary)":"currentColor"),kt=y(()=>t(zt)?"":"text-border"),w=y(()=>t(zt)?2:1),T=y(()=>t(j).type==="batch"?t(N)-A:t(N)),tt=y(()=>Math.abs(t(vt)-t(lt))),X=y(()=>Math.min(t(nt),t(tt)/2));var fe=Be(),Ce=Yt(fe);{var va=wt=>{var dt=re();k(()=>{gt(dt,"d",`M ${t(lt)??""} ${t(N)/3} L ${t(lt)??""} ${t(T)??""}`),gt(dt,"stroke",t(mt)),Xt(dt,0,se(t(kt)),"svelte-13q5gm4"),gt(dt,"stroke-width",t(w))}),_(wt,dt)},ha=wt=>{var dt=re();k(()=>{gt(dt,"d",`M ${t(lt)??""} ${t(N)/3}
1
+ import{t as oe,bo as st,bm as Z,bw as ie,bs as $t,bq as Me,b as ce}from"./AeC4KVgG.js";import{bs as le,a5 as L,bS as C,ay as Yt,aD as t,bA as $,bl as K,b_ as k,bO as D,W as _,bn as de,c9 as y,aA as rt,aB as O,bV as Mt,br as _a,aw as De,aj as Ne,bH as V,ai as ya,be as Ia,b$ as xa,bf as wa,aC as me,a7 as Be}from"./CJxGDkBm.js";import{i as at}from"./k2awEenT.js";import{I as ea,g as jt,i as Se}from"./CswzK9Go.js";import{f as Xt,g as ne,s as gt,c as se}from"./DrHJ7oPv.js";import{b as ba}from"./NtFyWdpR.js";import{f as Ut}from"./DJM6amHV.js";import"./jhNNYE0v.js";import{A as aa,b as na,a as sa}from"./CvCk2zex.js";import"./Dp2nUoTL.js";import{aw as ra,aN as oa,ay as Aa,az as ka,aA as We,ar as ia,b as $a,w as Ta,dI as Ca,aZ as Na,aB as Sa}from"./-5BGDZDk.js";import{R as Fa}from"./BbV7MtxC.js";import{F as pe,bA as Oa,bf as Ra,aB as Ma,aV as Wa,cD as Da}from"./Ci7mS1ie.js";import{H as Ba}from"./CCnGCUBh.js";import{A as La}from"./gJtrDJPm.js";import{L as Ea}from"./DC2f25QV.js";import{f as Pa}from"./DuU6k7P3.js";import{e as St,IX as Oe,nL as Ga,fM as za,c1 as ja,sm as Ka,uJ as Ha}from"./BkzMrEqG.js";import"./Bd1FsnP3.js";function qa(e){return e.type==="agent"}const Xa=180,Ya=180;var Le=O('<div class="activity-pill shrink-0 text-xs px-3 py-1.5 bg-muted/60 border border-border rounded-lg text-subtle max-w-32 truncate"><!> </div>'),Ua=O('<div class="text-ui text-subtle line-clamp-2 leading-tight px-1"> </div>'),Va=O('<div><div class="flex items-center justify-center gap-1"><!> <span class="truncate"> </span></div> <!> <!></div>'),Za=O('<div class="text-sm text-primary-ink flex items-center justify-center gap-1"><!> <span class="truncate"> </span></div>'),Fe=O('<span class="text-xs text-subtle"> </span>'),Qa=O('<span class="status-pill text-xs px-1.5 py-0.5 bg-muted/80 rounded-md text-subtle truncate max-w-[130px]"> </span>'),Ja=O('<div class="text-ui text-subtle truncate w-full px-1 leading-tight"> </div>'),tn=O('<div class="flex flex-col items-center gap-1"><div class="flex items-center justify-center gap-1.5"><!> <!></div> <!></div>'),en=O('<div class="text-sm text-subtle line-clamp-3 leading-tight"> </div>'),an=O('<div class="avatar-wrapper h-9 w-12 flex items-center justify-center bg-background rounded-full"><!></div> <span class="font-semibold text-center leading-tight line-clamp-2"> </span> <div class="status-footer mt-auto pt-2 w-full text-center"><!></div>',1),nn=O('<div class="agent-card-wrapper flex items-center gap-3 shadow"><!> <!> <!></div>');function ca(e,a){if(new.target)return oe({component:ca,...e});le(a,!0);const s=()=>$t(_t,"$attentionRequest$",o),g=()=>$t(it,"$agentSession$",o),u=()=>$t(x,"$agentIsResponding$",o),c=()=>$t(ct,"$agentIsWaitingForOtherAgents$",o),d=()=>$t(P,"$agentIsWaiting$",o),i=()=>$t(I,"$agentIsThinking$",o),[o,l]=Me();let n=st(a,"agent",7),p=st(a,"activeFile",7),R=st(a,"activeNote",7),m=st(a,"agentNames",7),v=st(a,"onclick",7),b=st(a,"onmouseenter",7),N=st(a,"onmouseleave",7);const x=ra(n().agentId),it=oa(n().agentId),E=y(()=>!n().waitingForAgentIds||n().waitingForAgentIds.length===0?[]:n().waitingForAgentIds.map(A=>m()?.get(A)||Z.agentOverview_hierarchyCard_agent_fallback()).slice(0,2)),I=Aa(n().agentId),P=ka(n().agentId),ct=We(n().agentId),_t=ia(n().agentId),Ft=y(()=>{const A={attentionKind:s()?.kind??null};return g()?na(g(),A):sa({status:n().status,isResponding:u(),isWaitingForOtherAgents:c()},{...A,isCompleted:n().status==="completed",isFailed:n().status==="failed"})});var Dt={get agent(){return n()},set agent(A){n(A),rt()},get activeFile(){return p()},set activeFile(A){p(A),rt()},get activeNote(){return R()},set activeNote(A){R(A),rt()},get agentNames(){return m()},set agentNames(A){m(A),rt()},get onclick(){return v()},set onclick(A){v(A),rt()},get onmouseenter(){return b()},set onmouseenter(A){b(A),rt()},get onmouseleave(){return N()},set onmouseleave(A){N(A),rt()},$set:ie,$on:(A,B)=>ce(a,A,B)},mt=nn(),bt=L(mt);{var Kt=A=>{var B=Le(),Tt=L(B);pe(Tt,{get icon(){return Ra},size:"xs",class:"inline"});var Rt=C(Tt);$(B),k(()=>D(Rt,` ${p()??""}`)),_(A,B)};at(bt,A=>{p()&&u()&&A(Kt)})}var Ot=C(bt,2);{let A=y(()=>d()?"border-primary-ink border-2":"");Ut(Ot,{variant:"ghost",type:"button",get class(){return`agent-card flex flex-col items-center px-2.5 py-4 bg-card border border-border
2
+ hover:shadow transition-all cursor-pointer ${t(A)??""}`},get style(){return`width: 180px; height: 180px; anchor-name: --agent-hierarchy-${n().agentId??""};`},get onclick(){return v()},get onmouseenter(){return b()},get onmouseleave(){return N()},children:(B,Tt)=>{var Rt=an(),Lt=Yt(Rt),he=L(Lt);aa(he,{get agentId(){return n().agentId},variant:"emphasized",get state(){return t(Ft)},get specialist(){return n().specialist}}),$(Lt);var Qt=C(Lt,2),_e=K(Qt,!0),Jt=C(Qt,2),te=L(Jt);{var ye=ft=>{var r=Va(),f=L(r),M=L(f);{let z=y(()=>s().kind==="blocker"?Ma:Wa);pe(M,{get icon(){return t(z)},size:"xs"})}var W=C(M,2),h=K(W,!0);$(f);var H=C(f,2);{var nt=z=>{var It=Ua(),ot=K(It,!0);k(()=>D(ot,s().reason)),_(z,It)};at(H,z=>{s().reason&&z(nt)})}var S=C(H,2);{var G=z=>{Fa(z,{get date(){return s().timestamp},class:"text-ui text-ghost"})};at(S,z=>{s().timestamp&&z(G)})}$(r),k(z=>{Xt(r,1,`text-sm flex flex-col items-center gap-0.5 ${s().kind==="blocker"?"text-red-500":"text-warning-ink"}`),D(h,z)},[()=>s().kind==="blocker"?Z.chat_agentCard_attentionBlocker_label():Z.chat_agentCard_attentionDiscussion_label()]),_(ft,r)},yt=ft=>{var r=Za(),f=L(r);pe(f,{get icon(){return Oa},size:"xs",class:"animate-pulse"});var M=C(f,2),W=K(M,!0);$(r),k(h=>D(W,h),[()=>Z.agentOverview_hierarchyCard_waitingFor_label({names:t(E).join(", ")})]),_(ft,r)},Ie=ft=>{const r=y(()=>n().activeToolName?$a(n().activeToolName,n().activeToolInput||{}):null),f=y(()=>t(r)&&!t(r).hidden?t(r):null);var M=tn(),W=L(M),h=L(W);ea(h,{size:14});var H=C(h,2);{var nt=Y=>{var Q=Fe(),pt=K(Q,!0);k(Et=>D(pt,Et),[()=>Z.agentOverview_hierarchyCard_thinking_label()]),_(Y,Q)},S=Y=>{var Q=Qa(),pt=K(Q);k(()=>D(pt,`${t(f).verb??""}
3
+ ${t(f).subject??""}`)),_(Y,Q)},G=Y=>{var Q=Fe(),pt=K(Q);k(()=>D(pt,`${t(f).verb??""}...`)),_(Y,Q)},z=Y=>{var Q=Fe(),pt=K(Q,!0);k(Et=>D(pt,Et),[()=>Z.agentOverview_hierarchyCard_responding_label()]),_(Y,Q)};at(H,Y=>{i()?Y(nt):t(f)&&t(f).subject?Y(S,1):t(f)?Y(G,2):Y(z,-1)})}$(W);var It=C(W,2);{var ot=Y=>{var Q=Ja(),pt=K(Q,!0);k(()=>D(pt,n().lastResponse)),_(Y,Q)};at(It,Y=>{!t(f)&&n().lastResponse&&Y(ot)})}$(M),_(ft,M)},xe=ft=>{var r=en(),f=K(r,!0);k(()=>D(f,n().lastResponse)),_(ft,r)};at(te,ft=>{s()?ft(ye):c()?ft(yt,1):u()||i()?ft(Ie,2):n().lastResponse&&ft(xe,3)})}$(Jt),k(()=>D(_e,n().name)),_(B,Rt)},$$slots:{default:!0}})}var ge=C(Ot,2);{var Bt=A=>{var B=Le(),Tt=L(B);pe(Tt,{get icon(){return Da},size:"xs",class:"inline"});var Rt=C(Tt);$(B),k(Lt=>D(Rt,` ${Lt??""}`),[()=>Z.agentOverview_hierarchyCard_note_label()]),_(A,B)};at(ge,A=>{R()&&u()&&A(Bt)})}$(mt),_(e,mt);var Zt=de(Dt);return l(),Zt}const sn=50;var rn=O('<span class="sr-only"> </span> <!>',1);function Re(e,a){if(new.target)return oe({component:Re,...e});le(a,!0);const s=()=>$t(R,"$attentionRequest$",c),g=()=>$t(m,"$agentSession$",c),u=()=>$t(p,"$agentIsWaitingForOtherAgents$",c),[c,d]=Me();let i=st(a,"agent",7),o=st(a,"onclick",7),l=st(a,"onmouseenter",7),n=st(a,"onmouseleave",7);const p=We(i().agentId),R=ia(i().agentId),m=oa(i().agentId),v=y(()=>{const x={attentionKind:s()?.kind??null};return g()?na(g(),x):sa({status:i().status,isResponding:i().status==="responding",isWaitingForOtherAgents:u()},{...x,isCompleted:i().status==="completed",isFailed:i().status==="failed"})});var b={get agent(){return i()},set agent(x){i(x),rt()},get onclick(){return o()},set onclick(x){o(x),rt()},get onmouseenter(){return l()},set onmouseenter(x){l(x),rt()},get onmouseleave(){return n()},set onmouseleave(x){n(x),rt()},$set:ie,$on:(x,it)=>ce(a,x,it)};Ut(e,{variant:"ghost",type:"button",class:"background-agent-card relative flex flex-col items-center justify-center gap-1 rounded-full bg-sidebar hover:bg-muted/70 transition-colors cursor-pointer p-2",get style(){return`width: 50px; min-height: 50px; anchor-name: --agent-hierarchy-${i().agentId??""};`},get onclick(){return o()},get onmouseenter(){return l()},get onmouseleave(){return n()},children:(x,it)=>{var E=rn(),I=Yt(E),P=K(I,!0),ct=C(I,2);aa(ct,{get agentId(){return i().agentId},size:32,get state(){return t(v)},get specialist(){return i().specialist}}),k(()=>D(P,i().name)),_(x,E)},$$slots:{default:!0}});var N=de(b);return d(),N}var re=me('<path fill="none"></path>'),on=O('<div class="batch-group-box relative z-10 bg-background border border-border rounded-xl"></div>'),cn=O('<svg class="connector-svg" style="overflow: visible; display: block;"><!><!></svg> <div class="children-items-row flex items-start justify-center"></div>',1),ln=O('<div class="children-wrapper flex flex-col items-center"></div>'),dn=O('<div class="agent-tree-node flex flex-col items-center"><div class="agent-card-wrapper relative z-10"><!></div> <!></div>'),gn=O('<div class="absolute inset-0 flex items-center justify-center"><div class="text-center text-subtle"><p class="text-lg font-medium"> </p> <p class="text-sm mt-1"> </p></div></div>'),un=O('<div class="utility-corral border border-dashed border-border rounded-lg p-3 min-w-20"><div class="corral-label text-xs text-subtle font-medium mb-2 text-center"> </div> <div class="corral-agents flex flex-col items-center gap-2"></div></div>'),fn=O('<div class="utility-corrals flex flex-col gap-4"></div>'),pn=O('<div class="text-xs text-subtle capitalize"> </div>'),vn=O('<span class="px-1.5 py-0.5 text-ui font-medium bg-muted text-subtle rounded"> </span>'),mn=O('<span class="text-warning-ink"> </span>'),hn=O('<span class="text-primary-ink"> </span>'),_n=O('<span class="text-green-500"> </span>'),yn=O('<span class="text-red-500"> </span>'),In=O("<span> </span>"),xn=O('<div class="text-xs text-subtle line-clamp-3 border-t border-border pt-2 mt-2"> </div>'),wn=O('<div class="text-xs text-subtle flex items-center gap-1"><!> <span> </span></div>'),bn=O('<div class="p-3 space-y-2"><div class="flex items-center gap-2"><!> <div class="flex-1 min-w-0"><div class="font-medium text-sm truncate"> </div> <!></div> <!></div> <div class="text-xs text-subtle"><!></div> <div class="text-xs text-subtle"> </div> <!> <!></div>'),An=me('<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="5" y1="12" x2="19" y2="12"></line></svg>'),kn=me('<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>'),$n=me('<svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"></path></svg>'),Tn=O('<div class="canvas-content absolute inset-0 flex items-center justify-center p-8 svelte-13q5gm4"><div class="hierarchy-wrapper flex items-start gap-8"><!> <div class="main-hierarchy flex flex-col items-center gap-4"><div class="hierarchy-container flex flex-col items-center gap-4"><div class="roots-row flex justify-center"></div></div></div></div> <!></div> <div class="zoom-controls absolute bottom-4 right-4 flex items-center gap-1 bg-card border border-border rounded-lg shadow-sm p-1"><!> <!> <!> <div class="w-px h-6 bg-border mx-1"></div> <!></div> <div class="absolute bottom-4 left-4 text-xs text-subtle"> </div>',1),Cn=O('<div class="agent-hierarchy-graph relative w-full h-full overflow-hidden bg-background svelte-13q5gm4"><!></div>');function la(e,a){if(new.target)return oe({component:la,...e});le(a,!0);const s=(r,f=wa,M)=>{const W=y(()=>f().agent.isBackground),h=y(()=>f().children.length>0),H=y(()=>t(h)&&f().children[0]?.agent.isBackground?sn:Xa),nt=y(()=>16),S=y(()=>60),G=y(()=>t(h)?Rt(f().children,t(H),i):[]),z=y(()=>(()=>{const F=[];for(let q=0;q<t(G).length;q+=Tt)F.push(t(G).slice(q,q+Tt));return F})()),It=y(()=>t(z).map(F=>F.reduce((q,J)=>q+J.width,0)+Math.max(0,F.length-1)*i)),ot=y(()=>Math.max(...t(It),0));var Y=dn(),Q=L(Y),pt=L(Q);{var Et=F=>{Re(F,{get agent(){return f().agent},onclick:q=>te(f().agent,q),onmouseenter:()=>x(f().agent.agentId),onmouseleave:it})},we=F=>{ca(F,{get agent(){return f().agent},get activeFile(){return f().activeFile},get activeNote(){return f().activeNote},get agentNames(){return t(Lt)},onclick:q=>te(f().agent,q),onmouseenter:()=>x(f().agent.agentId),onmouseleave:it})};at(pt,F=>{t(W)?F(Et):F(we,-1)})}$(Q);var be=C(Q,2);{var U=F=>{const q=y(()=>f().agent.status==="waiting"?f().agent.waitingForAgentIds||[]:[]),J=y(()=>t(q).length>0),et=y(()=>t(S)/2);var xt=ln();jt(xt,21,()=>t(z),Se,(Ht,At,Ct)=>{const Pt=y(()=>t(It)[Ct]),ee=y(()=>(t(ot)-t(Pt))/2),Ae=y(()=>(()=>{let ut=0;return t(At).map(j=>{const Nt=ut+j.width/2;return ut+=j.width+i,Nt})})());var ue=cn(),Gt=Yt(ue);gt(Gt,"height",t(S));var qt=L(Gt);{var ke=ut=>{var j=re();k(()=>{gt(j,"d",`M ${t(ot)/2} -${Ya} L ${t(ot)/2} ${t(S)/3}`),gt(j,"stroke",t(J)?"var(--primary-ink)":"currentColor"),Xt(j,0,se(t(J)?"":"text-border")),gt(j,"stroke-width",t(J)?2:1)}),_(ut,j)},$e=ut=>{var j=re();k(()=>{gt(j,"d",`M ${t(ot)/2} 0 L ${t(ot)/2} ${t(S)/3}`),gt(j,"stroke",t(J)?"var(--primary-ink)":"currentColor"),Xt(j,0,se(t(J)?"":"text-border")),gt(j,"stroke-width",t(J)?2:1)}),_(ut,j)};at(qt,ut=>{Ct>0?ut(ke):ut($e,-1)})}var Te=C(qt);jt(Te,17,()=>t(At),Se,(ut,j,Nt)=>{const vt=y(()=>t(ee)+t(Ae)[Nt]),lt=y(()=>t(ot)/2),zt=y(()=>t(j).type==="batch"?t(j).children.some(wt=>t(q).includes(wt.agent.agentId)):t(q).includes(t(j).child.agent.agentId)),ht=y(()=>t(zt)?"var(--color-primary)":"currentColor"),kt=y(()=>t(zt)?"":"text-border"),w=y(()=>t(zt)?2:1),T=y(()=>t(j).type==="batch"?t(S)-A:t(S)),tt=y(()=>Math.abs(t(vt)-t(lt))),X=y(()=>Math.min(t(nt),t(tt)/2));var fe=Be(),Ce=Yt(fe);{var va=wt=>{var dt=re();k(()=>{gt(dt,"d",`M ${t(lt)??""} ${t(S)/3} L ${t(lt)??""} ${t(T)??""}`),gt(dt,"stroke",t(ht)),Xt(dt,0,se(t(kt)),"svelte-13q5gm4"),gt(dt,"stroke-width",t(w))}),_(wt,dt)},ma=wt=>{var dt=re();k(()=>{gt(dt,"d",`M ${t(lt)??""} ${t(S)/3}
4
4
  L ${t(lt)??""} ${t(et)-t(X)}
5
5
  Q ${t(lt)??""} ${t(et)??""}, ${t(lt)-t(X)} ${t(et)??""}
6
6
  L ${t(vt)+t(X)} ${t(et)??""}
7
7
  Q ${t(vt)??""} ${t(et)??""}, ${t(vt)??""} ${t(et)+t(X)}
8
- L ${t(vt)??""} ${t(T)??""}`),gt(dt,"stroke",t(mt)),Xt(dt,0,se(t(kt)),"svelte-13q5gm4"),gt(dt,"stroke-width",t(w))}),_(wt,dt)},ma=wt=>{var dt=re();k(()=>{gt(dt,"d",`M ${t(lt)??""} ${t(N)/3}
8
+ L ${t(vt)??""} ${t(T)??""}`),gt(dt,"stroke",t(ht)),Xt(dt,0,se(t(kt)),"svelte-13q5gm4"),gt(dt,"stroke-width",t(w))}),_(wt,dt)},ha=wt=>{var dt=re();k(()=>{gt(dt,"d",`M ${t(lt)??""} ${t(S)/3}
9
9
  L ${t(lt)??""} ${t(et)-t(X)}
10
10
  Q ${t(lt)??""} ${t(et)??""}, ${t(lt)+t(X)} ${t(et)??""}
11
11
  L ${t(vt)-t(X)} ${t(et)??""}
12
12
  Q ${t(vt)??""} ${t(et)??""}, ${t(vt)??""} ${t(et)+t(X)}
13
- L ${t(vt)??""} ${t(T)??""}`),gt(dt,"stroke",t(mt)),Xt(dt,0,se(t(kt)),"svelte-13q5gm4"),gt(dt,"stroke-width",t(w))}),_(wt,dt)};at(Ce,wt=>{t(tt)<1?wt(va):t(vt)<t(lt)?wt(ha,1):wt(ma,-1)})}_(ut,fe)}),$(Gt);var ae=C(Gt,2);jt(ae,21,()=>t(At),Ne,(ut,j)=>{var St=Be(),vt=Yt(St);{var lt=mt=>{var kt=on();jt(kt,21,()=>t(j).children,w=>w.agent.agentId,(w,T)=>{s(w,()=>t(T))}),$(kt),k(()=>ne(kt,`padding: 10px; margin-top: -10px; display: grid; grid-template-columns: repeat(${t(j).cols??""}, auto); gap: 12px;`)),_(mt,kt)},zt=mt=>{s(mt,()=>t(j).child)};at(vt,mt=>{t(j).type==="batch"?mt(lt):mt(zt,-1)})}_(ut,St)}),$(ae),k(()=>{gt(Gt,"width",t(ot)),ne(ae,`gap: 12px; width: ${t(ot)??""}px;`)}),_(Ht,ue)}),$(xt),k(()=>ne(xt,`width: ${t(ot)??""}px;`)),_(O,xt)};at(be,O=>{t(m)&&O(U)})}$(Y),_(r,Y)};let g=st(a,"agents",7),u=st(a,"edges",7),c=st(a,"onAgentClick",7),d=st(a,"onFocus",7);const i=12,o=[{id:"git",label:"Git",types:["commit-message","pr-description"]},{id:"review",label:Q.agentOverview_hierarchyGraph_reviewCorral_label(),types:["code-review","code-walkthrough"]}];let l=Mt(1),n=Mt(0),p=Mt(0),R=Mt(!1),h=Mt(_a({x:0,y:0})),v=Mt(null),b=Mt(null),S=Mt(null);function x(r){t(S)&&clearTimeout(t(S)),V(b,r,!0)}function it(){t(S)&&(clearTimeout(t(S)),V(S,null)),V(b,null)}const E=y(()=>t(b)?g().find(r=>r.agentId===t(b)):null),I=.25,P=2,ct=.1;function _t(r){if(r.preventDefault(),r.ctrlKey||r.metaKey){const f=-r.deltaY*.001,M=Math.min(P,Math.max(I,t(l)*(1+f)));if(t(v)){const W=t(v).getBoundingClientRect(),m=r.clientX-W.left,H=r.clientY-W.top,nt=M/t(l);V(n,m-(m-t(n))*nt),V(p,H-(H-t(p))*nt)}V(l,M,!0)}else V(n,t(n)-r.deltaX),V(p,t(p)-r.deltaY)}function Ot(r){const f=r.target,M=f.closest(".agent-hierarchy-graph")&&!f.closest(".agent-card")&&!f.closest(".bg-agent-card")&&!f.closest(".zoom-controls");(r.button===1||r.button===0&&(r.shiftKey||M))&&(V(R,!0),V(h,{x:r.clientX,y:r.clientY},!0),r.preventDefault()),r.button===0&&d()?.()}function Dt(r){if(!t(R))return;const f=r.clientX-t(h).x,M=r.clientY-t(h).y;V(n,t(n)+f),V(p,t(p)+M),V(h,{x:r.clientX,y:r.clientY},!0)}function ht(){V(R,!1)}function bt(){V(l,Math.min(P,t(l)+ct),!0)}function Kt(){V(l,Math.max(I,t(l)-ct),!0)}function Ft(){V(l,1),V(n,0),V(p,0)}function ge(){V(l,.8),V(n,0),V(p,0)}const Bt=y(()=>Math.round(t(l)*100)),Qt=5e3,A=10,B=4,Tt=6;function Rt(r,f,M){if(r.length===0)return[];const W=[],m=new Map;for(const N of r){const G=N.agent.delegationBatchId;G&&(m.has(G)||m.set(G,[]),m.get(G).push(N))}const H=new Set;for(const N of r){const G=N.agent.delegationBatchId;if(G)H.has(G)||(H.add(G),W.push(m.get(G)));else{const z=W[W.length-1];if(z&&!z[0].agent.delegationBatchId){const It=new Date(z[z.length-1].agent.createdAt).getTime();if(new Date(N.agent.createdAt).getTime()-It<=Qt){z.push(N);continue}}W.push([N])}}const nt=f+M;return W.map(N=>{if(N.length===1)return{type:"single",child:N[0],width:f};const G=Math.min(Math.ceil(Math.sqrt(N.length)),B),z=Math.ceil(N.length/G);return{type:"batch",children:N,cols:G,rows:z,width:G*nt-M+A*2}})}const Lt=y(()=>{const r=new Map;for(const f of g())r.set(f.agentId,f.name);return r}),me=new Set(o.flatMap(r=>[...r.types])),Zt=y(()=>{const r=[];for(const f of o){const M=new Set(f.types),W=g().filter(m=>m.agentType&&M.has(m.agentType));W.length>0&&r.push({id:f.id,label:f.label,agents:W})}return r}),_e=y(()=>g().filter(r=>!r.agentType||!me.has(r.agentType))),Jt=y(()=>{const r=new Map,f=[];for(const m of t(_e))r.set(m.agentId,{agent:m,children:[],activeFile:void 0,activeNote:void 0});const M=u().filter(m=>m.isActive);for(const m of M){const H=m.sourceId.replace("agent-",""),nt=r.get(H);nt&&(m.type==="file-read"||m.type==="file-write"?nt.activeFile=m.targetId.replace("file-","").split("/").pop():(m.type==="note-read"||m.type==="note-write")&&(nt.activeNote=m.targetId.replace("note-","")))}for(const[,m]of r){const H=m.agent.parentAgentId;H&&r.has(H)?r.get(H).children.push(m):f.push(m)}const W=(m,H)=>new Date(m.agent.createdAt).getTime()-new Date(H.agent.createdAt).getTime();for(const[,m]of r)m.children.sort(W);return f.sort(W),f});function te(r,f){c()?.(r.agentId,r.name,f)}var ye={get agents(){return g()},set agents(r){g(r),rt()},get edges(){return u()},set edges(r){u(r),rt()},get onAgentClick(){return c()},set onAgentClick(r){c(r),rt()},get onFocus(){return d()},set onFocus(r){d(r),rt()},$set:ie,$on:(r,f)=>ce(a,r,f)},yt=Cn(),Ie=L(yt);{var xe=r=>{var f=gn(),M=L(f),W=L(M),m=K(W,!0),H=C(W,2),nt=K(H,!0);$(M),$(f),k((N,G)=>{D(m,N),D(nt,G)},[()=>Q.agentOverview_hierarchyGraph_noAgents_title(),()=>Q.agentOverview_hierarchyGraph_noAgents_description()]),_(r,f)},ft=r=>{var f=Tn(),M=Yt(f),W=L(M),m=L(W);{var H=U=>{var O=fn();jt(O,21,()=>t(Zt),q=>q.id,(q,J)=>{var et=un(),xt=L(et),Ht=K(xt,!0),At=C(xt,2);jt(At,21,()=>t(J).agents,Ct=>Ct.agentId,(Ct,Pt)=>{Re(Ct,{get agent(){return t(Pt)},onclick:ee=>te(t(Pt),ee),onmouseenter:()=>x(t(Pt).agentId),onmouseleave:it})}),$(At),$(et),k(()=>D(Ht,t(J).label)),_(q,et)}),$(O),_(U,O)};at(m,U=>{t(Zt).length>0&&U(H)})}var nt=C(m,2),N=L(nt),G=L(N);ne(G,"gap: 12px;"),jt(G,21,()=>t(Jt),U=>U.agent.agentId,(U,O)=>{s(U,()=>t(O))}),$(G),$(N),$(nt),$(W);var z=C(W,2);{var It=U=>{{let O=y(()=>"--agent-hierarchy-"+t(b));Ba(U,{get anchor(){return t(O)},position:"top",absolute:!0,children:(q,J)=>{var et=bn(),xt=L(et),Ht=L(xt);La(Ht,{variant:"emphasized",get agentId(){return t(E).agentId}});var At=C(Ht,2),Ct=L(At),Pt=K(Ct,!0),ee=C(Ct,2);{var Ae=w=>{var T=pn(),tt=K(T,!0);k(X=>D(tt,X),[()=>t(E).specialist.replace("-"," ")]),_(w,T)};at(ee,w=>{t(E).specialist&&w(Ae)})}$(At);var ue=C(At,2);{var Gt=w=>{var T=vn(),tt=K(T,!0);k(X=>D(tt,X),[()=>Q.agentOverview_hierarchyGraph_background_badge()]),_(w,T)};at(ue,w=>{t(E).isBackground&&w(Gt)})}$(xt);var qt=C(xt,2),ke=L(qt);{var $e=w=>{var T=hn(),tt=K(T);k(X=>D(tt,`● ${X??""}`),[()=>Q.agentOverview_hierarchyGraph_statusWaiting_label()]),_(w,T)},Te=w=>{var T=mn(),tt=K(T);k(X=>D(tt,`● ${X??""}`),[()=>Q.agentOverview_hierarchyGraph_statusResponding_label()]),_(w,T)},ae=w=>{var T=_n(),tt=K(T);k(X=>D(tt,`● ${X??""}`),[()=>Q.agentOverview_hierarchyGraph_statusCompleted_label()]),_(w,T)},ut=w=>{var T=yn(),tt=K(T);k(X=>D(tt,`● ${X??""}`),[()=>Q.agentOverview_hierarchyGraph_statusFailed_label()]),_(w,T)},j=w=>{var T=In(),tt=K(T);k(X=>D(tt,`● ${X??""}`),[()=>Q.agentOverview_hierarchyGraph_statusIdle_label()]),_(w,T)};at(ke,w=>{t(E).status==="waiting"?w($e):t(E).status==="responding"?w(Te,1):t(E).status==="completed"?w(ae,2):t(E).status==="failed"?w(ut,3):w(j,-1)})}$(qt);var St=C(qt,2),vt=K(St,!0),lt=C(St,2);{var zt=w=>{var T=xn(),tt=K(T,!0);k(()=>D(tt,t(E).lastResponse)),_(w,T)};at(lt,w=>{t(E).lastResponse&&w(zt)})}var mt=C(lt,2);{var kt=w=>{var T=wn(),tt=L(T);ea(tt,{size:12});var X=C(tt,2),fe=K(X,!0);$(T),k(Ce=>D(fe,Ce),[()=>Q.agentOverview_hierarchyGraph_usingTool_label({tool:t(E).activeToolName})]),_(w,T)};at(mt,w=>{t(E).activeToolName&&w(kt)})}$(et),k(w=>{D(Pt,t(E).name),D(vt,w)},[()=>Q.agentOverview_hierarchyGraph_created_label({time:Ea(t(E).createdAt)})]),_(q,et)},$$slots:{default:!0}})}};at(z,U=>{t(E)&&U(It)})}$(M);var ot=C(M,2),Y=L(ot);{let U=y(()=>Q.agentOverview_hierarchyGraph_zoomOut_tooltip());Ut(Y,{variant:"ghost",size:"icon",iconOnly:!0,type:"button",class:"zoom-btn hover:bg-muted transition-colors text-muted-foreground hover:text-foreground",onclick:Kt,get title(){return t(U)},children:(O,q)=>{var J=An();_(O,J)},$$slots:{default:!0}})}var Z=C(Y,2);{let U=y(()=>Q.agentOverview_hierarchyGraph_resetZoom_tooltip());Ut(Z,{variant:"ghost",type:"button",class:"zoom-percent w-12 h-8 flex items-center justify-center text-xs font-medium text-muted-foreground hover:text-foreground hover:bg-muted rounded transition-colors",onclick:Ft,get title(){return t(U)},children:(O,q)=>{Ia();var J=xa();k(()=>D(J,`${t(Bt)??""}%`)),_(O,J)},$$slots:{default:!0}})}var pt=C(Z,2);{let U=y(()=>Q.agentOverview_hierarchyGraph_zoomIn_tooltip());Ut(pt,{variant:"ghost",size:"icon",iconOnly:!0,type:"button",class:"zoom-btn hover:bg-muted transition-colors text-muted-foreground hover:text-foreground",onclick:bt,get title(){return t(U)},children:(O,q)=>{var J=kn();_(O,J)},$$slots:{default:!0}})}var Et=C(pt,4);{let U=y(()=>Q.agentOverview_hierarchyGraph_fitToView_tooltip());Ut(Et,{variant:"ghost",size:"icon",iconOnly:!0,type:"button",class:"zoom-btn hover:bg-muted transition-colors text-muted-foreground hover:text-foreground",onclick:ge,get title(){return t(U)},children:(O,q)=>{var J=$n();_(O,J)},$$slots:{default:!0}})}$(ot);var we=C(ot,2),be=K(we,!0);k(U=>{ne(M,`transform: translate(${t(n)??""}px, ${t(p)??""}px) scale(${t(l)??""}); transform-origin: center center;`),D(be,U)},[()=>Q.agentOverview_hierarchyGraph_panHint_label()]),_(r,f)};at(Ie,r=>{t(Jt).length===0?r(xe):r(ft,-1)})}return $(yt),ba(yt,r=>V(v,r),()=>t(v)),De("wheel",yt,_t),Se("mousedown",yt,Ot),Se("mousemove",yt,Dt),Se("mouseup",yt,ht),De("mouseleave",yt,ht),_(e,yt),de(ye)}ya(["mousedown","mousemove","mouseup"]);const Ee=new Set(["str-replace-editor","save-file","remove-files","str_replace_editor"]),Pe=new Set(["create_note","update_note","set_note_content","add_to_note","append_to_note","edit_note","edit_note_lines","update_note_metadata","read_note","view_note","delete_note"]),Sn=new Set(["read_note","view_note","list_note_tasks"]),Ge=new Set(["add_tasks","update_tasks","view_tasklist","reorganize_tasklist"]),Nn=new Set(["view_tasklist"]),ze=new Set(["delegate_task","create_sub_agent","create_agent"]),On=5e3;function Fn(e,a=!1){if(!e)return"idle";if(e.status===Nt.Completed)return"completed";if(e.status===Nt.Error||e.status===Nt.Deleted)return"failed";if(a||da(e))return"responding";if(ga(e.status))return"idle";if(e.messages&&e.messages.length>0){const s=[...e.messages].reverse().find(g=>g.role==="assistant");if(s&&(s.isStreaming||s.streamingComplete===!1))return"responding"}switch(e.status){case Nt.Active:return"idle";case Nt.Pending:case Nt.Idle:return"idle";case Nt.Processing:return a?"responding":"idle";case Nt.Waiting:return"waiting";default:return"idle"}}function da(e){return!!(e.isProcessing||e.isStreaming||e.isResponding)}function ga(e){return e===Nt.Idle||e==="idle"}function Rn(e){const a={};if(!e)return a;if(e.lastAgentResponse){const s=Ta(e.lastAgentResponse);s&&(a.lastResponse=s)}return ga(e.status)&&!da(e)||e.isStreaming&&e.lastToolUse?.name&&(a.activeToolName=e.lastToolUse.name,a.activeToolInput=e.lastToolUse.input||{}),a}function Wt(e){return(e.name||e.toolName||"").toLowerCase()}function Vt(e){return"input"in e&&e.input?e.input:"arguments"in e&&e.arguments?e.arguments:"parameters"in e&&e.parameters?e.parameters:{}}function Mn(e){const a=e.toLowerCase();if(Ee.has(e))return!0;for(const s of Ee)if(a.startsWith(s.toLowerCase()))return!0;return!!(a.startsWith("edit ")||a.startsWith("save ")||a.startsWith("create "))}function ua(e){const a=e.toLowerCase();return!!(a.startsWith("read `")&&!a.includes("read `.`")||a.startsWith("view")||a==="view")}function je(e){if(Pe.has(e))return!0;for(const a of Pe)if(e.startsWith(a))return!0;return!1}function Wn(e){return e==="save-file"?"create":e==="remove-files"?"delete":"modify"}function Ke(e){return e==="create_note"?"create":Sn.has(e)?"read":"write"}function He(e){if(Ge.has(e))return!0;for(const a of Ge)if(e.startsWith(a))return!0;return!1}function qe(e){return e==="add_tasks"?"create":Nn.has(e)?"read":"update"}function fa(e){if(e==="."||e==="./"||e.endsWith("/"))return!0;const s=(e.split("/").pop()||e).lastIndexOf(".");return s===-1||s===0}function Dn(e){const a=e.match(/`([^`]+)`/);if(a&&a[1]){const s=a[1];return fa(s)?null:s}return null}function Xe(e,a){const s=e.path||e.file_path||e.filePath;return typeof s=="string"?fa(s)?null:s:a?Dn(a):null}function Ye(e){const a=e.noteId||e.note_id||e.title;return typeof a=="string"?a:null}function Ue(e){return Mn(e)||ua(e)}function Ve(e){return ua(e)?"read":Wn(e)}function Bn(e,a){const s=[],g=new Set;for(const u of e){const c=u.timestamp?.toString()||a;if(u.toolCalls&&Array.isArray(u.toolCalls))for(const d of u.toolCalls){const i=Wt(d);if(!Ue(i))continue;const o=Vt(d),l=Xe(o,d.name||d.toolName);!l||g.has(l)||(g.add(l),s.push({path:l,type:Ve(i),timestamp:c}))}if(u.contentBlocks&&Array.isArray(u.contentBlocks))for(const d of u.contentBlocks){if(d.type!=="tool_use")continue;const i=Wt(d);if(!Ue(i))continue;const o=Vt(d),l=Xe(o,d.name);!l||g.has(l)||(g.add(l),s.push({path:l,type:Ve(i),timestamp:c}))}}return s}function Ln(e,a){const s=[],g=new Set;for(const u of e){const c=u.timestamp?.toString()||a;if(u.toolCalls&&Array.isArray(u.toolCalls))for(const d of u.toolCalls){const i=Wt(d);if(!je(i))continue;const o=Vt(d),l=Ye(o);!l||g.has(l)||(g.add(l),s.push({noteId:l,title:o.title||l,action:Ke(i),timestamp:c}))}if(u.contentBlocks&&Array.isArray(u.contentBlocks))for(const d of u.contentBlocks){if(d.type!=="tool_use")continue;const i=Wt(d);if(!je(i))continue;const o=Vt(d),l=Ye(o);!l||g.has(l)||(g.add(l),s.push({noteId:l,title:o.title||l,action:Ke(i),timestamp:c}))}}return s}function Qe(e){const a=[],s=e.tasks;if(Array.isArray(s)){for(const g of s)if(typeof g=="object"&&g!==null){const u=g,c=u.name;c&&a.push({taskId:`task-${c.toLowerCase().replace(/\s+/g,"-").slice(0,30)}`,name:c,description:u.description,state:u.state})}}if(Array.isArray(s)){for(const g of s)if(typeof g=="object"&&g!==null){const u=g,c=u.task_id;c&&!a.some(d=>d.taskId===c)&&a.push({taskId:c,name:u.name||c,description:u.description,state:u.state})}}return a}function Ze(e){if(!e)return"not_started";const a=e.toLowerCase();return a==="complete"||a==="completed"||a==="done"?"complete":a==="in_progress"||a==="in-progress"||a==="started"?"in_progress":a==="cancelled"||a==="canceled"?"cancelled":"not_started"}function En(e,a){const s=[],g=new Set;for(const u of e){const c=u.timestamp?.toString()||a;if(u.toolCalls&&Array.isArray(u.toolCalls))for(const d of u.toolCalls){const i=Wt(d);if(!He(i))continue;const o=Vt(d),l=qe(i),n=Qe(o);for(const p of n)g.has(p.taskId)||(g.add(p.taskId),s.push({taskId:p.taskId,name:p.name,description:p.description,state:Ze(p.state),action:l,timestamp:c}))}if(u.contentBlocks&&Array.isArray(u.contentBlocks))for(const d of u.contentBlocks){if(d.type!=="tool_use")continue;const i=Wt(d);if(!He(i))continue;const o=Vt(d),l=qe(i),n=Qe(o);for(const p of n)g.has(p.taskId)||(g.add(p.taskId),s.push({taskId:p.taskId,name:p.name,description:p.description,state:Ze(p.state),action:l,timestamp:c}))}}return s}function Je(e){if(ze.has(e))return!0;for(const a of ze)if(e.startsWith(a))return!0;return!1}function ta(e){if(!e)return null;const a=e.match(/Agent ID:\s*(\S+)/i);return a?a[1]:null}function ve(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.filter(a=>a&&typeof a=="object"&&a.type==="text"&&a.text).map(a=>a.text).join(`
14
- `);if(e&&typeof e=="object"){const a=e;if(typeof a.text=="string")return a.text;if(typeof a.content=="string")return a.content}return""}function Pn(e,a){const s=new Map,g=new Map;let u=0;for(const c of e){const d=[];if(c.contentBlocks&&Array.isArray(c.contentBlocks)){for(const i of c.contentBlocks)if(i.type==="tool_use"&&i.name){const o=Wt(i);Je(o)&&i.id&&d.push(i.id)}}if(c.toolCalls&&Array.isArray(c.toolCalls))for(const i of c.toolCalls){const o=Wt(i);if(Je(o)){const l=i.id;l&&!d.includes(l)&&d.push(l)}}if(d.length>1){const i=`${a}-batch-${u}`;for(const o of d)g.set(o,i);u++}}for(const c of e){if(c.contentBlocks&&Array.isArray(c.contentBlocks)){for(const d of c.contentBlocks)if(d.type==="tool_result"&&d.tool_use_id){const i=d.tool_use_id,o=g.get(i);if(o){const l=ve(d.text)||ve(d.content)||ve(d.output),n=ta(l);n&&s.set(n,o)}}}if(c.toolCalls&&Array.isArray(c.toolCalls))for(const d of c.toolCalls){const i=d.id;if(!i)continue;const o=g.get(i);if(!o)continue;const l=d.result;if(l){const n=ve(l),p=ta(n);p&&s.set(p,o)}}}return s}function Gn(e){const a={id:e.id,timestamp:e.timestamp,agentId:e.actor?.id||"",agentName:e.actor?.name};if(e.type==="agent:created"){const s=e.data;return{...a,type:"agent-created",agentId:s?.agentId||a.agentId,agentName:s?.agentName||a.agentName,parentAgentId:s?.createdByAgentId}}if(e.type==="agent:idle"){const s=e.data;return{...a,type:"agent-idle",agentId:s?.agentId||a.agentId,parentAgentId:s?.parentAgentId}}if(e.type==="file:changed"&&e.actor?.type==="agent"){const s=e.data,g=s?.action,u=g==="create"||g==="modify"||g==="delete",c=s?.relativePath;return{...a,type:u?"file-write":"file-read",targetId:s?.path||c,targetName:c?.split("/").pop()}}if(e.type?.startsWith("note:")&&e.actor?.type==="agent"){const s=e.data,g=e.type==="note:created"||e.type==="note:updated";return{...a,type:g?"note-write":"note-read",targetId:s?.noteId,targetName:s?.title}}if(e.type==="agent:tool:call"){const s=e.data,g=s?.toolName?.toLowerCase()||"";if(g.includes("read")&&s?.filesModified?.[0])return{...a,type:"file-read",targetId:s.filesModified[0],targetName:s.filesModified[0].split("/").pop()};if((g.includes("write")||g.includes("edit"))&&s?.filesModified?.[0])return{...a,type:"file-write",targetId:s.filesModified[0],targetName:s.filesModified[0].split("/").pop()}}return null}function zn(e,a){const s=e.workspaceEvents.byWorkspaceId[a]?.events??[],g=[];for(const u of s){const c=Gn(u);c&&g.push(c)}return g.sort((u,c)=>new Date(u.timestamp).getTime()-new Date(c.timestamp).getTime())}function jn(e){return e.length===0?new Date().toISOString():new Date(Math.max(...e.map(a=>new Date(a.timestamp).getTime()))).toISOString()}const Kn=Fe.createSelector((e,a)=>{const s=zn(e,a),g=jn(s),u=Ca.select(e,a),c={};for(const o of Sa.select(e,a))c[String(o.id)]=o;const d=e.workspaceNotes.byWorkspaceId[a],i=new Map;if(d)for(const o of Ga(d.notes))i.set(o.id,o);return Hn(s,c,g,!0,u,e,i)});function Hn(e,a,s,g,u,c,d){const i=new Date(s).getTime(),o=new Map;for(const I of u)o.set(I.path,I);const l=I=>d?.get(I)?.title||I,n=e.filter(I=>new Date(I.timestamp).getTime()<=i),p=[],R=[],h=new Map,v=new Set,b=[];let S=null;for(const[I,P]of Object.entries(a))if(za(P)==="topLevel"){S=I;break}for(const[I,P]of Object.entries(a)){if(h.has(I))continue;const ct=ja(P),_t=Rn(P),Ot=ra.select(c,I),Dt=We.select(c,I),ht=P.waitingForAgentIds;let bt=Fn(P,Ot);Dt?bt="waiting":(Ot||bt==="idle"&&_t.activeToolName)&&(bt="responding");const Kt={id:`agent-${I}`,type:"agent",agentId:I,name:P.name||"Agent",isCoordinator:I===S,isBackground:P.isBackground||!1,status:bt,specialist:P.metadata?.specialist||null,parentAgentId:ct,createdAt:String(P.createdAt||s),waitingForAgentIds:ht,activeToolName:_t.activeToolName,activeToolInput:_t.activeToolInput,lastResponse:_t.lastResponse,agentType:P.metadata?.agentType||null,x:0,y:0,vx:0,vy:0};if(h.set(I,Kt),p.push(Kt),ct&&a[ct]){const B=`del-${ct}-${I}`;v.has(B)||(v.add(B),b.push({key:B,sourceRawId:ct,targetRawId:I,edge:{id:B,type:"delegation",sourceId:`agent-${ct}`,targetId:`agent-${I}`,parentAgentId:ct,childAgentId:I,timestamp:String(P.createdAt||s),isActive:!1}}))}const Ft=P.messages||[];let Bt=Bn(Ft,s).map(B=>({...B,additions:o.get(B.path)?.additions,deletions:o.get(B.path)?.deletions}));Bt.length===0&&P.fileChanges&&P.fileChanges.length>0&&(Bt=P.fileChanges.map(B=>({path:B.path,type:B.type,timestamp:String(B.timestamp||s),additions:o.get(B.path)?.additions,deletions:o.get(B.path)?.deletions}))),qn(Bt,I,o,h,p,v,b,s);const Qt=Ln(Ft,s);Xn(Qt,I,l,h,p,v,b);const A=En(Ft,s);Yn(A,I,h,p,v,b)}for(const[I,P]of Object.entries(a)){const ct=P.messages||[];if(ct.length===0)continue;const _t=Pn(ct,I);if(_t.size!==0)for(const[Ot,Dt]of _t){const ht=h.get(Ot);ht&&ht.type==="agent"&&(ht.delegationBatchId=Dt)}}Un(n,g,i,a,o,l,h,p,v,b),Vn(p,u,a,S,h,v,R,g,s,c);for(const I of b)h.has(I.sourceRawId)&&h.has(I.targetRawId)&&R.push(I.edge);const x=e.map(I=>new Date(I.timestamp).getTime()),it=x.length>0?new Date(Math.min(...x)).toISOString():s,E=x.length>0?new Date(Math.max(...x)).toISOString():s;return{nodes:p,edges:R,currentTime:s,isLive:g,minTime:it,maxTime:E}}function qn(e,a,s,g,u,c,d,i){for(const o of e){const l=o.path;if(!l)continue;const n=o.type==="read",p=n?"file-read":"file-write",R=`file-${l}`;if(!g.has(l)){const v={id:R,type:"file",path:l,fileName:l.split("/").pop()||"",lastAction:o.type==="delete"?"delete":n?"read":"write",lastActionTimestamp:o.timestamp||i,x:0,y:0,vx:0,vy:0};g.set(l,v),u.push(v)}const h=`${p}-${a}-${l}`;if(!c.has(h)){c.add(h);const v=n?void 0:s.get(l);let b=n?void 0:o.additions??v?.additions,S=n?void 0:o.deletions??v?.deletions;if(!n&&b===void 0&&S===void 0){const x=l.split("").reduce((it,E)=>it+E.charCodeAt(0),0);o.type==="create"?(b=x%80+20,S=0):o.type==="modify"?(b=x%50+5,S=x%20+2):(b=x%30+3,S=x%15+1)}d.push({key:h,sourceRawId:a,targetRawId:l,edge:{id:h,type:p,sourceId:`agent-${a}`,targetId:R,agentId:a,filePath:l,timestamp:o.timestamp||i,isActive:!1,additions:b,deletions:S}})}}}function Xn(e,a,s,g,u,c,d){for(const i of e){const o=i.noteId,l=`note-${o}`;if(!g.has(o)){const R={id:l,type:"note",noteId:o,title:s(o),lastAction:i.action,lastActionTimestamp:i.timestamp,x:0,y:0,vx:0,vy:0};g.set(o,R),u.push(R)}const n=i.action==="read"?"note-read":"note-write",p=`${n}-${a}-${o}`;c.has(p)||(c.add(p),d.push({key:p,sourceRawId:a,targetRawId:o,edge:{id:p,type:n,sourceId:`agent-${a}`,targetId:l,agentId:a,noteId:o,timestamp:i.timestamp,isActive:!1}}))}}function Yn(e,a,s,g,u,c){for(const d of e){const i=d.taskId,o=`task-${i}`;if(!s.has(i)){const p={id:o,type:"task",taskId:i,name:d.name,description:d.description,state:d.state||"not_started",lastAction:d.action,lastActionTimestamp:d.timestamp,x:0,y:0,vx:0,vy:0};s.set(i,p),g.push(p)}const l=d.action==="create"?"task-create":"task-update",n=`${l}-${a}-${i}`;u.has(n)||(u.add(n),c.push({key:n,sourceRawId:a,targetRawId:i,edge:{id:n,type:l,sourceId:`agent-${a}`,targetId:o,agentId:a,taskId:i,timestamp:d.timestamp,isActive:!1}}))}}function Un(e,a,s,g,u,c,d,i,o,l){for(const n of e){const p=new Date(n.timestamp).getTime(),R=s-p<On;if((n.type==="agent-created"||n.type==="agent-idle")&&n.parentAgentId){const h=`del-${n.parentAgentId}-${n.agentId}`;o.has(h)||(o.add(h),l.push({key:h,sourceRawId:n.parentAgentId,targetRawId:n.agentId,edge:{id:h,type:"delegation",sourceId:`agent-${n.parentAgentId}`,targetId:`agent-${n.agentId}`,parentAgentId:n.parentAgentId,childAgentId:n.agentId,timestamp:n.timestamp,isActive:R}}))}if((n.type==="file-read"||n.type==="file-write")&&n.targetId){const h=`file-${n.targetId}`;if(!d.has(n.targetId)){const b={id:h,type:"file",path:n.targetId,fileName:n.targetName||n.targetId.split("/").pop()||"",lastAction:n.type==="file-write"?"write":"read",lastActionTimestamp:n.timestamp,x:0,y:0,vx:0,vy:0};d.set(n.targetId,b),i.push(b)}const v=`${n.type}-${n.agentId}-${n.targetId}`;if(!o.has(v)){o.add(v);const b=n.type==="file-write"?u.get(n.targetId):void 0;let S=b?.additions,x=b?.deletions;if(n.type==="file-write"&&S===void 0&&x===void 0){const it=n.targetId.split("").reduce((E,I)=>E+I.charCodeAt(0),0);S=it%50+5,x=it%20+2}l.push({key:v,sourceRawId:n.agentId,targetRawId:n.targetId,edge:{id:v,type:n.type,sourceId:`agent-${n.agentId}`,targetId:h,agentId:n.agentId,filePath:n.targetId,timestamp:n.timestamp,isActive:R,additions:S,deletions:x}})}}if((n.type==="note-read"||n.type==="note-write")&&n.targetId){const h=`note-${n.targetId}`;if(!d.has(n.targetId)){const b={id:h,type:"note",noteId:n.targetId,title:c(n.targetId)||n.targetName||n.targetId,lastAction:n.type==="note-write"?"write":"read",lastActionTimestamp:n.timestamp,x:0,y:0,vx:0,vy:0};d.set(n.targetId,b),i.push(b)}const v=`${n.type}-${n.agentId}-${n.targetId}`;o.has(v)||(o.add(v),l.push({key:v,sourceRawId:n.agentId,targetRawId:n.targetId,edge:{id:v,type:n.type,sourceId:`agent-${n.agentId}`,targetId:h,agentId:n.agentId,noteId:n.targetId,timestamp:n.timestamp,isActive:R}}))}}}function Vn(e,a,s,g,u,c,d,i,o,l){if(e.some(h=>h.type==="file")||a.length===0)return;const p=[];for(const h of Object.keys(s)){const v=Na.select(l,h);v&&(v.additions>0||v.deletions>0)&&p.push(h)}const R=p.length>0?p[0]:g;if(!(!R||!u.has(R)))for(const h of a){const v=h.path;if(!v)continue;const b=`file-${v}`;if(!u.has(v)){const S={id:b,type:"file",path:v,fileName:v.split("/").pop()||"",lastAction:h.action?.toLowerCase()==="delete"?"delete":"write",lastActionTimestamp:o,x:0,y:0,vx:0,vy:0};u.set(v,S),e.push(S);const x=`file-write-${R}-${v}`;c.has(x)||(c.add(x),d.push({id:x,type:"file-write",sourceId:`agent-${R}`,targetId:b,agentId:R,filePath:v,timestamp:o,isActive:i,additions:h.additions,deletions:h.deletions}))}}}var Qn=F('<div class="agent-overview-panel flex flex-col h-full bg-background overflow-auto svelte-1337n58"><!></div>');function pa(e,a){if(new.target)return oe({component:pa,...e});le(a,!0);const s=()=>$t(i,"$graphState$",g),[g,u]=Me();let c=st(a,"workspaceId",7),d=st(a,"onFocus",7);const i=Kn(c());Fe.dispatch(Ka(c()));function o(v,b,S){const x=S.metaKey||S.ctrlKey,it=Pa(S.target);Fe.dispatch(Ha(c(),{agentId:v,sourcePanelId:it,openInAdjacentPanel:x}))}const l=y(()=>s().nodes.filter(v=>qa(v)));var n={get workspaceId(){return c()},set workspaceId(v){c(v),rt()},get onFocus(){return d()},set onFocus(v){d(v),rt()},$set:ie,$on:(v,b)=>ce(a,v,b)},p=Qn(),R=L(p);la(R,{get agents(){return t(l)},get edges(){return s().edges},onAgentClick:o,get onFocus(){return d()}}),$(p),_(e,p);var h=de(n);return u(),h}function Zn(e,a){if(new.target)return oe({component:Zn,...e});le(a,!0);let s=st(a,"workspaceId",7),g=st(a,"onFocus",7);var u={get workspaceId(){return s()},set workspaceId(c){s(c),rt()},get onFocus(){return g()},set onFocus(c){g(c),rt()},$set:ie,$on:(c,d)=>ce(a,c,d)};return pa(e,{get workspaceId(){return s()},get onFocus(){return g()}}),de(u)}export{Zn as default};
13
+ L ${t(vt)??""} ${t(T)??""}`),gt(dt,"stroke",t(ht)),Xt(dt,0,se(t(kt)),"svelte-13q5gm4"),gt(dt,"stroke-width",t(w))}),_(wt,dt)};at(Ce,wt=>{t(tt)<1?wt(va):t(vt)<t(lt)?wt(ma,1):wt(ha,-1)})}_(ut,fe)}),$(Gt);var ae=C(Gt,2);jt(ae,21,()=>t(At),Se,(ut,j)=>{var Nt=Be(),vt=Yt(Nt);{var lt=ht=>{var kt=on();jt(kt,21,()=>t(j).children,w=>w.agent.agentId,(w,T)=>{s(w,()=>t(T))}),$(kt),k(()=>ne(kt,`padding: 10px; margin-top: -10px; display: grid; grid-template-columns: repeat(${t(j).cols??""}, auto); gap: 12px;`)),_(ht,kt)},zt=ht=>{s(ht,()=>t(j).child)};at(vt,ht=>{t(j).type==="batch"?ht(lt):ht(zt,-1)})}_(ut,Nt)}),$(ae),k(()=>{gt(Gt,"width",t(ot)),ne(ae,`gap: 12px; width: ${t(ot)??""}px;`)}),_(Ht,ue)}),$(xt),k(()=>ne(xt,`width: ${t(ot)??""}px;`)),_(F,xt)};at(be,F=>{t(h)&&F(U)})}$(Y),_(r,Y)};let g=st(a,"agents",7),u=st(a,"edges",7),c=st(a,"onAgentClick",7),d=st(a,"onFocus",7);const i=12,o=[{id:"git",label:"Git",types:["commit-message","pr-description"]},{id:"review",label:Z.agentOverview_hierarchyGraph_reviewCorral_label(),types:["code-review","code-walkthrough"]}];let l=Mt(1),n=Mt(0),p=Mt(0),R=Mt(!1),m=Mt(_a({x:0,y:0})),v=Mt(null),b=Mt(null),N=Mt(null);function x(r){t(N)&&clearTimeout(t(N)),V(b,r,!0)}function it(){t(N)&&(clearTimeout(t(N)),V(N,null)),V(b,null)}const E=y(()=>t(b)?g().find(r=>r.agentId===t(b)):null),I=.25,P=2,ct=.1;function _t(r){if(r.preventDefault(),r.ctrlKey||r.metaKey){const f=-r.deltaY*.001,M=Math.min(P,Math.max(I,t(l)*(1+f)));if(t(v)){const W=t(v).getBoundingClientRect(),h=r.clientX-W.left,H=r.clientY-W.top,nt=M/t(l);V(n,h-(h-t(n))*nt),V(p,H-(H-t(p))*nt)}V(l,M,!0)}else V(n,t(n)-r.deltaX),V(p,t(p)-r.deltaY)}function Ft(r){const f=r.target,M=f.closest(".agent-hierarchy-graph")&&!f.closest(".agent-card")&&!f.closest(".bg-agent-card")&&!f.closest(".zoom-controls");(r.button===1||r.button===0&&(r.shiftKey||M))&&(V(R,!0),V(m,{x:r.clientX,y:r.clientY},!0),r.preventDefault()),r.button===0&&d()?.()}function Dt(r){if(!t(R))return;const f=r.clientX-t(m).x,M=r.clientY-t(m).y;V(n,t(n)+f),V(p,t(p)+M),V(m,{x:r.clientX,y:r.clientY},!0)}function mt(){V(R,!1)}function bt(){V(l,Math.min(P,t(l)+ct),!0)}function Kt(){V(l,Math.max(I,t(l)-ct),!0)}function Ot(){V(l,1),V(n,0),V(p,0)}function ge(){V(l,.8),V(n,0),V(p,0)}const Bt=y(()=>Math.round(t(l)*100)),Zt=5e3,A=10,B=4,Tt=6;function Rt(r,f,M){if(r.length===0)return[];const W=[],h=new Map;for(const S of r){const G=S.agent.delegationBatchId;G&&(h.has(G)||h.set(G,[]),h.get(G).push(S))}const H=new Set;for(const S of r){const G=S.agent.delegationBatchId;if(G)H.has(G)||(H.add(G),W.push(h.get(G)));else{const z=W[W.length-1];if(z&&!z[0].agent.delegationBatchId){const It=new Date(z[z.length-1].agent.createdAt).getTime();if(new Date(S.agent.createdAt).getTime()-It<=Zt){z.push(S);continue}}W.push([S])}}const nt=f+M;return W.map(S=>{if(S.length===1)return{type:"single",child:S[0],width:f};const G=Math.min(Math.ceil(Math.sqrt(S.length)),B),z=Math.ceil(S.length/G);return{type:"batch",children:S,cols:G,rows:z,width:G*nt-M+A*2}})}const Lt=y(()=>{const r=new Map;for(const f of g())r.set(f.agentId,f.name);return r}),he=new Set(o.flatMap(r=>[...r.types])),Qt=y(()=>{const r=[];for(const f of o){const M=new Set(f.types),W=g().filter(h=>h.agentType&&M.has(h.agentType));W.length>0&&r.push({id:f.id,label:f.label,agents:W})}return r}),_e=y(()=>g().filter(r=>!r.agentType||!he.has(r.agentType))),Jt=y(()=>{const r=new Map,f=[];for(const h of t(_e))r.set(h.agentId,{agent:h,children:[],activeFile:void 0,activeNote:void 0});const M=u().filter(h=>h.isActive);for(const h of M){const H=h.sourceId.replace("agent-",""),nt=r.get(H);nt&&(h.type==="file-read"||h.type==="file-write"?nt.activeFile=h.targetId.replace("file-","").split("/").pop():(h.type==="note-read"||h.type==="note-write")&&(nt.activeNote=h.targetId.replace("note-","")))}for(const[,h]of r){const H=h.agent.parentAgentId;H&&r.has(H)?r.get(H).children.push(h):f.push(h)}const W=(h,H)=>new Date(h.agent.createdAt).getTime()-new Date(H.agent.createdAt).getTime();for(const[,h]of r)h.children.sort(W);return f.sort(W),f});function te(r,f){c()?.(r.agentId,r.name,f)}var ye={get agents(){return g()},set agents(r){g(r),rt()},get edges(){return u()},set edges(r){u(r),rt()},get onAgentClick(){return c()},set onAgentClick(r){c(r),rt()},get onFocus(){return d()},set onFocus(r){d(r),rt()},$set:ie,$on:(r,f)=>ce(a,r,f)},yt=Cn(),Ie=L(yt);{var xe=r=>{var f=gn(),M=L(f),W=L(M),h=K(W,!0),H=C(W,2),nt=K(H,!0);$(M),$(f),k((S,G)=>{D(h,S),D(nt,G)},[()=>Z.agentOverview_hierarchyGraph_noAgents_title(),()=>Z.agentOverview_hierarchyGraph_noAgents_description()]),_(r,f)},ft=r=>{var f=Tn(),M=Yt(f),W=L(M),h=L(W);{var H=U=>{var F=fn();jt(F,21,()=>t(Qt),q=>q.id,(q,J)=>{var et=un(),xt=L(et),Ht=K(xt,!0),At=C(xt,2);jt(At,21,()=>t(J).agents,Ct=>Ct.agentId,(Ct,Pt)=>{Re(Ct,{get agent(){return t(Pt)},onclick:ee=>te(t(Pt),ee),onmouseenter:()=>x(t(Pt).agentId),onmouseleave:it})}),$(At),$(et),k(()=>D(Ht,t(J).label)),_(q,et)}),$(F),_(U,F)};at(h,U=>{t(Qt).length>0&&U(H)})}var nt=C(h,2),S=L(nt),G=L(S);ne(G,"gap: 12px;"),jt(G,21,()=>t(Jt),U=>U.agent.agentId,(U,F)=>{s(U,()=>t(F))}),$(G),$(S),$(nt),$(W);var z=C(W,2);{var It=U=>{{let F=y(()=>"--agent-hierarchy-"+t(b));Ba(U,{get anchor(){return t(F)},position:"top",absolute:!0,children:(q,J)=>{var et=bn(),xt=L(et),Ht=L(xt);La(Ht,{variant:"emphasized",get agentId(){return t(E).agentId}});var At=C(Ht,2),Ct=L(At),Pt=K(Ct,!0),ee=C(Ct,2);{var Ae=w=>{var T=pn(),tt=K(T,!0);k(X=>D(tt,X),[()=>t(E).specialist.replace("-"," ")]),_(w,T)};at(ee,w=>{t(E).specialist&&w(Ae)})}$(At);var ue=C(At,2);{var Gt=w=>{var T=vn(),tt=K(T,!0);k(X=>D(tt,X),[()=>Z.agentOverview_hierarchyGraph_background_badge()]),_(w,T)};at(ue,w=>{t(E).isBackground&&w(Gt)})}$(xt);var qt=C(xt,2),ke=L(qt);{var $e=w=>{var T=mn(),tt=K(T);k(X=>D(tt,`● ${X??""}`),[()=>Z.agentOverview_hierarchyGraph_statusWaiting_label()]),_(w,T)},Te=w=>{var T=hn(),tt=K(T);k(X=>D(tt,`● ${X??""}`),[()=>Z.agentOverview_hierarchyGraph_statusResponding_label()]),_(w,T)},ae=w=>{var T=_n(),tt=K(T);k(X=>D(tt,`● ${X??""}`),[()=>Z.agentOverview_hierarchyGraph_statusCompleted_label()]),_(w,T)},ut=w=>{var T=yn(),tt=K(T);k(X=>D(tt,`● ${X??""}`),[()=>Z.agentOverview_hierarchyGraph_statusFailed_label()]),_(w,T)},j=w=>{var T=In(),tt=K(T);k(X=>D(tt,`● ${X??""}`),[()=>Z.agentOverview_hierarchyGraph_statusIdle_label()]),_(w,T)};at(ke,w=>{t(E).status==="waiting"?w($e):t(E).status==="responding"?w(Te,1):t(E).status==="completed"?w(ae,2):t(E).status==="failed"?w(ut,3):w(j,-1)})}$(qt);var Nt=C(qt,2),vt=K(Nt,!0),lt=C(Nt,2);{var zt=w=>{var T=xn(),tt=K(T,!0);k(()=>D(tt,t(E).lastResponse)),_(w,T)};at(lt,w=>{t(E).lastResponse&&w(zt)})}var ht=C(lt,2);{var kt=w=>{var T=wn(),tt=L(T);ea(tt,{size:12});var X=C(tt,2),fe=K(X,!0);$(T),k(Ce=>D(fe,Ce),[()=>Z.agentOverview_hierarchyGraph_usingTool_label({tool:t(E).activeToolName})]),_(w,T)};at(ht,w=>{t(E).activeToolName&&w(kt)})}$(et),k(w=>{D(Pt,t(E).name),D(vt,w)},[()=>Z.agentOverview_hierarchyGraph_created_label({time:Ea(t(E).createdAt)})]),_(q,et)},$$slots:{default:!0}})}};at(z,U=>{t(E)&&U(It)})}$(M);var ot=C(M,2),Y=L(ot);{let U=y(()=>Z.agentOverview_hierarchyGraph_zoomOut_tooltip());Ut(Y,{variant:"ghost",size:"icon",iconOnly:!0,type:"button",class:"zoom-btn hover:bg-muted transition-colors text-muted-foreground hover:text-foreground",onclick:Kt,get title(){return t(U)},children:(F,q)=>{var J=An();_(F,J)},$$slots:{default:!0}})}var Q=C(Y,2);{let U=y(()=>Z.agentOverview_hierarchyGraph_resetZoom_tooltip());Ut(Q,{variant:"ghost",type:"button",class:"zoom-percent w-12 h-8 flex items-center justify-center text-xs font-medium text-muted-foreground hover:text-foreground hover:bg-muted rounded transition-colors",onclick:Ot,get title(){return t(U)},children:(F,q)=>{Ia();var J=xa();k(()=>D(J,`${t(Bt)??""}%`)),_(F,J)},$$slots:{default:!0}})}var pt=C(Q,2);{let U=y(()=>Z.agentOverview_hierarchyGraph_zoomIn_tooltip());Ut(pt,{variant:"ghost",size:"icon",iconOnly:!0,type:"button",class:"zoom-btn hover:bg-muted transition-colors text-muted-foreground hover:text-foreground",onclick:bt,get title(){return t(U)},children:(F,q)=>{var J=kn();_(F,J)},$$slots:{default:!0}})}var Et=C(pt,4);{let U=y(()=>Z.agentOverview_hierarchyGraph_fitToView_tooltip());Ut(Et,{variant:"ghost",size:"icon",iconOnly:!0,type:"button",class:"zoom-btn hover:bg-muted transition-colors text-muted-foreground hover:text-foreground",onclick:ge,get title(){return t(U)},children:(F,q)=>{var J=$n();_(F,J)},$$slots:{default:!0}})}$(ot);var we=C(ot,2),be=K(we,!0);k(U=>{ne(M,`transform: translate(${t(n)??""}px, ${t(p)??""}px) scale(${t(l)??""}); transform-origin: center center;`),D(be,U)},[()=>Z.agentOverview_hierarchyGraph_panHint_label()]),_(r,f)};at(Ie,r=>{t(Jt).length===0?r(xe):r(ft,-1)})}return $(yt),ba(yt,r=>V(v,r),()=>t(v)),De("wheel",yt,_t),Ne("mousedown",yt,Ft),Ne("mousemove",yt,Dt),Ne("mouseup",yt,mt),De("mouseleave",yt,mt),_(e,yt),de(ye)}ya(["mousedown","mousemove","mouseup"]);const Ee=new Set(["str-replace-editor","save-file","remove-files","str_replace_editor"]),Pe=new Set(["create_note","update_note","set_note_content","add_to_note","append_to_note","edit_note","edit_note_lines","update_note_metadata","read_note","view_note","delete_note"]),Nn=new Set(["read_note","view_note","list_note_tasks"]),Ge=new Set(["add_tasks","update_tasks","view_tasklist","reorganize_tasklist"]),Sn=new Set(["view_tasklist"]),ze=new Set(["delegate_task","create_sub_agent","create_agent"]),Fn=5e3;function On(e,a=!1){if(!e)return"idle";if(e.status===St.Completed)return"completed";if(e.status===St.Error||e.status===St.Deleted)return"failed";if(a||da(e))return"responding";if(ga(e.status))return"idle";if(e.messages&&e.messages.length>0){const s=[...e.messages].reverse().find(g=>g.role==="assistant");if(s&&(s.isStreaming||s.streamingComplete===!1))return"responding"}switch(e.status){case St.Active:return"idle";case St.Pending:case St.Idle:return"idle";case St.Processing:return a?"responding":"idle";case St.Waiting:return"waiting";default:return"idle"}}function da(e){return!!(e.isProcessing||e.isStreaming||e.isResponding)}function ga(e){return e===St.Idle||e==="idle"}function Rn(e){const a={};if(!e)return a;if(e.lastAgentResponse){const s=Ta(e.lastAgentResponse);s&&(a.lastResponse=s)}return ga(e.status)&&!da(e)||e.isStreaming&&e.lastToolUse?.name&&(a.activeToolName=e.lastToolUse.name,a.activeToolInput=e.lastToolUse.input||{}),a}function Wt(e){return(e.name||e.toolName||"").toLowerCase()}function Vt(e){return"input"in e&&e.input?e.input:"arguments"in e&&e.arguments?e.arguments:"parameters"in e&&e.parameters?e.parameters:{}}function Mn(e){const a=e.toLowerCase();if(Ee.has(e))return!0;for(const s of Ee)if(a.startsWith(s.toLowerCase()))return!0;return!!(a.startsWith("edit ")||a.startsWith("save ")||a.startsWith("create "))}function ua(e){const a=e.toLowerCase();return!!(a.startsWith("read `")&&!a.includes("read `.`")||a.startsWith("view")||a==="view")}function je(e){if(Pe.has(e))return!0;for(const a of Pe)if(e.startsWith(a))return!0;return!1}function Wn(e){return e==="save-file"?"create":e==="remove-files"?"delete":"modify"}function Ke(e){return e==="create_note"?"create":Nn.has(e)?"read":"write"}function He(e){if(Ge.has(e))return!0;for(const a of Ge)if(e.startsWith(a))return!0;return!1}function qe(e){return e==="add_tasks"?"create":Sn.has(e)?"read":"update"}function fa(e){if(e==="."||e==="./"||e.endsWith("/"))return!0;const s=(e.split("/").pop()||e).lastIndexOf(".");return s===-1||s===0}function Dn(e){const a=e.match(/`([^`]+)`/);if(a&&a[1]){const s=a[1];return fa(s)?null:s}return null}function Xe(e,a){const s=e.path||e.file_path||e.filePath;return typeof s=="string"?fa(s)?null:s:a?Dn(a):null}function Ye(e){const a=e.noteId||e.note_id||e.title;return typeof a=="string"?a:null}function Ue(e){return Mn(e)||ua(e)}function Ve(e){return ua(e)?"read":Wn(e)}function Bn(e,a){const s=[],g=new Set;for(const u of e){const c=u.timestamp?.toString()||a;if(u.toolCalls&&Array.isArray(u.toolCalls))for(const d of u.toolCalls){const i=Wt(d);if(!Ue(i))continue;const o=Vt(d),l=Xe(o,d.name||d.toolName);!l||g.has(l)||(g.add(l),s.push({path:l,type:Ve(i),timestamp:c}))}if(u.contentBlocks&&Array.isArray(u.contentBlocks))for(const d of u.contentBlocks){if(d.type!=="tool_use")continue;const i=Wt(d);if(!Ue(i))continue;const o=Vt(d),l=Xe(o,d.name);!l||g.has(l)||(g.add(l),s.push({path:l,type:Ve(i),timestamp:c}))}}return s}function Ln(e,a){const s=[],g=new Set;for(const u of e){const c=u.timestamp?.toString()||a;if(u.toolCalls&&Array.isArray(u.toolCalls))for(const d of u.toolCalls){const i=Wt(d);if(!je(i))continue;const o=Vt(d),l=Ye(o);!l||g.has(l)||(g.add(l),s.push({noteId:l,title:o.title||l,action:Ke(i),timestamp:c}))}if(u.contentBlocks&&Array.isArray(u.contentBlocks))for(const d of u.contentBlocks){if(d.type!=="tool_use")continue;const i=Wt(d);if(!je(i))continue;const o=Vt(d),l=Ye(o);!l||g.has(l)||(g.add(l),s.push({noteId:l,title:o.title||l,action:Ke(i),timestamp:c}))}}return s}function Ze(e){const a=[],s=e.tasks;if(Array.isArray(s)){for(const g of s)if(typeof g=="object"&&g!==null){const u=g,c=u.name;c&&a.push({taskId:`task-${c.toLowerCase().replace(/\s+/g,"-").slice(0,30)}`,name:c,description:u.description,state:u.state})}}if(Array.isArray(s)){for(const g of s)if(typeof g=="object"&&g!==null){const u=g,c=u.task_id;c&&!a.some(d=>d.taskId===c)&&a.push({taskId:c,name:u.name||c,description:u.description,state:u.state})}}return a}function Qe(e){if(!e)return"not_started";const a=e.toLowerCase();return a==="complete"||a==="completed"||a==="done"?"complete":a==="in_progress"||a==="in-progress"||a==="started"?"in_progress":a==="cancelled"||a==="canceled"?"cancelled":"not_started"}function En(e,a){const s=[],g=new Set;for(const u of e){const c=u.timestamp?.toString()||a;if(u.toolCalls&&Array.isArray(u.toolCalls))for(const d of u.toolCalls){const i=Wt(d);if(!He(i))continue;const o=Vt(d),l=qe(i),n=Ze(o);for(const p of n)g.has(p.taskId)||(g.add(p.taskId),s.push({taskId:p.taskId,name:p.name,description:p.description,state:Qe(p.state),action:l,timestamp:c}))}if(u.contentBlocks&&Array.isArray(u.contentBlocks))for(const d of u.contentBlocks){if(d.type!=="tool_use")continue;const i=Wt(d);if(!He(i))continue;const o=Vt(d),l=qe(i),n=Ze(o);for(const p of n)g.has(p.taskId)||(g.add(p.taskId),s.push({taskId:p.taskId,name:p.name,description:p.description,state:Qe(p.state),action:l,timestamp:c}))}}return s}function Je(e){if(ze.has(e))return!0;for(const a of ze)if(e.startsWith(a))return!0;return!1}function ta(e){if(!e)return null;const a=e.match(/Agent ID:\s*(\S+)/i);return a?a[1]:null}function ve(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.filter(a=>a&&typeof a=="object"&&a.type==="text"&&a.text).map(a=>a.text).join(`
14
+ `);if(e&&typeof e=="object"){const a=e;if(typeof a.text=="string")return a.text;if(typeof a.content=="string")return a.content}return""}function Pn(e,a){const s=new Map,g=new Map;let u=0;for(const c of e){const d=[];if(c.contentBlocks&&Array.isArray(c.contentBlocks)){for(const i of c.contentBlocks)if(i.type==="tool_use"&&i.name){const o=Wt(i);Je(o)&&i.id&&d.push(i.id)}}if(c.toolCalls&&Array.isArray(c.toolCalls))for(const i of c.toolCalls){const o=Wt(i);if(Je(o)){const l=i.id;l&&!d.includes(l)&&d.push(l)}}if(d.length>1){const i=`${a}-batch-${u}`;for(const o of d)g.set(o,i);u++}}for(const c of e){if(c.contentBlocks&&Array.isArray(c.contentBlocks)){for(const d of c.contentBlocks)if(d.type==="tool_result"&&d.tool_use_id){const i=d.tool_use_id,o=g.get(i);if(o){const l=ve(d.text)||ve(d.content)||ve(d.output),n=ta(l);n&&s.set(n,o)}}}if(c.toolCalls&&Array.isArray(c.toolCalls))for(const d of c.toolCalls){const i=d.id;if(!i)continue;const o=g.get(i);if(!o)continue;const l=d.result;if(l){const n=ve(l),p=ta(n);p&&s.set(p,o)}}}return s}function Gn(e){const a={id:e.id,timestamp:e.timestamp,agentId:e.actor?.id||"",agentName:e.actor?.name};if(e.type==="agent:created"){const s=e.data;return{...a,type:"agent-created",agentId:s?.agentId||a.agentId,agentName:s?.agentName||a.agentName,parentAgentId:s?.createdByAgentId}}if(e.type==="agent:idle"){const s=e.data;return{...a,type:"agent-idle",agentId:s?.agentId||a.agentId,parentAgentId:s?.parentAgentId}}if(e.type==="file:changed"&&e.actor?.type==="agent"){const s=e.data,g=s?.action,u=g==="create"||g==="modify"||g==="delete",c=s?.relativePath;return{...a,type:u?"file-write":"file-read",targetId:s?.path||c,targetName:c?.split("/").pop()}}if(e.type?.startsWith("note:")&&e.actor?.type==="agent"){const s=e.data,g=e.type==="note:created"||e.type==="note:updated";return{...a,type:g?"note-write":"note-read",targetId:s?.noteId,targetName:s?.title}}if(e.type==="agent:tool:call"){const s=e.data,g=s?.toolName?.toLowerCase()||"";if(g.includes("read")&&s?.filesModified?.[0])return{...a,type:"file-read",targetId:s.filesModified[0],targetName:s.filesModified[0].split("/").pop()};if((g.includes("write")||g.includes("edit"))&&s?.filesModified?.[0])return{...a,type:"file-write",targetId:s.filesModified[0],targetName:s.filesModified[0].split("/").pop()}}return null}function zn(e,a){const s=e.workspaceEvents.byWorkspaceId[a]?.events??[],g=[];for(const u of s){const c=Gn(u);c&&g.push(c)}return g.sort((u,c)=>new Date(u.timestamp).getTime()-new Date(c.timestamp).getTime())}function jn(e){return e.length===0?new Date().toISOString():new Date(Math.max(...e.map(a=>new Date(a.timestamp).getTime()))).toISOString()}const Kn=Oe.createSelector((e,a)=>{const s=zn(e,a),g=jn(s),u=Ca.select(e,a),c={};for(const o of Na.select(e,a))c[String(o.id)]=o;const d=e.workspaceNotes.byWorkspaceId[a],i=new Map;if(d)for(const o of Ga(d.notes))i.set(o.id,o);return Hn(s,c,g,!0,u,e,i)});function Hn(e,a,s,g,u,c,d){const i=new Date(s).getTime(),o=new Map;for(const I of u)o.set(I.path,I);const l=I=>d?.get(I)?.title||I,n=e.filter(I=>new Date(I.timestamp).getTime()<=i),p=[],R=[],m=new Map,v=new Set,b=[];let N=null;for(const[I,P]of Object.entries(a))if(za(P)==="topLevel"){N=I;break}for(const[I,P]of Object.entries(a)){if(m.has(I))continue;const ct=ja(P),_t=Rn(P),Ft=ra.select(c,I),Dt=We.select(c,I),mt=P.waitingForAgentIds;let bt=On(P,Ft);Dt?bt="waiting":(Ft||bt==="idle"&&_t.activeToolName)&&(bt="responding");const Kt={id:`agent-${I}`,type:"agent",agentId:I,name:P.name||"Agent",isCoordinator:I===N,isBackground:P.isBackground||!1,status:bt,specialist:P.metadata?.specialist||null,parentAgentId:ct,createdAt:String(P.createdAt||s),waitingForAgentIds:mt,activeToolName:_t.activeToolName,activeToolInput:_t.activeToolInput,lastResponse:_t.lastResponse,agentType:P.metadata?.agentType||null,x:0,y:0,vx:0,vy:0};if(m.set(I,Kt),p.push(Kt),ct&&a[ct]){const B=`del-${ct}-${I}`;v.has(B)||(v.add(B),b.push({key:B,sourceRawId:ct,targetRawId:I,edge:{id:B,type:"delegation",sourceId:`agent-${ct}`,targetId:`agent-${I}`,parentAgentId:ct,childAgentId:I,timestamp:String(P.createdAt||s),isActive:!1}}))}const Ot=P.messages||[];let Bt=Bn(Ot,s).map(B=>({...B,additions:o.get(B.path)?.additions,deletions:o.get(B.path)?.deletions}));Bt.length===0&&P.fileChanges&&P.fileChanges.length>0&&(Bt=P.fileChanges.map(B=>({path:B.path,type:B.type,timestamp:String(B.timestamp||s),additions:o.get(B.path)?.additions,deletions:o.get(B.path)?.deletions}))),qn(Bt,I,o,m,p,v,b,s);const Zt=Ln(Ot,s);Xn(Zt,I,l,m,p,v,b);const A=En(Ot,s);Yn(A,I,m,p,v,b)}for(const[I,P]of Object.entries(a)){const ct=P.messages||[];if(ct.length===0)continue;const _t=Pn(ct,I);if(_t.size!==0)for(const[Ft,Dt]of _t){const mt=m.get(Ft);mt&&mt.type==="agent"&&(mt.delegationBatchId=Dt)}}Un(n,g,i,a,o,l,m,p,v,b),Vn(p,u,a,N,m,v,R,g,s,c);for(const I of b)m.has(I.sourceRawId)&&m.has(I.targetRawId)&&R.push(I.edge);const x=e.map(I=>new Date(I.timestamp).getTime()),it=x.length>0?new Date(Math.min(...x)).toISOString():s,E=x.length>0?new Date(Math.max(...x)).toISOString():s;return{nodes:p,edges:R,currentTime:s,isLive:g,minTime:it,maxTime:E}}function qn(e,a,s,g,u,c,d,i){for(const o of e){const l=o.path;if(!l)continue;const n=o.type==="read",p=n?"file-read":"file-write",R=`file-${l}`;if(!g.has(l)){const v={id:R,type:"file",path:l,fileName:l.split("/").pop()||"",lastAction:o.type==="delete"?"delete":n?"read":"write",lastActionTimestamp:o.timestamp||i,x:0,y:0,vx:0,vy:0};g.set(l,v),u.push(v)}const m=`${p}-${a}-${l}`;if(!c.has(m)){c.add(m);const v=n?void 0:s.get(l);let b=n?void 0:o.additions??v?.additions,N=n?void 0:o.deletions??v?.deletions;if(!n&&b===void 0&&N===void 0){const x=l.split("").reduce((it,E)=>it+E.charCodeAt(0),0);o.type==="create"?(b=x%80+20,N=0):o.type==="modify"?(b=x%50+5,N=x%20+2):(b=x%30+3,N=x%15+1)}d.push({key:m,sourceRawId:a,targetRawId:l,edge:{id:m,type:p,sourceId:`agent-${a}`,targetId:R,agentId:a,filePath:l,timestamp:o.timestamp||i,isActive:!1,additions:b,deletions:N}})}}}function Xn(e,a,s,g,u,c,d){for(const i of e){const o=i.noteId,l=`note-${o}`;if(!g.has(o)){const R={id:l,type:"note",noteId:o,title:s(o),lastAction:i.action,lastActionTimestamp:i.timestamp,x:0,y:0,vx:0,vy:0};g.set(o,R),u.push(R)}const n=i.action==="read"?"note-read":"note-write",p=`${n}-${a}-${o}`;c.has(p)||(c.add(p),d.push({key:p,sourceRawId:a,targetRawId:o,edge:{id:p,type:n,sourceId:`agent-${a}`,targetId:l,agentId:a,noteId:o,timestamp:i.timestamp,isActive:!1}}))}}function Yn(e,a,s,g,u,c){for(const d of e){const i=d.taskId,o=`task-${i}`;if(!s.has(i)){const p={id:o,type:"task",taskId:i,name:d.name,description:d.description,state:d.state||"not_started",lastAction:d.action,lastActionTimestamp:d.timestamp,x:0,y:0,vx:0,vy:0};s.set(i,p),g.push(p)}const l=d.action==="create"?"task-create":"task-update",n=`${l}-${a}-${i}`;u.has(n)||(u.add(n),c.push({key:n,sourceRawId:a,targetRawId:i,edge:{id:n,type:l,sourceId:`agent-${a}`,targetId:o,agentId:a,taskId:i,timestamp:d.timestamp,isActive:!1}}))}}function Un(e,a,s,g,u,c,d,i,o,l){for(const n of e){const p=new Date(n.timestamp).getTime(),R=s-p<Fn;if((n.type==="agent-created"||n.type==="agent-idle")&&n.parentAgentId){const m=`del-${n.parentAgentId}-${n.agentId}`;o.has(m)||(o.add(m),l.push({key:m,sourceRawId:n.parentAgentId,targetRawId:n.agentId,edge:{id:m,type:"delegation",sourceId:`agent-${n.parentAgentId}`,targetId:`agent-${n.agentId}`,parentAgentId:n.parentAgentId,childAgentId:n.agentId,timestamp:n.timestamp,isActive:R}}))}if((n.type==="file-read"||n.type==="file-write")&&n.targetId){const m=`file-${n.targetId}`;if(!d.has(n.targetId)){const b={id:m,type:"file",path:n.targetId,fileName:n.targetName||n.targetId.split("/").pop()||"",lastAction:n.type==="file-write"?"write":"read",lastActionTimestamp:n.timestamp,x:0,y:0,vx:0,vy:0};d.set(n.targetId,b),i.push(b)}const v=`${n.type}-${n.agentId}-${n.targetId}`;if(!o.has(v)){o.add(v);const b=n.type==="file-write"?u.get(n.targetId):void 0;let N=b?.additions,x=b?.deletions;if(n.type==="file-write"&&N===void 0&&x===void 0){const it=n.targetId.split("").reduce((E,I)=>E+I.charCodeAt(0),0);N=it%50+5,x=it%20+2}l.push({key:v,sourceRawId:n.agentId,targetRawId:n.targetId,edge:{id:v,type:n.type,sourceId:`agent-${n.agentId}`,targetId:m,agentId:n.agentId,filePath:n.targetId,timestamp:n.timestamp,isActive:R,additions:N,deletions:x}})}}if((n.type==="note-read"||n.type==="note-write")&&n.targetId){const m=`note-${n.targetId}`;if(!d.has(n.targetId)){const b={id:m,type:"note",noteId:n.targetId,title:c(n.targetId)||n.targetName||n.targetId,lastAction:n.type==="note-write"?"write":"read",lastActionTimestamp:n.timestamp,x:0,y:0,vx:0,vy:0};d.set(n.targetId,b),i.push(b)}const v=`${n.type}-${n.agentId}-${n.targetId}`;o.has(v)||(o.add(v),l.push({key:v,sourceRawId:n.agentId,targetRawId:n.targetId,edge:{id:v,type:n.type,sourceId:`agent-${n.agentId}`,targetId:m,agentId:n.agentId,noteId:n.targetId,timestamp:n.timestamp,isActive:R}}))}}}function Vn(e,a,s,g,u,c,d,i,o,l){if(e.some(m=>m.type==="file")||a.length===0)return;const p=[];for(const m of Object.keys(s)){const v=Sa.select(l,m);v&&(v.additions>0||v.deletions>0)&&p.push(m)}const R=p.length>0?p[0]:g;if(!(!R||!u.has(R)))for(const m of a){const v=m.path;if(!v)continue;const b=`file-${v}`;if(!u.has(v)){const N={id:b,type:"file",path:v,fileName:v.split("/").pop()||"",lastAction:m.action?.toLowerCase()==="delete"?"delete":"write",lastActionTimestamp:o,x:0,y:0,vx:0,vy:0};u.set(v,N),e.push(N);const x=`file-write-${R}-${v}`;c.has(x)||(c.add(x),d.push({id:x,type:"file-write",sourceId:`agent-${R}`,targetId:b,agentId:R,filePath:v,timestamp:o,isActive:i,additions:m.additions,deletions:m.deletions}))}}}var Zn=O('<div class="agent-overview-panel flex flex-col h-full bg-background overflow-auto svelte-1337n58"><!></div>');function pa(e,a){if(new.target)return oe({component:pa,...e});le(a,!0);const s=()=>$t(i,"$graphState$",g),[g,u]=Me();let c=st(a,"workspaceId",7),d=st(a,"onFocus",7);const i=Kn(c());Oe.dispatch(Ka(c()));function o(v,b,N){const x=N.metaKey||N.ctrlKey,it=Pa(N.target);Oe.dispatch(Ha(c(),{agentId:v,sourcePanelId:it,openInAdjacentPanel:x}))}const l=y(()=>s().nodes.filter(v=>qa(v)));var n={get workspaceId(){return c()},set workspaceId(v){c(v),rt()},get onFocus(){return d()},set onFocus(v){d(v),rt()},$set:ie,$on:(v,b)=>ce(a,v,b)},p=Zn(),R=L(p);la(R,{get agents(){return t(l)},get edges(){return s().edges},onAgentClick:o,get onFocus(){return d()}}),$(p),_(e,p);var m=de(n);return u(),m}function Qn(e,a){if(new.target)return oe({component:Qn,...e});le(a,!0);let s=st(a,"workspaceId",7),g=st(a,"onFocus",7);var u={get workspaceId(){return s()},set workspaceId(c){s(c),rt()},get onFocus(){return g()},set onFocus(c){g(c),rt()},$set:ie,$on:(c,d)=>ce(a,c,d)};return pa(e,{get workspaceId(){return s()},get onFocus(){return g()}}),de(u)}export{Qn as default};
@@ -1,2 +1,2 @@
1
- import{IX as l,rK as u,IA as v}from"./BkzMrEqG.js";import{at as b}from"./dxPehZVa.js";import{bv as m}from"./BEyxbMng.js";import{bd as S,b9 as P}from"./DkNdI_Wp.js";import{I as M}from"./R1d5Y9eD.js";import{bm as s}from"./AeC4KVgG.js";import{l as E}from"./DWUO9rBe.js";const D=l.createSelector(t=>t.backgroundAgentSettings.defaultModel),O=l.createSelector(t=>t.backgroundAgentSettings.typeOverrides),j=l.createSelector(t=>t.backgroundAgentSettings.defaultReasoningEffort),H=l.createSelector(t=>t.backgroundAgentSettings.typeReasoningEffortOverrides),w=l.createSelector(t=>t.backgroundAgentSettings),A=l.createSelector(t=>{const a=new Map,o=(e,i)=>{const n=a.get(e)??new Set;n.add(i),a.set(e,n)},f=m.select(t),d=M.select(t),g=b.select(t)[d];g&&d&&o(d,s.settings_providers_inUseDefaultModel_label({model:g})),u(d)&&!g&&o(d,s.settings_providers_inUseDefaultProvider_label());const p=t.backgroundAgentSettings?.providerId;p&&u(p)&&o(p,s.settings_providers_inUseQuickActions_label());for(const e of S.select(t)){const i=P.select(t,e.id),n=e.source?{project:s.settings_providers_pinSourceProject_label(),user:s.settings_providers_pinSourceUser_label(),bundled:s.settings_providers_pinSourceBundled_label(),builtin:s.settings_providers_pinSourceBuiltin_label(),"electron-store":s.settings_providers_pinSourceLegacy_label()}[e.source]:void 0,c=r=>n&&i?s.settings_providers_inUseSourcePath_label({reason:r,source:n,path:i}):n?s.settings_providers_inUseSource_label({reason:r,source:n}):i?s.settings_providers_inUsePath_label({reason:r,path:i}):r;if(e.codingAgent&&o(e.codingAgent,c(s.settings_providers_inUseSpecialistAgent_label({name:e.name}))),e.modelOptions?.forEach((r,_)=>{r.provider&&u(r.provider)&&o(r.provider,c(s.settings_providers_inUseSpecialistModelOption_label({name:e.name,position:E(_+1)})))}),e.defaultModel)if(e.defaultModel.includes(":")){const r=v(e.defaultModel).providerId??f;o(r,c(s.settings_providers_inUseSpecialistModel_label({name:e.name,model:e.defaultModel})))}else e.codingAgent||o(f,c(s.settings_providers_inUseSpecialistModel_label({name:e.name,model:e.defaultModel})))}return Object.fromEntries([...a].map(([e,i])=>[e,[...i].join(`
1
+ import{IX as l,rK as u,IA as b}from"./BkzMrEqG.js";import{at as v}from"./CWVUBnHm.js";import{bG as m}from"./-5BGDZDk.js";import{bd as S,b9 as P}from"./DcNzEJkC.js";import{I as M}from"./CP5zM-2z.js";import{bm as s}from"./AeC4KVgG.js";import{l as E}from"./DWUO9rBe.js";const D=l.createSelector(t=>t.backgroundAgentSettings.defaultModel),O=l.createSelector(t=>t.backgroundAgentSettings.typeOverrides),j=l.createSelector(t=>t.backgroundAgentSettings.defaultReasoningEffort),H=l.createSelector(t=>t.backgroundAgentSettings.typeReasoningEffortOverrides),w=l.createSelector(t=>t.backgroundAgentSettings),A=l.createSelector(t=>{const a=new Map,o=(e,i)=>{const n=a.get(e)??new Set;n.add(i),a.set(e,n)},f=m.select(t),d=M.select(t),g=v.select(t)[d];g&&d&&o(d,s.settings_providers_inUseDefaultModel_label({model:g})),u(d)&&!g&&o(d,s.settings_providers_inUseDefaultProvider_label());const p=t.backgroundAgentSettings?.providerId;p&&u(p)&&o(p,s.settings_providers_inUseQuickActions_label());for(const e of S.select(t)){const i=P.select(t,e.id),n=e.source?{project:s.settings_providers_pinSourceProject_label(),user:s.settings_providers_pinSourceUser_label(),bundled:s.settings_providers_pinSourceBundled_label(),builtin:s.settings_providers_pinSourceBuiltin_label(),"electron-store":s.settings_providers_pinSourceLegacy_label()}[e.source]:void 0,c=r=>n&&i?s.settings_providers_inUseSourcePath_label({reason:r,source:n,path:i}):n?s.settings_providers_inUseSource_label({reason:r,source:n}):i?s.settings_providers_inUsePath_label({reason:r,path:i}):r;if(e.codingAgent&&o(e.codingAgent,c(s.settings_providers_inUseSpecialistAgent_label({name:e.name}))),e.modelOptions?.forEach((r,_)=>{r.provider&&u(r.provider)&&o(r.provider,c(s.settings_providers_inUseSpecialistModelOption_label({name:e.name,position:E(_+1)})))}),e.defaultModel)if(e.defaultModel.includes(":")){const r=b(e.defaultModel).providerId??f;o(r,c(s.settings_providers_inUseSpecialistModel_label({name:e.name,model:e.defaultModel})))}else e.codingAgent||o(f,c(s.settings_providers_inUseSpecialistModel_label({name:e.name,model:e.defaultModel})))}return Object.fromEntries([...a].map(([e,i])=>[e,[...i].join(`
2
2
  `)]))});l.createSelector((t,a)=>A.select(t)[a]??null);const I=[{id:"dracula",label:"Dracula"},{id:"nord",label:"Nord"},{id:"rose-pine",label:"Rosé Pine"},{id:"tokyo-night",label:"Tokyo Night"},{id:"solarized",label:"Solarized"},{id:"github",label:"GitHub"},{id:"high-contrast",label:"High Contrast"}],N=I.map(({id:t})=>t);export{N as T,I as a,j as b,w as c,O as d,H as e,A as f,D as s};
@@ -1 +1 @@
1
- import{g as p,r as u,d as n}from"./aCDFJfWo.js";import{p as f}from"./DAwOD17b.js";import{b as a,ay as o}from"./C9otdzZM.js";import{M as c,c as d}from"./CfNfee-Y.js";var v=d().RailroadAbnf.parser.LangiumParser,i=a(e=>{const r=e.alternatives.map(g);return r.length===1?r[0]:{type:"choice",alternatives:r}},"transformAlternation"),g=a(e=>{const r=e.elements.map(y);return r.length===1?r[0]:{type:"sequence",elements:r}},"transformConcatenation"),b=a(e=>{if(e.includes("*")){const[t,s]=e.split("*"),l=t?parseInt(t,10):0,m=s?parseInt(s,10):1/0;return{min:l,max:m}}const r=parseInt(e,10);return{min:r,max:r}},"parseRepeat"),y=a(e=>{const r=A(e.primary);if(!e.repeat)return r;const{min:t,max:s}=b(e.repeat);return t===0&&s===1?{type:"optional",element:r}:{type:"repetition",element:r,min:t,max:s}},"transformElement"),A=a(e=>{switch(e.$type){case"AbnfStringLiteral":return{type:"terminal",value:e.value};case"AbnfNumVal":return{type:"terminal",value:e.value};case"AbnfRuleName":return{type:"nonterminal",name:e.name};case"AbnfGroup":return i(e.element);case"AbnfOptionalGroup":return{type:"optional",element:i(e.element)};default:throw new Error(`Unsupported ABNF primary node: ${e.$type}`)}},"transformPrimary"),P=a(e=>({name:e.name,definition:i(e.definition)}),"transformRule"),h=a(e=>{f(e,n),e.title&&n.setTitle(e.title),e.rules.map(r=>n.addRule(P(r)))},"populateDb"),R={parse:a(e=>{n.clear(),o.debug("[ABNF Parser] Starting Langium parse");const r=v.parse(e);if(r.lexerErrors.length>0||r.parserErrors.length>0)throw new c(r);const t=r.value;o.debug("[ABNF Parser] Parsed rules:",t.rules.length),h(t),o.debug("[ABNF Parser] Parse complete")},"parse"),parser:{yy:n}},w={parser:R,db:n,renderer:u,styles:p};export{w as diagram};
1
+ import{g as p,r as u,d as n}from"./CRBbB4Mw.js";import{p as f}from"./JWLuWIPn.js";import{b as a,ay as o}from"./BPeXyR5m.js";import{M as c,c as d}from"./CfNfee-Y.js";var v=d().RailroadAbnf.parser.LangiumParser,i=a(e=>{const r=e.alternatives.map(g);return r.length===1?r[0]:{type:"choice",alternatives:r}},"transformAlternation"),g=a(e=>{const r=e.elements.map(y);return r.length===1?r[0]:{type:"sequence",elements:r}},"transformConcatenation"),b=a(e=>{if(e.includes("*")){const[t,s]=e.split("*"),l=t?parseInt(t,10):0,m=s?parseInt(s,10):1/0;return{min:l,max:m}}const r=parseInt(e,10);return{min:r,max:r}},"parseRepeat"),y=a(e=>{const r=A(e.primary);if(!e.repeat)return r;const{min:t,max:s}=b(e.repeat);return t===0&&s===1?{type:"optional",element:r}:{type:"repetition",element:r,min:t,max:s}},"transformElement"),A=a(e=>{switch(e.$type){case"AbnfStringLiteral":return{type:"terminal",value:e.value};case"AbnfNumVal":return{type:"terminal",value:e.value};case"AbnfRuleName":return{type:"nonterminal",name:e.name};case"AbnfGroup":return i(e.element);case"AbnfOptionalGroup":return{type:"optional",element:i(e.element)};default:throw new Error(`Unsupported ABNF primary node: ${e.$type}`)}},"transformPrimary"),P=a(e=>({name:e.name,definition:i(e.definition)}),"transformRule"),h=a(e=>{f(e,n),e.title&&n.setTitle(e.title),e.rules.map(r=>n.addRule(P(r)))},"populateDb"),R={parse:a(e=>{n.clear(),o.debug("[ABNF Parser] Starting Langium parse");const r=v.parse(e);if(r.lexerErrors.length>0||r.parserErrors.length>0)throw new c(r);const t=r.value;o.debug("[ABNF Parser] Parsed rules:",t.rules.length),h(t),o.debug("[ABNF Parser] Parse complete")},"parse"),parser:{yy:n}},w={parser:R,db:n,renderer:u,styles:p};export{w as diagram};
@@ -1 +1 @@
1
- var Me=Object.defineProperty;var De=(i,s,e)=>s in i?Me(i,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[s]=e;var m=(i,s,e)=>De(i,typeof s!="symbol"?s+"":s,e);import{x as Ne,J as oe,Z as ce,ai as q,ar as Ce}from"./D0VMf2Fp.js";import{b_ as Le,c_ as le,cq as ue,cp as ve}from"./B0JbhmMb.js";import{IX as p,BG as we,bD as be,e as Fe,L0 as de,ie as me,bP as ke,DB as z,C3 as Ge,fc as Pe,A9 as xe,dZ as Ee,f8 as fe,dY as _e,AE as Ve,KG as Ue,wd as Be}from"./BkzMrEqG.js";import{aC as Ae,dH as he,A as H,P as ge,ay as K}from"./BEyxbMng.js";import{h as $e}from"./jhNNYE0v.js";import{c as W}from"./ChTqQfQN.js";import{a as Xe}from"./BdWqymET.js";import{m as Q}from"./BbV7MtxC.js";import"./CJxGDkBm.js";import{bm as n}from"./AeC4KVgG.js";import"./DrHJ7oPv.js";import"./Dp2nUoTL.js";import"./BNODdf6r.js";import{R as Re}from"./B5aYN90J.js";import{L as Ye}from"./CSiaiLHL.js";function We(i,s){return i.some(e=>e.id===s.id)?i.map(e=>e.id===s.id?{...s,...s.author==null&&e.author!==void 0?{author:e.author}:{}}:e):[...i,s]}const Z=typeof performance<"u"?performance:{now:()=>Date.now()},V=new Xe("PerformanceOptimizer"),w=class w{constructor(){m(this,"metricsBuffer");m(this,"metricsIndex",0);m(this,"metricsCount",0);m(this,"MAX_METRICS",500);m(this,"TARGET_RESPONSE_TIME",100);m(this,"memoCache",new Map);m(this,"MEMO_TTL",6e4);m(this,"MAX_CACHE_SIZE",100);m(this,"cacheHits",0);m(this,"cacheMisses",0);m(this,"pendingRequests",new Map);m(this,"requestQueue",[]);m(this,"cleanupInterval",null);this.metricsBuffer=new Array(this.MAX_METRICS).fill(null),this.startCacheCleanup(),V.info("PerformanceOptimizer initialized")}static getInstance(){return w.instance||(w.instance=new w),w.instance}reset(){this.metricsBuffer=new Array(this.MAX_METRICS).fill(null),this.metricsIndex=0,this.metricsCount=0,this.memoCache.clear(),this.pendingRequests.clear(),this.requestQueue=[],this.cacheHits=0,this.cacheMisses=0}clearCache(){this.memoCache.clear(),this.cacheHits=0,this.cacheMisses=0}async processBatch(s,e,t={}){const{batchSize:r=10,concurrency:a=4}=t,l=[];for(let c=0;c<s.length;c+=r){const f=s.slice(c,c+r).map((o,R)=>{const g=Math.floor(R/a)*10;return new Promise(d=>{setTimeout(async()=>{const k=await e(o);d(k)},g)})}),u=await Promise.all(f);l.push(...u)}return l}startCacheCleanup(){this.cleanupInterval=setInterval(()=>{this.cleanupCache()},3e4)}stopCacheCleanup(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null)}cleanupCache(){const s=Date.now(),e=[];this.memoCache.forEach((t,r)=>{s-t.timestamp>this.MEMO_TTL&&e.push(r)}),e.forEach(t=>this.memoCache.delete(t)),this.memoCache.size>this.MAX_CACHE_SIZE&&Array.from(this.memoCache.entries()).sort((a,l)=>a[1].hits-l[1].hits||a[1].timestamp-l[1].timestamp).slice(0,this.memoCache.size-this.MAX_CACHE_SIZE).forEach(([a])=>this.memoCache.delete(a))}async track(s,e,t={}){const r=Z.now();try{const a=t.cacheKey||s;if(t.memoize){const f=this.getMemoized(a);if(f!==void 0)return this.cacheHits++,V.debug("Memoized result used",{operation:s,cacheKey:a,hits:this.cacheHits}),f;this.cacheMisses++}if(t.coalesce){const f=this.pendingRequests.get(s);if(f)return V.debug("Request coalesced",{operation:s}),f}let l;t.coalesce?(l=t.timeout?this.withTimeout(e(),t.timeout):e(),this.pendingRequests.set(s,l)):l=t.timeout?this.withTimeout(e(),t.timeout):e();const c=await l;t.memoize&&this.memoize(a,c);const E=Z.now()-r;return this.recordMetric(s,E,!0,{strategy:t.priority||"normal",memoized:t.memoize||!1,coalesced:t.coalesce||!1}),E>this.TARGET_RESPONSE_TIME&&V.warn("Operation exceeded target time",{operation:s,duration:Math.round(E),target:this.TARGET_RESPONSE_TIME}),c}catch(a){const l=Z.now()-r;throw this.recordMetric(s,l,!1,{error:a instanceof Error?a.message:"Unknown error"}),a}finally{t.coalesce&&this.pendingRequests.delete(s)}}getStats(){if(this.metricsCount===0)return{avgResponseTime:0,p95ResponseTime:0,p99ResponseTime:0,successRate:100,slowOperations:[]};const s=[],e=this.metricsCount<this.MAX_METRICS?0:this.metricsIndex;for(let u=0;u<this.metricsCount;u++){const o=this.metricsBuffer[(e+u)%this.MAX_METRICS];o&&s.push(o)}if(s.length===0)return{avgResponseTime:0,p95ResponseTime:0,p99ResponseTime:0,successRate:100,slowOperations:[]};const t=s.sort((u,o)=>u.duration-o.duration);let r=0,a=0;const l=new Set;for(const u of s)a+=u.duration,u.success&&r++,u.duration>this.TARGET_RESPONSE_TIME&&l.add(u.operation);const c=a/s.length,E=Math.floor(t.length*.95),f=Math.floor(t.length*.99);return{avgResponseTime:Math.round(c),p95ResponseTime:Math.round(t[E]?.duration||0),p99ResponseTime:Math.round(t[f]?.duration||0),successRate:r/s.length*100,slowOperations:Array.from(l)}}getCacheStats(){const s=this.cacheHits+this.cacheMisses;return{size:this.memoCache.size,hitRate:s>0?this.cacheHits/s*100:0,hits:this.cacheHits,misses:this.cacheMisses}}getMemoized(s){const e=this.memoCache.get(s);if(e){if(Date.now()-e.timestamp>this.MEMO_TTL){this.memoCache.delete(s);return}return e.hits++,e.value}}memoize(s,e){const t=JSON.stringify(e).length;this.memoCache.set(s,{value:e,timestamp:Date.now(),hits:0,size:t}),this.memoCache.size>this.MAX_CACHE_SIZE&&this.cleanupCache()}async withTimeout(s,e){return Promise.race([s,new Promise((t,r)=>setTimeout(()=>r(new Error(`Operation timed out after ${e}ms`)),e))])}recordMetric(s,e,t,r){this.metricsBuffer[this.metricsIndex]={operation:s,duration:e,timestamp:Date.now(),success:t,metadata:r},this.metricsIndex=(this.metricsIndex+1)%this.MAX_METRICS,this.metricsCount<this.MAX_METRICS&&this.metricsCount++,e>this.TARGET_RESPONSE_TIME&&V.warn("Slow operation detected",{operation:s,duration:`${e.toFixed(2)}ms`,target:`${this.TARGET_RESPONSE_TIME}ms`,metadata:r})}};m(w,"instance");let ee=w;const qe=ee.getInstance(),pe={AGENT_CREATION:"https://docs.example.com/agent-creation",STREAMING:"https://docs.example.com/streaming-issues",STORAGE:"https://docs.example.com/storage-troubleshooting",MEMORY:"https://docs.example.com/memory-management",PROVIDER:"https://docs.example.com/provider-setup",GENERAL:"https://docs.example.com/help"},j={get AGENT_CREATION_FAILED(){return n.errors_catalog_agentCreationFailed_template({agentName:"{agentName}",details:"{details}"})},get AGENT_ALREADY_EXISTS(){return n.errors_catalog_agentAlreadyExists_template({agentName:"{agentName}"})},get INVALID_AGENT_CONFIG(){return n.errors_catalog_invalidAgentConfig_template({details:"{details}"})},get INVALID_CONFIG(){return n.errors_catalog_invalidConfig_template({details:"{details}"})},get SESSION_NOT_FOUND(){return n.errors_catalog_sessionNotFound_template({sessionId:"{sessionId}"})},get SESSION_ALREADY_ACTIVE(){return n.errors_catalog_sessionAlreadyActive_template()},get SESSION_INITIALIZATION_FAILED(){return n.errors_catalog_sessionInitializationFailed_template({details:"{details}"})},get STREAM_CONNECTION_FAILED(){return n.errors_catalog_streamConnectionFailed_template({details:"{details}"})},get STREAM_TIMEOUT(){return n.errors_catalog_streamTimeout_template({timeout:"{timeout}"})},get STREAM_INTERRUPTED(){return n.errors_catalog_streamInterrupted_template({attempt:"{attempt}",maxAttempts:"{maxAttempts}"})},get STREAM_RECOVERY_FAILED(){return n.errors_catalog_streamRecoveryFailed_template({attempts:"{attempts}"})},get MESSAGE_SEND_FAILED(){return n.errors_catalog_messageSendFailed_template({details:"{details}"})},get MESSAGE_VALIDATION_FAILED(){return n.errors_catalog_messageValidationFailed_template({details:"{details}"})},get MESSAGE_TOO_LONG(){return n.errors_catalog_messageTooLong_template({maxLength:"{maxLength}",currentLength:"{currentLength}"})},get PROVIDER_NOT_FOUND(){return n.errors_catalog_providerNotFound_template({provider:"{provider}"})},get PROVIDER_CONNECTION_FAILED(){return n.errors_catalog_providerConnectionFailed_template({provider:"{provider}",details:"{details}"})},get PROVIDER_PROCESS_DIED(){return n.errors_catalog_providerProcessDied_template({provider:"{provider}"})},get STORAGE_READ_FAILED(){return n.errors_catalog_storageReadFailed_template({details:"{details}"})},get STORAGE_WRITE_FAILED(){return n.errors_catalog_storageWriteFailed_template({details:"{details}"})},get STORAGE_CORRUPTED(){return n.errors_catalog_storageCorrupted_template({lastBackup:"{lastBackup}"})},get MEMORY_LIMIT_EXCEEDED(){return n.errors_catalog_memoryLimitExceeded_template({currentUsage:"{currentUsage}",limit:"{limit}"})},get RATE_LIMIT_EXCEEDED(){return n.errors_catalog_rateLimitExceeded_template({count:"{count}",window:"{window}"})},get CONCURRENT_LIMIT_EXCEEDED(){return n.errors_catalog_concurrentLimitExceeded_template({current:"{current}",max:"{max}"})}},ze={get AGENT_CREATION_FAILED(){return n.errors_catalog_agentCreationFailed_friendly()},get AGENT_ALREADY_EXISTS(){return n.errors_catalog_agentAlreadyExists_friendly()},get INVALID_AGENT_CONFIG(){return n.errors_catalog_invalidAgentConfig_friendly()},get INVALID_CONFIG(){return n.errors_catalog_invalidConfig_friendly()},get SESSION_NOT_FOUND(){return n.errors_catalog_sessionNotFound_friendly()},get SESSION_ALREADY_ACTIVE(){return n.errors_catalog_sessionAlreadyActive_friendly()},get SESSION_INITIALIZATION_FAILED(){return n.errors_catalog_sessionInitializationFailed_friendly()},get STREAM_CONNECTION_FAILED(){return n.errors_catalog_streamConnectionFailed_friendly()},get STREAM_TIMEOUT(){return n.errors_catalog_streamTimeout_friendly()},get STREAM_INTERRUPTED(){return n.errors_catalog_streamInterrupted_friendly()},get STREAM_RECOVERY_FAILED(){return n.errors_catalog_streamRecoveryFailed_friendly()},get MESSAGE_SEND_FAILED(){return n.errors_catalog_messageSendFailed_friendly()},get MESSAGE_VALIDATION_FAILED(){return n.errors_catalog_messageValidationFailed_friendly()},get MESSAGE_TOO_LONG(){return n.errors_catalog_messageTooLong_friendly()},get PROVIDER_NOT_FOUND(){return n.errors_catalog_providerNotFound_friendly()},get PROVIDER_CONNECTION_FAILED(){return n.errors_catalog_providerConnectionFailed_friendly()},get PROVIDER_PROCESS_DIED(){return n.errors_catalog_providerProcessDied_friendly()},get STORAGE_READ_FAILED(){return n.errors_catalog_storageReadFailed_friendly()},get STORAGE_WRITE_FAILED(){return n.errors_catalog_storageWriteFailed_friendly()},get STORAGE_CORRUPTED(){return n.errors_catalog_storageCorrupted_friendly()},get MEMORY_LIMIT_EXCEEDED(){return n.errors_catalog_memoryLimitExceeded_friendly()},get RATE_LIMIT_EXCEEDED(){return n.errors_catalog_rateLimitExceeded_friendly()},get CONCURRENT_LIMIT_EXCEEDED(){return n.errors_catalog_concurrentLimitExceeded_friendly()}};function He(i){return(i.match(/{(\w+)}/g)||[]).map(e=>e.slice(1,-1))}function Ke(i,s){return He(i).every(t=>t in s)}function Ie(i,s={}){return i.replace(/{(\w+)}/g,(e,t)=>String(s[t]??e))}function J(i){const s=n.errors_cleanMessage_fallback_error();if(!i)return s;let e=i;return e=e.replace(/^.*?failed(?:\s+to\s+.*?)?\s+after\s+\d+\s+attempts:\s*/i,""),e=e.replace(/^Error invoking remote method '[^']+':(\s*Error:)?\s*/i,""),e=e.replace(/^(Error:\s*)+/i,""),e=e.replace(/\n\s*at .+/g,""),e=e.replace(/\s+/g," ").trim(),e||s}function Qe(i,s){return s&&j[i]&&Ke(j[i],s)?Ie(j[i],s):ze[i]||n.errors_userFriendly_fallback_error()}function Ze(i){const e={AGENT_CREATION_FAILED:"AGENT_CREATION",AGENT_ALREADY_EXISTS:"AGENT_CREATION",INVALID_AGENT_CONFIG:"AGENT_CREATION",STREAM_CONNECTION_FAILED:"STREAMING",STREAM_TIMEOUT:"STREAMING",STREAM_INTERRUPTED:"STREAMING",STREAM_RECOVERY_FAILED:"STREAMING",STORAGE_READ_FAILED:"STORAGE",STORAGE_WRITE_FAILED:"STORAGE",STORAGE_CORRUPTED:"STORAGE",MEMORY_LIMIT_EXCEEDED:"MEMORY",RATE_LIMIT_EXCEEDED:"MEMORY",CONCURRENT_LIMIT_EXCEEDED:"MEMORY",PROVIDER_NOT_FOUND:"PROVIDER",PROVIDER_CONNECTION_FAILED:"PROVIDER",PROVIDER_PROCESS_DIED:"PROVIDER"}[i];return e?pe[e]:pe.GENERAL}const je={AGENT_CREATION_FAILED:[{action:"retry",description:"Try creating the agent again",automatic:!1,priority:"high"},{action:"check-config",description:"Verify agent configuration in settings",automatic:!1,priority:"high"},{action:"check-resources",description:"Ensure sufficient memory and disk space",automatic:!1,priority:"medium"}],AGENT_ALREADY_EXISTS:[{action:"rename",description:"Choose a different name for the agent",automatic:!1,priority:"high"},{action:"delete-existing",description:"Delete the existing agent first",automatic:!1,priority:"medium"}],INVALID_AGENT_CONFIG:[{action:"review-config",description:"Review and correct the configuration",automatic:!1,priority:"high"},{action:"use-defaults",description:"Reset to default configuration",automatic:!1,priority:"medium"}],INVALID_CONFIG:[{action:"review-config",description:"Review and correct the configuration",automatic:!1,priority:"high"},{action:"use-defaults",description:"Reset to default configuration",automatic:!1,priority:"medium"}],SESSION_NOT_FOUND:[{action:"start-new",description:"Start a new agent session",automatic:!1,priority:"high"},{action:"check-history",description:"Check session history for recent sessions",automatic:!1,priority:"medium"}],SESSION_ALREADY_ACTIVE:[{action:"wait",description:"Wait for the current session to complete",automatic:!1,priority:"high"},{action:"cancel",description:"Cancel the active session first",automatic:!1,priority:"high"}],SESSION_INITIALIZATION_FAILED:[{action:"retry",description:"Try initializing the session again",automatic:!1,priority:"high"},{action:"check-resources",description:"Ensure sufficient resources are available",automatic:!1,priority:"medium"}],MESSAGE_SEND_FAILED:[{action:"retry",description:"Try sending the message again",automatic:!1,priority:"high"},{action:"check-connection",description:"Check your network connection",automatic:!1,priority:"high"}],MESSAGE_VALIDATION_FAILED:[{action:"review-config",description:"Review and correct the message format",automatic:!1,priority:"high"},{action:"check-config",description:"Check configuration for valid message format",automatic:!1,priority:"medium"}],MESSAGE_TOO_LONG:[{action:"retry",description:"Shorten the message and try again",automatic:!1,priority:"high"},{action:"batch",description:"Split the message into multiple parts",automatic:!1,priority:"medium"}],PROVIDER_NOT_FOUND:[{action:"check-config",description:"Verify provider is properly configured",automatic:!1,priority:"high"},{action:"recreate",description:"Install or reinstall the provider",automatic:!1,priority:"high"}],PROVIDER_CONNECTION_FAILED:[{action:"retry",description:"Try connecting to the provider again",automatic:!1,priority:"high"},{action:"check-config",description:"Verify provider configuration",automatic:!1,priority:"high"}],STORAGE_READ_FAILED:[{action:"retry",description:"Try reading the data again",automatic:!1,priority:"high"},{action:"restore",description:"Restore from a recent backup",automatic:!1,priority:"medium"}],STORAGE_WRITE_FAILED:[{action:"retry",description:"Try saving again",automatic:!1,priority:"high"},{action:"check-resources",description:"Check available disk space",automatic:!1,priority:"high"}],STREAM_CONNECTION_FAILED:[{action:"retry",description:"Try connecting again",automatic:!1,priority:"high"},{action:"check-connection",description:"Check your network connection",automatic:!1,priority:"high"}],STREAM_RECOVERY_FAILED:[{action:"restart",description:"Restart the agent",automatic:!1,priority:"high"},{action:"check-config",description:"Check error logs for more details",automatic:!1,priority:"medium"}],STREAM_INTERRUPTED:[{action:"reconnect",description:"Attempting automatic reconnection",automatic:!0,priority:"high"},{action:"retry",description:"Retry sending the message",automatic:!1,priority:"high"},{action:"check-connection",description:"Check your internet connection",automatic:!1,priority:"medium"}],STREAM_TIMEOUT:[{action:"wait",description:"Wait for agent to complete processing",automatic:!1,priority:"high"},{action:"cancel",description:"Cancel current operation",automatic:!1,priority:"medium"},{action:"increase-timeout",description:"Increase timeout in settings",automatic:!1,priority:"low"}],PROVIDER_PROCESS_DIED:[{action:"restart",description:"Restart agent process",automatic:!0,priority:"high"},{action:"recreate",description:"Create new agent session",automatic:!1,priority:"high"}],STORAGE_CORRUPTED:[{action:"restore",description:"Restore from backup",automatic:!1,priority:"high"},{action:"reset",description:"Reset agent data",automatic:!1,priority:"medium"}],MEMORY_LIMIT_EXCEEDED:[{action:"cleanup",description:"Close unused agents",automatic:!1,priority:"high"},{action:"increase-limit",description:"Increase memory limit in settings",automatic:!1,priority:"medium"}],RATE_LIMIT_EXCEEDED:[{action:"wait",description:"Wait before making more requests",automatic:!1,priority:"high"},{action:"batch",description:"Batch requests together",automatic:!1,priority:"medium"}],CONCURRENT_LIMIT_EXCEEDED:[{action:"close-agents",description:"Close some running agents",automatic:!1,priority:"high"},{action:"queue",description:"Queue operation for later",automatic:!1,priority:"medium"}]};function Je(i){return je[i]||[{action:"retry",description:"Try the operation again",automatic:!1,priority:"high"}]}var D=(i=>(i.AGENT_CREATION_FAILED="AGENT_CREATION_FAILED",i.AGENT_ALREADY_EXISTS="AGENT_ALREADY_EXISTS",i.INVALID_AGENT_CONFIG="INVALID_AGENT_CONFIG",i.INVALID_CONFIG="INVALID_CONFIG",i.SESSION_NOT_FOUND="SESSION_NOT_FOUND",i.SESSION_ALREADY_ACTIVE="SESSION_ALREADY_ACTIVE",i.SESSION_INITIALIZATION_FAILED="SESSION_INITIALIZATION_FAILED",i.STREAM_CONNECTION_FAILED="STREAM_CONNECTION_FAILED",i.STREAM_TIMEOUT="STREAM_TIMEOUT",i.STREAM_INTERRUPTED="STREAM_INTERRUPTED",i.STREAM_RECOVERY_FAILED="STREAM_RECOVERY_FAILED",i.MESSAGE_SEND_FAILED="MESSAGE_SEND_FAILED",i.MESSAGE_VALIDATION_FAILED="MESSAGE_VALIDATION_FAILED",i.MESSAGE_TOO_LONG="MESSAGE_TOO_LONG",i.PROVIDER_NOT_FOUND="PROVIDER_NOT_FOUND",i.PROVIDER_CONNECTION_FAILED="PROVIDER_CONNECTION_FAILED",i.PROVIDER_PROCESS_DIED="PROVIDER_PROCESS_DIED",i.PROVIDER_UNAVAILABLE="PROVIDER_UNAVAILABLE",i.PROVIDER_ERROR="PROVIDER_ERROR",i.STORAGE_READ_FAILED="STORAGE_READ_FAILED",i.STORAGE_WRITE_FAILED="STORAGE_WRITE_FAILED",i.STORAGE_CORRUPTED="STORAGE_CORRUPTED",i.STORAGE_ERROR="STORAGE_ERROR",i.STORAGE_QUOTA_EXCEEDED="STORAGE_QUOTA_EXCEEDED",i.MEMORY_LIMIT_EXCEEDED="MEMORY_LIMIT_EXCEEDED",i.RATE_LIMIT_EXCEEDED="RATE_LIMIT_EXCEEDED",i.CONCURRENT_LIMIT_EXCEEDED="CONCURRENT_LIMIT_EXCEEDED",i.RESOURCE_NOT_FOUND="RESOURCE_NOT_FOUND",i.RESOURCE_EXHAUSTED="RESOURCE_EXHAUSTED",i.NETWORK_ERROR="NETWORK_ERROR",i.PERMISSION_DENIED="PERMISSION_DENIED",i.OPERATION_FAILED="OPERATION_FAILED",i.VALIDATION_ERROR="VALIDATION_ERROR",i.INVALID_RESPONSE="INVALID_RESPONSE",i.STATE_CORRUPTION="STATE_CORRUPTION",i.CONTEXT_OVERFLOW="CONTEXT_OVERFLOW",i))(D||{});class Y extends Error{constructor(e,t,r={},a){super(e);m(this,"code");m(this,"context");m(this,"recoverySuggestions");m(this,"userMessage");m(this,"isRecoverable");m(this,"cause");this.name="AgentError",this.code=t,this.context={...r,timestamp:new Date,stackTrace:this.stack},this.userMessage=a?.userMessage||this.getDefaultUserMessage(t),this.recoverySuggestions=a?.recoverySuggestions||this.getDefaultRecoverySuggestions(t),this.isRecoverable=a?.isRecoverable??this.isErrorRecoverable(t),a?.cause&&(this.cause=a.cause)}getDefaultUserMessage(e){return Qe(e,this.context)}getDefaultRecoverySuggestions(e){return Je(e)}isErrorRecoverable(e){return["STREAM_INTERRUPTED","STREAM_TIMEOUT","MESSAGE_SEND_FAILED","PROVIDER_PROCESS_DIED","STORAGE_READ_FAILED","STORAGE_WRITE_FAILED"].includes(e)}getHelpLink(){return Ze(this.code)}formatMessage(e){return Ie(e,this.context)}toJSON(){return{name:this.name,code:this.code,message:this.message,userMessage:this.userMessage,context:this.context,recoverySuggestions:this.recoverySuggestions,isRecoverable:this.isRecoverable,helpLink:this.getHelpLink(),stack:this.stack}}}const et={NON_RETRYABLE_ERRORS:["EACCES","EPERM","ENOSPC","EMFILE","permission","memory","fatal","process died","not available on your current plan","agent binary","rate limit","too many requests","hit your limit","you've hit your limit","quota exceeded"]};function ie(i){const s=i.toLowerCase();for(const e of et.NON_RETRYABLE_ERRORS)if(s.includes(e.toLowerCase()))return!0;return!1}const tt="Agent already has an in-flight prompt. Message was not delivered.",v=W("ErrorBoundary"),b=class b{constructor(){}static getInstance(){return b.instance||(b.instance=new b),b.instance}async wrap(s,e,t={}){const{retries:r=Re.DEFAULT_ATTEMPTS,retryDelay:a=Re.BASE_DELAY,exponentialBackoff:l=!0,notify:c=!1,notifyOnRetry:E=!1,context:f={},onError:u,onRetry:o,shouldRetry:R=this.defaultShouldRetry}=t;let g=null,d=0;for(d=1;d<=r+1;d++)try{v.debug(`[${e}] Attempt ${d}/${r+1}`);const h=await s();return d>1&&v.info(`[${e}] Succeeded after ${d} attempts`),h}catch(h){if(g=h,v.error(`[${e}] Attempt ${d} failed`,{error:g.message,attempt:d,maxAttempts:r+1,context:f}),u?.(g,d),d<=r&&R(g)){const C=l?a*Math.pow(2,d-1):a;E&&Q.warning(n.agent_errorBoundary_retrying_message({seconds:C/1e3})),o?.(d),v.info(`[${e}] Retrying in ${C}ms`),await this.sleep(C)}else break}const k=`${e} failed after ${d} attempt${d===1?"":"s"}: ${g?.message}`,P=J(g?.message||n.agent_errorBoundary_generic_error()),N=g?.message?.toLowerCase()||"",$=N.includes("no available models")||N.includes("all models exhausted")||N.includes("all models unavailable");throw c&&!$&&Q.error(P),new Y(P,D.OPERATION_FAILED,{originalError:g?.message,detailedMessage:k,attempts:d,context:f})}async wrapVoid(s,e,t={}){await this.wrap(s,e,t)}wrapSync(s,e,t={}){try{return s()}catch(r){const a=r;throw v.error(`[${e}] Failed`,{error:a.message,context:t.context}),t.notify&&Q.error(J(a.message)),new Y(J(a.message),D.OPERATION_FAILED,t.context)}}defaultShouldRetry(s){const e=s.message.toLowerCase();return ie(s.message)?!1:e.includes("network")||e.includes("timeout")?!0:s instanceof Y?[D.NETWORK_ERROR,D.STREAM_TIMEOUT,D.STREAM_CONNECTION_FAILED,D.PROVIDER_CONNECTION_FAILED,D.PROVIDER_UNAVAILABLE].includes(s.code):!(e.includes("invalid")||e.includes("interrupted")||e.includes("cancel")||e.includes("not found")||e.includes("not available")||e.includes("404")||e.includes("no available models")||e.includes("all models exhausted")||e.includes("all models unavailable")||e.includes("413")||e.includes("too long for the agent")||e.includes("request entity too large")||e.includes("payload too large")||e.includes("content too large")||e.includes("body too large")||e.includes("unauthorized")||e.includes("forbidden")||e.includes("401")||e.includes("403"))}sleep(s){return new Promise(e=>setTimeout(e,s))}async withTimeout(s,e,t){return Promise.race([s(),new Promise((r,a)=>setTimeout(()=>a(new Y(`${t} timed out after ${e}ms`,D.STREAM_TIMEOUT)),e))])}async batchOperations(s,e,t={}){const{concurrency:r=5,continueOnError:a=!0,operationName:l="batch operation"}=t,c=[],E=[];for(let f=0;f<s.length;f+=r){const u=s.slice(f,f+r);(await Promise.allSettled(u.map(R=>e(R)))).forEach((R,g)=>{if(R.status==="fulfilled")c.push(R.value);else{const d=R.reason;if(E.push({item:u[g],error:d}),v.error(`[${l}] Batch item failed`,{item:u[g],error:d.message}),!a)throw d}})}return E.length>0&&v.warn(`[${l}] Completed with ${E.length} errors`),{results:c,errors:E}}};m(b,"instance");let te=b;const st=te.getInstance(),se=W("browser/index"),F=new Map,B=new Map;let U;function it(i,s,e){for(const t of s)try{t(e)}catch(r){se.error("Error in agent subscriber callback",{agentId:i,error:r})}}function rt(){if(U)return;let i=!1;U=p.createSelector(e=>e.agentSessions)().subscribe(()=>{if(!i){i=!0;return}if(F.size===0)return;const e=p.state;for(const[t,r]of F){const a=Ae.select(e,t);B.get(t)!==a&&(B.set(t,a),it(t,r,a))}})}function at(){F.size>0||!U||(U(),U=void 0,B.clear())}function Ct(i,s,e){let t=F.get(i);const r=!t;t||(t=new Set,F.set(i,t)),t.add(s),rt();const a=p.state,l=Ae.select(a,i);return r&&B.set(i,l),l?se.debug("[subscribeToAgent] Initial callback data",{agentId:i,workspaceId:e??"current",hasSession:!0}):se.debug("[subscribeToAgent] No session found",{agentId:i,workspaceId:e??"current"}),s(l),()=>{const c=F.get(i);c&&(c.delete(s),c.size===0&&(F.delete(i),B.delete(i))),at()}}const y=W("ErrorRecovery"),Se={network:{maxRetries:3,initialBackoffMs:1e3,maxBackoffMs:1e4,backoffMultiplier:2,shouldRetry:i=>{const s=i.message.toLowerCase();return s.includes("network")||s.includes("fetch")||s.includes("connection")||s.includes("timeout")}},streaming:{maxRetries:5,initialBackoffMs:500,maxBackoffMs:5e3,backoffMultiplier:1.5,shouldRetry:(i,s)=>{if(s>=5)return!1;const e=i.message.toLowerCase();return e.includes("no available models")||e.includes("all models exhausted")||e.includes("all models unavailable")||ie(i.message)?!1:e.includes("stream")||e.includes("chunk")||e.includes("incomplete")}},persistence:{maxRetries:2,initialBackoffMs:100,maxBackoffMs:1e3,backoffMultiplier:2,shouldRetry:i=>{const s=i.message.toLowerCase();return s.includes("save")||s.includes("write")||s.includes("persist")}},rateLimit:{maxRetries:3,initialBackoffMs:5e3,maxBackoffMs:3e4,backoffMultiplier:2,shouldRetry:i=>{const s=i.message.toLowerCase();return s.includes("rate")||s.includes("limit")||s.includes("429")}}};class nt{constructor(){m(this,"listeners",new Map)}on(s,e){let t=this.listeners.get(s);t||(t=new Set,this.listeners.set(s,t)),t.add(e)}off(s,e){this.listeners.get(s)?.delete(e)}emit(s,...e){this.listeners.get(s)?.forEach(t=>{try{t(...e)}catch(r){y.error(`Error in event listener for ${s}:`,r)}})}removeAllListeners(){this.listeners.clear()}}class ot extends nt{constructor(){super(...arguments);m(this,"activeRecoveries",new Map);m(this,"recoveryStats",new Map)}async executeWithRecovery(e,t=Se.network,r){const a=Date.now(),l=new AbortController;r&&(this.cancelRecovery(r),this.activeRecoveries.set(r,l));let c,E=t.initialBackoffMs,f=0;for(let u=1;u<=t.maxRetries;u++){if(f=u,l.signal.aborted){y.info(`Recovery cancelled for operation ${r}`);break}try{y.debug(`Attempting operation (attempt ${u}/${t.maxRetries})`,{operationId:r});const o=await e();return this.updateStats(r,!0),this.emit("recovery:success",{operationId:r,attempt:u,duration:Date.now()-a}),r&&this.activeRecoveries.delete(r),{success:!0,data:o,attempts:u,totalTime:Date.now()-a}}catch(o){c=o,y.warn(`Operation failed (attempt ${u}/${t.maxRetries})`,{operationId:r,error:c.message});const R=c.message.toLowerCase();if(R.includes("interrupted")||R.includes("cancelled")||R.includes("canceled")){y.debug("User-initiated interruption/cancellation, not retrying",{operationId:r,error:c.message});break}if(R.includes("no available models")||R.includes("all models exhausted")||R.includes("all models unavailable")){y.debug("All models exhausted, not retrying",{operationId:r,error:c.message});break}if(ie(c.message)){y.debug("Fatal error detected, not retrying",{operationId:r,error:c.message});break}if(!t.shouldRetry(c,u)){y.debug("Error not retryable, stopping recovery",{operationId:r,error:c.message});break}if(u<t.maxRetries){const g=Math.random()*.2*E,d=Math.min(E+g,t.maxBackoffMs);t.onRetry?.(u,d),this.emit("recovery:retry",{operationId:r,attempt:u,delay:d,error:c.message}),await this.delay(d,l.signal),E=Math.min(E*t.backoffMultiplier,t.maxBackoffMs)}}}return this.updateStats(r,!1),t.onFailure?.(c,f),this.emit("recovery:failure",{operationId:r,attempts:f,duration:Date.now()-a,error:c?.message}),r&&this.activeRecoveries.delete(r),{success:!1,error:c,attempts:f,totalTime:Date.now()-a}}cancelRecovery(e){const t=this.activeRecoveries.get(e);t&&(t.abort(),this.activeRecoveries.delete(e),y.info(`Cancelled recovery for operation ${e}`))}cancelAllRecoveries(){for(const[e,t]of this.activeRecoveries)t.abort(),y.info(`Cancelled recovery for operation ${e}`);this.activeRecoveries.clear()}getStats(e){if(e)return this.recoveryStats.get(e)||{successes:0,failures:0};const t={};for(const[r,a]of this.recoveryStats)t[r]=a;return t}clearStats(e){e?this.recoveryStats.delete(e):this.recoveryStats.clear()}isRetryable(e,t){const r=e.message.toLowerCase();if(t)switch(t){case"NETWORK":return r.includes("network")||r.includes("fetch");case"TIMEOUT":return r.includes("timeout")||r.includes("timed out");case"RATE_LIMIT":return r.includes("rate")||r.includes("limit")||r.includes("429");case"TEMPORARY":return r.includes("temporary")||r.includes("transient");case"CONFLICT":return r.includes("conflict")||r.includes("concurrent");default:return!1}return this.isRetryable(e,"NETWORK")||this.isRetryable(e,"TIMEOUT")||this.isRetryable(e,"RATE_LIMIT")||this.isRetryable(e,"TEMPORARY")||this.isRetryable(e,"CONFLICT")}delay(e,t){return new Promise((r,a)=>{const l=setTimeout(r,e);if(t){const c=()=>{clearTimeout(l),a(new Error("Delay aborted"))};t.addEventListener("abort",c);const E=r;r=()=>{t.removeEventListener("abort",c),E()}}})}updateStats(e,t){if(!e)return;const r=this.recoveryStats.get(e)||{successes:0,failures:0};t?r.successes++:r.failures++,this.recoveryStats.set(e,r)}dispose(){this.cancelAllRecoveries(),this.recoveryStats.clear(),this.removeAllListeners()}}const ct=new ot,O=new Ye({category:"WorkspaceMetrics"}),lt=100;class ut{constructor(){m(this,"metrics",new Map);m(this,"operations",new Map)}startWorkspaceCreation(s){const e=Date.now();for(this.metrics.delete(s),this.metrics.set(s,{workspaceId:s,creationStarted:e});this.metrics.size>lt;){const t=this.metrics.keys().next().value;if(t===void 0)break;this.metrics.delete(t)}O.info("Started tracking workspace creation",{workspaceId:s})}recordMilestone(s,e){const t=this.metrics.get(s);if(!t){O.warn("No metrics found for workspace",{workspaceId:s,milestone:e});return}const r=Date.now();switch(e){case"optimisticNavigation":t.optimisticNavigation=r;break;case"realWorkspaceCreated":t.realWorkspaceCreated=r;break;case"agentCreated":t.agentCreated=r;break;case"agentReady":t.agentReady=r;break;case"firstMessageSent":t.firstMessageSent=r;break;case"firstResponseReceived":t.firstResponseReceived=r;break;case"firstChunkReceived":t.firstChunkReceived=r;break;case"totalDuration":t.totalDuration=r;break;case"workspaceId":case"creationStarted":O.warn("Cannot update milestone",{milestone:e});return}const a=r-t.creationStarted;O.info(`Milestone: ${e}`,{workspaceId:s,elapsed:`${a}ms`,timestamp:r}),e==="firstResponseReceived"&&(t.totalDuration=r-t.creationStarted,this.logSummary(s))}startOperation(s,e){this.operations.set(s,{startTime:Date.now(),metadata:e})}endOperation(s,e){const t=this.operations.get(s);if(!t)return O.warn("Operation not found",{operationId:s}),null;const r=Date.now();return t.endTime=r,t.duration=r-t.startTime,e&&(t.metadata={...t.metadata,...e}),O.info("Operation completed",{operationId:s,duration:`${t.duration}ms`,metadata:t.metadata}),this.operations.delete(s),t.duration}getMetrics(s){return this.metrics.get(s)}logSummary(s){const e=this.metrics.get(s);if(!e)return;const t={workspaceId:s,totalDuration:`${e.totalDuration}ms`,stages:{optimisticNavigation:e.optimisticNavigation?`${e.optimisticNavigation-e.creationStarted}ms`:"N/A",realWorkspaceCreation:e.realWorkspaceCreated?`${e.realWorkspaceCreated-e.creationStarted}ms`:"N/A",agentCreation:e.agentCreated?`${e.agentCreated-e.creationStarted}ms`:"N/A",agentReady:e.agentReady?`${e.agentReady-e.creationStarted}ms`:"N/A",firstMessage:e.firstMessageSent?`${e.firstMessageSent-e.creationStarted}ms`:"N/A",firstResponse:e.firstResponseReceived?`${e.firstResponseReceived-e.creationStarted}ms`:"N/A"}};O.info("=== Workspace Creation Metrics Summary ===",t),O.info("Workspace Creation Metrics:",t)}clearMetrics(s){this.metrics.delete(s)}incrementAgentCreated(s){const e=this.metrics.get(s);e&&(e.agentCreated=Date.now(),O.info("Agent created",{workspaceId:s}))}incrementMessageSent(s){const e=this.metrics.get(s);e&&!e.firstMessageSent&&(e.firstMessageSent=Date.now(),O.info("First message sent",{workspaceId:s}))}}const dt=new ut,M=W("AgentSend");function A(i){p.dispatch(i)}function Te(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function mt(i){const s=Te(i)&&i.success===!0&&"data"in i?i.data:i;return!Te(s)||s.success!==!1?!1:typeof s.error=="string"&&s.error.includes(tt)}async function Lt(i,s,e,t={}){const r=he.select(p.state,e.id);if(!r)return;const a=Ne(i,e.id),l=t.submission,c=!!l&&Le.select(p.state,l.scope)?.supported===!0,E=(o,R,g=!1)=>{l&&A(Be(l.scope,l.id,o,Date.now(),R,g))};let f=!1;const u=()=>(!l||f||ve.select(p.state,l))&&r===he.select(p.state,e.id)&&a.isCurrent(p.state.agentSessions?.byAgentId[i]?.workspaceId);return qe.track(`sendMessage:${a.key}:${i}:${l?.id??"legacy"}`,async()=>{if(!u())return;M.debug(`Sending message to agent ${i}`,{contentLength:s.length,hasContextReferences:!!t.contextReferences?.length,model:t.model});let o=await p.dispatch(we(e.id,i));if(u()){if(!o)throw new Error(n.agent_streamLifecycle_sessionNotFound_error({agentId:i}));o={...o,isStreaming:o.isStreaming??!1};{if(o&&(o.status==="pending"||!o.id)&&!o.backendSessionId&&o.activationState!==H.ACTIVE&&o.activationState!==H.ACTIVATING){const h=e.id.startsWith("optimistic-"),C=e.worktreePath||e.repositoryPath||e.path;if(!h&&C){M.info("Activating pending session in sendMessage",{agentId:i,status:o.status,activationState:o.activationState,hasBackendSessionId:!!o.backendSessionId});const x=await p.dispatch(be(e.id,i));if(!u())return;x&&(o=x)}else throw M.warn("Cannot activate agent - workspace not ready",{agentId:i,workspaceId:e.id,isOptimistic:h,hasWorktreePath:!!e.worktreePath,hasRepositoryPath:!!e.repositoryPath,hasPath:!!e.path}),new Error(n.agent_streamLifecycle_spaceNotReady_error())}else o&&o.status==="pending"&&o.backendSessionId&&(M.info("Fixing status for already-activated session",{agentId:i,backendSessionId:o.backendSessionId,activationState:o.activationState}),o={...o,status:Fe.Active,activationState:H.ACTIVE},A(de({...o,workspaceId:e.id})));if(!o)throw new Error(`Failed to get or create session for agent ${i}`);A(de({...o,workspaceId:e.id}));const g=[{type:"text",text:s}];if(t.imageBlocks)for(const h of t.imageBlocks)g.push({type:"image",...h.data!==void 0?{data:h.data}:{},...h.mimeType!==void 0?{mimeType:h.mimeType}:{},...h.attachmentId!==void 0?{attachmentId:h.attachmentId}:{}});if(t.fileBlocks)for(const h of t.fileBlocks)g.push({type:"file",attachmentId:h.attachmentId,fileName:h.fileName,...h.mimeType!==void 0?{mimeType:h.mimeType}:{},...h.size!==void 0?{size:h.size}:{}});const d=t.userAppMessageId??oe(),k=t.messageMetadata?.[ge],P={...t.contextReferences?.length?{contextReferences:t.contextReferences}:{},...k!==void 0?{[ge]:k}:{}},N={id:me(le()),appMessageId:d,role:"user",contentBlocks:g,timestamp:new Date().toISOString(),metadata:{...P,...t.messageMetadata??{}}};c||(l&&(E("rejected"),f=!0),A(ke(o.id,N))),A(z(o.id,!0));let $=!1;try{c||await p.dispatch(Ge(e.id,i,!0,{allowTruncation:t.resetHistory}));const h=me(`msg_${le()}`),C=oe(),x=async()=>st.wrap(async()=>{if(!u())return;M.info("Agent Service: Sending message to backend with image and file blocks",{agentId:i,sessionId:o.id,hasImageBlocks:!!t.imageBlocks,imageBlocksCount:t.imageBlocks?.length||0,imageBlockDetails:t.imageBlocks?.map(_=>({type:_.type,mimeType:_.mimeType,dataLength:_.data?.length||0}))||[],hasFileBlocks:!!t.fileBlocks,fileBlocksCount:t.fileBlocks?.length||0,fileBlockDetails:t.fileBlocks?.map(_=>({type:_.type,fileName:_.fileName,mimeType:_.mimeType,attachmentId:_.attachmentId,size:_.size}))||[]});const Oe=t.model??t.modelId??o.model??void 0;A(Pe(i));const ye=ce(i,e.id),ae=p.state.chatState?.byAgentId[i]?.attemptGeneration??0,T=await $e("agent.sendMessage",{agentId:i,...c&&l?{messageId:l.id}:{},workspaceId:e.id,content:s,model:Oe,contextReferences:t.contextReferences,imageBlocks:t.imageBlocks,fileBlocks:t.fileBlocks,noteIds:t.noteIds,stdinContext:t.stdinContext,assistantMessageId:h,userAppMessageId:d,assistantAppMessageId:C,priority:t.priority,...t.messageMetadata?{messageMetadata:t.messageMetadata}:{}}).catch(_=>{if(u())throw _});if(u()){if(mt(T)){M.info("Backend dropped duplicate in-flight prompt",{agentId:i,sessionId:o.id}),E("rejected");return}if(T&&typeof T=="object"&&"success"in T){if(!T.success){const _=T.error,I=typeof _=="string"?_:_?.message;throw $=!0,new Error(I||n.agent_streamLifecycle_sendToBackendFailed_error())}if("queued"in T&&T.queued===!0){if(M.info("sendMessage auto-queued by daemon (mid-turn or turn-startup race)",{agentId:i,sessionId:o.id,queuedMessageId:T.queuedMessage?.id}),(!c||!l||!ue.select(p.state,l))&&A(z(o.id,!1)),c||A(xe(o.id,N.id)),c){const I=T.queuedMessage,G=T.turnId,L=typeof G=="string"?G:I?.turnId;if(I&&typeof L=="string"){const S=Ee(s,t),X=K.select(p.state,i,e.id).find(ne=>ne.id===I.id||ne.turnId===L);A(fe(i,I.id,S,L,_e(X??I,S),!X&&!!l&&ue.select(p.state,l),ae))}E("accepted",I,!0),q(i,e.id);return}const _=T.queuedMessage;if(_){const I=T.turnId,G=typeof I=="string"?I:_.turnId;let L=_;if(u()&&ce(i,e.id)===ye){const S=K.select(p.state,i,e.id),X=We(S,_);A(Ve(i,X,e.id))}else u()&&(M.debug("queued-response queue seed superseded by an authoritative snapshot; reconciling via hydrate",{agentId:i,queuedMessageId:_.id}),await q(i,e.id).catch(()=>{}),L=K.select(p.state,i,e.id).find(S=>S.id===_.id||S.turnId===G));if(u()&&typeof G=="string"){const S=Ee(s,t);A(fe(i,_.id,S,G,_e(L??_,S),!L,ae))}else u()&&M.warn("auto-queued sendMessage response carried no turnId; retry record not parked",{agentId:i,queuedMessageId:_.id})}return}}c&&(E("accepted"),q(i,e.id),Ce(i,e.id)),dt.incrementMessageSent(e.id)}},"send message",{retries:c?0:2,notify:!1,context:{agentId:i,workspace:e.id}}),re=c?await x().then(()=>({success:!0,error:void 0})):await ct.executeWithRecovery(x,Se.streaming,`send-message-${i}`);if(!re.success)throw re.error||new Error(n.agent_streamLifecycle_sendFailed_error())}catch(h){if(!u())return;throw A(z(o.id,!1)),!c&&t.messageMetadata&&A(Ue(o.id,N.id,{metadata:P})),c&&E($?"rejected":"uncertain"),h}}}},{memoize:!1,coalesce:!0,priority:"high"})}export{Ct as a,J as c,We as r,Lt as s};
1
+ var Me=Object.defineProperty;var De=(i,s,e)=>s in i?Me(i,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[s]=e;var m=(i,s,e)=>De(i,typeof s!="symbol"?s+"":s,e);import{x as Ne,J as oe,Z as ce,ai as q,ar as Ce}from"./DihoaAJc.js";import{b_ as Le,c_ as le,cq as ue,cp as ve}from"./SFGrktzA.js";import{IX as p,BG as we,bD as be,e as Fe,L0 as de,ie as me,bP as ke,DB as z,C3 as Ge,fc as Pe,A9 as xe,dZ as Ee,f8 as fe,dY as _e,AE as Ve,KG as Ue,wd as Be}from"./BkzMrEqG.js";import{aN as Ae,dS as he,A as H,P as ge,aJ as K}from"./-5BGDZDk.js";import{h as $e}from"./jhNNYE0v.js";import{c as W}from"./ChTqQfQN.js";import{a as Xe}from"./BdWqymET.js";import{m as Q}from"./BbV7MtxC.js";import"./CJxGDkBm.js";import{bm as n}from"./AeC4KVgG.js";import"./DrHJ7oPv.js";import"./Dp2nUoTL.js";import"./BNODdf6r.js";import{R as Re}from"./B5aYN90J.js";import{L as Ye}from"./CSiaiLHL.js";function We(i,s){return i.some(e=>e.id===s.id)?i.map(e=>e.id===s.id?{...s,...s.author==null&&e.author!==void 0?{author:e.author}:{}}:e):[...i,s]}const Z=typeof performance<"u"?performance:{now:()=>Date.now()},V=new Xe("PerformanceOptimizer"),w=class w{constructor(){m(this,"metricsBuffer");m(this,"metricsIndex",0);m(this,"metricsCount",0);m(this,"MAX_METRICS",500);m(this,"TARGET_RESPONSE_TIME",100);m(this,"memoCache",new Map);m(this,"MEMO_TTL",6e4);m(this,"MAX_CACHE_SIZE",100);m(this,"cacheHits",0);m(this,"cacheMisses",0);m(this,"pendingRequests",new Map);m(this,"requestQueue",[]);m(this,"cleanupInterval",null);this.metricsBuffer=new Array(this.MAX_METRICS).fill(null),this.startCacheCleanup(),V.info("PerformanceOptimizer initialized")}static getInstance(){return w.instance||(w.instance=new w),w.instance}reset(){this.metricsBuffer=new Array(this.MAX_METRICS).fill(null),this.metricsIndex=0,this.metricsCount=0,this.memoCache.clear(),this.pendingRequests.clear(),this.requestQueue=[],this.cacheHits=0,this.cacheMisses=0}clearCache(){this.memoCache.clear(),this.cacheHits=0,this.cacheMisses=0}async processBatch(s,e,t={}){const{batchSize:r=10,concurrency:a=4}=t,l=[];for(let c=0;c<s.length;c+=r){const f=s.slice(c,c+r).map((o,R)=>{const g=Math.floor(R/a)*10;return new Promise(d=>{setTimeout(async()=>{const k=await e(o);d(k)},g)})}),u=await Promise.all(f);l.push(...u)}return l}startCacheCleanup(){this.cleanupInterval=setInterval(()=>{this.cleanupCache()},3e4)}stopCacheCleanup(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null)}cleanupCache(){const s=Date.now(),e=[];this.memoCache.forEach((t,r)=>{s-t.timestamp>this.MEMO_TTL&&e.push(r)}),e.forEach(t=>this.memoCache.delete(t)),this.memoCache.size>this.MAX_CACHE_SIZE&&Array.from(this.memoCache.entries()).sort((a,l)=>a[1].hits-l[1].hits||a[1].timestamp-l[1].timestamp).slice(0,this.memoCache.size-this.MAX_CACHE_SIZE).forEach(([a])=>this.memoCache.delete(a))}async track(s,e,t={}){const r=Z.now();try{const a=t.cacheKey||s;if(t.memoize){const f=this.getMemoized(a);if(f!==void 0)return this.cacheHits++,V.debug("Memoized result used",{operation:s,cacheKey:a,hits:this.cacheHits}),f;this.cacheMisses++}if(t.coalesce){const f=this.pendingRequests.get(s);if(f)return V.debug("Request coalesced",{operation:s}),f}let l;t.coalesce?(l=t.timeout?this.withTimeout(e(),t.timeout):e(),this.pendingRequests.set(s,l)):l=t.timeout?this.withTimeout(e(),t.timeout):e();const c=await l;t.memoize&&this.memoize(a,c);const E=Z.now()-r;return this.recordMetric(s,E,!0,{strategy:t.priority||"normal",memoized:t.memoize||!1,coalesced:t.coalesce||!1}),E>this.TARGET_RESPONSE_TIME&&V.warn("Operation exceeded target time",{operation:s,duration:Math.round(E),target:this.TARGET_RESPONSE_TIME}),c}catch(a){const l=Z.now()-r;throw this.recordMetric(s,l,!1,{error:a instanceof Error?a.message:"Unknown error"}),a}finally{t.coalesce&&this.pendingRequests.delete(s)}}getStats(){if(this.metricsCount===0)return{avgResponseTime:0,p95ResponseTime:0,p99ResponseTime:0,successRate:100,slowOperations:[]};const s=[],e=this.metricsCount<this.MAX_METRICS?0:this.metricsIndex;for(let u=0;u<this.metricsCount;u++){const o=this.metricsBuffer[(e+u)%this.MAX_METRICS];o&&s.push(o)}if(s.length===0)return{avgResponseTime:0,p95ResponseTime:0,p99ResponseTime:0,successRate:100,slowOperations:[]};const t=s.sort((u,o)=>u.duration-o.duration);let r=0,a=0;const l=new Set;for(const u of s)a+=u.duration,u.success&&r++,u.duration>this.TARGET_RESPONSE_TIME&&l.add(u.operation);const c=a/s.length,E=Math.floor(t.length*.95),f=Math.floor(t.length*.99);return{avgResponseTime:Math.round(c),p95ResponseTime:Math.round(t[E]?.duration||0),p99ResponseTime:Math.round(t[f]?.duration||0),successRate:r/s.length*100,slowOperations:Array.from(l)}}getCacheStats(){const s=this.cacheHits+this.cacheMisses;return{size:this.memoCache.size,hitRate:s>0?this.cacheHits/s*100:0,hits:this.cacheHits,misses:this.cacheMisses}}getMemoized(s){const e=this.memoCache.get(s);if(e){if(Date.now()-e.timestamp>this.MEMO_TTL){this.memoCache.delete(s);return}return e.hits++,e.value}}memoize(s,e){const t=JSON.stringify(e).length;this.memoCache.set(s,{value:e,timestamp:Date.now(),hits:0,size:t}),this.memoCache.size>this.MAX_CACHE_SIZE&&this.cleanupCache()}async withTimeout(s,e){return Promise.race([s,new Promise((t,r)=>setTimeout(()=>r(new Error(`Operation timed out after ${e}ms`)),e))])}recordMetric(s,e,t,r){this.metricsBuffer[this.metricsIndex]={operation:s,duration:e,timestamp:Date.now(),success:t,metadata:r},this.metricsIndex=(this.metricsIndex+1)%this.MAX_METRICS,this.metricsCount<this.MAX_METRICS&&this.metricsCount++,e>this.TARGET_RESPONSE_TIME&&V.warn("Slow operation detected",{operation:s,duration:`${e.toFixed(2)}ms`,target:`${this.TARGET_RESPONSE_TIME}ms`,metadata:r})}};m(w,"instance");let ee=w;const qe=ee.getInstance(),pe={AGENT_CREATION:"https://docs.example.com/agent-creation",STREAMING:"https://docs.example.com/streaming-issues",STORAGE:"https://docs.example.com/storage-troubleshooting",MEMORY:"https://docs.example.com/memory-management",PROVIDER:"https://docs.example.com/provider-setup",GENERAL:"https://docs.example.com/help"},j={get AGENT_CREATION_FAILED(){return n.errors_catalog_agentCreationFailed_template({agentName:"{agentName}",details:"{details}"})},get AGENT_ALREADY_EXISTS(){return n.errors_catalog_agentAlreadyExists_template({agentName:"{agentName}"})},get INVALID_AGENT_CONFIG(){return n.errors_catalog_invalidAgentConfig_template({details:"{details}"})},get INVALID_CONFIG(){return n.errors_catalog_invalidConfig_template({details:"{details}"})},get SESSION_NOT_FOUND(){return n.errors_catalog_sessionNotFound_template({sessionId:"{sessionId}"})},get SESSION_ALREADY_ACTIVE(){return n.errors_catalog_sessionAlreadyActive_template()},get SESSION_INITIALIZATION_FAILED(){return n.errors_catalog_sessionInitializationFailed_template({details:"{details}"})},get STREAM_CONNECTION_FAILED(){return n.errors_catalog_streamConnectionFailed_template({details:"{details}"})},get STREAM_TIMEOUT(){return n.errors_catalog_streamTimeout_template({timeout:"{timeout}"})},get STREAM_INTERRUPTED(){return n.errors_catalog_streamInterrupted_template({attempt:"{attempt}",maxAttempts:"{maxAttempts}"})},get STREAM_RECOVERY_FAILED(){return n.errors_catalog_streamRecoveryFailed_template({attempts:"{attempts}"})},get MESSAGE_SEND_FAILED(){return n.errors_catalog_messageSendFailed_template({details:"{details}"})},get MESSAGE_VALIDATION_FAILED(){return n.errors_catalog_messageValidationFailed_template({details:"{details}"})},get MESSAGE_TOO_LONG(){return n.errors_catalog_messageTooLong_template({maxLength:"{maxLength}",currentLength:"{currentLength}"})},get PROVIDER_NOT_FOUND(){return n.errors_catalog_providerNotFound_template({provider:"{provider}"})},get PROVIDER_CONNECTION_FAILED(){return n.errors_catalog_providerConnectionFailed_template({provider:"{provider}",details:"{details}"})},get PROVIDER_PROCESS_DIED(){return n.errors_catalog_providerProcessDied_template({provider:"{provider}"})},get STORAGE_READ_FAILED(){return n.errors_catalog_storageReadFailed_template({details:"{details}"})},get STORAGE_WRITE_FAILED(){return n.errors_catalog_storageWriteFailed_template({details:"{details}"})},get STORAGE_CORRUPTED(){return n.errors_catalog_storageCorrupted_template({lastBackup:"{lastBackup}"})},get MEMORY_LIMIT_EXCEEDED(){return n.errors_catalog_memoryLimitExceeded_template({currentUsage:"{currentUsage}",limit:"{limit}"})},get RATE_LIMIT_EXCEEDED(){return n.errors_catalog_rateLimitExceeded_template({count:"{count}",window:"{window}"})},get CONCURRENT_LIMIT_EXCEEDED(){return n.errors_catalog_concurrentLimitExceeded_template({current:"{current}",max:"{max}"})}},ze={get AGENT_CREATION_FAILED(){return n.errors_catalog_agentCreationFailed_friendly()},get AGENT_ALREADY_EXISTS(){return n.errors_catalog_agentAlreadyExists_friendly()},get INVALID_AGENT_CONFIG(){return n.errors_catalog_invalidAgentConfig_friendly()},get INVALID_CONFIG(){return n.errors_catalog_invalidConfig_friendly()},get SESSION_NOT_FOUND(){return n.errors_catalog_sessionNotFound_friendly()},get SESSION_ALREADY_ACTIVE(){return n.errors_catalog_sessionAlreadyActive_friendly()},get SESSION_INITIALIZATION_FAILED(){return n.errors_catalog_sessionInitializationFailed_friendly()},get STREAM_CONNECTION_FAILED(){return n.errors_catalog_streamConnectionFailed_friendly()},get STREAM_TIMEOUT(){return n.errors_catalog_streamTimeout_friendly()},get STREAM_INTERRUPTED(){return n.errors_catalog_streamInterrupted_friendly()},get STREAM_RECOVERY_FAILED(){return n.errors_catalog_streamRecoveryFailed_friendly()},get MESSAGE_SEND_FAILED(){return n.errors_catalog_messageSendFailed_friendly()},get MESSAGE_VALIDATION_FAILED(){return n.errors_catalog_messageValidationFailed_friendly()},get MESSAGE_TOO_LONG(){return n.errors_catalog_messageTooLong_friendly()},get PROVIDER_NOT_FOUND(){return n.errors_catalog_providerNotFound_friendly()},get PROVIDER_CONNECTION_FAILED(){return n.errors_catalog_providerConnectionFailed_friendly()},get PROVIDER_PROCESS_DIED(){return n.errors_catalog_providerProcessDied_friendly()},get STORAGE_READ_FAILED(){return n.errors_catalog_storageReadFailed_friendly()},get STORAGE_WRITE_FAILED(){return n.errors_catalog_storageWriteFailed_friendly()},get STORAGE_CORRUPTED(){return n.errors_catalog_storageCorrupted_friendly()},get MEMORY_LIMIT_EXCEEDED(){return n.errors_catalog_memoryLimitExceeded_friendly()},get RATE_LIMIT_EXCEEDED(){return n.errors_catalog_rateLimitExceeded_friendly()},get CONCURRENT_LIMIT_EXCEEDED(){return n.errors_catalog_concurrentLimitExceeded_friendly()}};function He(i){return(i.match(/{(\w+)}/g)||[]).map(e=>e.slice(1,-1))}function Ke(i,s){return He(i).every(t=>t in s)}function Ie(i,s={}){return i.replace(/{(\w+)}/g,(e,t)=>String(s[t]??e))}function J(i){const s=n.errors_cleanMessage_fallback_error();if(!i)return s;let e=i;return e=e.replace(/^.*?failed(?:\s+to\s+.*?)?\s+after\s+\d+\s+attempts:\s*/i,""),e=e.replace(/^Error invoking remote method '[^']+':(\s*Error:)?\s*/i,""),e=e.replace(/^(Error:\s*)+/i,""),e=e.replace(/\n\s*at .+/g,""),e=e.replace(/\s+/g," ").trim(),e||s}function Qe(i,s){return s&&j[i]&&Ke(j[i],s)?Ie(j[i],s):ze[i]||n.errors_userFriendly_fallback_error()}function Ze(i){const e={AGENT_CREATION_FAILED:"AGENT_CREATION",AGENT_ALREADY_EXISTS:"AGENT_CREATION",INVALID_AGENT_CONFIG:"AGENT_CREATION",STREAM_CONNECTION_FAILED:"STREAMING",STREAM_TIMEOUT:"STREAMING",STREAM_INTERRUPTED:"STREAMING",STREAM_RECOVERY_FAILED:"STREAMING",STORAGE_READ_FAILED:"STORAGE",STORAGE_WRITE_FAILED:"STORAGE",STORAGE_CORRUPTED:"STORAGE",MEMORY_LIMIT_EXCEEDED:"MEMORY",RATE_LIMIT_EXCEEDED:"MEMORY",CONCURRENT_LIMIT_EXCEEDED:"MEMORY",PROVIDER_NOT_FOUND:"PROVIDER",PROVIDER_CONNECTION_FAILED:"PROVIDER",PROVIDER_PROCESS_DIED:"PROVIDER"}[i];return e?pe[e]:pe.GENERAL}const je={AGENT_CREATION_FAILED:[{action:"retry",description:"Try creating the agent again",automatic:!1,priority:"high"},{action:"check-config",description:"Verify agent configuration in settings",automatic:!1,priority:"high"},{action:"check-resources",description:"Ensure sufficient memory and disk space",automatic:!1,priority:"medium"}],AGENT_ALREADY_EXISTS:[{action:"rename",description:"Choose a different name for the agent",automatic:!1,priority:"high"},{action:"delete-existing",description:"Delete the existing agent first",automatic:!1,priority:"medium"}],INVALID_AGENT_CONFIG:[{action:"review-config",description:"Review and correct the configuration",automatic:!1,priority:"high"},{action:"use-defaults",description:"Reset to default configuration",automatic:!1,priority:"medium"}],INVALID_CONFIG:[{action:"review-config",description:"Review and correct the configuration",automatic:!1,priority:"high"},{action:"use-defaults",description:"Reset to default configuration",automatic:!1,priority:"medium"}],SESSION_NOT_FOUND:[{action:"start-new",description:"Start a new agent session",automatic:!1,priority:"high"},{action:"check-history",description:"Check session history for recent sessions",automatic:!1,priority:"medium"}],SESSION_ALREADY_ACTIVE:[{action:"wait",description:"Wait for the current session to complete",automatic:!1,priority:"high"},{action:"cancel",description:"Cancel the active session first",automatic:!1,priority:"high"}],SESSION_INITIALIZATION_FAILED:[{action:"retry",description:"Try initializing the session again",automatic:!1,priority:"high"},{action:"check-resources",description:"Ensure sufficient resources are available",automatic:!1,priority:"medium"}],MESSAGE_SEND_FAILED:[{action:"retry",description:"Try sending the message again",automatic:!1,priority:"high"},{action:"check-connection",description:"Check your network connection",automatic:!1,priority:"high"}],MESSAGE_VALIDATION_FAILED:[{action:"review-config",description:"Review and correct the message format",automatic:!1,priority:"high"},{action:"check-config",description:"Check configuration for valid message format",automatic:!1,priority:"medium"}],MESSAGE_TOO_LONG:[{action:"retry",description:"Shorten the message and try again",automatic:!1,priority:"high"},{action:"batch",description:"Split the message into multiple parts",automatic:!1,priority:"medium"}],PROVIDER_NOT_FOUND:[{action:"check-config",description:"Verify provider is properly configured",automatic:!1,priority:"high"},{action:"recreate",description:"Install or reinstall the provider",automatic:!1,priority:"high"}],PROVIDER_CONNECTION_FAILED:[{action:"retry",description:"Try connecting to the provider again",automatic:!1,priority:"high"},{action:"check-config",description:"Verify provider configuration",automatic:!1,priority:"high"}],STORAGE_READ_FAILED:[{action:"retry",description:"Try reading the data again",automatic:!1,priority:"high"},{action:"restore",description:"Restore from a recent backup",automatic:!1,priority:"medium"}],STORAGE_WRITE_FAILED:[{action:"retry",description:"Try saving again",automatic:!1,priority:"high"},{action:"check-resources",description:"Check available disk space",automatic:!1,priority:"high"}],STREAM_CONNECTION_FAILED:[{action:"retry",description:"Try connecting again",automatic:!1,priority:"high"},{action:"check-connection",description:"Check your network connection",automatic:!1,priority:"high"}],STREAM_RECOVERY_FAILED:[{action:"restart",description:"Restart the agent",automatic:!1,priority:"high"},{action:"check-config",description:"Check error logs for more details",automatic:!1,priority:"medium"}],STREAM_INTERRUPTED:[{action:"reconnect",description:"Attempting automatic reconnection",automatic:!0,priority:"high"},{action:"retry",description:"Retry sending the message",automatic:!1,priority:"high"},{action:"check-connection",description:"Check your internet connection",automatic:!1,priority:"medium"}],STREAM_TIMEOUT:[{action:"wait",description:"Wait for agent to complete processing",automatic:!1,priority:"high"},{action:"cancel",description:"Cancel current operation",automatic:!1,priority:"medium"},{action:"increase-timeout",description:"Increase timeout in settings",automatic:!1,priority:"low"}],PROVIDER_PROCESS_DIED:[{action:"restart",description:"Restart agent process",automatic:!0,priority:"high"},{action:"recreate",description:"Create new agent session",automatic:!1,priority:"high"}],STORAGE_CORRUPTED:[{action:"restore",description:"Restore from backup",automatic:!1,priority:"high"},{action:"reset",description:"Reset agent data",automatic:!1,priority:"medium"}],MEMORY_LIMIT_EXCEEDED:[{action:"cleanup",description:"Close unused agents",automatic:!1,priority:"high"},{action:"increase-limit",description:"Increase memory limit in settings",automatic:!1,priority:"medium"}],RATE_LIMIT_EXCEEDED:[{action:"wait",description:"Wait before making more requests",automatic:!1,priority:"high"},{action:"batch",description:"Batch requests together",automatic:!1,priority:"medium"}],CONCURRENT_LIMIT_EXCEEDED:[{action:"close-agents",description:"Close some running agents",automatic:!1,priority:"high"},{action:"queue",description:"Queue operation for later",automatic:!1,priority:"medium"}]};function Je(i){return je[i]||[{action:"retry",description:"Try the operation again",automatic:!1,priority:"high"}]}var D=(i=>(i.AGENT_CREATION_FAILED="AGENT_CREATION_FAILED",i.AGENT_ALREADY_EXISTS="AGENT_ALREADY_EXISTS",i.INVALID_AGENT_CONFIG="INVALID_AGENT_CONFIG",i.INVALID_CONFIG="INVALID_CONFIG",i.SESSION_NOT_FOUND="SESSION_NOT_FOUND",i.SESSION_ALREADY_ACTIVE="SESSION_ALREADY_ACTIVE",i.SESSION_INITIALIZATION_FAILED="SESSION_INITIALIZATION_FAILED",i.STREAM_CONNECTION_FAILED="STREAM_CONNECTION_FAILED",i.STREAM_TIMEOUT="STREAM_TIMEOUT",i.STREAM_INTERRUPTED="STREAM_INTERRUPTED",i.STREAM_RECOVERY_FAILED="STREAM_RECOVERY_FAILED",i.MESSAGE_SEND_FAILED="MESSAGE_SEND_FAILED",i.MESSAGE_VALIDATION_FAILED="MESSAGE_VALIDATION_FAILED",i.MESSAGE_TOO_LONG="MESSAGE_TOO_LONG",i.PROVIDER_NOT_FOUND="PROVIDER_NOT_FOUND",i.PROVIDER_CONNECTION_FAILED="PROVIDER_CONNECTION_FAILED",i.PROVIDER_PROCESS_DIED="PROVIDER_PROCESS_DIED",i.PROVIDER_UNAVAILABLE="PROVIDER_UNAVAILABLE",i.PROVIDER_ERROR="PROVIDER_ERROR",i.STORAGE_READ_FAILED="STORAGE_READ_FAILED",i.STORAGE_WRITE_FAILED="STORAGE_WRITE_FAILED",i.STORAGE_CORRUPTED="STORAGE_CORRUPTED",i.STORAGE_ERROR="STORAGE_ERROR",i.STORAGE_QUOTA_EXCEEDED="STORAGE_QUOTA_EXCEEDED",i.MEMORY_LIMIT_EXCEEDED="MEMORY_LIMIT_EXCEEDED",i.RATE_LIMIT_EXCEEDED="RATE_LIMIT_EXCEEDED",i.CONCURRENT_LIMIT_EXCEEDED="CONCURRENT_LIMIT_EXCEEDED",i.RESOURCE_NOT_FOUND="RESOURCE_NOT_FOUND",i.RESOURCE_EXHAUSTED="RESOURCE_EXHAUSTED",i.NETWORK_ERROR="NETWORK_ERROR",i.PERMISSION_DENIED="PERMISSION_DENIED",i.OPERATION_FAILED="OPERATION_FAILED",i.VALIDATION_ERROR="VALIDATION_ERROR",i.INVALID_RESPONSE="INVALID_RESPONSE",i.STATE_CORRUPTION="STATE_CORRUPTION",i.CONTEXT_OVERFLOW="CONTEXT_OVERFLOW",i))(D||{});class Y extends Error{constructor(e,t,r={},a){super(e);m(this,"code");m(this,"context");m(this,"recoverySuggestions");m(this,"userMessage");m(this,"isRecoverable");m(this,"cause");this.name="AgentError",this.code=t,this.context={...r,timestamp:new Date,stackTrace:this.stack},this.userMessage=a?.userMessage||this.getDefaultUserMessage(t),this.recoverySuggestions=a?.recoverySuggestions||this.getDefaultRecoverySuggestions(t),this.isRecoverable=a?.isRecoverable??this.isErrorRecoverable(t),a?.cause&&(this.cause=a.cause)}getDefaultUserMessage(e){return Qe(e,this.context)}getDefaultRecoverySuggestions(e){return Je(e)}isErrorRecoverable(e){return["STREAM_INTERRUPTED","STREAM_TIMEOUT","MESSAGE_SEND_FAILED","PROVIDER_PROCESS_DIED","STORAGE_READ_FAILED","STORAGE_WRITE_FAILED"].includes(e)}getHelpLink(){return Ze(this.code)}formatMessage(e){return Ie(e,this.context)}toJSON(){return{name:this.name,code:this.code,message:this.message,userMessage:this.userMessage,context:this.context,recoverySuggestions:this.recoverySuggestions,isRecoverable:this.isRecoverable,helpLink:this.getHelpLink(),stack:this.stack}}}const et={NON_RETRYABLE_ERRORS:["EACCES","EPERM","ENOSPC","EMFILE","permission","memory","fatal","process died","not available on your current plan","agent binary","rate limit","too many requests","hit your limit","you've hit your limit","quota exceeded"]};function ie(i){const s=i.toLowerCase();for(const e of et.NON_RETRYABLE_ERRORS)if(s.includes(e.toLowerCase()))return!0;return!1}const tt="Agent already has an in-flight prompt. Message was not delivered.",v=W("ErrorBoundary"),b=class b{constructor(){}static getInstance(){return b.instance||(b.instance=new b),b.instance}async wrap(s,e,t={}){const{retries:r=Re.DEFAULT_ATTEMPTS,retryDelay:a=Re.BASE_DELAY,exponentialBackoff:l=!0,notify:c=!1,notifyOnRetry:E=!1,context:f={},onError:u,onRetry:o,shouldRetry:R=this.defaultShouldRetry}=t;let g=null,d=0;for(d=1;d<=r+1;d++)try{v.debug(`[${e}] Attempt ${d}/${r+1}`);const h=await s();return d>1&&v.info(`[${e}] Succeeded after ${d} attempts`),h}catch(h){if(g=h,v.error(`[${e}] Attempt ${d} failed`,{error:g.message,attempt:d,maxAttempts:r+1,context:f}),u?.(g,d),d<=r&&R(g)){const C=l?a*Math.pow(2,d-1):a;E&&Q.warning(n.agent_errorBoundary_retrying_message({seconds:C/1e3})),o?.(d),v.info(`[${e}] Retrying in ${C}ms`),await this.sleep(C)}else break}const k=`${e} failed after ${d} attempt${d===1?"":"s"}: ${g?.message}`,P=J(g?.message||n.agent_errorBoundary_generic_error()),N=g?.message?.toLowerCase()||"",$=N.includes("no available models")||N.includes("all models exhausted")||N.includes("all models unavailable");throw c&&!$&&Q.error(P),new Y(P,D.OPERATION_FAILED,{originalError:g?.message,detailedMessage:k,attempts:d,context:f})}async wrapVoid(s,e,t={}){await this.wrap(s,e,t)}wrapSync(s,e,t={}){try{return s()}catch(r){const a=r;throw v.error(`[${e}] Failed`,{error:a.message,context:t.context}),t.notify&&Q.error(J(a.message)),new Y(J(a.message),D.OPERATION_FAILED,t.context)}}defaultShouldRetry(s){const e=s.message.toLowerCase();return ie(s.message)?!1:e.includes("network")||e.includes("timeout")?!0:s instanceof Y?[D.NETWORK_ERROR,D.STREAM_TIMEOUT,D.STREAM_CONNECTION_FAILED,D.PROVIDER_CONNECTION_FAILED,D.PROVIDER_UNAVAILABLE].includes(s.code):!(e.includes("invalid")||e.includes("interrupted")||e.includes("cancel")||e.includes("not found")||e.includes("not available")||e.includes("404")||e.includes("no available models")||e.includes("all models exhausted")||e.includes("all models unavailable")||e.includes("413")||e.includes("too long for the agent")||e.includes("request entity too large")||e.includes("payload too large")||e.includes("content too large")||e.includes("body too large")||e.includes("unauthorized")||e.includes("forbidden")||e.includes("401")||e.includes("403"))}sleep(s){return new Promise(e=>setTimeout(e,s))}async withTimeout(s,e,t){return Promise.race([s(),new Promise((r,a)=>setTimeout(()=>a(new Y(`${t} timed out after ${e}ms`,D.STREAM_TIMEOUT)),e))])}async batchOperations(s,e,t={}){const{concurrency:r=5,continueOnError:a=!0,operationName:l="batch operation"}=t,c=[],E=[];for(let f=0;f<s.length;f+=r){const u=s.slice(f,f+r);(await Promise.allSettled(u.map(R=>e(R)))).forEach((R,g)=>{if(R.status==="fulfilled")c.push(R.value);else{const d=R.reason;if(E.push({item:u[g],error:d}),v.error(`[${l}] Batch item failed`,{item:u[g],error:d.message}),!a)throw d}})}return E.length>0&&v.warn(`[${l}] Completed with ${E.length} errors`),{results:c,errors:E}}};m(b,"instance");let te=b;const st=te.getInstance(),se=W("browser/index"),F=new Map,B=new Map;let U;function it(i,s,e){for(const t of s)try{t(e)}catch(r){se.error("Error in agent subscriber callback",{agentId:i,error:r})}}function rt(){if(U)return;let i=!1;U=p.createSelector(e=>e.agentSessions)().subscribe(()=>{if(!i){i=!0;return}if(F.size===0)return;const e=p.state;for(const[t,r]of F){const a=Ae.select(e,t);B.get(t)!==a&&(B.set(t,a),it(t,r,a))}})}function at(){F.size>0||!U||(U(),U=void 0,B.clear())}function Ct(i,s,e){let t=F.get(i);const r=!t;t||(t=new Set,F.set(i,t)),t.add(s),rt();const a=p.state,l=Ae.select(a,i);return r&&B.set(i,l),l?se.debug("[subscribeToAgent] Initial callback data",{agentId:i,workspaceId:e??"current",hasSession:!0}):se.debug("[subscribeToAgent] No session found",{agentId:i,workspaceId:e??"current"}),s(l),()=>{const c=F.get(i);c&&(c.delete(s),c.size===0&&(F.delete(i),B.delete(i))),at()}}const y=W("ErrorRecovery"),Se={network:{maxRetries:3,initialBackoffMs:1e3,maxBackoffMs:1e4,backoffMultiplier:2,shouldRetry:i=>{const s=i.message.toLowerCase();return s.includes("network")||s.includes("fetch")||s.includes("connection")||s.includes("timeout")}},streaming:{maxRetries:5,initialBackoffMs:500,maxBackoffMs:5e3,backoffMultiplier:1.5,shouldRetry:(i,s)=>{if(s>=5)return!1;const e=i.message.toLowerCase();return e.includes("no available models")||e.includes("all models exhausted")||e.includes("all models unavailable")||ie(i.message)?!1:e.includes("stream")||e.includes("chunk")||e.includes("incomplete")}},persistence:{maxRetries:2,initialBackoffMs:100,maxBackoffMs:1e3,backoffMultiplier:2,shouldRetry:i=>{const s=i.message.toLowerCase();return s.includes("save")||s.includes("write")||s.includes("persist")}},rateLimit:{maxRetries:3,initialBackoffMs:5e3,maxBackoffMs:3e4,backoffMultiplier:2,shouldRetry:i=>{const s=i.message.toLowerCase();return s.includes("rate")||s.includes("limit")||s.includes("429")}}};class nt{constructor(){m(this,"listeners",new Map)}on(s,e){let t=this.listeners.get(s);t||(t=new Set,this.listeners.set(s,t)),t.add(e)}off(s,e){this.listeners.get(s)?.delete(e)}emit(s,...e){this.listeners.get(s)?.forEach(t=>{try{t(...e)}catch(r){y.error(`Error in event listener for ${s}:`,r)}})}removeAllListeners(){this.listeners.clear()}}class ot extends nt{constructor(){super(...arguments);m(this,"activeRecoveries",new Map);m(this,"recoveryStats",new Map)}async executeWithRecovery(e,t=Se.network,r){const a=Date.now(),l=new AbortController;r&&(this.cancelRecovery(r),this.activeRecoveries.set(r,l));let c,E=t.initialBackoffMs,f=0;for(let u=1;u<=t.maxRetries;u++){if(f=u,l.signal.aborted){y.info(`Recovery cancelled for operation ${r}`);break}try{y.debug(`Attempting operation (attempt ${u}/${t.maxRetries})`,{operationId:r});const o=await e();return this.updateStats(r,!0),this.emit("recovery:success",{operationId:r,attempt:u,duration:Date.now()-a}),r&&this.activeRecoveries.delete(r),{success:!0,data:o,attempts:u,totalTime:Date.now()-a}}catch(o){c=o,y.warn(`Operation failed (attempt ${u}/${t.maxRetries})`,{operationId:r,error:c.message});const R=c.message.toLowerCase();if(R.includes("interrupted")||R.includes("cancelled")||R.includes("canceled")){y.debug("User-initiated interruption/cancellation, not retrying",{operationId:r,error:c.message});break}if(R.includes("no available models")||R.includes("all models exhausted")||R.includes("all models unavailable")){y.debug("All models exhausted, not retrying",{operationId:r,error:c.message});break}if(ie(c.message)){y.debug("Fatal error detected, not retrying",{operationId:r,error:c.message});break}if(!t.shouldRetry(c,u)){y.debug("Error not retryable, stopping recovery",{operationId:r,error:c.message});break}if(u<t.maxRetries){const g=Math.random()*.2*E,d=Math.min(E+g,t.maxBackoffMs);t.onRetry?.(u,d),this.emit("recovery:retry",{operationId:r,attempt:u,delay:d,error:c.message}),await this.delay(d,l.signal),E=Math.min(E*t.backoffMultiplier,t.maxBackoffMs)}}}return this.updateStats(r,!1),t.onFailure?.(c,f),this.emit("recovery:failure",{operationId:r,attempts:f,duration:Date.now()-a,error:c?.message}),r&&this.activeRecoveries.delete(r),{success:!1,error:c,attempts:f,totalTime:Date.now()-a}}cancelRecovery(e){const t=this.activeRecoveries.get(e);t&&(t.abort(),this.activeRecoveries.delete(e),y.info(`Cancelled recovery for operation ${e}`))}cancelAllRecoveries(){for(const[e,t]of this.activeRecoveries)t.abort(),y.info(`Cancelled recovery for operation ${e}`);this.activeRecoveries.clear()}getStats(e){if(e)return this.recoveryStats.get(e)||{successes:0,failures:0};const t={};for(const[r,a]of this.recoveryStats)t[r]=a;return t}clearStats(e){e?this.recoveryStats.delete(e):this.recoveryStats.clear()}isRetryable(e,t){const r=e.message.toLowerCase();if(t)switch(t){case"NETWORK":return r.includes("network")||r.includes("fetch");case"TIMEOUT":return r.includes("timeout")||r.includes("timed out");case"RATE_LIMIT":return r.includes("rate")||r.includes("limit")||r.includes("429");case"TEMPORARY":return r.includes("temporary")||r.includes("transient");case"CONFLICT":return r.includes("conflict")||r.includes("concurrent");default:return!1}return this.isRetryable(e,"NETWORK")||this.isRetryable(e,"TIMEOUT")||this.isRetryable(e,"RATE_LIMIT")||this.isRetryable(e,"TEMPORARY")||this.isRetryable(e,"CONFLICT")}delay(e,t){return new Promise((r,a)=>{const l=setTimeout(r,e);if(t){const c=()=>{clearTimeout(l),a(new Error("Delay aborted"))};t.addEventListener("abort",c);const E=r;r=()=>{t.removeEventListener("abort",c),E()}}})}updateStats(e,t){if(!e)return;const r=this.recoveryStats.get(e)||{successes:0,failures:0};t?r.successes++:r.failures++,this.recoveryStats.set(e,r)}dispose(){this.cancelAllRecoveries(),this.recoveryStats.clear(),this.removeAllListeners()}}const ct=new ot,O=new Ye({category:"WorkspaceMetrics"}),lt=100;class ut{constructor(){m(this,"metrics",new Map);m(this,"operations",new Map)}startWorkspaceCreation(s){const e=Date.now();for(this.metrics.delete(s),this.metrics.set(s,{workspaceId:s,creationStarted:e});this.metrics.size>lt;){const t=this.metrics.keys().next().value;if(t===void 0)break;this.metrics.delete(t)}O.info("Started tracking workspace creation",{workspaceId:s})}recordMilestone(s,e){const t=this.metrics.get(s);if(!t){O.warn("No metrics found for workspace",{workspaceId:s,milestone:e});return}const r=Date.now();switch(e){case"optimisticNavigation":t.optimisticNavigation=r;break;case"realWorkspaceCreated":t.realWorkspaceCreated=r;break;case"agentCreated":t.agentCreated=r;break;case"agentReady":t.agentReady=r;break;case"firstMessageSent":t.firstMessageSent=r;break;case"firstResponseReceived":t.firstResponseReceived=r;break;case"firstChunkReceived":t.firstChunkReceived=r;break;case"totalDuration":t.totalDuration=r;break;case"workspaceId":case"creationStarted":O.warn("Cannot update milestone",{milestone:e});return}const a=r-t.creationStarted;O.info(`Milestone: ${e}`,{workspaceId:s,elapsed:`${a}ms`,timestamp:r}),e==="firstResponseReceived"&&(t.totalDuration=r-t.creationStarted,this.logSummary(s))}startOperation(s,e){this.operations.set(s,{startTime:Date.now(),metadata:e})}endOperation(s,e){const t=this.operations.get(s);if(!t)return O.warn("Operation not found",{operationId:s}),null;const r=Date.now();return t.endTime=r,t.duration=r-t.startTime,e&&(t.metadata={...t.metadata,...e}),O.info("Operation completed",{operationId:s,duration:`${t.duration}ms`,metadata:t.metadata}),this.operations.delete(s),t.duration}getMetrics(s){return this.metrics.get(s)}logSummary(s){const e=this.metrics.get(s);if(!e)return;const t={workspaceId:s,totalDuration:`${e.totalDuration}ms`,stages:{optimisticNavigation:e.optimisticNavigation?`${e.optimisticNavigation-e.creationStarted}ms`:"N/A",realWorkspaceCreation:e.realWorkspaceCreated?`${e.realWorkspaceCreated-e.creationStarted}ms`:"N/A",agentCreation:e.agentCreated?`${e.agentCreated-e.creationStarted}ms`:"N/A",agentReady:e.agentReady?`${e.agentReady-e.creationStarted}ms`:"N/A",firstMessage:e.firstMessageSent?`${e.firstMessageSent-e.creationStarted}ms`:"N/A",firstResponse:e.firstResponseReceived?`${e.firstResponseReceived-e.creationStarted}ms`:"N/A"}};O.info("=== Workspace Creation Metrics Summary ===",t),O.info("Workspace Creation Metrics:",t)}clearMetrics(s){this.metrics.delete(s)}incrementAgentCreated(s){const e=this.metrics.get(s);e&&(e.agentCreated=Date.now(),O.info("Agent created",{workspaceId:s}))}incrementMessageSent(s){const e=this.metrics.get(s);e&&!e.firstMessageSent&&(e.firstMessageSent=Date.now(),O.info("First message sent",{workspaceId:s}))}}const dt=new ut,M=W("AgentSend");function A(i){p.dispatch(i)}function Te(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function mt(i){const s=Te(i)&&i.success===!0&&"data"in i?i.data:i;return!Te(s)||s.success!==!1?!1:typeof s.error=="string"&&s.error.includes(tt)}async function Lt(i,s,e,t={}){const r=he.select(p.state,e.id);if(!r)return;const a=Ne(i,e.id),l=t.submission,c=!!l&&Le.select(p.state,l.scope)?.supported===!0,E=(o,R,g=!1)=>{l&&A(Be(l.scope,l.id,o,Date.now(),R,g))};let f=!1;const u=()=>(!l||f||ve.select(p.state,l))&&r===he.select(p.state,e.id)&&a.isCurrent(p.state.agentSessions?.byAgentId[i]?.workspaceId);return qe.track(`sendMessage:${a.key}:${i}:${l?.id??"legacy"}`,async()=>{if(!u())return;M.debug(`Sending message to agent ${i}`,{contentLength:s.length,hasContextReferences:!!t.contextReferences?.length,model:t.model});let o=await p.dispatch(we(e.id,i));if(u()){if(!o)throw new Error(n.agent_streamLifecycle_sessionNotFound_error({agentId:i}));o={...o,isStreaming:o.isStreaming??!1};{if(o&&(o.status==="pending"||!o.id)&&!o.backendSessionId&&o.activationState!==H.ACTIVE&&o.activationState!==H.ACTIVATING){const h=e.id.startsWith("optimistic-"),C=e.worktreePath||e.repositoryPath||e.path;if(!h&&C){M.info("Activating pending session in sendMessage",{agentId:i,status:o.status,activationState:o.activationState,hasBackendSessionId:!!o.backendSessionId});const x=await p.dispatch(be(e.id,i));if(!u())return;x&&(o=x)}else throw M.warn("Cannot activate agent - workspace not ready",{agentId:i,workspaceId:e.id,isOptimistic:h,hasWorktreePath:!!e.worktreePath,hasRepositoryPath:!!e.repositoryPath,hasPath:!!e.path}),new Error(n.agent_streamLifecycle_spaceNotReady_error())}else o&&o.status==="pending"&&o.backendSessionId&&(M.info("Fixing status for already-activated session",{agentId:i,backendSessionId:o.backendSessionId,activationState:o.activationState}),o={...o,status:Fe.Active,activationState:H.ACTIVE},A(de({...o,workspaceId:e.id})));if(!o)throw new Error(`Failed to get or create session for agent ${i}`);A(de({...o,workspaceId:e.id}));const g=[{type:"text",text:s}];if(t.imageBlocks)for(const h of t.imageBlocks)g.push({type:"image",...h.data!==void 0?{data:h.data}:{},...h.mimeType!==void 0?{mimeType:h.mimeType}:{},...h.attachmentId!==void 0?{attachmentId:h.attachmentId}:{}});if(t.fileBlocks)for(const h of t.fileBlocks)g.push({type:"file",attachmentId:h.attachmentId,fileName:h.fileName,...h.mimeType!==void 0?{mimeType:h.mimeType}:{},...h.size!==void 0?{size:h.size}:{}});const d=t.userAppMessageId??oe(),k=t.messageMetadata?.[ge],P={...t.contextReferences?.length?{contextReferences:t.contextReferences}:{},...k!==void 0?{[ge]:k}:{}},N={id:me(le()),appMessageId:d,role:"user",contentBlocks:g,timestamp:new Date().toISOString(),metadata:{...P,...t.messageMetadata??{}}};c||(l&&(E("rejected"),f=!0),A(ke(o.id,N))),A(z(o.id,!0));let $=!1;try{c||await p.dispatch(Ge(e.id,i,!0,{allowTruncation:t.resetHistory}));const h=me(`msg_${le()}`),C=oe(),x=async()=>st.wrap(async()=>{if(!u())return;M.info("Agent Service: Sending message to backend with image and file blocks",{agentId:i,sessionId:o.id,hasImageBlocks:!!t.imageBlocks,imageBlocksCount:t.imageBlocks?.length||0,imageBlockDetails:t.imageBlocks?.map(_=>({type:_.type,mimeType:_.mimeType,dataLength:_.data?.length||0}))||[],hasFileBlocks:!!t.fileBlocks,fileBlocksCount:t.fileBlocks?.length||0,fileBlockDetails:t.fileBlocks?.map(_=>({type:_.type,fileName:_.fileName,mimeType:_.mimeType,attachmentId:_.attachmentId,size:_.size}))||[]});const Oe=t.model??t.modelId??o.model??void 0;A(Pe(i));const ye=ce(i,e.id),ae=p.state.chatState?.byAgentId[i]?.attemptGeneration??0,T=await $e("agent.sendMessage",{agentId:i,...c&&l?{messageId:l.id}:{},workspaceId:e.id,content:s,model:Oe,contextReferences:t.contextReferences,imageBlocks:t.imageBlocks,fileBlocks:t.fileBlocks,noteIds:t.noteIds,stdinContext:t.stdinContext,assistantMessageId:h,userAppMessageId:d,assistantAppMessageId:C,priority:t.priority,...t.messageMetadata?{messageMetadata:t.messageMetadata}:{}}).catch(_=>{if(u())throw _});if(u()){if(mt(T)){M.info("Backend dropped duplicate in-flight prompt",{agentId:i,sessionId:o.id}),E("rejected");return}if(T&&typeof T=="object"&&"success"in T){if(!T.success){const _=T.error,I=typeof _=="string"?_:_?.message;throw $=!0,new Error(I||n.agent_streamLifecycle_sendToBackendFailed_error())}if("queued"in T&&T.queued===!0){if(M.info("sendMessage auto-queued by daemon (mid-turn or turn-startup race)",{agentId:i,sessionId:o.id,queuedMessageId:T.queuedMessage?.id}),(!c||!l||!ue.select(p.state,l))&&A(z(o.id,!1)),c||A(xe(o.id,N.id)),c){const I=T.queuedMessage,G=T.turnId,L=typeof G=="string"?G:I?.turnId;if(I&&typeof L=="string"){const S=Ee(s,t),X=K.select(p.state,i,e.id).find(ne=>ne.id===I.id||ne.turnId===L);A(fe(i,I.id,S,L,_e(X??I,S),!X&&!!l&&ue.select(p.state,l),ae))}E("accepted",I,!0),q(i,e.id);return}const _=T.queuedMessage;if(_){const I=T.turnId,G=typeof I=="string"?I:_.turnId;let L=_;if(u()&&ce(i,e.id)===ye){const S=K.select(p.state,i,e.id),X=We(S,_);A(Ve(i,X,e.id))}else u()&&(M.debug("queued-response queue seed superseded by an authoritative snapshot; reconciling via hydrate",{agentId:i,queuedMessageId:_.id}),await q(i,e.id).catch(()=>{}),L=K.select(p.state,i,e.id).find(S=>S.id===_.id||S.turnId===G));if(u()&&typeof G=="string"){const S=Ee(s,t);A(fe(i,_.id,S,G,_e(L??_,S),!L,ae))}else u()&&M.warn("auto-queued sendMessage response carried no turnId; retry record not parked",{agentId:i,queuedMessageId:_.id})}return}}c&&(E("accepted"),q(i,e.id),Ce(i,e.id)),dt.incrementMessageSent(e.id)}},"send message",{retries:c?0:2,notify:!1,context:{agentId:i,workspace:e.id}}),re=c?await x().then(()=>({success:!0,error:void 0})):await ct.executeWithRecovery(x,Se.streaming,`send-message-${i}`);if(!re.success)throw re.error||new Error(n.agent_streamLifecycle_sendFailed_error())}catch(h){if(!u())return;throw A(z(o.id,!1)),!c&&t.messageMetadata&&A(Ue(o.id,N.id,{metadata:P})),c&&E($?"rejected":"uncertain"),h}}}},{memoize:!1,coalesce:!0,priority:"high"})}export{Ct as a,J as c,We as r,Lt as s};