@runfusion/fusion 0.32.0 → 0.34.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 (63) hide show
  1. package/dist/bin.js +24129 -11045
  2. package/dist/client/.vite/manifest.json +62 -61
  3. package/dist/client/assets/{AgentDetailView-CnFf_eBZ.js → AgentDetailView-CzqwIIpv.js} +3 -3
  4. package/dist/client/assets/{AgentPermissionPolicyEditor-Cmkt9Z01.js → AgentPermissionPolicyEditor-2eoM2XQH.js} +2 -2
  5. package/dist/client/assets/AgentsView-BrtAvhJl.js +29 -0
  6. package/dist/client/assets/ChatView-BuIe4MhL.js +6 -0
  7. package/dist/client/assets/DevServerView-CF6FPLRb.js +1 -0
  8. package/dist/client/assets/{DirectoryPicker-DctpCNrd.js → DirectoryPicker-BpvHQxhu.js} +1 -1
  9. package/dist/client/assets/{DocumentsView-DORp5JjC.js → DocumentsView-RMWZBJ-y.js} +1 -1
  10. package/dist/client/assets/{EvalsView-CYVJ1pbc.js → EvalsView-DtVxpc4T.js} +1 -1
  11. package/dist/client/assets/{ExperimentalAgentOnboardingModal-BULVNAiq.js → ExperimentalAgentOnboardingModal-fzJmb-yG.js} +2 -2
  12. package/dist/client/assets/{GoalsView-bmpZKOI_.js → GoalsView-BAchggxo.js} +1 -1
  13. package/dist/client/assets/{InsightsView-mmtem0RU.js → InsightsView-B8892IbG.js} +1 -1
  14. package/dist/client/assets/{MemoryView-HVpO1fCH.js → MemoryView-Cfp1WmAm.js} +2 -2
  15. package/dist/client/assets/NodesView-Dt26DSEQ.js +14 -0
  16. package/dist/client/assets/{PiExtensionsManager-Cyfas2VT.js → PiExtensionsManager-xHU56SMh.js} +2 -2
  17. package/dist/client/assets/{PluginManager-C7QDE3Lk.js → PluginManager-37WUEOmp.js} +1 -1
  18. package/dist/client/assets/ResearchView-pu88M5xL.js +1 -0
  19. package/dist/client/assets/SecretsView-BT7ofJLN.js +1 -0
  20. package/dist/client/assets/{SecretsView-BFhVwJu6.css → SecretsView-D5bHZ-wM.css} +1 -1
  21. package/dist/client/assets/SettingsModal-0gevFhXV.css +1 -0
  22. package/dist/client/assets/SettingsModal-Cz9MHNGg.js +31 -0
  23. package/dist/client/assets/{SettingsModal-YCJM5is3.js → SettingsModal-DxYXsn08.js} +1 -1
  24. package/dist/client/assets/{SetupWizardModal-BT-mj3VD.js → SetupWizardModal-yWTk3Cac.js} +1 -1
  25. package/dist/client/assets/{SkillsView-Db7dYpqd.js → SkillsView-CWNfKNTs.js} +1 -1
  26. package/dist/client/assets/{StashRecoveryView-CSYYcWux.js → StashRecoveryView-D0t4IIX-.js} +1 -1
  27. package/dist/client/assets/{TodoView-zqCqfy26.js → TodoView-B4W1Lhy6.js} +2 -2
  28. package/dist/client/assets/{dashboard-view-PpcsMDvN.js → dashboard-view-4OCJIthP.js} +1 -1
  29. package/dist/client/assets/{folder-open-mxsFQlAX.js → folder-open-BTdhwFQ5.js} +1 -1
  30. package/dist/client/assets/index-D4nQgFjo.js +742 -0
  31. package/dist/client/assets/index-k4s0JWir.css +1 -0
  32. package/dist/client/assets/{upload-j7JjaJzG.js → upload-kESyjow_.js} +1 -1
  33. package/dist/client/assets/{users-DZ_0WcB6.js → users-DNXMrdcp.js} +1 -1
  34. package/dist/client/index.html +102 -3
  35. package/dist/client/version.json +1 -1
  36. package/dist/droid-cli/package.json +1 -1
  37. package/dist/extension.js +18838 -6745
  38. package/dist/pi-claude-cli/package.json +1 -1
  39. package/dist/plugins/fusion-plugin-cli-printing-press/package.json +1 -1
  40. package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
  41. package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
  42. package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
  43. package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
  44. package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
  45. package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
  46. package/dist/plugins/fusion-plugin-reports/package.json +1 -1
  47. package/dist/plugins/fusion-plugin-reports/src/dashboard/__tests__/ReportsView.test.tsx +15 -0
  48. package/dist/plugins/fusion-plugin-reports/src/dashboard/test-setup.ts +9 -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/extension-tools.md +4 -1
  53. package/skill/fusion/references/fusion-capabilities.md +1 -1
  54. package/dist/client/assets/AgentsView-LkVv9hph.js +0 -34
  55. package/dist/client/assets/ChatView-DYjECCRG.js +0 -1
  56. package/dist/client/assets/DevServerView-D7legPr1.js +0 -1
  57. package/dist/client/assets/NodesView-CM0eoCP8.js +0 -14
  58. package/dist/client/assets/ResearchView-Bn2WxwnQ.js +0 -1
  59. package/dist/client/assets/SecretsView-DgrrgzFc.js +0 -1
  60. package/dist/client/assets/SettingsModal-BCZrCLl3.js +0 -31
  61. package/dist/client/assets/SettingsModal-BZBV2kLr.css +0 -1
  62. package/dist/client/assets/index-Ba-F8c1g.js +0 -732
  63. package/dist/client/assets/index-D4HhaIOp.css +0 -1
@@ -1,4 +1,4 @@
1
- import{r as t,j as e}from"./vendor-react-K0fH_qHe.js";import{c as Us,dQ as It,dR as Ot,dS as _t,dT as Ut,L as q,R as Rs,ax as tt,Z as Vt,ay as Ps,Y as Ss,a as xt,b as bt,dU as Jt,dV as Wt,dW as qt,v as pt,cU as Gt,dX as Yt,z as I,dY as Kt,dZ as vt,d_ as jt,d$ as Xt,i as ks,D as Es,s as Ns,by as Nt,k as yt,V as Ts,A as Cs,W as at,aY as Ye,e0 as Zt,X as St,F as is,e1 as Qt,cp as kt,e2 as Ct,e3 as ea,cM as sa,av as ta,bx as aa,az as wt,B as Vs,$ as na,a3 as nt,a4 as ia,a5 as la,e4 as Os,l as Rt,e5 as ra,bJ as oa,r as ca,aw as Mt,a2 as At,e6 as da,C as me,e7 as Ft,e8 as it,bA as lt,e9 as ua,ea as ma,eb as ha,ec as fa,ed as ls,ae as rs,ag as os,ah as cs,ac as Pt,ee as ga,ef as xa,cX as ba,h as pa,j as rt,a0 as ot,eg as va,eh as ja,m as Na,ei as _s,ej as ya,ek as Sa,Q as ka,el as Ca,em as wa,en as Et,eo as Ra,ep as Ma,eq as Aa,er as Fa,es as Pa}from"./index-Ba-F8c1g.js";import{S as Tt,A as Ea}from"./AgentPermissionPolicyEditor-Cmkt9Z01.js";import{f as $s,S as Ta,E as $a}from"./ExperimentalAgentOnboardingModal-BULVNAiq.js";import"./vendor-xterm-DzcZoU0P.js";import"./vendor-codemirror-jBKmHyH0.js";/**
1
+ import{r as t,j as e}from"./vendor-react-K0fH_qHe.js";import{c as Us,d_ as It,d$ as Ot,e0 as _t,e1 as Ut,L as q,R as Rs,ay as tt,Z as Vt,az as Ps,_ as Ss,a as xt,b as bt,e2 as Jt,e3 as Wt,e4 as qt,v as pt,c$ as Gt,e5 as Kt,z as I,e6 as Yt,e7 as vt,e8 as jt,e9 as Qt,i as ks,D as Es,s as Ns,bD as Nt,k as yt,Q as Ts,A as Cs,O as at,a_ as Ke,ea as Zt,X as St,F as is,eb as Xt,cw as kt,ec as Ct,ed as ea,cT as sa,aw as ta,bC as aa,aA as wt,B as Vs,a1 as na,$ as nt,a5 as ia,a6 as la,ee as Os,l as Rt,ef as ra,bQ as oa,r as ca,ax as Mt,a4 as At,eg as da,C as me,eh as Ft,ei as it,bG as lt,ej as ua,ek as ma,el as ha,em as fa,en as ls,af as rs,ah as os,ai as cs,ad as Pt,eo as ga,ep as xa,d2 as ba,h as pa,j as rt,a2 as ot,eq as va,er as ja,m as Na,es as _s,et as ya,eu as Sa,V as ka,ev as Ca,ew as wa,ex as Et,ey as Ra,ez as Ma,eA as Aa,eB as Fa,eC as Pa}from"./index-D4nQgFjo.js";import{S as Tt,A as Ea}from"./AgentPermissionPolicyEditor-2eoM2XQH.js";import{f as $s,S as Ta,E as $a}from"./ExperimentalAgentOnboardingModal-fzJmb-yG.js";import"./vendor-xterm-DzcZoU0P.js";import"./vendor-codemirror-jBKmHyH0.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 Us,dQ as It,dR
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 Ha=[["path",{d:"M16 17h6v-6",key:"t6n2it"}],["path",{d:"m22 17-8.5-8.5-5 5L2 7",key:"x473p"}]],Ba=Us("trending-down",Ha);function ct(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 Ia(s){return`${Math.round(s*100)}%`}function dt(s){const n=Date.now(),i=new Date(s).getTime(),l=n-i;if(l<0){const m=Math.abs(l);return m<6e4?"in a moment":m<36e5?`in ${Math.floor(m/6e4)}m`:m<864e5?`in ${Math.floor(m/36e5)}h`:`in ${Math.floor(m/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 Oa(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 as(s){return s instanceof Error&&s.message?s.message:String(s)}function _a(s){switch(s){case"improving":return"↑ Improving";case"declining":return"↓ Declining";case"stable":return"→ Stable";default:return"Insufficient data"}}function Ua(s){switch(s){case"improving":return"trend-improving";case"declining":return"trend-declining";case"stable":return"trend-stable";default:return"trend-insufficient"}}function ut(s,n=5){return e.jsx("span",{className:"rating-stars",children:Array.from({length:n},(i,l)=>e.jsx(Tt,{size:14,className:l<s?"star-filled":"star-empty",fill:l<s?"currentColor":"none"},l))})}function Va({agentId:s,projectId:n,addToast:i}){const[l,m]=t.useState([]),[g,P]=t.useState(null),[f,M]=t.useState(null),[N,L]=t.useState([]),[c,C]=t.useState(!0),[A,E]=t.useState(!0),[y,Q]=t.useState(!1),[J,p]=t.useState(!1),[v,S]=t.useState(null),[j,T]=t.useState(0),[F,O]=t.useState(""),[X,D]=t.useState(""),Z=t.useCallback(async()=>{try{const[r,$]=await Promise.all([It(s,20,n),Ot(s,void 0,n)]);m(r),P($)}catch(r){i(`Failed to load reflections: ${as(r)}`,"error")}finally{C(!1)}},[s,n,i]),k=t.useCallback(async()=>{try{const[r,$]=await Promise.all([_t(s,n),Ut(s,{limit:50},n)]);M(r),L($)}catch(r){i(`Failed to load ratings: ${as(r)}`,"error")}finally{E(!1)}},[s,n,i]);t.useEffect(()=>{Z(),k()},[Z,k]);const ae=async()=>{Q(!0);try{if(!await Jt(s,n)){i("Not enough history to generate a reflection yet","error");return}i("Reflection generated successfully","success"),C(!0),await Z()}catch(r){const $=as(r),W=$.toLowerCase();W.includes("agent not found")||W.includes("not found")?i("This agent is no longer available. It may have been deleted.","error"):W.includes("insufficient history")?i("Not enough history to generate a reflection yet","error"):i(`Failed to generate reflection: ${$}`,"error")}finally{Q(!1)}},R=async r=>{if(r.preventDefault(),j!==0){p(!0);try{await Wt(s,{score:j,category:F||void 0,comment:X||void 0,raterType:"user"},n),T(0),O(""),D(""),i("Rating added","success"),await k()}catch($){i(`Failed to add rating: ${as($)}`,"error")}finally{p(!1)}}},_=async r=>{try{await qt(s,r,n),i("Rating deleted","success"),await k()}catch($){i(`Failed to delete rating: ${as($)}`,"error")}},h=r=>{S($=>$===r?null:r)};if(c&&A)return e.jsx("div",{className:"reflections-tab",children:e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(q,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading evaluation..."})]})});const x=g&&g.totalTasksCompleted===0&&g.totalTasksFailed===0&&g.recentReflectionCount===0;return e.jsxs("div",{className:"reflections-tab",children:[e.jsxs("div",{className:"reflections-header",children:[e.jsxs("h3",{children:[e.jsx(ys,{size:16}),"Performance, Reflections & Ratings"]}),e.jsx("button",{className:"btn btn-secondary",onClick:ae,disabled:y,title:"Generate a manual reflection",children:y?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:14,className:"animate-spin"}),"Reflecting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Rs,{size:14}),"Reflect Now"]})})]}),g&&!x&&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(tt,{size:16,style:{color:"var(--color-success)"}}),g.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(Ba,{size:16,style:{color:"var(--color-error)"}}),g.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(Vt,{size:16,style:{color:"var(--in-progress)"}}),ct(g.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(ys,{size:16,style:{color:g.successRate>=.8?"var(--color-success)":g.successRate>=.5?"var(--color-warning)":"var(--color-error)"}}),Ia(g.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(Ps,{size:16,style:{color:"var(--color-info)"}}),g.recentReflectionCount]}),e.jsx("div",{className:"stat-label",children:"Reflections"})]})]}),x&&e.jsxs("div",{className:"reflections-no-data",children:[e.jsx(ys,{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"}),A?e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(q,{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)}),ut(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 ${Ua(f.trend)}`,children:_a(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,$])=>e.jsxs("div",{className:"category-item",children:[e.jsx("span",{className:"category-name",children:r}),e.jsx("span",{className:"category-score",children:$.toFixed(1)})]},r))]}),e.jsxs("form",{className:"add-rating-form",onSubmit:R,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:()=>T(r),title:`${r} star${r>1?"s":""}`,children:e.jsx(Tt,{size:24,fill:r<=j?"currentColor":"none",className:r<=j?"star-filled":"star-empty"})},r))}),e.jsxs("select",{value:F,onChange:r=>O(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:X,onChange:r=>D(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:j===0||J,children:J?"Submitting...":"Submit Rating"})]}),e.jsxs("div",{className:"rating-history",children:[e.jsx("h4",{children:"Rating History"}),N.length===0?e.jsx("p",{className:"no-ratings",children:"No ratings yet"}):N.map(r=>e.jsxs("div",{className:"rating-history-item",children:[e.jsxs("div",{className:"rating-item-header",children:[ut(r.score),r.category&&e.jsx("span",{className:"rating-category-badge",children:r.category}),e.jsx("span",{className:"rating-time",children:dt(r.createdAt)}),e.jsx("button",{type:"button",className:"rating-delete-btn touch-target",onClick:()=>void _(r.id),title:"Delete rating",children:e.jsx(Ss,{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(q,{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(Ps,{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 $=v===r.id;return e.jsxs("div",{className:`reflection-card ${$?"reflection-card--expanded":""}`,onClick:()=>h(r.id),role:"button",tabIndex:0,onKeyDown:W=>W.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:Oa(r.trigger)}),e.jsx("span",{className:"reflection-timestamp",children:dt(r.timestamp)}),e.jsx("span",{className:"reflection-chevron",children:$?e.jsx(xt,{size:16}):e.jsx(bt,{size:16})})]}),e.jsx("div",{className:"reflection-summary",children:r.summary}),$&&e.jsxs("div",{className:"reflection-details",children:[r.insights.length>0&&e.jsxs("div",{className:"reflection-insights",children:[e.jsxs("h5",{children:[e.jsx(Ps,{size:14})," Insights"]}),e.jsx("ul",{children:r.insights.map((W,ke)=>e.jsx("li",{children:W},ke))})]}),r.suggestedImprovements.length>0&&e.jsxs("div",{className:"reflection-suggestions",children:[e.jsxs("h5",{children:[e.jsx(tt,{size:14})," Suggested Improvements"]}),e.jsx("ul",{children:r.suggestedImprovements.map((W,ke)=>e.jsx("li",{children:W},ke))})]}),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:ct(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 re(...s){return s.filter(Boolean).join(" ")}function Ke(s){const n=Date.now(),i=new Date(s).getTime(),l=n-i;if(l<0){const m=Math.abs(l);return m<6e4?"in a moment":m<36e5?`in ${Math.floor(m/6e4)}m`:m<864e5?`in ${Math.floor(m/36e5)}h`:`in ${Math.floor(m/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 Ja=[{id:"dashboard",label:"Dashboard",icon:za},{id:"logs",label:"Logs",icon:is},{id:"mail",label:"Mail",icon:Qt},{id:"runs",label:"Runs",icon:Cs},{id:"tasks",label:"Tasks",icon:kt},{id:"employees",label:"Employees",icon:Ct},{id:"soul",label:"Soul",icon:ea},{id:"instructions",label:"Instructions",icon:sa},{id:"memory",label:"Agent Memory",icon:is},{id:"reflections",label:"Evaluation",icon:ys},{id:"config",label:"Settings",icon:ta}],Js={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)"}},ws={completed:{icon:me,color:"var(--color-success)"},failed:{icon:da,color:"var(--color-error)"},active:{icon:q,color:"var(--in-progress)"},terminated:{icon:Ye,color:"var(--text-muted)"}},mt={"long-term":"Long-term",daily:"Daily",dreams:"Dreams"},Wa={"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."},qa=At(_s),Ga=700;function Ya(s,n){return s.some(i=>i.path===n)?n:s.find(i=>i.layer==="long-term")?.path??s[0]?.path??""}function vn({agentId:s,projectId:n,onClose:i,addToast:l,onChildClick:m,inline:g=!1,showInlineBackButton:P=!1,initialTab:f,initialRunId:M,preferActiveRun:N=!1,onMutationSuccess:L}){const[c,C]=t.useState(null),{confirm:A}=pt(),[E,y]=t.useState([]),[Q,J]=t.useState(!0),[p,v]=t.useState(f??"dashboard"),[S,j]=t.useState(!1),[T,F]=t.useState(!1),[O,X]=t.useState(!1),[D,Z]=t.useState(!1),[k,ae]=t.useState(!1),[R,_]=t.useState(!1),[h,x]=t.useState(0),[r,$]=t.useState(0),[W,ke]=t.useState(0),[ce,ve]=t.useState(null),[je,Ne]=t.useState(null),[xe,U]=t.useState(!1),[H,u]=t.useState(null),b=t.useRef(null),ne=t.useRef(null),he=t.useRef(!1);Gt(b,!g,"fusion:agent-detail-modal-size");const Ve=t.useRef(i),Pe=t.useRef(l),Ae=t.useRef(null),oe=t.useRef(!1),Ee=t.useRef(null),se=t.useRef(0),Xe=t.useRef(s),ds=t.useRef(n);Ve.current=i,Pe.current=l,Ae.current=c;const Ce=t.useCallback(async()=>{Ae.current===null&&J(!0);try{const z=await Yt(s,n);C(z)}catch(z){Pe.current(`Failed to load agent: ${I(z)}`,"error"),Ve.current()}finally{J(!1)}},[s,n]),us=t.useCallback(async()=>{const d=se.current,z=s,V=n,B=()=>se.current!==d||s!==z||n!==V;try{if(c?.taskId){ve(null),Ee.current=null;const Te=await Kt(c.taskId,V,{limit:100});if(B())return;y(Te.entries);return}const te=await vt(z,1,V);if(B())return;const fe=te[0]??null;if(ve(fe),!fe){Ee.current=null,y([]);return}if(Ee.current===fe.id)return;const Se=await jt(z,fe.id,V);if(B())return;y(Se),Ee.current=fe.id}catch(te){if(B())return;console.error("Failed to load agent logs:",te)}},[c?.taskId,s,n]),Je=t.useCallback(async()=>{U(!0),u(null);try{const d=await Xt(s,n);Ne(d)}catch(d){u(I(d)),Ne(null)}finally{U(!1)}},[s,n]),He=t.useCallback(d=>{oe.current=d},[]),Be=t.useCallback(async(d=!1)=>{await L?.({agentId:s,deleted:d})},[s,L]),we=t.useCallback(async()=>{await Ce(),await Be(!1)},[Ce,Be]);t.useEffect(()=>{Ce()},[Ce]),t.useEffect(()=>{const d=setInterval(()=>{Ce()},3e4);return()=>{clearInterval(d)}},[Ce]),t.useEffect(()=>{c&&p==="logs"&&us()},[c,p,us]),t.useEffect(()=>{p!=="logs"&&(Ee.current=null)},[p]),t.useEffect(()=>{c&&p==="mail"&&Je()},[c,p,Je]),t.useEffect(()=>{if(!D)return;const d=V=>{ne.current?.contains(V.target)||Z(!1)},z=V=>{V.key==="Escape"&&Z(!1)};return document.addEventListener("mousedown",d),document.addEventListener("keydown",z),()=>{document.removeEventListener("mousedown",d),document.removeEventListener("keydown",z)}},[D]),t.useEffect(()=>{if(!D)return;let d=!1;return _(!0),ks(void 0,n).then(z=>{if(d)return;const V=z.filter(B=>!Es(B));x(V.filter(B=>B.state==="active"||B.state==="running").length),$(V.filter(B=>B.state==="paused").length)}).catch(()=>{d||(x(0),$(0))}).finally(()=>{d||_(!1)}),()=>{d=!0}},[D,n]),t.useEffect(()=>{if(p!=="logs"||c?.taskId||!ce||ce.status!=="active")return;const d=se.current,z=s,V=ce.id,B=n?`?projectId=${encodeURIComponent(n)}`:"",te=Ns(`/api/agents/${encodeURIComponent(z)}/runs/${encodeURIComponent(V)}/logs/stream${B}`,{events:{"agent:log":fe=>{if(se.current===d)try{const Se=JSON.parse(fe.data);y(Te=>[...Te,Se])}catch{}}},onOpen:()=>{se.current===d&&j(!0)},onError:()=>{se.current===d&&j(!1)}});return()=>{te(),se.current===d&&j(!1)}},[p,c?.taskId,s,n,ce]),t.useEffect(()=>{(Xe.current!==s||ds.current!==n)&&(Xe.current=s,ds.current=n,se.current++,y([]),j(!1),ve(null),Ne(null),u(null),Ee.current=null,oe.current=!1)},[s,n]),t.useEffect(()=>{const d=n?`?projectId=${encodeURIComponent(n)}`:"",z=se.current,V=B=>{if(se.current===z)try{const te=JSON.parse(B.data);if(!te||typeof te!="object"||te.agentId!==s)return;Ce()}catch{}};return Ns(`/api/events${d}`,{events:{"agent:updated":B=>{if(se.current===z)try{const te=JSON.parse(B.data);if(!te||typeof te!="object"||te.id!==s||oe.current)return;Ce()}catch{}},"approval:requested":V,"approval:updated":V,"approval:decided":V}})},[s,n,Ce]),t.useEffect(()=>{if(p!=="logs"||!c?.taskId){j(!1);return}const d=se.current,z=c.taskId,V=n?`?projectId=${encodeURIComponent(n)}`:"",B=Ns(`/api/tasks/${encodeURIComponent(z)}/logs/stream${V}`,{events:{"agent:log":te=>{if(se.current===d)try{const fe=JSON.parse(te.data);y(Se=>[...Se,fe])}catch{}}},onOpen:()=>{se.current===d&&j(!0)},onError:()=>{se.current===d&&j(!1)}});return()=>{B(),se.current===d&&j(!1)}},[c?.taskId,p,n]);const Re=async d=>{if(T||!Ae.current)return;const z=Ae.current.state;if(z!==d){F(!0),C(V=>V&&{...V,state:d});try{await nt(s,d,n),l(`Agent state updated to ${d}`,"success"),await we()}catch(V){C(B=>B&&{...B,state:z}),l(`Failed to update state: ${I(V)}`,"error")}finally{F(!1)}}},Ze=async d=>{if(!k){Z(!1),ae(!0);try{const V=(await ks(void 0,n)).filter(ue=>!Es(ue)),B=V.filter(ue=>d==="paused"?ue.state==="active"||ue.state==="running":ue.state==="paused"),te=V.length-B.length;if(B.length===0){l(`No agents eligible to ${d==="paused"?"pause":"resume"}`,"error");return}if(!await A({title:d==="paused"?"Pause All Agents":"Resume All Agents",message:`${d==="paused"?"Pause":"Resume"} ${B.length} agent${B.length===1?"":"s"} in this project?`,danger:d==="paused"}))return;const Se=await Promise.allSettled(B.map(ue=>nt(ue.id,d,n))),Te=Se.map((ue,We)=>({result:ue,agent:B[We]})).filter(ue=>ue.result.status==="rejected"),hs=Se.length-Te.length,fs=Te.length,gs=`${d==="paused"?"Paused":"Resumed"} ${hs} agent${hs===1?"":"s"}; skipped ${te}`;if(fs>0){const ue=Te.slice(0,3).map(({agent:We,result:Ms})=>`${We.name||We.id}: ${I(Ms.reason)}`).join("; ");l(`${gs}; failed ${fs}${ue?` (${ue})`:""}`,"error")}else l(gs,"success");await we()}catch(z){l(`Failed to ${d==="paused"?"pause":"resume"} agents: ${I(z)}`,"error")}finally{ae(!1)}}},Qe=async()=>{if(!O){X(!0);try{await ia(s,n,{source:"on_demand",triggerDetail:"Triggered from dashboard"}),l(`Heartbeat run started for ${c?.name??s}`,"success"),ke(d=>d+1)}catch(d){l(`Failed to start heartbeat run: ${I(d)}`,"error")}finally{X(!1)}}},es=async()=>{if(!(!c||!await A({title:"Delete Agent",message:`Delete agent "${c.name}"? This cannot be undone.`,danger:!0})))try{await la(s,n),l(`Agent "${c.name}" deleted`,"success"),await Be(!0),i()}catch(z){l(`Failed to delete agent: ${I(z)}`,"error")}},ms=()=>c?na(c):{label:"Unknown",icon:e.jsx(Vs,{size:14}),color:"var(--text-muted)",stateDerived:!1},Ie=()=>{c&&(navigator.clipboard.writeText(c.id),l("Agent ID copied to clipboard","success"))};if(Q)return g?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(q,{className:"animate-spin",size:24}),e.jsx("span",{children:"Loading agent..."})]})}):e.jsx("div",{className:"agent-detail-overlay",onMouseDown:d=>{d.target===d.currentTarget&&(he.current=!0)},onMouseUp:d=>{he.current&&d.target===d.currentTarget&&i(),he.current=!1},role:"dialog","aria-modal":"true",children:e.jsx("div",{className:"agent-detail-modal",ref:b,children:e.jsxs("div",{className:"agent-detail-loading",children:[e.jsx(q,{className:"animate-spin",size:24}),e.jsx("span",{children:"Loading agent..."})]})})});if(!c)return null;const Fe=Js[c.state],ie=ms(),Oe=g?"agent-detail-inline":"agent-detail-modal",ye=R||h===0,_e=R||r===0;return e.jsx("div",{className:g?"agent-detail-inline-shell":"agent-detail-overlay",onClick:d=>!g&&d.target===d.currentTarget&&i(),role:g?"region":"dialog","aria-label":g?"Agent detail":void 0,"aria-modal":g?void 0:"true",children:e.jsxs("div",{className:Oe,ref:b,children:[e.jsxs("div",{className:"agent-detail-header",children:[e.jsxs("div",{className:"agent-detail-identity",children:[g&&P?e.jsxs("button",{type:"button",className:"btn agent-detail-inline-back",onClick:i,"aria-label":"Back to agents",children:[e.jsx(Nt,{size:16}),"Agents"]}):null,e.jsx("div",{className:"agent-detail-icon",children:e.jsx(yt,{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:Fe.bg,color:Fe.text,border:`1px solid ${Fe.border}`},children:c.state}),e.jsxs("span",{className:"badge",style:{color:ie.color},title:ie.reason??ie.label,children:[ie.icon,!ie.stateDerived&&ie.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 Re("active"),disabled:T,children:[e.jsx(Ts,{size:14}),"Start"]}),e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void Qe(),"aria-label":`Run now for ${c.name}`,disabled:O||T,children:[e.jsx(Cs,{size:14}),"Run Now"]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:es,children:[e.jsx(Ss,{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 Re("paused"),disabled:T,"aria-label":"Pause",children:[e.jsx(at,{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 Re("paused"),disabled:T,"aria-label":"Stop",children:[e.jsx(Ye,{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 Qe(),"aria-label":`Run now for ${c.name}`,disabled:O||T,children:[e.jsx(Cs,{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 Re("active"),disabled:T,"aria-label":"Resume",children:[e.jsx(Ts,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:"Resume"})]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:es,children:[e.jsx(Ss,{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 Re("paused"),disabled:T,"aria-label":"Pause",children:[e.jsx(at,{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 Re("paused"),disabled:T,"aria-label":"Stop",children:[e.jsx(Ye,{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 Re("active"),disabled:T,children:[e.jsx(Ts,{size:14}),"Retry"]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:()=>void Re("paused"),disabled:T,"aria-label":"Stop",children:[e.jsx(Ye,{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:ne,children:[e.jsx("button",{type:"button",className:"btn-icon",onClick:()=>Z(d=>!d),"aria-haspopup":"menu","aria-expanded":D,"aria-label":"Bulk agent actions",title:"Bulk agent actions",disabled:T||k,children:e.jsx(Zt,{size:16})}),D&&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 Ze("paused"),disabled:ye||k,children:["Pause All Agents",e.jsx("span",{className:"agent-detail-bulk-menu-item-hint",children:R?"Loading eligible agents...":ye?"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 Ze("active"),disabled:_e||k,children:["Resume All Agents",e.jsx("span",{className:"agent-detail-bulk-menu-item-hint",children:R?"Loading eligible agents...":_e?"No paused agents eligible":`Resume ${r} paused agent${r===1?"":"s"}`})]})]})]}),e.jsx("button",{className:"btn-icon",onClick:()=>void Ce(),title:"Refresh","aria-label":"Refresh",children:e.jsx(Rs,{size:16})}),!g&&e.jsx("button",{className:"btn-icon",onClick:i,"aria-label":"Close",title:"Close",children:e.jsx(St,{size:20})})]})]})]}),e.jsx("div",{className:"agent-detail-tabs",children:Ja.map(d=>e.jsxs("button",{className:re("agent-detail-tab",p===d.id&&"active"),onClick:()=>v(d.id),children:[e.jsx(d.icon,{size:16}),d.label]},d.id))}),e.jsxs("div",{className:"agent-detail-content",children:[p==="dashboard"&&e.jsx(Ka,{agent:c,health:ie,onChildClick:m,projectId:n}),p==="logs"&&e.jsx(Xa,{logs:E,isStreaming:S,hasTask:!!c.taskId||E.length>0||ce!==null,fallbackLabel:!c.taskId&&ce?`Latest run · ${ce.id.slice(0,8)}`:null}),p==="mail"&&e.jsx(Qa,{agent:c,mailbox:je,isLoading:xe,error:H,projectId:n,addToast:l,onRefresh:()=>void Je()}),p==="runs"&&e.jsx(en,{addToast:l,agentId:c.id,projectId:n,agentState:c.state,agentName:c.name,initialRunId:M,preferActiveRun:N,runNowRefreshToken:W,isEphemeral:Es(c)}),p==="tasks"&&e.jsx(nn,{agentId:c.id,projectId:n,addToast:l}),p==="employees"&&e.jsx(mn,{agentId:c.id,projectId:n,onChildClick:m}),p==="soul"&&e.jsx(rn,{agent:c,projectId:n,addToast:l,onSaved:we}),p==="instructions"&&e.jsx(cn,{agent:c,projectId:n,addToast:l,onSaved:we}),p==="memory"&&e.jsx(on,{agent:c,projectId:n,addToast:l,onSaved:we}),p==="reflections"&&e.jsx(Va,{agentId:c.id,projectId:n,addToast:l}),p==="config"&&e.jsx(un,{agent:c,projectId:n,addToast:l,onSaved:we,onHasChangesChange:He,onDelete:es,onAgentDraftApplied:d=>{C(z=>z&&{...z,...d})}},c.id)]}),!g&&e.jsxs("div",{className:"agent-detail-footer",children:[e.jsx("button",{className:"btn-icon",onClick:Ie,title:"Copy Agent ID",children:e.jsx(aa,{})}),e.jsx("span",{className:"agent-detail-id",onClick:Ie,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(wt,{size:12})]})]})]})]})})}function Ka({agent:s,health:n,onChildClick:i,projectId:l}){const m=Js[s.state],[g,P]=t.useState([]),[f,M]=t.useState(!0),[N,L]=t.useState(null),[c,C]=t.useState([]),[A,E]=t.useState(null),[y,Q]=t.useState(null),[J,p]=t.useState(!1),[v,S]=t.useState(null),j=typeof s.runtimeConfig?.runtimeHint=="string"?s.runtimeConfig.runtimeHint:"",T=(()=>{const h=s.runtimeConfig??{};if(j){const x=c.find(r=>r.runtimeId===j);return x?x.name:j}if(h.modelProvider&&h.modelId)return`${h.modelProvider}/${h.modelId}`;if(typeof h.model=="string"&&h.model.includes("/")){const x=h.model.indexOf("/");return h.model.slice(x+1)}return null})();t.useEffect(()=>{Os(s.id,l).then(L).catch(()=>L(null))},[s.id,l]),t.useEffect(()=>{Rt(l).then(C).catch(()=>C([]))},[l]),t.useEffect(()=>{let h=!1;return M(!0),ra(s.id,l).then(x=>{if(h)return;const r=x.length>0&&x[0]?.id===s.id?[...x].reverse():x;P(r)}).catch(()=>{h||P([])}).finally(()=>{h||M(!1)}),()=>{h=!0}},[s.id,l]);const F=t.useMemo(()=>{const h=s.completedRuns||[],x=new Date;x.setHours(0,0,0,0);const r=h.filter(W=>new Date(W.startedAt)>=x),$=h.filter(W=>W.status==="completed");return{totalRuns:h.length,todayRuns:r.length,successfulRuns:$.length,successRate:h.length>0?Math.round($.length/h.length*100):0}},[s]),O=(s.completedRuns||[]).slice(0,5),X=Array.isArray(s.metadata?.skills)?s.metadata.skills:[],D=A?$s(A):null,Z=t.useCallback(async h=>{p(!0),S(null),Q(null);try{const x=await oa(h,l);Q(x)}catch(x){S(I(x))}finally{p(!1)}},[l]),k=t.useCallback(h=>{if(A===h){E(null),Q(null),S(null),p(!1);return}E(h),Z(h)},[Z,A]),ae=s.state==="active"||s.state==="running",R=ca(s.runtimeConfig?.heartbeatIntervalMs),_=ae&&s.lastHeartbeatAt?new Date(new Date(s.lastHeartbeatAt).getTime()+R).toISOString():null;return e.jsxs("div",{className:"dashboard-tab dashboard-summary-layout",children:[N?.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(Vs,{}),e.jsx("h3",{children:"Overview"}),e.jsx("strong",{children:s.name}),e.jsx("span",{className:"inline-badge",style:{background:m.bg,color:m.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:j?"Runtime":"Model"}),e.jsxs("span",{children:[" ",T??"Auto"]})]}),X.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:X.map(h=>{const x=A===h;return e.jsx("button",{type:"button",className:re("badge","badge-skill","dashboard-summary-skill-badge","dashboard-summary-skill-badge-btn",x&&"dashboard-summary-skill-badge--selected"),title:h,onClick:()=>k(h),"aria-expanded":x,"aria-label":`View details for ${$s(h)}`,children:$s(h)},h)})})]}):e.jsx("span",{children:"Skills: —"})]}),A?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:D}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>k(A),children:[e.jsx(St,{size:14}),"Close"]})]}),J?e.jsxs("div",{className:"dashboard-summary-skill-detail-loading",role:"status","aria-live":"polite",children:[e.jsx(q,{size:14,className:"animate-spin"}),"Loading skill content..."]}):v?e.jsxs("div",{className:"dashboard-summary-skill-detail-error",role:"alert",children:[e.jsx(Mt,{size:14}),e.jsx("span",{children:v}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void Z(A),children:"Retry"})]}):y?e.jsx("pre",{className:"dashboard-summary-skill-detail-content",children:y.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?Ke(s.lastHeartbeatAt):"Never"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:"Next expected"}),e.jsx("p",{children:_?Ke(_):"Not scheduled"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:"Interval"}),e.jsx("p",{children:At(R)})]}),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:re("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(wt,{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:[F.successfulRuns,"/",F.totalRuns," successful (",F.successRate,"%)"]}),O.length===0?e.jsx("p",{className:"text-muted",children:"No runs yet"}):e.jsx("div",{className:"runs-list",children:O.map(h=>{const x=ws[h.status]||ws.terminated,r=x.icon;return e.jsxs("div",{className:"run-item",children:[e.jsx(r,{size:14,style:{color:x.color}}),e.jsx("span",{children:Ke(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:F.totalRuns}),e.jsx("div",{className:"stat-label",children:"Total Runs"})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("div",{className:"stat-value",children:F.todayRuns}),e.jsx("div",{className:"stat-label",children:"Runs Today"})]}),e.jsxs("div",{className:"stat-card",children:[e.jsxs("div",{className:"stat-value",children:[F.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(q,{size:14,className:"animate-spin"}),e.jsx("span",{children:"Loading reporting chain..."})]}):g.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:g.map((h,x)=>{const r=x===g.length-1,$=!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:()=>$&&i?.(h.id),disabled:!$||!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 Xa({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(is,{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(Ft,{entries:s,loading:!1})]}):e.jsx("div",{className:"logs-tab",children:e.jsxs("div",{className:"logs-empty",children:[e.jsx(is,{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 Za(s){const n=new Date(s),l=new Date().getTime()-n.getTime(),m=Math.floor(l/6e4),g=Math.floor(l/36e5),P=Math.floor(l/864e5);return m<1?"Just now":m<60?`${m}m ago`:g<24?`${g}h ago`:P<7?`${P}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function js(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 Qa({agent:s,mailbox:n,isLoading:i,error:l,projectId:m,addToast:g,onRefresh:P}){const[f,M]=t.useState("inbox"),[N,L]=t.useState([]);t.useEffect(()=>{let v=!1;return ks(void 0,m).then(S=>{v||L(S)}).catch(()=>{v||L([])}),()=>{v=!0}},[m]);const c=t.useMemo(()=>{const v=new Map;for(const j of N){if(!j.id)continue;const T=typeof j.name=="string"?j.name.trim():"";T.length>0&&v.set(j.id,T)}const S=typeof s.name=="string"?s.name.trim():"";return S.length>0&&v.set(s.id,S),v},[N,s.id,s.name]),[C,A]=t.useState(null),E=f==="inbox"?n?.inbox??[]:n?.outbox??[],y=C?E.find(v=>v.id===C)??null:null;t.useEffect(()=>{A(null)},[f,s.id]);const Q=async v=>{if(A(v.id),!(f!=="inbox"||v.read))try{await Fa(v.id,m),P()}catch(S){const j=`Failed to mark message as read: ${I(S)}`;g?g(j,"error"):console.warn(j)}},J=()=>{A(null),P()},p=v=>e.jsxs("button",{type:"button",className:re("mailbox-item","agent-mail-tab-message",f==="inbox"&&!v.read&&"unread",C===v.id&&"agent-mail-tab-message--selected"),onClick:()=>void Q(v),"aria-pressed":C===v.id,children:[e.jsx("div",{className:"mailbox-item-avatar",children:(f==="inbox"?v.fromType:v.toType)==="agent"?e.jsx(Vs,{size:16}):e.jsx(ya,{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:js(v.fromId,v.fromType,c)}):e.jsxs("span",{className:"mailbox-item-to",children:["To: ",js(v.toId,v.toType,c)]}),e.jsx("span",{className:"mailbox-item-time",children:Za(v.createdAt)})]}),e.jsxs("div",{className:"mailbox-item-preview",children:[v.content.slice(0,80),v.content.length>80?"…":""]})]}),f==="inbox"&&!v.read?e.jsx("div",{className:"mailbox-item-unread-dot","aria-label":"Unread message"}):null]},v.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:J,disabled:i,children:[e.jsx(Rs,{size:14}),"Refresh"]})]}),e.jsxs("div",{className:"mailbox-agent-subtabs","data-testid":"agent-detail-mail-subtabs",children:[e.jsxs("button",{className:re("btn","btn-sm","btn-secondary","mailbox-agent-subtab",f==="inbox"&&"active"),onClick:()=>M("inbox"),children:[e.jsx(it,{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:re("btn","btn-sm","btn-secondary","mailbox-agent-subtab",f==="outbox"&&"active"),onClick:()=>M("outbox"),children:[e.jsx(lt,{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(q,{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(Mt,{size:16}),e.jsxs("span",{children:["Failed to load mailbox: ",l]})]}):null,!i&&!l?y?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:()=>A(null),children:[e.jsx(Nt,{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:js(y.fromId,y.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:js(y.toId,y.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:y.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(y.createdAt).toLocaleString()})]}),y.metadata?.replyTo?.messageId?e.jsxs("div",{className:"agent-mail-tab-reply-context",children:["↪ Replying to message ",y.metadata.replyTo.messageId]}):null]}),e.jsx("div",{className:"agent-mail-tab-detail-body",children:y.content})]}):e.jsx("div",{className:"mailbox-list","data-testid":"agent-detail-mail-list",children:E.length===0?e.jsxs("div",{className:"mailbox-empty","data-testid":"agent-detail-mail-empty",children:[f==="inbox"?e.jsx(it,{size:32}):e.jsx(lt,{size:32}),e.jsx("p",{children:f==="inbox"?"No received messages for this agent":"No sent messages for this agent"})]}):E.map(p)}):null]})}function en({addToast:s,agentId:n,projectId:i,agentState:l,agentName:m,initialRunId:g,preferActiveRun:P,runNowRefreshToken:f,isEphemeral:M}){const[N,L]=t.useState([]),{confirm:c}=pt(),[C,A]=t.useState(!0),[E,y]=t.useState(null),[Q,J]=t.useState([]),[p,v]=t.useState(!1),[S,j]=t.useState(null),[T,F]=t.useState(!1),[O,X]=t.useState(null),[D,Z]=t.useState([]),k=t.useRef(!1),ae=t.useRef(!1),R=t.useCallback(async()=>{try{const u=await vt(n,50,i);L(u)}catch(u){s(`Failed to load runs: ${I(u)}`,"error")}finally{A(!1)}},[n,i,s]);t.useEffect(()=>{R()},[R]),t.useEffect(()=>{if(M){X(null),Z([]);return}const u=i?`?projectId=${encodeURIComponent(i)}`:"";fetch(`/api/agents/${encodeURIComponent(n)}/token-usage${u}`).then(async b=>{if(!b.ok){if(b.status===400){X(null);return}throw new Error(`Request failed: ${b.status}`)}const ne=await b.json();X(ne)}).catch(b=>{s(`Failed to load cache hit ratio: ${I(b)}`,"error")}),ua(n,7,i).then(b=>Z(b)).catch(b=>{const ne=I(b).toLowerCase();if(ne.includes("ephemeral")||ne.includes("400")){Z([]);return}s(`Failed to load prompt sizes: ${I(b)}`,"error")})},[n,i,s,M]),t.useEffect(()=>{if(!ae.current){ae.current=!0;return}A(!0),R()},[R,f]);const _=N.some(u=>u.status==="active"),h=E?N.find(u=>u.id===E)?.status:void 0;t.useEffect(()=>{if(!_)return;const u=setInterval(()=>{R()},5e3);return()=>clearInterval(u)},[_,R]),t.useEffect(()=>{if(!E||h!=="active")return;const u=i?`?projectId=${encodeURIComponent(i)}`:"";return Ns(`/api/agents/${encodeURIComponent(n)}/runs/${encodeURIComponent(E)}/logs/stream${u}`,{events:{"agent:log":b=>{try{const ne=JSON.parse(b.data);J(he=>[...he,ne])}catch{}}}})},[E,h,n,i]);const x=t.useCallback(async u=>{if(E===u){y(null),J([]),j(null);return}y(u),v(!0),F(!0),J([]),j(null);try{const[b,ne]=await Promise.all([jt(n,u,i),ma(n,u,i)]);J(b),j(ne)}catch(b){s(`Failed to load run details: ${I(b)}`,"error"),J([]),j(null)}finally{v(!1),F(!1)}},[E,n,i,s]);t.useEffect(()=>{k.current=!1},[n,g,P]),t.useEffect(()=>{if(N.length===0||C||k.current)return;const u=g?N.find(b=>b.id===g):P?N.find(b=>b.status==="active"):null;k.current=!0,u&&x(u.id)},[g,P,N,C,x]);const r=async()=>{if(await c({title:"Stop Active Run",message:"Stop the active run? The agent's work will be interrupted.",danger:!0}))try{await Sa(n,i),s("Run stopped","success"),A(!0),R()}catch(b){s(`Failed to stop run: ${I(b)}`,"error")}};if(C&&N.length===0)return e.jsx("div",{className:"runs-tab",children:e.jsxs("div",{className:"runs-loading-row",children:[e.jsx(q,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading runs..."})]})});if(N.length===0)return e.jsx("div",{className:"runs-tab",children:e.jsxs("div",{className:"runs-empty",children:[e.jsx(Cs,{size:48,opacity:.3}),e.jsx("p",{children:"No runs yet"}),e.jsx("p",{className:"text-muted",children:"Heartbeat runs will appear here"})]})});const $=[...N].sort((u,b)=>new Date(b.startedAt).getTime()-new Date(u.startedAt).getTime()),W=$.filter(u=>u.status==="active"),ke=$.filter(u=>u.status!=="active"),ce=u=>u?e.jsxs("div",{className:"run-usage",children:[e.jsxs("span",{children:["Input: ",u.inputTokens.toLocaleString()]}),e.jsxs("span",{children:["Output: ",u.outputTokens.toLocaleString()]}),u.cachedTokens>0&&e.jsxs("span",{children:["Cache read: ",u.cachedTokens.toLocaleString()]}),(u.cacheWriteTokens??0)>0&&e.jsxs("span",{children:["Cache write: ",(u.cacheWriteTokens??0).toLocaleString()]})]}):null,ve=(u,b,ne)=>{const he=ws[u.status]||ws.completed,Ve=he.icon,Pe=u.endedAt?sn(new Date(u.startedAt),new Date(u.endedAt)):"In progress",Ae=E===u.id;return e.jsxs("div",{children:[e.jsxs("div",{className:re("run-card",ne&&"run-card--active",Ae&&"run-card--selected","run-card--clickable"),onClick:()=>void x(u.id),role:"button",tabIndex:0,"aria-expanded":Ae,"aria-label":`${ne?"Active":""} run ${u.id.slice(0,8)}, ${u.status}`,onKeyDown:oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),x(u.id))},children:[e.jsxs("div",{className:"run-header",children:[e.jsxs("div",{className:"run-header-group",children:[Ae?e.jsx(xt,{size:14}):e.jsx(bt,{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:["#",b+1," ",u.id.slice(0,8)]})]}),e.jsxs("div",{className:"run-header-group",children:[u.invocationSource&&e.jsx("span",{className:"badge run-badge--compact",children:u.invocationSource}),ne&&e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:oe=>{oe.preventDefault(),oe.stopPropagation(),r()},"aria-label":"Stop active run",children:[e.jsx(Ye,{size:12})," Stop"]}),e.jsxs("span",{className:re("run-status",u.status),children:[e.jsx(Ve,{size:14,style:{color:he.color}}),u.status]}),u.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 ",Ke(u.startedAt)]}),e.jsx("span",{children:"•"}),e.jsx("span",{children:Pe}),u.triggerDetail&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsx("span",{className:"text-muted",children:u.triggerDetail})]})]})]}),Ae&&e.jsxs("div",{className:"run-logs-container",children:[T?e.jsxs("div",{className:"run-details-loading-state",children:[e.jsx(q,{size:14,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading details..."})]}):S&&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"}),S.systemPrompt?e.jsx("pre",{className:"run-output-panel",children:S.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"}),S.executionPrompt?e.jsx("pre",{className:"run-output-panel",children:S.executionPrompt}):e.jsx("div",{className:"text-muted run-output-empty",children:"Execution prompt not captured for this run"})]})}),S.usageJson&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:"Token Usage"}),ce(S.usageJson)]}),S.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:S.stdoutExcerpt.length>2e3?`${S.stdoutExcerpt.slice(0,2e3)}
16
+ */const Ha=[["path",{d:"M16 17h6v-6",key:"t6n2it"}],["path",{d:"m22 17-8.5-8.5-5 5L2 7",key:"x473p"}]],Ba=Us("trending-down",Ha);function ct(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 Ia(s){return`${Math.round(s*100)}%`}function dt(s){const n=Date.now(),i=new Date(s).getTime(),l=n-i;if(l<0){const m=Math.abs(l);return m<6e4?"in a moment":m<36e5?`in ${Math.floor(m/6e4)}m`:m<864e5?`in ${Math.floor(m/36e5)}h`:`in ${Math.floor(m/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 Oa(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 as(s){return s instanceof Error&&s.message?s.message:String(s)}function _a(s){switch(s){case"improving":return"↑ Improving";case"declining":return"↓ Declining";case"stable":return"→ Stable";default:return"Insufficient data"}}function Ua(s){switch(s){case"improving":return"trend-improving";case"declining":return"trend-declining";case"stable":return"trend-stable";default:return"trend-insufficient"}}function ut(s,n=5){return e.jsx("span",{className:"rating-stars",children:Array.from({length:n},(i,l)=>e.jsx(Tt,{size:14,className:l<s?"star-filled":"star-empty",fill:l<s?"currentColor":"none"},l))})}function Va({agentId:s,projectId:n,addToast:i}){const[l,m]=t.useState([]),[g,P]=t.useState(null),[f,M]=t.useState(null),[N,L]=t.useState([]),[c,C]=t.useState(!0),[A,E]=t.useState(!0),[y,X]=t.useState(!1),[J,p]=t.useState(!1),[v,S]=t.useState(null),[j,T]=t.useState(0),[F,O]=t.useState(""),[Q,D]=t.useState(""),Z=t.useCallback(async()=>{try{const[r,$]=await Promise.all([It(s,20,n),Ot(s,void 0,n)]);m(r),P($)}catch(r){i(`Failed to load reflections: ${as(r)}`,"error")}finally{C(!1)}},[s,n,i]),k=t.useCallback(async()=>{try{const[r,$]=await Promise.all([_t(s,n),Ut(s,{limit:50},n)]);M(r),L($)}catch(r){i(`Failed to load ratings: ${as(r)}`,"error")}finally{E(!1)}},[s,n,i]);t.useEffect(()=>{Z(),k()},[Z,k]);const ae=async()=>{X(!0);try{if(!await Jt(s,n)){i("Not enough history to generate a reflection yet","error");return}i("Reflection generated successfully","success"),C(!0),await Z()}catch(r){const $=as(r),W=$.toLowerCase();W.includes("agent not found")||W.includes("not found")?i("This agent is no longer available. It may have been deleted.","error"):W.includes("insufficient history")?i("Not enough history to generate a reflection yet","error"):i(`Failed to generate reflection: ${$}`,"error")}finally{X(!1)}},R=async r=>{if(r.preventDefault(),j!==0){p(!0);try{await Wt(s,{score:j,category:F||void 0,comment:Q||void 0,raterType:"user"},n),T(0),O(""),D(""),i("Rating added","success"),await k()}catch($){i(`Failed to add rating: ${as($)}`,"error")}finally{p(!1)}}},_=async r=>{try{await qt(s,r,n),i("Rating deleted","success"),await k()}catch($){i(`Failed to delete rating: ${as($)}`,"error")}},h=r=>{S($=>$===r?null:r)};if(c&&A)return e.jsx("div",{className:"reflections-tab",children:e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(q,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading evaluation..."})]})});const x=g&&g.totalTasksCompleted===0&&g.totalTasksFailed===0&&g.recentReflectionCount===0;return e.jsxs("div",{className:"reflections-tab",children:[e.jsxs("div",{className:"reflections-header",children:[e.jsxs("h3",{children:[e.jsx(ys,{size:16}),"Performance, Reflections & Ratings"]}),e.jsx("button",{className:"btn btn-secondary",onClick:ae,disabled:y,title:"Generate a manual reflection",children:y?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:14,className:"animate-spin"}),"Reflecting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Rs,{size:14}),"Reflect Now"]})})]}),g&&!x&&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(tt,{size:16,style:{color:"var(--color-success)"}}),g.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(Ba,{size:16,style:{color:"var(--color-error)"}}),g.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(Vt,{size:16,style:{color:"var(--in-progress)"}}),ct(g.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(ys,{size:16,style:{color:g.successRate>=.8?"var(--color-success)":g.successRate>=.5?"var(--color-warning)":"var(--color-error)"}}),Ia(g.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(Ps,{size:16,style:{color:"var(--color-info)"}}),g.recentReflectionCount]}),e.jsx("div",{className:"stat-label",children:"Reflections"})]})]}),x&&e.jsxs("div",{className:"reflections-no-data",children:[e.jsx(ys,{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"}),A?e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(q,{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)}),ut(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 ${Ua(f.trend)}`,children:_a(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,$])=>e.jsxs("div",{className:"category-item",children:[e.jsx("span",{className:"category-name",children:r}),e.jsx("span",{className:"category-score",children:$.toFixed(1)})]},r))]}),e.jsxs("form",{className:"add-rating-form",onSubmit:R,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:()=>T(r),title:`${r} star${r>1?"s":""}`,children:e.jsx(Tt,{size:24,fill:r<=j?"currentColor":"none",className:r<=j?"star-filled":"star-empty"})},r))}),e.jsxs("select",{value:F,onChange:r=>O(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:Q,onChange:r=>D(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:j===0||J,children:J?"Submitting...":"Submit Rating"})]}),e.jsxs("div",{className:"rating-history",children:[e.jsx("h4",{children:"Rating History"}),N.length===0?e.jsx("p",{className:"no-ratings",children:"No ratings yet"}):N.map(r=>e.jsxs("div",{className:"rating-history-item",children:[e.jsxs("div",{className:"rating-item-header",children:[ut(r.score),r.category&&e.jsx("span",{className:"rating-category-badge",children:r.category}),e.jsx("span",{className:"rating-time",children:dt(r.createdAt)}),e.jsx("button",{type:"button",className:"rating-delete-btn touch-target",onClick:()=>void _(r.id),title:"Delete rating",children:e.jsx(Ss,{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(q,{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(Ps,{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 $=v===r.id;return e.jsxs("div",{className:`reflection-card ${$?"reflection-card--expanded":""}`,onClick:()=>h(r.id),role:"button",tabIndex:0,onKeyDown:W=>W.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:Oa(r.trigger)}),e.jsx("span",{className:"reflection-timestamp",children:dt(r.timestamp)}),e.jsx("span",{className:"reflection-chevron",children:$?e.jsx(xt,{size:16}):e.jsx(bt,{size:16})})]}),e.jsx("div",{className:"reflection-summary",children:r.summary}),$&&e.jsxs("div",{className:"reflection-details",children:[r.insights.length>0&&e.jsxs("div",{className:"reflection-insights",children:[e.jsxs("h5",{children:[e.jsx(Ps,{size:14})," Insights"]}),e.jsx("ul",{children:r.insights.map((W,ke)=>e.jsx("li",{children:W},ke))})]}),r.suggestedImprovements.length>0&&e.jsxs("div",{className:"reflection-suggestions",children:[e.jsxs("h5",{children:[e.jsx(tt,{size:14})," Suggested Improvements"]}),e.jsx("ul",{children:r.suggestedImprovements.map((W,ke)=>e.jsx("li",{children:W},ke))})]}),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:ct(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 re(...s){return s.filter(Boolean).join(" ")}function Ye(s){const n=Date.now(),i=new Date(s).getTime(),l=n-i;if(l<0){const m=Math.abs(l);return m<6e4?"in a moment":m<36e5?`in ${Math.floor(m/6e4)}m`:m<864e5?`in ${Math.floor(m/36e5)}h`:`in ${Math.floor(m/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 Ja=[{id:"dashboard",label:"Dashboard",icon:za},{id:"logs",label:"Logs",icon:is},{id:"mail",label:"Mail",icon:Xt},{id:"runs",label:"Runs",icon:Cs},{id:"tasks",label:"Tasks",icon:kt},{id:"employees",label:"Employees",icon:Ct},{id:"soul",label:"Soul",icon:ea},{id:"instructions",label:"Instructions",icon:sa},{id:"memory",label:"Agent Memory",icon:is},{id:"reflections",label:"Evaluation",icon:ys},{id:"config",label:"Settings",icon:ta}],Js={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)"}},ws={completed:{icon:me,color:"var(--color-success)"},failed:{icon:da,color:"var(--color-error)"},active:{icon:q,color:"var(--in-progress)"},terminated:{icon:Ke,color:"var(--text-muted)"}},mt={"long-term":"Long-term",daily:"Daily",dreams:"Dreams"},Wa={"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."},qa=At(_s),Ga=700;function Ka(s,n){return s.some(i=>i.path===n)?n:s.find(i=>i.layer==="long-term")?.path??s[0]?.path??""}function vn({agentId:s,projectId:n,onClose:i,addToast:l,onChildClick:m,inline:g=!1,showInlineBackButton:P=!1,initialTab:f,initialRunId:M,preferActiveRun:N=!1,onMutationSuccess:L}){const[c,C]=t.useState(null),{confirm:A}=pt(),[E,y]=t.useState([]),[X,J]=t.useState(!0),[p,v]=t.useState(f??"dashboard"),[S,j]=t.useState(!1),[T,F]=t.useState(!1),[O,Q]=t.useState(!1),[D,Z]=t.useState(!1),[k,ae]=t.useState(!1),[R,_]=t.useState(!1),[h,x]=t.useState(0),[r,$]=t.useState(0),[W,ke]=t.useState(0),[ce,ve]=t.useState(null),[je,Ne]=t.useState(null),[xe,U]=t.useState(!1),[H,u]=t.useState(null),b=t.useRef(null),ne=t.useRef(null),he=t.useRef(!1);Gt(b,!g,"fusion:agent-detail-modal-size");const Ve=t.useRef(i),Pe=t.useRef(l),Ae=t.useRef(null),oe=t.useRef(!1),Ee=t.useRef(null),se=t.useRef(0),Qe=t.useRef(s),ds=t.useRef(n);Ve.current=i,Pe.current=l,Ae.current=c;const Ce=t.useCallback(async()=>{Ae.current===null&&J(!0);try{const z=await Kt(s,n);C(z)}catch(z){Pe.current(`Failed to load agent: ${I(z)}`,"error"),Ve.current()}finally{J(!1)}},[s,n]),us=t.useCallback(async()=>{const d=se.current,z=s,V=n,B=()=>se.current!==d||s!==z||n!==V;try{if(c?.taskId){ve(null),Ee.current=null;const Te=await Yt(c.taskId,V,{limit:100});if(B())return;y(Te.entries);return}const te=await vt(z,1,V);if(B())return;const fe=te[0]??null;if(ve(fe),!fe){Ee.current=null,y([]);return}if(Ee.current===fe.id)return;const Se=await jt(z,fe.id,V);if(B())return;y(Se),Ee.current=fe.id}catch(te){if(B())return;console.error("Failed to load agent logs:",te)}},[c?.taskId,s,n]),Je=t.useCallback(async()=>{U(!0),u(null);try{const d=await Qt(s,n);Ne(d)}catch(d){u(I(d)),Ne(null)}finally{U(!1)}},[s,n]),He=t.useCallback(d=>{oe.current=d},[]),Be=t.useCallback(async(d=!1)=>{await L?.({agentId:s,deleted:d})},[s,L]),we=t.useCallback(async()=>{await Ce(),await Be(!1)},[Ce,Be]);t.useEffect(()=>{Ce()},[Ce]),t.useEffect(()=>{const d=setInterval(()=>{Ce()},3e4);return()=>{clearInterval(d)}},[Ce]),t.useEffect(()=>{c&&p==="logs"&&us()},[c,p,us]),t.useEffect(()=>{p!=="logs"&&(Ee.current=null)},[p]),t.useEffect(()=>{c&&p==="mail"&&Je()},[c,p,Je]),t.useEffect(()=>{if(!D)return;const d=V=>{ne.current?.contains(V.target)||Z(!1)},z=V=>{V.key==="Escape"&&Z(!1)};return document.addEventListener("mousedown",d),document.addEventListener("keydown",z),()=>{document.removeEventListener("mousedown",d),document.removeEventListener("keydown",z)}},[D]),t.useEffect(()=>{if(!D)return;let d=!1;return _(!0),ks(void 0,n).then(z=>{if(d)return;const V=z.filter(B=>!Es(B));x(V.filter(B=>B.state==="active"||B.state==="running").length),$(V.filter(B=>B.state==="paused").length)}).catch(()=>{d||(x(0),$(0))}).finally(()=>{d||_(!1)}),()=>{d=!0}},[D,n]),t.useEffect(()=>{if(p!=="logs"||c?.taskId||!ce||ce.status!=="active")return;const d=se.current,z=s,V=ce.id,B=n?`?projectId=${encodeURIComponent(n)}`:"",te=Ns(`/api/agents/${encodeURIComponent(z)}/runs/${encodeURIComponent(V)}/logs/stream${B}`,{events:{"agent:log":fe=>{if(se.current===d)try{const Se=JSON.parse(fe.data);y(Te=>[...Te,Se])}catch{}}},onOpen:()=>{se.current===d&&j(!0)},onError:()=>{se.current===d&&j(!1)}});return()=>{te(),se.current===d&&j(!1)}},[p,c?.taskId,s,n,ce]),t.useEffect(()=>{(Qe.current!==s||ds.current!==n)&&(Qe.current=s,ds.current=n,se.current++,y([]),j(!1),ve(null),Ne(null),u(null),Ee.current=null,oe.current=!1)},[s,n]),t.useEffect(()=>{const d=n?`?projectId=${encodeURIComponent(n)}`:"",z=se.current,V=B=>{if(se.current===z)try{const te=JSON.parse(B.data);if(!te||typeof te!="object"||te.agentId!==s)return;Ce()}catch{}};return Ns(`/api/events${d}`,{events:{"agent:updated":B=>{if(se.current===z)try{const te=JSON.parse(B.data);if(!te||typeof te!="object"||te.id!==s||oe.current)return;Ce()}catch{}},"approval:requested":V,"approval:updated":V,"approval:decided":V}})},[s,n,Ce]),t.useEffect(()=>{if(p!=="logs"||!c?.taskId){j(!1);return}const d=se.current,z=c.taskId,V=n?`?projectId=${encodeURIComponent(n)}`:"",B=Ns(`/api/tasks/${encodeURIComponent(z)}/logs/stream${V}`,{events:{"agent:log":te=>{if(se.current===d)try{const fe=JSON.parse(te.data);y(Se=>[...Se,fe])}catch{}}},onOpen:()=>{se.current===d&&j(!0)},onError:()=>{se.current===d&&j(!1)}});return()=>{B(),se.current===d&&j(!1)}},[c?.taskId,p,n]);const Re=async d=>{if(T||!Ae.current)return;const z=Ae.current.state;if(z!==d){F(!0),C(V=>V&&{...V,state:d});try{await nt(s,d,n),l(`Agent state updated to ${d}`,"success"),await we()}catch(V){C(B=>B&&{...B,state:z}),l(`Failed to update state: ${I(V)}`,"error")}finally{F(!1)}}},Ze=async d=>{if(!k){Z(!1),ae(!0);try{const V=(await ks(void 0,n)).filter(ue=>!Es(ue)),B=V.filter(ue=>d==="paused"?ue.state==="active"||ue.state==="running":ue.state==="paused"),te=V.length-B.length;if(B.length===0){l(`No agents eligible to ${d==="paused"?"pause":"resume"}`,"error");return}if(!await A({title:d==="paused"?"Pause All Agents":"Resume All Agents",message:`${d==="paused"?"Pause":"Resume"} ${B.length} agent${B.length===1?"":"s"} in this project?`,danger:d==="paused"}))return;const Se=await Promise.allSettled(B.map(ue=>nt(ue.id,d,n))),Te=Se.map((ue,We)=>({result:ue,agent:B[We]})).filter(ue=>ue.result.status==="rejected"),hs=Se.length-Te.length,fs=Te.length,gs=`${d==="paused"?"Paused":"Resumed"} ${hs} agent${hs===1?"":"s"}; skipped ${te}`;if(fs>0){const ue=Te.slice(0,3).map(({agent:We,result:Ms})=>`${We.name||We.id}: ${I(Ms.reason)}`).join("; ");l(`${gs}; failed ${fs}${ue?` (${ue})`:""}`,"error")}else l(gs,"success");await we()}catch(z){l(`Failed to ${d==="paused"?"pause":"resume"} agents: ${I(z)}`,"error")}finally{ae(!1)}}},Xe=async()=>{if(!O){Q(!0);try{await ia(s,n,{source:"on_demand",triggerDetail:"Triggered from dashboard"}),l(`Heartbeat run started for ${c?.name??s}`,"success"),ke(d=>d+1)}catch(d){l(`Failed to start heartbeat run: ${I(d)}`,"error")}finally{Q(!1)}}},es=async()=>{if(!(!c||!await A({title:"Delete Agent",message:`Delete agent "${c.name}"? This cannot be undone.`,danger:!0})))try{await la(s,n),l(`Agent "${c.name}" deleted`,"success"),await Be(!0),i()}catch(z){l(`Failed to delete agent: ${I(z)}`,"error")}},ms=()=>c?na(c):{label:"Unknown",icon:e.jsx(Vs,{size:14}),color:"var(--text-muted)",stateDerived:!1},Ie=()=>{c&&(navigator.clipboard.writeText(c.id),l("Agent ID copied to clipboard","success"))};if(X)return g?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(q,{className:"animate-spin",size:24}),e.jsx("span",{children:"Loading agent..."})]})}):e.jsx("div",{className:"agent-detail-overlay",onMouseDown:d=>{d.target===d.currentTarget&&(he.current=!0)},onMouseUp:d=>{he.current&&d.target===d.currentTarget&&i(),he.current=!1},role:"dialog","aria-modal":"true",children:e.jsx("div",{className:"agent-detail-modal",ref:b,children:e.jsxs("div",{className:"agent-detail-loading",children:[e.jsx(q,{className:"animate-spin",size:24}),e.jsx("span",{children:"Loading agent..."})]})})});if(!c)return null;const Fe=Js[c.state],ie=ms(),Oe=g?"agent-detail-inline":"agent-detail-modal",ye=R||h===0,_e=R||r===0;return e.jsx("div",{className:g?"agent-detail-inline-shell":"agent-detail-overlay",onClick:d=>!g&&d.target===d.currentTarget&&i(),role:g?"region":"dialog","aria-label":g?"Agent detail":void 0,"aria-modal":g?void 0:"true",children:e.jsxs("div",{className:Oe,ref:b,children:[e.jsxs("div",{className:"agent-detail-header",children:[e.jsxs("div",{className:"agent-detail-identity",children:[g&&P?e.jsxs("button",{type:"button",className:"btn agent-detail-inline-back",onClick:i,"aria-label":"Back to agents",children:[e.jsx(Nt,{size:16}),"Agents"]}):null,e.jsx("div",{className:"agent-detail-icon",children:e.jsx(yt,{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:Fe.bg,color:Fe.text,border:`1px solid ${Fe.border}`},children:c.state}),e.jsxs("span",{className:"badge",style:{color:ie.color},title:ie.reason??ie.label,children:[ie.icon,!ie.stateDerived&&ie.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 Re("active"),disabled:T,children:[e.jsx(Ts,{size:14}),"Start"]}),e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void Xe(),"aria-label":`Run now for ${c.name}`,disabled:O||T,children:[e.jsx(Cs,{size:14}),"Run Now"]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:es,children:[e.jsx(Ss,{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 Re("paused"),disabled:T,"aria-label":"Pause",children:[e.jsx(at,{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 Re("paused"),disabled:T,"aria-label":"Stop",children:[e.jsx(Ke,{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 Xe(),"aria-label":`Run now for ${c.name}`,disabled:O||T,children:[e.jsx(Cs,{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 Re("active"),disabled:T,"aria-label":"Resume",children:[e.jsx(Ts,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:"Resume"})]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:es,children:[e.jsx(Ss,{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 Re("paused"),disabled:T,"aria-label":"Pause",children:[e.jsx(at,{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 Re("paused"),disabled:T,"aria-label":"Stop",children:[e.jsx(Ke,{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 Re("active"),disabled:T,children:[e.jsx(Ts,{size:14}),"Retry"]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:()=>void Re("paused"),disabled:T,"aria-label":"Stop",children:[e.jsx(Ke,{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:ne,children:[e.jsx("button",{type:"button",className:"btn-icon",onClick:()=>Z(d=>!d),"aria-haspopup":"menu","aria-expanded":D,"aria-label":"Bulk agent actions",title:"Bulk agent actions",disabled:T||k,children:e.jsx(Zt,{size:16})}),D&&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 Ze("paused"),disabled:ye||k,children:["Pause All Agents",e.jsx("span",{className:"agent-detail-bulk-menu-item-hint",children:R?"Loading eligible agents...":ye?"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 Ze("active"),disabled:_e||k,children:["Resume All Agents",e.jsx("span",{className:"agent-detail-bulk-menu-item-hint",children:R?"Loading eligible agents...":_e?"No paused agents eligible":`Resume ${r} paused agent${r===1?"":"s"}`})]})]})]}),e.jsx("button",{className:"btn-icon",onClick:()=>void Ce(),title:"Refresh","aria-label":"Refresh",children:e.jsx(Rs,{size:16})}),!g&&e.jsx("button",{className:"btn-icon",onClick:i,"aria-label":"Close",title:"Close",children:e.jsx(St,{size:20})})]})]})]}),e.jsx("div",{className:"agent-detail-tabs",children:Ja.map(d=>e.jsxs("button",{className:re("agent-detail-tab",p===d.id&&"active"),onClick:()=>v(d.id),children:[e.jsx(d.icon,{size:16}),d.label]},d.id))}),e.jsxs("div",{className:"agent-detail-content",children:[p==="dashboard"&&e.jsx(Ya,{agent:c,health:ie,onChildClick:m,projectId:n}),p==="logs"&&e.jsx(Qa,{logs:E,isStreaming:S,hasTask:!!c.taskId||E.length>0||ce!==null,fallbackLabel:!c.taskId&&ce?`Latest run · ${ce.id.slice(0,8)}`:null}),p==="mail"&&e.jsx(Xa,{agent:c,mailbox:je,isLoading:xe,error:H,projectId:n,addToast:l,onRefresh:()=>void Je()}),p==="runs"&&e.jsx(en,{addToast:l,agentId:c.id,projectId:n,agentState:c.state,agentName:c.name,initialRunId:M,preferActiveRun:N,runNowRefreshToken:W,isEphemeral:Es(c)}),p==="tasks"&&e.jsx(nn,{agentId:c.id,projectId:n,addToast:l}),p==="employees"&&e.jsx(mn,{agentId:c.id,projectId:n,onChildClick:m}),p==="soul"&&e.jsx(rn,{agent:c,projectId:n,addToast:l,onSaved:we}),p==="instructions"&&e.jsx(cn,{agent:c,projectId:n,addToast:l,onSaved:we}),p==="memory"&&e.jsx(on,{agent:c,projectId:n,addToast:l,onSaved:we}),p==="reflections"&&e.jsx(Va,{agentId:c.id,projectId:n,addToast:l}),p==="config"&&e.jsx(un,{agent:c,projectId:n,addToast:l,onSaved:we,onHasChangesChange:He,onDelete:es,onAgentDraftApplied:d=>{C(z=>z&&{...z,...d})}},c.id)]}),!g&&e.jsxs("div",{className:"agent-detail-footer",children:[e.jsx("button",{className:"btn-icon",onClick:Ie,title:"Copy Agent ID",children:e.jsx(aa,{})}),e.jsx("span",{className:"agent-detail-id",onClick:Ie,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(wt,{size:12})]})]})]})]})})}function Ya({agent:s,health:n,onChildClick:i,projectId:l}){const m=Js[s.state],[g,P]=t.useState([]),[f,M]=t.useState(!0),[N,L]=t.useState(null),[c,C]=t.useState([]),[A,E]=t.useState(null),[y,X]=t.useState(null),[J,p]=t.useState(!1),[v,S]=t.useState(null),j=typeof s.runtimeConfig?.runtimeHint=="string"?s.runtimeConfig.runtimeHint:"",T=(()=>{const h=s.runtimeConfig??{};if(j){const x=c.find(r=>r.runtimeId===j);return x?x.name:j}if(h.modelProvider&&h.modelId)return`${h.modelProvider}/${h.modelId}`;if(typeof h.model=="string"&&h.model.includes("/")){const x=h.model.indexOf("/");return h.model.slice(x+1)}return null})();t.useEffect(()=>{Os(s.id,l).then(L).catch(()=>L(null))},[s.id,l]),t.useEffect(()=>{Rt(l).then(C).catch(()=>C([]))},[l]),t.useEffect(()=>{let h=!1;return M(!0),ra(s.id,l).then(x=>{if(h)return;const r=x.length>0&&x[0]?.id===s.id?[...x].reverse():x;P(r)}).catch(()=>{h||P([])}).finally(()=>{h||M(!1)}),()=>{h=!0}},[s.id,l]);const F=t.useMemo(()=>{const h=s.completedRuns||[],x=new Date;x.setHours(0,0,0,0);const r=h.filter(W=>new Date(W.startedAt)>=x),$=h.filter(W=>W.status==="completed");return{totalRuns:h.length,todayRuns:r.length,successfulRuns:$.length,successRate:h.length>0?Math.round($.length/h.length*100):0}},[s]),O=(s.completedRuns||[]).slice(0,5),Q=Array.isArray(s.metadata?.skills)?s.metadata.skills:[],D=A?$s(A):null,Z=t.useCallback(async h=>{p(!0),S(null),X(null);try{const x=await oa(h,l);X(x)}catch(x){S(I(x))}finally{p(!1)}},[l]),k=t.useCallback(h=>{if(A===h){E(null),X(null),S(null),p(!1);return}E(h),Z(h)},[Z,A]),ae=s.state==="active"||s.state==="running",R=ca(s.runtimeConfig?.heartbeatIntervalMs),_=ae&&s.lastHeartbeatAt?new Date(new Date(s.lastHeartbeatAt).getTime()+R).toISOString():null;return e.jsxs("div",{className:"dashboard-tab dashboard-summary-layout",children:[N?.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(Vs,{}),e.jsx("h3",{children:"Overview"}),e.jsx("strong",{children:s.name}),e.jsx("span",{className:"inline-badge",style:{background:m.bg,color:m.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:j?"Runtime":"Model"}),e.jsxs("span",{children:[" ",T??"Auto"]})]}),Q.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:Q.map(h=>{const x=A===h;return e.jsx("button",{type:"button",className:re("badge","badge-skill","dashboard-summary-skill-badge","dashboard-summary-skill-badge-btn",x&&"dashboard-summary-skill-badge--selected"),title:h,onClick:()=>k(h),"aria-expanded":x,"aria-label":`View details for ${$s(h)}`,children:$s(h)},h)})})]}):e.jsx("span",{children:"Skills: —"})]}),A?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:D}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>k(A),children:[e.jsx(St,{size:14}),"Close"]})]}),J?e.jsxs("div",{className:"dashboard-summary-skill-detail-loading",role:"status","aria-live":"polite",children:[e.jsx(q,{size:14,className:"animate-spin"}),"Loading skill content..."]}):v?e.jsxs("div",{className:"dashboard-summary-skill-detail-error",role:"alert",children:[e.jsx(Mt,{size:14}),e.jsx("span",{children:v}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void Z(A),children:"Retry"})]}):y?e.jsx("pre",{className:"dashboard-summary-skill-detail-content",children:y.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?Ye(s.lastHeartbeatAt):"Never"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:"Next expected"}),e.jsx("p",{children:_?Ye(_):"Not scheduled"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:"Interval"}),e.jsx("p",{children:At(R)})]}),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:re("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(wt,{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:[F.successfulRuns,"/",F.totalRuns," successful (",F.successRate,"%)"]}),O.length===0?e.jsx("p",{className:"text-muted",children:"No runs yet"}):e.jsx("div",{className:"runs-list",children:O.map(h=>{const x=ws[h.status]||ws.terminated,r=x.icon;return e.jsxs("div",{className:"run-item",children:[e.jsx(r,{size:14,style:{color:x.color}}),e.jsx("span",{children:Ye(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:F.totalRuns}),e.jsx("div",{className:"stat-label",children:"Total Runs"})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("div",{className:"stat-value",children:F.todayRuns}),e.jsx("div",{className:"stat-label",children:"Runs Today"})]}),e.jsxs("div",{className:"stat-card",children:[e.jsxs("div",{className:"stat-value",children:[F.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(q,{size:14,className:"animate-spin"}),e.jsx("span",{children:"Loading reporting chain..."})]}):g.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:g.map((h,x)=>{const r=x===g.length-1,$=!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:()=>$&&i?.(h.id),disabled:!$||!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 Qa({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(is,{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(Ft,{entries:s,loading:!1})]}):e.jsx("div",{className:"logs-tab",children:e.jsxs("div",{className:"logs-empty",children:[e.jsx(is,{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 Za(s){const n=new Date(s),l=new Date().getTime()-n.getTime(),m=Math.floor(l/6e4),g=Math.floor(l/36e5),P=Math.floor(l/864e5);return m<1?"Just now":m<60?`${m}m ago`:g<24?`${g}h ago`:P<7?`${P}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function js(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 Xa({agent:s,mailbox:n,isLoading:i,error:l,projectId:m,addToast:g,onRefresh:P}){const[f,M]=t.useState("inbox"),[N,L]=t.useState([]);t.useEffect(()=>{let v=!1;return ks(void 0,m).then(S=>{v||L(S)}).catch(()=>{v||L([])}),()=>{v=!0}},[m]);const c=t.useMemo(()=>{const v=new Map;for(const j of N){if(!j.id)continue;const T=typeof j.name=="string"?j.name.trim():"";T.length>0&&v.set(j.id,T)}const S=typeof s.name=="string"?s.name.trim():"";return S.length>0&&v.set(s.id,S),v},[N,s.id,s.name]),[C,A]=t.useState(null),E=f==="inbox"?n?.inbox??[]:n?.outbox??[],y=C?E.find(v=>v.id===C)??null:null;t.useEffect(()=>{A(null)},[f,s.id]);const X=async v=>{if(A(v.id),!(f!=="inbox"||v.read))try{await Fa(v.id,m),P()}catch(S){const j=`Failed to mark message as read: ${I(S)}`;g?g(j,"error"):console.warn(j)}},J=()=>{A(null),P()},p=v=>e.jsxs("button",{type:"button",className:re("mailbox-item","agent-mail-tab-message",f==="inbox"&&!v.read&&"unread",C===v.id&&"agent-mail-tab-message--selected"),onClick:()=>void X(v),"aria-pressed":C===v.id,children:[e.jsx("div",{className:"mailbox-item-avatar",children:(f==="inbox"?v.fromType:v.toType)==="agent"?e.jsx(Vs,{size:16}):e.jsx(ya,{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:js(v.fromId,v.fromType,c)}):e.jsxs("span",{className:"mailbox-item-to",children:["To: ",js(v.toId,v.toType,c)]}),e.jsx("span",{className:"mailbox-item-time",children:Za(v.createdAt)})]}),e.jsxs("div",{className:"mailbox-item-preview",children:[v.content.slice(0,80),v.content.length>80?"…":""]})]}),f==="inbox"&&!v.read?e.jsx("div",{className:"mailbox-item-unread-dot","aria-label":"Unread message"}):null]},v.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:J,disabled:i,children:[e.jsx(Rs,{size:14}),"Refresh"]})]}),e.jsxs("div",{className:"mailbox-agent-subtabs","data-testid":"agent-detail-mail-subtabs",children:[e.jsxs("button",{className:re("btn","btn-sm","btn-secondary","mailbox-agent-subtab",f==="inbox"&&"active"),onClick:()=>M("inbox"),children:[e.jsx(it,{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:re("btn","btn-sm","btn-secondary","mailbox-agent-subtab",f==="outbox"&&"active"),onClick:()=>M("outbox"),children:[e.jsx(lt,{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(q,{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(Mt,{size:16}),e.jsxs("span",{children:["Failed to load mailbox: ",l]})]}):null,!i&&!l?y?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:()=>A(null),children:[e.jsx(Nt,{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:js(y.fromId,y.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:js(y.toId,y.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:y.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(y.createdAt).toLocaleString()})]}),y.metadata?.replyTo?.messageId?e.jsxs("div",{className:"agent-mail-tab-reply-context",children:["↪ Replying to message ",y.metadata.replyTo.messageId]}):null]}),e.jsx("div",{className:"agent-mail-tab-detail-body",children:y.content})]}):e.jsx("div",{className:"mailbox-list","data-testid":"agent-detail-mail-list",children:E.length===0?e.jsxs("div",{className:"mailbox-empty","data-testid":"agent-detail-mail-empty",children:[f==="inbox"?e.jsx(it,{size:32}):e.jsx(lt,{size:32}),e.jsx("p",{children:f==="inbox"?"No received messages for this agent":"No sent messages for this agent"})]}):E.map(p)}):null]})}function en({addToast:s,agentId:n,projectId:i,agentState:l,agentName:m,initialRunId:g,preferActiveRun:P,runNowRefreshToken:f,isEphemeral:M}){const[N,L]=t.useState([]),{confirm:c}=pt(),[C,A]=t.useState(!0),[E,y]=t.useState(null),[X,J]=t.useState([]),[p,v]=t.useState(!1),[S,j]=t.useState(null),[T,F]=t.useState(!1),[O,Q]=t.useState(null),[D,Z]=t.useState([]),k=t.useRef(!1),ae=t.useRef(!1),R=t.useCallback(async()=>{try{const u=await vt(n,50,i);L(u)}catch(u){s(`Failed to load runs: ${I(u)}`,"error")}finally{A(!1)}},[n,i,s]);t.useEffect(()=>{R()},[R]),t.useEffect(()=>{if(M){Q(null),Z([]);return}const u=i?`?projectId=${encodeURIComponent(i)}`:"";fetch(`/api/agents/${encodeURIComponent(n)}/token-usage${u}`).then(async b=>{if(!b.ok){if(b.status===400){Q(null);return}throw new Error(`Request failed: ${b.status}`)}const ne=await b.json();Q(ne)}).catch(b=>{s(`Failed to load cache hit ratio: ${I(b)}`,"error")}),ua(n,7,i).then(b=>Z(b)).catch(b=>{const ne=I(b).toLowerCase();if(ne.includes("ephemeral")||ne.includes("400")){Z([]);return}s(`Failed to load prompt sizes: ${I(b)}`,"error")})},[n,i,s,M]),t.useEffect(()=>{if(!ae.current){ae.current=!0;return}A(!0),R()},[R,f]);const _=N.some(u=>u.status==="active"),h=E?N.find(u=>u.id===E)?.status:void 0;t.useEffect(()=>{if(!_)return;const u=setInterval(()=>{R()},5e3);return()=>clearInterval(u)},[_,R]),t.useEffect(()=>{if(!E||h!=="active")return;const u=i?`?projectId=${encodeURIComponent(i)}`:"";return Ns(`/api/agents/${encodeURIComponent(n)}/runs/${encodeURIComponent(E)}/logs/stream${u}`,{events:{"agent:log":b=>{try{const ne=JSON.parse(b.data);J(he=>[...he,ne])}catch{}}}})},[E,h,n,i]);const x=t.useCallback(async u=>{if(E===u){y(null),J([]),j(null);return}y(u),v(!0),F(!0),J([]),j(null);try{const[b,ne]=await Promise.all([jt(n,u,i),ma(n,u,i)]);J(b),j(ne)}catch(b){s(`Failed to load run details: ${I(b)}`,"error"),J([]),j(null)}finally{v(!1),F(!1)}},[E,n,i,s]);t.useEffect(()=>{k.current=!1},[n,g,P]),t.useEffect(()=>{if(N.length===0||C||k.current)return;const u=g?N.find(b=>b.id===g):P?N.find(b=>b.status==="active"):null;k.current=!0,u&&x(u.id)},[g,P,N,C,x]);const r=async()=>{if(await c({title:"Stop Active Run",message:"Stop the active run? The agent's work will be interrupted.",danger:!0}))try{await Sa(n,i),s("Run stopped","success"),A(!0),R()}catch(b){s(`Failed to stop run: ${I(b)}`,"error")}};if(C&&N.length===0)return e.jsx("div",{className:"runs-tab",children:e.jsxs("div",{className:"runs-loading-row",children:[e.jsx(q,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading runs..."})]})});if(N.length===0)return e.jsx("div",{className:"runs-tab",children:e.jsxs("div",{className:"runs-empty",children:[e.jsx(Cs,{size:48,opacity:.3}),e.jsx("p",{children:"No runs yet"}),e.jsx("p",{className:"text-muted",children:"Heartbeat runs will appear here"})]})});const $=[...N].sort((u,b)=>new Date(b.startedAt).getTime()-new Date(u.startedAt).getTime()),W=$.filter(u=>u.status==="active"),ke=$.filter(u=>u.status!=="active"),ce=u=>u?e.jsxs("div",{className:"run-usage",children:[e.jsxs("span",{children:["Input: ",u.inputTokens.toLocaleString()]}),e.jsxs("span",{children:["Output: ",u.outputTokens.toLocaleString()]}),u.cachedTokens>0&&e.jsxs("span",{children:["Cache read: ",u.cachedTokens.toLocaleString()]}),(u.cacheWriteTokens??0)>0&&e.jsxs("span",{children:["Cache write: ",(u.cacheWriteTokens??0).toLocaleString()]})]}):null,ve=(u,b,ne)=>{const he=ws[u.status]||ws.completed,Ve=he.icon,Pe=u.endedAt?sn(new Date(u.startedAt),new Date(u.endedAt)):"In progress",Ae=E===u.id;return e.jsxs("div",{children:[e.jsxs("div",{className:re("run-card",ne&&"run-card--active",Ae&&"run-card--selected","run-card--clickable"),onClick:()=>void x(u.id),role:"button",tabIndex:0,"aria-expanded":Ae,"aria-label":`${ne?"Active":""} run ${u.id.slice(0,8)}, ${u.status}`,onKeyDown:oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),x(u.id))},children:[e.jsxs("div",{className:"run-header",children:[e.jsxs("div",{className:"run-header-group",children:[Ae?e.jsx(xt,{size:14}):e.jsx(bt,{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:["#",b+1," ",u.id.slice(0,8)]})]}),e.jsxs("div",{className:"run-header-group",children:[u.invocationSource&&e.jsx("span",{className:"badge run-badge--compact",children:u.invocationSource}),ne&&e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:oe=>{oe.preventDefault(),oe.stopPropagation(),r()},"aria-label":"Stop active run",children:[e.jsx(Ke,{size:12})," Stop"]}),e.jsxs("span",{className:re("run-status",u.status),children:[e.jsx(Ve,{size:14,style:{color:he.color}}),u.status]}),u.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 ",Ye(u.startedAt)]}),e.jsx("span",{children:"•"}),e.jsx("span",{children:Pe}),u.triggerDetail&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsx("span",{className:"text-muted",children:u.triggerDetail})]})]})]}),Ae&&e.jsxs("div",{className:"run-logs-container",children:[T?e.jsxs("div",{className:"run-details-loading-state",children:[e.jsx(q,{size:14,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading details..."})]}):S&&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"}),S.systemPrompt?e.jsx("pre",{className:"run-output-panel",children:S.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"}),S.executionPrompt?e.jsx("pre",{className:"run-output-panel",children:S.executionPrompt}):e.jsx("div",{className:"text-muted run-output-empty",children:"Execution prompt not captured for this run"})]})}),S.usageJson&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:"Token Usage"}),ce(S.usageJson)]}),S.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:S.stdoutExcerpt.length>2e3?`${S.stdoutExcerpt.slice(0,2e3)}
17
17
 
18
- ... (truncated, ${S.stdoutExcerpt.length} chars total)`:S.stdoutExcerpt})]}),S.stderrExcerpt&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label run-output-label--error",children:"Errors"}),e.jsx(ka,{errorText:S.stderrExcerpt,summaryPrefix:"Run error",issueContext:{surface:"AgentDetailView runs",agentId:n,agentName:m,agentState:l,runId:S.id,taskId:void 0,timestamp:S.startedAt}})]}),S.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(S.resultJson,null,2)})]}),S.contextSnapshot&&Object.keys(S.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(S.contextSnapshot).map(([oe,Ee])=>e.jsxs("span",{className:"run-context-item",children:[e.jsxs("span",{className:"text-muted",children:[oe,":"]})," ",e.jsx("span",{children:String(Ee)})]},oe))})]}),!S.stdoutExcerpt&&!S.stderrExcerpt&&!S.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"}),p?e.jsxs("div",{className:"run-details-loading-state",children:[e.jsx(q,{size:14,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading logs..."})]}):Q.length===0?e.jsx("div",{className:"text-muted run-output-empty",children:"No logs available for this run"}):e.jsx(Ft,{entries:Q,loading:!1})]})]})]},u.id)},je=(u,b)=>e.jsxs("div",{className:"run-context-item",children:[e.jsxs("span",{className:"text-muted",children:[u,":"]})," ",e.jsxs("span",{children:[(b.hitRatio*100).toFixed(1),"% (",b.totalCachedTokens.toLocaleString()," / ",b.totalCacheWriteTokens.toLocaleString()," / ",b.totalInputTokens.toLocaleString()," / ",b.nTasks.toLocaleString(),")"]})]},u),Ne=D[0],xe=[...D].reverse(),U=Math.max(1,...xe.map(u=>u.execChars)),H=xe.map((u,b)=>{const ne=xe.length<=1?0:b/(xe.length-1)*100,he=100-Math.round(u.execChars/U*100);return`${ne},${he}`}).join(" ");return e.jsxs("div",{className:"runs-tab",children:[D.length>0&&Ne&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:"Prompt Size"}),e.jsxs("div",{className:"prompt-size-summary",children:[e.jsxs("svg",{className:"prompt-size-sparkline",viewBox:"0 0 100 100",role:"img","aria-label":"Execution prompt size over last 7 runs",children:[e.jsx("polyline",{className:"prompt-size-sparkline-grid",points:"0,100 100,100"}),e.jsx("polyline",{className:"prompt-size-sparkline-line",points:H})]}),e.jsxs("span",{className:"prompt-size-values",children:[Ne.systemChars.toLocaleString()," / ",Ne.execChars.toLocaleString()," / ",Ne.totalChars.toLocaleString()]})]})]}),O&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:"Cache hit ratio"}),e.jsxs("div",{className:"run-context-grid",children:[je("Last 24h",O.last24h),je("Last 7d",O.last7d),je("All time",O.allTime)]})]}),e.jsxs("div",{className:"runs-toolbar runs-toolbar--between",children:[e.jsxs("span",{className:"runs-toolbar-meta",children:[N.length," run",N.length!==1?"s":"",_&&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:_&&e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void r(),"aria-label":`Stop active run for ${m??n}`,children:[e.jsx(Ye,{size:14})," Stop Run"]})})]}),W.map((u,b)=>ve(u,b,!0)),ke.map((u,b)=>ve(u,W.length+b,!1))]})}function sn(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 tn={triage:"Triage",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"};function an(s){const n=s.title?.trim()||s.description?.trim()||s.id;return n.length>80?`${n.slice(0,77)}...`:n}function nn({agentId:s,projectId:n,addToast:i}){const[l,m]=t.useState([]),[g,P]=t.useState(!0);return t.useEffect(()=>{let f=!1;return P(!0),ha(s,n).then(M=>{f||m(M)}).catch(M=>{f||(m([]),i(`Failed to load assigned tasks: ${I(M)}`,"error"))}).finally(()=>{f||P(!1)}),()=>{f=!0}},[s,n,i]),g?e.jsxs("div",{className:"agent-tasks-empty",children:[e.jsx(q,{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(kt,{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:tn[f.column]})]}),e.jsx("div",{className:"agent-task-title",title:f.title||f.description||f.id,children:an(f)}),e.jsxs("div",{className:"agent-task-status",children:[f.status??"idle"," · Updated ",Ke(f.updatedAt)]})]},f.id))})}const ns=[{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 ln(s){const n={};for(const i of ns){const l=s[i.key]?.trim();if(l){if(i.type==="number"){const m=Number(l);if(Number.isNaN(m)||!Number.isFinite(m)){n[i.key]=`"${i.label}" must be a valid number`;continue}i.min!==void 0&&m<i.min&&(n[i.key]=`"${i.label}" must be at least ${i.min.toLocaleString()}`),i.max!==void 0&&m>i.max&&(n[i.key]=`"${i.label}" must be at most ${i.max.toLocaleString()}`)}if(i.type==="select"){const m=i.options?.map(g=>g.value)??[];m.length>0&&!m.includes(l)&&(n[i.key]=`"${i.label}" must be one of: ${m.join(", ")}`)}}}return n}function rn({agent:s,projectId:n,addToast:i,onSaved:l}){const[m,g]=t.useState(s.soul??""),[P,f]=t.useState(!1),[M,N]=t.useState(!1),[L,c]=t.useState(!1),C=t.useRef(null);t.useEffect(()=>{g(s.soul??""),N(!1),c(!1)},[s.id,s.soul]),t.useEffect(()=>()=>{C.current&&clearTimeout(C.current)},[]);const A=m!==(s.soul??""),E=async()=>{if(m.length>1e4){i("Soul must be at most 10,000 characters","error");return}f(!0);try{await Ca(s.id,m,n),i("Soul saved","success"),N(!0),C.current&&clearTimeout(C.current),C.current=setTimeout(()=>N(!1),3e3),await l()}catch(y){i(`Failed to save soul: ${I(y)}`,"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 ${L?"":"btn-primary"}`,onClick:()=>c(!1),disabled:!L,"aria-label":"Edit mode",children:[e.jsx(ls,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${L?"btn-primary":""}`,onClick:()=>c(!0),disabled:L,"aria-label":"Preview mode",children:[e.jsx(rs,{size:14}),"Preview"]})]})}),L?m.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(os,{remarkPlugins:[cs],children:m})}):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:m,onChange:y=>{g(y.target.value),N(!1)}}),!L&&e.jsx("span",{className:"config-hint",children:"Defines the agent's character and identity. Max 10,000 characters."})]})}),!L&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!A||P,onClick:()=>void E(),children:P?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(me,{size:16}),"Save Soul"]})}),!A&&M&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(me,{size:14}),"Soul saved"]})]})]})})}function on({agent:s,projectId:n,addToast:i,onSaved:l}){const[m,g]=t.useState(s.memory??""),[P,f]=t.useState(!1),[M,N]=t.useState(!1),[L,c]=t.useState(!1),[C,A]=t.useState(!1),[E,y]=t.useState([]),[Q,J]=t.useState(!1),[p,v]=t.useState(""),[S,j]=t.useState(""),[T,F]=t.useState(!1),[O,X]=t.useState(!1),[D,Z]=t.useState(!1),[k,ae]=t.useState(!1),[R,_]=t.useState(""),h=t.useRef(null),x=t.useRef(null),r=s.state==="running",$=m!==(s.memory??""),W=t.useMemo(()=>E.find(U=>U.path===p),[E,p]),ke=W?Wa[W.layer]:"Select a memory file to view or edit.",ce=t.useCallback(async U=>{X(!0);try{const H=await ga(s.id,U,n);v(H.path),j(H.content),F(!1),ae(!1)}catch(H){i(`Failed to load agent memory file: ${I(H)}`,"error")}finally{X(!1)}},[s.id,n,i]),ve=t.useCallback(async(U="")=>{J(!0);try{const{files:H}=await xa(s.id,n);if(y(H),H.length===0){v(""),j(""),F(!1);return}const u=Ya(H,U);await ce(u)}catch(H){i(`Failed to load memory files: ${I(H)}`,"error"),y([]),v(""),j(""),F(!1)}finally{J(!1)}},[s.id,n,i,ce]);t.useEffect(()=>{g(s.memory??""),N(!1),c(!1),A(!1),_(""),ae(!1),ve()},[s.id,s.memory,ve]),t.useEffect(()=>()=>{h.current&&clearTimeout(h.current),x.current&&clearTimeout(x.current)},[]);const je=async()=>{if(m.length>5e4){i("Memory must be at most 50,000 characters","error");return}f(!0);try{await Ra(s.id,m,n),i("Memory saved","success"),N(!0),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>N(!1),3e3),await l()}catch(U){i(`Failed to save memory: ${I(U)}`,"error")}finally{f(!1)}},Ne=async U=>{if(!(!U||U===p)){if(T){_("Save the current file before switching to another file.");return}_(""),await ce(U)}},xe=async()=>{if(p){Z(!0);try{await Ma(s.id,p,S,n),F(!1),ae(!0),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>ae(!1),3e3),_(""),await ve(p),i("Agent memory file saved","success"),await l()}catch(U){i(`Failed to save agent memory file: ${I(U)}`,"error")}finally{Z(!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 ${L?"":"btn-primary"}`,onClick:()=>c(!1),disabled:!L,"aria-label":"Edit mode",children:[e.jsx(ls,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${L?"btn-primary":""}`,onClick:()=>c(!0),disabled:L,"aria-label":"Preview mode",children:[e.jsx(rs,{size:14}),"Preview"]})]})}),L?m.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(os,{remarkPlugins:[cs],children:m})}):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:m,readOnly:r,onChange:U=>{g(U.target.value),N(!1)}}),!L&&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:Q||O||D||E.length===0,onChange:U=>{Ne(U.target.value)},children:E.length===0?e.jsx("option",{value:"",children:"No memory files found"}):E.map(U=>e.jsxs("option",{value:U.path,children:[mt[U.layer]," • ",U.label]},U.path))}),Q&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(q,{size:14,className:"animate-spin"}),"Loading memory files…"]}),W&&e.jsxs("div",{className:"config-hint config-hint--top-spacing",children:[e.jsx("strong",{children:mt[W.layer]})," · ",ke,e.jsx("br",{}),W.size.toLocaleString()," bytes · Updated ",Ke(W.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:()=>A(!1),disabled:!C,"aria-label":"Memory file edit mode",children:[e.jsx(ls,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${C?"btn-primary":""}`,onClick:()=>A(!0),disabled:C,"aria-label":"Memory file preview mode",children:[e.jsx(rs,{size:14}),"Preview"]})]})}),C?S.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(os,{remarkPlugins:[cs],children:S})}):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:S,readOnly:r||!p||O,onChange:U=>{j(U.target.value),F(!0),ae(!1),_("")}}),O&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(q,{size:14,className:"animate-spin"}),"Loading file content…"]}),R&&e.jsx("span",{className:"config-hint config-hint--top-spacing config-hint--block",children:R})]})]}),e.jsxs("div",{className:"config-actions",children:[!L&&e.jsx("button",{className:"btn btn-task-create",disabled:!$||P||r,onClick:()=>void je(),children:P?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(me,{size:16}),"Save Memory"]})}),!C&&e.jsx("button",{className:"btn",disabled:!T||D||!p||r,onClick:()=>void xe(),children:D?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),"Saving file…"]}):e.jsxs(e.Fragment,{children:[e.jsx(me,{size:16}),"Save Memory File"]})}),!$&&M&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(me,{size:14}),"Memory saved"]}),!T&&k&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(me,{size:14}),"Memory file saved"]})]})]})})}function cn({agent:s,projectId:n,addToast:i,onSaved:l}){const[m,g]=t.useState(s.instructionsText??""),[P,f]=t.useState(s.instructionsPath??""),[M,N]=t.useState(!1),[L,c]=t.useState(""),[C,A]=t.useState(!1),[E,y]=t.useState(!1),[Q,J]=t.useState(!1),[p,v]=t.useState(!1),[S,j]=t.useState(!1),[T,F]=t.useState(!1),O=t.useRef(null),X=t.useRef(null);t.useEffect(()=>{const R=P.trim();if(!R){c(""),y(!1);return}A(!0),Pt("project",R).then(_=>{c(_.content),y(!1)}).catch(_=>{const h=I(_);h.includes("ENOENT")||h.includes("Not found")||h.includes("not found")?(c(""),y(!1)):(i(`Failed to load instructions file: ${h}`,"error"),c(""))}).finally(()=>{A(!1)})},[P,i]),t.useEffect(()=>{g(s.instructionsText??""),f(s.instructionsPath??""),j(!1),F(!1),N(!1)},[s.id,s.instructionsText,s.instructionsPath]),t.useEffect(()=>()=>{O.current&&clearTimeout(O.current),X.current&&clearTimeout(X.current)},[]);const D=(()=>{const R=m??"",_=s.instructionsText??"",h=P?.trim()??"",x=s.instructionsPath?.trim()??"";return R!==_||h!==x})(),Z=async()=>{J(!0);try{await wa(s.id,{instructionsText:m||void 0,instructionsPath:P.trim()||void 0},n),i("Instructions saved","success"),j(!0),O.current&&clearTimeout(O.current),O.current=setTimeout(()=>j(!1),3e3),await l()}catch(R){i(`Failed to save instructions: ${I(R)}`,"error")}finally{J(!1)}},k=async()=>{const R=P.trim();if(!R){i("No instructions file path set","error");return}v(!0);try{await Et("project",R,L),i("Instructions file saved","success"),y(!1),F(!0),X.current&&clearTimeout(X.current),X.current=setTimeout(()=>F(!1),3e3),await l()}catch(_){i(`Failed to save instructions file: ${I(_)}`,"error")}finally{v(!1)}},ae=!!P.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 ${M?"":"btn-primary"}`,onClick:()=>N(!1),disabled:!M,"aria-label":"Edit mode","data-testid":"instructions-edit-toggle",children:[e.jsx(ls,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${M?"btn-primary":""}`,onClick:()=>N(!0),disabled:M,"aria-label":"Preview mode","data-testid":"instructions-preview-toggle",children:[e.jsx(rs,{size:14}),"Preview"]})]})}),M?m.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(os,{remarkPlugins:[cs],children:m})}):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:m,onChange:R=>{g(R.target.value),j(!1)}}),!M&&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:P,onChange:R=>{f(R.target.value),j(!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."})]})]}),!M&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!D||Q,onClick:()=>void Z(),children:Q?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(me,{size:16}),"Save Instructions"]})}),!D&&S&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(me,{size:14}),"Instructions saved"]})]})]}),ae&&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(q,{size:12,className:"animate-spin"}),"Loading..."]}),E&&!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:L,readOnly:C,onChange:R=>{c(R.target.value),y(!0),F(!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:!E||p,onClick:()=>void k(),children:p?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(me,{size:16}),"Save File"]})}),!E&&T&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(me,{size:14}),"File saved"]})]})]})]})}function ht(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),n.autoClaimCandidatesInPrompt!==void 0&&n.autoClaimCandidatesInPrompt!==null&&(i.autoClaimCandidatesInPrompt=String(n.autoClaimCandidatesInPrompt)),i}function Ls(s){return s?.enabled!==!1}function Ds(s){return s?.autoClaimRelevantTasks!==!1}function zs(s){return s?.runMissedHeartbeatOnStartup===!0}function Hs(s){return s?.allowParallelExecution!==!1}function Bs(s){return s?.skipHeartbeatWhenIdle===!0}function Is(s){const n=s?.heartbeatScopeDiscipline;return n==="strict"||n==="lite"||n==="off"?n:""}function ft(s){const n=s?.heartbeatPromptTemplate;return n==="default"||n==="compact"?n:""}function gt(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 dn({agent:s,projectId:n,addToast:i,onSaved:l}){const[m,g]=t.useState(!1),[P,f]=t.useState(!1),[M,N]=t.useState(!1),[L,c]=t.useState(!1),[C,A]=t.useState(!1),[E,y]=t.useState(""),[Q,J]=t.useState(!1),[p,v]=t.useState(null),[S,j]=t.useState(!1),T=t.useRef(null),F=s.heartbeatProcedurePath?.trim(),O=`.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`,X=`.fusion/agents/${s.id}/HEARTBEAT.md`,D=s.id.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"agent",Z=!!(F&&(F===O||F===X||new RegExp(`^\\.fusion/agents/[^/]+-${D}/HEARTBEAT\\.md$`).test(F))),k=!!F,ae=t.useCallback(async x=>{N(!0),v(null);try{const r=await Pt("project",x,n);y(r.content),J(!1)}catch(r){const $=I(r);v($),i(`Failed to load heartbeat procedure file: ${$}`,"error")}finally{N(!1)}},[i,n]);t.useEffect(()=>{f(!1),A(!1),y(""),J(!1),v(null),N(!1),c(!1),j(!1)},[s.id,F]),t.useEffect(()=>()=>{T.current&&clearTimeout(T.current)},[]);const R=async()=>{F&&(f(!0),await ae(F))},_=async()=>{if(F){c(!0);try{await Et("project",F,E,n),J(!1),j(!0),i("Heartbeat procedure file saved","success"),T.current&&clearTimeout(T.current),T.current=setTimeout(()=>j(!1),3e3),await l()}catch(x){i(`Failed to save heartbeat procedure file: ${I(x)}`,"error")}finally{c(!1)}}},h=async()=>{g(!0);try{const x=await Pa(s.id,n);i(x.procedureFileSeeded?`Heartbeat procedure file ready at ${x.heartbeatProcedurePath}`:`Heartbeat procedure path set to ${x.heartbeatProcedurePath}`,"success"),await l()}catch(x){i(`Failed to upgrade heartbeat procedure: ${I(x)}`,"error")}finally{g(!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:F||"(none — using built-in default)"})]}),k&&e.jsx("div",{className:"heartbeat-procedure-actions",children:e.jsx("button",{className:"btn btn-sm",onClick:()=>void R(),disabled:M,children:M?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),"Loading file…"]}):e.jsxs(e.Fragment,{children:[e.jsx(is,{size:16}),"View Heartbeat Markdown"]})})})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("button",{className:"btn",disabled:m||Z,onClick:()=>void h(),"aria-label":"Upgrade agent to default heartbeat procedure file",children:m?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),"Upgrading…"]}):Z?e.jsxs(e.Fragment,{children:[e.jsx(me,{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:O})," ","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."]})]})]}),P&&k&&F&&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:()=>A(!1),disabled:!C,"aria-label":"Heartbeat file edit mode",children:[e.jsx(ls,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${C?"btn-primary":""}`,onClick:()=>A(!0),disabled:C,"aria-label":"Heartbeat file preview mode",children:[e.jsx(rs,{size:14}),"Preview"]})]}),M&&e.jsxs("span",{className:"config-hint heartbeat-procedure-status",children:[e.jsx(q,{size:12,className:"animate-spin"}),"Loading..."]}),Q&&!M&&e.jsx("span",{className:"config-hint heartbeat-procedure-status heartbeat-procedure-status--warning",children:"Unsaved changes"})]}),C?E.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(os,{remarkPlugins:[cs],children:E})}):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:E,readOnly:M,placeholder:"Heartbeat procedure markdown file content will appear here...",onChange:x=>{y(x.target.value),J(!0),j(!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:F}),"."]})]}),!C&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!Q||L||M,onClick:()=>void _(),children:L?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(me,{size:16}),"Save Heartbeat File"]})}),!Q&&S&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(me,{size:14}),"File saved"]})]})]})]})}function un({agent:s,projectId:n,addToast:i,onSaved:l,onHasChangesChange:m,onDelete:g,onAgentDraftApplied:P}){const[f,M]=t.useState(s.name),[N,L]=t.useState(s.role),[c,C]=t.useState(s.title??""),[A,E]=t.useState(s.icon??""),[y,Q]=t.useState(s.reportsTo??""),[J,p]=t.useState([]),[v,S]=t.useState(!1),[j,T]=t.useState(!1),[F,O]=t.useState(!1),X=t.useRef(null),[D,Z]=t.useState(()=>{const a={};for(const o of ns){const w=s.metadata[o.key];w!=null&&(a[o.key]=String(w))}return a}),[k,ae]=t.useState(()=>ht(s.runtimeConfig)),[R,_]=t.useState(()=>Ls(s.runtimeConfig)),[h,x]=t.useState(()=>Ds(s.runtimeConfig)),[r,$]=t.useState(()=>zs(s.runtimeConfig)),[W,ke]=t.useState(()=>Hs(s.runtimeConfig)),[ce,ve]=t.useState(()=>Bs(s.runtimeConfig)),[je,Ne]=t.useState(()=>Is(s.runtimeConfig)),[xe,U]=t.useState(()=>ft(s.runtimeConfig)),[H,u]=t.useState(()=>gt(s.runtimeConfig)),[b,ne]=t.useState(s.bundleConfig?.mode??""),[he,Ve]=t.useState(s.bundleConfig?.entryFile??"AGENTS.md"),[Pe,Ae]=t.useState(s.bundleConfig?.externalPath??""),[oe,Ee]=t.useState(s.bundleConfig?.files??[]),[se,Xe]=t.useState(Array.isArray(s.metadata?.skills)?s.metadata.skills:[]),[ds,Ce]=t.useState([]),[us,Je]=t.useState(!1),[He,Be]=t.useState([]),[we,Re]=t.useState([]),[Ze,Qe]=t.useState([]),[es,ms]=t.useState(!1),Ie=(()=>{const a=s.runtimeConfig??{};return a.modelProvider&&a.modelId?`${a.modelProvider}/${a.modelId}`:typeof a.model=="string"&&a.model.includes("/")?a.model:""})(),Fe=typeof s.runtimeConfig?.runtimeHint=="string"?s.runtimeConfig.runtimeHint:"",[ie,Oe]=t.useState(Fe?"runtime":"model"),[ye,_e]=t.useState(Ie),[d,z]=t.useState(Fe),[V,B]=t.useState(s.permissionPolicy),[te,fe]=t.useState(void 0),Se=y.trim(),Te=t.useMemo(()=>J.filter(a=>a.id!==s.id),[J,s.id]),hs=!!Se&&!Te.some(a=>a.id===Se),fs=t.useMemo(()=>({name:f,role:N,title:c||void 0,instructionsText:s.instructionsText,soul:s.soul,memory:s.memory,reportsTo:y||void 0,skills:se,model:ye||void 0,runtimeHint:ie==="runtime"&&d||void 0,thinkingLevel:D.thinkingLevel??void 0,maxTurns:D.maxTurns?Number(D.maxTurns):void 0,heartbeatIntervalMs:k.heartbeatIntervalMs?Number(k.heartbeatIntervalMs)*1e3:void 0,heartbeatTimeoutMs:k.heartbeatTimeoutMs?Number(k.heartbeatTimeoutMs)*1e3:void 0,maxConcurrentRuns:k.maxConcurrentRuns?Number(k.maxConcurrentRuns):void 0,messageResponseMode:k.messageResponseMode}),[s.instructionsText,s.memory,s.soul,D.maxTurns,D.thinkingLevel,k.heartbeatIntervalMs,k.heartbeatTimeoutMs,k.maxConcurrentRuns,k.messageResponseMode,ye,f,y,N,ie,d,se,c]),gs=t.useCallback(a=>{M(a.name),L(a.role),C(a.title??""),E(a.icon??""),Q(a.reportsTo??""),a.skills&&Xe(a.skills),a.thinkingLevel&&Z(w=>({...w,thinkingLevel:a.thinkingLevel})),a.maxTurns!==void 0&&Z(w=>({...w,maxTurns:String(a.maxTurns)})),a.runtimeHint!==void 0?(Oe("runtime"),z(a.runtimeHint??""),a.runtimeHint&&_e("")):a.model!==void 0&&(Oe("model"),_e(a.model??""),z(""));const o=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));P?.(o),O(!1),i("Interview draft applied. Review and save when ready.","success")},[i,P]);t.useEffect(()=>{B(s.permissionPolicy)},[s.permissionPolicy]),t.useEffect(()=>{ba(n).then(a=>fe(a.project?.defaultAgentPermissionPolicy?.rules)).catch(()=>fe(void 0))},[n]);const ue=async a=>{B(a);try{await ot(s.id,{permissionPolicy:a},n),await l(),i("Permission policy updated","success")}catch(o){i(`Failed to update permission policy: ${I(o)}`,"error")}};t.useEffect(()=>{let a=!1;return S(!0),ks(void 0,n).then(o=>{a||p(o)}).catch(()=>{a||p([])}).finally(()=>{a||S(!1)}),()=>{a=!0}},[n]),t.useEffect(()=>{Je(!0),pa().then(a=>{Ce(a.models),Be(a.favoriteProviders),Re(a.favoriteModels)}).catch(()=>{}).finally(()=>Je(!1))},[]);const We=t.useCallback(async a=>{const o=He,Y=o.includes(a)?o.filter(ge=>ge!==a):[a,...o];Be(Y);try{await rt({favoriteProviders:Y,favoriteModels:we})}catch{Be(o)}},[He,we]),Ms=t.useCallback(async a=>{const o=we,Y=o.includes(a)?o.filter(ge=>ge!==a):[a,...o];Re(Y);try{await rt({favoriteProviders:He,favoriteModels:Y})}catch{Re(o)}},[He,we]);t.useEffect(()=>{ms(!0),Rt(n).then(Qe).catch(()=>Qe([])).finally(()=>ms(!1))},[n]);const[De,As]=t.useState(null),[Ws,qs]=t.useState(!1);t.useEffect(()=>{Os(s.id,n).then(As).catch(()=>As(null))},[s.id,n]);const $t=async()=>{qs(!0);try{await Aa(s.id,n),i("Budget usage reset successfully","success");const a=await Os(s.id,n);As(a)}catch(a){i(`Failed to reset budget: ${I(a)}`,"error")}finally{qs(!1)}},[ze,Gs]=t.useState(!1),[G,Ue]=t.useState({}),[Lt,qe]=t.useState(!1),[Fs,xs]=t.useState(null),Ys=s.state==="idle"||s.state==="paused",ss=t.useRef(null),Ks=t.useRef(null),Xs=t.useRef(null),bs=t.useRef(0);t.useEffect(()=>()=>{ss.current&&clearTimeout(ss.current)},[]);const Me=(()=>{if(f!==s.name||N!==s.role||c!==(s.title??"")||A!==(s.icon??"")||y!==(s.reportsTo??"")||b!==(s.bundleConfig?.mode??"")||he!==(s.bundleConfig?.entryFile??"AGENTS.md")||Pe!==(s.bundleConfig?.externalPath??"")||JSON.stringify(oe)!==JSON.stringify(s.bundleConfig?.files??[]))return!0;for(const ee of ns){const be=D[ee.key]?.trim()??"",pe=s.metadata[ee.key]!==void 0&&s.metadata[ee.key]!==null?String(s.metadata[ee.key]):"";if(be!==pe)return!0}const a=s.runtimeConfig??{};if(R!==Ls(s.runtimeConfig)||h!==Ds(s.runtimeConfig)||r!==zs(s.runtimeConfig)||W!==Hs(s.runtimeConfig)||ce!==Bs(s.runtimeConfig)||je!==Is(s.runtimeConfig)||xe!==ft(s.runtimeConfig))return!0;for(const ee of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns","messageResponseMode","autoClaimCandidatesInPrompt"]){const be=k[ee]?.trim()??"";let pe=a[ee]!==void 0&&a[ee]!==null?String(a[ee]):"";if((ee==="heartbeatIntervalMs"||ee==="heartbeatTimeoutMs")&&pe&&(pe=String(Number(pe)/1e3)),be!==pe)return!0}const o=a.budgetConfig;for(const ee of["tokenBudget","budgetPeriod","resetDay"]){const be=H[ee]?.trim()??"",pe=o?.[ee]!==void 0&&o?.[ee]!==null?String(o[ee]):"";if(be!==pe)return!0}const w=H.usageThreshold?.trim()??"",Y=o?.usageThreshold!==void 0&&o?.usageThreshold!==null?String(Number(o.usageThreshold)*100):"";if(w!==Y)return!0;const ge=Array.isArray(s.metadata?.skills)?s.metadata.skills:[];return JSON.stringify(se)!==JSON.stringify(ge)||ie!==(Fe?"runtime":"model")||ye!==Ie||d!==Fe})(),Zs=t.useRef(null);t.useEffect(()=>{m&&Zs.current!==Me&&(Zs.current=Me,m(Me))},[Me,m]),t.useEffect(()=>()=>{m?.(!1)},[m]),t.useEffect(()=>{const a={id:s.id,updatedAt:s.updatedAt},o=Ks.current;(!o||o.id!==a.id||o.updatedAt!==a.updatedAt)&&(Me||(Ks.current=a,ae(ht(s.runtimeConfig)),_(Ls(s.runtimeConfig)),x(Ds(s.runtimeConfig)),$(zs(s.runtimeConfig)),ke(Hs(s.runtimeConfig)),ve(Bs(s.runtimeConfig)),Ne(Is(s.runtimeConfig)),u(gt(s.runtimeConfig)),_e(Ie),z(Fe),Oe(Fe?"runtime":"model")))},[s,Me,Ie,Fe]);const Qs=(a,o)=>{Z(w=>({...w,[a]:o})),qe(!1),G[a]&&Ue(w=>{const Y={...w};return delete Y[a],Y})},ps=(a,o)=>{ae(w=>({...w,[a]:o})),qe(!1),G[a]&&Ue(w=>{const Y={...w};return delete Y[a],Y})},Dt=a=>{_(a),qe(!1)},vs=(a,o)=>{u(w=>({...w,[a]:o})),qe(!1),G[a]&&Ue(w=>{const Y={...w};return delete Y[a],Y})},$e=t.useMemo(()=>{const a=ln(D);for(const[K,le]of Object.entries({heartbeatIntervalMs:{label:"Heartbeat Interval",min:1},heartbeatTimeoutMs:{label:"Heartbeat Timeout",min:5},maxConcurrentRuns:{label:"Max Concurrent Runs",min:1}})){const Le=k[K]?.trim();if(!Le)continue;const Ge=Number(Le);Number.isNaN(Ge)||!Number.isFinite(Ge)?a[K]=`"${le.label}" must be a valid number`:Ge<le.min&&(a[K]=`"${le.label}" must be at least ${le.min.toLocaleString()}`)}const o=k.autoClaimCandidatesInPrompt?.trim();if(o){const K=Number(o);(!Number.isInteger(K)||K<0||K>10)&&(a.autoClaimCandidatesInPrompt='"Auto-claim candidates in prompt" must be an integer between 0 and 10')}const w=k.messageResponseMode?.trim();w&&!["immediate","on-heartbeat"].includes(w)&&(a.messageResponseMode='"Message Response Mode" must be either immediate or on-heartbeat');const Y=H.tokenBudget?.trim();if(Y){const K=Number(Y);Number.isNaN(K)||!Number.isFinite(K)?a.tokenBudget='"Token Budget" must be a valid number':K<=0&&(a.tokenBudget='"Token Budget" must be greater than 0')}const ge=H.usageThreshold?.trim();if(ge){const K=Number(ge);Number.isNaN(K)||!Number.isFinite(K)?a.usageThreshold='"Usage Threshold" must be a valid number':(K<1||K>100)&&(a.usageThreshold='"Usage Threshold" must be between 1 and 100')}const ee=H.budgetPeriod?.trim();ee&&!["daily","weekly","monthly","lifetime"].includes(ee)&&(a.budgetPeriod='"Budget Period" must be one of: daily, weekly, monthly, lifetime');const be=H.resetDay?.trim(),pe=ee||"lifetime";if(be){const K=Number(be);Number.isNaN(K)||!Number.isFinite(K)?a.resetDay='"Reset Day" must be a valid number':pe==="weekly"?(K<0||K>6||!Number.isInteger(K))&&(a.resetDay='"Reset Day" must be between 0 (Sunday) and 6 (Saturday) for weekly period'):pe==="monthly"&&(K<1||K>31||!Number.isInteger(K))&&(a.resetDay='"Reset Day" must be between 1 and 31 for monthly period')}return a},[D,k,H]),et=t.useCallback(()=>{if(Object.keys($e).length>0)return null;const a={...s.metadata};for(const le of ns){const Le=D[le.key]?.trim();Le?le.type==="number"?a[le.key]=Number(Le):a[le.key]=Le:delete a[le.key]}se.length>0?a.skills=se:delete a.skills;const o={...s.runtimeConfig};o.enabled=R,o.autoClaimRelevantTasks=h,o.runMissedHeartbeatOnStartup=r,o.allowParallelExecution=W,o.skipHeartbeatWhenIdle=ce;for(const le of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns","autoClaimCandidatesInPrompt"]){const Le=k[le]?.trim();if(!Le)delete o[le];else{const Ge=Number(Le);o[le]=le==="maxConcurrentRuns"||le==="autoClaimCandidatesInPrompt"?Ge:Ge*1e3}}const w=k.messageResponseMode?.trim();if(w?o.messageResponseMode=w:delete o.messageResponseMode,je?o.heartbeatScopeDiscipline=je:delete o.heartbeatScopeDiscipline,xe?o.heartbeatPromptTemplate=xe:delete o.heartbeatPromptTemplate,ie==="runtime")d.trim()?o.runtimeHint=d.trim():delete o.runtimeHint,delete o.modelProvider,delete o.modelId,delete o.model;else if(delete o.runtimeHint,ye.trim()){const le=ye.indexOf("/");le!==-1&&(o.modelProvider=ye.slice(0,le),o.modelId=ye.slice(le+1),o.model=ye.trim())}else delete o.modelProvider,delete o.modelId,delete o.model;const Y={},ge=H.tokenBudget?.trim(),ee=H.usageThreshold?.trim(),be=H.budgetPeriod?.trim(),pe=H.resetDay?.trim();ge&&(Y.tokenBudget=Number(ge)),ee&&(Y.usageThreshold=Number(ee)/100),be&&(Y.budgetPeriod=be),pe&&(Y.resetDay=Number(pe)),Object.keys(Y).length>0?o.budgetConfig=Y:delete o.budgetConfig;let K;return b&&(K={mode:b,entryFile:he||"AGENTS.md",files:oe.length>0?oe:["AGENTS.md"]},b==="external"&&Pe.trim()&&(K.externalPath=Pe.trim())),{name:f.trim()||void 0,role:N,title:c.trim()||void 0,icon:A.trim()||void 0,reportsTo:y.trim()||void 0,metadata:a,runtimeConfig:o,bundleConfig:K}},[s.metadata,s.runtimeConfig,W,h,H,he,Pe,oe,b,D,R,xe,je,k,A,ye,f,y,N,r,ie,d,se,ce,c,$e]),ts=t.useCallback(async(a,o)=>{const w=et();if(!w)return Ue($e),a&&i("Please fix validation errors before saving","error"),o==="auto"&&xs("Fix validation errors to save changes"),!1;const Y=JSON.stringify(w);if(Y===Xs.current)return!1;const ge=++bs.current;Ue({}),xs(null),Gs(!0);try{return await ot(s.id,w,n),ge!==bs.current?!1:(Xs.current=Y,o==="manual"&&i("Settings saved","success"),xs(null),qe(!0),ss.current&&clearTimeout(ss.current),ss.current=setTimeout(()=>qe(!1),3e3),await l(),!0)}catch(ee){if(ge===bs.current){const be=I(ee);xs(be),i(`Failed to save settings: ${be}`,"error")}return!1}finally{ge===bs.current&&Gs(!1)}},[i,s.id,et,l,n,$e]),zt=async()=>{await ts(!0,"manual")},de=t.useCallback(()=>{if(!(!Me||ze)){if(Object.keys($e).length>0){Ue($e);return}ts(!1,"auto")}},[Me,ze,ts,$e]);t.useEffect(()=>{if(!Me||ze)return;if(Object.keys($e).length>0){Ue($e);return}const a=setTimeout(()=>{ts(!1,"auto")},Ga);return()=>clearTimeout(a)},[Me,ze,ts,$e]);const Ht=t.useCallback(async a=>{T(!0);try{await va(s.id,a,n),await l(),i("Avatar uploaded","success")}catch(o){i(I(o),"error")}finally{T(!1),X.current&&(X.current.value="")}},[i,s.id,l,n]),Bt=t.useCallback(async()=>{T(!0);try{await ja(s.id,n),await l(),i("Avatar removed","success")}catch(a){i(I(a),"error")}finally{T(!1)}},[i,s.id,l,n]),st=ze?"Saving changes…":Fs?`Save failed: ${Fs}`:!Me&&Lt?"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:()=>O(!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=>M(a.target.value),onBlur:()=>{de()}})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-role",children:"Role"}),e.jsxs("select",{id:"agent-role",className:"select",value:N,onChange:a=>{L(a.target.value),de()},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:()=>{de()}})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{children:"Avatar"}),e.jsxs("div",{className:"agent-avatar-editor",children:[e.jsx(yt,{agent:s,size:64,className:"agent-avatar-editor-preview"}),e.jsxs("div",{className:"agent-avatar-editor-actions",children:[e.jsx("input",{ref:X,id:"agent-avatar-upload",type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",className:"visually-hidden",disabled:j,onChange:a=>{const o=a.target.files?.[0];o&&Ht(o)}}),e.jsx("button",{type:"button",className:"btn btn-sm",disabled:j,onClick:()=>X.current?.click(),children:"Upload Avatar"}),s.imageUrl?e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void Bt(),disabled:j,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:A,onChange:a=>E(a.target.value),onBlur:()=>{de()}})]}),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:y,onChange:a=>{Q(a.target.value),de()},disabled:v,children:[e.jsx("option",{value:"",children:"No manager"}),hs&&e.jsxs("option",{value:Se,children:["Unknown manager (",Se,")"]}),Te.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(Ta,{id:"agent-skills",label:"Skills",value:se,onChange:a=>{Xe(a),de()},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${ie==="model"?" active":""}`,role:"tab","aria-selected":ie==="model",tabIndex:ie==="model"?0:-1,onClick:()=>{Oe("model"),z(""),de()},children:"Built-in Model"}),e.jsx("button",{type:"button",className:`config-runtime-tab${ie==="runtime"?" active":""}`,role:"tab","aria-selected":ie==="runtime",tabIndex:ie==="runtime"?0:-1,onClick:()=>{Oe("runtime"),de()},children:"Plugin Runtime"})]})]}),ie==="model"?e.jsx("div",{className:"config-field",children:e.jsx(Na,{models:ds,value:ye,onChange:a=>{_e(a),de()},placeholder:"Use global default",label:"Agent Model",disabled:us,favoriteProviders:He,onToggleFavorite:We,favoriteModels:we,onToggleModelFavorite:Ms})}):e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-runtime-hint",children:"Runtime"}),es?e.jsx("span",{className:"config-hint",children:"Loading runtimes…"}):e.jsxs("select",{id:"agent-runtime-hint",className:"select",value:d,onChange:a=>{z(a.target.value),de()},children:[e.jsx("option",{value:"",children:Ze.length>0?"Select a plugin runtime…":"No plugin runtimes available"}),Ze.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:"Permissions"}),e.jsx("p",{className:"config-description",children:"Per-agent settings override project defaults. Each category controls a separate approval gate."}),V===void 0?e.jsxs("div",{className:"agent-permission-inherit-banner",children:[e.jsx("span",{children:"Inheriting project default — no per-agent override set"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void ue({presetId:"custom",rules:{git_write:te?.git_write??"allow",file_write_delete:te?.file_write_delete??"allow",command_execution:te?.command_execution??"allow",network_api:te?.network_api??"allow",task_agent_mutation:te?.task_agent_mutation??"allow"}}),children:"Customize for this agent"})]}):null,e.jsx(Ea,{mode:"agent-override",value:V,projectDefault:te,onChange:a=>{ue(a)}})]}),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 agent-heartbeat-auto-claim-card",children:[e.jsxs("div",{className:"agent-heartbeat-preset-row",children:[e.jsxs("div",{children:[e.jsx("label",{className:"agent-heartbeat-preset-label",children:"Coordination-only agent"}),e.jsx("span",{className:"config-hint",children:"Disables auto-claim and removes the candidate section from heartbeat prompts. Recommended for routing/CEO-style agents."})]}),e.jsx("button",{type:"button",className:"btn btn-sm agent-heartbeat-preset-btn",onClick:()=>{x(!1),ae(a=>({...a,autoClaimCandidatesInPrompt:"0"})),de()},children:"Apply preset"})]}),e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-autoClaimRelevantTasks",children:[e.jsx("input",{id:"hb-autoClaimRelevantTasks",type:"checkbox",checked:h,onChange:a=>{x(a.target.checked),de()}}),"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-enabled",children:[e.jsx("input",{id:"hb-enabled",type:"checkbox",checked:R,onChange:a=>{Dt(a.target.checked),de()}}),"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-runMissedHeartbeatOnStartup",children:[e.jsx("input",{id:"hb-runMissedHeartbeatOnStartup",type:"checkbox",checked:r,onChange:a=>{$(a.target.checked),de()}}),"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:W,onChange:a=>{ke(a.target.checked),de()}}),"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.jsxs("label",{className:"checkbox-label",htmlFor:"hb-skipHeartbeatWhenIdle",children:[e.jsx("input",{id:"hb-skipHeartbeatWhenIdle",type:"checkbox",checked:ce,onChange:a=>{ve(a.target.checked),de()}}),"Skip heartbeat when idle"]}),e.jsx("span",{className:"config-hint",children:"When enabled, scheduled (timer) heartbeats are skipped while this agent has no assigned task. The agent still wakes immediately when a task is assigned or you trigger a run manually. Default: off."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-heartbeatScopeDiscipline",children:"Heartbeat Scope Discipline"}),e.jsxs("select",{id:"hb-heartbeatScopeDiscipline",className:"select",value:je,onChange:a=>{const o=a.target.value;Ne(o==="strict"||o==="lite"||o==="off"?o:""),de()},children:[e.jsx("option",{value:"",children:"Inherit project default"}),e.jsx("option",{value:"strict",children:"Strict"}),e.jsx("option",{value:"lite",children:"Lite"}),e.jsx("option",{value:"off",children:"Off"})]}),e.jsx("span",{className:"config-hint",children:"Strict — coordination-focused; higher per-tick tokens. Lite — pre-2026-05-11 behavior. Off — minimal procedure."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-heartbeatPromptTemplate",children:"Heartbeat Prompt Template"}),e.jsxs("select",{id:"hb-heartbeatPromptTemplate",className:"select",value:xe,onChange:a=>{const o=a.target.value;U(o==="default"||o==="compact"?o:""),de()},children:[e.jsx("option",{value:"",children:"Inherit project default"}),e.jsx("option",{value:"default",children:"Default"}),e.jsx("option",{value:"compact",children:"Compact"})]})]}),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:re("input",!!G.heartbeatIntervalMs&&"input--error"),placeholder:String(_s/1e3),value:k.heartbeatIntervalMs??"",onChange:a=>ps("heartbeatIntervalMs",a.target.value)}),G.heartbeatIntervalMs?e.jsx("span",{className:"config-error",children:G.heartbeatIntervalMs}):e.jsxs("span",{className:"config-hint",children:["How often heartbeats are checked. Leave empty for system default (",_s/1e3,"s / ",qa,")."]})]}),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:re("input",!!G.heartbeatTimeoutMs&&"input--error"),placeholder:"60",value:k.heartbeatTimeoutMs??"",onChange:a=>ps("heartbeatTimeoutMs",a.target.value)}),G.heartbeatTimeoutMs?e.jsx("span",{className:"config-error",children:G.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:re("input",!!G.maxConcurrentRuns&&"input--error"),placeholder:"1",value:k.maxConcurrentRuns??"",onChange:a=>ps("maxConcurrentRuns",a.target.value)}),G.maxConcurrentRuns?e.jsx("span",{className:"config-error",children:G.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:re("select",!!G.messageResponseMode&&"input--error"),value:k.messageResponseMode??"",onChange:a=>ps("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"})]}),G.messageResponseMode?e.jsx("span",{className:"config-error",children:G.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:re("input",!!G.tokenBudget&&"input--error"),placeholder:"No limit",value:H.tokenBudget??"",onChange:a=>vs("tokenBudget",a.target.value)}),G.tokenBudget?e.jsx("span",{className:"config-error",children:G.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:re("input",!!G.usageThreshold&&"input--error"),placeholder:"80",value:H.usageThreshold??"",onChange:a=>vs("usageThreshold",a.target.value)}),G.usageThreshold?e.jsx("span",{className:"config-error",children:G.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:re("select",!!G.budgetPeriod&&"input--error"),value:H.budgetPeriod??"",onChange:a=>vs("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"})]}),G.budgetPeriod?e.jsx("span",{className:"config-error",children:G.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:re("input",!!G.resetDay&&"input--error"),placeholder:"Auto",value:H.resetDay??"",onChange:a=>vs("resetDay",a.target.value)}),G.resetDay?e.jsx("span",{className:"config-error",children:G.resetDay}):e.jsx("span",{className:"config-hint",children:H.budgetPeriod==="weekly"?"Day of week (0=Sunday to 6=Saturday) for reset.":H.budgetPeriod==="monthly"?"Day of month (1-31) for reset.":"Day for reset (weekly: 0-6, monthly: 1-31). Leave empty for automatic."})]}),De?.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:re("budget-progress-bar__fill",(De.usagePercent??0)>=100?"budget-progress-bar__fill--red":(De.usagePercent??0)>=80?"budget-progress-bar__fill--amber":"budget-progress-bar__fill--green"),style:{width:`${Math.min(De.usagePercent??0,100)}%`}})}),e.jsxs("span",{className:"budget-progress-label",children:[(De.currentUsage??0).toLocaleString()," / ",(De.budgetLimit??0).toLocaleString()," tokens (",Math.round(De.usagePercent??0),"% used)"]})]})]}),De?.budgetLimit!=null&&e.jsx("div",{className:"config-field",children:e.jsx("button",{className:"btn btn-reset-budget",onClick:()=>void $t(),disabled:Ws,children:Ws?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:14,className:"animate-spin"}),"Resetting…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Rs,{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:b,onChange:a=>ne(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:[b==="managed"&&"Files will be stored in a system-managed directory within .fusion/agents/",b==="external"&&"Specify an external directory path for the instruction files",!b&&"Select a mode to enable instruction bundling"]})]}),b&&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:he,onChange:a=>Ve(a.target.value)}),e.jsx("span",{className:"config-hint",children:"Primary instructions file name (default: AGENTS.md)"})]}),b==="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:Pe,onChange:a=>Ae(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:oe.join(", "),onChange:a=>Ee(a.target.value.split(",").map(o=>o.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:ns.map(a=>{const o=!!G[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:re("select",o&&"input--error"),value:D[a.key]??"",onChange:w=>Qs(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:re("input",o&&"input--error"),placeholder:a.placeholder,value:D[a.key]??"",onChange:w=>Qs(a.key,w.target.value)}),o&&e.jsx("span",{className:"config-error",children:G[a.key]}),!o&&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:!Me||ze,onClick:()=>void zt(),children:ze?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(me,{size:16}),"Save Settings"]})}),st&&e.jsxs("span",{className:re("config-saved-indicator",Fs&&"config-saved-indicator--error"),children:[ze?e.jsx(q,{size:14,className:"animate-spin"}):e.jsx(me,{size:14}),st]})]})]}),e.jsx(dn,{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:!Ys||!g,onClick:()=>void g?.(),children:[e.jsx(Ss,{size:16}),"Delete Agent"]}),e.jsx("span",{className:"config-danger-note",children:Ys?"Deletion is permanent and cannot be undone.":`Agent deletion is only available when state is idle or paused (current state: ${s.state}).`})]})})]}),e.jsx($a,{isOpen:F,onClose:()=>O(!1),onUseDraft:gs,projectId:n,existingAgents:J,mode:"edit",existingAgentConfig:fs})]})}function mn({agentId:s,projectId:n,onChildClick:i}){const[l,m]=t.useState([]),[g,P]=t.useState(!0);return t.useEffect(()=>{P(!0),fa(s,n).then(m).finally(()=>P(!1))},[s,n]),g?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(q,{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(Ct,{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 M=Js[f.state];return e.jsxs("div",{className:"agent-tree__node agent-is-child",onClick:()=>i?.(f.id),role:"button",tabIndex:0,onKeyDown:N=>{(N.key==="Enter"||N.key===" ")&&(N.key===" "&&N.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:M?.bg??"var(--state-idle-bg)",color:M?.text??"var(--state-idle-text)",border:`1px solid ${M?.border??"var(--state-idle-border)"}`},children:f.state})]},f.id)})})})]})}export{vn as AgentDetailView,Ke as relativeTime};
18
+ ... (truncated, ${S.stdoutExcerpt.length} chars total)`:S.stdoutExcerpt})]}),S.stderrExcerpt&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label run-output-label--error",children:"Errors"}),e.jsx(ka,{errorText:S.stderrExcerpt,summaryPrefix:"Run error",issueContext:{surface:"AgentDetailView runs",agentId:n,agentName:m,agentState:l,runId:S.id,taskId:void 0,timestamp:S.startedAt}})]}),S.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(S.resultJson,null,2)})]}),S.contextSnapshot&&Object.keys(S.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(S.contextSnapshot).map(([oe,Ee])=>e.jsxs("span",{className:"run-context-item",children:[e.jsxs("span",{className:"text-muted",children:[oe,":"]})," ",e.jsx("span",{children:String(Ee)})]},oe))})]}),!S.stdoutExcerpt&&!S.stderrExcerpt&&!S.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"}),p?e.jsxs("div",{className:"run-details-loading-state",children:[e.jsx(q,{size:14,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading logs..."})]}):X.length===0?e.jsx("div",{className:"text-muted run-output-empty",children:"No logs available for this run"}):e.jsx(Ft,{entries:X,loading:!1})]})]})]},u.id)},je=(u,b)=>e.jsxs("div",{className:"run-context-item",children:[e.jsxs("span",{className:"text-muted",children:[u,":"]})," ",e.jsxs("span",{children:[(b.hitRatio*100).toFixed(1),"% (",b.totalCachedTokens.toLocaleString()," / ",b.totalCacheWriteTokens.toLocaleString()," / ",b.totalInputTokens.toLocaleString()," / ",b.nTasks.toLocaleString(),")"]})]},u),Ne=D[0],xe=[...D].reverse(),U=Math.max(1,...xe.map(u=>u.execChars)),H=xe.map((u,b)=>{const ne=xe.length<=1?0:b/(xe.length-1)*100,he=100-Math.round(u.execChars/U*100);return`${ne},${he}`}).join(" ");return e.jsxs("div",{className:"runs-tab",children:[D.length>0&&Ne&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:"Prompt Size"}),e.jsxs("div",{className:"prompt-size-summary",children:[e.jsxs("svg",{className:"prompt-size-sparkline",viewBox:"0 0 100 100",role:"img","aria-label":"Execution prompt size over last 7 runs",children:[e.jsx("polyline",{className:"prompt-size-sparkline-grid",points:"0,100 100,100"}),e.jsx("polyline",{className:"prompt-size-sparkline-line",points:H})]}),e.jsxs("span",{className:"prompt-size-values",children:[Ne.systemChars.toLocaleString()," / ",Ne.execChars.toLocaleString()," / ",Ne.totalChars.toLocaleString()]})]})]}),O&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:"Cache hit ratio"}),e.jsxs("div",{className:"run-context-grid",children:[je("Last 24h",O.last24h),je("Last 7d",O.last7d),je("All time",O.allTime)]})]}),e.jsxs("div",{className:"runs-toolbar runs-toolbar--between",children:[e.jsxs("span",{className:"runs-toolbar-meta",children:[N.length," run",N.length!==1?"s":"",_&&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:_&&e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void r(),"aria-label":`Stop active run for ${m??n}`,children:[e.jsx(Ke,{size:14})," Stop Run"]})})]}),W.map((u,b)=>ve(u,b,!0)),ke.map((u,b)=>ve(u,W.length+b,!1))]})}function sn(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 tn={triage:"Triage",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"};function an(s){const n=s.title?.trim()||s.description?.trim()||s.id;return n.length>80?`${n.slice(0,77)}...`:n}function nn({agentId:s,projectId:n,addToast:i}){const[l,m]=t.useState([]),[g,P]=t.useState(!0);return t.useEffect(()=>{let f=!1;return P(!0),ha(s,n).then(M=>{f||m(M)}).catch(M=>{f||(m([]),i(`Failed to load assigned tasks: ${I(M)}`,"error"))}).finally(()=>{f||P(!1)}),()=>{f=!0}},[s,n,i]),g?e.jsxs("div",{className:"agent-tasks-empty",children:[e.jsx(q,{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(kt,{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:tn[f.column]})]}),e.jsx("div",{className:"agent-task-title",title:f.title||f.description||f.id,children:an(f)}),e.jsxs("div",{className:"agent-task-status",children:[f.status??"idle"," · Updated ",Ye(f.updatedAt)]})]},f.id))})}const ns=[{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 ln(s){const n={};for(const i of ns){const l=s[i.key]?.trim();if(l){if(i.type==="number"){const m=Number(l);if(Number.isNaN(m)||!Number.isFinite(m)){n[i.key]=`"${i.label}" must be a valid number`;continue}i.min!==void 0&&m<i.min&&(n[i.key]=`"${i.label}" must be at least ${i.min.toLocaleString()}`),i.max!==void 0&&m>i.max&&(n[i.key]=`"${i.label}" must be at most ${i.max.toLocaleString()}`)}if(i.type==="select"){const m=i.options?.map(g=>g.value)??[];m.length>0&&!m.includes(l)&&(n[i.key]=`"${i.label}" must be one of: ${m.join(", ")}`)}}}return n}function rn({agent:s,projectId:n,addToast:i,onSaved:l}){const[m,g]=t.useState(s.soul??""),[P,f]=t.useState(!1),[M,N]=t.useState(!1),[L,c]=t.useState(!1),C=t.useRef(null);t.useEffect(()=>{g(s.soul??""),N(!1),c(!1)},[s.id,s.soul]),t.useEffect(()=>()=>{C.current&&clearTimeout(C.current)},[]);const A=m!==(s.soul??""),E=async()=>{if(m.length>1e4){i("Soul must be at most 10,000 characters","error");return}f(!0);try{await Ca(s.id,m,n),i("Soul saved","success"),N(!0),C.current&&clearTimeout(C.current),C.current=setTimeout(()=>N(!1),3e3),await l()}catch(y){i(`Failed to save soul: ${I(y)}`,"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 ${L?"":"btn-primary"}`,onClick:()=>c(!1),disabled:!L,"aria-label":"Edit mode",children:[e.jsx(ls,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${L?"btn-primary":""}`,onClick:()=>c(!0),disabled:L,"aria-label":"Preview mode",children:[e.jsx(rs,{size:14}),"Preview"]})]})}),L?m.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(os,{remarkPlugins:[cs],children:m})}):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:m,onChange:y=>{g(y.target.value),N(!1)}}),!L&&e.jsx("span",{className:"config-hint",children:"Defines the agent's character and identity. Max 10,000 characters."})]})}),!L&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!A||P,onClick:()=>void E(),children:P?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(me,{size:16}),"Save Soul"]})}),!A&&M&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(me,{size:14}),"Soul saved"]})]})]})})}function on({agent:s,projectId:n,addToast:i,onSaved:l}){const[m,g]=t.useState(s.memory??""),[P,f]=t.useState(!1),[M,N]=t.useState(!1),[L,c]=t.useState(!1),[C,A]=t.useState(!1),[E,y]=t.useState([]),[X,J]=t.useState(!1),[p,v]=t.useState(""),[S,j]=t.useState(""),[T,F]=t.useState(!1),[O,Q]=t.useState(!1),[D,Z]=t.useState(!1),[k,ae]=t.useState(!1),[R,_]=t.useState(""),h=t.useRef(null),x=t.useRef(null),r=s.state==="running",$=m!==(s.memory??""),W=t.useMemo(()=>E.find(U=>U.path===p),[E,p]),ke=W?Wa[W.layer]:"Select a memory file to view or edit.",ce=t.useCallback(async U=>{Q(!0);try{const H=await ga(s.id,U,n);v(H.path),j(H.content),F(!1),ae(!1)}catch(H){i(`Failed to load agent memory file: ${I(H)}`,"error")}finally{Q(!1)}},[s.id,n,i]),ve=t.useCallback(async(U="")=>{J(!0);try{const{files:H}=await xa(s.id,n);if(y(H),H.length===0){v(""),j(""),F(!1);return}const u=Ka(H,U);await ce(u)}catch(H){i(`Failed to load memory files: ${I(H)}`,"error"),y([]),v(""),j(""),F(!1)}finally{J(!1)}},[s.id,n,i,ce]);t.useEffect(()=>{g(s.memory??""),N(!1),c(!1),A(!1),_(""),ae(!1),ve()},[s.id,s.memory,ve]),t.useEffect(()=>()=>{h.current&&clearTimeout(h.current),x.current&&clearTimeout(x.current)},[]);const je=async()=>{if(m.length>5e4){i("Memory must be at most 50,000 characters","error");return}f(!0);try{await Ra(s.id,m,n),i("Memory saved","success"),N(!0),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>N(!1),3e3),await l()}catch(U){i(`Failed to save memory: ${I(U)}`,"error")}finally{f(!1)}},Ne=async U=>{if(!(!U||U===p)){if(T){_("Save the current file before switching to another file.");return}_(""),await ce(U)}},xe=async()=>{if(p){Z(!0);try{await Ma(s.id,p,S,n),F(!1),ae(!0),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>ae(!1),3e3),_(""),await ve(p),i("Agent memory file saved","success"),await l()}catch(U){i(`Failed to save agent memory file: ${I(U)}`,"error")}finally{Z(!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 ${L?"":"btn-primary"}`,onClick:()=>c(!1),disabled:!L,"aria-label":"Edit mode",children:[e.jsx(ls,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${L?"btn-primary":""}`,onClick:()=>c(!0),disabled:L,"aria-label":"Preview mode",children:[e.jsx(rs,{size:14}),"Preview"]})]})}),L?m.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(os,{remarkPlugins:[cs],children:m})}):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:m,readOnly:r,onChange:U=>{g(U.target.value),N(!1)}}),!L&&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:X||O||D||E.length===0,onChange:U=>{Ne(U.target.value)},children:E.length===0?e.jsx("option",{value:"",children:"No memory files found"}):E.map(U=>e.jsxs("option",{value:U.path,children:[mt[U.layer]," • ",U.label]},U.path))}),X&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(q,{size:14,className:"animate-spin"}),"Loading memory files…"]}),W&&e.jsxs("div",{className:"config-hint config-hint--top-spacing",children:[e.jsx("strong",{children:mt[W.layer]})," · ",ke,e.jsx("br",{}),W.size.toLocaleString()," bytes · Updated ",Ye(W.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:()=>A(!1),disabled:!C,"aria-label":"Memory file edit mode",children:[e.jsx(ls,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${C?"btn-primary":""}`,onClick:()=>A(!0),disabled:C,"aria-label":"Memory file preview mode",children:[e.jsx(rs,{size:14}),"Preview"]})]})}),C?S.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(os,{remarkPlugins:[cs],children:S})}):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:S,readOnly:r||!p||O,onChange:U=>{j(U.target.value),F(!0),ae(!1),_("")}}),O&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(q,{size:14,className:"animate-spin"}),"Loading file content…"]}),R&&e.jsx("span",{className:"config-hint config-hint--top-spacing config-hint--block",children:R})]})]}),e.jsxs("div",{className:"config-actions",children:[!L&&e.jsx("button",{className:"btn btn-task-create",disabled:!$||P||r,onClick:()=>void je(),children:P?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(me,{size:16}),"Save Memory"]})}),!C&&e.jsx("button",{className:"btn",disabled:!T||D||!p||r,onClick:()=>void xe(),children:D?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),"Saving file…"]}):e.jsxs(e.Fragment,{children:[e.jsx(me,{size:16}),"Save Memory File"]})}),!$&&M&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(me,{size:14}),"Memory saved"]}),!T&&k&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(me,{size:14}),"Memory file saved"]})]})]})})}function cn({agent:s,projectId:n,addToast:i,onSaved:l}){const[m,g]=t.useState(s.instructionsText??""),[P,f]=t.useState(s.instructionsPath??""),[M,N]=t.useState(!1),[L,c]=t.useState(""),[C,A]=t.useState(!1),[E,y]=t.useState(!1),[X,J]=t.useState(!1),[p,v]=t.useState(!1),[S,j]=t.useState(!1),[T,F]=t.useState(!1),O=t.useRef(null),Q=t.useRef(null);t.useEffect(()=>{const R=P.trim();if(!R){c(""),y(!1);return}A(!0),Pt("project",R).then(_=>{c(_.content),y(!1)}).catch(_=>{const h=I(_);h.includes("ENOENT")||h.includes("Not found")||h.includes("not found")?(c(""),y(!1)):(i(`Failed to load instructions file: ${h}`,"error"),c(""))}).finally(()=>{A(!1)})},[P,i]),t.useEffect(()=>{g(s.instructionsText??""),f(s.instructionsPath??""),j(!1),F(!1),N(!1)},[s.id,s.instructionsText,s.instructionsPath]),t.useEffect(()=>()=>{O.current&&clearTimeout(O.current),Q.current&&clearTimeout(Q.current)},[]);const D=(()=>{const R=m??"",_=s.instructionsText??"",h=P?.trim()??"",x=s.instructionsPath?.trim()??"";return R!==_||h!==x})(),Z=async()=>{J(!0);try{await wa(s.id,{instructionsText:m||void 0,instructionsPath:P.trim()||void 0},n),i("Instructions saved","success"),j(!0),O.current&&clearTimeout(O.current),O.current=setTimeout(()=>j(!1),3e3),await l()}catch(R){i(`Failed to save instructions: ${I(R)}`,"error")}finally{J(!1)}},k=async()=>{const R=P.trim();if(!R){i("No instructions file path set","error");return}v(!0);try{await Et("project",R,L),i("Instructions file saved","success"),y(!1),F(!0),Q.current&&clearTimeout(Q.current),Q.current=setTimeout(()=>F(!1),3e3),await l()}catch(_){i(`Failed to save instructions file: ${I(_)}`,"error")}finally{v(!1)}},ae=!!P.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 ${M?"":"btn-primary"}`,onClick:()=>N(!1),disabled:!M,"aria-label":"Edit mode","data-testid":"instructions-edit-toggle",children:[e.jsx(ls,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${M?"btn-primary":""}`,onClick:()=>N(!0),disabled:M,"aria-label":"Preview mode","data-testid":"instructions-preview-toggle",children:[e.jsx(rs,{size:14}),"Preview"]})]})}),M?m.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(os,{remarkPlugins:[cs],children:m})}):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:m,onChange:R=>{g(R.target.value),j(!1)}}),!M&&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:P,onChange:R=>{f(R.target.value),j(!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."})]})]}),!M&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!D||X,onClick:()=>void Z(),children:X?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(me,{size:16}),"Save Instructions"]})}),!D&&S&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(me,{size:14}),"Instructions saved"]})]})]}),ae&&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(q,{size:12,className:"animate-spin"}),"Loading..."]}),E&&!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:L,readOnly:C,onChange:R=>{c(R.target.value),y(!0),F(!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:!E||p,onClick:()=>void k(),children:p?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(me,{size:16}),"Save File"]})}),!E&&T&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(me,{size:14}),"File saved"]})]})]})]})}function ht(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),n.autoClaimCandidatesInPrompt!==void 0&&n.autoClaimCandidatesInPrompt!==null&&(i.autoClaimCandidatesInPrompt=String(n.autoClaimCandidatesInPrompt)),i}function Ls(s){return s?.enabled!==!1}function Ds(s){return s?.autoClaimRelevantTasks!==!1}function zs(s){return s?.runMissedHeartbeatOnStartup===!0}function Hs(s){return s?.allowParallelExecution!==!1}function Bs(s){return s?.skipHeartbeatWhenIdle===!0}function Is(s){const n=s?.heartbeatScopeDiscipline;return n==="strict"||n==="lite"||n==="off"?n:""}function ft(s){const n=s?.heartbeatPromptTemplate;return n==="default"||n==="compact"?n:""}function gt(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 dn({agent:s,projectId:n,addToast:i,onSaved:l}){const[m,g]=t.useState(!1),[P,f]=t.useState(!1),[M,N]=t.useState(!1),[L,c]=t.useState(!1),[C,A]=t.useState(!1),[E,y]=t.useState(""),[X,J]=t.useState(!1),[p,v]=t.useState(null),[S,j]=t.useState(!1),T=t.useRef(null),F=s.heartbeatProcedurePath?.trim(),O=`.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`,Q=`.fusion/agents/${s.id}/HEARTBEAT.md`,D=s.id.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"agent",Z=!!(F&&(F===O||F===Q||new RegExp(`^\\.fusion/agents/[^/]+-${D}/HEARTBEAT\\.md$`).test(F))),k=!!F,ae=t.useCallback(async x=>{N(!0),v(null);try{const r=await Pt("project",x,n);y(r.content),J(!1)}catch(r){const $=I(r);v($),i(`Failed to load heartbeat procedure file: ${$}`,"error")}finally{N(!1)}},[i,n]);t.useEffect(()=>{f(!1),A(!1),y(""),J(!1),v(null),N(!1),c(!1),j(!1)},[s.id,F]),t.useEffect(()=>()=>{T.current&&clearTimeout(T.current)},[]);const R=async()=>{F&&(f(!0),await ae(F))},_=async()=>{if(F){c(!0);try{await Et("project",F,E,n),J(!1),j(!0),i("Heartbeat procedure file saved","success"),T.current&&clearTimeout(T.current),T.current=setTimeout(()=>j(!1),3e3),await l()}catch(x){i(`Failed to save heartbeat procedure file: ${I(x)}`,"error")}finally{c(!1)}}},h=async()=>{g(!0);try{const x=await Pa(s.id,n);i(x.procedureFileSeeded?`Heartbeat procedure file ready at ${x.heartbeatProcedurePath}`:`Heartbeat procedure path set to ${x.heartbeatProcedurePath}`,"success"),await l()}catch(x){i(`Failed to upgrade heartbeat procedure: ${I(x)}`,"error")}finally{g(!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:F||"(none — using built-in default)"})]}),k&&e.jsx("div",{className:"heartbeat-procedure-actions",children:e.jsx("button",{className:"btn btn-sm",onClick:()=>void R(),disabled:M,children:M?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),"Loading file…"]}):e.jsxs(e.Fragment,{children:[e.jsx(is,{size:16}),"View Heartbeat Markdown"]})})})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("button",{className:"btn",disabled:m||Z,onClick:()=>void h(),"aria-label":"Upgrade agent to default heartbeat procedure file",children:m?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),"Upgrading…"]}):Z?e.jsxs(e.Fragment,{children:[e.jsx(me,{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:O})," ","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."]})]})]}),P&&k&&F&&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:()=>A(!1),disabled:!C,"aria-label":"Heartbeat file edit mode",children:[e.jsx(ls,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${C?"btn-primary":""}`,onClick:()=>A(!0),disabled:C,"aria-label":"Heartbeat file preview mode",children:[e.jsx(rs,{size:14}),"Preview"]})]}),M&&e.jsxs("span",{className:"config-hint heartbeat-procedure-status",children:[e.jsx(q,{size:12,className:"animate-spin"}),"Loading..."]}),X&&!M&&e.jsx("span",{className:"config-hint heartbeat-procedure-status heartbeat-procedure-status--warning",children:"Unsaved changes"})]}),C?E.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(os,{remarkPlugins:[cs],children:E})}):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:E,readOnly:M,placeholder:"Heartbeat procedure markdown file content will appear here...",onChange:x=>{y(x.target.value),J(!0),j(!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:F}),"."]})]}),!C&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!X||L||M,onClick:()=>void _(),children:L?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(me,{size:16}),"Save Heartbeat File"]})}),!X&&S&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(me,{size:14}),"File saved"]})]})]})]})}function un({agent:s,projectId:n,addToast:i,onSaved:l,onHasChangesChange:m,onDelete:g,onAgentDraftApplied:P}){const[f,M]=t.useState(s.name),[N,L]=t.useState(s.role),[c,C]=t.useState(s.title??""),[A,E]=t.useState(s.icon??""),[y,X]=t.useState(s.reportsTo??""),[J,p]=t.useState([]),[v,S]=t.useState(!1),[j,T]=t.useState(!1),[F,O]=t.useState(!1),Q=t.useRef(null),[D,Z]=t.useState(()=>{const a={};for(const o of ns){const w=s.metadata[o.key];w!=null&&(a[o.key]=String(w))}return a}),[k,ae]=t.useState(()=>ht(s.runtimeConfig)),[R,_]=t.useState(()=>Ls(s.runtimeConfig)),[h,x]=t.useState(()=>Ds(s.runtimeConfig)),[r,$]=t.useState(()=>zs(s.runtimeConfig)),[W,ke]=t.useState(()=>Hs(s.runtimeConfig)),[ce,ve]=t.useState(()=>Bs(s.runtimeConfig)),[je,Ne]=t.useState(()=>Is(s.runtimeConfig)),[xe,U]=t.useState(()=>ft(s.runtimeConfig)),[H,u]=t.useState(()=>gt(s.runtimeConfig)),[b,ne]=t.useState(s.bundleConfig?.mode??""),[he,Ve]=t.useState(s.bundleConfig?.entryFile??"AGENTS.md"),[Pe,Ae]=t.useState(s.bundleConfig?.externalPath??""),[oe,Ee]=t.useState(s.bundleConfig?.files??[]),[se,Qe]=t.useState(Array.isArray(s.metadata?.skills)?s.metadata.skills:[]),[ds,Ce]=t.useState([]),[us,Je]=t.useState(!1),[He,Be]=t.useState([]),[we,Re]=t.useState([]),[Ze,Xe]=t.useState([]),[es,ms]=t.useState(!1),Ie=(()=>{const a=s.runtimeConfig??{};return a.modelProvider&&a.modelId?`${a.modelProvider}/${a.modelId}`:typeof a.model=="string"&&a.model.includes("/")?a.model:""})(),Fe=typeof s.runtimeConfig?.runtimeHint=="string"?s.runtimeConfig.runtimeHint:"",[ie,Oe]=t.useState(Fe?"runtime":"model"),[ye,_e]=t.useState(Ie),[d,z]=t.useState(Fe),[V,B]=t.useState(s.permissionPolicy),[te,fe]=t.useState(void 0),Se=y.trim(),Te=t.useMemo(()=>J.filter(a=>a.id!==s.id),[J,s.id]),hs=!!Se&&!Te.some(a=>a.id===Se),fs=t.useMemo(()=>({name:f,role:N,title:c||void 0,instructionsText:s.instructionsText,soul:s.soul,memory:s.memory,reportsTo:y||void 0,skills:se,model:ye||void 0,runtimeHint:ie==="runtime"&&d||void 0,thinkingLevel:D.thinkingLevel??void 0,maxTurns:D.maxTurns?Number(D.maxTurns):void 0,heartbeatIntervalMs:k.heartbeatIntervalMs?Number(k.heartbeatIntervalMs)*1e3:void 0,heartbeatTimeoutMs:k.heartbeatTimeoutMs?Number(k.heartbeatTimeoutMs)*1e3:void 0,maxConcurrentRuns:k.maxConcurrentRuns?Number(k.maxConcurrentRuns):void 0,messageResponseMode:k.messageResponseMode}),[s.instructionsText,s.memory,s.soul,D.maxTurns,D.thinkingLevel,k.heartbeatIntervalMs,k.heartbeatTimeoutMs,k.maxConcurrentRuns,k.messageResponseMode,ye,f,y,N,ie,d,se,c]),gs=t.useCallback(a=>{M(a.name),L(a.role),C(a.title??""),E(a.icon??""),X(a.reportsTo??""),a.skills&&Qe(a.skills),a.thinkingLevel&&Z(w=>({...w,thinkingLevel:a.thinkingLevel})),a.maxTurns!==void 0&&Z(w=>({...w,maxTurns:String(a.maxTurns)})),a.runtimeHint!==void 0?(Oe("runtime"),z(a.runtimeHint??""),a.runtimeHint&&_e("")):a.model!==void 0&&(Oe("model"),_e(a.model??""),z(""));const o=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));P?.(o),O(!1),i("Interview draft applied. Review and save when ready.","success")},[i,P]);t.useEffect(()=>{B(s.permissionPolicy)},[s.permissionPolicy]),t.useEffect(()=>{ba(n).then(a=>fe(a.project?.defaultAgentPermissionPolicy?.rules)).catch(()=>fe(void 0))},[n]);const ue=async a=>{B(a);try{await ot(s.id,{permissionPolicy:a},n),await l(),i("Permission policy updated","success")}catch(o){i(`Failed to update permission policy: ${I(o)}`,"error")}};t.useEffect(()=>{let a=!1;return S(!0),ks(void 0,n).then(o=>{a||p(o)}).catch(()=>{a||p([])}).finally(()=>{a||S(!1)}),()=>{a=!0}},[n]),t.useEffect(()=>{Je(!0),pa().then(a=>{Ce(a.models),Be(a.favoriteProviders),Re(a.favoriteModels)}).catch(()=>{}).finally(()=>Je(!1))},[]);const We=t.useCallback(async a=>{const o=He,K=o.includes(a)?o.filter(ge=>ge!==a):[a,...o];Be(K);try{await rt({favoriteProviders:K,favoriteModels:we})}catch{Be(o)}},[He,we]),Ms=t.useCallback(async a=>{const o=we,K=o.includes(a)?o.filter(ge=>ge!==a):[a,...o];Re(K);try{await rt({favoriteProviders:He,favoriteModels:K})}catch{Re(o)}},[He,we]);t.useEffect(()=>{ms(!0),Rt(n).then(Xe).catch(()=>Xe([])).finally(()=>ms(!1))},[n]);const[De,As]=t.useState(null),[Ws,qs]=t.useState(!1);t.useEffect(()=>{Os(s.id,n).then(As).catch(()=>As(null))},[s.id,n]);const $t=async()=>{qs(!0);try{await Aa(s.id,n),i("Budget usage reset successfully","success");const a=await Os(s.id,n);As(a)}catch(a){i(`Failed to reset budget: ${I(a)}`,"error")}finally{qs(!1)}},[ze,Gs]=t.useState(!1),[G,Ue]=t.useState({}),[Lt,qe]=t.useState(!1),[Fs,xs]=t.useState(null),Ks=s.state==="idle"||s.state==="paused",ss=t.useRef(null),Ys=t.useRef(null),Qs=t.useRef(null),bs=t.useRef(0);t.useEffect(()=>()=>{ss.current&&clearTimeout(ss.current)},[]);const Me=(()=>{if(f!==s.name||N!==s.role||c!==(s.title??"")||A!==(s.icon??"")||y!==(s.reportsTo??"")||b!==(s.bundleConfig?.mode??"")||he!==(s.bundleConfig?.entryFile??"AGENTS.md")||Pe!==(s.bundleConfig?.externalPath??"")||JSON.stringify(oe)!==JSON.stringify(s.bundleConfig?.files??[]))return!0;for(const ee of ns){const be=D[ee.key]?.trim()??"",pe=s.metadata[ee.key]!==void 0&&s.metadata[ee.key]!==null?String(s.metadata[ee.key]):"";if(be!==pe)return!0}const a=s.runtimeConfig??{};if(R!==Ls(s.runtimeConfig)||h!==Ds(s.runtimeConfig)||r!==zs(s.runtimeConfig)||W!==Hs(s.runtimeConfig)||ce!==Bs(s.runtimeConfig)||je!==Is(s.runtimeConfig)||xe!==ft(s.runtimeConfig))return!0;for(const ee of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns","messageResponseMode","autoClaimCandidatesInPrompt"]){const be=k[ee]?.trim()??"";let pe=a[ee]!==void 0&&a[ee]!==null?String(a[ee]):"";if((ee==="heartbeatIntervalMs"||ee==="heartbeatTimeoutMs")&&pe&&(pe=String(Number(pe)/1e3)),be!==pe)return!0}const o=a.budgetConfig;for(const ee of["tokenBudget","budgetPeriod","resetDay"]){const be=H[ee]?.trim()??"",pe=o?.[ee]!==void 0&&o?.[ee]!==null?String(o[ee]):"";if(be!==pe)return!0}const w=H.usageThreshold?.trim()??"",K=o?.usageThreshold!==void 0&&o?.usageThreshold!==null?String(Number(o.usageThreshold)*100):"";if(w!==K)return!0;const ge=Array.isArray(s.metadata?.skills)?s.metadata.skills:[];return JSON.stringify(se)!==JSON.stringify(ge)||ie!==(Fe?"runtime":"model")||ye!==Ie||d!==Fe})(),Zs=t.useRef(null);t.useEffect(()=>{m&&Zs.current!==Me&&(Zs.current=Me,m(Me))},[Me,m]),t.useEffect(()=>()=>{m?.(!1)},[m]),t.useEffect(()=>{const a={id:s.id,updatedAt:s.updatedAt},o=Ys.current;(!o||o.id!==a.id||o.updatedAt!==a.updatedAt)&&(Me||(Ys.current=a,ae(ht(s.runtimeConfig)),_(Ls(s.runtimeConfig)),x(Ds(s.runtimeConfig)),$(zs(s.runtimeConfig)),ke(Hs(s.runtimeConfig)),ve(Bs(s.runtimeConfig)),Ne(Is(s.runtimeConfig)),u(gt(s.runtimeConfig)),_e(Ie),z(Fe),Oe(Fe?"runtime":"model")))},[s,Me,Ie,Fe]);const Xs=(a,o)=>{Z(w=>({...w,[a]:o})),qe(!1),G[a]&&Ue(w=>{const K={...w};return delete K[a],K})},ps=(a,o)=>{ae(w=>({...w,[a]:o})),qe(!1),G[a]&&Ue(w=>{const K={...w};return delete K[a],K})},Dt=a=>{_(a),qe(!1)},vs=(a,o)=>{u(w=>({...w,[a]:o})),qe(!1),G[a]&&Ue(w=>{const K={...w};return delete K[a],K})},$e=t.useMemo(()=>{const a=ln(D);for(const[Y,le]of Object.entries({heartbeatIntervalMs:{label:"Heartbeat Interval",min:1},heartbeatTimeoutMs:{label:"Heartbeat Timeout",min:5},maxConcurrentRuns:{label:"Max Concurrent Runs",min:1}})){const Le=k[Y]?.trim();if(!Le)continue;const Ge=Number(Le);Number.isNaN(Ge)||!Number.isFinite(Ge)?a[Y]=`"${le.label}" must be a valid number`:Ge<le.min&&(a[Y]=`"${le.label}" must be at least ${le.min.toLocaleString()}`)}const o=k.autoClaimCandidatesInPrompt?.trim();if(o){const Y=Number(o);(!Number.isInteger(Y)||Y<0||Y>10)&&(a.autoClaimCandidatesInPrompt='"Auto-claim candidates in prompt" must be an integer between 0 and 10')}const w=k.messageResponseMode?.trim();w&&!["immediate","on-heartbeat"].includes(w)&&(a.messageResponseMode='"Message Response Mode" must be either immediate or on-heartbeat');const K=H.tokenBudget?.trim();if(K){const Y=Number(K);Number.isNaN(Y)||!Number.isFinite(Y)?a.tokenBudget='"Token Budget" must be a valid number':Y<=0&&(a.tokenBudget='"Token Budget" must be greater than 0')}const ge=H.usageThreshold?.trim();if(ge){const Y=Number(ge);Number.isNaN(Y)||!Number.isFinite(Y)?a.usageThreshold='"Usage Threshold" must be a valid number':(Y<1||Y>100)&&(a.usageThreshold='"Usage Threshold" must be between 1 and 100')}const ee=H.budgetPeriod?.trim();ee&&!["daily","weekly","monthly","lifetime"].includes(ee)&&(a.budgetPeriod='"Budget Period" must be one of: daily, weekly, monthly, lifetime');const be=H.resetDay?.trim(),pe=ee||"lifetime";if(be){const Y=Number(be);Number.isNaN(Y)||!Number.isFinite(Y)?a.resetDay='"Reset Day" must be a valid number':pe==="weekly"?(Y<0||Y>6||!Number.isInteger(Y))&&(a.resetDay='"Reset Day" must be between 0 (Sunday) and 6 (Saturday) for weekly period'):pe==="monthly"&&(Y<1||Y>31||!Number.isInteger(Y))&&(a.resetDay='"Reset Day" must be between 1 and 31 for monthly period')}return a},[D,k,H]),et=t.useCallback(()=>{if(Object.keys($e).length>0)return null;const a={...s.metadata};for(const le of ns){const Le=D[le.key]?.trim();Le?le.type==="number"?a[le.key]=Number(Le):a[le.key]=Le:delete a[le.key]}se.length>0?a.skills=se:delete a.skills;const o={...s.runtimeConfig};o.enabled=R,o.autoClaimRelevantTasks=h,o.runMissedHeartbeatOnStartup=r,o.allowParallelExecution=W,o.skipHeartbeatWhenIdle=ce;for(const le of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns","autoClaimCandidatesInPrompt"]){const Le=k[le]?.trim();if(!Le)delete o[le];else{const Ge=Number(Le);o[le]=le==="maxConcurrentRuns"||le==="autoClaimCandidatesInPrompt"?Ge:Ge*1e3}}const w=k.messageResponseMode?.trim();if(w?o.messageResponseMode=w:delete o.messageResponseMode,je?o.heartbeatScopeDiscipline=je:delete o.heartbeatScopeDiscipline,xe?o.heartbeatPromptTemplate=xe:delete o.heartbeatPromptTemplate,ie==="runtime")d.trim()?o.runtimeHint=d.trim():delete o.runtimeHint,delete o.modelProvider,delete o.modelId,delete o.model;else if(delete o.runtimeHint,ye.trim()){const le=ye.indexOf("/");le!==-1&&(o.modelProvider=ye.slice(0,le),o.modelId=ye.slice(le+1),o.model=ye.trim())}else delete o.modelProvider,delete o.modelId,delete o.model;const K={},ge=H.tokenBudget?.trim(),ee=H.usageThreshold?.trim(),be=H.budgetPeriod?.trim(),pe=H.resetDay?.trim();ge&&(K.tokenBudget=Number(ge)),ee&&(K.usageThreshold=Number(ee)/100),be&&(K.budgetPeriod=be),pe&&(K.resetDay=Number(pe)),Object.keys(K).length>0?o.budgetConfig=K:delete o.budgetConfig;let Y;return b&&(Y={mode:b,entryFile:he||"AGENTS.md",files:oe.length>0?oe:["AGENTS.md"]},b==="external"&&Pe.trim()&&(Y.externalPath=Pe.trim())),{name:f.trim()||void 0,role:N,title:c.trim()||void 0,icon:A.trim()||void 0,reportsTo:y.trim()||void 0,metadata:a,runtimeConfig:o,bundleConfig:Y}},[s.metadata,s.runtimeConfig,W,h,H,he,Pe,oe,b,D,R,xe,je,k,A,ye,f,y,N,r,ie,d,se,ce,c,$e]),ts=t.useCallback(async(a,o)=>{const w=et();if(!w)return Ue($e),a&&i("Please fix validation errors before saving","error"),o==="auto"&&xs("Fix validation errors to save changes"),!1;const K=JSON.stringify(w);if(K===Qs.current)return!1;const ge=++bs.current;Ue({}),xs(null),Gs(!0);try{return await ot(s.id,w,n),ge!==bs.current?!1:(Qs.current=K,o==="manual"&&i("Settings saved","success"),xs(null),qe(!0),ss.current&&clearTimeout(ss.current),ss.current=setTimeout(()=>qe(!1),3e3),await l(),!0)}catch(ee){if(ge===bs.current){const be=I(ee);xs(be),i(`Failed to save settings: ${be}`,"error")}return!1}finally{ge===bs.current&&Gs(!1)}},[i,s.id,et,l,n,$e]),zt=async()=>{await ts(!0,"manual")},de=t.useCallback(()=>{if(!(!Me||ze)){if(Object.keys($e).length>0){Ue($e);return}ts(!1,"auto")}},[Me,ze,ts,$e]);t.useEffect(()=>{if(!Me||ze)return;if(Object.keys($e).length>0){Ue($e);return}const a=setTimeout(()=>{ts(!1,"auto")},Ga);return()=>clearTimeout(a)},[Me,ze,ts,$e]);const Ht=t.useCallback(async a=>{T(!0);try{await va(s.id,a,n),await l(),i("Avatar uploaded","success")}catch(o){i(I(o),"error")}finally{T(!1),Q.current&&(Q.current.value="")}},[i,s.id,l,n]),Bt=t.useCallback(async()=>{T(!0);try{await ja(s.id,n),await l(),i("Avatar removed","success")}catch(a){i(I(a),"error")}finally{T(!1)}},[i,s.id,l,n]),st=ze?"Saving changes…":Fs?`Save failed: ${Fs}`:!Me&&Lt?"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:()=>O(!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=>M(a.target.value),onBlur:()=>{de()}})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-role",children:"Role"}),e.jsxs("select",{id:"agent-role",className:"select",value:N,onChange:a=>{L(a.target.value),de()},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:()=>{de()}})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{children:"Avatar"}),e.jsxs("div",{className:"agent-avatar-editor",children:[e.jsx(yt,{agent:s,size:64,className:"agent-avatar-editor-preview"}),e.jsxs("div",{className:"agent-avatar-editor-actions",children:[e.jsx("input",{ref:Q,id:"agent-avatar-upload",type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",className:"visually-hidden",disabled:j,onChange:a=>{const o=a.target.files?.[0];o&&Ht(o)}}),e.jsx("button",{type:"button",className:"btn btn-sm",disabled:j,onClick:()=>Q.current?.click(),children:"Upload Avatar"}),s.imageUrl?e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void Bt(),disabled:j,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:A,onChange:a=>E(a.target.value),onBlur:()=>{de()}})]}),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:y,onChange:a=>{X(a.target.value),de()},disabled:v,children:[e.jsx("option",{value:"",children:"No manager"}),hs&&e.jsxs("option",{value:Se,children:["Unknown manager (",Se,")"]}),Te.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(Ta,{id:"agent-skills",label:"Skills",value:se,onChange:a=>{Qe(a),de()},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${ie==="model"?" active":""}`,role:"tab","aria-selected":ie==="model",tabIndex:ie==="model"?0:-1,onClick:()=>{Oe("model"),z(""),de()},children:"Built-in Model"}),e.jsx("button",{type:"button",className:`config-runtime-tab${ie==="runtime"?" active":""}`,role:"tab","aria-selected":ie==="runtime",tabIndex:ie==="runtime"?0:-1,onClick:()=>{Oe("runtime"),de()},children:"Plugin Runtime"})]})]}),ie==="model"?e.jsx("div",{className:"config-field",children:e.jsx(Na,{models:ds,value:ye,onChange:a=>{_e(a),de()},placeholder:"Use global default",label:"Agent Model",disabled:us,favoriteProviders:He,onToggleFavorite:We,favoriteModels:we,onToggleModelFavorite:Ms})}):e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-runtime-hint",children:"Runtime"}),es?e.jsx("span",{className:"config-hint",children:"Loading runtimes…"}):e.jsxs("select",{id:"agent-runtime-hint",className:"select",value:d,onChange:a=>{z(a.target.value),de()},children:[e.jsx("option",{value:"",children:Ze.length>0?"Select a plugin runtime…":"No plugin runtimes available"}),Ze.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:"Permissions"}),e.jsx("p",{className:"config-description",children:"Per-agent settings override project defaults. Each category controls a separate approval gate."}),V===void 0?e.jsxs("div",{className:"agent-permission-inherit-banner",children:[e.jsx("span",{children:"Inheriting project default — no per-agent override set"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void ue({presetId:"custom",rules:{git_write:te?.git_write??"allow",file_write_delete:te?.file_write_delete??"allow",command_execution:te?.command_execution??"allow",network_api:te?.network_api??"allow",task_agent_mutation:te?.task_agent_mutation??"allow"}}),children:"Customize for this agent"})]}):null,e.jsx(Ea,{mode:"agent-override",value:V,projectDefault:te,onChange:a=>{ue(a)}})]}),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 agent-heartbeat-auto-claim-card",children:[e.jsxs("div",{className:"agent-heartbeat-preset-row",children:[e.jsxs("div",{children:[e.jsx("label",{className:"agent-heartbeat-preset-label",children:"Coordination-only agent"}),e.jsx("span",{className:"config-hint",children:"Disables auto-claim and removes the candidate section from heartbeat prompts. Recommended for routing/CEO-style agents."})]}),e.jsx("button",{type:"button",className:"btn btn-sm agent-heartbeat-preset-btn",onClick:()=>{x(!1),ae(a=>({...a,autoClaimCandidatesInPrompt:"0"})),de()},children:"Apply preset"})]}),e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-autoClaimRelevantTasks",children:[e.jsx("input",{id:"hb-autoClaimRelevantTasks",type:"checkbox",checked:h,onChange:a=>{x(a.target.checked),de()}}),"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-enabled",children:[e.jsx("input",{id:"hb-enabled",type:"checkbox",checked:R,onChange:a=>{Dt(a.target.checked),de()}}),"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-runMissedHeartbeatOnStartup",children:[e.jsx("input",{id:"hb-runMissedHeartbeatOnStartup",type:"checkbox",checked:r,onChange:a=>{$(a.target.checked),de()}}),"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:W,onChange:a=>{ke(a.target.checked),de()}}),"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.jsxs("label",{className:"checkbox-label",htmlFor:"hb-skipHeartbeatWhenIdle",children:[e.jsx("input",{id:"hb-skipHeartbeatWhenIdle",type:"checkbox",checked:ce,onChange:a=>{ve(a.target.checked),de()}}),"Skip heartbeat when idle"]}),e.jsx("span",{className:"config-hint",children:"When enabled, scheduled (timer) heartbeats are skipped while this agent has no assigned task. The agent still wakes immediately when a task is assigned or you trigger a run manually. Default: off."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-heartbeatScopeDiscipline",children:"Heartbeat Scope Discipline"}),e.jsxs("select",{id:"hb-heartbeatScopeDiscipline",className:"select",value:je,onChange:a=>{const o=a.target.value;Ne(o==="strict"||o==="lite"||o==="off"?o:""),de()},children:[e.jsx("option",{value:"",children:"Inherit project default"}),e.jsx("option",{value:"strict",children:"Strict"}),e.jsx("option",{value:"lite",children:"Lite"}),e.jsx("option",{value:"off",children:"Off"})]}),e.jsx("span",{className:"config-hint",children:"Strict — coordination-focused; higher per-tick tokens. Lite — pre-2026-05-11 behavior. Off — minimal procedure."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-heartbeatPromptTemplate",children:"Heartbeat Prompt Template"}),e.jsxs("select",{id:"hb-heartbeatPromptTemplate",className:"select",value:xe,onChange:a=>{const o=a.target.value;U(o==="default"||o==="compact"?o:""),de()},children:[e.jsx("option",{value:"",children:"Inherit project default"}),e.jsx("option",{value:"default",children:"Default"}),e.jsx("option",{value:"compact",children:"Compact"})]})]}),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:re("input",!!G.heartbeatIntervalMs&&"input--error"),placeholder:String(_s/1e3),value:k.heartbeatIntervalMs??"",onChange:a=>ps("heartbeatIntervalMs",a.target.value)}),G.heartbeatIntervalMs?e.jsx("span",{className:"config-error",children:G.heartbeatIntervalMs}):e.jsxs("span",{className:"config-hint",children:["How often heartbeats are checked. Leave empty for system default (",_s/1e3,"s / ",qa,")."]})]}),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:re("input",!!G.heartbeatTimeoutMs&&"input--error"),placeholder:"60",value:k.heartbeatTimeoutMs??"",onChange:a=>ps("heartbeatTimeoutMs",a.target.value)}),G.heartbeatTimeoutMs?e.jsx("span",{className:"config-error",children:G.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:re("input",!!G.maxConcurrentRuns&&"input--error"),placeholder:"1",value:k.maxConcurrentRuns??"",onChange:a=>ps("maxConcurrentRuns",a.target.value)}),G.maxConcurrentRuns?e.jsx("span",{className:"config-error",children:G.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:re("select",!!G.messageResponseMode&&"input--error"),value:k.messageResponseMode??"",onChange:a=>ps("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"})]}),G.messageResponseMode?e.jsx("span",{className:"config-error",children:G.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:re("input",!!G.tokenBudget&&"input--error"),placeholder:"No limit",value:H.tokenBudget??"",onChange:a=>vs("tokenBudget",a.target.value)}),G.tokenBudget?e.jsx("span",{className:"config-error",children:G.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:re("input",!!G.usageThreshold&&"input--error"),placeholder:"80",value:H.usageThreshold??"",onChange:a=>vs("usageThreshold",a.target.value)}),G.usageThreshold?e.jsx("span",{className:"config-error",children:G.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:re("select",!!G.budgetPeriod&&"input--error"),value:H.budgetPeriod??"",onChange:a=>vs("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"})]}),G.budgetPeriod?e.jsx("span",{className:"config-error",children:G.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:re("input",!!G.resetDay&&"input--error"),placeholder:"Auto",value:H.resetDay??"",onChange:a=>vs("resetDay",a.target.value)}),G.resetDay?e.jsx("span",{className:"config-error",children:G.resetDay}):e.jsx("span",{className:"config-hint",children:H.budgetPeriod==="weekly"?"Day of week (0=Sunday to 6=Saturday) for reset.":H.budgetPeriod==="monthly"?"Day of month (1-31) for reset.":"Day for reset (weekly: 0-6, monthly: 1-31). Leave empty for automatic."})]}),De?.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:re("budget-progress-bar__fill",(De.usagePercent??0)>=100?"budget-progress-bar__fill--red":(De.usagePercent??0)>=80?"budget-progress-bar__fill--amber":"budget-progress-bar__fill--green"),style:{width:`${Math.min(De.usagePercent??0,100)}%`}})}),e.jsxs("span",{className:"budget-progress-label",children:[(De.currentUsage??0).toLocaleString()," / ",(De.budgetLimit??0).toLocaleString()," tokens (",Math.round(De.usagePercent??0),"% used)"]})]})]}),De?.budgetLimit!=null&&e.jsx("div",{className:"config-field",children:e.jsx("button",{className:"btn btn-reset-budget",onClick:()=>void $t(),disabled:Ws,children:Ws?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:14,className:"animate-spin"}),"Resetting…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Rs,{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:b,onChange:a=>ne(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:[b==="managed"&&"Files will be stored in a system-managed directory within .fusion/agents/",b==="external"&&"Specify an external directory path for the instruction files",!b&&"Select a mode to enable instruction bundling"]})]}),b&&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:he,onChange:a=>Ve(a.target.value)}),e.jsx("span",{className:"config-hint",children:"Primary instructions file name (default: AGENTS.md)"})]}),b==="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:Pe,onChange:a=>Ae(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:oe.join(", "),onChange:a=>Ee(a.target.value.split(",").map(o=>o.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:ns.map(a=>{const o=!!G[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:re("select",o&&"input--error"),value:D[a.key]??"",onChange:w=>Xs(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:re("input",o&&"input--error"),placeholder:a.placeholder,value:D[a.key]??"",onChange:w=>Xs(a.key,w.target.value)}),o&&e.jsx("span",{className:"config-error",children:G[a.key]}),!o&&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:!Me||ze,onClick:()=>void zt(),children:ze?e.jsxs(e.Fragment,{children:[e.jsx(q,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(me,{size:16}),"Save Settings"]})}),st&&e.jsxs("span",{className:re("config-saved-indicator",Fs&&"config-saved-indicator--error"),children:[ze?e.jsx(q,{size:14,className:"animate-spin"}):e.jsx(me,{size:14}),st]})]})]}),e.jsx(dn,{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:!Ks||!g,onClick:()=>void g?.(),children:[e.jsx(Ss,{size:16}),"Delete Agent"]}),e.jsx("span",{className:"config-danger-note",children:Ks?"Deletion is permanent and cannot be undone.":`Agent deletion is only available when state is idle or paused (current state: ${s.state}).`})]})})]}),e.jsx($a,{isOpen:F,onClose:()=>O(!1),onUseDraft:gs,projectId:n,existingAgents:J,mode:"edit",existingAgentConfig:fs})]})}function mn({agentId:s,projectId:n,onChildClick:i}){const[l,m]=t.useState([]),[g,P]=t.useState(!0);return t.useEffect(()=>{P(!0),fa(s,n).then(m).finally(()=>P(!1))},[s,n]),g?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(q,{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(Ct,{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 M=Js[f.state];return e.jsxs("div",{className:"agent-tree__node agent-is-child",onClick:()=>i?.(f.id),role:"button",tabIndex:0,onKeyDown:N=>{(N.key==="Enter"||N.key===" ")&&(N.key===" "&&N.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:M?.bg??"var(--state-idle-bg)",color:M?.text??"var(--state-idle-text)",border:`1px solid ${M?.border??"var(--state-idle-border)"}`},children:f.state})]},f.id)})})})]})}export{vn as AgentDetailView,Ye as relativeTime};