@runfusion/fusion 0.58.0 → 0.59.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/README.md +2 -3
- package/dist/bin.js +16894 -14563
- package/dist/client/.vite/manifest.json +247 -244
- package/dist/client/assets/AgentDetailView-UmilJU0C.js +18 -0
- package/dist/client/assets/{AgentPermissionPolicyEditor-3x5cc2cp.js → AgentPermissionPolicyEditor-DqYOX1kN.js} +1 -1
- package/dist/client/assets/{AgentsView-B77vHi_7.js → AgentsView-Dt0nKyx7.js} +4 -4
- package/dist/client/assets/ChatView-C7trV16u.js +6 -0
- package/dist/client/assets/CommandCenter-DSrIaOro.css +1 -0
- package/dist/client/assets/CommandCenter-Dsg16_mK.js +99 -0
- package/dist/client/assets/{DevServerView-BXmkO05R.js → DevServerView-DnpnAU_g.js} +1 -1
- package/dist/client/assets/{DirectoryPicker-CZ3EXSE5.js → DirectoryPicker-BzpWdpTC.js} +1 -1
- package/dist/client/assets/{DocumentsView-BSWFgTsC.css → DocumentsView-BSC7wh2B.css} +1 -1
- package/dist/client/assets/{DocumentsView-GlAyW64J.js → DocumentsView-C2jRDIo6.js} +2 -2
- package/dist/client/assets/{EvalsView-BLmcsNNf.js → EvalsView-M1nIXx-S.js} +1 -1
- package/dist/client/assets/ExperimentalAgentOnboardingModal-5Kg2iQtB.js +1 -0
- package/dist/client/assets/{GoalsView-BRfZ4qGe.js → GoalsView-7bFpy-lr.js} +1 -1
- package/dist/client/assets/InsightsView-D0HPy3RP.js +11 -0
- package/dist/client/assets/{MemoryView-ChkuBpUf.js → MemoryView-CNzJcoPi.js} +2 -2
- package/dist/client/assets/{PiExtensionsManager-DXwQdB7b.js → PiExtensionsManager-D0a8Q47c.js} +1 -1
- package/dist/client/assets/{PluginManager-B8zAjhqf.js → PluginManager-N2Ne57i_.js} +1 -1
- package/dist/client/assets/{PullRequestView-DL1E1ixh.js → PullRequestView-Be4GM2H5.js} +2 -2
- package/dist/client/assets/{ResearchView-BCYCHiyQ.js → ResearchView-DYW9ViMl.js} +1 -1
- package/dist/client/assets/SecretsView-B3jEFeGp.js +1 -0
- package/dist/client/assets/{SessionTerminal-BvK8A98c.css → SessionTerminal-CDTiqrd7.css} +1 -1
- package/dist/client/assets/SessionTerminal-DGFADOH4.js +2 -0
- package/dist/client/assets/SettingsModal-CtOCCZEj.js +21 -0
- package/dist/client/assets/{SettingsModal-U7ma-5OU.js → SettingsModal-Lw0RmeRd.js} +1 -1
- package/dist/client/assets/{SetupWizardModal-BCDoA33s.js → SetupWizardModal-BifMmJIa.js} +2 -2
- package/dist/client/assets/{ShadcnColorPicker-EVU2cXpo.js → ShadcnColorPicker-B1UClHqm.js} +2 -2
- package/dist/client/assets/{SkillsView-V48VsthB.js → SkillsView--U-5lH1V.js} +1 -1
- package/dist/client/assets/TodoView-BwxNdIXm.js +6 -0
- package/dist/client/assets/TodoView-CUD4xw3T.css +1 -0
- package/dist/client/assets/WorkflowNodeEditor-BmTZR0i8.js +8 -0
- package/dist/client/assets/{agentSkills-B-QDeW2q.js → agentSkills-PqEK0Uf_.js} +1 -1
- package/dist/client/assets/{app-SucmTDhV.js → app-BlgX3hw4.js} +3 -3
- package/dist/client/assets/{app-RIK4I745.js → app-C7eDKtXM.js} +3 -3
- package/dist/client/assets/{app-SHNioZxk.js → app-CL1Ik1qS.js} +3 -3
- package/dist/client/assets/{app-De_pkbYi.js → app-Ckb9wA3K.js} +3 -3
- package/dist/client/assets/{app-cZgmPvs6.js → app-Den3D7oy.js} +3 -3
- package/dist/client/assets/{app--U62_ZWS.js → app-nAsTBQMW.js} +3 -3
- package/dist/client/assets/{architectureDiagram-3BPJPVTR-DvR35aCH.js → architectureDiagram-3BPJPVTR-DxAKryer.js} +1 -1
- package/dist/client/assets/{blockDiagram-GPEHLZMM-ciQdpSqc.js → blockDiagram-GPEHLZMM-BfPC7WG4.js} +1 -1
- package/dist/client/assets/{c4Diagram-AAUBKEIU-CV0Z6UEL.js → c4Diagram-AAUBKEIU-DnVJBAB1.js} +1 -1
- package/dist/client/assets/channel-D23u9xEh.js +1 -0
- package/dist/client/assets/{chunk-2J33WTMH-CkAQRX3g.js → chunk-2J33WTMH-2LaGYtnx.js} +1 -1
- package/dist/client/assets/{chunk-4BX2VUAB-CJXvYVcN.js → chunk-4BX2VUAB-C7xxOb1T.js} +1 -1
- package/dist/client/assets/{chunk-55IACEB6-DOv0lN1u.js → chunk-55IACEB6-CAxHAFXx.js} +1 -1
- package/dist/client/assets/{chunk-727SXJPM-tRsHXz7i.js → chunk-727SXJPM-CnZuaU-I.js} +1 -1
- package/dist/client/assets/{chunk-AQP2D5EJ-CfzOMXn9.js → chunk-AQP2D5EJ-DutKSMk1.js} +1 -1
- package/dist/client/assets/{chunk-FMBD7UC4-BKvUZ2cn.js → chunk-FMBD7UC4-C7PQ58jc.js} +1 -1
- package/dist/client/assets/{chunk-ND2GUHAM-FqiVnW7u.js → chunk-ND2GUHAM-BQ0UHfJw.js} +1 -1
- package/dist/client/assets/{chunk-QZHKN3VN-BAJDyCpZ.js → chunk-QZHKN3VN-BadmXu1v.js} +1 -1
- package/dist/client/assets/classDiagram-4FO5ZUOK-BMIDIijD.js +1 -0
- package/dist/client/assets/classDiagram-v2-Q7XG4LA2-BMIDIijD.js +1 -0
- package/dist/client/assets/{cose-bilkent-S5V4N54A-DYizdcNp.js → cose-bilkent-S5V4N54A-37z9Hx7d.js} +1 -1
- package/dist/client/assets/{dagre-BM42HDAG-BDWwvXJx.js → dagre-BM42HDAG-B70rt1ZW.js} +1 -1
- package/dist/client/assets/{dashboard-view-BYn_jRw9.js → dashboard-view-DdAL0vfN.js} +1 -1
- package/dist/client/assets/{dashboard-view-DmfIFCV-.js → dashboard-view-GT7dDNd7.js} +1 -1
- package/dist/client/assets/{diagram-2AECGRRQ-C8ic2E9q.js → diagram-2AECGRRQ-se4pabEk.js} +1 -1
- package/dist/client/assets/{diagram-5GNKFQAL-H5IDcv9E.js → diagram-5GNKFQAL-ijyxpVgX.js} +1 -1
- package/dist/client/assets/{diagram-KO2AKTUF-DkczJXd6.js → diagram-KO2AKTUF-DUGQ8jXI.js} +1 -1
- package/dist/client/assets/{diagram-LMA3HP47-P1vh7RIU.js → diagram-LMA3HP47-BYydC37K.js} +1 -1
- package/dist/client/assets/{diagram-OG6HWLK6-CgeybA5t.js → diagram-OG6HWLK6-DlUn5jkD.js} +1 -1
- package/dist/client/assets/{erDiagram-TEJ5UH35-DSJa4zRQ.js → erDiagram-TEJ5UH35-ChYKGDIc.js} +1 -1
- package/dist/client/assets/{flowDiagram-I6XJVG4X-DG91ZWS9.js → flowDiagram-I6XJVG4X-CoQKr6ba.js} +1 -1
- package/dist/client/assets/{folder-open-iGyAYoN-.js → folder-open-YuIEuDwd.js} +1 -1
- package/dist/client/assets/{ganttDiagram-6RSMTGT7-dkOQjOK8.js → ganttDiagram-6RSMTGT7-Cff6URun.js} +1 -1
- package/dist/client/assets/{gitGraphDiagram-PVQCEYII-GqrJtmDT.js → gitGraphDiagram-PVQCEYII-CnlZVE6T.js} +1 -1
- package/dist/client/assets/index-C2HFa2A-.css +1 -0
- package/dist/client/assets/index-aBQwNV_I.js +2540 -0
- package/dist/client/assets/{infoDiagram-5YYISTIA-BfFhhqbU.js → infoDiagram-5YYISTIA-DYLBAKrj.js} +1 -1
- package/dist/client/assets/{ishikawaDiagram-YF4QCWOH-DBBV-PIS.js → ishikawaDiagram-YF4QCWOH-7xSxQNhn.js} +1 -1
- package/dist/client/assets/{journeyDiagram-JHISSGLW-xZisXOgZ.js → journeyDiagram-JHISSGLW-DREqJGeQ.js} +1 -1
- package/dist/client/assets/{kanban-definition-UN3LZRKU-CbOJloOw.js → kanban-definition-UN3LZRKU-_lzeYhpL.js} +1 -1
- package/dist/client/assets/{mermaid.core-DKBiVV3q.js → mermaid.core-DNTJMy0V.js} +4 -4
- package/dist/client/assets/{mindmap-definition-RKZ34NQL-Bf9V63ac.js → mindmap-definition-RKZ34NQL-DR9UulDp.js} +1 -1
- package/dist/client/assets/{pieDiagram-4H26LBE5-0ukMaTVl.js → pieDiagram-4H26LBE5-DD1LCdSp.js} +1 -1
- package/dist/client/assets/{puzzle-BvEf9PLH.js → puzzle-DaVSYDOd.js} +1 -1
- package/dist/client/assets/{quadrantDiagram-W4KKPZXB-CwXZAtYI.js → quadrantDiagram-W4KKPZXB-iLEGylFT.js} +1 -1
- package/dist/client/assets/{requirementDiagram-4Y6WPE33-DVsu9t-w.js → requirementDiagram-4Y6WPE33-D7IX9UbY.js} +1 -1
- package/dist/client/assets/{sankeyDiagram-5OEKKPKP-DOJUnv7J.js → sankeyDiagram-5OEKKPKP-DC30taEV.js} +1 -1
- package/dist/client/assets/{sequenceDiagram-3UESZ5HK-B67g0g9m.js → sequenceDiagram-3UESZ5HK-DjMKbjmL.js} +1 -1
- package/dist/client/assets/{shield-alert-4FPCIFZ2.js → shield-alert-BcyPZs5t.js} +1 -1
- package/dist/client/assets/{stateDiagram-AJRCARHV-CPPa0bHh.js → stateDiagram-AJRCARHV-DJSnSkUL.js} +1 -1
- package/dist/client/assets/{stateDiagram-v2-BHNVJYJU-Dyj14elw.js → stateDiagram-v2-BHNVJYJU-KC2rSU3J.js} +1 -1
- package/dist/client/assets/{timeline-definition-PNZ67QCA-UVWf2E8M.js → timeline-definition-PNZ67QCA-5DyrH8WZ.js} +1 -1
- package/dist/client/assets/{upload-BkgVjwwc.js → upload-C_8IHSzk.js} +1 -1
- package/dist/client/assets/{users-9nCT4liw.js → users-DfGiwmqG.js} +1 -1
- package/dist/client/assets/{vennDiagram-CIIHVFJN-CqGrv1wQ.js → vennDiagram-CIIHVFJN-Bh5X-uVf.js} +1 -1
- package/dist/client/assets/{wardley-L42UT6IY-aA0pos_F.js → wardley-L42UT6IY-ZIwV-wIZ.js} +1 -1
- package/dist/client/assets/{wardleyDiagram-YWT4CUSO-C-O5tD1L.js → wardleyDiagram-YWT4CUSO-DI92L1jA.js} +1 -1
- package/dist/client/assets/{xychartDiagram-2RQKCTM6-qoIF674C.js → xychartDiagram-2RQKCTM6-B6RjJCM8.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 +12961 -11668
- package/dist/pi-claude-cli/package.json +1 -1
- package/dist/plugin-sdk/index.d.ts +20 -1
- package/dist/plugins/fusion-plugin-acp-runtime/bundled.js +4 -1
- package/dist/plugins/fusion-plugin-acp-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-cli-printing-press/package.json +1 -1
- package/dist/plugins/fusion-plugin-compound-engineering/package.json +1 -1
- package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
- package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-grok-runtime/bundled.js +4 -1
- package/dist/plugins/fusion-plugin-grok-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-linear-import/package.json +1 -1
- package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-reports/package.json +1 -1
- package/dist/plugins/fusion-plugin-reports/src/dashboard/components/ShareBlocksPanel.tsx +4 -1
- package/dist/plugins/fusion-plugin-reports/src/dashboard/components/__tests__/ShareBlocksPanel.test.tsx +41 -2
- package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
- package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
- package/package.json +1 -1
- package/skill/fusion/SKILL.md +1 -1
- package/skill/fusion/references/engine-tools.md +1 -0
- package/skill/fusion/references/extension-tools.md +10 -0
- package/skill/fusion/references/fusion-capabilities.md +1 -0
- package/dist/client/assets/AgentDetailView-whCXABbu.js +0 -18
- package/dist/client/assets/ChatView-CninsTIm.js +0 -6
- package/dist/client/assets/CommandCenter-B9q-zM9p.css +0 -1
- package/dist/client/assets/CommandCenter-C6LmdUin.js +0 -71
- package/dist/client/assets/ExperimentalAgentOnboardingModal-DvDix9pH.js +0 -1
- package/dist/client/assets/InsightsView-X4RlcgrU.js +0 -11
- package/dist/client/assets/SecretsView-B48BIZKw.js +0 -1
- package/dist/client/assets/SessionTerminal-CUyYlq16.js +0 -2
- package/dist/client/assets/SettingsModal-DbjBoUYD.js +0 -21
- package/dist/client/assets/TodoView-DmpJmxu7.css +0 -1
- package/dist/client/assets/TodoView-MZ9Pfl65.js +0 -6
- package/dist/client/assets/WorkflowNodeEditor-B95Dvf-O.js +0 -8
- package/dist/client/assets/channel-Y_Uhrtqx.js +0 -1
- package/dist/client/assets/classDiagram-4FO5ZUOK-DhicwSPE.js +0 -1
- package/dist/client/assets/classDiagram-v2-Q7XG4LA2-DhicwSPE.js +0 -1
- package/dist/client/assets/index-Bg8SMXUs.css +0 -1
- package/dist/client/assets/index-DO9Ch72Y.js +0 -2544
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
import{r as a,j as e}from"./vendor-react-SZ_qB27O.js";import{c as Yt,bX as qs,bY as Ys,bZ as Ks,b_ as Zs,L as q,R as Rt,bE as os,Z as Qs,bn as Dt,b$ as js,u as lt,C as ys,e as Ns,c0 as Xs,c1 as ea,c2 as ta,ag as Ss,c3 as sa,c4 as aa,bj as U,c5 as na,c6 as ks,c7 as Cs,c8 as ia,bi as kt,c9 as zt,ak as Nt,bm as ws,a8 as Rs,ca as Ht,bB as Ct,cb as cs,cc as Ze,cd as ra,X as Ms,b6 as ot,ce as la,bl as As,cf as Fs,cg as oa,N as ca,q as da,ch as Ps,al as Ts,bo as Kt,ci as ua,cj as ds,ck as ma,cl as ga,cm as Gt,cn as Es,co as ha,b as fa,cp as pa,g as Ls,cq as Ds,a$ as ba,a9 as ge,cr as zs,cs as us,ct as ms,cu as xa,cv as va,cw as ja,cx as ya,cy as Mt,o as At,h as Ft,r as Pt,cz as Hs,cA as Na,cB as Sa,aV as ka,cC as Ca,cD as wa,cE as gs,bz as Ra,cF as It,cG as Ma,cH as Aa,bD as Fa,an as Pa,cI as qt,cJ as Ta,cK as Ea,cL as La,cM as Da,cN as za,cO as Is,cP as Ha,cQ as Ia,cR as Ba,cS as $a,cT as Oa}from"./index-DO9Ch72Y.js";import{u as Ne}from"./vendor-i18n-GF3RlKbq.js";import{f as Bt,S as _a}from"./agentSkills-B-QDeW2q.js";import{ExperimentalAgentOnboardingModal as Ua}from"./ExperimentalAgentOnboardingModal-DvDix9pH.js";import{B as Va,A as Wa}from"./AgentPermissionPolicyEditor-3x5cc2cp.js";import"./vendor-reactflow-9C3XTE7_.js";import"./vendor-codemirror-jBKmHyH0.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 Ja=[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M18 17V9",key:"2bz60n"}],["path",{d:"M13 17V5",key:"1frdt8"}],["path",{d:"M8 17v-3",key:"17ska0"}]],St=Yt("chart-column",Ja);/**
|
|
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 Ga=[["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"}]],qa=Yt("square-activity",Ga);/**
|
|
12
|
-
* @license lucide-react v1.7.0 - ISC
|
|
13
|
-
*
|
|
14
|
-
* This source code is licensed under the ISC license.
|
|
15
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
16
|
-
*/const Ya=[["path",{d:"M16 17h6v-6",key:"t6n2it"}],["path",{d:"m22 17-8.5-8.5-5 5L2 7",key:"x473p"}]],Ka=Yt("trending-down",Ya);function hs(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 Za(t){return`${Math.round(t*100)}%`}function fs(t,r){const l=Date.now(),o=new Date(t).getTime(),s=l-o;if(s<0){const f=Math.abs(s);return f<6e4?r("agents.time.inAMoment","in a moment"):f<36e5?r("agents.time.inMinutes","in {{count}}m",{count:Math.floor(f/6e4)}):f<864e5?r("agents.time.inHours","in {{count}}h",{count:Math.floor(f/36e5)}):r("agents.time.inDays","in {{count}}d",{count:Math.floor(f/864e5)})}return s<6e4?r("agents.time.justNow","just now"):s<36e5?r("agents.time.minutesAgo","{{count}}m ago",{count:Math.floor(s/6e4)}):s<864e5?r("agents.time.hoursAgo","{{count}}h ago",{count:Math.floor(s/36e5)}):r("agents.time.daysAgo","{{count}}d ago",{count:Math.floor(s/864e5)})}function Qa(t,r){switch(t){case"periodic":return r("agents.reflections.triggerPeriodic","Periodic");case"post-task":return r("agents.reflections.triggerPostTask","Post-Task");case"manual":return r("agents.reflections.triggerManual","Manual");case"user-requested":return r("agents.reflections.triggerUserRequested","User Requested");default:return t}}function it(t){return t instanceof Error&&t.message?t.message:String(t)}function Xa(t,r){switch(t){case"improving":return r("agents.ratings.trendImproving","↑ Improving");case"declining":return r("agents.ratings.trendDeclining","↓ Declining");case"stable":return r("agents.ratings.trendStable","→ Stable");default:return r("agents.ratings.trendInsufficient","Insufficient data")}}function en(t){switch(t){case"improving":return"trend-improving";case"declining":return"trend-declining";case"stable":return"trend-stable";default:return"trend-insufficient"}}function ps(t,r=5){return e.jsx("span",{className:"rating-stars",children:Array.from({length:r},(l,o)=>e.jsx(js,{size:14,className:o<t?"star-filled":"star-empty",fill:o<t?"currentColor":"none"},o))})}function tn({agentId:t,projectId:r,addToast:l}){const{t:o}=Ne("app"),[s,f]=a.useState([]),[k,n]=a.useState(null),[h,u]=a.useState(null),[j,c]=a.useState([]),[m,A]=a.useState(!0),[T,H]=a.useState(!0),[C,_]=a.useState(!1),[V,P]=a.useState(!1),[N,w]=a.useState(null),[S,E]=a.useState(0),[L,W]=a.useState(""),[Z,$]=a.useState(""),J=a.useCallback(async()=>{try{const[d,D]=await Promise.all([qs(t,20,r),Ys(t,void 0,r)]);f(d),n(D)}catch(d){l(o("agents.reflections.loadError","Failed to load reflections: {{error}}",{error:it(d)}),"error")}finally{A(!1)}},[t,r,l]),M=a.useCallback(async()=>{try{const[d,D]=await Promise.all([Ks(t,r),Zs(t,{limit:50},r)]);u(d),c(D)}catch(d){l(o("agents.ratings.loadError","Failed to load ratings: {{error}}",{error:it(d)}),"error")}finally{H(!1)}},[t,r,l]);a.useEffect(()=>{J(),M()},[J,M]);const se=async()=>{_(!0);try{if(!await Xs(t,r)){l(o("agents.reflections.insufficientHistory","Not enough history to generate a reflection yet"),"error");return}l(o("agents.reflections.generateSuccess","Reflection generated successfully"),"success"),A(!0),await J()}catch(d){const D=it(d),X=D.toLowerCase();X.includes("agent not found")||X.includes("not found")?l(o("agents.reflections.agentNotFound","This agent is no longer available. It may have been deleted."),"error"):X.includes("insufficient history")?l(o("agents.reflections.insufficientHistory","Not enough history to generate a reflection yet"),"error"):l(o("agents.reflections.generateError","Failed to generate reflection: {{error}}",{error:D}),"error")}finally{_(!1)}},F=async d=>{if(d.preventDefault(),S!==0){P(!0);try{await ea(t,{score:S,category:L||void 0,comment:Z||void 0,raterType:"user"},r),E(0),W(""),$(""),l(o("agents.ratings.addSuccess","Rating added"),"success"),await M()}catch(D){l(o("agents.ratings.addError","Failed to add rating: {{error}}",{error:it(D)}),"error")}finally{P(!1)}}},G=async d=>{try{await ta(t,d,r),l(o("agents.ratings.deleteSuccess","Rating deleted"),"success"),await M()}catch(D){l(o("agents.ratings.deleteError","Failed to delete rating: {{error}}",{error:it(D)}),"error")}},b=d=>{w(D=>D===d?null:d)};if(m&&T)return e.jsx("div",{className:"reflections-tab",children:e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(q,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:o("agents.reflections.loadingEvaluation","Loading evaluation...")})]})});const y=k&&k.totalTasksCompleted===0&&k.totalTasksFailed===0&&k.recentReflectionCount===0;return e.jsxs("div",{className:"reflections-tab",children:[e.jsxs("div",{className:"reflections-header",children:[e.jsxs("h3",{children:[e.jsx(St,{size:16}),o("agents.reflections.sectionTitle","Performance, Reflections & Ratings")]}),e.jsx("button",{className:"btn btn-secondary",onClick:se,disabled:C,title:o("agents.reflections.reflectNowTitle","Generate a manual reflection"),children:C?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:14,className:"animate-spin"}),o("agents.reflections.reflecting","Reflecting...")]}):e.jsxs(e.Fragment,{children:[e.jsx(Rt,{size:14}),o("agents.reflections.reflectNow","Reflect Now")]})})]}),k&&!y&&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(os,{size:16,style:{color:"var(--color-success)"}}),k.totalTasksCompleted]}),e.jsx("div",{className:"stat-label",children:o("agents.performance.tasksCompleted","Tasks Completed")})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(Ka,{size:16,style:{color:"var(--color-error)"}}),k.totalTasksFailed]}),e.jsx("div",{className:"stat-label",children:o("agents.performance.tasksFailed","Tasks Failed")})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(Qs,{size:16,style:{color:"var(--in-progress)"}}),hs(k.avgDurationMs)]}),e.jsx("div",{className:"stat-label",children:o("agents.performance.avgDuration","Avg Duration")})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(St,{size:16,style:{color:k.successRate>=.8?"var(--color-success)":k.successRate>=.5?"var(--color-warning)":"var(--color-error)"}}),Za(k.successRate)]}),e.jsx("div",{className:"stat-label",children:o("agents.performance.successRate","Success Rate")})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(Dt,{size:16,style:{color:"var(--color-info)"}}),k.recentReflectionCount]}),e.jsx("div",{className:"stat-label",children:o("agents.performance.reflections","Reflections")})]})]}),y&&e.jsxs("div",{className:"reflections-no-data",children:[e.jsx(St,{size:24,opacity:.3}),e.jsx("p",{children:o("agents.performance.noData","No performance data yet")})]}),e.jsxs("div",{className:"reflections-ratings-section",children:[e.jsx("h4",{children:o("agents.ratings.title","User Ratings")}),T?e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(q,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:o("agents.ratings.loading","Loading ratings...")})]}):e.jsxs(e.Fragment,{children:[h&&e.jsxs("div",{className:"rating-summary-card",children:[e.jsxs("div",{className:"rating-score-display",children:[e.jsx("span",{className:"rating-average",children:h.averageScore.toFixed(1)}),ps(Math.round(h.averageScore))]}),e.jsxs("div",{className:"rating-stats",children:[e.jsx("span",{className:"rating-count",children:o("agents.ratings.count","{{count}} ratings",{count:h.totalRatings})}),e.jsx("span",{className:`rating-trend-badge ${en(h.trend)}`,children:Xa(h.trend,o)})]})]}),h&&Object.keys(h.categoryAverages).length>0&&e.jsxs("div",{className:"category-breakdown",children:[e.jsx("h4",{children:o("agents.ratings.categoryAverages","Category Averages")}),Object.entries(h.categoryAverages).map(([d,D])=>e.jsxs("div",{className:"category-item",children:[e.jsx("span",{className:"category-name",children:d}),e.jsx("span",{className:"category-score",children:D.toFixed(1)})]},d))]}),e.jsxs("form",{className:"add-rating-form",onSubmit:F,children:[e.jsx("h4",{children:o("agents.ratings.addRating","Add Rating")}),e.jsx("div",{className:"star-selector",children:[1,2,3,4,5].map(d=>e.jsx("button",{type:"button",className:"star-btn touch-target",onClick:()=>E(d),title:o("agents.ratings.starCount","{{count}} star",{count:d,defaultValue_one:"{{count}} star",defaultValue_other:"{{count}} stars"}),children:e.jsx(js,{size:24,fill:d<=S?"currentColor":"none",className:d<=S?"star-filled":"star-empty"})},d))}),e.jsxs("select",{value:L,onChange:d=>W(d.target.value),className:"select add-rating-category-select",children:[e.jsx("option",{value:"",children:o("agents.ratings.categorySelect","Select category...")}),e.jsx("option",{value:"quality",children:o("agents.ratings.categoryQuality","Quality")}),e.jsx("option",{value:"speed",children:o("agents.ratings.categorySpeed","Speed")}),e.jsx("option",{value:"communication",children:o("agents.ratings.categoryCommunication","Communication")}),e.jsx("option",{value:"reliability",children:o("agents.ratings.categoryReliability","Reliability")}),e.jsx("option",{value:"other",children:o("agents.ratings.categoryOther","Other")})]}),e.jsx("textarea",{value:Z,onChange:d=>$(d.target.value),placeholder:o("agents.ratings.commentPlaceholder","Optional comment..."),className:"input add-rating-comment-input",rows:3}),e.jsx("button",{type:"submit",className:"btn btn-task-create",disabled:S===0||V,children:V?o("agents.ratings.submitting","Submitting..."):o("agents.ratings.submitRating","Submit Rating")})]}),e.jsxs("div",{className:"rating-history",children:[e.jsx("h4",{children:o("agents.ratings.historyTitle","Rating History")}),j.length===0?e.jsx("p",{className:"no-ratings",children:o("agents.ratings.noRatings","No ratings yet")}):j.map(d=>e.jsxs("div",{className:"rating-history-item",children:[e.jsxs("div",{className:"rating-item-header",children:[ps(d.score),d.category&&e.jsx("span",{className:"rating-category-badge",children:d.category}),e.jsx("span",{className:"rating-time",children:fs(d.createdAt,o)}),e.jsx("button",{type:"button",className:"rating-delete-btn touch-target",onClick:()=>void G(d.id),title:o("agents.ratings.deleteRating","Delete rating"),children:e.jsx(lt,{size:14})})]}),d.comment&&e.jsx("p",{className:"rating-comment",children:d.comment})]},d.id))]})]})]}),e.jsxs("div",{className:"reflections-list",children:[e.jsx("h4",{children:o("agents.reflections.historyTitle","Reflection History")}),m?e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(q,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:o("agents.reflections.loading","Loading reflections...")})]}):s.length===0?e.jsxs("div",{className:"reflection-empty",children:[e.jsx(Dt,{size:32,opacity:.3}),e.jsx("p",{children:o("agents.reflections.noReflections","No reflections yet")}),e.jsx("p",{className:"text-secondary",children:o("agents.reflections.getStarted","Trigger a reflection to get started")})]}):e.jsx("div",{className:"reflection-cards",children:s.map(d=>{const D=N===d.id;return e.jsxs("div",{className:`reflection-card ${D?"reflection-card--expanded":""}`,onClick:()=>b(d.id),role:"button",tabIndex:0,onKeyDown:X=>X.key==="Enter"&&b(d.id),children:[e.jsxs("div",{className:"reflection-card-header",children:[e.jsx("span",{className:`reflection-trigger-badge reflection-trigger-${d.trigger}`,children:Qa(d.trigger,o)}),e.jsx("span",{className:"reflection-timestamp",children:fs(d.timestamp,o)}),e.jsx("span",{className:"reflection-chevron",children:D?e.jsx(ys,{size:16}):e.jsx(Ns,{size:16})})]}),e.jsx("div",{className:"reflection-summary",children:d.summary}),D&&e.jsxs("div",{className:"reflection-details",children:[d.insights.length>0&&e.jsxs("div",{className:"reflection-insights",children:[e.jsxs("h5",{children:[e.jsx(Dt,{size:14})," ",o("agents.reflections.insights","Insights")]}),e.jsx("ul",{children:d.insights.map((X,pe)=>e.jsx("li",{children:X},pe))})]}),d.suggestedImprovements.length>0&&e.jsxs("div",{className:"reflection-suggestions",children:[e.jsxs("h5",{children:[e.jsx(os,{size:14})," ",o("agents.reflections.suggestedImprovements","Suggested Improvements")]}),e.jsx("ul",{children:d.suggestedImprovements.map((X,pe)=>e.jsx("li",{children:X},pe))})]}),d.metrics&&e.jsxs("div",{className:"reflection-metrics",children:[e.jsx("h5",{children:o("agents.reflections.metrics","Metrics")}),e.jsxs("div",{className:"metrics-grid",children:[d.metrics.tasksCompleted!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:o("agents.reflections.metricTasks","Tasks:")}),e.jsx("span",{className:"metric-value",children:d.metrics.tasksCompleted})]}),d.metrics.tasksFailed!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:o("agents.reflections.metricFailed","Failed:")}),e.jsx("span",{className:"metric-value",children:d.metrics.tasksFailed})]}),d.metrics.avgDurationMs!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:o("agents.reflections.metricAvgDuration","Avg Duration:")}),e.jsx("span",{className:"metric-value",children:hs(d.metrics.avgDurationMs)})]}),d.metrics.errorCount!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:o("agents.reflections.metricErrors","Errors:")}),e.jsx("span",{className:"metric-value",children:d.metrics.errorCount})]})]})]})]})]},d.id)})})]})]})}function oe(...t){return t.filter(Boolean).join(" ")}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 Qe(t,r){const l=Date.now(),o=new Date(t).getTime(),s=l-o,f=r??((n,h,u)=>u?h.replace(/\{\{(\w+)\}\}/g,(j,c)=>String(u[c]??"")):h);if(s<0){const n=Math.abs(s);if(n<6e4)return f("time.inAMoment","in a moment");if(n<36e5){const u=Math.floor(n/6e4);return f("time.inMinutes","in {{n}}m",{n:u})}if(n<864e5){const u=Math.floor(n/36e5);return f("time.inHours","in {{n}}h",{n:u})}const h=Math.floor(n/864e5);return f("time.inDays","in {{n}}d",{n:h})}if(s<6e4)return f("time.justNow","just now");if(s<36e5){const n=Math.floor(s/6e4);return f("time.minutesAgo","{{n}}m ago",{n})}if(s<864e5){const n=Math.floor(s/36e5);return f("time.hoursAgo","{{n}}h ago",{n})}const k=Math.floor(s/864e5);return f("time.daysAgo","{{n}}d ago",{n:k})}const an="⚠️",nn=[{id:"dashboard",label:"Dashboard",icon:qa},{id:"logs",label:"Logs",icon:ot},{id:"mail",label:"Mail",icon:la},{id:"runs",label:"Runs",icon:Ct},{id:"tasks",label:"Tasks",icon:As},{id:"employees",label:"Employees",icon:Fs},{id:"soul",label:"Soul",icon:oa},{id:"instructions",label:"Instructions",icon:Va},{id:"memory",label:"Agent Memory",icon:ot},{id:"reflections",label:"Evaluation",icon:St},{id:"config",label:"Settings",icon:ca}],Zt={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)"}},wt={completed:{icon:ge,color:"var(--color-success)"},failed:{icon:ba,color:"var(--color-error)"},active:{icon:q,color:"var(--in-progress)"},terminated:{icon:Ze,color:"var(--text-muted)"}},rn=Ds(qt),ln=700;function on(t,r){return t.some(l=>l.path===r)?r:t.find(l=>l.layer==="long-term")?.path??t[0]?.path??""}function En({agentId:t,projectId:r,onClose:l,addToast:o,onChildClick:s,inline:f=!1,showInlineBackButton:k=!1,initialTab:n,initialRunId:h,preferActiveRun:u=!1,onMutationSuccess:j}){const{t:c}=Ne("app"),[m,A]=a.useState(null),{confirm:T}=Ss(),[H,C]=a.useState([]),[_,V]=a.useState(!0),[P,N]=a.useState(n??"dashboard"),[w,S]=a.useState(!1),[E,L]=a.useState(!1),[W,Z]=a.useState(!1),[$,J]=a.useState(!1),[M,se]=a.useState(!1),[F,G]=a.useState(!1),[b,y]=a.useState(0),[d,D]=a.useState(0),[X,pe]=a.useState(0),[ue,Re]=a.useState(null),[Se,I]=a.useState(null),[ee,Le]=a.useState(!1),[De,x]=a.useState(null),v=a.useRef(null),ie=a.useRef(null),ae=a.useRef(!1);sa(v,!f,"fusion:agent-detail-modal-size");const We=a.useRef(l),ze=a.useRef(o),Me=a.useRef(null),ce=a.useRef(!1),Fe=a.useRef(null),ne=a.useRef(0),ct=a.useRef(t),Pe=a.useRef(r);We.current=l,ze.current=o,Me.current=m;const ve=a.useCallback(async()=>{Me.current===null&&V(!0);try{const z=await aa(t,r);A(z)}catch(z){ze.current(`Failed to load agent: ${U(z)}`,"error"),We.current()}finally{V(!1)}},[t,r]),dt=a.useCallback(async()=>{const p=ne.current,z=t,B=r,O=()=>ne.current!==p||t!==z||r!==B;try{if(m?.taskId){Re(null),Fe.current=null;const Ae=await na(m.taskId,B,{limit:100});if(O())return;C(Ae.entries);return}const re=await ks(z,1,B);if(O())return;const fe=re[0]??null;if(Re(fe),!fe){Fe.current=null,C([]);return}if(Fe.current===fe.id)return;const Ce=await Cs(z,fe.id,B);if(O())return;C(Ce),Fe.current=fe.id}catch(re){if(O())return;console.error("Failed to load agent logs:",re)}},[m?.taskId,t,r]),Xe=a.useCallback(async()=>{Le(!0),x(null);try{const p=await ia(t,r);I(p)}catch(p){x(U(p)),I(null)}finally{Le(!1)}},[t,r]),Tt=a.useCallback(p=>{ce.current=p},[]),et=a.useCallback(async(p=!1)=>{await j?.({agentId:t,deleted:p})},[t,j]),Be=a.useCallback(async()=>{await ve(),await et(!1)},[ve,et]);a.useEffect(()=>{ve()},[ve]),a.useEffect(()=>{const p=setInterval(()=>{ve()},3e4);return()=>{clearInterval(p)}},[ve]),a.useEffect(()=>{m&&P==="logs"&&dt()},[m,P,dt]),a.useEffect(()=>{P!=="logs"&&(Fe.current=null)},[P]),a.useEffect(()=>{m&&P==="mail"&&Xe()},[m,P,Xe]),a.useEffect(()=>{if(!$)return;const p=B=>{ie.current?.contains(B.target)||J(!1)},z=B=>{B.key==="Escape"&&J(!1)};return document.addEventListener("mousedown",p),document.addEventListener("keydown",z),()=>{document.removeEventListener("mousedown",p),document.removeEventListener("keydown",z)}},[$]),a.useEffect(()=>{if(!$)return;let p=!1;return G(!0),kt(void 0,r).then(z=>{if(p)return;const B=z.filter(O=>!zt(O));y(B.filter(O=>O.state==="active"||O.state==="running").length),D(B.filter(O=>O.state==="paused").length)}).catch(()=>{p||(y(0),D(0))}).finally(()=>{p||G(!1)}),()=>{p=!0}},[$,r]),a.useEffect(()=>{if(P!=="logs"||m?.taskId||!ue||ue.status!=="active")return;const p=ne.current,z=t,B=ue.id,O=r?`?projectId=${encodeURIComponent(r)}`:"",re=Nt(`/api/agents/${encodeURIComponent(z)}/runs/${encodeURIComponent(B)}/logs/stream${O}`,{events:{"agent:log":fe=>{if(ne.current===p)try{const Ce=JSON.parse(fe.data);C(Ae=>[...Ae,Ce])}catch{}}},onOpen:()=>{ne.current===p&&S(!0)},onError:()=>{ne.current===p&&S(!1)}});return()=>{re(),ne.current===p&&S(!1)}},[P,m?.taskId,t,r,ue]),a.useEffect(()=>{(ct.current!==t||Pe.current!==r)&&(ct.current=t,Pe.current=r,ne.current++,C([]),S(!1),Re(null),I(null),x(null),Fe.current=null,ce.current=!1)},[t,r]),a.useEffect(()=>{const p=r?`?projectId=${encodeURIComponent(r)}`:"",z=ne.current,B=O=>{if(ne.current===z)try{const re=JSON.parse(O.data);if(!re||typeof re!="object"||re.agentId!==t)return;ve()}catch{}};return Nt(`/api/events${p}`,{events:{"agent:updated":O=>{if(ne.current===z)try{const re=JSON.parse(O.data);if(!re||typeof re!="object"||re.id!==t||ce.current)return;ve()}catch{}},"approval:requested":B,"approval:updated":B,"approval:decided":B}})},[t,r,ve]),a.useEffect(()=>{if(P!=="logs"||!m?.taskId){S(!1);return}const p=ne.current,z=m.taskId,B=r?`?projectId=${encodeURIComponent(r)}`:"",O=Nt(`/api/tasks/${encodeURIComponent(z)}/logs/stream${B}`,{events:{"agent:log":re=>{if(ne.current===p)try{const fe=JSON.parse(re.data);C(Ce=>[...Ce,fe])}catch{}}},onOpen:()=>{ne.current===p&&S(!0)},onError:()=>{ne.current===p&&S(!1)}});return()=>{O(),ne.current===p&&S(!1)}},[m?.taskId,P,r]);const Te=async p=>{if(E||!Me.current)return;const z=Me.current.state;if(z!==p){L(!0),A(B=>B&&{...B,state:p});try{await ds(t,p,r),o(c("agents.stateUpdated","Agent state updated to {{newState}}",{newState:p}),"success"),await Be()}catch(B){A(O=>O&&{...O,state:z}),o(c("agents.stateUpdateFailed","Failed to update state: {{error}}",{error:U(B)}),"error")}finally{L(!1)}}},ut=async p=>{if(!M){J(!1),se(!0);try{const B=(await kt(void 0,r)).filter(me=>!zt(me)),O=B.filter(me=>p==="paused"?me.state==="active"||me.state==="running":me.state==="paused"),re=B.length-O.length;if(O.length===0){o(c("agents.bulkNoEligible","No agents eligible to {{action}}",{action:p==="paused"?c("agents.pause","pause"):c("agents.resume","resume")}),"error");return}if(!await T({title:p==="paused"?c("agents.pauseAllTitle","Pause All Agents"):c("agents.resumeAllTitle","Resume All Agents"),message:c("agents.bulkConfirmMessage","{{action}} {{count}} agent(s) in this project?",{action:p==="paused"?c("agents.pauseAction","Pause"):c("agents.resumeAction","Resume"),count:O.length}),danger:p==="paused"}))return;const Ce=await Promise.allSettled(O.map(me=>ds(me.id,p,r))),Ae=Ce.map((me,qe)=>({result:me,agent:O[qe]})).filter(me=>me.result.status==="rejected"),je=Ce.length-Ae.length,st=Ae.length,Ge=p==="paused"?c("agents.pausedPast","Paused"):c("agents.resumedPast","Resumed"),ht=je===1?c("agents.agentSingular","agent"):c("agents.agentPlural","agents"),ft=c(je===1?"agents.bulkResult_one":"agents.bulkResult_other","{{action}} {{successCount}} {{agentWord}}; skipped {{skippedCount}}",{action:Ge,successCount:je,agentWord:ht,skippedCount:re});if(st>0){const me=Ae.slice(0,3).map(({agent:qe,result:pt})=>`${qe.name||qe.id}: ${U(pt.reason)}`).join("; ");o(c("agents.bulkResultWithFailures","{{summary}}; failed {{failureCount}}{{detail}}",{summary:ft,failureCount:st,detail:me?` (${me})`:""}),"error")}else o(ft,"success");await Be()}catch(z){o(c("agents.bulkActionFailed","Failed to {{action}} agents: {{error}}",{action:p==="paused"?c("agents.pause","pause"):c("agents.resume","resume"),error:U(z)}),"error")}finally{se(!1)}}},tt=async()=>{if(!W){Z(!0);try{await ma(t,r,{source:"on_demand",triggerDetail:"Triggered from dashboard"}),o(c("agents.heartbeatStarted","Heartbeat run started for {{name}}",{name:m?.name??t}),"success"),pe(p=>p+1)}catch(p){o(c("agents.heartbeatStartFailed","Failed to start heartbeat run: {{error}}",{error:U(p)}),"error")}finally{Z(!1)}}},Ue=async()=>{if(!(!m||!await T({title:c("agents.deleteTitle","Delete Agent"),message:c("agents.deleteConfirm",'Delete agent "{{name}}"? This cannot be undone.',{name:m.name}),danger:!0})))try{await ga(t,r),o(c("agents.deleted",'Agent "{{name}}" deleted',{name:m.name}),"success"),await et(!0),l()}catch(z){o(c("agents.deleteFailed","Failed to delete agent: {{error}}",{error:U(z)}),"error")}},mt=()=>m?ua(m):{label:"Unknown",icon:e.jsx(Kt,{size:14}),color:"var(--text-muted)",stateDerived:!1},gt=()=>{m&&(navigator.clipboard.writeText(m.id),o(c("agents.idCopied","Agent ID copied to clipboard"),"success"))};if(_)return f?e.jsx("div",{className:"agent-detail-inline-loading",role:"region","aria-label":c("agents.detailLoadingLabel","Agent detail loading"),children:e.jsxs("div",{className:"agent-detail-loading",children:[e.jsx(q,{className:"animate-spin",size:24}),e.jsx("span",{children:c("agents.loading","Loading agent...")})]})}):e.jsx("div",{className:"agent-detail-overlay",onMouseDown:p=>{p.target===p.currentTarget&&(ae.current=!0)},onMouseUp:p=>{ae.current&&p.target===p.currentTarget&&l(),ae.current=!1},role:"dialog","aria-modal":"true",children:e.jsx("div",{className:"agent-detail-modal",ref:v,children:e.jsxs("div",{className:"agent-detail-loading",children:[e.jsx(q,{className:"animate-spin",size:24}),e.jsx("span",{children:c("agents.loading","Loading agent...")})]})})});if(!m)return null;const Je=Zt[m.state],ke=mt(),He=f?"agent-detail-inline":"agent-detail-modal",he=F||b===0,$e=F||d===0;return e.jsx("div",{className:f?"agent-detail-inline-shell":"agent-detail-overlay",onClick:p=>!f&&p.target===p.currentTarget&&l(),role:f?"region":"dialog","aria-label":f?"Agent detail":void 0,"aria-modal":f?void 0:"true",children:e.jsxs("div",{className:He,ref:v,children:[e.jsxs("div",{className:"agent-detail-header",children:[e.jsxs("div",{className:"agent-detail-identity",children:[f&&k?e.jsxs("button",{type:"button",className:"btn agent-detail-inline-back",onClick:l,"aria-label":c("agents.backToAgents","Back to agents"),children:[e.jsx(ws,{size:16}),c("agents.agentsLabel","Agents")]}):null,e.jsx("div",{className:"agent-detail-icon",children:e.jsx(Rs,{agent:m,size:36})}),e.jsxs("div",{className:"agent-detail-info",children:[e.jsx("h2",{children:m.name}),e.jsxs("div",{className:"agent-detail-badges",children:[e.jsx("span",{className:"badge",style:{background:Je.bg,color:Je.text,border:`1px solid ${Je.border}`},children:m.state}),e.jsxs("span",{className:"badge",style:{color:ke.color},title:ke.reason??ke.label,children:[ke.icon,!ke.stateDerived&&ke.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 Te("active"),disabled:E,children:[e.jsx(Ht,{size:14}),c("agents.start","Start")]}),e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void tt(),"aria-label":c("agents.runNowFor","Run now for {{name}}",{name:m.name}),disabled:W||E,children:[e.jsx(Ct,{size:14}),c("agents.runNow","Run Now")]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:Ue,children:[e.jsx(lt,{size:14}),c("agents.delete","Delete")]})]}),m.state==="active"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--compact agent-detail-mobile-icon-control",onClick:()=>void Te("paused"),disabled:E,"aria-label":c("agents.pause","Pause"),children:[e.jsx(cs,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:c("agents.pause","Pause")})]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:()=>void Te("paused"),disabled:E,"aria-label":c("agents.stop","Stop"),children:[e.jsx(Ze,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:c("agents.stop","Stop")})]}),e.jsxs("button",{className:"btn btn-task-create btn--compact agent-detail-mobile-icon-control",onClick:()=>void tt(),"aria-label":c("agents.runNowFor","Run now for {{name}}",{name:m.name}),disabled:W||E,children:[e.jsx(Ct,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:c("agents.runNow","Run Now")})]})]}),m.state==="paused"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact agent-detail-mobile-icon-control",onClick:()=>void Te("active"),disabled:E,"aria-label":c("agents.resume","Resume"),children:[e.jsx(Ht,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:c("agents.resume","Resume")})]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:Ue,children:[e.jsx(lt,{size:14}),c("agents.delete","Delete")]})]}),m.state==="running"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--compact agent-detail-mobile-icon-control",onClick:()=>void Te("paused"),disabled:E,"aria-label":c("agents.pause","Pause"),children:[e.jsx(cs,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:c("agents.pause","Pause")})]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:()=>void Te("paused"),disabled:E,"aria-label":c("agents.stop","Stop"),children:[e.jsx(Ze,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:c("agents.stop","Stop")})]})]}),m.state==="error"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void Te("active"),disabled:E,children:[e.jsx(Ht,{size:14}),c("agents.retry","Retry")]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:()=>void Te("paused"),disabled:E,"aria-label":c("agents.stop","Stop"),children:[e.jsx(Ze,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:c("agents.stop","Stop")})]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:Ue,"aria-label":c("agents.delete","Delete"),children:[e.jsx(lt,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:c("agents.delete","Delete")})]})]})]}),e.jsxs("div",{className:"agent-detail-utility-actions",children:[e.jsxs("div",{className:"agent-detail-bulk-menu",ref:ie,children:[e.jsx("button",{type:"button",className:"btn-icon",onClick:()=>J(p=>!p),"aria-haspopup":"menu","aria-expanded":$,"aria-label":c("agents.bulkActions","Bulk agent actions"),title:c("agents.bulkActions","Bulk agent actions"),disabled:E||M,children:e.jsx(ra,{size:16})}),$&&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 ut("paused"),disabled:he||M,children:[c("agents.pauseAll","Pause All Agents"),e.jsx("span",{className:"agent-detail-bulk-menu-item-hint",children:F?c("agents.loadingEligible","Loading eligible agents..."):he?c("agents.noActiveEligible","No active agents eligible"):c(b===1?"agents.pauseCountHint_one":"agents.pauseCountHint_other",b===1?"Pause {{count}} active/running agent":"Pause {{count}} active/running agents",{count:b})})]}),e.jsxs("button",{type:"button",role:"menuitem",className:"agent-detail-bulk-menu-item",onClick:()=>void ut("active"),disabled:$e||M,children:[c("agents.resumeAll","Resume All Agents"),e.jsx("span",{className:"agent-detail-bulk-menu-item-hint",children:F?c("agents.loadingEligible","Loading eligible agents..."):$e?c("agents.noPausedEligible","No paused agents eligible"):c(d===1?"agents.resumeCountHint_one":"agents.resumeCountHint_other",d===1?"Resume {{count}} paused agent":"Resume {{count}} paused agents",{count:d})})]})]})]}),e.jsx("button",{className:"btn-icon",onClick:()=>void ve(),title:c("common.refresh","Refresh"),"aria-label":c("common.refresh","Refresh"),children:e.jsx(Rt,{size:16})}),!f&&e.jsx("button",{className:"btn-icon",onClick:l,"aria-label":c("common.close","Close"),title:c("common.close","Close"),children:e.jsx(Ms,{size:20})})]})]})]}),e.jsx("div",{className:"agent-detail-tabs",children:nn.map(p=>{const z={dashboard:c("agents.tabDashboard","Dashboard"),logs:c("agents.tabLogs","Logs"),mail:c("agents.tabMail","Mail"),runs:c("agents.tabRuns","Runs"),tasks:c("agents.tabTasks","Tasks"),employees:c("agents.tabEmployees","Employees"),soul:c("agents.tabSoul","Soul"),instructions:c("agents.tabInstructions","Instructions"),memory:c("agents.tabMemory","Agent Memory"),reflections:c("agents.tabReflections","Evaluation"),config:c("agents.tabConfig","Settings")};return e.jsxs("button",{className:oe("agent-detail-tab",P===p.id&&"active"),onClick:()=>N(p.id),children:[e.jsx(p.icon,{size:16}),z[p.id]]},p.id)})}),e.jsxs("div",{className:"agent-detail-content",children:[P==="dashboard"&&e.jsx(cn,{agent:m,health:ke,onChildClick:s,projectId:r}),P==="logs"&&e.jsx(dn,{logs:H,isStreaming:w,hasTask:!!m.taskId||H.length>0||ue!==null,fallbackLabel:!m.taskId&&ue?c("agents.latestRunLabel","Latest run · {{id}}",{id:ue.id.slice(0,8)}):null}),P==="mail"&&e.jsx(mn,{agent:m,mailbox:Se,isLoading:ee,error:De,projectId:r,addToast:o,onRefresh:()=>void Xe()}),P==="runs"&&e.jsx(gn,{addToast:o,agentId:m.id,projectId:r,agentState:m.state,agentName:m.name,initialRunId:h,preferActiveRun:u,runNowRefreshToken:X,isEphemeral:zt(m)}),P==="tasks"&&e.jsx(pn,{agentId:m.id,projectId:r,addToast:o}),P==="employees"&&e.jsx(Sn,{agentId:m.id,projectId:r,onChildClick:s}),P==="soul"&&e.jsx(xn,{agent:m,projectId:r,addToast:o,onSaved:Be}),P==="instructions"&&e.jsx(jn,{agent:m,projectId:r,addToast:o,onSaved:Be}),P==="memory"&&e.jsx(vn,{agent:m,projectId:r,addToast:o,onSaved:Be}),P==="reflections"&&e.jsx(tn,{agentId:m.id,projectId:r,addToast:o}),P==="config"&&e.jsx(Nn,{agent:m,projectId:r,addToast:o,onSaved:Be,onHasChangesChange:Tt,onDelete:Ue,onAgentDraftApplied:p=>{A(z=>z&&{...z,...p})}},m.id)]}),!f&&e.jsxs("div",{className:"agent-detail-footer",children:[e.jsx("button",{className:"btn-icon",onClick:gt,title:c("agents.copyId","Copy Agent ID"),children:e.jsx(da,{})}),e.jsx("span",{className:"agent-detail-id",onClick:gt,children:m.id}),m.taskId&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"divider",children:"|"}),e.jsx("span",{className:"text-muted",children:c("agents.workingOn","Working on:")}),e.jsxs("a",{href:`/tasks/${m.taskId}`,className:"link",children:[e.jsx(Ps,{taskId:m.taskId,taskColumn:m.taskColumn}),e.jsx(Ts,{size:12})]})]})]})]})})}function cn({agent:t,health:r,onChildClick:l,projectId:o}){const{t:s}=Ne("app"),f=Zt[t.state],[k,n]=a.useState([]),[h,u]=a.useState(!0),[j,c]=a.useState(null),[m,A]=a.useState([]),[T,H]=a.useState(null),[C,_]=a.useState(null),[V,P]=a.useState(!1),[N,w]=a.useState(null),S=typeof t.runtimeConfig?.runtimeHint=="string"?t.runtimeConfig.runtimeHint:"",E=(()=>{const b=t.runtimeConfig??{};if(S){const y=m.find(d=>d.runtimeId===S);return y?y.name:S}if(b.modelProvider&&b.modelId)return`${b.modelProvider}/${b.modelId}`;if(typeof b.model=="string"&&b.model.includes("/")){const y=b.model.indexOf("/");return b.model.slice(y+1)}return null})();a.useEffect(()=>{Gt(t.id,o).then(c).catch(()=>c(null))},[t.id,o]),a.useEffect(()=>{Es(o).then(A).catch(()=>A([]))},[o]),a.useEffect(()=>{let b=!1;return u(!0),ha(t.id,o).then(y=>{if(b)return;const d=y.length>0&&y[0]?.id===t.id?[...y].reverse():y;n(d)}).catch(()=>{b||n([])}).finally(()=>{b||u(!1)}),()=>{b=!0}},[t.id,o]);const L=a.useMemo(()=>{const b=t.completedRuns||[],y=new Date;y.setHours(0,0,0,0);const d=b.filter(X=>new Date(X.startedAt)>=y),D=b.filter(X=>X.status==="completed");return{totalRuns:b.length,todayRuns:d.length,successfulRuns:D.length,successRate:b.length>0?Math.round(D.length/b.length*100):0}},[t]),W=(t.completedRuns||[]).slice(0,5),Z=Array.isArray(t.metadata?.skills)?t.metadata.skills:[],$=T?Bt(T):null,J=a.useCallback(async b=>{P(!0),w(null),_(null);try{const y=await fa(b,o);_(y)}catch(y){w(U(y))}finally{P(!1)}},[o]),M=a.useCallback(b=>{if(T===b){H(null),_(null),w(null),P(!1);return}H(b),J(b)},[J,T]),se=t.state==="active"||t.state==="running",F=pa(t.runtimeConfig?.heartbeatIntervalMs),G=se&&t.lastHeartbeatAt?new Date(new Date(t.lastHeartbeatAt).getTime()+F).toISOString():null;return e.jsxs("div",{className:"dashboard-tab dashboard-summary-layout",children:[j?.isOverBudget&&e.jsxs("div",{className:"budget-warning-banner",role:"alert",children:[e.jsx("span",{children:an}),e.jsxs("span",{children:[e.jsx("strong",{children:s("agents.budgetExhaustedTitle","Budget Exhausted:")})," ",s("agents.budgetExhaustedBody","This agent has exceeded its token budget and may operate with limited functionality.")]})]}),e.jsxs("section",{className:"dashboard-summary-card dashboard-summary-hero",children:[e.jsxs("div",{className:"dashboard-summary-hero__heading",children:[e.jsx(Kt,{}),e.jsx("h3",{children:s("agents.overview","Overview")}),e.jsx("strong",{children:t.name}),e.jsx("span",{className:"inline-badge",style:{background:f.bg,color:f.text},children:t.state})]}),e.jsxs("div",{className:"dashboard-summary-hero__meta",children:[e.jsxs("span",{className:"dashboard-summary-hero__health",title:r.reason??r.label,children:[r.icon," ",r.label]}),(t.pendingApprovalCount??0)>0?e.jsxs("span",{className:"badge agent-detail-approval-badge",title:s("agents.pendingApprovals","Pending approvals"),children:[e.jsx("span",{className:"status-dot status-dot--pending"}),s("agents.pendingApprovalsCount","{{count}} pending approvals",{count:t.pendingApprovalCount})]}):null,e.jsx("span",{children:s("agents.roleLabel","Role: {{role}}",{role:t.role})}),e.jsxs("span",{children:[e.jsx("span",{className:"dashboard-summary-label",children:S?s("agents.runtime","Runtime"):s("agents.model","Model")}),e.jsxs("span",{children:[" ",E??s("agents.auto","Auto")]})]}),Z.length>0?e.jsxs("span",{className:"dashboard-summary-skills",children:[e.jsx("span",{className:"dashboard-summary-label",children:s("agents.skills","Skills")}),e.jsx("span",{className:"dashboard-summary-skill-badges",role:"list","aria-label":s("agents.assignedSkills","Assigned skills"),children:Z.map(b=>{const y=T===b;return e.jsx("button",{type:"button",className:oe("badge","badge-skill","dashboard-summary-skill-badge","dashboard-summary-skill-badge-btn",y&&"dashboard-summary-skill-badge--selected"),title:b,onClick:()=>M(b),"aria-expanded":y,"aria-label":s("agents.viewSkillDetails","View details for {{skill}}",{skill:Bt(b)}),children:Bt(b)},b)})})]}):e.jsx("span",{children:s("agents.skillsNone","Skills: —")})]}),T?e.jsxs("div",{className:"dashboard-summary-skill-detail","data-testid":"agent-skill-detail",children:[e.jsxs("div",{className:"dashboard-summary-skill-detail-header",children:[e.jsx("span",{className:"dashboard-summary-skill-detail-title",children:$}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>M(T),children:[e.jsx(Ms,{size:14}),s("common.close","Close")]})]}),V?e.jsxs("div",{className:"dashboard-summary-skill-detail-loading",role:"status","aria-live":"polite",children:[e.jsx(q,{size:14,className:"animate-spin"}),s("agents.loadingSkillContent","Loading skill content...")]}):N?e.jsxs("div",{className:"dashboard-summary-skill-detail-error",role:"alert",children:[e.jsx(Ls,{size:14}),e.jsx("span",{children:N}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void J(T),children:s("common.retry","Retry")})]}):C?e.jsx("pre",{className:"dashboard-summary-skill-detail-content",children:C.skillMd||s("agents.noSkillMd","(No SKILL.md found)")}):e.jsx("div",{className:"dashboard-summary-skill-detail-empty",children:s("agents.noSkillContent","No skill content available")})]}):null]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:s("agents.heartbeatAndHealth","Heartbeat & Health")}),e.jsxs("div",{className:"dashboard-summary-grid",children:[e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:s("agents.lastHeartbeat","Last heartbeat")}),e.jsx("p",{children:t.lastHeartbeatAt?Qe(t.lastHeartbeatAt,s):s("agents.never","Never")})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:s("agents.nextExpected","Next expected")}),e.jsx("p",{children:G?Qe(G,s):s("agents.notScheduled","Not scheduled")})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:s("agents.interval","Interval")}),e.jsx("p",{children:Ds(F)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:s("agents.status","Status")}),e.jsxs("p",{className:"dashboard-summary-health-row",children:[e.jsx("span",{className:oe("status-dot",t.state==="running"&&"status-dot--running")}),r.label,r.reason&&e.jsxs("span",{className:"text-secondary dashboard-summary-health-reason",title:r.reason,children:["(",r.reason,")"]})]})]})]})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:s("agents.currentWork","Current Work")}),t.taskId?e.jsxs("div",{className:"current-task",children:[e.jsx("a",{href:`/tasks/${t.taskId}`,className:"task-badge",children:e.jsx(Ps,{taskId:t.taskId,taskColumn:t.taskColumn})}),e.jsxs("a",{href:`/tasks/${t.taskId}`,className:"btn btn-sm",children:[s("agents.viewTask","View Task")," ",e.jsx(Ts,{size:14})]})]}):e.jsx("p",{className:"text-muted",children:s("agents.noActiveAssignment","No active assignment")})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:s("agents.recentRuns","Recent Runs")}),e.jsx("p",{className:"dashboard-summary-label",children:s("agents.runsSuccessRate","{{successful}}/{{total}} successful ({{rate}}%)",{successful:L.successfulRuns,total:L.totalRuns,rate:L.successRate})}),W.length===0?e.jsx("p",{className:"text-muted",children:s("agents.noRunsYet","No runs yet")}):e.jsx("div",{className:"runs-list",children:W.map(b=>{const y=wt[b.status]||wt.terminated,d=y.icon;return e.jsxs("div",{className:"run-item",children:[e.jsx(d,{size:14,style:{color:y.color}}),e.jsx("span",{children:Qe(b.startedAt,s)}),e.jsxs("span",{className:"text-muted",children:[Math.max(0,Math.round((new Date(b.endedAt||b.startedAt).getTime()-new Date(b.startedAt).getTime())/1e3)),"s"]})]},b.id)})})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:s("agents.throughput","Throughput")}),e.jsxs("div",{className:"stats-grid",children:[e.jsxs("div",{className:"stat-card",children:[e.jsx("div",{className:"stat-value",children:L.totalRuns}),e.jsx("div",{className:"stat-label",children:s("agents.totalRuns","Total Runs")})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("div",{className:"stat-value",children:L.todayRuns}),e.jsx("div",{className:"stat-label",children:s("agents.runsToday","Runs Today")})]}),e.jsxs("div",{className:"stat-card",children:[e.jsxs("div",{className:"stat-value",children:[L.successRate,"%"]}),e.jsx("div",{className:"stat-label",children:s("agents.successRate","Success Rate")})]})]})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:s("agents.chainOfCommand","Chain of Command")}),h?e.jsxs("div",{className:"chain-of-command-loading",role:"status","aria-live":"polite",children:[e.jsx(q,{size:14,className:"animate-spin"}),e.jsx("span",{children:s("agents.loadingReportingChain","Loading reporting chain...")})]}):k.length<=1?e.jsx("p",{className:"text-muted",children:s("agents.noReportingChain","No reporting chain")}):e.jsx("div",{className:"chain-of-command-path","aria-label":s("agents.chainOfCommand","Chain of command"),children:k.map((b,y)=>{const d=y===k.length-1,D=!d;return e.jsxs("div",{className:"chain-of-command-item",children:[e.jsx("button",{type:"button",className:`chain-of-command-node${d?" chain-of-command-node--current":""}`,onClick:()=>D&&l?.(b.id),disabled:!D||!l,title:d?s("agents.currentAgent","Current agent"):s("agents.viewAgent","View {{name}}",{name:b.name}),children:b.name}),!d&&e.jsx("span",{className:"chain-of-command-separator","aria-hidden":"true",children:"→"})]},b.id)})})]})]})}function dn({logs:t,isStreaming:r,hasTask:l,fallbackLabel:o}){const{t:s}=Ne("app");return l?e.jsxs("div",{className:"logs-tab",children:[e.jsxs("div",{className:"logs-header",children:[e.jsx("span",{className:"logs-count",children:s("agents.logEntries","{{count}} entries",{count:t.length})}),o&&e.jsx("span",{className:"text-muted logs-fallback-label",children:o}),r&&e.jsxs("span",{className:"streaming-indicator",children:[e.jsx("span",{className:"streaming-dot"}),s("agents.live","Live")]})]}),t.length===0?e.jsxs("div",{className:"logs-empty",children:[e.jsx(ot,{size:48,opacity:.3}),e.jsx("p",{children:s("agents.noLogEntriesYet","No log entries yet")}),e.jsx("p",{className:"text-muted",children:r?s("agents.waitingForActivity","Waiting for activity..."):s("agents.logsWillAppearActive","Logs will appear here when the agent is active")})]}):e.jsx(zs,{entries:t,loading:!1})]}):e.jsx("div",{className:"logs-tab",children:e.jsxs("div",{className:"logs-empty",children:[e.jsx(ot,{size:48,opacity:.3}),e.jsx("p",{children:s("agents.noActivityYet","No activity yet")}),e.jsx("p",{className:"text-muted",children:s("agents.logsWillAppear","Agent logs will appear here from the current task or most recent run")})]})})}function un(t,r){const l=new Date(t),s=new Date().getTime()-l.getTime(),f=Math.floor(s/6e4),k=Math.floor(s/36e5),n=Math.floor(s/864e5),h=r??((u,j,c)=>c?j.replace(/\{\{(\w+)\}\}/g,(m,A)=>String(c[A]??"")):j);return f<1?h("time.justNow","just now"):f<60?h("time.minutesAgo","{{n}}m ago",{n:f}):k<24?h("time.hoursAgo","{{n}}h ago",{n:k}):n<7?h("time.daysAgo","{{n}}d ago",{n}):l.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function yt(t,r,l,o){const s=o??((f,k,n)=>n?k.replace(/\{\{(\w+)\}\}/g,(h,u)=>String(n[u]??"")):k);if(r==="user")return t==="dashboard"?s("mailbox.you","You"):s("mailbox.userLabel","User: {{id}}",{id:t});if(r==="agent"){const f=l?.get(t)?.trim();return!f||f===t?s("mailbox.agentById","Agent: {{id}}",{id:t}):s("mailbox.agentByName","Agent: {{name}}",{name:f})}return s("mailbox.system","System")}function mn({agent:t,mailbox:r,isLoading:l,error:o,projectId:s,addToast:f,onRefresh:k}){const{t:n}=Ne("app"),[h,u]=a.useState("inbox"),[j,c]=a.useState([]);a.useEffect(()=>{let N=!1;return kt(void 0,s).then(w=>{N||c(w)}).catch(()=>{N||c([])}),()=>{N=!0}},[s]);const m=a.useMemo(()=>{const N=new Map;for(const S of j){if(!S.id)continue;const E=typeof S.name=="string"?S.name.trim():"";E.length>0&&N.set(S.id,E)}const w=typeof t.name=="string"?t.name.trim():"";return w.length>0&&N.set(t.id,w),N},[j,t.id,t.name]),[A,T]=a.useState(null),H=h==="inbox"?r?.inbox??[]:r?.outbox??[],C=A?H.find(N=>N.id===A)??null:null;a.useEffect(()=>{T(null)},[h,t.id]);const _=async N=>{if(T(N.id),!(h!=="inbox"||N.read))try{await $a(N.id,s),k()}catch(w){const S=`Failed to mark message as read: ${U(w)}`;f?f(S,"error"):console.warn(S)}},V=()=>{T(null),k()},P=N=>e.jsxs("button",{type:"button",className:oe("mailbox-item","agent-mail-tab-message",h==="inbox"&&!N.read&&"unread",A===N.id&&"agent-mail-tab-message--selected"),onClick:()=>void _(N),"aria-pressed":A===N.id,children:[e.jsx("div",{className:"mailbox-item-avatar",children:(h==="inbox"?N.fromType:N.toType)==="agent"?e.jsx(Kt,{size:16}):e.jsx(Ta,{size:16})}),e.jsxs("div",{className:"mailbox-item-content",children:[e.jsxs("div",{className:"mailbox-item-header",children:[h==="inbox"?e.jsx("span",{className:"mailbox-item-from",children:yt(N.fromId,N.fromType,m,n)}):e.jsx("span",{className:"mailbox-item-to",children:n("agents.mailTo","To: {{recipient}}",{recipient:yt(N.toId,N.toType,m,n)})}),e.jsx("span",{className:"mailbox-item-time",children:un(N.createdAt,n)})]}),e.jsxs("div",{className:"mailbox-item-preview",children:[N.content.slice(0,80),N.content.length>80?"…":""]})]}),h==="inbox"&&!N.read?e.jsx("div",{className:"mailbox-item-unread-dot","aria-label":n("agents.unreadMessage","Unread message")}):null]},N.id);return e.jsxs("div",{className:"agent-mail-tab",children:[e.jsxs("div",{className:"agent-mail-tab-header",children:[e.jsx("h3",{children:n("agents.agentMail","{{name}} Mail",{name:t.name})}),e.jsxs("button",{className:"btn btn-sm",onClick:V,disabled:l,children:[e.jsx(Rt,{size:14}),n("common.refresh","Refresh")]})]}),e.jsxs("div",{className:"mailbox-agent-subtabs","data-testid":"agent-detail-mail-subtabs",children:[e.jsxs("button",{className:oe("btn","btn-sm","btn-secondary","mailbox-agent-subtab",h==="inbox"&&"active"),onClick:()=>u("inbox"),children:[e.jsx(us,{size:12}),e.jsx("span",{children:n("agents.inbox","Inbox")}),(r?.unreadCount??0)>0?e.jsx("span",{className:"mailbox-tab-badge",children:r?.unreadCount}):null]}),e.jsxs("button",{className:oe("btn","btn-sm","btn-secondary","mailbox-agent-subtab",h==="outbox"&&"active"),onClick:()=>u("outbox"),children:[e.jsx(ms,{size:12}),e.jsx("span",{children:n("agents.outbox","Outbox")})]})]}),l&&!r?e.jsxs("div",{className:"agent-detail-loading agent-detail-loading--inline",role:"status","aria-live":"polite",children:[e.jsx(q,{className:"animate-spin",size:16}),e.jsx("span",{children:n("agents.loadingMailbox","Loading mailbox...")})]}):null,!l&&o?e.jsxs("div",{className:"agent-mail-tab-error",role:"alert",children:[e.jsx(Ls,{size:16}),e.jsx("span",{children:n("agents.mailboxLoadFailed","Failed to load mailbox: {{error}}",{error:o})})]}):null,!l&&!o?C?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:()=>T(null),children:[e.jsx(ws,{size:14}),h==="inbox"?n("agents.backToInbox","Back to Inbox"):n("agents.backToOutbox","Back to Outbox")]}),e.jsxs("div",{className:"agent-mail-tab-detail-meta",children:[e.jsxs("div",{className:"agent-mail-tab-detail-row",children:[e.jsx("span",{className:"agent-mail-tab-detail-label",children:n("agents.mailFrom","From")}),e.jsx("span",{children:yt(C.fromId,C.fromType,m,n)})]}),e.jsxs("div",{className:"agent-mail-tab-detail-row",children:[e.jsx("span",{className:"agent-mail-tab-detail-label",children:n("agents.mailToLabel","To")}),e.jsx("span",{children:yt(C.toId,C.toType,m,n)})]}),e.jsxs("div",{className:"agent-mail-tab-detail-row",children:[e.jsx("span",{className:"agent-mail-tab-detail-label",children:n("agents.mailType","Type")}),e.jsx("span",{children:C.type})]}),e.jsxs("div",{className:"agent-mail-tab-detail-row",children:[e.jsx("span",{className:"agent-mail-tab-detail-label",children:n("agents.mailSent","Sent")}),e.jsx("span",{children:new Date(C.createdAt).toLocaleString()})]}),C.metadata?.replyTo?.messageId?e.jsx("div",{className:"agent-mail-tab-reply-context",children:n("agents.replyingTo","↪ Replying to message {{id}}",{id:C.metadata.replyTo.messageId})}):null]}),e.jsx("div",{className:"agent-mail-tab-detail-body",children:C.content})]}):e.jsx("div",{className:"mailbox-list","data-testid":"agent-detail-mail-list",children:H.length===0?e.jsxs("div",{className:"mailbox-empty","data-testid":"agent-detail-mail-empty",children:[h==="inbox"?e.jsx(us,{size:32}):e.jsx(ms,{size:32}),e.jsx("p",{children:h==="inbox"?n("agents.noInboxMessages","No received messages for this agent"):n("agents.noOutboxMessages","No sent messages for this agent")})]}):H.map(P)}):null]})}function gn({addToast:t,agentId:r,projectId:l,agentState:o,agentName:s,initialRunId:f,preferActiveRun:k,runNowRefreshToken:n,isEphemeral:h}){const{t:u}=Ne("app"),[j,c]=a.useState([]),{confirm:m}=Ss(),[A,T]=a.useState(!0),[H,C]=a.useState(null),[_,V]=a.useState([]),[P,N]=a.useState(!1),[w,S]=a.useState(null),[E,L]=a.useState(!1),[W,Z]=a.useState(null),[$,J]=a.useState([]),M=a.useRef(!1),se=a.useRef(!1),F=a.useCallback(async()=>{try{const x=await ks(r,50,l);c(x)}catch(x){t(`Failed to load runs: ${U(x)}`,"error")}finally{T(!1)}},[r,l,t]);a.useEffect(()=>{F()},[F]),a.useEffect(()=>{if(h){Z(null),J([]);return}const x=l?`?projectId=${encodeURIComponent(l)}`:"";fetch(`/api/agents/${encodeURIComponent(r)}/token-usage${x}`).then(async v=>{if(!v.ok){if(v.status===400){Z(null);return}throw new Error(`Request failed: ${v.status}`)}const ie=await v.json();Z(ie)}).catch(v=>{t(`Failed to load cache hit ratio: ${U(v)}`,"error")}),xa(r,7,l).then(v=>J(v)).catch(v=>{const ie=U(v).toLowerCase();if(ie.includes("ephemeral")||ie.includes("400")){J([]);return}t(`Failed to load prompt sizes: ${U(v)}`,"error")})},[r,l,t,h]),a.useEffect(()=>{if(!se.current){se.current=!0;return}T(!0),F()},[F,n]);const G=j.some(x=>x.status==="active"),b=H?j.find(x=>x.id===H)?.status:void 0;a.useEffect(()=>{if(!G)return;const x=setInterval(()=>{F()},5e3);return()=>clearInterval(x)},[G,F]),a.useEffect(()=>{if(!H||b!=="active")return;const x=l?`?projectId=${encodeURIComponent(l)}`:"";return Nt(`/api/agents/${encodeURIComponent(r)}/runs/${encodeURIComponent(H)}/logs/stream${x}`,{events:{"agent:log":v=>{try{const ie=JSON.parse(v.data);V(ae=>[...ae,ie])}catch{}}}})},[H,b,r,l]);const y=a.useCallback(async x=>{if(H===x){C(null),V([]),S(null);return}C(x),N(!0),L(!0),V([]),S(null);try{const[v,ie]=await Promise.all([Cs(r,x,l),va(r,x,l)]);V(v),S(ie)}catch(v){t(u("agents.runDetailsFailed","Failed to load run details: {{error}}",{error:U(v)}),"error"),V([]),S(null)}finally{N(!1),L(!1)}},[H,r,l,t]);a.useEffect(()=>{M.current=!1},[r,f,k]),a.useEffect(()=>{if(j.length===0||A||M.current)return;const x=f?j.find(v=>v.id===f):k?j.find(v=>v.status==="active"):null;M.current=!0,x&&y(x.id)},[f,k,j,A,y]);const d=async()=>{if(await m({title:u("agents.stopRunTitle","Stop Active Run"),message:u("agents.stopRunConfirm","Stop the active run? The agent's work will be interrupted."),danger:!0}))try{await Ea(r,l),t(u("agents.runStopped","Run stopped"),"success"),T(!0),F()}catch(v){t(u("agents.stopRunFailed","Failed to stop run: {{error}}",{error:U(v)}),"error")}};if(A&&j.length===0)return e.jsx("div",{className:"runs-tab",children:e.jsxs("div",{className:"runs-loading-row",children:[e.jsx(q,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:u("agents.loadingRuns","Loading runs...")})]})});if(j.length===0)return e.jsx("div",{className:"runs-tab",children:e.jsxs("div",{className:"runs-empty",children:[e.jsx(Ct,{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 D=[...j].sort((x,v)=>new Date(v.startedAt).getTime()-new Date(x.startedAt).getTime()),X=D.filter(x=>x.status==="active"),pe=D.filter(x=>x.status!=="active"),ue=x=>x?e.jsxs("div",{className:"run-usage",children:[e.jsx("span",{children:u("agents.inputTokens","Input: {{value}}",{value:x.inputTokens.toLocaleString()})}),e.jsx("span",{children:u("agents.outputTokens","Output: {{value}}",{value:x.outputTokens.toLocaleString()})}),x.cachedTokens>0&&e.jsx("span",{children:u("agents.cacheReadTokens","Cache read: {{value}}",{value:x.cachedTokens.toLocaleString()})}),(x.cacheWriteTokens??0)>0&&e.jsx("span",{children:u("agents.cacheWriteTokens","Cache write: {{value}}",{value:(x.cacheWriteTokens??0).toLocaleString()})})]}):null,Re=(x,v,ie)=>{const ae=wt[x.status]||wt.completed,We=ae.icon,ze=x.endedAt?hn(new Date(x.startedAt),new Date(x.endedAt)):u("agents.inProgress","In progress"),Me=H===x.id;return e.jsxs("div",{children:[e.jsxs("div",{className:oe("run-card",ie&&"run-card--active",Me&&"run-card--selected","run-card--clickable"),onClick:()=>void y(x.id),role:"button",tabIndex:0,"aria-expanded":Me,"aria-label":u("agents.runAriaLabel","{{active}}run {{id}}, {{status}}",{active:ie?u("agents.activePrefix","Active "):"",id:x.id.slice(0,8),status:x.status}),onKeyDown:ce=>{(ce.key==="Enter"||ce.key===" ")&&(ce.preventDefault(),y(x.id))},children:[e.jsxs("div",{className:"run-header",children:[e.jsxs("div",{className:"run-header-group",children:[Me?e.jsx(ys,{size:14}):e.jsx(Ns,{size:14}),ie?e.jsxs("span",{className:"run-live-indicator",children:[e.jsx("span",{className:"live-dot"}),u("agents.liveRun","Live Run")]}):e.jsxs("span",{className:"run-id",children:["#",v+1," ",x.id.slice(0,8)]})]}),e.jsxs("div",{className:"run-header-group",children:[x.invocationSource&&e.jsx("span",{className:"badge run-badge--compact",children:x.invocationSource}),ie&&e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:ce=>{ce.preventDefault(),ce.stopPropagation(),d()},"aria-label":u("agents.stopActiveRun","Stop active run"),children:[e.jsx(Ze,{size:12})," ",u("agents.stop","Stop")]}),e.jsxs("span",{className:oe("run-status",x.status),children:[e.jsx(We,{size:14,style:{color:ae.color}}),x.status]}),x.heartbeatProcedureSource==="custom"&&e.jsx("span",{className:"badge run-badge--compact",children:u("agents.heartbeatCustom","Heartbeat: custom")})]})]}),e.jsxs("div",{className:"run-details",children:[e.jsx("span",{children:u("agents.runStarted","Started {{time}}",{time:Qe(x.startedAt,u)})}),e.jsx("span",{children:"•"}),e.jsx("span",{children:ze}),x.triggerDetail&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsx("span",{className:"text-muted",children:x.triggerDetail})]})]})]}),Me&&e.jsxs("div",{className:"run-logs-container",children:[E?e.jsxs("div",{className:"run-details-loading-state",children:[e.jsx(q,{size:14,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:u("agents.loadingDetails","Loading details...")})]}):w&&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")}),w.systemPrompt?e.jsx("pre",{className:"run-output-panel",children:w.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")}),w.executionPrompt?e.jsx("pre",{className:"run-output-panel",children:w.executionPrompt}):e.jsx("div",{className:"text-muted run-output-empty",children:u("agents.executionPromptNotCaptured","Execution prompt not captured for this run")})]})}),w.usageJson&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:u("agents.tokenUsage","Token Usage")}),ue(w.usageJson)]}),w.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:w.stdoutExcerpt.length>2e3?`${w.stdoutExcerpt.slice(0,2e3)}
|
|
17
|
-
|
|
18
|
-
... (truncated, ${w.stdoutExcerpt.length} chars total)`:w.stdoutExcerpt})]}),w.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(La,{errorText:w.stderrExcerpt,summaryPrefix:"Run error",issueContext:{surface:"AgentDetailView runs",agentId:r,agentName:s,agentState:o,runId:w.id,taskId:void 0,timestamp:w.startedAt}})]}),w.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(w.resultJson,null,2)})]}),w.contextSnapshot&&Object.keys(w.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(w.contextSnapshot).map(([ce,Fe])=>e.jsxs("span",{className:"run-context-item",children:[e.jsxs("span",{className:"text-muted",children:[ce,":"]})," ",e.jsx("span",{children:String(Fe)})]},ce))})]}),!w.stdoutExcerpt&&!w.stderrExcerpt&&!w.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")}),P?e.jsxs("div",{className:"run-details-loading-state",children:[e.jsx(q,{size:14,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:u("agents.loadingLogs","Loading logs...")})]}):_.length===0?e.jsx("div",{className:"text-muted run-output-empty",children:u("agents.noLogsForRun","No logs available for this run")}):e.jsx(zs,{entries:_,loading:!1})]})]})]},x.id)},Se=(x,v)=>e.jsxs("div",{className:"run-context-item",children:[e.jsxs("span",{className:"text-muted",children:[x,":"]})," ",e.jsx("span",{children:u("agents.cacheWindowSummary","{{percent}}% ({{cached}} / {{written}} / {{input}} / {{tasks}})",{percent:(v.hitRatio*100).toFixed(1),cached:v.totalCachedTokens.toLocaleString(),written:v.totalCacheWriteTokens.toLocaleString(),input:v.totalInputTokens.toLocaleString(),tasks:v.nTasks.toLocaleString()})})]},x),I=$[0],ee=[...$].reverse(),Le=Math.max(1,...ee.map(x=>x.execChars)),De=ee.map((x,v)=>{const ie=ee.length<=1?0:v/(ee.length-1)*100,ae=100-Math.round(x.execChars/Le*100);return`${ie},${ae}`}).join(" ");return e.jsxs("div",{className:"runs-tab",children:[$.length>0&&I&&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:De})]}),e.jsxs("span",{className:"prompt-size-values",children:[I.systemChars.toLocaleString()," / ",I.execChars.toLocaleString()," / ",I.totalChars.toLocaleString()]})]})]}),W&&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:[Se(u("agents.last24h","Last 24h"),W.last24h),Se(u("agents.last7d","Last 7d"),W.last7d),Se(u("agents.allTime","All time"),W.allTime)]})]}),e.jsxs("div",{className:"runs-toolbar runs-toolbar--between",children:[e.jsxs("span",{className:"runs-toolbar-meta",children:[u("agents.runsCount",{count:j.length,defaultValue_one:"{{count}} run",defaultValue_other:"{{count}} runs"}),G&&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:G&&e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void d(),"aria-label":u("agents.stopActiveRunFor","Stop active run for {{name}}",{name:s??r}),children:[e.jsx(Ze,{size:14})," ",u("agents.stopRun","Stop Run")]})})]}),X.map((x,v)=>Re(x,v,!0)),pe.map((x,v)=>Re(x,X.length+v,!1))]})}function hn(t,r){const l=Math.floor((r.getTime()-t.getTime())/1e3);return l<60?`${l}s`:l<3600?`${Math.floor(l/60)}m ${l%60}s`:`${Math.floor(l/3600)}h ${Math.floor(l%3600/60)}m`}function fn(t){const r=t.title?.trim()||t.description?.trim()||t.id;return r.length>80?`${r.slice(0,77)}...`:r}function pn({agentId:t,projectId:r,addToast:l}){const{t:o}=Ne("app"),[s,f]=a.useState([]),[k,n]=a.useState(!0);return a.useEffect(()=>{let h=!1;return n(!0),ja(t,r).then(u=>{h||f(u)}).catch(u=>{h||(f([]),l(o("agents.loadTasksFailed","Failed to load assigned tasks: {{error}}",{error:U(u)}),"error"))}).finally(()=>{h||n(!1)}),()=>{h=!0}},[t,r,l]),k?e.jsxs("div",{className:"agent-tasks-empty",children:[e.jsx(q,{size:16,className:"animate-spin"}),e.jsx("p",{children:o("agents.loadingTasks","Loading assigned tasks...")})]}):s.length===0?e.jsxs("div",{className:"agent-tasks-empty",children:[e.jsx(As,{size:18}),e.jsx("p",{children:o("agents.noTasksAssigned","No tasks assigned to this agent")})]}):e.jsx("div",{className:"agent-tasks-list",children:s.map(h=>e.jsxs("a",{className:"agent-task-item",href:`/tasks/${h.id}`,children:[e.jsxs("div",{className:"agent-task-row",children:[e.jsx("span",{className:"agent-task-id",children:h.id}),e.jsx("span",{className:`agent-task-column column-${h.column}`,children:{triage:o("board.triage","Planning"),todo:o("board.todo","Todo"),"in-progress":o("board.inProgress","In Progress"),"in-review":o("board.inReview","In Review"),done:o("board.done","Done"),archived:o("board.archived","Archived")}[h.column]??h.column})]}),e.jsx("div",{className:"agent-task-title",title:h.title||h.description||h.id,children:fn(h)}),e.jsxs("div",{className:"agent-task-status",children:[h.status??"idle"," · ",o("agents.taskUpdated","Updated {{time}}",{time:Qe(h.updatedAt,o)})]})]},h.id))})}const rt=[{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 r={};for(const l of rt){const o=t[l.key]?.trim();if(o){if(l.type==="number"){const s=Number(o);if(Number.isNaN(s)||!Number.isFinite(s)){r[l.key]=`"${l.label}" must be a valid number`;continue}l.min!==void 0&&s<l.min&&(r[l.key]=`"${l.label}" must be at least ${l.min.toLocaleString()}`),l.max!==void 0&&s>l.max&&(r[l.key]=`"${l.label}" must be at most ${l.max.toLocaleString()}`)}if(l.type==="select"){const s=l.options?.map(f=>f.value)??[];s.length>0&&!s.includes(o)&&(r[l.key]=`"${l.label}" must be one of: ${s.join(", ")}`)}}}return r}function xn({agent:t,projectId:r,addToast:l,onSaved:o}){const{t:s}=Ne("app"),[f,k]=a.useState(t.soul??""),[n,h]=a.useState(!1),[u,j]=a.useState(!1),[c,m]=a.useState(!1),A=a.useRef(null);a.useEffect(()=>{k(t.soul??""),j(!1),m(!1)},[t.id,t.soul]),a.useEffect(()=>()=>{A.current&&clearTimeout(A.current)},[]);const T=f!==(t.soul??""),H=async()=>{if(f.length>1e4){l(s("agents.soulTooLong","Soul must be at most 10,000 characters"),"error");return}h(!0);try{await Da(t.id,f,r),l(s("agents.soulSaved","Soul saved"),"success"),j(!0),A.current&&clearTimeout(A.current),A.current=setTimeout(()=>j(!1),3e3),await o()}catch(C){l(s("agents.soulSaveFailed","Failed to save soul: {{error}}",{error:U(C)}),"error")}finally{h(!1)}};return e.jsx("div",{className:"config-tab",children:e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:s("agents.soulTitle","Soul")}),e.jsx("p",{className:"config-description",children:s("agents.soulDescription","Define this agent's personality and identity.")}),e.jsx("div",{className:"config-fields",children:e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-soul",children:s("agents.agentSoulLabel","Agent Soul")}),e.jsx("div",{className:"agent-content-toolbar",children:e.jsxs("div",{className:"agent-content-mode-toggle",children:[e.jsxs("button",{className:`btn btn-sm ${c?"":"btn-primary"}`,onClick:()=>m(!1),disabled:!c,"aria-label":s("common.editMode","Edit mode"),children:[e.jsx(Mt,{size:14}),s("common.edit","Edit")]}),e.jsxs("button",{className:`btn btn-sm ${c?"btn-primary":""}`,onClick:()=>m(!0),disabled:c,"aria-label":s("common.previewMode","Preview mode"),children:[e.jsx(At,{size:14}),s("common.preview","Preview")]})]})}),c?f.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(Ft,{remarkPlugins:[Pt],children:f})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:s("agents.soulEmptyPreview","No soul defined yet. Switch to Edit mode to define the agent's personality.")}):e.jsx("textarea",{id:"agent-soul",className:"input config-textarea-mono",rows:12,placeholder:s("agents.soulPlaceholder","Describe this agent's personality, tone, and behavioral traits..."),value:f,onChange:C=>{k(C.target.value),j(!1)}}),!c&&e.jsx("span",{className:"config-hint",children:s("agents.soulHint","Defines the agent's character and identity. Max 10,000 characters.")})]})}),!c&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!T||n,onClick:()=>void H(),children:n?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),s("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(ge,{size:16}),s("agents.saveSoul","Save Soul")]})}),!T&&u&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ge,{size:14}),s("agents.soulSaved","Soul saved")]})]})]})})}function vn({agent:t,projectId:r,addToast:l,onSaved:o}){const{t:s}=Ne("app"),[f,k]=a.useState(t.memory??""),[n,h]=a.useState(!1),[u,j]=a.useState(!1),[c,m]=a.useState(!1),[A,T]=a.useState([]),[H,C]=a.useState(!1),[_,V]=a.useState(""),[P,N]=a.useState(""),[w,S]=a.useState(!1),[E,L]=a.useState(!1),[W,Z]=a.useState(!1),[$,J]=a.useState(!1),[M,se]=a.useState(""),F=a.useRef(null),G=a.useRef(null),b=t.state==="running",y=f!==(t.memory??""),d=a.useMemo(()=>A.find(I=>I.path===_),[A,_]),D=d?{"long-term":s("agents.memoryLayerLongTermDesc","Curated durable decisions, conventions, constraints, and pitfalls for this specific agent."),daily:s("agents.memoryLayerDailyDesc","Raw daily observations and open loops recorded by this agent."),dreams:s("agents.memoryLayerDreamsDesc","Synthesized patterns and emerging themes distilled from this agent's daily memory.")}[d.layer]??d.layer:s("agents.selectMemoryFile","Select a memory file to view or edit."),X=a.useCallback(async I=>{L(!0);try{const ee=await Na(t.id,I,r);V(ee.path),N(ee.content),S(!1),J(!1)}catch(ee){l(s("agents.memoryFileLoadFailed","Failed to load agent memory file: {{error}}",{error:U(ee)}),"error")}finally{L(!1)}},[t.id,r,l]),pe=a.useCallback(async(I="")=>{C(!0);try{const{files:ee}=await Sa(t.id,r);if(T(ee),ee.length===0){V(""),N(""),S(!1);return}const Le=on(ee,I);await X(Le)}catch(ee){l(s("agents.memoryFilesLoadFailed","Failed to load memory files: {{error}}",{error:U(ee)}),"error"),T([]),V(""),N(""),S(!1)}finally{C(!1)}},[t.id,r,l,X]);a.useEffect(()=>{k(t.memory??""),j(!1),m(!1),se(""),J(!1),pe()},[t.id,t.memory,pe]),a.useEffect(()=>()=>{F.current&&clearTimeout(F.current),G.current&&clearTimeout(G.current)},[]);const ue=async()=>{if(f.length>5e4){l(s("agents.memoryTooLong","Memory must be at most 50,000 characters"),"error");return}h(!0);try{await Ha(t.id,f,r),l(s("agents.memorySaved","Memory saved"),"success"),j(!0),F.current&&clearTimeout(F.current),F.current=setTimeout(()=>j(!1),3e3),await o()}catch(I){l(s("agents.memorySaveFailed","Failed to save memory: {{error}}",{error:U(I)}),"error")}finally{h(!1)}},Re=async I=>{if(!(!I||I===_)){if(w){se(s("agents.saveBeforeSwitch","Save the current file before switching to another file."));return}se(""),await X(I)}},Se=async()=>{if(_){Z(!0);try{await Ia(t.id,_,P,r),S(!1),J(!0),G.current&&clearTimeout(G.current),G.current=setTimeout(()=>J(!1),3e3),se(""),await pe(_),l(s("agents.memoryFileSaved","Agent memory file saved"),"success"),await o()}catch(I){l(s("agents.memoryFileSaveFailed","Failed to save agent memory file: {{error}}",{error:U(I)}),"error")}finally{Z(!1)}}};return e.jsx("div",{className:"config-tab",children:e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:s("agents.memoryTitle","Agent Memory")}),e.jsx("p",{className:"config-description",children:s("agents.memoryDescription","Store context that belongs to this agent only. Workspace memory, daily notes, dreams, and qmd search live in project settings under Project Memory.")}),b&&e.jsx("p",{className:"config-hint config-hint--block-spacing",children:s("agents.memoryReadOnly","Read-only while this agent is running.")}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-memory",children:s("agents.inlineMemoryLabel","Inline Memory")}),e.jsx("span",{className:"config-hint config-hint--block",children:s("agents.inlineMemoryHint","Short-form memory stored directly on the agent record and injected into prompts.")}),e.jsx("div",{className:"agent-content-toolbar",children:e.jsxs("div",{className:"agent-content-mode-toggle",children:[!b&&e.jsxs("button",{className:`btn btn-sm ${c?"":"btn-primary"}`,onClick:()=>m(!1),disabled:!c,"aria-label":s("agents.inlineMemoryEditMode","Inline memory edit mode"),children:[e.jsx(Mt,{size:14}),s("common.edit","Edit")]}),e.jsxs("button",{className:`btn btn-sm ${c?"btn-primary":""}`,onClick:()=>m(!0),disabled:c,"aria-label":s("agents.inlineMemoryPreviewMode","Inline memory preview mode"),children:[e.jsx(At,{size:14}),s("common.preview","Preview")]})]})}),c?f.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(Ft,{remarkPlugins:[Pt],children:f})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:s("agents.memoryEmptyPreview","No agent memory defined yet. Switch to Edit mode to add memory content.")}):e.jsx("textarea",{id:"agent-memory","aria-label":s("agents.memoryTitle","Agent Memory"),className:"input config-textarea-mono",rows:10,placeholder:s("agents.memoryPlaceholder","Durable preferences, operating habits, and context this agent should carry across tasks..."),value:f,readOnly:b,onChange:I=>{k(I.target.value),j(!1)}}),!c&&e.jsx("span",{className:"config-hint",children:s("agents.inlineMemoryFieldHint","This is the inline memory field on the agent JSON record. Max 50,000 characters.")}),!c&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!y||n||b,onClick:()=>void ue(),children:n?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),s("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(ge,{size:16}),s("agents.saveMemory","Save Memory")]})}),!y&&u&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ge,{size:14}),s("agents.memorySaved","Memory saved")]})]})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-memory-file-select",children:s("agents.memoryFilesLabel","Memory Files")}),e.jsxs("span",{className:"config-hint config-hint--block",children:[s("agents.memoryFilesHint","Full OpenClaw memory files at")," ",e.jsxs("code",{children:["agent/",t.name||t.id,"/memory/"]})," ",s("agents.memoryFilesHintSuffix","(MEMORY.md, DREAMS.md, and daily notes).")]}),e.jsx("select",{id:"agent-memory-file-select",className:"select",value:_,disabled:H||E||W||A.length===0,onChange:I=>{Re(I.target.value)},children:A.length===0?e.jsx("option",{value:"",children:s("agents.noMemoryFiles","No memory files found")}):A.map(I=>{const ee={"long-term":s("agents.memoryLayerLongTerm","Long-term"),daily:s("agents.memoryLayerDaily","Daily"),dreams:s("agents.memoryLayerDreams","Dreams")}[I.layer]??I.layer;return e.jsxs("option",{value:I.path,children:[ee," • ",I.label]},I.path)})}),H&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(q,{size:14,className:"animate-spin"}),s("agents.loadingMemoryFiles","Loading memory files…")]}),d&&e.jsxs("div",{className:"config-hint config-hint--top-spacing",children:[e.jsx("strong",{children:{"long-term":s("agents.memoryLayerLongTerm","Long-term"),daily:s("agents.memoryLayerDaily","Daily"),dreams:s("agents.memoryLayerDreams","Dreams")}[d.layer]??d.layer})," · ",D,e.jsx("br",{}),s("agents.memoryFileMeta","{{size}} bytes · updated {{date}}",{size:d.size.toLocaleString(),date:Qe(d.updatedAt,s)})]}),e.jsx("div",{className:"agent-memory-file-editor config-textarea-top-spacing",children:e.jsx(ka,{content:P,onChange:I=>{N(I),S(!0),J(!1),se("")},readOnly:b||!_||E,filePath:_||"MEMORY.md",forceToolbarActionsVisible:!0})}),E&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(q,{size:14,className:"animate-spin"}),s("agents.loadingFileContent","Loading file content…")]}),M&&e.jsx("span",{className:"config-hint config-hint--top-spacing config-hint--block",children:M}),e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!w||W||!_||b,onClick:()=>void Se(),children:W?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),s("agents.savingFile","Saving file…")]}):e.jsxs(e.Fragment,{children:[e.jsx(ge,{size:16}),s("agents.saveMemoryFile","Save Memory File")]})}),!w&&$&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ge,{size:14}),s("agents.memoryFileSaved","Memory file saved")]})]})]})]})]})})}function jn({agent:t,projectId:r,addToast:l,onSaved:o}){const{t:s}=Ne("app"),[f,k]=a.useState(t.instructionsText??""),[n,h]=a.useState(t.instructionsPath??""),[u,j]=a.useState(!1),[c,m]=a.useState(""),[A,T]=a.useState(!1),[H,C]=a.useState(!1),[_,V]=a.useState(!1),[P,N]=a.useState(!1),[w,S]=a.useState(!1),[E,L]=a.useState(!1),W=a.useRef(null),Z=a.useRef(null);a.useEffect(()=>{const F=n.trim();if(!F){m(""),C(!1);return}T(!0),Hs("project",F).then(G=>{m(G.content),C(!1)}).catch(G=>{const b=U(G);b.includes("ENOENT")||b.includes("Not found")||b.includes("not found")?(m(""),C(!1)):(l(`Failed to load instructions file: ${b}`,"error"),m(""))}).finally(()=>{T(!1)})},[n,l]),a.useEffect(()=>{k(t.instructionsText??""),h(t.instructionsPath??""),S(!1),L(!1),j(!1)},[t.id,t.instructionsText,t.instructionsPath]),a.useEffect(()=>()=>{W.current&&clearTimeout(W.current),Z.current&&clearTimeout(Z.current)},[]);const $=(()=>{const F=f??"",G=t.instructionsText??"",b=n?.trim()??"",y=t.instructionsPath?.trim()??"";return F!==G||b!==y})(),J=async()=>{V(!0);try{await za(t.id,{instructionsText:f||void 0,instructionsPath:n.trim()||void 0},r),l(s("agents.instructionsSaved","Instructions saved"),"success"),S(!0),W.current&&clearTimeout(W.current),W.current=setTimeout(()=>S(!1),3e3),await o()}catch(F){l(s("agents.instructionsSaveFailed","Failed to save instructions: {{error}}",{error:U(F)}),"error")}finally{V(!1)}},M=async()=>{const F=n.trim();if(!F){l(s("agents.noInstructionsPath","No instructions file path set"),"error");return}N(!0);try{await Is("project",F,c),l(s("agents.instructionsFileSaved","Instructions file saved"),"success"),C(!1),L(!0),Z.current&&clearTimeout(Z.current),Z.current=setTimeout(()=>L(!1),3e3),await o()}catch(G){l(s("agents.instructionsFileSaveFailed","Failed to save instructions file: {{error}}",{error:U(G)}),"error")}finally{N(!1)}},se=!!n.trim();return e.jsxs("div",{className:"config-tab",children:[e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:s("agents.instructionsTitle","Custom Instructions")}),e.jsx("p",{className:"config-description",children:s("agents.instructionsDescription","Append custom instructions to this agent's system prompt at execution time. Use this to customize behavior, coding style, or project conventions without modifying built-in prompts.")}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"instructions-text",children:s("agents.inlineInstructions","Inline Instructions")}),e.jsx("div",{className:"agent-content-toolbar",children:e.jsxs("div",{className:"agent-content-mode-toggle",children:[e.jsxs("button",{className:`btn btn-sm ${u?"":"btn-primary"}`,onClick:()=>j(!1),disabled:!u,"aria-label":s("common.editMode","Edit mode"),"data-testid":"instructions-edit-toggle",children:[e.jsx(Mt,{size:14}),s("common.edit","Edit")]}),e.jsxs("button",{className:`btn btn-sm ${u?"btn-primary":""}`,onClick:()=>j(!0),disabled:u,"aria-label":s("common.previewMode","Preview mode"),"data-testid":"instructions-preview-toggle",children:[e.jsx(At,{size:14}),s("common.preview","Preview")]})]})}),u?f.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(Ft,{remarkPlugins:[Pt],children:f})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:s("agents.instructionsEmptyPreview","No inline instructions defined yet. Switch to Edit mode to add instructions.")}):e.jsx("textarea",{id:"instructions-text",className:"input",rows:10,placeholder:s("agents.instructionsPlaceholder","Enter custom instructions to append to this agent's system prompt..."),value:f,onChange:F=>{k(F.target.value),S(!1)}}),!u&&e.jsx("span",{className:"config-hint",children:s("agents.instructionsHint","Markdown formatting supported. Max 50,000 characters.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"instructions-path",children:s("agents.instructionsPathLabel","Instructions File Path")}),e.jsx("input",{id:"instructions-path",type:"text",className:"input",placeholder:s("agents.instructionsPathPlaceholder","e.g., .fusion/agents/my-agent-instructions.md"),value:n,onChange:F=>{h(F.target.value),S(!1)}}),e.jsx("span",{className:"config-hint",children:s("agents.instructionsPathHint","Path to a .md file (relative to project root). Contents are read and appended at execution time.")})]})]}),!u&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!$||_,onClick:()=>void J(),children:_?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),s("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(ge,{size:16}),s("agents.saveInstructions","Save Instructions")]})}),!$&&w&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ge,{size:14}),s("agents.instructionsSaved","Instructions saved")]})]})]}),se&&e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:s("agents.instructionsFileEditorTitle","Instructions File Editor")}),e.jsx("p",{className:"config-description",children:s("agents.instructionsFileEditorDesc","Edit the instructions file directly. Changes are saved separately from the path configuration.")}),e.jsx("div",{className:"config-fields",children:e.jsxs("div",{className:"config-field",children:[e.jsxs("div",{className:"config-inline-header",children:[e.jsx("label",{htmlFor:"instructions-file-content",children:s("agents.fileContentLabel","File Content")}),A&&e.jsxs("span",{className:"config-hint config-hint--inline-tight",children:[e.jsx(q,{size:12,className:"animate-spin"}),s("common.loading","Loading...")]}),H&&!A&&e.jsx("span",{className:"config-hint config-hint--warning",children:s("common.unsavedChanges","Unsaved changes")})]}),e.jsx("textarea",{id:"instructions-file-content",className:"input config-textarea-mono",rows:20,placeholder:s("agents.fileContentPlaceholder","File content will appear here when loaded..."),value:c,readOnly:A,onChange:F=>{m(F.target.value),C(!0),L(!1)}}),e.jsx("span",{className:"config-hint",children:s("agents.fileContentHint","Edit the markdown file content directly. Save separately using the button below.")})]})}),e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!H||P,onClick:()=>void M(),children:P?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),s("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(ge,{size:16}),s("agents.saveFile","Save File")]})}),!H&&E&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ge,{size:14}),s("agents.fileSaved","File saved")]})]})]})]})}function bs(t){const r=t??{},l={};return r.heartbeatIntervalMs!==void 0&&r.heartbeatIntervalMs!==null&&(l.heartbeatIntervalMs=String(Number(r.heartbeatIntervalMs)/1e3)),r.heartbeatTimeoutMs!==void 0&&r.heartbeatTimeoutMs!==null&&(l.heartbeatTimeoutMs=String(Number(r.heartbeatTimeoutMs)/1e3)),r.maxConcurrentRuns!==void 0&&r.maxConcurrentRuns!==null&&(l.maxConcurrentRuns=String(r.maxConcurrentRuns)),(r.messageResponseMode==="immediate"||r.messageResponseMode==="on-heartbeat")&&(l.messageResponseMode=r.messageResponseMode),r.autoClaimCandidatesInPrompt!==void 0&&r.autoClaimCandidatesInPrompt!==null&&(l.autoClaimCandidatesInPrompt=String(r.autoClaimCandidatesInPrompt)),l}function $t(t){return t?.enabled!==!1}function Ot(t){return t?.autoClaimRelevantTasks!==!1}function _t(t){return t?.engineerBacklogAutoClaim===!0}function Ut(t){return t?.runMissedHeartbeatOnStartup===!0}function Vt(t){return t?.allowParallelExecution!==!1}function Wt(t){return t?.skipHeartbeatWhenIdle===!0}function Jt(t){const r=t?.heartbeatScopeDiscipline;return r==="strict"||r==="lite"||r==="off"?r:""}function xs(t){const r=t?.heartbeatPromptTemplate;return r==="default"||r==="compact"?r:""}function vs(t){const r=(t??{}).budgetConfig,l={};return r&&(r.tokenBudget!==void 0&&r.tokenBudget!==null&&(l.tokenBudget=String(r.tokenBudget)),r.usageThreshold!==void 0&&r.usageThreshold!==null&&(l.usageThreshold=String(Number(r.usageThreshold)*100)),r.budgetPeriod!==void 0&&r.budgetPeriod!==null&&(l.budgetPeriod=String(r.budgetPeriod)),r.resetDay!==void 0&&r.resetDay!==null&&(l.resetDay=String(r.resetDay))),l}function yn({agent:t,projectId:r,addToast:l,onSaved:o}){const{t:s}=Ne("app"),[f,k]=a.useState(!1),[n,h]=a.useState(!1),[u,j]=a.useState(!1),[c,m]=a.useState(!1),[A,T]=a.useState(!1),[H,C]=a.useState(""),[_,V]=a.useState(!1),[P,N]=a.useState(null),[w,S]=a.useState(!1),E=a.useRef(null),L=t.heartbeatProcedurePath?.trim(),W=`.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`,$=t.id.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"agent",J=!!(L&&(L===W||L===Z||new RegExp(`^\\.fusion/agents/[^/]+-${$}/HEARTBEAT\\.md$`).test(L))),M=!!L,se=a.useCallback(async y=>{j(!0),N(null);try{const d=await Hs("project",y,r);C(d.content),V(!1)}catch(d){const D=U(d);N(D),l(s("agents.heartbeatFileLoadFailed","Failed to load heartbeat procedure file: {{error}}",{error:D}),"error")}finally{j(!1)}},[l,r]);a.useEffect(()=>{h(!1),T(!1),C(""),V(!1),N(null),j(!1),m(!1),S(!1)},[t.id,L]),a.useEffect(()=>()=>{E.current&&clearTimeout(E.current)},[]);const F=async()=>{L&&(h(!0),await se(L))},G=async()=>{if(L){m(!0);try{await Is("project",L,H,r),V(!1),S(!0),l(s("agents.heartbeatFileSaved","Heartbeat procedure file saved"),"success"),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>S(!1),3e3),await o()}catch(y){l(s("agents.heartbeatFileSaveFailed","Failed to save heartbeat procedure file: {{error}}",{error:U(y)}),"error")}finally{m(!1)}}},b=async()=>{k(!0);try{const y=await Oa(t.id,r);l(y.procedureFileSeeded?s("agents.heartbeatProcedureFileReady","Heartbeat procedure file ready at {{path}}",{path:y.heartbeatProcedurePath}):s("agents.heartbeatProcedurePathSet","Heartbeat procedure path set to {{path}}",{path:y.heartbeatProcedurePath}),"success"),await o()}catch(y){l(s("agents.heartbeatUpgradeFailed","Failed to upgrade heartbeat procedure: {{error}}",{error:U(y)}),"error")}finally{k(!1)}};return e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:s("agents.heartbeatProcedureTitle","Heartbeat Procedure")}),e.jsxs("p",{className:"config-description",children:[s("agents.heartbeatProcedureDesc","The per-tick procedure this agent runs every wake. Defaults to a per-agent markdown file (for example")," ",e.jsx("code",{children:".fusion/agents/ceo-agent2736/HEARTBEAT.md"}),s("agents.heartbeatProcedureDescSuffix",") that you can edit. Legacy id-only default paths remain valid. Resets on every tick — no need to restart the agent after editing.")]}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsxs("span",{className:"config-hint",children:[s("agents.currentPath","Current path:")," ",e.jsx("code",{children:L||s("agents.noneUsingBuiltIn","(none — using built-in default)")})]}),M&&e.jsx("div",{className:"heartbeat-procedure-actions",children:e.jsx("button",{className:"btn btn-sm",onClick:()=>void F(),disabled:u,children:u?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),s("agents.loadingFile","Loading file…")]}):e.jsxs(e.Fragment,{children:[e.jsx(ot,{size:16}),s("agents.viewHeartbeatMarkdown","View Heartbeat Markdown")]})})})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("button",{className:"btn",disabled:f||J,onClick:()=>void b(),"aria-label":s("agents.upgradeToDefaultAriaLabel","Upgrade agent to default heartbeat procedure file"),children:f?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),s("agents.upgrading","Upgrading…")]}):J?e.jsxs(e.Fragment,{children:[e.jsx(ge,{size:16}),s("agents.alreadyOnDefault","Already on default")]}):s("agents.upgradeToDefault","Upgrade to Default Heartbeat Procedure")}),e.jsxs("span",{className:"config-hint",children:[s("agents.upgradeHint","Sets")," ",e.jsx("code",{children:"heartbeatProcedurePath"})," ",s("agents.upgradeHintTo","to")," ",e.jsx("code",{children:W})," ",s("agents.upgradeHintSuffix","and seeds the file from the built-in template if it doesn't exist. Each agent gets its own per-agent file, so edits stay scoped to this agent. Operator edits to the file are preserved.")]})]})]}),n&&M&&L&&e.jsxs("div",{className:"config-fields heartbeat-procedure-viewer",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"heartbeat-procedure-file-content",children:s("agents.heartbeatProcedureFileLabel","Heartbeat Procedure File")}),e.jsxs("div",{className:"agent-content-toolbar",children:[e.jsxs("div",{className:"agent-content-mode-toggle",children:[e.jsxs("button",{className:`btn btn-sm ${A?"":"btn-primary"}`,onClick:()=>T(!1),disabled:!A,"aria-label":s("agents.heartbeatFileEditMode","Heartbeat file edit mode"),children:[e.jsx(Mt,{size:14}),s("common.edit","Edit")]}),e.jsxs("button",{className:`btn btn-sm ${A?"btn-primary":""}`,onClick:()=>T(!0),disabled:A,"aria-label":s("agents.heartbeatFilePreviewMode","Heartbeat file preview mode"),children:[e.jsx(At,{size:14}),s("common.preview","Preview")]})]}),u&&e.jsxs("span",{className:"config-hint heartbeat-procedure-status",children:[e.jsx(q,{size:12,className:"animate-spin"}),s("common.loading","Loading...")]}),_&&!u&&e.jsx("span",{className:"config-hint heartbeat-procedure-status heartbeat-procedure-status--warning",children:s("common.unsavedChanges","Unsaved changes")})]}),A?H.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(Ft,{remarkPlugins:[Pt],children:H})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:s("agents.heartbeatFileEmptyPreview","No heartbeat procedure markdown content yet.")}):e.jsx("textarea",{id:"heartbeat-procedure-file-content",className:"input",rows:16,value:H,readOnly:u,placeholder:s("agents.heartbeatFilePlaceholder","Heartbeat procedure markdown file content will appear here..."),onChange:y=>{C(y.target.value),V(!0),S(!1)}}),P&&e.jsx("span",{className:"config-error",children:s("agents.fileLoadError","Failed to load file: {{error}}",{error:P})}),e.jsxs("span",{className:"config-hint",children:[s("agents.heartbeatFileEditorHint","This editor writes directly to")," ",e.jsx("code",{children:L}),"."]})]}),!A&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!_||c||u,onClick:()=>void G(),children:c?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),s("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(ge,{size:16}),s("agents.saveHeartbeatFile","Save Heartbeat File")]})}),!_&&w&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ge,{size:14}),s("agents.fileSaved","File saved")]})]})]})]})}function Nn({agent:t,projectId:r,addToast:l,onSaved:o,onHasChangesChange:s,onDelete:f,onAgentDraftApplied:k}){const{t:n}=Ne("app"),[h,u]=a.useState(t.name),[j,c]=a.useState(t.role),[m,A]=a.useState(t.title??""),[T,H]=a.useState(t.icon??""),[C,_]=a.useState(t.reportsTo??""),[V,P]=a.useState([]),[N,w]=a.useState(!1),[S,E]=a.useState(!1),[L,W]=a.useState(!1),Z=a.useRef(null),[$,J]=a.useState(()=>{const i={};for(const g of rt){const R=t.metadata[g.key];R!=null&&(i[g.key]=String(R))}return i}),[M,se]=a.useState(()=>bs(t.runtimeConfig)),[F,G]=a.useState(()=>$t(t.runtimeConfig)),[b,y]=a.useState(()=>Ot(t.runtimeConfig)),[d,D]=a.useState(()=>_t(t.runtimeConfig)),[X,pe]=a.useState(()=>Ut(t.runtimeConfig)),[ue,Re]=a.useState(()=>Vt(t.runtimeConfig)),[Se,I]=a.useState(()=>Wt(t.runtimeConfig)),[ee,Le]=a.useState(()=>Jt(t.runtimeConfig)),[De,x]=a.useState(()=>xs(t.runtimeConfig)),[v,ie]=a.useState(()=>vs(t.runtimeConfig)),[ae,We]=a.useState(t.bundleConfig?.mode??""),[ze,Me]=a.useState(t.bundleConfig?.entryFile??"AGENTS.md"),[ce,Fe]=a.useState(t.bundleConfig?.externalPath??""),[ne,ct]=a.useState(t.bundleConfig?.files??[]),[Pe,ve]=a.useState(Array.isArray(t.metadata?.skills)?t.metadata.skills:[]),{favoriteProviders:dt,favoriteModels:Xe,toggleFavoriteProvider:Tt,toggleFavoriteModel:et}=Ca(),[Be,Te]=a.useState([]),[ut,tt]=a.useState(!1),[Ue,mt]=a.useState([]),[gt,Je]=a.useState(!1),ke=(()=>{const i=t.runtimeConfig??{};return i.modelProvider&&i.modelId?`${i.modelProvider}/${i.modelId}`:typeof i.model=="string"&&i.model.includes("/")?i.model:""})(),He=typeof t.runtimeConfig?.runtimeHint=="string"?t.runtimeConfig.runtimeHint:"",[he,$e]=a.useState(He?"runtime":"model"),[p,z]=a.useState(ke),[B,O]=a.useState(He),[re,fe]=a.useState(t.permissionPolicy),[Ce,Ae]=a.useState(t.permissions??{}),[je,st]=a.useState(void 0),Ge=C.trim(),ht=a.useMemo(()=>V.filter(i=>i.id!==t.id),[V,t.id]),ft=!!Ge&&!ht.some(i=>i.id===Ge),me=a.useMemo(()=>({name:h,role:j,title:m||void 0,instructionsText:t.instructionsText,soul:t.soul,memory:t.memory,reportsTo:C||void 0,skills:Pe,model:p||void 0,runtimeHint:he==="runtime"&&B||void 0,thinkingLevel:$.thinkingLevel??void 0,maxTurns:$.maxTurns?Number($.maxTurns):void 0,heartbeatIntervalMs:M.heartbeatIntervalMs?Number(M.heartbeatIntervalMs)*1e3:void 0,heartbeatTimeoutMs:M.heartbeatTimeoutMs?Number(M.heartbeatTimeoutMs)*1e3:void 0,maxConcurrentRuns:M.maxConcurrentRuns?Number(M.maxConcurrentRuns):void 0,messageResponseMode:M.messageResponseMode}),[t.instructionsText,t.memory,t.soul,$.maxTurns,$.thinkingLevel,M.heartbeatIntervalMs,M.heartbeatTimeoutMs,M.maxConcurrentRuns,M.messageResponseMode,p,h,C,j,he,B,Pe,m]),qe=a.useCallback(i=>{u(i.name),c(i.role),A(i.title??""),H(i.icon??""),_(i.reportsTo??""),i.skills&&ve(i.skills),i.thinkingLevel&&J(R=>({...R,thinkingLevel:i.thinkingLevel})),i.maxTurns!==void 0&&J(R=>({...R,maxTurns:String(i.maxTurns)})),i.runtimeHint!==void 0?($e("runtime"),O(i.runtimeHint??""),i.runtimeHint&&z("")):i.model!==void 0&&($e("model"),z(i.model??""),O(""));const g=Object.fromEntries(Object.entries({name:i.name,role:i.role,title:i.title,icon:i.icon,reportsTo:i.reportsTo,instructionsText:i.instructionsText,soul:i.soul,memory:i.memory}).filter(([,R])=>R!==void 0));k?.(g),W(!1),l(n("agents.interviewDraftApplied","Interview draft applied. Review and save when ready."),"success")},[l,k]);a.useEffect(()=>{fe(t.permissionPolicy)},[t.permissionPolicy]),a.useEffect(()=>{Ae(t.permissions??{})},[t.permissions]),a.useEffect(()=>{wa(r).then(i=>st(i.project?.defaultAgentPermissionPolicy)).catch(()=>st(void 0))},[r]);const pt=async i=>{fe(i);try{await It(t.id,{permissionPolicy:i},r),await o(),l(n("agents.permissionPolicyUpdated","Permission policy updated"),"success")}catch(g){l(n("agents.permissionPolicyFailed","Failed to update permission policy: {{error}}",{error:U(g)}),"error")}},Bs=a.useMemo(()=>new Set(sn[j]??[]),[j]),$s=a.useMemo(()=>new Set(gs.filter(i=>Ce[i]===!0)),[Ce]),Os=async(i,g)=>{const R={...Ce};g?R[i]=!0:delete R[i],Ae(R);try{await It(t.id,{permissions:R},r),await o(),l(n("agents.capabilityPermissionsUpdated","Capability grants updated"),"success")}catch(Q){Ae(t.permissions??{}),l(n("agents.capabilityPermissionsFailed","Failed to update capability grants: {{error}}",{error:U(Q)}),"error")}};a.useEffect(()=>{let i=!1;return w(!0),kt(void 0,r).then(g=>{i||P(g)}).catch(()=>{i||P([])}).finally(()=>{i||w(!1)}),()=>{i=!0}},[r]),a.useEffect(()=>{tt(!0),Ra().then(i=>{Te(i.models)}).catch(()=>{}).finally(()=>tt(!1))},[]),a.useEffect(()=>{Je(!0),Es(r).then(mt).catch(()=>mt([])).finally(()=>Je(!1))},[r]);const[Oe,Et]=a.useState(null),[Qt,Xt]=a.useState(!1);a.useEffect(()=>{Gt(t.id,r).then(Et).catch(()=>Et(null))},[t.id,r]);const _s=async()=>{Xt(!0);try{await Ba(t.id,r),l(n("agents.budgetResetSuccess","Budget usage reset successfully"),"success");const i=await Gt(t.id,r);Et(i)}catch(i){l(n("agents.budgetResetFailed","Failed to reset budget: {{error}}",{error:U(i)}),"error")}finally{Xt(!1)}},[_e,es]=a.useState(!1),[Y,Ve]=a.useState({}),[Us,Ye]=a.useState(!1),[Lt,bt]=a.useState(null),ts=t.state==="idle"||t.state==="paused",at=a.useRef(null),ss=a.useRef(null),as=a.useRef(null),xt=a.useRef(0);a.useEffect(()=>()=>{at.current&&clearTimeout(at.current)},[]);const we=(()=>{if(h!==t.name||j!==t.role||m!==(t.title??"")||T!==(t.icon??"")||C!==(t.reportsTo??"")||ae!==(t.bundleConfig?.mode??"")||ze!==(t.bundleConfig?.entryFile??"AGENTS.md")||ce!==(t.bundleConfig?.externalPath??"")||JSON.stringify(ne)!==JSON.stringify(t.bundleConfig?.files??[]))return!0;for(const te of rt){const be=$[te.key]?.trim()??"",xe=t.metadata[te.key]!==void 0&&t.metadata[te.key]!==null?String(t.metadata[te.key]):"";if(be!==xe)return!0}const i=t.runtimeConfig??{};if(F!==$t(t.runtimeConfig)||b!==Ot(t.runtimeConfig)||d!==_t(t.runtimeConfig)||X!==Ut(t.runtimeConfig)||ue!==Vt(t.runtimeConfig)||Se!==Wt(t.runtimeConfig)||ee!==Jt(t.runtimeConfig)||De!==xs(t.runtimeConfig))return!0;for(const te of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns","messageResponseMode","autoClaimCandidatesInPrompt"]){const be=M[te]?.trim()??"";let xe=i[te]!==void 0&&i[te]!==null?String(i[te]):"";if((te==="heartbeatIntervalMs"||te==="heartbeatTimeoutMs")&&xe&&(xe=String(Number(xe)/1e3)),be!==xe)return!0}const g=i.budgetConfig;for(const te of["tokenBudget","budgetPeriod","resetDay"]){const be=v[te]?.trim()??"",xe=g?.[te]!==void 0&&g?.[te]!==null?String(g[te]):"";if(be!==xe)return!0}const R=v.usageThreshold?.trim()??"",Q=g?.usageThreshold!==void 0&&g?.usageThreshold!==null?String(Number(g.usageThreshold)*100):"";if(R!==Q)return!0;const ye=Array.isArray(t.metadata?.skills)?t.metadata.skills:[];return JSON.stringify(Pe)!==JSON.stringify(ye)||he!==(He?"runtime":"model")||p!==ke||B!==He})(),ns=a.useRef(null);a.useEffect(()=>{s&&ns.current!==we&&(ns.current=we,s(we))},[we,s]),a.useEffect(()=>()=>{s?.(!1)},[s]),a.useEffect(()=>{const i={id:t.id,updatedAt:t.updatedAt},g=ss.current;(!g||g.id!==i.id||g.updatedAt!==i.updatedAt)&&(we||(ss.current=i,se(bs(t.runtimeConfig)),G($t(t.runtimeConfig)),y(Ot(t.runtimeConfig)),D(_t(t.runtimeConfig)),pe(Ut(t.runtimeConfig)),Re(Vt(t.runtimeConfig)),I(Wt(t.runtimeConfig)),Le(Jt(t.runtimeConfig)),ie(vs(t.runtimeConfig)),z(ke),O(He),$e(He?"runtime":"model")))},[t,we,ke,He]);const is=(i,g)=>{J(R=>({...R,[i]:g})),Ye(!1),Y[i]&&Ve(R=>{const Q={...R};return delete Q[i],Q})},vt=(i,g)=>{se(R=>({...R,[i]:g})),Ye(!1),Y[i]&&Ve(R=>{const Q={...R};return delete Q[i],Q})},Vs=i=>{G(i),Ye(!1)},jt=(i,g)=>{ie(R=>({...R,[i]:g})),Ye(!1),Y[i]&&Ve(R=>{const Q={...R};return delete Q[i],Q})},Ee=a.useMemo(()=>{const i=bn($);for(const[K,le]of Object.entries({heartbeatIntervalMs:{label:"Heartbeat Interval",min:1},heartbeatTimeoutMs:{label:"Heartbeat Timeout",min:5},maxConcurrentRuns:{label:"Max Concurrent Runs",min:1}})){const Ie=M[K]?.trim();if(!Ie)continue;const Ke=Number(Ie);Number.isNaN(Ke)||!Number.isFinite(Ke)?i[K]=`"${le.label}" must be a valid number`:Ke<le.min&&(i[K]=`"${le.label}" must be at least ${le.min.toLocaleString()}`)}const g=M.autoClaimCandidatesInPrompt?.trim();if(g){const K=Number(g);(!Number.isInteger(K)||K<0||K>10)&&(i.autoClaimCandidatesInPrompt='"Auto-claim candidates in prompt" must be an integer between 0 and 10')}const R=M.messageResponseMode?.trim();R&&!["immediate","on-heartbeat"].includes(R)&&(i.messageResponseMode='"Message Response Mode" must be either immediate or on-heartbeat');const Q=v.tokenBudget?.trim();if(Q){const K=Number(Q);Number.isNaN(K)||!Number.isFinite(K)?i.tokenBudget='"Token Budget" must be a valid number':K<=0&&(i.tokenBudget='"Token Budget" must be greater than 0')}const ye=v.usageThreshold?.trim();if(ye){const K=Number(ye);Number.isNaN(K)||!Number.isFinite(K)?i.usageThreshold='"Usage Threshold" must be a valid number':(K<1||K>100)&&(i.usageThreshold='"Usage Threshold" must be between 1 and 100')}const te=v.budgetPeriod?.trim();te&&!["daily","weekly","monthly","lifetime"].includes(te)&&(i.budgetPeriod='"Budget Period" must be one of: daily, weekly, monthly, lifetime');const be=v.resetDay?.trim(),xe=te||"lifetime";if(be){const K=Number(be);Number.isNaN(K)||!Number.isFinite(K)?i.resetDay='"Reset Day" must be a valid number':xe==="weekly"?(K<0||K>6||!Number.isInteger(K))&&(i.resetDay='"Reset Day" must be between 0 (Sunday) and 6 (Saturday) for weekly period'):xe==="monthly"&&(K<1||K>31||!Number.isInteger(K))&&(i.resetDay='"Reset Day" must be between 1 and 31 for monthly period')}return i},[$,M,v]),rs=a.useCallback(()=>{if(Object.keys(Ee).length>0)return null;const i={...t.metadata};for(const le of rt){const Ie=$[le.key]?.trim();Ie?le.type==="number"?i[le.key]=Number(Ie):i[le.key]=Ie:delete i[le.key]}Pe.length>0?i.skills=Pe:delete i.skills;const g={...t.runtimeConfig};g.enabled=F,g.autoClaimRelevantTasks=b,g.engineerBacklogAutoClaim=d,g.runMissedHeartbeatOnStartup=X,g.allowParallelExecution=ue,g.skipHeartbeatWhenIdle=Se;for(const le of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns","autoClaimCandidatesInPrompt"]){const Ie=M[le]?.trim();if(!Ie)delete g[le];else{const Ke=Number(Ie);g[le]=le==="maxConcurrentRuns"||le==="autoClaimCandidatesInPrompt"?Ke:Ke*1e3}}const R=M.messageResponseMode?.trim();if(R?g.messageResponseMode=R:delete g.messageResponseMode,ee?g.heartbeatScopeDiscipline=ee:delete g.heartbeatScopeDiscipline,De?g.heartbeatPromptTemplate=De:delete g.heartbeatPromptTemplate,he==="runtime")B.trim()?g.runtimeHint=B.trim():delete g.runtimeHint,delete g.modelProvider,delete g.modelId,delete g.model;else if(delete g.runtimeHint,p.trim()){const le=p.indexOf("/");le!==-1&&(g.modelProvider=p.slice(0,le),g.modelId=p.slice(le+1),g.model=p.trim())}else delete g.modelProvider,delete g.modelId,delete g.model;const Q={},ye=v.tokenBudget?.trim(),te=v.usageThreshold?.trim(),be=v.budgetPeriod?.trim(),xe=v.resetDay?.trim();ye&&(Q.tokenBudget=Number(ye)),te&&(Q.usageThreshold=Number(te)/100),be&&(Q.budgetPeriod=be),xe&&(Q.resetDay=Number(xe)),Object.keys(Q).length>0?g.budgetConfig=Q:delete g.budgetConfig;let K;return ae&&(K={mode:ae,entryFile:ze||"AGENTS.md",files:ne.length>0?ne:["AGENTS.md"]},ae==="external"&&ce.trim()&&(K.externalPath=ce.trim())),{name:h.trim()||void 0,role:j,title:m.trim()||void 0,icon:T.trim()||void 0,reportsTo:C.trim()||void 0,metadata:i,runtimeConfig:g,bundleConfig:K}},[t.metadata,t.runtimeConfig,ue,b,v,ze,ce,ne,ae,d,$,F,De,ee,M,T,p,h,C,j,X,he,B,Pe,Se,m,Ee]),nt=a.useCallback(async(i,g)=>{const R=rs();if(!R)return Ve(Ee),i&&l(n("agents.fixValidationErrors","Please fix validation errors before saving"),"error"),g==="auto"&&bt(n("agents.fixValidationToSave","Fix validation errors to save changes")),!1;const Q=JSON.stringify(R);if(Q===as.current)return!1;const ye=++xt.current;Ve({}),bt(null),es(!0);try{return await It(t.id,R,r),ye!==xt.current?!1:(as.current=Q,g==="manual"&&l(n("agents.settingsSaved","Settings saved"),"success"),bt(null),Ye(!0),at.current&&clearTimeout(at.current),at.current=setTimeout(()=>Ye(!1),3e3),await o(),!0)}catch(te){if(ye===xt.current){const be=U(te);bt(be),l(n("agents.settingsSaveFailed","Failed to save settings: {{error}}",{error:be}),"error")}return!1}finally{ye===xt.current&&es(!1)}},[l,t.id,rs,o,r,Ee]),Ws=async()=>{await nt(!0,"manual")},de=a.useCallback(()=>{if(!(!we||_e)){if(Object.keys(Ee).length>0){Ve(Ee);return}nt(!1,"auto")}},[we,_e,nt,Ee]);a.useEffect(()=>{if(!we||_e)return;if(Object.keys(Ee).length>0){Ve(Ee);return}const i=setTimeout(()=>{nt(!1,"auto")},ln);return()=>clearTimeout(i)},[we,_e,nt,Ee]);const Js=a.useCallback(async i=>{E(!0);try{await Ma(t.id,i,r),await o(),l(n("agents.avatarUploaded","Avatar uploaded"),"success")}catch(g){l(U(g),"error")}finally{E(!1),Z.current&&(Z.current.value="")}},[l,t.id,o,r]),Gs=a.useCallback(async()=>{E(!0);try{await Aa(t.id,r),await o(),l(n("agents.avatarRemoved","Avatar removed"),"success")}catch(i){l(U(i),"error")}finally{E(!1)}},[l,t.id,o,r]),ls=_e?n("agents.savingChanges","Saving changes…"):Lt?n("agents.saveFailed","Save failed: {{error}}",{error:Lt}):!we&&Us?n("agents.allChangesSaved","All changes saved"):null;return e.jsxs("div",{className:"config-tab",children:[e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:n("agents.configTitle","Agent Configuration")}),e.jsx("p",{className:"config-description",children:n("agents.configDescription","Configure agent settings and behavior.")}),e.jsx("div",{className:"config-actions-row",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>W(!0),children:n("agents.aiInterview","AI Interview")})}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-name",children:n("agents.nameLabel","Name")}),e.jsx("input",{id:"agent-name",type:"text",className:"input",value:h,onChange:i=>u(i.target.value),onBlur:()=>{de()}})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-role",children:n("agents.roleLabel2","Role")}),e.jsxs("select",{id:"agent-role",className:"select",value:j,onChange:i=>{c(i.target.value),de()},children:[e.jsx("option",{value:"triage",children:n("agents.roleTriage","Triage")}),e.jsx("option",{value:"executor",children:n("agents.roleExecutor","Executor")}),e.jsx("option",{value:"reviewer",children:n("agents.roleReviewer","Reviewer")}),e.jsx("option",{value:"merger",children:n("agents.roleMerger","Merger")}),e.jsx("option",{value:"scheduler",children:n("agents.roleScheduler","Scheduler")}),e.jsx("option",{value:"custom",children:n("agents.roleCustom","Custom")})]})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-title",children:n("agents.titleLabel","Title")}),e.jsx("input",{id:"agent-title",type:"text",className:"input",placeholder:n("agents.titlePlaceholder","e.g. Senior Code Reviewer"),value:m,onChange:i=>A(i.target.value),onBlur:()=>{de()}})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{children:n("agents.avatarLabel","Avatar")}),e.jsxs("div",{className:"agent-avatar-editor",children:[e.jsx(Rs,{agent:t,size:64,className:"agent-avatar-editor-preview"}),e.jsxs("div",{className:"agent-avatar-editor-actions",children:[e.jsx("input",{ref:Z,id:"agent-avatar-upload",type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",className:"visually-hidden",disabled:S,onChange:i=>{const g=i.target.files?.[0];g&&Js(g)}}),e.jsx("button",{type:"button",className:"btn btn-sm",disabled:S,onClick:()=>Z.current?.click(),children:n("agents.uploadAvatar","Upload Avatar")}),t.imageUrl?e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void Gs(),disabled:S,children:n("agents.removeAvatar","Remove Avatar")}):null]})]})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-icon",children:n("agents.iconLabel","Icon")}),e.jsx("input",{id:"agent-icon",type:"text",className:"input",placeholder:n("agents.iconPlaceholder","e.g. 🤖"),value:T,onChange:i=>H(i.target.value),onBlur:()=>{de()}})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-reports-to",children:n("agents.reportsToLabel","Reports To")}),e.jsxs("select",{id:"agent-reports-to",className:"select",value:C,onChange:i=>{_(i.target.value),de()},disabled:N,children:[e.jsx("option",{value:"",children:n("agents.noManager","No manager")}),ft&&e.jsx("option",{value:Ge,children:n("agents.unknownManager","Unknown manager ({{id}})",{id:Ge})}),ht.map(i=>e.jsxs("option",{value:i.id,children:[i.name," (",i.id,")"]},i.id))]})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:n("agents.skillsTitle","Skills")}),e.jsx("p",{className:"config-description",children:n("agents.skillsDescription","Assign skills to this agent for specialized behavior.")}),e.jsx("div",{className:"config-fields",children:e.jsx("div",{className:"config-field",children:e.jsx(_a,{id:"agent-skills",label:"Skills",value:Pe,onChange:i=>{ve(i),de()},projectId:r})})})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:n("agents.modelTitle","Model")}),e.jsx("p",{className:"config-description",children:n("agents.modelDescription","Choose either a built-in model or a plugin runtime for this agent. These options are mutually exclusive.")}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{children:n("agents.runtimeSource","Runtime Source")}),e.jsxs("div",{className:"config-runtime-tabs",role:"tablist","aria-label":n("agents.runtimeSource","Runtime source"),children:[e.jsx("button",{type:"button",className:`config-runtime-tab${he==="model"?" active":""}`,role:"tab","aria-selected":he==="model",tabIndex:he==="model"?0:-1,onClick:()=>{$e("model"),O(""),de()},children:n("agents.builtInModel","Built-in Model")}),e.jsx("button",{type:"button",className:`config-runtime-tab${he==="runtime"?" active":""}`,role:"tab","aria-selected":he==="runtime",tabIndex:he==="runtime"?0:-1,onClick:()=>{$e("runtime"),de()},children:n("agents.pluginRuntime","Plugin Runtime")})]})]}),he==="model"?e.jsx("div",{className:"config-field",children:e.jsx(Fa,{models:Be,value:p,onChange:i=>{z(i),de()},placeholder:n("agents.useGlobalDefault","Use global default"),label:n("agents.agentModelLabel","Agent Model"),disabled:ut,favoriteProviders:dt,onToggleFavorite:Tt,favoriteModels:Xe,onToggleModelFavorite:et})}):e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-runtime-hint",children:n("agents.runtimeLabel","Runtime")}),gt?e.jsx("span",{className:"config-hint",children:e.jsx(Pa,{label:n("agents.loadingRuntimes","Loading runtimes…")})}):e.jsxs("select",{id:"agent-runtime-hint",className:"select",value:B,onChange:i=>{O(i.target.value),de()},children:[e.jsx("option",{value:"",children:Ue.length>0?n("agents.selectRuntime","Select a plugin runtime…"):n("agents.noRuntimes","No plugin runtimes available")}),Ue.map(i=>e.jsx("option",{value:i.runtimeId,children:i.description?`${i.name} — ${i.description}`:i.name},`${i.pluginId}:${i.runtimeId}`))]})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:n("agents.permissionsTitle","Permissions")}),e.jsx("p",{className:"config-description",children:n("agents.permissionsDescription","Per-agent settings override project defaults. Each category controls a separate approval gate.")}),e.jsxs("div",{className:"agent-capability-grants","data-testid":"agent-capability-grants",children:[e.jsx("h4",{children:n("agents.capabilityGrantsTitle","Capability grants")}),e.jsx("p",{className:"config-hint",children:n("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:gs.map(i=>{const g=Bs.has(i),R=$s.has(i),Q=`agent-capability-${t.id}-${i.replace(/[^a-z0-9]+/gi,"-")}`;return e.jsxs("label",{className:"agent-capability-grant-row",htmlFor:Q,children:[e.jsxs("span",{children:[e.jsx("span",{className:"agent-capability-grant-name",children:i}),e.jsx("span",{className:"config-hint",children:g?n("agents.roleDefaultGrant","Role default grant"):R?n("agents.explicitGrant","Explicit grant"):n("agents.notGranted","Not granted")})]}),e.jsx("input",{id:Q,type:"checkbox",checked:R,"aria-label":n("agents.toggleCapabilityGrant","Toggle explicit grant for {{permission}}",{permission:i}),onChange:ye=>{Os(i,ye.target.checked)}})]},i)})})]}),re===void 0?e.jsxs("div",{className:"agent-permission-inherit-banner",children:[e.jsx("span",{children:n("agents.inheritingProjectDefault","Inheriting project default — no per-agent override set")}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void pt({presetId:"custom",rules:{git_write:je?.rules?.git_write??"allow",file_write_delete:je?.rules?.file_write_delete??"allow",command_execution:je?.rules?.command_execution??"allow",network_api:je?.rules?.network_api??"allow",task_agent_mutation:je?.rules?.task_agent_mutation??"allow",review_gate_bypass:je?.rules?.review_gate_bypass??"require-approval",file_scope:je?.rules?.file_scope??"allow"}}),children:n("agents.customizeForAgent","Customize for this agent")})]}):null,e.jsx(Wa,{mode:"agent-override",value:re,projectDefault:je?.rules,projectDefaultToolRules:je?.toolRules,onChange:i=>{pt(i)}})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:n("agents.heartbeatSettingsTitle","Heartbeat Settings")}),e.jsx("p",{className:"config-description",children:n("agents.heartbeatSettingsDesc","Configure how this agent's heartbeat is monitored. Leave a field empty to use system defaults.")}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field agent-heartbeat-auto-claim-card",children:[e.jsxs("div",{className:"agent-heartbeat-preset-row",children:[e.jsxs("div",{children:[e.jsx("label",{className:"agent-heartbeat-preset-label",children:n("agents.coordinationOnlyAgent","Coordination-only agent")}),e.jsx("span",{className:"config-hint",children:n("agents.coordinationOnlyHint","Disables auto-claim and removes the candidate section from heartbeat prompts. Recommended for routing/CEO-style agents.")})]}),e.jsx("button",{type:"button",className:"btn btn-sm agent-heartbeat-preset-btn",onClick:()=>{y(!1),se(i=>({...i,autoClaimCandidatesInPrompt:"0"})),de()},children:n("agents.applyPreset","Apply preset")})]}),e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-autoClaimRelevantTasks",children:[e.jsx("input",{id:"hb-autoClaimRelevantTasks",type:"checkbox",checked:b,onChange:i=>{y(i.target.checked),de()}}),n("agents.autoClaimRelevantTasks","Auto-Claim Relevant Tasks")]}),e.jsx("span",{className:"config-hint",children:n("agents.autoClaimHint","When enabled (default), no-task heartbeats scan open unowned work and auto-claim tasks aligned with this agent's role and soul.")}),e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-engineerBacklogAutoClaim",children:[e.jsx("input",{id:"hb-engineerBacklogAutoClaim",type:"checkbox",checked:d,onChange:i=>{D(i.target.checked),de()}}),n("agents.engineerBacklogAutoClaim","Engineer Backlog Auto-Claim")]}),e.jsx("span",{className:"config-hint",children:n("agents.engineerBacklogAutoClaimHint","Per-agent override of the project default. Allows this engineer-role agent to auto-claim unowned backlog tasks; explicit assignment and delegation are unchanged.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-enabled",children:[e.jsx("input",{id:"hb-enabled",type:"checkbox",checked:F,onChange:i=>{Vs(i.target.checked),de()}}),n("agents.heartbeatEnabled","Heartbeat Enabled")]}),e.jsx("span",{className:"config-hint",children:n("agents.heartbeatEnabledHint","When enabled, this agent receives scheduled heartbeat runs based on its interval.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-runMissedHeartbeatOnStartup",children:[e.jsx("input",{id:"hb-runMissedHeartbeatOnStartup",type:"checkbox",checked:X,onChange:i=>{pe(i.target.checked),de()}}),n("agents.runMissedHeartbeat","Run Missed Heartbeat On Startup")]}),e.jsx("span",{className:"config-hint",children:n("agents.runMissedHeartbeatHint","When enabled, if the server was down across this agent's scheduled heartbeat tick, fire a single catch-up heartbeat at startup. Default: off.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-allowParallelExecution",children:[e.jsx("input",{id:"hb-allowParallelExecution",type:"checkbox",checked:ue,onChange:i=>{Re(i.target.checked),de()}}),n("agents.allowParallelExecution","Allow Parallel Execution")]}),e.jsx("span",{className:"config-hint",children:n("agents.allowParallelExecutionHint","When disabled, the heartbeat and task execution paths serialize for this agent (heartbeat will not start while the agent's task is executing, and vice versa). Permanent agents only.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-skipHeartbeatWhenIdle",children:[e.jsx("input",{id:"hb-skipHeartbeatWhenIdle",type:"checkbox",checked:Se,onChange:i=>{I(i.target.checked),de()}}),n("agents.skipHeartbeatWhenIdle","Skip heartbeat when idle")]}),e.jsx("span",{className:"config-hint",children:n("agents.skipHeartbeatWhenIdleHint","When enabled, scheduled (timer) heartbeats are skipped while this agent has no assigned task. The agent still wakes immediately when a task is assigned or you trigger a run manually. Default: off.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-heartbeatScopeDiscipline",children:n("agents.heartbeatScopeDiscipline","Heartbeat Scope Discipline")}),e.jsxs("select",{id:"hb-heartbeatScopeDiscipline",className:"select",value:ee,onChange:i=>{const g=i.target.value;Le(g==="strict"||g==="lite"||g==="off"?g:""),de()},children:[e.jsx("option",{value:"",children:n("agents.inheritProjectDefault","Inherit project default")}),e.jsx("option",{value:"strict",children:n("agents.strict","Strict")}),e.jsx("option",{value:"lite",children:n("agents.lite","Lite")}),e.jsx("option",{value:"off",children:n("agents.off","Off")})]}),e.jsx("span",{className:"config-hint",children:n("agents.scopeDisciplineHint","Strict — coordination-focused; higher per-tick tokens. Lite — pre-2026-05-11 behavior. Off — minimal procedure.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-heartbeatPromptTemplate",children:n("agents.heartbeatPromptTemplate","Heartbeat Prompt Template")}),e.jsxs("select",{id:"hb-heartbeatPromptTemplate",className:"select",value:De,onChange:i=>{const g=i.target.value;x(g==="default"||g==="compact"?g:""),de()},children:[e.jsx("option",{value:"",children:n("agents.inheritProjectDefault","Inherit project default")}),e.jsx("option",{value:"default",children:n("agents.templateDefault","Default")}),e.jsx("option",{value:"compact",children:n("agents.templateCompact","Compact")})]})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-heartbeatIntervalMs",children:n("agents.heartbeatIntervalLabel","Heartbeat Interval (s)")}),e.jsx("input",{id:"hb-heartbeatIntervalMs",type:"text",inputMode:"numeric",className:oe("input",!!Y.heartbeatIntervalMs&&"input--error"),placeholder:String(qt/1e3),value:M.heartbeatIntervalMs??"",onChange:i=>vt("heartbeatIntervalMs",i.target.value)}),Y.heartbeatIntervalMs?e.jsx("span",{className:"config-error",children:Y.heartbeatIntervalMs}):e.jsx("span",{className:"config-hint",children:n("agents.heartbeatIntervalHint","How often heartbeats are checked. Leave empty for system default ({{seconds}}s / {{label}}).",{seconds:qt/1e3,label:rn})})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-heartbeatTimeoutMs",children:n("agents.heartbeatTimeoutLabel","Heartbeat Timeout (s)")}),e.jsx("input",{id:"hb-heartbeatTimeoutMs",type:"text",inputMode:"numeric",className:oe("input",!!Y.heartbeatTimeoutMs&&"input--error"),placeholder:"60",value:M.heartbeatTimeoutMs??"",onChange:i=>vt("heartbeatTimeoutMs",i.target.value)}),Y.heartbeatTimeoutMs?e.jsx("span",{className:"config-error",children:Y.heartbeatTimeoutMs}):e.jsx("span",{className:"config-hint",children:n("agents.heartbeatTimeoutHint","Time without heartbeat before agent is considered unresponsive. Leave empty for system default (60s)")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-maxConcurrentRuns",children:n("agents.maxConcurrentRunsLabel","Max Concurrent Runs")}),e.jsx("input",{id:"hb-maxConcurrentRuns",type:"text",inputMode:"numeric",className:oe("input",!!Y.maxConcurrentRuns&&"input--error"),placeholder:"1",value:M.maxConcurrentRuns??"",onChange:i=>vt("maxConcurrentRuns",i.target.value)}),Y.maxConcurrentRuns?e.jsx("span",{className:"config-error",children:Y.maxConcurrentRuns}):e.jsx("span",{className:"config-hint",children:n("agents.maxConcurrentRunsHint","Maximum simultaneous heartbeat runs for this agent. Leave empty for system default (1).")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-messageResponseMode",children:n("agents.messageResponseModeLabel","Message Response Mode")}),e.jsxs("select",{id:"hb-messageResponseMode",className:oe("select",!!Y.messageResponseMode&&"input--error"),value:M.messageResponseMode??"",onChange:i=>vt("messageResponseMode",i.target.value),children:[e.jsx("option",{value:"",children:n("agents.systemDefaultOnHeartbeat","System Default (On Heartbeat)")}),e.jsx("option",{value:"on-heartbeat",children:n("agents.onHeartbeat","On Heartbeat")}),e.jsx("option",{value:"immediate",children:n("agents.immediate","Immediate")})]}),Y.messageResponseMode?e.jsx("span",{className:"config-error",children:Y.messageResponseMode}):e.jsx("span",{className:"config-hint",children:n("agents.messageResponseModeHint","How this agent responds to incoming messages. 'Immediate' wakes the agent as soon as a message arrives. 'On Heartbeat' defers processing to the next scheduled heartbeat.")})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:n("agents.budgetSettingsTitle","Budget Settings")}),e.jsx("p",{className:"config-description",children:n("agents.budgetSettingsDesc","Configure token budget limits for this agent. Leave all fields empty to disable budget tracking.")}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"budget-tokenBudget",children:n("agents.tokenBudgetLabel","Token Budget")}),e.jsx("input",{id:"budget-tokenBudget",type:"text",inputMode:"numeric",className:oe("input",!!Y.tokenBudget&&"input--error"),placeholder:n("agents.noLimit","No limit"),value:v.tokenBudget??"",onChange:i=>jt("tokenBudget",i.target.value)}),Y.tokenBudget?e.jsx("span",{className:"config-error",children:Y.tokenBudget}):e.jsx("span",{className:"config-hint",children:n("agents.tokenBudgetHint","Total token cap (input + output) for this agent. Leave empty for no limit.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"budget-usageThreshold",children:n("agents.usageThresholdLabel","Usage Threshold (%)")}),e.jsx("input",{id:"budget-usageThreshold",type:"text",inputMode:"numeric",className:oe("input",!!Y.usageThreshold&&"input--error"),placeholder:"80",value:v.usageThreshold??"",onChange:i=>jt("usageThreshold",i.target.value)}),Y.usageThreshold?e.jsx("span",{className:"config-error",children:Y.usageThreshold}):e.jsx("span",{className:"config-hint",children:n("agents.usageThresholdHint","Warning threshold as a percentage. Agent warns when usage reaches this level. Default: 80%.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"budget-budgetPeriod",children:n("agents.budgetPeriodLabel","Budget Period")}),e.jsxs("select",{id:"budget-budgetPeriod",className:oe("select",!!Y.budgetPeriod&&"input--error"),value:v.budgetPeriod??"",onChange:i=>jt("budgetPeriod",i.target.value),children:[e.jsx("option",{value:"",children:n("agents.noReset","No reset (lifetime)")}),e.jsx("option",{value:"daily",children:n("agents.daily","Daily")}),e.jsx("option",{value:"weekly",children:n("agents.weekly","Weekly")}),e.jsx("option",{value:"monthly",children:n("agents.monthly","Monthly")})]}),Y.budgetPeriod?e.jsx("span",{className:"config-error",children:Y.budgetPeriod}):e.jsx("span",{className:"config-hint",children:n("agents.budgetPeriodHint","How often the budget counter resets. Leave empty for lifetime budget.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"budget-resetDay",children:n("agents.resetDayLabel","Reset Day")}),e.jsx("input",{id:"budget-resetDay",type:"text",inputMode:"numeric",className:oe("input",!!Y.resetDay&&"input--error"),placeholder:n("agents.auto","Auto"),value:v.resetDay??"",onChange:i=>jt("resetDay",i.target.value)}),Y.resetDay?e.jsx("span",{className:"config-error",children:Y.resetDay}):e.jsx("span",{className:"config-hint",children:v.budgetPeriod==="weekly"?n("agents.resetDayWeekly","Day of week (0=Sunday to 6=Saturday) for reset."):v.budgetPeriod==="monthly"?n("agents.resetDayMonthly","Day of month (1-31) for reset."):n("agents.resetDayHint","Day for reset (weekly: 0-6, monthly: 1-31). Leave empty for automatic.")})]}),Oe?.budgetLimit!=null&&e.jsxs("div",{className:"config-field",children:[e.jsx("label",{children:n("agents.currentUsage","Current Usage")}),e.jsxs("div",{className:"budget-progress-container",children:[e.jsx("div",{className:"budget-progress-bar",children:e.jsx("div",{className:oe("budget-progress-bar__fill",(Oe.usagePercent??0)>=100?"budget-progress-bar__fill--red":(Oe.usagePercent??0)>=80?"budget-progress-bar__fill--amber":"budget-progress-bar__fill--green"),style:{width:`${Math.min(Oe.usagePercent??0,100)}%`}})}),e.jsx("span",{className:"budget-progress-label",children:n("agents.budgetUsageDisplay","{{used}} / {{limit}} tokens ({{percent}}% used)",{used:(Oe.currentUsage??0).toLocaleString(),limit:(Oe.budgetLimit??0).toLocaleString(),percent:Math.round(Oe.usagePercent??0)})})]})]}),Oe?.budgetLimit!=null&&e.jsx("div",{className:"config-field",children:e.jsx("button",{className:"btn btn-reset-budget",onClick:()=>void _s(),disabled:Qt,children:Qt?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:14,className:"animate-spin"}),n("agents.resetting","Resetting…")]}):e.jsxs(e.Fragment,{children:[e.jsx(Rt,{size:14}),n("agents.resetBudgetUsage","Reset Budget Usage")]})})})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:n("agents.bundleTitle","Instruction Bundle")}),e.jsx("p",{className:"config-description",children:n("agents.bundleDescription","Configure the agent's instruction bundle. Leave empty to use inline instructions only.")}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-mode",children:n("agents.bundleModeLabel","Bundle Mode")}),e.jsxs("select",{id:"bundle-mode",className:"select",value:ae,onChange:i=>We(i.target.value),children:[e.jsx("option",{value:"",children:n("agents.bundleNone","None (use inline instructions)")}),e.jsx("option",{value:"managed",children:n("agents.bundleManaged","Managed (system-managed directory)")}),e.jsx("option",{value:"external",children:n("agents.bundleExternal","External (user-specified path)")})]}),e.jsxs("span",{className:"config-hint",children:[ae==="managed"&&n("agents.bundleManagedHint","Files will be stored in a system-managed directory within .fusion/agents/"),ae==="external"&&n("agents.bundleExternalHint","Specify an external directory path for the instruction files"),!ae&&n("agents.bundleSelectMode","Select a mode to enable instruction bundling")]})]}),ae&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-entry-file",children:n("agents.bundleEntryFileLabel","Entry File")}),e.jsx("input",{id:"bundle-entry-file",type:"text",className:"input",placeholder:"AGENTS.md",value:ze,onChange:i=>Me(i.target.value)}),e.jsx("span",{className:"config-hint",children:n("agents.bundleEntryFileHint","Primary instructions file name (default: AGENTS.md)")})]}),ae==="external"&&e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-external-path",children:n("agents.bundleExternalPathLabel","External Path")}),e.jsx("input",{id:"bundle-external-path",type:"text",className:"input",placeholder:n("agents.bundleExternalPathPlaceholder","e.g. .fusion/agents/my-agent"),value:ce,onChange:i=>Fe(i.target.value)}),e.jsx("span",{className:"config-hint",children:n("agents.bundleExternalPathHint","Absolute or relative path to the external directory")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-files",children:n("agents.bundleFilesLabel","Files (comma-separated)")}),e.jsx("input",{id:"bundle-files",type:"text",className:"input",placeholder:"AGENTS.md, PROMPTS.md",value:ne.join(", "),onChange:i=>ct(i.target.value.split(",").map(g=>g.trim()).filter(Boolean))}),e.jsx("span",{className:"config-hint",children:n("agents.bundleFilesHint","List of file names in the bundle directory")})]})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:n("agents.advancedSettingsTitle","Advanced Settings")}),e.jsx("p",{className:"config-description",children:n("agents.advancedSettingsDesc","Advanced configuration options for this agent. Leave a field empty to use system defaults.")}),e.jsx("div",{className:"config-fields",children:rt.map(i=>{const g=!!Y[i.key];return e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:`adv-${i.key}`,children:i.label}),i.type==="select"?e.jsxs("select",{id:`adv-${i.key}`,className:oe("select",g&&"input--error"),value:$[i.key]??"",onChange:R=>is(i.key,R.target.value),children:[e.jsx("option",{value:"",children:n("agents.systemDefault","System Default")}),i.options?.map(R=>e.jsx("option",{value:R.value,children:R.label},R.value))]}):e.jsx("input",{id:`adv-${i.key}`,type:"text",inputMode:i.type==="number"?"numeric":void 0,className:oe("input",g&&"input--error"),placeholder:i.placeholder,value:$[i.key]??"",onChange:R=>is(i.key,R.target.value)}),g&&e.jsx("span",{className:"config-error",children:Y[i.key]}),!g&&i.hint&&e.jsx("span",{className:"config-hint",children:i.hint})]},i.key)})}),e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!we||_e,onClick:()=>void Ws(),children:_e?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),n("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(ge,{size:16}),n("agents.saveSettings","Save Settings")]})}),ls&&e.jsxs("span",{className:oe("config-saved-indicator",Lt&&"config-saved-indicator--error"),children:[_e?e.jsx(q,{size:14,className:"animate-spin"}):e.jsx(ge,{size:14}),ls]})]})]}),e.jsx(yn,{agent:t,projectId:r,addToast:l,onSaved:o}),e.jsxs("div",{className:"config-section config-section--danger",children:[e.jsx("h3",{children:n("agents.dangerZone","Danger Zone")}),e.jsx("p",{className:"config-description",children:n("agents.dangerZoneDesc","Permanently delete this agent from the project.")}),e.jsx("div",{className:"config-fields",children:e.jsxs("div",{className:"config-field",children:[e.jsxs("button",{className:"btn btn--danger",disabled:!ts||!f,onClick:()=>void f?.(),children:[e.jsx(lt,{size:16}),n("agents.deleteAgent","Delete Agent")]}),e.jsx("span",{className:"config-danger-note",children:ts?n("agents.deletionPermanent","Deletion is permanent and cannot be undone."):n("agents.deletionNotAvailable","Agent deletion is only available when state is idle or paused (current state: {{state}}).",{state:t.state})})]})})]}),e.jsx(Ua,{isOpen:L,onClose:()=>W(!1),onUseDraft:qe,projectId:r,existingAgents:V,mode:"edit",existingAgentConfig:me})]})}function Sn({agentId:t,projectId:r,onChildClick:l}){const{t:o}=Ne("app"),[s,f]=a.useState([]),[k,n]=a.useState(!0);return a.useEffect(()=>{n(!0),ya(t,r).then(f).finally(()=>n(!1))},[t,r]),k?e.jsxs("div",{className:"detail-section",children:[e.jsx("div",{className:"detail-section-header",children:e.jsx("h3",{children:o("agents.employeesTitle","Employees")})}),e.jsxs("div",{className:"detail-section-body detail-section-body--loading",children:[e.jsx(q,{size:16,className:"spin"}),e.jsx("span",{className:"text-muted",children:o("agents.loadingEmployees","Loading employees...")})]})]}):e.jsxs("div",{className:"detail-section",children:[e.jsxs("div",{className:"detail-section-header",children:[e.jsx("h3",{children:o("agents.employeesTitle","Employees")}),e.jsxs("span",{className:"text-muted",children:["(",s.length,")"]})]}),e.jsx("div",{className:"detail-section-body",children:s.length===0?e.jsxs("div",{className:"agent-empty agent-empty--padded",children:[e.jsx(Fs,{size:32,opacity:.3}),e.jsx("p",{children:o("agents.noEmployees","No employees")}),e.jsx("p",{className:"text-muted",children:o("agents.noEmployeesDesc","This agent has no employees")})]}):e.jsx("div",{className:"agent-tree__children",children:s.map(h=>{const u=Zt[h.state];return e.jsxs("div",{className:"agent-tree__node agent-is-child",onClick:()=>l?.(h.id),role:"button",tabIndex:0,onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&(j.key===" "&&j.preventDefault(),l?.(h.id))},style:{cursor:l?"pointer":"default"},children:[e.jsx("span",{className:"agent-tree__icon",children:h.icon??"🤖"}),e.jsx("span",{className:"agent-tree__name",children:h.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:h.state})]},h.id)})})})]})}export{En as AgentDetailView,Qe as relativeTime};
|