@runfusion/fusion 0.70.2 → 0.72.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +2425 -2183
- package/dist/child-process-worker.js +1575 -1491
- package/dist/client/.vite/manifest.json +250 -250
- package/dist/client/assets/{AgentDetailView-UMM9DyW-.js → AgentDetailView-Bq6qfKGR.js} +5 -5
- package/dist/client/assets/{AgentPermissionPolicyEditor-BfNZUiDb.js → AgentPermissionPolicyEditor-Dah1P8IX.js} +2 -2
- package/dist/client/assets/{AgentsView-DtC-DVyX.js → AgentsView-Bu8h0vGY.js} +4 -4
- package/dist/client/assets/{ChatView-sDJXcOwT.js → ChatView-BTE8fIib.js} +1 -1
- package/dist/client/assets/{CommandCenter-B7BECRSV.js → CommandCenter-l4no66mI.js} +1 -1
- package/dist/client/assets/{DevServerView-CyW7l6rY.js → DevServerView-Cuxhgjdv.js} +1 -1
- package/dist/client/assets/DirectoryPicker-tm1SS2jF.js +1 -0
- package/dist/client/assets/{DocumentsView-Dbn8T4ZT.js → DocumentsView-Dg8lFF7X.js} +2 -2
- package/dist/client/assets/{EvalsView-DGOBPt3P.js → EvalsView-TccfkTNy.js} +1 -1
- package/dist/client/assets/{ExperimentalAgentOnboardingModal-Beno0EK8.js → ExperimentalAgentOnboardingModal-2qAtocIG.js} +1 -1
- package/dist/client/assets/{GoalsView-BLxtocMB.js → GoalsView-Du_jIEn2.js} +1 -1
- package/dist/client/assets/{InsightsView-DjTpiw1S.js → InsightsView-BxJ327Tj.js} +2 -2
- package/dist/client/assets/{MemoryView-BvAhPVCo.js → MemoryView-Blv0YUWC.js} +2 -2
- package/dist/client/assets/{PiExtensionsManager-Di3Q9J6V.js → PiExtensionsManager-BUS_ZKwO.js} +2 -2
- package/dist/client/assets/{PluginManager-reQpowmU.js → PluginManager-DM5-rNen.js} +1 -1
- package/dist/client/assets/{PullRequestView-DLDz9RXL.js → PullRequestView-D7ozwDrc.js} +2 -2
- package/dist/client/assets/{ResearchView-BpdpPwyr.js → ResearchView-CRGaOkBH.js} +1 -1
- package/dist/client/assets/{SecretsView-BHu1JHnH.js → SecretsView-Nwc-7xGn.js} +1 -1
- package/dist/client/assets/{SessionTerminal-rtlAx2uQ.js → SessionTerminal-gC7X57E6.js} +1 -1
- package/dist/client/assets/{SettingsModal-Dxz7-SNa.js → SettingsModal-CuEXiFb_.js} +4 -4
- package/dist/client/assets/{SettingsModal-B7m-bZlG.js → SettingsModal-q_D1o7T-.js} +1 -1
- package/dist/client/assets/{SettingsTextareaRow-5Vb6XYSC.js → SettingsTextareaRow-DnsWtbkh.js} +1 -1
- package/dist/client/assets/SetupWizardModal-3-mXX0VJ.js +2 -0
- package/dist/client/assets/{SkillsView-CNQaKfLx.js → SkillsView-Dw8m0G-9.js} +1 -1
- package/dist/client/assets/{ThemeDropdown-Bhz3TH1Z.js → ThemeDropdown-C7qybW7w.js} +1 -1
- package/dist/client/assets/{TodoView-Ccr5rxPw.js → TodoView-r_qHhO28.js} +2 -2
- package/dist/client/assets/{WorkflowNodeEditor-BeY_3iQR.js → WorkflowNodeEditor-B0TGhu5B.js} +1 -1
- package/dist/client/assets/{app-bX7Aarj6.js → app-0sCAWTFb.js} +1 -1
- package/dist/client/assets/{app-BFkCDjfl.js → app-Cndq8AGV.js} +1 -1
- package/dist/client/assets/{app-Bx4Tg9WL.js → app-CqpqmC8O.js} +1 -1
- package/dist/client/assets/{app-BwKqEIVs.js → app-DjxXVWX9.js} +1 -1
- package/dist/client/assets/{app-gasJpw6T.js → app-DrnsOtt9.js} +1 -1
- package/dist/client/assets/{app-BLTqCjPk.js → app-Kb21Gl_h.js} +1 -1
- package/dist/client/assets/{architectureDiagram-3BPJPVTR-DbmZMyHk.js → architectureDiagram-3BPJPVTR-9REjGWnr.js} +1 -1
- package/dist/client/assets/{blockDiagram-GPEHLZMM-BkspaqvN.js → blockDiagram-GPEHLZMM-OATfTc06.js} +1 -1
- package/dist/client/assets/{c4Diagram-AAUBKEIU-BfOk6DAf.js → c4Diagram-AAUBKEIU-B-nq1avj.js} +1 -1
- package/dist/client/assets/channel-BW-0I-xJ.js +1 -0
- package/dist/client/assets/{chunk-2J33WTMH-DbL54v_S.js → chunk-2J33WTMH-Dds2A4Un.js} +1 -1
- package/dist/client/assets/{chunk-4BX2VUAB-VAUWnfVr.js → chunk-4BX2VUAB-Dc-jRxxZ.js} +1 -1
- package/dist/client/assets/{chunk-55IACEB6-C5h7MxPM.js → chunk-55IACEB6-CKtwSOvQ.js} +1 -1
- package/dist/client/assets/{chunk-727SXJPM-CCc56jyj.js → chunk-727SXJPM-DbRZhQCr.js} +1 -1
- package/dist/client/assets/{chunk-AQP2D5EJ-CUK6s79q.js → chunk-AQP2D5EJ-Dq_cSIeh.js} +1 -1
- package/dist/client/assets/{chunk-FMBD7UC4-COFczZ8r.js → chunk-FMBD7UC4-BmnvYNOo.js} +1 -1
- package/dist/client/assets/{chunk-ND2GUHAM-BXTcFeIM.js → chunk-ND2GUHAM-D6nyZn0C.js} +1 -1
- package/dist/client/assets/{chunk-QZHKN3VN-BEYAo7eA.js → chunk-QZHKN3VN-FFojVCmd.js} +1 -1
- package/dist/client/assets/classDiagram-4FO5ZUOK-DfBIljo4.js +1 -0
- package/dist/client/assets/classDiagram-v2-Q7XG4LA2-DfBIljo4.js +1 -0
- package/dist/client/assets/{cose-bilkent-S5V4N54A-DqQ74MrB.js → cose-bilkent-S5V4N54A-DysS3-yZ.js} +1 -1
- package/dist/client/assets/{dagre-BM42HDAG-D1DsLIdG.js → dagre-BM42HDAG-DgL7uNq4.js} +1 -1
- package/dist/client/assets/{dashboard-view-D5F_ho0i.js → dashboard-view-Bu_nB-cd.js} +1 -1
- package/dist/client/assets/{dashboard-view-DFy7Ta-E.js → dashboard-view-DlxD_dta.js} +1 -1
- package/dist/client/assets/{dashboard-view-CgBE7XiJ.js → dashboard-view-ln6_a3ZY.js} +1 -1
- package/dist/client/assets/{diagram-2AECGRRQ-p-547bXh.js → diagram-2AECGRRQ-DTACb17z.js} +1 -1
- package/dist/client/assets/{diagram-5GNKFQAL-BE9UnZuh.js → diagram-5GNKFQAL-DqdKDR_d.js} +1 -1
- package/dist/client/assets/{diagram-KO2AKTUF-BHTLL-vQ.js → diagram-KO2AKTUF-CCKa3iUW.js} +1 -1
- package/dist/client/assets/{diagram-LMA3HP47-CWLbQcuj.js → diagram-LMA3HP47-C2SLmXdM.js} +1 -1
- package/dist/client/assets/{diagram-OG6HWLK6-CXUiMHIE.js → diagram-OG6HWLK6-Dz9wXgRN.js} +1 -1
- package/dist/client/assets/{erDiagram-TEJ5UH35-Dre62Vsd.js → erDiagram-TEJ5UH35-GGHapzlB.js} +1 -1
- package/dist/client/assets/{flowDiagram-I6XJVG4X-BFeMnep3.js → flowDiagram-I6XJVG4X-B3SLxAlP.js} +1 -1
- package/dist/client/assets/{folder-open-s7aQO2Ib.js → folder-open-BWBZSyO2.js} +1 -1
- package/dist/client/assets/{ganttDiagram-6RSMTGT7-CfrUWiHI.js → ganttDiagram-6RSMTGT7-DYveq-32.js} +1 -1
- package/dist/client/assets/{gitGraphDiagram-PVQCEYII-KjKsgpva.js → gitGraphDiagram-PVQCEYII-Bxh-7IFt.js} +1 -1
- package/dist/client/assets/index-CiqkhNwQ.css +1 -0
- package/dist/client/assets/{index-DF2cd-e3.js → index-D8sgsB8q.js} +268 -268
- package/dist/client/assets/{infoDiagram-5YYISTIA-Cb_8B_3K.js → infoDiagram-5YYISTIA-B3_g2TQW.js} +1 -1
- package/dist/client/assets/{ishikawaDiagram-YF4QCWOH-8jtlcCaf.js → ishikawaDiagram-YF4QCWOH-CExRn4qZ.js} +1 -1
- package/dist/client/assets/{journeyDiagram-JHISSGLW-O6X0tJvH.js → journeyDiagram-JHISSGLW-Dgck68vd.js} +1 -1
- package/dist/client/assets/{kanban-definition-UN3LZRKU-BetEnps7.js → kanban-definition-UN3LZRKU-B258_39Z.js} +1 -1
- package/dist/client/assets/{mermaid.core-CZbT2qhF.js → mermaid.core-uCT9za93.js} +4 -4
- package/dist/client/assets/{mindmap-definition-RKZ34NQL-BRjDmxQK.js → mindmap-definition-RKZ34NQL-DHevd0he.js} +1 -1
- package/dist/client/assets/{pieDiagram-4H26LBE5-CJHx1ZvR.js → pieDiagram-4H26LBE5-rTbXqg0x.js} +1 -1
- package/dist/client/assets/{puzzle-BJEQBgfR.js → puzzle-D7NHfczg.js} +1 -1
- package/dist/client/assets/{quadrantDiagram-W4KKPZXB-D49nAI3y.js → quadrantDiagram-W4KKPZXB-C-N3JbLv.js} +1 -1
- package/dist/client/assets/{requirementDiagram-4Y6WPE33-BM4Uv6Jr.js → requirementDiagram-4Y6WPE33-DNINb6LP.js} +1 -1
- package/dist/client/assets/{sankeyDiagram-5OEKKPKP-RSKSlyjr.js → sankeyDiagram-5OEKKPKP-UI7SyvRN.js} +1 -1
- package/dist/client/assets/{sequenceDiagram-3UESZ5HK-BXpcHAnr.js → sequenceDiagram-3UESZ5HK-pc1RDjwM.js} +1 -1
- package/dist/client/assets/{shield-alert-DcsqJWMG.js → shield-alert-c_--H0ce.js} +1 -1
- package/dist/client/assets/{standing-instructions-template-CUYzx5D8.js → standing-instructions-template-aTeHy5lT.js} +1 -1
- package/dist/client/assets/{stateDiagram-AJRCARHV-CavU8Ef4.js → stateDiagram-AJRCARHV-CEiZfKWc.js} +1 -1
- package/dist/client/assets/{stateDiagram-v2-BHNVJYJU-Cq-9bJPI.js → stateDiagram-v2-BHNVJYJU-B7aNz5OD.js} +1 -1
- package/dist/client/assets/{timeline-definition-PNZ67QCA-7fHh3hS9.js → timeline-definition-PNZ67QCA-DyE71jn0.js} +1 -1
- package/dist/client/assets/{upload-DNwFaPfV.js → upload-YGrA50-5.js} +1 -1
- package/dist/client/assets/{users-D-kPhpXu.js → users-fxiLvP6C.js} +1 -1
- package/dist/client/assets/{vennDiagram-CIIHVFJN-mCh9G6D5.js → vennDiagram-CIIHVFJN-DX-6Y82D.js} +1 -1
- package/dist/client/assets/{wardley-L42UT6IY-DEu4AYE9.js → wardley-L42UT6IY-ew7KQxeH.js} +1 -1
- package/dist/client/assets/{wardleyDiagram-YWT4CUSO-DRL0ZyeQ.js → wardleyDiagram-YWT4CUSO-DqSCrJdO.js} +1 -1
- package/dist/client/assets/{xychartDiagram-2RQKCTM6-DUpC-GBX.js → xychartDiagram-2RQKCTM6-CEtZEj45.js} +1 -1
- package/dist/client/index.html +2 -2
- package/dist/client/version.json +1 -1
- package/dist/extension.js +1797 -1713
- package/dist/plugins/fusion-plugin-dependency-graph/.bundled.reload-1.js +8084 -0
- package/dist/plugins/fusion-plugin-grok-runtime/.bundled.reload-2.js +26479 -0
- package/package.json +1 -1
- package/dist/client/assets/DirectoryPicker-BT3OeDJ3.js +0 -1
- package/dist/client/assets/SetupWizardModal-BixsaVgv.js +0 -2
- package/dist/client/assets/channel-CABKCAbA.js +0 -1
- package/dist/client/assets/classDiagram-4FO5ZUOK-DgshwmmF.js +0 -1
- package/dist/client/assets/classDiagram-v2-Q7XG4LA2-DgshwmmF.js +0 -1
- package/dist/client/assets/index-Co20nJU4.css +0 -1
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
import{r as a,j as e}from"./vendor-react-SZ_qB27O.js";import{c as
|
|
1
|
+
import{r as a,j as e}from"./vendor-react-SZ_qB27O.js";import{c as Zt,bN as Qs,bO as Xs,bP as ea,bQ as ta,L as G,R as At,bz as us,Z as sa,bh as Ht,bR as Ss,s as ct,C as Cs,e as ws,bS as aa,bT as na,bU as ia,a1 as Rs,bV as ra,aK as la,bW as oa,bc as U,bX as ca,bY as Ms,bZ as As,b_ as da,bb as wt,b$ as It,a5 as St,bg as Fs,aA as Ps,c0 as Bt,bw as Rt,c1 as ms,c2 as Xe,c3 as ua,X as Ts,a$ as dt,c4 as ma,bf as Es,c5 as Ls,c6 as ga,N as ha,p as fa,c7 as Ds,a6 as zs,bi as Qt,c8 as pa,c9 as gs,ca as ba,cb as xa,cc as Yt,cd as Hs,ce as va,b as ja,cf as ya,g as Is,cg as Bs,aT as Na,aB as fe,ch as Os,ci as hs,cj as fs,ck as ka,cl as Sa,cm as Ca,cn as wa,co as Ft,n as Pt,h as Tt,r as Et,cp as $s,cq as Ra,cr as Ma,aN as Aa,cs as Fa,ct as Pa,cu as ps,bu as Ta,cv as Ot,cw as Ea,cx as La,by as Da,a8 as za,cy as Kt,u as Ha,cz as Ia,cA as Ba,cB as Oa,cC as $a,cD as _a,cE as _s,cF as Ua,cG as Va,cH as Wa,cI as Ja,cJ as Ga}from"./index-D8sgsB8q.js";import{u as ke}from"./vendor-i18n-GF3RlKbq.js";import{f as $t,S as qa,a as Ya}from"./standing-instructions-template-aTeHy5lT.js";import{ExperimentalAgentOnboardingModal as Ka}from"./ExperimentalAgentOnboardingModal-2qAtocIG.js";import{B as Za,A as Qa}from"./AgentPermissionPolicyEditor-Dah1P8IX.js";import"./vendor-reactflow-9C3XTE7_.js";import"./vendor-codemirror-jBKmHyH0.js";import"./vendor-xterm-BNq00GSj.js";/**
|
|
2
2
|
* @license lucide-react v1.7.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
5
5
|
* See the LICENSE file in the root directory of this source tree.
|
|
6
|
-
*/const Xa=[["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"}]],Ct=
|
|
6
|
+
*/const Xa=[["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"}]],Ct=Zt("chart-column",Xa);/**
|
|
7
7
|
* @license lucide-react v1.7.0 - ISC
|
|
8
8
|
*
|
|
9
9
|
* This source code is licensed under the ISC license.
|
|
10
10
|
* See the LICENSE file in the root directory of this source tree.
|
|
11
|
-
*/const en=[["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"}]],tn=
|
|
11
|
+
*/const en=[["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"}]],tn=Zt("square-activity",en);/**
|
|
12
12
|
* @license lucide-react v1.7.0 - ISC
|
|
13
13
|
*
|
|
14
14
|
* This source code is licensed under the ISC license.
|
|
15
15
|
* See the LICENSE file in the root directory of this source tree.
|
|
16
|
-
*/const sn=[["path",{d:"M16 17h6v-6",key:"t6n2it"}],["path",{d:"m22 17-8.5-8.5-5 5L2 7",key:"x473p"}]],an=Kt("trending-down",sn);function bs(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 nn(t){return`${Math.round(t*100)}%`}function xs(t,r){const l=Date.now(),o=new Date(t).getTime(),s=l-o;if(s<0){const p=Math.abs(s);return p<6e4?r("agents.time.inAMoment","in a moment"):p<36e5?r("agents.time.inMinutes","in {{count}}m",{count:Math.floor(p/6e4)}):p<864e5?r("agents.time.inHours","in {{count}}h",{count:Math.floor(p/36e5)}):r("agents.time.inDays","in {{count}}d",{count:Math.floor(p/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 rn(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 lt(t){return t instanceof Error&&t.message?t.message:String(t)}function ln(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 on(t){switch(t){case"improving":return"trend-improving";case"declining":return"trend-declining";case"stable":return"trend-stable";default:return"trend-insufficient"}}function vs(t,r=5){return e.jsx("span",{className:"rating-stars",children:Array.from({length:r},(l,o)=>e.jsx(Ss,{size:14,className:o<t?"star-filled":"star-empty",fill:o<t?"currentColor":"none"},o))})}function cn({agentId:t,projectId:r,addToast:l}){const{t:o}=ke("app"),[s,p]=a.useState([]),[k,n]=a.useState(null),[f,u]=a.useState(null),[j,c]=a.useState([]),[m,w]=a.useState(!0),[T,z]=a.useState(!0),[R,B]=a.useState(!1),[O,se]=a.useState(!1),[N,v]=a.useState(null),[M,Z]=a.useState(0),[P,E]=a.useState(""),[K,$]=a.useState(""),V=a.useCallback(async()=>{try{const[d,D]=await Promise.all([Qs(t,20,r),Xs(t,void 0,r)]);p(d),n(D)}catch(d){l(o("agents.reflections.loadError","Failed to load reflections: {{error}}",{error:lt(d)}),"error")}finally{w(!1)}},[t,r,l]),S=a.useCallback(async()=>{try{const[d,D]=await Promise.all([ea(t,r),ta(t,{limit:50},r)]);u(d),c(D)}catch(d){l(o("agents.ratings.loadError","Failed to load ratings: {{error}}",{error:lt(d)}),"error")}finally{z(!1)}},[t,r,l]);a.useEffect(()=>{V(),S()},[V,S]);const X=async()=>{B(!0);try{if(!await aa(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"),w(!0),await V()}catch(d){const D=lt(d),J=D.toLowerCase();J.includes("agent not found")||J.includes("not found")?l(o("agents.reflections.agentNotFound","This agent is no longer available. It may have been deleted."),"error"):J.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{B(!1)}},F=async d=>{if(d.preventDefault(),M!==0){se(!0);try{await na(t,{score:M,category:P||void 0,comment:K||void 0,raterType:"user"},r),Z(0),E(""),$(""),l(o("agents.ratings.addSuccess","Rating added"),"success"),await S()}catch(D){l(o("agents.ratings.addError","Failed to add rating: {{error}}",{error:lt(D)}),"error")}finally{se(!1)}}},W=async d=>{try{await ia(t,d,r),l(o("agents.ratings.deleteSuccess","Rating deleted"),"success"),await S()}catch(D){l(o("agents.ratings.deleteError","Failed to delete rating: {{error}}",{error:lt(D)}),"error")}},b=d=>{v(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(G,{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(Ct,{size:16}),o("agents.reflections.sectionTitle","Performance, Reflections & Ratings")]}),e.jsx("button",{className:"btn btn-secondary",onClick:X,disabled:R,title:o("agents.reflections.reflectNowTitle","Generate a manual reflection"),children:R?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:14,className:"animate-spin"}),o("agents.reflections.reflecting","Reflecting...")]}):e.jsxs(e.Fragment,{children:[e.jsx(At,{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(us,{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(an,{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(sa,{size:16,style:{color:"var(--in-progress)"}}),bs(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(Ct,{size:16,style:{color:k.successRate>=.8?"var(--color-success)":k.successRate>=.5?"var(--color-warning)":"var(--color-error)"}}),nn(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(Ht,{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(Ct,{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(G,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:o("agents.ratings.loading","Loading ratings...")})]}):e.jsxs(e.Fragment,{children:[f&&e.jsxs("div",{className:"rating-summary-card",children:[e.jsxs("div",{className:"rating-score-display",children:[e.jsx("span",{className:"rating-average",children:f.averageScore.toFixed(1)}),vs(Math.round(f.averageScore))]}),e.jsxs("div",{className:"rating-stats",children:[e.jsx("span",{className:"rating-count",children:o("agents.ratings.count","{{count}} ratings",{count:f.totalRatings})}),e.jsx("span",{className:`rating-trend-badge ${on(f.trend)}`,children:ln(f.trend,o)})]})]}),f&&Object.keys(f.categoryAverages).length>0&&e.jsxs("div",{className:"category-breakdown",children:[e.jsx("h4",{children:o("agents.ratings.categoryAverages","Category Averages")}),Object.entries(f.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:()=>Z(d),title:o("agents.ratings.starCount","{{count}} star",{count:d,defaultValue_one:"{{count}} star",defaultValue_other:"{{count}} stars"}),children:e.jsx(Ss,{size:24,fill:d<=M?"currentColor":"none",className:d<=M?"star-filled":"star-empty"})},d))}),e.jsxs("select",{value:P,onChange:d=>E(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:K,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:M===0||O,children:O?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:[vs(d.score),d.category&&e.jsx("span",{className:"rating-category-badge",children:d.category}),e.jsx("span",{className:"rating-time",children:xs(d.createdAt,o)}),e.jsx("button",{type:"button",className:"rating-delete-btn touch-target",onClick:()=>void W(d.id),title:o("agents.ratings.deleteRating","Delete rating"),children:e.jsx(ct,{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(G,{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(Ht,{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:J=>J.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:rn(d.trigger,o)}),e.jsx("span",{className:"reflection-timestamp",children:xs(d.timestamp,o)}),e.jsx("span",{className:"reflection-chevron",children:D?e.jsx(Cs,{size:16}):e.jsx(ws,{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(Ht,{size:14})," ",o("agents.reflections.insights","Insights")]}),e.jsx("ul",{children:d.insights.map((J,xe)=>e.jsx("li",{children:J},xe))})]}),d.suggestedImprovements.length>0&&e.jsxs("div",{className:"reflection-suggestions",children:[e.jsxs("h5",{children:[e.jsx(us,{size:14})," ",o("agents.reflections.suggestedImprovements","Suggested Improvements")]}),e.jsx("ul",{children:d.suggestedImprovements.map((J,xe)=>e.jsx("li",{children:J},xe))})]}),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:bs(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 dn={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 et(t,r){const l=Date.now(),o=new Date(t).getTime(),s=l-o,p=r??((n,f,u)=>u?f.replace(/\{\{(\w+)\}\}/g,(j,c)=>String(u[c]??"")):f);if(s<0){const n=Math.abs(s);if(n<6e4)return p("time.inAMoment","in a moment");if(n<36e5){const u=Math.floor(n/6e4);return p("time.inMinutes","in {{n}}m",{n:u})}if(n<864e5){const u=Math.floor(n/36e5);return p("time.inHours","in {{n}}h",{n:u})}const f=Math.floor(n/864e5);return p("time.inDays","in {{n}}d",{n:f})}if(s<6e4)return p("time.justNow","just now");if(s<36e5){const n=Math.floor(s/6e4);return p("time.minutesAgo","{{n}}m ago",{n})}if(s<864e5){const n=Math.floor(s/36e5);return p("time.hoursAgo","{{n}}h ago",{n})}const k=Math.floor(s/864e5);return p("time.daysAgo","{{n}}d ago",{n:k})}const un="⚠️",mn=[{id:"dashboard",label:"Dashboard",icon:tn},{id:"logs",label:"Logs",icon:dt},{id:"mail",label:"Mail",icon:ma},{id:"runs",label:"Runs",icon:Rt},{id:"tasks",label:"Tasks",icon:Es},{id:"employees",label:"Employees",icon:Ls},{id:"soul",label:"Soul",icon:ga},{id:"instructions",label:"Instructions",icon:Ka},{id:"memory",label:"Agent Memory",icon:dt},{id:"reflections",label:"Evaluation",icon:Ct},{id:"config",label:"Settings",icon:ha}],Xt={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)"}},Mt={completed:{icon:fe,color:"var(--color-success)"},failed:{icon:Na,color:"var(--color-error)"},active:{icon:G,color:"var(--in-progress)"},terminated:{icon:Xe,color:"var(--text-muted)"}},gn=Bs(Zt),hn=700;function fn(t,r){return t.some(l=>l.path===r)?r:t.find(l=>l.layer==="long-term")?.path??t[0]?.path??""}function On({agentId:t,projectId:r,onClose:l,addToast:o,onChildClick:s,inline:p=!1,showInlineBackButton:k=!1,initialTab:n,initialRunId:f,preferActiveRun:u=!1,onMutationSuccess:j}){const{t:c}=ke("app"),[m,w]=a.useState(null),[T,z]=a.useState(1),{confirm:R}=Rs(),[B,O]=a.useState([]),[se,N]=a.useState(!0),[v,M]=a.useState(n??"dashboard"),[Z,P]=a.useState(!1),[E,K]=a.useState(!1),[$,V]=a.useState(!1),[S,X]=a.useState(!1),[F,W]=a.useState(!1),[b,y]=a.useState(!1),[d,D]=a.useState(0),[J,xe]=a.useState(0),[Me,Le]=a.useState(0),[ce,H]=a.useState(null),[ae,Ae]=a.useState(null),[De,x]=a.useState(!1),[A,ie]=a.useState(null),q=a.useRef(null),Je=a.useRef(null),ue=a.useRef(!1);ra(q,!p,"fusion:agent-detail-modal-size");const ze=a.useRef(l),me=a.useRef(o),Be=a.useRef(null),He=a.useRef(!1),Oe=a.useRef(null),ne=a.useRef(0),ut=a.useRef(t),Fe=a.useRef(r);ze.current=l,me.current=o,Be.current=m,a.useEffect(()=>{let h=!1;return la(r).then(L=>{h||z(L.heartbeatMultiplier??1)}).catch(()=>{h||z(1)}),()=>{h=!0}},[r]);const ye=a.useCallback(async()=>{Be.current===null&&N(!0);try{const L=await oa(t,r);w(L)}catch(L){me.current(`Failed to load agent: ${U(L)}`,"error"),ze.current()}finally{N(!1)}},[t,r]),mt=a.useCallback(async()=>{const h=ne.current,L=t,I=r,_=()=>ne.current!==h||t!==L||r!==I;try{if(m?.taskId){H(null),Oe.current=null;const Re=await ca(m.taskId,I,{limit:100});if(_())return;O(Re.entries);return}const le=await Ms(L,1,I);if(_())return;const be=le[0]??null;if(H(be),!be){Oe.current=null,O([]);return}if(Oe.current===be.id)return;const Ce=await As(L,be.id,I);if(_())return;O(Ce),Oe.current=be.id}catch(le){if(_())return;console.error("Failed to load agent logs:",le)}},[m?.taskId,t,r]),tt=a.useCallback(async()=>{x(!0),ie(null);try{const h=await da(t,r);Ae(h)}catch(h){ie(U(h)),Ae(null)}finally{x(!1)}},[t,r]),Lt=a.useCallback(h=>{He.current=h},[]),st=a.useCallback(async(h=!1)=>{await j?.({agentId:t,deleted:h})},[t,j]),$e=a.useCallback(async()=>{await ye(),await st(!1)},[ye,st]);a.useEffect(()=>{ye()},[ye]),a.useEffect(()=>{const h=setInterval(()=>{ye()},3e4);return()=>{clearInterval(h)}},[ye]),a.useEffect(()=>{m&&v==="logs"&&mt()},[m,v,mt]),a.useEffect(()=>{v!=="logs"&&(Oe.current=null)},[v]),a.useEffect(()=>{m&&v==="mail"&&tt()},[m,v,tt]),a.useEffect(()=>{if(!S)return;const h=I=>{Je.current?.contains(I.target)||X(!1)},L=I=>{I.key==="Escape"&&X(!1)};return document.addEventListener("mousedown",h),document.addEventListener("keydown",L),()=>{document.removeEventListener("mousedown",h),document.removeEventListener("keydown",L)}},[S]),a.useEffect(()=>{if(!S)return;let h=!1;return y(!0),wt(void 0,r).then(L=>{if(h)return;const I=L.filter(_=>!It(_));D(I.filter(_=>_.state==="active"||_.state==="running").length),xe(I.filter(_=>_.state==="paused").length)}).catch(()=>{h||(D(0),xe(0))}).finally(()=>{h||y(!1)}),()=>{h=!0}},[S,r]),a.useEffect(()=>{if(v!=="logs"||m?.taskId||!ce||ce.status!=="active")return;const h=ne.current,L=t,I=ce.id,_=r?`?projectId=${encodeURIComponent(r)}`:"",le=St(`/api/agents/${encodeURIComponent(L)}/runs/${encodeURIComponent(I)}/logs/stream${_}`,{events:{"agent:log":be=>{if(ne.current===h)try{const Ce=JSON.parse(be.data);O(Re=>[...Re,Ce])}catch{}}},onOpen:()=>{ne.current===h&&P(!0)},onError:()=>{ne.current===h&&P(!1)}});return()=>{le(),ne.current===h&&P(!1)}},[v,m?.taskId,t,r,ce]),a.useEffect(()=>{(ut.current!==t||Fe.current!==r)&&(ut.current=t,Fe.current=r,ne.current++,O([]),P(!1),H(null),Ae(null),ie(null),Oe.current=null,He.current=!1)},[t,r]),a.useEffect(()=>{const h=r?`?projectId=${encodeURIComponent(r)}`:"",L=ne.current,I=_=>{if(ne.current===L)try{const le=JSON.parse(_.data);if(!le||typeof le!="object"||le.agentId!==t)return;ye()}catch{}};return St(`/api/events${h}`,{events:{"agent:updated":_=>{if(ne.current===L)try{const le=JSON.parse(_.data);if(!le||typeof le!="object"||le.id!==t||He.current)return;ye()}catch{}},"approval:requested":I,"approval:updated":I,"approval:decided":I}})},[t,r,ye]),a.useEffect(()=>{if(v!=="logs"||!m?.taskId){P(!1);return}const h=ne.current,L=m.taskId,I=r?`?projectId=${encodeURIComponent(r)}`:"",_=St(`/api/tasks/${encodeURIComponent(L)}/logs/stream${I}`,{events:{"agent:log":le=>{if(ne.current===h)try{const be=JSON.parse(le.data);O(Ce=>[...Ce,be])}catch{}}},onOpen:()=>{ne.current===h&&P(!0)},onError:()=>{ne.current===h&&P(!1)}});return()=>{_(),ne.current===h&&P(!1)}},[m?.taskId,v,r]);const Pe=async h=>{if(E||!Be.current)return;const L=Be.current.state;if(L!==h){K(!0),w(I=>I&&{...I,state:h});try{await gs(t,h,r),o(c("agents.stateUpdated","Agent state updated to {{newState}}",{newState:h}),"success"),await $e()}catch(I){w(_=>_&&{..._,state:L}),o(c("agents.stateUpdateFailed","Failed to update state: {{error}}",{error:U(I)}),"error")}finally{K(!1)}}},gt=async h=>{if(!F){X(!1),W(!0);try{const I=(await wt(void 0,r)).filter(he=>!It(he)),_=I.filter(he=>h==="paused"?he.state==="active"||he.state==="running":he.state==="paused"),le=I.length-_.length;if(_.length===0){o(c("agents.bulkNoEligible","No agents eligible to {{action}}",{action:h==="paused"?c("agents.pause","pause"):c("agents.resume","resume")}),"error");return}if(!await R({title:h==="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:h==="paused"?c("agents.pauseAction","Pause"):c("agents.resumeAction","Resume"),count:_.length}),danger:h==="paused"}))return;const Ce=await Promise.allSettled(_.map(he=>gs(he.id,h,r))),Re=Ce.map((he,Ke)=>({result:he,agent:_[Ke]})).filter(he=>he.result.status==="rejected"),Ne=Ce.length-Re.length,nt=Re.length,Ze=h==="paused"?c("agents.pausedPast","Paused"):c("agents.resumedPast","Resumed"),pt=Ne===1?c("agents.agentSingular","agent"):c("agents.agentPlural","agents"),bt=c(Ne===1?"agents.bulkResult_one":"agents.bulkResult_other","{{action}} {{successCount}} {{agentWord}}; skipped {{skippedCount}}",{action:Ze,successCount:Ne,agentWord:pt,skippedCount:le});if(nt>0){const he=Re.slice(0,3).map(({agent:Ke,result:xt})=>`${Ke.name||Ke.id}: ${U(xt.reason)}`).join("; ");o(c("agents.bulkResultWithFailures","{{summary}}; failed {{failureCount}}{{detail}}",{summary:bt,failureCount:nt,detail:he?` (${he})`:""}),"error")}else o(bt,"success");await $e()}catch(L){o(c("agents.bulkActionFailed","Failed to {{action}} agents: {{error}}",{action:h==="paused"?c("agents.pause","pause"):c("agents.resume","resume"),error:U(L)}),"error")}finally{W(!1)}}},at=async()=>{if(!$){V(!0);try{await ba(t,r,{source:"on_demand",triggerDetail:"Triggered from dashboard"}),o(c("agents.heartbeatStarted","Heartbeat run started for {{name}}",{name:m?.name??t}),"success"),Le(h=>h+1)}catch(h){o(c("agents.heartbeatStartFailed","Failed to start heartbeat run: {{error}}",{error:U(h)}),"error")}finally{V(!1)}}},Ge=async()=>{if(!(!m||!await R({title:c("agents.deleteTitle","Delete Agent"),message:c("agents.deleteConfirm",'Delete agent "{{name}}"? This cannot be undone.',{name:m.name}),danger:!0})))try{await xa(t,r),o(c("agents.deleted",'Agent "{{name}}" deleted',{name:m.name}),"success"),await st(!0),l()}catch(L){o(c("agents.deleteFailed","Failed to delete agent: {{error}}",{error:U(L)}),"error")}},ht=()=>m?pa(m,T):{label:"Unknown",icon:e.jsx(Qt,{size:14}),color:"var(--text-muted)",stateDerived:!1},ft=async()=>{if(m){const h=await Ha(m.id);o(h?c("agents.idCopied","Agent ID copied to clipboard"):c("agents.idCopyFailed","Failed to copy agent ID"),h?"success":"error")}};if(se)return p?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(G,{className:"animate-spin",size:24}),e.jsx("span",{children:c("agents.loading","Loading agent...")})]})}):e.jsx("div",{className:"agent-detail-overlay",onMouseDown:h=>{h.target===h.currentTarget&&(ue.current=!0)},onMouseUp:h=>{ue.current&&h.target===h.currentTarget&&l(),ue.current=!1},role:"dialog","aria-modal":"true",children:e.jsx("div",{className:"agent-detail-modal",ref:q,children:e.jsxs("div",{className:"agent-detail-loading",children:[e.jsx(G,{className:"animate-spin",size:24}),e.jsx("span",{children:c("agents.loading","Loading agent...")})]})})});if(!m)return null;const Ye=Xt[m.state],Se=ht(),Ie=p?"agent-detail-inline":"agent-detail-modal",pe=b||d===0,_e=b||J===0;return e.jsx("div",{className:p?"agent-detail-inline-shell":"agent-detail-overlay",onClick:h=>!p&&h.target===h.currentTarget&&l(),role:p?"region":"dialog","aria-label":p?"Agent detail":void 0,"aria-modal":p?void 0:"true",children:e.jsxs("div",{className:Ie,ref:q,children:[e.jsxs("div",{className:"agent-detail-header",children:[e.jsxs("div",{className:"agent-detail-identity",children:[p&&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(Fs,{size:16}),c("agents.agentsLabel","Agents")]}):null,e.jsx("div",{className:"agent-detail-icon",children:e.jsx(Ps,{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:Ye.bg,color:Ye.text,border:`1px solid ${Ye.border}`},children:m.state}),e.jsxs("span",{className:"badge",style:{color:Se.color},title:Se.reason??Se.label,children:[Se.icon,!Se.stateDerived&&Se.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 Pe("active"),disabled:E,children:[e.jsx(Bt,{size:14}),c("agents.start","Start")]}),e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void at(),"aria-label":c("agents.runNowFor","Run now for {{name}}",{name:m.name}),disabled:$||E,children:[e.jsx(Rt,{size:14}),c("agents.runNow","Run Now")]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:Ge,children:[e.jsx(ct,{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 Pe("paused"),disabled:E,"aria-label":c("agents.pause","Pause"),children:[e.jsx(ms,{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 Pe("paused"),disabled:E,"aria-label":c("agents.stop","Stop"),children:[e.jsx(Xe,{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 at(),"aria-label":c("agents.runNowFor","Run now for {{name}}",{name:m.name}),disabled:$||E,children:[e.jsx(Rt,{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 Pe("active"),disabled:E,"aria-label":c("agents.resume","Resume"),children:[e.jsx(Bt,{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:Ge,children:[e.jsx(ct,{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 Pe("paused"),disabled:E,"aria-label":c("agents.pause","Pause"),children:[e.jsx(ms,{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 Pe("paused"),disabled:E,"aria-label":c("agents.stop","Stop"),children:[e.jsx(Xe,{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 Pe("active"),disabled:E,children:[e.jsx(Bt,{size:14}),c("agents.retry","Retry")]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:()=>void Pe("paused"),disabled:E,"aria-label":c("agents.stop","Stop"),children:[e.jsx(Xe,{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:Ge,"aria-label":c("agents.delete","Delete"),children:[e.jsx(ct,{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:Je,children:[e.jsx("button",{type:"button",className:"btn-icon",onClick:()=>X(h=>!h),"aria-haspopup":"menu","aria-expanded":S,"aria-label":c("agents.bulkActions","Bulk agent actions"),title:c("agents.bulkActions","Bulk agent actions"),disabled:E||F,children:e.jsx(ua,{size:16})}),S&&e.jsxs("div",{className:"agent-detail-bulk-menu-popover",role:"menu",children:[e.jsxs("button",{type:"button",role:"menuitem",className:"agent-detail-bulk-menu-item",onClick:()=>void gt("paused"),disabled:pe||F,children:[c("agents.pauseAll","Pause All Agents"),e.jsx("span",{className:"agent-detail-bulk-menu-item-hint",children:b?c("agents.loadingEligible","Loading eligible agents..."):pe?c("agents.noActiveEligible","No active agents eligible"):c(d===1?"agents.pauseCountHint_one":"agents.pauseCountHint_other",d===1?"Pause {{count}} active/running agent":"Pause {{count}} active/running agents",{count:d})})]}),e.jsxs("button",{type:"button",role:"menuitem",className:"agent-detail-bulk-menu-item",onClick:()=>void gt("active"),disabled:_e||F,children:[c("agents.resumeAll","Resume All Agents"),e.jsx("span",{className:"agent-detail-bulk-menu-item-hint",children:b?c("agents.loadingEligible","Loading eligible agents..."):_e?c("agents.noPausedEligible","No paused agents eligible"):c(J===1?"agents.resumeCountHint_one":"agents.resumeCountHint_other",J===1?"Resume {{count}} paused agent":"Resume {{count}} paused agents",{count:J})})]})]})]}),e.jsx("button",{className:"btn-icon",onClick:()=>void ye(),title:c("common.refresh","Refresh"),"aria-label":c("common.refresh","Refresh"),children:e.jsx(At,{size:16})}),!p&&e.jsx("button",{className:"btn-icon",onClick:l,"aria-label":c("common.close","Close"),title:c("common.close","Close"),children:e.jsx(Ts,{size:20})})]})]})]}),e.jsx("div",{className:"agent-detail-tabs",children:mn.map(h=>{const L={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",v===h.id&&"active"),onClick:()=>M(h.id),children:[e.jsx(h.icon,{size:16}),L[h.id]]},h.id)})}),e.jsxs("div",{className:"agent-detail-content",children:[v==="dashboard"&&e.jsx(pn,{agent:m,health:Se,onChildClick:s,projectId:r}),v==="logs"&&e.jsx(bn,{logs:B,isStreaming:Z,hasTask:!!m.taskId||B.length>0||ce!==null,fallbackLabel:!m.taskId&&ce?c("agents.latestRunLabel","Latest run · {{id}}",{id:ce.id.slice(0,8)}):null}),v==="mail"&&e.jsx(vn,{agent:m,mailbox:ae,isLoading:De,error:A,projectId:r,addToast:o,onRefresh:()=>void tt()}),v==="runs"&&e.jsx(jn,{addToast:o,agentId:m.id,projectId:r,agentState:m.state,agentName:m.name,initialRunId:f,preferActiveRun:u,runNowRefreshToken:Me,isEphemeral:It(m)}),v==="tasks"&&e.jsx(kn,{agentId:m.id,projectId:r,addToast:o}),v==="employees"&&e.jsx(Fn,{agentId:m.id,projectId:r,onChildClick:s}),v==="soul"&&e.jsx(Cn,{agent:m,projectId:r,addToast:o,onSaved:$e}),v==="instructions"&&e.jsx(Rn,{agent:m,projectId:r,addToast:o,onSaved:$e}),v==="memory"&&e.jsx(wn,{agent:m,projectId:r,addToast:o,onSaved:$e}),v==="reflections"&&e.jsx(cn,{agentId:m.id,projectId:r,addToast:o}),v==="config"&&e.jsx(An,{agent:m,projectId:r,addToast:o,onSaved:$e,onHasChangesChange:Lt,onDelete:Ge,onAgentDraftApplied:h=>{w(L=>L&&{...L,...h})}},m.id)]}),!p&&e.jsxs("div",{className:"agent-detail-footer",children:[e.jsx("button",{className:"btn-icon",onClick:ft,title:c("agents.copyId","Copy Agent ID"),children:e.jsx(fa,{})}),e.jsx("span",{className:"agent-detail-id",onClick:ft,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(Ds,{taskId:m.taskId,taskColumn:m.taskColumn}),e.jsx(zs,{size:12})]})]})]})]})})}function pn({agent:t,health:r,onChildClick:l,projectId:o}){const{t:s}=ke("app"),p=Xt[t.state],[k,n]=a.useState([]),[f,u]=a.useState(!0),[j,c]=a.useState(null),[m,w]=a.useState([]),[T,z]=a.useState(null),[R,B]=a.useState(null),[O,se]=a.useState(!1),[N,v]=a.useState(null),M=typeof t.runtimeConfig?.runtimeHint=="string"?t.runtimeConfig.runtimeHint:"",Z=(()=>{const b=t.runtimeConfig??{};if(M){const y=m.find(d=>d.runtimeId===M);return y?y.name:M}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(()=>{Yt(t.id,o).then(c).catch(()=>c(null))},[t.id,o]),a.useEffect(()=>{Hs(o).then(w).catch(()=>w([]))},[o]),a.useEffect(()=>{let b=!1;return u(!0),va(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 P=a.useMemo(()=>{const b=t.completedRuns||[],y=new Date;y.setHours(0,0,0,0);const d=b.filter(J=>new Date(J.startedAt)>=y),D=b.filter(J=>J.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]),E=(t.completedRuns||[]).slice(0,5),K=Array.isArray(t.metadata?.skills)?t.metadata.skills:[],$=T?$t(T):null,V=a.useCallback(async b=>{se(!0),v(null),B(null);try{const y=await ja(b,o);B(y)}catch(y){v(U(y))}finally{se(!1)}},[o]),S=a.useCallback(b=>{if(T===b){z(null),B(null),v(null),se(!1);return}z(b),V(b)},[V,T]),X=t.state==="active"||t.state==="running",F=ya(t.runtimeConfig?.heartbeatIntervalMs),W=X&&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:un}),e.jsxs("span",{children:[e.jsx("strong",{children:s("agents.budgetExhaustedTitle","Budget Exhausted:")})," ",s("agents.budgetExhaustedBody","This agent has exceeded its token budget and may operate with limited functionality.")]})]}),e.jsxs("section",{className:"dashboard-summary-card dashboard-summary-hero",children:[e.jsxs("div",{className:"dashboard-summary-hero__heading",children:[e.jsx(Qt,{}),e.jsx("h3",{children:s("agents.overview","Overview")}),e.jsx("strong",{children:t.name}),e.jsx("span",{className:"inline-badge",style:{background:p.bg,color:p.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:M?s("agents.runtime","Runtime"):s("agents.model","Model")}),e.jsxs("span",{children:[" ",Z??s("agents.auto","Auto")]})]}),K.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:K.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:()=>S(b),"aria-expanded":y,"aria-label":s("agents.viewSkillDetails","View details for {{skill}}",{skill:$t(b)}),children:$t(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:()=>S(T),children:[e.jsx(Ts,{size:14}),s("common.close","Close")]})]}),O?e.jsxs("div",{className:"dashboard-summary-skill-detail-loading",role:"status","aria-live":"polite",children:[e.jsx(G,{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(Is,{size:14}),e.jsx("span",{children:N}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void V(T),children:s("common.retry","Retry")})]}):R?e.jsx("pre",{className:"dashboard-summary-skill-detail-content",children:R.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?et(t.lastHeartbeatAt,s):s("agents.never","Never")})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:s("agents.nextExpected","Next expected")}),e.jsx("p",{children:W?et(W,s):s("agents.notScheduled","Not scheduled")})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:s("agents.interval","Interval")}),e.jsx("p",{children:Bs(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(Ds,{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(zs,{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:P.successfulRuns,total:P.totalRuns,rate:P.successRate})}),E.length===0?e.jsx("p",{className:"text-muted",children:s("agents.noRunsYet","No runs yet")}):e.jsx("div",{className:"runs-list",children:E.map(b=>{const y=Mt[b.status]||Mt.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:et(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:P.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:P.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:[P.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")}),f?e.jsxs("div",{className:"chain-of-command-loading",role:"status","aria-live":"polite",children:[e.jsx(G,{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 bn({logs:t,isStreaming:r,hasTask:l,fallbackLabel:o}){const{t:s}=ke("app");return l?e.jsxs("div",{className:"logs-tab",children:[e.jsxs("div",{className:"logs-header",children:[e.jsx("span",{className:"logs-count",children:s("agents.logEntries","{{count}} entries",{count:t.length})}),o&&e.jsx("span",{className:"text-muted logs-fallback-label",children:o}),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(dt,{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(Os,{entries:t,loading:!1})]}):e.jsx("div",{className:"logs-tab",children:e.jsxs("div",{className:"logs-empty",children:[e.jsx(dt,{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 xn(t,r){const l=new Date(t),s=new Date().getTime()-l.getTime(),p=Math.floor(s/6e4),k=Math.floor(s/36e5),n=Math.floor(s/864e5),f=r??((u,j,c)=>c?j.replace(/\{\{(\w+)\}\}/g,(m,w)=>String(c[w]??"")):j);return p<1?f("time.justNow","just now"):p<60?f("time.minutesAgo","{{n}}m ago",{n:p}):k<24?f("time.hoursAgo","{{n}}h ago",{n:k}):n<7?f("time.daysAgo","{{n}}d ago",{n}):l.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function kt(t,r,l,o){const s=o??((p,k,n)=>n?k.replace(/\{\{(\w+)\}\}/g,(f,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 p=l?.get(t)?.trim();return!p||p===t?s("mailbox.agentById","Agent: {{id}}",{id:t}):s("mailbox.agentByName","Agent: {{name}}",{name:p})}return s("mailbox.system","System")}function vn({agent:t,mailbox:r,isLoading:l,error:o,projectId:s,addToast:p,onRefresh:k}){const{t:n}=ke("app"),[f,u]=a.useState("inbox"),[j,c]=a.useState([]);a.useEffect(()=>{let N=!1;return wt(void 0,s).then(v=>{N||c(v)}).catch(()=>{N||c([])}),()=>{N=!0}},[s]);const m=a.useMemo(()=>{const N=new Map;for(const M of j){if(!M.id)continue;const Z=typeof M.name=="string"?M.name.trim():"";Z.length>0&&N.set(M.id,Z)}const v=typeof t.name=="string"?t.name.trim():"";return v.length>0&&N.set(t.id,v),N},[j,t.id,t.name]),[w,T]=a.useState(null),z=f==="inbox"?r?.inbox??[]:r?.outbox??[],R=w?z.find(N=>N.id===w)??null:null;a.useEffect(()=>{T(null)},[f,t.id]);const B=async N=>{if(T(N.id),!(f!=="inbox"||N.read))try{await Ja(N.id,s),k()}catch(v){const M=`Failed to mark message as read: ${U(v)}`;p?p(M,"error"):console.warn(M)}},O=()=>{T(null),k()},se=N=>e.jsxs("button",{type:"button",className:oe("mailbox-item","agent-mail-tab-message",f==="inbox"&&!N.read&&"unread",w===N.id&&"agent-mail-tab-message--selected"),onClick:()=>void B(N),"aria-pressed":w===N.id,children:[e.jsx("div",{className:"mailbox-item-avatar",children:(f==="inbox"?N.fromType:N.toType)==="agent"?e.jsx(Qt,{size:16}):e.jsx(Ia,{size:16})}),e.jsxs("div",{className:"mailbox-item-content",children:[e.jsxs("div",{className:"mailbox-item-header",children:[f==="inbox"?e.jsx("span",{className:"mailbox-item-from",children:kt(N.fromId,N.fromType,m,n)}):e.jsx("span",{className:"mailbox-item-to",children:n("agents.mailTo","To: {{recipient}}",{recipient:kt(N.toId,N.toType,m,n)})}),e.jsx("span",{className:"mailbox-item-time",children:xn(N.createdAt,n)})]}),e.jsxs("div",{className:"mailbox-item-preview",children:[N.content.slice(0,80),N.content.length>80?"…":""]})]}),f==="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:O,disabled:l,children:[e.jsx(At,{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",f==="inbox"&&"active"),onClick:()=>u("inbox"),children:[e.jsx(hs,{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",f==="outbox"&&"active"),onClick:()=>u("outbox"),children:[e.jsx(fs,{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(G,{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(Is,{size:16}),e.jsx("span",{children:n("agents.mailboxLoadFailed","Failed to load mailbox: {{error}}",{error:o})})]}):null,!l&&!o?R?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(Fs,{size:14}),f==="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:kt(R.fromId,R.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:kt(R.toId,R.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:R.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(R.createdAt).toLocaleString()})]}),R.metadata?.replyTo?.messageId?e.jsx("div",{className:"agent-mail-tab-reply-context",children:n("agents.replyingTo","↪ Replying to message {{id}}",{id:R.metadata.replyTo.messageId})}):null]}),e.jsx("div",{className:"agent-mail-tab-detail-body",children:R.content})]}):e.jsx("div",{className:"mailbox-list","data-testid":"agent-detail-mail-list",children:z.length===0?e.jsxs("div",{className:"mailbox-empty","data-testid":"agent-detail-mail-empty",children:[f==="inbox"?e.jsx(hs,{size:32}):e.jsx(fs,{size:32}),e.jsx("p",{children:f==="inbox"?n("agents.noInboxMessages","No received messages for this agent"):n("agents.noOutboxMessages","No sent messages for this agent")})]}):z.map(se)}):null]})}function jn({addToast:t,agentId:r,projectId:l,agentState:o,agentName:s,initialRunId:p,preferActiveRun:k,runNowRefreshToken:n,isEphemeral:f}){const{t:u}=ke("app"),[j,c]=a.useState([]),{confirm:m}=Rs(),[w,T]=a.useState(!0),[z,R]=a.useState(null),[B,O]=a.useState([]),[se,N]=a.useState(!1),[v,M]=a.useState(null),[Z,P]=a.useState(!1),[E,K]=a.useState(null),[$,V]=a.useState([]),S=a.useRef(!1),X=a.useRef(!1),F=a.useCallback(async()=>{try{const x=await Ms(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(f){K(null),V([]);return}const x=l?`?projectId=${encodeURIComponent(l)}`:"";fetch(`/api/agents/${encodeURIComponent(r)}/token-usage${x}`).then(async A=>{if(!A.ok){if(A.status===400){K(null);return}throw new Error(`Request failed: ${A.status}`)}const ie=await A.json();K(ie)}).catch(A=>{t(`Failed to load cache hit ratio: ${U(A)}`,"error")}),ka(r,7,l).then(A=>V(A)).catch(A=>{const ie=U(A).toLowerCase();if(ie.includes("ephemeral")||ie.includes("400")){V([]);return}t(`Failed to load prompt sizes: ${U(A)}`,"error")})},[r,l,t,f]),a.useEffect(()=>{if(!X.current){X.current=!0;return}T(!0),F()},[F,n]);const W=j.some(x=>x.status==="active"),b=z?j.find(x=>x.id===z)?.status:void 0;a.useEffect(()=>{if(!W)return;const x=setInterval(()=>{F()},5e3);return()=>clearInterval(x)},[W,F]),a.useEffect(()=>{if(!z||b!=="active")return;const x=l?`?projectId=${encodeURIComponent(l)}`:"";return St(`/api/agents/${encodeURIComponent(r)}/runs/${encodeURIComponent(z)}/logs/stream${x}`,{events:{"agent:log":A=>{try{const ie=JSON.parse(A.data);O(q=>[...q,ie])}catch{}}}})},[z,b,r,l]);const y=a.useCallback(async x=>{if(z===x){R(null),O([]),M(null);return}R(x),N(!0),P(!0),O([]),M(null);try{const[A,ie]=await Promise.all([As(r,x,l),Sa(r,x,l)]);O(A),M(ie)}catch(A){t(u("agents.runDetailsFailed","Failed to load run details: {{error}}",{error:U(A)}),"error"),O([]),M(null)}finally{N(!1),P(!1)}},[z,r,l,t]);a.useEffect(()=>{S.current=!1},[r,p,k]),a.useEffect(()=>{if(j.length===0||w||S.current)return;const x=p?j.find(A=>A.id===p):k?j.find(A=>A.status==="active"):null;S.current=!0,x&&y(x.id)},[p,k,j,w,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 Ba(r,l),t(u("agents.runStopped","Run stopped"),"success"),T(!0),F()}catch(A){t(u("agents.stopRunFailed","Failed to stop run: {{error}}",{error:U(A)}),"error")}};if(w&&j.length===0)return e.jsx("div",{className:"runs-tab",children:e.jsxs("div",{className:"runs-loading-row",children:[e.jsx(G,{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(Rt,{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,A)=>new Date(A.startedAt).getTime()-new Date(x.startedAt).getTime()),J=D.filter(x=>x.status==="active"),xe=D.filter(x=>x.status!=="active"),Me=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,Le=(x,A,ie)=>{const q=Mt[x.status]||Mt.completed,Je=q.icon,ue=x.endedAt?yn(new Date(x.startedAt),new Date(x.endedAt)):u("agents.inProgress","In progress"),ze=z===x.id;return e.jsxs("div",{children:[e.jsxs("div",{className:oe("run-card",ie&&"run-card--active",ze&&"run-card--selected","run-card--clickable"),onClick:()=>void y(x.id),role:"button",tabIndex:0,"aria-expanded":ze,"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:me=>{(me.key==="Enter"||me.key===" ")&&(me.preventDefault(),y(x.id))},children:[e.jsxs("div",{className:"run-header",children:[e.jsxs("div",{className:"run-header-group",children:[ze?e.jsx(Cs,{size:14}):e.jsx(ws,{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:["#",A+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:me=>{me.preventDefault(),me.stopPropagation(),d()},"aria-label":u("agents.stopActiveRun","Stop active run"),children:[e.jsx(Xe,{size:12})," ",u("agents.stop","Stop")]}),e.jsxs("span",{className:oe("run-status",x.status),children:[e.jsx(Je,{size:14,style:{color:q.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:et(x.startedAt,u)})}),e.jsx("span",{children:"•"}),e.jsx("span",{children:ue}),x.triggerDetail&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsx("span",{className:"text-muted",children:x.triggerDetail})]})]})]}),ze&&e.jsxs("div",{className:"run-logs-container",children:[Z?e.jsxs("div",{className:"run-details-loading-state",children:[e.jsx(G,{size:14,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:u("agents.loadingDetails","Loading details...")})]}):v&&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")}),v.systemPrompt?e.jsx("pre",{className:"run-output-panel",children:v.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")}),v.executionPrompt?e.jsx("pre",{className:"run-output-panel",children:v.executionPrompt}):e.jsx("div",{className:"text-muted run-output-empty",children:u("agents.executionPromptNotCaptured","Execution prompt not captured for this run")})]})}),v.usageJson&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:u("agents.tokenUsage","Token Usage")}),Me(v.usageJson)]}),v.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:v.stdoutExcerpt.length>2e3?`${v.stdoutExcerpt.slice(0,2e3)}
|
|
16
|
+
*/const sn=[["path",{d:"M16 17h6v-6",key:"t6n2it"}],["path",{d:"m22 17-8.5-8.5-5 5L2 7",key:"x473p"}]],an=Zt("trending-down",sn);function bs(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 nn(t){return`${Math.round(t*100)}%`}function xs(t,r){const l=Date.now(),o=new Date(t).getTime(),s=l-o;if(s<0){const p=Math.abs(s);return p<6e4?r("agents.time.inAMoment","in a moment"):p<36e5?r("agents.time.inMinutes","in {{count}}m",{count:Math.floor(p/6e4)}):p<864e5?r("agents.time.inHours","in {{count}}h",{count:Math.floor(p/36e5)}):r("agents.time.inDays","in {{count}}d",{count:Math.floor(p/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 rn(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 lt(t){return t instanceof Error&&t.message?t.message:String(t)}function ln(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 on(t){switch(t){case"improving":return"trend-improving";case"declining":return"trend-declining";case"stable":return"trend-stable";default:return"trend-insufficient"}}function vs(t,r=5){return e.jsx("span",{className:"rating-stars",children:Array.from({length:r},(l,o)=>e.jsx(Ss,{size:14,className:o<t?"star-filled":"star-empty",fill:o<t?"currentColor":"none"},o))})}function cn({agentId:t,projectId:r,addToast:l}){const{t:o}=ke("app"),[s,p]=a.useState([]),[k,n]=a.useState(null),[f,u]=a.useState(null),[j,c]=a.useState([]),[m,w]=a.useState(!0),[T,z]=a.useState(!0),[R,B]=a.useState(!1),[O,se]=a.useState(!1),[N,v]=a.useState(null),[M,K]=a.useState(0),[P,E]=a.useState(""),[Z,$]=a.useState(""),V=a.useCallback(async()=>{try{const[d,D]=await Promise.all([Qs(t,20,r),Xs(t,void 0,r)]);p(d),n(D)}catch(d){l(o("agents.reflections.loadError","Failed to load reflections: {{error}}",{error:lt(d)}),"error")}finally{w(!1)}},[t,r,l]),S=a.useCallback(async()=>{try{const[d,D]=await Promise.all([ea(t,r),ta(t,{limit:50},r)]);u(d),c(D)}catch(d){l(o("agents.ratings.loadError","Failed to load ratings: {{error}}",{error:lt(d)}),"error")}finally{z(!1)}},[t,r,l]);a.useEffect(()=>{V(),S()},[V,S]);const X=async()=>{B(!0);try{if(!await aa(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"),w(!0),await V()}catch(d){const D=lt(d),J=D.toLowerCase();J.includes("agent not found")||J.includes("not found")?l(o("agents.reflections.agentNotFound","This agent is no longer available. It may have been deleted."),"error"):J.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{B(!1)}},F=async d=>{if(d.preventDefault(),M!==0){se(!0);try{await na(t,{score:M,category:P||void 0,comment:Z||void 0,raterType:"user"},r),K(0),E(""),$(""),l(o("agents.ratings.addSuccess","Rating added"),"success"),await S()}catch(D){l(o("agents.ratings.addError","Failed to add rating: {{error}}",{error:lt(D)}),"error")}finally{se(!1)}}},W=async d=>{try{await ia(t,d,r),l(o("agents.ratings.deleteSuccess","Rating deleted"),"success"),await S()}catch(D){l(o("agents.ratings.deleteError","Failed to delete rating: {{error}}",{error:lt(D)}),"error")}},b=d=>{v(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(G,{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(Ct,{size:16}),o("agents.reflections.sectionTitle","Performance, Reflections & Ratings")]}),e.jsx("button",{className:"btn btn-secondary",onClick:X,disabled:R,title:o("agents.reflections.reflectNowTitle","Generate a manual reflection"),children:R?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:14,className:"animate-spin"}),o("agents.reflections.reflecting","Reflecting...")]}):e.jsxs(e.Fragment,{children:[e.jsx(At,{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(us,{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(an,{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(sa,{size:16,style:{color:"var(--in-progress)"}}),bs(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(Ct,{size:16,style:{color:k.successRate>=.8?"var(--color-success)":k.successRate>=.5?"var(--color-warning)":"var(--color-error)"}}),nn(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(Ht,{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(Ct,{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(G,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:o("agents.ratings.loading","Loading ratings...")})]}):e.jsxs(e.Fragment,{children:[f&&e.jsxs("div",{className:"rating-summary-card",children:[e.jsxs("div",{className:"rating-score-display",children:[e.jsx("span",{className:"rating-average",children:f.averageScore.toFixed(1)}),vs(Math.round(f.averageScore))]}),e.jsxs("div",{className:"rating-stats",children:[e.jsx("span",{className:"rating-count",children:o("agents.ratings.count","{{count}} ratings",{count:f.totalRatings})}),e.jsx("span",{className:`rating-trend-badge ${on(f.trend)}`,children:ln(f.trend,o)})]})]}),f&&Object.keys(f.categoryAverages).length>0&&e.jsxs("div",{className:"category-breakdown",children:[e.jsx("h4",{children:o("agents.ratings.categoryAverages","Category Averages")}),Object.entries(f.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:()=>K(d),title:o("agents.ratings.starCount","{{count}} star",{count:d,defaultValue_one:"{{count}} star",defaultValue_other:"{{count}} stars"}),children:e.jsx(Ss,{size:24,fill:d<=M?"currentColor":"none",className:d<=M?"star-filled":"star-empty"})},d))}),e.jsxs("select",{value:P,onChange:d=>E(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:M===0||O,children:O?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:[vs(d.score),d.category&&e.jsx("span",{className:"rating-category-badge",children:d.category}),e.jsx("span",{className:"rating-time",children:xs(d.createdAt,o)}),e.jsx("button",{type:"button",className:"rating-delete-btn touch-target",onClick:()=>void W(d.id),title:o("agents.ratings.deleteRating","Delete rating"),children:e.jsx(ct,{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(G,{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(Ht,{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:J=>J.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:rn(d.trigger,o)}),e.jsx("span",{className:"reflection-timestamp",children:xs(d.timestamp,o)}),e.jsx("span",{className:"reflection-chevron",children:D?e.jsx(Cs,{size:16}):e.jsx(ws,{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(Ht,{size:14})," ",o("agents.reflections.insights","Insights")]}),e.jsx("ul",{children:d.insights.map((J,xe)=>e.jsx("li",{children:J},xe))})]}),d.suggestedImprovements.length>0&&e.jsxs("div",{className:"reflection-suggestions",children:[e.jsxs("h5",{children:[e.jsx(us,{size:14})," ",o("agents.reflections.suggestedImprovements","Suggested Improvements")]}),e.jsx("ul",{children:d.suggestedImprovements.map((J,xe)=>e.jsx("li",{children:J},xe))})]}),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:bs(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 dn={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 et(t,r){const l=Date.now(),o=new Date(t).getTime(),s=l-o,p=r??((n,f,u)=>u?f.replace(/\{\{(\w+)\}\}/g,(j,c)=>String(u[c]??"")):f);if(s<0){const n=Math.abs(s);if(n<6e4)return p("time.inAMoment","in a moment");if(n<36e5){const u=Math.floor(n/6e4);return p("time.inMinutes","in {{n}}m",{n:u})}if(n<864e5){const u=Math.floor(n/36e5);return p("time.inHours","in {{n}}h",{n:u})}const f=Math.floor(n/864e5);return p("time.inDays","in {{n}}d",{n:f})}if(s<6e4)return p("time.justNow","just now");if(s<36e5){const n=Math.floor(s/6e4);return p("time.minutesAgo","{{n}}m ago",{n})}if(s<864e5){const n=Math.floor(s/36e5);return p("time.hoursAgo","{{n}}h ago",{n})}const k=Math.floor(s/864e5);return p("time.daysAgo","{{n}}d ago",{n:k})}const un="⚠️",mn=[{id:"dashboard",label:"Dashboard",icon:tn},{id:"logs",label:"Logs",icon:dt},{id:"mail",label:"Mail",icon:ma},{id:"runs",label:"Runs",icon:Rt},{id:"tasks",label:"Tasks",icon:Es},{id:"employees",label:"Employees",icon:Ls},{id:"soul",label:"Soul",icon:ga},{id:"instructions",label:"Instructions",icon:Za},{id:"memory",label:"Agent Memory",icon:dt},{id:"reflections",label:"Evaluation",icon:Ct},{id:"config",label:"Settings",icon:ha}],Xt={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)"}},Mt={completed:{icon:fe,color:"var(--color-success)"},failed:{icon:Na,color:"var(--color-error)"},active:{icon:G,color:"var(--in-progress)"},terminated:{icon:Xe,color:"var(--text-muted)"}},gn=Bs(Kt),hn=700;function fn(t,r){return t.some(l=>l.path===r)?r:t.find(l=>l.layer==="long-term")?.path??t[0]?.path??""}function On({agentId:t,projectId:r,onClose:l,addToast:o,onChildClick:s,inline:p=!1,showInlineBackButton:k=!1,initialTab:n,initialRunId:f,preferActiveRun:u=!1,onMutationSuccess:j}){const{t:c}=ke("app"),[m,w]=a.useState(null),[T,z]=a.useState(1),{confirm:R}=Rs(),[B,O]=a.useState([]),[se,N]=a.useState(!0),[v,M]=a.useState(n??"dashboard"),[K,P]=a.useState(!1),[E,Z]=a.useState(!1),[$,V]=a.useState(!1),[S,X]=a.useState(!1),[F,W]=a.useState(!1),[b,y]=a.useState(!1),[d,D]=a.useState(0),[J,xe]=a.useState(0),[Me,Le]=a.useState(0),[ce,H]=a.useState(null),[ae,Ae]=a.useState(null),[De,x]=a.useState(!1),[A,ie]=a.useState(null),q=a.useRef(null),Je=a.useRef(null),ue=a.useRef(!1);ra(q,!p,"fusion:agent-detail-modal-size");const ze=a.useRef(l),me=a.useRef(o),Be=a.useRef(null),He=a.useRef(!1),Oe=a.useRef(null),ne=a.useRef(0),ut=a.useRef(t),Fe=a.useRef(r);ze.current=l,me.current=o,Be.current=m,a.useEffect(()=>{let h=!1;return la(r).then(L=>{h||z(L.heartbeatMultiplier??1)}).catch(()=>{h||z(1)}),()=>{h=!0}},[r]);const ye=a.useCallback(async()=>{Be.current===null&&N(!0);try{const L=await oa(t,r);w(L)}catch(L){me.current(`Failed to load agent: ${U(L)}`,"error"),ze.current()}finally{N(!1)}},[t,r]),mt=a.useCallback(async()=>{const h=ne.current,L=t,I=r,_=()=>ne.current!==h||t!==L||r!==I;try{if(m?.taskId){H(null),Oe.current=null;const Re=await ca(m.taskId,I,{limit:100});if(_())return;O(Re.entries);return}const le=await Ms(L,1,I);if(_())return;const be=le[0]??null;if(H(be),!be){Oe.current=null,O([]);return}if(Oe.current===be.id)return;const Ce=await As(L,be.id,I);if(_())return;O(Ce),Oe.current=be.id}catch(le){if(_())return;console.error("Failed to load agent logs:",le)}},[m?.taskId,t,r]),tt=a.useCallback(async()=>{x(!0),ie(null);try{const h=await da(t,r);Ae(h)}catch(h){ie(U(h)),Ae(null)}finally{x(!1)}},[t,r]),Lt=a.useCallback(h=>{He.current=h},[]),st=a.useCallback(async(h=!1)=>{await j?.({agentId:t,deleted:h})},[t,j]),$e=a.useCallback(async()=>{await ye(),await st(!1)},[ye,st]);a.useEffect(()=>{ye()},[ye]),a.useEffect(()=>{const h=setInterval(()=>{ye()},3e4);return()=>{clearInterval(h)}},[ye]),a.useEffect(()=>{m&&v==="logs"&&mt()},[m,v,mt]),a.useEffect(()=>{v!=="logs"&&(Oe.current=null)},[v]),a.useEffect(()=>{m&&v==="mail"&&tt()},[m,v,tt]),a.useEffect(()=>{if(!S)return;const h=I=>{Je.current?.contains(I.target)||X(!1)},L=I=>{I.key==="Escape"&&X(!1)};return document.addEventListener("mousedown",h),document.addEventListener("keydown",L),()=>{document.removeEventListener("mousedown",h),document.removeEventListener("keydown",L)}},[S]),a.useEffect(()=>{if(!S)return;let h=!1;return y(!0),wt(void 0,r).then(L=>{if(h)return;const I=L.filter(_=>!It(_));D(I.filter(_=>_.state==="active"||_.state==="running").length),xe(I.filter(_=>_.state==="paused").length)}).catch(()=>{h||(D(0),xe(0))}).finally(()=>{h||y(!1)}),()=>{h=!0}},[S,r]),a.useEffect(()=>{if(v!=="logs"||m?.taskId||!ce||ce.status!=="active")return;const h=ne.current,L=t,I=ce.id,_=r?`?projectId=${encodeURIComponent(r)}`:"",le=St(`/api/agents/${encodeURIComponent(L)}/runs/${encodeURIComponent(I)}/logs/stream${_}`,{events:{"agent:log":be=>{if(ne.current===h)try{const Ce=JSON.parse(be.data);O(Re=>[...Re,Ce])}catch{}}},onOpen:()=>{ne.current===h&&P(!0)},onError:()=>{ne.current===h&&P(!1)}});return()=>{le(),ne.current===h&&P(!1)}},[v,m?.taskId,t,r,ce]),a.useEffect(()=>{(ut.current!==t||Fe.current!==r)&&(ut.current=t,Fe.current=r,ne.current++,O([]),P(!1),H(null),Ae(null),ie(null),Oe.current=null,He.current=!1)},[t,r]),a.useEffect(()=>{const h=r?`?projectId=${encodeURIComponent(r)}`:"",L=ne.current,I=_=>{if(ne.current===L)try{const le=JSON.parse(_.data);if(!le||typeof le!="object"||le.agentId!==t)return;ye()}catch{}};return St(`/api/events${h}`,{events:{"agent:updated":_=>{if(ne.current===L)try{const le=JSON.parse(_.data);if(!le||typeof le!="object"||le.id!==t||He.current)return;ye()}catch{}},"approval:requested":I,"approval:updated":I,"approval:decided":I}})},[t,r,ye]),a.useEffect(()=>{if(v!=="logs"||!m?.taskId){P(!1);return}const h=ne.current,L=m.taskId,I=r?`?projectId=${encodeURIComponent(r)}`:"",_=St(`/api/tasks/${encodeURIComponent(L)}/logs/stream${I}`,{events:{"agent:log":le=>{if(ne.current===h)try{const be=JSON.parse(le.data);O(Ce=>[...Ce,be])}catch{}}},onOpen:()=>{ne.current===h&&P(!0)},onError:()=>{ne.current===h&&P(!1)}});return()=>{_(),ne.current===h&&P(!1)}},[m?.taskId,v,r]);const Pe=async h=>{if(E||!Be.current)return;const L=Be.current.state;if(L!==h){Z(!0),w(I=>I&&{...I,state:h});try{await gs(t,h,r),o(c("agents.stateUpdated","Agent state updated to {{newState}}",{newState:h}),"success"),await $e()}catch(I){w(_=>_&&{..._,state:L}),o(c("agents.stateUpdateFailed","Failed to update state: {{error}}",{error:U(I)}),"error")}finally{Z(!1)}}},gt=async h=>{if(!F){X(!1),W(!0);try{const I=(await wt(void 0,r)).filter(he=>!It(he)),_=I.filter(he=>h==="paused"?he.state==="active"||he.state==="running":he.state==="paused"),le=I.length-_.length;if(_.length===0){o(c("agents.bulkNoEligible","No agents eligible to {{action}}",{action:h==="paused"?c("agents.pause","pause"):c("agents.resume","resume")}),"error");return}if(!await R({title:h==="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:h==="paused"?c("agents.pauseAction","Pause"):c("agents.resumeAction","Resume"),count:_.length}),danger:h==="paused"}))return;const Ce=await Promise.allSettled(_.map(he=>gs(he.id,h,r))),Re=Ce.map((he,Ze)=>({result:he,agent:_[Ze]})).filter(he=>he.result.status==="rejected"),Ne=Ce.length-Re.length,nt=Re.length,Ke=h==="paused"?c("agents.pausedPast","Paused"):c("agents.resumedPast","Resumed"),pt=Ne===1?c("agents.agentSingular","agent"):c("agents.agentPlural","agents"),bt=c(Ne===1?"agents.bulkResult_one":"agents.bulkResult_other","{{action}} {{successCount}} {{agentWord}}; skipped {{skippedCount}}",{action:Ke,successCount:Ne,agentWord:pt,skippedCount:le});if(nt>0){const he=Re.slice(0,3).map(({agent:Ze,result:xt})=>`${Ze.name||Ze.id}: ${U(xt.reason)}`).join("; ");o(c("agents.bulkResultWithFailures","{{summary}}; failed {{failureCount}}{{detail}}",{summary:bt,failureCount:nt,detail:he?` (${he})`:""}),"error")}else o(bt,"success");await $e()}catch(L){o(c("agents.bulkActionFailed","Failed to {{action}} agents: {{error}}",{action:h==="paused"?c("agents.pause","pause"):c("agents.resume","resume"),error:U(L)}),"error")}finally{W(!1)}}},at=async()=>{if(!$){V(!0);try{await ba(t,r,{source:"on_demand",triggerDetail:"Triggered from dashboard"}),o(c("agents.heartbeatStarted","Heartbeat run started for {{name}}",{name:m?.name??t}),"success"),Le(h=>h+1)}catch(h){o(c("agents.heartbeatStartFailed","Failed to start heartbeat run: {{error}}",{error:U(h)}),"error")}finally{V(!1)}}},Ge=async()=>{if(!(!m||!await R({title:c("agents.deleteTitle","Delete Agent"),message:c("agents.deleteConfirm",'Delete agent "{{name}}"? This cannot be undone.',{name:m.name}),danger:!0})))try{await xa(t,r),o(c("agents.deleted",'Agent "{{name}}" deleted',{name:m.name}),"success"),await st(!0),l()}catch(L){o(c("agents.deleteFailed","Failed to delete agent: {{error}}",{error:U(L)}),"error")}},ht=()=>m?pa(m,T):{label:"Unknown",icon:e.jsx(Qt,{size:14}),color:"var(--text-muted)",stateDerived:!1},ft=async()=>{if(m){const h=await Ha(m.id);o(h?c("agents.idCopied","Agent ID copied to clipboard"):c("agents.idCopyFailed","Failed to copy agent ID"),h?"success":"error")}};if(se)return p?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(G,{className:"animate-spin",size:24}),e.jsx("span",{children:c("agents.loading","Loading agent...")})]})}):e.jsx("div",{className:"agent-detail-overlay",onMouseDown:h=>{h.target===h.currentTarget&&(ue.current=!0)},onMouseUp:h=>{ue.current&&h.target===h.currentTarget&&l(),ue.current=!1},role:"dialog","aria-modal":"true",children:e.jsx("div",{className:"agent-detail-modal",ref:q,children:e.jsxs("div",{className:"agent-detail-loading",children:[e.jsx(G,{className:"animate-spin",size:24}),e.jsx("span",{children:c("agents.loading","Loading agent...")})]})})});if(!m)return null;const Ye=Xt[m.state],Se=ht(),Ie=p?"agent-detail-inline":"agent-detail-modal",pe=b||d===0,_e=b||J===0;return e.jsx("div",{className:p?"agent-detail-inline-shell":"agent-detail-overlay",onClick:h=>!p&&h.target===h.currentTarget&&l(),role:p?"region":"dialog","aria-label":p?"Agent detail":void 0,"aria-modal":p?void 0:"true",children:e.jsxs("div",{className:Ie,ref:q,children:[e.jsxs("div",{className:"agent-detail-header",children:[e.jsxs("div",{className:"agent-detail-identity",children:[p&&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(Fs,{size:16}),c("agents.agentsLabel","Agents")]}):null,e.jsx("div",{className:"agent-detail-icon",children:e.jsx(Ps,{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:Ye.bg,color:Ye.text,border:`1px solid ${Ye.border}`},children:m.state}),e.jsxs("span",{className:"badge",style:{color:Se.color},title:Se.reason??Se.label,children:[Se.icon,!Se.stateDerived&&Se.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 Pe("active"),disabled:E,children:[e.jsx(Bt,{size:14}),c("agents.start","Start")]}),e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void at(),"aria-label":c("agents.runNowFor","Run now for {{name}}",{name:m.name}),disabled:$||E,children:[e.jsx(Rt,{size:14}),c("agents.runNow","Run Now")]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:Ge,children:[e.jsx(ct,{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 Pe("paused"),disabled:E,"aria-label":c("agents.pause","Pause"),children:[e.jsx(ms,{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 Pe("paused"),disabled:E,"aria-label":c("agents.stop","Stop"),children:[e.jsx(Xe,{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 at(),"aria-label":c("agents.runNowFor","Run now for {{name}}",{name:m.name}),disabled:$||E,children:[e.jsx(Rt,{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 Pe("active"),disabled:E,"aria-label":c("agents.resume","Resume"),children:[e.jsx(Bt,{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:Ge,children:[e.jsx(ct,{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 Pe("paused"),disabled:E,"aria-label":c("agents.pause","Pause"),children:[e.jsx(ms,{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 Pe("paused"),disabled:E,"aria-label":c("agents.stop","Stop"),children:[e.jsx(Xe,{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 Pe("active"),disabled:E,children:[e.jsx(Bt,{size:14}),c("agents.retry","Retry")]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:()=>void Pe("paused"),disabled:E,"aria-label":c("agents.stop","Stop"),children:[e.jsx(Xe,{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:Ge,"aria-label":c("agents.delete","Delete"),children:[e.jsx(ct,{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:Je,children:[e.jsx("button",{type:"button",className:"btn-icon",onClick:()=>X(h=>!h),"aria-haspopup":"menu","aria-expanded":S,"aria-label":c("agents.bulkActions","Bulk agent actions"),title:c("agents.bulkActions","Bulk agent actions"),disabled:E||F,children:e.jsx(ua,{size:16})}),S&&e.jsxs("div",{className:"agent-detail-bulk-menu-popover",role:"menu",children:[e.jsxs("button",{type:"button",role:"menuitem",className:"agent-detail-bulk-menu-item",onClick:()=>void gt("paused"),disabled:pe||F,children:[c("agents.pauseAll","Pause All Agents"),e.jsx("span",{className:"agent-detail-bulk-menu-item-hint",children:b?c("agents.loadingEligible","Loading eligible agents..."):pe?c("agents.noActiveEligible","No active agents eligible"):c(d===1?"agents.pauseCountHint_one":"agents.pauseCountHint_other",d===1?"Pause {{count}} active/running agent":"Pause {{count}} active/running agents",{count:d})})]}),e.jsxs("button",{type:"button",role:"menuitem",className:"agent-detail-bulk-menu-item",onClick:()=>void gt("active"),disabled:_e||F,children:[c("agents.resumeAll","Resume All Agents"),e.jsx("span",{className:"agent-detail-bulk-menu-item-hint",children:b?c("agents.loadingEligible","Loading eligible agents..."):_e?c("agents.noPausedEligible","No paused agents eligible"):c(J===1?"agents.resumeCountHint_one":"agents.resumeCountHint_other",J===1?"Resume {{count}} paused agent":"Resume {{count}} paused agents",{count:J})})]})]})]}),e.jsx("button",{className:"btn-icon",onClick:()=>void ye(),title:c("common.refresh","Refresh"),"aria-label":c("common.refresh","Refresh"),children:e.jsx(At,{size:16})}),!p&&e.jsx("button",{className:"btn-icon",onClick:l,"aria-label":c("common.close","Close"),title:c("common.close","Close"),children:e.jsx(Ts,{size:20})})]})]})]}),e.jsx("div",{className:"agent-detail-tabs",children:mn.map(h=>{const L={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",v===h.id&&"active"),onClick:()=>M(h.id),children:[e.jsx(h.icon,{size:16}),L[h.id]]},h.id)})}),e.jsxs("div",{className:"agent-detail-content",children:[v==="dashboard"&&e.jsx(pn,{agent:m,health:Se,onChildClick:s,projectId:r}),v==="logs"&&e.jsx(bn,{logs:B,isStreaming:K,hasTask:!!m.taskId||B.length>0||ce!==null,fallbackLabel:!m.taskId&&ce?c("agents.latestRunLabel","Latest run · {{id}}",{id:ce.id.slice(0,8)}):null}),v==="mail"&&e.jsx(vn,{agent:m,mailbox:ae,isLoading:De,error:A,projectId:r,addToast:o,onRefresh:()=>void tt()}),v==="runs"&&e.jsx(jn,{addToast:o,agentId:m.id,projectId:r,agentState:m.state,agentName:m.name,initialRunId:f,preferActiveRun:u,runNowRefreshToken:Me,isEphemeral:It(m)}),v==="tasks"&&e.jsx(kn,{agentId:m.id,projectId:r,addToast:o}),v==="employees"&&e.jsx(Fn,{agentId:m.id,projectId:r,onChildClick:s}),v==="soul"&&e.jsx(Cn,{agent:m,projectId:r,addToast:o,onSaved:$e}),v==="instructions"&&e.jsx(Rn,{agent:m,projectId:r,addToast:o,onSaved:$e}),v==="memory"&&e.jsx(wn,{agent:m,projectId:r,addToast:o,onSaved:$e}),v==="reflections"&&e.jsx(cn,{agentId:m.id,projectId:r,addToast:o}),v==="config"&&e.jsx(An,{agent:m,projectId:r,addToast:o,onSaved:$e,onHasChangesChange:Lt,onDelete:Ge,onAgentDraftApplied:h=>{w(L=>L&&{...L,...h})}},m.id)]}),!p&&e.jsxs("div",{className:"agent-detail-footer",children:[e.jsx("button",{className:"btn-icon",onClick:ft,title:c("agents.copyId","Copy Agent ID"),children:e.jsx(fa,{})}),e.jsx("span",{className:"agent-detail-id",onClick:ft,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(Ds,{taskId:m.taskId,taskColumn:m.taskColumn}),e.jsx(zs,{size:12})]})]})]})]})})}function pn({agent:t,health:r,onChildClick:l,projectId:o}){const{t:s}=ke("app"),p=Xt[t.state],[k,n]=a.useState([]),[f,u]=a.useState(!0),[j,c]=a.useState(null),[m,w]=a.useState([]),[T,z]=a.useState(null),[R,B]=a.useState(null),[O,se]=a.useState(!1),[N,v]=a.useState(null),M=typeof t.runtimeConfig?.runtimeHint=="string"?t.runtimeConfig.runtimeHint:"",K=(()=>{const b=t.runtimeConfig??{};if(M){const y=m.find(d=>d.runtimeId===M);return y?y.name:M}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(()=>{Yt(t.id,o).then(c).catch(()=>c(null))},[t.id,o]),a.useEffect(()=>{Hs(o).then(w).catch(()=>w([]))},[o]),a.useEffect(()=>{let b=!1;return u(!0),va(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 P=a.useMemo(()=>{const b=t.completedRuns||[],y=new Date;y.setHours(0,0,0,0);const d=b.filter(J=>new Date(J.startedAt)>=y),D=b.filter(J=>J.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]),E=(t.completedRuns||[]).slice(0,5),Z=Array.isArray(t.metadata?.skills)?t.metadata.skills:[],$=T?$t(T):null,V=a.useCallback(async b=>{se(!0),v(null),B(null);try{const y=await ja(b,o);B(y)}catch(y){v(U(y))}finally{se(!1)}},[o]),S=a.useCallback(b=>{if(T===b){z(null),B(null),v(null),se(!1);return}z(b),V(b)},[V,T]),X=t.state==="active"||t.state==="running",F=ya(t.runtimeConfig?.heartbeatIntervalMs),W=X&&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:un}),e.jsxs("span",{children:[e.jsx("strong",{children:s("agents.budgetExhaustedTitle","Budget Exhausted:")})," ",s("agents.budgetExhaustedBody","This agent has exceeded its token budget and may operate with limited functionality.")]})]}),e.jsxs("section",{className:"dashboard-summary-card dashboard-summary-hero",children:[e.jsxs("div",{className:"dashboard-summary-hero__heading",children:[e.jsx(Qt,{}),e.jsx("h3",{children:s("agents.overview","Overview")}),e.jsx("strong",{children:t.name}),e.jsx("span",{className:"inline-badge",style:{background:p.bg,color:p.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:M?s("agents.runtime","Runtime"):s("agents.model","Model")}),e.jsxs("span",{children:[" ",K??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:()=>S(b),"aria-expanded":y,"aria-label":s("agents.viewSkillDetails","View details for {{skill}}",{skill:$t(b)}),children:$t(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:()=>S(T),children:[e.jsx(Ts,{size:14}),s("common.close","Close")]})]}),O?e.jsxs("div",{className:"dashboard-summary-skill-detail-loading",role:"status","aria-live":"polite",children:[e.jsx(G,{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(Is,{size:14}),e.jsx("span",{children:N}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void V(T),children:s("common.retry","Retry")})]}):R?e.jsx("pre",{className:"dashboard-summary-skill-detail-content",children:R.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?et(t.lastHeartbeatAt,s):s("agents.never","Never")})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:s("agents.nextExpected","Next expected")}),e.jsx("p",{children:W?et(W,s):s("agents.notScheduled","Not scheduled")})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:s("agents.interval","Interval")}),e.jsx("p",{children:Bs(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(Ds,{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(zs,{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:P.successfulRuns,total:P.totalRuns,rate:P.successRate})}),E.length===0?e.jsx("p",{className:"text-muted",children:s("agents.noRunsYet","No runs yet")}):e.jsx("div",{className:"runs-list",children:E.map(b=>{const y=Mt[b.status]||Mt.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:et(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:P.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:P.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:[P.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")}),f?e.jsxs("div",{className:"chain-of-command-loading",role:"status","aria-live":"polite",children:[e.jsx(G,{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 bn({logs:t,isStreaming:r,hasTask:l,fallbackLabel:o}){const{t:s}=ke("app");return l?e.jsxs("div",{className:"logs-tab",children:[e.jsxs("div",{className:"logs-header",children:[e.jsx("span",{className:"logs-count",children:s("agents.logEntries","{{count}} entries",{count:t.length})}),o&&e.jsx("span",{className:"text-muted logs-fallback-label",children:o}),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(dt,{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(Os,{entries:t,loading:!1})]}):e.jsx("div",{className:"logs-tab",children:e.jsxs("div",{className:"logs-empty",children:[e.jsx(dt,{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 xn(t,r){const l=new Date(t),s=new Date().getTime()-l.getTime(),p=Math.floor(s/6e4),k=Math.floor(s/36e5),n=Math.floor(s/864e5),f=r??((u,j,c)=>c?j.replace(/\{\{(\w+)\}\}/g,(m,w)=>String(c[w]??"")):j);return p<1?f("time.justNow","just now"):p<60?f("time.minutesAgo","{{n}}m ago",{n:p}):k<24?f("time.hoursAgo","{{n}}h ago",{n:k}):n<7?f("time.daysAgo","{{n}}d ago",{n}):l.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function kt(t,r,l,o){const s=o??((p,k,n)=>n?k.replace(/\{\{(\w+)\}\}/g,(f,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 p=l?.get(t)?.trim();return!p||p===t?s("mailbox.agentById","Agent: {{id}}",{id:t}):s("mailbox.agentByName","Agent: {{name}}",{name:p})}return s("mailbox.system","System")}function vn({agent:t,mailbox:r,isLoading:l,error:o,projectId:s,addToast:p,onRefresh:k}){const{t:n}=ke("app"),[f,u]=a.useState("inbox"),[j,c]=a.useState([]);a.useEffect(()=>{let N=!1;return wt(void 0,s).then(v=>{N||c(v)}).catch(()=>{N||c([])}),()=>{N=!0}},[s]);const m=a.useMemo(()=>{const N=new Map;for(const M of j){if(!M.id)continue;const K=typeof M.name=="string"?M.name.trim():"";K.length>0&&N.set(M.id,K)}const v=typeof t.name=="string"?t.name.trim():"";return v.length>0&&N.set(t.id,v),N},[j,t.id,t.name]),[w,T]=a.useState(null),z=f==="inbox"?r?.inbox??[]:r?.outbox??[],R=w?z.find(N=>N.id===w)??null:null;a.useEffect(()=>{T(null)},[f,t.id]);const B=async N=>{if(T(N.id),!(f!=="inbox"||N.read))try{await Ja(N.id,s),k()}catch(v){const M=`Failed to mark message as read: ${U(v)}`;p?p(M,"error"):console.warn(M)}},O=()=>{T(null),k()},se=N=>e.jsxs("button",{type:"button",className:oe("mailbox-item","agent-mail-tab-message",f==="inbox"&&!N.read&&"unread",w===N.id&&"agent-mail-tab-message--selected"),onClick:()=>void B(N),"aria-pressed":w===N.id,children:[e.jsx("div",{className:"mailbox-item-avatar",children:(f==="inbox"?N.fromType:N.toType)==="agent"?e.jsx(Qt,{size:16}):e.jsx(Ia,{size:16})}),e.jsxs("div",{className:"mailbox-item-content",children:[e.jsxs("div",{className:"mailbox-item-header",children:[f==="inbox"?e.jsx("span",{className:"mailbox-item-from",children:kt(N.fromId,N.fromType,m,n)}):e.jsx("span",{className:"mailbox-item-to",children:n("agents.mailTo","To: {{recipient}}",{recipient:kt(N.toId,N.toType,m,n)})}),e.jsx("span",{className:"mailbox-item-time",children:xn(N.createdAt,n)})]}),e.jsxs("div",{className:"mailbox-item-preview",children:[N.content.slice(0,80),N.content.length>80?"…":""]})]}),f==="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:O,disabled:l,children:[e.jsx(At,{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",f==="inbox"&&"active"),onClick:()=>u("inbox"),children:[e.jsx(hs,{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",f==="outbox"&&"active"),onClick:()=>u("outbox"),children:[e.jsx(fs,{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(G,{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(Is,{size:16}),e.jsx("span",{children:n("agents.mailboxLoadFailed","Failed to load mailbox: {{error}}",{error:o})})]}):null,!l&&!o?R?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(Fs,{size:14}),f==="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:kt(R.fromId,R.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:kt(R.toId,R.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:R.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(R.createdAt).toLocaleString()})]}),R.metadata?.replyTo?.messageId?e.jsx("div",{className:"agent-mail-tab-reply-context",children:n("agents.replyingTo","↪ Replying to message {{id}}",{id:R.metadata.replyTo.messageId})}):null]}),e.jsx("div",{className:"agent-mail-tab-detail-body",children:R.content})]}):e.jsx("div",{className:"mailbox-list","data-testid":"agent-detail-mail-list",children:z.length===0?e.jsxs("div",{className:"mailbox-empty","data-testid":"agent-detail-mail-empty",children:[f==="inbox"?e.jsx(hs,{size:32}):e.jsx(fs,{size:32}),e.jsx("p",{children:f==="inbox"?n("agents.noInboxMessages","No received messages for this agent"):n("agents.noOutboxMessages","No sent messages for this agent")})]}):z.map(se)}):null]})}function jn({addToast:t,agentId:r,projectId:l,agentState:o,agentName:s,initialRunId:p,preferActiveRun:k,runNowRefreshToken:n,isEphemeral:f}){const{t:u}=ke("app"),[j,c]=a.useState([]),{confirm:m}=Rs(),[w,T]=a.useState(!0),[z,R]=a.useState(null),[B,O]=a.useState([]),[se,N]=a.useState(!1),[v,M]=a.useState(null),[K,P]=a.useState(!1),[E,Z]=a.useState(null),[$,V]=a.useState([]),S=a.useRef(!1),X=a.useRef(!1),F=a.useCallback(async()=>{try{const x=await Ms(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(f){Z(null),V([]);return}const x=l?`?projectId=${encodeURIComponent(l)}`:"";fetch(`/api/agents/${encodeURIComponent(r)}/token-usage${x}`).then(async A=>{if(!A.ok){if(A.status===400){Z(null);return}throw new Error(`Request failed: ${A.status}`)}const ie=await A.json();Z(ie)}).catch(A=>{t(`Failed to load cache hit ratio: ${U(A)}`,"error")}),ka(r,7,l).then(A=>V(A)).catch(A=>{const ie=U(A).toLowerCase();if(ie.includes("ephemeral")||ie.includes("400")){V([]);return}t(`Failed to load prompt sizes: ${U(A)}`,"error")})},[r,l,t,f]),a.useEffect(()=>{if(!X.current){X.current=!0;return}T(!0),F()},[F,n]);const W=j.some(x=>x.status==="active"),b=z?j.find(x=>x.id===z)?.status:void 0;a.useEffect(()=>{if(!W)return;const x=setInterval(()=>{F()},5e3);return()=>clearInterval(x)},[W,F]),a.useEffect(()=>{if(!z||b!=="active")return;const x=l?`?projectId=${encodeURIComponent(l)}`:"";return St(`/api/agents/${encodeURIComponent(r)}/runs/${encodeURIComponent(z)}/logs/stream${x}`,{events:{"agent:log":A=>{try{const ie=JSON.parse(A.data);O(q=>[...q,ie])}catch{}}}})},[z,b,r,l]);const y=a.useCallback(async x=>{if(z===x){R(null),O([]),M(null);return}R(x),N(!0),P(!0),O([]),M(null);try{const[A,ie]=await Promise.all([As(r,x,l),Sa(r,x,l)]);O(A),M(ie)}catch(A){t(u("agents.runDetailsFailed","Failed to load run details: {{error}}",{error:U(A)}),"error"),O([]),M(null)}finally{N(!1),P(!1)}},[z,r,l,t]);a.useEffect(()=>{S.current=!1},[r,p,k]),a.useEffect(()=>{if(j.length===0||w||S.current)return;const x=p?j.find(A=>A.id===p):k?j.find(A=>A.status==="active"):null;S.current=!0,x&&y(x.id)},[p,k,j,w,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 Ba(r,l),t(u("agents.runStopped","Run stopped"),"success"),T(!0),F()}catch(A){t(u("agents.stopRunFailed","Failed to stop run: {{error}}",{error:U(A)}),"error")}};if(w&&j.length===0)return e.jsx("div",{className:"runs-tab",children:e.jsxs("div",{className:"runs-loading-row",children:[e.jsx(G,{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(Rt,{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,A)=>new Date(A.startedAt).getTime()-new Date(x.startedAt).getTime()),J=D.filter(x=>x.status==="active"),xe=D.filter(x=>x.status!=="active"),Me=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,Le=(x,A,ie)=>{const q=Mt[x.status]||Mt.completed,Je=q.icon,ue=x.endedAt?yn(new Date(x.startedAt),new Date(x.endedAt)):u("agents.inProgress","In progress"),ze=z===x.id;return e.jsxs("div",{children:[e.jsxs("div",{className:oe("run-card",ie&&"run-card--active",ze&&"run-card--selected","run-card--clickable"),onClick:()=>void y(x.id),role:"button",tabIndex:0,"aria-expanded":ze,"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:me=>{(me.key==="Enter"||me.key===" ")&&(me.preventDefault(),y(x.id))},children:[e.jsxs("div",{className:"run-header",children:[e.jsxs("div",{className:"run-header-group",children:[ze?e.jsx(Cs,{size:14}):e.jsx(ws,{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:["#",A+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:me=>{me.preventDefault(),me.stopPropagation(),d()},"aria-label":u("agents.stopActiveRun","Stop active run"),children:[e.jsx(Xe,{size:12})," ",u("agents.stop","Stop")]}),e.jsxs("span",{className:oe("run-status",x.status),children:[e.jsx(Je,{size:14,style:{color:q.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:et(x.startedAt,u)})}),e.jsx("span",{children:"•"}),e.jsx("span",{children:ue}),x.triggerDetail&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsx("span",{className:"text-muted",children:x.triggerDetail})]})]})]}),ze&&e.jsxs("div",{className:"run-logs-container",children:[K?e.jsxs("div",{className:"run-details-loading-state",children:[e.jsx(G,{size:14,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:u("agents.loadingDetails","Loading details...")})]}):v&&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")}),v.systemPrompt?e.jsx("pre",{className:"run-output-panel",children:v.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")}),v.executionPrompt?e.jsx("pre",{className:"run-output-panel",children:v.executionPrompt}):e.jsx("div",{className:"text-muted run-output-empty",children:u("agents.executionPromptNotCaptured","Execution prompt not captured for this run")})]})}),v.usageJson&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:u("agents.tokenUsage","Token Usage")}),Me(v.usageJson)]}),v.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:v.stdoutExcerpt.length>2e3?`${v.stdoutExcerpt.slice(0,2e3)}
|
|
17
17
|
|
|
18
|
-
... (truncated, ${v.stdoutExcerpt.length} chars total)`:v.stdoutExcerpt})]}),v.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(Oa,{errorText:v.stderrExcerpt,summaryPrefix:"Run error",issueContext:{surface:"AgentDetailView runs",agentId:r,agentName:s,agentState:o,runId:v.id,taskId:void 0,timestamp:v.startedAt}})]}),v.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(v.resultJson,null,2)})]}),v.contextSnapshot&&Object.keys(v.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(v.contextSnapshot).map(([me,Be])=>e.jsxs("span",{className:"run-context-item",children:[e.jsxs("span",{className:"text-muted",children:[me,":"]})," ",e.jsx("span",{children:String(Be)})]},me))})]}),!v.stdoutExcerpt&&!v.stderrExcerpt&&!v.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")}),se?e.jsxs("div",{className:"run-details-loading-state",children:[e.jsx(G,{size:14,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:u("agents.loadingLogs","Loading logs...")})]}):B.length===0?e.jsx("div",{className:"text-muted run-output-empty",children:u("agents.noLogsForRun","No logs available for this run")}):e.jsx(Os,{entries:B,loading:!1})]})]})]},x.id)},ce=(x,A)=>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:(A.hitRatio*100).toFixed(1),cached:A.totalCachedTokens.toLocaleString(),written:A.totalCacheWriteTokens.toLocaleString(),input:A.totalInputTokens.toLocaleString(),tasks:A.nTasks.toLocaleString()})})]},x),H=$[0],ae=[...$].reverse(),Ae=Math.max(1,...ae.map(x=>x.execChars)),De=ae.map((x,A)=>{const ie=ae.length<=1?0:A/(ae.length-1)*100,q=100-Math.round(x.execChars/Ae*100);return`${ie},${q}`}).join(" ");return e.jsxs("div",{className:"runs-tab",children:[$.length>0&&H&&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:[H.systemChars.toLocaleString()," / ",H.execChars.toLocaleString()," / ",H.totalChars.toLocaleString()]})]})]}),E&&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:[ce(u("agents.last24h","Last 24h"),E.last24h),ce(u("agents.last7d","Last 7d"),E.last7d),ce(u("agents.allTime","All time"),E.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"}),W&&e.jsxs("span",{className:"run-live-indicator run-live-indicator--with-margin",children:[e.jsx("span",{className:"live-dot"}),u("agents.live","Live")]})]}),e.jsx("div",{className:"run-header-group",children:W&&e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void d(),"aria-label":u("agents.stopActiveRunFor","Stop active run for {{name}}",{name:s??r}),children:[e.jsx(Xe,{size:14})," ",u("agents.stopRun","Stop Run")]})})]}),J.map((x,A)=>Le(x,A,!0)),xe.map((x,A)=>Le(x,J.length+A,!1))]})}function yn(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 Nn(t){const r=t.title?.trim()||t.description?.trim()||t.id;return r.length>80?`${r.slice(0,77)}...`:r}function kn({agentId:t,projectId:r,addToast:l}){const{t:o}=ke("app"),[s,p]=a.useState([]),[k,n]=a.useState(!0);return a.useEffect(()=>{let f=!1;return n(!0),Ca(t,r).then(u=>{f||p(u)}).catch(u=>{f||(p([]),l(o("agents.loadTasksFailed","Failed to load assigned tasks: {{error}}",{error:U(u)}),"error"))}).finally(()=>{f||n(!1)}),()=>{f=!0}},[t,r,l]),k?e.jsxs("div",{className:"agent-tasks-empty",children:[e.jsx(G,{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(Es,{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(f=>e.jsxs("a",{className:"agent-task-item",href:`/tasks/${f.id}`,children:[e.jsxs("div",{className:"agent-task-row",children:[e.jsx("span",{className:"agent-task-id",children:f.id}),e.jsx("span",{className:`agent-task-column column-${f.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")}[f.column]??f.column})]}),e.jsx("div",{className:"agent-task-title",title:f.title||f.description||f.id,children:Nn(f)}),e.jsxs("div",{className:"agent-task-status",children:[f.status??"idle"," · ",o("agents.taskUpdated","Updated {{time}}",{time:et(f.updatedAt,o)})]})]},f.id))})}const ot=[{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 Sn(t){const r={};for(const l of ot){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(p=>p.value)??[];s.length>0&&!s.includes(o)&&(r[l.key]=`"${l.label}" must be one of: ${s.join(", ")}`)}}}return r}function Cn({agent:t,projectId:r,addToast:l,onSaved:o}){const{t:s}=ke("app"),[p,k]=a.useState(t.soul??""),[n,f]=a.useState(!1),[u,j]=a.useState(!1),[c,m]=a.useState(!1),w=a.useRef(null);a.useEffect(()=>{k(t.soul??""),j(!1),m(!1)},[t.id,t.soul]),a.useEffect(()=>()=>{w.current&&clearTimeout(w.current)},[]);const T=p!==(t.soul??""),z=async()=>{if(p.length>1e4){l(s("agents.soulTooLong","Soul must be at most 10,000 characters"),"error");return}f(!0);try{await $a(t.id,p,r),l(s("agents.soulSaved","Soul saved"),"success"),j(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>j(!1),3e3),await o()}catch(R){l(s("agents.soulSaveFailed","Failed to save soul: {{error}}",{error:U(R)}),"error")}finally{f(!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(Ft,{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(Pt,{size:14}),s("common.preview","Preview")]})]})}),c?p.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(Tt,{remarkPlugins:[Et],children:p})}):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:p,onChange:R=>{k(R.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 z(),children:n?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:16,className:"animate-spin"}),s("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{size:16}),s("agents.saveSoul","Save Soul")]})}),!T&&u&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(fe,{size:14}),s("agents.soulSaved","Soul saved")]})]})]})})}function wn({agent:t,projectId:r,addToast:l,onSaved:o}){const{t:s}=ke("app"),[p,k]=a.useState(t.memory??""),[n,f]=a.useState(!1),[u,j]=a.useState(!1),[c,m]=a.useState(!1),[w,T]=a.useState([]),[z,R]=a.useState(!1),[B,O]=a.useState(""),[se,N]=a.useState(""),[v,M]=a.useState(!1),[Z,P]=a.useState(!1),[E,K]=a.useState(!1),[$,V]=a.useState(!1),[S,X]=a.useState(""),F=a.useRef(null),W=a.useRef(null),b=t.state==="running",y=p!==(t.memory??""),d=a.useMemo(()=>w.find(H=>H.path===B),[w,B]),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."),J=a.useCallback(async H=>{P(!0);try{const ae=await Ra(t.id,H,r);O(ae.path),N(ae.content),M(!1),V(!1)}catch(ae){l(s("agents.memoryFileLoadFailed","Failed to load agent memory file: {{error}}",{error:U(ae)}),"error")}finally{P(!1)}},[t.id,r,l]),xe=a.useCallback(async(H="")=>{R(!0);try{const{files:ae}=await Ma(t.id,r);if(T(ae),ae.length===0){O(""),N(""),M(!1);return}const Ae=fn(ae,H);await J(Ae)}catch(ae){l(s("agents.memoryFilesLoadFailed","Failed to load memory files: {{error}}",{error:U(ae)}),"error"),T([]),O(""),N(""),M(!1)}finally{R(!1)}},[t.id,r,l,J]);a.useEffect(()=>{k(t.memory??""),j(!1),m(!1),X(""),V(!1),xe()},[t.id,t.memory,xe]),a.useEffect(()=>()=>{F.current&&clearTimeout(F.current),W.current&&clearTimeout(W.current)},[]);const Me=async()=>{if(p.length>5e4){l(s("agents.memoryTooLong","Memory must be at most 50,000 characters"),"error");return}f(!0);try{await Ua(t.id,p,r),l(s("agents.memorySaved","Memory saved"),"success"),j(!0),F.current&&clearTimeout(F.current),F.current=setTimeout(()=>j(!1),3e3),await o()}catch(H){l(s("agents.memorySaveFailed","Failed to save memory: {{error}}",{error:U(H)}),"error")}finally{f(!1)}},Le=async H=>{if(!(!H||H===B)){if(v){X(s("agents.saveBeforeSwitch","Save the current file before switching to another file."));return}X(""),await J(H)}},ce=async()=>{if(B){K(!0);try{await Va(t.id,B,se,r),M(!1),V(!0),W.current&&clearTimeout(W.current),W.current=setTimeout(()=>V(!1),3e3),X(""),await xe(B),l(s("agents.memoryFileSaved","Agent memory file saved"),"success"),await o()}catch(H){l(s("agents.memoryFileSaveFailed","Failed to save agent memory file: {{error}}",{error:U(H)}),"error")}finally{K(!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(Ft,{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(Pt,{size:14}),s("common.preview","Preview")]})]})}),c?p.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(Tt,{remarkPlugins:[Et],children:p})}):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:p,readOnly:b,onChange:H=>{k(H.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 Me(),children:n?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:16,className:"animate-spin"}),s("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{size:16}),s("agents.saveMemory","Save Memory")]})}),!y&&u&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(fe,{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:B,disabled:z||Z||E||w.length===0,onChange:H=>{Le(H.target.value)},children:w.length===0?e.jsx("option",{value:"",children:s("agents.noMemoryFiles","No memory files found")}):w.map(H=>{const ae={"long-term":s("agents.memoryLayerLongTerm","Long-term"),daily:s("agents.memoryLayerDaily","Daily"),dreams:s("agents.memoryLayerDreams","Dreams")}[H.layer]??H.layer;return e.jsxs("option",{value:H.path,children:[ae," • ",H.label]},H.path)})}),z&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(G,{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:et(d.updatedAt,s)})]}),e.jsx("div",{className:"agent-memory-file-editor config-textarea-top-spacing",children:e.jsx(Aa,{content:se,onChange:H=>{N(H),M(!0),V(!1),X("")},readOnly:b||!B||Z,filePath:B||"MEMORY.md",forceToolbarActionsVisible:!0})}),Z&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(G,{size:14,className:"animate-spin"}),s("agents.loadingFileContent","Loading file content…")]}),S&&e.jsx("span",{className:"config-hint config-hint--top-spacing config-hint--block",children:S}),e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!v||E||!B||b,onClick:()=>void ce(),children:E?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:16,className:"animate-spin"}),s("agents.savingFile","Saving file…")]}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{size:16}),s("agents.saveMemoryFile","Save Memory File")]})}),!v&&$&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(fe,{size:14}),s("agents.memoryFileSaved","Memory file saved")]})]})]})]})]})})}function Rn({agent:t,projectId:r,addToast:l,onSaved:o}){const{t:s}=ke("app"),[p,k]=a.useState(t.instructionsText??""),[n,f]=a.useState(t.instructionsPath??""),[u,j]=a.useState(!1),[c,m]=a.useState(""),[w,T]=a.useState(!1),[z,R]=a.useState(!1),[B,O]=a.useState(!1),[se,N]=a.useState(!1),[v,M]=a.useState(!1),[Z,P]=a.useState(!1),E=a.useRef(null),K=a.useRef(null);a.useEffect(()=>{const F=n.trim();if(!F){m(""),R(!1);return}T(!0),$s("project",F).then(W=>{m(W.content),R(!1)}).catch(W=>{const b=U(W);b.includes("ENOENT")||b.includes("Not found")||b.includes("not found")?(m(""),R(!1)):(l(`Failed to load instructions file: ${b}`,"error"),m(""))}).finally(()=>{T(!1)})},[n,l]),a.useEffect(()=>{k(t.instructionsText??""),f(t.instructionsPath??""),M(!1),P(!1),j(!1)},[t.id,t.instructionsText,t.instructionsPath]),a.useEffect(()=>()=>{E.current&&clearTimeout(E.current),K.current&&clearTimeout(K.current)},[]);const $=(()=>{const F=p??"",W=t.instructionsText??"",b=n?.trim()??"",y=t.instructionsPath?.trim()??"";return F!==W||b!==y})(),V=async()=>{O(!0);try{await _a(t.id,{instructionsText:p||void 0,instructionsPath:n.trim()||void 0},r),l(s("agents.instructionsSaved","Instructions saved"),"success"),M(!0),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>M(!1),3e3),await o()}catch(F){l(s("agents.instructionsSaveFailed","Failed to save instructions: {{error}}",{error:U(F)}),"error")}finally{O(!1)}},S=async()=>{const F=n.trim();if(!F){l(s("agents.noInstructionsPath","No instructions file path set"),"error");return}N(!0);try{await _s("project",F,c),l(s("agents.instructionsFileSaved","Instructions file saved"),"success"),R(!1),P(!0),K.current&&clearTimeout(K.current),K.current=setTimeout(()=>P(!1),3e3),await o()}catch(W){l(s("agents.instructionsFileSaveFailed","Failed to save instructions file: {{error}}",{error:U(W)}),"error")}finally{N(!1)}},X=!!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:[!p.trim()&&!u&&e.jsx("button",{type:"button",className:"btn btn-sm","data-testid":"instructions-insert-template",onClick:()=>{k(qa),M(!1)},children:s("agents.insertInstructionsTemplate","Insert template")}),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(Ft,{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(Pt,{size:14}),s("common.preview","Preview")]})]})}),u?p.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(Tt,{remarkPlugins:[Et],children:p})}):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:p,onChange:F=>{k(F.target.value),M(!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=>{f(F.target.value),M(!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:!$||B,onClick:()=>void V(),children:B?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:16,className:"animate-spin"}),s("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{size:16}),s("agents.saveInstructions","Save Instructions")]})}),!$&&v&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(fe,{size:14}),s("agents.instructionsSaved","Instructions saved")]})]})]}),X&&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")}),w&&e.jsxs("span",{className:"config-hint config-hint--inline-tight",children:[e.jsx(G,{size:12,className:"animate-spin"}),s("common.loading","Loading...")]}),z&&!w&&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:w,onChange:F=>{m(F.target.value),R(!0),P(!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:!z||se,onClick:()=>void S(),children:se?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:16,className:"animate-spin"}),s("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{size:16}),s("agents.saveFile","Save File")]})}),!z&&Z&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(fe,{size:14}),s("agents.fileSaved","File saved")]})]})]})]})}function js(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 Ut(t){return t?.autoClaimRelevantTasks!==!1}function Vt(t){return t?.engineerBacklogAutoClaim===!0}function ys(t){const r=t?.assignmentPolicy;return r==="explicit-only"||r==="none"?r:"auto"}function Wt(t){return t?.runMissedHeartbeatOnStartup===!0}function Jt(t){return t?.allowParallelExecution!==!1}function Gt(t){return t?.skipHeartbeatWhenIdle===!0}function qt(t){const r=t?.heartbeatScopeDiscipline;return r==="strict"||r==="lite"||r==="off"?r:""}function Ns(t){const r=t?.heartbeatPromptTemplate;return r==="default"||r==="compact"?r:""}function ks(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 Mn({agent:t,projectId:r,addToast:l,onSaved:o}){const{t:s}=ke("app"),[p,k]=a.useState(!1),[n,f]=a.useState(!1),[u,j]=a.useState(!1),[c,m]=a.useState(!1),[w,T]=a.useState(!1),[z,R]=a.useState(""),[B,O]=a.useState(!1),[se,N]=a.useState(null),[v,M]=a.useState(!1),Z=a.useRef(null),P=t.heartbeatProcedurePath?.trim(),E=`.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`,K=`.fusion/agents/${t.id}/HEARTBEAT.md`,$=t.id.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"agent",V=!!(P&&(P===E||P===K||new RegExp(`^\\.fusion/agents/[^/]+-${$}/HEARTBEAT\\.md$`).test(P))),S=!!P,X=a.useCallback(async y=>{j(!0),N(null);try{const d=await $s("project",y,r);R(d.content),O(!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(()=>{f(!1),T(!1),R(""),O(!1),N(null),j(!1),m(!1),M(!1)},[t.id,P]),a.useEffect(()=>()=>{Z.current&&clearTimeout(Z.current)},[]);const F=async()=>{P&&(f(!0),await X(P))},W=async()=>{if(P){m(!0);try{await _s("project",P,z,r),O(!1),M(!0),l(s("agents.heartbeatFileSaved","Heartbeat procedure file saved"),"success"),Z.current&&clearTimeout(Z.current),Z.current=setTimeout(()=>M(!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 Ga(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:P||s("agents.noneUsingBuiltIn","(none — using built-in default)")})]}),S&&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(G,{size:16,className:"animate-spin"}),s("agents.loadingFile","Loading file…")]}):e.jsxs(e.Fragment,{children:[e.jsx(dt,{size:16}),s("agents.viewHeartbeatMarkdown","View Heartbeat Markdown")]})})})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("button",{className:"btn",disabled:p||V,onClick:()=>void b(),"aria-label":s("agents.upgradeToDefaultAriaLabel","Upgrade agent to default heartbeat procedure file"),children:p?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:16,className:"animate-spin"}),s("agents.upgrading","Upgrading…")]}):V?e.jsxs(e.Fragment,{children:[e.jsx(fe,{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:E})," ",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&&S&&P&&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 ${w?"":"btn-primary"}`,onClick:()=>T(!1),disabled:!w,"aria-label":s("agents.heartbeatFileEditMode","Heartbeat file edit mode"),children:[e.jsx(Ft,{size:14}),s("common.edit","Edit")]}),e.jsxs("button",{className:`btn btn-sm ${w?"btn-primary":""}`,onClick:()=>T(!0),disabled:w,"aria-label":s("agents.heartbeatFilePreviewMode","Heartbeat file preview mode"),children:[e.jsx(Pt,{size:14}),s("common.preview","Preview")]})]}),u&&e.jsxs("span",{className:"config-hint heartbeat-procedure-status",children:[e.jsx(G,{size:12,className:"animate-spin"}),s("common.loading","Loading...")]}),B&&!u&&e.jsx("span",{className:"config-hint heartbeat-procedure-status heartbeat-procedure-status--warning",children:s("common.unsavedChanges","Unsaved changes")})]}),w?z.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(Tt,{remarkPlugins:[Et],children:z})}):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:z,readOnly:u,placeholder:s("agents.heartbeatFilePlaceholder","Heartbeat procedure markdown file content will appear here..."),onChange:y=>{R(y.target.value),O(!0),M(!1)}}),se&&e.jsx("span",{className:"config-error",children:s("agents.fileLoadError","Failed to load file: {{error}}",{error:se})}),e.jsxs("span",{className:"config-hint",children:[s("agents.heartbeatFileEditorHint","This editor writes directly to")," ",e.jsx("code",{children:P}),"."]})]}),!w&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!B||c||u,onClick:()=>void W(),children:c?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:16,className:"animate-spin"}),s("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{size:16}),s("agents.saveHeartbeatFile","Save Heartbeat File")]})}),!B&&v&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(fe,{size:14}),s("agents.fileSaved","File saved")]})]})]})]})}function An({agent:t,projectId:r,addToast:l,onSaved:o,onHasChangesChange:s,onDelete:p,onAgentDraftApplied:k}){const{t:n}=ke("app"),[f,u]=a.useState(t.name),[j,c]=a.useState(t.role),[m,w]=a.useState(t.title??""),[T,z]=a.useState(t.icon??""),[R,B]=a.useState(t.reportsTo??""),[O,se]=a.useState([]),[N,v]=a.useState(!1),[M,Z]=a.useState(!1),[P,E]=a.useState(!1),K=a.useRef(null),[$,V]=a.useState(()=>{const i={};for(const g of ot){const C=t.metadata[g.key];C!=null&&(i[g.key]=String(C))}return i.thinkingLevel=typeof t.runtimeConfig?.thinkingLevel=="string"?t.runtimeConfig.thinkingLevel:"off",i}),[S,X]=a.useState(()=>js(t.runtimeConfig)),[F,W]=a.useState(()=>_t(t.runtimeConfig)),[b,y]=a.useState(()=>Ut(t.runtimeConfig)),[d,D]=a.useState(()=>Vt(t.runtimeConfig)),[J,xe]=a.useState(()=>ys(t.runtimeConfig)),[Me,Le]=a.useState(()=>Wt(t.runtimeConfig)),[ce,H]=a.useState(()=>Jt(t.runtimeConfig)),[ae,Ae]=a.useState(()=>Gt(t.runtimeConfig)),[De,x]=a.useState(()=>qt(t.runtimeConfig)),[A,ie]=a.useState(()=>Ns(t.runtimeConfig)),[q,Je]=a.useState(()=>ks(t.runtimeConfig)),[ue,ze]=a.useState(t.bundleConfig?.mode??""),[me,Be]=a.useState(t.bundleConfig?.entryFile??"AGENTS.md"),[He,Oe]=a.useState(t.bundleConfig?.externalPath??""),[ne,ut]=a.useState(t.bundleConfig?.files??[]),[Fe,ye]=a.useState(Array.isArray(t.metadata?.skills)?t.metadata.skills:[]),{favoriteProviders:mt,favoriteModels:tt,toggleFavoriteProvider:Lt,toggleFavoriteModel:st}=Fa(),[$e,Pe]=a.useState([]),[gt,at]=a.useState(!1),[Ge,ht]=a.useState([]),[ft,Ye]=a.useState(!1),Se=(()=>{const i=t.runtimeConfig??{};return i.modelProvider&&i.modelId?`${i.modelProvider}/${i.modelId}`:typeof i.model=="string"&&i.model.includes("/")?i.model:""})(),Ie=typeof t.runtimeConfig?.runtimeHint=="string"?t.runtimeConfig.runtimeHint:"",[pe,_e]=a.useState(Ie?"runtime":"model"),[h,L]=a.useState(Se),[I,_]=a.useState(Ie),[le,be]=a.useState(t.permissionPolicy),[Ce,Re]=a.useState(t.permissions??{}),[Ne,nt]=a.useState(void 0),Ze=R.trim(),pt=a.useMemo(()=>O.filter(i=>i.id!==t.id),[O,t.id]),bt=!!Ze&&!pt.some(i=>i.id===Ze),he=a.useMemo(()=>({name:f,role:j,title:m||void 0,instructionsText:t.instructionsText,soul:t.soul,memory:t.memory,reportsTo:R||void 0,skills:Fe,model:h||void 0,runtimeHint:pe==="runtime"&&I||void 0,thinkingLevel:$.thinkingLevel??void 0,maxTurns:$.maxTurns?Number($.maxTurns):void 0,heartbeatIntervalMs:S.heartbeatIntervalMs?Number(S.heartbeatIntervalMs)*1e3:void 0,heartbeatTimeoutMs:S.heartbeatTimeoutMs?Number(S.heartbeatTimeoutMs)*1e3:void 0,maxConcurrentRuns:S.maxConcurrentRuns?Number(S.maxConcurrentRuns):void 0,messageResponseMode:S.messageResponseMode}),[t.instructionsText,t.memory,t.soul,$.maxTurns,$.thinkingLevel,S.heartbeatIntervalMs,S.heartbeatTimeoutMs,S.maxConcurrentRuns,S.messageResponseMode,h,f,R,j,pe,I,Fe,m]),Ke=a.useCallback(i=>{u(i.name),c(i.role),w(i.title??""),z(i.icon??""),B(i.reportsTo??""),i.skills&&ye(i.skills),i.thinkingLevel&&V(C=>({...C,thinkingLevel:i.thinkingLevel})),i.maxTurns!==void 0&&V(C=>({...C,maxTurns:String(i.maxTurns)})),i.runtimeHint!==void 0?(_e("runtime"),_(i.runtimeHint??""),i.runtimeHint&&L("")):i.model!==void 0&&(_e("model"),L(i.model??""),_(""));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(([,C])=>C!==void 0));k?.(g),E(!1),l(n("agents.interviewDraftApplied","Interview draft applied. Review and save when ready."),"success")},[l,k]);a.useEffect(()=>{be(t.permissionPolicy)},[t.permissionPolicy]),a.useEffect(()=>{Re(t.permissions??{})},[t.permissions]),a.useEffect(()=>{Pa(r).then(i=>nt(i.project?.defaultAgentPermissionPolicy)).catch(()=>nt(void 0))},[r]);const xt=async i=>{be(i);try{await Ot(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")}},Us=a.useMemo(()=>new Set(dn[j]??[]),[j]),Vs=a.useMemo(()=>new Set(ps.filter(i=>Ce[i]===!0)),[Ce]),Ws=async(i,g)=>{const C={...Ce};g?C[i]=!0:delete C[i],Re(C);try{await Ot(t.id,{permissions:C},r),await o(),l(n("agents.capabilityPermissionsUpdated","Capability grants updated"),"success")}catch(ee){Re(t.permissions??{}),l(n("agents.capabilityPermissionsFailed","Failed to update capability grants: {{error}}",{error:U(ee)}),"error")}};a.useEffect(()=>{let i=!1;return v(!0),wt(void 0,r).then(g=>{i||se(g)}).catch(()=>{i||se([])}).finally(()=>{i||v(!1)}),()=>{i=!0}},[r]),a.useEffect(()=>{at(!0),Ta().then(i=>{Pe(i.models)}).catch(()=>{}).finally(()=>at(!1))},[]),a.useEffect(()=>{Ye(!0),Hs(r).then(ht).catch(()=>ht([])).finally(()=>Ye(!1))},[r]);const[Ue,Dt]=a.useState(null),[es,ts]=a.useState(!1);a.useEffect(()=>{Yt(t.id,r).then(Dt).catch(()=>Dt(null))},[t.id,r]);const Js=async()=>{ts(!0);try{await Wa(t.id,r),l(n("agents.budgetResetSuccess","Budget usage reset successfully"),"success");const i=await Yt(t.id,r);Dt(i)}catch(i){l(n("agents.budgetResetFailed","Failed to reset budget: {{error}}",{error:U(i)}),"error")}finally{ts(!1)}},[Ve,ss]=a.useState(!1),[Y,qe]=a.useState({}),[Gs,Qe]=a.useState(!1),[zt,vt]=a.useState(null),as=t.state==="idle"||t.state==="paused",it=a.useRef(null),ns=a.useRef(null),is=a.useRef(null),jt=a.useRef(0);a.useEffect(()=>()=>{it.current&&clearTimeout(it.current)},[]);const we=(()=>{if(f!==t.name||j!==t.role||m!==(t.title??"")||T!==(t.icon??"")||R!==(t.reportsTo??"")||ue!==(t.bundleConfig?.mode??"")||me!==(t.bundleConfig?.entryFile??"AGENTS.md")||He!==(t.bundleConfig?.externalPath??"")||JSON.stringify(ne)!==JSON.stringify(t.bundleConfig?.files??[]))return!0;for(const te of ot){const ve=$[te.key]?.trim()??"",je=t.metadata[te.key]!==void 0&&t.metadata[te.key]!==null?String(t.metadata[te.key]):"";if(ve!==je)return!0}const i=t.runtimeConfig??{};if(F!==_t(t.runtimeConfig)||b!==Ut(t.runtimeConfig)||d!==Vt(t.runtimeConfig)||J!==ys(t.runtimeConfig)||Me!==Wt(t.runtimeConfig)||ce!==Jt(t.runtimeConfig)||ae!==Gt(t.runtimeConfig)||De!==qt(t.runtimeConfig)||A!==Ns(t.runtimeConfig))return!0;for(const te of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns","messageResponseMode","autoClaimCandidatesInPrompt"]){const ve=S[te]?.trim()??"";let je=i[te]!==void 0&&i[te]!==null?String(i[te]):"";if((te==="heartbeatIntervalMs"||te==="heartbeatTimeoutMs")&&je&&(je=String(Number(je)/1e3)),ve!==je)return!0}const g=i.budgetConfig;for(const te of["tokenBudget","budgetPeriod","resetDay"]){const ve=q[te]?.trim()??"",je=g?.[te]!==void 0&&g?.[te]!==null?String(g[te]):"";if(ve!==je)return!0}const C=q.usageThreshold?.trim()??"",ee=g?.usageThreshold!==void 0&&g?.usageThreshold!==null?String(Number(g.usageThreshold)*100):"";if(C!==ee)return!0;const ge=Array.isArray(t.metadata?.skills)?t.metadata.skills:[];return JSON.stringify(Fe)!==JSON.stringify(ge)||pe!==(Ie?"runtime":"model")||h!==Se||I!==Ie||($.thinkingLevel||"off")!==(typeof i.thinkingLevel=="string"?i.thinkingLevel:"off")})(),rs=a.useRef(null);a.useEffect(()=>{s&&rs.current!==we&&(rs.current=we,s(we))},[we,s]),a.useEffect(()=>()=>{s?.(!1)},[s]),a.useEffect(()=>{const i={id:t.id,updatedAt:t.updatedAt},g=ns.current;(!g||g.id!==i.id||g.updatedAt!==i.updatedAt)&&(we||(ns.current=i,X(js(t.runtimeConfig)),W(_t(t.runtimeConfig)),y(Ut(t.runtimeConfig)),D(Vt(t.runtimeConfig)),Le(Wt(t.runtimeConfig)),H(Jt(t.runtimeConfig)),Ae(Gt(t.runtimeConfig)),x(qt(t.runtimeConfig)),Je(ks(t.runtimeConfig)),V(ee=>({...ee,thinkingLevel:typeof t.runtimeConfig?.thinkingLevel=="string"?t.runtimeConfig.thinkingLevel:"off"})),L(Se),_(Ie),_e(Ie?"runtime":"model")))},[t,we,Se,Ie]);const ls=(i,g)=>{V(C=>({...C,[i]:g})),Qe(!1),Y[i]&&qe(C=>{const ee={...C};return delete ee[i],ee})},yt=(i,g)=>{X(C=>({...C,[i]:g})),Qe(!1),Y[i]&&qe(C=>{const ee={...C};return delete ee[i],ee})},qs=i=>{W(i),Qe(!1)},Nt=(i,g)=>{Je(C=>({...C,[i]:g})),Qe(!1),Y[i]&&qe(C=>{const ee={...C};return delete ee[i],ee})},Te=a.useMemo(()=>{const i=Sn($);for(const[Q,We]of Object.entries({heartbeatIntervalMs:{label:"Heartbeat Interval",min:1},heartbeatTimeoutMs:{label:"Heartbeat Timeout",min:5},maxConcurrentRuns:{label:"Max Concurrent Runs",min:1}})){const de=S[Q]?.trim();if(!de)continue;const Ee=Number(de);Number.isNaN(Ee)||!Number.isFinite(Ee)?i[Q]=`"${We.label}" must be a valid number`:Ee<We.min&&(i[Q]=`"${We.label}" must be at least ${We.min.toLocaleString()}`)}const g=S.autoClaimCandidatesInPrompt?.trim();if(g){const Q=Number(g);(!Number.isInteger(Q)||Q<0||Q>10)&&(i.autoClaimCandidatesInPrompt='"Auto-claim candidates in prompt" must be an integer between 0 and 10')}const C=S.messageResponseMode?.trim();C&&!["immediate","on-heartbeat"].includes(C)&&(i.messageResponseMode='"Message Response Mode" must be either immediate or on-heartbeat');const ee=q.tokenBudget?.trim();if(ee){const Q=Number(ee);Number.isNaN(Q)||!Number.isFinite(Q)?i.tokenBudget='"Token Budget" must be a valid number':Q<=0&&(i.tokenBudget='"Token Budget" must be greater than 0')}const ge=q.usageThreshold?.trim();if(ge){const Q=Number(ge);Number.isNaN(Q)||!Number.isFinite(Q)?i.usageThreshold='"Usage Threshold" must be a valid number':(Q<1||Q>100)&&(i.usageThreshold='"Usage Threshold" must be between 1 and 100')}const te=q.budgetPeriod?.trim();te&&!["daily","weekly","monthly","lifetime"].includes(te)&&(i.budgetPeriod='"Budget Period" must be one of: daily, weekly, monthly, lifetime');const ve=q.resetDay?.trim(),je=te||"lifetime";if(ve){const Q=Number(ve);Number.isNaN(Q)||!Number.isFinite(Q)?i.resetDay='"Reset Day" must be a valid number':je==="weekly"?(Q<0||Q>6||!Number.isInteger(Q))&&(i.resetDay='"Reset Day" must be between 0 (Sunday) and 6 (Saturday) for weekly period'):je==="monthly"&&(Q<1||Q>31||!Number.isInteger(Q))&&(i.resetDay='"Reset Day" must be between 1 and 31 for monthly period')}return i},[$,S,q]),os=a.useCallback(()=>{if(Object.keys(Te).length>0)return null;const i={...t.metadata};for(const de of ot){const Ee=$[de.key]?.trim();Ee?de.type==="number"?i[de.key]=Number(Ee):i[de.key]=Ee:delete i[de.key]}Fe.length>0?i.skills=Fe:delete i.skills;const g={...t.runtimeConfig};g.enabled=F,g.autoClaimRelevantTasks=b,g.engineerBacklogAutoClaim=d,J==="auto"?delete g.assignmentPolicy:g.assignmentPolicy=J,g.runMissedHeartbeatOnStartup=Me,g.allowParallelExecution=ce,g.skipHeartbeatWhenIdle=ae;for(const de of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns","autoClaimCandidatesInPrompt"]){const Ee=S[de]?.trim();if(!Ee)delete g[de];else{const ds=Number(Ee);g[de]=de==="maxConcurrentRuns"||de==="autoClaimCandidatesInPrompt"?ds:ds*1e3}}const C=S.messageResponseMode?.trim();C?g.messageResponseMode=C:delete g.messageResponseMode,De?g.heartbeatScopeDiscipline=De:delete g.heartbeatScopeDiscipline,A?g.heartbeatPromptTemplate=A:delete g.heartbeatPromptTemplate;const ee=$.thinkingLevel||"off";if(g.thinkingLevel=ee,pe==="runtime")I.trim()?g.runtimeHint=I.trim():delete g.runtimeHint,delete g.modelProvider,delete g.modelId,delete g.model;else if(delete g.runtimeHint,h.trim()){const de=h.indexOf("/");de!==-1&&(g.modelProvider=h.slice(0,de),g.modelId=h.slice(de+1),g.model=h.trim())}else delete g.modelProvider,delete g.modelId,delete g.model;const ge={},te=q.tokenBudget?.trim(),ve=q.usageThreshold?.trim(),je=q.budgetPeriod?.trim(),Q=q.resetDay?.trim();te&&(ge.tokenBudget=Number(te)),ve&&(ge.usageThreshold=Number(ve)/100),je&&(ge.budgetPeriod=je),Q&&(ge.resetDay=Number(Q)),Object.keys(ge).length>0?g.budgetConfig=ge:delete g.budgetConfig;let We;return ue&&(We={mode:ue,entryFile:me||"AGENTS.md",files:ne.length>0?ne:["AGENTS.md"]},ue==="external"&&He.trim()&&(We.externalPath=He.trim())),{name:f.trim()||void 0,role:j,title:m.trim()||void 0,icon:T.trim()||void 0,reportsTo:R.trim()||void 0,metadata:i,runtimeConfig:g,bundleConfig:We}},[t.metadata,t.runtimeConfig,ce,J,b,q,me,He,ne,ue,d,$,F,A,De,S,T,h,f,R,j,Me,pe,I,Fe,ae,m,Te]),rt=a.useCallback(async(i,g)=>{const C=os();if(!C)return qe(Te),i&&l(n("agents.fixValidationErrors","Please fix validation errors before saving"),"error"),g==="auto"&&vt(n("agents.fixValidationToSave","Fix validation errors to save changes")),!1;const ee=JSON.stringify(C);if(ee===is.current)return!1;const ge=++jt.current;qe({}),vt(null),ss(!0);try{return await Ot(t.id,C,r),ge!==jt.current?!1:(is.current=ee,g==="manual"&&l(n("agents.settingsSaved","Settings saved"),"success"),vt(null),Qe(!0),it.current&&clearTimeout(it.current),it.current=setTimeout(()=>Qe(!1),3e3),await o(),!0)}catch(te){if(ge===jt.current){const ve=U(te);vt(ve),l(n("agents.settingsSaveFailed","Failed to save settings: {{error}}",{error:ve}),"error")}return!1}finally{ge===jt.current&&ss(!1)}},[l,t.id,os,o,r,Te]),Ys=async()=>{await rt(!0,"manual")},re=a.useCallback(()=>{if(!(!we||Ve)){if(Object.keys(Te).length>0){qe(Te);return}rt(!1,"auto")}},[we,Ve,rt,Te]);a.useEffect(()=>{if(!we||Ve)return;if(Object.keys(Te).length>0){qe(Te);return}const i=setTimeout(()=>{rt(!1,"auto")},hn);return()=>clearTimeout(i)},[we,Ve,rt,Te]);const Zs=a.useCallback(async i=>{Z(!0);try{await Ea(t.id,i,r),await o(),l(n("agents.avatarUploaded","Avatar uploaded"),"success")}catch(g){l(U(g),"error")}finally{Z(!1),K.current&&(K.current.value="")}},[l,t.id,o,r]),Ks=a.useCallback(async()=>{Z(!0);try{await La(t.id,r),await o(),l(n("agents.avatarRemoved","Avatar removed"),"success")}catch(i){l(U(i),"error")}finally{Z(!1)}},[l,t.id,o,r]),cs=Ve?n("agents.savingChanges","Saving changes…"):zt?n("agents.saveFailed","Save failed: {{error}}",{error:zt}):!we&&Gs?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:()=>E(!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:f,onChange:i=>u(i.target.value),onBlur:()=>{re()}})]}),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),re()},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=>w(i.target.value),onBlur:()=>{re()}})]}),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(Ps,{agent:t,size:64,className:"agent-avatar-editor-preview"}),e.jsxs("div",{className:"agent-avatar-editor-actions",children:[e.jsx("input",{ref:K,id:"agent-avatar-upload",type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",className:"visually-hidden",disabled:M,onChange:i=>{const g=i.target.files?.[0];g&&Zs(g)}}),e.jsx("button",{type:"button",className:"btn btn-sm",disabled:M,onClick:()=>K.current?.click(),children:n("agents.uploadAvatar","Upload Avatar")}),t.imageUrl?e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void Ks(),disabled:M,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=>z(i.target.value),onBlur:()=>{re()}})]}),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:R,onChange:i=>{B(i.target.value),re()},disabled:N,children:[e.jsx("option",{value:"",children:n("agents.noManager","No manager")}),bt&&e.jsx("option",{value:Ze,children:n("agents.unknownManager","Unknown manager ({{id}})",{id:Ze})}),pt.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(Ya,{id:"agent-skills",label:"Skills",value:Fe,onChange:i=>{ye(i),re()},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${pe==="model"?" active":""}`,role:"tab","aria-selected":pe==="model",tabIndex:pe==="model"?0:-1,onClick:()=>{_e("model"),_(""),re()},children:n("agents.builtInModel","Built-in Model")}),e.jsx("button",{type:"button",className:`config-runtime-tab${pe==="runtime"?" active":""}`,role:"tab","aria-selected":pe==="runtime",tabIndex:pe==="runtime"?0:-1,onClick:()=>{_e("runtime"),re()},children:n("agents.pluginRuntime","Plugin Runtime")})]})]}),pe==="model"?e.jsx("div",{className:"config-field",children:e.jsx(Da,{models:$e,value:h,onChange:i=>{L(i),re()},placeholder:n("agents.useGlobalDefault","Use global default"),label:n("agents.agentModelLabel","Agent Model"),disabled:gt,favoriteProviders:mt,onToggleFavorite:Lt,favoriteModels:tt,onToggleModelFavorite:st,thinkingLevel:$.thinkingLevel??"",onThinkingLevelChange:i=>{V(g=>({...g,thinkingLevel:i})),re()}})}):e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-runtime-hint",children:n("agents.runtimeLabel","Runtime")}),ft?e.jsx("span",{className:"config-hint",children:e.jsx(za,{label:n("agents.loadingRuntimes","Loading runtimes…")})}):e.jsxs("select",{id:"agent-runtime-hint",className:"select",value:I,onChange:i=>{_(i.target.value),re()},children:[e.jsx("option",{value:"",children:Ge.length>0?n("agents.selectRuntime","Select a plugin runtime…"):n("agents.noRuntimes","No plugin runtimes available")}),Ge.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:ps.map(i=>{const g=Us.has(i),C=Vs.has(i),ee=`agent-capability-${t.id}-${i.replace(/[^a-z0-9]+/gi,"-")}`;return e.jsxs("label",{className:"agent-capability-grant-row",htmlFor:ee,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"):C?n("agents.explicitGrant","Explicit grant"):n("agents.notGranted","Not granted")})]}),e.jsx("input",{id:ee,type:"checkbox",checked:C,"aria-label":n("agents.toggleCapabilityGrant","Toggle explicit grant for {{permission}}",{permission:i}),onChange:ge=>{Ws(i,ge.target.checked)}})]},i)})})]}),le===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 xt({presetId:"custom",rules:{git_write:Ne?.rules?.git_write??"allow",file_write_delete:Ne?.rules?.file_write_delete??"allow",command_execution:Ne?.rules?.command_execution??"allow",network_api:Ne?.rules?.network_api??"allow",task_agent_mutation:Ne?.rules?.task_agent_mutation??"allow",review_gate_bypass:Ne?.rules?.review_gate_bypass??"require-approval",file_scope:Ne?.rules?.file_scope??"allow"}}),children:n("agents.customizeForAgent","Customize for this agent")})]}):null,e.jsx(Qa,{mode:"agent-override",value:le,projectDefault:Ne?.rules,projectDefaultToolRules:Ne?.toolRules,onChange:i=>{xt(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),X(i=>({...i,autoClaimCandidatesInPrompt:"0"})),re()},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),re()}}),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),re()}}),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.jsx("label",{htmlFor:"hb-assignmentPolicy",children:n("agents.assignmentPolicy","Assignment Policy")}),e.jsxs("select",{id:"hb-assignmentPolicy",value:J,onChange:i=>{xe(i.target.value),re()},children:[e.jsx("option",{value:"auto",children:n("agents.assignmentPolicyAuto","Auto (default) — eligible for automatic assignment")}),e.jsx("option",{value:"explicit-only",children:n("agents.assignmentPolicyExplicitOnly","Explicit only — never auto-assigned; accepts direct assignment/delegation")}),e.jsx("option",{value:"none",children:n("agents.assignmentPolicyNone","None — can never receive implementation tasks")})]}),e.jsx("span",{className:"config-hint",children:n("agents.assignmentPolicyHint",'Controls whether task routing may bind work to this agent. Use "None" for liaison/observer agents that must never execute product tasks — no override can bypass it.')})]}),e.jsxs("div",{className:"config-field",children:[e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-enabled",children:[e.jsx("input",{id:"hb-enabled",type:"checkbox",checked:F,onChange:i=>{qs(i.target.checked),re()}}),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:Me,onChange:i=>{Le(i.target.checked),re()}}),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:ce,onChange:i=>{H(i.target.checked),re()}}),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:ae,onChange:i=>{Ae(i.target.checked),re()}}),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:De,onChange:i=>{const g=i.target.value;x(g==="strict"||g==="lite"||g==="off"?g:""),re()},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:A,onChange:i=>{const g=i.target.value;ie(g==="default"||g==="compact"?g:""),re()},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(Zt/1e3),value:S.heartbeatIntervalMs??"",onChange:i=>yt("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:Zt/1e3,label:gn})})]}),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:S.heartbeatTimeoutMs??"",onChange:i=>yt("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:S.maxConcurrentRuns??"",onChange:i=>yt("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:S.messageResponseMode??"",onChange:i=>yt("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:q.tokenBudget??"",onChange:i=>Nt("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:q.usageThreshold??"",onChange:i=>Nt("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:q.budgetPeriod??"",onChange:i=>Nt("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:q.resetDay??"",onChange:i=>Nt("resetDay",i.target.value)}),Y.resetDay?e.jsx("span",{className:"config-error",children:Y.resetDay}):e.jsx("span",{className:"config-hint",children:q.budgetPeriod==="weekly"?n("agents.resetDayWeekly","Day of week (0=Sunday to 6=Saturday) for reset."):q.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.")})]}),Ue?.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",(Ue.usagePercent??0)>=100?"budget-progress-bar__fill--red":(Ue.usagePercent??0)>=80?"budget-progress-bar__fill--amber":"budget-progress-bar__fill--green"),style:{width:`${Math.min(Ue.usagePercent??0,100)}%`}})}),e.jsx("span",{className:"budget-progress-label",children:n("agents.budgetUsageDisplay","{{used}} / {{limit}} tokens ({{percent}}% used)",{used:(Ue.currentUsage??0).toLocaleString(),limit:(Ue.budgetLimit??0).toLocaleString(),percent:Math.round(Ue.usagePercent??0)})})]})]}),Ue?.budgetLimit!=null&&e.jsx("div",{className:"config-field",children:e.jsx("button",{className:"btn btn-reset-budget",onClick:()=>void Js(),disabled:es,children:es?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:14,className:"animate-spin"}),n("agents.resetting","Resetting…")]}):e.jsxs(e.Fragment,{children:[e.jsx(At,{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:ue,onChange:i=>ze(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:[ue==="managed"&&n("agents.bundleManagedHint","Files will be stored in a system-managed directory within .fusion/agents/"),ue==="external"&&n("agents.bundleExternalHint","Specify an external directory path for the instruction files"),!ue&&n("agents.bundleSelectMode","Select a mode to enable instruction bundling")]})]}),ue&&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:me,onChange:i=>Be(i.target.value)}),e.jsx("span",{className:"config-hint",children:n("agents.bundleEntryFileHint","Primary instructions file name (default: AGENTS.md)")})]}),ue==="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:He,onChange:i=>Oe(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=>ut(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:ot.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:C=>ls(i.key,C.target.value),children:[e.jsx("option",{value:"",children:n("agents.systemDefault","System Default")}),i.options?.map(C=>e.jsx("option",{value:C.value,children:C.label},C.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:C=>ls(i.key,C.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||Ve,onClick:()=>void Ys(),children:Ve?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:16,className:"animate-spin"}),n("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{size:16}),n("agents.saveSettings","Save Settings")]})}),cs&&e.jsxs("span",{className:oe("config-saved-indicator",zt&&"config-saved-indicator--error"),children:[Ve?e.jsx(G,{size:14,className:"animate-spin"}):e.jsx(fe,{size:14}),cs]})]})]}),e.jsx(Mn,{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:!as||!p,onClick:()=>void p?.(),children:[e.jsx(ct,{size:16}),n("agents.deleteAgent","Delete Agent")]}),e.jsx("span",{className:"config-danger-note",children:as?n("agents.deletionPermanent","Deletion is permanent and cannot be undone."):n("agents.deletionNotAvailable","Agent deletion is only available when state is idle or paused (current state: {{state}}).",{state:t.state})})]})})]}),e.jsx(Za,{isOpen:P,onClose:()=>E(!1),onUseDraft:Ke,projectId:r,existingAgents:O,mode:"edit",existingAgentConfig:he})]})}function Fn({agentId:t,projectId:r,onChildClick:l}){const{t:o}=ke("app"),[s,p]=a.useState([]),[k,n]=a.useState(!0);return a.useEffect(()=>{n(!0),wa(t,r).then(p).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(G,{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(Ls,{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(f=>{const u=Xt[f.state];return e.jsxs("div",{className:"agent-tree__node agent-is-child",onClick:()=>l?.(f.id),role:"button",tabIndex:0,onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&(j.key===" "&&j.preventDefault(),l?.(f.id))},style:{cursor:l?"pointer":"default"},children:[e.jsx("span",{className:"agent-tree__icon",children:f.icon??"🤖"}),e.jsx("span",{className:"agent-tree__name",children:f.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:f.state})]},f.id)})})})]})}export{On as AgentDetailView,et as relativeTime};
|
|
18
|
+
... (truncated, ${v.stdoutExcerpt.length} chars total)`:v.stdoutExcerpt})]}),v.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(Oa,{errorText:v.stderrExcerpt,summaryPrefix:"Run error",issueContext:{surface:"AgentDetailView runs",agentId:r,agentName:s,agentState:o,runId:v.id,taskId:void 0,timestamp:v.startedAt}})]}),v.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(v.resultJson,null,2)})]}),v.contextSnapshot&&Object.keys(v.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(v.contextSnapshot).map(([me,Be])=>e.jsxs("span",{className:"run-context-item",children:[e.jsxs("span",{className:"text-muted",children:[me,":"]})," ",e.jsx("span",{children:String(Be)})]},me))})]}),!v.stdoutExcerpt&&!v.stderrExcerpt&&!v.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")}),se?e.jsxs("div",{className:"run-details-loading-state",children:[e.jsx(G,{size:14,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:u("agents.loadingLogs","Loading logs...")})]}):B.length===0?e.jsx("div",{className:"text-muted run-output-empty",children:u("agents.noLogsForRun","No logs available for this run")}):e.jsx(Os,{entries:B,loading:!1})]})]})]},x.id)},ce=(x,A)=>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:(A.hitRatio*100).toFixed(1),cached:A.totalCachedTokens.toLocaleString(),written:A.totalCacheWriteTokens.toLocaleString(),input:A.totalInputTokens.toLocaleString(),tasks:A.nTasks.toLocaleString()})})]},x),H=$[0],ae=[...$].reverse(),Ae=Math.max(1,...ae.map(x=>x.execChars)),De=ae.map((x,A)=>{const ie=ae.length<=1?0:A/(ae.length-1)*100,q=100-Math.round(x.execChars/Ae*100);return`${ie},${q}`}).join(" ");return e.jsxs("div",{className:"runs-tab",children:[$.length>0&&H&&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:[H.systemChars.toLocaleString()," / ",H.execChars.toLocaleString()," / ",H.totalChars.toLocaleString()]})]})]}),E&&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:[ce(u("agents.last24h","Last 24h"),E.last24h),ce(u("agents.last7d","Last 7d"),E.last7d),ce(u("agents.allTime","All time"),E.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"}),W&&e.jsxs("span",{className:"run-live-indicator run-live-indicator--with-margin",children:[e.jsx("span",{className:"live-dot"}),u("agents.live","Live")]})]}),e.jsx("div",{className:"run-header-group",children:W&&e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void d(),"aria-label":u("agents.stopActiveRunFor","Stop active run for {{name}}",{name:s??r}),children:[e.jsx(Xe,{size:14})," ",u("agents.stopRun","Stop Run")]})})]}),J.map((x,A)=>Le(x,A,!0)),xe.map((x,A)=>Le(x,J.length+A,!1))]})}function yn(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 Nn(t){const r=t.title?.trim()||t.description?.trim()||t.id;return r.length>80?`${r.slice(0,77)}...`:r}function kn({agentId:t,projectId:r,addToast:l}){const{t:o}=ke("app"),[s,p]=a.useState([]),[k,n]=a.useState(!0);return a.useEffect(()=>{let f=!1;return n(!0),Ca(t,r).then(u=>{f||p(u)}).catch(u=>{f||(p([]),l(o("agents.loadTasksFailed","Failed to load assigned tasks: {{error}}",{error:U(u)}),"error"))}).finally(()=>{f||n(!1)}),()=>{f=!0}},[t,r,l]),k?e.jsxs("div",{className:"agent-tasks-empty",children:[e.jsx(G,{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(Es,{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(f=>e.jsxs("a",{className:"agent-task-item",href:`/tasks/${f.id}`,children:[e.jsxs("div",{className:"agent-task-row",children:[e.jsx("span",{className:"agent-task-id",children:f.id}),e.jsx("span",{className:`agent-task-column column-${f.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")}[f.column]??f.column})]}),e.jsx("div",{className:"agent-task-title",title:f.title||f.description||f.id,children:Nn(f)}),e.jsxs("div",{className:"agent-task-status",children:[f.status??"idle"," · ",o("agents.taskUpdated","Updated {{time}}",{time:et(f.updatedAt,o)})]})]},f.id))})}const ot=[{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 Sn(t){const r={};for(const l of ot){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(p=>p.value)??[];s.length>0&&!s.includes(o)&&(r[l.key]=`"${l.label}" must be one of: ${s.join(", ")}`)}}}return r}function Cn({agent:t,projectId:r,addToast:l,onSaved:o}){const{t:s}=ke("app"),[p,k]=a.useState(t.soul??""),[n,f]=a.useState(!1),[u,j]=a.useState(!1),[c,m]=a.useState(!1),w=a.useRef(null);a.useEffect(()=>{k(t.soul??""),j(!1),m(!1)},[t.id,t.soul]),a.useEffect(()=>()=>{w.current&&clearTimeout(w.current)},[]);const T=p!==(t.soul??""),z=async()=>{if(p.length>1e4){l(s("agents.soulTooLong","Soul must be at most 10,000 characters"),"error");return}f(!0);try{await $a(t.id,p,r),l(s("agents.soulSaved","Soul saved"),"success"),j(!0),w.current&&clearTimeout(w.current),w.current=setTimeout(()=>j(!1),3e3),await o()}catch(R){l(s("agents.soulSaveFailed","Failed to save soul: {{error}}",{error:U(R)}),"error")}finally{f(!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(Ft,{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(Pt,{size:14}),s("common.preview","Preview")]})]})}),c?p.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(Tt,{remarkPlugins:[Et],children:p})}):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:p,onChange:R=>{k(R.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 z(),children:n?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:16,className:"animate-spin"}),s("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{size:16}),s("agents.saveSoul","Save Soul")]})}),!T&&u&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(fe,{size:14}),s("agents.soulSaved","Soul saved")]})]})]})})}function wn({agent:t,projectId:r,addToast:l,onSaved:o}){const{t:s}=ke("app"),[p,k]=a.useState(t.memory??""),[n,f]=a.useState(!1),[u,j]=a.useState(!1),[c,m]=a.useState(!1),[w,T]=a.useState([]),[z,R]=a.useState(!1),[B,O]=a.useState(""),[se,N]=a.useState(""),[v,M]=a.useState(!1),[K,P]=a.useState(!1),[E,Z]=a.useState(!1),[$,V]=a.useState(!1),[S,X]=a.useState(""),F=a.useRef(null),W=a.useRef(null),b=t.state==="running",y=p!==(t.memory??""),d=a.useMemo(()=>w.find(H=>H.path===B),[w,B]),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."),J=a.useCallback(async H=>{P(!0);try{const ae=await Ra(t.id,H,r);O(ae.path),N(ae.content),M(!1),V(!1)}catch(ae){l(s("agents.memoryFileLoadFailed","Failed to load agent memory file: {{error}}",{error:U(ae)}),"error")}finally{P(!1)}},[t.id,r,l]),xe=a.useCallback(async(H="")=>{R(!0);try{const{files:ae}=await Ma(t.id,r);if(T(ae),ae.length===0){O(""),N(""),M(!1);return}const Ae=fn(ae,H);await J(Ae)}catch(ae){l(s("agents.memoryFilesLoadFailed","Failed to load memory files: {{error}}",{error:U(ae)}),"error"),T([]),O(""),N(""),M(!1)}finally{R(!1)}},[t.id,r,l,J]);a.useEffect(()=>{k(t.memory??""),j(!1),m(!1),X(""),V(!1),xe()},[t.id,t.memory,xe]),a.useEffect(()=>()=>{F.current&&clearTimeout(F.current),W.current&&clearTimeout(W.current)},[]);const Me=async()=>{if(p.length>5e4){l(s("agents.memoryTooLong","Memory must be at most 50,000 characters"),"error");return}f(!0);try{await Ua(t.id,p,r),l(s("agents.memorySaved","Memory saved"),"success"),j(!0),F.current&&clearTimeout(F.current),F.current=setTimeout(()=>j(!1),3e3),await o()}catch(H){l(s("agents.memorySaveFailed","Failed to save memory: {{error}}",{error:U(H)}),"error")}finally{f(!1)}},Le=async H=>{if(!(!H||H===B)){if(v){X(s("agents.saveBeforeSwitch","Save the current file before switching to another file."));return}X(""),await J(H)}},ce=async()=>{if(B){Z(!0);try{await Va(t.id,B,se,r),M(!1),V(!0),W.current&&clearTimeout(W.current),W.current=setTimeout(()=>V(!1),3e3),X(""),await xe(B),l(s("agents.memoryFileSaved","Agent memory file saved"),"success"),await o()}catch(H){l(s("agents.memoryFileSaveFailed","Failed to save agent memory file: {{error}}",{error:U(H)}),"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(Ft,{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(Pt,{size:14}),s("common.preview","Preview")]})]})}),c?p.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(Tt,{remarkPlugins:[Et],children:p})}):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:p,readOnly:b,onChange:H=>{k(H.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 Me(),children:n?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:16,className:"animate-spin"}),s("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{size:16}),s("agents.saveMemory","Save Memory")]})}),!y&&u&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(fe,{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:B,disabled:z||K||E||w.length===0,onChange:H=>{Le(H.target.value)},children:w.length===0?e.jsx("option",{value:"",children:s("agents.noMemoryFiles","No memory files found")}):w.map(H=>{const ae={"long-term":s("agents.memoryLayerLongTerm","Long-term"),daily:s("agents.memoryLayerDaily","Daily"),dreams:s("agents.memoryLayerDreams","Dreams")}[H.layer]??H.layer;return e.jsxs("option",{value:H.path,children:[ae," • ",H.label]},H.path)})}),z&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(G,{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:et(d.updatedAt,s)})]}),e.jsx("div",{className:"agent-memory-file-editor config-textarea-top-spacing",children:e.jsx(Aa,{content:se,onChange:H=>{N(H),M(!0),V(!1),X("")},readOnly:b||!B||K,filePath:B||"MEMORY.md",forceToolbarActionsVisible:!0})}),K&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(G,{size:14,className:"animate-spin"}),s("agents.loadingFileContent","Loading file content…")]}),S&&e.jsx("span",{className:"config-hint config-hint--top-spacing config-hint--block",children:S}),e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!v||E||!B||b,onClick:()=>void ce(),children:E?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:16,className:"animate-spin"}),s("agents.savingFile","Saving file…")]}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{size:16}),s("agents.saveMemoryFile","Save Memory File")]})}),!v&&$&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(fe,{size:14}),s("agents.memoryFileSaved","Memory file saved")]})]})]})]})]})})}function Rn({agent:t,projectId:r,addToast:l,onSaved:o}){const{t:s}=ke("app"),[p,k]=a.useState(t.instructionsText??""),[n,f]=a.useState(t.instructionsPath??""),[u,j]=a.useState(!1),[c,m]=a.useState(""),[w,T]=a.useState(!1),[z,R]=a.useState(!1),[B,O]=a.useState(!1),[se,N]=a.useState(!1),[v,M]=a.useState(!1),[K,P]=a.useState(!1),E=a.useRef(null),Z=a.useRef(null);a.useEffect(()=>{const F=n.trim();if(!F){m(""),R(!1);return}T(!0),$s("project",F).then(W=>{m(W.content),R(!1)}).catch(W=>{const b=U(W);b.includes("ENOENT")||b.includes("Not found")||b.includes("not found")?(m(""),R(!1)):(l(`Failed to load instructions file: ${b}`,"error"),m(""))}).finally(()=>{T(!1)})},[n,l]),a.useEffect(()=>{k(t.instructionsText??""),f(t.instructionsPath??""),M(!1),P(!1),j(!1)},[t.id,t.instructionsText,t.instructionsPath]),a.useEffect(()=>()=>{E.current&&clearTimeout(E.current),Z.current&&clearTimeout(Z.current)},[]);const $=(()=>{const F=p??"",W=t.instructionsText??"",b=n?.trim()??"",y=t.instructionsPath?.trim()??"";return F!==W||b!==y})(),V=async()=>{O(!0);try{await _a(t.id,{instructionsText:p||void 0,instructionsPath:n.trim()||void 0},r),l(s("agents.instructionsSaved","Instructions saved"),"success"),M(!0),E.current&&clearTimeout(E.current),E.current=setTimeout(()=>M(!1),3e3),await o()}catch(F){l(s("agents.instructionsSaveFailed","Failed to save instructions: {{error}}",{error:U(F)}),"error")}finally{O(!1)}},S=async()=>{const F=n.trim();if(!F){l(s("agents.noInstructionsPath","No instructions file path set"),"error");return}N(!0);try{await _s("project",F,c),l(s("agents.instructionsFileSaved","Instructions file saved"),"success"),R(!1),P(!0),Z.current&&clearTimeout(Z.current),Z.current=setTimeout(()=>P(!1),3e3),await o()}catch(W){l(s("agents.instructionsFileSaveFailed","Failed to save instructions file: {{error}}",{error:U(W)}),"error")}finally{N(!1)}},X=!!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:[!p.trim()&&!u&&e.jsx("button",{type:"button",className:"btn btn-sm","data-testid":"instructions-insert-template",onClick:()=>{k(qa),M(!1)},children:s("agents.insertInstructionsTemplate","Insert template")}),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(Ft,{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(Pt,{size:14}),s("common.preview","Preview")]})]})}),u?p.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(Tt,{remarkPlugins:[Et],children:p})}):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:p,onChange:F=>{k(F.target.value),M(!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=>{f(F.target.value),M(!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:!$||B,onClick:()=>void V(),children:B?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:16,className:"animate-spin"}),s("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{size:16}),s("agents.saveInstructions","Save Instructions")]})}),!$&&v&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(fe,{size:14}),s("agents.instructionsSaved","Instructions saved")]})]})]}),X&&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")}),w&&e.jsxs("span",{className:"config-hint config-hint--inline-tight",children:[e.jsx(G,{size:12,className:"animate-spin"}),s("common.loading","Loading...")]}),z&&!w&&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:w,onChange:F=>{m(F.target.value),R(!0),P(!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:!z||se,onClick:()=>void S(),children:se?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:16,className:"animate-spin"}),s("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{size:16}),s("agents.saveFile","Save File")]})}),!z&&K&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(fe,{size:14}),s("agents.fileSaved","File saved")]})]})]})]})}function js(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 Ut(t){return t?.autoClaimRelevantTasks!==!1}function Vt(t){return t?.engineerBacklogAutoClaim===!0}function ys(t){const r=t?.assignmentPolicy;return r==="explicit-only"||r==="none"?r:"auto"}function Wt(t){return t?.runMissedHeartbeatOnStartup===!0}function Jt(t){return t?.allowParallelExecution!==!1}function Gt(t){return t?.skipHeartbeatWhenIdle===!0}function qt(t){const r=t?.heartbeatScopeDiscipline;return r==="strict"||r==="lite"||r==="off"?r:""}function Ns(t){const r=t?.heartbeatPromptTemplate;return r==="default"||r==="compact"?r:""}function ks(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 Mn({agent:t,projectId:r,addToast:l,onSaved:o}){const{t:s}=ke("app"),[p,k]=a.useState(!1),[n,f]=a.useState(!1),[u,j]=a.useState(!1),[c,m]=a.useState(!1),[w,T]=a.useState(!1),[z,R]=a.useState(""),[B,O]=a.useState(!1),[se,N]=a.useState(null),[v,M]=a.useState(!1),K=a.useRef(null),P=t.heartbeatProcedurePath?.trim(),E=`.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",V=!!(P&&(P===E||P===Z||new RegExp(`^\\.fusion/agents/[^/]+-${$}/HEARTBEAT\\.md$`).test(P))),S=!!P,X=a.useCallback(async y=>{j(!0),N(null);try{const d=await $s("project",y,r);R(d.content),O(!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(()=>{f(!1),T(!1),R(""),O(!1),N(null),j(!1),m(!1),M(!1)},[t.id,P]),a.useEffect(()=>()=>{K.current&&clearTimeout(K.current)},[]);const F=async()=>{P&&(f(!0),await X(P))},W=async()=>{if(P){m(!0);try{await _s("project",P,z,r),O(!1),M(!0),l(s("agents.heartbeatFileSaved","Heartbeat procedure file saved"),"success"),K.current&&clearTimeout(K.current),K.current=setTimeout(()=>M(!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 Ga(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:P||s("agents.noneUsingBuiltIn","(none — using built-in default)")})]}),S&&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(G,{size:16,className:"animate-spin"}),s("agents.loadingFile","Loading file…")]}):e.jsxs(e.Fragment,{children:[e.jsx(dt,{size:16}),s("agents.viewHeartbeatMarkdown","View Heartbeat Markdown")]})})})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("button",{className:"btn",disabled:p||V,onClick:()=>void b(),"aria-label":s("agents.upgradeToDefaultAriaLabel","Upgrade agent to default heartbeat procedure file"),children:p?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:16,className:"animate-spin"}),s("agents.upgrading","Upgrading…")]}):V?e.jsxs(e.Fragment,{children:[e.jsx(fe,{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:E})," ",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&&S&&P&&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 ${w?"":"btn-primary"}`,onClick:()=>T(!1),disabled:!w,"aria-label":s("agents.heartbeatFileEditMode","Heartbeat file edit mode"),children:[e.jsx(Ft,{size:14}),s("common.edit","Edit")]}),e.jsxs("button",{className:`btn btn-sm ${w?"btn-primary":""}`,onClick:()=>T(!0),disabled:w,"aria-label":s("agents.heartbeatFilePreviewMode","Heartbeat file preview mode"),children:[e.jsx(Pt,{size:14}),s("common.preview","Preview")]})]}),u&&e.jsxs("span",{className:"config-hint heartbeat-procedure-status",children:[e.jsx(G,{size:12,className:"animate-spin"}),s("common.loading","Loading...")]}),B&&!u&&e.jsx("span",{className:"config-hint heartbeat-procedure-status heartbeat-procedure-status--warning",children:s("common.unsavedChanges","Unsaved changes")})]}),w?z.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(Tt,{remarkPlugins:[Et],children:z})}):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:z,readOnly:u,placeholder:s("agents.heartbeatFilePlaceholder","Heartbeat procedure markdown file content will appear here..."),onChange:y=>{R(y.target.value),O(!0),M(!1)}}),se&&e.jsx("span",{className:"config-error",children:s("agents.fileLoadError","Failed to load file: {{error}}",{error:se})}),e.jsxs("span",{className:"config-hint",children:[s("agents.heartbeatFileEditorHint","This editor writes directly to")," ",e.jsx("code",{children:P}),"."]})]}),!w&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!B||c||u,onClick:()=>void W(),children:c?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:16,className:"animate-spin"}),s("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{size:16}),s("agents.saveHeartbeatFile","Save Heartbeat File")]})}),!B&&v&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(fe,{size:14}),s("agents.fileSaved","File saved")]})]})]})]})}function An({agent:t,projectId:r,addToast:l,onSaved:o,onHasChangesChange:s,onDelete:p,onAgentDraftApplied:k}){const{t:n}=ke("app"),[f,u]=a.useState(t.name),[j,c]=a.useState(t.role),[m,w]=a.useState(t.title??""),[T,z]=a.useState(t.icon??""),[R,B]=a.useState(t.reportsTo??""),[O,se]=a.useState([]),[N,v]=a.useState(!1),[M,K]=a.useState(!1),[P,E]=a.useState(!1),Z=a.useRef(null),[$,V]=a.useState(()=>{const i={};for(const g of ot){const C=t.metadata[g.key];C!=null&&(i[g.key]=String(C))}return i.thinkingLevel=typeof t.runtimeConfig?.thinkingLevel=="string"?t.runtimeConfig.thinkingLevel:"off",i}),[S,X]=a.useState(()=>js(t.runtimeConfig)),[F,W]=a.useState(()=>_t(t.runtimeConfig)),[b,y]=a.useState(()=>Ut(t.runtimeConfig)),[d,D]=a.useState(()=>Vt(t.runtimeConfig)),[J,xe]=a.useState(()=>ys(t.runtimeConfig)),[Me,Le]=a.useState(()=>Wt(t.runtimeConfig)),[ce,H]=a.useState(()=>Jt(t.runtimeConfig)),[ae,Ae]=a.useState(()=>Gt(t.runtimeConfig)),[De,x]=a.useState(()=>qt(t.runtimeConfig)),[A,ie]=a.useState(()=>Ns(t.runtimeConfig)),[q,Je]=a.useState(()=>ks(t.runtimeConfig)),[ue,ze]=a.useState(t.bundleConfig?.mode??""),[me,Be]=a.useState(t.bundleConfig?.entryFile??"AGENTS.md"),[He,Oe]=a.useState(t.bundleConfig?.externalPath??""),[ne,ut]=a.useState(t.bundleConfig?.files??[]),[Fe,ye]=a.useState(Array.isArray(t.metadata?.skills)?t.metadata.skills:[]),{favoriteProviders:mt,favoriteModels:tt,toggleFavoriteProvider:Lt,toggleFavoriteModel:st}=Fa(),[$e,Pe]=a.useState([]),[gt,at]=a.useState(!1),[Ge,ht]=a.useState([]),[ft,Ye]=a.useState(!1),Se=(()=>{const i=t.runtimeConfig??{};return i.modelProvider&&i.modelId?`${i.modelProvider}/${i.modelId}`:typeof i.model=="string"&&i.model.includes("/")?i.model:""})(),Ie=typeof t.runtimeConfig?.runtimeHint=="string"?t.runtimeConfig.runtimeHint:"",[pe,_e]=a.useState(Ie?"runtime":"model"),[h,L]=a.useState(Se),[I,_]=a.useState(Ie),[le,be]=a.useState(t.permissionPolicy),[Ce,Re]=a.useState(t.permissions??{}),[Ne,nt]=a.useState(void 0),Ke=R.trim(),pt=a.useMemo(()=>O.filter(i=>i.id!==t.id),[O,t.id]),bt=!!Ke&&!pt.some(i=>i.id===Ke),he=a.useMemo(()=>({name:f,role:j,title:m||void 0,instructionsText:t.instructionsText,soul:t.soul,memory:t.memory,reportsTo:R||void 0,skills:Fe,model:h||void 0,runtimeHint:pe==="runtime"&&I||void 0,thinkingLevel:$.thinkingLevel??void 0,maxTurns:$.maxTurns?Number($.maxTurns):void 0,heartbeatIntervalMs:S.heartbeatIntervalMs?Number(S.heartbeatIntervalMs)*1e3:void 0,heartbeatTimeoutMs:S.heartbeatTimeoutMs?Number(S.heartbeatTimeoutMs)*1e3:void 0,maxConcurrentRuns:S.maxConcurrentRuns?Number(S.maxConcurrentRuns):void 0,messageResponseMode:S.messageResponseMode}),[t.instructionsText,t.memory,t.soul,$.maxTurns,$.thinkingLevel,S.heartbeatIntervalMs,S.heartbeatTimeoutMs,S.maxConcurrentRuns,S.messageResponseMode,h,f,R,j,pe,I,Fe,m]),Ze=a.useCallback(i=>{u(i.name),c(i.role),w(i.title??""),z(i.icon??""),B(i.reportsTo??""),i.skills&&ye(i.skills),i.thinkingLevel&&V(C=>({...C,thinkingLevel:i.thinkingLevel})),i.maxTurns!==void 0&&V(C=>({...C,maxTurns:String(i.maxTurns)})),i.runtimeHint!==void 0?(_e("runtime"),_(i.runtimeHint??""),i.runtimeHint&&L("")):i.model!==void 0&&(_e("model"),L(i.model??""),_(""));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(([,C])=>C!==void 0));k?.(g),E(!1),l(n("agents.interviewDraftApplied","Interview draft applied. Review and save when ready."),"success")},[l,k]);a.useEffect(()=>{be(t.permissionPolicy)},[t.permissionPolicy]),a.useEffect(()=>{Re(t.permissions??{})},[t.permissions]),a.useEffect(()=>{Pa(r).then(i=>nt(i.project?.defaultAgentPermissionPolicy)).catch(()=>nt(void 0))},[r]);const xt=async i=>{be(i);try{await Ot(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")}},Us=a.useMemo(()=>new Set(dn[j]??[]),[j]),Vs=a.useMemo(()=>new Set(ps.filter(i=>Ce[i]===!0)),[Ce]),Ws=async(i,g)=>{const C={...Ce};g?C[i]=!0:delete C[i],Re(C);try{await Ot(t.id,{permissions:C},r),await o(),l(n("agents.capabilityPermissionsUpdated","Capability grants updated"),"success")}catch(ee){Re(t.permissions??{}),l(n("agents.capabilityPermissionsFailed","Failed to update capability grants: {{error}}",{error:U(ee)}),"error")}};a.useEffect(()=>{let i=!1;return v(!0),wt(void 0,r).then(g=>{i||se(g)}).catch(()=>{i||se([])}).finally(()=>{i||v(!1)}),()=>{i=!0}},[r]),a.useEffect(()=>{at(!0),Ta().then(i=>{Pe(i.models)}).catch(()=>{}).finally(()=>at(!1))},[]),a.useEffect(()=>{Ye(!0),Hs(r).then(ht).catch(()=>ht([])).finally(()=>Ye(!1))},[r]);const[Ue,Dt]=a.useState(null),[es,ts]=a.useState(!1);a.useEffect(()=>{Yt(t.id,r).then(Dt).catch(()=>Dt(null))},[t.id,r]);const Js=async()=>{ts(!0);try{await Wa(t.id,r),l(n("agents.budgetResetSuccess","Budget usage reset successfully"),"success");const i=await Yt(t.id,r);Dt(i)}catch(i){l(n("agents.budgetResetFailed","Failed to reset budget: {{error}}",{error:U(i)}),"error")}finally{ts(!1)}},[Ve,ss]=a.useState(!1),[Y,qe]=a.useState({}),[Gs,Qe]=a.useState(!1),[zt,vt]=a.useState(null),as=t.state==="idle"||t.state==="paused",it=a.useRef(null),ns=a.useRef(null),is=a.useRef(null),jt=a.useRef(0);a.useEffect(()=>()=>{it.current&&clearTimeout(it.current)},[]);const we=(()=>{if(f!==t.name||j!==t.role||m!==(t.title??"")||T!==(t.icon??"")||R!==(t.reportsTo??"")||ue!==(t.bundleConfig?.mode??"")||me!==(t.bundleConfig?.entryFile??"AGENTS.md")||He!==(t.bundleConfig?.externalPath??"")||JSON.stringify(ne)!==JSON.stringify(t.bundleConfig?.files??[]))return!0;for(const te of ot){const ve=$[te.key]?.trim()??"",je=t.metadata[te.key]!==void 0&&t.metadata[te.key]!==null?String(t.metadata[te.key]):"";if(ve!==je)return!0}const i=t.runtimeConfig??{};if(F!==_t(t.runtimeConfig)||b!==Ut(t.runtimeConfig)||d!==Vt(t.runtimeConfig)||J!==ys(t.runtimeConfig)||Me!==Wt(t.runtimeConfig)||ce!==Jt(t.runtimeConfig)||ae!==Gt(t.runtimeConfig)||De!==qt(t.runtimeConfig)||A!==Ns(t.runtimeConfig))return!0;for(const te of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns","messageResponseMode","autoClaimCandidatesInPrompt"]){const ve=S[te]?.trim()??"";let je=i[te]!==void 0&&i[te]!==null?String(i[te]):"";if((te==="heartbeatIntervalMs"||te==="heartbeatTimeoutMs")&&je&&(je=String(Number(je)/1e3)),ve!==je)return!0}const g=i.budgetConfig;for(const te of["tokenBudget","budgetPeriod","resetDay"]){const ve=q[te]?.trim()??"",je=g?.[te]!==void 0&&g?.[te]!==null?String(g[te]):"";if(ve!==je)return!0}const C=q.usageThreshold?.trim()??"",ee=g?.usageThreshold!==void 0&&g?.usageThreshold!==null?String(Number(g.usageThreshold)*100):"";if(C!==ee)return!0;const ge=Array.isArray(t.metadata?.skills)?t.metadata.skills:[];return JSON.stringify(Fe)!==JSON.stringify(ge)||pe!==(Ie?"runtime":"model")||h!==Se||I!==Ie||($.thinkingLevel||"off")!==(typeof i.thinkingLevel=="string"?i.thinkingLevel:"off")})(),rs=a.useRef(null);a.useEffect(()=>{s&&rs.current!==we&&(rs.current=we,s(we))},[we,s]),a.useEffect(()=>()=>{s?.(!1)},[s]),a.useEffect(()=>{const i={id:t.id,updatedAt:t.updatedAt},g=ns.current;(!g||g.id!==i.id||g.updatedAt!==i.updatedAt)&&(we||(ns.current=i,X(js(t.runtimeConfig)),W(_t(t.runtimeConfig)),y(Ut(t.runtimeConfig)),D(Vt(t.runtimeConfig)),Le(Wt(t.runtimeConfig)),H(Jt(t.runtimeConfig)),Ae(Gt(t.runtimeConfig)),x(qt(t.runtimeConfig)),Je(ks(t.runtimeConfig)),V(ee=>({...ee,thinkingLevel:typeof t.runtimeConfig?.thinkingLevel=="string"?t.runtimeConfig.thinkingLevel:"off"})),L(Se),_(Ie),_e(Ie?"runtime":"model")))},[t,we,Se,Ie]);const ls=(i,g)=>{V(C=>({...C,[i]:g})),Qe(!1),Y[i]&&qe(C=>{const ee={...C};return delete ee[i],ee})},yt=(i,g)=>{X(C=>({...C,[i]:g})),Qe(!1),Y[i]&&qe(C=>{const ee={...C};return delete ee[i],ee})},qs=i=>{W(i),Qe(!1)},Nt=(i,g)=>{Je(C=>({...C,[i]:g})),Qe(!1),Y[i]&&qe(C=>{const ee={...C};return delete ee[i],ee})},Te=a.useMemo(()=>{const i=Sn($);for(const[Q,We]of Object.entries({heartbeatIntervalMs:{label:"Heartbeat Interval",min:1},heartbeatTimeoutMs:{label:"Heartbeat Timeout",min:5},maxConcurrentRuns:{label:"Max Concurrent Runs",min:1}})){const de=S[Q]?.trim();if(!de)continue;const Ee=Number(de);Number.isNaN(Ee)||!Number.isFinite(Ee)?i[Q]=`"${We.label}" must be a valid number`:Ee<We.min&&(i[Q]=`"${We.label}" must be at least ${We.min.toLocaleString()}`)}const g=S.autoClaimCandidatesInPrompt?.trim();if(g){const Q=Number(g);(!Number.isInteger(Q)||Q<0||Q>10)&&(i.autoClaimCandidatesInPrompt='"Auto-claim candidates in prompt" must be an integer between 0 and 10')}const C=S.messageResponseMode?.trim();C&&!["immediate","on-heartbeat"].includes(C)&&(i.messageResponseMode='"Message Response Mode" must be either immediate or on-heartbeat');const ee=q.tokenBudget?.trim();if(ee){const Q=Number(ee);Number.isNaN(Q)||!Number.isFinite(Q)?i.tokenBudget='"Token Budget" must be a valid number':Q<=0&&(i.tokenBudget='"Token Budget" must be greater than 0')}const ge=q.usageThreshold?.trim();if(ge){const Q=Number(ge);Number.isNaN(Q)||!Number.isFinite(Q)?i.usageThreshold='"Usage Threshold" must be a valid number':(Q<1||Q>100)&&(i.usageThreshold='"Usage Threshold" must be between 1 and 100')}const te=q.budgetPeriod?.trim();te&&!["daily","weekly","monthly","lifetime"].includes(te)&&(i.budgetPeriod='"Budget Period" must be one of: daily, weekly, monthly, lifetime');const ve=q.resetDay?.trim(),je=te||"lifetime";if(ve){const Q=Number(ve);Number.isNaN(Q)||!Number.isFinite(Q)?i.resetDay='"Reset Day" must be a valid number':je==="weekly"?(Q<0||Q>6||!Number.isInteger(Q))&&(i.resetDay='"Reset Day" must be between 0 (Sunday) and 6 (Saturday) for weekly period'):je==="monthly"&&(Q<1||Q>31||!Number.isInteger(Q))&&(i.resetDay='"Reset Day" must be between 1 and 31 for monthly period')}return i},[$,S,q]),os=a.useCallback(()=>{if(Object.keys(Te).length>0)return null;const i={...t.metadata};for(const de of ot){const Ee=$[de.key]?.trim();Ee?de.type==="number"?i[de.key]=Number(Ee):i[de.key]=Ee:delete i[de.key]}Fe.length>0?i.skills=Fe:delete i.skills;const g={...t.runtimeConfig};g.enabled=F,g.autoClaimRelevantTasks=b,g.engineerBacklogAutoClaim=d,J==="auto"?delete g.assignmentPolicy:g.assignmentPolicy=J,g.runMissedHeartbeatOnStartup=Me,g.allowParallelExecution=ce,g.skipHeartbeatWhenIdle=ae;for(const de of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns","autoClaimCandidatesInPrompt"]){const Ee=S[de]?.trim();if(!Ee)delete g[de];else{const ds=Number(Ee);g[de]=de==="maxConcurrentRuns"||de==="autoClaimCandidatesInPrompt"?ds:ds*1e3}}const C=S.messageResponseMode?.trim();C?g.messageResponseMode=C:delete g.messageResponseMode,De?g.heartbeatScopeDiscipline=De:delete g.heartbeatScopeDiscipline,A?g.heartbeatPromptTemplate=A:delete g.heartbeatPromptTemplate;const ee=$.thinkingLevel||"off";if(g.thinkingLevel=ee,pe==="runtime")I.trim()?g.runtimeHint=I.trim():delete g.runtimeHint,delete g.modelProvider,delete g.modelId,delete g.model;else if(delete g.runtimeHint,h.trim()){const de=h.indexOf("/");de!==-1&&(g.modelProvider=h.slice(0,de),g.modelId=h.slice(de+1),g.model=h.trim())}else delete g.modelProvider,delete g.modelId,delete g.model;const ge={},te=q.tokenBudget?.trim(),ve=q.usageThreshold?.trim(),je=q.budgetPeriod?.trim(),Q=q.resetDay?.trim();te&&(ge.tokenBudget=Number(te)),ve&&(ge.usageThreshold=Number(ve)/100),je&&(ge.budgetPeriod=je),Q&&(ge.resetDay=Number(Q)),Object.keys(ge).length>0?g.budgetConfig=ge:delete g.budgetConfig;let We;return ue&&(We={mode:ue,entryFile:me||"AGENTS.md",files:ne.length>0?ne:["AGENTS.md"]},ue==="external"&&He.trim()&&(We.externalPath=He.trim())),{name:f.trim()||void 0,role:j,title:m.trim()||void 0,icon:T.trim()||void 0,reportsTo:R.trim()||void 0,metadata:i,runtimeConfig:g,bundleConfig:We}},[t.metadata,t.runtimeConfig,ce,J,b,q,me,He,ne,ue,d,$,F,A,De,S,T,h,f,R,j,Me,pe,I,Fe,ae,m,Te]),rt=a.useCallback(async(i,g)=>{const C=os();if(!C)return qe(Te),i&&l(n("agents.fixValidationErrors","Please fix validation errors before saving"),"error"),g==="auto"&&vt(n("agents.fixValidationToSave","Fix validation errors to save changes")),!1;const ee=JSON.stringify(C);if(ee===is.current)return!1;const ge=++jt.current;qe({}),vt(null),ss(!0);try{return await Ot(t.id,C,r),ge!==jt.current?!1:(is.current=ee,g==="manual"&&l(n("agents.settingsSaved","Settings saved"),"success"),vt(null),Qe(!0),it.current&&clearTimeout(it.current),it.current=setTimeout(()=>Qe(!1),3e3),await o(),!0)}catch(te){if(ge===jt.current){const ve=U(te);vt(ve),l(n("agents.settingsSaveFailed","Failed to save settings: {{error}}",{error:ve}),"error")}return!1}finally{ge===jt.current&&ss(!1)}},[l,t.id,os,o,r,Te]),Ys=async()=>{await rt(!0,"manual")},re=a.useCallback(()=>{if(!(!we||Ve)){if(Object.keys(Te).length>0){qe(Te);return}rt(!1,"auto")}},[we,Ve,rt,Te]);a.useEffect(()=>{if(!we||Ve)return;if(Object.keys(Te).length>0){qe(Te);return}const i=setTimeout(()=>{rt(!1,"auto")},hn);return()=>clearTimeout(i)},[we,Ve,rt,Te]);const Ks=a.useCallback(async i=>{K(!0);try{await Ea(t.id,i,r),await o(),l(n("agents.avatarUploaded","Avatar uploaded"),"success")}catch(g){l(U(g),"error")}finally{K(!1),Z.current&&(Z.current.value="")}},[l,t.id,o,r]),Zs=a.useCallback(async()=>{K(!0);try{await La(t.id,r),await o(),l(n("agents.avatarRemoved","Avatar removed"),"success")}catch(i){l(U(i),"error")}finally{K(!1)}},[l,t.id,o,r]),cs=Ve?n("agents.savingChanges","Saving changes…"):zt?n("agents.saveFailed","Save failed: {{error}}",{error:zt}):!we&&Gs?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:()=>E(!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:f,onChange:i=>u(i.target.value),onBlur:()=>{re()}})]}),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),re()},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=>w(i.target.value),onBlur:()=>{re()}})]}),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(Ps,{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:M,onChange:i=>{const g=i.target.files?.[0];g&&Ks(g)}}),e.jsx("button",{type:"button",className:"btn btn-sm",disabled:M,onClick:()=>Z.current?.click(),children:n("agents.uploadAvatar","Upload Avatar")}),t.imageUrl?e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void Zs(),disabled:M,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=>z(i.target.value),onBlur:()=>{re()}})]}),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:R,onChange:i=>{B(i.target.value),re()},disabled:N,children:[e.jsx("option",{value:"",children:n("agents.noManager","No manager")}),bt&&e.jsx("option",{value:Ke,children:n("agents.unknownManager","Unknown manager ({{id}})",{id:Ke})}),pt.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(Ya,{id:"agent-skills",label:"Skills",value:Fe,onChange:i=>{ye(i),re()},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${pe==="model"?" active":""}`,role:"tab","aria-selected":pe==="model",tabIndex:pe==="model"?0:-1,onClick:()=>{_e("model"),_(""),re()},children:n("agents.builtInModel","Built-in Model")}),e.jsx("button",{type:"button",className:`config-runtime-tab${pe==="runtime"?" active":""}`,role:"tab","aria-selected":pe==="runtime",tabIndex:pe==="runtime"?0:-1,onClick:()=>{_e("runtime"),re()},children:n("agents.pluginRuntime","Plugin Runtime")})]})]}),pe==="model"?e.jsx("div",{className:"config-field",children:e.jsx(Da,{models:$e,value:h,onChange:i=>{L(i),re()},placeholder:n("agents.useGlobalDefault","Use global default"),label:n("agents.agentModelLabel","Agent Model"),disabled:gt,favoriteProviders:mt,onToggleFavorite:Lt,favoriteModels:tt,onToggleModelFavorite:st,thinkingLevel:$.thinkingLevel??"",onThinkingLevelChange:i=>{V(g=>({...g,thinkingLevel:i})),re()}})}):e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-runtime-hint",children:n("agents.runtimeLabel","Runtime")}),ft?e.jsx("span",{className:"config-hint",children:e.jsx(za,{label:n("agents.loadingRuntimes","Loading runtimes…")})}):e.jsxs("select",{id:"agent-runtime-hint",className:"select",value:I,onChange:i=>{_(i.target.value),re()},children:[e.jsx("option",{value:"",children:Ge.length>0?n("agents.selectRuntime","Select a plugin runtime…"):n("agents.noRuntimes","No plugin runtimes available")}),Ge.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:ps.map(i=>{const g=Us.has(i),C=Vs.has(i),ee=`agent-capability-${t.id}-${i.replace(/[^a-z0-9]+/gi,"-")}`;return e.jsxs("label",{className:"agent-capability-grant-row",htmlFor:ee,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"):C?n("agents.explicitGrant","Explicit grant"):n("agents.notGranted","Not granted")})]}),e.jsx("input",{id:ee,type:"checkbox",checked:C,"aria-label":n("agents.toggleCapabilityGrant","Toggle explicit grant for {{permission}}",{permission:i}),onChange:ge=>{Ws(i,ge.target.checked)}})]},i)})})]}),le===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 xt({presetId:"custom",rules:{git_write:Ne?.rules?.git_write??"allow",file_write_delete:Ne?.rules?.file_write_delete??"allow",command_execution:Ne?.rules?.command_execution??"allow",network_api:Ne?.rules?.network_api??"allow",task_agent_mutation:Ne?.rules?.task_agent_mutation??"allow",review_gate_bypass:Ne?.rules?.review_gate_bypass??"require-approval",file_scope:Ne?.rules?.file_scope??"allow"}}),children:n("agents.customizeForAgent","Customize for this agent")})]}):null,e.jsx(Qa,{mode:"agent-override",value:le,projectDefault:Ne?.rules,projectDefaultToolRules:Ne?.toolRules,onChange:i=>{xt(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),X(i=>({...i,autoClaimCandidatesInPrompt:"0"})),re()},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),re()}}),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),re()}}),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.jsx("label",{htmlFor:"hb-assignmentPolicy",children:n("agents.assignmentPolicy","Assignment Policy")}),e.jsxs("select",{id:"hb-assignmentPolicy",value:J,onChange:i=>{xe(i.target.value),re()},children:[e.jsx("option",{value:"auto",children:n("agents.assignmentPolicyAuto","Auto (default) — eligible for automatic assignment")}),e.jsx("option",{value:"explicit-only",children:n("agents.assignmentPolicyExplicitOnly","Explicit only — never auto-assigned; accepts direct assignment/delegation")}),e.jsx("option",{value:"none",children:n("agents.assignmentPolicyNone","None — can never receive implementation tasks")})]}),e.jsx("span",{className:"config-hint",children:n("agents.assignmentPolicyHint",'Controls whether task routing may bind work to this agent. Use "None" for liaison/observer agents that must never execute product tasks — no override can bypass it.')})]}),e.jsxs("div",{className:"config-field",children:[e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-enabled",children:[e.jsx("input",{id:"hb-enabled",type:"checkbox",checked:F,onChange:i=>{qs(i.target.checked),re()}}),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:Me,onChange:i=>{Le(i.target.checked),re()}}),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:ce,onChange:i=>{H(i.target.checked),re()}}),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:ae,onChange:i=>{Ae(i.target.checked),re()}}),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:De,onChange:i=>{const g=i.target.value;x(g==="strict"||g==="lite"||g==="off"?g:""),re()},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:A,onChange:i=>{const g=i.target.value;ie(g==="default"||g==="compact"?g:""),re()},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(Kt/1e3),value:S.heartbeatIntervalMs??"",onChange:i=>yt("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:Kt/1e3,label:gn})})]}),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:S.heartbeatTimeoutMs??"",onChange:i=>yt("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:S.maxConcurrentRuns??"",onChange:i=>yt("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:S.messageResponseMode??"",onChange:i=>yt("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:q.tokenBudget??"",onChange:i=>Nt("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:q.usageThreshold??"",onChange:i=>Nt("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:q.budgetPeriod??"",onChange:i=>Nt("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:q.resetDay??"",onChange:i=>Nt("resetDay",i.target.value)}),Y.resetDay?e.jsx("span",{className:"config-error",children:Y.resetDay}):e.jsx("span",{className:"config-hint",children:q.budgetPeriod==="weekly"?n("agents.resetDayWeekly","Day of week (0=Sunday to 6=Saturday) for reset."):q.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.")})]}),Ue?.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",(Ue.usagePercent??0)>=100?"budget-progress-bar__fill--red":(Ue.usagePercent??0)>=80?"budget-progress-bar__fill--amber":"budget-progress-bar__fill--green"),style:{width:`${Math.min(Ue.usagePercent??0,100)}%`}})}),e.jsx("span",{className:"budget-progress-label",children:n("agents.budgetUsageDisplay","{{used}} / {{limit}} tokens ({{percent}}% used)",{used:(Ue.currentUsage??0).toLocaleString(),limit:(Ue.budgetLimit??0).toLocaleString(),percent:Math.round(Ue.usagePercent??0)})})]})]}),Ue?.budgetLimit!=null&&e.jsx("div",{className:"config-field",children:e.jsx("button",{className:"btn btn-reset-budget",onClick:()=>void Js(),disabled:es,children:es?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:14,className:"animate-spin"}),n("agents.resetting","Resetting…")]}):e.jsxs(e.Fragment,{children:[e.jsx(At,{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:ue,onChange:i=>ze(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:[ue==="managed"&&n("agents.bundleManagedHint","Files will be stored in a system-managed directory within .fusion/agents/"),ue==="external"&&n("agents.bundleExternalHint","Specify an external directory path for the instruction files"),!ue&&n("agents.bundleSelectMode","Select a mode to enable instruction bundling")]})]}),ue&&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:me,onChange:i=>Be(i.target.value)}),e.jsx("span",{className:"config-hint",children:n("agents.bundleEntryFileHint","Primary instructions file name (default: AGENTS.md)")})]}),ue==="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:He,onChange:i=>Oe(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=>ut(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:ot.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:C=>ls(i.key,C.target.value),children:[e.jsx("option",{value:"",children:n("agents.systemDefault","System Default")}),i.options?.map(C=>e.jsx("option",{value:C.value,children:C.label},C.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:C=>ls(i.key,C.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||Ve,onClick:()=>void Ys(),children:Ve?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:16,className:"animate-spin"}),n("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{size:16}),n("agents.saveSettings","Save Settings")]})}),cs&&e.jsxs("span",{className:oe("config-saved-indicator",zt&&"config-saved-indicator--error"),children:[Ve?e.jsx(G,{size:14,className:"animate-spin"}):e.jsx(fe,{size:14}),cs]})]})]}),e.jsx(Mn,{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:!as||!p,onClick:()=>void p?.(),children:[e.jsx(ct,{size:16}),n("agents.deleteAgent","Delete Agent")]}),e.jsx("span",{className:"config-danger-note",children:as?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(Ka,{isOpen:P,onClose:()=>E(!1),onUseDraft:Ze,projectId:r,existingAgents:O,mode:"edit",existingAgentConfig:he})]})}function Fn({agentId:t,projectId:r,onChildClick:l}){const{t:o}=ke("app"),[s,p]=a.useState([]),[k,n]=a.useState(!0);return a.useEffect(()=>{n(!0),wa(t,r).then(p).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(G,{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(Ls,{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(f=>{const u=Xt[f.state];return e.jsxs("div",{className:"agent-tree__node agent-is-child",onClick:()=>l?.(f.id),role:"button",tabIndex:0,onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&(j.key===" "&&j.preventDefault(),l?.(f.id))},style:{cursor:l?"pointer":"default"},children:[e.jsx("span",{className:"agent-tree__icon",children:f.icon??"🤖"}),e.jsx("span",{className:"agent-tree__name",children:f.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:f.state})]},f.id)})})})]})}export{On as AgentDetailView,et as relativeTime};
|