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