@runfusion/fusion 0.76.0-beta.3 → 0.77.0-beta.0

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 (175) hide show
  1. package/dist/bin.js +13802 -9587
  2. package/dist/child-process-worker.js +6472 -4028
  3. package/dist/client/.vite/manifest.json +280 -269
  4. package/dist/client/assets/AgentDetailView-0G9qFd4j.js +13 -0
  5. package/dist/client/assets/{AgentDetailView-Cc3ATg8a.css → AgentDetailView-jzgy1BAS.css} +1 -1
  6. package/dist/client/assets/{AgentPermissionPolicyEditor--u9jyUf2.js → AgentPermissionPolicyEditor-BM68g7wo.js} +1 -1
  7. package/dist/client/assets/AgentsView-DkOUZWw4.js +24 -0
  8. package/dist/client/assets/ChatView-BPSm2JIH.js +13 -0
  9. package/dist/client/assets/{CommandCenter-CSRYoveB.js → CommandCenter-DxRSFWNc.js} +26 -26
  10. package/dist/client/assets/CommandCenter-ilm-DbtI.css +1 -0
  11. package/dist/client/assets/{DevServerView-B9So_oYx.js → DevServerView-DO-bqJFE.js} +1 -1
  12. package/dist/client/assets/{DirectoryPicker-BhyDL_2m.js → DirectoryPicker-Cp2gddTE.js} +1 -1
  13. package/dist/client/assets/DocumentsView-D0E-3G96.js +1 -0
  14. package/dist/client/assets/EvalsView-BoFVq5hw.js +1 -0
  15. package/dist/client/assets/ExperimentalAgentOnboardingModal-CS1Sdogm.js +1 -0
  16. package/dist/client/assets/{GoalsView-B6X5_0Ve.js → GoalsView-sybf7JY4.js} +1 -1
  17. package/dist/client/assets/InsightsView-nHa7aShn.js +11 -0
  18. package/dist/client/assets/{MemoryView-DN_3IFmA.css → MemoryView-CdpQqPJJ.css} +1 -1
  19. package/dist/client/assets/MemoryView-D0IG44za.js +3 -0
  20. package/dist/client/assets/{PiExtensionsManager-B8At6fO8.js → PiExtensionsManager-CU76weJe.js} +2 -2
  21. package/dist/client/assets/PluginManager-DyT8XbcG.js +1 -0
  22. package/dist/client/assets/{PullRequestView-B1hZFrWo.js → PullRequestView-CnxWUSen.js} +2 -2
  23. package/dist/client/assets/{ReportModal-C46V_zEa.js → ReportModal-CMrmMQjD.js} +5 -5
  24. package/dist/client/assets/{ResearchView-D8G85BYN.js → ResearchView-BTytQSgy.js} +2 -2
  25. package/dist/client/assets/{SecretsView-CTri9LRK.js → SecretsView-BuSH5J87.js} +1 -1
  26. package/dist/client/assets/SessionTerminal-D04kYRrT.js +2 -0
  27. package/dist/client/assets/SettingsModal-C0FY8MPW.css +1 -0
  28. package/dist/client/assets/{SettingsModal-rUQcSTJp.js → SettingsModal-Dm-ngbRr.js} +1 -1
  29. package/dist/client/assets/{SettingsModal-DmfMotcd.css → SettingsModal-Ds0Yj47X.css} +1 -1
  30. package/dist/client/assets/SettingsModal-xSLhH7Tr.js +21 -0
  31. package/dist/client/assets/{SettingsTextareaRow-BirlBcem.js → SettingsTextareaRow-CHPgocEp.js} +1 -1
  32. package/dist/client/assets/{SetupWizardModal-xnCBM9EL.js → SetupWizardModal-y88aXNIQ.js} +2 -2
  33. package/dist/client/assets/{SkillsView-O5U0ep50.js → SkillsView-CYyQW1Hv.js} +1 -1
  34. package/dist/client/assets/{WorkflowNodeEditor-BX4d2qqF.js → WorkflowNodeEditor-hYeoz1X8.js} +3 -3
  35. package/dist/client/assets/{agent-import-generation-DnqVkPkz.js → agent-import-generation-CjiYXzCr.js} +1 -1
  36. package/dist/client/assets/agentsOrgChartLayout-C0UP_X3z.js +1 -0
  37. package/dist/client/assets/app-BgpuMvTU.js +13 -0
  38. package/dist/client/assets/app-BlexHhbW.js +13 -0
  39. package/dist/client/assets/app-BsuUOR0P.js +13 -0
  40. package/dist/client/assets/app-DQVOujmO.js +13 -0
  41. package/dist/client/assets/app-DjyTRx1N.js +5 -0
  42. package/dist/client/assets/app-Dniggype.js +13 -0
  43. package/dist/client/assets/app-EV-lyZ0T.js +5 -0
  44. package/dist/client/assets/{architectureDiagram-3BPJPVTR-gi467xY0.js → architectureDiagram-3BPJPVTR-Dd6GPcqM.js} +1 -1
  45. package/dist/client/assets/{blockDiagram-GPEHLZMM-B_gpcYiR.js → blockDiagram-GPEHLZMM-CC6pLxlz.js} +1 -1
  46. package/dist/client/assets/{c4Diagram-AAUBKEIU-DeylEYsQ.js → c4Diagram-AAUBKEIU-DxMP_l6y.js} +1 -1
  47. package/dist/client/assets/channel-DlCEMoEf.js +1 -0
  48. package/dist/client/assets/{chunk-2J33WTMH-BL2WY0HN.js → chunk-2J33WTMH-BKYToL43.js} +1 -1
  49. package/dist/client/assets/{chunk-4BX2VUAB-BkLExGMe.js → chunk-4BX2VUAB-Bg6rjQb3.js} +1 -1
  50. package/dist/client/assets/{chunk-55IACEB6-CSTvCF5T.js → chunk-55IACEB6-CPUwbbGa.js} +1 -1
  51. package/dist/client/assets/{chunk-727SXJPM-9J8pKk4x.js → chunk-727SXJPM-DScQBCvv.js} +1 -1
  52. package/dist/client/assets/{chunk-AQP2D5EJ-DXC1vPWr.js → chunk-AQP2D5EJ-DbX7uaXK.js} +1 -1
  53. package/dist/client/assets/{chunk-FMBD7UC4-CFRUb-zD.js → chunk-FMBD7UC4-DvYKea1c.js} +1 -1
  54. package/dist/client/assets/{chunk-ND2GUHAM-B87HFYS8.js → chunk-ND2GUHAM-CH-Tvw7w.js} +1 -1
  55. package/dist/client/assets/{chunk-QZHKN3VN-CTjHiGbd.js → chunk-QZHKN3VN-CbyEvOoM.js} +1 -1
  56. package/dist/client/assets/classDiagram-4FO5ZUOK-Bc92O8Ks.js +1 -0
  57. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-Bc92O8Ks.js +1 -0
  58. package/dist/client/assets/{cose-bilkent-S5V4N54A-D3Edq3L9.js → cose-bilkent-S5V4N54A-BPB5fV3A.js} +1 -1
  59. package/dist/client/assets/{dagre-BM42HDAG-CwwbeQfN.js → dagre-BM42HDAG-CilYJ3rR.js} +1 -1
  60. package/dist/client/assets/{dashboard-view-QxQwJFLz.js → dashboard-view-BnGe8cWo.js} +1 -1
  61. package/dist/client/assets/{dashboard-view-BLAoW3D4.js → dashboard-view-DnVf3tmI.js} +1 -1
  62. package/dist/client/assets/{dashboard-view-DAlJxqiJ.js → dashboard-view-DoLU6FxZ.js} +1 -1
  63. package/dist/client/assets/{dashboard-view-aPzfv99T.js → dashboard-view-dChSM_So.js} +1 -1
  64. package/dist/client/assets/{diagram-2AECGRRQ-koJWWXE4.js → diagram-2AECGRRQ-m9u1Qhyx.js} +1 -1
  65. package/dist/client/assets/{diagram-5GNKFQAL-Yob5cOKT.js → diagram-5GNKFQAL-DVr7Kf0N.js} +1 -1
  66. package/dist/client/assets/{diagram-KO2AKTUF-DelvFSkK.js → diagram-KO2AKTUF-D7sgJDFx.js} +1 -1
  67. package/dist/client/assets/{diagram-LMA3HP47-CMput2h2.js → diagram-LMA3HP47-DNKNDS6r.js} +1 -1
  68. package/dist/client/assets/{diagram-OG6HWLK6-04VXDl79.js → diagram-OG6HWLK6-1Bff4FWn.js} +1 -1
  69. package/dist/client/assets/{erDiagram-TEJ5UH35-C9iP8Uyp.js → erDiagram-TEJ5UH35-DGua1UHN.js} +1 -1
  70. package/dist/client/assets/{flowDiagram-I6XJVG4X-DENQvu_t.js → flowDiagram-I6XJVG4X-UDfDtwsE.js} +1 -1
  71. package/dist/client/assets/{folder-open-D-554oji.js → folder-open-CteOypVk.js} +1 -1
  72. package/dist/client/assets/{ganttDiagram-6RSMTGT7-BqOttZAT.js → ganttDiagram-6RSMTGT7-COdmD328.js} +1 -1
  73. package/dist/client/assets/{gitGraphDiagram-PVQCEYII-CDcydi-5.js → gitGraphDiagram-PVQCEYII-SUSls7Kw.js} +1 -1
  74. package/dist/client/assets/index-0ovTXt3t.css +1 -0
  75. package/dist/client/assets/index-DpCHwyiD.js +2818 -0
  76. package/dist/client/assets/{infoDiagram-5YYISTIA-B5LQQnxt.js → infoDiagram-5YYISTIA-e_DloXj7.js} +1 -1
  77. package/dist/client/assets/{ishikawaDiagram-YF4QCWOH-DpFEt7D2.js → ishikawaDiagram-YF4QCWOH-DVWqihXg.js} +1 -1
  78. package/dist/client/assets/{journeyDiagram-JHISSGLW-MELtgu22.js → journeyDiagram-JHISSGLW-BcPY-XP0.js} +1 -1
  79. package/dist/client/assets/{kanban-definition-UN3LZRKU-h33PLATd.js → kanban-definition-UN3LZRKU-BCFG2Jle.js} +1 -1
  80. package/dist/client/assets/{mermaid.core-Dk2mUPOq.js → mermaid.core-5yPje9Bi.js} +4 -4
  81. package/dist/client/assets/{mindmap-definition-RKZ34NQL-B_T4O2-B.js → mindmap-definition-RKZ34NQL-DDApeT3K.js} +1 -1
  82. package/dist/client/assets/{pieDiagram-4H26LBE5-B1YIFkRl.js → pieDiagram-4H26LBE5-N61_jyeP.js} +1 -1
  83. package/dist/client/assets/{puzzle-hvecxlpJ.js → puzzle-BkaCP30D.js} +1 -1
  84. package/dist/client/assets/{quadrantDiagram-W4KKPZXB-BoGQR_hO.js → quadrantDiagram-W4KKPZXB-C5qHiApF.js} +1 -1
  85. package/dist/client/assets/{requirementDiagram-4Y6WPE33-BSDmUBIx.js → requirementDiagram-4Y6WPE33-C71okgzt.js} +1 -1
  86. package/dist/client/assets/{sankeyDiagram-5OEKKPKP-Dz_GqOa5.js → sankeyDiagram-5OEKKPKP-B2iKyLjB.js} +1 -1
  87. package/dist/client/assets/{sequenceDiagram-3UESZ5HK-B6twjYUH.js → sequenceDiagram-3UESZ5HK-DfdoYKKk.js} +1 -1
  88. package/dist/client/assets/{shield-alert-BX4WRJOv.js → shield-alert-BNSeDB8l.js} +1 -1
  89. package/dist/client/assets/standing-instructions-template-pZtzo1lK.js +20 -0
  90. package/dist/client/assets/standing-instructions-template-w7Ouw_37.css +1 -0
  91. package/dist/client/assets/{stateDiagram-AJRCARHV-DuwqWLx-.js → stateDiagram-AJRCARHV-lS-sUi12.js} +1 -1
  92. package/dist/client/assets/{stateDiagram-v2-BHNVJYJU-Bu8Sk187.js → stateDiagram-v2-BHNVJYJU-DXJNDrV9.js} +1 -1
  93. package/dist/client/assets/{timeline-definition-PNZ67QCA-BS6VnqSI.js → timeline-definition-PNZ67QCA-CCwvX81K.js} +1 -1
  94. package/dist/client/assets/{upload-CaDoyaMW.js → upload-CDovVbu2.js} +1 -1
  95. package/dist/client/assets/useDiscoveredSkillsCache-BYqP-afh.js +1 -0
  96. package/dist/client/assets/{users-C5uCLwVM.js → users-CTqECGLo.js} +1 -1
  97. package/dist/client/assets/{vennDiagram-CIIHVFJN-CUbzqT5Y.js → vennDiagram-CIIHVFJN-DaiR5nv9.js} +1 -1
  98. package/dist/client/assets/{wardley-L42UT6IY-Mv-NotFS.js → wardley-L42UT6IY-hA5IHyPW.js} +1 -1
  99. package/dist/client/assets/{wardleyDiagram-YWT4CUSO-DuYpvLZX.js → wardleyDiagram-YWT4CUSO-CILUNESc.js} +1 -1
  100. package/dist/client/assets/{xychartDiagram-2RQKCTM6-24_7QXdw.js → xychartDiagram-2RQKCTM6-72eNMmjz.js} +1 -1
  101. package/dist/client/index.html +2 -2
  102. package/dist/client/version.json +1 -1
  103. package/dist/droid-cli/package.json +1 -1
  104. package/dist/extension.js +10671 -6904
  105. package/dist/migrations/0059_fn_9037_tasks_source_agent_index.sql +3 -0
  106. package/dist/migrations/0060_fn_9059_workspace_coordination_leases.sql +10 -0
  107. package/dist/pi-claude-cli/package.json +1 -1
  108. package/dist/plugin-sdk/index.d.ts +190 -9
  109. package/dist/plugin-sdk/index.js +74 -28
  110. package/dist/plugins/fusion-plugin-acp-runtime/bundled.js +83 -29
  111. package/dist/plugins/fusion-plugin-acp-runtime/package.json +1 -1
  112. package/dist/plugins/fusion-plugin-claude-runtime/bundled.js +83 -29
  113. package/dist/plugins/fusion-plugin-claude-runtime/package.json +1 -1
  114. package/dist/plugins/fusion-plugin-cli-printing-press/bundled.js +74 -28
  115. package/dist/plugins/fusion-plugin-cli-printing-press/package.json +1 -1
  116. package/dist/plugins/fusion-plugin-compound-engineering/bundled.js +74 -28
  117. package/dist/plugins/fusion-plugin-compound-engineering/package.json +1 -1
  118. package/dist/plugins/fusion-plugin-cursor-runtime/bundled.js +1096 -73
  119. package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
  120. package/dist/plugins/fusion-plugin-dependency-graph/bundled.js +74 -28
  121. package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
  122. package/dist/plugins/fusion-plugin-droid-runtime/bundled.js +74 -28
  123. package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
  124. package/dist/plugins/fusion-plugin-grok-runtime/bundled.js +83 -29
  125. package/dist/plugins/fusion-plugin-grok-runtime/package.json +1 -1
  126. package/dist/plugins/fusion-plugin-hermes-runtime/bundled.js +302 -71
  127. package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
  128. package/dist/plugins/fusion-plugin-linear-import/bundled.js +74 -28
  129. package/dist/plugins/fusion-plugin-linear-import/package.json +1 -1
  130. package/dist/plugins/fusion-plugin-omp-runtime/bundled.js +83 -29
  131. package/dist/plugins/fusion-plugin-omp-runtime/package.json +1 -1
  132. package/dist/plugins/fusion-plugin-openclaw-runtime/bundled.js +74 -28
  133. package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
  134. package/dist/plugins/fusion-plugin-paperclip-runtime/bundled.js +74 -28
  135. package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
  136. package/dist/plugins/fusion-plugin-quality/bundled.js +176 -46
  137. package/dist/plugins/fusion-plugin-quality/package.json +1 -1
  138. package/dist/plugins/fusion-plugin-reports/bundled.js +74 -28
  139. package/dist/plugins/fusion-plugin-reports/package.json +1 -1
  140. package/dist/plugins/fusion-plugin-roadmap/bundled.js +74 -28
  141. package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
  142. package/dist/plugins/fusion-plugin-todos/bundled.js +74 -28
  143. package/dist/plugins/fusion-plugin-todos/package.json +1 -1
  144. package/dist/plugins/fusion-plugin-whatsapp-chat/bundled.js +74 -28
  145. package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
  146. package/package.json +1 -1
  147. package/skill/fusion/references/extension-tools.md +2 -0
  148. package/dist/client/assets/AgentDetailView-T767kKTg.js +0 -13
  149. package/dist/client/assets/AgentsView-6Ifu7qDr.js +0 -24
  150. package/dist/client/assets/ChatView-BV3lixQi.js +0 -13
  151. package/dist/client/assets/CommandCenter-CE4rYjHn.css +0 -1
  152. package/dist/client/assets/DocumentsView-pbERA7O-.js +0 -1
  153. package/dist/client/assets/EvalsView-DJQ4ltCg.js +0 -1
  154. package/dist/client/assets/ExperimentalAgentOnboardingModal-BwJuzkzB.js +0 -1
  155. package/dist/client/assets/InsightsView-CJgI0J7S.js +0 -11
  156. package/dist/client/assets/MemoryView-BHq1AHPu.js +0 -3
  157. package/dist/client/assets/PluginManager-k7hV7_9e.js +0 -1
  158. package/dist/client/assets/SessionTerminal-BRf6r4Vp.js +0 -2
  159. package/dist/client/assets/SettingsModal-B30rPfYC.css +0 -1
  160. package/dist/client/assets/SettingsModal-D0RBeZik.js +0 -21
  161. package/dist/client/assets/agentsOrgChartLayout-CKuzbhFf.js +0 -1
  162. package/dist/client/assets/app-B2FwULu2.js +0 -5
  163. package/dist/client/assets/app-B6nJaqAl.js +0 -13
  164. package/dist/client/assets/app-CGXZeIRc.js +0 -13
  165. package/dist/client/assets/app-CGtkeBF5.js +0 -13
  166. package/dist/client/assets/app-CNzN1Plu.js +0 -13
  167. package/dist/client/assets/app-DLs-f5yM.js +0 -13
  168. package/dist/client/assets/app-DsvtcRUG.js +0 -5
  169. package/dist/client/assets/channel-BoE8DeM4.js +0 -1
  170. package/dist/client/assets/classDiagram-4FO5ZUOK-qnbLX_9_.js +0 -1
  171. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-qnbLX_9_.js +0 -1
  172. package/dist/client/assets/index-CXTd3LAB.css +0 -1
  173. package/dist/client/assets/index-CtYRoouR.js +0 -2818
  174. package/dist/client/assets/standing-instructions-template-BJY317CC.js +0 -20
  175. package/dist/client/assets/standing-instructions-template-Ddi_4TIk.css +0 -1
@@ -1,13 +0,0 @@
1
- import{r as s,j as e}from"./vendor-react-SZ_qB27O.js";import{c as Ls,bz as ra,bA as la,bB as oa,bC as ca,L as J,bD as Pt,R as St,bE as xs,Z as da,bF as Ut,bG as Ds,x as yt,C as Hs,g as zs,bH as ua,bI as ma,bJ as ga,ab as Is,aX as ha,bK as fa,bL as B,bM as pa,bN as ba,bO as xa,bP as Os,bQ as ts,bR as va,bS as Et,bT as Vt,bh as Tt,F as vs,bU as Bs,am as $s,bV as Wt,bW as Lt,bX as js,bY as dt,bZ as ja,X as _s,aH as Nt,b_ as ya,b$ as Us,c0 as Vs,c1 as Na,_ as Sa,u as ka,c2 as Ws,aR as Gs,c3 as is,c4 as Ca,c5 as ys,c6 as wa,c7 as Ra,c8 as ss,c9 as Js,ca as Ma,d as Aa,cb as Fa,h as qs,cc as Ks,b4 as Pa,an as be,cd as Ns,ce as Ss,cf as Ta,cg as Ea,ch as La,ci as Da,cj as Ht,p as zt,j as It,r as Ot,aA as Ys,ck as Ha,cl as za,cm as Ia,aJ as Xs,aK as Oa,cn as Gt,co as Ba,cp as $a,cq as ks,cr as _a,cs as Ua,ct as Jt,cu as Va,cv as Wa,cw as Ga,cx as as,y as Ja,cy as rs,cz as qa,cA as Ka,cB as Ya,cC as Xa,cD as Za,cE as Qa,aB as Zs,cF as en,cG as tn,cH as sn,cI as an,cJ as nn}from"./index-CtYRoouR.js";import{r as rn,f as qt,S as ln,a as on,b as cn}from"./standing-instructions-template-BJY317CC.js";import{u as ke}from"./vendor-i18n-Duky4gdQ.js";import{ExperimentalAgentOnboardingModal as dn}from"./ExperimentalAgentOnboardingModal-BwJuzkzB.js";import{B as un,A as mn}from"./AgentPermissionPolicyEditor--u9jyUf2.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";/**
2
- * @license lucide-react v1.7.0 - ISC
3
- *
4
- * This source code is licensed under the ISC license.
5
- * See the LICENSE file in the root directory of this source tree.
6
- */const gn=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M17 12h-2l-2 5-2-10-2 5H7",key:"15hlnc"}]],hn=Ls("square-activity",gn);/**
7
- * @license lucide-react v1.7.0 - ISC
8
- *
9
- * This source code is licensed under the ISC license.
10
- * See the LICENSE file in the root directory of this source tree.
11
- */const fn=[["path",{d:"M16 17h6v-6",key:"t6n2it"}],["path",{d:"m22 17-8.5-8.5-5 5L2 7",key:"x473p"}]],pn=Ls("trending-down",fn);function Cs(t){return t<1e3?`${t}ms`:t<6e4?`${(t/1e3).toFixed(1)}s`:t<36e5?`${Math.floor(t/6e4)}m`:`${(t/36e5).toFixed(1)}h`}function bn(t){return`${Math.round(t*100)}%`}function ws(t,i){const o=Date.now(),l=new Date(t).getTime(),r=o-l;if(r<0){const c=Math.abs(r);return c<6e4?i("agents.time.inAMoment","in a moment"):c<36e5?i("agents.time.inMinutes","in {{count}}m",{count:Math.floor(c/6e4)}):c<864e5?i("agents.time.inHours","in {{count}}h",{count:Math.floor(c/36e5)}):i("agents.time.inDays","in {{count}}d",{count:Math.floor(c/864e5)})}return r<6e4?i("agents.time.justNow","just now"):r<36e5?i("agents.time.minutesAgo","{{count}}m ago",{count:Math.floor(r/6e4)}):r<864e5?i("agents.time.hoursAgo","{{count}}h ago",{count:Math.floor(r/36e5)}):i("agents.time.daysAgo","{{count}}d ago",{count:Math.floor(r/864e5)})}function xn(t,i){switch(t){case"periodic":return i("agents.reflections.triggerPeriodic","Periodic");case"post-task":return i("agents.reflections.triggerPostTask","Post-Task");case"manual":return i("agents.reflections.triggerManual","Manual");case"user-requested":return i("agents.reflections.triggerUserRequested","User Requested");default:return t}}function vt(t){return t instanceof Error&&t.message?t.message:String(t)}function vn(t,i){switch(t){case"improving":return i("agents.ratings.trendImproving","↑ Improving");case"declining":return i("agents.ratings.trendDeclining","↓ Declining");case"stable":return i("agents.ratings.trendStable","→ Stable");default:return i("agents.ratings.trendInsufficient","Insufficient data")}}function jn(t){switch(t){case"improving":return"trend-improving";case"declining":return"trend-declining";case"stable":return"trend-stable";default:return"trend-insufficient"}}function Rs(t,i=5){return e.jsx("span",{className:"rating-stars",children:Array.from({length:i},(o,l)=>e.jsx(Ds,{size:14,className:l<t?"star-filled":"star-empty",fill:l<t?"currentColor":"none"},l))})}function yn({agentId:t,projectId:i,addToast:o}){const{t:l}=ke("app"),[r,c]=s.useState([]),[y,x]=s.useState(null),[a,u]=s.useState(null),[w,R]=s.useState([]),[d,g]=s.useState(!0),[I,F]=s.useState(!0),[T,z]=s.useState(!1),[V,Z]=s.useState(!1),[j,N]=s.useState(null),[P,q]=s.useState(0),[S,$]=s.useState(""),[se,K]=s.useState(""),D=s.useCallback(async()=>{try{const[m,k]=await Promise.all([ra(t,20,i),la(t,void 0,i)]);c(m),x(k)}catch(m){o(l("agents.reflections.loadError","Failed to load reflections: {{error}}",{error:vt(m)}),"error")}finally{g(!1)}},[t,i,o]),Q=s.useCallback(async()=>{try{const[m,k]=await Promise.all([oa(t,i),ca(t,{limit:50},i)]);u(m),R(k)}catch(m){o(l("agents.ratings.loadError","Failed to load ratings: {{error}}",{error:vt(m)}),"error")}finally{F(!1)}},[t,i,o]);s.useEffect(()=>{D(),Q()},[D,Q]);const E=async()=>{z(!0);try{if(!await ua(t,i)){o(l("agents.reflections.insufficientHistory","Not enough history to generate a reflection yet"),"error");return}o(l("agents.reflections.generateSuccess","Reflection generated successfully"),"success"),g(!0),await D()}catch(m){const k=vt(m),_=k.toLowerCase();_.includes("agent not found")||_.includes("not found")?o(l("agents.reflections.agentNotFound","This agent is no longer available. It may have been deleted."),"error"):_.includes("insufficient history")?o(l("agents.reflections.insufficientHistory","Not enough history to generate a reflection yet"),"error"):o(l("agents.reflections.generateError","Failed to generate reflection: {{error}}",{error:k}),"error")}finally{z(!1)}},H=async m=>{if(m.preventDefault(),P!==0){Z(!0);try{await ma(t,{score:P,category:S||void 0,comment:se||void 0,raterType:"user"},i),q(0),$(""),K(""),o(l("agents.ratings.addSuccess","Rating added"),"success"),await Q()}catch(k){o(l("agents.ratings.addError","Failed to add rating: {{error}}",{error:vt(k)}),"error")}finally{Z(!1)}}},M=async m=>{try{await ga(t,m,i),o(l("agents.ratings.deleteSuccess","Rating deleted"),"success"),await Q()}catch(k){o(l("agents.ratings.deleteError","Failed to delete rating: {{error}}",{error:vt(k)}),"error")}},O=m=>{N(k=>k===m?null:m)};if(d&&I)return e.jsx("div",{className:"reflections-tab",children:e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(J,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:l("agents.reflections.loadingEvaluation","Loading evaluation...")})]})});const b=y&&y.totalTasksCompleted===0&&y.totalTasksFailed===0&&y.recentReflectionCount===0;return e.jsxs("div",{className:"reflections-tab",children:[e.jsxs("div",{className:"reflections-header",children:[e.jsxs("h3",{children:[e.jsx(Pt,{size:16}),l("agents.reflections.sectionTitle","Performance, Reflections & Ratings")]}),e.jsx("button",{className:"btn btn-secondary",onClick:E,disabled:T,title:l("agents.reflections.reflectNowTitle","Generate a manual reflection"),children:T?e.jsxs(e.Fragment,{children:[e.jsx(J,{size:14,className:"animate-spin"}),l("agents.reflections.reflecting","Reflecting...")]}):e.jsxs(e.Fragment,{children:[e.jsx(St,{size:14}),l("agents.reflections.reflectNow","Reflect Now")]})})]}),y&&!b&&e.jsxs("div",{className:"reflections-stats-grid",children:[e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(xs,{size:16,style:{color:"var(--color-success)"}}),y.totalTasksCompleted]}),e.jsx("div",{className:"stat-label",children:l("agents.performance.tasksCompleted","Tasks Completed")})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(pn,{size:16,style:{color:"var(--color-error)"}}),y.totalTasksFailed]}),e.jsx("div",{className:"stat-label",children:l("agents.performance.tasksFailed","Tasks Failed")})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(da,{size:16,style:{color:"var(--in-progress)"}}),Cs(y.avgDurationMs)]}),e.jsx("div",{className:"stat-label",children:l("agents.performance.avgDuration","Avg Duration")})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(Pt,{size:16,style:{color:y.successRate>=.8?"var(--color-success)":y.successRate>=.5?"var(--color-warning)":"var(--color-error)"}}),bn(y.successRate)]}),e.jsx("div",{className:"stat-label",children:l("agents.performance.successRate","Success Rate")})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(Ut,{size:16,style:{color:"var(--color-info)"}}),y.recentReflectionCount]}),e.jsx("div",{className:"stat-label",children:l("agents.performance.reflections","Reflections")})]})]}),b&&e.jsxs("div",{className:"reflections-no-data",children:[e.jsx(Pt,{size:24,opacity:.3}),e.jsx("p",{children:l("agents.performance.noData","No performance data yet")})]}),e.jsxs("div",{className:"reflections-ratings-section",children:[e.jsx("h4",{children:l("agents.ratings.title","User Ratings")}),I?e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(J,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:l("agents.ratings.loading","Loading ratings...")})]}):e.jsxs(e.Fragment,{children:[a&&e.jsxs("div",{className:"rating-summary-card",children:[e.jsxs("div",{className:"rating-score-display",children:[e.jsx("span",{className:"rating-average",children:a.averageScore.toFixed(1)}),Rs(Math.round(a.averageScore))]}),e.jsxs("div",{className:"rating-stats",children:[e.jsx("span",{className:"rating-count",children:l("agents.ratings.count","{{count}} ratings",{count:a.totalRatings})}),e.jsx("span",{className:`rating-trend-badge ${jn(a.trend)}`,children:vn(a.trend,l)})]})]}),a&&Object.keys(a.categoryAverages).length>0&&e.jsxs("div",{className:"category-breakdown",children:[e.jsx("h4",{children:l("agents.ratings.categoryAverages","Category Averages")}),Object.entries(a.categoryAverages).map(([m,k])=>e.jsxs("div",{className:"category-item",children:[e.jsx("span",{className:"category-name",children:m}),e.jsx("span",{className:"category-score",children:k.toFixed(1)})]},m))]}),e.jsxs("form",{className:"add-rating-form",onSubmit:H,children:[e.jsx("h4",{children:l("agents.ratings.addRating","Add Rating")}),e.jsx("div",{className:"star-selector",children:[1,2,3,4,5].map(m=>e.jsx("button",{type:"button",className:"star-btn touch-target",onClick:()=>q(m),title:l("agents.ratings.starCount","{{count}} star",{count:m,defaultValue_one:"{{count}} star",defaultValue_other:"{{count}} stars"}),children:e.jsx(Ds,{size:24,fill:m<=P?"currentColor":"none",className:m<=P?"star-filled":"star-empty"})},m))}),e.jsxs("select",{value:S,onChange:m=>$(m.target.value),className:"select add-rating-category-select",children:[e.jsx("option",{value:"",children:l("agents.ratings.categorySelect","Select category...")}),e.jsx("option",{value:"quality",children:l("agents.ratings.categoryQuality","Quality")}),e.jsx("option",{value:"speed",children:l("agents.ratings.categorySpeed","Speed")}),e.jsx("option",{value:"communication",children:l("agents.ratings.categoryCommunication","Communication")}),e.jsx("option",{value:"reliability",children:l("agents.ratings.categoryReliability","Reliability")}),e.jsx("option",{value:"other",children:l("agents.ratings.categoryOther","Other")})]}),e.jsx("textarea",{value:se,onChange:m=>K(m.target.value),placeholder:l("agents.ratings.commentPlaceholder","Optional comment..."),className:"input add-rating-comment-input",rows:3}),e.jsx("button",{type:"submit",className:"btn btn-task-create",disabled:P===0||V,children:V?l("agents.ratings.submitting","Submitting..."):l("agents.ratings.submitRating","Submit Rating")})]}),e.jsxs("div",{className:"rating-history",children:[e.jsx("h4",{children:l("agents.ratings.historyTitle","Rating History")}),w.length===0?e.jsx("p",{className:"no-ratings",children:l("agents.ratings.noRatings","No ratings yet")}):w.map(m=>e.jsxs("div",{className:"rating-history-item",children:[e.jsxs("div",{className:"rating-item-header",children:[Rs(m.score),m.category&&e.jsx("span",{className:"rating-category-badge",children:m.category}),e.jsx("span",{className:"rating-time",children:ws(m.createdAt,l)}),e.jsx("button",{type:"button",className:"rating-delete-btn touch-target",onClick:()=>void M(m.id),title:l("agents.ratings.deleteRating","Delete rating"),children:e.jsx(yt,{size:14})})]}),m.comment&&e.jsx("p",{className:"rating-comment",children:m.comment})]},m.id))]})]})]}),e.jsxs("div",{className:"reflections-list",children:[e.jsx("h4",{children:l("agents.reflections.historyTitle","Reflection History")}),d?e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(J,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:l("agents.reflections.loading","Loading reflections...")})]}):r.length===0?e.jsxs("div",{className:"reflection-empty",children:[e.jsx(Ut,{size:32,opacity:.3}),e.jsx("p",{children:l("agents.reflections.noReflections","No reflections yet")}),e.jsx("p",{className:"text-secondary",children:l("agents.reflections.getStarted","Trigger a reflection to get started")})]}):e.jsx("div",{className:"reflection-cards",children:r.map(m=>{const k=j===m.id;return e.jsxs("div",{className:`reflection-card ${k?"reflection-card--expanded":""}`,onClick:()=>O(m.id),role:"button",tabIndex:0,onKeyDown:_=>_.key==="Enter"&&O(m.id),children:[e.jsxs("div",{className:"reflection-card-header",children:[e.jsx("span",{className:`reflection-trigger-badge reflection-trigger-${m.trigger}`,children:xn(m.trigger,l)}),e.jsx("span",{className:"reflection-timestamp",children:ws(m.timestamp,l)}),e.jsx("span",{className:"reflection-chevron",children:k?e.jsx(Hs,{size:16}):e.jsx(zs,{size:16})})]}),e.jsx("div",{className:"reflection-summary",children:m.summary}),k&&e.jsxs("div",{className:"reflection-details",children:[m.insights.length>0&&e.jsxs("div",{className:"reflection-insights",children:[e.jsxs("h5",{children:[e.jsx(Ut,{size:14})," ",l("agents.reflections.insights","Insights")]}),e.jsx("ul",{children:m.insights.map((_,ne)=>e.jsx("li",{children:_},ne))})]}),m.suggestedImprovements.length>0&&e.jsxs("div",{className:"reflection-suggestions",children:[e.jsxs("h5",{children:[e.jsx(xs,{size:14})," ",l("agents.reflections.suggestedImprovements","Suggested Improvements")]}),e.jsx("ul",{children:m.suggestedImprovements.map((_,ne)=>e.jsx("li",{children:_},ne))})]}),m.metrics&&e.jsxs("div",{className:"reflection-metrics",children:[e.jsx("h5",{children:l("agents.reflections.metrics","Metrics")}),e.jsxs("div",{className:"metrics-grid",children:[m.metrics.tasksCompleted!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:l("agents.reflections.metricTasks","Tasks:")}),e.jsx("span",{className:"metric-value",children:m.metrics.tasksCompleted})]}),m.metrics.tasksFailed!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:l("agents.reflections.metricFailed","Failed:")}),e.jsx("span",{className:"metric-value",children:m.metrics.tasksFailed})]}),m.metrics.avgDurationMs!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:l("agents.reflections.metricAvgDuration","Avg Duration:")}),e.jsx("span",{className:"metric-value",children:Cs(m.metrics.avgDurationMs)})]}),m.metrics.errorCount!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:l("agents.reflections.metricErrors","Errors:")}),e.jsx("span",{className:"metric-value",children:m.metrics.errorCount})]})]})]})]})]},m.id)})})]})]})}function me(...t){return t.filter(Boolean).join(" ")}const Nn={triage:["tasks:create","agents:view","messages:read"],executor:["tasks:execute","agents:view","messages:read","messages:send"],reviewer:["tasks:review","agents:view","messages:read","messages:send"],merger:["tasks:merge","agents:view","messages:read"],scheduler:["tasks:assign","tasks:create","tasks:archive","agents:view","automations:manage","missions:manage","messages:read"],engineer:["tasks:execute","tasks:review","agents:view","messages:read","messages:send"],custom:[]};function tt(t,i){const o=Date.now(),l=new Date(t).getTime(),r=o-l,c=i??((x,a,u)=>u?a.replace(/\{\{(\w+)\}\}/g,(w,R)=>String(u[R]??"")):a);if(r<0){const x=Math.abs(r);if(x<6e4)return c("time.inAMoment","in a moment");if(x<36e5){const u=Math.floor(x/6e4);return c("time.inMinutes","in {{n}}m",{n:u})}if(x<864e5){const u=Math.floor(x/36e5);return c("time.inHours","in {{n}}h",{n:u})}const a=Math.floor(x/864e5);return c("time.inDays","in {{n}}d",{n:a})}if(r<6e4)return c("time.justNow","just now");if(r<36e5){const x=Math.floor(r/6e4);return c("time.minutesAgo","{{n}}m ago",{n:x})}if(r<864e5){const x=Math.floor(r/36e5);return c("time.hoursAgo","{{n}}h ago",{n:x})}const y=Math.floor(r/864e5);return c("time.daysAgo","{{n}}d ago",{n:y})}const Sn="⚠️",kn=[{id:"dashboard",label:"Dashboard",icon:hn},{id:"logs",label:"Logs",icon:Nt},{id:"mail",label:"Mail",icon:ya},{id:"runs",label:"Runs",icon:Lt},{id:"tasks",label:"Tasks",icon:Us},{id:"employees",label:"Employees",icon:Vs},{id:"soul",label:"Soul",icon:Na},{id:"instructions",label:"Instructions",icon:un},{id:"memory",label:"Agent Memory",icon:Nt},{id:"reflections",label:"Evaluation",icon:Pt},{id:"config",label:"Settings",icon:Sa}],ls={idle:{bg:"var(--state-idle-bg)",text:"var(--state-idle-text)",border:"var(--state-idle-border)"},active:{bg:"var(--state-active-bg)",text:"var(--state-active-text)",border:"var(--state-active-border)"},running:{bg:"var(--state-active-bg)",text:"var(--state-active-text)",border:"var(--state-active-border)"},paused:{bg:"var(--state-paused-bg)",text:"var(--state-paused-text)",border:"var(--state-paused-border)"},error:{bg:"var(--state-error-bg)",text:"var(--state-error-text)",border:"var(--state-error-border)"}},Dt={completed:{icon:be,color:"var(--color-success)"},failed:{icon:Pa,color:"var(--color-error)"},active:{icon:J,color:"var(--in-progress)"},terminated:{icon:dt,color:"var(--text-muted)"}},Cn=Ks(as),wn=700,Ms=rs,As=rs,Rn=100,Mn=1e3;function ns(t,i){const o=Math.max(rs,t.length);return t.length+1<=o?[...t,i]:[...t.slice(t.length+1-o),i]}function Qs({entries:t,resetKey:i,testId:o}){const{t:l}=ke("app"),[r,c]=s.useState(Ms);s.useEffect(()=>{c(Ms)},[i]);const y=Math.max(0,t.length-r),x=s.useMemo(()=>t.length>r?t.slice(t.length-r):t,[t,r]),a=s.useCallback(()=>{c(u=>u+As)},[]);return e.jsxs(e.Fragment,{children:[y>0&&e.jsx("div",{className:"log-window-loader",children:e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm","data-testid":`${o}-load-older`,onClick:a,children:l("agents.loadOlderLogs","Load {{count}} older ({{remaining}} remaining)",{count:Math.min(As,y),remaining:y})})}),e.jsx(qa,{entries:x,loading:!1})]})}function An(t,i){return t.some(o=>o.path===i)?i:t.find(o=>o.layer==="long-term")?.path??t[0]?.path??""}function ei({agentId:t,projectId:i,onClose:o,addToast:l,onChildClick:r,inline:c=!1,showInlineBackButton:y=!1,initialTab:x,initialRunId:a,preferActiveRun:u=!1,onMutationSuccess:w,floatingWindowKey:R="agent-detail"}){const{t:d}=ke("app"),[g,I]=s.useState(null),[F,T]=s.useState(1),[z,V]=s.useState({}),{confirm:Z}=Is(),[j,N]=s.useState([]),[P,q]=s.useState(!0),[S,$]=s.useState(x??"dashboard"),[se,K]=s.useState(!1),[D,Q]=s.useState(!1),[E,H]=s.useState(!1),[M,O]=s.useState(!1),[b,m]=s.useState(!1),[k,_]=s.useState(!1),[ne,xe]=s.useState(0),[pe,Ve]=s.useState(0),[Ce,fe]=s.useState(0),[ce,ve]=s.useState(null),[Ae,ze]=s.useState(null),[p,A]=s.useState(!1),[v,ae]=s.useState(null),ee=s.useRef(null),je=s.useRef(!1),re=s.useRef(o),ye=s.useRef(l),Ee=s.useRef(null),st=s.useRef(!1),Fe=s.useRef(null),kt=s.useRef([]);kt.current=j;const Le=s.useRef(null),oe=s.useRef(0),Ie=s.useRef(t),ut=s.useRef(i);re.current=o,ye.current=l,Ee.current=g,s.useEffect(()=>{let f=!1;return ha(i).then(L=>{f||(T(L.heartbeatMultiplier??1),V(L))}).catch(()=>{f||T(1)}),()=>{f=!0}},[i]);const we=s.useCallback(async()=>{Ee.current===null&&q(!0);try{const L=await fa(t,i);I(L)}catch(L){ye.current(`Failed to load agent: ${B(L)}`,"error"),re.current()}finally{q(!1)}},[t,i]),at=s.useCallback(async f=>{const L=oe.current,G=t,U=i,te=()=>oe.current!==L||t!==G||i!==U;try{if(g?.taskId){const $e=g.taskId;ve(null),Fe.current=null;const Qe=Le.current===`task:${$e}`,it=Qe?kt.current:[],rt=it.length-pa(it),lt=Math.min(Mn,Math.max(Rn,rt)),he=await ba($e,U,{limit:lt});if(te())return;N(Ke=>xa(Qe?Ke:[],he.entries,[],$e).entries),Le.current=`task:${$e}`;return}const Re=await Os(G,1,U);if(te())return;const ge=Re[0]??null;if(ve(ge),!ge){Fe.current=null,Le.current=null,N([]);return}if(!f?.force&&Fe.current===ge.id)return;const Be=await ts(G,ge.id,U);if(te())return;N(Be),Le.current=`run:${ge.id}`,Fe.current=ge.id}catch(Re){if(te())return;console.error("Failed to load agent logs:",Re)}},[g?.taskId,t,i]),mt=s.useRef(at);mt.current=at;const gt=s.useCallback(async()=>{A(!0),ae(null);try{const f=await va(t,i);ze(f)}catch(f){ae(B(f)),ze(null)}finally{A(!1)}},[t,i]),Bt=s.useCallback(f=>{st.current=f},[]),ht=s.useCallback(async(f=!1)=>{await w?.({agentId:t,deleted:f})},[t,w]),Ge=s.useCallback(async()=>{await we(),await ht(!1)},[we,ht]);s.useEffect(()=>{we()},[we]),s.useEffect(()=>{const f=setInterval(()=>{we()},3e4);return()=>{clearInterval(f)}},[we]),s.useEffect(()=>{g&&S==="logs"&&at()},[g,S,at]),s.useEffect(()=>{S!=="logs"&&(Fe.current=null)},[S]),s.useEffect(()=>{g&&S==="mail"&&gt()},[g,S,gt]),s.useEffect(()=>{if(!M)return;const f=G=>{ee.current?.contains(G.target)||O(!1)},L=G=>{G.key==="Escape"&&O(!1)};return document.addEventListener("mousedown",f),document.addEventListener("keydown",L),()=>{document.removeEventListener("mousedown",f),document.removeEventListener("keydown",L)}},[M]),s.useEffect(()=>{if(!M)return;let f=!1;return _(!0),Et(void 0,i).then(L=>{if(f)return;const G=L.filter(U=>!Vt(U));xe(G.filter(U=>U.state==="active"||U.state==="running").length),Ve(G.filter(U=>U.state==="paused").length)}).catch(()=>{f||(xe(0),Ve(0))}).finally(()=>{f||_(!1)}),()=>{f=!0}},[M,i]),s.useEffect(()=>{if(S!=="logs"||g?.taskId||!ce||ce.status!=="active")return;const f=oe.current,L=t,G=ce.id,U=i?`?projectId=${encodeURIComponent(i)}`:"",te=Tt(`/api/agents/${encodeURIComponent(L)}/runs/${encodeURIComponent(G)}/logs/stream${U}`,{events:{"agent:log":Re=>{if(oe.current===f)try{const ge=JSON.parse(Re.data);N(Be=>ns(Be,ge))}catch{}}},onOpen:()=>{oe.current===f&&K(!0)},onReconnect:()=>{oe.current===f&&(K(!0),mt.current({force:!0}))},onError:()=>{oe.current===f&&K(!1)}});return()=>{te(),oe.current===f&&K(!1)}},[S,g?.taskId,t,i,ce]),s.useEffect(()=>{(Ie.current!==t||ut.current!==i)&&(Ie.current=t,ut.current=i,oe.current++,N([]),K(!1),ve(null),ze(null),ae(null),Fe.current=null,Le.current=null,st.current=!1)},[t,i]),s.useEffect(()=>{const f=i?`?projectId=${encodeURIComponent(i)}`:"",L=oe.current,G=U=>{if(oe.current===L)try{const te=JSON.parse(U.data);if(!te||typeof te!="object"||te.agentId!==t)return;we()}catch{}};return Tt(`/api/events${f}`,{events:{"agent:updated":U=>{if(oe.current===L)try{const te=JSON.parse(U.data);if(!te||typeof te!="object"||te.id!==t||st.current)return;we()}catch{}},"approval:requested":G,"approval:updated":G,"approval:decided":G},onReconnect:()=>{oe.current===L&&(st.current||we())}})},[t,i,we]),s.useEffect(()=>{if(S!=="logs"||!g?.taskId){K(!1);return}const f=oe.current,L=g.taskId,G=i?`?projectId=${encodeURIComponent(i)}`:"",U=Tt(`/api/tasks/${encodeURIComponent(L)}/logs/stream${G}`,{events:{"agent:log":te=>{if(oe.current===f)try{const Re=JSON.parse(te.data);N(ge=>ns(ge,Re))}catch{}}},onOpen:()=>{oe.current===f&&K(!0)},onReconnect:()=>{oe.current===f&&(K(!0),mt.current({force:!0}))},onError:()=>{oe.current===f&&K(!1)}});return()=>{U(),oe.current===f&&K(!1)}},[g?.taskId,S,i]);const De=async f=>{if(D||!Ee.current)return;const L=Ee.current.state;if(L!==f){Q(!0),I(G=>G&&{...G,state:f});try{await ys(t,f,i),l(d("agents.stateUpdated","Agent state updated to {{newState}}",{newState:f}),"success"),await Ge()}catch(G){I(U=>U&&{...U,state:L}),l(d("agents.stateUpdateFailed","Failed to update state: {{error}}",{error:B(G)}),"error")}finally{Q(!1)}}},ft=async f=>{if(!b){O(!1),m(!0);try{const G=(await Et(void 0,i)).filter(he=>!Vt(he)),U=G.filter(he=>f==="paused"?he.state==="active"||he.state==="running":he.state==="paused"),te=G.length-U.length;if(U.length===0){l(d("agents.bulkNoEligible","No agents eligible to {{action}}",{action:f==="paused"?d("agents.pause","pause"):d("agents.resume","resume")}),"error");return}if(!await Z({title:f==="paused"?d("agents.pauseAllTitle","Pause All Agents"):d("agents.resumeAllTitle","Resume All Agents"),message:d("agents.bulkConfirmMessage","{{action}} {{count}} agent(s) in this project?",{action:f==="paused"?d("agents.pauseAction","Pause"):d("agents.resumeAction","Resume"),count:U.length}),danger:f==="paused"}))return;const ge=await Promise.allSettled(U.map(he=>ys(he.id,f,i))),Be=ge.map((he,Ke)=>({result:he,agent:U[Ke]})).filter(he=>he.result.status==="rejected"),$e=ge.length-Be.length,Qe=Be.length,it=f==="paused"?d("agents.pausedPast","Paused"):d("agents.resumedPast","Resumed"),rt=$e===1?d("agents.agentSingular","agent"):d("agents.agentPlural","agents"),lt=d($e===1?"agents.bulkResult_one":"agents.bulkResult_other","{{action}} {{successCount}} {{agentWord}}; skipped {{skippedCount}}",{action:it,successCount:$e,agentWord:rt,skippedCount:te});if(Qe>0){const he=Be.slice(0,3).map(({agent:Ke,result:_e})=>`${Ke.name||Ke.id}: ${B(_e.reason)}`).join("; ");l(d("agents.bulkResultWithFailures","{{summary}}; failed {{failureCount}}{{detail}}",{summary:lt,failureCount:Qe,detail:he?` (${he})`:""}),"error")}else l(lt,"success");await Ge()}catch(L){l(d("agents.bulkActionFailed","Failed to {{action}} agents: {{error}}",{action:f==="paused"?d("agents.pause","pause"):d("agents.resume","resume"),error:B(L)}),"error")}finally{m(!1)}}},pt=async()=>{if(!E){H(!0);try{await wa(t,i,{source:"on_demand",triggerDetail:"Triggered from dashboard"}),l(d("agents.heartbeatStarted","Heartbeat run started for {{name}}",{name:g?.name??t}),"success"),fe(f=>f+1)}catch(f){l(d("agents.heartbeatStartFailed","Failed to start heartbeat run: {{error}}",{error:B(f)}),"error")}finally{H(!1)}}},nt=async()=>{if(!(!g||!await Z({title:d("agents.deleteTitle","Delete Agent"),message:d("agents.deleteConfirm",'Delete agent "{{name}}"? This cannot be undone.',{name:g.name}),danger:!0})))try{await Ra(t,i),l(d("agents.deleted",'Agent "{{name}}" deleted',{name:g.name}),"success"),await ht(!0),o()}catch(L){l(d("agents.deleteFailed","Failed to delete agent: {{error}}",{error:B(L)}),"error")}},Ct=()=>g?Ca(g,F):{label:"Unknown",icon:e.jsx(is,{size:14}),color:"var(--text-muted)",stateDerived:!1},Xe=async()=>{if(g){const f=await Ja(g.id);l(f?d("agents.idCopied","Agent ID copied to clipboard"):d("agents.idCopyFailed","Failed to copy agent ID"),f?"success":"error")}};if(P)return c?e.jsx("div",{className:"agent-detail-inline-loading",role:"region","aria-label":d("agents.detailLoadingLabel","Agent detail loading"),children:e.jsxs("div",{className:"agent-detail-loading",children:[e.jsx(J,{className:"animate-spin",size:24}),e.jsx("span",{children:d("agents.loading","Loading agent...")})]})}):e.jsx(vs,{windowKey:R,title:d("agents.loading","Loading agent..."),ariaLabel:d("agents.detailLoadingLabel","Agent detail loading"),onClose:o,modal:!0,hideHeader:!0,dragHandleSelector:".agent-detail-header",className:"floating-window--agent-detail",defaultSize:{width:608,height:640},minSize:{width:400,height:320},persistGeometryKey:`floating-window:${R}`,suspendGeometryPersistenceOnMobile:!0,suspendGeometryPersistenceOnShortViewport:!0,backdropMouseHandlers:{onMouseDown:f=>{f.target===f.currentTarget&&(je.current=!0)},onMouseUp:f=>{je.current&&f.target===f.currentTarget&&o(),je.current=!1}},children:e.jsx("div",{className:"agent-detail-modal",children:e.jsxs("div",{className:"agent-detail-loading",children:[e.jsx(J,{className:"animate-spin",size:24}),e.jsx("span",{children:d("agents.loading","Loading agent...")})]})})});if(!g)return null;const He=ls[g.state],de=Ct(),Je=`${R}-modal-title`,Pe=c?"agent-detail-inline":"agent-detail-modal",Ze=k||ne===0,Oe=k||pe===0,qe=e.jsxs("div",{className:Pe,children:[e.jsxs("div",{className:"agent-detail-header",children:[e.jsxs("div",{className:"agent-detail-identity",children:[c&&y?e.jsxs("button",{type:"button",className:"btn agent-detail-inline-back",onClick:o,"aria-label":d("agents.backToAgents","Back to agents"),children:[e.jsx(Bs,{size:16}),d("agents.agentsLabel","Agents")]}):null,e.jsx("div",{className:"agent-detail-icon",children:e.jsx($s,{agent:g,size:36})}),e.jsxs("div",{className:"agent-detail-info",children:[e.jsx("h2",{id:Je,children:g.name}),e.jsxs("div",{className:"agent-detail-badges",children:[e.jsx("span",{className:"badge",style:{background:He.bg,color:He.text,border:`1px solid ${He.border}`},children:g.state}),e.jsxs("span",{className:"badge",style:{color:de.color},title:de.reason??de.label,children:[de.icon,!de.stateDerived&&de.label]})]})]})]}),e.jsxs("div",{className:"agent-detail-header-actions",children:[e.jsxs("div",{className:"agent-detail-controls",children:[g.state==="idle"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void De("active"),disabled:D,children:[e.jsx(Wt,{size:14}),d("agents.start","Start")]}),e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void pt(),"aria-label":d("agents.runNowFor","Run now for {{name}}",{name:g.name}),disabled:E||D,children:[e.jsx(Lt,{size:14}),d("agents.runNow","Run Now")]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:nt,children:[e.jsx(yt,{size:14}),d("agents.delete","Delete")]})]}),g.state==="active"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--compact agent-detail-mobile-icon-control",onClick:()=>void De("paused"),disabled:D,"aria-label":d("agents.pause","Pause"),children:[e.jsx(js,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:d("agents.pause","Pause")})]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:()=>void De("paused"),disabled:D,"aria-label":d("agents.stop","Stop"),children:[e.jsx(dt,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:d("agents.stop","Stop")})]}),e.jsxs("button",{className:"btn btn-task-create btn--compact agent-detail-mobile-icon-control",onClick:()=>void pt(),"aria-label":d("agents.runNowFor","Run now for {{name}}",{name:g.name}),disabled:E||D,children:[e.jsx(Lt,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:d("agents.runNow","Run Now")})]})]}),g.state==="paused"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact agent-detail-mobile-icon-control",onClick:()=>void De("active"),disabled:D,"aria-label":d("agents.resume","Resume"),children:[e.jsx(Wt,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:d("agents.resume","Resume")})]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:nt,children:[e.jsx(yt,{size:14}),d("agents.delete","Delete")]})]}),g.state==="running"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--compact agent-detail-mobile-icon-control",onClick:()=>void De("paused"),disabled:D,"aria-label":d("agents.pause","Pause"),children:[e.jsx(js,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:d("agents.pause","Pause")})]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:()=>void De("paused"),disabled:D,"aria-label":d("agents.stop","Stop"),children:[e.jsx(dt,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:d("agents.stop","Stop")})]})]}),g.state==="error"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void De("active"),disabled:D,children:[e.jsx(Wt,{size:14}),d("agents.retry","Retry")]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:()=>void De("paused"),disabled:D,"aria-label":d("agents.stop","Stop"),children:[e.jsx(dt,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:d("agents.stop","Stop")})]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:nt,"aria-label":d("agents.delete","Delete"),children:[e.jsx(yt,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:d("agents.delete","Delete")})]})]})]}),e.jsxs("div",{className:"agent-detail-utility-actions",children:[e.jsxs("div",{className:"agent-detail-bulk-menu",ref:ee,children:[e.jsx("button",{type:"button",className:"btn-icon",onClick:()=>O(f=>!f),"aria-haspopup":"menu","aria-expanded":M,"aria-label":d("agents.bulkActions","Bulk agent actions"),title:d("agents.bulkActions","Bulk agent actions"),disabled:D||b,children:e.jsx(ja,{size:16})}),M&&e.jsxs("div",{className:"agent-detail-bulk-menu-popover",role:"menu",children:[e.jsxs("button",{type:"button",role:"menuitem",className:"agent-detail-bulk-menu-item",onClick:()=>void ft("paused"),disabled:Ze||b,children:[d("agents.pauseAll","Pause All Agents"),e.jsx("span",{className:"agent-detail-bulk-menu-item-hint",children:k?d("agents.loadingEligible","Loading eligible agents..."):Ze?d("agents.noActiveEligible","No active agents eligible"):d(ne===1?"agents.pauseCountHint_one":"agents.pauseCountHint_other",ne===1?"Pause {{count}} active/running agent":"Pause {{count}} active/running agents",{count:ne})})]}),e.jsxs("button",{type:"button",role:"menuitem",className:"agent-detail-bulk-menu-item",onClick:()=>void ft("active"),disabled:Oe||b,children:[d("agents.resumeAll","Resume All Agents"),e.jsx("span",{className:"agent-detail-bulk-menu-item-hint",children:k?d("agents.loadingEligible","Loading eligible agents..."):Oe?d("agents.noPausedEligible","No paused agents eligible"):d(pe===1?"agents.resumeCountHint_one":"agents.resumeCountHint_other",pe===1?"Resume {{count}} paused agent":"Resume {{count}} paused agents",{count:pe})})]})]})]}),e.jsx("button",{className:"btn-icon",onClick:()=>void we(),title:d("common.refresh","Refresh"),"aria-label":d("common.refresh","Refresh"),children:e.jsx(St,{size:16})}),!c&&e.jsx("button",{className:"btn-icon",onClick:o,"aria-label":d("common.close","Close"),title:d("common.close","Close"),children:e.jsx(_s,{size:20})})]})]})]}),e.jsx("div",{className:"agent-detail-tabs",children:kn.map(f=>{const L={dashboard:d("agents.tabDashboard","Dashboard"),logs:d("agents.tabLogs","Logs"),mail:d("agents.tabMail","Mail"),runs:d("agents.tabRuns","Runs"),tasks:d("agents.tabTasks","Tasks"),employees:d("agents.tabEmployees","Employees"),soul:d("agents.tabSoul","Soul"),instructions:d("agents.tabInstructions","Instructions"),memory:d("agents.tabMemory","Agent Memory"),reflections:d("agents.tabReflections","Evaluation"),config:d("agents.tabConfig","Settings")};return e.jsxs("button",{className:me("agent-detail-tab",S===f.id&&"active"),onClick:()=>$(f.id),children:[e.jsx(f.icon,{size:16}),L[f.id]]},f.id)})}),e.jsxs("div",{className:"agent-detail-content",children:[S==="dashboard"&&e.jsx(Fn,{agent:g,health:de,onChildClick:r,projectId:i,agentModelSettings:z}),S==="logs"&&e.jsx(Pn,{logs:j,isStreaming:se,hasTask:!!g.taskId||j.length>0||ce!==null,fallbackLabel:!g.taskId&&ce?d("agents.latestRunLabel","Latest run · {{id}}",{id:ce.id.slice(0,8)}):null,windowResetKey:g.taskId??ce?.id??"none"}),S==="mail"&&e.jsx(En,{agent:g,mailbox:Ae,isLoading:p,error:v,projectId:i,addToast:l,onRefresh:()=>void gt()}),S==="runs"&&e.jsx(Ln,{addToast:l,agentId:g.id,projectId:i,agentState:g.state,agentName:g.name,initialRunId:a,preferActiveRun:u,runNowRefreshToken:Ce,isEphemeral:Vt(g)}),S==="tasks"&&e.jsx(zn,{agentId:g.id,projectId:i,addToast:l}),S==="employees"&&e.jsx(Vn,{agentId:g.id,projectId:i,onChildClick:r}),S==="soul"&&e.jsx(On,{agent:g,projectId:i,addToast:l,onSaved:Ge}),S==="instructions"&&e.jsx($n,{agent:g,projectId:i,addToast:l,onSaved:Ge}),S==="memory"&&e.jsx(Bn,{agent:g,projectId:i,addToast:l,onSaved:Ge}),S==="reflections"&&e.jsx(yn,{agentId:g.id,projectId:i,addToast:l}),S==="config"&&e.jsx(Un,{agent:g,projectId:i,agentModelSettings:z,addToast:l,onSaved:Ge,onHasChangesChange:Bt,onDelete:nt,onAgentDraftApplied:f=>{I(L=>L&&{...L,...f})}},g.id)]}),!c&&e.jsxs("div",{className:"agent-detail-footer",children:[e.jsx("button",{className:"btn-icon",onClick:Xe,title:d("agents.copyId","Copy Agent ID"),children:e.jsx(ka,{})}),e.jsx("span",{className:"agent-detail-id",onClick:Xe,children:g.id}),g.taskId&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"divider",children:"|"}),e.jsx("span",{className:"text-muted",children:d("agents.workingOn","Working on:")}),e.jsxs("a",{href:`/tasks/${g.taskId}`,className:"link",children:[e.jsx(Ws,{taskId:g.taskId,taskColumn:g.taskColumn}),e.jsx(Gs,{size:12})]})]})]})]});return c?e.jsx("div",{className:"agent-detail-inline-shell",role:"region","aria-label":"Agent detail",children:qe}):e.jsx(vs,{windowKey:R,title:g.name,ariaLabelledBy:Je,onClose:o,modal:!0,hideHeader:!0,dragHandleSelector:".agent-detail-header",className:"floating-window--agent-detail",defaultSize:{width:608,height:640},minSize:{width:400,height:320},persistGeometryKey:`floating-window:${R}`,suspendGeometryPersistenceOnMobile:!0,suspendGeometryPersistenceOnShortViewport:!0,backdropMouseHandlers:{onMouseDown:f=>{f.target===f.currentTarget&&(je.current=!0)},onMouseUp:f=>{je.current&&f.target===f.currentTarget&&o(),je.current=!1}},children:qe})}function Fn({agent:t,health:i,onChildClick:o,projectId:l,agentModelSettings:r}){const{t:c}=ke("app"),y=ls[t.state],[x,a]=s.useState([]),[u,w]=s.useState(!0),[R,d]=s.useState(null),[g,I]=s.useState([]),[F,T]=s.useState(null),[z,V]=s.useState(null),[Z,j]=s.useState(!1),[N,P]=s.useState(null),q=typeof t.runtimeConfig?.runtimeHint=="string"?t.runtimeConfig.runtimeHint:"",S=(()=>{const b=t.runtimeConfig??{};if(q){const k=g.find(_=>_.runtimeId===q);return k?k.name:q}if(b.modelProvider&&b.modelId)return`${b.modelProvider}/${b.modelId}`;if(typeof b.model=="string"&&b.model.includes("/")){const k=b.model.indexOf("/");return b.model.slice(k+1)}const m=rn(t,r);return m.provider&&m.modelId?`${m.provider}/${m.modelId}`:null})();s.useEffect(()=>{ss(t.id,l).then(d).catch(()=>d(null))},[t.id,l]),s.useEffect(()=>{Js(l).then(I).catch(()=>I([]))},[l]),s.useEffect(()=>{let b=!1;return w(!0),Ma(t.id,l).then(m=>{if(b)return;const k=m.length>0&&m[0]?.id===t.id?[...m].reverse():m;a(k)}).catch(()=>{b||a([])}).finally(()=>{b||w(!1)}),()=>{b=!0}},[t.id,l]);const $=s.useMemo(()=>{const b=t.completedRuns||[],m=new Date;m.setHours(0,0,0,0);const k=b.filter(ne=>new Date(ne.startedAt)>=m),_=b.filter(ne=>ne.status==="completed");return{totalRuns:b.length,todayRuns:k.length,successfulRuns:_.length,successRate:b.length>0?Math.round(_.length/b.length*100):0}},[t]),se=(t.completedRuns||[]).slice(0,5),K=Array.isArray(t.metadata?.skills)?t.metadata.skills:[],D=F?qt(F):null,Q=s.useCallback(async b=>{j(!0),P(null),V(null);try{const m=await Aa(b,l);V(m)}catch(m){P(B(m))}finally{j(!1)}},[l]),E=s.useCallback(b=>{if(F===b){T(null),V(null),P(null),j(!1);return}T(b),Q(b)},[Q,F]),H=t.state==="active"||t.state==="running",M=Fa(t.runtimeConfig?.heartbeatIntervalMs),O=H&&t.lastHeartbeatAt?new Date(new Date(t.lastHeartbeatAt).getTime()+M).toISOString():null;return e.jsxs("div",{className:"dashboard-tab dashboard-summary-layout",children:[R?.isOverBudget&&e.jsxs("div",{className:"budget-warning-banner",role:"alert",children:[e.jsx("span",{children:Sn}),e.jsxs("span",{children:[e.jsx("strong",{children:c("agents.budgetExhaustedTitle","Budget Exhausted:")})," ",c("agents.budgetExhaustedBody","This agent has exceeded its token budget and may operate with limited functionality.")]})]}),e.jsxs("section",{className:"dashboard-summary-card dashboard-summary-hero",children:[e.jsxs("div",{className:"dashboard-summary-hero__heading",children:[e.jsx(is,{}),e.jsx("h3",{children:c("agents.overview","Overview")}),e.jsx("strong",{children:t.name}),e.jsx("span",{className:"inline-badge",style:{background:y.bg,color:y.text},children:t.state})]}),e.jsxs("div",{className:"dashboard-summary-hero__meta",children:[e.jsxs("span",{className:"dashboard-summary-hero__health",title:i.reason??i.label,children:[i.icon," ",i.label]}),(t.pendingApprovalCount??0)>0?e.jsxs("span",{className:"badge agent-detail-approval-badge",title:c("agents.pendingApprovals","Pending approvals"),children:[e.jsx("span",{className:"status-dot status-dot--pending"}),c("agents.pendingApprovalsCount","{{count}} pending approvals",{count:t.pendingApprovalCount})]}):null,e.jsx("span",{children:c("agents.roleLabel","Roles: {{role}}",{role:(t.roles??[t.role]).join(", ")})}),e.jsxs("span",{children:[e.jsx("span",{className:"dashboard-summary-label",children:q?c("agents.runtime","Runtime"):c("agents.model","Model")}),e.jsxs("span",{children:[" ",S??c("agents.auto","Auto")]})]}),K.length>0?e.jsxs("span",{className:"dashboard-summary-skills",children:[e.jsx("span",{className:"dashboard-summary-label",children:c("agents.skills","Skills")}),e.jsx("span",{className:"dashboard-summary-skill-badges",role:"list","aria-label":c("agents.assignedSkills","Assigned skills"),children:K.map(b=>{const m=F===b;return e.jsx("button",{type:"button",className:me("badge","badge-skill","dashboard-summary-skill-badge","dashboard-summary-skill-badge-btn",m&&"dashboard-summary-skill-badge--selected"),title:b,onClick:()=>E(b),"aria-expanded":m,"aria-label":c("agents.viewSkillDetails","View details for {{skill}}",{skill:qt(b)}),children:qt(b)},b)})})]}):e.jsx("span",{children:c("agents.skillsNone","Skills: —")})]}),F?e.jsxs("div",{className:"dashboard-summary-skill-detail","data-testid":"agent-skill-detail",children:[e.jsxs("div",{className:"dashboard-summary-skill-detail-header",children:[e.jsx("span",{className:"dashboard-summary-skill-detail-title",children:D}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>E(F),children:[e.jsx(_s,{size:14}),c("common.close","Close")]})]}),Z?e.jsxs("div",{className:"dashboard-summary-skill-detail-loading",role:"status","aria-live":"polite",children:[e.jsx(J,{size:14,className:"animate-spin"}),c("agents.loadingSkillContent","Loading skill content...")]}):N?e.jsxs("div",{className:"dashboard-summary-skill-detail-error",role:"alert",children:[e.jsx(qs,{size:14}),e.jsx("span",{children:N}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void Q(F),children:c("common.retry","Retry")})]}):z?e.jsx("pre",{className:"dashboard-summary-skill-detail-content",children:z.skillMd||c("agents.noSkillMd","(No SKILL.md found)")}):e.jsx("div",{className:"dashboard-summary-skill-detail-empty",children:c("agents.noSkillContent","No skill content available")})]}):null]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:c("agents.heartbeatAndHealth","Heartbeat & Health")}),e.jsxs("div",{className:"dashboard-summary-grid",children:[e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:c("agents.lastHeartbeat","Last heartbeat")}),e.jsx("p",{children:t.lastHeartbeatAt?tt(t.lastHeartbeatAt,c):c("agents.never","Never")})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:c("agents.nextExpected","Next expected")}),e.jsx("p",{children:O?tt(O,c):c("agents.notScheduled","Not scheduled")})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:c("agents.interval","Interval")}),e.jsx("p",{children:Ks(M)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:c("agents.status","Status")}),e.jsxs("p",{className:"dashboard-summary-health-row",children:[e.jsx("span",{className:me("status-dot",t.state==="running"&&"status-dot--running")}),i.label,i.reason&&e.jsxs("span",{className:"text-secondary dashboard-summary-health-reason",title:i.reason,children:["(",i.reason,")"]})]})]})]})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:c("agents.currentWork","Current Work")}),t.taskId?e.jsxs("div",{className:"current-task",children:[e.jsx("a",{href:`/tasks/${t.taskId}`,className:"task-badge",children:e.jsx(Ws,{taskId:t.taskId,taskColumn:t.taskColumn})}),e.jsxs("a",{href:`/tasks/${t.taskId}`,className:"btn btn-sm",children:[c("agents.viewTask","View Task")," ",e.jsx(Gs,{size:14})]})]}):e.jsx("p",{className:"text-muted",children:c("agents.noActiveAssignment","No active assignment")})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:c("agents.recentRuns","Recent Runs")}),e.jsx("p",{className:"dashboard-summary-label",children:c("agents.runsSuccessRate","{{successful}}/{{total}} successful ({{rate}}%)",{successful:$.successfulRuns,total:$.totalRuns,rate:$.successRate})}),se.length===0?e.jsx("p",{className:"text-muted",children:c("agents.noRunsYet","No runs yet")}):e.jsx("div",{className:"runs-list",children:se.map(b=>{const m=Dt[b.status]||Dt.terminated,k=m.icon;return e.jsxs("div",{className:"run-item",children:[e.jsx(k,{size:14,style:{color:m.color}}),e.jsx("span",{children:tt(b.startedAt,c)}),e.jsxs("span",{className:"text-muted",children:[Math.max(0,Math.round((new Date(b.endedAt||b.startedAt).getTime()-new Date(b.startedAt).getTime())/1e3)),"s"]})]},b.id)})})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:c("agents.throughput","Throughput")}),e.jsxs("div",{className:"stats-grid",children:[e.jsxs("div",{className:"stat-card",children:[e.jsx("div",{className:"stat-value",children:$.totalRuns}),e.jsx("div",{className:"stat-label",children:c("agents.totalRuns","Total Runs")})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("div",{className:"stat-value",children:$.todayRuns}),e.jsx("div",{className:"stat-label",children:c("agents.runsToday","Runs Today")})]}),e.jsxs("div",{className:"stat-card",children:[e.jsxs("div",{className:"stat-value",children:[$.successRate,"%"]}),e.jsx("div",{className:"stat-label",children:c("agents.successRate","Success Rate")})]})]})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:c("agents.chainOfCommand","Chain of Command")}),u?e.jsxs("div",{className:"chain-of-command-loading",role:"status","aria-live":"polite",children:[e.jsx(J,{size:14,className:"animate-spin"}),e.jsx("span",{children:c("agents.loadingReportingChain","Loading reporting chain...")})]}):x.length<=1?e.jsx("p",{className:"text-muted",children:c("agents.noReportingChain","No reporting chain")}):e.jsx("div",{className:"chain-of-command-path","aria-label":c("agents.chainOfCommand","Chain of command"),children:x.map((b,m)=>{const k=m===x.length-1,_=!k;return e.jsxs("div",{className:"chain-of-command-item",children:[e.jsx("button",{type:"button",className:`chain-of-command-node${k?" chain-of-command-node--current":""}`,onClick:()=>_&&o?.(b.id),disabled:!_||!o,title:k?c("agents.currentAgent","Current agent"):c("agents.viewAgent","View {{name}}",{name:b.name}),children:b.name}),!k&&e.jsx("span",{className:"chain-of-command-separator","aria-hidden":"true",children:"→"})]},b.id)})})]})]})}function Pn({logs:t,isStreaming:i,hasTask:o,fallbackLabel:l,windowResetKey:r}){const{t:c}=ke("app");return o?e.jsxs("div",{className:"logs-tab",children:[e.jsxs("div",{className:"logs-header",children:[e.jsx("span",{className:"logs-count",children:c("agents.logEntries","{{count}} entries",{count:t.length})}),l&&e.jsx("span",{className:"text-muted logs-fallback-label",children:l}),i&&e.jsxs("span",{className:"streaming-indicator",children:[e.jsx("span",{className:"streaming-dot"}),c("agents.live","Live")]})]}),t.length===0?e.jsxs("div",{className:"logs-empty",children:[e.jsx(Nt,{size:48,opacity:.3}),e.jsx("p",{children:c("agents.noLogEntriesYet","No log entries yet")}),e.jsx("p",{className:"text-muted",children:i?c("agents.waitingForActivity","Waiting for activity..."):c("agents.logsWillAppearActive","Logs will appear here when the agent is active")})]}):e.jsx(Qs,{entries:t,resetKey:r,testId:"agent-logs"})]}):e.jsx("div",{className:"logs-tab",children:e.jsxs("div",{className:"logs-empty",children:[e.jsx(Nt,{size:48,opacity:.3}),e.jsx("p",{children:c("agents.noActivityYet","No activity yet")}),e.jsx("p",{className:"text-muted",children:c("agents.logsWillAppear","Agent logs will appear here from the current task or most recent run")})]})})}function Tn(t,i){const o=new Date(t),r=new Date().getTime()-o.getTime(),c=Math.floor(r/6e4),y=Math.floor(r/36e5),x=Math.floor(r/864e5),a=i??((u,w,R)=>R?w.replace(/\{\{(\w+)\}\}/g,(d,g)=>String(R[g]??"")):w);return c<1?a("time.justNow","just now"):c<60?a("time.minutesAgo","{{n}}m ago",{n:c}):y<24?a("time.hoursAgo","{{n}}h ago",{n:y}):x<7?a("time.daysAgo","{{n}}d ago",{n:x}):o.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function Ft(t,i,o,l){const r=l??((c,y,x)=>x?y.replace(/\{\{(\w+)\}\}/g,(a,u)=>String(x[u]??"")):y);if(i==="user")return t==="dashboard"?r("mailbox.you","You"):r("mailbox.userLabel","User: {{id}}",{id:t});if(i==="agent"){const c=o?.get(t)?.trim();return!c||c===t?r("mailbox.agentById","Agent: {{id}}",{id:t}):r("mailbox.agentByName","Agent: {{name}}",{name:c})}return r("mailbox.system","System")}function En({agent:t,mailbox:i,isLoading:o,error:l,projectId:r,addToast:c,onRefresh:y}){const{t:x}=ke("app"),[a,u]=s.useState("inbox"),[w,R]=s.useState([]);s.useEffect(()=>{let j=!1;return Et(void 0,r).then(N=>{j||R(N)}).catch(()=>{j||R([])}),()=>{j=!0}},[r]);const d=s.useMemo(()=>{const j=new Map;for(const P of w){if(!P.id)continue;const q=typeof P.name=="string"?P.name.trim():"";q.length>0&&j.set(P.id,q)}const N=typeof t.name=="string"?t.name.trim():"";return N.length>0&&j.set(t.id,N),j},[w,t.id,t.name]),[g,I]=s.useState(null),F=a==="inbox"?i?.inbox??[]:i?.outbox??[],T=g?F.find(j=>j.id===g)??null:null;s.useEffect(()=>{I(null)},[a,t.id]);const z=async j=>{if(I(j.id),!(a!=="inbox"||j.read))try{await an(j.id,r),y()}catch(N){const P=`Failed to mark message as read: ${B(N)}`;c?c(P,"error"):console.warn(P)}},V=()=>{I(null),y()},Z=j=>e.jsxs("button",{type:"button",className:me("mailbox-item","agent-mail-tab-message",a==="inbox"&&!j.read&&"unread",g===j.id&&"agent-mail-tab-message--selected"),onClick:()=>void z(j),"aria-pressed":g===j.id,children:[e.jsx("div",{className:"mailbox-item-avatar",children:(a==="inbox"?j.fromType:j.toType)==="agent"?e.jsx(is,{size:16}):e.jsx(Ka,{size:16})}),e.jsxs("div",{className:"mailbox-item-content",children:[e.jsxs("div",{className:"mailbox-item-header",children:[a==="inbox"?e.jsx("span",{className:"mailbox-item-from",children:Ft(j.fromId,j.fromType,d,x)}):e.jsx("span",{className:"mailbox-item-to",children:x("agents.mailTo","To: {{recipient}}",{recipient:Ft(j.toId,j.toType,d,x)})}),e.jsx("span",{className:"mailbox-item-time",children:Tn(j.createdAt,x)})]}),e.jsxs("div",{className:"mailbox-item-preview",children:[j.content.slice(0,80),j.content.length>80?"…":""]})]}),a==="inbox"&&!j.read?e.jsx("div",{className:"mailbox-item-unread-dot","aria-label":x("agents.unreadMessage","Unread message")}):null]},j.id);return e.jsxs("div",{className:"agent-mail-tab",children:[e.jsxs("div",{className:"agent-mail-tab-header",children:[e.jsx("h3",{children:x("agents.agentMail","{{name}} Mail",{name:t.name})}),e.jsxs("button",{className:"btn btn-sm",onClick:V,disabled:o,children:[e.jsx(St,{size:14}),x("common.refresh","Refresh")]})]}),e.jsxs("div",{className:"mailbox-agent-subtabs","data-testid":"agent-detail-mail-subtabs",children:[e.jsxs("button",{className:me("btn","btn-sm","btn-secondary","mailbox-agent-subtab",a==="inbox"&&"active"),onClick:()=>u("inbox"),children:[e.jsx(Ns,{size:12}),e.jsx("span",{children:x("agents.inbox","Inbox")}),(i?.unreadCount??0)>0?e.jsx("span",{className:"mailbox-tab-badge",children:i?.unreadCount}):null]}),e.jsxs("button",{className:me("btn","btn-sm","btn-secondary","mailbox-agent-subtab",a==="outbox"&&"active"),onClick:()=>u("outbox"),children:[e.jsx(Ss,{size:12}),e.jsx("span",{children:x("agents.outbox","Outbox")})]})]}),o&&!i?e.jsxs("div",{className:"agent-detail-loading agent-detail-loading--inline",role:"status","aria-live":"polite",children:[e.jsx(J,{className:"animate-spin",size:16}),e.jsx("span",{children:x("agents.loadingMailbox","Loading mailbox...")})]}):null,!o&&l?e.jsxs("div",{className:"agent-mail-tab-error",role:"alert",children:[e.jsx(qs,{size:16}),e.jsx("span",{children:x("agents.mailboxLoadFailed","Failed to load mailbox: {{error}}",{error:l})})]}):null,!o&&!l?T?e.jsxs("div",{className:"agent-mail-tab-detail","data-testid":"agent-detail-mail-message",children:[e.jsxs("button",{type:"button",className:"btn btn-sm agent-mail-tab-back","data-testid":"agent-detail-mail-back",onClick:()=>I(null),children:[e.jsx(Bs,{size:14}),a==="inbox"?x("agents.backToInbox","Back to Inbox"):x("agents.backToOutbox","Back to Outbox")]}),e.jsxs("div",{className:"agent-mail-tab-detail-meta",children:[e.jsxs("div",{className:"agent-mail-tab-detail-row",children:[e.jsx("span",{className:"agent-mail-tab-detail-label",children:x("agents.mailFrom","From")}),e.jsx("span",{children:Ft(T.fromId,T.fromType,d,x)})]}),e.jsxs("div",{className:"agent-mail-tab-detail-row",children:[e.jsx("span",{className:"agent-mail-tab-detail-label",children:x("agents.mailToLabel","To")}),e.jsx("span",{children:Ft(T.toId,T.toType,d,x)})]}),e.jsxs("div",{className:"agent-mail-tab-detail-row",children:[e.jsx("span",{className:"agent-mail-tab-detail-label",children:x("agents.mailType","Type")}),e.jsx("span",{children:T.type})]}),e.jsxs("div",{className:"agent-mail-tab-detail-row",children:[e.jsx("span",{className:"agent-mail-tab-detail-label",children:x("agents.mailSent","Sent")}),e.jsx("span",{children:new Date(T.createdAt).toLocaleString()})]}),T.metadata?.replyTo?.messageId?e.jsx("div",{className:"agent-mail-tab-reply-context",children:x("agents.replyingTo","↪ Replying to message {{id}}",{id:T.metadata.replyTo.messageId})}):null]}),e.jsx("div",{className:"agent-mail-tab-detail-body",children:T.content})]}):e.jsx("div",{className:"mailbox-list","data-testid":"agent-detail-mail-list",children:F.length===0?e.jsxs("div",{className:"mailbox-empty","data-testid":"agent-detail-mail-empty",children:[a==="inbox"?e.jsx(Ns,{size:32}):e.jsx(Ss,{size:32}),e.jsx("p",{children:a==="inbox"?x("agents.noInboxMessages","No received messages for this agent"):x("agents.noOutboxMessages","No sent messages for this agent")})]}):F.map(Z)}):null]})}function Ln({addToast:t,agentId:i,projectId:o,agentState:l,agentName:r,initialRunId:c,preferActiveRun:y,runNowRefreshToken:x,isEphemeral:a}){const{t:u}=ke("app"),[w,R]=s.useState([]),{confirm:d}=Is(),[g,I]=s.useState(!0),[F,T]=s.useState(null),[z,V]=s.useState([]),[Z,j]=s.useState(!1),[N,P]=s.useState(null),[q,S]=s.useState(!1),[$,se]=s.useState(null),[K,D]=s.useState([]),Q=s.useRef(!1),E=s.useRef(!1),H=s.useRef(null);H.current=F;const M=s.useRef(async()=>{});M.current=async()=>{const p=H.current;if(p)try{const A=await ts(i,p,o);if(H.current!==p)return;V(A)}catch{}};const O=s.useCallback(async()=>{try{const p=await Os(i,50,o);R(p)}catch(p){t(`Failed to load runs: ${B(p)}`,"error")}finally{I(!1)}},[i,o,t]);s.useEffect(()=>{O()},[O]),s.useEffect(()=>{if(a){se(null),D([]);return}const p=o?`?projectId=${encodeURIComponent(o)}`:"";fetch(`/api/agents/${encodeURIComponent(i)}/token-usage${p}`).then(async A=>{if(!A.ok){if(A.status===400){se(null);return}throw new Error(`Request failed: ${A.status}`)}const v=await A.json();se(v)}).catch(A=>{t(`Failed to load cache hit ratio: ${B(A)}`,"error")}),Ta(i,7,o).then(A=>D(A)).catch(A=>{const v=B(A).toLowerCase();if(v.includes("ephemeral")||v.includes("400")){D([]);return}t(`Failed to load prompt sizes: ${B(A)}`,"error")})},[i,o,t,a]),s.useEffect(()=>{if(!E.current){E.current=!0;return}I(!0),O()},[O,x]);const b=w.some(p=>p.status==="active"),m=F?w.find(p=>p.id===F)?.status:void 0;s.useEffect(()=>{if(!b)return;const p=setInterval(()=>{O()},5e3);return()=>clearInterval(p)},[b,O]),s.useEffect(()=>{if(!F||m!=="active")return;const p=o?`?projectId=${encodeURIComponent(o)}`:"";return Tt(`/api/agents/${encodeURIComponent(i)}/runs/${encodeURIComponent(F)}/logs/stream${p}`,{events:{"agent:log":A=>{try{const v=JSON.parse(A.data);V(ae=>ns(ae,v))}catch{}}},onReconnect:()=>{M.current()}})},[F,m,i,o]);const k=s.useCallback(async p=>{if(F===p){T(null),V([]),P(null);return}T(p),j(!0),S(!0),V([]),P(null);try{const[A,v]=await Promise.all([ts(i,p,o),Ea(i,p,o)]);V(A),P(v)}catch(A){t(u("agents.runDetailsFailed","Failed to load run details: {{error}}",{error:B(A)}),"error"),V([]),P(null)}finally{j(!1),S(!1)}},[F,i,o,t]);s.useEffect(()=>{Q.current=!1},[i,c,y]),s.useEffect(()=>{if(w.length===0||g||Q.current)return;const p=c?w.find(A=>A.id===c):y?w.find(A=>A.status==="active"):null;Q.current=!0,p&&k(p.id)},[c,y,w,g,k]);const _=async()=>{if(await d({title:u("agents.stopRunTitle","Stop Active Run"),message:u("agents.stopRunConfirm","Stop the active run? The agent's work will be interrupted."),danger:!0}))try{await Ya(i,o),t(u("agents.runStopped","Run stopped"),"success"),I(!0),O()}catch(A){t(u("agents.stopRunFailed","Failed to stop run: {{error}}",{error:B(A)}),"error")}};if(g&&w.length===0)return e.jsx("div",{className:"runs-tab",children:e.jsxs("div",{className:"runs-loading-row",children:[e.jsx(J,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:u("agents.loadingRuns","Loading runs...")})]})});if(w.length===0)return e.jsx("div",{className:"runs-tab",children:e.jsxs("div",{className:"runs-empty",children:[e.jsx(Lt,{size:48,opacity:.3}),e.jsx("p",{children:u("agents.noRunsYet","No runs yet")}),e.jsx("p",{className:"text-muted",children:u("agents.heartbeatRunsWillAppear","Heartbeat runs will appear here")})]})});const ne=[...w].sort((p,A)=>new Date(A.startedAt).getTime()-new Date(p.startedAt).getTime()),xe=ne.filter(p=>p.status==="active"),pe=ne.filter(p=>p.status!=="active"),Ve=p=>p?e.jsxs("div",{className:"run-usage",children:[e.jsx("span",{children:u("agents.inputTokens","Input: {{value}}",{value:p.inputTokens.toLocaleString()})}),e.jsx("span",{children:u("agents.outputTokens","Output: {{value}}",{value:p.outputTokens.toLocaleString()})}),p.cachedTokens>0&&e.jsx("span",{children:u("agents.cacheReadTokens","Cache read: {{value}}",{value:p.cachedTokens.toLocaleString()})}),(p.cacheWriteTokens??0)>0&&e.jsx("span",{children:u("agents.cacheWriteTokens","Cache write: {{value}}",{value:(p.cacheWriteTokens??0).toLocaleString()})})]}):null,Ce=(p,A,v)=>{const ae=Dt[p.status]||Dt.completed,ee=ae.icon,je=p.endedAt?Dn(new Date(p.startedAt),new Date(p.endedAt)):u("agents.inProgress","In progress"),re=F===p.id;return e.jsxs("div",{children:[e.jsxs("div",{className:me("run-card",v&&"run-card--active",re&&"run-card--selected","run-card--clickable"),onClick:()=>void k(p.id),role:"button",tabIndex:0,"aria-expanded":re,"aria-label":u("agents.runAriaLabel","{{active}}run {{id}}, {{status}}",{active:v?u("agents.activePrefix","Active "):"",id:p.id.slice(0,8),status:p.status}),onKeyDown:ye=>{(ye.key==="Enter"||ye.key===" ")&&(ye.preventDefault(),k(p.id))},children:[e.jsxs("div",{className:"run-header",children:[e.jsxs("div",{className:"run-header-group",children:[re?e.jsx(Hs,{size:14}):e.jsx(zs,{size:14}),v?e.jsxs("span",{className:"run-live-indicator",children:[e.jsx("span",{className:"live-dot"}),u("agents.liveRun","Live Run")]}):e.jsxs("span",{className:"run-id",children:["#",A+1," ",p.id.slice(0,8)]})]}),e.jsxs("div",{className:"run-header-group",children:[p.invocationSource&&e.jsx("span",{className:"badge run-badge--compact",children:p.invocationSource}),v&&e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:ye=>{ye.preventDefault(),ye.stopPropagation(),_()},"aria-label":u("agents.stopActiveRun","Stop active run"),children:[e.jsx(dt,{size:12})," ",u("agents.stop","Stop")]}),e.jsxs("span",{className:me("run-status",p.status),children:[e.jsx(ee,{size:14,style:{color:ae.color}}),p.status]}),p.heartbeatProcedureSource==="custom"&&e.jsx("span",{className:"badge run-badge--compact",children:u("agents.heartbeatCustom","Heartbeat: custom")})]})]}),e.jsxs("div",{className:"run-details",children:[e.jsx("span",{children:u("agents.runStarted","Started {{time}}",{time:tt(p.startedAt,u)})}),e.jsx("span",{children:"•"}),e.jsx("span",{children:je}),p.triggerDetail&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsx("span",{className:"text-muted",children:p.triggerDetail})]})]})]}),re&&e.jsxs("div",{className:"run-logs-container",children:[q?e.jsxs("div",{className:"run-details-loading-state",children:[e.jsx(J,{size:14,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:u("agents.loadingDetails","Loading details...")})]}):N&&e.jsxs("div",{className:"run-output-sections",children:[e.jsx("div",{className:"run-output-section",children:e.jsxs("details",{children:[e.jsx("summary",{className:"run-output-label run-output-summary",children:u("agents.systemPrompt","System Prompt")}),N.systemPrompt?e.jsx("pre",{className:"run-output-panel",children:N.systemPrompt}):e.jsx("div",{className:"text-muted run-output-empty",children:u("agents.systemPromptNotCaptured","System prompt not captured for this run")})]})}),e.jsx("div",{className:"run-output-section",children:e.jsxs("details",{children:[e.jsx("summary",{className:"run-output-label run-output-summary",children:u("agents.executionPrompt","Execution Prompt")}),N.executionPrompt?e.jsx("pre",{className:"run-output-panel",children:N.executionPrompt}):e.jsx("div",{className:"text-muted run-output-empty",children:u("agents.executionPromptNotCaptured","Execution prompt not captured for this run")})]})}),N.usageJson&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:u("agents.tokenUsage","Token Usage")}),Ve(N.usageJson)]}),N.stdoutExcerpt&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:u("agents.output","Output")}),e.jsx("pre",{className:"run-output-panel",children:N.stdoutExcerpt.length>2e3?`${N.stdoutExcerpt.slice(0,2e3)}
12
-
13
- ... (truncated, ${N.stdoutExcerpt.length} chars total)`:N.stdoutExcerpt})]}),N.stderrExcerpt&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label run-output-label--error",children:u("agents.errors","Errors")}),e.jsx(Xa,{errorText:N.stderrExcerpt,summaryPrefix:"Run error",issueContext:{surface:"AgentDetailView runs",agentId:i,agentName:r,agentState:l,runId:N.id,taskId:void 0,timestamp:N.startedAt}})]}),N.resultJson&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:u("agents.result","Result")}),e.jsx("pre",{className:"run-output-panel",children:JSON.stringify(N.resultJson,null,2)})]}),N.contextSnapshot&&Object.keys(N.contextSnapshot).length>0&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:u("agents.context","Context")}),e.jsx("div",{className:"run-context-grid",children:Object.entries(N.contextSnapshot).map(([ye,Ee])=>e.jsxs("span",{className:"run-context-item",children:[e.jsxs("span",{className:"text-muted",children:[ye,":"]})," ",e.jsx("span",{children:String(Ee)})]},ye))})]}),!N.stdoutExcerpt&&!N.stderrExcerpt&&!N.resultJson&&e.jsx("div",{className:"text-muted run-output-empty",children:u("agents.noOutputCaptured","No output captured")})]}),e.jsxs("div",{className:"run-agent-logs-section",children:[e.jsx("div",{className:"run-output-label",children:u("agents.agentLogs","Agent Logs")}),Z?e.jsxs("div",{className:"run-details-loading-state",children:[e.jsx(J,{size:14,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:u("agents.loadingLogs","Loading logs...")})]}):z.length===0?e.jsx("div",{className:"text-muted run-output-empty",children:u("agents.noLogsForRun","No logs available for this run")}):e.jsx(Qs,{entries:z,resetKey:F??"none",testId:"agent-run-logs"})]})]})]},p.id)},fe=(p,A)=>e.jsxs("div",{className:"run-context-item",children:[e.jsxs("span",{className:"text-muted",children:[p,":"]})," ",e.jsx("span",{children:u("agents.cacheWindowSummary","{{percent}}% ({{cached}} / {{written}} / {{input}} / {{tasks}})",{percent:(A.hitRatio*100).toFixed(1),cached:A.totalCachedTokens.toLocaleString(),written:A.totalCacheWriteTokens.toLocaleString(),input:A.totalInputTokens.toLocaleString(),tasks:A.nTasks.toLocaleString()})})]},p),ce=K[0],ve=[...K].reverse(),Ae=Math.max(1,...ve.map(p=>p.execChars)),ze=ve.map((p,A)=>{const v=ve.length<=1?0:A/(ve.length-1)*100,ae=100-Math.round(p.execChars/Ae*100);return`${v},${ae}`}).join(" ");return e.jsxs("div",{className:"runs-tab",children:[K.length>0&&ce&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:u("agents.promptSize","Prompt Size")}),e.jsxs("div",{className:"prompt-size-summary",children:[e.jsxs("svg",{className:"prompt-size-sparkline",viewBox:"0 0 100 100",role:"img","aria-label":u("agents.promptSizeChart","Execution prompt size over last 7 runs"),children:[e.jsx("polyline",{className:"prompt-size-sparkline-grid",points:"0,100 100,100"}),e.jsx("polyline",{className:"prompt-size-sparkline-line",points:ze})]}),e.jsxs("span",{className:"prompt-size-values",children:[ce.systemChars.toLocaleString()," / ",ce.execChars.toLocaleString()," / ",ce.totalChars.toLocaleString()]})]})]}),$&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:u("agents.cacheHitRatio","Cache hit ratio")}),e.jsxs("div",{className:"run-context-grid",children:[fe(u("agents.last24h","Last 24h"),$.last24h),fe(u("agents.last7d","Last 7d"),$.last7d),fe(u("agents.allTime","All time"),$.allTime)]})]}),e.jsxs("div",{className:"runs-toolbar runs-toolbar--between",children:[e.jsxs("span",{className:"runs-toolbar-meta",children:[u("agents.runsCount",{count:w.length,defaultValue_one:"{{count}} run",defaultValue_other:"{{count}} runs"}),b&&e.jsxs("span",{className:"run-live-indicator run-live-indicator--with-margin",children:[e.jsx("span",{className:"live-dot"}),u("agents.live","Live")]})]}),e.jsx("div",{className:"run-header-group",children:b&&e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void _(),"aria-label":u("agents.stopActiveRunFor","Stop active run for {{name}}",{name:r??i}),children:[e.jsx(dt,{size:14})," ",u("agents.stopRun","Stop Run")]})})]}),xe.map((p,A)=>Ce(p,A,!0)),pe.map((p,A)=>Ce(p,xe.length+A,!1))]})}function Dn(t,i){const o=Math.floor((i.getTime()-t.getTime())/1e3);return o<60?`${o}s`:o<3600?`${Math.floor(o/60)}m ${o%60}s`:`${Math.floor(o/3600)}h ${Math.floor(o%3600/60)}m`}function Hn(t){const i=t.title?.trim()||t.description?.trim()||t.id;return i.length>80?`${i.slice(0,77)}...`:i}function zn({agentId:t,projectId:i,addToast:o}){const{t:l}=ke("app"),[r,c]=s.useState([]),[y,x]=s.useState(!0);return s.useEffect(()=>{let a=!1;return x(!0),La(t,i).then(u=>{a||c(u)}).catch(u=>{a||(c([]),o(l("agents.loadTasksFailed","Failed to load agent tasks: {{error}}",{error:B(u)}),"error"))}).finally(()=>{a||x(!1)}),()=>{a=!0}},[t,i,o]),y?e.jsxs("div",{className:"agent-tasks-empty",children:[e.jsx(J,{size:16,className:"animate-spin"}),e.jsx("p",{children:l("agents.loadingTasks","Loading agent tasks...")})]}):r.length===0?e.jsxs("div",{className:"agent-tasks-empty",children:[e.jsx(Us,{size:18}),e.jsx("p",{children:l("agents.noVisibleTasks","No assigned or active workflow tasks for this agent")})]}):e.jsx("div",{className:"agent-tasks-list",children:r.map(a=>e.jsxs("a",{className:"agent-task-item",href:`/tasks/${a.id}`,children:[e.jsxs("div",{className:"agent-task-row",children:[e.jsx("span",{className:"agent-task-id",children:a.id}),e.jsx("span",{className:`agent-task-column column-${a.column}`,children:{triage:l("board.triage","Planning"),todo:l("board.todo","Todo"),"in-progress":l("board.inProgress","In Progress"),"in-review":l("board.inReview","In Review"),done:l("board.done","Done"),archived:l("board.archived","Archived")}[a.column]??a.column})]}),e.jsx("div",{className:"agent-task-title",title:a.title||a.description||a.id,children:Hn(a)}),e.jsxs("div",{className:"agent-task-status",children:[a.status??"idle"," · ",l("agents.taskUpdated","Updated {{time}}",{time:tt(a.updatedAt,l)})]})]},a.id))})}const jt=[{key:"maxRetries",label:"Max Retries",type:"number",placeholder:"3",hint:"Maximum number of automatic retries on task failure (0–10, default 3)",min:0,max:10},{key:"timeoutMs",label:"Task Timeout (ms)",type:"number",placeholder:"600000",hint:"Maximum time in ms before a task is considered timed out (minimum 60000ms, default 600000ms)",min:6e4,max:864e5},{key:"logLevel",label:"Log Level",type:"select",hint:"Verbosity of agent log output",options:[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warning"},{value:"error",label:"Error"}]}];function In(t){const i={};for(const o of jt){const l=t[o.key]?.trim();if(l){if(o.type==="number"){const r=Number(l);if(Number.isNaN(r)||!Number.isFinite(r)){i[o.key]=`"${o.label}" must be a valid number`;continue}o.min!==void 0&&r<o.min&&(i[o.key]=`"${o.label}" must be at least ${o.min.toLocaleString()}`),o.max!==void 0&&r>o.max&&(i[o.key]=`"${o.label}" must be at most ${o.max.toLocaleString()}`)}if(o.type==="select"){const r=o.options?.map(c=>c.value)??[];r.length>0&&!r.includes(l)&&(i[o.key]=`"${o.label}" must be one of: ${r.join(", ")}`)}}}return i}function On({agent:t,projectId:i,addToast:o,onSaved:l}){const{t:r}=ke("app"),[c,y]=s.useState(t.soul??""),[x,a]=s.useState(!1),[u,w]=s.useState(!1),[R,d]=s.useState(!1),g=s.useRef(null);s.useEffect(()=>{y(t.soul??""),w(!1),d(!1)},[t.id,t.soul]),s.useEffect(()=>()=>{g.current&&clearTimeout(g.current)},[]);const I=c!==(t.soul??""),F=async()=>{if(c.length>1e4){o(r("agents.soulTooLong","Soul must be at most 10,000 characters"),"error");return}a(!0);try{await Za(t.id,c,i),o(r("agents.soulSaved","Soul saved"),"success"),w(!0),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>w(!1),3e3),await l()}catch(T){o(r("agents.soulSaveFailed","Failed to save soul: {{error}}",{error:B(T)}),"error")}finally{a(!1)}};return e.jsx("div",{className:"config-tab",children:e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:r("agents.soulTitle","Soul")}),e.jsx("p",{className:"config-description",children:r("agents.soulDescription","Define this agent's personality and identity.")}),e.jsx("div",{className:"config-fields",children:e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-soul",children:r("agents.agentSoulLabel","Agent Soul")}),e.jsx("div",{className:"agent-content-toolbar",children:e.jsxs("div",{className:"agent-content-mode-toggle",children:[e.jsxs("button",{className:`btn btn-sm ${R?"":"btn-primary"}`,onClick:()=>d(!1),disabled:!R,"aria-label":r("common.editMode","Edit mode"),children:[e.jsx(Ht,{size:14}),r("common.edit","Edit")]}),e.jsxs("button",{className:`btn btn-sm ${R?"btn-primary":""}`,onClick:()=>d(!0),disabled:R,"aria-label":r("common.previewMode","Preview mode"),children:[e.jsx(zt,{size:14}),r("common.preview","Preview")]})]})}),R?c.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(It,{remarkPlugins:[Ot],children:c})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:r("agents.soulEmptyPreview","No soul defined yet. Switch to Edit mode to define the agent's personality.")}):e.jsx("textarea",{id:"agent-soul",className:"input config-textarea-mono",rows:12,placeholder:r("agents.soulPlaceholder","Describe this agent's personality, tone, and behavioral traits..."),value:c,onChange:T=>{y(T.target.value),w(!1)}}),!R&&e.jsx("span",{className:"config-hint",children:r("agents.soulHint","Defines the agent's character and identity. Max 10,000 characters.")})]})}),!R&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!I||x,onClick:()=>void F(),children:x?e.jsxs(e.Fragment,{children:[e.jsx(J,{size:16,className:"animate-spin"}),r("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(be,{size:16}),r("agents.saveSoul","Save Soul")]})}),!I&&u&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(be,{size:14}),r("agents.soulSaved","Soul saved")]})]})]})})}function Bn({agent:t,projectId:i,addToast:o,onSaved:l}){const{t:r}=ke("app"),[c,y]=s.useState(t.memory??""),[x,a]=s.useState(!1),[u,w]=s.useState(!1),[R,d]=s.useState(!1),[g,I]=s.useState([]),[F,T]=s.useState(!1),[z,V]=s.useState(""),[Z,j]=s.useState(""),[N,P]=s.useState(!1),[q,S]=s.useState(!1),[$,se]=s.useState(!1),[K,D]=s.useState(!1),[Q,E]=s.useState(""),[H,M]=s.useState([]),[O,b]=s.useState(!1),[m,k]=s.useState(""),_=s.useRef(null),ne=s.useRef(null),xe=t.state==="running",pe=t.metadata?.builtInMemoryAgent===!0,Ve=c!==(t.memory??""),Ce=s.useCallback(async()=>{if(pe){b(!0),k("");try{const v=await Ha(t.id,50,i);M(v.events)}catch(v){k(B(v))}finally{b(!1)}}},[t.id,pe,i]);s.useEffect(()=>{Ce()},[Ce]);const fe=s.useMemo(()=>g.find(v=>v.path===z),[g,z]),ce=fe?{"long-term":r("agents.memoryLayerLongTermDesc","Curated durable decisions, conventions, constraints, and pitfalls for this specific agent."),daily:r("agents.memoryLayerDailyDesc","Raw daily observations and open loops recorded by this agent."),dreams:r("agents.memoryLayerDreamsDesc","Synthesized patterns and emerging themes distilled from this agent's daily memory.")}[fe.layer]??fe.layer:r("agents.selectMemoryFile","Select a memory file to view or edit."),ve=s.useCallback(async v=>{S(!0);try{const ae=await za(t.id,v,i);V(ae.path),j(ae.content),P(!1),D(!1)}catch(ae){o(r("agents.memoryFileLoadFailed","Failed to load agent memory file: {{error}}",{error:B(ae)}),"error")}finally{S(!1)}},[t.id,i,o]),Ae=s.useCallback(async(v="")=>{T(!0);try{const{files:ae}=await Ia(t.id,i);if(I(ae),ae.length===0){V(""),j(""),P(!1);return}const ee=An(ae,v);await ve(ee)}catch(ae){o(r("agents.memoryFilesLoadFailed","Failed to load memory files: {{error}}",{error:B(ae)}),"error"),I([]),V(""),j(""),P(!1)}finally{T(!1)}},[t.id,i,o,ve]);s.useEffect(()=>{y(t.memory??""),w(!1),d(!1),E(""),D(!1),Ae()},[t.id,t.memory,Ae]),s.useEffect(()=>()=>{_.current&&clearTimeout(_.current),ne.current&&clearTimeout(ne.current)},[]);const ze=async()=>{if(c.length>5e4){o(r("agents.memoryTooLong","Memory must be at most 50,000 characters"),"error");return}a(!0);try{await en(t.id,c,i),o(r("agents.memorySaved","Memory saved"),"success"),w(!0),_.current&&clearTimeout(_.current),_.current=setTimeout(()=>w(!1),3e3),await l()}catch(v){o(r("agents.memorySaveFailed","Failed to save memory: {{error}}",{error:B(v)}),"error")}finally{a(!1)}},p=async v=>{if(!(!v||v===z)){if(N){E(r("agents.saveBeforeSwitch","Save the current file before switching to another file."));return}E(""),await ve(v)}},A=async()=>{if(z){se(!0);try{await tn(t.id,z,Z,i),P(!1),D(!0),ne.current&&clearTimeout(ne.current),ne.current=setTimeout(()=>D(!1),3e3),E(""),await Ae(z),o(r("agents.memoryFileSaved","Agent memory file saved"),"success"),await l()}catch(v){o(r("agents.memoryFileSaveFailed","Failed to save agent memory file: {{error}}",{error:B(v)}),"error")}finally{se(!1)}}};return e.jsx("div",{className:"config-tab",children:e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:r("agents.memoryTitle","Agent Memory")}),e.jsx("p",{className:"config-description",children:r("agents.memoryDescription","Store context that belongs to this agent only. Workspace memory, daily notes, dreams, and qmd search live in project settings under Project Memory.")}),pe&&e.jsxs("section",{className:"memory-consolidation-history","aria-label":r("agents.consolidationHistory","Consolidation history"),children:[e.jsxs("div",{className:"memory-consolidation-history__heading",children:[e.jsx("h4",{children:r("agents.consolidationHistory","Consolidation history")}),e.jsxs("button",{className:"btn btn-sm",onClick:()=>void Ce(),disabled:O,children:[e.jsx(St,{size:14}),r("common.refresh","Refresh")]})]}),O?e.jsx(Xs,{}):m?e.jsx("p",{className:"config-hint",children:r("agents.consolidationHistoryError","Unable to load consolidation history: {{error}}",{error:m})}):H.length===0?e.jsx("p",{className:"config-hint",children:r("agents.consolidationHistoryEmpty","No consolidation activity yet.")}):e.jsx("ul",{className:"memory-consolidation-history__list",children:H.map(v=>{const ae=v.mutationType.endsWith("completed")?r("agents.consolidationCompleted","Completed"):v.mutationType.endsWith("skipped")?r("agents.consolidationSkipped","Skipped"):r("agents.consolidationFailed","Failed"),ee=v.metadata??{},je=["graphChanged","parsedFiles","recallCreated","reason","stage"].flatMap(re=>ee[re]===void 0?[]:[`${re}: ${String(ee[re])}`]);return e.jsxs("li",{className:`memory-consolidation-history__row memory-consolidation-history__row--${v.mutationType.split("-").at(-1)}`,children:[e.jsx("span",{children:tt(v.timestamp,r)}),e.jsx("strong",{children:ae}),je.length>0&&e.jsx("span",{children:je.join(" · ")})]},v.id)})})]}),xe&&e.jsx("p",{className:"config-hint config-hint--block-spacing",children:r("agents.memoryReadOnly","Read-only while this agent is running.")}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-memory",children:r("agents.inlineMemoryLabel","Inline Memory")}),e.jsx("span",{className:"config-hint config-hint--block",children:r("agents.inlineMemoryHint","Short-form memory stored directly on the agent record and injected into prompts.")}),e.jsx("div",{className:"agent-content-toolbar",children:e.jsxs("div",{className:"agent-content-mode-toggle",children:[!xe&&e.jsxs("button",{className:`btn btn-sm ${R?"":"btn-primary"}`,onClick:()=>d(!1),disabled:!R,"aria-label":r("agents.inlineMemoryEditMode","Inline memory edit mode"),children:[e.jsx(Ht,{size:14}),r("common.edit","Edit")]}),e.jsxs("button",{className:`btn btn-sm ${R?"btn-primary":""}`,onClick:()=>d(!0),disabled:R,"aria-label":r("agents.inlineMemoryPreviewMode","Inline memory preview mode"),children:[e.jsx(zt,{size:14}),r("common.preview","Preview")]})]})}),R?c.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(It,{remarkPlugins:[Ot],children:c})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:r("agents.memoryEmptyPreview","No agent memory defined yet. Switch to Edit mode to add memory content.")}):e.jsx("textarea",{id:"agent-memory","aria-label":r("agents.memoryTitle","Agent Memory"),className:"input config-textarea-mono",rows:10,placeholder:r("agents.memoryPlaceholder","Durable preferences, operating habits, and context this agent should carry across tasks..."),value:c,readOnly:xe,onChange:v=>{y(v.target.value),w(!1)}}),!R&&e.jsx("span",{className:"config-hint",children:r("agents.inlineMemoryFieldHint","This is the inline memory field on the agent JSON record. Max 50,000 characters.")}),!R&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!Ve||x||xe,onClick:()=>void ze(),children:x?e.jsxs(e.Fragment,{children:[e.jsx(J,{size:16,className:"animate-spin"}),r("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(be,{size:16}),r("agents.saveMemory","Save Memory")]})}),!Ve&&u&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(be,{size:14}),r("agents.memorySaved","Memory saved")]})]})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-memory-file-select",children:r("agents.memoryFilesLabel","Memory Files")}),e.jsxs("span",{className:"config-hint config-hint--block",children:[r("agents.memoryFilesHint","Full OpenClaw memory files at")," ",e.jsxs("code",{children:["agent/",t.name||t.id,"/memory/"]})," ",r("agents.memoryFilesHintSuffix","(MEMORY.md, DREAMS.md, and daily notes).")]}),e.jsx("select",{id:"agent-memory-file-select",className:"select",value:z,disabled:F||q||$||g.length===0,onChange:v=>{p(v.target.value)},children:g.length===0?e.jsx("option",{value:"",children:r("agents.noMemoryFiles","No memory files found")}):g.map(v=>{const ae={"long-term":r("agents.memoryLayerLongTerm","Long-term"),daily:r("agents.memoryLayerDaily","Daily"),dreams:r("agents.memoryLayerDreams","Dreams")}[v.layer]??v.layer;return e.jsxs("option",{value:v.path,children:[ae," • ",v.label]},v.path)})}),F&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(J,{size:14,className:"animate-spin"}),r("agents.loadingMemoryFiles","Loading memory files…")]}),fe&&e.jsxs("div",{className:"config-hint config-hint--top-spacing",children:[e.jsx("strong",{children:{"long-term":r("agents.memoryLayerLongTerm","Long-term"),daily:r("agents.memoryLayerDaily","Daily"),dreams:r("agents.memoryLayerDreams","Dreams")}[fe.layer]??fe.layer})," · ",ce,e.jsx("br",{}),r("agents.memoryFileMeta","{{size}} bytes · updated {{date}}",{size:fe.size.toLocaleString(),date:tt(fe.updatedAt,r)})]}),e.jsx("div",{className:"agent-memory-file-editor config-textarea-top-spacing",children:e.jsx(Oa,{content:Z,onChange:v=>{j(v),P(!0),D(!1),E("")},readOnly:xe||!z||q,filePath:z||"MEMORY.md",forceToolbarActionsVisible:!0})}),q&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(J,{size:14,className:"animate-spin"}),r("agents.loadingFileContent","Loading file content…")]}),Q&&e.jsx("span",{className:"config-hint config-hint--top-spacing config-hint--block",children:Q}),e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!N||$||!z||xe,onClick:()=>void A(),children:$?e.jsxs(e.Fragment,{children:[e.jsx(J,{size:16,className:"animate-spin"}),r("agents.savingFile","Saving file…")]}):e.jsxs(e.Fragment,{children:[e.jsx(be,{size:16}),r("agents.saveMemoryFile","Save Memory File")]})}),!N&&K&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(be,{size:14}),r("agents.memoryFileSaved","Memory file saved")]})]})]})]})]})})}function $n({agent:t,projectId:i,addToast:o,onSaved:l}){const{t:r}=ke("app"),[c,y]=s.useState(t.instructionsText??""),[x,a]=s.useState(t.instructionsPath??""),[u,w]=s.useState(!1),[R,d]=s.useState(""),[g,I]=s.useState(!1),[F,T]=s.useState(!1),[z,V]=s.useState(!1),[Z,j]=s.useState(!1),[N,P]=s.useState(!1),[q,S]=s.useState(!1),$=s.useRef(null),se=s.useRef(null);s.useEffect(()=>{const H=x.trim();if(!H){d(""),T(!1);return}I(!0),Ys("project",H).then(M=>{d(M.content),T(!1)}).catch(M=>{const O=B(M);O.includes("ENOENT")||O.includes("Not found")||O.includes("not found")?(d(""),T(!1)):(o(`Failed to load instructions file: ${O}`,"error"),d(""))}).finally(()=>{I(!1)})},[x,o]),s.useEffect(()=>{y(t.instructionsText??""),a(t.instructionsPath??""),P(!1),S(!1),w(!1)},[t.id,t.instructionsText,t.instructionsPath]),s.useEffect(()=>()=>{$.current&&clearTimeout($.current),se.current&&clearTimeout(se.current)},[]);const K=(()=>{const H=c??"",M=t.instructionsText??"",O=x?.trim()??"",b=t.instructionsPath?.trim()??"";return H!==M||O!==b})(),D=async()=>{V(!0);try{await Qa(t.id,{instructionsText:c||void 0,instructionsPath:x.trim()||void 0},i),o(r("agents.instructionsSaved","Instructions saved"),"success"),P(!0),$.current&&clearTimeout($.current),$.current=setTimeout(()=>P(!1),3e3),await l()}catch(H){o(r("agents.instructionsSaveFailed","Failed to save instructions: {{error}}",{error:B(H)}),"error")}finally{V(!1)}},Q=async()=>{const H=x.trim();if(!H){o(r("agents.noInstructionsPath","No instructions file path set"),"error");return}j(!0);try{await Zs("project",H,R),o(r("agents.instructionsFileSaved","Instructions file saved"),"success"),T(!1),S(!0),se.current&&clearTimeout(se.current),se.current=setTimeout(()=>S(!1),3e3),await l()}catch(M){o(r("agents.instructionsFileSaveFailed","Failed to save instructions file: {{error}}",{error:B(M)}),"error")}finally{j(!1)}},E=!!x.trim();return e.jsxs("div",{className:"config-tab",children:[e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:r("agents.instructionsTitle","Custom Instructions")}),e.jsx("p",{className:"config-description",children:r("agents.instructionsDescription","Append custom instructions to this agent's system prompt at execution time. Use this to customize behavior, coding style, or project conventions without modifying built-in prompts.")}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"instructions-text",children:r("agents.inlineInstructions","Inline Instructions")}),e.jsx("div",{className:"agent-content-toolbar",children:e.jsxs("div",{className:"agent-content-mode-toggle",children:[!c.trim()&&!u&&e.jsx("button",{type:"button",className:"btn btn-sm","data-testid":"instructions-insert-template",onClick:()=>{y(ln),P(!1)},children:r("agents.insertInstructionsTemplate","Insert template")}),e.jsxs("button",{className:`btn btn-sm ${u?"":"btn-primary"}`,onClick:()=>w(!1),disabled:!u,"aria-label":r("common.editMode","Edit mode"),"data-testid":"instructions-edit-toggle",children:[e.jsx(Ht,{size:14}),r("common.edit","Edit")]}),e.jsxs("button",{className:`btn btn-sm ${u?"btn-primary":""}`,onClick:()=>w(!0),disabled:u,"aria-label":r("common.previewMode","Preview mode"),"data-testid":"instructions-preview-toggle",children:[e.jsx(zt,{size:14}),r("common.preview","Preview")]})]})}),u?c.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(It,{remarkPlugins:[Ot],children:c})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:r("agents.instructionsEmptyPreview","No inline instructions defined yet. Switch to Edit mode to add instructions.")}):e.jsx("textarea",{id:"instructions-text",className:"input",rows:10,placeholder:r("agents.instructionsPlaceholder","Enter custom instructions to append to this agent's system prompt..."),value:c,onChange:H=>{y(H.target.value),P(!1)}}),!u&&e.jsx("span",{className:"config-hint",children:r("agents.instructionsHint","Markdown formatting supported. Max 50,000 characters.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"instructions-path",children:r("agents.instructionsPathLabel","Instructions File Path")}),e.jsx("input",{id:"instructions-path",type:"text",className:"input",placeholder:r("agents.instructionsPathPlaceholder","e.g., .fusion/agents/my-agent-instructions.md"),value:x,onChange:H=>{a(H.target.value),P(!1)}}),e.jsx("span",{className:"config-hint",children:r("agents.instructionsPathHint","Path to a .md file (relative to project root). Contents are read and appended at execution time.")})]})]}),!u&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!K||z,onClick:()=>void D(),children:z?e.jsxs(e.Fragment,{children:[e.jsx(J,{size:16,className:"animate-spin"}),r("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(be,{size:16}),r("agents.saveInstructions","Save Instructions")]})}),!K&&N&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(be,{size:14}),r("agents.instructionsSaved","Instructions saved")]})]})]}),E&&e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:r("agents.instructionsFileEditorTitle","Instructions File Editor")}),e.jsx("p",{className:"config-description",children:r("agents.instructionsFileEditorDesc","Edit the instructions file directly. Changes are saved separately from the path configuration.")}),e.jsx("div",{className:"config-fields",children:e.jsxs("div",{className:"config-field",children:[e.jsxs("div",{className:"config-inline-header",children:[e.jsx("label",{htmlFor:"instructions-file-content",children:r("agents.fileContentLabel","File Content")}),g&&e.jsxs("span",{className:"config-hint config-hint--inline-tight",children:[e.jsx(J,{size:12,className:"animate-spin"}),r("common.loading","Loading...")]}),F&&!g&&e.jsx("span",{className:"config-hint config-hint--warning",children:r("common.unsavedChanges","Unsaved changes")})]}),e.jsx("textarea",{id:"instructions-file-content",className:"input config-textarea-mono",rows:20,placeholder:r("agents.fileContentPlaceholder","File content will appear here when loaded..."),value:R,readOnly:g,onChange:H=>{d(H.target.value),T(!0),S(!1)}}),e.jsx("span",{className:"config-hint",children:r("agents.fileContentHint","Edit the markdown file content directly. Save separately using the button below.")})]})}),e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!F||Z,onClick:()=>void Q(),children:Z?e.jsxs(e.Fragment,{children:[e.jsx(J,{size:16,className:"animate-spin"}),r("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(be,{size:16}),r("agents.saveFile","Save File")]})}),!F&&q&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(be,{size:14}),r("agents.fileSaved","File saved")]})]})]})]})}function Fs(t){const i=t??{},o={};return i.heartbeatIntervalMs!==void 0&&i.heartbeatIntervalMs!==null&&(o.heartbeatIntervalMs=String(Number(i.heartbeatIntervalMs)/1e3)),i.heartbeatTimeoutMs!==void 0&&i.heartbeatTimeoutMs!==null&&(o.heartbeatTimeoutMs=String(Number(i.heartbeatTimeoutMs)/1e3)),i.maxConcurrentRuns!==void 0&&i.maxConcurrentRuns!==null&&(o.maxConcurrentRuns=String(i.maxConcurrentRuns)),(i.messageResponseMode==="immediate"||i.messageResponseMode==="on-heartbeat")&&(o.messageResponseMode=i.messageResponseMode),i.autoClaimCandidatesInPrompt!==void 0&&i.autoClaimCandidatesInPrompt!==null&&(o.autoClaimCandidatesInPrompt=String(i.autoClaimCandidatesInPrompt)),o}function Kt(t){return t?.autoClaimRelevantTasks!==!1}function Yt(t){return t?.engineerBacklogAutoClaim===!0}function Ps(t){const i=t?.assignmentPolicy;return i==="explicit-only"||i==="none"?i:"auto"}function Xt(t){return t?.runMissedHeartbeatOnStartup===!0}function Zt(t){return t?.allowParallelExecution!==!1}function Qt(t){return t?.skipHeartbeatWhenIdle===!0}function es(t){const i=t?.heartbeatScopeDiscipline;return i==="strict"||i==="lite"||i==="off"?i:""}function Ts(t){const i=t?.heartbeatPromptTemplate;return i==="default"||i==="compact"?i:""}function Es(t){const i=(t??{}).budgetConfig,o={};return i&&(i.tokenBudget!==void 0&&i.tokenBudget!==null&&(o.tokenBudget=String(i.tokenBudget)),i.usageThreshold!==void 0&&i.usageThreshold!==null&&(o.usageThreshold=String(Number(i.usageThreshold)*100)),i.budgetPeriod!==void 0&&i.budgetPeriod!==null&&(o.budgetPeriod=String(i.budgetPeriod)),i.resetDay!==void 0&&i.resetDay!==null&&(o.resetDay=String(i.resetDay))),o}function _n({agent:t,projectId:i,addToast:o,onSaved:l}){const{t:r}=ke("app"),[c,y]=s.useState(!1),[x,a]=s.useState(!1),[u,w]=s.useState(!1),[R,d]=s.useState(!1),[g,I]=s.useState(!1),[F,T]=s.useState(""),[z,V]=s.useState(!1),[Z,j]=s.useState(null),[N,P]=s.useState(!1),q=s.useRef(null),S=t.heartbeatProcedurePath?.trim(),$=`.fusion/agents/${t.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t.id.toLowerCase().replace(/[^a-z0-9]+/g,"-")||"agent"}-${t.id.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"agent"}/HEARTBEAT.md`,se=`.fusion/agents/${t.id}/HEARTBEAT.md`,K=t.id.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"agent",D=!!(S&&(S===$||S===se||new RegExp(`^\\.fusion/agents/[^/]+-${K}/HEARTBEAT\\.md$`).test(S))),Q=!!S,E=s.useCallback(async b=>{w(!0),j(null);try{const m=await Ys("project",b,i);T(m.content),V(!1)}catch(m){const k=B(m);j(k),o(r("agents.heartbeatFileLoadFailed","Failed to load heartbeat procedure file: {{error}}",{error:k}),"error")}finally{w(!1)}},[o,i]);s.useEffect(()=>{a(!1),I(!1),T(""),V(!1),j(null),w(!1),d(!1),P(!1)},[t.id,S]),s.useEffect(()=>()=>{q.current&&clearTimeout(q.current)},[]);const H=async()=>{S&&(a(!0),await E(S))},M=async()=>{if(S){d(!0);try{await Zs("project",S,F,i),V(!1),P(!0),o(r("agents.heartbeatFileSaved","Heartbeat procedure file saved"),"success"),q.current&&clearTimeout(q.current),q.current=setTimeout(()=>P(!1),3e3),await l()}catch(b){o(r("agents.heartbeatFileSaveFailed","Failed to save heartbeat procedure file: {{error}}",{error:B(b)}),"error")}finally{d(!1)}}},O=async()=>{y(!0);try{const b=await nn(t.id,i);o(b.procedureFileSeeded?r("agents.heartbeatProcedureFileReady","Heartbeat procedure file ready at {{path}}",{path:b.heartbeatProcedurePath}):r("agents.heartbeatProcedurePathSet","Heartbeat procedure path set to {{path}}",{path:b.heartbeatProcedurePath}),"success"),await l()}catch(b){o(r("agents.heartbeatUpgradeFailed","Failed to upgrade heartbeat procedure: {{error}}",{error:B(b)}),"error")}finally{y(!1)}};return e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:r("agents.heartbeatProcedureTitle","Heartbeat Procedure")}),e.jsxs("p",{className:"config-description",children:[r("agents.heartbeatProcedureDesc","The per-tick procedure this agent runs every wake. Defaults to a per-agent markdown file (for example")," ",e.jsx("code",{children:".fusion/agents/ceo-agent2736/HEARTBEAT.md"}),r("agents.heartbeatProcedureDescSuffix",") that you can edit. Legacy id-only default paths remain valid. Resets on every tick — no need to restart the agent after editing.")]}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsxs("span",{className:"config-hint",children:[r("agents.currentPath","Current path:")," ",e.jsx("code",{children:S||r("agents.noneUsingBuiltIn","(none — using built-in default)")})]}),Q&&e.jsx("div",{className:"heartbeat-procedure-actions",children:e.jsx("button",{className:"btn btn-sm",onClick:()=>void H(),disabled:u,children:u?e.jsxs(e.Fragment,{children:[e.jsx(J,{size:16,className:"animate-spin"}),r("agents.loadingFile","Loading file…")]}):e.jsxs(e.Fragment,{children:[e.jsx(Nt,{size:16}),r("agents.viewHeartbeatMarkdown","View Heartbeat Markdown")]})})})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("button",{className:"btn",disabled:c||D,onClick:()=>void O(),"aria-label":r("agents.upgradeToDefaultAriaLabel","Upgrade agent to default heartbeat procedure file"),children:c?e.jsxs(e.Fragment,{children:[e.jsx(J,{size:16,className:"animate-spin"}),r("agents.upgrading","Upgrading…")]}):D?e.jsxs(e.Fragment,{children:[e.jsx(be,{size:16}),r("agents.alreadyOnDefault","Already on default")]}):r("agents.upgradeToDefault","Upgrade to Default Heartbeat Procedure")}),e.jsxs("span",{className:"config-hint",children:[r("agents.upgradeHint","Sets")," ",e.jsx("code",{children:"heartbeatProcedurePath"})," ",r("agents.upgradeHintTo","to")," ",e.jsx("code",{children:$})," ",r("agents.upgradeHintSuffix","and seeds the file from the built-in template if it doesn't exist. Each agent gets its own per-agent file, so edits stay scoped to this agent. Operator edits to the file are preserved.")]})]})]}),x&&Q&&S&&e.jsxs("div",{className:"config-fields heartbeat-procedure-viewer",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"heartbeat-procedure-file-content",children:r("agents.heartbeatProcedureFileLabel","Heartbeat Procedure File")}),e.jsxs("div",{className:"agent-content-toolbar",children:[e.jsxs("div",{className:"agent-content-mode-toggle",children:[e.jsxs("button",{className:`btn btn-sm ${g?"":"btn-primary"}`,onClick:()=>I(!1),disabled:!g,"aria-label":r("agents.heartbeatFileEditMode","Heartbeat file edit mode"),children:[e.jsx(Ht,{size:14}),r("common.edit","Edit")]}),e.jsxs("button",{className:`btn btn-sm ${g?"btn-primary":""}`,onClick:()=>I(!0),disabled:g,"aria-label":r("agents.heartbeatFilePreviewMode","Heartbeat file preview mode"),children:[e.jsx(zt,{size:14}),r("common.preview","Preview")]})]}),u&&e.jsxs("span",{className:"config-hint heartbeat-procedure-status",children:[e.jsx(J,{size:12,className:"animate-spin"}),r("common.loading","Loading...")]}),z&&!u&&e.jsx("span",{className:"config-hint heartbeat-procedure-status heartbeat-procedure-status--warning",children:r("common.unsavedChanges","Unsaved changes")})]}),g?F.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(It,{remarkPlugins:[Ot],children:F})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:r("agents.heartbeatFileEmptyPreview","No heartbeat procedure markdown content yet.")}):e.jsx("textarea",{id:"heartbeat-procedure-file-content",className:"input",rows:16,value:F,readOnly:u,placeholder:r("agents.heartbeatFilePlaceholder","Heartbeat procedure markdown file content will appear here..."),onChange:b=>{T(b.target.value),V(!0),P(!1)}}),Z&&e.jsx("span",{className:"config-error",children:r("agents.fileLoadError","Failed to load file: {{error}}",{error:Z})}),e.jsxs("span",{className:"config-hint",children:[r("agents.heartbeatFileEditorHint","This editor writes directly to")," ",e.jsx("code",{children:S}),"."]})]}),!g&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!z||R||u,onClick:()=>void M(),children:R?e.jsxs(e.Fragment,{children:[e.jsx(J,{size:16,className:"animate-spin"}),r("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(be,{size:16}),r("agents.saveHeartbeatFile","Save Heartbeat File")]})}),!z&&N&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(be,{size:14}),r("agents.fileSaved","File saved")]})]})]})]})}function Un({agent:t,projectId:i,agentModelSettings:o,addToast:l,onSaved:r,onHasChangesChange:c,onDelete:y,onAgentDraftApplied:x}){const{t:a}=ke("app"),[u,w]=s.useState(t.name),[R,d]=s.useState(t.role),[g,I]=s.useState(()=>(t.roles??[t.role]).filter(n=>n!==t.role)),[F,T]=s.useState(t.title??""),[z,V]=s.useState(t.icon??""),[Z,j]=s.useState(t.reportsTo??""),[N,P]=s.useState([]),[q,S]=s.useState(!1),[$,se]=s.useState(!1),[K,D]=s.useState(!1),Q=s.useRef(null),[E,H]=s.useState(()=>{const n={};for(const h of jt){const C=t.metadata[h.key];C!=null&&(n[h.key]=String(C))}return n.thinkingLevel=typeof t.runtimeConfig?.thinkingLevel=="string"?t.runtimeConfig.thinkingLevel:"",n}),[M,O]=s.useState(()=>Fs(t.runtimeConfig)),[b,m]=s.useState(()=>Gt(t)),[k,_]=s.useState(()=>Kt(t.runtimeConfig)),[ne,xe]=s.useState(()=>Yt(t.runtimeConfig)),[pe,Ve]=s.useState(()=>Ps(t.runtimeConfig)),[Ce,fe]=s.useState(()=>Xt(t.runtimeConfig)),[ce,ve]=s.useState(()=>Zt(t.runtimeConfig)),[Ae,ze]=s.useState(()=>Qt(t.runtimeConfig)),[p,A]=s.useState(()=>es(t.runtimeConfig)),[v,ae]=s.useState(()=>Ts(t.runtimeConfig)),[ee,je]=s.useState(()=>Es(t.runtimeConfig)),[re,ye]=s.useState(t.bundleConfig?.mode??""),[Ee,st]=s.useState(t.bundleConfig?.entryFile??"AGENTS.md"),[Fe,kt]=s.useState(t.bundleConfig?.externalPath??""),[Le,oe]=s.useState(t.bundleConfig?.files??[]),[Ie,ut]=s.useState(Array.isArray(t.metadata?.skills)?t.metadata.skills:[]),{favoriteProviders:we,favoriteModels:at,toggleFavoriteProvider:mt,toggleFavoriteModel:gt}=Ba(),[Bt,ht]=s.useState([]),[Ge,De]=s.useState(!1),[ft,pt]=s.useState([]),[nt,Ct]=s.useState(!1),Xe=(()=>{const n=t.runtimeConfig??{};return n.modelProvider&&n.modelId?`${n.modelProvider}/${n.modelId}`:typeof n.model=="string"&&n.model.includes("/")?n.model:""})(),He=typeof t.runtimeConfig?.runtimeHint=="string"?t.runtimeConfig.runtimeHint:"",[de,Je]=s.useState(He?"runtime":"model"),[Pe,Ze]=s.useState(Xe),[Oe,qe]=s.useState(He),[f,L]=s.useState(t.permissionPolicy),[G,U]=s.useState(t.permissions??{}),[te,Re]=s.useState(void 0),ge=Z.trim(),Be=s.useMemo(()=>N.filter(n=>n.id!==t.id),[N,t.id]),$e=!!ge&&!Be.some(n=>n.id===ge),Qe=s.useMemo(()=>({name:u,role:R,title:F||void 0,instructionsText:t.instructionsText,soul:t.soul,memory:t.memory,reportsTo:Z||void 0,skills:Ie,model:Pe||void 0,runtimeHint:de==="runtime"&&Oe||void 0,thinkingLevel:E.thinkingLevel??void 0,maxTurns:E.maxTurns?Number(E.maxTurns):void 0,heartbeatIntervalMs:M.heartbeatIntervalMs?Number(M.heartbeatIntervalMs)*1e3:void 0,heartbeatTimeoutMs:M.heartbeatTimeoutMs?Number(M.heartbeatTimeoutMs)*1e3:void 0,maxConcurrentRuns:M.maxConcurrentRuns?Number(M.maxConcurrentRuns):void 0,messageResponseMode:M.messageResponseMode}),[t.instructionsText,t.memory,t.soul,E.maxTurns,E.thinkingLevel,M.heartbeatIntervalMs,M.heartbeatTimeoutMs,M.maxConcurrentRuns,M.messageResponseMode,Pe,u,Z,R,de,Oe,Ie,F]),it=s.useCallback(n=>{w(n.name),d(n.role),T(n.title??""),V(n.icon??""),j(n.reportsTo??""),n.skills&&ut(n.skills),n.thinkingLevel&&H(C=>({...C,thinkingLevel:n.thinkingLevel})),n.maxTurns!==void 0&&H(C=>({...C,maxTurns:String(n.maxTurns)})),n.runtimeHint!==void 0?(Je("runtime"),qe(n.runtimeHint??""),n.runtimeHint&&Ze("")):n.model!==void 0&&(Je("model"),Ze(n.model??""),qe(""));const h=Object.fromEntries(Object.entries({name:n.name,role:n.role,title:n.title,icon:n.icon,reportsTo:n.reportsTo,instructionsText:n.instructionsText,soul:n.soul,memory:n.memory}).filter(([,C])=>C!==void 0));x?.(h),D(!1),l(a("agents.interviewDraftApplied","Interview draft applied. Review and save when ready."),"success")},[l,x]);s.useEffect(()=>{L(t.permissionPolicy)},[t.permissionPolicy]),s.useEffect(()=>{U(t.permissions??{})},[t.permissions]),s.useEffect(()=>{$a(i).then(n=>Re(n.project?.defaultAgentPermissionPolicy)).catch(()=>Re(void 0))},[i]);const rt=async n=>{L(n);try{await Jt(t.id,{permissionPolicy:n},i),await r(),l(a("agents.permissionPolicyUpdated","Permission policy updated"),"success")}catch(h){l(a("agents.permissionPolicyFailed","Failed to update permission policy: {{error}}",{error:B(h)}),"error")}},lt=s.useMemo(()=>new Set(Nn[R]??[]),[R]),he=s.useMemo(()=>new Set(ks.filter(n=>G[n]===!0)),[G]),Ke=async(n,h)=>{const C={...G};h?C[n]=!0:delete C[n],U(C);try{await Jt(t.id,{permissions:C},i),await r(),l(a("agents.capabilityPermissionsUpdated","Capability grants updated"),"success")}catch(W){U(t.permissions??{}),l(a("agents.capabilityPermissionsFailed","Failed to update capability grants: {{error}}",{error:B(W)}),"error")}};s.useEffect(()=>{let n=!1;return S(!0),Et(void 0,i).then(h=>{n||P(h)}).catch(()=>{n||P([])}).finally(()=>{n||S(!1)}),()=>{n=!0}},[i]),s.useEffect(()=>{De(!0),_a().then(n=>{ht(n.models)}).catch(()=>{}).finally(()=>De(!1))},[]),s.useEffect(()=>{Ct(!0),Js(i).then(pt).catch(()=>pt([])).finally(()=>Ct(!1))},[i]);const[_e,$t]=s.useState(null),[os,cs]=s.useState(!1);s.useEffect(()=>{ss(t.id,i).then($t).catch(()=>$t(null))},[t.id,i]);const ea=async()=>{cs(!0);try{await sn(t.id,i),l(a("agents.budgetResetSuccess","Budget usage reset successfully"),"success");const n=await ss(t.id,i);$t(n)}catch(n){l(a("agents.budgetResetFailed","Failed to reset budget: {{error}}",{error:B(n)}),"error")}finally{cs(!1)}},[Ye,ds]=s.useState(!1),[Y,et]=s.useState({}),[ta,ot]=s.useState(!1),[_t,wt]=s.useState(null),us=t.state==="idle"||t.state==="paused",bt=s.useRef(null),ms=s.useRef(null),gs=s.useRef(null),Rt=s.useRef(0);s.useEffect(()=>()=>{bt.current&&clearTimeout(bt.current)},[]);const Te=(()=>{if(u!==t.name||R!==t.role||F!==(t.title??"")||z!==(t.icon??"")||Z!==(t.reportsTo??"")||re!==(t.bundleConfig?.mode??"")||Ee!==(t.bundleConfig?.entryFile??"AGENTS.md")||Fe!==(t.bundleConfig?.externalPath??"")||JSON.stringify(Le)!==JSON.stringify(t.bundleConfig?.files??[]))return!0;for(const ie of jt){const Ne=E[ie.key]?.trim()??"",Se=t.metadata[ie.key]!==void 0&&t.metadata[ie.key]!==null?String(t.metadata[ie.key]):"";if(Ne!==Se)return!0}const n=t.runtimeConfig??{};if(b!==Gt(t)||k!==Kt(t.runtimeConfig)||ne!==Yt(t.runtimeConfig)||pe!==Ps(t.runtimeConfig)||Ce!==Xt(t.runtimeConfig)||ce!==Zt(t.runtimeConfig)||Ae!==Qt(t.runtimeConfig)||p!==es(t.runtimeConfig)||v!==Ts(t.runtimeConfig))return!0;for(const ie of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns","messageResponseMode","autoClaimCandidatesInPrompt"]){const Ne=M[ie]?.trim()??"";let Se=n[ie]!==void 0&&n[ie]!==null?String(n[ie]):"";if((ie==="heartbeatIntervalMs"||ie==="heartbeatTimeoutMs")&&Se&&(Se=String(Number(Se)/1e3)),Ne!==Se)return!0}const h=n.budgetConfig;for(const ie of["tokenBudget","budgetPeriod","resetDay"]){const Ne=ee[ie]?.trim()??"",Se=h?.[ie]!==void 0&&h?.[ie]!==null?String(h[ie]):"";if(Ne!==Se)return!0}const C=ee.usageThreshold?.trim()??"",W=h?.usageThreshold!==void 0&&h?.usageThreshold!==null?String(Number(h.usageThreshold)*100):"";if(C!==W)return!0;const Me=Array.isArray(t.metadata?.skills)?t.metadata.skills:[];return JSON.stringify(Ie)!==JSON.stringify(Me)||de!==(He?"runtime":"model")||Pe!==Xe||Oe!==He||(E.thinkingLevel??"")!==(typeof n.thinkingLevel=="string"?n.thinkingLevel:"")})(),hs=s.useRef(null);s.useEffect(()=>{c&&hs.current!==Te&&(hs.current=Te,c(Te))},[Te,c]),s.useEffect(()=>()=>{c?.(!1)},[c]),s.useEffect(()=>{const n={id:t.id,updatedAt:t.updatedAt},h=ms.current;(!h||h.id!==n.id||h.updatedAt!==n.updatedAt)&&(Te||(ms.current=n,O(Fs(t.runtimeConfig)),m(Gt(t)),_(Kt(t.runtimeConfig)),xe(Yt(t.runtimeConfig)),fe(Xt(t.runtimeConfig)),ve(Zt(t.runtimeConfig)),ze(Qt(t.runtimeConfig)),A(es(t.runtimeConfig)),je(Es(t.runtimeConfig)),H(W=>({...W,thinkingLevel:typeof t.runtimeConfig?.thinkingLevel=="string"?t.runtimeConfig.thinkingLevel:""})),Ze(Xe),qe(He),Je(He?"runtime":"model")))},[t,Te,Xe,He]);const fs=(n,h)=>{H(C=>({...C,[n]:h})),ot(!1),Y[n]&&et(C=>{const W={...C};return delete W[n],W})},Mt=(n,h)=>{O(C=>({...C,[n]:h})),ot(!1),Y[n]&&et(C=>{const W={...C};return delete W[n],W})},sa=n=>{m(n),ot(!1)},At=(n,h)=>{je(C=>({...C,[n]:h})),ot(!1),Y[n]&&et(C=>{const W={...C};return delete W[n],W})},Ue=s.useMemo(()=>{const n=In(E);for(const[X,ue]of Object.entries({heartbeatIntervalMs:{label:"Heartbeat Interval",min:1},heartbeatTimeoutMs:{label:"Heartbeat Timeout",min:5},maxConcurrentRuns:{label:"Max Concurrent Runs",min:1}})){const We=M[X]?.trim();if(!We)continue;const ct=Number(We);Number.isNaN(ct)||!Number.isFinite(ct)?n[X]=`"${ue.label}" must be a valid number`:ct<ue.min&&(n[X]=`"${ue.label}" must be at least ${ue.min.toLocaleString()}`)}const h=M.autoClaimCandidatesInPrompt?.trim();if(h){const X=Number(h);(!Number.isInteger(X)||X<0||X>10)&&(n.autoClaimCandidatesInPrompt='"Auto-claim candidates in prompt" must be an integer between 0 and 10')}const C=M.messageResponseMode?.trim();C&&!["immediate","on-heartbeat"].includes(C)&&(n.messageResponseMode='"Message Response Mode" must be either immediate or on-heartbeat');const W=ee.tokenBudget?.trim();if(W){const X=Number(W);Number.isNaN(X)||!Number.isFinite(X)?n.tokenBudget='"Token Budget" must be a valid number':X<=0&&(n.tokenBudget='"Token Budget" must be greater than 0')}const Me=ee.usageThreshold?.trim();if(Me){const X=Number(Me);Number.isNaN(X)||!Number.isFinite(X)?n.usageThreshold='"Usage Threshold" must be a valid number':(X<1||X>100)&&(n.usageThreshold='"Usage Threshold" must be between 1 and 100')}const ie=ee.budgetPeriod?.trim();ie&&!["daily","weekly","monthly","lifetime"].includes(ie)&&(n.budgetPeriod='"Budget Period" must be one of: daily, weekly, monthly, lifetime');const Ne=ee.resetDay?.trim(),Se=ie||"lifetime";if(Ne){const X=Number(Ne);Number.isNaN(X)||!Number.isFinite(X)?n.resetDay='"Reset Day" must be a valid number':Se==="weekly"?(X<0||X>6||!Number.isInteger(X))&&(n.resetDay='"Reset Day" must be between 0 (Sunday) and 6 (Saturday) for weekly period'):Se==="monthly"&&(X<1||X>31||!Number.isInteger(X))&&(n.resetDay='"Reset Day" must be between 1 and 31 for monthly period')}return n},[E,M,ee]),ps=s.useCallback(()=>{if(Object.keys(Ue).length>0)return null;const n={...t.metadata};for(const ue of jt){const We=E[ue.key]?.trim();We?ue.type==="number"?n[ue.key]=Number(We):n[ue.key]=We:delete n[ue.key]}Ie.length>0?n.skills=Ie:delete n.skills;const h={...t.runtimeConfig};Object.assign(h,Ua(t,b)),h.autoClaimRelevantTasks=k,h.engineerBacklogAutoClaim=ne,pe==="auto"?delete h.assignmentPolicy:h.assignmentPolicy=pe,h.runMissedHeartbeatOnStartup=Ce,h.allowParallelExecution=ce,h.skipHeartbeatWhenIdle=Ae;for(const ue of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns","autoClaimCandidatesInPrompt"]){const We=M[ue]?.trim();if(!We)delete h[ue];else{const ct=Number(We);h[ue]=ue==="maxConcurrentRuns"||ue==="autoClaimCandidatesInPrompt"?ct:ct*1e3}}const C=M.messageResponseMode?.trim();if(C?h.messageResponseMode=C:delete h.messageResponseMode,p?h.heartbeatScopeDiscipline=p:delete h.heartbeatScopeDiscipline,v?h.heartbeatPromptTemplate=v:delete h.heartbeatPromptTemplate,E.thinkingLevel?h.thinkingLevel=E.thinkingLevel:delete h.thinkingLevel,de==="runtime")Oe.trim()?h.runtimeHint=Oe.trim():delete h.runtimeHint,delete h.modelProvider,delete h.modelId,delete h.model;else if(delete h.runtimeHint,Pe.trim()){const ue=Pe.indexOf("/");ue!==-1&&(h.modelProvider=Pe.slice(0,ue),h.modelId=Pe.slice(ue+1),h.model=Pe.trim())}else delete h.modelProvider,delete h.modelId,delete h.model;const W={},Me=ee.tokenBudget?.trim(),ie=ee.usageThreshold?.trim(),Ne=ee.budgetPeriod?.trim(),Se=ee.resetDay?.trim();Me&&(W.tokenBudget=Number(Me)),ie&&(W.usageThreshold=Number(ie)/100),Ne&&(W.budgetPeriod=Ne),Se&&(W.resetDay=Number(Se)),Object.keys(W).length>0?h.budgetConfig=W:delete h.budgetConfig;let X;return re&&(X={mode:re,entryFile:Ee||"AGENTS.md",files:Le.length>0?Le:["AGENTS.md"]},re==="external"&&Fe.trim()&&(X.externalPath=Fe.trim())),{name:u.trim()||void 0,roles:[R,...g],title:F.trim()||void 0,icon:z.trim()||void 0,reportsTo:Z.trim()||void 0,metadata:n,runtimeConfig:h,bundleConfig:X}},[g,t.metadata,t.runtimeConfig,ce,pe,k,ee,Ee,Fe,Le,re,ne,E,b,v,p,M,z,Pe,u,Z,R,Ce,de,Oe,Ie,Ae,F,Ue]),xt=s.useCallback(async(n,h)=>{const C=ps();if(!C)return et(Ue),n&&l(a("agents.fixValidationErrors","Please fix validation errors before saving"),"error"),h==="auto"&&wt(a("agents.fixValidationToSave","Fix validation errors to save changes")),!1;const W=JSON.stringify(C);if(W===gs.current)return!1;const Me=++Rt.current;et({}),wt(null),ds(!0);try{return await Jt(t.id,C,i),Me!==Rt.current?!1:(gs.current=W,h==="manual"&&l(a("agents.settingsSaved","Settings saved"),"success"),wt(null),ot(!0),bt.current&&clearTimeout(bt.current),bt.current=setTimeout(()=>ot(!1),3e3),await r(),!0)}catch(ie){if(Me===Rt.current){const Ne=B(ie);wt(Ne),l(a("agents.settingsSaveFailed","Failed to save settings: {{error}}",{error:Ne}),"error")}return!1}finally{Me===Rt.current&&ds(!1)}},[l,t.id,ps,r,i,Ue]),aa=async()=>{await xt(!0,"manual")},le=s.useCallback(()=>{if(!(!Te||Ye)){if(Object.keys(Ue).length>0){et(Ue);return}xt(!1,"auto")}},[Te,Ye,xt,Ue]);s.useEffect(()=>{if(!Te||Ye)return;if(Object.keys(Ue).length>0){et(Ue);return}const n=setTimeout(()=>{xt(!1,"auto")},wn);return()=>clearTimeout(n)},[Te,Ye,xt,Ue]);const na=s.useCallback(async n=>{se(!0);try{await Va(t.id,n,i),await r(),l(a("agents.avatarUploaded","Avatar uploaded"),"success")}catch(h){l(B(h),"error")}finally{se(!1),Q.current&&(Q.current.value="")}},[l,t.id,r,i]),ia=s.useCallback(async()=>{se(!0);try{await Wa(t.id,i),await r(),l(a("agents.avatarRemoved","Avatar removed"),"success")}catch(n){l(B(n),"error")}finally{se(!1)}},[l,t.id,r,i]),bs=Ye?a("agents.savingChanges","Saving changes…"):_t?a("agents.saveFailed","Save failed: {{error}}",{error:_t}):!Te&&ta?a("agents.allChangesSaved","All changes saved"):null;return e.jsxs("div",{className:"config-tab",children:[e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:a("agents.configTitle","Agent Configuration")}),e.jsx("p",{className:"config-description",children:a("agents.configDescription","Configure agent settings and behavior.")}),e.jsx("div",{className:"config-actions-row",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>D(!0),children:a("agents.aiInterview","AI Interview")})}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-name",children:a("agents.nameLabel","Name")}),e.jsx("input",{id:"agent-name",type:"text",className:"input",value:u,onChange:n=>w(n.target.value),onBlur:()=>{le()}})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-role",children:a("agents.roleLabel2","Primary role")}),e.jsxs("select",{id:"agent-role",className:"select",value:R,onChange:n=>{const h=n.target.value;d(h),I(C=>C.filter(W=>W!==h)),le()},children:[e.jsx("option",{value:"triage",children:a("agents.roleTriage","Triage")}),e.jsx("option",{value:"executor",children:a("agents.roleExecutor","Executor")}),e.jsx("option",{value:"reviewer",children:a("agents.roleReviewer","Reviewer")}),e.jsx("option",{value:"merger",children:a("agents.roleMerger","Merger")}),e.jsx("option",{value:"scheduler",children:a("agents.roleScheduler","Scheduler")}),e.jsx("option",{value:"engineer",children:a("agents.roleEngineer","Engineer")}),e.jsx("option",{value:"custom",children:a("agents.roleCustom","Custom")})]}),e.jsxs("fieldset",{className:"config-role-tags","aria-label":a("agents.additionalRoles","Additional workflow roles"),children:[e.jsx("legend",{children:a("agents.additionalRoles","Additional workflow roles")}),["triage","executor","reviewer","merger","scheduler","engineer","custom"].filter(n=>n!==R).map(n=>e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:g.includes(n),onChange:()=>{I(h=>h.includes(n)?h.filter(C=>C!==n):[...h,n]),le()}}),n]},n))]})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-title",children:a("agents.titleLabel","Title")}),e.jsx("input",{id:"agent-title",type:"text",className:"input",placeholder:a("agents.titlePlaceholder","e.g. Senior Code Reviewer"),value:F,onChange:n=>T(n.target.value),onBlur:()=>{le()}})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{children:a("agents.avatarLabel","Avatar")}),e.jsxs("div",{className:"agent-avatar-editor",children:[e.jsx($s,{agent:t,size:64,className:"agent-avatar-editor-preview"}),e.jsxs("div",{className:"agent-avatar-editor-actions",children:[e.jsx("input",{ref:Q,id:"agent-avatar-upload",type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",className:"visually-hidden",disabled:$,onChange:n=>{const h=n.target.files?.[0];h&&na(h)}}),e.jsx("button",{type:"button",className:"btn btn-sm agent-avatar-editor-action",disabled:$,onClick:()=>Q.current?.click(),children:a("agents.uploadAvatar","Upload Avatar")}),t.imageUrl?e.jsx("button",{type:"button",className:"btn btn-sm agent-avatar-editor-action",onClick:()=>void ia(),disabled:$,children:a("agents.removeAvatar","Remove Avatar")}):null]})]})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-icon",children:a("agents.iconLabel","Icon")}),e.jsx("input",{id:"agent-icon",type:"text",className:"input",placeholder:a("agents.iconPlaceholder","e.g. 🤖"),value:z,onChange:n=>V(n.target.value),onBlur:()=>{le()}})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-reports-to",children:a("agents.reportsToLabel","Reports To")}),e.jsxs("select",{id:"agent-reports-to",className:"select",value:Z,onChange:n=>{j(n.target.value),le()},disabled:q,children:[e.jsx("option",{value:"",children:a("agents.noManager","No manager")}),$e&&e.jsx("option",{value:ge,children:a("agents.unknownManager","Unknown manager ({{id}})",{id:ge})}),Be.map(n=>e.jsxs("option",{value:n.id,children:[n.name," (",n.id,")"]},n.id))]})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:a("agents.skillsTitle","Skills")}),e.jsx("p",{className:"config-description",children:a("agents.skillsDescription","Assign skills to this agent for specialized behavior.")}),e.jsx("div",{className:"config-fields",children:e.jsx("div",{className:"config-field",children:e.jsx(on,{id:"agent-skills",label:"Skills",value:Ie,onChange:n=>{ut(n),le()},projectId:i})})})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:a("agents.modelTitle","Model")}),e.jsx("p",{className:"config-description",children:a("agents.modelDescription","Choose either a built-in model or a plugin runtime for this agent. These options are mutually exclusive.")}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{children:a("agents.runtimeSource","Runtime Source")}),e.jsxs("div",{className:"config-runtime-tabs",role:"tablist","aria-label":a("agents.runtimeSource","Runtime source"),children:[e.jsx("button",{type:"button",className:`config-runtime-tab${de==="model"?" active":""}`,role:"tab","aria-selected":de==="model",tabIndex:de==="model"?0:-1,onClick:()=>{Je("model"),qe(""),le()},children:a("agents.builtInModel","Built-in Model")}),e.jsx("button",{type:"button",className:`config-runtime-tab${de==="runtime"?" active":""}`,role:"tab","aria-selected":de==="runtime",tabIndex:de==="runtime"?0:-1,onClick:()=>{Je("runtime"),le()},children:a("agents.pluginRuntime","Plugin Runtime")})]})]}),de==="model"?e.jsx("div",{className:"config-field",children:e.jsx(Ga,{models:Bt,value:Pe,onChange:n=>{Ze(n),le()},placeholder:a("agents.inheritProjectRoleDefault","Inherit project/role default"),label:a("agents.agentModelLabel","Agent Model"),disabled:Ge,favoriteProviders:we,onToggleFavorite:mt,favoriteModels:at,onToggleModelFavorite:gt,thinkingLevel:E.thinkingLevel??"",defaultThinkingLevel:E.thinkingLevel?void 0:cn(t,o),onThinkingLevelChange:n=>{H(h=>({...h,thinkingLevel:n})),le()}})}):e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-runtime-hint",children:a("agents.runtimeLabel","Runtime")}),nt?e.jsx("span",{className:"config-hint",children:e.jsx(Xs,{label:a("agents.loadingRuntimes","Loading runtimes…")})}):e.jsxs("select",{id:"agent-runtime-hint",className:"select",value:Oe,onChange:n=>{qe(n.target.value),le()},children:[e.jsx("option",{value:"",children:ft.length>0?a("agents.selectRuntime","Select a plugin runtime…"):a("agents.noRuntimes","No plugin runtimes available")}),ft.map(n=>e.jsx("option",{value:n.runtimeId,children:n.description?`${n.name} — ${n.description}`:n.name},`${n.pluginId}:${n.runtimeId}`))]})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:a("agents.permissionsTitle","Permissions")}),e.jsx("p",{className:"config-description",children:a("agents.permissionsDescription","Per-agent settings override project defaults. Each category controls a separate approval gate.")}),e.jsxs("div",{className:"agent-capability-grants","data-testid":"agent-capability-grants",children:[e.jsx("h4",{children:a("agents.capabilityGrantsTitle","Capability grants")}),e.jsx("p",{className:"config-hint",children:a("agents.capabilityGrantsDescription","Explicit grants add to this agent's role defaults and apply to both permanent and ephemeral agents.")}),e.jsx("div",{className:"agent-capability-grants-grid",children:ks.map(n=>{const h=lt.has(n),C=he.has(n),W=`agent-capability-${t.id}-${n.replace(/[^a-z0-9]+/gi,"-")}`;return e.jsxs("label",{className:"agent-capability-grant-row",htmlFor:W,children:[e.jsxs("span",{children:[e.jsx("span",{className:"agent-capability-grant-name",children:n}),e.jsx("span",{className:"config-hint",children:h?a("agents.roleDefaultGrant","Role default grant"):C?a("agents.explicitGrant","Explicit grant"):a("agents.notGranted","Not granted")})]}),e.jsx("input",{id:W,type:"checkbox",checked:C,"aria-label":a("agents.toggleCapabilityGrant","Toggle explicit grant for {{permission}}",{permission:n}),onChange:Me=>{Ke(n,Me.target.checked)}})]},n)})})]}),f===void 0?e.jsxs("div",{className:"agent-permission-inherit-banner",children:[e.jsx("span",{children:a("agents.inheritingProjectDefault","Inheriting project default — no per-agent override set")}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void rt({presetId:"custom",rules:{git_write:te?.rules?.git_write??"allow",file_write_delete:te?.rules?.file_write_delete??"allow",command_execution:te?.rules?.command_execution??"allow",network_api:te?.rules?.network_api??"allow",task_agent_mutation:te?.rules?.task_agent_mutation??"allow",review_gate_bypass:te?.rules?.review_gate_bypass??"require-approval",file_scope:te?.rules?.file_scope??"allow"}}),children:a("agents.customizeForAgent","Customize for this agent")})]}):null,e.jsx(mn,{mode:"agent-override",value:f,projectDefault:te?.rules,projectDefaultToolRules:te?.toolRules,onChange:n=>{rt(n)}})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:a("agents.heartbeatSettingsTitle","Heartbeat Settings")}),e.jsx("p",{className:"config-description",children:a("agents.heartbeatSettingsDesc","Configure how this agent's heartbeat is monitored. Leave a field empty to use system defaults.")}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field agent-heartbeat-auto-claim-card",children:[e.jsxs("div",{className:"agent-heartbeat-preset-row",children:[e.jsxs("div",{children:[e.jsx("label",{className:"agent-heartbeat-preset-label",children:a("agents.coordinationOnlyAgent","Coordination-only agent")}),e.jsx("span",{className:"config-hint",children:a("agents.coordinationOnlyHint","Disables auto-claim and removes the candidate section from heartbeat prompts. Recommended for routing/CEO-style agents.")})]}),e.jsx("button",{type:"button",className:"btn btn-sm agent-heartbeat-preset-btn",onClick:()=>{_(!1),O(n=>({...n,autoClaimCandidatesInPrompt:"0"})),le()},children:a("agents.applyPreset","Apply preset")})]}),e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-autoClaimRelevantTasks",children:[e.jsx("input",{id:"hb-autoClaimRelevantTasks",type:"checkbox",checked:k,onChange:n=>{_(n.target.checked),le()}}),a("agents.autoClaimRelevantTasks","Auto-Claim Relevant Tasks")]}),e.jsx("span",{className:"config-hint",children:a("agents.autoClaimHint","When enabled (default), no-task heartbeats scan open unowned work and auto-claim tasks aligned with this agent's role and soul.")}),e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-engineerBacklogAutoClaim",children:[e.jsx("input",{id:"hb-engineerBacklogAutoClaim",type:"checkbox",checked:ne,onChange:n=>{xe(n.target.checked),le()}}),a("agents.engineerBacklogAutoClaim","Engineer Backlog Auto-Claim")]}),e.jsx("span",{className:"config-hint",children:a("agents.engineerBacklogAutoClaimHint","Per-agent override of the project default. Allows this engineer-role agent to auto-claim unowned backlog tasks; explicit assignment and delegation are unchanged.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-assignmentPolicy",children:a("agents.assignmentPolicy","Assignment Policy")}),e.jsxs("select",{id:"hb-assignmentPolicy",value:pe,onChange:n=>{Ve(n.target.value),le()},children:[e.jsx("option",{value:"auto",children:a("agents.assignmentPolicyAuto","Auto (default) — eligible for automatic assignment")}),e.jsx("option",{value:"explicit-only",children:a("agents.assignmentPolicyExplicitOnly","Explicit only — never auto-assigned; accepts direct assignment/delegation")}),e.jsx("option",{value:"none",children:a("agents.assignmentPolicyNone","None — can never receive implementation tasks")})]}),e.jsx("span",{className:"config-hint",children:a("agents.assignmentPolicyHint",'Controls whether task routing may bind work to this agent. Use "None" for liaison/observer agents that must never execute product tasks — no override can bypass it.')})]}),e.jsxs("div",{className:"config-field",children:[e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-enabled",children:[e.jsx("input",{id:"hb-enabled",type:"checkbox",checked:b,onChange:n=>{sa(n.target.checked),le()}}),a("agents.heartbeatEnabled","Heartbeat Enabled")]}),e.jsx("span",{className:"config-hint",children:a("agents.heartbeatEnabledHint","When enabled, this agent receives scheduled heartbeat runs based on its interval.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-runMissedHeartbeatOnStartup",children:[e.jsx("input",{id:"hb-runMissedHeartbeatOnStartup",type:"checkbox",checked:Ce,onChange:n=>{fe(n.target.checked),le()}}),a("agents.runMissedHeartbeat","Run Missed Heartbeat On Startup")]}),e.jsx("span",{className:"config-hint",children:a("agents.runMissedHeartbeatHint","When enabled, if the server was down across this agent's scheduled heartbeat tick, fire a single catch-up heartbeat at startup. Default: off.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-allowParallelExecution",children:[e.jsx("input",{id:"hb-allowParallelExecution",type:"checkbox",checked:ce,onChange:n=>{ve(n.target.checked),le()}}),a("agents.allowParallelExecution","Allow Parallel Execution")]}),e.jsx("span",{className:"config-hint",children:a("agents.allowParallelExecutionHint","When disabled, the heartbeat and task execution paths serialize for this agent (heartbeat will not start while the agent's task is executing, and vice versa). Permanent agents only.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-skipHeartbeatWhenIdle",children:[e.jsx("input",{id:"hb-skipHeartbeatWhenIdle",type:"checkbox",checked:Ae,onChange:n=>{ze(n.target.checked),le()}}),a("agents.skipHeartbeatWhenIdle","Skip heartbeat when idle")]}),e.jsx("span",{className:"config-hint",children:a("agents.skipHeartbeatWhenIdleHint","When enabled, scheduled (timer) heartbeats are skipped while this agent has no assigned task. The agent still wakes immediately when a task is assigned or you trigger a run manually. Default: off.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-heartbeatScopeDiscipline",children:a("agents.heartbeatScopeDiscipline","Heartbeat Scope Discipline")}),e.jsxs("select",{id:"hb-heartbeatScopeDiscipline",className:"select",value:p,onChange:n=>{const h=n.target.value;A(h==="strict"||h==="lite"||h==="off"?h:""),le()},children:[e.jsx("option",{value:"",children:a("agents.inheritProjectDefault","Inherit project default")}),e.jsx("option",{value:"strict",children:a("agents.strict","Strict")}),e.jsx("option",{value:"lite",children:a("agents.lite","Lite")}),e.jsx("option",{value:"off",children:a("agents.off","Off")})]}),e.jsx("span",{className:"config-hint",children:a("agents.scopeDisciplineHint","Strict — coordination-focused; higher per-tick tokens. Lite — pre-2026-05-11 behavior. Off — minimal procedure.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-heartbeatPromptTemplate",children:a("agents.heartbeatPromptTemplate","Heartbeat Prompt Template")}),e.jsxs("select",{id:"hb-heartbeatPromptTemplate",className:"select",value:v,onChange:n=>{const h=n.target.value;ae(h==="default"||h==="compact"?h:""),le()},children:[e.jsx("option",{value:"",children:a("agents.inheritProjectDefault","Inherit project default")}),e.jsx("option",{value:"default",children:a("agents.templateDefault","Default")}),e.jsx("option",{value:"compact",children:a("agents.templateCompact","Compact")})]})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-heartbeatIntervalMs",children:a("agents.heartbeatIntervalLabel","Heartbeat Interval (s)")}),e.jsx("input",{id:"hb-heartbeatIntervalMs",type:"text",inputMode:"numeric",className:me("input",!!Y.heartbeatIntervalMs&&"input--error"),placeholder:String(as/1e3),value:M.heartbeatIntervalMs??"",onChange:n=>Mt("heartbeatIntervalMs",n.target.value)}),Y.heartbeatIntervalMs?e.jsx("span",{className:"config-error",children:Y.heartbeatIntervalMs}):e.jsx("span",{className:"config-hint",children:a("agents.heartbeatIntervalHint","How often heartbeats are checked. Leave empty for system default ({{seconds}}s / {{label}}).",{seconds:as/1e3,label:Cn})})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-heartbeatTimeoutMs",children:a("agents.heartbeatTimeoutLabel","Heartbeat Timeout (s)")}),e.jsx("input",{id:"hb-heartbeatTimeoutMs",type:"text",inputMode:"numeric",className:me("input",!!Y.heartbeatTimeoutMs&&"input--error"),placeholder:"60",value:M.heartbeatTimeoutMs??"",onChange:n=>Mt("heartbeatTimeoutMs",n.target.value)}),Y.heartbeatTimeoutMs?e.jsx("span",{className:"config-error",children:Y.heartbeatTimeoutMs}):e.jsx("span",{className:"config-hint",children:a("agents.heartbeatTimeoutHint","Time without heartbeat before agent is considered unresponsive. Leave empty for system default (60s)")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-maxConcurrentRuns",children:a("agents.maxConcurrentRunsLabel","Max Concurrent Runs")}),e.jsx("input",{id:"hb-maxConcurrentRuns",type:"text",inputMode:"numeric",className:me("input",!!Y.maxConcurrentRuns&&"input--error"),placeholder:"1",value:M.maxConcurrentRuns??"",onChange:n=>Mt("maxConcurrentRuns",n.target.value)}),Y.maxConcurrentRuns?e.jsx("span",{className:"config-error",children:Y.maxConcurrentRuns}):e.jsx("span",{className:"config-hint",children:a("agents.maxConcurrentRunsHint","Maximum simultaneous heartbeat runs for this agent. Leave empty for system default (1).")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-messageResponseMode",children:a("agents.messageResponseModeLabel","Message Response Mode")}),e.jsxs("select",{id:"hb-messageResponseMode",className:me("select",!!Y.messageResponseMode&&"input--error"),value:M.messageResponseMode??"",onChange:n=>Mt("messageResponseMode",n.target.value),children:[e.jsx("option",{value:"",children:a("agents.systemDefaultOnHeartbeat","System Default (On Heartbeat)")}),e.jsx("option",{value:"on-heartbeat",children:a("agents.onHeartbeat","On Heartbeat")}),e.jsx("option",{value:"immediate",children:a("agents.immediate","Immediate")})]}),Y.messageResponseMode?e.jsx("span",{className:"config-error",children:Y.messageResponseMode}):e.jsx("span",{className:"config-hint",children:a("agents.messageResponseModeHint","How this agent responds to incoming messages. 'Immediate' wakes the agent as soon as a message arrives. 'On Heartbeat' defers processing to the next scheduled heartbeat.")})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:a("agents.budgetSettingsTitle","Budget Settings")}),e.jsx("p",{className:"config-description",children:a("agents.budgetSettingsDesc","Configure token budget limits for this agent. Leave all fields empty to disable budget tracking.")}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"budget-tokenBudget",children:a("agents.tokenBudgetLabel","Token Budget")}),e.jsx("input",{id:"budget-tokenBudget",type:"text",inputMode:"numeric",className:me("input",!!Y.tokenBudget&&"input--error"),placeholder:a("agents.noLimit","No limit"),value:ee.tokenBudget??"",onChange:n=>At("tokenBudget",n.target.value)}),Y.tokenBudget?e.jsx("span",{className:"config-error",children:Y.tokenBudget}):e.jsx("span",{className:"config-hint",children:a("agents.tokenBudgetHint","Total token cap (input + output) for this agent. Leave empty for no limit.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"budget-usageThreshold",children:a("agents.usageThresholdLabel","Usage Threshold (%)")}),e.jsx("input",{id:"budget-usageThreshold",type:"text",inputMode:"numeric",className:me("input",!!Y.usageThreshold&&"input--error"),placeholder:"80",value:ee.usageThreshold??"",onChange:n=>At("usageThreshold",n.target.value)}),Y.usageThreshold?e.jsx("span",{className:"config-error",children:Y.usageThreshold}):e.jsx("span",{className:"config-hint",children:a("agents.usageThresholdHint","Warning threshold as a percentage. Agent warns when usage reaches this level. Default: 80%.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"budget-budgetPeriod",children:a("agents.budgetPeriodLabel","Budget Period")}),e.jsxs("select",{id:"budget-budgetPeriod",className:me("select",!!Y.budgetPeriod&&"input--error"),value:ee.budgetPeriod??"",onChange:n=>At("budgetPeriod",n.target.value),children:[e.jsx("option",{value:"",children:a("agents.noReset","No reset (lifetime)")}),e.jsx("option",{value:"daily",children:a("agents.daily","Daily")}),e.jsx("option",{value:"weekly",children:a("agents.weekly","Weekly")}),e.jsx("option",{value:"monthly",children:a("agents.monthly","Monthly")})]}),Y.budgetPeriod?e.jsx("span",{className:"config-error",children:Y.budgetPeriod}):e.jsx("span",{className:"config-hint",children:a("agents.budgetPeriodHint","How often the budget counter resets. Leave empty for lifetime budget.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"budget-resetDay",children:a("agents.resetDayLabel","Reset Day")}),e.jsx("input",{id:"budget-resetDay",type:"text",inputMode:"numeric",className:me("input",!!Y.resetDay&&"input--error"),placeholder:a("agents.auto","Auto"),value:ee.resetDay??"",onChange:n=>At("resetDay",n.target.value)}),Y.resetDay?e.jsx("span",{className:"config-error",children:Y.resetDay}):e.jsx("span",{className:"config-hint",children:ee.budgetPeriod==="weekly"?a("agents.resetDayWeekly","Day of week (0=Sunday to 6=Saturday) for reset."):ee.budgetPeriod==="monthly"?a("agents.resetDayMonthly","Day of month (1-31) for reset."):a("agents.resetDayHint","Day for reset (weekly: 0-6, monthly: 1-31). Leave empty for automatic.")})]}),_e?.budgetLimit!=null&&e.jsxs("div",{className:"config-field",children:[e.jsx("label",{children:a("agents.currentUsage","Current Usage")}),e.jsxs("div",{className:"budget-progress-container",children:[e.jsx("div",{className:"budget-progress-bar",children:e.jsx("div",{className:me("budget-progress-bar__fill",(_e.usagePercent??0)>=100?"budget-progress-bar__fill--red":(_e.usagePercent??0)>=80?"budget-progress-bar__fill--amber":"budget-progress-bar__fill--green"),style:{width:`${Math.min(_e.usagePercent??0,100)}%`}})}),e.jsx("span",{className:"budget-progress-label",children:a("agents.budgetUsageDisplay","{{used}} / {{limit}} tokens ({{percent}}% used)",{used:(_e.currentUsage??0).toLocaleString(),limit:(_e.budgetLimit??0).toLocaleString(),percent:Math.round(_e.usagePercent??0)})})]})]}),_e?.budgetLimit!=null&&e.jsx("div",{className:"config-field",children:e.jsx("button",{className:"btn btn-reset-budget",onClick:()=>void ea(),disabled:os,children:os?e.jsxs(e.Fragment,{children:[e.jsx(J,{size:14,className:"animate-spin"}),a("agents.resetting","Resetting…")]}):e.jsxs(e.Fragment,{children:[e.jsx(St,{size:14}),a("agents.resetBudgetUsage","Reset Budget Usage")]})})})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:a("agents.bundleTitle","Instruction Bundle")}),e.jsx("p",{className:"config-description",children:a("agents.bundleDescription","Configure the agent's instruction bundle. Leave empty to use inline instructions only.")}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-mode",children:a("agents.bundleModeLabel","Bundle Mode")}),e.jsxs("select",{id:"bundle-mode",className:"select",value:re,onChange:n=>ye(n.target.value),children:[e.jsx("option",{value:"",children:a("agents.bundleNone","None (use inline instructions)")}),e.jsx("option",{value:"managed",children:a("agents.bundleManaged","Managed (system-managed directory)")}),e.jsx("option",{value:"external",children:a("agents.bundleExternal","External (user-specified path)")})]}),e.jsxs("span",{className:"config-hint",children:[re==="managed"&&a("agents.bundleManagedHint","Files will be stored in a system-managed directory within .fusion/agents/"),re==="external"&&a("agents.bundleExternalHint","Specify an external directory path for the instruction files"),!re&&a("agents.bundleSelectMode","Select a mode to enable instruction bundling")]})]}),re&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-entry-file",children:a("agents.bundleEntryFileLabel","Entry File")}),e.jsx("input",{id:"bundle-entry-file",type:"text",className:"input",placeholder:"AGENTS.md",value:Ee,onChange:n=>st(n.target.value)}),e.jsx("span",{className:"config-hint",children:a("agents.bundleEntryFileHint","Primary instructions file name (default: AGENTS.md)")})]}),re==="external"&&e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-external-path",children:a("agents.bundleExternalPathLabel","External Path")}),e.jsx("input",{id:"bundle-external-path",type:"text",className:"input",placeholder:a("agents.bundleExternalPathPlaceholder","e.g. .fusion/agents/my-agent"),value:Fe,onChange:n=>kt(n.target.value)}),e.jsx("span",{className:"config-hint",children:a("agents.bundleExternalPathHint","Absolute or relative path to the external directory")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-files",children:a("agents.bundleFilesLabel","Files (comma-separated)")}),e.jsx("input",{id:"bundle-files",type:"text",className:"input",placeholder:"AGENTS.md, PROMPTS.md",value:Le.join(", "),onChange:n=>oe(n.target.value.split(",").map(h=>h.trim()).filter(Boolean))}),e.jsx("span",{className:"config-hint",children:a("agents.bundleFilesHint","List of file names in the bundle directory")})]})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:a("agents.advancedSettingsTitle","Advanced Settings")}),e.jsx("p",{className:"config-description",children:a("agents.advancedSettingsDesc","Advanced configuration options for this agent. Leave a field empty to use system defaults.")}),e.jsx("div",{className:"config-fields",children:jt.map(n=>{const h=!!Y[n.key];return e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:`adv-${n.key}`,children:n.label}),n.type==="select"?e.jsxs("select",{id:`adv-${n.key}`,className:me("select",h&&"input--error"),value:E[n.key]??"",onChange:C=>fs(n.key,C.target.value),children:[e.jsx("option",{value:"",children:a("agents.systemDefault","System Default")}),n.options?.map(C=>e.jsx("option",{value:C.value,children:C.label},C.value))]}):e.jsx("input",{id:`adv-${n.key}`,type:"text",inputMode:n.type==="number"?"numeric":void 0,className:me("input",h&&"input--error"),placeholder:n.placeholder,value:E[n.key]??"",onChange:C=>fs(n.key,C.target.value)}),h&&e.jsx("span",{className:"config-error",children:Y[n.key]}),!h&&n.hint&&e.jsx("span",{className:"config-hint",children:n.hint})]},n.key)})}),e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!Te||Ye,onClick:()=>void aa(),children:Ye?e.jsxs(e.Fragment,{children:[e.jsx(J,{size:16,className:"animate-spin"}),a("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(be,{size:16}),a("agents.saveSettings","Save Settings")]})}),bs&&e.jsxs("span",{className:me("config-saved-indicator",_t&&"config-saved-indicator--error"),children:[Ye?e.jsx(J,{size:14,className:"animate-spin"}):e.jsx(be,{size:14}),bs]})]})]}),e.jsx(_n,{agent:t,projectId:i,addToast:l,onSaved:r}),e.jsxs("div",{className:"config-section config-section--danger",children:[e.jsx("h3",{children:a("agents.dangerZone","Danger Zone")}),e.jsx("p",{className:"config-description",children:a("agents.dangerZoneDesc","Permanently delete this agent from the project.")}),e.jsx("div",{className:"config-fields",children:e.jsxs("div",{className:"config-field",children:[e.jsxs("button",{className:"btn btn--danger",disabled:!us||!y,onClick:()=>void y?.(),children:[e.jsx(yt,{size:16}),a("agents.deleteAgent","Delete Agent")]}),e.jsx("span",{className:"config-danger-note",children:us?a("agents.deletionPermanent","Deletion is permanent and cannot be undone."):a("agents.deletionNotAvailable","Agent deletion is only available when state is idle or paused (current state: {{state}}).",{state:t.state})})]})})]}),e.jsx(dn,{isOpen:K,onClose:()=>D(!1),onUseDraft:it,projectId:i,existingAgents:N,mode:"edit",existingAgentConfig:Qe})]})}function Vn({agentId:t,projectId:i,onChildClick:o}){const{t:l}=ke("app"),[r,c]=s.useState([]),[y,x]=s.useState(!0);return s.useEffect(()=>{x(!0),Da(t,i).then(c).finally(()=>x(!1))},[t,i]),y?e.jsxs("div",{className:"detail-section",children:[e.jsx("div",{className:"detail-section-header",children:e.jsx("h3",{children:l("agents.employeesTitle","Employees")})}),e.jsxs("div",{className:"detail-section-body detail-section-body--loading",children:[e.jsx(J,{size:16,className:"spin"}),e.jsx("span",{className:"text-muted",children:l("agents.loadingEmployees","Loading employees...")})]})]}):e.jsxs("div",{className:"detail-section",children:[e.jsxs("div",{className:"detail-section-header",children:[e.jsx("h3",{children:l("agents.employeesTitle","Employees")}),e.jsxs("span",{className:"text-muted",children:["(",r.length,")"]})]}),e.jsx("div",{className:"detail-section-body",children:r.length===0?e.jsxs("div",{className:"agent-empty agent-empty--padded",children:[e.jsx(Vs,{size:32,opacity:.3}),e.jsx("p",{children:l("agents.noEmployees","No employees")}),e.jsx("p",{className:"text-muted",children:l("agents.noEmployeesDesc","This agent has no employees")})]}):e.jsx("div",{className:"agent-tree__children",children:r.map(a=>{const u=ls[a.state];return e.jsxs("div",{className:"agent-tree__node agent-is-child",onClick:()=>o?.(a.id),role:"button",tabIndex:0,onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.key===" "&&w.preventDefault(),o?.(a.id))},style:{cursor:o?"pointer":"default"},children:[e.jsx("span",{className:"agent-tree__icon",children:a.icon??"🤖"}),e.jsx("span",{className:"agent-tree__name",children:a.name}),e.jsx("span",{className:"agent-tree__badge",style:{background:u?.bg??"var(--state-idle-bg)",color:u?.text??"var(--state-idle-text)",border:`1px solid ${u?.border??"var(--state-idle-border)"}`},children:a.state})]},a.id)})})})]})}export{ei as AgentDetailView,tt as relativeTime};