@runfusion/fusion 0.27.1 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/bin.js +3418 -864
  2. package/dist/client/assets/AgentDetailView-DSpIqBOs.css +1 -0
  3. package/dist/client/assets/{AgentDetailView-shgiiUb4.js → AgentDetailView-V32TpEe1.js} +3 -3
  4. package/dist/client/assets/{AgentsView-CpwqOVDz.js → AgentsView-CxITZE-U.js} +3 -3
  5. package/dist/client/assets/ChatView-7WPHyB_7.js +1 -0
  6. package/dist/client/assets/DevServerView-Diw4hjw0.js +1 -0
  7. package/dist/client/assets/{DirectoryPicker-C0kmRv0u.js → DirectoryPicker-CWSApoLU.js} +1 -1
  8. package/dist/client/assets/{DocumentsView-B94U9ijs.js → DocumentsView-1kr0dhsV.js} +1 -1
  9. package/dist/client/assets/{EvalsView-O_4YWy--.js → EvalsView-cDfXYiK6.js} +1 -1
  10. package/dist/client/assets/{ExperimentalAgentOnboardingModal-CkEiF85-.js → ExperimentalAgentOnboardingModal-lNSf6UtY.js} +1 -1
  11. package/dist/client/assets/{InsightsView-D-Qe0tRr.js → InsightsView-D2AjxOnu.js} +1 -1
  12. package/dist/client/assets/{MemoryView-CoRUmRvb.js → MemoryView-Dq4yjIPI.js} +1 -1
  13. package/dist/client/assets/{NodesView-DQzXjcLc.js → NodesView-Cpmkze7n.js} +4 -4
  14. package/dist/client/assets/{PiExtensionsManager-Dn1LmFbq.js → PiExtensionsManager-oi9FHT0y.js} +2 -2
  15. package/dist/client/assets/PluginManager-C4UoLv4U.css +1 -0
  16. package/dist/client/assets/PluginManager-o12KG4e8.js +1 -0
  17. package/dist/client/assets/ResearchView-C7uXon3o.css +1 -0
  18. package/dist/client/assets/ResearchView-C9bjVB7-.js +1 -0
  19. package/dist/client/assets/{SettingsModal-Bg1-3JO_.js → SettingsModal-CT01a5Rh.js} +1 -1
  20. package/dist/client/assets/SettingsModal-Cu93Jjho.js +31 -0
  21. package/dist/client/assets/{SetupWizardModal-DuzYPbuJ.js → SetupWizardModal-Agi3XNtZ.js} +1 -1
  22. package/dist/client/assets/{SkillsView-BIFoVNUf.js → SkillsView-DmZfbGLs.js} +1 -1
  23. package/dist/client/assets/{StashRecoveryView-C52KsV7f.js → StashRecoveryView-BwKJQaUW.js} +1 -1
  24. package/dist/client/assets/{TodoView-sS_mT0Y7.js → TodoView-uJRg4Cnl.js} +2 -2
  25. package/dist/client/assets/dashboard-view-C7Snlgow.js +21 -0
  26. package/dist/client/assets/dashboard-view-DqWnXEbq.css +1 -0
  27. package/dist/client/assets/{folder-open-B9cwJ-OX.js → folder-open-DU-Ec_iC.js} +1 -1
  28. package/dist/client/assets/index-CD0_dkME.css +1 -0
  29. package/dist/client/assets/index-DiewofJh.js +692 -0
  30. package/dist/client/assets/{star-BDn04UYV.js → star-Qi0GspVN.js} +1 -1
  31. package/dist/client/assets/{upload-zdPPycKQ.js → upload-Dx_l9Vbu.js} +1 -1
  32. package/dist/client/assets/{users-CPYZjK2g.js → users-3Qw_TMah.js} +1 -1
  33. package/dist/client/index.html +2 -2
  34. package/dist/client/version.json +1 -1
  35. package/dist/droid-cli/package.json +1 -1
  36. package/dist/extension.js +2628 -573
  37. package/dist/pi-claude-cli/package.json +1 -1
  38. package/dist/plugins/fusion-plugin-cli-printing-press/package.json +1 -1
  39. package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/registration.test.ts +2 -4
  40. package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/runtime-availability.test.ts +5 -2
  41. package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/workflow-integration.test.ts +7 -4
  42. package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
  43. package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
  44. package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
  45. package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
  46. package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
  47. package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
  48. package/dist/plugins/fusion-plugin-reports/package.json +1 -1
  49. package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
  50. package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
  51. package/package.json +1 -1
  52. package/skill/fusion/references/engine-tools.md +1 -0
  53. package/skill/fusion/references/extension-tools.md +3 -1
  54. package/dist/client/assets/AgentDetailView-B7QRcHJH.css +0 -1
  55. package/dist/client/assets/ChatView-DyRBOIKL.js +0 -1
  56. package/dist/client/assets/DevServerView-Cdelj9-m.js +0 -1
  57. package/dist/client/assets/PluginManager-DtRQXia5.css +0 -1
  58. package/dist/client/assets/PluginManager-Y0fs-6No.js +0 -1
  59. package/dist/client/assets/ResearchView-BEI4ZSGs.css +0 -1
  60. package/dist/client/assets/ResearchView-CjOxKhdS.js +0 -1
  61. package/dist/client/assets/SettingsModal-DL7tjJQa.js +0 -31
  62. package/dist/client/assets/dashboard-view-BoTzlP8b.css +0 -1
  63. package/dist/client/assets/dashboard-view-MB-86hAu.js +0 -21
  64. package/dist/client/assets/index-BOjPRqEk.js +0 -692
  65. package/dist/client/assets/index-BmSEq8Rb.css +0 -1
@@ -1,4 +1,4 @@
1
- import{r as t,j as e}from"./vendor-react-K0fH_qHe.js";import{c as $s,dB as Ct,dC as wt,dD as Rt,dE as Mt,L as V,R as Ns,ar as Vs,Z as At,as as ks,W as bs,a as at,b as nt,dF as Ft,dG as Et,dH as Tt,v as it,cK as $t,dI as Pt,z as K,dJ as Lt,dK as lt,dL as rt,dM as Dt,i as ps,D as Js,s as gs,br as ot,k as ct,U as Cs,A as vs,V as Ws,aS as Ve,dN as zt,X as dt,F as es,dO as Bt,ch as ut,dP as mt,dQ as Ot,cE as Ht,ap as It,bq as Ut,at as ht,B as Ps,Y as _t,a2 as qs,a3 as Vt,a4 as Jt,dR as Es,l as ft,dS as Wt,bB as qt,r as Gt,aq as gt,a1 as xt,dT as Kt,C as ue,dU as bt,dV as Gs,bt as Ks,dW as Yt,dX as Zt,dY as Xt,dZ as ss,a9 as ts,ab as as,ac as ns,a7 as pt,d_ as Qt,d$ as ea,h as sa,j as Ys,$ as ta,e0 as aa,e1 as na,m as ia,e2 as Ts,e3 as la,e4 as ra,O as oa,e5 as ca,e6 as da,e7 as vt,e8 as ua,e9 as ma,ea as ha,eb as fa,ec as ga}from"./index-BOjPRqEk.js";import{S as jt}from"./star-BDn04UYV.js";import{f as ws,S as xa,E as ba}from"./ExperimentalAgentOnboardingModal-CkEiF85-.js";import"./vendor-xterm-DzcZoU0P.js";/**
1
+ import{r as t,j as e}from"./vendor-react-K0fH_qHe.js";import{c as $s,dE as Ct,dF as wt,dG as Rt,dH as Mt,L as V,R as Ns,ar as Vs,Z as At,as as ks,W as bs,a as at,b as nt,dI as Ft,dJ as Et,dK as Tt,v as it,cN as $t,dL as Pt,z as K,dM as Lt,dN as lt,dO as rt,dP as Dt,i as ps,D as Js,s as gs,bt as ot,k as ct,U as Cs,A as vs,V as Ws,aS as Ve,dQ as zt,X as dt,F as es,dR as Bt,ck as ut,dS as mt,dT as Ot,cH as Ht,ap as It,bs as Ut,at as ht,B as Ps,Y as _t,a2 as Gs,a3 as Vt,a4 as Jt,dU as Es,l as ft,dV as Wt,bE as Gt,r as qt,aq as gt,a1 as xt,dW as Kt,C as ue,dX as bt,dY as qs,bv as Ks,dZ as Yt,d_ as Zt,d$ as Xt,e0 as ss,a9 as ts,ab as as,ac as ns,a7 as pt,e1 as Qt,e2 as ea,h as sa,j as Ys,$ as ta,e3 as aa,e4 as na,m as ia,e5 as Ts,e6 as la,e7 as ra,O as oa,e8 as ca,e9 as da,ea as vt,eb as ua,ec as ma,ed as ha,ee as fa,ef as ga}from"./index-DiewofJh.js";import{S as jt}from"./star-Qi0GspVN.js";import{f as ws,S as xa,E as ba}from"./ExperimentalAgentOnboardingModal-lNSf6UtY.js";import"./vendor-xterm-DzcZoU0P.js";/**
2
2
  * @license lucide-react v1.7.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -13,6 +13,6 @@ import{r as t,j as e}from"./vendor-react-K0fH_qHe.js";import{c as $s,dB as Ct,dC
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 Na=[["path",{d:"M16 17h6v-6",key:"t6n2it"}],["path",{d:"m22 17-8.5-8.5-5 5L2 7",key:"x473p"}]],ya=$s("trending-down",Na);function Zs(s){return s<1e3?`${s}ms`:s<6e4?`${(s/1e3).toFixed(1)}s`:s<36e5?`${Math.floor(s/6e4)}m`:`${(s/36e5).toFixed(1)}h`}function Sa(s){return`${Math.round(s*100)}%`}function Xs(s){const n=Date.now(),i=new Date(s).getTime(),l=n-i;if(l<0){const d=Math.abs(l);return d<6e4?"in a moment":d<36e5?`in ${Math.floor(d/6e4)}m`:d<864e5?`in ${Math.floor(d/36e5)}h`:`in ${Math.floor(d/864e5)}d`}return l<6e4?"just now":l<36e5?`${Math.floor(l/6e4)}m ago`:l<864e5?`${Math.floor(l/36e5)}h ago`:`${Math.floor(l/864e5)}d ago`}function ka(s){switch(s){case"periodic":return"Periodic";case"post-task":return"Post-Task";case"manual":return"Manual";case"user-requested":return"User Requested";default:return s}}function Xe(s){return s instanceof Error&&s.message?s.message:String(s)}function Ca(s){switch(s){case"improving":return"↑ Improving";case"declining":return"↓ Declining";case"stable":return"→ Stable";default:return"Insufficient data"}}function wa(s){switch(s){case"improving":return"trend-improving";case"declining":return"trend-declining";case"stable":return"trend-stable";default:return"trend-insufficient"}}function Qs(s,n=5){return e.jsx("span",{className:"rating-stars",children:Array.from({length:n},(i,l)=>e.jsx(jt,{size:14,className:l<s?"star-filled":"star-empty",fill:l<s?"currentColor":"none"},l))})}function Ra({agentId:s,projectId:n,addToast:i}){const[l,d]=t.useState([]),[x,M]=t.useState(null),[f,v]=t.useState(null),[A,P]=t.useState([]),[c,C]=t.useState(!0),[y,D]=t.useState(!0),[j,J]=t.useState(!1),[Z,p]=t.useState(!1),[m,I]=t.useState(null),[N,F]=t.useState(0),[R,W]=t.useState(""),[O,T]=t.useState(""),Y=t.useCallback(async()=>{try{const[r,o]=await Promise.all([Ct(s,20,n),wt(s,void 0,n)]);d(r),M(o)}catch(r){i(`Failed to load reflections: ${Xe(r)}`,"error")}finally{C(!1)}},[s,n,i]),S=t.useCallback(async()=>{try{const[r,o]=await Promise.all([Rt(s,n),Mt(s,{limit:50},n)]);v(r),P(o)}catch(r){i(`Failed to load ratings: ${Xe(r)}`,"error")}finally{D(!1)}},[s,n,i]);t.useEffect(()=>{Y(),S()},[Y,S]);const Q=async()=>{J(!0);try{if(!await Ft(s,n)){i("Not enough history to generate a reflection yet","error");return}i("Reflection generated successfully","success"),C(!0),await Y()}catch(r){const o=Xe(r),k=o.toLowerCase();k.includes("agent not found")||k.includes("not found")?i("This agent is no longer available. It may have been deleted.","error"):k.includes("insufficient history")?i("Not enough history to generate a reflection yet","error"):i(`Failed to generate reflection: ${o}`,"error")}finally{J(!1)}},$=async r=>{if(r.preventDefault(),N!==0){p(!0);try{await Et(s,{score:N,category:R||void 0,comment:O||void 0,raterType:"user"},n),F(0),W(""),T(""),i("Rating added","success"),await S()}catch(o){i(`Failed to add rating: ${Xe(o)}`,"error")}finally{p(!1)}}},q=async r=>{try{await Tt(s,r,n),i("Rating deleted","success"),await S()}catch(o){i(`Failed to delete rating: ${Xe(o)}`,"error")}},h=r=>{I(o=>o===r?null:r)};if(c&&y)return e.jsx("div",{className:"reflections-tab",children:e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(V,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading evaluation..."})]})});const b=x&&x.totalTasksCompleted===0&&x.totalTasksFailed===0&&x.recentReflectionCount===0;return e.jsxs("div",{className:"reflections-tab",children:[e.jsxs("div",{className:"reflections-header",children:[e.jsxs("h3",{children:[e.jsx(xs,{size:16}),"Performance, Reflections & Ratings"]}),e.jsx("button",{className:"btn btn-secondary",onClick:Q,disabled:j,title:"Generate a manual reflection",children:j?e.jsxs(e.Fragment,{children:[e.jsx(V,{size:14,className:"animate-spin"}),"Reflecting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ns,{size:14}),"Reflect Now"]})})]}),x&&!b&&e.jsxs("div",{className:"reflections-stats-grid",children:[e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(Vs,{size:16,style:{color:"var(--color-success)"}}),x.totalTasksCompleted]}),e.jsx("div",{className:"stat-label",children:"Tasks Completed"})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(ya,{size:16,style:{color:"var(--color-error)"}}),x.totalTasksFailed]}),e.jsx("div",{className:"stat-label",children:"Tasks Failed"})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(At,{size:16,style:{color:"var(--in-progress)"}}),Zs(x.avgDurationMs)]}),e.jsx("div",{className:"stat-label",children:"Avg Duration"})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(xs,{size:16,style:{color:x.successRate>=.8?"var(--color-success)":x.successRate>=.5?"var(--color-warning)":"var(--color-error)"}}),Sa(x.successRate)]}),e.jsx("div",{className:"stat-label",children:"Success Rate"})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(ks,{size:16,style:{color:"var(--color-info)"}}),x.recentReflectionCount]}),e.jsx("div",{className:"stat-label",children:"Reflections"})]})]}),b&&e.jsxs("div",{className:"reflections-no-data",children:[e.jsx(xs,{size:24,opacity:.3}),e.jsx("p",{children:"No performance data yet"})]}),e.jsxs("div",{className:"reflections-ratings-section",children:[e.jsx("h4",{children:"User Ratings"}),y?e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(V,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"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)}),Qs(Math.round(f.averageScore))]}),e.jsxs("div",{className:"rating-stats",children:[e.jsxs("span",{className:"rating-count",children:[f.totalRatings," ratings"]}),e.jsx("span",{className:`rating-trend-badge ${wa(f.trend)}`,children:Ca(f.trend)})]})]}),f&&Object.keys(f.categoryAverages).length>0&&e.jsxs("div",{className:"category-breakdown",children:[e.jsx("h4",{children:"Category Averages"}),Object.entries(f.categoryAverages).map(([r,o])=>e.jsxs("div",{className:"category-item",children:[e.jsx("span",{className:"category-name",children:r}),e.jsx("span",{className:"category-score",children:o.toFixed(1)})]},r))]}),e.jsxs("form",{className:"add-rating-form",onSubmit:$,children:[e.jsx("h4",{children:"Add Rating"}),e.jsx("div",{className:"star-selector",children:[1,2,3,4,5].map(r=>e.jsx("button",{type:"button",className:"star-btn touch-target",onClick:()=>F(r),title:`${r} star${r>1?"s":""}`,children:e.jsx(jt,{size:24,fill:r<=N?"currentColor":"none",className:r<=N?"star-filled":"star-empty"})},r))}),e.jsxs("select",{value:R,onChange:r=>W(r.target.value),className:"select add-rating-category-select",children:[e.jsx("option",{value:"",children:"Select category..."}),e.jsx("option",{value:"quality",children:"Quality"}),e.jsx("option",{value:"speed",children:"Speed"}),e.jsx("option",{value:"communication",children:"Communication"}),e.jsx("option",{value:"reliability",children:"Reliability"}),e.jsx("option",{value:"other",children:"Other"})]}),e.jsx("textarea",{value:O,onChange:r=>T(r.target.value),placeholder:"Optional comment...",className:"input add-rating-comment-input",rows:3}),e.jsx("button",{type:"submit",className:"btn btn-task-create",disabled:N===0||Z,children:Z?"Submitting...":"Submit Rating"})]}),e.jsxs("div",{className:"rating-history",children:[e.jsx("h4",{children:"Rating History"}),A.length===0?e.jsx("p",{className:"no-ratings",children:"No ratings yet"}):A.map(r=>e.jsxs("div",{className:"rating-history-item",children:[e.jsxs("div",{className:"rating-item-header",children:[Qs(r.score),r.category&&e.jsx("span",{className:"rating-category-badge",children:r.category}),e.jsx("span",{className:"rating-time",children:Xs(r.createdAt)}),e.jsx("button",{type:"button",className:"rating-delete-btn touch-target",onClick:()=>void q(r.id),title:"Delete rating",children:e.jsx(bs,{size:14})})]}),r.comment&&e.jsx("p",{className:"rating-comment",children:r.comment})]},r.id))]})]})]}),e.jsxs("div",{className:"reflections-list",children:[e.jsx("h4",{children:"Reflection History"}),c?e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(V,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading reflections..."})]}):l.length===0?e.jsxs("div",{className:"reflection-empty",children:[e.jsx(ks,{size:32,opacity:.3}),e.jsx("p",{children:"No reflections yet"}),e.jsx("p",{className:"text-secondary",children:"Trigger a reflection to get started"})]}):e.jsx("div",{className:"reflection-cards",children:l.map(r=>{const o=m===r.id;return e.jsxs("div",{className:`reflection-card ${o?"reflection-card--expanded":""}`,onClick:()=>h(r.id),role:"button",tabIndex:0,onKeyDown:k=>k.key==="Enter"&&h(r.id),children:[e.jsxs("div",{className:"reflection-card-header",children:[e.jsx("span",{className:`reflection-trigger-badge reflection-trigger-${r.trigger}`,children:ka(r.trigger)}),e.jsx("span",{className:"reflection-timestamp",children:Xs(r.timestamp)}),e.jsx("span",{className:"reflection-chevron",children:o?e.jsx(at,{size:16}):e.jsx(nt,{size:16})})]}),e.jsx("div",{className:"reflection-summary",children:r.summary}),o&&e.jsxs("div",{className:"reflection-details",children:[r.insights.length>0&&e.jsxs("div",{className:"reflection-insights",children:[e.jsxs("h5",{children:[e.jsx(ks,{size:14})," Insights"]}),e.jsx("ul",{children:r.insights.map((k,ne)=>e.jsx("li",{children:k},ne))})]}),r.suggestedImprovements.length>0&&e.jsxs("div",{className:"reflection-suggestions",children:[e.jsxs("h5",{children:[e.jsx(Vs,{size:14})," Suggested Improvements"]}),e.jsx("ul",{children:r.suggestedImprovements.map((k,ne)=>e.jsx("li",{children:k},ne))})]}),r.metrics&&e.jsxs("div",{className:"reflection-metrics",children:[e.jsx("h5",{children:"Metrics"}),e.jsxs("div",{className:"metrics-grid",children:[r.metrics.tasksCompleted!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:"Tasks:"}),e.jsx("span",{className:"metric-value",children:r.metrics.tasksCompleted})]}),r.metrics.tasksFailed!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:"Failed:"}),e.jsx("span",{className:"metric-value",children:r.metrics.tasksFailed})]}),r.metrics.avgDurationMs!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:"Avg Duration:"}),e.jsx("span",{className:"metric-value",children:Zs(r.metrics.avgDurationMs)})]}),r.metrics.errorCount!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:"Errors:"}),e.jsx("span",{className:"metric-value",children:r.metrics.errorCount})]})]})]})]})]},r.id)})})]})]})}function ae(...s){return s.filter(Boolean).join(" ")}function Je(s){const n=Date.now(),i=new Date(s).getTime(),l=n-i;if(l<0){const d=Math.abs(l);return d<6e4?"in a moment":d<36e5?`in ${Math.floor(d/6e4)}m`:d<864e5?`in ${Math.floor(d/36e5)}h`:`in ${Math.floor(d/864e5)}d`}return l<6e4?"just now":l<36e5?`${Math.floor(l/6e4)}m ago`:l<864e5?`${Math.floor(l/36e5)}h ago`:`${Math.floor(l/864e5)}d ago`}const Ma=[{id:"dashboard",label:"Dashboard",icon:ja},{id:"logs",label:"Logs",icon:es},{id:"mail",label:"Mail",icon:Bt},{id:"runs",label:"Runs",icon:vs},{id:"tasks",label:"Tasks",icon:ut},{id:"employees",label:"Employees",icon:mt},{id:"soul",label:"Soul",icon:Ot},{id:"instructions",label:"Instructions",icon:Ht},{id:"memory",label:"Agent Memory",icon:es},{id:"reflections",label:"Evaluation",icon:xs},{id:"config",label:"Settings",icon:It}],Ls={idle:{bg:"var(--state-idle-bg)",text:"var(--state-idle-text)",border:"var(--state-idle-border)"},active:{bg:"var(--state-active-bg)",text:"var(--state-active-text)",border:"var(--state-active-border)"},running:{bg:"var(--state-active-bg)",text:"var(--state-active-text)",border:"var(--state-active-border)"},paused:{bg:"var(--state-paused-bg)",text:"var(--state-paused-text)",border:"var(--state-paused-border)"},error:{bg:"var(--state-error-bg)",text:"var(--state-error-text)",border:"var(--state-error-border)"}},js={completed:{icon:ue,color:"var(--color-success)"},failed:{icon:Kt,color:"var(--color-error)"},active:{icon:V,color:"var(--in-progress)"},terminated:{icon:Ve,color:"var(--text-muted)"}},et={"long-term":"Long-term",daily:"Daily",dreams:"Dreams"},Aa={"long-term":"Curated durable decisions, conventions, constraints, and pitfalls for this specific agent.",daily:"Raw daily observations and open loops recorded by this agent.",dreams:"Synthesized patterns and emerging themes distilled from this agent's daily memory."},Fa=xt(Ts),Ea=700;function Ta(s,n){return s.some(i=>i.path===n)?n:s.find(i=>i.layer==="long-term")?.path??s[0]?.path??""}function en({agentId:s,projectId:n,onClose:i,addToast:l,onChildClick:d,inline:x=!1,showInlineBackButton:M=!1,initialTab:f,initialRunId:v,preferActiveRun:A=!1,onMutationSuccess:P}){const[c,C]=t.useState(null),{confirm:y}=it(),[D,j]=t.useState([]),[J,Z]=t.useState(!0),[p,m]=t.useState(f??"dashboard"),[I,N]=t.useState(!1),[F,R]=t.useState(!1),[W,O]=t.useState(!1),[T,Y]=t.useState(!1),[S,Q]=t.useState(!1),[$,q]=t.useState(!1),[h,b]=t.useState(0),[r,o]=t.useState(0),[k,ne]=t.useState(0),[L,pe]=t.useState(null),[re,ve]=t.useState(null),[ie,U]=t.useState(!1),[le,ze]=t.useState(null),Ae=t.useRef(null),is=t.useRef(null),ye=t.useRef(!1);$t(Ae,!x,"fusion:agent-detail-modal-size");const We=t.useRef(i),ls=t.useRef(l),Be=t.useRef(null),qe=t.useRef(!1),Fe=t.useRef(null),ee=t.useRef(0),Oe=t.useRef(s),$e=t.useRef(n);We.current=i,ls.current=l,Be.current=c;const fe=t.useCallback(async()=>{Be.current===null&&Z(!0);try{const z=await Pt(s,n);C(z)}catch(z){ls.current(`Failed to load agent: ${K(z)}`,"error"),We.current()}finally{Z(!1)}},[s,n]),Ge=t.useCallback(async()=>{const g=ee.current,z=s,_=n,E=()=>ee.current!==g||s!==z||n!==_;try{if(c?.taskId){pe(null),Fe.current=null;const Te=await Lt(c.taskId,_,{limit:100});if(E())return;j(Te.entries);return}const te=await lt(z,1,_);if(E())return;const he=te[0]??null;if(pe(he),!he){Fe.current=null,j([]);return}if(Fe.current===he.id)return;const ke=await rt(z,he.id,_);if(E())return;j(ke),Fe.current=he.id}catch(te){if(E())return;console.error("Failed to load agent logs:",te)}},[c?.taskId,s,n]),He=t.useCallback(async()=>{U(!0),ze(null);try{const g=await Dt(s,n);ve(g)}catch(g){ze(K(g)),ve(null)}finally{U(!1)}},[s,n]),ys=t.useCallback(g=>{qe.current=g},[]),Ie=t.useCallback(async(g=!1)=>{await P?.({agentId:s,deleted:g})},[s,P]),Se=t.useCallback(async()=>{await fe(),await Ie(!1)},[fe,Ie]);t.useEffect(()=>{fe()},[fe]),t.useEffect(()=>{const g=setInterval(()=>{fe()},3e4);return()=>{clearInterval(g)}},[fe]),t.useEffect(()=>{c&&p==="logs"&&Ge()},[c,p,Ge]),t.useEffect(()=>{p!=="logs"&&(Fe.current=null)},[p]),t.useEffect(()=>{c&&p==="mail"&&He()},[c,p,He]),t.useEffect(()=>{if(!T)return;const g=_=>{is.current?.contains(_.target)||Y(!1)},z=_=>{_.key==="Escape"&&Y(!1)};return document.addEventListener("mousedown",g),document.addEventListener("keydown",z),()=>{document.removeEventListener("mousedown",g),document.removeEventListener("keydown",z)}},[T]),t.useEffect(()=>{if(!T)return;let g=!1;return q(!0),ps(void 0,n).then(z=>{if(g)return;const _=z.filter(E=>!Js(E));b(_.filter(E=>E.state==="active"||E.state==="running").length),o(_.filter(E=>E.state==="paused").length)}).catch(()=>{g||(b(0),o(0))}).finally(()=>{g||q(!1)}),()=>{g=!0}},[T,n]),t.useEffect(()=>{if(p!=="logs"||c?.taskId||!L||L.status!=="active")return;const g=ee.current,z=s,_=L.id,E=n?`?projectId=${encodeURIComponent(n)}`:"",te=gs(`/api/agents/${encodeURIComponent(z)}/runs/${encodeURIComponent(_)}/logs/stream${E}`,{events:{"agent:log":he=>{if(ee.current===g)try{const ke=JSON.parse(he.data);j(Te=>[...Te,ke])}catch{}}},onOpen:()=>{ee.current===g&&N(!0)},onError:()=>{ee.current===g&&N(!1)}});return()=>{te(),ee.current===g&&N(!1)}},[p,c?.taskId,s,n,L]),t.useEffect(()=>{(Oe.current!==s||$e.current!==n)&&(Oe.current=s,$e.current=n,ee.current++,j([]),N(!1),pe(null),ve(null),ze(null),Fe.current=null,qe.current=!1)},[s,n]),t.useEffect(()=>{const g=n?`?projectId=${encodeURIComponent(n)}`:"",z=ee.current,_=E=>{if(ee.current===z)try{const te=JSON.parse(E.data);if(!te||typeof te!="object"||te.agentId!==s)return;fe()}catch{}};return gs(`/api/events${g}`,{events:{"agent:updated":E=>{if(ee.current===z)try{const te=JSON.parse(E.data);if(!te||typeof te!="object"||te.id!==s||qe.current)return;fe()}catch{}},"approval:requested":_,"approval:updated":_,"approval:decided":_}})},[s,n,fe]),t.useEffect(()=>{if(p!=="logs"||!c?.taskId){N(!1);return}const g=ee.current,z=c.taskId,_=n?`?projectId=${encodeURIComponent(n)}`:"",E=gs(`/api/tasks/${encodeURIComponent(z)}/logs/stream${_}`,{events:{"agent:log":te=>{if(ee.current===g)try{const he=JSON.parse(te.data);j(ke=>[...ke,he])}catch{}}},onOpen:()=>{ee.current===g&&N(!0)},onError:()=>{ee.current===g&&N(!1)}});return()=>{E(),ee.current===g&&N(!1)}},[c?.taskId,p,n]);const ce=async g=>{if(F||!Be.current)return;const z=Be.current.state;if(z!==g){R(!0),C(_=>_&&{..._,state:g});try{await qs(s,g,n),l(`Agent state updated to ${g}`,"success"),await Se()}catch(_){C(E=>E&&{...E,state:z}),l(`Failed to update state: ${K(_)}`,"error")}finally{R(!1)}}},me=async g=>{if(!S){Y(!1),Q(!0);try{const _=(await ps(void 0,n)).filter(se=>!Js(se)),E=_.filter(se=>g==="paused"?se.state==="active"||se.state==="running":se.state==="paused"),te=_.length-E.length;if(E.length===0){l(`No agents eligible to ${g==="paused"?"pause":"resume"}`,"error");return}if(!await y({title:g==="paused"?"Pause All Agents":"Resume All Agents",message:`${g==="paused"?"Pause":"Resume"} ${E.length} agent${E.length===1?"":"s"} in this project?`,danger:g==="paused"}))return;const ke=await Promise.allSettled(E.map(se=>qs(se.id,g,n))),Te=ke.map((se,_e)=>({result:se,agent:E[_e]})).filter(se=>se.result.status==="rejected"),Ce=ke.length-Te.length,Ke=Te.length,H=`${g==="paused"?"Paused":"Resumed"} ${Ce} agent${Ce===1?"":"s"}; skipped ${te}`;if(Ke>0){const se=Te.slice(0,3).map(({agent:_e,result:Le})=>`${_e.name||_e.id}: ${K(Le.reason)}`).join("; ");l(`${H}; failed ${Ke}${se?` (${se})`:""}`,"error")}else l(H,"success");await Se()}catch(z){l(`Failed to ${g==="paused"?"pause":"resume"} agents: ${K(z)}`,"error")}finally{Q(!1)}}},Pe=async()=>{if(!W){O(!0);try{await Vt(s,n,{source:"on_demand",triggerDetail:"Triggered from dashboard"}),l(`Heartbeat run started for ${c?.name??s}`,"success"),ne(g=>g+1)}catch(g){l(`Failed to start heartbeat run: ${K(g)}`,"error")}finally{O(!1)}}},ge=async()=>{if(!(!c||!await y({title:"Delete Agent",message:`Delete agent "${c.name}"? This cannot be undone.`,danger:!0})))try{await Jt(s,n),l(`Agent "${c.name}" deleted`,"success"),await Ie(!0),i()}catch(z){l(`Failed to delete agent: ${K(z)}`,"error")}},Ue=()=>c?_t(c):{label:"Unknown",icon:e.jsx(Ps,{size:14}),color:"var(--text-muted)",stateDerived:!1},we=()=>{c&&(navigator.clipboard.writeText(c.id),l("Agent ID copied to clipboard","success"))};if(J)return x?e.jsx("div",{className:"agent-detail-inline-loading",role:"region","aria-label":"Agent detail loading",children:e.jsxs("div",{className:"agent-detail-loading",children:[e.jsx(V,{className:"animate-spin",size:24}),e.jsx("span",{children:"Loading agent..."})]})}):e.jsx("div",{className:"agent-detail-overlay",onMouseDown:g=>{g.target===g.currentTarget&&(ye.current=!0)},onMouseUp:g=>{ye.current&&g.target===g.currentTarget&&i(),ye.current=!1},role:"dialog","aria-modal":"true",children:e.jsx("div",{className:"agent-detail-modal",ref:Ae,children:e.jsxs("div",{className:"agent-detail-loading",children:[e.jsx(V,{className:"animate-spin",size:24}),e.jsx("span",{children:"Loading agent..."})]})})});if(!c)return null;const Ee=Ls[c.state],je=Ue(),rs=x?"agent-detail-inline":"agent-detail-modal",os=$||h===0,cs=$||r===0;return e.jsx("div",{className:x?"agent-detail-inline-shell":"agent-detail-overlay",onClick:g=>!x&&g.target===g.currentTarget&&i(),role:x?"region":"dialog","aria-label":x?"Agent detail":void 0,"aria-modal":x?void 0:"true",children:e.jsxs("div",{className:rs,ref:Ae,children:[e.jsxs("div",{className:"agent-detail-header",children:[e.jsxs("div",{className:"agent-detail-identity",children:[x&&M?e.jsxs("button",{type:"button",className:"btn agent-detail-inline-back",onClick:i,"aria-label":"Back to agents",children:[e.jsx(ot,{size:16}),"Agents"]}):null,e.jsx("div",{className:"agent-detail-icon",children:e.jsx(ct,{agent:c,size:36})}),e.jsxs("div",{className:"agent-detail-info",children:[e.jsx("h2",{children:c.name}),e.jsxs("div",{className:"agent-detail-badges",children:[e.jsx("span",{className:"badge",style:{background:Ee.bg,color:Ee.text,border:`1px solid ${Ee.border}`},children:c.state}),e.jsxs("span",{className:"badge",style:{color:je.color},title:je.reason??je.label,children:[je.icon,!je.stateDerived&&je.label]})]})]})]}),e.jsxs("div",{className:"agent-detail-header-actions",children:[e.jsxs("div",{className:"agent-detail-controls",children:[c.state==="idle"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void ce("active"),disabled:F,children:[e.jsx(Cs,{size:14}),"Start"]}),e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void Pe(),"aria-label":`Run now for ${c.name}`,disabled:W||F,children:[e.jsx(vs,{size:14}),"Run Now"]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:ge,children:[e.jsx(bs,{size:14}),"Delete"]})]}),c.state==="active"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--compact agent-detail-mobile-icon-control",onClick:()=>void ce("paused"),disabled:F,"aria-label":"Pause",children:[e.jsx(Ws,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:"Pause"})]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:()=>void ce("paused"),disabled:F,"aria-label":"Stop",children:[e.jsx(Ve,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:"Stop"})]}),e.jsxs("button",{className:"btn btn-task-create btn--compact agent-detail-mobile-icon-control",onClick:()=>void Pe(),"aria-label":`Run now for ${c.name}`,disabled:W||F,children:[e.jsx(vs,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:"Run Now"})]})]}),c.state==="paused"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact agent-detail-mobile-icon-control",onClick:()=>void ce("active"),disabled:F,"aria-label":"Resume",children:[e.jsx(Cs,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:"Resume"})]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:ge,children:[e.jsx(bs,{size:14}),"Delete"]})]}),c.state==="running"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--compact agent-detail-mobile-icon-control",onClick:()=>void ce("paused"),disabled:F,"aria-label":"Pause",children:[e.jsx(Ws,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:"Pause"})]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:()=>void ce("paused"),disabled:F,"aria-label":"Stop",children:[e.jsx(Ve,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:"Stop"})]})]}),c.state==="error"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void ce("active"),disabled:F,children:[e.jsx(Cs,{size:14}),"Retry"]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:()=>void ce("paused"),disabled:F,"aria-label":"Stop",children:[e.jsx(Ve,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:"Stop"})]})]})]}),e.jsxs("div",{className:"agent-detail-utility-actions",children:[e.jsxs("div",{className:"agent-detail-bulk-menu",ref:is,children:[e.jsx("button",{type:"button",className:"btn-icon",onClick:()=>Y(g=>!g),"aria-haspopup":"menu","aria-expanded":T,"aria-label":"Bulk agent actions",title:"Bulk agent actions",disabled:F||S,children:e.jsx(zt,{size:16})}),T&&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 me("paused"),disabled:os||S,children:["Pause All Agents",e.jsx("span",{className:"agent-detail-bulk-menu-item-hint",children:$?"Loading eligible agents...":os?"No active agents eligible":`Pause ${h} active/running agent${h===1?"":"s"}`})]}),e.jsxs("button",{type:"button",role:"menuitem",className:"agent-detail-bulk-menu-item",onClick:()=>void me("active"),disabled:cs||S,children:["Resume All Agents",e.jsx("span",{className:"agent-detail-bulk-menu-item-hint",children:$?"Loading eligible agents...":cs?"No paused agents eligible":`Resume ${r} paused agent${r===1?"":"s"}`})]})]})]}),e.jsx("button",{className:"btn-icon",onClick:()=>void fe(),title:"Refresh","aria-label":"Refresh",children:e.jsx(Ns,{size:16})}),!x&&e.jsx("button",{className:"btn-icon",onClick:i,"aria-label":"Close",title:"Close",children:e.jsx(dt,{size:20})})]})]})]}),e.jsx("div",{className:"agent-detail-tabs",children:Ma.map(g=>e.jsxs("button",{className:ae("agent-detail-tab",p===g.id&&"active"),onClick:()=>m(g.id),children:[e.jsx(g.icon,{size:16}),g.label]},g.id))}),e.jsxs("div",{className:"agent-detail-content",children:[p==="dashboard"&&e.jsx($a,{agent:c,health:je,onChildClick:d,projectId:n}),p==="logs"&&e.jsx(Pa,{logs:D,isStreaming:I,hasTask:!!c.taskId||D.length>0||L!==null,fallbackLabel:!c.taskId&&L?`Latest run · ${L.id.slice(0,8)}`:null}),p==="mail"&&e.jsx(Da,{agent:c,mailbox:re,isLoading:ie,error:le,projectId:n,addToast:l,onRefresh:()=>void He()}),p==="runs"&&e.jsx(za,{addToast:l,agentId:c.id,projectId:n,agentState:c.state,agentName:c.name,initialRunId:v,preferActiveRun:A,runNowRefreshToken:k}),p==="tasks"&&e.jsx(Ia,{agentId:c.id,projectId:n,addToast:l}),p==="employees"&&e.jsx(Ga,{agentId:c.id,projectId:n,onChildClick:d}),p==="soul"&&e.jsx(_a,{agent:c,projectId:n,addToast:l,onSaved:Se}),p==="instructions"&&e.jsx(Ja,{agent:c,projectId:n,addToast:l,onSaved:Se}),p==="memory"&&e.jsx(Va,{agent:c,projectId:n,addToast:l,onSaved:Se}),p==="reflections"&&e.jsx(Ra,{agentId:c.id,projectId:n,addToast:l}),p==="config"&&e.jsx(qa,{agent:c,projectId:n,addToast:l,onSaved:Se,onHasChangesChange:ys,onDelete:ge,onAgentDraftApplied:g=>{C(z=>z&&{...z,...g})}},c.id)]}),!x&&e.jsxs("div",{className:"agent-detail-footer",children:[e.jsx("button",{className:"btn-icon",onClick:we,title:"Copy Agent ID",children:e.jsx(Ut,{})}),e.jsx("span",{className:"agent-detail-id",onClick:we,children:c.id}),c.taskId&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"divider",children:"|"}),e.jsx("span",{className:"text-muted",children:"Working on:"}),e.jsxs("a",{href:`/tasks/${c.taskId}`,className:"link",children:[c.taskId,e.jsx(ht,{size:12})]})]})]})]})})}function $a({agent:s,health:n,onChildClick:i,projectId:l}){const d=Ls[s.state],[x,M]=t.useState([]),[f,v]=t.useState(!0),[A,P]=t.useState(null),[c,C]=t.useState([]),[y,D]=t.useState(null),[j,J]=t.useState(null),[Z,p]=t.useState(!1),[m,I]=t.useState(null),N=typeof s.runtimeConfig?.runtimeHint=="string"?s.runtimeConfig.runtimeHint:"",F=(()=>{const h=s.runtimeConfig??{};if(N){const b=c.find(r=>r.runtimeId===N);return b?b.name:N}if(h.modelProvider&&h.modelId)return`${h.modelProvider}/${h.modelId}`;if(typeof h.model=="string"&&h.model.includes("/")){const b=h.model.indexOf("/");return h.model.slice(b+1)}return null})();t.useEffect(()=>{Es(s.id,l).then(P).catch(()=>P(null))},[s.id,l]),t.useEffect(()=>{ft(l).then(C).catch(()=>C([]))},[l]),t.useEffect(()=>{let h=!1;return v(!0),Wt(s.id,l).then(b=>{if(h)return;const r=b.length>0&&b[0]?.id===s.id?[...b].reverse():b;M(r)}).catch(()=>{h||M([])}).finally(()=>{h||v(!1)}),()=>{h=!0}},[s.id,l]);const R=t.useMemo(()=>{const h=s.completedRuns||[],b=new Date;b.setHours(0,0,0,0);const r=h.filter(k=>new Date(k.startedAt)>=b),o=h.filter(k=>k.status==="completed");return{totalRuns:h.length,todayRuns:r.length,successfulRuns:o.length,successRate:h.length>0?Math.round(o.length/h.length*100):0}},[s]),W=(s.completedRuns||[]).slice(0,5),O=Array.isArray(s.metadata?.skills)?s.metadata.skills:[],T=y?ws(y):null,Y=t.useCallback(async h=>{p(!0),I(null),J(null);try{const b=await qt(h,l);J(b)}catch(b){I(K(b))}finally{p(!1)}},[l]),S=t.useCallback(h=>{if(y===h){D(null),J(null),I(null),p(!1);return}D(h),Y(h)},[Y,y]),Q=s.state==="active"||s.state==="running",$=Gt(s.runtimeConfig?.heartbeatIntervalMs),q=Q&&s.lastHeartbeatAt?new Date(new Date(s.lastHeartbeatAt).getTime()+$).toISOString():null;return e.jsxs("div",{className:"dashboard-tab dashboard-summary-layout",children:[A?.isOverBudget&&e.jsxs("div",{className:"budget-warning-banner",role:"alert",children:[e.jsx("span",{children:"⚠️"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Budget Exhausted:"})," 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(Ps,{}),e.jsx("h3",{children:"Overview"}),e.jsx("strong",{children:s.name}),e.jsx("span",{className:"inline-badge",style:{background:d.bg,color:d.text},children:s.state})]}),e.jsxs("div",{className:"dashboard-summary-hero__meta",children:[e.jsxs("span",{className:"dashboard-summary-hero__health",title:n.reason??n.label,children:[n.icon," ",n.label]}),(s.pendingApprovalCount??0)>0?e.jsxs("span",{className:"badge agent-detail-approval-badge",title:"Pending approvals",children:[e.jsx("span",{className:"status-dot status-dot--pending"}),s.pendingApprovalCount," pending approvals"]}):null,e.jsxs("span",{children:["Role: ",s.role]}),e.jsxs("span",{children:[e.jsx("span",{className:"dashboard-summary-label",children:N?"Runtime":"Model"}),e.jsxs("span",{children:[" ",F??"Auto"]})]}),O.length>0?e.jsxs("span",{className:"dashboard-summary-skills",children:[e.jsx("span",{className:"dashboard-summary-label",children:"Skills"}),e.jsx("span",{className:"dashboard-summary-skill-badges",role:"list","aria-label":"Assigned skills",children:O.map(h=>{const b=y===h;return e.jsx("button",{type:"button",className:ae("badge","badge-skill","dashboard-summary-skill-badge","dashboard-summary-skill-badge-btn",b&&"dashboard-summary-skill-badge--selected"),title:h,onClick:()=>S(h),"aria-expanded":b,"aria-label":`View details for ${ws(h)}`,children:ws(h)},h)})})]}):e.jsx("span",{children:"Skills: —"})]}),y?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:T}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>S(y),children:[e.jsx(dt,{size:14}),"Close"]})]}),Z?e.jsxs("div",{className:"dashboard-summary-skill-detail-loading",role:"status","aria-live":"polite",children:[e.jsx(V,{size:14,className:"animate-spin"}),"Loading skill content..."]}):m?e.jsxs("div",{className:"dashboard-summary-skill-detail-error",role:"alert",children:[e.jsx(gt,{size:14}),e.jsx("span",{children:m}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void Y(y),children:"Retry"})]}):j?e.jsx("pre",{className:"dashboard-summary-skill-detail-content",children:j.skillMd||"(No SKILL.md found)"}):e.jsx("div",{className:"dashboard-summary-skill-detail-empty",children:"No skill content available"})]}):null]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:"Heartbeat & Health"}),e.jsxs("div",{className:"dashboard-summary-grid",children:[e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:"Last heartbeat"}),e.jsx("p",{children:s.lastHeartbeatAt?Je(s.lastHeartbeatAt):"Never"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:"Next expected"}),e.jsx("p",{children:q?Je(q):"Not scheduled"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:"Interval"}),e.jsx("p",{children:xt($)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:"Status"}),e.jsxs("p",{className:"dashboard-summary-health-row",children:[e.jsx("span",{className:ae("status-dot",s.state==="running"&&"status-dot--running")}),n.label,n.reason&&e.jsxs("span",{className:"text-secondary dashboard-summary-health-reason",title:n.reason,children:["(",n.reason,")"]})]})]})]})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:"Current Work"}),s.taskId?e.jsxs("div",{className:"current-task",children:[e.jsx("a",{href:`/tasks/${s.taskId}`,className:"task-badge",children:s.taskId}),e.jsxs("a",{href:`/tasks/${s.taskId}`,className:"btn btn-sm",children:["View Task ",e.jsx(ht,{size:14})]})]}):e.jsx("p",{className:"text-muted",children:"No active assignment"})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:"Recent Runs"}),e.jsxs("p",{className:"dashboard-summary-label",children:[R.successfulRuns,"/",R.totalRuns," successful (",R.successRate,"%)"]}),W.length===0?e.jsx("p",{className:"text-muted",children:"No runs yet"}):e.jsx("div",{className:"runs-list",children:W.map(h=>{const b=js[h.status]||js.terminated,r=b.icon;return e.jsxs("div",{className:"run-item",children:[e.jsx(r,{size:14,style:{color:b.color}}),e.jsx("span",{children:Je(h.startedAt)}),e.jsxs("span",{className:"text-muted",children:[Math.max(0,Math.round((new Date(h.endedAt||h.startedAt).getTime()-new Date(h.startedAt).getTime())/1e3)),"s"]})]},h.id)})})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:"Throughput"}),e.jsxs("div",{className:"stats-grid",children:[e.jsxs("div",{className:"stat-card",children:[e.jsx("div",{className:"stat-value",children:R.totalRuns}),e.jsx("div",{className:"stat-label",children:"Total Runs"})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("div",{className:"stat-value",children:R.todayRuns}),e.jsx("div",{className:"stat-label",children:"Runs Today"})]}),e.jsxs("div",{className:"stat-card",children:[e.jsxs("div",{className:"stat-value",children:[R.successRate,"%"]}),e.jsx("div",{className:"stat-label",children:"Success Rate"})]})]})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:"Chain of Command"}),f?e.jsxs("div",{className:"chain-of-command-loading",role:"status","aria-live":"polite",children:[e.jsx(V,{size:14,className:"animate-spin"}),e.jsx("span",{children:"Loading reporting chain..."})]}):x.length<=1?e.jsx("p",{className:"text-muted",children:"No reporting chain"}):e.jsx("div",{className:"chain-of-command-path","aria-label":"Chain of command",children:x.map((h,b)=>{const r=b===x.length-1,o=!r;return e.jsxs("div",{className:"chain-of-command-item",children:[e.jsx("button",{type:"button",className:`chain-of-command-node${r?" chain-of-command-node--current":""}`,onClick:()=>o&&i?.(h.id),disabled:!o||!i,title:r?"Current agent":`View ${h.name}`,children:h.name}),!r&&e.jsx("span",{className:"chain-of-command-separator","aria-hidden":"true",children:"→"})]},h.id)})})]})]})}function Pa({logs:s,isStreaming:n,hasTask:i,fallbackLabel:l}){return i?e.jsxs("div",{className:"logs-tab",children:[e.jsxs("div",{className:"logs-header",children:[e.jsxs("span",{className:"logs-count",children:[s.length," entries"]}),l&&e.jsx("span",{className:"text-muted logs-fallback-label",children:l}),n&&e.jsxs("span",{className:"streaming-indicator",children:[e.jsx("span",{className:"streaming-dot"}),"Live"]})]}),s.length===0?e.jsxs("div",{className:"logs-empty",children:[e.jsx(es,{size:48,opacity:.3}),e.jsx("p",{children:"No log entries yet"}),e.jsx("p",{className:"text-muted",children:n?"Waiting for activity...":"Logs will appear here when the agent is active"})]}):e.jsx(bt,{entries:s,loading:!1})]}):e.jsx("div",{className:"logs-tab",children:e.jsxs("div",{className:"logs-empty",children:[e.jsx(es,{size:48,opacity:.3}),e.jsx("p",{children:"No activity yet"}),e.jsx("p",{className:"text-muted",children:"Agent logs will appear here from the current task or most recent run"})]})})}function La(s){const n=new Date(s),l=new Date().getTime()-n.getTime(),d=Math.floor(l/6e4),x=Math.floor(l/36e5),M=Math.floor(l/864e5);return d<1?"Just now":d<60?`${d}m ago`:x<24?`${x}h ago`:M<7?`${M}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function fs(s,n,i){if(n==="user")return s==="dashboard"?"You":`User: ${s}`;if(n==="agent"){const l=i?.get(s)?.trim();return!l||l===s?`Agent: ${s}`:`Agent: ${l}`}return"System"}function Da({agent:s,mailbox:n,isLoading:i,error:l,projectId:d,addToast:x,onRefresh:M}){const[f,v]=t.useState("inbox"),[A,P]=t.useState([]);t.useEffect(()=>{let m=!1;return ps(void 0,d).then(I=>{m||P(I)}).catch(()=>{m||P([])}),()=>{m=!0}},[d]);const c=t.useMemo(()=>{const m=new Map;for(const N of A){if(!N.id)continue;const F=typeof N.name=="string"?N.name.trim():"";F.length>0&&m.set(N.id,F)}const I=typeof s.name=="string"?s.name.trim():"";return I.length>0&&m.set(s.id,I),m},[A,s.id,s.name]),[C,y]=t.useState(null),D=f==="inbox"?n?.inbox??[]:n?.outbox??[],j=C?D.find(m=>m.id===C)??null:null;t.useEffect(()=>{y(null)},[f,s.id]);const J=async m=>{if(y(m.id),!(f!=="inbox"||m.read))try{await fa(m.id,d),M()}catch(I){const N=`Failed to mark message as read: ${K(I)}`;x?x(N,"error"):console.warn(N)}},Z=()=>{y(null),M()},p=m=>e.jsxs("button",{type:"button",className:ae("mailbox-item","agent-mail-tab-message",f==="inbox"&&!m.read&&"unread",C===m.id&&"agent-mail-tab-message--selected"),onClick:()=>void J(m),"aria-pressed":C===m.id,children:[e.jsx("div",{className:"mailbox-item-avatar",children:(f==="inbox"?m.fromType:m.toType)==="agent"?e.jsx(Ps,{size:16}):e.jsx(la,{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:fs(m.fromId,m.fromType,c)}):e.jsxs("span",{className:"mailbox-item-to",children:["To: ",fs(m.toId,m.toType,c)]}),e.jsx("span",{className:"mailbox-item-time",children:La(m.createdAt)})]}),e.jsxs("div",{className:"mailbox-item-preview",children:[m.content.slice(0,80),m.content.length>80?"…":""]})]}),f==="inbox"&&!m.read?e.jsx("div",{className:"mailbox-item-unread-dot","aria-label":"Unread message"}):null]},m.id);return e.jsxs("div",{className:"agent-mail-tab",children:[e.jsxs("div",{className:"agent-mail-tab-header",children:[e.jsxs("h3",{children:[s.name," Mail"]}),e.jsxs("button",{className:"btn btn-sm",onClick:Z,disabled:i,children:[e.jsx(Ns,{size:14}),"Refresh"]})]}),e.jsxs("div",{className:"mailbox-agent-subtabs","data-testid":"agent-detail-mail-subtabs",children:[e.jsxs("button",{className:ae("btn","btn-sm","btn-secondary","mailbox-agent-subtab",f==="inbox"&&"active"),onClick:()=>v("inbox"),children:[e.jsx(Gs,{size:12}),e.jsx("span",{children:"Inbox"}),(n?.unreadCount??0)>0?e.jsx("span",{className:"mailbox-tab-badge",children:n?.unreadCount}):null]}),e.jsxs("button",{className:ae("btn","btn-sm","btn-secondary","mailbox-agent-subtab",f==="outbox"&&"active"),onClick:()=>v("outbox"),children:[e.jsx(Ks,{size:12}),e.jsx("span",{children:"Outbox"})]})]}),i&&!n?e.jsxs("div",{className:"agent-detail-loading agent-detail-loading--inline",role:"status","aria-live":"polite",children:[e.jsx(V,{className:"animate-spin",size:16}),e.jsx("span",{children:"Loading mailbox..."})]}):null,!i&&l?e.jsxs("div",{className:"agent-mail-tab-error",role:"alert",children:[e.jsx(gt,{size:16}),e.jsxs("span",{children:["Failed to load mailbox: ",l]})]}):null,!i&&!l?j?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:()=>y(null),children:[e.jsx(ot,{size:14}),"Back to ",f==="inbox"?"Inbox":"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:"From"}),e.jsx("span",{children:fs(j.fromId,j.fromType,c)})]}),e.jsxs("div",{className:"agent-mail-tab-detail-row",children:[e.jsx("span",{className:"agent-mail-tab-detail-label",children:"To"}),e.jsx("span",{children:fs(j.toId,j.toType,c)})]}),e.jsxs("div",{className:"agent-mail-tab-detail-row",children:[e.jsx("span",{className:"agent-mail-tab-detail-label",children:"Type"}),e.jsx("span",{children:j.type})]}),e.jsxs("div",{className:"agent-mail-tab-detail-row",children:[e.jsx("span",{className:"agent-mail-tab-detail-label",children:"Sent"}),e.jsx("span",{children:new Date(j.createdAt).toLocaleString()})]}),j.metadata?.replyTo?.messageId?e.jsxs("div",{className:"agent-mail-tab-reply-context",children:["↪ Replying to message ",j.metadata.replyTo.messageId]}):null]}),e.jsx("div",{className:"agent-mail-tab-detail-body",children:j.content})]}):e.jsx("div",{className:"mailbox-list","data-testid":"agent-detail-mail-list",children:D.length===0?e.jsxs("div",{className:"mailbox-empty","data-testid":"agent-detail-mail-empty",children:[f==="inbox"?e.jsx(Gs,{size:32}):e.jsx(Ks,{size:32}),e.jsx("p",{children:f==="inbox"?"No received messages for this agent":"No sent messages for this agent"})]}):D.map(p)}):null]})}function za({addToast:s,agentId:n,projectId:i,agentState:l,agentName:d,initialRunId:x,preferActiveRun:M,runNowRefreshToken:f}){const[v,A]=t.useState([]),{confirm:P}=it(),[c,C]=t.useState(!0),[y,D]=t.useState(null),[j,J]=t.useState([]),[Z,p]=t.useState(!1),[m,I]=t.useState(null),[N,F]=t.useState(!1),R=t.useRef(!1),W=t.useRef(!1),O=t.useCallback(async()=>{try{const o=await lt(n,50,i);A(o)}catch(o){s(`Failed to load runs: ${K(o)}`,"error")}finally{C(!1)}},[n,i,s]);t.useEffect(()=>{O()},[O]),t.useEffect(()=>{if(!W.current){W.current=!0;return}C(!0),O()},[O,f]);const T=v.some(o=>o.status==="active"),Y=y?v.find(o=>o.id===y)?.status:void 0;t.useEffect(()=>{if(!T)return;const o=setInterval(()=>{O()},5e3);return()=>clearInterval(o)},[T,O]),t.useEffect(()=>{if(!y||Y!=="active")return;const o=i?`?projectId=${encodeURIComponent(i)}`:"";return gs(`/api/agents/${encodeURIComponent(n)}/runs/${encodeURIComponent(y)}/logs/stream${o}`,{events:{"agent:log":k=>{try{const ne=JSON.parse(k.data);J(L=>[...L,ne])}catch{}}}})},[y,Y,n,i]);const S=t.useCallback(async o=>{if(y===o){D(null),J([]),I(null);return}D(o),p(!0),F(!0),J([]),I(null);try{const[k,ne]=await Promise.all([rt(n,o,i),Yt(n,o,i)]);J(k),I(ne)}catch(k){s(`Failed to load run details: ${K(k)}`,"error"),J([]),I(null)}finally{p(!1),F(!1)}},[y,n,i,s]);t.useEffect(()=>{R.current=!1},[n,x,M]),t.useEffect(()=>{if(v.length===0||c||R.current)return;const o=x?v.find(k=>k.id===x):M?v.find(k=>k.status==="active"):null;R.current=!0,o&&S(o.id)},[x,M,v,c,S]);const Q=async()=>{if(await P({title:"Stop Active Run",message:"Stop the active run? The agent's work will be interrupted.",danger:!0}))try{await ra(n,i),s("Run stopped","success"),C(!0),O()}catch(k){s(`Failed to stop run: ${K(k)}`,"error")}};if(c&&v.length===0)return e.jsx("div",{className:"runs-tab",children:e.jsxs("div",{className:"runs-loading-row",children:[e.jsx(V,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading runs..."})]})});if(v.length===0)return e.jsx("div",{className:"runs-tab",children:e.jsxs("div",{className:"runs-empty",children:[e.jsx(vs,{size:48,opacity:.3}),e.jsx("p",{children:"No runs yet"}),e.jsx("p",{className:"text-muted",children:"Heartbeat runs will appear here"})]})});const $=[...v].sort((o,k)=>new Date(k.startedAt).getTime()-new Date(o.startedAt).getTime()),q=$.filter(o=>o.status==="active"),h=$.filter(o=>o.status!=="active"),b=o=>o?e.jsxs("div",{className:"run-usage",children:[e.jsxs("span",{children:["Input: ",o.inputTokens.toLocaleString()]}),e.jsxs("span",{children:["Output: ",o.outputTokens.toLocaleString()]}),o.cachedTokens>0&&e.jsxs("span",{children:["Cached: ",o.cachedTokens.toLocaleString()]})]}):null,r=(o,k,ne)=>{const L=js[o.status]||js.completed,pe=L.icon,re=o.endedAt?Ba(new Date(o.startedAt),new Date(o.endedAt)):"In progress",ve=y===o.id;return e.jsxs("div",{children:[e.jsxs("div",{className:ae("run-card",ne&&"run-card--active",ve&&"run-card--selected","run-card--clickable"),onClick:()=>void S(o.id),role:"button",tabIndex:0,"aria-expanded":ve,"aria-label":`${ne?"Active":""} run ${o.id.slice(0,8)}, ${o.status}`,onKeyDown:ie=>{(ie.key==="Enter"||ie.key===" ")&&(ie.preventDefault(),S(o.id))},children:[e.jsxs("div",{className:"run-header",children:[e.jsxs("div",{className:"run-header-group",children:[ve?e.jsx(at,{size:14}):e.jsx(nt,{size:14}),ne?e.jsxs("span",{className:"run-live-indicator",children:[e.jsx("span",{className:"live-dot"}),"Live Run"]}):e.jsxs("span",{className:"run-id",children:["#",k+1," ",o.id.slice(0,8)]})]}),e.jsxs("div",{className:"run-header-group",children:[o.invocationSource&&e.jsx("span",{className:"badge run-badge--compact",children:o.invocationSource}),ne&&e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:ie=>{ie.preventDefault(),ie.stopPropagation(),Q()},"aria-label":"Stop active run",children:[e.jsx(Ve,{size:12})," Stop"]}),e.jsxs("span",{className:ae("run-status",o.status),children:[e.jsx(pe,{size:14,style:{color:L.color}}),o.status]}),o.heartbeatProcedureSource==="custom"&&e.jsx("span",{className:"badge run-badge--compact",children:"Heartbeat: custom"})]})]}),e.jsxs("div",{className:"run-details",children:[e.jsxs("span",{children:["Started ",Je(o.startedAt)]}),e.jsx("span",{children:"•"}),e.jsx("span",{children:re}),o.triggerDetail&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsx("span",{className:"text-muted",children:o.triggerDetail})]})]})]}),ve&&e.jsxs("div",{className:"run-logs-container",children:[N?e.jsxs("div",{className:"run-details-loading-state",children:[e.jsx(V,{size:14,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading details..."})]}):m&&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:"System Prompt"}),m.systemPrompt?e.jsx("pre",{className:"run-output-panel",children:m.systemPrompt}):e.jsx("div",{className:"text-muted run-output-empty",children:"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:"Execution Prompt"}),m.executionPrompt?e.jsx("pre",{className:"run-output-panel",children:m.executionPrompt}):e.jsx("div",{className:"text-muted run-output-empty",children:"Execution prompt not captured for this run"})]})}),m.usageJson&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:"Token Usage"}),b(m.usageJson)]}),m.stdoutExcerpt&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:"Output"}),e.jsx("pre",{className:"run-output-panel",children:m.stdoutExcerpt.length>2e3?`${m.stdoutExcerpt.slice(0,2e3)}
16
+ */const Na=[["path",{d:"M16 17h6v-6",key:"t6n2it"}],["path",{d:"m22 17-8.5-8.5-5 5L2 7",key:"x473p"}]],ya=$s("trending-down",Na);function Zs(s){return s<1e3?`${s}ms`:s<6e4?`${(s/1e3).toFixed(1)}s`:s<36e5?`${Math.floor(s/6e4)}m`:`${(s/36e5).toFixed(1)}h`}function Sa(s){return`${Math.round(s*100)}%`}function Xs(s){const n=Date.now(),i=new Date(s).getTime(),l=n-i;if(l<0){const d=Math.abs(l);return d<6e4?"in a moment":d<36e5?`in ${Math.floor(d/6e4)}m`:d<864e5?`in ${Math.floor(d/36e5)}h`:`in ${Math.floor(d/864e5)}d`}return l<6e4?"just now":l<36e5?`${Math.floor(l/6e4)}m ago`:l<864e5?`${Math.floor(l/36e5)}h ago`:`${Math.floor(l/864e5)}d ago`}function ka(s){switch(s){case"periodic":return"Periodic";case"post-task":return"Post-Task";case"manual":return"Manual";case"user-requested":return"User Requested";default:return s}}function Xe(s){return s instanceof Error&&s.message?s.message:String(s)}function Ca(s){switch(s){case"improving":return"↑ Improving";case"declining":return"↓ Declining";case"stable":return"→ Stable";default:return"Insufficient data"}}function wa(s){switch(s){case"improving":return"trend-improving";case"declining":return"trend-declining";case"stable":return"trend-stable";default:return"trend-insufficient"}}function Qs(s,n=5){return e.jsx("span",{className:"rating-stars",children:Array.from({length:n},(i,l)=>e.jsx(jt,{size:14,className:l<s?"star-filled":"star-empty",fill:l<s?"currentColor":"none"},l))})}function Ra({agentId:s,projectId:n,addToast:i}){const[l,d]=t.useState([]),[x,M]=t.useState(null),[f,v]=t.useState(null),[A,P]=t.useState([]),[c,C]=t.useState(!0),[y,D]=t.useState(!0),[j,J]=t.useState(!1),[Z,p]=t.useState(!1),[m,I]=t.useState(null),[N,F]=t.useState(0),[R,W]=t.useState(""),[O,T]=t.useState(""),Y=t.useCallback(async()=>{try{const[r,o]=await Promise.all([Ct(s,20,n),wt(s,void 0,n)]);d(r),M(o)}catch(r){i(`Failed to load reflections: ${Xe(r)}`,"error")}finally{C(!1)}},[s,n,i]),S=t.useCallback(async()=>{try{const[r,o]=await Promise.all([Rt(s,n),Mt(s,{limit:50},n)]);v(r),P(o)}catch(r){i(`Failed to load ratings: ${Xe(r)}`,"error")}finally{D(!1)}},[s,n,i]);t.useEffect(()=>{Y(),S()},[Y,S]);const Q=async()=>{J(!0);try{if(!await Ft(s,n)){i("Not enough history to generate a reflection yet","error");return}i("Reflection generated successfully","success"),C(!0),await Y()}catch(r){const o=Xe(r),k=o.toLowerCase();k.includes("agent not found")||k.includes("not found")?i("This agent is no longer available. It may have been deleted.","error"):k.includes("insufficient history")?i("Not enough history to generate a reflection yet","error"):i(`Failed to generate reflection: ${o}`,"error")}finally{J(!1)}},$=async r=>{if(r.preventDefault(),N!==0){p(!0);try{await Et(s,{score:N,category:R||void 0,comment:O||void 0,raterType:"user"},n),F(0),W(""),T(""),i("Rating added","success"),await S()}catch(o){i(`Failed to add rating: ${Xe(o)}`,"error")}finally{p(!1)}}},G=async r=>{try{await Tt(s,r,n),i("Rating deleted","success"),await S()}catch(o){i(`Failed to delete rating: ${Xe(o)}`,"error")}},h=r=>{I(o=>o===r?null:r)};if(c&&y)return e.jsx("div",{className:"reflections-tab",children:e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(V,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading evaluation..."})]})});const b=x&&x.totalTasksCompleted===0&&x.totalTasksFailed===0&&x.recentReflectionCount===0;return e.jsxs("div",{className:"reflections-tab",children:[e.jsxs("div",{className:"reflections-header",children:[e.jsxs("h3",{children:[e.jsx(xs,{size:16}),"Performance, Reflections & Ratings"]}),e.jsx("button",{className:"btn btn-secondary",onClick:Q,disabled:j,title:"Generate a manual reflection",children:j?e.jsxs(e.Fragment,{children:[e.jsx(V,{size:14,className:"animate-spin"}),"Reflecting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ns,{size:14}),"Reflect Now"]})})]}),x&&!b&&e.jsxs("div",{className:"reflections-stats-grid",children:[e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(Vs,{size:16,style:{color:"var(--color-success)"}}),x.totalTasksCompleted]}),e.jsx("div",{className:"stat-label",children:"Tasks Completed"})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(ya,{size:16,style:{color:"var(--color-error)"}}),x.totalTasksFailed]}),e.jsx("div",{className:"stat-label",children:"Tasks Failed"})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(At,{size:16,style:{color:"var(--in-progress)"}}),Zs(x.avgDurationMs)]}),e.jsx("div",{className:"stat-label",children:"Avg Duration"})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(xs,{size:16,style:{color:x.successRate>=.8?"var(--color-success)":x.successRate>=.5?"var(--color-warning)":"var(--color-error)"}}),Sa(x.successRate)]}),e.jsx("div",{className:"stat-label",children:"Success Rate"})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(ks,{size:16,style:{color:"var(--color-info)"}}),x.recentReflectionCount]}),e.jsx("div",{className:"stat-label",children:"Reflections"})]})]}),b&&e.jsxs("div",{className:"reflections-no-data",children:[e.jsx(xs,{size:24,opacity:.3}),e.jsx("p",{children:"No performance data yet"})]}),e.jsxs("div",{className:"reflections-ratings-section",children:[e.jsx("h4",{children:"User Ratings"}),y?e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(V,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"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)}),Qs(Math.round(f.averageScore))]}),e.jsxs("div",{className:"rating-stats",children:[e.jsxs("span",{className:"rating-count",children:[f.totalRatings," ratings"]}),e.jsx("span",{className:`rating-trend-badge ${wa(f.trend)}`,children:Ca(f.trend)})]})]}),f&&Object.keys(f.categoryAverages).length>0&&e.jsxs("div",{className:"category-breakdown",children:[e.jsx("h4",{children:"Category Averages"}),Object.entries(f.categoryAverages).map(([r,o])=>e.jsxs("div",{className:"category-item",children:[e.jsx("span",{className:"category-name",children:r}),e.jsx("span",{className:"category-score",children:o.toFixed(1)})]},r))]}),e.jsxs("form",{className:"add-rating-form",onSubmit:$,children:[e.jsx("h4",{children:"Add Rating"}),e.jsx("div",{className:"star-selector",children:[1,2,3,4,5].map(r=>e.jsx("button",{type:"button",className:"star-btn touch-target",onClick:()=>F(r),title:`${r} star${r>1?"s":""}`,children:e.jsx(jt,{size:24,fill:r<=N?"currentColor":"none",className:r<=N?"star-filled":"star-empty"})},r))}),e.jsxs("select",{value:R,onChange:r=>W(r.target.value),className:"select add-rating-category-select",children:[e.jsx("option",{value:"",children:"Select category..."}),e.jsx("option",{value:"quality",children:"Quality"}),e.jsx("option",{value:"speed",children:"Speed"}),e.jsx("option",{value:"communication",children:"Communication"}),e.jsx("option",{value:"reliability",children:"Reliability"}),e.jsx("option",{value:"other",children:"Other"})]}),e.jsx("textarea",{value:O,onChange:r=>T(r.target.value),placeholder:"Optional comment...",className:"input add-rating-comment-input",rows:3}),e.jsx("button",{type:"submit",className:"btn btn-task-create",disabled:N===0||Z,children:Z?"Submitting...":"Submit Rating"})]}),e.jsxs("div",{className:"rating-history",children:[e.jsx("h4",{children:"Rating History"}),A.length===0?e.jsx("p",{className:"no-ratings",children:"No ratings yet"}):A.map(r=>e.jsxs("div",{className:"rating-history-item",children:[e.jsxs("div",{className:"rating-item-header",children:[Qs(r.score),r.category&&e.jsx("span",{className:"rating-category-badge",children:r.category}),e.jsx("span",{className:"rating-time",children:Xs(r.createdAt)}),e.jsx("button",{type:"button",className:"rating-delete-btn touch-target",onClick:()=>void G(r.id),title:"Delete rating",children:e.jsx(bs,{size:14})})]}),r.comment&&e.jsx("p",{className:"rating-comment",children:r.comment})]},r.id))]})]})]}),e.jsxs("div",{className:"reflections-list",children:[e.jsx("h4",{children:"Reflection History"}),c?e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(V,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading reflections..."})]}):l.length===0?e.jsxs("div",{className:"reflection-empty",children:[e.jsx(ks,{size:32,opacity:.3}),e.jsx("p",{children:"No reflections yet"}),e.jsx("p",{className:"text-secondary",children:"Trigger a reflection to get started"})]}):e.jsx("div",{className:"reflection-cards",children:l.map(r=>{const o=m===r.id;return e.jsxs("div",{className:`reflection-card ${o?"reflection-card--expanded":""}`,onClick:()=>h(r.id),role:"button",tabIndex:0,onKeyDown:k=>k.key==="Enter"&&h(r.id),children:[e.jsxs("div",{className:"reflection-card-header",children:[e.jsx("span",{className:`reflection-trigger-badge reflection-trigger-${r.trigger}`,children:ka(r.trigger)}),e.jsx("span",{className:"reflection-timestamp",children:Xs(r.timestamp)}),e.jsx("span",{className:"reflection-chevron",children:o?e.jsx(at,{size:16}):e.jsx(nt,{size:16})})]}),e.jsx("div",{className:"reflection-summary",children:r.summary}),o&&e.jsxs("div",{className:"reflection-details",children:[r.insights.length>0&&e.jsxs("div",{className:"reflection-insights",children:[e.jsxs("h5",{children:[e.jsx(ks,{size:14})," Insights"]}),e.jsx("ul",{children:r.insights.map((k,ne)=>e.jsx("li",{children:k},ne))})]}),r.suggestedImprovements.length>0&&e.jsxs("div",{className:"reflection-suggestions",children:[e.jsxs("h5",{children:[e.jsx(Vs,{size:14})," Suggested Improvements"]}),e.jsx("ul",{children:r.suggestedImprovements.map((k,ne)=>e.jsx("li",{children:k},ne))})]}),r.metrics&&e.jsxs("div",{className:"reflection-metrics",children:[e.jsx("h5",{children:"Metrics"}),e.jsxs("div",{className:"metrics-grid",children:[r.metrics.tasksCompleted!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:"Tasks:"}),e.jsx("span",{className:"metric-value",children:r.metrics.tasksCompleted})]}),r.metrics.tasksFailed!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:"Failed:"}),e.jsx("span",{className:"metric-value",children:r.metrics.tasksFailed})]}),r.metrics.avgDurationMs!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:"Avg Duration:"}),e.jsx("span",{className:"metric-value",children:Zs(r.metrics.avgDurationMs)})]}),r.metrics.errorCount!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:"Errors:"}),e.jsx("span",{className:"metric-value",children:r.metrics.errorCount})]})]})]})]})]},r.id)})})]})]})}function ae(...s){return s.filter(Boolean).join(" ")}function Je(s){const n=Date.now(),i=new Date(s).getTime(),l=n-i;if(l<0){const d=Math.abs(l);return d<6e4?"in a moment":d<36e5?`in ${Math.floor(d/6e4)}m`:d<864e5?`in ${Math.floor(d/36e5)}h`:`in ${Math.floor(d/864e5)}d`}return l<6e4?"just now":l<36e5?`${Math.floor(l/6e4)}m ago`:l<864e5?`${Math.floor(l/36e5)}h ago`:`${Math.floor(l/864e5)}d ago`}const Ma=[{id:"dashboard",label:"Dashboard",icon:ja},{id:"logs",label:"Logs",icon:es},{id:"mail",label:"Mail",icon:Bt},{id:"runs",label:"Runs",icon:vs},{id:"tasks",label:"Tasks",icon:ut},{id:"employees",label:"Employees",icon:mt},{id:"soul",label:"Soul",icon:Ot},{id:"instructions",label:"Instructions",icon:Ht},{id:"memory",label:"Agent Memory",icon:es},{id:"reflections",label:"Evaluation",icon:xs},{id:"config",label:"Settings",icon:It}],Ls={idle:{bg:"var(--state-idle-bg)",text:"var(--state-idle-text)",border:"var(--state-idle-border)"},active:{bg:"var(--state-active-bg)",text:"var(--state-active-text)",border:"var(--state-active-border)"},running:{bg:"var(--state-active-bg)",text:"var(--state-active-text)",border:"var(--state-active-border)"},paused:{bg:"var(--state-paused-bg)",text:"var(--state-paused-text)",border:"var(--state-paused-border)"},error:{bg:"var(--state-error-bg)",text:"var(--state-error-text)",border:"var(--state-error-border)"}},js={completed:{icon:ue,color:"var(--color-success)"},failed:{icon:Kt,color:"var(--color-error)"},active:{icon:V,color:"var(--in-progress)"},terminated:{icon:Ve,color:"var(--text-muted)"}},et={"long-term":"Long-term",daily:"Daily",dreams:"Dreams"},Aa={"long-term":"Curated durable decisions, conventions, constraints, and pitfalls for this specific agent.",daily:"Raw daily observations and open loops recorded by this agent.",dreams:"Synthesized patterns and emerging themes distilled from this agent's daily memory."},Fa=xt(Ts),Ea=700;function Ta(s,n){return s.some(i=>i.path===n)?n:s.find(i=>i.layer==="long-term")?.path??s[0]?.path??""}function en({agentId:s,projectId:n,onClose:i,addToast:l,onChildClick:d,inline:x=!1,showInlineBackButton:M=!1,initialTab:f,initialRunId:v,preferActiveRun:A=!1,onMutationSuccess:P}){const[c,C]=t.useState(null),{confirm:y}=it(),[D,j]=t.useState([]),[J,Z]=t.useState(!0),[p,m]=t.useState(f??"dashboard"),[I,N]=t.useState(!1),[F,R]=t.useState(!1),[W,O]=t.useState(!1),[T,Y]=t.useState(!1),[S,Q]=t.useState(!1),[$,G]=t.useState(!1),[h,b]=t.useState(0),[r,o]=t.useState(0),[k,ne]=t.useState(0),[L,pe]=t.useState(null),[re,ve]=t.useState(null),[ie,U]=t.useState(!1),[le,ze]=t.useState(null),Ae=t.useRef(null),is=t.useRef(null),ye=t.useRef(!1);$t(Ae,!x,"fusion:agent-detail-modal-size");const We=t.useRef(i),ls=t.useRef(l),Be=t.useRef(null),Ge=t.useRef(!1),Fe=t.useRef(null),ee=t.useRef(0),Oe=t.useRef(s),$e=t.useRef(n);We.current=i,ls.current=l,Be.current=c;const fe=t.useCallback(async()=>{Be.current===null&&Z(!0);try{const z=await Pt(s,n);C(z)}catch(z){ls.current(`Failed to load agent: ${K(z)}`,"error"),We.current()}finally{Z(!1)}},[s,n]),qe=t.useCallback(async()=>{const g=ee.current,z=s,_=n,E=()=>ee.current!==g||s!==z||n!==_;try{if(c?.taskId){pe(null),Fe.current=null;const Te=await Lt(c.taskId,_,{limit:100});if(E())return;j(Te.entries);return}const te=await lt(z,1,_);if(E())return;const he=te[0]??null;if(pe(he),!he){Fe.current=null,j([]);return}if(Fe.current===he.id)return;const ke=await rt(z,he.id,_);if(E())return;j(ke),Fe.current=he.id}catch(te){if(E())return;console.error("Failed to load agent logs:",te)}},[c?.taskId,s,n]),He=t.useCallback(async()=>{U(!0),ze(null);try{const g=await Dt(s,n);ve(g)}catch(g){ze(K(g)),ve(null)}finally{U(!1)}},[s,n]),ys=t.useCallback(g=>{Ge.current=g},[]),Ie=t.useCallback(async(g=!1)=>{await P?.({agentId:s,deleted:g})},[s,P]),Se=t.useCallback(async()=>{await fe(),await Ie(!1)},[fe,Ie]);t.useEffect(()=>{fe()},[fe]),t.useEffect(()=>{const g=setInterval(()=>{fe()},3e4);return()=>{clearInterval(g)}},[fe]),t.useEffect(()=>{c&&p==="logs"&&qe()},[c,p,qe]),t.useEffect(()=>{p!=="logs"&&(Fe.current=null)},[p]),t.useEffect(()=>{c&&p==="mail"&&He()},[c,p,He]),t.useEffect(()=>{if(!T)return;const g=_=>{is.current?.contains(_.target)||Y(!1)},z=_=>{_.key==="Escape"&&Y(!1)};return document.addEventListener("mousedown",g),document.addEventListener("keydown",z),()=>{document.removeEventListener("mousedown",g),document.removeEventListener("keydown",z)}},[T]),t.useEffect(()=>{if(!T)return;let g=!1;return G(!0),ps(void 0,n).then(z=>{if(g)return;const _=z.filter(E=>!Js(E));b(_.filter(E=>E.state==="active"||E.state==="running").length),o(_.filter(E=>E.state==="paused").length)}).catch(()=>{g||(b(0),o(0))}).finally(()=>{g||G(!1)}),()=>{g=!0}},[T,n]),t.useEffect(()=>{if(p!=="logs"||c?.taskId||!L||L.status!=="active")return;const g=ee.current,z=s,_=L.id,E=n?`?projectId=${encodeURIComponent(n)}`:"",te=gs(`/api/agents/${encodeURIComponent(z)}/runs/${encodeURIComponent(_)}/logs/stream${E}`,{events:{"agent:log":he=>{if(ee.current===g)try{const ke=JSON.parse(he.data);j(Te=>[...Te,ke])}catch{}}},onOpen:()=>{ee.current===g&&N(!0)},onError:()=>{ee.current===g&&N(!1)}});return()=>{te(),ee.current===g&&N(!1)}},[p,c?.taskId,s,n,L]),t.useEffect(()=>{(Oe.current!==s||$e.current!==n)&&(Oe.current=s,$e.current=n,ee.current++,j([]),N(!1),pe(null),ve(null),ze(null),Fe.current=null,Ge.current=!1)},[s,n]),t.useEffect(()=>{const g=n?`?projectId=${encodeURIComponent(n)}`:"",z=ee.current,_=E=>{if(ee.current===z)try{const te=JSON.parse(E.data);if(!te||typeof te!="object"||te.agentId!==s)return;fe()}catch{}};return gs(`/api/events${g}`,{events:{"agent:updated":E=>{if(ee.current===z)try{const te=JSON.parse(E.data);if(!te||typeof te!="object"||te.id!==s||Ge.current)return;fe()}catch{}},"approval:requested":_,"approval:updated":_,"approval:decided":_}})},[s,n,fe]),t.useEffect(()=>{if(p!=="logs"||!c?.taskId){N(!1);return}const g=ee.current,z=c.taskId,_=n?`?projectId=${encodeURIComponent(n)}`:"",E=gs(`/api/tasks/${encodeURIComponent(z)}/logs/stream${_}`,{events:{"agent:log":te=>{if(ee.current===g)try{const he=JSON.parse(te.data);j(ke=>[...ke,he])}catch{}}},onOpen:()=>{ee.current===g&&N(!0)},onError:()=>{ee.current===g&&N(!1)}});return()=>{E(),ee.current===g&&N(!1)}},[c?.taskId,p,n]);const ce=async g=>{if(F||!Be.current)return;const z=Be.current.state;if(z!==g){R(!0),C(_=>_&&{..._,state:g});try{await Gs(s,g,n),l(`Agent state updated to ${g}`,"success"),await Se()}catch(_){C(E=>E&&{...E,state:z}),l(`Failed to update state: ${K(_)}`,"error")}finally{R(!1)}}},me=async g=>{if(!S){Y(!1),Q(!0);try{const _=(await ps(void 0,n)).filter(se=>!Js(se)),E=_.filter(se=>g==="paused"?se.state==="active"||se.state==="running":se.state==="paused"),te=_.length-E.length;if(E.length===0){l(`No agents eligible to ${g==="paused"?"pause":"resume"}`,"error");return}if(!await y({title:g==="paused"?"Pause All Agents":"Resume All Agents",message:`${g==="paused"?"Pause":"Resume"} ${E.length} agent${E.length===1?"":"s"} in this project?`,danger:g==="paused"}))return;const ke=await Promise.allSettled(E.map(se=>Gs(se.id,g,n))),Te=ke.map((se,_e)=>({result:se,agent:E[_e]})).filter(se=>se.result.status==="rejected"),Ce=ke.length-Te.length,Ke=Te.length,H=`${g==="paused"?"Paused":"Resumed"} ${Ce} agent${Ce===1?"":"s"}; skipped ${te}`;if(Ke>0){const se=Te.slice(0,3).map(({agent:_e,result:Le})=>`${_e.name||_e.id}: ${K(Le.reason)}`).join("; ");l(`${H}; failed ${Ke}${se?` (${se})`:""}`,"error")}else l(H,"success");await Se()}catch(z){l(`Failed to ${g==="paused"?"pause":"resume"} agents: ${K(z)}`,"error")}finally{Q(!1)}}},Pe=async()=>{if(!W){O(!0);try{await Vt(s,n,{source:"on_demand",triggerDetail:"Triggered from dashboard"}),l(`Heartbeat run started for ${c?.name??s}`,"success"),ne(g=>g+1)}catch(g){l(`Failed to start heartbeat run: ${K(g)}`,"error")}finally{O(!1)}}},ge=async()=>{if(!(!c||!await y({title:"Delete Agent",message:`Delete agent "${c.name}"? This cannot be undone.`,danger:!0})))try{await Jt(s,n),l(`Agent "${c.name}" deleted`,"success"),await Ie(!0),i()}catch(z){l(`Failed to delete agent: ${K(z)}`,"error")}},Ue=()=>c?_t(c):{label:"Unknown",icon:e.jsx(Ps,{size:14}),color:"var(--text-muted)",stateDerived:!1},we=()=>{c&&(navigator.clipboard.writeText(c.id),l("Agent ID copied to clipboard","success"))};if(J)return x?e.jsx("div",{className:"agent-detail-inline-loading",role:"region","aria-label":"Agent detail loading",children:e.jsxs("div",{className:"agent-detail-loading",children:[e.jsx(V,{className:"animate-spin",size:24}),e.jsx("span",{children:"Loading agent..."})]})}):e.jsx("div",{className:"agent-detail-overlay",onMouseDown:g=>{g.target===g.currentTarget&&(ye.current=!0)},onMouseUp:g=>{ye.current&&g.target===g.currentTarget&&i(),ye.current=!1},role:"dialog","aria-modal":"true",children:e.jsx("div",{className:"agent-detail-modal",ref:Ae,children:e.jsxs("div",{className:"agent-detail-loading",children:[e.jsx(V,{className:"animate-spin",size:24}),e.jsx("span",{children:"Loading agent..."})]})})});if(!c)return null;const Ee=Ls[c.state],je=Ue(),rs=x?"agent-detail-inline":"agent-detail-modal",os=$||h===0,cs=$||r===0;return e.jsx("div",{className:x?"agent-detail-inline-shell":"agent-detail-overlay",onClick:g=>!x&&g.target===g.currentTarget&&i(),role:x?"region":"dialog","aria-label":x?"Agent detail":void 0,"aria-modal":x?void 0:"true",children:e.jsxs("div",{className:rs,ref:Ae,children:[e.jsxs("div",{className:"agent-detail-header",children:[e.jsxs("div",{className:"agent-detail-identity",children:[x&&M?e.jsxs("button",{type:"button",className:"btn agent-detail-inline-back",onClick:i,"aria-label":"Back to agents",children:[e.jsx(ot,{size:16}),"Agents"]}):null,e.jsx("div",{className:"agent-detail-icon",children:e.jsx(ct,{agent:c,size:36})}),e.jsxs("div",{className:"agent-detail-info",children:[e.jsx("h2",{children:c.name}),e.jsxs("div",{className:"agent-detail-badges",children:[e.jsx("span",{className:"badge",style:{background:Ee.bg,color:Ee.text,border:`1px solid ${Ee.border}`},children:c.state}),e.jsxs("span",{className:"badge",style:{color:je.color},title:je.reason??je.label,children:[je.icon,!je.stateDerived&&je.label]})]})]})]}),e.jsxs("div",{className:"agent-detail-header-actions",children:[e.jsxs("div",{className:"agent-detail-controls",children:[c.state==="idle"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void ce("active"),disabled:F,children:[e.jsx(Cs,{size:14}),"Start"]}),e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void Pe(),"aria-label":`Run now for ${c.name}`,disabled:W||F,children:[e.jsx(vs,{size:14}),"Run Now"]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:ge,children:[e.jsx(bs,{size:14}),"Delete"]})]}),c.state==="active"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--compact agent-detail-mobile-icon-control",onClick:()=>void ce("paused"),disabled:F,"aria-label":"Pause",children:[e.jsx(Ws,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:"Pause"})]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:()=>void ce("paused"),disabled:F,"aria-label":"Stop",children:[e.jsx(Ve,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:"Stop"})]}),e.jsxs("button",{className:"btn btn-task-create btn--compact agent-detail-mobile-icon-control",onClick:()=>void Pe(),"aria-label":`Run now for ${c.name}`,disabled:W||F,children:[e.jsx(vs,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:"Run Now"})]})]}),c.state==="paused"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact agent-detail-mobile-icon-control",onClick:()=>void ce("active"),disabled:F,"aria-label":"Resume",children:[e.jsx(Cs,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:"Resume"})]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:ge,children:[e.jsx(bs,{size:14}),"Delete"]})]}),c.state==="running"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--compact agent-detail-mobile-icon-control",onClick:()=>void ce("paused"),disabled:F,"aria-label":"Pause",children:[e.jsx(Ws,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:"Pause"})]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:()=>void ce("paused"),disabled:F,"aria-label":"Stop",children:[e.jsx(Ve,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:"Stop"})]})]}),c.state==="error"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void ce("active"),disabled:F,children:[e.jsx(Cs,{size:14}),"Retry"]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:()=>void ce("paused"),disabled:F,"aria-label":"Stop",children:[e.jsx(Ve,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:"Stop"})]})]})]}),e.jsxs("div",{className:"agent-detail-utility-actions",children:[e.jsxs("div",{className:"agent-detail-bulk-menu",ref:is,children:[e.jsx("button",{type:"button",className:"btn-icon",onClick:()=>Y(g=>!g),"aria-haspopup":"menu","aria-expanded":T,"aria-label":"Bulk agent actions",title:"Bulk agent actions",disabled:F||S,children:e.jsx(zt,{size:16})}),T&&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 me("paused"),disabled:os||S,children:["Pause All Agents",e.jsx("span",{className:"agent-detail-bulk-menu-item-hint",children:$?"Loading eligible agents...":os?"No active agents eligible":`Pause ${h} active/running agent${h===1?"":"s"}`})]}),e.jsxs("button",{type:"button",role:"menuitem",className:"agent-detail-bulk-menu-item",onClick:()=>void me("active"),disabled:cs||S,children:["Resume All Agents",e.jsx("span",{className:"agent-detail-bulk-menu-item-hint",children:$?"Loading eligible agents...":cs?"No paused agents eligible":`Resume ${r} paused agent${r===1?"":"s"}`})]})]})]}),e.jsx("button",{className:"btn-icon",onClick:()=>void fe(),title:"Refresh","aria-label":"Refresh",children:e.jsx(Ns,{size:16})}),!x&&e.jsx("button",{className:"btn-icon",onClick:i,"aria-label":"Close",title:"Close",children:e.jsx(dt,{size:20})})]})]})]}),e.jsx("div",{className:"agent-detail-tabs",children:Ma.map(g=>e.jsxs("button",{className:ae("agent-detail-tab",p===g.id&&"active"),onClick:()=>m(g.id),children:[e.jsx(g.icon,{size:16}),g.label]},g.id))}),e.jsxs("div",{className:"agent-detail-content",children:[p==="dashboard"&&e.jsx($a,{agent:c,health:je,onChildClick:d,projectId:n}),p==="logs"&&e.jsx(Pa,{logs:D,isStreaming:I,hasTask:!!c.taskId||D.length>0||L!==null,fallbackLabel:!c.taskId&&L?`Latest run · ${L.id.slice(0,8)}`:null}),p==="mail"&&e.jsx(Da,{agent:c,mailbox:re,isLoading:ie,error:le,projectId:n,addToast:l,onRefresh:()=>void He()}),p==="runs"&&e.jsx(za,{addToast:l,agentId:c.id,projectId:n,agentState:c.state,agentName:c.name,initialRunId:v,preferActiveRun:A,runNowRefreshToken:k}),p==="tasks"&&e.jsx(Ia,{agentId:c.id,projectId:n,addToast:l}),p==="employees"&&e.jsx(qa,{agentId:c.id,projectId:n,onChildClick:d}),p==="soul"&&e.jsx(_a,{agent:c,projectId:n,addToast:l,onSaved:Se}),p==="instructions"&&e.jsx(Ja,{agent:c,projectId:n,addToast:l,onSaved:Se}),p==="memory"&&e.jsx(Va,{agent:c,projectId:n,addToast:l,onSaved:Se}),p==="reflections"&&e.jsx(Ra,{agentId:c.id,projectId:n,addToast:l}),p==="config"&&e.jsx(Ga,{agent:c,projectId:n,addToast:l,onSaved:Se,onHasChangesChange:ys,onDelete:ge,onAgentDraftApplied:g=>{C(z=>z&&{...z,...g})}},c.id)]}),!x&&e.jsxs("div",{className:"agent-detail-footer",children:[e.jsx("button",{className:"btn-icon",onClick:we,title:"Copy Agent ID",children:e.jsx(Ut,{})}),e.jsx("span",{className:"agent-detail-id",onClick:we,children:c.id}),c.taskId&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"divider",children:"|"}),e.jsx("span",{className:"text-muted",children:"Working on:"}),e.jsxs("a",{href:`/tasks/${c.taskId}`,className:"link",children:[c.taskId,e.jsx(ht,{size:12})]})]})]})]})})}function $a({agent:s,health:n,onChildClick:i,projectId:l}){const d=Ls[s.state],[x,M]=t.useState([]),[f,v]=t.useState(!0),[A,P]=t.useState(null),[c,C]=t.useState([]),[y,D]=t.useState(null),[j,J]=t.useState(null),[Z,p]=t.useState(!1),[m,I]=t.useState(null),N=typeof s.runtimeConfig?.runtimeHint=="string"?s.runtimeConfig.runtimeHint:"",F=(()=>{const h=s.runtimeConfig??{};if(N){const b=c.find(r=>r.runtimeId===N);return b?b.name:N}if(h.modelProvider&&h.modelId)return`${h.modelProvider}/${h.modelId}`;if(typeof h.model=="string"&&h.model.includes("/")){const b=h.model.indexOf("/");return h.model.slice(b+1)}return null})();t.useEffect(()=>{Es(s.id,l).then(P).catch(()=>P(null))},[s.id,l]),t.useEffect(()=>{ft(l).then(C).catch(()=>C([]))},[l]),t.useEffect(()=>{let h=!1;return v(!0),Wt(s.id,l).then(b=>{if(h)return;const r=b.length>0&&b[0]?.id===s.id?[...b].reverse():b;M(r)}).catch(()=>{h||M([])}).finally(()=>{h||v(!1)}),()=>{h=!0}},[s.id,l]);const R=t.useMemo(()=>{const h=s.completedRuns||[],b=new Date;b.setHours(0,0,0,0);const r=h.filter(k=>new Date(k.startedAt)>=b),o=h.filter(k=>k.status==="completed");return{totalRuns:h.length,todayRuns:r.length,successfulRuns:o.length,successRate:h.length>0?Math.round(o.length/h.length*100):0}},[s]),W=(s.completedRuns||[]).slice(0,5),O=Array.isArray(s.metadata?.skills)?s.metadata.skills:[],T=y?ws(y):null,Y=t.useCallback(async h=>{p(!0),I(null),J(null);try{const b=await Gt(h,l);J(b)}catch(b){I(K(b))}finally{p(!1)}},[l]),S=t.useCallback(h=>{if(y===h){D(null),J(null),I(null),p(!1);return}D(h),Y(h)},[Y,y]),Q=s.state==="active"||s.state==="running",$=qt(s.runtimeConfig?.heartbeatIntervalMs),G=Q&&s.lastHeartbeatAt?new Date(new Date(s.lastHeartbeatAt).getTime()+$).toISOString():null;return e.jsxs("div",{className:"dashboard-tab dashboard-summary-layout",children:[A?.isOverBudget&&e.jsxs("div",{className:"budget-warning-banner",role:"alert",children:[e.jsx("span",{children:"⚠️"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Budget Exhausted:"})," 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(Ps,{}),e.jsx("h3",{children:"Overview"}),e.jsx("strong",{children:s.name}),e.jsx("span",{className:"inline-badge",style:{background:d.bg,color:d.text},children:s.state})]}),e.jsxs("div",{className:"dashboard-summary-hero__meta",children:[e.jsxs("span",{className:"dashboard-summary-hero__health",title:n.reason??n.label,children:[n.icon," ",n.label]}),(s.pendingApprovalCount??0)>0?e.jsxs("span",{className:"badge agent-detail-approval-badge",title:"Pending approvals",children:[e.jsx("span",{className:"status-dot status-dot--pending"}),s.pendingApprovalCount," pending approvals"]}):null,e.jsxs("span",{children:["Role: ",s.role]}),e.jsxs("span",{children:[e.jsx("span",{className:"dashboard-summary-label",children:N?"Runtime":"Model"}),e.jsxs("span",{children:[" ",F??"Auto"]})]}),O.length>0?e.jsxs("span",{className:"dashboard-summary-skills",children:[e.jsx("span",{className:"dashboard-summary-label",children:"Skills"}),e.jsx("span",{className:"dashboard-summary-skill-badges",role:"list","aria-label":"Assigned skills",children:O.map(h=>{const b=y===h;return e.jsx("button",{type:"button",className:ae("badge","badge-skill","dashboard-summary-skill-badge","dashboard-summary-skill-badge-btn",b&&"dashboard-summary-skill-badge--selected"),title:h,onClick:()=>S(h),"aria-expanded":b,"aria-label":`View details for ${ws(h)}`,children:ws(h)},h)})})]}):e.jsx("span",{children:"Skills: —"})]}),y?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:T}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>S(y),children:[e.jsx(dt,{size:14}),"Close"]})]}),Z?e.jsxs("div",{className:"dashboard-summary-skill-detail-loading",role:"status","aria-live":"polite",children:[e.jsx(V,{size:14,className:"animate-spin"}),"Loading skill content..."]}):m?e.jsxs("div",{className:"dashboard-summary-skill-detail-error",role:"alert",children:[e.jsx(gt,{size:14}),e.jsx("span",{children:m}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void Y(y),children:"Retry"})]}):j?e.jsx("pre",{className:"dashboard-summary-skill-detail-content",children:j.skillMd||"(No SKILL.md found)"}):e.jsx("div",{className:"dashboard-summary-skill-detail-empty",children:"No skill content available"})]}):null]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:"Heartbeat & Health"}),e.jsxs("div",{className:"dashboard-summary-grid",children:[e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:"Last heartbeat"}),e.jsx("p",{children:s.lastHeartbeatAt?Je(s.lastHeartbeatAt):"Never"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:"Next expected"}),e.jsx("p",{children:G?Je(G):"Not scheduled"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:"Interval"}),e.jsx("p",{children:xt($)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:"Status"}),e.jsxs("p",{className:"dashboard-summary-health-row",children:[e.jsx("span",{className:ae("status-dot",s.state==="running"&&"status-dot--running")}),n.label,n.reason&&e.jsxs("span",{className:"text-secondary dashboard-summary-health-reason",title:n.reason,children:["(",n.reason,")"]})]})]})]})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:"Current Work"}),s.taskId?e.jsxs("div",{className:"current-task",children:[e.jsx("a",{href:`/tasks/${s.taskId}`,className:"task-badge",children:s.taskId}),e.jsxs("a",{href:`/tasks/${s.taskId}`,className:"btn btn-sm",children:["View Task ",e.jsx(ht,{size:14})]})]}):e.jsx("p",{className:"text-muted",children:"No active assignment"})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:"Recent Runs"}),e.jsxs("p",{className:"dashboard-summary-label",children:[R.successfulRuns,"/",R.totalRuns," successful (",R.successRate,"%)"]}),W.length===0?e.jsx("p",{className:"text-muted",children:"No runs yet"}):e.jsx("div",{className:"runs-list",children:W.map(h=>{const b=js[h.status]||js.terminated,r=b.icon;return e.jsxs("div",{className:"run-item",children:[e.jsx(r,{size:14,style:{color:b.color}}),e.jsx("span",{children:Je(h.startedAt)}),e.jsxs("span",{className:"text-muted",children:[Math.max(0,Math.round((new Date(h.endedAt||h.startedAt).getTime()-new Date(h.startedAt).getTime())/1e3)),"s"]})]},h.id)})})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:"Throughput"}),e.jsxs("div",{className:"stats-grid",children:[e.jsxs("div",{className:"stat-card",children:[e.jsx("div",{className:"stat-value",children:R.totalRuns}),e.jsx("div",{className:"stat-label",children:"Total Runs"})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("div",{className:"stat-value",children:R.todayRuns}),e.jsx("div",{className:"stat-label",children:"Runs Today"})]}),e.jsxs("div",{className:"stat-card",children:[e.jsxs("div",{className:"stat-value",children:[R.successRate,"%"]}),e.jsx("div",{className:"stat-label",children:"Success Rate"})]})]})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:"Chain of Command"}),f?e.jsxs("div",{className:"chain-of-command-loading",role:"status","aria-live":"polite",children:[e.jsx(V,{size:14,className:"animate-spin"}),e.jsx("span",{children:"Loading reporting chain..."})]}):x.length<=1?e.jsx("p",{className:"text-muted",children:"No reporting chain"}):e.jsx("div",{className:"chain-of-command-path","aria-label":"Chain of command",children:x.map((h,b)=>{const r=b===x.length-1,o=!r;return e.jsxs("div",{className:"chain-of-command-item",children:[e.jsx("button",{type:"button",className:`chain-of-command-node${r?" chain-of-command-node--current":""}`,onClick:()=>o&&i?.(h.id),disabled:!o||!i,title:r?"Current agent":`View ${h.name}`,children:h.name}),!r&&e.jsx("span",{className:"chain-of-command-separator","aria-hidden":"true",children:"→"})]},h.id)})})]})]})}function Pa({logs:s,isStreaming:n,hasTask:i,fallbackLabel:l}){return i?e.jsxs("div",{className:"logs-tab",children:[e.jsxs("div",{className:"logs-header",children:[e.jsxs("span",{className:"logs-count",children:[s.length," entries"]}),l&&e.jsx("span",{className:"text-muted logs-fallback-label",children:l}),n&&e.jsxs("span",{className:"streaming-indicator",children:[e.jsx("span",{className:"streaming-dot"}),"Live"]})]}),s.length===0?e.jsxs("div",{className:"logs-empty",children:[e.jsx(es,{size:48,opacity:.3}),e.jsx("p",{children:"No log entries yet"}),e.jsx("p",{className:"text-muted",children:n?"Waiting for activity...":"Logs will appear here when the agent is active"})]}):e.jsx(bt,{entries:s,loading:!1})]}):e.jsx("div",{className:"logs-tab",children:e.jsxs("div",{className:"logs-empty",children:[e.jsx(es,{size:48,opacity:.3}),e.jsx("p",{children:"No activity yet"}),e.jsx("p",{className:"text-muted",children:"Agent logs will appear here from the current task or most recent run"})]})})}function La(s){const n=new Date(s),l=new Date().getTime()-n.getTime(),d=Math.floor(l/6e4),x=Math.floor(l/36e5),M=Math.floor(l/864e5);return d<1?"Just now":d<60?`${d}m ago`:x<24?`${x}h ago`:M<7?`${M}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function fs(s,n,i){if(n==="user")return s==="dashboard"?"You":`User: ${s}`;if(n==="agent"){const l=i?.get(s)?.trim();return!l||l===s?`Agent: ${s}`:`Agent: ${l}`}return"System"}function Da({agent:s,mailbox:n,isLoading:i,error:l,projectId:d,addToast:x,onRefresh:M}){const[f,v]=t.useState("inbox"),[A,P]=t.useState([]);t.useEffect(()=>{let m=!1;return ps(void 0,d).then(I=>{m||P(I)}).catch(()=>{m||P([])}),()=>{m=!0}},[d]);const c=t.useMemo(()=>{const m=new Map;for(const N of A){if(!N.id)continue;const F=typeof N.name=="string"?N.name.trim():"";F.length>0&&m.set(N.id,F)}const I=typeof s.name=="string"?s.name.trim():"";return I.length>0&&m.set(s.id,I),m},[A,s.id,s.name]),[C,y]=t.useState(null),D=f==="inbox"?n?.inbox??[]:n?.outbox??[],j=C?D.find(m=>m.id===C)??null:null;t.useEffect(()=>{y(null)},[f,s.id]);const J=async m=>{if(y(m.id),!(f!=="inbox"||m.read))try{await fa(m.id,d),M()}catch(I){const N=`Failed to mark message as read: ${K(I)}`;x?x(N,"error"):console.warn(N)}},Z=()=>{y(null),M()},p=m=>e.jsxs("button",{type:"button",className:ae("mailbox-item","agent-mail-tab-message",f==="inbox"&&!m.read&&"unread",C===m.id&&"agent-mail-tab-message--selected"),onClick:()=>void J(m),"aria-pressed":C===m.id,children:[e.jsx("div",{className:"mailbox-item-avatar",children:(f==="inbox"?m.fromType:m.toType)==="agent"?e.jsx(Ps,{size:16}):e.jsx(la,{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:fs(m.fromId,m.fromType,c)}):e.jsxs("span",{className:"mailbox-item-to",children:["To: ",fs(m.toId,m.toType,c)]}),e.jsx("span",{className:"mailbox-item-time",children:La(m.createdAt)})]}),e.jsxs("div",{className:"mailbox-item-preview",children:[m.content.slice(0,80),m.content.length>80?"…":""]})]}),f==="inbox"&&!m.read?e.jsx("div",{className:"mailbox-item-unread-dot","aria-label":"Unread message"}):null]},m.id);return e.jsxs("div",{className:"agent-mail-tab",children:[e.jsxs("div",{className:"agent-mail-tab-header",children:[e.jsxs("h3",{children:[s.name," Mail"]}),e.jsxs("button",{className:"btn btn-sm",onClick:Z,disabled:i,children:[e.jsx(Ns,{size:14}),"Refresh"]})]}),e.jsxs("div",{className:"mailbox-agent-subtabs","data-testid":"agent-detail-mail-subtabs",children:[e.jsxs("button",{className:ae("btn","btn-sm","btn-secondary","mailbox-agent-subtab",f==="inbox"&&"active"),onClick:()=>v("inbox"),children:[e.jsx(qs,{size:12}),e.jsx("span",{children:"Inbox"}),(n?.unreadCount??0)>0?e.jsx("span",{className:"mailbox-tab-badge",children:n?.unreadCount}):null]}),e.jsxs("button",{className:ae("btn","btn-sm","btn-secondary","mailbox-agent-subtab",f==="outbox"&&"active"),onClick:()=>v("outbox"),children:[e.jsx(Ks,{size:12}),e.jsx("span",{children:"Outbox"})]})]}),i&&!n?e.jsxs("div",{className:"agent-detail-loading agent-detail-loading--inline",role:"status","aria-live":"polite",children:[e.jsx(V,{className:"animate-spin",size:16}),e.jsx("span",{children:"Loading mailbox..."})]}):null,!i&&l?e.jsxs("div",{className:"agent-mail-tab-error",role:"alert",children:[e.jsx(gt,{size:16}),e.jsxs("span",{children:["Failed to load mailbox: ",l]})]}):null,!i&&!l?j?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:()=>y(null),children:[e.jsx(ot,{size:14}),"Back to ",f==="inbox"?"Inbox":"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:"From"}),e.jsx("span",{children:fs(j.fromId,j.fromType,c)})]}),e.jsxs("div",{className:"agent-mail-tab-detail-row",children:[e.jsx("span",{className:"agent-mail-tab-detail-label",children:"To"}),e.jsx("span",{children:fs(j.toId,j.toType,c)})]}),e.jsxs("div",{className:"agent-mail-tab-detail-row",children:[e.jsx("span",{className:"agent-mail-tab-detail-label",children:"Type"}),e.jsx("span",{children:j.type})]}),e.jsxs("div",{className:"agent-mail-tab-detail-row",children:[e.jsx("span",{className:"agent-mail-tab-detail-label",children:"Sent"}),e.jsx("span",{children:new Date(j.createdAt).toLocaleString()})]}),j.metadata?.replyTo?.messageId?e.jsxs("div",{className:"agent-mail-tab-reply-context",children:["↪ Replying to message ",j.metadata.replyTo.messageId]}):null]}),e.jsx("div",{className:"agent-mail-tab-detail-body",children:j.content})]}):e.jsx("div",{className:"mailbox-list","data-testid":"agent-detail-mail-list",children:D.length===0?e.jsxs("div",{className:"mailbox-empty","data-testid":"agent-detail-mail-empty",children:[f==="inbox"?e.jsx(qs,{size:32}):e.jsx(Ks,{size:32}),e.jsx("p",{children:f==="inbox"?"No received messages for this agent":"No sent messages for this agent"})]}):D.map(p)}):null]})}function za({addToast:s,agentId:n,projectId:i,agentState:l,agentName:d,initialRunId:x,preferActiveRun:M,runNowRefreshToken:f}){const[v,A]=t.useState([]),{confirm:P}=it(),[c,C]=t.useState(!0),[y,D]=t.useState(null),[j,J]=t.useState([]),[Z,p]=t.useState(!1),[m,I]=t.useState(null),[N,F]=t.useState(!1),R=t.useRef(!1),W=t.useRef(!1),O=t.useCallback(async()=>{try{const o=await lt(n,50,i);A(o)}catch(o){s(`Failed to load runs: ${K(o)}`,"error")}finally{C(!1)}},[n,i,s]);t.useEffect(()=>{O()},[O]),t.useEffect(()=>{if(!W.current){W.current=!0;return}C(!0),O()},[O,f]);const T=v.some(o=>o.status==="active"),Y=y?v.find(o=>o.id===y)?.status:void 0;t.useEffect(()=>{if(!T)return;const o=setInterval(()=>{O()},5e3);return()=>clearInterval(o)},[T,O]),t.useEffect(()=>{if(!y||Y!=="active")return;const o=i?`?projectId=${encodeURIComponent(i)}`:"";return gs(`/api/agents/${encodeURIComponent(n)}/runs/${encodeURIComponent(y)}/logs/stream${o}`,{events:{"agent:log":k=>{try{const ne=JSON.parse(k.data);J(L=>[...L,ne])}catch{}}}})},[y,Y,n,i]);const S=t.useCallback(async o=>{if(y===o){D(null),J([]),I(null);return}D(o),p(!0),F(!0),J([]),I(null);try{const[k,ne]=await Promise.all([rt(n,o,i),Yt(n,o,i)]);J(k),I(ne)}catch(k){s(`Failed to load run details: ${K(k)}`,"error"),J([]),I(null)}finally{p(!1),F(!1)}},[y,n,i,s]);t.useEffect(()=>{R.current=!1},[n,x,M]),t.useEffect(()=>{if(v.length===0||c||R.current)return;const o=x?v.find(k=>k.id===x):M?v.find(k=>k.status==="active"):null;R.current=!0,o&&S(o.id)},[x,M,v,c,S]);const Q=async()=>{if(await P({title:"Stop Active Run",message:"Stop the active run? The agent's work will be interrupted.",danger:!0}))try{await ra(n,i),s("Run stopped","success"),C(!0),O()}catch(k){s(`Failed to stop run: ${K(k)}`,"error")}};if(c&&v.length===0)return e.jsx("div",{className:"runs-tab",children:e.jsxs("div",{className:"runs-loading-row",children:[e.jsx(V,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading runs..."})]})});if(v.length===0)return e.jsx("div",{className:"runs-tab",children:e.jsxs("div",{className:"runs-empty",children:[e.jsx(vs,{size:48,opacity:.3}),e.jsx("p",{children:"No runs yet"}),e.jsx("p",{className:"text-muted",children:"Heartbeat runs will appear here"})]})});const $=[...v].sort((o,k)=>new Date(k.startedAt).getTime()-new Date(o.startedAt).getTime()),G=$.filter(o=>o.status==="active"),h=$.filter(o=>o.status!=="active"),b=o=>o?e.jsxs("div",{className:"run-usage",children:[e.jsxs("span",{children:["Input: ",o.inputTokens.toLocaleString()]}),e.jsxs("span",{children:["Output: ",o.outputTokens.toLocaleString()]}),o.cachedTokens>0&&e.jsxs("span",{children:["Cached: ",o.cachedTokens.toLocaleString()]})]}):null,r=(o,k,ne)=>{const L=js[o.status]||js.completed,pe=L.icon,re=o.endedAt?Ba(new Date(o.startedAt),new Date(o.endedAt)):"In progress",ve=y===o.id;return e.jsxs("div",{children:[e.jsxs("div",{className:ae("run-card",ne&&"run-card--active",ve&&"run-card--selected","run-card--clickable"),onClick:()=>void S(o.id),role:"button",tabIndex:0,"aria-expanded":ve,"aria-label":`${ne?"Active":""} run ${o.id.slice(0,8)}, ${o.status}`,onKeyDown:ie=>{(ie.key==="Enter"||ie.key===" ")&&(ie.preventDefault(),S(o.id))},children:[e.jsxs("div",{className:"run-header",children:[e.jsxs("div",{className:"run-header-group",children:[ve?e.jsx(at,{size:14}):e.jsx(nt,{size:14}),ne?e.jsxs("span",{className:"run-live-indicator",children:[e.jsx("span",{className:"live-dot"}),"Live Run"]}):e.jsxs("span",{className:"run-id",children:["#",k+1," ",o.id.slice(0,8)]})]}),e.jsxs("div",{className:"run-header-group",children:[o.invocationSource&&e.jsx("span",{className:"badge run-badge--compact",children:o.invocationSource}),ne&&e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:ie=>{ie.preventDefault(),ie.stopPropagation(),Q()},"aria-label":"Stop active run",children:[e.jsx(Ve,{size:12})," Stop"]}),e.jsxs("span",{className:ae("run-status",o.status),children:[e.jsx(pe,{size:14,style:{color:L.color}}),o.status]}),o.heartbeatProcedureSource==="custom"&&e.jsx("span",{className:"badge run-badge--compact",children:"Heartbeat: custom"})]})]}),e.jsxs("div",{className:"run-details",children:[e.jsxs("span",{children:["Started ",Je(o.startedAt)]}),e.jsx("span",{children:"•"}),e.jsx("span",{children:re}),o.triggerDetail&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsx("span",{className:"text-muted",children:o.triggerDetail})]})]})]}),ve&&e.jsxs("div",{className:"run-logs-container",children:[N?e.jsxs("div",{className:"run-details-loading-state",children:[e.jsx(V,{size:14,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading details..."})]}):m&&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:"System Prompt"}),m.systemPrompt?e.jsx("pre",{className:"run-output-panel",children:m.systemPrompt}):e.jsx("div",{className:"text-muted run-output-empty",children:"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:"Execution Prompt"}),m.executionPrompt?e.jsx("pre",{className:"run-output-panel",children:m.executionPrompt}):e.jsx("div",{className:"text-muted run-output-empty",children:"Execution prompt not captured for this run"})]})}),m.usageJson&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:"Token Usage"}),b(m.usageJson)]}),m.stdoutExcerpt&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:"Output"}),e.jsx("pre",{className:"run-output-panel",children:m.stdoutExcerpt.length>2e3?`${m.stdoutExcerpt.slice(0,2e3)}
17
17
 
18
- ... (truncated, ${m.stdoutExcerpt.length} chars total)`:m.stdoutExcerpt})]}),m.stderrExcerpt&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label run-output-label--error",children:"Errors"}),e.jsx(oa,{errorText:m.stderrExcerpt,summaryPrefix:"Run error",issueContext:{surface:"AgentDetailView runs",agentId:n,agentName:d,agentState:l,runId:m.id,taskId:void 0,timestamp:m.startedAt}})]}),m.resultJson&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:"Result"}),e.jsx("pre",{className:"run-output-panel",children:JSON.stringify(m.resultJson,null,2)})]}),m.contextSnapshot&&Object.keys(m.contextSnapshot).length>0&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:"Context"}),e.jsx("div",{className:"run-context-grid",children:Object.entries(m.contextSnapshot).map(([ie,U])=>e.jsxs("span",{className:"run-context-item",children:[e.jsxs("span",{className:"text-muted",children:[ie,":"]})," ",e.jsx("span",{children:String(U)})]},ie))})]}),!m.stdoutExcerpt&&!m.stderrExcerpt&&!m.resultJson&&e.jsx("div",{className:"text-muted run-output-empty",children:"No output captured"})]}),e.jsxs("div",{className:"run-agent-logs-section",children:[e.jsx("div",{className:"run-output-label",children:"Agent Logs"}),Z?e.jsxs("div",{className:"run-details-loading-state",children:[e.jsx(V,{size:14,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading logs..."})]}):j.length===0?e.jsx("div",{className:"text-muted run-output-empty",children:"No logs available for this run"}):e.jsx(bt,{entries:j,loading:!1})]})]})]},o.id)};return e.jsxs("div",{className:"runs-tab",children:[e.jsxs("div",{className:"runs-toolbar runs-toolbar--between",children:[e.jsxs("span",{className:"runs-toolbar-meta",children:[v.length," run",v.length!==1?"s":"",T&&e.jsxs("span",{className:"run-live-indicator run-live-indicator--with-margin",children:[e.jsx("span",{className:"live-dot"}),"Live"]})]}),e.jsx("div",{className:"run-header-group",children:T&&e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void Q(),"aria-label":`Stop active run for ${d??n}`,children:[e.jsx(Ve,{size:14})," Stop Run"]})})]}),q.map((o,k)=>r(o,k,!0)),h.map((o,k)=>r(o,q.length+k,!1))]})}function Ba(s,n){const i=Math.floor((n.getTime()-s.getTime())/1e3);return i<60?`${i}s`:i<3600?`${Math.floor(i/60)}m ${i%60}s`:`${Math.floor(i/3600)}h ${Math.floor(i%3600/60)}m`}const Oa={triage:"Triage",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"};function Ha(s){const n=s.title?.trim()||s.description?.trim()||s.id;return n.length>80?`${n.slice(0,77)}...`:n}function Ia({agentId:s,projectId:n,addToast:i}){const[l,d]=t.useState([]),[x,M]=t.useState(!0);return t.useEffect(()=>{let f=!1;return M(!0),Zt(s,n).then(v=>{f||d(v)}).catch(v=>{f||(d([]),i(`Failed to load assigned tasks: ${K(v)}`,"error"))}).finally(()=>{f||M(!1)}),()=>{f=!0}},[s,n,i]),x?e.jsxs("div",{className:"agent-tasks-empty",children:[e.jsx(V,{size:16,className:"animate-spin"}),e.jsx("p",{children:"Loading assigned tasks..."})]}):l.length===0?e.jsxs("div",{className:"agent-tasks-empty",children:[e.jsx(ut,{size:18}),e.jsx("p",{children:"No tasks assigned to this agent"})]}):e.jsx("div",{className:"agent-tasks-list",children:l.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:Oa[f.column]})]}),e.jsx("div",{className:"agent-task-title",title:f.title||f.description||f.id,children:Ha(f)}),e.jsxs("div",{className:"agent-task-status",children:[f.status??"idle"," · Updated ",Je(f.updatedAt)]})]},f.id))})}const Qe=[{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 Ua(s){const n={};for(const i of Qe){const l=s[i.key]?.trim();if(l){if(i.type==="number"){const d=Number(l);if(Number.isNaN(d)||!Number.isFinite(d)){n[i.key]=`"${i.label}" must be a valid number`;continue}i.min!==void 0&&d<i.min&&(n[i.key]=`"${i.label}" must be at least ${i.min.toLocaleString()}`),i.max!==void 0&&d>i.max&&(n[i.key]=`"${i.label}" must be at most ${i.max.toLocaleString()}`)}if(i.type==="select"){const d=i.options?.map(x=>x.value)??[];d.length>0&&!d.includes(l)&&(n[i.key]=`"${i.label}" must be one of: ${d.join(", ")}`)}}}return n}function _a({agent:s,projectId:n,addToast:i,onSaved:l}){const[d,x]=t.useState(s.soul??""),[M,f]=t.useState(!1),[v,A]=t.useState(!1),[P,c]=t.useState(!1),C=t.useRef(null);t.useEffect(()=>{x(s.soul??""),A(!1),c(!1)},[s.id,s.soul]),t.useEffect(()=>()=>{C.current&&clearTimeout(C.current)},[]);const y=d!==(s.soul??""),D=async()=>{if(d.length>1e4){i("Soul must be at most 10,000 characters","error");return}f(!0);try{await ca(s.id,d,n),i("Soul saved","success"),A(!0),C.current&&clearTimeout(C.current),C.current=setTimeout(()=>A(!1),3e3),await l()}catch(j){i(`Failed to save soul: ${K(j)}`,"error")}finally{f(!1)}};return e.jsx("div",{className:"config-tab",children:e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Soul"}),e.jsx("p",{className:"config-description",children:"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:"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 ${P?"":"btn-primary"}`,onClick:()=>c(!1),disabled:!P,"aria-label":"Edit mode",children:[e.jsx(ss,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${P?"btn-primary":""}`,onClick:()=>c(!0),disabled:P,"aria-label":"Preview mode",children:[e.jsx(ts,{size:14}),"Preview"]})]})}),P?d.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(as,{remarkPlugins:[ns],children:d})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:"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:"Describe this agent's personality, tone, and behavioral traits...",value:d,onChange:j=>{x(j.target.value),A(!1)}}),!P&&e.jsx("span",{className:"config-hint",children:"Defines the agent's character and identity. Max 10,000 characters."})]})}),!P&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!y||M,onClick:()=>void D(),children:M?e.jsxs(e.Fragment,{children:[e.jsx(V,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ue,{size:16}),"Save Soul"]})}),!y&&v&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ue,{size:14}),"Soul saved"]})]})]})})}function Va({agent:s,projectId:n,addToast:i,onSaved:l}){const[d,x]=t.useState(s.memory??""),[M,f]=t.useState(!1),[v,A]=t.useState(!1),[P,c]=t.useState(!1),[C,y]=t.useState(!1),[D,j]=t.useState([]),[J,Z]=t.useState(!1),[p,m]=t.useState(""),[I,N]=t.useState(""),[F,R]=t.useState(!1),[W,O]=t.useState(!1),[T,Y]=t.useState(!1),[S,Q]=t.useState(!1),[$,q]=t.useState(""),h=t.useRef(null),b=t.useRef(null),r=s.state==="running",o=d!==(s.memory??""),k=t.useMemo(()=>D.find(U=>U.path===p),[D,p]),ne=k?Aa[k.layer]:"Select a memory file to view or edit.",L=t.useCallback(async U=>{O(!0);try{const le=await Qt(s.id,U,n);m(le.path),N(le.content),R(!1),Q(!1)}catch(le){i(`Failed to load agent memory file: ${K(le)}`,"error")}finally{O(!1)}},[s.id,n,i]),pe=t.useCallback(async(U="")=>{Z(!0);try{const{files:le}=await ea(s.id,n);if(j(le),le.length===0){m(""),N(""),R(!1);return}const ze=Ta(le,U);await L(ze)}catch(le){i(`Failed to load memory files: ${K(le)}`,"error"),j([]),m(""),N(""),R(!1)}finally{Z(!1)}},[s.id,n,i,L]);t.useEffect(()=>{x(s.memory??""),A(!1),c(!1),y(!1),q(""),Q(!1),pe()},[s.id,s.memory,pe]),t.useEffect(()=>()=>{h.current&&clearTimeout(h.current),b.current&&clearTimeout(b.current)},[]);const re=async()=>{if(d.length>5e4){i("Memory must be at most 50,000 characters","error");return}f(!0);try{await ua(s.id,d,n),i("Memory saved","success"),A(!0),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>A(!1),3e3),await l()}catch(U){i(`Failed to save memory: ${K(U)}`,"error")}finally{f(!1)}},ve=async U=>{if(!(!U||U===p)){if(F){q("Save the current file before switching to another file.");return}q(""),await L(U)}},ie=async()=>{if(p){Y(!0);try{await ma(s.id,p,I,n),R(!1),Q(!0),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>Q(!1),3e3),q(""),await pe(p),i("Agent memory file saved","success"),await l()}catch(U){i(`Failed to save agent memory file: ${K(U)}`,"error")}finally{Y(!1)}}};return e.jsx("div",{className:"config-tab",children:e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Agent Memory"}),e.jsx("p",{className:"config-description",children:"Store context that belongs to this agent only. Workspace memory, daily notes, dreams, and qmd search live in project settings under Project Memory."}),r&&e.jsx("p",{className:"config-hint config-hint--block-spacing",children:"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:"Inline Memory"}),e.jsx("span",{className:"config-hint config-hint--block",children:"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:[!r&&e.jsxs("button",{className:`btn btn-sm ${P?"":"btn-primary"}`,onClick:()=>c(!1),disabled:!P,"aria-label":"Edit mode",children:[e.jsx(ss,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${P?"btn-primary":""}`,onClick:()=>c(!0),disabled:P,"aria-label":"Preview mode",children:[e.jsx(ts,{size:14}),"Preview"]})]})}),P?d.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(as,{remarkPlugins:[ns],children:d})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:"No agent memory defined yet. Switch to Edit mode to add memory content."}):e.jsx("textarea",{id:"agent-memory","aria-label":"Agent Memory",className:"input config-textarea-mono",rows:10,placeholder:"Durable preferences, operating habits, and context this agent should carry across tasks...",value:d,readOnly:r,onChange:U=>{x(U.target.value),A(!1)}}),!P&&e.jsx("span",{className:"config-hint",children:"This is the inline memory field on the agent JSON record. Max 50,000 characters."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-memory-file-select",children:"Memory Files"}),e.jsxs("span",{className:"config-hint config-hint--block",children:["Full OpenClaw memory files at ",e.jsxs("code",{children:["agent/",s.name||s.id,"/memory/"]})," (MEMORY.md, DREAMS.md, and daily notes)."]}),e.jsx("select",{id:"agent-memory-file-select",className:"select",value:p,disabled:J||W||T||D.length===0,onChange:U=>{ve(U.target.value)},children:D.length===0?e.jsx("option",{value:"",children:"No memory files found"}):D.map(U=>e.jsxs("option",{value:U.path,children:[et[U.layer]," • ",U.label]},U.path))}),J&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(V,{size:14,className:"animate-spin"}),"Loading memory files…"]}),k&&e.jsxs("div",{className:"config-hint config-hint--top-spacing",children:[e.jsx("strong",{children:et[k.layer]})," · ",ne,e.jsx("br",{}),k.size.toLocaleString()," bytes · Updated ",Je(k.updatedAt)]}),e.jsx("div",{className:"agent-content-toolbar config-textarea-top-spacing",children:e.jsxs("div",{className:"agent-content-mode-toggle",children:[!r&&e.jsxs("button",{className:`btn btn-sm ${C?"":"btn-primary"}`,onClick:()=>y(!1),disabled:!C,"aria-label":"Memory file edit mode",children:[e.jsx(ss,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${C?"btn-primary":""}`,onClick:()=>y(!0),disabled:C,"aria-label":"Memory file preview mode",children:[e.jsx(ts,{size:14}),"Preview"]})]})}),C?I.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(as,{remarkPlugins:[ns],children:I})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:"No memory file content yet. Switch to Edit mode to add content."}):e.jsx("textarea",{className:"input config-textarea-mono",rows:14,placeholder:"Select a memory file to view and edit its content...",value:I,readOnly:r||!p||W,onChange:U=>{N(U.target.value),R(!0),Q(!1),q("")}}),W&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(V,{size:14,className:"animate-spin"}),"Loading file content…"]}),$&&e.jsx("span",{className:"config-hint config-hint--top-spacing config-hint--block",children:$})]})]}),e.jsxs("div",{className:"config-actions",children:[!P&&e.jsx("button",{className:"btn btn-task-create",disabled:!o||M||r,onClick:()=>void re(),children:M?e.jsxs(e.Fragment,{children:[e.jsx(V,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ue,{size:16}),"Save Memory"]})}),!C&&e.jsx("button",{className:"btn",disabled:!F||T||!p||r,onClick:()=>void ie(),children:T?e.jsxs(e.Fragment,{children:[e.jsx(V,{size:16,className:"animate-spin"}),"Saving file…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ue,{size:16}),"Save Memory File"]})}),!o&&v&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ue,{size:14}),"Memory saved"]}),!F&&S&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ue,{size:14}),"Memory file saved"]})]})]})})}function Ja({agent:s,projectId:n,addToast:i,onSaved:l}){const[d,x]=t.useState(s.instructionsText??""),[M,f]=t.useState(s.instructionsPath??""),[v,A]=t.useState(!1),[P,c]=t.useState(""),[C,y]=t.useState(!1),[D,j]=t.useState(!1),[J,Z]=t.useState(!1),[p,m]=t.useState(!1),[I,N]=t.useState(!1),[F,R]=t.useState(!1),W=t.useRef(null),O=t.useRef(null);t.useEffect(()=>{const $=M.trim();if(!$){c(""),j(!1);return}y(!0),pt("project",$).then(q=>{c(q.content),j(!1)}).catch(q=>{const h=K(q);h.includes("ENOENT")||h.includes("Not found")||h.includes("not found")?(c(""),j(!1)):(i(`Failed to load instructions file: ${h}`,"error"),c(""))}).finally(()=>{y(!1)})},[M,i]),t.useEffect(()=>{x(s.instructionsText??""),f(s.instructionsPath??""),N(!1),R(!1),A(!1)},[s.id,s.instructionsText,s.instructionsPath]),t.useEffect(()=>()=>{W.current&&clearTimeout(W.current),O.current&&clearTimeout(O.current)},[]);const T=(()=>{const $=d??"",q=s.instructionsText??"",h=M?.trim()??"",b=s.instructionsPath?.trim()??"";return $!==q||h!==b})(),Y=async()=>{Z(!0);try{await da(s.id,{instructionsText:d||void 0,instructionsPath:M.trim()||void 0},n),i("Instructions saved","success"),N(!0),W.current&&clearTimeout(W.current),W.current=setTimeout(()=>N(!1),3e3),await l()}catch($){i(`Failed to save instructions: ${K($)}`,"error")}finally{Z(!1)}},S=async()=>{const $=M.trim();if(!$){i("No instructions file path set","error");return}m(!0);try{await vt("project",$,P),i("Instructions file saved","success"),j(!1),R(!0),O.current&&clearTimeout(O.current),O.current=setTimeout(()=>R(!1),3e3),await l()}catch(q){i(`Failed to save instructions file: ${K(q)}`,"error")}finally{m(!1)}},Q=!!M.trim();return e.jsxs("div",{className:"config-tab",children:[e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Custom Instructions"}),e.jsx("p",{className:"config-description",children:"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:"Inline Instructions"}),e.jsx("div",{className:"agent-content-toolbar",children:e.jsxs("div",{className:"agent-content-mode-toggle",children:[e.jsxs("button",{className:`btn btn-sm ${v?"":"btn-primary"}`,onClick:()=>A(!1),disabled:!v,"aria-label":"Edit mode","data-testid":"instructions-edit-toggle",children:[e.jsx(ss,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${v?"btn-primary":""}`,onClick:()=>A(!0),disabled:v,"aria-label":"Preview mode","data-testid":"instructions-preview-toggle",children:[e.jsx(ts,{size:14}),"Preview"]})]})}),v?d.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(as,{remarkPlugins:[ns],children:d})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:"No inline instructions defined yet. Switch to Edit mode to add instructions."}):e.jsx("textarea",{id:"instructions-text",className:"input",rows:10,placeholder:"Enter custom instructions to append to this agent's system prompt...",value:d,onChange:$=>{x($.target.value),N(!1)}}),!v&&e.jsx("span",{className:"config-hint",children:"Markdown formatting supported. Max 50,000 characters."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"instructions-path",children:"Instructions File Path"}),e.jsx("input",{id:"instructions-path",type:"text",className:"input",placeholder:"e.g., .fusion/agents/my-agent-instructions.md",value:M,onChange:$=>{f($.target.value),N(!1)}}),e.jsx("span",{className:"config-hint",children:"Path to a .md file (relative to project root). Contents are read and appended at execution time."})]})]}),!v&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!T||J,onClick:()=>void Y(),children:J?e.jsxs(e.Fragment,{children:[e.jsx(V,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ue,{size:16}),"Save Instructions"]})}),!T&&I&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ue,{size:14}),"Instructions saved"]})]})]}),Q&&e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Instructions File Editor"}),e.jsx("p",{className:"config-description",children:"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:"File Content"}),C&&e.jsxs("span",{className:"config-hint config-hint--inline-tight",children:[e.jsx(V,{size:12,className:"animate-spin"}),"Loading..."]}),D&&!C&&e.jsx("span",{className:"config-hint config-hint--warning",children:"Unsaved changes"})]}),e.jsx("textarea",{id:"instructions-file-content",className:"input config-textarea-mono",rows:20,placeholder:"File content will appear here when loaded...",value:P,readOnly:C,onChange:$=>{c($.target.value),j(!0),R(!1)}}),e.jsx("span",{className:"config-hint",children:"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:!D||p,onClick:()=>void S(),children:p?e.jsxs(e.Fragment,{children:[e.jsx(V,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ue,{size:16}),"Save File"]})}),!D&&F&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ue,{size:14}),"File saved"]})]})]})]})}function st(s){const n=s??{},i={};return n.heartbeatIntervalMs!==void 0&&n.heartbeatIntervalMs!==null&&(i.heartbeatIntervalMs=String(Number(n.heartbeatIntervalMs)/1e3)),n.heartbeatTimeoutMs!==void 0&&n.heartbeatTimeoutMs!==null&&(i.heartbeatTimeoutMs=String(Number(n.heartbeatTimeoutMs)/1e3)),n.maxConcurrentRuns!==void 0&&n.maxConcurrentRuns!==null&&(i.maxConcurrentRuns=String(n.maxConcurrentRuns)),(n.messageResponseMode==="immediate"||n.messageResponseMode==="on-heartbeat")&&(i.messageResponseMode=n.messageResponseMode),i}function Rs(s){return s?.enabled!==!1}function Ms(s){return s?.autoClaimRelevantTasks!==!1}function As(s){return s?.runMissedHeartbeatOnStartup===!0}function Fs(s){return s?.allowParallelExecution!==!1}function tt(s){const n=(s??{}).budgetConfig,i={};return n&&(n.tokenBudget!==void 0&&n.tokenBudget!==null&&(i.tokenBudget=String(n.tokenBudget)),n.usageThreshold!==void 0&&n.usageThreshold!==null&&(i.usageThreshold=String(Number(n.usageThreshold)*100)),n.budgetPeriod!==void 0&&n.budgetPeriod!==null&&(i.budgetPeriod=String(n.budgetPeriod)),n.resetDay!==void 0&&n.resetDay!==null&&(i.resetDay=String(n.resetDay))),i}function Wa({agent:s,projectId:n,addToast:i,onSaved:l}){const[d,x]=t.useState(!1),[M,f]=t.useState(!1),[v,A]=t.useState(!1),[P,c]=t.useState(!1),[C,y]=t.useState(!1),[D,j]=t.useState(""),[J,Z]=t.useState(!1),[p,m]=t.useState(null),[I,N]=t.useState(!1),F=t.useRef(null),R=s.heartbeatProcedurePath?.trim(),W=`.fusion/agents/${s.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||s.id.toLowerCase().replace(/[^a-z0-9]+/g,"-")||"agent"}-${s.id.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"agent"}/HEARTBEAT.md`,O=`.fusion/agents/${s.id}/HEARTBEAT.md`,T=s.id.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"agent",Y=!!(R&&(R===W||R===O||new RegExp(`^\\.fusion/agents/[^/]+-${T}/HEARTBEAT\\.md$`).test(R))),S=!!R,Q=t.useCallback(async b=>{A(!0),m(null);try{const r=await pt("project",b,n);j(r.content),Z(!1)}catch(r){const o=K(r);m(o),i(`Failed to load heartbeat procedure file: ${o}`,"error")}finally{A(!1)}},[i,n]);t.useEffect(()=>{f(!1),y(!1),j(""),Z(!1),m(null),A(!1),c(!1),N(!1)},[s.id,R]),t.useEffect(()=>()=>{F.current&&clearTimeout(F.current)},[]);const $=async()=>{R&&(f(!0),await Q(R))},q=async()=>{if(R){c(!0);try{await vt("project",R,D,n),Z(!1),N(!0),i("Heartbeat procedure file saved","success"),F.current&&clearTimeout(F.current),F.current=setTimeout(()=>N(!1),3e3),await l()}catch(b){i(`Failed to save heartbeat procedure file: ${K(b)}`,"error")}finally{c(!1)}}},h=async()=>{x(!0);try{const b=await ga(s.id,n);i(b.procedureFileSeeded?`Heartbeat procedure file ready at ${b.heartbeatProcedurePath}`:`Heartbeat procedure path set to ${b.heartbeatProcedurePath}`,"success"),await l()}catch(b){i(`Failed to upgrade heartbeat procedure: ${K(b)}`,"error")}finally{x(!1)}};return e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Heartbeat Procedure"}),e.jsxs("p",{className:"config-description",children:["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"}),") 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:["Current path: ",e.jsx("code",{children:R||"(none — using built-in default)"})]}),S&&e.jsx("div",{className:"heartbeat-procedure-actions",children:e.jsx("button",{className:"btn btn-sm",onClick:()=>void $(),disabled:v,children:v?e.jsxs(e.Fragment,{children:[e.jsx(V,{size:16,className:"animate-spin"}),"Loading file…"]}):e.jsxs(e.Fragment,{children:[e.jsx(es,{size:16}),"View Heartbeat Markdown"]})})})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("button",{className:"btn",disabled:d||Y,onClick:()=>void h(),"aria-label":"Upgrade agent to default heartbeat procedure file",children:d?e.jsxs(e.Fragment,{children:[e.jsx(V,{size:16,className:"animate-spin"}),"Upgrading…"]}):Y?e.jsxs(e.Fragment,{children:[e.jsx(ue,{size:16}),"Already on default"]}):"Upgrade to Default Heartbeat Procedure"}),e.jsxs("span",{className:"config-hint",children:["Sets ",e.jsx("code",{children:"heartbeatProcedurePath"})," to"," ",e.jsx("code",{children:W})," ","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."]})]})]}),M&&S&&R&&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:"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 ${C?"":"btn-primary"}`,onClick:()=>y(!1),disabled:!C,"aria-label":"Heartbeat file edit mode",children:[e.jsx(ss,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${C?"btn-primary":""}`,onClick:()=>y(!0),disabled:C,"aria-label":"Heartbeat file preview mode",children:[e.jsx(ts,{size:14}),"Preview"]})]}),v&&e.jsxs("span",{className:"config-hint heartbeat-procedure-status",children:[e.jsx(V,{size:12,className:"animate-spin"}),"Loading..."]}),J&&!v&&e.jsx("span",{className:"config-hint heartbeat-procedure-status heartbeat-procedure-status--warning",children:"Unsaved changes"})]}),C?D.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(as,{remarkPlugins:[ns],children:D})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:"No heartbeat procedure markdown content yet."}):e.jsx("textarea",{id:"heartbeat-procedure-file-content",className:"input",rows:16,value:D,readOnly:v,placeholder:"Heartbeat procedure markdown file content will appear here...",onChange:b=>{j(b.target.value),Z(!0),N(!1)}}),p&&e.jsxs("span",{className:"config-error",children:["Failed to load file: ",p]}),e.jsxs("span",{className:"config-hint",children:["This editor writes directly to ",e.jsx("code",{children:R}),"."]})]}),!C&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!J||P||v,onClick:()=>void q(),children:P?e.jsxs(e.Fragment,{children:[e.jsx(V,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ue,{size:16}),"Save Heartbeat File"]})}),!J&&I&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ue,{size:14}),"File saved"]})]})]})]})}function qa({agent:s,projectId:n,addToast:i,onSaved:l,onHasChangesChange:d,onDelete:x,onAgentDraftApplied:M}){const[f,v]=t.useState(s.name),[A,P]=t.useState(s.role),[c,C]=t.useState(s.title??""),[y,D]=t.useState(s.icon??""),[j,J]=t.useState(s.reportsTo??""),[Z,p]=t.useState([]),[m,I]=t.useState(!1),[N,F]=t.useState(!1),[R,W]=t.useState(!1),O=t.useRef(null),[T,Y]=t.useState(()=>{const a={};for(const u of Qe){const w=s.metadata[u.key];w!=null&&(a[u.key]=String(w))}return a}),[S,Q]=t.useState(()=>st(s.runtimeConfig)),[$,q]=t.useState(()=>Rs(s.runtimeConfig)),[h,b]=t.useState(()=>Ms(s.runtimeConfig)),[r,o]=t.useState(()=>As(s.runtimeConfig)),[k,ne]=t.useState(()=>Fs(s.runtimeConfig)),[L,pe]=t.useState(()=>tt(s.runtimeConfig)),[re,ve]=t.useState(s.bundleConfig?.mode??""),[ie,U]=t.useState(s.bundleConfig?.entryFile??"AGENTS.md"),[le,ze]=t.useState(s.bundleConfig?.externalPath??""),[Ae,is]=t.useState(s.bundleConfig?.files??[]),[ye,We]=t.useState(Array.isArray(s.metadata?.skills)?s.metadata.skills:[]),[ls,Be]=t.useState([]),[qe,Fe]=t.useState(!1),[ee,Oe]=t.useState([]),[$e,fe]=t.useState([]),[Ge,He]=t.useState([]),[ys,Ie]=t.useState(!1),Se=(()=>{const a=s.runtimeConfig??{};return a.modelProvider&&a.modelId?`${a.modelProvider}/${a.modelId}`:typeof a.model=="string"&&a.model.includes("/")?a.model:""})(),ce=typeof s.runtimeConfig?.runtimeHint=="string"?s.runtimeConfig.runtimeHint:"",[me,Pe]=t.useState(ce?"runtime":"model"),[ge,Ue]=t.useState(Se),[we,Ee]=t.useState(ce),je=j.trim(),rs=t.useMemo(()=>Z.filter(a=>a.id!==s.id),[Z,s.id]),os=!!je&&!rs.some(a=>a.id===je),cs=t.useMemo(()=>({name:f,role:A,title:c||void 0,instructionsText:s.instructionsText,soul:s.soul,memory:s.memory,reportsTo:j||void 0,skills:ye,model:ge||void 0,runtimeHint:me==="runtime"&&we||void 0,thinkingLevel:T.thinkingLevel??void 0,maxTurns:T.maxTurns?Number(T.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}),[s.instructionsText,s.memory,s.soul,T.maxTurns,T.thinkingLevel,S.heartbeatIntervalMs,S.heartbeatTimeoutMs,S.maxConcurrentRuns,S.messageResponseMode,ge,f,j,A,me,we,ye,c]),g=t.useCallback(a=>{v(a.name),P(a.role),C(a.title??""),D(a.icon??""),J(a.reportsTo??""),a.skills&&We(a.skills),a.thinkingLevel&&Y(w=>({...w,thinkingLevel:a.thinkingLevel})),a.maxTurns!==void 0&&Y(w=>({...w,maxTurns:String(a.maxTurns)})),a.runtimeHint!==void 0?(Pe("runtime"),Ee(a.runtimeHint??""),a.runtimeHint&&Ue("")):a.model!==void 0&&(Pe("model"),Ue(a.model??""),Ee(""));const u=Object.fromEntries(Object.entries({name:a.name,role:a.role,title:a.title,icon:a.icon,reportsTo:a.reportsTo,instructionsText:a.instructionsText,soul:a.soul,memory:a.memory}).filter(([,w])=>w!==void 0));M?.(u),W(!1),i("Interview draft applied. Review and save when ready.","success")},[i,M]);t.useEffect(()=>{let a=!1;return I(!0),ps(void 0,n).then(u=>{a||p(u)}).catch(()=>{a||p([])}).finally(()=>{a||I(!1)}),()=>{a=!0}},[n]),t.useEffect(()=>{Fe(!0),sa().then(a=>{Be(a.models),Oe(a.favoriteProviders),fe(a.favoriteModels)}).catch(()=>{}).finally(()=>Fe(!1))},[]);const z=t.useCallback(async a=>{const u=ee,G=u.includes(a)?u.filter(de=>de!==a):[a,...u];Oe(G);try{await Ys({favoriteProviders:G,favoriteModels:$e})}catch{Oe(u)}},[ee,$e]),_=t.useCallback(async a=>{const u=$e,G=u.includes(a)?u.filter(de=>de!==a):[a,...u];fe(G);try{await Ys({favoriteProviders:ee,favoriteModels:G})}catch{fe(u)}},[ee,$e]);t.useEffect(()=>{Ie(!0),ft(n).then(He).catch(()=>He([])).finally(()=>Ie(!1))},[n]);const[E,te]=t.useState(null),[he,ke]=t.useState(!1);t.useEffect(()=>{Es(s.id,n).then(te).catch(()=>te(null))},[s.id,n]);const Te=async()=>{ke(!0);try{await ha(s.id,n),i("Budget usage reset successfully","success");const a=await Es(s.id,n);te(a)}catch(a){i(`Failed to reset budget: ${K(a)}`,"error")}finally{ke(!1)}},[Ce,Ke]=t.useState(!1),[H,se]=t.useState({}),[_e,Le]=t.useState(!1),[Ss,ds]=t.useState(null),Ds=s.state==="idle"||s.state==="paused",Ye=t.useRef(null),zs=t.useRef(null),Bs=t.useRef(null),us=t.useRef(0);t.useEffect(()=>()=>{Ye.current&&clearTimeout(Ye.current)},[]);const Ne=(()=>{if(f!==s.name||A!==s.role||c!==(s.title??"")||y!==(s.icon??"")||j!==(s.reportsTo??"")||re!==(s.bundleConfig?.mode??"")||ie!==(s.bundleConfig?.entryFile??"AGENTS.md")||le!==(s.bundleConfig?.externalPath??"")||JSON.stringify(Ae)!==JSON.stringify(s.bundleConfig?.files??[]))return!0;for(const X of Qe){const be=T[X.key]?.trim()??"",B=s.metadata[X.key]!==void 0&&s.metadata[X.key]!==null?String(s.metadata[X.key]):"";if(be!==B)return!0}const a=s.runtimeConfig??{};if($!==Rs(s.runtimeConfig)||h!==Ms(s.runtimeConfig)||r!==As(s.runtimeConfig)||k!==Fs(s.runtimeConfig))return!0;for(const X of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns","messageResponseMode"]){const be=S[X]?.trim()??"";let B=a[X]!==void 0&&a[X]!==null?String(a[X]):"";if((X==="heartbeatIntervalMs"||X==="heartbeatTimeoutMs")&&B&&(B=String(Number(B)/1e3)),be!==B)return!0}const u=a.budgetConfig;for(const X of["tokenBudget","budgetPeriod","resetDay"]){const be=L[X]?.trim()??"",B=u?.[X]!==void 0&&u?.[X]!==null?String(u[X]):"";if(be!==B)return!0}const w=L.usageThreshold?.trim()??"",G=u?.usageThreshold!==void 0&&u?.usageThreshold!==null?String(Number(u.usageThreshold)*100):"";if(w!==G)return!0;const de=Array.isArray(s.metadata?.skills)?s.metadata.skills:[];return JSON.stringify(ye)!==JSON.stringify(de)||me!==(ce?"runtime":"model")||ge!==Se||we!==ce})(),Os=t.useRef(null);t.useEffect(()=>{d&&Os.current!==Ne&&(Os.current=Ne,d(Ne))},[Ne,d]),t.useEffect(()=>()=>{d?.(!1)},[d]),t.useEffect(()=>{const a={id:s.id,updatedAt:s.updatedAt},u=zs.current;(!u||u.id!==a.id||u.updatedAt!==a.updatedAt)&&(Ne||(zs.current=a,Q(st(s.runtimeConfig)),q(Rs(s.runtimeConfig)),b(Ms(s.runtimeConfig)),o(As(s.runtimeConfig)),ne(Fs(s.runtimeConfig)),pe(tt(s.runtimeConfig)),Ue(Se),Ee(ce),Pe(ce?"runtime":"model")))},[s,Ne,Se,ce]);const Hs=(a,u)=>{Y(w=>({...w,[a]:u})),Le(!1),H[a]&&se(w=>{const G={...w};return delete G[a],G})},ms=(a,u)=>{Q(w=>({...w,[a]:u})),Le(!1),H[a]&&se(w=>{const G={...w};return delete G[a],G})},Nt=a=>{q(a),Le(!1)},hs=(a,u)=>{pe(w=>({...w,[a]:u})),Le(!1),H[a]&&se(w=>{const G={...w};return delete G[a],G})},Re=t.useMemo(()=>{const a=Ua(T);for(const[B,De]of Object.entries({heartbeatIntervalMs:{label:"Heartbeat Interval",min:1},heartbeatTimeoutMs:{label:"Heartbeat Timeout",min:5},maxConcurrentRuns:{label:"Max Concurrent Runs",min:1}})){const oe=S[B]?.trim();if(!oe)continue;const Me=Number(oe);Number.isNaN(Me)||!Number.isFinite(Me)?a[B]=`"${De.label}" must be a valid number`:Me<De.min&&(a[B]=`"${De.label}" must be at least ${De.min.toLocaleString()}`)}const u=S.messageResponseMode?.trim();u&&!["immediate","on-heartbeat"].includes(u)&&(a.messageResponseMode='"Message Response Mode" must be either immediate or on-heartbeat');const w=L.tokenBudget?.trim();if(w){const B=Number(w);Number.isNaN(B)||!Number.isFinite(B)?a.tokenBudget='"Token Budget" must be a valid number':B<=0&&(a.tokenBudget='"Token Budget" must be greater than 0')}const G=L.usageThreshold?.trim();if(G){const B=Number(G);Number.isNaN(B)||!Number.isFinite(B)?a.usageThreshold='"Usage Threshold" must be a valid number':(B<1||B>100)&&(a.usageThreshold='"Usage Threshold" must be between 1 and 100')}const de=L.budgetPeriod?.trim();de&&!["daily","weekly","monthly","lifetime"].includes(de)&&(a.budgetPeriod='"Budget Period" must be one of: daily, weekly, monthly, lifetime');const X=L.resetDay?.trim(),be=de||"lifetime";if(X){const B=Number(X);Number.isNaN(B)||!Number.isFinite(B)?a.resetDay='"Reset Day" must be a valid number':be==="weekly"?(B<0||B>6||!Number.isInteger(B))&&(a.resetDay='"Reset Day" must be between 0 (Sunday) and 6 (Saturday) for weekly period'):be==="monthly"&&(B<1||B>31||!Number.isInteger(B))&&(a.resetDay='"Reset Day" must be between 1 and 31 for monthly period')}return a},[T,S,L]),Is=t.useCallback(()=>{if(Object.keys(Re).length>0)return null;const a={...s.metadata};for(const oe of Qe){const Me=T[oe.key]?.trim();Me?oe.type==="number"?a[oe.key]=Number(Me):a[oe.key]=Me:delete a[oe.key]}ye.length>0?a.skills=ye:delete a.skills;const u={...s.runtimeConfig};u.enabled=$,u.autoClaimRelevantTasks=h,u.runMissedHeartbeatOnStartup=r,u.allowParallelExecution=k;for(const oe of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns"]){const Me=S[oe]?.trim();if(!Me)delete u[oe];else{const _s=Number(Me);u[oe]=oe==="maxConcurrentRuns"?_s:_s*1e3}}const w=S.messageResponseMode?.trim();if(w?u.messageResponseMode=w:delete u.messageResponseMode,me==="runtime")we.trim()?u.runtimeHint=we.trim():delete u.runtimeHint,delete u.modelProvider,delete u.modelId,delete u.model;else if(delete u.runtimeHint,ge.trim()){const oe=ge.indexOf("/");oe!==-1&&(u.modelProvider=ge.slice(0,oe),u.modelId=ge.slice(oe+1),u.model=ge.trim())}else delete u.modelProvider,delete u.modelId,delete u.model;const G={},de=L.tokenBudget?.trim(),X=L.usageThreshold?.trim(),be=L.budgetPeriod?.trim(),B=L.resetDay?.trim();de&&(G.tokenBudget=Number(de)),X&&(G.usageThreshold=Number(X)/100),be&&(G.budgetPeriod=be),B&&(G.resetDay=Number(B)),Object.keys(G).length>0?u.budgetConfig=G:delete u.budgetConfig;let De;return re&&(De={mode:re,entryFile:ie||"AGENTS.md",files:Ae.length>0?Ae:["AGENTS.md"]},re==="external"&&le.trim()&&(De.externalPath=le.trim())),{name:f.trim()||void 0,role:A,title:c.trim()||void 0,icon:y.trim()||void 0,reportsTo:j.trim()||void 0,metadata:a,runtimeConfig:u,bundleConfig:De}},[s.metadata,s.runtimeConfig,k,h,L,ie,le,Ae,re,T,$,S,y,ge,f,j,A,r,me,we,ye,c,Re]),Ze=t.useCallback(async(a,u)=>{const w=Is();if(!w)return se(Re),a&&i("Please fix validation errors before saving","error"),u==="auto"&&ds("Fix validation errors to save changes"),!1;const G=JSON.stringify(w);if(G===Bs.current)return!1;const de=++us.current;se({}),ds(null),Ke(!0);try{return await ta(s.id,w,n),de!==us.current?!1:(Bs.current=G,u==="manual"&&i("Settings saved","success"),ds(null),Le(!0),Ye.current&&clearTimeout(Ye.current),Ye.current=setTimeout(()=>Le(!1),3e3),await l(),!0)}catch(X){if(de===us.current){const be=K(X);ds(be),i(`Failed to save settings: ${be}`,"error")}return!1}finally{de===us.current&&Ke(!1)}},[i,s.id,Is,l,n,Re]),yt=async()=>{await Ze(!0,"manual")},xe=t.useCallback(()=>{if(!(!Ne||Ce)){if(Object.keys(Re).length>0){se(Re);return}Ze(!1,"auto")}},[Ne,Ce,Ze,Re]);t.useEffect(()=>{if(!Ne||Ce)return;if(Object.keys(Re).length>0){se(Re);return}const a=setTimeout(()=>{Ze(!1,"auto")},Ea);return()=>clearTimeout(a)},[Ne,Ce,Ze,Re]);const St=t.useCallback(async a=>{F(!0);try{await aa(s.id,a,n),await l(),i("Avatar uploaded","success")}catch(u){i(K(u),"error")}finally{F(!1),O.current&&(O.current.value="")}},[i,s.id,l,n]),kt=t.useCallback(async()=>{F(!0);try{await na(s.id,n),await l(),i("Avatar removed","success")}catch(a){i(K(a),"error")}finally{F(!1)}},[i,s.id,l,n]),Us=Ce?"Saving changes…":Ss?`Save failed: ${Ss}`:!Ne&&_e?"All changes saved":null;return e.jsxs("div",{className:"config-tab",children:[e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Agent Configuration"}),e.jsx("p",{className:"config-description",children:"Configure agent settings and behavior."}),e.jsx("div",{className:"config-actions-row",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>W(!0),children:"AI Interview"})}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-name",children:"Name"}),e.jsx("input",{id:"agent-name",type:"text",className:"input",value:f,onChange:a=>v(a.target.value),onBlur:()=>{xe()}})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-role",children:"Role"}),e.jsxs("select",{id:"agent-role",className:"select",value:A,onChange:a=>{P(a.target.value),xe()},children:[e.jsx("option",{value:"triage",children:"Triage"}),e.jsx("option",{value:"executor",children:"Executor"}),e.jsx("option",{value:"reviewer",children:"Reviewer"}),e.jsx("option",{value:"merger",children:"Merger"}),e.jsx("option",{value:"scheduler",children:"Scheduler"}),e.jsx("option",{value:"custom",children:"Custom"})]})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-title",children:"Title"}),e.jsx("input",{id:"agent-title",type:"text",className:"input",placeholder:"e.g. Senior Code Reviewer",value:c,onChange:a=>C(a.target.value),onBlur:()=>{xe()}})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{children:"Avatar"}),e.jsxs("div",{className:"agent-avatar-editor",children:[e.jsx(ct,{agent:s,size:64,className:"agent-avatar-editor-preview"}),e.jsxs("div",{className:"agent-avatar-editor-actions",children:[e.jsx("input",{ref:O,id:"agent-avatar-upload",type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",className:"visually-hidden",disabled:N,onChange:a=>{const u=a.target.files?.[0];u&&St(u)}}),e.jsx("button",{type:"button",className:"btn btn-sm",disabled:N,onClick:()=>O.current?.click(),children:"Upload Avatar"}),s.imageUrl?e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void kt(),disabled:N,children:"Remove Avatar"}):null]})]})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-icon",children:"Icon"}),e.jsx("input",{id:"agent-icon",type:"text",className:"input",placeholder:"e.g. 🤖",value:y,onChange:a=>D(a.target.value),onBlur:()=>{xe()}})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-reports-to",children:"Reports To"}),e.jsxs("select",{id:"agent-reports-to",className:"select",value:j,onChange:a=>{J(a.target.value),xe()},disabled:m,children:[e.jsx("option",{value:"",children:"No manager"}),os&&e.jsxs("option",{value:je,children:["Unknown manager (",je,")"]}),rs.map(a=>e.jsxs("option",{value:a.id,children:[a.name," (",a.id,")"]},a.id))]})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Skills"}),e.jsx("p",{className:"config-description",children:"Assign skills to this agent for specialized behavior."}),e.jsx("div",{className:"config-fields",children:e.jsx("div",{className:"config-field",children:e.jsx(xa,{id:"agent-skills",label:"Skills",value:ye,onChange:a=>{We(a),xe()},projectId:n})})})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Model"}),e.jsx("p",{className:"config-description",children:"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:"Runtime Source"}),e.jsxs("div",{className:"config-runtime-tabs",role:"tablist","aria-label":"Runtime source",children:[e.jsx("button",{type:"button",className:`config-runtime-tab${me==="model"?" active":""}`,role:"tab","aria-selected":me==="model",tabIndex:me==="model"?0:-1,onClick:()=>{Pe("model"),Ee(""),xe()},children:"Built-in Model"}),e.jsx("button",{type:"button",className:`config-runtime-tab${me==="runtime"?" active":""}`,role:"tab","aria-selected":me==="runtime",tabIndex:me==="runtime"?0:-1,onClick:()=>{Pe("runtime"),xe()},children:"Plugin Runtime"})]})]}),me==="model"?e.jsx("div",{className:"config-field",children:e.jsx(ia,{models:ls,value:ge,onChange:a=>{Ue(a),xe()},placeholder:"Use global default",label:"Agent Model",disabled:qe,favoriteProviders:ee,onToggleFavorite:z,favoriteModels:$e,onToggleModelFavorite:_})}):e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-runtime-hint",children:"Runtime"}),ys?e.jsx("span",{className:"config-hint",children:"Loading runtimes…"}):e.jsxs("select",{id:"agent-runtime-hint",className:"select",value:we,onChange:a=>{Ee(a.target.value),xe()},children:[e.jsx("option",{value:"",children:Ge.length>0?"Select a plugin runtime…":"No plugin runtimes available"}),Ge.map(a=>e.jsx("option",{value:a.runtimeId,children:a.description?`${a.name} — ${a.description}`:a.name},`${a.pluginId}:${a.runtimeId}`))]})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Heartbeat Settings"}),e.jsx("p",{className:"config-description",children:"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",children:[e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-enabled",children:[e.jsx("input",{id:"hb-enabled",type:"checkbox",checked:$,onChange:a=>{Nt(a.target.checked),xe()}}),"Heartbeat Enabled"]}),e.jsx("span",{className:"config-hint",children:"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-autoClaimRelevantTasks",children:[e.jsx("input",{id:"hb-autoClaimRelevantTasks",type:"checkbox",checked:h,onChange:a=>{b(a.target.checked),xe()}}),"Auto-Claim Relevant Tasks"]}),e.jsx("span",{className:"config-hint",children:"When enabled (default), no-task heartbeats scan open unowned work and auto-claim tasks aligned with this agent's role and soul."})]}),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:r,onChange:a=>{o(a.target.checked),xe()}}),"Run Missed Heartbeat On Startup"]}),e.jsx("span",{className:"config-hint",children:"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:k,onChange:a=>{ne(a.target.checked),xe()}}),"Allow Parallel Execution"]}),e.jsx("span",{className:"config-hint",children:"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.jsx("label",{htmlFor:"hb-heartbeatIntervalMs",children:"Heartbeat Interval (s)"}),e.jsx("input",{id:"hb-heartbeatIntervalMs",type:"text",inputMode:"numeric",className:ae("input",!!H.heartbeatIntervalMs&&"input--error"),placeholder:String(Ts/1e3),value:S.heartbeatIntervalMs??"",onChange:a=>ms("heartbeatIntervalMs",a.target.value)}),H.heartbeatIntervalMs?e.jsx("span",{className:"config-error",children:H.heartbeatIntervalMs}):e.jsxs("span",{className:"config-hint",children:["How often heartbeats are checked. Leave empty for system default (",Ts/1e3,"s / ",Fa,")."]})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-heartbeatTimeoutMs",children:"Heartbeat Timeout (s)"}),e.jsx("input",{id:"hb-heartbeatTimeoutMs",type:"text",inputMode:"numeric",className:ae("input",!!H.heartbeatTimeoutMs&&"input--error"),placeholder:"60",value:S.heartbeatTimeoutMs??"",onChange:a=>ms("heartbeatTimeoutMs",a.target.value)}),H.heartbeatTimeoutMs?e.jsx("span",{className:"config-error",children:H.heartbeatTimeoutMs}):e.jsx("span",{className:"config-hint",children:"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:"Max Concurrent Runs"}),e.jsx("input",{id:"hb-maxConcurrentRuns",type:"text",inputMode:"numeric",className:ae("input",!!H.maxConcurrentRuns&&"input--error"),placeholder:"1",value:S.maxConcurrentRuns??"",onChange:a=>ms("maxConcurrentRuns",a.target.value)}),H.maxConcurrentRuns?e.jsx("span",{className:"config-error",children:H.maxConcurrentRuns}):e.jsx("span",{className:"config-hint",children:"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:"Message Response Mode"}),e.jsxs("select",{id:"hb-messageResponseMode",className:ae("select",!!H.messageResponseMode&&"input--error"),value:S.messageResponseMode??"",onChange:a=>ms("messageResponseMode",a.target.value),children:[e.jsx("option",{value:"",children:"System Default (On Heartbeat)"}),e.jsx("option",{value:"on-heartbeat",children:"On Heartbeat"}),e.jsx("option",{value:"immediate",children:"Immediate"})]}),H.messageResponseMode?e.jsx("span",{className:"config-error",children:H.messageResponseMode}):e.jsx("span",{className:"config-hint",children:"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:"Budget Settings"}),e.jsx("p",{className:"config-description",children:"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:"Token Budget"}),e.jsx("input",{id:"budget-tokenBudget",type:"text",inputMode:"numeric",className:ae("input",!!H.tokenBudget&&"input--error"),placeholder:"No limit",value:L.tokenBudget??"",onChange:a=>hs("tokenBudget",a.target.value)}),H.tokenBudget?e.jsx("span",{className:"config-error",children:H.tokenBudget}):e.jsx("span",{className:"config-hint",children:"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:"Usage Threshold (%)"}),e.jsx("input",{id:"budget-usageThreshold",type:"text",inputMode:"numeric",className:ae("input",!!H.usageThreshold&&"input--error"),placeholder:"80",value:L.usageThreshold??"",onChange:a=>hs("usageThreshold",a.target.value)}),H.usageThreshold?e.jsx("span",{className:"config-error",children:H.usageThreshold}):e.jsx("span",{className:"config-hint",children:"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:"Budget Period"}),e.jsxs("select",{id:"budget-budgetPeriod",className:ae("select",!!H.budgetPeriod&&"input--error"),value:L.budgetPeriod??"",onChange:a=>hs("budgetPeriod",a.target.value),children:[e.jsx("option",{value:"",children:"No reset (lifetime)"}),e.jsx("option",{value:"daily",children:"Daily"}),e.jsx("option",{value:"weekly",children:"Weekly"}),e.jsx("option",{value:"monthly",children:"Monthly"})]}),H.budgetPeriod?e.jsx("span",{className:"config-error",children:H.budgetPeriod}):e.jsx("span",{className:"config-hint",children:"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:"Reset Day"}),e.jsx("input",{id:"budget-resetDay",type:"text",inputMode:"numeric",className:ae("input",!!H.resetDay&&"input--error"),placeholder:"Auto",value:L.resetDay??"",onChange:a=>hs("resetDay",a.target.value)}),H.resetDay?e.jsx("span",{className:"config-error",children:H.resetDay}):e.jsx("span",{className:"config-hint",children:L.budgetPeriod==="weekly"?"Day of week (0=Sunday to 6=Saturday) for reset.":L.budgetPeriod==="monthly"?"Day of month (1-31) for reset.":"Day for reset (weekly: 0-6, monthly: 1-31). Leave empty for automatic."})]}),E?.budgetLimit!=null&&e.jsxs("div",{className:"config-field",children:[e.jsx("label",{children:"Current Usage"}),e.jsxs("div",{className:"budget-progress-container",children:[e.jsx("div",{className:"budget-progress-bar",children:e.jsx("div",{className:ae("budget-progress-bar__fill",(E.usagePercent??0)>=100?"budget-progress-bar__fill--red":(E.usagePercent??0)>=80?"budget-progress-bar__fill--amber":"budget-progress-bar__fill--green"),style:{width:`${Math.min(E.usagePercent??0,100)}%`}})}),e.jsxs("span",{className:"budget-progress-label",children:[(E.currentUsage??0).toLocaleString()," / ",(E.budgetLimit??0).toLocaleString()," tokens (",Math.round(E.usagePercent??0),"% used)"]})]})]}),E?.budgetLimit!=null&&e.jsx("div",{className:"config-field",children:e.jsx("button",{className:"btn btn-reset-budget",onClick:()=>void Te(),disabled:he,children:he?e.jsxs(e.Fragment,{children:[e.jsx(V,{size:14,className:"animate-spin"}),"Resetting…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ns,{size:14}),"Reset Budget Usage"]})})})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Instruction Bundle"}),e.jsx("p",{className:"config-description",children:"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:"Bundle Mode"}),e.jsxs("select",{id:"bundle-mode",className:"select",value:re,onChange:a=>ve(a.target.value),children:[e.jsx("option",{value:"",children:"None (use inline instructions)"}),e.jsx("option",{value:"managed",children:"Managed (system-managed directory)"}),e.jsx("option",{value:"external",children:"External (user-specified path)"})]}),e.jsxs("span",{className:"config-hint",children:[re==="managed"&&"Files will be stored in a system-managed directory within .fusion/agents/",re==="external"&&"Specify an external directory path for the instruction files",!re&&"Select a mode to enable instruction bundling"]})]}),re&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-entry-file",children:"Entry File"}),e.jsx("input",{id:"bundle-entry-file",type:"text",className:"input",placeholder:"AGENTS.md",value:ie,onChange:a=>U(a.target.value)}),e.jsx("span",{className:"config-hint",children:"Primary instructions file name (default: AGENTS.md)"})]}),re==="external"&&e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-external-path",children:"External Path"}),e.jsx("input",{id:"bundle-external-path",type:"text",className:"input",placeholder:"e.g. .fusion/agents/my-agent",value:le,onChange:a=>ze(a.target.value)}),e.jsx("span",{className:"config-hint",children:"Absolute or relative path to the external directory"})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-files",children:"Files (comma-separated)"}),e.jsx("input",{id:"bundle-files",type:"text",className:"input",placeholder:"AGENTS.md, PROMPTS.md",value:Ae.join(", "),onChange:a=>is(a.target.value.split(",").map(u=>u.trim()).filter(Boolean))}),e.jsx("span",{className:"config-hint",children:"List of file names in the bundle directory"})]})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Advanced Settings"}),e.jsx("p",{className:"config-description",children:"Advanced configuration options for this agent. Leave a field empty to use system defaults."}),e.jsx("div",{className:"config-fields",children:Qe.map(a=>{const u=!!H[a.key];return e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:`adv-${a.key}`,children:a.label}),a.type==="select"?e.jsxs("select",{id:`adv-${a.key}`,className:ae("select",u&&"input--error"),value:T[a.key]??"",onChange:w=>Hs(a.key,w.target.value),children:[e.jsx("option",{value:"",children:"System Default"}),a.options?.map(w=>e.jsx("option",{value:w.value,children:w.label},w.value))]}):e.jsx("input",{id:`adv-${a.key}`,type:"text",inputMode:a.type==="number"?"numeric":void 0,className:ae("input",u&&"input--error"),placeholder:a.placeholder,value:T[a.key]??"",onChange:w=>Hs(a.key,w.target.value)}),u&&e.jsx("span",{className:"config-error",children:H[a.key]}),!u&&a.hint&&e.jsx("span",{className:"config-hint",children:a.hint})]},a.key)})}),e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!Ne||Ce,onClick:()=>void yt(),children:Ce?e.jsxs(e.Fragment,{children:[e.jsx(V,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ue,{size:16}),"Save Settings"]})}),Us&&e.jsxs("span",{className:ae("config-saved-indicator",Ss&&"config-saved-indicator--error"),children:[Ce?e.jsx(V,{size:14,className:"animate-spin"}):e.jsx(ue,{size:14}),Us]})]})]}),e.jsx(Wa,{agent:s,projectId:n,addToast:i,onSaved:l}),e.jsxs("div",{className:"config-section config-section--danger",children:[e.jsx("h3",{children:"Danger Zone"}),e.jsx("p",{className:"config-description",children:"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:!Ds||!x,onClick:()=>void x?.(),children:[e.jsx(bs,{size:16}),"Delete Agent"]}),e.jsx("span",{className:"config-danger-note",children:Ds?"Deletion is permanent and cannot be undone.":`Agent deletion is only available when state is idle or paused (current state: ${s.state}).`})]})})]}),e.jsx(ba,{isOpen:R,onClose:()=>W(!1),onUseDraft:g,projectId:n,existingAgents:Z,mode:"edit",existingAgentConfig:cs})]})}function Ga({agentId:s,projectId:n,onChildClick:i}){const[l,d]=t.useState([]),[x,M]=t.useState(!0);return t.useEffect(()=>{M(!0),Xt(s,n).then(d).finally(()=>M(!1))},[s,n]),x?e.jsxs("div",{className:"detail-section",children:[e.jsx("div",{className:"detail-section-header",children:e.jsx("h3",{children:"Employees"})}),e.jsxs("div",{className:"detail-section-body detail-section-body--loading",children:[e.jsx(V,{size:16,className:"spin"}),e.jsx("span",{className:"text-muted",children:"Loading employees..."})]})]}):e.jsxs("div",{className:"detail-section",children:[e.jsxs("div",{className:"detail-section-header",children:[e.jsx("h3",{children:"Employees"}),e.jsxs("span",{className:"text-muted",children:["(",l.length,")"]})]}),e.jsx("div",{className:"detail-section-body",children:l.length===0?e.jsxs("div",{className:"agent-empty agent-empty--padded",children:[e.jsx(mt,{size:32,opacity:.3}),e.jsx("p",{children:"No employees"}),e.jsx("p",{className:"text-muted",children:"This agent has no employees"})]}):e.jsx("div",{className:"agent-tree__children",children:l.map(f=>{const v=Ls[f.state];return e.jsxs("div",{className:"agent-tree__node agent-is-child",onClick:()=>i?.(f.id),role:"button",tabIndex:0,onKeyDown:A=>{(A.key==="Enter"||A.key===" ")&&(A.key===" "&&A.preventDefault(),i?.(f.id))},style:{cursor:i?"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:v?.bg??"var(--state-idle-bg)",color:v?.text??"var(--state-idle-text)",border:`1px solid ${v?.border??"var(--state-idle-border)"}`},children:f.state})]},f.id)})})})]})}export{en as AgentDetailView,Je as relativeTime};
18
+ ... (truncated, ${m.stdoutExcerpt.length} chars total)`:m.stdoutExcerpt})]}),m.stderrExcerpt&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label run-output-label--error",children:"Errors"}),e.jsx(oa,{errorText:m.stderrExcerpt,summaryPrefix:"Run error",issueContext:{surface:"AgentDetailView runs",agentId:n,agentName:d,agentState:l,runId:m.id,taskId:void 0,timestamp:m.startedAt}})]}),m.resultJson&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:"Result"}),e.jsx("pre",{className:"run-output-panel",children:JSON.stringify(m.resultJson,null,2)})]}),m.contextSnapshot&&Object.keys(m.contextSnapshot).length>0&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:"Context"}),e.jsx("div",{className:"run-context-grid",children:Object.entries(m.contextSnapshot).map(([ie,U])=>e.jsxs("span",{className:"run-context-item",children:[e.jsxs("span",{className:"text-muted",children:[ie,":"]})," ",e.jsx("span",{children:String(U)})]},ie))})]}),!m.stdoutExcerpt&&!m.stderrExcerpt&&!m.resultJson&&e.jsx("div",{className:"text-muted run-output-empty",children:"No output captured"})]}),e.jsxs("div",{className:"run-agent-logs-section",children:[e.jsx("div",{className:"run-output-label",children:"Agent Logs"}),Z?e.jsxs("div",{className:"run-details-loading-state",children:[e.jsx(V,{size:14,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading logs..."})]}):j.length===0?e.jsx("div",{className:"text-muted run-output-empty",children:"No logs available for this run"}):e.jsx(bt,{entries:j,loading:!1})]})]})]},o.id)};return e.jsxs("div",{className:"runs-tab",children:[e.jsxs("div",{className:"runs-toolbar runs-toolbar--between",children:[e.jsxs("span",{className:"runs-toolbar-meta",children:[v.length," run",v.length!==1?"s":"",T&&e.jsxs("span",{className:"run-live-indicator run-live-indicator--with-margin",children:[e.jsx("span",{className:"live-dot"}),"Live"]})]}),e.jsx("div",{className:"run-header-group",children:T&&e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void Q(),"aria-label":`Stop active run for ${d??n}`,children:[e.jsx(Ve,{size:14})," Stop Run"]})})]}),G.map((o,k)=>r(o,k,!0)),h.map((o,k)=>r(o,G.length+k,!1))]})}function Ba(s,n){const i=Math.floor((n.getTime()-s.getTime())/1e3);return i<60?`${i}s`:i<3600?`${Math.floor(i/60)}m ${i%60}s`:`${Math.floor(i/3600)}h ${Math.floor(i%3600/60)}m`}const Oa={triage:"Triage",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"};function Ha(s){const n=s.title?.trim()||s.description?.trim()||s.id;return n.length>80?`${n.slice(0,77)}...`:n}function Ia({agentId:s,projectId:n,addToast:i}){const[l,d]=t.useState([]),[x,M]=t.useState(!0);return t.useEffect(()=>{let f=!1;return M(!0),Zt(s,n).then(v=>{f||d(v)}).catch(v=>{f||(d([]),i(`Failed to load assigned tasks: ${K(v)}`,"error"))}).finally(()=>{f||M(!1)}),()=>{f=!0}},[s,n,i]),x?e.jsxs("div",{className:"agent-tasks-empty",children:[e.jsx(V,{size:16,className:"animate-spin"}),e.jsx("p",{children:"Loading assigned tasks..."})]}):l.length===0?e.jsxs("div",{className:"agent-tasks-empty",children:[e.jsx(ut,{size:18}),e.jsx("p",{children:"No tasks assigned to this agent"})]}):e.jsx("div",{className:"agent-tasks-list",children:l.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:Oa[f.column]})]}),e.jsx("div",{className:"agent-task-title",title:f.title||f.description||f.id,children:Ha(f)}),e.jsxs("div",{className:"agent-task-status",children:[f.status??"idle"," · Updated ",Je(f.updatedAt)]})]},f.id))})}const Qe=[{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 Ua(s){const n={};for(const i of Qe){const l=s[i.key]?.trim();if(l){if(i.type==="number"){const d=Number(l);if(Number.isNaN(d)||!Number.isFinite(d)){n[i.key]=`"${i.label}" must be a valid number`;continue}i.min!==void 0&&d<i.min&&(n[i.key]=`"${i.label}" must be at least ${i.min.toLocaleString()}`),i.max!==void 0&&d>i.max&&(n[i.key]=`"${i.label}" must be at most ${i.max.toLocaleString()}`)}if(i.type==="select"){const d=i.options?.map(x=>x.value)??[];d.length>0&&!d.includes(l)&&(n[i.key]=`"${i.label}" must be one of: ${d.join(", ")}`)}}}return n}function _a({agent:s,projectId:n,addToast:i,onSaved:l}){const[d,x]=t.useState(s.soul??""),[M,f]=t.useState(!1),[v,A]=t.useState(!1),[P,c]=t.useState(!1),C=t.useRef(null);t.useEffect(()=>{x(s.soul??""),A(!1),c(!1)},[s.id,s.soul]),t.useEffect(()=>()=>{C.current&&clearTimeout(C.current)},[]);const y=d!==(s.soul??""),D=async()=>{if(d.length>1e4){i("Soul must be at most 10,000 characters","error");return}f(!0);try{await ca(s.id,d,n),i("Soul saved","success"),A(!0),C.current&&clearTimeout(C.current),C.current=setTimeout(()=>A(!1),3e3),await l()}catch(j){i(`Failed to save soul: ${K(j)}`,"error")}finally{f(!1)}};return e.jsx("div",{className:"config-tab",children:e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Soul"}),e.jsx("p",{className:"config-description",children:"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:"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 ${P?"":"btn-primary"}`,onClick:()=>c(!1),disabled:!P,"aria-label":"Edit mode",children:[e.jsx(ss,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${P?"btn-primary":""}`,onClick:()=>c(!0),disabled:P,"aria-label":"Preview mode",children:[e.jsx(ts,{size:14}),"Preview"]})]})}),P?d.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(as,{remarkPlugins:[ns],children:d})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:"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:"Describe this agent's personality, tone, and behavioral traits...",value:d,onChange:j=>{x(j.target.value),A(!1)}}),!P&&e.jsx("span",{className:"config-hint",children:"Defines the agent's character and identity. Max 10,000 characters."})]})}),!P&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!y||M,onClick:()=>void D(),children:M?e.jsxs(e.Fragment,{children:[e.jsx(V,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ue,{size:16}),"Save Soul"]})}),!y&&v&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ue,{size:14}),"Soul saved"]})]})]})})}function Va({agent:s,projectId:n,addToast:i,onSaved:l}){const[d,x]=t.useState(s.memory??""),[M,f]=t.useState(!1),[v,A]=t.useState(!1),[P,c]=t.useState(!1),[C,y]=t.useState(!1),[D,j]=t.useState([]),[J,Z]=t.useState(!1),[p,m]=t.useState(""),[I,N]=t.useState(""),[F,R]=t.useState(!1),[W,O]=t.useState(!1),[T,Y]=t.useState(!1),[S,Q]=t.useState(!1),[$,G]=t.useState(""),h=t.useRef(null),b=t.useRef(null),r=s.state==="running",o=d!==(s.memory??""),k=t.useMemo(()=>D.find(U=>U.path===p),[D,p]),ne=k?Aa[k.layer]:"Select a memory file to view or edit.",L=t.useCallback(async U=>{O(!0);try{const le=await Qt(s.id,U,n);m(le.path),N(le.content),R(!1),Q(!1)}catch(le){i(`Failed to load agent memory file: ${K(le)}`,"error")}finally{O(!1)}},[s.id,n,i]),pe=t.useCallback(async(U="")=>{Z(!0);try{const{files:le}=await ea(s.id,n);if(j(le),le.length===0){m(""),N(""),R(!1);return}const ze=Ta(le,U);await L(ze)}catch(le){i(`Failed to load memory files: ${K(le)}`,"error"),j([]),m(""),N(""),R(!1)}finally{Z(!1)}},[s.id,n,i,L]);t.useEffect(()=>{x(s.memory??""),A(!1),c(!1),y(!1),G(""),Q(!1),pe()},[s.id,s.memory,pe]),t.useEffect(()=>()=>{h.current&&clearTimeout(h.current),b.current&&clearTimeout(b.current)},[]);const re=async()=>{if(d.length>5e4){i("Memory must be at most 50,000 characters","error");return}f(!0);try{await ua(s.id,d,n),i("Memory saved","success"),A(!0),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>A(!1),3e3),await l()}catch(U){i(`Failed to save memory: ${K(U)}`,"error")}finally{f(!1)}},ve=async U=>{if(!(!U||U===p)){if(F){G("Save the current file before switching to another file.");return}G(""),await L(U)}},ie=async()=>{if(p){Y(!0);try{await ma(s.id,p,I,n),R(!1),Q(!0),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>Q(!1),3e3),G(""),await pe(p),i("Agent memory file saved","success"),await l()}catch(U){i(`Failed to save agent memory file: ${K(U)}`,"error")}finally{Y(!1)}}};return e.jsx("div",{className:"config-tab",children:e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Agent Memory"}),e.jsx("p",{className:"config-description",children:"Store context that belongs to this agent only. Workspace memory, daily notes, dreams, and qmd search live in project settings under Project Memory."}),r&&e.jsx("p",{className:"config-hint config-hint--block-spacing",children:"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:"Inline Memory"}),e.jsx("span",{className:"config-hint config-hint--block",children:"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:[!r&&e.jsxs("button",{className:`btn btn-sm ${P?"":"btn-primary"}`,onClick:()=>c(!1),disabled:!P,"aria-label":"Edit mode",children:[e.jsx(ss,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${P?"btn-primary":""}`,onClick:()=>c(!0),disabled:P,"aria-label":"Preview mode",children:[e.jsx(ts,{size:14}),"Preview"]})]})}),P?d.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(as,{remarkPlugins:[ns],children:d})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:"No agent memory defined yet. Switch to Edit mode to add memory content."}):e.jsx("textarea",{id:"agent-memory","aria-label":"Agent Memory",className:"input config-textarea-mono",rows:10,placeholder:"Durable preferences, operating habits, and context this agent should carry across tasks...",value:d,readOnly:r,onChange:U=>{x(U.target.value),A(!1)}}),!P&&e.jsx("span",{className:"config-hint",children:"This is the inline memory field on the agent JSON record. Max 50,000 characters."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-memory-file-select",children:"Memory Files"}),e.jsxs("span",{className:"config-hint config-hint--block",children:["Full OpenClaw memory files at ",e.jsxs("code",{children:["agent/",s.name||s.id,"/memory/"]})," (MEMORY.md, DREAMS.md, and daily notes)."]}),e.jsx("select",{id:"agent-memory-file-select",className:"select",value:p,disabled:J||W||T||D.length===0,onChange:U=>{ve(U.target.value)},children:D.length===0?e.jsx("option",{value:"",children:"No memory files found"}):D.map(U=>e.jsxs("option",{value:U.path,children:[et[U.layer]," • ",U.label]},U.path))}),J&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(V,{size:14,className:"animate-spin"}),"Loading memory files…"]}),k&&e.jsxs("div",{className:"config-hint config-hint--top-spacing",children:[e.jsx("strong",{children:et[k.layer]})," · ",ne,e.jsx("br",{}),k.size.toLocaleString()," bytes · Updated ",Je(k.updatedAt)]}),e.jsx("div",{className:"agent-content-toolbar config-textarea-top-spacing",children:e.jsxs("div",{className:"agent-content-mode-toggle",children:[!r&&e.jsxs("button",{className:`btn btn-sm ${C?"":"btn-primary"}`,onClick:()=>y(!1),disabled:!C,"aria-label":"Memory file edit mode",children:[e.jsx(ss,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${C?"btn-primary":""}`,onClick:()=>y(!0),disabled:C,"aria-label":"Memory file preview mode",children:[e.jsx(ts,{size:14}),"Preview"]})]})}),C?I.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(as,{remarkPlugins:[ns],children:I})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:"No memory file content yet. Switch to Edit mode to add content."}):e.jsx("textarea",{className:"input config-textarea-mono",rows:14,placeholder:"Select a memory file to view and edit its content...",value:I,readOnly:r||!p||W,onChange:U=>{N(U.target.value),R(!0),Q(!1),G("")}}),W&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(V,{size:14,className:"animate-spin"}),"Loading file content…"]}),$&&e.jsx("span",{className:"config-hint config-hint--top-spacing config-hint--block",children:$})]})]}),e.jsxs("div",{className:"config-actions",children:[!P&&e.jsx("button",{className:"btn btn-task-create",disabled:!o||M||r,onClick:()=>void re(),children:M?e.jsxs(e.Fragment,{children:[e.jsx(V,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ue,{size:16}),"Save Memory"]})}),!C&&e.jsx("button",{className:"btn",disabled:!F||T||!p||r,onClick:()=>void ie(),children:T?e.jsxs(e.Fragment,{children:[e.jsx(V,{size:16,className:"animate-spin"}),"Saving file…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ue,{size:16}),"Save Memory File"]})}),!o&&v&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ue,{size:14}),"Memory saved"]}),!F&&S&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ue,{size:14}),"Memory file saved"]})]})]})})}function Ja({agent:s,projectId:n,addToast:i,onSaved:l}){const[d,x]=t.useState(s.instructionsText??""),[M,f]=t.useState(s.instructionsPath??""),[v,A]=t.useState(!1),[P,c]=t.useState(""),[C,y]=t.useState(!1),[D,j]=t.useState(!1),[J,Z]=t.useState(!1),[p,m]=t.useState(!1),[I,N]=t.useState(!1),[F,R]=t.useState(!1),W=t.useRef(null),O=t.useRef(null);t.useEffect(()=>{const $=M.trim();if(!$){c(""),j(!1);return}y(!0),pt("project",$).then(G=>{c(G.content),j(!1)}).catch(G=>{const h=K(G);h.includes("ENOENT")||h.includes("Not found")||h.includes("not found")?(c(""),j(!1)):(i(`Failed to load instructions file: ${h}`,"error"),c(""))}).finally(()=>{y(!1)})},[M,i]),t.useEffect(()=>{x(s.instructionsText??""),f(s.instructionsPath??""),N(!1),R(!1),A(!1)},[s.id,s.instructionsText,s.instructionsPath]),t.useEffect(()=>()=>{W.current&&clearTimeout(W.current),O.current&&clearTimeout(O.current)},[]);const T=(()=>{const $=d??"",G=s.instructionsText??"",h=M?.trim()??"",b=s.instructionsPath?.trim()??"";return $!==G||h!==b})(),Y=async()=>{Z(!0);try{await da(s.id,{instructionsText:d||void 0,instructionsPath:M.trim()||void 0},n),i("Instructions saved","success"),N(!0),W.current&&clearTimeout(W.current),W.current=setTimeout(()=>N(!1),3e3),await l()}catch($){i(`Failed to save instructions: ${K($)}`,"error")}finally{Z(!1)}},S=async()=>{const $=M.trim();if(!$){i("No instructions file path set","error");return}m(!0);try{await vt("project",$,P),i("Instructions file saved","success"),j(!1),R(!0),O.current&&clearTimeout(O.current),O.current=setTimeout(()=>R(!1),3e3),await l()}catch(G){i(`Failed to save instructions file: ${K(G)}`,"error")}finally{m(!1)}},Q=!!M.trim();return e.jsxs("div",{className:"config-tab",children:[e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Custom Instructions"}),e.jsx("p",{className:"config-description",children:"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:"Inline Instructions"}),e.jsx("div",{className:"agent-content-toolbar",children:e.jsxs("div",{className:"agent-content-mode-toggle",children:[e.jsxs("button",{className:`btn btn-sm ${v?"":"btn-primary"}`,onClick:()=>A(!1),disabled:!v,"aria-label":"Edit mode","data-testid":"instructions-edit-toggle",children:[e.jsx(ss,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${v?"btn-primary":""}`,onClick:()=>A(!0),disabled:v,"aria-label":"Preview mode","data-testid":"instructions-preview-toggle",children:[e.jsx(ts,{size:14}),"Preview"]})]})}),v?d.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(as,{remarkPlugins:[ns],children:d})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:"No inline instructions defined yet. Switch to Edit mode to add instructions."}):e.jsx("textarea",{id:"instructions-text",className:"input",rows:10,placeholder:"Enter custom instructions to append to this agent's system prompt...",value:d,onChange:$=>{x($.target.value),N(!1)}}),!v&&e.jsx("span",{className:"config-hint",children:"Markdown formatting supported. Max 50,000 characters."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"instructions-path",children:"Instructions File Path"}),e.jsx("input",{id:"instructions-path",type:"text",className:"input",placeholder:"e.g., .fusion/agents/my-agent-instructions.md",value:M,onChange:$=>{f($.target.value),N(!1)}}),e.jsx("span",{className:"config-hint",children:"Path to a .md file (relative to project root). Contents are read and appended at execution time."})]})]}),!v&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!T||J,onClick:()=>void Y(),children:J?e.jsxs(e.Fragment,{children:[e.jsx(V,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ue,{size:16}),"Save Instructions"]})}),!T&&I&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ue,{size:14}),"Instructions saved"]})]})]}),Q&&e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Instructions File Editor"}),e.jsx("p",{className:"config-description",children:"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:"File Content"}),C&&e.jsxs("span",{className:"config-hint config-hint--inline-tight",children:[e.jsx(V,{size:12,className:"animate-spin"}),"Loading..."]}),D&&!C&&e.jsx("span",{className:"config-hint config-hint--warning",children:"Unsaved changes"})]}),e.jsx("textarea",{id:"instructions-file-content",className:"input config-textarea-mono",rows:20,placeholder:"File content will appear here when loaded...",value:P,readOnly:C,onChange:$=>{c($.target.value),j(!0),R(!1)}}),e.jsx("span",{className:"config-hint",children:"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:!D||p,onClick:()=>void S(),children:p?e.jsxs(e.Fragment,{children:[e.jsx(V,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ue,{size:16}),"Save File"]})}),!D&&F&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ue,{size:14}),"File saved"]})]})]})]})}function st(s){const n=s??{},i={};return n.heartbeatIntervalMs!==void 0&&n.heartbeatIntervalMs!==null&&(i.heartbeatIntervalMs=String(Number(n.heartbeatIntervalMs)/1e3)),n.heartbeatTimeoutMs!==void 0&&n.heartbeatTimeoutMs!==null&&(i.heartbeatTimeoutMs=String(Number(n.heartbeatTimeoutMs)/1e3)),n.maxConcurrentRuns!==void 0&&n.maxConcurrentRuns!==null&&(i.maxConcurrentRuns=String(n.maxConcurrentRuns)),(n.messageResponseMode==="immediate"||n.messageResponseMode==="on-heartbeat")&&(i.messageResponseMode=n.messageResponseMode),i}function Rs(s){return s?.enabled!==!1}function Ms(s){return s?.autoClaimRelevantTasks!==!1}function As(s){return s?.runMissedHeartbeatOnStartup===!0}function Fs(s){return s?.allowParallelExecution!==!1}function tt(s){const n=(s??{}).budgetConfig,i={};return n&&(n.tokenBudget!==void 0&&n.tokenBudget!==null&&(i.tokenBudget=String(n.tokenBudget)),n.usageThreshold!==void 0&&n.usageThreshold!==null&&(i.usageThreshold=String(Number(n.usageThreshold)*100)),n.budgetPeriod!==void 0&&n.budgetPeriod!==null&&(i.budgetPeriod=String(n.budgetPeriod)),n.resetDay!==void 0&&n.resetDay!==null&&(i.resetDay=String(n.resetDay))),i}function Wa({agent:s,projectId:n,addToast:i,onSaved:l}){const[d,x]=t.useState(!1),[M,f]=t.useState(!1),[v,A]=t.useState(!1),[P,c]=t.useState(!1),[C,y]=t.useState(!1),[D,j]=t.useState(""),[J,Z]=t.useState(!1),[p,m]=t.useState(null),[I,N]=t.useState(!1),F=t.useRef(null),R=s.heartbeatProcedurePath?.trim(),W=`.fusion/agents/${s.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||s.id.toLowerCase().replace(/[^a-z0-9]+/g,"-")||"agent"}-${s.id.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"agent"}/HEARTBEAT.md`,O=`.fusion/agents/${s.id}/HEARTBEAT.md`,T=s.id.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"agent",Y=!!(R&&(R===W||R===O||new RegExp(`^\\.fusion/agents/[^/]+-${T}/HEARTBEAT\\.md$`).test(R))),S=!!R,Q=t.useCallback(async b=>{A(!0),m(null);try{const r=await pt("project",b,n);j(r.content),Z(!1)}catch(r){const o=K(r);m(o),i(`Failed to load heartbeat procedure file: ${o}`,"error")}finally{A(!1)}},[i,n]);t.useEffect(()=>{f(!1),y(!1),j(""),Z(!1),m(null),A(!1),c(!1),N(!1)},[s.id,R]),t.useEffect(()=>()=>{F.current&&clearTimeout(F.current)},[]);const $=async()=>{R&&(f(!0),await Q(R))},G=async()=>{if(R){c(!0);try{await vt("project",R,D,n),Z(!1),N(!0),i("Heartbeat procedure file saved","success"),F.current&&clearTimeout(F.current),F.current=setTimeout(()=>N(!1),3e3),await l()}catch(b){i(`Failed to save heartbeat procedure file: ${K(b)}`,"error")}finally{c(!1)}}},h=async()=>{x(!0);try{const b=await ga(s.id,n);i(b.procedureFileSeeded?`Heartbeat procedure file ready at ${b.heartbeatProcedurePath}`:`Heartbeat procedure path set to ${b.heartbeatProcedurePath}`,"success"),await l()}catch(b){i(`Failed to upgrade heartbeat procedure: ${K(b)}`,"error")}finally{x(!1)}};return e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Heartbeat Procedure"}),e.jsxs("p",{className:"config-description",children:["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"}),") 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:["Current path: ",e.jsx("code",{children:R||"(none — using built-in default)"})]}),S&&e.jsx("div",{className:"heartbeat-procedure-actions",children:e.jsx("button",{className:"btn btn-sm",onClick:()=>void $(),disabled:v,children:v?e.jsxs(e.Fragment,{children:[e.jsx(V,{size:16,className:"animate-spin"}),"Loading file…"]}):e.jsxs(e.Fragment,{children:[e.jsx(es,{size:16}),"View Heartbeat Markdown"]})})})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("button",{className:"btn",disabled:d||Y,onClick:()=>void h(),"aria-label":"Upgrade agent to default heartbeat procedure file",children:d?e.jsxs(e.Fragment,{children:[e.jsx(V,{size:16,className:"animate-spin"}),"Upgrading…"]}):Y?e.jsxs(e.Fragment,{children:[e.jsx(ue,{size:16}),"Already on default"]}):"Upgrade to Default Heartbeat Procedure"}),e.jsxs("span",{className:"config-hint",children:["Sets ",e.jsx("code",{children:"heartbeatProcedurePath"})," to"," ",e.jsx("code",{children:W})," ","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."]})]})]}),M&&S&&R&&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:"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 ${C?"":"btn-primary"}`,onClick:()=>y(!1),disabled:!C,"aria-label":"Heartbeat file edit mode",children:[e.jsx(ss,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${C?"btn-primary":""}`,onClick:()=>y(!0),disabled:C,"aria-label":"Heartbeat file preview mode",children:[e.jsx(ts,{size:14}),"Preview"]})]}),v&&e.jsxs("span",{className:"config-hint heartbeat-procedure-status",children:[e.jsx(V,{size:12,className:"animate-spin"}),"Loading..."]}),J&&!v&&e.jsx("span",{className:"config-hint heartbeat-procedure-status heartbeat-procedure-status--warning",children:"Unsaved changes"})]}),C?D.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(as,{remarkPlugins:[ns],children:D})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:"No heartbeat procedure markdown content yet."}):e.jsx("textarea",{id:"heartbeat-procedure-file-content",className:"input",rows:16,value:D,readOnly:v,placeholder:"Heartbeat procedure markdown file content will appear here...",onChange:b=>{j(b.target.value),Z(!0),N(!1)}}),p&&e.jsxs("span",{className:"config-error",children:["Failed to load file: ",p]}),e.jsxs("span",{className:"config-hint",children:["This editor writes directly to ",e.jsx("code",{children:R}),"."]})]}),!C&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!J||P||v,onClick:()=>void G(),children:P?e.jsxs(e.Fragment,{children:[e.jsx(V,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ue,{size:16}),"Save Heartbeat File"]})}),!J&&I&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ue,{size:14}),"File saved"]})]})]})]})}function Ga({agent:s,projectId:n,addToast:i,onSaved:l,onHasChangesChange:d,onDelete:x,onAgentDraftApplied:M}){const[f,v]=t.useState(s.name),[A,P]=t.useState(s.role),[c,C]=t.useState(s.title??""),[y,D]=t.useState(s.icon??""),[j,J]=t.useState(s.reportsTo??""),[Z,p]=t.useState([]),[m,I]=t.useState(!1),[N,F]=t.useState(!1),[R,W]=t.useState(!1),O=t.useRef(null),[T,Y]=t.useState(()=>{const a={};for(const u of Qe){const w=s.metadata[u.key];w!=null&&(a[u.key]=String(w))}return a}),[S,Q]=t.useState(()=>st(s.runtimeConfig)),[$,G]=t.useState(()=>Rs(s.runtimeConfig)),[h,b]=t.useState(()=>Ms(s.runtimeConfig)),[r,o]=t.useState(()=>As(s.runtimeConfig)),[k,ne]=t.useState(()=>Fs(s.runtimeConfig)),[L,pe]=t.useState(()=>tt(s.runtimeConfig)),[re,ve]=t.useState(s.bundleConfig?.mode??""),[ie,U]=t.useState(s.bundleConfig?.entryFile??"AGENTS.md"),[le,ze]=t.useState(s.bundleConfig?.externalPath??""),[Ae,is]=t.useState(s.bundleConfig?.files??[]),[ye,We]=t.useState(Array.isArray(s.metadata?.skills)?s.metadata.skills:[]),[ls,Be]=t.useState([]),[Ge,Fe]=t.useState(!1),[ee,Oe]=t.useState([]),[$e,fe]=t.useState([]),[qe,He]=t.useState([]),[ys,Ie]=t.useState(!1),Se=(()=>{const a=s.runtimeConfig??{};return a.modelProvider&&a.modelId?`${a.modelProvider}/${a.modelId}`:typeof a.model=="string"&&a.model.includes("/")?a.model:""})(),ce=typeof s.runtimeConfig?.runtimeHint=="string"?s.runtimeConfig.runtimeHint:"",[me,Pe]=t.useState(ce?"runtime":"model"),[ge,Ue]=t.useState(Se),[we,Ee]=t.useState(ce),je=j.trim(),rs=t.useMemo(()=>Z.filter(a=>a.id!==s.id),[Z,s.id]),os=!!je&&!rs.some(a=>a.id===je),cs=t.useMemo(()=>({name:f,role:A,title:c||void 0,instructionsText:s.instructionsText,soul:s.soul,memory:s.memory,reportsTo:j||void 0,skills:ye,model:ge||void 0,runtimeHint:me==="runtime"&&we||void 0,thinkingLevel:T.thinkingLevel??void 0,maxTurns:T.maxTurns?Number(T.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}),[s.instructionsText,s.memory,s.soul,T.maxTurns,T.thinkingLevel,S.heartbeatIntervalMs,S.heartbeatTimeoutMs,S.maxConcurrentRuns,S.messageResponseMode,ge,f,j,A,me,we,ye,c]),g=t.useCallback(a=>{v(a.name),P(a.role),C(a.title??""),D(a.icon??""),J(a.reportsTo??""),a.skills&&We(a.skills),a.thinkingLevel&&Y(w=>({...w,thinkingLevel:a.thinkingLevel})),a.maxTurns!==void 0&&Y(w=>({...w,maxTurns:String(a.maxTurns)})),a.runtimeHint!==void 0?(Pe("runtime"),Ee(a.runtimeHint??""),a.runtimeHint&&Ue("")):a.model!==void 0&&(Pe("model"),Ue(a.model??""),Ee(""));const u=Object.fromEntries(Object.entries({name:a.name,role:a.role,title:a.title,icon:a.icon,reportsTo:a.reportsTo,instructionsText:a.instructionsText,soul:a.soul,memory:a.memory}).filter(([,w])=>w!==void 0));M?.(u),W(!1),i("Interview draft applied. Review and save when ready.","success")},[i,M]);t.useEffect(()=>{let a=!1;return I(!0),ps(void 0,n).then(u=>{a||p(u)}).catch(()=>{a||p([])}).finally(()=>{a||I(!1)}),()=>{a=!0}},[n]),t.useEffect(()=>{Fe(!0),sa().then(a=>{Be(a.models),Oe(a.favoriteProviders),fe(a.favoriteModels)}).catch(()=>{}).finally(()=>Fe(!1))},[]);const z=t.useCallback(async a=>{const u=ee,q=u.includes(a)?u.filter(de=>de!==a):[a,...u];Oe(q);try{await Ys({favoriteProviders:q,favoriteModels:$e})}catch{Oe(u)}},[ee,$e]),_=t.useCallback(async a=>{const u=$e,q=u.includes(a)?u.filter(de=>de!==a):[a,...u];fe(q);try{await Ys({favoriteProviders:ee,favoriteModels:q})}catch{fe(u)}},[ee,$e]);t.useEffect(()=>{Ie(!0),ft(n).then(He).catch(()=>He([])).finally(()=>Ie(!1))},[n]);const[E,te]=t.useState(null),[he,ke]=t.useState(!1);t.useEffect(()=>{Es(s.id,n).then(te).catch(()=>te(null))},[s.id,n]);const Te=async()=>{ke(!0);try{await ha(s.id,n),i("Budget usage reset successfully","success");const a=await Es(s.id,n);te(a)}catch(a){i(`Failed to reset budget: ${K(a)}`,"error")}finally{ke(!1)}},[Ce,Ke]=t.useState(!1),[H,se]=t.useState({}),[_e,Le]=t.useState(!1),[Ss,ds]=t.useState(null),Ds=s.state==="idle"||s.state==="paused",Ye=t.useRef(null),zs=t.useRef(null),Bs=t.useRef(null),us=t.useRef(0);t.useEffect(()=>()=>{Ye.current&&clearTimeout(Ye.current)},[]);const Ne=(()=>{if(f!==s.name||A!==s.role||c!==(s.title??"")||y!==(s.icon??"")||j!==(s.reportsTo??"")||re!==(s.bundleConfig?.mode??"")||ie!==(s.bundleConfig?.entryFile??"AGENTS.md")||le!==(s.bundleConfig?.externalPath??"")||JSON.stringify(Ae)!==JSON.stringify(s.bundleConfig?.files??[]))return!0;for(const X of Qe){const be=T[X.key]?.trim()??"",B=s.metadata[X.key]!==void 0&&s.metadata[X.key]!==null?String(s.metadata[X.key]):"";if(be!==B)return!0}const a=s.runtimeConfig??{};if($!==Rs(s.runtimeConfig)||h!==Ms(s.runtimeConfig)||r!==As(s.runtimeConfig)||k!==Fs(s.runtimeConfig))return!0;for(const X of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns","messageResponseMode"]){const be=S[X]?.trim()??"";let B=a[X]!==void 0&&a[X]!==null?String(a[X]):"";if((X==="heartbeatIntervalMs"||X==="heartbeatTimeoutMs")&&B&&(B=String(Number(B)/1e3)),be!==B)return!0}const u=a.budgetConfig;for(const X of["tokenBudget","budgetPeriod","resetDay"]){const be=L[X]?.trim()??"",B=u?.[X]!==void 0&&u?.[X]!==null?String(u[X]):"";if(be!==B)return!0}const w=L.usageThreshold?.trim()??"",q=u?.usageThreshold!==void 0&&u?.usageThreshold!==null?String(Number(u.usageThreshold)*100):"";if(w!==q)return!0;const de=Array.isArray(s.metadata?.skills)?s.metadata.skills:[];return JSON.stringify(ye)!==JSON.stringify(de)||me!==(ce?"runtime":"model")||ge!==Se||we!==ce})(),Os=t.useRef(null);t.useEffect(()=>{d&&Os.current!==Ne&&(Os.current=Ne,d(Ne))},[Ne,d]),t.useEffect(()=>()=>{d?.(!1)},[d]),t.useEffect(()=>{const a={id:s.id,updatedAt:s.updatedAt},u=zs.current;(!u||u.id!==a.id||u.updatedAt!==a.updatedAt)&&(Ne||(zs.current=a,Q(st(s.runtimeConfig)),G(Rs(s.runtimeConfig)),b(Ms(s.runtimeConfig)),o(As(s.runtimeConfig)),ne(Fs(s.runtimeConfig)),pe(tt(s.runtimeConfig)),Ue(Se),Ee(ce),Pe(ce?"runtime":"model")))},[s,Ne,Se,ce]);const Hs=(a,u)=>{Y(w=>({...w,[a]:u})),Le(!1),H[a]&&se(w=>{const q={...w};return delete q[a],q})},ms=(a,u)=>{Q(w=>({...w,[a]:u})),Le(!1),H[a]&&se(w=>{const q={...w};return delete q[a],q})},Nt=a=>{G(a),Le(!1)},hs=(a,u)=>{pe(w=>({...w,[a]:u})),Le(!1),H[a]&&se(w=>{const q={...w};return delete q[a],q})},Re=t.useMemo(()=>{const a=Ua(T);for(const[B,De]of Object.entries({heartbeatIntervalMs:{label:"Heartbeat Interval",min:1},heartbeatTimeoutMs:{label:"Heartbeat Timeout",min:5},maxConcurrentRuns:{label:"Max Concurrent Runs",min:1}})){const oe=S[B]?.trim();if(!oe)continue;const Me=Number(oe);Number.isNaN(Me)||!Number.isFinite(Me)?a[B]=`"${De.label}" must be a valid number`:Me<De.min&&(a[B]=`"${De.label}" must be at least ${De.min.toLocaleString()}`)}const u=S.messageResponseMode?.trim();u&&!["immediate","on-heartbeat"].includes(u)&&(a.messageResponseMode='"Message Response Mode" must be either immediate or on-heartbeat');const w=L.tokenBudget?.trim();if(w){const B=Number(w);Number.isNaN(B)||!Number.isFinite(B)?a.tokenBudget='"Token Budget" must be a valid number':B<=0&&(a.tokenBudget='"Token Budget" must be greater than 0')}const q=L.usageThreshold?.trim();if(q){const B=Number(q);Number.isNaN(B)||!Number.isFinite(B)?a.usageThreshold='"Usage Threshold" must be a valid number':(B<1||B>100)&&(a.usageThreshold='"Usage Threshold" must be between 1 and 100')}const de=L.budgetPeriod?.trim();de&&!["daily","weekly","monthly","lifetime"].includes(de)&&(a.budgetPeriod='"Budget Period" must be one of: daily, weekly, monthly, lifetime');const X=L.resetDay?.trim(),be=de||"lifetime";if(X){const B=Number(X);Number.isNaN(B)||!Number.isFinite(B)?a.resetDay='"Reset Day" must be a valid number':be==="weekly"?(B<0||B>6||!Number.isInteger(B))&&(a.resetDay='"Reset Day" must be between 0 (Sunday) and 6 (Saturday) for weekly period'):be==="monthly"&&(B<1||B>31||!Number.isInteger(B))&&(a.resetDay='"Reset Day" must be between 1 and 31 for monthly period')}return a},[T,S,L]),Is=t.useCallback(()=>{if(Object.keys(Re).length>0)return null;const a={...s.metadata};for(const oe of Qe){const Me=T[oe.key]?.trim();Me?oe.type==="number"?a[oe.key]=Number(Me):a[oe.key]=Me:delete a[oe.key]}ye.length>0?a.skills=ye:delete a.skills;const u={...s.runtimeConfig};u.enabled=$,u.autoClaimRelevantTasks=h,u.runMissedHeartbeatOnStartup=r,u.allowParallelExecution=k;for(const oe of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns"]){const Me=S[oe]?.trim();if(!Me)delete u[oe];else{const _s=Number(Me);u[oe]=oe==="maxConcurrentRuns"?_s:_s*1e3}}const w=S.messageResponseMode?.trim();if(w?u.messageResponseMode=w:delete u.messageResponseMode,me==="runtime")we.trim()?u.runtimeHint=we.trim():delete u.runtimeHint,delete u.modelProvider,delete u.modelId,delete u.model;else if(delete u.runtimeHint,ge.trim()){const oe=ge.indexOf("/");oe!==-1&&(u.modelProvider=ge.slice(0,oe),u.modelId=ge.slice(oe+1),u.model=ge.trim())}else delete u.modelProvider,delete u.modelId,delete u.model;const q={},de=L.tokenBudget?.trim(),X=L.usageThreshold?.trim(),be=L.budgetPeriod?.trim(),B=L.resetDay?.trim();de&&(q.tokenBudget=Number(de)),X&&(q.usageThreshold=Number(X)/100),be&&(q.budgetPeriod=be),B&&(q.resetDay=Number(B)),Object.keys(q).length>0?u.budgetConfig=q:delete u.budgetConfig;let De;return re&&(De={mode:re,entryFile:ie||"AGENTS.md",files:Ae.length>0?Ae:["AGENTS.md"]},re==="external"&&le.trim()&&(De.externalPath=le.trim())),{name:f.trim()||void 0,role:A,title:c.trim()||void 0,icon:y.trim()||void 0,reportsTo:j.trim()||void 0,metadata:a,runtimeConfig:u,bundleConfig:De}},[s.metadata,s.runtimeConfig,k,h,L,ie,le,Ae,re,T,$,S,y,ge,f,j,A,r,me,we,ye,c,Re]),Ze=t.useCallback(async(a,u)=>{const w=Is();if(!w)return se(Re),a&&i("Please fix validation errors before saving","error"),u==="auto"&&ds("Fix validation errors to save changes"),!1;const q=JSON.stringify(w);if(q===Bs.current)return!1;const de=++us.current;se({}),ds(null),Ke(!0);try{return await ta(s.id,w,n),de!==us.current?!1:(Bs.current=q,u==="manual"&&i("Settings saved","success"),ds(null),Le(!0),Ye.current&&clearTimeout(Ye.current),Ye.current=setTimeout(()=>Le(!1),3e3),await l(),!0)}catch(X){if(de===us.current){const be=K(X);ds(be),i(`Failed to save settings: ${be}`,"error")}return!1}finally{de===us.current&&Ke(!1)}},[i,s.id,Is,l,n,Re]),yt=async()=>{await Ze(!0,"manual")},xe=t.useCallback(()=>{if(!(!Ne||Ce)){if(Object.keys(Re).length>0){se(Re);return}Ze(!1,"auto")}},[Ne,Ce,Ze,Re]);t.useEffect(()=>{if(!Ne||Ce)return;if(Object.keys(Re).length>0){se(Re);return}const a=setTimeout(()=>{Ze(!1,"auto")},Ea);return()=>clearTimeout(a)},[Ne,Ce,Ze,Re]);const St=t.useCallback(async a=>{F(!0);try{await aa(s.id,a,n),await l(),i("Avatar uploaded","success")}catch(u){i(K(u),"error")}finally{F(!1),O.current&&(O.current.value="")}},[i,s.id,l,n]),kt=t.useCallback(async()=>{F(!0);try{await na(s.id,n),await l(),i("Avatar removed","success")}catch(a){i(K(a),"error")}finally{F(!1)}},[i,s.id,l,n]),Us=Ce?"Saving changes…":Ss?`Save failed: ${Ss}`:!Ne&&_e?"All changes saved":null;return e.jsxs("div",{className:"config-tab",children:[e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Agent Configuration"}),e.jsx("p",{className:"config-description",children:"Configure agent settings and behavior."}),e.jsx("div",{className:"config-actions-row",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>W(!0),children:"AI Interview"})}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-name",children:"Name"}),e.jsx("input",{id:"agent-name",type:"text",className:"input",value:f,onChange:a=>v(a.target.value),onBlur:()=>{xe()}})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-role",children:"Role"}),e.jsxs("select",{id:"agent-role",className:"select",value:A,onChange:a=>{P(a.target.value),xe()},children:[e.jsx("option",{value:"triage",children:"Triage"}),e.jsx("option",{value:"executor",children:"Executor"}),e.jsx("option",{value:"reviewer",children:"Reviewer"}),e.jsx("option",{value:"merger",children:"Merger"}),e.jsx("option",{value:"scheduler",children:"Scheduler"}),e.jsx("option",{value:"custom",children:"Custom"})]})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-title",children:"Title"}),e.jsx("input",{id:"agent-title",type:"text",className:"input",placeholder:"e.g. Senior Code Reviewer",value:c,onChange:a=>C(a.target.value),onBlur:()=>{xe()}})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{children:"Avatar"}),e.jsxs("div",{className:"agent-avatar-editor",children:[e.jsx(ct,{agent:s,size:64,className:"agent-avatar-editor-preview"}),e.jsxs("div",{className:"agent-avatar-editor-actions",children:[e.jsx("input",{ref:O,id:"agent-avatar-upload",type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",className:"visually-hidden",disabled:N,onChange:a=>{const u=a.target.files?.[0];u&&St(u)}}),e.jsx("button",{type:"button",className:"btn btn-sm",disabled:N,onClick:()=>O.current?.click(),children:"Upload Avatar"}),s.imageUrl?e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void kt(),disabled:N,children:"Remove Avatar"}):null]})]})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-icon",children:"Icon"}),e.jsx("input",{id:"agent-icon",type:"text",className:"input",placeholder:"e.g. 🤖",value:y,onChange:a=>D(a.target.value),onBlur:()=>{xe()}})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-reports-to",children:"Reports To"}),e.jsxs("select",{id:"agent-reports-to",className:"select",value:j,onChange:a=>{J(a.target.value),xe()},disabled:m,children:[e.jsx("option",{value:"",children:"No manager"}),os&&e.jsxs("option",{value:je,children:["Unknown manager (",je,")"]}),rs.map(a=>e.jsxs("option",{value:a.id,children:[a.name," (",a.id,")"]},a.id))]})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Skills"}),e.jsx("p",{className:"config-description",children:"Assign skills to this agent for specialized behavior."}),e.jsx("div",{className:"config-fields",children:e.jsx("div",{className:"config-field",children:e.jsx(xa,{id:"agent-skills",label:"Skills",value:ye,onChange:a=>{We(a),xe()},projectId:n})})})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Model"}),e.jsx("p",{className:"config-description",children:"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:"Runtime Source"}),e.jsxs("div",{className:"config-runtime-tabs",role:"tablist","aria-label":"Runtime source",children:[e.jsx("button",{type:"button",className:`config-runtime-tab${me==="model"?" active":""}`,role:"tab","aria-selected":me==="model",tabIndex:me==="model"?0:-1,onClick:()=>{Pe("model"),Ee(""),xe()},children:"Built-in Model"}),e.jsx("button",{type:"button",className:`config-runtime-tab${me==="runtime"?" active":""}`,role:"tab","aria-selected":me==="runtime",tabIndex:me==="runtime"?0:-1,onClick:()=>{Pe("runtime"),xe()},children:"Plugin Runtime"})]})]}),me==="model"?e.jsx("div",{className:"config-field",children:e.jsx(ia,{models:ls,value:ge,onChange:a=>{Ue(a),xe()},placeholder:"Use global default",label:"Agent Model",disabled:Ge,favoriteProviders:ee,onToggleFavorite:z,favoriteModels:$e,onToggleModelFavorite:_})}):e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-runtime-hint",children:"Runtime"}),ys?e.jsx("span",{className:"config-hint",children:"Loading runtimes…"}):e.jsxs("select",{id:"agent-runtime-hint",className:"select",value:we,onChange:a=>{Ee(a.target.value),xe()},children:[e.jsx("option",{value:"",children:qe.length>0?"Select a plugin runtime…":"No plugin runtimes available"}),qe.map(a=>e.jsx("option",{value:a.runtimeId,children:a.description?`${a.name} — ${a.description}`:a.name},`${a.pluginId}:${a.runtimeId}`))]})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Heartbeat Settings"}),e.jsx("p",{className:"config-description",children:"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",children:[e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-enabled",children:[e.jsx("input",{id:"hb-enabled",type:"checkbox",checked:$,onChange:a=>{Nt(a.target.checked),xe()}}),"Heartbeat Enabled"]}),e.jsx("span",{className:"config-hint",children:"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-autoClaimRelevantTasks",children:[e.jsx("input",{id:"hb-autoClaimRelevantTasks",type:"checkbox",checked:h,onChange:a=>{b(a.target.checked),xe()}}),"Auto-Claim Relevant Tasks"]}),e.jsx("span",{className:"config-hint",children:"When enabled (default), no-task heartbeats scan open unowned work and auto-claim tasks aligned with this agent's role and soul."})]}),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:r,onChange:a=>{o(a.target.checked),xe()}}),"Run Missed Heartbeat On Startup"]}),e.jsx("span",{className:"config-hint",children:"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:k,onChange:a=>{ne(a.target.checked),xe()}}),"Allow Parallel Execution"]}),e.jsx("span",{className:"config-hint",children:"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.jsx("label",{htmlFor:"hb-heartbeatIntervalMs",children:"Heartbeat Interval (s)"}),e.jsx("input",{id:"hb-heartbeatIntervalMs",type:"text",inputMode:"numeric",className:ae("input",!!H.heartbeatIntervalMs&&"input--error"),placeholder:String(Ts/1e3),value:S.heartbeatIntervalMs??"",onChange:a=>ms("heartbeatIntervalMs",a.target.value)}),H.heartbeatIntervalMs?e.jsx("span",{className:"config-error",children:H.heartbeatIntervalMs}):e.jsxs("span",{className:"config-hint",children:["How often heartbeats are checked. Leave empty for system default (",Ts/1e3,"s / ",Fa,")."]})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-heartbeatTimeoutMs",children:"Heartbeat Timeout (s)"}),e.jsx("input",{id:"hb-heartbeatTimeoutMs",type:"text",inputMode:"numeric",className:ae("input",!!H.heartbeatTimeoutMs&&"input--error"),placeholder:"60",value:S.heartbeatTimeoutMs??"",onChange:a=>ms("heartbeatTimeoutMs",a.target.value)}),H.heartbeatTimeoutMs?e.jsx("span",{className:"config-error",children:H.heartbeatTimeoutMs}):e.jsx("span",{className:"config-hint",children:"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:"Max Concurrent Runs"}),e.jsx("input",{id:"hb-maxConcurrentRuns",type:"text",inputMode:"numeric",className:ae("input",!!H.maxConcurrentRuns&&"input--error"),placeholder:"1",value:S.maxConcurrentRuns??"",onChange:a=>ms("maxConcurrentRuns",a.target.value)}),H.maxConcurrentRuns?e.jsx("span",{className:"config-error",children:H.maxConcurrentRuns}):e.jsx("span",{className:"config-hint",children:"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:"Message Response Mode"}),e.jsxs("select",{id:"hb-messageResponseMode",className:ae("select",!!H.messageResponseMode&&"input--error"),value:S.messageResponseMode??"",onChange:a=>ms("messageResponseMode",a.target.value),children:[e.jsx("option",{value:"",children:"System Default (On Heartbeat)"}),e.jsx("option",{value:"on-heartbeat",children:"On Heartbeat"}),e.jsx("option",{value:"immediate",children:"Immediate"})]}),H.messageResponseMode?e.jsx("span",{className:"config-error",children:H.messageResponseMode}):e.jsx("span",{className:"config-hint",children:"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:"Budget Settings"}),e.jsx("p",{className:"config-description",children:"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:"Token Budget"}),e.jsx("input",{id:"budget-tokenBudget",type:"text",inputMode:"numeric",className:ae("input",!!H.tokenBudget&&"input--error"),placeholder:"No limit",value:L.tokenBudget??"",onChange:a=>hs("tokenBudget",a.target.value)}),H.tokenBudget?e.jsx("span",{className:"config-error",children:H.tokenBudget}):e.jsx("span",{className:"config-hint",children:"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:"Usage Threshold (%)"}),e.jsx("input",{id:"budget-usageThreshold",type:"text",inputMode:"numeric",className:ae("input",!!H.usageThreshold&&"input--error"),placeholder:"80",value:L.usageThreshold??"",onChange:a=>hs("usageThreshold",a.target.value)}),H.usageThreshold?e.jsx("span",{className:"config-error",children:H.usageThreshold}):e.jsx("span",{className:"config-hint",children:"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:"Budget Period"}),e.jsxs("select",{id:"budget-budgetPeriod",className:ae("select",!!H.budgetPeriod&&"input--error"),value:L.budgetPeriod??"",onChange:a=>hs("budgetPeriod",a.target.value),children:[e.jsx("option",{value:"",children:"No reset (lifetime)"}),e.jsx("option",{value:"daily",children:"Daily"}),e.jsx("option",{value:"weekly",children:"Weekly"}),e.jsx("option",{value:"monthly",children:"Monthly"})]}),H.budgetPeriod?e.jsx("span",{className:"config-error",children:H.budgetPeriod}):e.jsx("span",{className:"config-hint",children:"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:"Reset Day"}),e.jsx("input",{id:"budget-resetDay",type:"text",inputMode:"numeric",className:ae("input",!!H.resetDay&&"input--error"),placeholder:"Auto",value:L.resetDay??"",onChange:a=>hs("resetDay",a.target.value)}),H.resetDay?e.jsx("span",{className:"config-error",children:H.resetDay}):e.jsx("span",{className:"config-hint",children:L.budgetPeriod==="weekly"?"Day of week (0=Sunday to 6=Saturday) for reset.":L.budgetPeriod==="monthly"?"Day of month (1-31) for reset.":"Day for reset (weekly: 0-6, monthly: 1-31). Leave empty for automatic."})]}),E?.budgetLimit!=null&&e.jsxs("div",{className:"config-field",children:[e.jsx("label",{children:"Current Usage"}),e.jsxs("div",{className:"budget-progress-container",children:[e.jsx("div",{className:"budget-progress-bar",children:e.jsx("div",{className:ae("budget-progress-bar__fill",(E.usagePercent??0)>=100?"budget-progress-bar__fill--red":(E.usagePercent??0)>=80?"budget-progress-bar__fill--amber":"budget-progress-bar__fill--green"),style:{width:`${Math.min(E.usagePercent??0,100)}%`}})}),e.jsxs("span",{className:"budget-progress-label",children:[(E.currentUsage??0).toLocaleString()," / ",(E.budgetLimit??0).toLocaleString()," tokens (",Math.round(E.usagePercent??0),"% used)"]})]})]}),E?.budgetLimit!=null&&e.jsx("div",{className:"config-field",children:e.jsx("button",{className:"btn btn-reset-budget",onClick:()=>void Te(),disabled:he,children:he?e.jsxs(e.Fragment,{children:[e.jsx(V,{size:14,className:"animate-spin"}),"Resetting…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ns,{size:14}),"Reset Budget Usage"]})})})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Instruction Bundle"}),e.jsx("p",{className:"config-description",children:"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:"Bundle Mode"}),e.jsxs("select",{id:"bundle-mode",className:"select",value:re,onChange:a=>ve(a.target.value),children:[e.jsx("option",{value:"",children:"None (use inline instructions)"}),e.jsx("option",{value:"managed",children:"Managed (system-managed directory)"}),e.jsx("option",{value:"external",children:"External (user-specified path)"})]}),e.jsxs("span",{className:"config-hint",children:[re==="managed"&&"Files will be stored in a system-managed directory within .fusion/agents/",re==="external"&&"Specify an external directory path for the instruction files",!re&&"Select a mode to enable instruction bundling"]})]}),re&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-entry-file",children:"Entry File"}),e.jsx("input",{id:"bundle-entry-file",type:"text",className:"input",placeholder:"AGENTS.md",value:ie,onChange:a=>U(a.target.value)}),e.jsx("span",{className:"config-hint",children:"Primary instructions file name (default: AGENTS.md)"})]}),re==="external"&&e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-external-path",children:"External Path"}),e.jsx("input",{id:"bundle-external-path",type:"text",className:"input",placeholder:"e.g. .fusion/agents/my-agent",value:le,onChange:a=>ze(a.target.value)}),e.jsx("span",{className:"config-hint",children:"Absolute or relative path to the external directory"})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-files",children:"Files (comma-separated)"}),e.jsx("input",{id:"bundle-files",type:"text",className:"input",placeholder:"AGENTS.md, PROMPTS.md",value:Ae.join(", "),onChange:a=>is(a.target.value.split(",").map(u=>u.trim()).filter(Boolean))}),e.jsx("span",{className:"config-hint",children:"List of file names in the bundle directory"})]})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Advanced Settings"}),e.jsx("p",{className:"config-description",children:"Advanced configuration options for this agent. Leave a field empty to use system defaults."}),e.jsx("div",{className:"config-fields",children:Qe.map(a=>{const u=!!H[a.key];return e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:`adv-${a.key}`,children:a.label}),a.type==="select"?e.jsxs("select",{id:`adv-${a.key}`,className:ae("select",u&&"input--error"),value:T[a.key]??"",onChange:w=>Hs(a.key,w.target.value),children:[e.jsx("option",{value:"",children:"System Default"}),a.options?.map(w=>e.jsx("option",{value:w.value,children:w.label},w.value))]}):e.jsx("input",{id:`adv-${a.key}`,type:"text",inputMode:a.type==="number"?"numeric":void 0,className:ae("input",u&&"input--error"),placeholder:a.placeholder,value:T[a.key]??"",onChange:w=>Hs(a.key,w.target.value)}),u&&e.jsx("span",{className:"config-error",children:H[a.key]}),!u&&a.hint&&e.jsx("span",{className:"config-hint",children:a.hint})]},a.key)})}),e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!Ne||Ce,onClick:()=>void yt(),children:Ce?e.jsxs(e.Fragment,{children:[e.jsx(V,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ue,{size:16}),"Save Settings"]})}),Us&&e.jsxs("span",{className:ae("config-saved-indicator",Ss&&"config-saved-indicator--error"),children:[Ce?e.jsx(V,{size:14,className:"animate-spin"}):e.jsx(ue,{size:14}),Us]})]})]}),e.jsx(Wa,{agent:s,projectId:n,addToast:i,onSaved:l}),e.jsxs("div",{className:"config-section config-section--danger",children:[e.jsx("h3",{children:"Danger Zone"}),e.jsx("p",{className:"config-description",children:"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:!Ds||!x,onClick:()=>void x?.(),children:[e.jsx(bs,{size:16}),"Delete Agent"]}),e.jsx("span",{className:"config-danger-note",children:Ds?"Deletion is permanent and cannot be undone.":`Agent deletion is only available when state is idle or paused (current state: ${s.state}).`})]})})]}),e.jsx(ba,{isOpen:R,onClose:()=>W(!1),onUseDraft:g,projectId:n,existingAgents:Z,mode:"edit",existingAgentConfig:cs})]})}function qa({agentId:s,projectId:n,onChildClick:i}){const[l,d]=t.useState([]),[x,M]=t.useState(!0);return t.useEffect(()=>{M(!0),Xt(s,n).then(d).finally(()=>M(!1))},[s,n]),x?e.jsxs("div",{className:"detail-section",children:[e.jsx("div",{className:"detail-section-header",children:e.jsx("h3",{children:"Employees"})}),e.jsxs("div",{className:"detail-section-body detail-section-body--loading",children:[e.jsx(V,{size:16,className:"spin"}),e.jsx("span",{className:"text-muted",children:"Loading employees..."})]})]}):e.jsxs("div",{className:"detail-section",children:[e.jsxs("div",{className:"detail-section-header",children:[e.jsx("h3",{children:"Employees"}),e.jsxs("span",{className:"text-muted",children:["(",l.length,")"]})]}),e.jsx("div",{className:"detail-section-body",children:l.length===0?e.jsxs("div",{className:"agent-empty agent-empty--padded",children:[e.jsx(mt,{size:32,opacity:.3}),e.jsx("p",{children:"No employees"}),e.jsx("p",{className:"text-muted",children:"This agent has no employees"})]}):e.jsx("div",{className:"agent-tree__children",children:l.map(f=>{const v=Ls[f.state];return e.jsxs("div",{className:"agent-tree__node agent-is-child",onClick:()=>i?.(f.id),role:"button",tabIndex:0,onKeyDown:A=>{(A.key==="Enter"||A.key===" ")&&(A.key===" "&&A.preventDefault(),i?.(f.id))},style:{cursor:i?"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:v?.bg??"var(--state-idle-bg)",color:v?.text??"var(--state-idle-text)",border:`1px solid ${v?.border??"var(--state-idle-border)"}`},children:f.state})]},f.id)})})})]})}export{en as AgentDetailView,Je as relativeTime};