@runfusion/fusion 0.54.0 → 0.55.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 (135) hide show
  1. package/dist/bin.js +3384 -768
  2. package/dist/client/.vite/manifest.json +283 -251
  3. package/dist/client/assets/AgentDetailView-B_VfFSlt.js +18 -0
  4. package/dist/client/assets/{AgentDetailView-BzSyldiW.css → AgentDetailView-D7UY2Tup.css} +1 -1
  5. package/dist/client/assets/{AgentPermissionPolicyEditor-D2AQ6swg.js → AgentPermissionPolicyEditor-QZhz41AU.js} +1 -1
  6. package/dist/client/assets/{AgentsView-DwEFPKuN.js → AgentsView-hkhJ8SUq.js} +6 -6
  7. package/dist/client/assets/ChatView-B4WnXLYA.js +6 -0
  8. package/dist/client/assets/{CommandCenter-BABqoSkg.js → CommandCenter-B3fAajUO.js} +16 -16
  9. package/dist/client/assets/{DevServerView-DlgOzRdC.js → DevServerView-BR0ngFBw.js} +1 -1
  10. package/dist/client/assets/{DirectoryPicker-BwMSmxYS.js → DirectoryPicker-BiS41Hca.js} +1 -1
  11. package/dist/client/assets/DocumentsView-BnRvIUpa.js +1 -0
  12. package/dist/client/assets/{EvalsView-CQBNrO5n.js → EvalsView-Bvx18QyC.js} +1 -1
  13. package/dist/client/assets/{ExperimentalAgentOnboardingModal-2SDqP2lc.js → ExperimentalAgentOnboardingModal-CKGJcfXI.js} +1 -1
  14. package/dist/client/assets/{GoalsView-BgkX-_SB.js → GoalsView-Bj1yVIiv.js} +1 -1
  15. package/dist/client/assets/{InsightsView-CJY4eZcO.js → InsightsView-DBX8DI60.js} +2 -2
  16. package/dist/client/assets/{MemoryView-5Crtfanz.js → MemoryView-CqkRH2fa.js} +1 -1
  17. package/dist/client/assets/{PiExtensionsManager-COmzskVa.js → PiExtensionsManager-BMMmGWe2.js} +2 -2
  18. package/dist/client/assets/PluginManager-C1bdfN2W.js +1 -0
  19. package/dist/client/assets/{PullRequestView-DAHh0FVM.js → PullRequestView-D0CsXWLl.js} +2 -2
  20. package/dist/client/assets/{ResearchView-cSUka3sd.js → ResearchView-CVgmXAlj.js} +1 -1
  21. package/dist/client/assets/{SecretsView-ChFAfFRY.js → SecretsView-Bv_gw5Ix.js} +1 -1
  22. package/dist/client/assets/{SessionTerminal-D4R3ScvQ.css → SessionTerminal-BvK8A98c.css} +1 -1
  23. package/dist/client/assets/{SessionTerminal-CtQKDaqI.js → SessionTerminal-VLdVV3Ji.js} +1 -1
  24. package/dist/client/assets/{SettingsModal-BzZNPNIh.css → SettingsModal-4t8rV7rh.css} +1 -1
  25. package/dist/client/assets/{SettingsModal-pAz_hOoN.js → SettingsModal-D7YgojbV.js} +1 -1
  26. package/dist/client/assets/SettingsModal-gcrh5EOG.js +21 -0
  27. package/dist/client/assets/SetupWizardModal-DvmTlFP_.js +2 -0
  28. package/dist/client/assets/{ShadcnColorPicker-CsfgWpf6.js → ShadcnColorPicker-DM2fqGwl.js} +1 -1
  29. package/dist/client/assets/{SkillsView-BSUplEYb.js → SkillsView-Bb-JTo99.js} +1 -1
  30. package/dist/client/assets/{TodoView-DhBseLvM.js → TodoView-bV-7deOh.js} +1 -1
  31. package/dist/client/assets/{WorkflowNodeEditor-Bi12CNif.js → WorkflowNodeEditor-Ui1q_fFI.js} +3 -3
  32. package/dist/client/assets/{agentSkills-qVb0x_G3.js → agentSkills-DGFyuKuP.js} +1 -1
  33. package/dist/client/assets/{app-DczBmsP4.js → app--OM-ul6R.js} +3 -3
  34. package/dist/client/assets/{app-BhtYYxin.js → app-BCvqf8qq.js} +3 -3
  35. package/dist/client/assets/app-BZqqEiWR.js +13 -0
  36. package/dist/client/assets/{app-5S4z84u5.js → app-DQeH1UDD.js} +3 -3
  37. package/dist/client/assets/{app-Cts0__Vx.js → app-FiYwRatp.js} +3 -3
  38. package/dist/client/assets/{app-_GFUqcMK.js → app-rGdYcsAA.js} +3 -3
  39. package/dist/client/assets/{architectureDiagram-3BPJPVTR-DEt4eIEQ.js → architectureDiagram-3BPJPVTR-DP7vOyXY.js} +1 -1
  40. package/dist/client/assets/{blockDiagram-GPEHLZMM-CJuX0UM_.js → blockDiagram-GPEHLZMM-Di9v1pV8.js} +1 -1
  41. package/dist/client/assets/{c4Diagram-AAUBKEIU-a46Lm113.js → c4Diagram-AAUBKEIU-Dvb8RSfr.js} +1 -1
  42. package/dist/client/assets/channel-C5g9M3Sk.js +1 -0
  43. package/dist/client/assets/{chunk-2J33WTMH-iBhwyS0c.js → chunk-2J33WTMH-gLcAuGjI.js} +1 -1
  44. package/dist/client/assets/{chunk-4BX2VUAB-C7lS5wER.js → chunk-4BX2VUAB-B-B0wjkx.js} +1 -1
  45. package/dist/client/assets/{chunk-55IACEB6-CQ6YOncn.js → chunk-55IACEB6-XUDeC0Co.js} +1 -1
  46. package/dist/client/assets/{chunk-727SXJPM-CveMaMKK.js → chunk-727SXJPM-1eebiGA2.js} +1 -1
  47. package/dist/client/assets/{chunk-AQP2D5EJ-DErjGUEk.js → chunk-AQP2D5EJ-D9VOB5QS.js} +1 -1
  48. package/dist/client/assets/{chunk-FMBD7UC4-DXUvEFfJ.js → chunk-FMBD7UC4-EFNFEaAz.js} +1 -1
  49. package/dist/client/assets/{chunk-ND2GUHAM-w5RqSj1J.js → chunk-ND2GUHAM-CbeQailD.js} +1 -1
  50. package/dist/client/assets/{chunk-QZHKN3VN-CAi0lJ7V.js → chunk-QZHKN3VN-D55N6EBz.js} +1 -1
  51. package/dist/client/assets/classDiagram-4FO5ZUOK-B-wdlvD6.js +1 -0
  52. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-B-wdlvD6.js +1 -0
  53. package/dist/client/assets/{cose-bilkent-S5V4N54A-Ck2h4uV5.js → cose-bilkent-S5V4N54A-B0zbhkX3.js} +1 -1
  54. package/dist/client/assets/createLucideIcon-CshVyKO4.js +21 -0
  55. package/dist/client/assets/{dagre-BM42HDAG-BCRTXNj6.js → dagre-BM42HDAG-BL6peXwl.js} +1 -1
  56. package/dist/client/assets/dashboard-view-Bsdq3OM4.css +1 -0
  57. package/dist/client/assets/dashboard-view-CS1H5SQN.js +1 -0
  58. package/dist/client/assets/dashboard-view-DafOfnxI.js +1 -0
  59. package/dist/client/assets/{dashboard-view-D9rF_PCq.js → dashboard-view-Db3n_W85.js} +1320 -1335
  60. package/dist/client/assets/{diagram-2AECGRRQ-DTTk-DYO.js → diagram-2AECGRRQ-cYKwSHk7.js} +1 -1
  61. package/dist/client/assets/{diagram-5GNKFQAL-jDc9kMi2.js → diagram-5GNKFQAL-DHIwTGuM.js} +1 -1
  62. package/dist/client/assets/{diagram-KO2AKTUF-CcLmzlGr.js → diagram-KO2AKTUF-DfHBJ4aX.js} +1 -1
  63. package/dist/client/assets/{diagram-LMA3HP47-DCW8XKQj.js → diagram-LMA3HP47-pWhYmB6Z.js} +1 -1
  64. package/dist/client/assets/{diagram-OG6HWLK6-wbbKquPs.js → diagram-OG6HWLK6-GzWqbi_m.js} +1 -1
  65. package/dist/client/assets/{erDiagram-TEJ5UH35-Fo933Mo7.js → erDiagram-TEJ5UH35-CCVm5eiR.js} +1 -1
  66. package/dist/client/assets/{flowDiagram-I6XJVG4X-Dfum7HZP.js → flowDiagram-I6XJVG4X-CUTdnU6S.js} +1 -1
  67. package/dist/client/assets/{folder-open-B8vOwFeP.js → folder-open-DOCy9GVC.js} +1 -1
  68. package/dist/client/assets/{ganttDiagram-6RSMTGT7-BzEBCn01.js → ganttDiagram-6RSMTGT7-CW4ENJaC.js} +1 -1
  69. package/dist/client/assets/{gitGraphDiagram-PVQCEYII-CgovghHs.js → gitGraphDiagram-PVQCEYII-QXXMfSzp.js} +1 -1
  70. package/dist/client/assets/index-B6ttSchA.js +1336 -0
  71. package/dist/client/assets/index-CPE2Kwra.css +1 -0
  72. package/dist/client/assets/{infoDiagram-5YYISTIA-BzpU4Wys.js → infoDiagram-5YYISTIA-CZyHbj0n.js} +1 -1
  73. package/dist/client/assets/{ishikawaDiagram-YF4QCWOH-cpp5pozu.js → ishikawaDiagram-YF4QCWOH-Dea84lqZ.js} +1 -1
  74. package/dist/client/assets/{journeyDiagram-JHISSGLW-BVjcw6oo.js → journeyDiagram-JHISSGLW-Db2iKGU5.js} +1 -1
  75. package/dist/client/assets/{kanban-definition-UN3LZRKU-4unAhBzo.js → kanban-definition-UN3LZRKU-CB9loIqR.js} +1 -1
  76. package/dist/client/assets/loader-circle-CMNcxXXr.js +16 -0
  77. package/dist/client/assets/{mermaid.core-DzIyUj9t.js → mermaid.core-CoQ8aCb0.js} +4 -4
  78. package/dist/client/assets/{mindmap-definition-RKZ34NQL-Be_yfVir.js → mindmap-definition-RKZ34NQL-JPb2wF-K.js} +1 -1
  79. package/dist/client/assets/{pieDiagram-4H26LBE5-Cfnw2aji.js → pieDiagram-4H26LBE5-pdZzOreP.js} +1 -1
  80. package/dist/client/assets/{quadrantDiagram-W4KKPZXB-BFlC-_Uo.js → quadrantDiagram-W4KKPZXB-Dh9Ids90.js} +1 -1
  81. package/dist/client/assets/{requirementDiagram-4Y6WPE33-DpVPzCOx.js → requirementDiagram-4Y6WPE33-BVPOSvHU.js} +1 -1
  82. package/dist/client/assets/{sankeyDiagram-5OEKKPKP-DM-gKKP0.js → sankeyDiagram-5OEKKPKP-BqSMUpsx.js} +1 -1
  83. package/dist/client/assets/{sequenceDiagram-3UESZ5HK-DjhZCZhd.js → sequenceDiagram-3UESZ5HK-B8nepQ6X.js} +1 -1
  84. package/dist/client/assets/{shield-alert-DCfkjjYc.js → shield-alert-CtSaIQNY.js} +1 -1
  85. package/dist/client/assets/{stateDiagram-AJRCARHV-BCA96rdI.js → stateDiagram-AJRCARHV-CQv9RdRp.js} +1 -1
  86. package/dist/client/assets/{stateDiagram-v2-BHNVJYJU-DHds08RS.js → stateDiagram-v2-BHNVJYJU-BZ_mlvie.js} +1 -1
  87. package/dist/client/assets/{timeline-definition-PNZ67QCA-CHW2OQRw.js → timeline-definition-PNZ67QCA-CAjwM-Z5.js} +1 -1
  88. package/dist/client/assets/{upload-EJc5PJPz.js → upload-0_pT1euA.js} +1 -1
  89. package/dist/client/assets/{users-C-e-99Vp.js → users--1B6mnm8.js} +1 -1
  90. package/dist/client/assets/{vennDiagram-CIIHVFJN-shGh4eBY.js → vennDiagram-CIIHVFJN-BO3Um3rH.js} +1 -1
  91. package/dist/client/assets/{wardley-L42UT6IY-l0RGrVhn.js → wardley-L42UT6IY-BzqJcqDA.js} +1 -1
  92. package/dist/client/assets/{wardleyDiagram-YWT4CUSO-C-USmO8A.js → wardleyDiagram-YWT4CUSO-Bctxc6_5.js} +1 -1
  93. package/dist/client/assets/{xychartDiagram-2RQKCTM6-CHX9Umta.js → xychartDiagram-2RQKCTM6-CgDuiMFR.js} +1 -1
  94. package/dist/client/assets/zoom-out-DzDzWQt1.js +21 -0
  95. package/dist/client/index.html +13 -4
  96. package/dist/client/version.json +1 -1
  97. package/dist/droid-cli/package.json +1 -1
  98. package/dist/extension.js +2066 -271
  99. package/dist/pi-claude-cli/package.json +1 -1
  100. package/dist/plugin-sdk/index.d.ts +61 -1
  101. package/dist/plugins/fusion-plugin-acp-runtime/package.json +1 -1
  102. package/dist/plugins/fusion-plugin-cli-printing-press/package.json +1 -1
  103. package/dist/plugins/fusion-plugin-compound-engineering/package.json +1 -1
  104. package/dist/plugins/fusion-plugin-cursor-runtime/bundled.js +70 -25
  105. package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
  106. package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
  107. package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
  108. package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
  109. package/dist/plugins/fusion-plugin-linear-import/bundled.js +658 -0
  110. package/dist/plugins/fusion-plugin-linear-import/manifest.json +48 -0
  111. package/dist/plugins/fusion-plugin-linear-import/package.json +11 -0
  112. package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
  113. package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
  114. package/dist/plugins/fusion-plugin-reports/package.json +1 -1
  115. package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
  116. package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
  117. package/package.json +2 -1
  118. package/skill/fusion/SKILL.md +2 -2
  119. package/skill/fusion/references/engine-tools.md +1 -0
  120. package/skill/fusion/references/extension-tools.md +81 -0
  121. package/skill/fusion/references/fusion-capabilities.md +7 -0
  122. package/dist/client/assets/AgentDetailView-BJditQat.js +0 -18
  123. package/dist/client/assets/ChatView-B4bjPXFN.js +0 -6
  124. package/dist/client/assets/DocumentsView-BfaRXFg5.js +0 -1
  125. package/dist/client/assets/PluginManager-CGWXqZMa.js +0 -1
  126. package/dist/client/assets/SettingsModal-BYaotQ2o.js +0 -21
  127. package/dist/client/assets/SetupWizardModal-eHZHi8VP.js +0 -2
  128. package/dist/client/assets/app-B1VYocx2.js +0 -13
  129. package/dist/client/assets/channel-BGI9APMr.js +0 -1
  130. package/dist/client/assets/classDiagram-4FO5ZUOK-g6hCcufy.js +0 -1
  131. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-g6hCcufy.js +0 -1
  132. package/dist/client/assets/dashboard-view-BfLJ60Kd.js +0 -1
  133. package/dist/client/assets/index-BjELA24x.js +0 -1336
  134. package/dist/client/assets/index-DwGW7OJh.css +0 -1
  135. package/dist/client/assets/zoom-out-NWbVkreR.js +0 -41
@@ -1,18 +0,0 @@
1
- import{r as a,j as e}from"./vendor-react-SZ_qB27O.js";import{c as Jt,c6 as _s,c7 as Us,c8 as Vs,c9 as Ws,L as q,R as Mt,bQ as is,Z as Js,bt as Et,ca as ps,J as rt,o as xs,C as vs,cb as qs,cc as Gs,cd as Ks,ae as js,ce as Ys,cf as Zs,bp as U,cg as Qs,ch as ys,ci as Ns,cj as Xs,bo as Ct,ck as Lt,ai as St,bs as Ss,f as ks,cl as Dt,bN as wt,cm as rs,cn as Ke,co as ea,X as Cs,aJ as lt,cp as ta,br as ws,cq as Rs,cr as sa,a3 as aa,H as na,cs as Ms,aj as Fs,bu as qt,ct as ia,cu as ls,cv as ra,cw as la,cx as Vt,cy as As,cz as oa,l as ca,cA as da,q as Ps,cB as Ts,bc as ua,h as he,cC as Es,cD as os,cE as cs,cF as ma,cG as ga,cH as ha,cI as fa,cJ as ot,F as ct,s as dt,v as ut,aH as Ls,cK as ba,cL as pa,cM as xa,cN as va,bL as ja,cO as ds,cP as ya,cQ as Na,bP as Sa,al as ka,cR as Wt,cS as Ca,cT as wa,cU as Ra,cV as Ma,cW as Fa,cX as Ds,cY as Aa,cZ as Pa,c_ as Ta,c$ as Ea,d0 as La}from"./index-BjELA24x.js";import{u as ke}from"./vendor-i18n-GF3RlKbq.js";import{f as zt,S as Da}from"./agentSkills-qVb0x_G3.js";import{ExperimentalAgentOnboardingModal as za}from"./ExperimentalAgentOnboardingModal-2SDqP2lc.js";import{B as Ha,A as Ia}from"./AgentPermissionPolicyEditor-D2AQ6swg.js";import"./vendor-reactflow-CnI7NMXG.js";import"./vendor-xterm-BNq00GSj.js";import"./vendor-codemirror-jBKmHyH0.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 Ba=[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M18 17V9",key:"2bz60n"}],["path",{d:"M13 17V5",key:"1frdt8"}],["path",{d:"M8 17v-3",key:"17ska0"}]],kt=Jt("chart-column",Ba);/**
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 $a=[["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"}]],Oa=Jt("square-activity",$a);/**
12
- * @license lucide-react v1.7.0 - ISC
13
- *
14
- * This source code is licensed under the ISC license.
15
- * See the LICENSE file in the root directory of this source tree.
16
- */const _a=[["path",{d:"M16 17h6v-6",key:"t6n2it"}],["path",{d:"m22 17-8.5-8.5-5 5L2 7",key:"x473p"}]],Ua=Jt("trending-down",_a);function us(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 Va(t){return`${Math.round(t*100)}%`}function ms(t,i){const l=Date.now(),o=new Date(t).getTime(),s=l-o;if(s<0){const h=Math.abs(s);return h<6e4?i("agents.time.inAMoment","in a moment"):h<36e5?i("agents.time.inMinutes","in {{count}}m",{count:Math.floor(h/6e4)}):h<864e5?i("agents.time.inHours","in {{count}}h",{count:Math.floor(h/36e5)}):i("agents.time.inDays","in {{count}}d",{count:Math.floor(h/864e5)})}return s<6e4?i("agents.time.justNow","just now"):s<36e5?i("agents.time.minutesAgo","{{count}}m ago",{count:Math.floor(s/6e4)}):s<864e5?i("agents.time.hoursAgo","{{count}}h ago",{count:Math.floor(s/36e5)}):i("agents.time.daysAgo","{{count}}d ago",{count:Math.floor(s/864e5)})}function Wa(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 nt(t){return t instanceof Error&&t.message?t.message:String(t)}function Ja(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 qa(t){switch(t){case"improving":return"trend-improving";case"declining":return"trend-declining";case"stable":return"trend-stable";default:return"trend-insufficient"}}function gs(t,i=5){return e.jsx("span",{className:"rating-stars",children:Array.from({length:i},(l,o)=>e.jsx(ps,{size:14,className:o<t?"star-filled":"star-empty",fill:o<t?"currentColor":"none"},o))})}function Ga({agentId:t,projectId:i,addToast:l}){const{t:o}=ke("app"),[s,h]=a.useState([]),[N,n]=a.useState(null),[g,u]=a.useState(null),[y,c]=a.useState([]),[m,M]=a.useState(!0),[P,L]=a.useState(!0),[w,Q]=a.useState(!1),[J,S]=a.useState(!1),[k,R]=a.useState(null),[C,D]=a.useState(0),[T,V]=a.useState(""),[Y,I]=a.useState(""),Z=a.useCallback(async()=>{try{const[d,z]=await Promise.all([_s(t,20,i),Us(t,void 0,i)]);h(d),n(z)}catch(d){l(o("agents.reflections.loadError","Failed to load reflections: {{error}}",{error:nt(d)}),"error")}finally{M(!1)}},[t,i,l]),F=a.useCallback(async()=>{try{const[d,z]=await Promise.all([Vs(t,i),Ws(t,{limit:50},i)]);u(d),c(z)}catch(d){l(o("agents.ratings.loadError","Failed to load ratings: {{error}}",{error:nt(d)}),"error")}finally{L(!1)}},[t,i,l]);a.useEffect(()=>{Z(),F()},[Z,F]);const ee=async()=>{Q(!0);try{if(!await qs(t,i)){l(o("agents.reflections.insufficientHistory","Not enough history to generate a reflection yet"),"error");return}l(o("agents.reflections.generateSuccess","Reflection generated successfully"),"success"),M(!0),await Z()}catch(d){const z=nt(d),_=z.toLowerCase();_.includes("agent not found")||_.includes("not found")?l(o("agents.reflections.agentNotFound","This agent is no longer available. It may have been deleted."),"error"):_.includes("insufficient history")?l(o("agents.reflections.insufficientHistory","Not enough history to generate a reflection yet"),"error"):l(o("agents.reflections.generateError","Failed to generate reflection: {{error}}",{error:z}),"error")}finally{Q(!1)}},A=async d=>{if(d.preventDefault(),C!==0){S(!0);try{await Gs(t,{score:C,category:T||void 0,comment:Y||void 0,raterType:"user"},i),D(0),V(""),I(""),l(o("agents.ratings.addSuccess","Rating added"),"success"),await F()}catch(z){l(o("agents.ratings.addError","Failed to add rating: {{error}}",{error:nt(z)}),"error")}finally{S(!1)}}},W=async d=>{try{await Ks(t,d,i),l(o("agents.ratings.deleteSuccess","Rating deleted"),"success"),await F()}catch(z){l(o("agents.ratings.deleteError","Failed to delete rating: {{error}}",{error:nt(z)}),"error")}},p=d=>{R(z=>z===d?null:d)};if(m&&P)return e.jsx("div",{className:"reflections-tab",children:e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(q,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:o("agents.reflections.loadingEvaluation","Loading evaluation...")})]})});const j=N&&N.totalTasksCompleted===0&&N.totalTasksFailed===0&&N.recentReflectionCount===0;return e.jsxs("div",{className:"reflections-tab",children:[e.jsxs("div",{className:"reflections-header",children:[e.jsxs("h3",{children:[e.jsx(kt,{size:16}),o("agents.reflections.sectionTitle","Performance, Reflections & Ratings")]}),e.jsx("button",{className:"btn btn-secondary",onClick:ee,disabled:w,title:o("agents.reflections.reflectNowTitle","Generate a manual reflection"),children:w?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:14,className:"animate-spin"}),o("agents.reflections.reflecting","Reflecting...")]}):e.jsxs(e.Fragment,{children:[e.jsx(Mt,{size:14}),o("agents.reflections.reflectNow","Reflect Now")]})})]}),N&&!j&&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(is,{size:16,style:{color:"var(--color-success)"}}),N.totalTasksCompleted]}),e.jsx("div",{className:"stat-label",children:o("agents.performance.tasksCompleted","Tasks Completed")})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(Ua,{size:16,style:{color:"var(--color-error)"}}),N.totalTasksFailed]}),e.jsx("div",{className:"stat-label",children:o("agents.performance.tasksFailed","Tasks Failed")})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(Js,{size:16,style:{color:"var(--in-progress)"}}),us(N.avgDurationMs)]}),e.jsx("div",{className:"stat-label",children:o("agents.performance.avgDuration","Avg Duration")})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(kt,{size:16,style:{color:N.successRate>=.8?"var(--color-success)":N.successRate>=.5?"var(--color-warning)":"var(--color-error)"}}),Va(N.successRate)]}),e.jsx("div",{className:"stat-label",children:o("agents.performance.successRate","Success Rate")})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(Et,{size:16,style:{color:"var(--color-info)"}}),N.recentReflectionCount]}),e.jsx("div",{className:"stat-label",children:o("agents.performance.reflections","Reflections")})]})]}),j&&e.jsxs("div",{className:"reflections-no-data",children:[e.jsx(kt,{size:24,opacity:.3}),e.jsx("p",{children:o("agents.performance.noData","No performance data yet")})]}),e.jsxs("div",{className:"reflections-ratings-section",children:[e.jsx("h4",{children:o("agents.ratings.title","User Ratings")}),P?e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(q,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:o("agents.ratings.loading","Loading ratings...")})]}):e.jsxs(e.Fragment,{children:[g&&e.jsxs("div",{className:"rating-summary-card",children:[e.jsxs("div",{className:"rating-score-display",children:[e.jsx("span",{className:"rating-average",children:g.averageScore.toFixed(1)}),gs(Math.round(g.averageScore))]}),e.jsxs("div",{className:"rating-stats",children:[e.jsx("span",{className:"rating-count",children:o("agents.ratings.count","{{count}} ratings",{count:g.totalRatings})}),e.jsx("span",{className:`rating-trend-badge ${qa(g.trend)}`,children:Ja(g.trend,o)})]})]}),g&&Object.keys(g.categoryAverages).length>0&&e.jsxs("div",{className:"category-breakdown",children:[e.jsx("h4",{children:o("agents.ratings.categoryAverages","Category Averages")}),Object.entries(g.categoryAverages).map(([d,z])=>e.jsxs("div",{className:"category-item",children:[e.jsx("span",{className:"category-name",children:d}),e.jsx("span",{className:"category-score",children:z.toFixed(1)})]},d))]}),e.jsxs("form",{className:"add-rating-form",onSubmit:A,children:[e.jsx("h4",{children:o("agents.ratings.addRating","Add Rating")}),e.jsx("div",{className:"star-selector",children:[1,2,3,4,5].map(d=>e.jsx("button",{type:"button",className:"star-btn touch-target",onClick:()=>D(d),title:o("agents.ratings.starCount","{{count}} star",{count:d,defaultValue_one:"{{count}} star",defaultValue_other:"{{count}} stars"}),children:e.jsx(ps,{size:24,fill:d<=C?"currentColor":"none",className:d<=C?"star-filled":"star-empty"})},d))}),e.jsxs("select",{value:T,onChange:d=>V(d.target.value),className:"select add-rating-category-select",children:[e.jsx("option",{value:"",children:o("agents.ratings.categorySelect","Select category...")}),e.jsx("option",{value:"quality",children:o("agents.ratings.categoryQuality","Quality")}),e.jsx("option",{value:"speed",children:o("agents.ratings.categorySpeed","Speed")}),e.jsx("option",{value:"communication",children:o("agents.ratings.categoryCommunication","Communication")}),e.jsx("option",{value:"reliability",children:o("agents.ratings.categoryReliability","Reliability")}),e.jsx("option",{value:"other",children:o("agents.ratings.categoryOther","Other")})]}),e.jsx("textarea",{value:Y,onChange:d=>I(d.target.value),placeholder:o("agents.ratings.commentPlaceholder","Optional comment..."),className:"input add-rating-comment-input",rows:3}),e.jsx("button",{type:"submit",className:"btn btn-task-create",disabled:C===0||J,children:J?o("agents.ratings.submitting","Submitting..."):o("agents.ratings.submitRating","Submit Rating")})]}),e.jsxs("div",{className:"rating-history",children:[e.jsx("h4",{children:o("agents.ratings.historyTitle","Rating History")}),y.length===0?e.jsx("p",{className:"no-ratings",children:o("agents.ratings.noRatings","No ratings yet")}):y.map(d=>e.jsxs("div",{className:"rating-history-item",children:[e.jsxs("div",{className:"rating-item-header",children:[gs(d.score),d.category&&e.jsx("span",{className:"rating-category-badge",children:d.category}),e.jsx("span",{className:"rating-time",children:ms(d.createdAt,o)}),e.jsx("button",{type:"button",className:"rating-delete-btn touch-target",onClick:()=>void W(d.id),title:o("agents.ratings.deleteRating","Delete rating"),children:e.jsx(rt,{size:14})})]}),d.comment&&e.jsx("p",{className:"rating-comment",children:d.comment})]},d.id))]})]})]}),e.jsxs("div",{className:"reflections-list",children:[e.jsx("h4",{children:o("agents.reflections.historyTitle","Reflection History")}),m?e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(q,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:o("agents.reflections.loading","Loading reflections...")})]}):s.length===0?e.jsxs("div",{className:"reflection-empty",children:[e.jsx(Et,{size:32,opacity:.3}),e.jsx("p",{children:o("agents.reflections.noReflections","No reflections yet")}),e.jsx("p",{className:"text-secondary",children:o("agents.reflections.getStarted","Trigger a reflection to get started")})]}):e.jsx("div",{className:"reflection-cards",children:s.map(d=>{const z=k===d.id;return e.jsxs("div",{className:`reflection-card ${z?"reflection-card--expanded":""}`,onClick:()=>p(d.id),role:"button",tabIndex:0,onKeyDown:_=>_.key==="Enter"&&p(d.id),children:[e.jsxs("div",{className:"reflection-card-header",children:[e.jsx("span",{className:`reflection-trigger-badge reflection-trigger-${d.trigger}`,children:Wa(d.trigger,o)}),e.jsx("span",{className:"reflection-timestamp",children:ms(d.timestamp,o)}),e.jsx("span",{className:"reflection-chevron",children:z?e.jsx(xs,{size:16}):e.jsx(vs,{size:16})})]}),e.jsx("div",{className:"reflection-summary",children:d.summary}),z&&e.jsxs("div",{className:"reflection-details",children:[d.insights.length>0&&e.jsxs("div",{className:"reflection-insights",children:[e.jsxs("h5",{children:[e.jsx(Et,{size:14})," ",o("agents.reflections.insights","Insights")]}),e.jsx("ul",{children:d.insights.map((_,Ce)=>e.jsx("li",{children:_},Ce))})]}),d.suggestedImprovements.length>0&&e.jsxs("div",{className:"reflection-suggestions",children:[e.jsxs("h5",{children:[e.jsx(is,{size:14})," ",o("agents.reflections.suggestedImprovements","Suggested Improvements")]}),e.jsx("ul",{children:d.suggestedImprovements.map((_,Ce)=>e.jsx("li",{children:_},Ce))})]}),d.metrics&&e.jsxs("div",{className:"reflection-metrics",children:[e.jsx("h5",{children:o("agents.reflections.metrics","Metrics")}),e.jsxs("div",{className:"metrics-grid",children:[d.metrics.tasksCompleted!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:o("agents.reflections.metricTasks","Tasks:")}),e.jsx("span",{className:"metric-value",children:d.metrics.tasksCompleted})]}),d.metrics.tasksFailed!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:o("agents.reflections.metricFailed","Failed:")}),e.jsx("span",{className:"metric-value",children:d.metrics.tasksFailed})]}),d.metrics.avgDurationMs!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:o("agents.reflections.metricAvgDuration","Avg Duration:")}),e.jsx("span",{className:"metric-value",children:us(d.metrics.avgDurationMs)})]}),d.metrics.errorCount!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:o("agents.reflections.metricErrors","Errors:")}),e.jsx("span",{className:"metric-value",children:d.metrics.errorCount})]})]})]})]})]},d.id)})})]})]})}function oe(...t){return t.filter(Boolean).join(" ")}function Ye(t,i){const l=Date.now(),o=new Date(t).getTime(),s=l-o,h=i??((n,g,u)=>u?g.replace(/\{\{(\w+)\}\}/g,(y,c)=>String(u[c]??"")):g);if(s<0){const n=Math.abs(s);if(n<6e4)return h("time.inAMoment","in a moment");if(n<36e5){const u=Math.floor(n/6e4);return h("time.inMinutes","in {{n}}m",{n:u})}if(n<864e5){const u=Math.floor(n/36e5);return h("time.inHours","in {{n}}h",{n:u})}const g=Math.floor(n/864e5);return h("time.inDays","in {{n}}d",{n:g})}if(s<6e4)return h("time.justNow","just now");if(s<36e5){const n=Math.floor(s/6e4);return h("time.minutesAgo","{{n}}m ago",{n})}if(s<864e5){const n=Math.floor(s/36e5);return h("time.hoursAgo","{{n}}h ago",{n})}const N=Math.floor(s/864e5);return h("time.daysAgo","{{n}}d ago",{n:N})}const Ka="⚠️",Ya=[{id:"dashboard",label:"Dashboard",icon:Oa},{id:"logs",label:"Logs",icon:lt},{id:"mail",label:"Mail",icon:ta},{id:"runs",label:"Runs",icon:wt},{id:"tasks",label:"Tasks",icon:ws},{id:"employees",label:"Employees",icon:Rs},{id:"soul",label:"Soul",icon:sa},{id:"instructions",label:"Instructions",icon:Ha},{id:"memory",label:"Agent Memory",icon:lt},{id:"reflections",label:"Evaluation",icon:kt},{id:"config",label:"Settings",icon:aa}],Gt={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)"}},Rt={completed:{icon:he,color:"var(--color-success)"},failed:{icon:ua,color:"var(--color-error)"},active:{icon:q,color:"var(--in-progress)"},terminated:{icon:Ke,color:"var(--text-muted)"}},Za=Ts(Wt),Qa=700;function Xa(t,i){return t.some(l=>l.path===i)?i:t.find(l=>l.layer==="long-term")?.path??t[0]?.path??""}function Cn({agentId:t,projectId:i,onClose:l,addToast:o,onChildClick:s,inline:h=!1,showInlineBackButton:N=!1,initialTab:n,initialRunId:g,preferActiveRun:u=!1,onMutationSuccess:y}){const{t:c}=ke("app"),[m,M]=a.useState(null),{confirm:P}=js(),[L,w]=a.useState([]),[Q,J]=a.useState(!0),[S,k]=a.useState(n??"dashboard"),[R,C]=a.useState(!1),[D,T]=a.useState(!1),[V,Y]=a.useState(!1),[I,Z]=a.useState(!1),[F,ee]=a.useState(!1),[A,W]=a.useState(!1),[p,j]=a.useState(0),[d,z]=a.useState(0),[_,Ce]=a.useState(0),[ue,je]=a.useState(null),[we,ye]=a.useState(null),[pe,O]=a.useState(!1),[se,x]=a.useState(null),v=a.useRef(null),ie=a.useRef(null),ae=a.useRef(!1);Ys(v,!h,"fusion:agent-detail-modal-size");const We=a.useRef(l),ze=a.useRef(o),Fe=a.useRef(null),ce=a.useRef(!1),Pe=a.useRef(null),ne=a.useRef(0),mt=a.useRef(t),Te=a.useRef(i);We.current=l,ze.current=o,Fe.current=m;const Ne=a.useCallback(async()=>{Fe.current===null&&J(!0);try{const H=await Zs(t,i);M(H)}catch(H){ze.current(`Failed to load agent: ${U(H)}`,"error"),We.current()}finally{J(!1)}},[t,i]),gt=a.useCallback(async()=>{const b=ne.current,H=t,B=i,$=()=>ne.current!==b||t!==H||i!==B;try{if(m?.taskId){je(null),Pe.current=null;const Le=await Qs(m.taskId,B,{limit:100});if($())return;w(Le.entries);return}const re=await ys(H,1,B);if($())return;const be=re[0]??null;if(je(be),!be){Pe.current=null,w([]);return}if(Pe.current===be.id)return;const ge=await Ns(H,be.id,B);if($())return;w(ge),Pe.current=be.id}catch(re){if($())return;console.error("Failed to load agent logs:",re)}},[m?.taskId,t,i]),Ze=a.useCallback(async()=>{O(!0),x(null);try{const b=await Xs(t,i);ye(b)}catch(b){x(U(b)),ye(null)}finally{O(!1)}},[t,i]),Ft=a.useCallback(b=>{ce.current=b},[]),Qe=a.useCallback(async(b=!1)=>{await y?.({agentId:t,deleted:b})},[t,y]),Be=a.useCallback(async()=>{await Ne(),await Qe(!1)},[Ne,Qe]);a.useEffect(()=>{Ne()},[Ne]),a.useEffect(()=>{const b=setInterval(()=>{Ne()},3e4);return()=>{clearInterval(b)}},[Ne]),a.useEffect(()=>{m&&S==="logs"&&gt()},[m,S,gt]),a.useEffect(()=>{S!=="logs"&&(Pe.current=null)},[S]),a.useEffect(()=>{m&&S==="mail"&&Ze()},[m,S,Ze]),a.useEffect(()=>{if(!I)return;const b=B=>{ie.current?.contains(B.target)||Z(!1)},H=B=>{B.key==="Escape"&&Z(!1)};return document.addEventListener("mousedown",b),document.addEventListener("keydown",H),()=>{document.removeEventListener("mousedown",b),document.removeEventListener("keydown",H)}},[I]),a.useEffect(()=>{if(!I)return;let b=!1;return W(!0),Ct(void 0,i).then(H=>{if(b)return;const B=H.filter($=>!Lt($));j(B.filter($=>$.state==="active"||$.state==="running").length),z(B.filter($=>$.state==="paused").length)}).catch(()=>{b||(j(0),z(0))}).finally(()=>{b||W(!1)}),()=>{b=!0}},[I,i]),a.useEffect(()=>{if(S!=="logs"||m?.taskId||!ue||ue.status!=="active")return;const b=ne.current,H=t,B=ue.id,$=i?`?projectId=${encodeURIComponent(i)}`:"",re=St(`/api/agents/${encodeURIComponent(H)}/runs/${encodeURIComponent(B)}/logs/stream${$}`,{events:{"agent:log":be=>{if(ne.current===b)try{const ge=JSON.parse(be.data);w(Le=>[...Le,ge])}catch{}}},onOpen:()=>{ne.current===b&&C(!0)},onError:()=>{ne.current===b&&C(!1)}});return()=>{re(),ne.current===b&&C(!1)}},[S,m?.taskId,t,i,ue]),a.useEffect(()=>{(mt.current!==t||Te.current!==i)&&(mt.current=t,Te.current=i,ne.current++,w([]),C(!1),je(null),ye(null),x(null),Pe.current=null,ce.current=!1)},[t,i]),a.useEffect(()=>{const b=i?`?projectId=${encodeURIComponent(i)}`:"",H=ne.current,B=$=>{if(ne.current===H)try{const re=JSON.parse($.data);if(!re||typeof re!="object"||re.agentId!==t)return;Ne()}catch{}};return St(`/api/events${b}`,{events:{"agent:updated":$=>{if(ne.current===H)try{const re=JSON.parse($.data);if(!re||typeof re!="object"||re.id!==t||ce.current)return;Ne()}catch{}},"approval:requested":B,"approval:updated":B,"approval:decided":B}})},[t,i,Ne]),a.useEffect(()=>{if(S!=="logs"||!m?.taskId){C(!1);return}const b=ne.current,H=m.taskId,B=i?`?projectId=${encodeURIComponent(i)}`:"",$=St(`/api/tasks/${encodeURIComponent(H)}/logs/stream${B}`,{events:{"agent:log":re=>{if(ne.current===b)try{const be=JSON.parse(re.data);w(ge=>[...ge,be])}catch{}}},onOpen:()=>{ne.current===b&&C(!0)},onError:()=>{ne.current===b&&C(!1)}});return()=>{$(),ne.current===b&&C(!1)}},[m?.taskId,S,i]);const Ee=async b=>{if(D||!Fe.current)return;const H=Fe.current.state;if(H!==b){T(!0),M(B=>B&&{...B,state:b});try{await ls(t,b,i),o(c("agents.stateUpdated","Agent state updated to {{newState}}",{newState:b}),"success"),await Be()}catch(B){M($=>$&&{...$,state:H}),o(c("agents.stateUpdateFailed","Failed to update state: {{error}}",{error:U(B)}),"error")}finally{T(!1)}}},ht=async b=>{if(!F){Z(!1),ee(!0);try{const B=(await Ct(void 0,i)).filter(me=>!Lt(me)),$=B.filter(me=>b==="paused"?me.state==="active"||me.state==="running":me.state==="paused"),re=B.length-$.length;if($.length===0){o(c("agents.bulkNoEligible","No agents eligible to {{action}}",{action:b==="paused"?c("agents.pause","pause"):c("agents.resume","resume")}),"error");return}if(!await P({title:b==="paused"?c("agents.pauseAllTitle","Pause All Agents"):c("agents.resumeAllTitle","Resume All Agents"),message:c("agents.bulkConfirmMessage","{{action}} {{count}} agent(s) in this project?",{action:b==="paused"?c("agents.pauseAction","Pause"):c("agents.resumeAction","Resume"),count:$.length}),danger:b==="paused"}))return;const ge=await Promise.allSettled($.map(me=>ls(me.id,b,i))),Le=ge.map((me,Se)=>({result:me,agent:$[Se]})).filter(me=>me.result.status==="rejected"),Oe=ge.length-Le.length,et=Le.length,At=b==="paused"?c("agents.pausedPast","Paused"):c("agents.resumedPast","Resumed"),Pt=Oe===1?c("agents.agentSingular","agent"):c("agents.agentPlural","agents"),pt=c(Oe===1?"agents.bulkResult_one":"agents.bulkResult_other","{{action}} {{successCount}} {{agentWord}}; skipped {{skippedCount}}",{action:At,successCount:Oe,agentWord:Pt,skippedCount:re});if(et>0){const me=Le.slice(0,3).map(({agent:Se,result:tt})=>`${Se.name||Se.id}: ${U(tt.reason)}`).join("; ");o(c("agents.bulkResultWithFailures","{{summary}}; failed {{failureCount}}{{detail}}",{summary:pt,failureCount:et,detail:me?` (${me})`:""}),"error")}else o(pt,"success");await Be()}catch(H){o(c("agents.bulkActionFailed","Failed to {{action}} agents: {{error}}",{action:b==="paused"?c("agents.pause","pause"):c("agents.resume","resume"),error:U(H)}),"error")}finally{ee(!1)}}},Xe=async()=>{if(!V){Y(!0);try{await ra(t,i,{source:"on_demand",triggerDetail:"Triggered from dashboard"}),o(c("agents.heartbeatStarted","Heartbeat run started for {{name}}",{name:m?.name??t}),"success"),Ce(b=>b+1)}catch(b){o(c("agents.heartbeatStartFailed","Failed to start heartbeat run: {{error}}",{error:U(b)}),"error")}finally{Y(!1)}}},Ue=async()=>{if(!(!m||!await P({title:c("agents.deleteTitle","Delete Agent"),message:c("agents.deleteConfirm",'Delete agent "{{name}}"? This cannot be undone.',{name:m.name}),danger:!0})))try{await la(t,i),o(c("agents.deleted",'Agent "{{name}}" deleted',{name:m.name}),"success"),await Qe(!0),l()}catch(H){o(c("agents.deleteFailed","Failed to delete agent: {{error}}",{error:U(H)}),"error")}},ft=()=>m?ia(m):{label:"Unknown",icon:e.jsx(qt,{size:14}),color:"var(--text-muted)",stateDerived:!1},bt=()=>{m&&(navigator.clipboard.writeText(m.id),o(c("agents.idCopied","Agent ID copied to clipboard"),"success"))};if(Q)return h?e.jsx("div",{className:"agent-detail-inline-loading",role:"region","aria-label":c("agents.detailLoadingLabel","Agent detail loading"),children:e.jsxs("div",{className:"agent-detail-loading",children:[e.jsx(q,{className:"animate-spin",size:24}),e.jsx("span",{children:c("agents.loading","Loading agent...")})]})}):e.jsx("div",{className:"agent-detail-overlay",onMouseDown:b=>{b.target===b.currentTarget&&(ae.current=!0)},onMouseUp:b=>{ae.current&&b.target===b.currentTarget&&l(),ae.current=!1},role:"dialog","aria-modal":"true",children:e.jsx("div",{className:"agent-detail-modal",ref:v,children:e.jsxs("div",{className:"agent-detail-loading",children:[e.jsx(q,{className:"animate-spin",size:24}),e.jsx("span",{children:c("agents.loading","Loading agent...")})]})})});if(!m)return null;const Je=Gt[m.state],Re=ft(),He=h?"agent-detail-inline":"agent-detail-modal",fe=A||p===0,$e=A||d===0;return e.jsx("div",{className:h?"agent-detail-inline-shell":"agent-detail-overlay",onClick:b=>!h&&b.target===b.currentTarget&&l(),role:h?"region":"dialog","aria-label":h?"Agent detail":void 0,"aria-modal":h?void 0:"true",children:e.jsxs("div",{className:He,ref:v,children:[e.jsxs("div",{className:"agent-detail-header",children:[e.jsxs("div",{className:"agent-detail-identity",children:[h&&N?e.jsxs("button",{type:"button",className:"btn agent-detail-inline-back",onClick:l,"aria-label":c("agents.backToAgents","Back to agents"),children:[e.jsx(Ss,{size:16}),c("agents.agentsLabel","Agents")]}):null,e.jsx("div",{className:"agent-detail-icon",children:e.jsx(ks,{agent:m,size:36})}),e.jsxs("div",{className:"agent-detail-info",children:[e.jsx("h2",{children:m.name}),e.jsxs("div",{className:"agent-detail-badges",children:[e.jsx("span",{className:"badge",style:{background:Je.bg,color:Je.text,border:`1px solid ${Je.border}`},children:m.state}),e.jsxs("span",{className:"badge",style:{color:Re.color},title:Re.reason??Re.label,children:[Re.icon,!Re.stateDerived&&Re.label]})]})]})]}),e.jsxs("div",{className:"agent-detail-header-actions",children:[e.jsxs("div",{className:"agent-detail-controls",children:[m.state==="idle"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void Ee("active"),disabled:D,children:[e.jsx(Dt,{size:14}),c("agents.start","Start")]}),e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void Xe(),"aria-label":c("agents.runNowFor","Run now for {{name}}",{name:m.name}),disabled:V||D,children:[e.jsx(wt,{size:14}),c("agents.runNow","Run Now")]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:Ue,children:[e.jsx(rt,{size:14}),c("agents.delete","Delete")]})]}),m.state==="active"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--compact agent-detail-mobile-icon-control",onClick:()=>void Ee("paused"),disabled:D,"aria-label":c("agents.pause","Pause"),children:[e.jsx(rs,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:c("agents.pause","Pause")})]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:()=>void Ee("paused"),disabled:D,"aria-label":c("agents.stop","Stop"),children:[e.jsx(Ke,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:c("agents.stop","Stop")})]}),e.jsxs("button",{className:"btn btn-task-create btn--compact agent-detail-mobile-icon-control",onClick:()=>void Xe(),"aria-label":c("agents.runNowFor","Run now for {{name}}",{name:m.name}),disabled:V||D,children:[e.jsx(wt,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:c("agents.runNow","Run Now")})]})]}),m.state==="paused"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact agent-detail-mobile-icon-control",onClick:()=>void Ee("active"),disabled:D,"aria-label":c("agents.resume","Resume"),children:[e.jsx(Dt,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:c("agents.resume","Resume")})]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:Ue,children:[e.jsx(rt,{size:14}),c("agents.delete","Delete")]})]}),m.state==="running"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--compact agent-detail-mobile-icon-control",onClick:()=>void Ee("paused"),disabled:D,"aria-label":c("agents.pause","Pause"),children:[e.jsx(rs,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:c("agents.pause","Pause")})]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:()=>void Ee("paused"),disabled:D,"aria-label":c("agents.stop","Stop"),children:[e.jsx(Ke,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:c("agents.stop","Stop")})]})]}),m.state==="error"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void Ee("active"),disabled:D,children:[e.jsx(Dt,{size:14}),c("agents.retry","Retry")]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:()=>void Ee("paused"),disabled:D,"aria-label":c("agents.stop","Stop"),children:[e.jsx(Ke,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:c("agents.stop","Stop")})]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:Ue,"aria-label":c("agents.delete","Delete"),children:[e.jsx(rt,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:c("agents.delete","Delete")})]})]})]}),e.jsxs("div",{className:"agent-detail-utility-actions",children:[e.jsxs("div",{className:"agent-detail-bulk-menu",ref:ie,children:[e.jsx("button",{type:"button",className:"btn-icon",onClick:()=>Z(b=>!b),"aria-haspopup":"menu","aria-expanded":I,"aria-label":c("agents.bulkActions","Bulk agent actions"),title:c("agents.bulkActions","Bulk agent actions"),disabled:D||F,children:e.jsx(ea,{size:16})}),I&&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 ht("paused"),disabled:fe||F,children:[c("agents.pauseAll","Pause All Agents"),e.jsx("span",{className:"agent-detail-bulk-menu-item-hint",children:A?c("agents.loadingEligible","Loading eligible agents..."):fe?c("agents.noActiveEligible","No active agents eligible"):c(p===1?"agents.pauseCountHint_one":"agents.pauseCountHint_other",p===1?"Pause {{count}} active/running agent":"Pause {{count}} active/running agents",{count:p})})]}),e.jsxs("button",{type:"button",role:"menuitem",className:"agent-detail-bulk-menu-item",onClick:()=>void ht("active"),disabled:$e||F,children:[c("agents.resumeAll","Resume All Agents"),e.jsx("span",{className:"agent-detail-bulk-menu-item-hint",children:A?c("agents.loadingEligible","Loading eligible agents..."):$e?c("agents.noPausedEligible","No paused agents eligible"):c(d===1?"agents.resumeCountHint_one":"agents.resumeCountHint_other",d===1?"Resume {{count}} paused agent":"Resume {{count}} paused agents",{count:d})})]})]})]}),e.jsx("button",{className:"btn-icon",onClick:()=>void Ne(),title:c("common.refresh","Refresh"),"aria-label":c("common.refresh","Refresh"),children:e.jsx(Mt,{size:16})}),!h&&e.jsx("button",{className:"btn-icon",onClick:l,"aria-label":c("common.close","Close"),title:c("common.close","Close"),children:e.jsx(Cs,{size:20})})]})]})]}),e.jsx("div",{className:"agent-detail-tabs",children:Ya.map(b=>{const H={dashboard:c("agents.tabDashboard","Dashboard"),logs:c("agents.tabLogs","Logs"),mail:c("agents.tabMail","Mail"),runs:c("agents.tabRuns","Runs"),tasks:c("agents.tabTasks","Tasks"),employees:c("agents.tabEmployees","Employees"),soul:c("agents.tabSoul","Soul"),instructions:c("agents.tabInstructions","Instructions"),memory:c("agents.tabMemory","Agent Memory"),reflections:c("agents.tabReflections","Evaluation"),config:c("agents.tabConfig","Settings")};return e.jsxs("button",{className:oe("agent-detail-tab",S===b.id&&"active"),onClick:()=>k(b.id),children:[e.jsx(b.icon,{size:16}),H[b.id]]},b.id)})}),e.jsxs("div",{className:"agent-detail-content",children:[S==="dashboard"&&e.jsx(en,{agent:m,health:Re,onChildClick:s,projectId:i}),S==="logs"&&e.jsx(tn,{logs:L,isStreaming:R,hasTask:!!m.taskId||L.length>0||ue!==null,fallbackLabel:!m.taskId&&ue?c("agents.latestRunLabel","Latest run · {{id}}",{id:ue.id.slice(0,8)}):null}),S==="mail"&&e.jsx(an,{agent:m,mailbox:we,isLoading:pe,error:se,projectId:i,addToast:o,onRefresh:()=>void Ze()}),S==="runs"&&e.jsx(nn,{addToast:o,agentId:m.id,projectId:i,agentState:m.state,agentName:m.name,initialRunId:g,preferActiveRun:u,runNowRefreshToken:_,isEphemeral:Lt(m)}),S==="tasks"&&e.jsx(on,{agentId:m.id,projectId:i,addToast:o}),S==="employees"&&e.jsx(fn,{agentId:m.id,projectId:i,onChildClick:s}),S==="soul"&&e.jsx(dn,{agent:m,projectId:i,addToast:o,onSaved:Be}),S==="instructions"&&e.jsx(mn,{agent:m,projectId:i,addToast:o,onSaved:Be}),S==="memory"&&e.jsx(un,{agent:m,projectId:i,addToast:o,onSaved:Be}),S==="reflections"&&e.jsx(Ga,{agentId:m.id,projectId:i,addToast:o}),S==="config"&&e.jsx(hn,{agent:m,projectId:i,addToast:o,onSaved:Be,onHasChangesChange:Ft,onDelete:Ue,onAgentDraftApplied:b=>{M(H=>H&&{...H,...b})}},m.id)]}),!h&&e.jsxs("div",{className:"agent-detail-footer",children:[e.jsx("button",{className:"btn-icon",onClick:bt,title:c("agents.copyId","Copy Agent ID"),children:e.jsx(na,{})}),e.jsx("span",{className:"agent-detail-id",onClick:bt,children:m.id}),m.taskId&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"divider",children:"|"}),e.jsx("span",{className:"text-muted",children:c("agents.workingOn","Working on:")}),e.jsxs("a",{href:`/tasks/${m.taskId}`,className:"link",children:[e.jsx(Ms,{taskId:m.taskId,taskColumn:m.taskColumn}),e.jsx(Fs,{size:12})]})]})]})]})})}function en({agent:t,health:i,onChildClick:l,projectId:o}){const{t:s}=ke("app"),h=Gt[t.state],[N,n]=a.useState([]),[g,u]=a.useState(!0),[y,c]=a.useState(null),[m,M]=a.useState([]),[P,L]=a.useState(null),[w,Q]=a.useState(null),[J,S]=a.useState(!1),[k,R]=a.useState(null),C=typeof t.runtimeConfig?.runtimeHint=="string"?t.runtimeConfig.runtimeHint:"",D=(()=>{const p=t.runtimeConfig??{};if(C){const j=m.find(d=>d.runtimeId===C);return j?j.name:C}if(p.modelProvider&&p.modelId)return`${p.modelProvider}/${p.modelId}`;if(typeof p.model=="string"&&p.model.includes("/")){const j=p.model.indexOf("/");return p.model.slice(j+1)}return null})();a.useEffect(()=>{Vt(t.id,o).then(c).catch(()=>c(null))},[t.id,o]),a.useEffect(()=>{As(o).then(M).catch(()=>M([]))},[o]),a.useEffect(()=>{let p=!1;return u(!0),oa(t.id,o).then(j=>{if(p)return;const d=j.length>0&&j[0]?.id===t.id?[...j].reverse():j;n(d)}).catch(()=>{p||n([])}).finally(()=>{p||u(!1)}),()=>{p=!0}},[t.id,o]);const T=a.useMemo(()=>{const p=t.completedRuns||[],j=new Date;j.setHours(0,0,0,0);const d=p.filter(_=>new Date(_.startedAt)>=j),z=p.filter(_=>_.status==="completed");return{totalRuns:p.length,todayRuns:d.length,successfulRuns:z.length,successRate:p.length>0?Math.round(z.length/p.length*100):0}},[t]),V=(t.completedRuns||[]).slice(0,5),Y=Array.isArray(t.metadata?.skills)?t.metadata.skills:[],I=P?zt(P):null,Z=a.useCallback(async p=>{S(!0),R(null),Q(null);try{const j=await ca(p,o);Q(j)}catch(j){R(U(j))}finally{S(!1)}},[o]),F=a.useCallback(p=>{if(P===p){L(null),Q(null),R(null),S(!1);return}L(p),Z(p)},[Z,P]),ee=t.state==="active"||t.state==="running",A=da(t.runtimeConfig?.heartbeatIntervalMs),W=ee&&t.lastHeartbeatAt?new Date(new Date(t.lastHeartbeatAt).getTime()+A).toISOString():null;return e.jsxs("div",{className:"dashboard-tab dashboard-summary-layout",children:[y?.isOverBudget&&e.jsxs("div",{className:"budget-warning-banner",role:"alert",children:[e.jsx("span",{children:Ka}),e.jsxs("span",{children:[e.jsx("strong",{children:s("agents.budgetExhaustedTitle","Budget Exhausted:")})," ",s("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(qt,{}),e.jsx("h3",{children:s("agents.overview","Overview")}),e.jsx("strong",{children:t.name}),e.jsx("span",{className:"inline-badge",style:{background:h.bg,color:h.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:s("agents.pendingApprovals","Pending approvals"),children:[e.jsx("span",{className:"status-dot status-dot--pending"}),s("agents.pendingApprovalsCount","{{count}} pending approvals",{count:t.pendingApprovalCount})]}):null,e.jsx("span",{children:s("agents.roleLabel","Role: {{role}}",{role:t.role})}),e.jsxs("span",{children:[e.jsx("span",{className:"dashboard-summary-label",children:C?s("agents.runtime","Runtime"):s("agents.model","Model")}),e.jsxs("span",{children:[" ",D??s("agents.auto","Auto")]})]}),Y.length>0?e.jsxs("span",{className:"dashboard-summary-skills",children:[e.jsx("span",{className:"dashboard-summary-label",children:s("agents.skills","Skills")}),e.jsx("span",{className:"dashboard-summary-skill-badges",role:"list","aria-label":s("agents.assignedSkills","Assigned skills"),children:Y.map(p=>{const j=P===p;return e.jsx("button",{type:"button",className:oe("badge","badge-skill","dashboard-summary-skill-badge","dashboard-summary-skill-badge-btn",j&&"dashboard-summary-skill-badge--selected"),title:p,onClick:()=>F(p),"aria-expanded":j,"aria-label":s("agents.viewSkillDetails","View details for {{skill}}",{skill:zt(p)}),children:zt(p)},p)})})]}):e.jsx("span",{children:s("agents.skillsNone","Skills: —")})]}),P?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:I}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>F(P),children:[e.jsx(Cs,{size:14}),s("common.close","Close")]})]}),J?e.jsxs("div",{className:"dashboard-summary-skill-detail-loading",role:"status","aria-live":"polite",children:[e.jsx(q,{size:14,className:"animate-spin"}),s("agents.loadingSkillContent","Loading skill content...")]}):k?e.jsxs("div",{className:"dashboard-summary-skill-detail-error",role:"alert",children:[e.jsx(Ps,{size:14}),e.jsx("span",{children:k}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void Z(P),children:s("common.retry","Retry")})]}):w?e.jsx("pre",{className:"dashboard-summary-skill-detail-content",children:w.skillMd||s("agents.noSkillMd","(No SKILL.md found)")}):e.jsx("div",{className:"dashboard-summary-skill-detail-empty",children:s("agents.noSkillContent","No skill content available")})]}):null]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:s("agents.heartbeatAndHealth","Heartbeat & Health")}),e.jsxs("div",{className:"dashboard-summary-grid",children:[e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:s("agents.lastHeartbeat","Last heartbeat")}),e.jsx("p",{children:t.lastHeartbeatAt?Ye(t.lastHeartbeatAt,s):s("agents.never","Never")})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:s("agents.nextExpected","Next expected")}),e.jsx("p",{children:W?Ye(W,s):s("agents.notScheduled","Not scheduled")})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:s("agents.interval","Interval")}),e.jsx("p",{children:Ts(A)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:s("agents.status","Status")}),e.jsxs("p",{className:"dashboard-summary-health-row",children:[e.jsx("span",{className:oe("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:s("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(Ms,{taskId:t.taskId,taskColumn:t.taskColumn})}),e.jsxs("a",{href:`/tasks/${t.taskId}`,className:"btn btn-sm",children:[s("agents.viewTask","View Task")," ",e.jsx(Fs,{size:14})]})]}):e.jsx("p",{className:"text-muted",children:s("agents.noActiveAssignment","No active assignment")})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:s("agents.recentRuns","Recent Runs")}),e.jsx("p",{className:"dashboard-summary-label",children:s("agents.runsSuccessRate","{{successful}}/{{total}} successful ({{rate}}%)",{successful:T.successfulRuns,total:T.totalRuns,rate:T.successRate})}),V.length===0?e.jsx("p",{className:"text-muted",children:s("agents.noRunsYet","No runs yet")}):e.jsx("div",{className:"runs-list",children:V.map(p=>{const j=Rt[p.status]||Rt.terminated,d=j.icon;return e.jsxs("div",{className:"run-item",children:[e.jsx(d,{size:14,style:{color:j.color}}),e.jsx("span",{children:Ye(p.startedAt,s)}),e.jsxs("span",{className:"text-muted",children:[Math.max(0,Math.round((new Date(p.endedAt||p.startedAt).getTime()-new Date(p.startedAt).getTime())/1e3)),"s"]})]},p.id)})})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:s("agents.throughput","Throughput")}),e.jsxs("div",{className:"stats-grid",children:[e.jsxs("div",{className:"stat-card",children:[e.jsx("div",{className:"stat-value",children:T.totalRuns}),e.jsx("div",{className:"stat-label",children:s("agents.totalRuns","Total Runs")})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("div",{className:"stat-value",children:T.todayRuns}),e.jsx("div",{className:"stat-label",children:s("agents.runsToday","Runs Today")})]}),e.jsxs("div",{className:"stat-card",children:[e.jsxs("div",{className:"stat-value",children:[T.successRate,"%"]}),e.jsx("div",{className:"stat-label",children:s("agents.successRate","Success Rate")})]})]})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:s("agents.chainOfCommand","Chain of Command")}),g?e.jsxs("div",{className:"chain-of-command-loading",role:"status","aria-live":"polite",children:[e.jsx(q,{size:14,className:"animate-spin"}),e.jsx("span",{children:s("agents.loadingReportingChain","Loading reporting chain...")})]}):N.length<=1?e.jsx("p",{className:"text-muted",children:s("agents.noReportingChain","No reporting chain")}):e.jsx("div",{className:"chain-of-command-path","aria-label":s("agents.chainOfCommand","Chain of command"),children:N.map((p,j)=>{const d=j===N.length-1,z=!d;return e.jsxs("div",{className:"chain-of-command-item",children:[e.jsx("button",{type:"button",className:`chain-of-command-node${d?" chain-of-command-node--current":""}`,onClick:()=>z&&l?.(p.id),disabled:!z||!l,title:d?s("agents.currentAgent","Current agent"):s("agents.viewAgent","View {{name}}",{name:p.name}),children:p.name}),!d&&e.jsx("span",{className:"chain-of-command-separator","aria-hidden":"true",children:"→"})]},p.id)})})]})]})}function tn({logs:t,isStreaming:i,hasTask:l,fallbackLabel:o}){const{t:s}=ke("app");return l?e.jsxs("div",{className:"logs-tab",children:[e.jsxs("div",{className:"logs-header",children:[e.jsx("span",{className:"logs-count",children:s("agents.logEntries","{{count}} entries",{count:t.length})}),o&&e.jsx("span",{className:"text-muted logs-fallback-label",children:o}),i&&e.jsxs("span",{className:"streaming-indicator",children:[e.jsx("span",{className:"streaming-dot"}),s("agents.live","Live")]})]}),t.length===0?e.jsxs("div",{className:"logs-empty",children:[e.jsx(lt,{size:48,opacity:.3}),e.jsx("p",{children:s("agents.noLogEntriesYet","No log entries yet")}),e.jsx("p",{className:"text-muted",children:i?s("agents.waitingForActivity","Waiting for activity..."):s("agents.logsWillAppearActive","Logs will appear here when the agent is active")})]}):e.jsx(Es,{entries:t,loading:!1})]}):e.jsx("div",{className:"logs-tab",children:e.jsxs("div",{className:"logs-empty",children:[e.jsx(lt,{size:48,opacity:.3}),e.jsx("p",{children:s("agents.noActivityYet","No activity yet")}),e.jsx("p",{className:"text-muted",children:s("agents.logsWillAppear","Agent logs will appear here from the current task or most recent run")})]})})}function sn(t,i){const l=new Date(t),s=new Date().getTime()-l.getTime(),h=Math.floor(s/6e4),N=Math.floor(s/36e5),n=Math.floor(s/864e5),g=i??((u,y,c)=>c?y.replace(/\{\{(\w+)\}\}/g,(m,M)=>String(c[M]??"")):y);return h<1?g("time.justNow","just now"):h<60?g("time.minutesAgo","{{n}}m ago",{n:h}):N<24?g("time.hoursAgo","{{n}}h ago",{n:N}):n<7?g("time.daysAgo","{{n}}d ago",{n}):l.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function Nt(t,i,l,o){const s=o??((h,N,n)=>n?N.replace(/\{\{(\w+)\}\}/g,(g,u)=>String(n[u]??"")):N);if(i==="user")return t==="dashboard"?s("mailbox.you","You"):s("mailbox.userLabel","User: {{id}}",{id:t});if(i==="agent"){const h=l?.get(t)?.trim();return!h||h===t?s("mailbox.agentById","Agent: {{id}}",{id:t}):s("mailbox.agentByName","Agent: {{name}}",{name:h})}return s("mailbox.system","System")}function an({agent:t,mailbox:i,isLoading:l,error:o,projectId:s,addToast:h,onRefresh:N}){const{t:n}=ke("app"),[g,u]=a.useState("inbox"),[y,c]=a.useState([]);a.useEffect(()=>{let k=!1;return Ct(void 0,s).then(R=>{k||c(R)}).catch(()=>{k||c([])}),()=>{k=!0}},[s]);const m=a.useMemo(()=>{const k=new Map;for(const C of y){if(!C.id)continue;const D=typeof C.name=="string"?C.name.trim():"";D.length>0&&k.set(C.id,D)}const R=typeof t.name=="string"?t.name.trim():"";return R.length>0&&k.set(t.id,R),k},[y,t.id,t.name]),[M,P]=a.useState(null),L=g==="inbox"?i?.inbox??[]:i?.outbox??[],w=M?L.find(k=>k.id===M)??null:null;a.useEffect(()=>{P(null)},[g,t.id]);const Q=async k=>{if(P(k.id),!(g!=="inbox"||k.read))try{await Ea(k.id,s),N()}catch(R){const C=`Failed to mark message as read: ${U(R)}`;h?h(C,"error"):console.warn(C)}},J=()=>{P(null),N()},S=k=>e.jsxs("button",{type:"button",className:oe("mailbox-item","agent-mail-tab-message",g==="inbox"&&!k.read&&"unread",M===k.id&&"agent-mail-tab-message--selected"),onClick:()=>void Q(k),"aria-pressed":M===k.id,children:[e.jsx("div",{className:"mailbox-item-avatar",children:(g==="inbox"?k.fromType:k.toType)==="agent"?e.jsx(qt,{size:16}):e.jsx(Ca,{size:16})}),e.jsxs("div",{className:"mailbox-item-content",children:[e.jsxs("div",{className:"mailbox-item-header",children:[g==="inbox"?e.jsx("span",{className:"mailbox-item-from",children:Nt(k.fromId,k.fromType,m,n)}):e.jsx("span",{className:"mailbox-item-to",children:n("agents.mailTo","To: {{recipient}}",{recipient:Nt(k.toId,k.toType,m,n)})}),e.jsx("span",{className:"mailbox-item-time",children:sn(k.createdAt,n)})]}),e.jsxs("div",{className:"mailbox-item-preview",children:[k.content.slice(0,80),k.content.length>80?"…":""]})]}),g==="inbox"&&!k.read?e.jsx("div",{className:"mailbox-item-unread-dot","aria-label":n("agents.unreadMessage","Unread message")}):null]},k.id);return e.jsxs("div",{className:"agent-mail-tab",children:[e.jsxs("div",{className:"agent-mail-tab-header",children:[e.jsx("h3",{children:n("agents.agentMail","{{name}} Mail",{name:t.name})}),e.jsxs("button",{className:"btn btn-sm",onClick:J,disabled:l,children:[e.jsx(Mt,{size:14}),n("common.refresh","Refresh")]})]}),e.jsxs("div",{className:"mailbox-agent-subtabs","data-testid":"agent-detail-mail-subtabs",children:[e.jsxs("button",{className:oe("btn","btn-sm","btn-secondary","mailbox-agent-subtab",g==="inbox"&&"active"),onClick:()=>u("inbox"),children:[e.jsx(os,{size:12}),e.jsx("span",{children:n("agents.inbox","Inbox")}),(i?.unreadCount??0)>0?e.jsx("span",{className:"mailbox-tab-badge",children:i?.unreadCount}):null]}),e.jsxs("button",{className:oe("btn","btn-sm","btn-secondary","mailbox-agent-subtab",g==="outbox"&&"active"),onClick:()=>u("outbox"),children:[e.jsx(cs,{size:12}),e.jsx("span",{children:n("agents.outbox","Outbox")})]})]}),l&&!i?e.jsxs("div",{className:"agent-detail-loading agent-detail-loading--inline",role:"status","aria-live":"polite",children:[e.jsx(q,{className:"animate-spin",size:16}),e.jsx("span",{children:n("agents.loadingMailbox","Loading mailbox...")})]}):null,!l&&o?e.jsxs("div",{className:"agent-mail-tab-error",role:"alert",children:[e.jsx(Ps,{size:16}),e.jsx("span",{children:n("agents.mailboxLoadFailed","Failed to load mailbox: {{error}}",{error:o})})]}):null,!l&&!o?w?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:()=>P(null),children:[e.jsx(Ss,{size:14}),g==="inbox"?n("agents.backToInbox","Back to Inbox"):n("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:n("agents.mailFrom","From")}),e.jsx("span",{children:Nt(w.fromId,w.fromType,m,n)})]}),e.jsxs("div",{className:"agent-mail-tab-detail-row",children:[e.jsx("span",{className:"agent-mail-tab-detail-label",children:n("agents.mailToLabel","To")}),e.jsx("span",{children:Nt(w.toId,w.toType,m,n)})]}),e.jsxs("div",{className:"agent-mail-tab-detail-row",children:[e.jsx("span",{className:"agent-mail-tab-detail-label",children:n("agents.mailType","Type")}),e.jsx("span",{children:w.type})]}),e.jsxs("div",{className:"agent-mail-tab-detail-row",children:[e.jsx("span",{className:"agent-mail-tab-detail-label",children:n("agents.mailSent","Sent")}),e.jsx("span",{children:new Date(w.createdAt).toLocaleString()})]}),w.metadata?.replyTo?.messageId?e.jsx("div",{className:"agent-mail-tab-reply-context",children:n("agents.replyingTo","↪ Replying to message {{id}}",{id:w.metadata.replyTo.messageId})}):null]}),e.jsx("div",{className:"agent-mail-tab-detail-body",children:w.content})]}):e.jsx("div",{className:"mailbox-list","data-testid":"agent-detail-mail-list",children:L.length===0?e.jsxs("div",{className:"mailbox-empty","data-testid":"agent-detail-mail-empty",children:[g==="inbox"?e.jsx(os,{size:32}):e.jsx(cs,{size:32}),e.jsx("p",{children:g==="inbox"?n("agents.noInboxMessages","No received messages for this agent"):n("agents.noOutboxMessages","No sent messages for this agent")})]}):L.map(S)}):null]})}function nn({addToast:t,agentId:i,projectId:l,agentState:o,agentName:s,initialRunId:h,preferActiveRun:N,runNowRefreshToken:n,isEphemeral:g}){const{t:u}=ke("app"),[y,c]=a.useState([]),{confirm:m}=js(),[M,P]=a.useState(!0),[L,w]=a.useState(null),[Q,J]=a.useState([]),[S,k]=a.useState(!1),[R,C]=a.useState(null),[D,T]=a.useState(!1),[V,Y]=a.useState(null),[I,Z]=a.useState([]),F=a.useRef(!1),ee=a.useRef(!1),A=a.useCallback(async()=>{try{const x=await ys(i,50,l);c(x)}catch(x){t(`Failed to load runs: ${U(x)}`,"error")}finally{P(!1)}},[i,l,t]);a.useEffect(()=>{A()},[A]),a.useEffect(()=>{if(g){Y(null),Z([]);return}const x=l?`?projectId=${encodeURIComponent(l)}`:"";fetch(`/api/agents/${encodeURIComponent(i)}/token-usage${x}`).then(async v=>{if(!v.ok){if(v.status===400){Y(null);return}throw new Error(`Request failed: ${v.status}`)}const ie=await v.json();Y(ie)}).catch(v=>{t(`Failed to load cache hit ratio: ${U(v)}`,"error")}),ma(i,7,l).then(v=>Z(v)).catch(v=>{const ie=U(v).toLowerCase();if(ie.includes("ephemeral")||ie.includes("400")){Z([]);return}t(`Failed to load prompt sizes: ${U(v)}`,"error")})},[i,l,t,g]),a.useEffect(()=>{if(!ee.current){ee.current=!0;return}P(!0),A()},[A,n]);const W=y.some(x=>x.status==="active"),p=L?y.find(x=>x.id===L)?.status:void 0;a.useEffect(()=>{if(!W)return;const x=setInterval(()=>{A()},5e3);return()=>clearInterval(x)},[W,A]),a.useEffect(()=>{if(!L||p!=="active")return;const x=l?`?projectId=${encodeURIComponent(l)}`:"";return St(`/api/agents/${encodeURIComponent(i)}/runs/${encodeURIComponent(L)}/logs/stream${x}`,{events:{"agent:log":v=>{try{const ie=JSON.parse(v.data);J(ae=>[...ae,ie])}catch{}}}})},[L,p,i,l]);const j=a.useCallback(async x=>{if(L===x){w(null),J([]),C(null);return}w(x),k(!0),T(!0),J([]),C(null);try{const[v,ie]=await Promise.all([Ns(i,x,l),ga(i,x,l)]);J(v),C(ie)}catch(v){t(u("agents.runDetailsFailed","Failed to load run details: {{error}}",{error:U(v)}),"error"),J([]),C(null)}finally{k(!1),T(!1)}},[L,i,l,t]);a.useEffect(()=>{F.current=!1},[i,h,N]),a.useEffect(()=>{if(y.length===0||M||F.current)return;const x=h?y.find(v=>v.id===h):N?y.find(v=>v.status==="active"):null;F.current=!0,x&&j(x.id)},[h,N,y,M,j]);const d=async()=>{if(await m({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 wa(i,l),t(u("agents.runStopped","Run stopped"),"success"),P(!0),A()}catch(v){t(u("agents.stopRunFailed","Failed to stop run: {{error}}",{error:U(v)}),"error")}};if(M&&y.length===0)return e.jsx("div",{className:"runs-tab",children:e.jsxs("div",{className:"runs-loading-row",children:[e.jsx(q,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:u("agents.loadingRuns","Loading runs...")})]})});if(y.length===0)return e.jsx("div",{className:"runs-tab",children:e.jsxs("div",{className:"runs-empty",children:[e.jsx(wt,{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 z=[...y].sort((x,v)=>new Date(v.startedAt).getTime()-new Date(x.startedAt).getTime()),_=z.filter(x=>x.status==="active"),Ce=z.filter(x=>x.status!=="active"),ue=x=>x?e.jsxs("div",{className:"run-usage",children:[e.jsx("span",{children:u("agents.inputTokens","Input: {{value}}",{value:x.inputTokens.toLocaleString()})}),e.jsx("span",{children:u("agents.outputTokens","Output: {{value}}",{value:x.outputTokens.toLocaleString()})}),x.cachedTokens>0&&e.jsx("span",{children:u("agents.cacheReadTokens","Cache read: {{value}}",{value:x.cachedTokens.toLocaleString()})}),(x.cacheWriteTokens??0)>0&&e.jsx("span",{children:u("agents.cacheWriteTokens","Cache write: {{value}}",{value:(x.cacheWriteTokens??0).toLocaleString()})})]}):null,je=(x,v,ie)=>{const ae=Rt[x.status]||Rt.completed,We=ae.icon,ze=x.endedAt?rn(new Date(x.startedAt),new Date(x.endedAt)):u("agents.inProgress","In progress"),Fe=L===x.id;return e.jsxs("div",{children:[e.jsxs("div",{className:oe("run-card",ie&&"run-card--active",Fe&&"run-card--selected","run-card--clickable"),onClick:()=>void j(x.id),role:"button",tabIndex:0,"aria-expanded":Fe,"aria-label":u("agents.runAriaLabel","{{active}}run {{id}}, {{status}}",{active:ie?u("agents.activePrefix","Active "):"",id:x.id.slice(0,8),status:x.status}),onKeyDown:ce=>{(ce.key==="Enter"||ce.key===" ")&&(ce.preventDefault(),j(x.id))},children:[e.jsxs("div",{className:"run-header",children:[e.jsxs("div",{className:"run-header-group",children:[Fe?e.jsx(xs,{size:14}):e.jsx(vs,{size:14}),ie?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:["#",v+1," ",x.id.slice(0,8)]})]}),e.jsxs("div",{className:"run-header-group",children:[x.invocationSource&&e.jsx("span",{className:"badge run-badge--compact",children:x.invocationSource}),ie&&e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:ce=>{ce.preventDefault(),ce.stopPropagation(),d()},"aria-label":u("agents.stopActiveRun","Stop active run"),children:[e.jsx(Ke,{size:12})," ",u("agents.stop","Stop")]}),e.jsxs("span",{className:oe("run-status",x.status),children:[e.jsx(We,{size:14,style:{color:ae.color}}),x.status]}),x.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:Ye(x.startedAt,u)})}),e.jsx("span",{children:"•"}),e.jsx("span",{children:ze}),x.triggerDetail&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsx("span",{className:"text-muted",children:x.triggerDetail})]})]})]}),Fe&&e.jsxs("div",{className:"run-logs-container",children:[D?e.jsxs("div",{className:"run-details-loading-state",children:[e.jsx(q,{size:14,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:u("agents.loadingDetails","Loading details...")})]}):R&&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")}),R.systemPrompt?e.jsx("pre",{className:"run-output-panel",children:R.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")}),R.executionPrompt?e.jsx("pre",{className:"run-output-panel",children:R.executionPrompt}):e.jsx("div",{className:"text-muted run-output-empty",children:u("agents.executionPromptNotCaptured","Execution prompt not captured for this run")})]})}),R.usageJson&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:u("agents.tokenUsage","Token Usage")}),ue(R.usageJson)]}),R.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:R.stdoutExcerpt.length>2e3?`${R.stdoutExcerpt.slice(0,2e3)}
17
-
18
- ... (truncated, ${R.stdoutExcerpt.length} chars total)`:R.stdoutExcerpt})]}),R.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(Ra,{errorText:R.stderrExcerpt,summaryPrefix:"Run error",issueContext:{surface:"AgentDetailView runs",agentId:i,agentName:s,agentState:o,runId:R.id,taskId:void 0,timestamp:R.startedAt}})]}),R.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(R.resultJson,null,2)})]}),R.contextSnapshot&&Object.keys(R.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(R.contextSnapshot).map(([ce,Pe])=>e.jsxs("span",{className:"run-context-item",children:[e.jsxs("span",{className:"text-muted",children:[ce,":"]})," ",e.jsx("span",{children:String(Pe)})]},ce))})]}),!R.stdoutExcerpt&&!R.stderrExcerpt&&!R.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")}),S?e.jsxs("div",{className:"run-details-loading-state",children:[e.jsx(q,{size:14,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:u("agents.loadingLogs","Loading logs...")})]}):Q.length===0?e.jsx("div",{className:"text-muted run-output-empty",children:u("agents.noLogsForRun","No logs available for this run")}):e.jsx(Es,{entries:Q,loading:!1})]})]})]},x.id)},we=(x,v)=>e.jsxs("div",{className:"run-context-item",children:[e.jsxs("span",{className:"text-muted",children:[x,":"]})," ",e.jsx("span",{children:u("agents.cacheWindowSummary","{{percent}}% ({{cached}} / {{written}} / {{input}} / {{tasks}})",{percent:(v.hitRatio*100).toFixed(1),cached:v.totalCachedTokens.toLocaleString(),written:v.totalCacheWriteTokens.toLocaleString(),input:v.totalInputTokens.toLocaleString(),tasks:v.nTasks.toLocaleString()})})]},x),ye=I[0],pe=[...I].reverse(),O=Math.max(1,...pe.map(x=>x.execChars)),se=pe.map((x,v)=>{const ie=pe.length<=1?0:v/(pe.length-1)*100,ae=100-Math.round(x.execChars/O*100);return`${ie},${ae}`}).join(" ");return e.jsxs("div",{className:"runs-tab",children:[I.length>0&&ye&&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:se})]}),e.jsxs("span",{className:"prompt-size-values",children:[ye.systemChars.toLocaleString()," / ",ye.execChars.toLocaleString()," / ",ye.totalChars.toLocaleString()]})]})]}),V&&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:[we(u("agents.last24h","Last 24h"),V.last24h),we(u("agents.last7d","Last 7d"),V.last7d),we(u("agents.allTime","All time"),V.allTime)]})]}),e.jsxs("div",{className:"runs-toolbar runs-toolbar--between",children:[e.jsxs("span",{className:"runs-toolbar-meta",children:[u("agents.runsCount",{count:y.length,defaultValue_one:"{{count}} run",defaultValue_other:"{{count}} runs"}),W&&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:W&&e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void d(),"aria-label":u("agents.stopActiveRunFor","Stop active run for {{name}}",{name:s??i}),children:[e.jsx(Ke,{size:14})," ",u("agents.stopRun","Stop Run")]})})]}),_.map((x,v)=>je(x,v,!0)),Ce.map((x,v)=>je(x,_.length+v,!1))]})}function rn(t,i){const l=Math.floor((i.getTime()-t.getTime())/1e3);return l<60?`${l}s`:l<3600?`${Math.floor(l/60)}m ${l%60}s`:`${Math.floor(l/3600)}h ${Math.floor(l%3600/60)}m`}function ln(t){const i=t.title?.trim()||t.description?.trim()||t.id;return i.length>80?`${i.slice(0,77)}...`:i}function on({agentId:t,projectId:i,addToast:l}){const{t:o}=ke("app"),[s,h]=a.useState([]),[N,n]=a.useState(!0);return a.useEffect(()=>{let g=!1;return n(!0),ha(t,i).then(u=>{g||h(u)}).catch(u=>{g||(h([]),l(o("agents.loadTasksFailed","Failed to load assigned tasks: {{error}}",{error:U(u)}),"error"))}).finally(()=>{g||n(!1)}),()=>{g=!0}},[t,i,l]),N?e.jsxs("div",{className:"agent-tasks-empty",children:[e.jsx(q,{size:16,className:"animate-spin"}),e.jsx("p",{children:o("agents.loadingTasks","Loading assigned tasks...")})]}):s.length===0?e.jsxs("div",{className:"agent-tasks-empty",children:[e.jsx(ws,{size:18}),e.jsx("p",{children:o("agents.noTasksAssigned","No tasks assigned to this agent")})]}):e.jsx("div",{className:"agent-tasks-list",children:s.map(g=>e.jsxs("a",{className:"agent-task-item",href:`/tasks/${g.id}`,children:[e.jsxs("div",{className:"agent-task-row",children:[e.jsx("span",{className:"agent-task-id",children:g.id}),e.jsx("span",{className:`agent-task-column column-${g.column}`,children:{triage:o("board.triage","Triage"),todo:o("board.todo","Todo"),"in-progress":o("board.inProgress","In Progress"),"in-review":o("board.inReview","In Review"),done:o("board.done","Done"),archived:o("board.archived","Archived")}[g.column]??g.column})]}),e.jsx("div",{className:"agent-task-title",title:g.title||g.description||g.id,children:ln(g)}),e.jsxs("div",{className:"agent-task-status",children:[g.status??"idle"," · ",o("agents.taskUpdated","Updated {{time}}",{time:Ye(g.updatedAt,o)})]})]},g.id))})}const it=[{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 cn(t){const i={};for(const l of it){const o=t[l.key]?.trim();if(o){if(l.type==="number"){const s=Number(o);if(Number.isNaN(s)||!Number.isFinite(s)){i[l.key]=`"${l.label}" must be a valid number`;continue}l.min!==void 0&&s<l.min&&(i[l.key]=`"${l.label}" must be at least ${l.min.toLocaleString()}`),l.max!==void 0&&s>l.max&&(i[l.key]=`"${l.label}" must be at most ${l.max.toLocaleString()}`)}if(l.type==="select"){const s=l.options?.map(h=>h.value)??[];s.length>0&&!s.includes(o)&&(i[l.key]=`"${l.label}" must be one of: ${s.join(", ")}`)}}}return i}function dn({agent:t,projectId:i,addToast:l,onSaved:o}){const{t:s}=ke("app"),[h,N]=a.useState(t.soul??""),[n,g]=a.useState(!1),[u,y]=a.useState(!1),[c,m]=a.useState(!1),M=a.useRef(null);a.useEffect(()=>{N(t.soul??""),y(!1),m(!1)},[t.id,t.soul]),a.useEffect(()=>()=>{M.current&&clearTimeout(M.current)},[]);const P=h!==(t.soul??""),L=async()=>{if(h.length>1e4){l(s("agents.soulTooLong","Soul must be at most 10,000 characters"),"error");return}g(!0);try{await Ma(t.id,h,i),l(s("agents.soulSaved","Soul saved"),"success"),y(!0),M.current&&clearTimeout(M.current),M.current=setTimeout(()=>y(!1),3e3),await o()}catch(w){l(s("agents.soulSaveFailed","Failed to save soul: {{error}}",{error:U(w)}),"error")}finally{g(!1)}};return e.jsx("div",{className:"config-tab",children:e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:s("agents.soulTitle","Soul")}),e.jsx("p",{className:"config-description",children:s("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:s("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 ${c?"":"btn-primary"}`,onClick:()=>m(!1),disabled:!c,"aria-label":s("common.editMode","Edit mode"),children:[e.jsx(ot,{size:14}),s("common.edit","Edit")]}),e.jsxs("button",{className:`btn btn-sm ${c?"btn-primary":""}`,onClick:()=>m(!0),disabled:c,"aria-label":s("common.previewMode","Preview mode"),children:[e.jsx(ct,{size:14}),s("common.preview","Preview")]})]})}),c?h.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(dt,{remarkPlugins:[ut],children:h})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:s("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:s("agents.soulPlaceholder","Describe this agent's personality, tone, and behavioral traits..."),value:h,onChange:w=>{N(w.target.value),y(!1)}}),!c&&e.jsx("span",{className:"config-hint",children:s("agents.soulHint","Defines the agent's character and identity. Max 10,000 characters.")})]})}),!c&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!P||n,onClick:()=>void L(),children:n?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),s("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(he,{size:16}),s("agents.saveSoul","Save Soul")]})}),!P&&u&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(he,{size:14}),s("agents.soulSaved","Soul saved")]})]})]})})}function un({agent:t,projectId:i,addToast:l,onSaved:o}){const{t:s}=ke("app"),[h,N]=a.useState(t.memory??""),[n,g]=a.useState(!1),[u,y]=a.useState(!1),[c,m]=a.useState(!1),[M,P]=a.useState(!1),[L,w]=a.useState([]),[Q,J]=a.useState(!1),[S,k]=a.useState(""),[R,C]=a.useState(""),[D,T]=a.useState(!1),[V,Y]=a.useState(!1),[I,Z]=a.useState(!1),[F,ee]=a.useState(!1),[A,W]=a.useState(""),p=a.useRef(null),j=a.useRef(null),d=t.state==="running",z=h!==(t.memory??""),_=a.useMemo(()=>L.find(O=>O.path===S),[L,S]),Ce=_?{"long-term":s("agents.memoryLayerLongTermDesc","Curated durable decisions, conventions, constraints, and pitfalls for this specific agent."),daily:s("agents.memoryLayerDailyDesc","Raw daily observations and open loops recorded by this agent."),dreams:s("agents.memoryLayerDreamsDesc","Synthesized patterns and emerging themes distilled from this agent's daily memory.")}[_.layer]??_.layer:s("agents.selectMemoryFile","Select a memory file to view or edit."),ue=a.useCallback(async O=>{Y(!0);try{const se=await ba(t.id,O,i);k(se.path),C(se.content),T(!1),ee(!1)}catch(se){l(s("agents.memoryFileLoadFailed","Failed to load agent memory file: {{error}}",{error:U(se)}),"error")}finally{Y(!1)}},[t.id,i,l]),je=a.useCallback(async(O="")=>{J(!0);try{const{files:se}=await pa(t.id,i);if(w(se),se.length===0){k(""),C(""),T(!1);return}const x=Xa(se,O);await ue(x)}catch(se){l(s("agents.memoryFilesLoadFailed","Failed to load memory files: {{error}}",{error:U(se)}),"error"),w([]),k(""),C(""),T(!1)}finally{J(!1)}},[t.id,i,l,ue]);a.useEffect(()=>{N(t.memory??""),y(!1),m(!1),P(!1),W(""),ee(!1),je()},[t.id,t.memory,je]),a.useEffect(()=>()=>{p.current&&clearTimeout(p.current),j.current&&clearTimeout(j.current)},[]);const we=async()=>{if(h.length>5e4){l(s("agents.memoryTooLong","Memory must be at most 50,000 characters"),"error");return}g(!0);try{await Aa(t.id,h,i),l(s("agents.memorySaved","Memory saved"),"success"),y(!0),p.current&&clearTimeout(p.current),p.current=setTimeout(()=>y(!1),3e3),await o()}catch(O){l(s("agents.memorySaveFailed","Failed to save memory: {{error}}",{error:U(O)}),"error")}finally{g(!1)}},ye=async O=>{if(!(!O||O===S)){if(D){W(s("agents.saveBeforeSwitch","Save the current file before switching to another file."));return}W(""),await ue(O)}},pe=async()=>{if(S){Z(!0);try{await Pa(t.id,S,R,i),T(!1),ee(!0),j.current&&clearTimeout(j.current),j.current=setTimeout(()=>ee(!1),3e3),W(""),await je(S),l(s("agents.memoryFileSaved","Agent memory file saved"),"success"),await o()}catch(O){l(s("agents.memoryFileSaveFailed","Failed to save agent memory file: {{error}}",{error:U(O)}),"error")}finally{Z(!1)}}};return e.jsx("div",{className:"config-tab",children:e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:s("agents.memoryTitle","Agent Memory")}),e.jsx("p",{className:"config-description",children:s("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.")}),d&&e.jsx("p",{className:"config-hint config-hint--block-spacing",children:s("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:s("agents.inlineMemoryLabel","Inline Memory")}),e.jsx("span",{className:"config-hint config-hint--block",children:s("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:[!d&&e.jsxs("button",{className:`btn btn-sm ${c?"":"btn-primary"}`,onClick:()=>m(!1),disabled:!c,"aria-label":s("common.editMode","Edit mode"),children:[e.jsx(ot,{size:14}),s("common.edit","Edit")]}),e.jsxs("button",{className:`btn btn-sm ${c?"btn-primary":""}`,onClick:()=>m(!0),disabled:c,"aria-label":s("common.previewMode","Preview mode"),children:[e.jsx(ct,{size:14}),s("common.preview","Preview")]})]})}),c?h.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(dt,{remarkPlugins:[ut],children:h})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:s("agents.memoryEmptyPreview","No agent memory defined yet. Switch to Edit mode to add memory content.")}):e.jsx("textarea",{id:"agent-memory","aria-label":s("agents.memoryTitle","Agent Memory"),className:"input config-textarea-mono",rows:10,placeholder:s("agents.memoryPlaceholder","Durable preferences, operating habits, and context this agent should carry across tasks..."),value:h,readOnly:d,onChange:O=>{N(O.target.value),y(!1)}}),!c&&e.jsx("span",{className:"config-hint",children:s("agents.inlineMemoryFieldHint","This is the inline memory field on the agent JSON record. Max 50,000 characters.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-memory-file-select",children:s("agents.memoryFilesLabel","Memory Files")}),e.jsxs("span",{className:"config-hint config-hint--block",children:[s("agents.memoryFilesHint","Full OpenClaw memory files at")," ",e.jsxs("code",{children:["agent/",t.name||t.id,"/memory/"]})," ",s("agents.memoryFilesHintSuffix","(MEMORY.md, DREAMS.md, and daily notes).")]}),e.jsx("select",{id:"agent-memory-file-select",className:"select",value:S,disabled:Q||V||I||L.length===0,onChange:O=>{ye(O.target.value)},children:L.length===0?e.jsx("option",{value:"",children:s("agents.noMemoryFiles","No memory files found")}):L.map(O=>{const se={"long-term":s("agents.memoryLayerLongTerm","Long-term"),daily:s("agents.memoryLayerDaily","Daily"),dreams:s("agents.memoryLayerDreams","Dreams")}[O.layer]??O.layer;return e.jsxs("option",{value:O.path,children:[se," • ",O.label]},O.path)})}),Q&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(q,{size:14,className:"animate-spin"}),s("agents.loadingMemoryFiles","Loading memory files…")]}),_&&e.jsxs("div",{className:"config-hint config-hint--top-spacing",children:[e.jsx("strong",{children:{"long-term":s("agents.memoryLayerLongTerm","Long-term"),daily:s("agents.memoryLayerDaily","Daily"),dreams:s("agents.memoryLayerDreams","Dreams")}[_.layer]??_.layer})," · ",Ce,e.jsx("br",{}),s("agents.memoryFileMeta","{{size}} bytes · Updated {{time}}",{size:_.size.toLocaleString(),time:Ye(_.updatedAt,s)})]}),e.jsx("div",{className:"agent-content-toolbar config-textarea-top-spacing",children:e.jsxs("div",{className:"agent-content-mode-toggle",children:[!d&&e.jsxs("button",{className:`btn btn-sm ${M?"":"btn-primary"}`,onClick:()=>P(!1),disabled:!M,"aria-label":s("agents.memoryFileEditMode","Memory file edit mode"),children:[e.jsx(ot,{size:14}),s("common.edit","Edit")]}),e.jsxs("button",{className:`btn btn-sm ${M?"btn-primary":""}`,onClick:()=>P(!0),disabled:M,"aria-label":s("agents.memoryFilePreviewMode","Memory file preview mode"),children:[e.jsx(ct,{size:14}),s("common.preview","Preview")]})]})}),M?R.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(dt,{remarkPlugins:[ut],children:R})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:s("agents.memoryFileEmptyPreview","No memory file content yet. Switch to Edit mode to add content.")}):e.jsx("textarea",{className:"input config-textarea-mono",rows:14,placeholder:s("agents.memoryFilePlaceholder","Select a memory file to view and edit its content..."),value:R,readOnly:d||!S||V,onChange:O=>{C(O.target.value),T(!0),ee(!1),W("")}}),V&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(q,{size:14,className:"animate-spin"}),s("agents.loadingFileContent","Loading file content…")]}),A&&e.jsx("span",{className:"config-hint config-hint--top-spacing config-hint--block",children:A})]})]}),e.jsxs("div",{className:"config-actions",children:[!c&&e.jsx("button",{className:"btn btn-task-create",disabled:!z||n||d,onClick:()=>void we(),children:n?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),s("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(he,{size:16}),s("agents.saveMemory","Save Memory")]})}),!M&&e.jsx("button",{className:"btn",disabled:!D||I||!S||d,onClick:()=>void pe(),children:I?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),s("agents.savingFile","Saving file…")]}):e.jsxs(e.Fragment,{children:[e.jsx(he,{size:16}),s("agents.saveMemoryFile","Save Memory File")]})}),!z&&u&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(he,{size:14}),s("agents.memorySaved","Memory saved")]}),!D&&F&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(he,{size:14}),s("agents.memoryFileSaved","Memory file saved")]})]})]})})}function mn({agent:t,projectId:i,addToast:l,onSaved:o}){const{t:s}=ke("app"),[h,N]=a.useState(t.instructionsText??""),[n,g]=a.useState(t.instructionsPath??""),[u,y]=a.useState(!1),[c,m]=a.useState(""),[M,P]=a.useState(!1),[L,w]=a.useState(!1),[Q,J]=a.useState(!1),[S,k]=a.useState(!1),[R,C]=a.useState(!1),[D,T]=a.useState(!1),V=a.useRef(null),Y=a.useRef(null);a.useEffect(()=>{const A=n.trim();if(!A){m(""),w(!1);return}P(!0),Ls("project",A).then(W=>{m(W.content),w(!1)}).catch(W=>{const p=U(W);p.includes("ENOENT")||p.includes("Not found")||p.includes("not found")?(m(""),w(!1)):(l(`Failed to load instructions file: ${p}`,"error"),m(""))}).finally(()=>{P(!1)})},[n,l]),a.useEffect(()=>{N(t.instructionsText??""),g(t.instructionsPath??""),C(!1),T(!1),y(!1)},[t.id,t.instructionsText,t.instructionsPath]),a.useEffect(()=>()=>{V.current&&clearTimeout(V.current),Y.current&&clearTimeout(Y.current)},[]);const I=(()=>{const A=h??"",W=t.instructionsText??"",p=n?.trim()??"",j=t.instructionsPath?.trim()??"";return A!==W||p!==j})(),Z=async()=>{J(!0);try{await Fa(t.id,{instructionsText:h||void 0,instructionsPath:n.trim()||void 0},i),l(s("agents.instructionsSaved","Instructions saved"),"success"),C(!0),V.current&&clearTimeout(V.current),V.current=setTimeout(()=>C(!1),3e3),await o()}catch(A){l(s("agents.instructionsSaveFailed","Failed to save instructions: {{error}}",{error:U(A)}),"error")}finally{J(!1)}},F=async()=>{const A=n.trim();if(!A){l(s("agents.noInstructionsPath","No instructions file path set"),"error");return}k(!0);try{await Ds("project",A,c),l(s("agents.instructionsFileSaved","Instructions file saved"),"success"),w(!1),T(!0),Y.current&&clearTimeout(Y.current),Y.current=setTimeout(()=>T(!1),3e3),await o()}catch(W){l(s("agents.instructionsFileSaveFailed","Failed to save instructions file: {{error}}",{error:U(W)}),"error")}finally{k(!1)}},ee=!!n.trim();return e.jsxs("div",{className:"config-tab",children:[e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:s("agents.instructionsTitle","Custom Instructions")}),e.jsx("p",{className:"config-description",children:s("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:s("agents.inlineInstructions","Inline Instructions")}),e.jsx("div",{className:"agent-content-toolbar",children:e.jsxs("div",{className:"agent-content-mode-toggle",children:[e.jsxs("button",{className:`btn btn-sm ${u?"":"btn-primary"}`,onClick:()=>y(!1),disabled:!u,"aria-label":s("common.editMode","Edit mode"),"data-testid":"instructions-edit-toggle",children:[e.jsx(ot,{size:14}),s("common.edit","Edit")]}),e.jsxs("button",{className:`btn btn-sm ${u?"btn-primary":""}`,onClick:()=>y(!0),disabled:u,"aria-label":s("common.previewMode","Preview mode"),"data-testid":"instructions-preview-toggle",children:[e.jsx(ct,{size:14}),s("common.preview","Preview")]})]})}),u?h.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(dt,{remarkPlugins:[ut],children:h})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:s("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:s("agents.instructionsPlaceholder","Enter custom instructions to append to this agent's system prompt..."),value:h,onChange:A=>{N(A.target.value),C(!1)}}),!u&&e.jsx("span",{className:"config-hint",children:s("agents.instructionsHint","Markdown formatting supported. Max 50,000 characters.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"instructions-path",children:s("agents.instructionsPathLabel","Instructions File Path")}),e.jsx("input",{id:"instructions-path",type:"text",className:"input",placeholder:s("agents.instructionsPathPlaceholder","e.g., .fusion/agents/my-agent-instructions.md"),value:n,onChange:A=>{g(A.target.value),C(!1)}}),e.jsx("span",{className:"config-hint",children:s("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:!I||Q,onClick:()=>void Z(),children:Q?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),s("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(he,{size:16}),s("agents.saveInstructions","Save Instructions")]})}),!I&&R&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(he,{size:14}),s("agents.instructionsSaved","Instructions saved")]})]})]}),ee&&e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:s("agents.instructionsFileEditorTitle","Instructions File Editor")}),e.jsx("p",{className:"config-description",children:s("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:s("agents.fileContentLabel","File Content")}),M&&e.jsxs("span",{className:"config-hint config-hint--inline-tight",children:[e.jsx(q,{size:12,className:"animate-spin"}),s("common.loading","Loading...")]}),L&&!M&&e.jsx("span",{className:"config-hint config-hint--warning",children:s("common.unsavedChanges","Unsaved changes")})]}),e.jsx("textarea",{id:"instructions-file-content",className:"input config-textarea-mono",rows:20,placeholder:s("agents.fileContentPlaceholder","File content will appear here when loaded..."),value:c,readOnly:M,onChange:A=>{m(A.target.value),w(!0),T(!1)}}),e.jsx("span",{className:"config-hint",children:s("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:!L||S,onClick:()=>void F(),children:S?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),s("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(he,{size:16}),s("agents.saveFile","Save File")]})}),!L&&D&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(he,{size:14}),s("agents.fileSaved","File saved")]})]})]})]})}function hs(t){const i=t??{},l={};return i.heartbeatIntervalMs!==void 0&&i.heartbeatIntervalMs!==null&&(l.heartbeatIntervalMs=String(Number(i.heartbeatIntervalMs)/1e3)),i.heartbeatTimeoutMs!==void 0&&i.heartbeatTimeoutMs!==null&&(l.heartbeatTimeoutMs=String(Number(i.heartbeatTimeoutMs)/1e3)),i.maxConcurrentRuns!==void 0&&i.maxConcurrentRuns!==null&&(l.maxConcurrentRuns=String(i.maxConcurrentRuns)),(i.messageResponseMode==="immediate"||i.messageResponseMode==="on-heartbeat")&&(l.messageResponseMode=i.messageResponseMode),i.autoClaimCandidatesInPrompt!==void 0&&i.autoClaimCandidatesInPrompt!==null&&(l.autoClaimCandidatesInPrompt=String(i.autoClaimCandidatesInPrompt)),l}function Ht(t){return t?.enabled!==!1}function It(t){return t?.autoClaimRelevantTasks!==!1}function Bt(t){return t?.engineerBacklogAutoClaim===!0}function $t(t){return t?.runMissedHeartbeatOnStartup===!0}function Ot(t){return t?.allowParallelExecution!==!1}function _t(t){return t?.skipHeartbeatWhenIdle===!0}function Ut(t){const i=t?.heartbeatScopeDiscipline;return i==="strict"||i==="lite"||i==="off"?i:""}function fs(t){const i=t?.heartbeatPromptTemplate;return i==="default"||i==="compact"?i:""}function bs(t){const i=(t??{}).budgetConfig,l={};return i&&(i.tokenBudget!==void 0&&i.tokenBudget!==null&&(l.tokenBudget=String(i.tokenBudget)),i.usageThreshold!==void 0&&i.usageThreshold!==null&&(l.usageThreshold=String(Number(i.usageThreshold)*100)),i.budgetPeriod!==void 0&&i.budgetPeriod!==null&&(l.budgetPeriod=String(i.budgetPeriod)),i.resetDay!==void 0&&i.resetDay!==null&&(l.resetDay=String(i.resetDay))),l}function gn({agent:t,projectId:i,addToast:l,onSaved:o}){const{t:s}=ke("app"),[h,N]=a.useState(!1),[n,g]=a.useState(!1),[u,y]=a.useState(!1),[c,m]=a.useState(!1),[M,P]=a.useState(!1),[L,w]=a.useState(""),[Q,J]=a.useState(!1),[S,k]=a.useState(null),[R,C]=a.useState(!1),D=a.useRef(null),T=t.heartbeatProcedurePath?.trim(),V=`.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`,Y=`.fusion/agents/${t.id}/HEARTBEAT.md`,I=t.id.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"agent",Z=!!(T&&(T===V||T===Y||new RegExp(`^\\.fusion/agents/[^/]+-${I}/HEARTBEAT\\.md$`).test(T))),F=!!T,ee=a.useCallback(async j=>{y(!0),k(null);try{const d=await Ls("project",j,i);w(d.content),J(!1)}catch(d){const z=U(d);k(z),l(s("agents.heartbeatFileLoadFailed","Failed to load heartbeat procedure file: {{error}}",{error:z}),"error")}finally{y(!1)}},[l,i]);a.useEffect(()=>{g(!1),P(!1),w(""),J(!1),k(null),y(!1),m(!1),C(!1)},[t.id,T]),a.useEffect(()=>()=>{D.current&&clearTimeout(D.current)},[]);const A=async()=>{T&&(g(!0),await ee(T))},W=async()=>{if(T){m(!0);try{await Ds("project",T,L,i),J(!1),C(!0),l(s("agents.heartbeatFileSaved","Heartbeat procedure file saved"),"success"),D.current&&clearTimeout(D.current),D.current=setTimeout(()=>C(!1),3e3),await o()}catch(j){l(s("agents.heartbeatFileSaveFailed","Failed to save heartbeat procedure file: {{error}}",{error:U(j)}),"error")}finally{m(!1)}}},p=async()=>{N(!0);try{const j=await La(t.id,i);l(j.procedureFileSeeded?s("agents.heartbeatProcedureFileReady","Heartbeat procedure file ready at {{path}}",{path:j.heartbeatProcedurePath}):s("agents.heartbeatProcedurePathSet","Heartbeat procedure path set to {{path}}",{path:j.heartbeatProcedurePath}),"success"),await o()}catch(j){l(s("agents.heartbeatUpgradeFailed","Failed to upgrade heartbeat procedure: {{error}}",{error:U(j)}),"error")}finally{N(!1)}};return e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:s("agents.heartbeatProcedureTitle","Heartbeat Procedure")}),e.jsxs("p",{className:"config-description",children:[s("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"}),s("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:[s("agents.currentPath","Current path:")," ",e.jsx("code",{children:T||s("agents.noneUsingBuiltIn","(none — using built-in default)")})]}),F&&e.jsx("div",{className:"heartbeat-procedure-actions",children:e.jsx("button",{className:"btn btn-sm",onClick:()=>void A(),disabled:u,children:u?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),s("agents.loadingFile","Loading file…")]}):e.jsxs(e.Fragment,{children:[e.jsx(lt,{size:16}),s("agents.viewHeartbeatMarkdown","View Heartbeat Markdown")]})})})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("button",{className:"btn",disabled:h||Z,onClick:()=>void p(),"aria-label":s("agents.upgradeToDefaultAriaLabel","Upgrade agent to default heartbeat procedure file"),children:h?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),s("agents.upgrading","Upgrading…")]}):Z?e.jsxs(e.Fragment,{children:[e.jsx(he,{size:16}),s("agents.alreadyOnDefault","Already on default")]}):s("agents.upgradeToDefault","Upgrade to Default Heartbeat Procedure")}),e.jsxs("span",{className:"config-hint",children:[s("agents.upgradeHint","Sets")," ",e.jsx("code",{children:"heartbeatProcedurePath"})," ",s("agents.upgradeHintTo","to")," ",e.jsx("code",{children:V})," ",s("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.")]})]})]}),n&&F&&T&&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:s("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 ${M?"":"btn-primary"}`,onClick:()=>P(!1),disabled:!M,"aria-label":s("agents.heartbeatFileEditMode","Heartbeat file edit mode"),children:[e.jsx(ot,{size:14}),s("common.edit","Edit")]}),e.jsxs("button",{className:`btn btn-sm ${M?"btn-primary":""}`,onClick:()=>P(!0),disabled:M,"aria-label":s("agents.heartbeatFilePreviewMode","Heartbeat file preview mode"),children:[e.jsx(ct,{size:14}),s("common.preview","Preview")]})]}),u&&e.jsxs("span",{className:"config-hint heartbeat-procedure-status",children:[e.jsx(q,{size:12,className:"animate-spin"}),s("common.loading","Loading...")]}),Q&&!u&&e.jsx("span",{className:"config-hint heartbeat-procedure-status heartbeat-procedure-status--warning",children:s("common.unsavedChanges","Unsaved changes")})]}),M?L.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(dt,{remarkPlugins:[ut],children:L})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:s("agents.heartbeatFileEmptyPreview","No heartbeat procedure markdown content yet.")}):e.jsx("textarea",{id:"heartbeat-procedure-file-content",className:"input",rows:16,value:L,readOnly:u,placeholder:s("agents.heartbeatFilePlaceholder","Heartbeat procedure markdown file content will appear here..."),onChange:j=>{w(j.target.value),J(!0),C(!1)}}),S&&e.jsx("span",{className:"config-error",children:s("agents.fileLoadError","Failed to load file: {{error}}",{error:S})}),e.jsxs("span",{className:"config-hint",children:[s("agents.heartbeatFileEditorHint","This editor writes directly to")," ",e.jsx("code",{children:T}),"."]})]}),!M&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!Q||c||u,onClick:()=>void W(),children:c?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),s("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(he,{size:16}),s("agents.saveHeartbeatFile","Save Heartbeat File")]})}),!Q&&R&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(he,{size:14}),s("agents.fileSaved","File saved")]})]})]})]})}function hn({agent:t,projectId:i,addToast:l,onSaved:o,onHasChangesChange:s,onDelete:h,onAgentDraftApplied:N}){const{t:n}=ke("app"),[g,u]=a.useState(t.name),[y,c]=a.useState(t.role),[m,M]=a.useState(t.title??""),[P,L]=a.useState(t.icon??""),[w,Q]=a.useState(t.reportsTo??""),[J,S]=a.useState([]),[k,R]=a.useState(!1),[C,D]=a.useState(!1),[T,V]=a.useState(!1),Y=a.useRef(null),[I,Z]=a.useState(()=>{const r={};for(const f of it){const E=t.metadata[f.key];E!=null&&(r[f.key]=String(E))}return r}),[F,ee]=a.useState(()=>hs(t.runtimeConfig)),[A,W]=a.useState(()=>Ht(t.runtimeConfig)),[p,j]=a.useState(()=>It(t.runtimeConfig)),[d,z]=a.useState(()=>Bt(t.runtimeConfig)),[_,Ce]=a.useState(()=>$t(t.runtimeConfig)),[ue,je]=a.useState(()=>Ot(t.runtimeConfig)),[we,ye]=a.useState(()=>_t(t.runtimeConfig)),[pe,O]=a.useState(()=>Ut(t.runtimeConfig)),[se,x]=a.useState(()=>fs(t.runtimeConfig)),[v,ie]=a.useState(()=>bs(t.runtimeConfig)),[ae,We]=a.useState(t.bundleConfig?.mode??""),[ze,Fe]=a.useState(t.bundleConfig?.entryFile??"AGENTS.md"),[ce,Pe]=a.useState(t.bundleConfig?.externalPath??""),[ne,mt]=a.useState(t.bundleConfig?.files??[]),[Te,Ne]=a.useState(Array.isArray(t.metadata?.skills)?t.metadata.skills:[]),{favoriteProviders:gt,favoriteModels:Ze,toggleFavoriteProvider:Ft,toggleFavoriteModel:Qe}=xa(),[Be,Ee]=a.useState([]),[ht,Xe]=a.useState(!1),[Ue,ft]=a.useState([]),[bt,Je]=a.useState(!1),Re=(()=>{const r=t.runtimeConfig??{};return r.modelProvider&&r.modelId?`${r.modelProvider}/${r.modelId}`:typeof r.model=="string"&&r.model.includes("/")?r.model:""})(),He=typeof t.runtimeConfig?.runtimeHint=="string"?t.runtimeConfig.runtimeHint:"",[fe,$e]=a.useState(He?"runtime":"model"),[b,H]=a.useState(Re),[B,$]=a.useState(He),[re,be]=a.useState(t.permissionPolicy),[ge,Le]=a.useState(void 0),Oe=w.trim(),et=a.useMemo(()=>J.filter(r=>r.id!==t.id),[J,t.id]),At=!!Oe&&!et.some(r=>r.id===Oe),Pt=a.useMemo(()=>({name:g,role:y,title:m||void 0,instructionsText:t.instructionsText,soul:t.soul,memory:t.memory,reportsTo:w||void 0,skills:Te,model:b||void 0,runtimeHint:fe==="runtime"&&B||void 0,thinkingLevel:I.thinkingLevel??void 0,maxTurns:I.maxTurns?Number(I.maxTurns):void 0,heartbeatIntervalMs:F.heartbeatIntervalMs?Number(F.heartbeatIntervalMs)*1e3:void 0,heartbeatTimeoutMs:F.heartbeatTimeoutMs?Number(F.heartbeatTimeoutMs)*1e3:void 0,maxConcurrentRuns:F.maxConcurrentRuns?Number(F.maxConcurrentRuns):void 0,messageResponseMode:F.messageResponseMode}),[t.instructionsText,t.memory,t.soul,I.maxTurns,I.thinkingLevel,F.heartbeatIntervalMs,F.heartbeatTimeoutMs,F.maxConcurrentRuns,F.messageResponseMode,b,g,w,y,fe,B,Te,m]),pt=a.useCallback(r=>{u(r.name),c(r.role),M(r.title??""),L(r.icon??""),Q(r.reportsTo??""),r.skills&&Ne(r.skills),r.thinkingLevel&&Z(E=>({...E,thinkingLevel:r.thinkingLevel})),r.maxTurns!==void 0&&Z(E=>({...E,maxTurns:String(r.maxTurns)})),r.runtimeHint!==void 0?($e("runtime"),$(r.runtimeHint??""),r.runtimeHint&&H("")):r.model!==void 0&&($e("model"),H(r.model??""),$(""));const f=Object.fromEntries(Object.entries({name:r.name,role:r.role,title:r.title,icon:r.icon,reportsTo:r.reportsTo,instructionsText:r.instructionsText,soul:r.soul,memory:r.memory}).filter(([,E])=>E!==void 0));N?.(f),V(!1),l(n("agents.interviewDraftApplied","Interview draft applied. Review and save when ready."),"success")},[l,N]);a.useEffect(()=>{be(t.permissionPolicy)},[t.permissionPolicy]),a.useEffect(()=>{va(i).then(r=>Le(r.project?.defaultAgentPermissionPolicy)).catch(()=>Le(void 0))},[i]);const me=async r=>{be(r);try{await ds(t.id,{permissionPolicy:r},i),await o(),l(n("agents.permissionPolicyUpdated","Permission policy updated"),"success")}catch(f){l(n("agents.permissionPolicyFailed","Failed to update permission policy: {{error}}",{error:U(f)}),"error")}};a.useEffect(()=>{let r=!1;return R(!0),Ct(void 0,i).then(f=>{r||S(f)}).catch(()=>{r||S([])}).finally(()=>{r||R(!1)}),()=>{r=!0}},[i]),a.useEffect(()=>{Xe(!0),ja().then(r=>{Ee(r.models)}).catch(()=>{}).finally(()=>Xe(!1))},[]),a.useEffect(()=>{Je(!0),As(i).then(ft).catch(()=>ft([])).finally(()=>Je(!1))},[i]);const[Se,tt]=a.useState(null),[Kt,Yt]=a.useState(!1);a.useEffect(()=>{Vt(t.id,i).then(tt).catch(()=>tt(null))},[t.id,i]);const zs=async()=>{Yt(!0);try{await Ta(t.id,i),l(n("agents.budgetResetSuccess","Budget usage reset successfully"),"success");const r=await Vt(t.id,i);tt(r)}catch(r){l(n("agents.budgetResetFailed","Failed to reset budget: {{error}}",{error:U(r)}),"error")}finally{Yt(!1)}},[_e,Zt]=a.useState(!1),[G,Ve]=a.useState({}),[Hs,qe]=a.useState(!1),[Tt,xt]=a.useState(null),Qt=t.state==="idle"||t.state==="paused",st=a.useRef(null),Xt=a.useRef(null),es=a.useRef(null),vt=a.useRef(0);a.useEffect(()=>()=>{st.current&&clearTimeout(st.current)},[]);const Me=(()=>{if(g!==t.name||y!==t.role||m!==(t.title??"")||P!==(t.icon??"")||w!==(t.reportsTo??"")||ae!==(t.bundleConfig?.mode??"")||ze!==(t.bundleConfig?.entryFile??"AGENTS.md")||ce!==(t.bundleConfig?.externalPath??"")||JSON.stringify(ne)!==JSON.stringify(t.bundleConfig?.files??[]))return!0;for(const X of it){const xe=I[X.key]?.trim()??"",ve=t.metadata[X.key]!==void 0&&t.metadata[X.key]!==null?String(t.metadata[X.key]):"";if(xe!==ve)return!0}const r=t.runtimeConfig??{};if(A!==Ht(t.runtimeConfig)||p!==It(t.runtimeConfig)||d!==Bt(t.runtimeConfig)||_!==$t(t.runtimeConfig)||ue!==Ot(t.runtimeConfig)||we!==_t(t.runtimeConfig)||pe!==Ut(t.runtimeConfig)||se!==fs(t.runtimeConfig))return!0;for(const X of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns","messageResponseMode","autoClaimCandidatesInPrompt"]){const xe=F[X]?.trim()??"";let ve=r[X]!==void 0&&r[X]!==null?String(r[X]):"";if((X==="heartbeatIntervalMs"||X==="heartbeatTimeoutMs")&&ve&&(ve=String(Number(ve)/1e3)),xe!==ve)return!0}const f=r.budgetConfig;for(const X of["tokenBudget","budgetPeriod","resetDay"]){const xe=v[X]?.trim()??"",ve=f?.[X]!==void 0&&f?.[X]!==null?String(f[X]):"";if(xe!==ve)return!0}const E=v.usageThreshold?.trim()??"",te=f?.usageThreshold!==void 0&&f?.usageThreshold!==null?String(Number(f.usageThreshold)*100):"";if(E!==te)return!0;const Ae=Array.isArray(t.metadata?.skills)?t.metadata.skills:[];return JSON.stringify(Te)!==JSON.stringify(Ae)||fe!==(He?"runtime":"model")||b!==Re||B!==He})(),ts=a.useRef(null);a.useEffect(()=>{s&&ts.current!==Me&&(ts.current=Me,s(Me))},[Me,s]),a.useEffect(()=>()=>{s?.(!1)},[s]),a.useEffect(()=>{const r={id:t.id,updatedAt:t.updatedAt},f=Xt.current;(!f||f.id!==r.id||f.updatedAt!==r.updatedAt)&&(Me||(Xt.current=r,ee(hs(t.runtimeConfig)),W(Ht(t.runtimeConfig)),j(It(t.runtimeConfig)),z(Bt(t.runtimeConfig)),Ce($t(t.runtimeConfig)),je(Ot(t.runtimeConfig)),ye(_t(t.runtimeConfig)),O(Ut(t.runtimeConfig)),ie(bs(t.runtimeConfig)),H(Re),$(He),$e(He?"runtime":"model")))},[t,Me,Re,He]);const ss=(r,f)=>{Z(E=>({...E,[r]:f})),qe(!1),G[r]&&Ve(E=>{const te={...E};return delete te[r],te})},jt=(r,f)=>{ee(E=>({...E,[r]:f})),qe(!1),G[r]&&Ve(E=>{const te={...E};return delete te[r],te})},Is=r=>{W(r),qe(!1)},yt=(r,f)=>{ie(E=>({...E,[r]:f})),qe(!1),G[r]&&Ve(E=>{const te={...E};return delete te[r],te})},De=a.useMemo(()=>{const r=cn(I);for(const[K,le]of Object.entries({heartbeatIntervalMs:{label:"Heartbeat Interval",min:1},heartbeatTimeoutMs:{label:"Heartbeat Timeout",min:5},maxConcurrentRuns:{label:"Max Concurrent Runs",min:1}})){const Ie=F[K]?.trim();if(!Ie)continue;const Ge=Number(Ie);Number.isNaN(Ge)||!Number.isFinite(Ge)?r[K]=`"${le.label}" must be a valid number`:Ge<le.min&&(r[K]=`"${le.label}" must be at least ${le.min.toLocaleString()}`)}const f=F.autoClaimCandidatesInPrompt?.trim();if(f){const K=Number(f);(!Number.isInteger(K)||K<0||K>10)&&(r.autoClaimCandidatesInPrompt='"Auto-claim candidates in prompt" must be an integer between 0 and 10')}const E=F.messageResponseMode?.trim();E&&!["immediate","on-heartbeat"].includes(E)&&(r.messageResponseMode='"Message Response Mode" must be either immediate or on-heartbeat');const te=v.tokenBudget?.trim();if(te){const K=Number(te);Number.isNaN(K)||!Number.isFinite(K)?r.tokenBudget='"Token Budget" must be a valid number':K<=0&&(r.tokenBudget='"Token Budget" must be greater than 0')}const Ae=v.usageThreshold?.trim();if(Ae){const K=Number(Ae);Number.isNaN(K)||!Number.isFinite(K)?r.usageThreshold='"Usage Threshold" must be a valid number':(K<1||K>100)&&(r.usageThreshold='"Usage Threshold" must be between 1 and 100')}const X=v.budgetPeriod?.trim();X&&!["daily","weekly","monthly","lifetime"].includes(X)&&(r.budgetPeriod='"Budget Period" must be one of: daily, weekly, monthly, lifetime');const xe=v.resetDay?.trim(),ve=X||"lifetime";if(xe){const K=Number(xe);Number.isNaN(K)||!Number.isFinite(K)?r.resetDay='"Reset Day" must be a valid number':ve==="weekly"?(K<0||K>6||!Number.isInteger(K))&&(r.resetDay='"Reset Day" must be between 0 (Sunday) and 6 (Saturday) for weekly period'):ve==="monthly"&&(K<1||K>31||!Number.isInteger(K))&&(r.resetDay='"Reset Day" must be between 1 and 31 for monthly period')}return r},[I,F,v]),as=a.useCallback(()=>{if(Object.keys(De).length>0)return null;const r={...t.metadata};for(const le of it){const Ie=I[le.key]?.trim();Ie?le.type==="number"?r[le.key]=Number(Ie):r[le.key]=Ie:delete r[le.key]}Te.length>0?r.skills=Te:delete r.skills;const f={...t.runtimeConfig};f.enabled=A,f.autoClaimRelevantTasks=p,f.engineerBacklogAutoClaim=d,f.runMissedHeartbeatOnStartup=_,f.allowParallelExecution=ue,f.skipHeartbeatWhenIdle=we;for(const le of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns","autoClaimCandidatesInPrompt"]){const Ie=F[le]?.trim();if(!Ie)delete f[le];else{const Ge=Number(Ie);f[le]=le==="maxConcurrentRuns"||le==="autoClaimCandidatesInPrompt"?Ge:Ge*1e3}}const E=F.messageResponseMode?.trim();if(E?f.messageResponseMode=E:delete f.messageResponseMode,pe?f.heartbeatScopeDiscipline=pe:delete f.heartbeatScopeDiscipline,se?f.heartbeatPromptTemplate=se:delete f.heartbeatPromptTemplate,fe==="runtime")B.trim()?f.runtimeHint=B.trim():delete f.runtimeHint,delete f.modelProvider,delete f.modelId,delete f.model;else if(delete f.runtimeHint,b.trim()){const le=b.indexOf("/");le!==-1&&(f.modelProvider=b.slice(0,le),f.modelId=b.slice(le+1),f.model=b.trim())}else delete f.modelProvider,delete f.modelId,delete f.model;const te={},Ae=v.tokenBudget?.trim(),X=v.usageThreshold?.trim(),xe=v.budgetPeriod?.trim(),ve=v.resetDay?.trim();Ae&&(te.tokenBudget=Number(Ae)),X&&(te.usageThreshold=Number(X)/100),xe&&(te.budgetPeriod=xe),ve&&(te.resetDay=Number(ve)),Object.keys(te).length>0?f.budgetConfig=te:delete f.budgetConfig;let K;return ae&&(K={mode:ae,entryFile:ze||"AGENTS.md",files:ne.length>0?ne:["AGENTS.md"]},ae==="external"&&ce.trim()&&(K.externalPath=ce.trim())),{name:g.trim()||void 0,role:y,title:m.trim()||void 0,icon:P.trim()||void 0,reportsTo:w.trim()||void 0,metadata:r,runtimeConfig:f,bundleConfig:K}},[t.metadata,t.runtimeConfig,ue,p,v,ze,ce,ne,ae,d,I,A,se,pe,F,P,b,g,w,y,_,fe,B,Te,we,m,De]),at=a.useCallback(async(r,f)=>{const E=as();if(!E)return Ve(De),r&&l(n("agents.fixValidationErrors","Please fix validation errors before saving"),"error"),f==="auto"&&xt(n("agents.fixValidationToSave","Fix validation errors to save changes")),!1;const te=JSON.stringify(E);if(te===es.current)return!1;const Ae=++vt.current;Ve({}),xt(null),Zt(!0);try{return await ds(t.id,E,i),Ae!==vt.current?!1:(es.current=te,f==="manual"&&l(n("agents.settingsSaved","Settings saved"),"success"),xt(null),qe(!0),st.current&&clearTimeout(st.current),st.current=setTimeout(()=>qe(!1),3e3),await o(),!0)}catch(X){if(Ae===vt.current){const xe=U(X);xt(xe),l(n("agents.settingsSaveFailed","Failed to save settings: {{error}}",{error:xe}),"error")}return!1}finally{Ae===vt.current&&Zt(!1)}},[l,t.id,as,o,i,De]),Bs=async()=>{await at(!0,"manual")},de=a.useCallback(()=>{if(!(!Me||_e)){if(Object.keys(De).length>0){Ve(De);return}at(!1,"auto")}},[Me,_e,at,De]);a.useEffect(()=>{if(!Me||_e)return;if(Object.keys(De).length>0){Ve(De);return}const r=setTimeout(()=>{at(!1,"auto")},Qa);return()=>clearTimeout(r)},[Me,_e,at,De]);const $s=a.useCallback(async r=>{D(!0);try{await ya(t.id,r,i),await o(),l(n("agents.avatarUploaded","Avatar uploaded"),"success")}catch(f){l(U(f),"error")}finally{D(!1),Y.current&&(Y.current.value="")}},[l,t.id,o,i]),Os=a.useCallback(async()=>{D(!0);try{await Na(t.id,i),await o(),l(n("agents.avatarRemoved","Avatar removed"),"success")}catch(r){l(U(r),"error")}finally{D(!1)}},[l,t.id,o,i]),ns=_e?n("agents.savingChanges","Saving changes…"):Tt?n("agents.saveFailed","Save failed: {{error}}",{error:Tt}):!Me&&Hs?n("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:n("agents.configTitle","Agent Configuration")}),e.jsx("p",{className:"config-description",children:n("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:()=>V(!0),children:n("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:n("agents.nameLabel","Name")}),e.jsx("input",{id:"agent-name",type:"text",className:"input",value:g,onChange:r=>u(r.target.value),onBlur:()=>{de()}})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-role",children:n("agents.roleLabel2","Role")}),e.jsxs("select",{id:"agent-role",className:"select",value:y,onChange:r=>{c(r.target.value),de()},children:[e.jsx("option",{value:"triage",children:n("agents.roleTriage","Triage")}),e.jsx("option",{value:"executor",children:n("agents.roleExecutor","Executor")}),e.jsx("option",{value:"reviewer",children:n("agents.roleReviewer","Reviewer")}),e.jsx("option",{value:"merger",children:n("agents.roleMerger","Merger")}),e.jsx("option",{value:"scheduler",children:n("agents.roleScheduler","Scheduler")}),e.jsx("option",{value:"custom",children:n("agents.roleCustom","Custom")})]})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-title",children:n("agents.titleLabel","Title")}),e.jsx("input",{id:"agent-title",type:"text",className:"input",placeholder:n("agents.titlePlaceholder","e.g. Senior Code Reviewer"),value:m,onChange:r=>M(r.target.value),onBlur:()=>{de()}})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{children:n("agents.avatarLabel","Avatar")}),e.jsxs("div",{className:"agent-avatar-editor",children:[e.jsx(ks,{agent:t,size:64,className:"agent-avatar-editor-preview"}),e.jsxs("div",{className:"agent-avatar-editor-actions",children:[e.jsx("input",{ref:Y,id:"agent-avatar-upload",type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",className:"visually-hidden",disabled:C,onChange:r=>{const f=r.target.files?.[0];f&&$s(f)}}),e.jsx("button",{type:"button",className:"btn btn-sm",disabled:C,onClick:()=>Y.current?.click(),children:n("agents.uploadAvatar","Upload Avatar")}),t.imageUrl?e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void Os(),disabled:C,children:n("agents.removeAvatar","Remove Avatar")}):null]})]})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-icon",children:n("agents.iconLabel","Icon")}),e.jsx("input",{id:"agent-icon",type:"text",className:"input",placeholder:n("agents.iconPlaceholder","e.g. 🤖"),value:P,onChange:r=>L(r.target.value),onBlur:()=>{de()}})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-reports-to",children:n("agents.reportsToLabel","Reports To")}),e.jsxs("select",{id:"agent-reports-to",className:"select",value:w,onChange:r=>{Q(r.target.value),de()},disabled:k,children:[e.jsx("option",{value:"",children:n("agents.noManager","No manager")}),At&&e.jsx("option",{value:Oe,children:n("agents.unknownManager","Unknown manager ({{id}})",{id:Oe})}),et.map(r=>e.jsxs("option",{value:r.id,children:[r.name," (",r.id,")"]},r.id))]})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:n("agents.skillsTitle","Skills")}),e.jsx("p",{className:"config-description",children:n("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(Da,{id:"agent-skills",label:"Skills",value:Te,onChange:r=>{Ne(r),de()},projectId:i})})})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:n("agents.modelTitle","Model")}),e.jsx("p",{className:"config-description",children:n("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:n("agents.runtimeSource","Runtime Source")}),e.jsxs("div",{className:"config-runtime-tabs",role:"tablist","aria-label":n("agents.runtimeSource","Runtime source"),children:[e.jsx("button",{type:"button",className:`config-runtime-tab${fe==="model"?" active":""}`,role:"tab","aria-selected":fe==="model",tabIndex:fe==="model"?0:-1,onClick:()=>{$e("model"),$(""),de()},children:n("agents.builtInModel","Built-in Model")}),e.jsx("button",{type:"button",className:`config-runtime-tab${fe==="runtime"?" active":""}`,role:"tab","aria-selected":fe==="runtime",tabIndex:fe==="runtime"?0:-1,onClick:()=>{$e("runtime"),de()},children:n("agents.pluginRuntime","Plugin Runtime")})]})]}),fe==="model"?e.jsx("div",{className:"config-field",children:e.jsx(Sa,{models:Be,value:b,onChange:r=>{H(r),de()},placeholder:n("agents.useGlobalDefault","Use global default"),label:n("agents.agentModelLabel","Agent Model"),disabled:ht,favoriteProviders:gt,onToggleFavorite:Ft,favoriteModels:Ze,onToggleModelFavorite:Qe})}):e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-runtime-hint",children:n("agents.runtimeLabel","Runtime")}),bt?e.jsx("span",{className:"config-hint",children:e.jsx(ka,{label:n("agents.loadingRuntimes","Loading runtimes…")})}):e.jsxs("select",{id:"agent-runtime-hint",className:"select",value:B,onChange:r=>{$(r.target.value),de()},children:[e.jsx("option",{value:"",children:Ue.length>0?n("agents.selectRuntime","Select a plugin runtime…"):n("agents.noRuntimes","No plugin runtimes available")}),Ue.map(r=>e.jsx("option",{value:r.runtimeId,children:r.description?`${r.name} — ${r.description}`:r.name},`${r.pluginId}:${r.runtimeId}`))]})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:n("agents.permissionsTitle","Permissions")}),e.jsx("p",{className:"config-description",children:n("agents.permissionsDescription","Per-agent settings override project defaults. Each category controls a separate approval gate.")}),re===void 0?e.jsxs("div",{className:"agent-permission-inherit-banner",children:[e.jsx("span",{children:n("agents.inheritingProjectDefault","Inheriting project default — no per-agent override set")}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void me({presetId:"custom",rules:{git_write:ge?.rules?.git_write??"allow",file_write_delete:ge?.rules?.file_write_delete??"allow",command_execution:ge?.rules?.command_execution??"allow",network_api:ge?.rules?.network_api??"allow",task_agent_mutation:ge?.rules?.task_agent_mutation??"allow"}}),children:n("agents.customizeForAgent","Customize for this agent")})]}):null,e.jsx(Ia,{mode:"agent-override",value:re,projectDefault:ge?.rules,projectDefaultToolRules:ge?.toolRules,onChange:r=>{me(r)}})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:n("agents.heartbeatSettingsTitle","Heartbeat Settings")}),e.jsx("p",{className:"config-description",children:n("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:n("agents.coordinationOnlyAgent","Coordination-only agent")}),e.jsx("span",{className:"config-hint",children:n("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:()=>{j(!1),ee(r=>({...r,autoClaimCandidatesInPrompt:"0"})),de()},children:n("agents.applyPreset","Apply preset")})]}),e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-autoClaimRelevantTasks",children:[e.jsx("input",{id:"hb-autoClaimRelevantTasks",type:"checkbox",checked:p,onChange:r=>{j(r.target.checked),de()}}),n("agents.autoClaimRelevantTasks","Auto-Claim Relevant Tasks")]}),e.jsx("span",{className:"config-hint",children:n("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:d,onChange:r=>{z(r.target.checked),de()}}),n("agents.engineerBacklogAutoClaim","Engineer Backlog Auto-Claim")]}),e.jsx("span",{className:"config-hint",children:n("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.jsxs("label",{className:"checkbox-label",htmlFor:"hb-enabled",children:[e.jsx("input",{id:"hb-enabled",type:"checkbox",checked:A,onChange:r=>{Is(r.target.checked),de()}}),n("agents.heartbeatEnabled","Heartbeat Enabled")]}),e.jsx("span",{className:"config-hint",children:n("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:_,onChange:r=>{Ce(r.target.checked),de()}}),n("agents.runMissedHeartbeat","Run Missed Heartbeat On Startup")]}),e.jsx("span",{className:"config-hint",children:n("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:ue,onChange:r=>{je(r.target.checked),de()}}),n("agents.allowParallelExecution","Allow Parallel Execution")]}),e.jsx("span",{className:"config-hint",children:n("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:we,onChange:r=>{ye(r.target.checked),de()}}),n("agents.skipHeartbeatWhenIdle","Skip heartbeat when idle")]}),e.jsx("span",{className:"config-hint",children:n("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:n("agents.heartbeatScopeDiscipline","Heartbeat Scope Discipline")}),e.jsxs("select",{id:"hb-heartbeatScopeDiscipline",className:"select",value:pe,onChange:r=>{const f=r.target.value;O(f==="strict"||f==="lite"||f==="off"?f:""),de()},children:[e.jsx("option",{value:"",children:n("agents.inheritProjectDefault","Inherit project default")}),e.jsx("option",{value:"strict",children:n("agents.strict","Strict")}),e.jsx("option",{value:"lite",children:n("agents.lite","Lite")}),e.jsx("option",{value:"off",children:n("agents.off","Off")})]}),e.jsx("span",{className:"config-hint",children:n("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:n("agents.heartbeatPromptTemplate","Heartbeat Prompt Template")}),e.jsxs("select",{id:"hb-heartbeatPromptTemplate",className:"select",value:se,onChange:r=>{const f=r.target.value;x(f==="default"||f==="compact"?f:""),de()},children:[e.jsx("option",{value:"",children:n("agents.inheritProjectDefault","Inherit project default")}),e.jsx("option",{value:"default",children:n("agents.templateDefault","Default")}),e.jsx("option",{value:"compact",children:n("agents.templateCompact","Compact")})]})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-heartbeatIntervalMs",children:n("agents.heartbeatIntervalLabel","Heartbeat Interval (s)")}),e.jsx("input",{id:"hb-heartbeatIntervalMs",type:"text",inputMode:"numeric",className:oe("input",!!G.heartbeatIntervalMs&&"input--error"),placeholder:String(Wt/1e3),value:F.heartbeatIntervalMs??"",onChange:r=>jt("heartbeatIntervalMs",r.target.value)}),G.heartbeatIntervalMs?e.jsx("span",{className:"config-error",children:G.heartbeatIntervalMs}):e.jsx("span",{className:"config-hint",children:n("agents.heartbeatIntervalHint","How often heartbeats are checked. Leave empty for system default ({{seconds}}s / {{label}}).",{seconds:Wt/1e3,label:Za})})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-heartbeatTimeoutMs",children:n("agents.heartbeatTimeoutLabel","Heartbeat Timeout (s)")}),e.jsx("input",{id:"hb-heartbeatTimeoutMs",type:"text",inputMode:"numeric",className:oe("input",!!G.heartbeatTimeoutMs&&"input--error"),placeholder:"60",value:F.heartbeatTimeoutMs??"",onChange:r=>jt("heartbeatTimeoutMs",r.target.value)}),G.heartbeatTimeoutMs?e.jsx("span",{className:"config-error",children:G.heartbeatTimeoutMs}):e.jsx("span",{className:"config-hint",children:n("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:n("agents.maxConcurrentRunsLabel","Max Concurrent Runs")}),e.jsx("input",{id:"hb-maxConcurrentRuns",type:"text",inputMode:"numeric",className:oe("input",!!G.maxConcurrentRuns&&"input--error"),placeholder:"1",value:F.maxConcurrentRuns??"",onChange:r=>jt("maxConcurrentRuns",r.target.value)}),G.maxConcurrentRuns?e.jsx("span",{className:"config-error",children:G.maxConcurrentRuns}):e.jsx("span",{className:"config-hint",children:n("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:n("agents.messageResponseModeLabel","Message Response Mode")}),e.jsxs("select",{id:"hb-messageResponseMode",className:oe("select",!!G.messageResponseMode&&"input--error"),value:F.messageResponseMode??"",onChange:r=>jt("messageResponseMode",r.target.value),children:[e.jsx("option",{value:"",children:n("agents.systemDefaultOnHeartbeat","System Default (On Heartbeat)")}),e.jsx("option",{value:"on-heartbeat",children:n("agents.onHeartbeat","On Heartbeat")}),e.jsx("option",{value:"immediate",children:n("agents.immediate","Immediate")})]}),G.messageResponseMode?e.jsx("span",{className:"config-error",children:G.messageResponseMode}):e.jsx("span",{className:"config-hint",children:n("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:n("agents.budgetSettingsTitle","Budget Settings")}),e.jsx("p",{className:"config-description",children:n("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:n("agents.tokenBudgetLabel","Token Budget")}),e.jsx("input",{id:"budget-tokenBudget",type:"text",inputMode:"numeric",className:oe("input",!!G.tokenBudget&&"input--error"),placeholder:n("agents.noLimit","No limit"),value:v.tokenBudget??"",onChange:r=>yt("tokenBudget",r.target.value)}),G.tokenBudget?e.jsx("span",{className:"config-error",children:G.tokenBudget}):e.jsx("span",{className:"config-hint",children:n("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:n("agents.usageThresholdLabel","Usage Threshold (%)")}),e.jsx("input",{id:"budget-usageThreshold",type:"text",inputMode:"numeric",className:oe("input",!!G.usageThreshold&&"input--error"),placeholder:"80",value:v.usageThreshold??"",onChange:r=>yt("usageThreshold",r.target.value)}),G.usageThreshold?e.jsx("span",{className:"config-error",children:G.usageThreshold}):e.jsx("span",{className:"config-hint",children:n("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:n("agents.budgetPeriodLabel","Budget Period")}),e.jsxs("select",{id:"budget-budgetPeriod",className:oe("select",!!G.budgetPeriod&&"input--error"),value:v.budgetPeriod??"",onChange:r=>yt("budgetPeriod",r.target.value),children:[e.jsx("option",{value:"",children:n("agents.noReset","No reset (lifetime)")}),e.jsx("option",{value:"daily",children:n("agents.daily","Daily")}),e.jsx("option",{value:"weekly",children:n("agents.weekly","Weekly")}),e.jsx("option",{value:"monthly",children:n("agents.monthly","Monthly")})]}),G.budgetPeriod?e.jsx("span",{className:"config-error",children:G.budgetPeriod}):e.jsx("span",{className:"config-hint",children:n("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:n("agents.resetDayLabel","Reset Day")}),e.jsx("input",{id:"budget-resetDay",type:"text",inputMode:"numeric",className:oe("input",!!G.resetDay&&"input--error"),placeholder:n("agents.auto","Auto"),value:v.resetDay??"",onChange:r=>yt("resetDay",r.target.value)}),G.resetDay?e.jsx("span",{className:"config-error",children:G.resetDay}):e.jsx("span",{className:"config-hint",children:v.budgetPeriod==="weekly"?n("agents.resetDayWeekly","Day of week (0=Sunday to 6=Saturday) for reset."):v.budgetPeriod==="monthly"?n("agents.resetDayMonthly","Day of month (1-31) for reset."):n("agents.resetDayHint","Day for reset (weekly: 0-6, monthly: 1-31). Leave empty for automatic.")})]}),Se?.budgetLimit!=null&&e.jsxs("div",{className:"config-field",children:[e.jsx("label",{children:n("agents.currentUsage","Current Usage")}),e.jsxs("div",{className:"budget-progress-container",children:[e.jsx("div",{className:"budget-progress-bar",children:e.jsx("div",{className:oe("budget-progress-bar__fill",(Se.usagePercent??0)>=100?"budget-progress-bar__fill--red":(Se.usagePercent??0)>=80?"budget-progress-bar__fill--amber":"budget-progress-bar__fill--green"),style:{width:`${Math.min(Se.usagePercent??0,100)}%`}})}),e.jsx("span",{className:"budget-progress-label",children:n("agents.budgetUsageDisplay","{{used}} / {{limit}} tokens ({{percent}}% used)",{used:(Se.currentUsage??0).toLocaleString(),limit:(Se.budgetLimit??0).toLocaleString(),percent:Math.round(Se.usagePercent??0)})})]})]}),Se?.budgetLimit!=null&&e.jsx("div",{className:"config-field",children:e.jsx("button",{className:"btn btn-reset-budget",onClick:()=>void zs(),disabled:Kt,children:Kt?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:14,className:"animate-spin"}),n("agents.resetting","Resetting…")]}):e.jsxs(e.Fragment,{children:[e.jsx(Mt,{size:14}),n("agents.resetBudgetUsage","Reset Budget Usage")]})})})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:n("agents.bundleTitle","Instruction Bundle")}),e.jsx("p",{className:"config-description",children:n("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:n("agents.bundleModeLabel","Bundle Mode")}),e.jsxs("select",{id:"bundle-mode",className:"select",value:ae,onChange:r=>We(r.target.value),children:[e.jsx("option",{value:"",children:n("agents.bundleNone","None (use inline instructions)")}),e.jsx("option",{value:"managed",children:n("agents.bundleManaged","Managed (system-managed directory)")}),e.jsx("option",{value:"external",children:n("agents.bundleExternal","External (user-specified path)")})]}),e.jsxs("span",{className:"config-hint",children:[ae==="managed"&&n("agents.bundleManagedHint","Files will be stored in a system-managed directory within .fusion/agents/"),ae==="external"&&n("agents.bundleExternalHint","Specify an external directory path for the instruction files"),!ae&&n("agents.bundleSelectMode","Select a mode to enable instruction bundling")]})]}),ae&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-entry-file",children:n("agents.bundleEntryFileLabel","Entry File")}),e.jsx("input",{id:"bundle-entry-file",type:"text",className:"input",placeholder:"AGENTS.md",value:ze,onChange:r=>Fe(r.target.value)}),e.jsx("span",{className:"config-hint",children:n("agents.bundleEntryFileHint","Primary instructions file name (default: AGENTS.md)")})]}),ae==="external"&&e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-external-path",children:n("agents.bundleExternalPathLabel","External Path")}),e.jsx("input",{id:"bundle-external-path",type:"text",className:"input",placeholder:n("agents.bundleExternalPathPlaceholder","e.g. .fusion/agents/my-agent"),value:ce,onChange:r=>Pe(r.target.value)}),e.jsx("span",{className:"config-hint",children:n("agents.bundleExternalPathHint","Absolute or relative path to the external directory")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-files",children:n("agents.bundleFilesLabel","Files (comma-separated)")}),e.jsx("input",{id:"bundle-files",type:"text",className:"input",placeholder:"AGENTS.md, PROMPTS.md",value:ne.join(", "),onChange:r=>mt(r.target.value.split(",").map(f=>f.trim()).filter(Boolean))}),e.jsx("span",{className:"config-hint",children:n("agents.bundleFilesHint","List of file names in the bundle directory")})]})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:n("agents.advancedSettingsTitle","Advanced Settings")}),e.jsx("p",{className:"config-description",children:n("agents.advancedSettingsDesc","Advanced configuration options for this agent. Leave a field empty to use system defaults.")}),e.jsx("div",{className:"config-fields",children:it.map(r=>{const f=!!G[r.key];return e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:`adv-${r.key}`,children:r.label}),r.type==="select"?e.jsxs("select",{id:`adv-${r.key}`,className:oe("select",f&&"input--error"),value:I[r.key]??"",onChange:E=>ss(r.key,E.target.value),children:[e.jsx("option",{value:"",children:n("agents.systemDefault","System Default")}),r.options?.map(E=>e.jsx("option",{value:E.value,children:E.label},E.value))]}):e.jsx("input",{id:`adv-${r.key}`,type:"text",inputMode:r.type==="number"?"numeric":void 0,className:oe("input",f&&"input--error"),placeholder:r.placeholder,value:I[r.key]??"",onChange:E=>ss(r.key,E.target.value)}),f&&e.jsx("span",{className:"config-error",children:G[r.key]}),!f&&r.hint&&e.jsx("span",{className:"config-hint",children:r.hint})]},r.key)})}),e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!Me||_e,onClick:()=>void Bs(),children:_e?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),n("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(he,{size:16}),n("agents.saveSettings","Save Settings")]})}),ns&&e.jsxs("span",{className:oe("config-saved-indicator",Tt&&"config-saved-indicator--error"),children:[_e?e.jsx(q,{size:14,className:"animate-spin"}):e.jsx(he,{size:14}),ns]})]})]}),e.jsx(gn,{agent:t,projectId:i,addToast:l,onSaved:o}),e.jsxs("div",{className:"config-section config-section--danger",children:[e.jsx("h3",{children:n("agents.dangerZone","Danger Zone")}),e.jsx("p",{className:"config-description",children:n("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:!Qt||!h,onClick:()=>void h?.(),children:[e.jsx(rt,{size:16}),n("agents.deleteAgent","Delete Agent")]}),e.jsx("span",{className:"config-danger-note",children:Qt?n("agents.deletionPermanent","Deletion is permanent and cannot be undone."):n("agents.deletionNotAvailable","Agent deletion is only available when state is idle or paused (current state: {{state}}).",{state:t.state})})]})})]}),e.jsx(za,{isOpen:T,onClose:()=>V(!1),onUseDraft:pt,projectId:i,existingAgents:J,mode:"edit",existingAgentConfig:Pt})]})}function fn({agentId:t,projectId:i,onChildClick:l}){const{t:o}=ke("app"),[s,h]=a.useState([]),[N,n]=a.useState(!0);return a.useEffect(()=>{n(!0),fa(t,i).then(h).finally(()=>n(!1))},[t,i]),N?e.jsxs("div",{className:"detail-section",children:[e.jsx("div",{className:"detail-section-header",children:e.jsx("h3",{children:o("agents.employeesTitle","Employees")})}),e.jsxs("div",{className:"detail-section-body detail-section-body--loading",children:[e.jsx(q,{size:16,className:"spin"}),e.jsx("span",{className:"text-muted",children:o("agents.loadingEmployees","Loading employees...")})]})]}):e.jsxs("div",{className:"detail-section",children:[e.jsxs("div",{className:"detail-section-header",children:[e.jsx("h3",{children:o("agents.employeesTitle","Employees")}),e.jsxs("span",{className:"text-muted",children:["(",s.length,")"]})]}),e.jsx("div",{className:"detail-section-body",children:s.length===0?e.jsxs("div",{className:"agent-empty agent-empty--padded",children:[e.jsx(Rs,{size:32,opacity:.3}),e.jsx("p",{children:o("agents.noEmployees","No employees")}),e.jsx("p",{className:"text-muted",children:o("agents.noEmployeesDesc","This agent has no employees")})]}):e.jsx("div",{className:"agent-tree__children",children:s.map(g=>{const u=Gt[g.state];return e.jsxs("div",{className:"agent-tree__node agent-is-child",onClick:()=>l?.(g.id),role:"button",tabIndex:0,onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.key===" "&&y.preventDefault(),l?.(g.id))},style:{cursor:l?"pointer":"default"},children:[e.jsx("span",{className:"agent-tree__icon",children:g.icon??"🤖"}),e.jsx("span",{className:"agent-tree__name",children:g.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:g.state})]},g.id)})})})]})}export{Cn as AgentDetailView,Ye as relativeTime};