@runfusion/fusion 0.41.0 → 0.42.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 (83) hide show
  1. package/dist/bin.js +44240 -41922
  2. package/dist/client/.vite/manifest.json +72 -72
  3. package/dist/client/assets/AgentDetailView-C5Lb3fd3.js +18 -0
  4. package/dist/client/assets/AgentDetailView-DiWELtb1.css +1 -0
  5. package/dist/client/assets/{AgentPermissionPolicyEditor-VDXL4XQc.js → AgentPermissionPolicyEditor-DtRcvE6M.js} +2 -2
  6. package/dist/client/assets/{AgentsView-ChXccELt.js → AgentsView-BVW-NOYD.js} +3 -3
  7. package/dist/client/assets/ChatView-Dy-oIkrK.js +6 -0
  8. package/dist/client/assets/{DevServerView-DGOahw1o.js → DevServerView-DLsFSP4s.js} +1 -1
  9. package/dist/client/assets/{DirectoryPicker-DgqHlxyh.js → DirectoryPicker-_QawX-uL.js} +1 -1
  10. package/dist/client/assets/{DocumentsView-CbbZwzbH.js → DocumentsView-DierUJsj.js} +1 -1
  11. package/dist/client/assets/{EvalsView-BL_ue7fJ.js → EvalsView-B83lYKQl.js} +1 -1
  12. package/dist/client/assets/{ExperimentalAgentOnboardingModal-8H4XAu4O.js → ExperimentalAgentOnboardingModal-CTctYTPU.js} +1 -1
  13. package/dist/client/assets/{GoalsView-CO4FVL3E.js → GoalsView-CKn8i0i0.js} +1 -1
  14. package/dist/client/assets/{InsightsView-C5vLvWVE.js → InsightsView-EpRHCD8G.js} +1 -1
  15. package/dist/client/assets/{MemoryView-BL3W3yOv.js → MemoryView-Df_ocTc5.js} +2 -2
  16. package/dist/client/assets/NodesView-DF7xJ_3z.js +14 -0
  17. package/dist/client/assets/{PiExtensionsManager-HvSiVeDN.js → PiExtensionsManager-BOooOEDx.js} +2 -2
  18. package/dist/client/assets/{PluginManager-DIjrlhnU.js → PluginManager-CHrDAzK6.js} +1 -1
  19. package/dist/client/assets/{PullRequestView-C2jQX8xZ.js → PullRequestView-CJU21OZ6.js} +2 -2
  20. package/dist/client/assets/{ReliabilityView-DbqEwoRs.js → ReliabilityView-uHkW1Qeu.js} +1 -1
  21. package/dist/client/assets/{ResearchView-C1QghmLI.js → ResearchView-oZ2-vbjL.js} +1 -1
  22. package/dist/client/assets/{SecretsView-Y2MQ-9n5.js → SecretsView-BpkqSV_E.js} +1 -1
  23. package/dist/client/assets/SessionTerminal-D9IW4cDj.js +2 -0
  24. package/dist/client/assets/{SettingsModal-DabcZZ6S.js → SettingsModal-BmB5l2bA.js} +1 -1
  25. package/dist/client/assets/SettingsModal-C8gsAazm.js +31 -0
  26. package/dist/client/assets/{SetupWizardModal-Db-Rxinm.js → SetupWizardModal-BYLEU_7o.js} +1 -1
  27. package/dist/client/assets/{SkillsView-CIEY1-DE.js → SkillsView-8GgQ8Z_Z.js} +1 -1
  28. package/dist/client/assets/{StashRecoveryView-B6iDu5tI.js → StashRecoveryView-CT1t1Uf2.js} +1 -1
  29. package/dist/client/assets/{TodoView-B8IK_BPM.js → TodoView-BUj6ITAb.js} +2 -2
  30. package/dist/client/assets/WorkflowNodeEditor-CN7GPmvV.js +8 -0
  31. package/dist/client/assets/WorkflowNodeEditor-aPj8cv81.css +1 -0
  32. package/dist/client/assets/app-B2ZxMfJT.js +13 -0
  33. package/dist/client/assets/app-BffGU_HQ.js +13 -0
  34. package/dist/client/assets/app-C8AHhs5N.js +13 -0
  35. package/dist/client/assets/app-DCot4oXA.js +13 -0
  36. package/dist/client/assets/app-Ri9Te2Dv.js +13 -0
  37. package/dist/client/assets/app-sEkTyT-w.js +13 -0
  38. package/dist/client/assets/{dashboard-view-O5j3PSGY.js → dashboard-view-C3SsjXo1.js} +1621 -1621
  39. package/dist/client/assets/{dashboard-view-Dn4CztR6.js → dashboard-view-CrYwb0oQ.js} +1 -1
  40. package/dist/client/assets/dashboard-view-Du53JbmQ.css +1 -0
  41. package/dist/client/assets/{folder-open-C9XAaduE.js → folder-open-CREXTATY.js} +1 -1
  42. package/dist/client/assets/index-2kYpdJrx.js +793 -0
  43. package/dist/client/assets/index-CJUfvGdC.css +1 -0
  44. package/dist/client/assets/{upload-BRAEugYV.js → upload-BvLUlwaH.js} +1 -1
  45. package/dist/client/assets/{users-BlflbMZ3.js → users-CjhbU-sF.js} +1 -1
  46. package/dist/client/index.html +2 -2
  47. package/dist/client/version.json +1 -1
  48. package/dist/droid-cli/package.json +1 -1
  49. package/dist/extension.js +43622 -41519
  50. package/dist/pi-claude-cli/package.json +1 -1
  51. package/dist/plugins/fusion-plugin-acp-runtime/package.json +1 -1
  52. package/dist/plugins/fusion-plugin-cli-printing-press/package.json +1 -1
  53. package/dist/plugins/fusion-plugin-compound-engineering/bundled.js +59 -8
  54. package/dist/plugins/fusion-plugin-compound-engineering/package.json +1 -1
  55. package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
  56. package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
  57. package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
  58. package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
  59. package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
  60. package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
  61. package/dist/plugins/fusion-plugin-reports/package.json +1 -1
  62. package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
  63. package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
  64. package/package.json +2 -1
  65. package/skill/fusion/references/extension-tools.md +3 -3
  66. package/skill/fusion/references/fusion-capabilities.md +2 -2
  67. package/dist/client/assets/AgentDetailView-CY-O6VkV.css +0 -1
  68. package/dist/client/assets/AgentDetailView-krC0B2O0.js +0 -18
  69. package/dist/client/assets/ChatView-Dz_xBKit.js +0 -6
  70. package/dist/client/assets/NodesView-DfBNNm9c.js +0 -14
  71. package/dist/client/assets/SessionTerminal-DaTXNT3A.js +0 -2
  72. package/dist/client/assets/SettingsModal-BAzm2kYd.js +0 -31
  73. package/dist/client/assets/WorkflowNodeEditor-DaPyvD_R.js +0 -8
  74. package/dist/client/assets/WorkflowNodeEditor-Po5uv_dN.css +0 -1
  75. package/dist/client/assets/app-CTRT_hQh.js +0 -13
  76. package/dist/client/assets/app-CVg6W-HU.js +0 -13
  77. package/dist/client/assets/app-CY3pQXOr.js +0 -13
  78. package/dist/client/assets/app-DNh04p5I.js +0 -13
  79. package/dist/client/assets/app-DhHgtB9j.js +0 -13
  80. package/dist/client/assets/app-NL_hPGDS.js +0 -13
  81. package/dist/client/assets/dashboard-view-BgiLoG1G.css +0 -1
  82. package/dist/client/assets/index-BHGM5W8a.css +0 -1
  83. package/dist/client/assets/index-CgfrecpF.js +0 -793
@@ -1,18 +0,0 @@
1
- import{r as a,j as e}from"./vendor-react-D37HfzIf.js";import{c as Wt,fn as Is,fo as Bs,fp as $s,fq as Os,L as G,R as Ft,az as ss,Z as _s,aA as Et,el as hs,U as lt,a as fs,b as bs,fr as Us,fs as Vs,ft as Ws,v as ps,dS as Js,fu as qs,z as U,fv as Gs,fw as xs,fx as vs,fy as Ks,j as wt,D as Lt,s as kt,bK as js,k as ys,Q as Dt,A as Rt,O as as,b1 as Ke,fz as Ys,X as Ns,F as ot,fA as Zs,cD as Ss,ez as ks,fB as Qs,ax as Xs,bJ as ea,aB as Cs,B as Jt,a1 as ta,$ as ns,a6 as sa,a2 as aa,fC as Ut,l as ws,fD as na,bX as ia,r as ra,ay as Rs,a5 as Ms,cI as la,C as ge,fE as Fs,fF as is,bN as rs,fG as oa,fH as ca,fI as da,fJ as ua,fK as ct,af as dt,ah as ut,ai as mt,ad as As,fL as ma,fM as ga,h as ha,dV as fa,i as ba,a3 as ls,fN as pa,fO as xa,m as va,fP as Vt,fQ as ja,fR as ya,W as Na,fS as Sa,fT as ka,fU as Ps,fV as Ca,fW as wa,fX as Ra,fY as Ma,fZ as Fa}from"./index-CgfrecpF.js";import{u as ke}from"./vendor-i18n-CV0mwX_-.js";import{f as zt,S as Aa,E as Pa}from"./ExperimentalAgentOnboardingModal-8H4XAu4O.js";import{B as Ta,A as Ea}from"./AgentPermissionPolicyEditor-VDXL4XQc.js";import"./vendor-reactflow-CRZcPCXF.js";import"./vendor-xterm-tcedd2Jt.js";import"./vendor-codemirror-jBKmHyH0.js";/**
2
- * @license lucide-react v1.7.0 - ISC
3
- *
4
- * This source code is licensed under the ISC license.
5
- * See the LICENSE file in the root directory of this source tree.
6
- */const La=[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M18 17V9",key:"2bz60n"}],["path",{d:"M13 17V5",key:"1frdt8"}],["path",{d:"M8 17v-3",key:"17ska0"}]],Ct=Wt("chart-column",La);/**
7
- * @license lucide-react v1.7.0 - ISC
8
- *
9
- * This source code is licensed under the ISC license.
10
- * See the LICENSE file in the root directory of this source tree.
11
- */const Da=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M17 12h-2l-2 5-2-10-2 5H7",key:"15hlnc"}]],za=Wt("square-activity",Da);/**
12
- * @license lucide-react v1.7.0 - ISC
13
- *
14
- * This source code is licensed under the ISC license.
15
- * See the LICENSE file in the root directory of this source tree.
16
- */const Ha=[["path",{d:"M16 17h6v-6",key:"t6n2it"}],["path",{d:"m22 17-8.5-8.5-5 5L2 7",key:"x473p"}]],Ia=Wt("trending-down",Ha);function os(t){return t<1e3?`${t}ms`:t<6e4?`${(t/1e3).toFixed(1)}s`:t<36e5?`${Math.floor(t/6e4)}m`:`${(t/36e5).toFixed(1)}h`}function Ba(t){return`${Math.round(t*100)}%`}function cs(t,i){const l=Date.now(),o=new Date(t).getTime(),s=l-o;if(s<0){const h=Math.abs(s);return h<6e4?i("agents.time.inAMoment","in a moment"):h<36e5?i("agents.time.inMinutes","in {{count}}m",{count:Math.floor(h/6e4)}):h<864e5?i("agents.time.inHours","in {{count}}h",{count:Math.floor(h/36e5)}):i("agents.time.inDays","in {{count}}d",{count:Math.floor(h/864e5)})}return s<6e4?i("agents.time.justNow","just now"):s<36e5?i("agents.time.minutesAgo","{{count}}m ago",{count:Math.floor(s/6e4)}):s<864e5?i("agents.time.hoursAgo","{{count}}h ago",{count:Math.floor(s/36e5)}):i("agents.time.daysAgo","{{count}}d ago",{count:Math.floor(s/864e5)})}function $a(t,i){switch(t){case"periodic":return i("agents.reflections.triggerPeriodic","Periodic");case"post-task":return i("agents.reflections.triggerPostTask","Post-Task");case"manual":return i("agents.reflections.triggerManual","Manual");case"user-requested":return i("agents.reflections.triggerUserRequested","User Requested");default:return t}}function it(t){return t instanceof Error&&t.message?t.message:String(t)}function Oa(t,i){switch(t){case"improving":return i("agents.ratings.trendImproving","↑ Improving");case"declining":return i("agents.ratings.trendDeclining","↓ Declining");case"stable":return i("agents.ratings.trendStable","→ Stable");default:return i("agents.ratings.trendInsufficient","Insufficient data")}}function _a(t){switch(t){case"improving":return"trend-improving";case"declining":return"trend-declining";case"stable":return"trend-stable";default:return"trend-insufficient"}}function ds(t,i=5){return e.jsx("span",{className:"rating-stars",children:Array.from({length:i},(l,o)=>e.jsx(hs,{size:14,className:o<t?"star-filled":"star-empty",fill:o<t?"currentColor":"none"},o))})}function Ua({agentId:t,projectId:i,addToast:l}){const{t:o}=ke("app"),[s,h]=a.useState([]),[N,n]=a.useState(null),[g,u]=a.useState(null),[j,c]=a.useState([]),[m,M]=a.useState(!0),[P,L]=a.useState(!0),[w,X]=a.useState(!1),[q,S]=a.useState(!1),[k,R]=a.useState(null),[C,D]=a.useState(0),[T,V]=a.useState(""),[Z,I]=a.useState(""),Q=a.useCallback(async()=>{try{const[d,z]=await Promise.all([Is(t,20,i),Bs(t,void 0,i)]);h(d),n(z)}catch(d){l(o("agents.reflections.loadError","Failed to load reflections: {{error}}",{error:it(d)}),"error")}finally{M(!1)}},[t,i,l]),F=a.useCallback(async()=>{try{const[d,z]=await Promise.all([$s(t,i),Os(t,{limit:50},i)]);u(d),c(z)}catch(d){l(o("agents.ratings.loadError","Failed to load ratings: {{error}}",{error:it(d)}),"error")}finally{L(!1)}},[t,i,l]);a.useEffect(()=>{Q(),F()},[Q,F]);const ae=async()=>{X(!0);try{if(!await Us(t,i)){l(o("agents.reflections.insufficientHistory","Not enough history to generate a reflection yet"),"error");return}l(o("agents.reflections.generateSuccess","Reflection generated successfully"),"success"),M(!0),await Q()}catch(d){const z=it(d),$=z.toLowerCase();$.includes("agent not found")||$.includes("not found")?l(o("agents.reflections.agentNotFound","This agent is no longer available. It may have been deleted."),"error"):$.includes("insufficient history")?l(o("agents.reflections.insufficientHistory","Not enough history to generate a reflection yet"),"error"):l(o("agents.reflections.generateError","Failed to generate reflection: {{error}}",{error:z}),"error")}finally{X(!1)}},A=async d=>{if(d.preventDefault(),C!==0){S(!0);try{await Vs(t,{score:C,category:T||void 0,comment:Z||void 0,raterType:"user"},i),D(0),V(""),I(""),l(o("agents.ratings.addSuccess","Rating added"),"success"),await F()}catch(z){l(o("agents.ratings.addError","Failed to add rating: {{error}}",{error:it(z)}),"error")}finally{S(!1)}}},W=async d=>{try{await Ws(t,d,i),l(o("agents.ratings.deleteSuccess","Rating deleted"),"success"),await F()}catch(z){l(o("agents.ratings.deleteError","Failed to delete rating: {{error}}",{error:it(z)}),"error")}},x=d=>{R(z=>z===d?null:d)};if(m&&P)return e.jsx("div",{className:"reflections-tab",children:e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(G,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:o("agents.reflections.loadingEvaluation","Loading evaluation...")})]})});const v=N&&N.totalTasksCompleted===0&&N.totalTasksFailed===0&&N.recentReflectionCount===0;return e.jsxs("div",{className:"reflections-tab",children:[e.jsxs("div",{className:"reflections-header",children:[e.jsxs("h3",{children:[e.jsx(Ct,{size:16}),o("agents.reflections.sectionTitle","Performance, Reflections & Ratings")]}),e.jsx("button",{className:"btn btn-secondary",onClick:ae,disabled:w,title:o("agents.reflections.reflectNowTitle","Generate a manual reflection"),children:w?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:14,className:"animate-spin"}),o("agents.reflections.reflecting","Reflecting...")]}):e.jsxs(e.Fragment,{children:[e.jsx(Ft,{size:14}),o("agents.reflections.reflectNow","Reflect Now")]})})]}),N&&!v&&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(ss,{size:16,style:{color:"var(--color-success)"}}),N.totalTasksCompleted]}),e.jsx("div",{className:"stat-label",children:o("agents.performance.tasksCompleted","Tasks Completed")})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(Ia,{size:16,style:{color:"var(--color-error)"}}),N.totalTasksFailed]}),e.jsx("div",{className:"stat-label",children:o("agents.performance.tasksFailed","Tasks Failed")})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(_s,{size:16,style:{color:"var(--in-progress)"}}),os(N.avgDurationMs)]}),e.jsx("div",{className:"stat-label",children:o("agents.performance.avgDuration","Avg Duration")})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(Ct,{size:16,style:{color:N.successRate>=.8?"var(--color-success)":N.successRate>=.5?"var(--color-warning)":"var(--color-error)"}}),Ba(N.successRate)]}),e.jsx("div",{className:"stat-label",children:o("agents.performance.successRate","Success Rate")})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(Et,{size:16,style:{color:"var(--color-info)"}}),N.recentReflectionCount]}),e.jsx("div",{className:"stat-label",children:o("agents.performance.reflections","Reflections")})]})]}),v&&e.jsxs("div",{className:"reflections-no-data",children:[e.jsx(Ct,{size:24,opacity:.3}),e.jsx("p",{children:o("agents.performance.noData","No performance data yet")})]}),e.jsxs("div",{className:"reflections-ratings-section",children:[e.jsx("h4",{children:o("agents.ratings.title","User Ratings")}),P?e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(G,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:o("agents.ratings.loading","Loading ratings...")})]}):e.jsxs(e.Fragment,{children:[g&&e.jsxs("div",{className:"rating-summary-card",children:[e.jsxs("div",{className:"rating-score-display",children:[e.jsx("span",{className:"rating-average",children:g.averageScore.toFixed(1)}),ds(Math.round(g.averageScore))]}),e.jsxs("div",{className:"rating-stats",children:[e.jsx("span",{className:"rating-count",children:o("agents.ratings.count","{{count}} ratings",{count:g.totalRatings})}),e.jsx("span",{className:`rating-trend-badge ${_a(g.trend)}`,children:Oa(g.trend,o)})]})]}),g&&Object.keys(g.categoryAverages).length>0&&e.jsxs("div",{className:"category-breakdown",children:[e.jsx("h4",{children:o("agents.ratings.categoryAverages","Category Averages")}),Object.entries(g.categoryAverages).map(([d,z])=>e.jsxs("div",{className:"category-item",children:[e.jsx("span",{className:"category-name",children:d}),e.jsx("span",{className:"category-score",children:z.toFixed(1)})]},d))]}),e.jsxs("form",{className:"add-rating-form",onSubmit:A,children:[e.jsx("h4",{children:o("agents.ratings.addRating","Add Rating")}),e.jsx("div",{className:"star-selector",children:[1,2,3,4,5].map(d=>e.jsx("button",{type:"button",className:"star-btn touch-target",onClick:()=>D(d),title:o("agents.ratings.starCount","{{count}} star",{count:d,defaultValue_one:"{{count}} star",defaultValue_other:"{{count}} stars"}),children:e.jsx(hs,{size:24,fill:d<=C?"currentColor":"none",className:d<=C?"star-filled":"star-empty"})},d))}),e.jsxs("select",{value:T,onChange:d=>V(d.target.value),className:"select add-rating-category-select",children:[e.jsx("option",{value:"",children:o("agents.ratings.categorySelect","Select category...")}),e.jsx("option",{value:"quality",children:o("agents.ratings.categoryQuality","Quality")}),e.jsx("option",{value:"speed",children:o("agents.ratings.categorySpeed","Speed")}),e.jsx("option",{value:"communication",children:o("agents.ratings.categoryCommunication","Communication")}),e.jsx("option",{value:"reliability",children:o("agents.ratings.categoryReliability","Reliability")}),e.jsx("option",{value:"other",children:o("agents.ratings.categoryOther","Other")})]}),e.jsx("textarea",{value:Z,onChange:d=>I(d.target.value),placeholder:o("agents.ratings.commentPlaceholder","Optional comment..."),className:"input add-rating-comment-input",rows:3}),e.jsx("button",{type:"submit",className:"btn btn-task-create",disabled:C===0||q,children:q?o("agents.ratings.submitting","Submitting..."):o("agents.ratings.submitRating","Submit Rating")})]}),e.jsxs("div",{className:"rating-history",children:[e.jsx("h4",{children:o("agents.ratings.historyTitle","Rating History")}),j.length===0?e.jsx("p",{className:"no-ratings",children:o("agents.ratings.noRatings","No ratings yet")}):j.map(d=>e.jsxs("div",{className:"rating-history-item",children:[e.jsxs("div",{className:"rating-item-header",children:[ds(d.score),d.category&&e.jsx("span",{className:"rating-category-badge",children:d.category}),e.jsx("span",{className:"rating-time",children:cs(d.createdAt,o)}),e.jsx("button",{type:"button",className:"rating-delete-btn touch-target",onClick:()=>void W(d.id),title:o("agents.ratings.deleteRating","Delete rating"),children:e.jsx(lt,{size:14})})]}),d.comment&&e.jsx("p",{className:"rating-comment",children:d.comment})]},d.id))]})]})]}),e.jsxs("div",{className:"reflections-list",children:[e.jsx("h4",{children:o("agents.reflections.historyTitle","Reflection History")}),m?e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(G,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:o("agents.reflections.loading","Loading reflections...")})]}):s.length===0?e.jsxs("div",{className:"reflection-empty",children:[e.jsx(Et,{size:32,opacity:.3}),e.jsx("p",{children:o("agents.reflections.noReflections","No reflections yet")}),e.jsx("p",{className:"text-secondary",children:o("agents.reflections.getStarted","Trigger a reflection to get started")})]}):e.jsx("div",{className:"reflection-cards",children:s.map(d=>{const z=k===d.id;return e.jsxs("div",{className:`reflection-card ${z?"reflection-card--expanded":""}`,onClick:()=>x(d.id),role:"button",tabIndex:0,onKeyDown:$=>$.key==="Enter"&&x(d.id),children:[e.jsxs("div",{className:"reflection-card-header",children:[e.jsx("span",{className:`reflection-trigger-badge reflection-trigger-${d.trigger}`,children:$a(d.trigger,o)}),e.jsx("span",{className:"reflection-timestamp",children:cs(d.timestamp,o)}),e.jsx("span",{className:"reflection-chevron",children:z?e.jsx(fs,{size:16}):e.jsx(bs,{size:16})})]}),e.jsx("div",{className:"reflection-summary",children:d.summary}),z&&e.jsxs("div",{className:"reflection-details",children:[d.insights.length>0&&e.jsxs("div",{className:"reflection-insights",children:[e.jsxs("h5",{children:[e.jsx(Et,{size:14})," ",o("agents.reflections.insights","Insights")]}),e.jsx("ul",{children:d.insights.map(($,Ce)=>e.jsx("li",{children:$},Ce))})]}),d.suggestedImprovements.length>0&&e.jsxs("div",{className:"reflection-suggestions",children:[e.jsxs("h5",{children:[e.jsx(ss,{size:14})," ",o("agents.reflections.suggestedImprovements","Suggested Improvements")]}),e.jsx("ul",{children:d.suggestedImprovements.map(($,Ce)=>e.jsx("li",{children:$},Ce))})]}),d.metrics&&e.jsxs("div",{className:"reflection-metrics",children:[e.jsx("h5",{children:o("agents.reflections.metrics","Metrics")}),e.jsxs("div",{className:"metrics-grid",children:[d.metrics.tasksCompleted!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:o("agents.reflections.metricTasks","Tasks:")}),e.jsx("span",{className:"metric-value",children:d.metrics.tasksCompleted})]}),d.metrics.tasksFailed!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:o("agents.reflections.metricFailed","Failed:")}),e.jsx("span",{className:"metric-value",children:d.metrics.tasksFailed})]}),d.metrics.avgDurationMs!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:o("agents.reflections.metricAvgDuration","Avg Duration:")}),e.jsx("span",{className:"metric-value",children:os(d.metrics.avgDurationMs)})]}),d.metrics.errorCount!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:o("agents.reflections.metricErrors","Errors:")}),e.jsx("span",{className:"metric-value",children:d.metrics.errorCount})]})]})]})]})]},d.id)})})]})]})}function oe(...t){return t.filter(Boolean).join(" ")}function Ye(t,i){const l=Date.now(),o=new Date(t).getTime(),s=l-o,h=i??((n,g,u)=>u?g.replace(/\{\{(\w+)\}\}/g,(j,c)=>String(u[c]??"")):g);if(s<0){const n=Math.abs(s);if(n<6e4)return h("time.inAMoment","in a moment");if(n<36e5){const u=Math.floor(n/6e4);return h("time.inMinutes","in {{n}}m",{n:u})}if(n<864e5){const u=Math.floor(n/36e5);return h("time.inHours","in {{n}}h",{n:u})}const g=Math.floor(n/864e5);return h("time.inDays","in {{n}}d",{n:g})}if(s<6e4)return h("time.justNow","just now");if(s<36e5){const n=Math.floor(s/6e4);return h("time.minutesAgo","{{n}}m ago",{n})}if(s<864e5){const n=Math.floor(s/36e5);return h("time.hoursAgo","{{n}}h ago",{n})}const N=Math.floor(s/864e5);return h("time.daysAgo","{{n}}d ago",{n:N})}const Va=[{id:"dashboard",label:"Dashboard",icon:za},{id:"logs",label:"Logs",icon:ot},{id:"mail",label:"Mail",icon:Zs},{id:"runs",label:"Runs",icon:Rt},{id:"tasks",label:"Tasks",icon:Ss},{id:"employees",label:"Employees",icon:ks},{id:"soul",label:"Soul",icon:Qs},{id:"instructions",label:"Instructions",icon:Ta},{id:"memory",label:"Agent Memory",icon:ot},{id:"reflections",label:"Evaluation",icon:Ct},{id:"config",label:"Settings",icon:Xs}],qt={idle:{bg:"var(--state-idle-bg)",text:"var(--state-idle-text)",border:"var(--state-idle-border)"},active:{bg:"var(--state-active-bg)",text:"var(--state-active-text)",border:"var(--state-active-border)"},running:{bg:"var(--state-active-bg)",text:"var(--state-active-text)",border:"var(--state-active-border)"},paused:{bg:"var(--state-paused-bg)",text:"var(--state-paused-text)",border:"var(--state-paused-border)"},error:{bg:"var(--state-error-bg)",text:"var(--state-error-text)",border:"var(--state-error-border)"}},Mt={completed:{icon:ge,color:"var(--color-success)"},failed:{icon:la,color:"var(--color-error)"},active:{icon:G,color:"var(--in-progress)"},terminated:{icon:Ke,color:"var(--text-muted)"}},Wa=Ms(Vt),Ja=700;function qa(t,i){return t.some(l=>l.path===i)?i:t.find(l=>l.layer==="long-term")?.path??t[0]?.path??""}function xn({agentId:t,projectId:i,onClose:l,addToast:o,onChildClick:s,inline:h=!1,showInlineBackButton:N=!1,initialTab:n,initialRunId:g,preferActiveRun:u=!1,onMutationSuccess:j}){const{t:c}=ke("app"),[m,M]=a.useState(null),{confirm:P}=ps(),[L,w]=a.useState([]),[X,q]=a.useState(!0),[S,k]=a.useState(n??"dashboard"),[R,C]=a.useState(!1),[D,T]=a.useState(!1),[V,Z]=a.useState(!1),[I,Q]=a.useState(!1),[F,ae]=a.useState(!1),[A,W]=a.useState(!1),[x,v]=a.useState(0),[d,z]=a.useState(0),[$,Ce]=a.useState(0),[de,ve]=a.useState(null),[je,ye]=a.useState(null),[be,O]=a.useState(!1),[B,p]=a.useState(null),y=a.useRef(null),ie=a.useRef(null),he=a.useRef(!1);Js(y,!h,"fusion:agent-detail-modal-size");const We=a.useRef(l),Ee=a.useRef(o),Me=a.useRef(null),ce=a.useRef(!1),Le=a.useRef(null),te=a.useRef(0),Ze=a.useRef(t),gt=a.useRef(i);We.current=l,Ee.current=o,Me.current=m;const we=a.useCallback(async()=>{Me.current===null&&q(!0);try{const H=await qs(t,i);M(H)}catch(H){Ee.current(`Failed to load agent: ${U(H)}`,"error"),We.current()}finally{q(!1)}},[t,i]),ht=a.useCallback(async()=>{const b=te.current,H=t,J=i,_=()=>te.current!==b||t!==H||i!==J;try{if(m?.taskId){ve(null),Le.current=null;const De=await Gs(m.taskId,J,{limit:100});if(_())return;w(De.entries);return}const se=await xs(H,1,J);if(_())return;const fe=se[0]??null;if(ve(fe),!fe){Le.current=null,w([]);return}if(Le.current===fe.id)return;const Se=await vs(H,fe.id,J);if(_())return;w(Se),Le.current=fe.id}catch(se){if(_())return;console.error("Failed to load agent logs:",se)}},[m?.taskId,t,i]),Qe=a.useCallback(async()=>{O(!0),p(null);try{const b=await Ks(t,i);ye(b)}catch(b){p(U(b)),ye(null)}finally{O(!1)}},[t,i]),At=a.useCallback(b=>{ce.current=b},[]),Xe=a.useCallback(async(b=!1)=>{await j?.({agentId:t,deleted:b})},[t,j]),Ie=a.useCallback(async()=>{await we(),await Xe(!1)},[we,Xe]);a.useEffect(()=>{we()},[we]),a.useEffect(()=>{const b=setInterval(()=>{we()},3e4);return()=>{clearInterval(b)}},[we]),a.useEffect(()=>{m&&S==="logs"&&ht()},[m,S,ht]),a.useEffect(()=>{S!=="logs"&&(Le.current=null)},[S]),a.useEffect(()=>{m&&S==="mail"&&Qe()},[m,S,Qe]),a.useEffect(()=>{if(!I)return;const b=J=>{ie.current?.contains(J.target)||Q(!1)},H=J=>{J.key==="Escape"&&Q(!1)};return document.addEventListener("mousedown",b),document.addEventListener("keydown",H),()=>{document.removeEventListener("mousedown",b),document.removeEventListener("keydown",H)}},[I]),a.useEffect(()=>{if(!I)return;let b=!1;return W(!0),wt(void 0,i).then(H=>{if(b)return;const J=H.filter(_=>!Lt(_));v(J.filter(_=>_.state==="active"||_.state==="running").length),z(J.filter(_=>_.state==="paused").length)}).catch(()=>{b||(v(0),z(0))}).finally(()=>{b||W(!1)}),()=>{b=!0}},[I,i]),a.useEffect(()=>{if(S!=="logs"||m?.taskId||!de||de.status!=="active")return;const b=te.current,H=t,J=de.id,_=i?`?projectId=${encodeURIComponent(i)}`:"",se=kt(`/api/agents/${encodeURIComponent(H)}/runs/${encodeURIComponent(J)}/logs/stream${_}`,{events:{"agent:log":fe=>{if(te.current===b)try{const Se=JSON.parse(fe.data);w(De=>[...De,Se])}catch{}}},onOpen:()=>{te.current===b&&C(!0)},onError:()=>{te.current===b&&C(!1)}});return()=>{se(),te.current===b&&C(!1)}},[S,m?.taskId,t,i,de]),a.useEffect(()=>{(Ze.current!==t||gt.current!==i)&&(Ze.current=t,gt.current=i,te.current++,w([]),C(!1),ve(null),ye(null),p(null),Le.current=null,ce.current=!1)},[t,i]),a.useEffect(()=>{const b=i?`?projectId=${encodeURIComponent(i)}`:"",H=te.current,J=_=>{if(te.current===H)try{const se=JSON.parse(_.data);if(!se||typeof se!="object"||se.agentId!==t)return;we()}catch{}};return kt(`/api/events${b}`,{events:{"agent:updated":_=>{if(te.current===H)try{const se=JSON.parse(_.data);if(!se||typeof se!="object"||se.id!==t||ce.current)return;we()}catch{}},"approval:requested":J,"approval:updated":J,"approval:decided":J}})},[t,i,we]),a.useEffect(()=>{if(S!=="logs"||!m?.taskId){C(!1);return}const b=te.current,H=m.taskId,J=i?`?projectId=${encodeURIComponent(i)}`:"",_=kt(`/api/tasks/${encodeURIComponent(H)}/logs/stream${J}`,{events:{"agent:log":se=>{if(te.current===b)try{const fe=JSON.parse(se.data);w(Se=>[...Se,fe])}catch{}}},onOpen:()=>{te.current===b&&C(!0)},onError:()=>{te.current===b&&C(!1)}});return()=>{_(),te.current===b&&C(!1)}},[m?.taskId,S,i]);const Fe=async b=>{if(D||!Me.current)return;const H=Me.current.state;if(H!==b){T(!0),M(J=>J&&{...J,state:b});try{await ns(t,b,i),o(c("agents.stateUpdated","Agent state updated to {{newState}}",{newState:b}),"success"),await Ie()}catch(J){M(_=>_&&{..._,state:H}),o(c("agents.stateUpdateFailed","Failed to update state: {{error}}",{error:U(J)}),"error")}finally{T(!1)}}},et=async b=>{if(!F){Q(!1),ae(!0);try{const J=(await wt(void 0,i)).filter(ue=>!Lt(ue)),_=J.filter(ue=>b==="paused"?ue.state==="active"||ue.state==="running":ue.state==="paused"),se=J.length-_.length;if(_.length===0){o(c("agents.bulkNoEligible","No agents eligible to {{action}}",{action:b==="paused"?c("agents.pause","pause"):c("agents.resume","resume")}),"error");return}if(!await P({title:b==="paused"?c("agents.pauseAllTitle","Pause All Agents"):c("agents.resumeAllTitle","Resume All Agents"),message:c("agents.bulkConfirmMessage","{{action}} {{count}} agent(s) in this project?",{action:b==="paused"?c("agents.pauseAction","Pause"):c("agents.resumeAction","Resume"),count:_.length}),danger:b==="paused"}))return;const Se=await Promise.allSettled(_.map(ue=>ns(ue.id,b,i))),De=Se.map((ue,Ue)=>({result:ue,agent:_[Ue]})).filter(ue=>ue.result.status==="rejected"),st=Se.length-De.length,bt=De.length,Pt=b==="paused"?c("agents.pausedPast","Paused"):c("agents.resumedPast","Resumed"),pt=st===1?c("agents.agentSingular","agent"):c("agents.agentPlural","agents"),Pe=c(st===1?"agents.bulkResult_one":"agents.bulkResult_other","{{action}} {{successCount}} {{agentWord}}; skipped {{skippedCount}}",{action:Pt,successCount:st,agentWord:pt,skippedCount:se});if(bt>0){const ue=De.slice(0,3).map(({agent:Ue,result:xt})=>`${Ue.name||Ue.id}: ${U(xt.reason)}`).join("; ");o(c("agents.bulkResultWithFailures","{{summary}}; failed {{failureCount}}{{detail}}",{summary:Pe,failureCount:bt,detail:ue?` (${ue})`:""}),"error")}else o(Pe,"success");await Ie()}catch(H){o(c("agents.bulkActionFailed","Failed to {{action}} agents: {{error}}",{action:b==="paused"?c("agents.pause","pause"):c("agents.resume","resume"),error:U(H)}),"error")}finally{ae(!1)}}},tt=async()=>{if(!V){Z(!0);try{await sa(t,i,{source:"on_demand",triggerDetail:"Triggered from dashboard"}),o(c("agents.heartbeatStarted","Heartbeat run started for {{name}}",{name:m?.name??t}),"success"),Ce(b=>b+1)}catch(b){o(c("agents.heartbeatStartFailed","Failed to start heartbeat run: {{error}}",{error:U(b)}),"error")}finally{Z(!1)}}},Je=async()=>{if(!(!m||!await P({title:c("agents.deleteTitle","Delete Agent"),message:c("agents.deleteConfirm",'Delete agent "{{name}}"? This cannot be undone.',{name:m.name}),danger:!0})))try{await aa(t,i),o(c("agents.deleted",'Agent "{{name}}" deleted',{name:m.name}),"success"),await Xe(!0),l()}catch(H){o(c("agents.deleteFailed","Failed to delete agent: {{error}}",{error:U(H)}),"error")}},ft=()=>m?ta(m):{label:"Unknown",icon:e.jsx(Jt,{size:14}),color:"var(--text-muted)",stateDerived:!1},$e=()=>{m&&(navigator.clipboard.writeText(m.id),o(c("agents.idCopied","Agent ID copied to clipboard"),"success"))};if(X)return h?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(G,{className:"animate-spin",size:24}),e.jsx("span",{children:c("agents.loading","Loading agent...")})]})}):e.jsx("div",{className:"agent-detail-overlay",onMouseDown:b=>{b.target===b.currentTarget&&(he.current=!0)},onMouseUp:b=>{he.current&&b.target===b.currentTarget&&l(),he.current=!1},role:"dialog","aria-modal":"true",children:e.jsx("div",{className:"agent-detail-modal",ref:y,children:e.jsxs("div",{className:"agent-detail-loading",children:[e.jsx(G,{className:"animate-spin",size:24}),e.jsx("span",{children:c("agents.loading","Loading agent...")})]})})});if(!m)return null;const Ae=qt[m.state],re=ft(),Oe=h?"agent-detail-inline":"agent-detail-modal",Ne=A||x===0,_e=A||d===0;return e.jsx("div",{className:h?"agent-detail-inline-shell":"agent-detail-overlay",onClick:b=>!h&&b.target===b.currentTarget&&l(),role:h?"region":"dialog","aria-label":h?"Agent detail":void 0,"aria-modal":h?void 0:"true",children:e.jsxs("div",{className:Oe,ref:y,children:[e.jsxs("div",{className:"agent-detail-header",children:[e.jsxs("div",{className:"agent-detail-identity",children:[h&&N?e.jsxs("button",{type:"button",className:"btn agent-detail-inline-back",onClick:l,"aria-label":c("agents.backToAgents","Back to agents"),children:[e.jsx(js,{size:16}),c("agents.agentsLabel","Agents")]}):null,e.jsx("div",{className:"agent-detail-icon",children:e.jsx(ys,{agent:m,size:36})}),e.jsxs("div",{className:"agent-detail-info",children:[e.jsx("h2",{children:m.name}),e.jsxs("div",{className:"agent-detail-badges",children:[e.jsx("span",{className:"badge",style:{background:Ae.bg,color:Ae.text,border:`1px solid ${Ae.border}`},children:m.state}),e.jsxs("span",{className:"badge",style:{color:re.color},title:re.reason??re.label,children:[re.icon,!re.stateDerived&&re.label]})]})]})]}),e.jsxs("div",{className:"agent-detail-header-actions",children:[e.jsxs("div",{className:"agent-detail-controls",children:[m.state==="idle"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void Fe("active"),disabled:D,children:[e.jsx(Dt,{size:14}),c("agents.start","Start")]}),e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void tt(),"aria-label":c("agents.runNowFor","Run now for {{name}}",{name:m.name}),disabled:V||D,children:[e.jsx(Rt,{size:14}),c("agents.runNow","Run Now")]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:Je,children:[e.jsx(lt,{size:14}),c("agents.delete","Delete")]})]}),m.state==="active"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--compact agent-detail-mobile-icon-control",onClick:()=>void Fe("paused"),disabled:D,"aria-label":c("agents.pause","Pause"),children:[e.jsx(as,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:c("agents.pause","Pause")})]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:()=>void Fe("paused"),disabled:D,"aria-label":c("agents.stop","Stop"),children:[e.jsx(Ke,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:c("agents.stop","Stop")})]}),e.jsxs("button",{className:"btn btn-task-create btn--compact agent-detail-mobile-icon-control",onClick:()=>void tt(),"aria-label":c("agents.runNowFor","Run now for {{name}}",{name:m.name}),disabled:V||D,children:[e.jsx(Rt,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:c("agents.runNow","Run Now")})]})]}),m.state==="paused"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact agent-detail-mobile-icon-control",onClick:()=>void Fe("active"),disabled:D,"aria-label":c("agents.resume","Resume"),children:[e.jsx(Dt,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:c("agents.resume","Resume")})]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:Je,children:[e.jsx(lt,{size:14}),c("agents.delete","Delete")]})]}),m.state==="running"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--compact agent-detail-mobile-icon-control",onClick:()=>void Fe("paused"),disabled:D,"aria-label":c("agents.pause","Pause"),children:[e.jsx(as,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:c("agents.pause","Pause")})]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:()=>void Fe("paused"),disabled:D,"aria-label":c("agents.stop","Stop"),children:[e.jsx(Ke,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:c("agents.stop","Stop")})]})]}),m.state==="error"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void Fe("active"),disabled:D,children:[e.jsx(Dt,{size:14}),c("agents.retry","Retry")]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:()=>void Fe("paused"),disabled:D,"aria-label":c("agents.stop","Stop"),children:[e.jsx(Ke,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:c("agents.stop","Stop")})]}),e.jsxs("button",{className:"btn btn--danger btn--compact agent-detail-mobile-icon-control",onClick:Je,"aria-label":c("agents.delete","Delete"),children:[e.jsx(lt,{size:14}),e.jsx("span",{className:"agent-detail-control-label",children:c("agents.delete","Delete")})]})]})]}),e.jsxs("div",{className:"agent-detail-utility-actions",children:[e.jsxs("div",{className:"agent-detail-bulk-menu",ref:ie,children:[e.jsx("button",{type:"button",className:"btn-icon",onClick:()=>Q(b=>!b),"aria-haspopup":"menu","aria-expanded":I,"aria-label":c("agents.bulkActions","Bulk agent actions"),title:c("agents.bulkActions","Bulk agent actions"),disabled:D||F,children:e.jsx(Ys,{size:16})}),I&&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 et("paused"),disabled:Ne||F,children:[c("agents.pauseAll","Pause All Agents"),e.jsx("span",{className:"agent-detail-bulk-menu-item-hint",children:A?c("agents.loadingEligible","Loading eligible agents..."):Ne?c("agents.noActiveEligible","No active agents eligible"):c(x===1?"agents.pauseCountHint_one":"agents.pauseCountHint_other",x===1?"Pause {{count}} active/running agent":"Pause {{count}} active/running agents",{count:x})})]}),e.jsxs("button",{type:"button",role:"menuitem",className:"agent-detail-bulk-menu-item",onClick:()=>void et("active"),disabled:_e||F,children:[c("agents.resumeAll","Resume All Agents"),e.jsx("span",{className:"agent-detail-bulk-menu-item-hint",children:A?c("agents.loadingEligible","Loading eligible agents..."):_e?c("agents.noPausedEligible","No paused agents eligible"):c(d===1?"agents.resumeCountHint_one":"agents.resumeCountHint_other",d===1?"Resume {{count}} paused agent":"Resume {{count}} paused agents",{count:d})})]})]})]}),e.jsx("button",{className:"btn-icon",onClick:()=>void we(),title:c("common.refresh","Refresh"),"aria-label":c("common.refresh","Refresh"),children:e.jsx(Ft,{size:16})}),!h&&e.jsx("button",{className:"btn-icon",onClick:l,"aria-label":c("common.close","Close"),title:c("common.close","Close"),children:e.jsx(Ns,{size:20})})]})]})]}),e.jsx("div",{className:"agent-detail-tabs",children:Va.map(b=>{const H={dashboard:c("agents.tabDashboard","Dashboard"),logs:c("agents.tabLogs","Logs"),mail:c("agents.tabMail","Mail"),runs:c("agents.tabRuns","Runs"),tasks:c("agents.tabTasks","Tasks"),employees:c("agents.tabEmployees","Employees"),soul:c("agents.tabSoul","Soul"),instructions:c("agents.tabInstructions","Instructions"),memory:c("agents.tabMemory","Agent Memory"),reflections:c("agents.tabReflections","Evaluation"),config:c("agents.tabConfig","Settings")};return e.jsxs("button",{className:oe("agent-detail-tab",S===b.id&&"active"),onClick:()=>k(b.id),children:[e.jsx(b.icon,{size:16}),H[b.id]]},b.id)})}),e.jsxs("div",{className:"agent-detail-content",children:[S==="dashboard"&&e.jsx(Ga,{agent:m,health:re,onChildClick:s,projectId:i}),S==="logs"&&e.jsx(Ka,{logs:L,isStreaming:R,hasTask:!!m.taskId||L.length>0||de!==null,fallbackLabel:!m.taskId&&de?c("agents.latestRunLabel","Latest run · {{id}}",{id:de.id.slice(0,8)}):null}),S==="mail"&&e.jsx(Za,{agent:m,mailbox:je,isLoading:be,error:B,projectId:i,addToast:o,onRefresh:()=>void Qe()}),S==="runs"&&e.jsx(Qa,{addToast:o,agentId:m.id,projectId:i,agentState:m.state,agentName:m.name,initialRunId:g,preferActiveRun:u,runNowRefreshToken:$,isEphemeral:Lt(m)}),S==="tasks"&&e.jsx(tn,{agentId:m.id,projectId:i,addToast:o}),S==="employees"&&e.jsx(cn,{agentId:m.id,projectId:i,onChildClick:s}),S==="soul"&&e.jsx(an,{agent:m,projectId:i,addToast:o,onSaved:Ie}),S==="instructions"&&e.jsx(rn,{agent:m,projectId:i,addToast:o,onSaved:Ie}),S==="memory"&&e.jsx(nn,{agent:m,projectId:i,addToast:o,onSaved:Ie}),S==="reflections"&&e.jsx(Ua,{agentId:m.id,projectId:i,addToast:o}),S==="config"&&e.jsx(on,{agent:m,projectId:i,addToast:o,onSaved:Ie,onHasChangesChange:At,onDelete:Je,onAgentDraftApplied:b=>{M(H=>H&&{...H,...b})}},m.id)]}),!h&&e.jsxs("div",{className:"agent-detail-footer",children:[e.jsx("button",{className:"btn-icon",onClick:$e,title:c("agents.copyId","Copy Agent ID"),children:e.jsx(ea,{})}),e.jsx("span",{className:"agent-detail-id",onClick:$e,children:m.id}),m.taskId&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"divider",children:"|"}),e.jsx("span",{className:"text-muted",children:c("agents.workingOn","Working on:")}),e.jsxs("a",{href:`/tasks/${m.taskId}`,className:"link",children:[m.taskId,e.jsx(Cs,{size:12})]})]})]})]})})}function Ga({agent:t,health:i,onChildClick:l,projectId:o}){const{t:s}=ke("app"),h=qt[t.state],[N,n]=a.useState([]),[g,u]=a.useState(!0),[j,c]=a.useState(null),[m,M]=a.useState([]),[P,L]=a.useState(null),[w,X]=a.useState(null),[q,S]=a.useState(!1),[k,R]=a.useState(null),C=typeof t.runtimeConfig?.runtimeHint=="string"?t.runtimeConfig.runtimeHint:"",D=(()=>{const x=t.runtimeConfig??{};if(C){const v=m.find(d=>d.runtimeId===C);return v?v.name:C}if(x.modelProvider&&x.modelId)return`${x.modelProvider}/${x.modelId}`;if(typeof x.model=="string"&&x.model.includes("/")){const v=x.model.indexOf("/");return x.model.slice(v+1)}return null})();a.useEffect(()=>{Ut(t.id,o).then(c).catch(()=>c(null))},[t.id,o]),a.useEffect(()=>{ws(o).then(M).catch(()=>M([]))},[o]),a.useEffect(()=>{let x=!1;return u(!0),na(t.id,o).then(v=>{if(x)return;const d=v.length>0&&v[0]?.id===t.id?[...v].reverse():v;n(d)}).catch(()=>{x||n([])}).finally(()=>{x||u(!1)}),()=>{x=!0}},[t.id,o]);const T=a.useMemo(()=>{const x=t.completedRuns||[],v=new Date;v.setHours(0,0,0,0);const d=x.filter($=>new Date($.startedAt)>=v),z=x.filter($=>$.status==="completed");return{totalRuns:x.length,todayRuns:d.length,successfulRuns:z.length,successRate:x.length>0?Math.round(z.length/x.length*100):0}},[t]),V=(t.completedRuns||[]).slice(0,5),Z=Array.isArray(t.metadata?.skills)?t.metadata.skills:[],I=P?zt(P):null,Q=a.useCallback(async x=>{S(!0),R(null),X(null);try{const v=await ia(x,o);X(v)}catch(v){R(U(v))}finally{S(!1)}},[o]),F=a.useCallback(x=>{if(P===x){L(null),X(null),R(null),S(!1);return}L(x),Q(x)},[Q,P]),ae=t.state==="active"||t.state==="running",A=ra(t.runtimeConfig?.heartbeatIntervalMs),W=ae&&t.lastHeartbeatAt?new Date(new Date(t.lastHeartbeatAt).getTime()+A).toISOString():null;return e.jsxs("div",{className:"dashboard-tab dashboard-summary-layout",children:[j?.isOverBudget&&e.jsxs("div",{className:"budget-warning-banner",role:"alert",children:[e.jsx("span",{children:"⚠️"}),e.jsxs("span",{children:[e.jsx("strong",{children:s("agents.budgetExhaustedTitle","Budget Exhausted:")})," ",s("agents.budgetExhaustedBody","This agent has exceeded its token budget and may operate with limited functionality.")]})]}),e.jsxs("section",{className:"dashboard-summary-card dashboard-summary-hero",children:[e.jsxs("div",{className:"dashboard-summary-hero__heading",children:[e.jsx(Jt,{}),e.jsx("h3",{children:s("agents.overview","Overview")}),e.jsx("strong",{children:t.name}),e.jsx("span",{className:"inline-badge",style:{background:h.bg,color:h.text},children:t.state})]}),e.jsxs("div",{className:"dashboard-summary-hero__meta",children:[e.jsxs("span",{className:"dashboard-summary-hero__health",title:i.reason??i.label,children:[i.icon," ",i.label]}),(t.pendingApprovalCount??0)>0?e.jsxs("span",{className:"badge agent-detail-approval-badge",title:s("agents.pendingApprovals","Pending approvals"),children:[e.jsx("span",{className:"status-dot status-dot--pending"}),s("agents.pendingApprovalsCount","{{count}} pending approvals",{count:t.pendingApprovalCount})]}):null,e.jsx("span",{children:s("agents.roleLabel","Role: {{role}}",{role:t.role})}),e.jsxs("span",{children:[e.jsx("span",{className:"dashboard-summary-label",children:C?s("agents.runtime","Runtime"):s("agents.model","Model")}),e.jsxs("span",{children:[" ",D??s("agents.auto","Auto")]})]}),Z.length>0?e.jsxs("span",{className:"dashboard-summary-skills",children:[e.jsx("span",{className:"dashboard-summary-label",children:s("agents.skills","Skills")}),e.jsx("span",{className:"dashboard-summary-skill-badges",role:"list","aria-label":s("agents.assignedSkills","Assigned skills"),children:Z.map(x=>{const v=P===x;return e.jsx("button",{type:"button",className:oe("badge","badge-skill","dashboard-summary-skill-badge","dashboard-summary-skill-badge-btn",v&&"dashboard-summary-skill-badge--selected"),title:x,onClick:()=>F(x),"aria-expanded":v,"aria-label":s("agents.viewSkillDetails","View details for {{skill}}",{skill:zt(x)}),children:zt(x)},x)})})]}):e.jsx("span",{children:s("agents.skillsNone","Skills: —")})]}),P?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:I}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>F(P),children:[e.jsx(Ns,{size:14}),s("common.close","Close")]})]}),q?e.jsxs("div",{className:"dashboard-summary-skill-detail-loading",role:"status","aria-live":"polite",children:[e.jsx(G,{size:14,className:"animate-spin"}),s("agents.loadingSkillContent","Loading skill content...")]}):k?e.jsxs("div",{className:"dashboard-summary-skill-detail-error",role:"alert",children:[e.jsx(Rs,{size:14}),e.jsx("span",{children:k}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void Q(P),children:s("common.retry","Retry")})]}):w?e.jsx("pre",{className:"dashboard-summary-skill-detail-content",children:w.skillMd||s("agents.noSkillMd","(No SKILL.md found)")}):e.jsx("div",{className:"dashboard-summary-skill-detail-empty",children:s("agents.noSkillContent","No skill content available")})]}):null]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:s("agents.heartbeatAndHealth","Heartbeat & Health")}),e.jsxs("div",{className:"dashboard-summary-grid",children:[e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:s("agents.lastHeartbeat","Last heartbeat")}),e.jsx("p",{children:t.lastHeartbeatAt?Ye(t.lastHeartbeatAt,s):s("agents.never","Never")})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:s("agents.nextExpected","Next expected")}),e.jsx("p",{children:W?Ye(W,s):s("agents.notScheduled","Not scheduled")})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:s("agents.interval","Interval")}),e.jsx("p",{children:Ms(A)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:s("agents.status","Status")}),e.jsxs("p",{className:"dashboard-summary-health-row",children:[e.jsx("span",{className:oe("status-dot",t.state==="running"&&"status-dot--running")}),i.label,i.reason&&e.jsxs("span",{className:"text-secondary dashboard-summary-health-reason",title:i.reason,children:["(",i.reason,")"]})]})]})]})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:s("agents.currentWork","Current Work")}),t.taskId?e.jsxs("div",{className:"current-task",children:[e.jsx("a",{href:`/tasks/${t.taskId}`,className:"task-badge",children:t.taskId}),e.jsxs("a",{href:`/tasks/${t.taskId}`,className:"btn btn-sm",children:[s("agents.viewTask","View Task")," ",e.jsx(Cs,{size:14})]})]}):e.jsx("p",{className:"text-muted",children:s("agents.noActiveAssignment","No active assignment")})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:s("agents.recentRuns","Recent Runs")}),e.jsx("p",{className:"dashboard-summary-label",children:s("agents.runsSuccessRate","{{successful}}/{{total}} successful ({{rate}}%)",{successful:T.successfulRuns,total:T.totalRuns,rate:T.successRate})}),V.length===0?e.jsx("p",{className:"text-muted",children:s("agents.noRunsYet","No runs yet")}):e.jsx("div",{className:"runs-list",children:V.map(x=>{const v=Mt[x.status]||Mt.terminated,d=v.icon;return e.jsxs("div",{className:"run-item",children:[e.jsx(d,{size:14,style:{color:v.color}}),e.jsx("span",{children:Ye(x.startedAt,s)}),e.jsxs("span",{className:"text-muted",children:[Math.max(0,Math.round((new Date(x.endedAt||x.startedAt).getTime()-new Date(x.startedAt).getTime())/1e3)),"s"]})]},x.id)})})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:s("agents.throughput","Throughput")}),e.jsxs("div",{className:"stats-grid",children:[e.jsxs("div",{className:"stat-card",children:[e.jsx("div",{className:"stat-value",children:T.totalRuns}),e.jsx("div",{className:"stat-label",children:s("agents.totalRuns","Total Runs")})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("div",{className:"stat-value",children:T.todayRuns}),e.jsx("div",{className:"stat-label",children:s("agents.runsToday","Runs Today")})]}),e.jsxs("div",{className:"stat-card",children:[e.jsxs("div",{className:"stat-value",children:[T.successRate,"%"]}),e.jsx("div",{className:"stat-label",children:s("agents.successRate","Success Rate")})]})]})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:s("agents.chainOfCommand","Chain of Command")}),g?e.jsxs("div",{className:"chain-of-command-loading",role:"status","aria-live":"polite",children:[e.jsx(G,{size:14,className:"animate-spin"}),e.jsx("span",{children:s("agents.loadingReportingChain","Loading reporting chain...")})]}):N.length<=1?e.jsx("p",{className:"text-muted",children:s("agents.noReportingChain","No reporting chain")}):e.jsx("div",{className:"chain-of-command-path","aria-label":s("agents.chainOfCommand","Chain of command"),children:N.map((x,v)=>{const d=v===N.length-1,z=!d;return e.jsxs("div",{className:"chain-of-command-item",children:[e.jsx("button",{type:"button",className:`chain-of-command-node${d?" chain-of-command-node--current":""}`,onClick:()=>z&&l?.(x.id),disabled:!z||!l,title:d?s("agents.currentAgent","Current agent"):s("agents.viewAgent","View {{name}}",{name:x.name}),children:x.name}),!d&&e.jsx("span",{className:"chain-of-command-separator","aria-hidden":"true",children:"→"})]},x.id)})})]})]})}function Ka({logs:t,isStreaming:i,hasTask:l,fallbackLabel:o}){const{t:s}=ke("app");return l?e.jsxs("div",{className:"logs-tab",children:[e.jsxs("div",{className:"logs-header",children:[e.jsx("span",{className:"logs-count",children:s("agents.logEntries","{{count}} entries",{count:t.length})}),o&&e.jsx("span",{className:"text-muted logs-fallback-label",children:o}),i&&e.jsxs("span",{className:"streaming-indicator",children:[e.jsx("span",{className:"streaming-dot"}),s("agents.live","Live")]})]}),t.length===0?e.jsxs("div",{className:"logs-empty",children:[e.jsx(ot,{size:48,opacity:.3}),e.jsx("p",{children:s("agents.noLogEntriesYet","No log entries yet")}),e.jsx("p",{className:"text-muted",children:i?s("agents.waitingForActivity","Waiting for activity..."):s("agents.logsWillAppearActive","Logs will appear here when the agent is active")})]}):e.jsx(Fs,{entries:t,loading:!1})]}):e.jsx("div",{className:"logs-tab",children:e.jsxs("div",{className:"logs-empty",children:[e.jsx(ot,{size:48,opacity:.3}),e.jsx("p",{children:s("agents.noActivityYet","No activity yet")}),e.jsx("p",{className:"text-muted",children:s("agents.logsWillAppear","Agent logs will appear here from the current task or most recent run")})]})})}function Ya(t,i){const l=new Date(t),s=new Date().getTime()-l.getTime(),h=Math.floor(s/6e4),N=Math.floor(s/36e5),n=Math.floor(s/864e5),g=i??((u,j,c)=>c?j.replace(/\{\{(\w+)\}\}/g,(m,M)=>String(c[M]??"")):j);return h<1?g("time.justNow","just now"):h<60?g("time.minutesAgo","{{n}}m ago",{n:h}):N<24?g("time.hoursAgo","{{n}}h ago",{n:N}):n<7?g("time.daysAgo","{{n}}d ago",{n}):l.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function St(t,i,l,o){const s=o??((h,N,n)=>n?N.replace(/\{\{(\w+)\}\}/g,(g,u)=>String(n[u]??"")):N);if(i==="user")return t==="dashboard"?s("mailbox.you","You"):s("mailbox.userLabel","User: {{id}}",{id:t});if(i==="agent"){const h=l?.get(t)?.trim();return!h||h===t?s("mailbox.agentById","Agent: {{id}}",{id:t}):s("mailbox.agentByName","Agent: {{name}}",{name:h})}return s("mailbox.system","System")}function Za({agent:t,mailbox:i,isLoading:l,error:o,projectId:s,addToast:h,onRefresh:N}){const{t:n}=ke("app"),[g,u]=a.useState("inbox"),[j,c]=a.useState([]);a.useEffect(()=>{let k=!1;return wt(void 0,s).then(R=>{k||c(R)}).catch(()=>{k||c([])}),()=>{k=!0}},[s]);const m=a.useMemo(()=>{const k=new Map;for(const C of j){if(!C.id)continue;const D=typeof C.name=="string"?C.name.trim():"";D.length>0&&k.set(C.id,D)}const R=typeof t.name=="string"?t.name.trim():"";return R.length>0&&k.set(t.id,R),k},[j,t.id,t.name]),[M,P]=a.useState(null),L=g==="inbox"?i?.inbox??[]:i?.outbox??[],w=M?L.find(k=>k.id===M)??null:null;a.useEffect(()=>{P(null)},[g,t.id]);const X=async k=>{if(P(k.id),!(g!=="inbox"||k.read))try{await Ma(k.id,s),N()}catch(R){const C=`Failed to mark message as read: ${U(R)}`;h?h(C,"error"):console.warn(C)}},q=()=>{P(null),N()},S=k=>e.jsxs("button",{type:"button",className:oe("mailbox-item","agent-mail-tab-message",g==="inbox"&&!k.read&&"unread",M===k.id&&"agent-mail-tab-message--selected"),onClick:()=>void X(k),"aria-pressed":M===k.id,children:[e.jsx("div",{className:"mailbox-item-avatar",children:(g==="inbox"?k.fromType:k.toType)==="agent"?e.jsx(Jt,{size:16}):e.jsx(ja,{size:16})}),e.jsxs("div",{className:"mailbox-item-content",children:[e.jsxs("div",{className:"mailbox-item-header",children:[g==="inbox"?e.jsx("span",{className:"mailbox-item-from",children:St(k.fromId,k.fromType,m,n)}):e.jsx("span",{className:"mailbox-item-to",children:n("agents.mailTo","To: {{recipient}}",{recipient:St(k.toId,k.toType,m,n)})}),e.jsx("span",{className:"mailbox-item-time",children:Ya(k.createdAt,n)})]}),e.jsxs("div",{className:"mailbox-item-preview",children:[k.content.slice(0,80),k.content.length>80?"…":""]})]}),g==="inbox"&&!k.read?e.jsx("div",{className:"mailbox-item-unread-dot","aria-label":n("agents.unreadMessage","Unread message")}):null]},k.id);return e.jsxs("div",{className:"agent-mail-tab",children:[e.jsxs("div",{className:"agent-mail-tab-header",children:[e.jsx("h3",{children:n("agents.agentMail","{{name}} Mail",{name:t.name})}),e.jsxs("button",{className:"btn btn-sm",onClick:q,disabled:l,children:[e.jsx(Ft,{size:14}),n("common.refresh","Refresh")]})]}),e.jsxs("div",{className:"mailbox-agent-subtabs","data-testid":"agent-detail-mail-subtabs",children:[e.jsxs("button",{className:oe("btn","btn-sm","btn-secondary","mailbox-agent-subtab",g==="inbox"&&"active"),onClick:()=>u("inbox"),children:[e.jsx(is,{size:12}),e.jsx("span",{children:n("agents.inbox","Inbox")}),(i?.unreadCount??0)>0?e.jsx("span",{className:"mailbox-tab-badge",children:i?.unreadCount}):null]}),e.jsxs("button",{className:oe("btn","btn-sm","btn-secondary","mailbox-agent-subtab",g==="outbox"&&"active"),onClick:()=>u("outbox"),children:[e.jsx(rs,{size:12}),e.jsx("span",{children:n("agents.outbox","Outbox")})]})]}),l&&!i?e.jsxs("div",{className:"agent-detail-loading agent-detail-loading--inline",role:"status","aria-live":"polite",children:[e.jsx(G,{className:"animate-spin",size:16}),e.jsx("span",{children:n("agents.loadingMailbox","Loading mailbox...")})]}):null,!l&&o?e.jsxs("div",{className:"agent-mail-tab-error",role:"alert",children:[e.jsx(Rs,{size:16}),e.jsx("span",{children:n("agents.mailboxLoadFailed","Failed to load mailbox: {{error}}",{error:o})})]}):null,!l&&!o?w?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:()=>P(null),children:[e.jsx(js,{size:14}),g==="inbox"?n("agents.backToInbox","Back to Inbox"):n("agents.backToOutbox","Back to Outbox")]}),e.jsxs("div",{className:"agent-mail-tab-detail-meta",children:[e.jsxs("div",{className:"agent-mail-tab-detail-row",children:[e.jsx("span",{className:"agent-mail-tab-detail-label",children:n("agents.mailFrom","From")}),e.jsx("span",{children:St(w.fromId,w.fromType,m,n)})]}),e.jsxs("div",{className:"agent-mail-tab-detail-row",children:[e.jsx("span",{className:"agent-mail-tab-detail-label",children:n("agents.mailToLabel","To")}),e.jsx("span",{children:St(w.toId,w.toType,m,n)})]}),e.jsxs("div",{className:"agent-mail-tab-detail-row",children:[e.jsx("span",{className:"agent-mail-tab-detail-label",children:n("agents.mailType","Type")}),e.jsx("span",{children:w.type})]}),e.jsxs("div",{className:"agent-mail-tab-detail-row",children:[e.jsx("span",{className:"agent-mail-tab-detail-label",children:n("agents.mailSent","Sent")}),e.jsx("span",{children:new Date(w.createdAt).toLocaleString()})]}),w.metadata?.replyTo?.messageId?e.jsx("div",{className:"agent-mail-tab-reply-context",children:n("agents.replyingTo","↪ Replying to message {{id}}",{id:w.metadata.replyTo.messageId})}):null]}),e.jsx("div",{className:"agent-mail-tab-detail-body",children:w.content})]}):e.jsx("div",{className:"mailbox-list","data-testid":"agent-detail-mail-list",children:L.length===0?e.jsxs("div",{className:"mailbox-empty","data-testid":"agent-detail-mail-empty",children:[g==="inbox"?e.jsx(is,{size:32}):e.jsx(rs,{size:32}),e.jsx("p",{children:g==="inbox"?n("agents.noInboxMessages","No received messages for this agent"):n("agents.noOutboxMessages","No sent messages for this agent")})]}):L.map(S)}):null]})}function Qa({addToast:t,agentId:i,projectId:l,agentState:o,agentName:s,initialRunId:h,preferActiveRun:N,runNowRefreshToken:n,isEphemeral:g}){const{t:u}=ke("app"),[j,c]=a.useState([]),{confirm:m}=ps(),[M,P]=a.useState(!0),[L,w]=a.useState(null),[X,q]=a.useState([]),[S,k]=a.useState(!1),[R,C]=a.useState(null),[D,T]=a.useState(!1),[V,Z]=a.useState(null),[I,Q]=a.useState([]),F=a.useRef(!1),ae=a.useRef(!1),A=a.useCallback(async()=>{try{const p=await xs(i,50,l);c(p)}catch(p){t(`Failed to load runs: ${U(p)}`,"error")}finally{P(!1)}},[i,l,t]);a.useEffect(()=>{A()},[A]),a.useEffect(()=>{if(g){Z(null),Q([]);return}const p=l?`?projectId=${encodeURIComponent(l)}`:"";fetch(`/api/agents/${encodeURIComponent(i)}/token-usage${p}`).then(async y=>{if(!y.ok){if(y.status===400){Z(null);return}throw new Error(`Request failed: ${y.status}`)}const ie=await y.json();Z(ie)}).catch(y=>{t(`Failed to load cache hit ratio: ${U(y)}`,"error")}),oa(i,7,l).then(y=>Q(y)).catch(y=>{const ie=U(y).toLowerCase();if(ie.includes("ephemeral")||ie.includes("400")){Q([]);return}t(`Failed to load prompt sizes: ${U(y)}`,"error")})},[i,l,t,g]),a.useEffect(()=>{if(!ae.current){ae.current=!0;return}P(!0),A()},[A,n]);const W=j.some(p=>p.status==="active"),x=L?j.find(p=>p.id===L)?.status:void 0;a.useEffect(()=>{if(!W)return;const p=setInterval(()=>{A()},5e3);return()=>clearInterval(p)},[W,A]),a.useEffect(()=>{if(!L||x!=="active")return;const p=l?`?projectId=${encodeURIComponent(l)}`:"";return kt(`/api/agents/${encodeURIComponent(i)}/runs/${encodeURIComponent(L)}/logs/stream${p}`,{events:{"agent:log":y=>{try{const ie=JSON.parse(y.data);q(he=>[...he,ie])}catch{}}}})},[L,x,i,l]);const v=a.useCallback(async p=>{if(L===p){w(null),q([]),C(null);return}w(p),k(!0),T(!0),q([]),C(null);try{const[y,ie]=await Promise.all([vs(i,p,l),ca(i,p,l)]);q(y),C(ie)}catch(y){t(u("agents.runDetailsFailed","Failed to load run details: {{error}}",{error:U(y)}),"error"),q([]),C(null)}finally{k(!1),T(!1)}},[L,i,l,t]);a.useEffect(()=>{F.current=!1},[i,h,N]),a.useEffect(()=>{if(j.length===0||M||F.current)return;const p=h?j.find(y=>y.id===h):N?j.find(y=>y.status==="active"):null;F.current=!0,p&&v(p.id)},[h,N,j,M,v]);const d=async()=>{if(await m({title:u("agents.stopRunTitle","Stop Active Run"),message:u("agents.stopRunConfirm","Stop the active run? The agent's work will be interrupted."),danger:!0}))try{await ya(i,l),t(u("agents.runStopped","Run stopped"),"success"),P(!0),A()}catch(y){t(u("agents.stopRunFailed","Failed to stop run: {{error}}",{error:U(y)}),"error")}};if(M&&j.length===0)return e.jsx("div",{className:"runs-tab",children:e.jsxs("div",{className:"runs-loading-row",children:[e.jsx(G,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:u("agents.loadingRuns","Loading runs...")})]})});if(j.length===0)return e.jsx("div",{className:"runs-tab",children:e.jsxs("div",{className:"runs-empty",children:[e.jsx(Rt,{size:48,opacity:.3}),e.jsx("p",{children:u("agents.noRunsYet","No runs yet")}),e.jsx("p",{className:"text-muted",children:u("agents.heartbeatRunsWillAppear","Heartbeat runs will appear here")})]})});const z=[...j].sort((p,y)=>new Date(y.startedAt).getTime()-new Date(p.startedAt).getTime()),$=z.filter(p=>p.status==="active"),Ce=z.filter(p=>p.status!=="active"),de=p=>p?e.jsxs("div",{className:"run-usage",children:[e.jsx("span",{children:u("agents.inputTokens","Input: {{value}}",{value:p.inputTokens.toLocaleString()})}),e.jsx("span",{children:u("agents.outputTokens","Output: {{value}}",{value:p.outputTokens.toLocaleString()})}),p.cachedTokens>0&&e.jsx("span",{children:u("agents.cacheReadTokens","Cache read: {{value}}",{value:p.cachedTokens.toLocaleString()})}),(p.cacheWriteTokens??0)>0&&e.jsx("span",{children:u("agents.cacheWriteTokens","Cache write: {{value}}",{value:(p.cacheWriteTokens??0).toLocaleString()})})]}):null,ve=(p,y,ie)=>{const he=Mt[p.status]||Mt.completed,We=he.icon,Ee=p.endedAt?Xa(new Date(p.startedAt),new Date(p.endedAt)):u("agents.inProgress","In progress"),Me=L===p.id;return e.jsxs("div",{children:[e.jsxs("div",{className:oe("run-card",ie&&"run-card--active",Me&&"run-card--selected","run-card--clickable"),onClick:()=>void v(p.id),role:"button",tabIndex:0,"aria-expanded":Me,"aria-label":u("agents.runAriaLabel","{{active}}run {{id}}, {{status}}",{active:ie?u("agents.activePrefix","Active "):"",id:p.id.slice(0,8),status:p.status}),onKeyDown:ce=>{(ce.key==="Enter"||ce.key===" ")&&(ce.preventDefault(),v(p.id))},children:[e.jsxs("div",{className:"run-header",children:[e.jsxs("div",{className:"run-header-group",children:[Me?e.jsx(fs,{size:14}):e.jsx(bs,{size:14}),ie?e.jsxs("span",{className:"run-live-indicator",children:[e.jsx("span",{className:"live-dot"}),u("agents.liveRun","Live Run")]}):e.jsxs("span",{className:"run-id",children:["#",y+1," ",p.id.slice(0,8)]})]}),e.jsxs("div",{className:"run-header-group",children:[p.invocationSource&&e.jsx("span",{className:"badge run-badge--compact",children:p.invocationSource}),ie&&e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:ce=>{ce.preventDefault(),ce.stopPropagation(),d()},"aria-label":u("agents.stopActiveRun","Stop active run"),children:[e.jsx(Ke,{size:12})," ",u("agents.stop","Stop")]}),e.jsxs("span",{className:oe("run-status",p.status),children:[e.jsx(We,{size:14,style:{color:he.color}}),p.status]}),p.heartbeatProcedureSource==="custom"&&e.jsx("span",{className:"badge run-badge--compact",children:u("agents.heartbeatCustom","Heartbeat: custom")})]})]}),e.jsxs("div",{className:"run-details",children:[e.jsx("span",{children:u("agents.runStarted","Started {{time}}",{time:Ye(p.startedAt,u)})}),e.jsx("span",{children:"•"}),e.jsx("span",{children:Ee}),p.triggerDetail&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsx("span",{className:"text-muted",children:p.triggerDetail})]})]})]}),Me&&e.jsxs("div",{className:"run-logs-container",children:[D?e.jsxs("div",{className:"run-details-loading-state",children:[e.jsx(G,{size:14,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:u("agents.loadingDetails","Loading details...")})]}):R&&e.jsxs("div",{className:"run-output-sections",children:[e.jsx("div",{className:"run-output-section",children:e.jsxs("details",{children:[e.jsx("summary",{className:"run-output-label run-output-summary",children:u("agents.systemPrompt","System Prompt")}),R.systemPrompt?e.jsx("pre",{className:"run-output-panel",children:R.systemPrompt}):e.jsx("div",{className:"text-muted run-output-empty",children:u("agents.systemPromptNotCaptured","System prompt not captured for this run")})]})}),e.jsx("div",{className:"run-output-section",children:e.jsxs("details",{children:[e.jsx("summary",{className:"run-output-label run-output-summary",children:u("agents.executionPrompt","Execution Prompt")}),R.executionPrompt?e.jsx("pre",{className:"run-output-panel",children:R.executionPrompt}):e.jsx("div",{className:"text-muted run-output-empty",children:u("agents.executionPromptNotCaptured","Execution prompt not captured for this run")})]})}),R.usageJson&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:u("agents.tokenUsage","Token Usage")}),de(R.usageJson)]}),R.stdoutExcerpt&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:u("agents.output","Output")}),e.jsx("pre",{className:"run-output-panel",children:R.stdoutExcerpt.length>2e3?`${R.stdoutExcerpt.slice(0,2e3)}
17
-
18
- ... (truncated, ${R.stdoutExcerpt.length} chars total)`:R.stdoutExcerpt})]}),R.stderrExcerpt&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label run-output-label--error",children:u("agents.errors","Errors")}),e.jsx(Na,{errorText:R.stderrExcerpt,summaryPrefix:"Run error",issueContext:{surface:"AgentDetailView runs",agentId:i,agentName:s,agentState:o,runId:R.id,taskId:void 0,timestamp:R.startedAt}})]}),R.resultJson&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:u("agents.result","Result")}),e.jsx("pre",{className:"run-output-panel",children:JSON.stringify(R.resultJson,null,2)})]}),R.contextSnapshot&&Object.keys(R.contextSnapshot).length>0&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:u("agents.context","Context")}),e.jsx("div",{className:"run-context-grid",children:Object.entries(R.contextSnapshot).map(([ce,Le])=>e.jsxs("span",{className:"run-context-item",children:[e.jsxs("span",{className:"text-muted",children:[ce,":"]})," ",e.jsx("span",{children:String(Le)})]},ce))})]}),!R.stdoutExcerpt&&!R.stderrExcerpt&&!R.resultJson&&e.jsx("div",{className:"text-muted run-output-empty",children:u("agents.noOutputCaptured","No output captured")})]}),e.jsxs("div",{className:"run-agent-logs-section",children:[e.jsx("div",{className:"run-output-label",children:u("agents.agentLogs","Agent Logs")}),S?e.jsxs("div",{className:"run-details-loading-state",children:[e.jsx(G,{size:14,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:u("agents.loadingLogs","Loading logs...")})]}):X.length===0?e.jsx("div",{className:"text-muted run-output-empty",children:u("agents.noLogsForRun","No logs available for this run")}):e.jsx(Fs,{entries:X,loading:!1})]})]})]},p.id)},je=(p,y)=>e.jsxs("div",{className:"run-context-item",children:[e.jsxs("span",{className:"text-muted",children:[p,":"]})," ",e.jsxs("span",{children:[(y.hitRatio*100).toFixed(1),"% (",y.totalCachedTokens.toLocaleString()," / ",y.totalCacheWriteTokens.toLocaleString()," / ",y.totalInputTokens.toLocaleString()," / ",y.nTasks.toLocaleString(),")"]})]},p),ye=I[0],be=[...I].reverse(),O=Math.max(1,...be.map(p=>p.execChars)),B=be.map((p,y)=>{const ie=be.length<=1?0:y/(be.length-1)*100,he=100-Math.round(p.execChars/O*100);return`${ie},${he}`}).join(" ");return e.jsxs("div",{className:"runs-tab",children:[I.length>0&&ye&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:u("agents.promptSize","Prompt Size")}),e.jsxs("div",{className:"prompt-size-summary",children:[e.jsxs("svg",{className:"prompt-size-sparkline",viewBox:"0 0 100 100",role:"img","aria-label":u("agents.promptSizeChart","Execution prompt size over last 7 runs"),children:[e.jsx("polyline",{className:"prompt-size-sparkline-grid",points:"0,100 100,100"}),e.jsx("polyline",{className:"prompt-size-sparkline-line",points:B})]}),e.jsxs("span",{className:"prompt-size-values",children:[ye.systemChars.toLocaleString()," / ",ye.execChars.toLocaleString()," / ",ye.totalChars.toLocaleString()]})]})]}),V&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:u("agents.cacheHitRatio","Cache hit ratio")}),e.jsxs("div",{className:"run-context-grid",children:[je(u("agents.last24h","Last 24h"),V.last24h),je(u("agents.last7d","Last 7d"),V.last7d),je(u("agents.allTime","All time"),V.allTime)]})]}),e.jsxs("div",{className:"runs-toolbar runs-toolbar--between",children:[e.jsxs("span",{className:"runs-toolbar-meta",children:[u("agents.runsCount",{count:j.length,defaultValue_one:"{{count}} run",defaultValue_other:"{{count}} runs"}),W&&e.jsxs("span",{className:"run-live-indicator run-live-indicator--with-margin",children:[e.jsx("span",{className:"live-dot"}),u("agents.live","Live")]})]}),e.jsx("div",{className:"run-header-group",children:W&&e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void d(),"aria-label":u("agents.stopActiveRunFor","Stop active run for {{name}}",{name:s??i}),children:[e.jsx(Ke,{size:14})," ",u("agents.stopRun","Stop Run")]})})]}),$.map((p,y)=>ve(p,y,!0)),Ce.map((p,y)=>ve(p,$.length+y,!1))]})}function Xa(t,i){const l=Math.floor((i.getTime()-t.getTime())/1e3);return l<60?`${l}s`:l<3600?`${Math.floor(l/60)}m ${l%60}s`:`${Math.floor(l/3600)}h ${Math.floor(l%3600/60)}m`}function en(t){const i=t.title?.trim()||t.description?.trim()||t.id;return i.length>80?`${i.slice(0,77)}...`:i}function tn({agentId:t,projectId:i,addToast:l}){const{t:o}=ke("app"),[s,h]=a.useState([]),[N,n]=a.useState(!0);return a.useEffect(()=>{let g=!1;return n(!0),da(t,i).then(u=>{g||h(u)}).catch(u=>{g||(h([]),l(o("agents.loadTasksFailed","Failed to load assigned tasks: {{error}}",{error:U(u)}),"error"))}).finally(()=>{g||n(!1)}),()=>{g=!0}},[t,i,l]),N?e.jsxs("div",{className:"agent-tasks-empty",children:[e.jsx(G,{size:16,className:"animate-spin"}),e.jsx("p",{children:o("agents.loadingTasks","Loading assigned tasks...")})]}):s.length===0?e.jsxs("div",{className:"agent-tasks-empty",children:[e.jsx(Ss,{size:18}),e.jsx("p",{children:o("agents.noTasksAssigned","No tasks assigned to this agent")})]}):e.jsx("div",{className:"agent-tasks-list",children:s.map(g=>e.jsxs("a",{className:"agent-task-item",href:`/tasks/${g.id}`,children:[e.jsxs("div",{className:"agent-task-row",children:[e.jsx("span",{className:"agent-task-id",children:g.id}),e.jsx("span",{className:`agent-task-column column-${g.column}`,children:{triage:o("board.triage","Triage"),todo:o("board.todo","Todo"),"in-progress":o("board.inProgress","In Progress"),"in-review":o("board.inReview","In Review"),done:o("board.done","Done"),archived:o("board.archived","Archived")}[g.column]??g.column})]}),e.jsx("div",{className:"agent-task-title",title:g.title||g.description||g.id,children:en(g)}),e.jsxs("div",{className:"agent-task-status",children:[g.status??"idle"," · ",o("agents.taskUpdated","Updated {{time}}",{time:Ye(g.updatedAt,o)})]})]},g.id))})}const rt=[{key:"maxRetries",label:"Max Retries",type:"number",placeholder:"3",hint:"Maximum number of automatic retries on task failure (0–10, default 3)",min:0,max:10},{key:"timeoutMs",label:"Task Timeout (ms)",type:"number",placeholder:"600000",hint:"Maximum time in ms before a task is considered timed out (minimum 60000ms, default 600000ms)",min:6e4,max:864e5},{key:"logLevel",label:"Log Level",type:"select",hint:"Verbosity of agent log output",options:[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warning"},{value:"error",label:"Error"}]}];function sn(t){const i={};for(const l of rt){const o=t[l.key]?.trim();if(o){if(l.type==="number"){const s=Number(o);if(Number.isNaN(s)||!Number.isFinite(s)){i[l.key]=`"${l.label}" must be a valid number`;continue}l.min!==void 0&&s<l.min&&(i[l.key]=`"${l.label}" must be at least ${l.min.toLocaleString()}`),l.max!==void 0&&s>l.max&&(i[l.key]=`"${l.label}" must be at most ${l.max.toLocaleString()}`)}if(l.type==="select"){const s=l.options?.map(h=>h.value)??[];s.length>0&&!s.includes(o)&&(i[l.key]=`"${l.label}" must be one of: ${s.join(", ")}`)}}}return i}function an({agent:t,projectId:i,addToast:l,onSaved:o}){const{t:s}=ke("app"),[h,N]=a.useState(t.soul??""),[n,g]=a.useState(!1),[u,j]=a.useState(!1),[c,m]=a.useState(!1),M=a.useRef(null);a.useEffect(()=>{N(t.soul??""),j(!1),m(!1)},[t.id,t.soul]),a.useEffect(()=>()=>{M.current&&clearTimeout(M.current)},[]);const P=h!==(t.soul??""),L=async()=>{if(h.length>1e4){l(s("agents.soulTooLong","Soul must be at most 10,000 characters"),"error");return}g(!0);try{await Sa(t.id,h,i),l(s("agents.soulSaved","Soul saved"),"success"),j(!0),M.current&&clearTimeout(M.current),M.current=setTimeout(()=>j(!1),3e3),await o()}catch(w){l(s("agents.soulSaveFailed","Failed to save soul: {{error}}",{error:U(w)}),"error")}finally{g(!1)}};return e.jsx("div",{className:"config-tab",children:e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:s("agents.soulTitle","Soul")}),e.jsx("p",{className:"config-description",children:s("agents.soulDescription","Define this agent's personality and identity.")}),e.jsx("div",{className:"config-fields",children:e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-soul",children:s("agents.agentSoulLabel","Agent Soul")}),e.jsx("div",{className:"agent-content-toolbar",children:e.jsxs("div",{className:"agent-content-mode-toggle",children:[e.jsxs("button",{className:`btn btn-sm ${c?"":"btn-primary"}`,onClick:()=>m(!1),disabled:!c,"aria-label":s("common.editMode","Edit mode"),children:[e.jsx(ct,{size:14}),s("common.edit","Edit")]}),e.jsxs("button",{className:`btn btn-sm ${c?"btn-primary":""}`,onClick:()=>m(!0),disabled:c,"aria-label":s("common.previewMode","Preview mode"),children:[e.jsx(dt,{size:14}),s("common.preview","Preview")]})]})}),c?h.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(ut,{remarkPlugins:[mt],children:h})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:s("agents.soulEmptyPreview","No soul defined yet. Switch to Edit mode to define the agent's personality.")}):e.jsx("textarea",{id:"agent-soul",className:"input config-textarea-mono",rows:12,placeholder:s("agents.soulPlaceholder","Describe this agent's personality, tone, and behavioral traits..."),value:h,onChange:w=>{N(w.target.value),j(!1)}}),!c&&e.jsx("span",{className:"config-hint",children:s("agents.soulHint","Defines the agent's character and identity. Max 10,000 characters.")})]})}),!c&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!P||n,onClick:()=>void L(),children:n?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:16,className:"animate-spin"}),s("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(ge,{size:16}),s("agents.saveSoul","Save Soul")]})}),!P&&u&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ge,{size:14}),s("agents.soulSaved","Soul saved")]})]})]})})}function nn({agent:t,projectId:i,addToast:l,onSaved:o}){const{t:s}=ke("app"),[h,N]=a.useState(t.memory??""),[n,g]=a.useState(!1),[u,j]=a.useState(!1),[c,m]=a.useState(!1),[M,P]=a.useState(!1),[L,w]=a.useState([]),[X,q]=a.useState(!1),[S,k]=a.useState(""),[R,C]=a.useState(""),[D,T]=a.useState(!1),[V,Z]=a.useState(!1),[I,Q]=a.useState(!1),[F,ae]=a.useState(!1),[A,W]=a.useState(""),x=a.useRef(null),v=a.useRef(null),d=t.state==="running",z=h!==(t.memory??""),$=a.useMemo(()=>L.find(O=>O.path===S),[L,S]),Ce=$?{"long-term":s("agents.memoryLayerLongTermDesc","Curated durable decisions, conventions, constraints, and pitfalls for this specific agent."),daily:s("agents.memoryLayerDailyDesc","Raw daily observations and open loops recorded by this agent."),dreams:s("agents.memoryLayerDreamsDesc","Synthesized patterns and emerging themes distilled from this agent's daily memory.")}[$.layer]??$.layer:s("agents.selectMemoryFile","Select a memory file to view or edit."),de=a.useCallback(async O=>{Z(!0);try{const B=await ma(t.id,O,i);k(B.path),C(B.content),T(!1),ae(!1)}catch(B){l(s("agents.memoryFileLoadFailed","Failed to load agent memory file: {{error}}",{error:U(B)}),"error")}finally{Z(!1)}},[t.id,i,l]),ve=a.useCallback(async(O="")=>{q(!0);try{const{files:B}=await ga(t.id,i);if(w(B),B.length===0){k(""),C(""),T(!1);return}const p=qa(B,O);await de(p)}catch(B){l(s("agents.memoryFilesLoadFailed","Failed to load memory files: {{error}}",{error:U(B)}),"error"),w([]),k(""),C(""),T(!1)}finally{q(!1)}},[t.id,i,l,de]);a.useEffect(()=>{N(t.memory??""),j(!1),m(!1),P(!1),W(""),ae(!1),ve()},[t.id,t.memory,ve]),a.useEffect(()=>()=>{x.current&&clearTimeout(x.current),v.current&&clearTimeout(v.current)},[]);const je=async()=>{if(h.length>5e4){l(s("agents.memoryTooLong","Memory must be at most 50,000 characters"),"error");return}g(!0);try{await Ca(t.id,h,i),l(s("agents.memorySaved","Memory saved"),"success"),j(!0),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>j(!1),3e3),await o()}catch(O){l(s("agents.memorySaveFailed","Failed to save memory: {{error}}",{error:U(O)}),"error")}finally{g(!1)}},ye=async O=>{if(!(!O||O===S)){if(D){W(s("agents.saveBeforeSwitch","Save the current file before switching to another file."));return}W(""),await de(O)}},be=async()=>{if(S){Q(!0);try{await wa(t.id,S,R,i),T(!1),ae(!0),v.current&&clearTimeout(v.current),v.current=setTimeout(()=>ae(!1),3e3),W(""),await ve(S),l(s("agents.memoryFileSaved","Agent memory file saved"),"success"),await o()}catch(O){l(s("agents.memoryFileSaveFailed","Failed to save agent memory file: {{error}}",{error:U(O)}),"error")}finally{Q(!1)}}};return e.jsx("div",{className:"config-tab",children:e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:s("agents.memoryTitle","Agent Memory")}),e.jsx("p",{className:"config-description",children:s("agents.memoryDescription","Store context that belongs to this agent only. Workspace memory, daily notes, dreams, and qmd search live in project settings under Project Memory.")}),d&&e.jsx("p",{className:"config-hint config-hint--block-spacing",children:s("agents.memoryReadOnly","Read-only while this agent is running.")}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-memory",children:s("agents.inlineMemoryLabel","Inline Memory")}),e.jsx("span",{className:"config-hint config-hint--block",children:s("agents.inlineMemoryHint","Short-form memory stored directly on the agent record and injected into prompts.")}),e.jsx("div",{className:"agent-content-toolbar",children:e.jsxs("div",{className:"agent-content-mode-toggle",children:[!d&&e.jsxs("button",{className:`btn btn-sm ${c?"":"btn-primary"}`,onClick:()=>m(!1),disabled:!c,"aria-label":s("common.editMode","Edit mode"),children:[e.jsx(ct,{size:14}),s("common.edit","Edit")]}),e.jsxs("button",{className:`btn btn-sm ${c?"btn-primary":""}`,onClick:()=>m(!0),disabled:c,"aria-label":s("common.previewMode","Preview mode"),children:[e.jsx(dt,{size:14}),s("common.preview","Preview")]})]})}),c?h.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(ut,{remarkPlugins:[mt],children:h})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:s("agents.memoryEmptyPreview","No agent memory defined yet. Switch to Edit mode to add memory content.")}):e.jsx("textarea",{id:"agent-memory","aria-label":s("agents.memoryTitle","Agent Memory"),className:"input config-textarea-mono",rows:10,placeholder:s("agents.memoryPlaceholder","Durable preferences, operating habits, and context this agent should carry across tasks..."),value:h,readOnly:d,onChange:O=>{N(O.target.value),j(!1)}}),!c&&e.jsx("span",{className:"config-hint",children:s("agents.inlineMemoryFieldHint","This is the inline memory field on the agent JSON record. Max 50,000 characters.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-memory-file-select",children:s("agents.memoryFilesLabel","Memory Files")}),e.jsxs("span",{className:"config-hint config-hint--block",children:[s("agents.memoryFilesHint","Full OpenClaw memory files at")," ",e.jsxs("code",{children:["agent/",t.name||t.id,"/memory/"]})," ",s("agents.memoryFilesHintSuffix","(MEMORY.md, DREAMS.md, and daily notes).")]}),e.jsx("select",{id:"agent-memory-file-select",className:"select",value:S,disabled:X||V||I||L.length===0,onChange:O=>{ye(O.target.value)},children:L.length===0?e.jsx("option",{value:"",children:s("agents.noMemoryFiles","No memory files found")}):L.map(O=>{const B={"long-term":s("agents.memoryLayerLongTerm","Long-term"),daily:s("agents.memoryLayerDaily","Daily"),dreams:s("agents.memoryLayerDreams","Dreams")}[O.layer]??O.layer;return e.jsxs("option",{value:O.path,children:[B," • ",O.label]},O.path)})}),X&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(G,{size:14,className:"animate-spin"}),s("agents.loadingMemoryFiles","Loading memory files…")]}),$&&e.jsxs("div",{className:"config-hint config-hint--top-spacing",children:[e.jsx("strong",{children:{"long-term":s("agents.memoryLayerLongTerm","Long-term"),daily:s("agents.memoryLayerDaily","Daily"),dreams:s("agents.memoryLayerDreams","Dreams")}[$.layer]??$.layer})," · ",Ce,e.jsx("br",{}),s("agents.memoryFileMeta","{{size}} bytes · Updated {{time}}",{size:$.size.toLocaleString(),time:Ye($.updatedAt,s)})]}),e.jsx("div",{className:"agent-content-toolbar config-textarea-top-spacing",children:e.jsxs("div",{className:"agent-content-mode-toggle",children:[!d&&e.jsxs("button",{className:`btn btn-sm ${M?"":"btn-primary"}`,onClick:()=>P(!1),disabled:!M,"aria-label":s("agents.memoryFileEditMode","Memory file edit mode"),children:[e.jsx(ct,{size:14}),s("common.edit","Edit")]}),e.jsxs("button",{className:`btn btn-sm ${M?"btn-primary":""}`,onClick:()=>P(!0),disabled:M,"aria-label":s("agents.memoryFilePreviewMode","Memory file preview mode"),children:[e.jsx(dt,{size:14}),s("common.preview","Preview")]})]})}),M?R.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(ut,{remarkPlugins:[mt],children:R})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:s("agents.memoryFileEmptyPreview","No memory file content yet. Switch to Edit mode to add content.")}):e.jsx("textarea",{className:"input config-textarea-mono",rows:14,placeholder:s("agents.memoryFilePlaceholder","Select a memory file to view and edit its content..."),value:R,readOnly:d||!S||V,onChange:O=>{C(O.target.value),T(!0),ae(!1),W("")}}),V&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(G,{size:14,className:"animate-spin"}),s("agents.loadingFileContent","Loading file content…")]}),A&&e.jsx("span",{className:"config-hint config-hint--top-spacing config-hint--block",children:A})]})]}),e.jsxs("div",{className:"config-actions",children:[!c&&e.jsx("button",{className:"btn btn-task-create",disabled:!z||n||d,onClick:()=>void je(),children:n?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:16,className:"animate-spin"}),s("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(ge,{size:16}),s("agents.saveMemory","Save Memory")]})}),!M&&e.jsx("button",{className:"btn",disabled:!D||I||!S||d,onClick:()=>void be(),children:I?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:16,className:"animate-spin"}),s("agents.savingFile","Saving file…")]}):e.jsxs(e.Fragment,{children:[e.jsx(ge,{size:16}),s("agents.saveMemoryFile","Save Memory File")]})}),!z&&u&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ge,{size:14}),s("agents.memorySaved","Memory saved")]}),!D&&F&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ge,{size:14}),s("agents.memoryFileSaved","Memory file saved")]})]})]})})}function rn({agent:t,projectId:i,addToast:l,onSaved:o}){const{t:s}=ke("app"),[h,N]=a.useState(t.instructionsText??""),[n,g]=a.useState(t.instructionsPath??""),[u,j]=a.useState(!1),[c,m]=a.useState(""),[M,P]=a.useState(!1),[L,w]=a.useState(!1),[X,q]=a.useState(!1),[S,k]=a.useState(!1),[R,C]=a.useState(!1),[D,T]=a.useState(!1),V=a.useRef(null),Z=a.useRef(null);a.useEffect(()=>{const A=n.trim();if(!A){m(""),w(!1);return}P(!0),As("project",A).then(W=>{m(W.content),w(!1)}).catch(W=>{const x=U(W);x.includes("ENOENT")||x.includes("Not found")||x.includes("not found")?(m(""),w(!1)):(l(`Failed to load instructions file: ${x}`,"error"),m(""))}).finally(()=>{P(!1)})},[n,l]),a.useEffect(()=>{N(t.instructionsText??""),g(t.instructionsPath??""),C(!1),T(!1),j(!1)},[t.id,t.instructionsText,t.instructionsPath]),a.useEffect(()=>()=>{V.current&&clearTimeout(V.current),Z.current&&clearTimeout(Z.current)},[]);const I=(()=>{const A=h??"",W=t.instructionsText??"",x=n?.trim()??"",v=t.instructionsPath?.trim()??"";return A!==W||x!==v})(),Q=async()=>{q(!0);try{await ka(t.id,{instructionsText:h||void 0,instructionsPath:n.trim()||void 0},i),l(s("agents.instructionsSaved","Instructions saved"),"success"),C(!0),V.current&&clearTimeout(V.current),V.current=setTimeout(()=>C(!1),3e3),await o()}catch(A){l(s("agents.instructionsSaveFailed","Failed to save instructions: {{error}}",{error:U(A)}),"error")}finally{q(!1)}},F=async()=>{const A=n.trim();if(!A){l(s("agents.noInstructionsPath","No instructions file path set"),"error");return}k(!0);try{await Ps("project",A,c),l(s("agents.instructionsFileSaved","Instructions file saved"),"success"),w(!1),T(!0),Z.current&&clearTimeout(Z.current),Z.current=setTimeout(()=>T(!1),3e3),await o()}catch(W){l(s("agents.instructionsFileSaveFailed","Failed to save instructions file: {{error}}",{error:U(W)}),"error")}finally{k(!1)}},ae=!!n.trim();return e.jsxs("div",{className:"config-tab",children:[e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:s("agents.instructionsTitle","Custom Instructions")}),e.jsx("p",{className:"config-description",children:s("agents.instructionsDescription","Append custom instructions to this agent's system prompt at execution time. Use this to customize behavior, coding style, or project conventions without modifying built-in prompts.")}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"instructions-text",children:"Inline Instructions"}),e.jsx("div",{className:"agent-content-toolbar",children:e.jsxs("div",{className:"agent-content-mode-toggle",children:[e.jsxs("button",{className:`btn btn-sm ${u?"":"btn-primary"}`,onClick:()=>j(!1),disabled:!u,"aria-label":s("common.editMode","Edit mode"),"data-testid":"instructions-edit-toggle",children:[e.jsx(ct,{size:14}),s("common.edit","Edit")]}),e.jsxs("button",{className:`btn btn-sm ${u?"btn-primary":""}`,onClick:()=>j(!0),disabled:u,"aria-label":s("common.previewMode","Preview mode"),"data-testid":"instructions-preview-toggle",children:[e.jsx(dt,{size:14}),s("common.preview","Preview")]})]})}),u?h.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(ut,{remarkPlugins:[mt],children:h})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:s("agents.instructionsEmptyPreview","No inline instructions defined yet. Switch to Edit mode to add instructions.")}):e.jsx("textarea",{id:"instructions-text",className:"input",rows:10,placeholder:s("agents.instructionsPlaceholder","Enter custom instructions to append to this agent's system prompt..."),value:h,onChange:A=>{N(A.target.value),C(!1)}}),!u&&e.jsx("span",{className:"config-hint",children:s("agents.instructionsHint","Markdown formatting supported. Max 50,000 characters.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"instructions-path",children:s("agents.instructionsPathLabel","Instructions File Path")}),e.jsx("input",{id:"instructions-path",type:"text",className:"input",placeholder:s("agents.instructionsPathPlaceholder","e.g., .fusion/agents/my-agent-instructions.md"),value:n,onChange:A=>{g(A.target.value),C(!1)}}),e.jsx("span",{className:"config-hint",children:s("agents.instructionsPathHint","Path to a .md file (relative to project root). Contents are read and appended at execution time.")})]})]}),!u&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!I||X,onClick:()=>void Q(),children:X?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:16,className:"animate-spin"}),s("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(ge,{size:16}),s("agents.saveInstructions","Save Instructions")]})}),!I&&R&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ge,{size:14}),s("agents.instructionsSaved","Instructions saved")]})]})]}),ae&&e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:s("agents.instructionsFileEditorTitle","Instructions File Editor")}),e.jsx("p",{className:"config-description",children:s("agents.instructionsFileEditorDesc","Edit the instructions file directly. Changes are saved separately from the path configuration.")}),e.jsx("div",{className:"config-fields",children:e.jsxs("div",{className:"config-field",children:[e.jsxs("div",{className:"config-inline-header",children:[e.jsx("label",{htmlFor:"instructions-file-content",children:s("agents.fileContentLabel","File Content")}),M&&e.jsxs("span",{className:"config-hint config-hint--inline-tight",children:[e.jsx(G,{size:12,className:"animate-spin"}),s("common.loading","Loading...")]}),L&&!M&&e.jsx("span",{className:"config-hint config-hint--warning",children:s("common.unsavedChanges","Unsaved changes")})]}),e.jsx("textarea",{id:"instructions-file-content",className:"input config-textarea-mono",rows:20,placeholder:s("agents.fileContentPlaceholder","File content will appear here when loaded..."),value:c,readOnly:M,onChange:A=>{m(A.target.value),w(!0),T(!1)}}),e.jsx("span",{className:"config-hint",children:s("agents.fileContentHint","Edit the markdown file content directly. Save separately using the button below.")})]})}),e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!L||S,onClick:()=>void F(),children:S?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:16,className:"animate-spin"}),s("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(ge,{size:16}),s("agents.saveFile","Save File")]})}),!L&&D&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ge,{size:14}),s("agents.fileSaved","File saved")]})]})]})]})}function us(t){const i=t??{},l={};return i.heartbeatIntervalMs!==void 0&&i.heartbeatIntervalMs!==null&&(l.heartbeatIntervalMs=String(Number(i.heartbeatIntervalMs)/1e3)),i.heartbeatTimeoutMs!==void 0&&i.heartbeatTimeoutMs!==null&&(l.heartbeatTimeoutMs=String(Number(i.heartbeatTimeoutMs)/1e3)),i.maxConcurrentRuns!==void 0&&i.maxConcurrentRuns!==null&&(l.maxConcurrentRuns=String(i.maxConcurrentRuns)),(i.messageResponseMode==="immediate"||i.messageResponseMode==="on-heartbeat")&&(l.messageResponseMode=i.messageResponseMode),i.autoClaimCandidatesInPrompt!==void 0&&i.autoClaimCandidatesInPrompt!==null&&(l.autoClaimCandidatesInPrompt=String(i.autoClaimCandidatesInPrompt)),l}function Ht(t){return t?.enabled!==!1}function It(t){return t?.autoClaimRelevantTasks!==!1}function Bt(t){return t?.runMissedHeartbeatOnStartup===!0}function $t(t){return t?.allowParallelExecution!==!1}function Ot(t){return t?.skipHeartbeatWhenIdle===!0}function _t(t){const i=t?.heartbeatScopeDiscipline;return i==="strict"||i==="lite"||i==="off"?i:""}function ms(t){const i=t?.heartbeatPromptTemplate;return i==="default"||i==="compact"?i:""}function gs(t){const i=(t??{}).budgetConfig,l={};return i&&(i.tokenBudget!==void 0&&i.tokenBudget!==null&&(l.tokenBudget=String(i.tokenBudget)),i.usageThreshold!==void 0&&i.usageThreshold!==null&&(l.usageThreshold=String(Number(i.usageThreshold)*100)),i.budgetPeriod!==void 0&&i.budgetPeriod!==null&&(l.budgetPeriod=String(i.budgetPeriod)),i.resetDay!==void 0&&i.resetDay!==null&&(l.resetDay=String(i.resetDay))),l}function ln({agent:t,projectId:i,addToast:l,onSaved:o}){const{t:s}=ke("app"),[h,N]=a.useState(!1),[n,g]=a.useState(!1),[u,j]=a.useState(!1),[c,m]=a.useState(!1),[M,P]=a.useState(!1),[L,w]=a.useState(""),[X,q]=a.useState(!1),[S,k]=a.useState(null),[R,C]=a.useState(!1),D=a.useRef(null),T=t.heartbeatProcedurePath?.trim(),V=`.fusion/agents/${t.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||t.id.toLowerCase().replace(/[^a-z0-9]+/g,"-")||"agent"}-${t.id.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"agent"}/HEARTBEAT.md`,Z=`.fusion/agents/${t.id}/HEARTBEAT.md`,I=t.id.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"agent",Q=!!(T&&(T===V||T===Z||new RegExp(`^\\.fusion/agents/[^/]+-${I}/HEARTBEAT\\.md$`).test(T))),F=!!T,ae=a.useCallback(async v=>{j(!0),k(null);try{const d=await As("project",v,i);w(d.content),q(!1)}catch(d){const z=U(d);k(z),l(s("agents.heartbeatFileLoadFailed","Failed to load heartbeat procedure file: {{error}}",{error:z}),"error")}finally{j(!1)}},[l,i]);a.useEffect(()=>{g(!1),P(!1),w(""),q(!1),k(null),j(!1),m(!1),C(!1)},[t.id,T]),a.useEffect(()=>()=>{D.current&&clearTimeout(D.current)},[]);const A=async()=>{T&&(g(!0),await ae(T))},W=async()=>{if(T){m(!0);try{await Ps("project",T,L,i),q(!1),C(!0),l(s("agents.heartbeatFileSaved","Heartbeat procedure file saved"),"success"),D.current&&clearTimeout(D.current),D.current=setTimeout(()=>C(!1),3e3),await o()}catch(v){l(s("agents.heartbeatFileSaveFailed","Failed to save heartbeat procedure file: {{error}}",{error:U(v)}),"error")}finally{m(!1)}}},x=async()=>{N(!0);try{const v=await Fa(t.id,i);l(v.procedureFileSeeded?s("agents.heartbeatProcedureFileReady","Heartbeat procedure file ready at {{path}}",{path:v.heartbeatProcedurePath}):s("agents.heartbeatProcedurePathSet","Heartbeat procedure path set to {{path}}",{path:v.heartbeatProcedurePath}),"success"),await o()}catch(v){l(s("agents.heartbeatUpgradeFailed","Failed to upgrade heartbeat procedure: {{error}}",{error:U(v)}),"error")}finally{N(!1)}};return e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:s("agents.heartbeatProcedureTitle","Heartbeat Procedure")}),e.jsxs("p",{className:"config-description",children:[s("agents.heartbeatProcedureDesc","The per-tick procedure this agent runs every wake. Defaults to a per-agent markdown file (for example")," ",e.jsx("code",{children:".fusion/agents/ceo-agent2736/HEARTBEAT.md"}),s("agents.heartbeatProcedureDescSuffix",") that you can edit. Legacy id-only default paths remain valid. Resets on every tick — no need to restart the agent after editing.")]}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsxs("span",{className:"config-hint",children:[s("agents.currentPath","Current path:")," ",e.jsx("code",{children:T||s("agents.noneUsingBuiltIn","(none — using built-in default)")})]}),F&&e.jsx("div",{className:"heartbeat-procedure-actions",children:e.jsx("button",{className:"btn btn-sm",onClick:()=>void A(),disabled:u,children:u?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:16,className:"animate-spin"}),s("agents.loadingFile","Loading file…")]}):e.jsxs(e.Fragment,{children:[e.jsx(ot,{size:16}),s("agents.viewHeartbeatMarkdown","View Heartbeat Markdown")]})})})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("button",{className:"btn",disabled:h||Q,onClick:()=>void x(),"aria-label":s("agents.upgradeToDefaultAriaLabel","Upgrade agent to default heartbeat procedure file"),children:h?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:16,className:"animate-spin"}),s("agents.upgrading","Upgrading…")]}):Q?e.jsxs(e.Fragment,{children:[e.jsx(ge,{size:16}),s("agents.alreadyOnDefault","Already on default")]}):s("agents.upgradeToDefault","Upgrade to Default Heartbeat Procedure")}),e.jsxs("span",{className:"config-hint",children:[s("agents.upgradeHint","Sets")," ",e.jsx("code",{children:"heartbeatProcedurePath"})," ",s("agents.upgradeHintTo","to")," ",e.jsx("code",{children:V})," ",s("agents.upgradeHintSuffix","and seeds the file from the built-in template if it doesn't exist. Each agent gets its own per-agent file, so edits stay scoped to this agent. Operator edits to the file are preserved.")]})]})]}),n&&F&&T&&e.jsxs("div",{className:"config-fields heartbeat-procedure-viewer",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"heartbeat-procedure-file-content",children:s("agents.heartbeatProcedureFileLabel","Heartbeat Procedure File")}),e.jsxs("div",{className:"agent-content-toolbar",children:[e.jsxs("div",{className:"agent-content-mode-toggle",children:[e.jsxs("button",{className:`btn btn-sm ${M?"":"btn-primary"}`,onClick:()=>P(!1),disabled:!M,"aria-label":s("agents.heartbeatFileEditMode","Heartbeat file edit mode"),children:[e.jsx(ct,{size:14}),s("common.edit","Edit")]}),e.jsxs("button",{className:`btn btn-sm ${M?"btn-primary":""}`,onClick:()=>P(!0),disabled:M,"aria-label":s("agents.heartbeatFilePreviewMode","Heartbeat file preview mode"),children:[e.jsx(dt,{size:14}),s("common.preview","Preview")]})]}),u&&e.jsxs("span",{className:"config-hint heartbeat-procedure-status",children:[e.jsx(G,{size:12,className:"animate-spin"}),s("common.loading","Loading...")]}),X&&!u&&e.jsx("span",{className:"config-hint heartbeat-procedure-status heartbeat-procedure-status--warning",children:s("common.unsavedChanges","Unsaved changes")})]}),M?L.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(ut,{remarkPlugins:[mt],children:L})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:s("agents.heartbeatFileEmptyPreview","No heartbeat procedure markdown content yet.")}):e.jsx("textarea",{id:"heartbeat-procedure-file-content",className:"input",rows:16,value:L,readOnly:u,placeholder:s("agents.heartbeatFilePlaceholder","Heartbeat procedure markdown file content will appear here..."),onChange:v=>{w(v.target.value),q(!0),C(!1)}}),S&&e.jsx("span",{className:"config-error",children:s("agents.fileLoadError","Failed to load file: {{error}}",{error:S})}),e.jsxs("span",{className:"config-hint",children:[s("agents.heartbeatFileEditorHint","This editor writes directly to")," ",e.jsx("code",{children:T}),"."]})]}),!M&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!X||c||u,onClick:()=>void W(),children:c?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:16,className:"animate-spin"}),s("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(ge,{size:16}),s("agents.saveHeartbeatFile","Save Heartbeat File")]})}),!X&&R&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ge,{size:14}),s("agents.fileSaved","File saved")]})]})]})]})}function on({agent:t,projectId:i,addToast:l,onSaved:o,onHasChangesChange:s,onDelete:h,onAgentDraftApplied:N}){const{t:n}=ke("app"),[g,u]=a.useState(t.name),[j,c]=a.useState(t.role),[m,M]=a.useState(t.title??""),[P,L]=a.useState(t.icon??""),[w,X]=a.useState(t.reportsTo??""),[q,S]=a.useState([]),[k,R]=a.useState(!1),[C,D]=a.useState(!1),[T,V]=a.useState(!1),Z=a.useRef(null),[I,Q]=a.useState(()=>{const r={};for(const f of rt){const E=t.metadata[f.key];E!=null&&(r[f.key]=String(E))}return r}),[F,ae]=a.useState(()=>us(t.runtimeConfig)),[A,W]=a.useState(()=>Ht(t.runtimeConfig)),[x,v]=a.useState(()=>It(t.runtimeConfig)),[d,z]=a.useState(()=>Bt(t.runtimeConfig)),[$,Ce]=a.useState(()=>$t(t.runtimeConfig)),[de,ve]=a.useState(()=>Ot(t.runtimeConfig)),[je,ye]=a.useState(()=>_t(t.runtimeConfig)),[be,O]=a.useState(()=>ms(t.runtimeConfig)),[B,p]=a.useState(()=>gs(t.runtimeConfig)),[y,ie]=a.useState(t.bundleConfig?.mode??""),[he,We]=a.useState(t.bundleConfig?.entryFile??"AGENTS.md"),[Ee,Me]=a.useState(t.bundleConfig?.externalPath??""),[ce,Le]=a.useState(t.bundleConfig?.files??[]),[te,Ze]=a.useState(Array.isArray(t.metadata?.skills)?t.metadata.skills:[]),{favoriteProviders:gt,favoriteModels:we,toggleFavoriteProvider:ht,toggleFavoriteModel:Qe}=ha(),[At,Xe]=a.useState([]),[Ie,Fe]=a.useState(!1),[et,tt]=a.useState([]),[Je,ft]=a.useState(!1),$e=(()=>{const r=t.runtimeConfig??{};return r.modelProvider&&r.modelId?`${r.modelProvider}/${r.modelId}`:typeof r.model=="string"&&r.model.includes("/")?r.model:""})(),Ae=typeof t.runtimeConfig?.runtimeHint=="string"?t.runtimeConfig.runtimeHint:"",[re,Oe]=a.useState(Ae?"runtime":"model"),[Ne,_e]=a.useState($e),[b,H]=a.useState(Ae),[J,_]=a.useState(t.permissionPolicy),[se,fe]=a.useState(void 0),Se=w.trim(),De=a.useMemo(()=>q.filter(r=>r.id!==t.id),[q,t.id]),st=!!Se&&!De.some(r=>r.id===Se),bt=a.useMemo(()=>({name:g,role:j,title:m||void 0,instructionsText:t.instructionsText,soul:t.soul,memory:t.memory,reportsTo:w||void 0,skills:te,model:Ne||void 0,runtimeHint:re==="runtime"&&b||void 0,thinkingLevel:I.thinkingLevel??void 0,maxTurns:I.maxTurns?Number(I.maxTurns):void 0,heartbeatIntervalMs:F.heartbeatIntervalMs?Number(F.heartbeatIntervalMs)*1e3:void 0,heartbeatTimeoutMs:F.heartbeatTimeoutMs?Number(F.heartbeatTimeoutMs)*1e3:void 0,maxConcurrentRuns:F.maxConcurrentRuns?Number(F.maxConcurrentRuns):void 0,messageResponseMode:F.messageResponseMode}),[t.instructionsText,t.memory,t.soul,I.maxTurns,I.thinkingLevel,F.heartbeatIntervalMs,F.heartbeatTimeoutMs,F.maxConcurrentRuns,F.messageResponseMode,Ne,g,w,j,re,b,te,m]),Pt=a.useCallback(r=>{u(r.name),c(r.role),M(r.title??""),L(r.icon??""),X(r.reportsTo??""),r.skills&&Ze(r.skills),r.thinkingLevel&&Q(E=>({...E,thinkingLevel:r.thinkingLevel})),r.maxTurns!==void 0&&Q(E=>({...E,maxTurns:String(r.maxTurns)})),r.runtimeHint!==void 0?(Oe("runtime"),H(r.runtimeHint??""),r.runtimeHint&&_e("")):r.model!==void 0&&(Oe("model"),_e(r.model??""),H(""));const f=Object.fromEntries(Object.entries({name:r.name,role:r.role,title:r.title,icon:r.icon,reportsTo:r.reportsTo,instructionsText:r.instructionsText,soul:r.soul,memory:r.memory}).filter(([,E])=>E!==void 0));N?.(f),V(!1),l(n("agents.interviewDraftApplied","Interview draft applied. Review and save when ready."),"success")},[l,N]);a.useEffect(()=>{_(t.permissionPolicy)},[t.permissionPolicy]),a.useEffect(()=>{fa(i).then(r=>fe(r.project?.defaultAgentPermissionPolicy?.rules)).catch(()=>fe(void 0))},[i]);const pt=async r=>{_(r);try{await ls(t.id,{permissionPolicy:r},i),await o(),l(n("agents.permissionPolicyUpdated","Permission policy updated"),"success")}catch(f){l(n("agents.permissionPolicyFailed","Failed to update permission policy: {{error}}",{error:U(f)}),"error")}};a.useEffect(()=>{let r=!1;return R(!0),wt(void 0,i).then(f=>{r||S(f)}).catch(()=>{r||S([])}).finally(()=>{r||R(!1)}),()=>{r=!0}},[i]),a.useEffect(()=>{Fe(!0),ba().then(r=>{Xe(r.models)}).catch(()=>{}).finally(()=>Fe(!1))},[]),a.useEffect(()=>{ft(!0),ws(i).then(tt).catch(()=>tt([])).finally(()=>ft(!1))},[i]);const[Pe,ue]=a.useState(null),[Ue,xt]=a.useState(!1);a.useEffect(()=>{Ut(t.id,i).then(ue).catch(()=>ue(null))},[t.id,i]);const Ts=async()=>{xt(!0);try{await Ra(t.id,i),l(n("agents.budgetResetSuccess","Budget usage reset successfully"),"success");const r=await Ut(t.id,i);ue(r)}catch(r){l(n("agents.budgetResetFailed","Failed to reset budget: {{error}}",{error:U(r)}),"error")}finally{xt(!1)}},[Be,Gt]=a.useState(!1),[K,Ve]=a.useState({}),[Es,qe]=a.useState(!1),[Tt,vt]=a.useState(null),Kt=t.state==="idle"||t.state==="paused",at=a.useRef(null),Yt=a.useRef(null),Zt=a.useRef(null),jt=a.useRef(0);a.useEffect(()=>()=>{at.current&&clearTimeout(at.current)},[]);const Re=(()=>{if(g!==t.name||j!==t.role||m!==(t.title??"")||P!==(t.icon??"")||w!==(t.reportsTo??"")||y!==(t.bundleConfig?.mode??"")||he!==(t.bundleConfig?.entryFile??"AGENTS.md")||Ee!==(t.bundleConfig?.externalPath??"")||JSON.stringify(ce)!==JSON.stringify(t.bundleConfig?.files??[]))return!0;for(const ee of rt){const pe=I[ee.key]?.trim()??"",xe=t.metadata[ee.key]!==void 0&&t.metadata[ee.key]!==null?String(t.metadata[ee.key]):"";if(pe!==xe)return!0}const r=t.runtimeConfig??{};if(A!==Ht(t.runtimeConfig)||x!==It(t.runtimeConfig)||d!==Bt(t.runtimeConfig)||$!==$t(t.runtimeConfig)||de!==Ot(t.runtimeConfig)||je!==_t(t.runtimeConfig)||be!==ms(t.runtimeConfig))return!0;for(const ee of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns","messageResponseMode","autoClaimCandidatesInPrompt"]){const pe=F[ee]?.trim()??"";let xe=r[ee]!==void 0&&r[ee]!==null?String(r[ee]):"";if((ee==="heartbeatIntervalMs"||ee==="heartbeatTimeoutMs")&&xe&&(xe=String(Number(xe)/1e3)),pe!==xe)return!0}const f=r.budgetConfig;for(const ee of["tokenBudget","budgetPeriod","resetDay"]){const pe=B[ee]?.trim()??"",xe=f?.[ee]!==void 0&&f?.[ee]!==null?String(f[ee]):"";if(pe!==xe)return!0}const E=B.usageThreshold?.trim()??"",ne=f?.usageThreshold!==void 0&&f?.usageThreshold!==null?String(Number(f.usageThreshold)*100):"";if(E!==ne)return!0;const Te=Array.isArray(t.metadata?.skills)?t.metadata.skills:[];return JSON.stringify(te)!==JSON.stringify(Te)||re!==(Ae?"runtime":"model")||Ne!==$e||b!==Ae})(),Qt=a.useRef(null);a.useEffect(()=>{s&&Qt.current!==Re&&(Qt.current=Re,s(Re))},[Re,s]),a.useEffect(()=>()=>{s?.(!1)},[s]),a.useEffect(()=>{const r={id:t.id,updatedAt:t.updatedAt},f=Yt.current;(!f||f.id!==r.id||f.updatedAt!==r.updatedAt)&&(Re||(Yt.current=r,ae(us(t.runtimeConfig)),W(Ht(t.runtimeConfig)),v(It(t.runtimeConfig)),z(Bt(t.runtimeConfig)),Ce($t(t.runtimeConfig)),ve(Ot(t.runtimeConfig)),ye(_t(t.runtimeConfig)),p(gs(t.runtimeConfig)),_e($e),H(Ae),Oe(Ae?"runtime":"model")))},[t,Re,$e,Ae]);const Xt=(r,f)=>{Q(E=>({...E,[r]:f})),qe(!1),K[r]&&Ve(E=>{const ne={...E};return delete ne[r],ne})},yt=(r,f)=>{ae(E=>({...E,[r]:f})),qe(!1),K[r]&&Ve(E=>{const ne={...E};return delete ne[r],ne})},Ls=r=>{W(r),qe(!1)},Nt=(r,f)=>{p(E=>({...E,[r]:f})),qe(!1),K[r]&&Ve(E=>{const ne={...E};return delete ne[r],ne})},ze=a.useMemo(()=>{const r=sn(I);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 He=F[Y]?.trim();if(!He)continue;const Ge=Number(He);Number.isNaN(Ge)||!Number.isFinite(Ge)?r[Y]=`"${le.label}" must be a valid number`:Ge<le.min&&(r[Y]=`"${le.label}" must be at least ${le.min.toLocaleString()}`)}const f=F.autoClaimCandidatesInPrompt?.trim();if(f){const Y=Number(f);(!Number.isInteger(Y)||Y<0||Y>10)&&(r.autoClaimCandidatesInPrompt='"Auto-claim candidates in prompt" must be an integer between 0 and 10')}const E=F.messageResponseMode?.trim();E&&!["immediate","on-heartbeat"].includes(E)&&(r.messageResponseMode='"Message Response Mode" must be either immediate or on-heartbeat');const ne=B.tokenBudget?.trim();if(ne){const Y=Number(ne);Number.isNaN(Y)||!Number.isFinite(Y)?r.tokenBudget='"Token Budget" must be a valid number':Y<=0&&(r.tokenBudget='"Token Budget" must be greater than 0')}const Te=B.usageThreshold?.trim();if(Te){const Y=Number(Te);Number.isNaN(Y)||!Number.isFinite(Y)?r.usageThreshold='"Usage Threshold" must be a valid number':(Y<1||Y>100)&&(r.usageThreshold='"Usage Threshold" must be between 1 and 100')}const ee=B.budgetPeriod?.trim();ee&&!["daily","weekly","monthly","lifetime"].includes(ee)&&(r.budgetPeriod='"Budget Period" must be one of: daily, weekly, monthly, lifetime');const pe=B.resetDay?.trim(),xe=ee||"lifetime";if(pe){const Y=Number(pe);Number.isNaN(Y)||!Number.isFinite(Y)?r.resetDay='"Reset Day" must be a valid number':xe==="weekly"?(Y<0||Y>6||!Number.isInteger(Y))&&(r.resetDay='"Reset Day" must be between 0 (Sunday) and 6 (Saturday) for weekly period'):xe==="monthly"&&(Y<1||Y>31||!Number.isInteger(Y))&&(r.resetDay='"Reset Day" must be between 1 and 31 for monthly period')}return r},[I,F,B]),es=a.useCallback(()=>{if(Object.keys(ze).length>0)return null;const r={...t.metadata};for(const le of rt){const He=I[le.key]?.trim();He?le.type==="number"?r[le.key]=Number(He):r[le.key]=He:delete r[le.key]}te.length>0?r.skills=te:delete r.skills;const f={...t.runtimeConfig};f.enabled=A,f.autoClaimRelevantTasks=x,f.runMissedHeartbeatOnStartup=d,f.allowParallelExecution=$,f.skipHeartbeatWhenIdle=de;for(const le of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns","autoClaimCandidatesInPrompt"]){const He=F[le]?.trim();if(!He)delete f[le];else{const Ge=Number(He);f[le]=le==="maxConcurrentRuns"||le==="autoClaimCandidatesInPrompt"?Ge:Ge*1e3}}const E=F.messageResponseMode?.trim();if(E?f.messageResponseMode=E:delete f.messageResponseMode,je?f.heartbeatScopeDiscipline=je:delete f.heartbeatScopeDiscipline,be?f.heartbeatPromptTemplate=be:delete f.heartbeatPromptTemplate,re==="runtime")b.trim()?f.runtimeHint=b.trim():delete f.runtimeHint,delete f.modelProvider,delete f.modelId,delete f.model;else if(delete f.runtimeHint,Ne.trim()){const le=Ne.indexOf("/");le!==-1&&(f.modelProvider=Ne.slice(0,le),f.modelId=Ne.slice(le+1),f.model=Ne.trim())}else delete f.modelProvider,delete f.modelId,delete f.model;const ne={},Te=B.tokenBudget?.trim(),ee=B.usageThreshold?.trim(),pe=B.budgetPeriod?.trim(),xe=B.resetDay?.trim();Te&&(ne.tokenBudget=Number(Te)),ee&&(ne.usageThreshold=Number(ee)/100),pe&&(ne.budgetPeriod=pe),xe&&(ne.resetDay=Number(xe)),Object.keys(ne).length>0?f.budgetConfig=ne:delete f.budgetConfig;let Y;return y&&(Y={mode:y,entryFile:he||"AGENTS.md",files:ce.length>0?ce:["AGENTS.md"]},y==="external"&&Ee.trim()&&(Y.externalPath=Ee.trim())),{name:g.trim()||void 0,role:j,title:m.trim()||void 0,icon:P.trim()||void 0,reportsTo:w.trim()||void 0,metadata:r,runtimeConfig:f,bundleConfig:Y}},[t.metadata,t.runtimeConfig,$,x,B,he,Ee,ce,y,I,A,be,je,F,P,Ne,g,w,j,d,re,b,te,de,m,ze]),nt=a.useCallback(async(r,f)=>{const E=es();if(!E)return Ve(ze),r&&l(n("agents.fixValidationErrors","Please fix validation errors before saving"),"error"),f==="auto"&&vt(n("agents.fixValidationToSave","Fix validation errors to save changes")),!1;const ne=JSON.stringify(E);if(ne===Zt.current)return!1;const Te=++jt.current;Ve({}),vt(null),Gt(!0);try{return await ls(t.id,E,i),Te!==jt.current?!1:(Zt.current=ne,f==="manual"&&l(n("agents.settingsSaved","Settings saved"),"success"),vt(null),qe(!0),at.current&&clearTimeout(at.current),at.current=setTimeout(()=>qe(!1),3e3),await o(),!0)}catch(ee){if(Te===jt.current){const pe=U(ee);vt(pe),l(n("agents.settingsSaveFailed","Failed to save settings: {{error}}",{error:pe}),"error")}return!1}finally{Te===jt.current&&Gt(!1)}},[l,t.id,es,o,i,ze]),Ds=async()=>{await nt(!0,"manual")},me=a.useCallback(()=>{if(!(!Re||Be)){if(Object.keys(ze).length>0){Ve(ze);return}nt(!1,"auto")}},[Re,Be,nt,ze]);a.useEffect(()=>{if(!Re||Be)return;if(Object.keys(ze).length>0){Ve(ze);return}const r=setTimeout(()=>{nt(!1,"auto")},Ja);return()=>clearTimeout(r)},[Re,Be,nt,ze]);const zs=a.useCallback(async r=>{D(!0);try{await pa(t.id,r,i),await o(),l(n("agents.avatarUploaded","Avatar uploaded"),"success")}catch(f){l(U(f),"error")}finally{D(!1),Z.current&&(Z.current.value="")}},[l,t.id,o,i]),Hs=a.useCallback(async()=>{D(!0);try{await xa(t.id,i),await o(),l(n("agents.avatarRemoved","Avatar removed"),"success")}catch(r){l(U(r),"error")}finally{D(!1)}},[l,t.id,o,i]),ts=Be?n("agents.savingChanges","Saving changes…"):Tt?n("agents.saveFailed","Save failed: {{error}}",{error:Tt}):!Re&&Es?n("agents.allChangesSaved","All changes saved"):null;return e.jsxs("div",{className:"config-tab",children:[e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:n("agents.configTitle","Agent Configuration")}),e.jsx("p",{className:"config-description",children:n("agents.configDescription","Configure agent settings and behavior.")}),e.jsx("div",{className:"config-actions-row",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>V(!0),children:n("agents.aiInterview","AI Interview")})}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-name",children:n("agents.nameLabel","Name")}),e.jsx("input",{id:"agent-name",type:"text",className:"input",value:g,onChange:r=>u(r.target.value),onBlur:()=>{me()}})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-role",children:n("agents.roleLabel2","Role")}),e.jsxs("select",{id:"agent-role",className:"select",value:j,onChange:r=>{c(r.target.value),me()},children:[e.jsx("option",{value:"triage",children:n("agents.roleTriage","Triage")}),e.jsx("option",{value:"executor",children:n("agents.roleExecutor","Executor")}),e.jsx("option",{value:"reviewer",children:n("agents.roleReviewer","Reviewer")}),e.jsx("option",{value:"merger",children:n("agents.roleMerger","Merger")}),e.jsx("option",{value:"scheduler",children:n("agents.roleScheduler","Scheduler")}),e.jsx("option",{value:"custom",children:n("agents.roleCustom","Custom")})]})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-title",children:n("agents.titleLabel","Title")}),e.jsx("input",{id:"agent-title",type:"text",className:"input",placeholder:n("agents.titlePlaceholder","e.g. Senior Code Reviewer"),value:m,onChange:r=>M(r.target.value),onBlur:()=>{me()}})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{children:n("agents.avatarLabel","Avatar")}),e.jsxs("div",{className:"agent-avatar-editor",children:[e.jsx(ys,{agent:t,size:64,className:"agent-avatar-editor-preview"}),e.jsxs("div",{className:"agent-avatar-editor-actions",children:[e.jsx("input",{ref:Z,id:"agent-avatar-upload",type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",className:"visually-hidden",disabled:C,onChange:r=>{const f=r.target.files?.[0];f&&zs(f)}}),e.jsx("button",{type:"button",className:"btn btn-sm",disabled:C,onClick:()=>Z.current?.click(),children:n("agents.uploadAvatar","Upload Avatar")}),t.imageUrl?e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void Hs(),disabled:C,children:n("agents.removeAvatar","Remove Avatar")}):null]})]})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-icon",children:n("agents.iconLabel","Icon")}),e.jsx("input",{id:"agent-icon",type:"text",className:"input",placeholder:n("agents.iconPlaceholder","e.g. 🤖"),value:P,onChange:r=>L(r.target.value),onBlur:()=>{me()}})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-reports-to",children:n("agents.reportsToLabel","Reports To")}),e.jsxs("select",{id:"agent-reports-to",className:"select",value:w,onChange:r=>{X(r.target.value),me()},disabled:k,children:[e.jsx("option",{value:"",children:n("agents.noManager","No manager")}),st&&e.jsx("option",{value:Se,children:n("agents.unknownManager","Unknown manager ({{id}})",{id:Se})}),De.map(r=>e.jsxs("option",{value:r.id,children:[r.name," (",r.id,")"]},r.id))]})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:n("agents.skillsTitle","Skills")}),e.jsx("p",{className:"config-description",children:n("agents.skillsDescription","Assign skills to this agent for specialized behavior.")}),e.jsx("div",{className:"config-fields",children:e.jsx("div",{className:"config-field",children:e.jsx(Aa,{id:"agent-skills",label:"Skills",value:te,onChange:r=>{Ze(r),me()},projectId:i})})})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:n("agents.modelTitle","Model")}),e.jsx("p",{className:"config-description",children:n("agents.modelDescription","Choose either a built-in model or a plugin runtime for this agent. These options are mutually exclusive.")}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{children:n("agents.runtimeSource","Runtime Source")}),e.jsxs("div",{className:"config-runtime-tabs",role:"tablist","aria-label":n("agents.runtimeSource","Runtime source"),children:[e.jsx("button",{type:"button",className:`config-runtime-tab${re==="model"?" active":""}`,role:"tab","aria-selected":re==="model",tabIndex:re==="model"?0:-1,onClick:()=>{Oe("model"),H(""),me()},children:n("agents.builtInModel","Built-in Model")}),e.jsx("button",{type:"button",className:`config-runtime-tab${re==="runtime"?" active":""}`,role:"tab","aria-selected":re==="runtime",tabIndex:re==="runtime"?0:-1,onClick:()=>{Oe("runtime"),me()},children:n("agents.pluginRuntime","Plugin Runtime")})]})]}),re==="model"?e.jsx("div",{className:"config-field",children:e.jsx(va,{models:At,value:Ne,onChange:r=>{_e(r),me()},placeholder:n("agents.useGlobalDefault","Use global default"),label:n("agents.agentModelLabel","Agent Model"),disabled:Ie,favoriteProviders:gt,onToggleFavorite:ht,favoriteModels:we,onToggleModelFavorite:Qe})}):e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-runtime-hint",children:n("agents.runtimeLabel","Runtime")}),Je?e.jsx("span",{className:"config-hint",children:n("agents.loadingRuntimes","Loading runtimes…")}):e.jsxs("select",{id:"agent-runtime-hint",className:"select",value:b,onChange:r=>{H(r.target.value),me()},children:[e.jsx("option",{value:"",children:et.length>0?n("agents.selectRuntime","Select a plugin runtime…"):n("agents.noRuntimes","No plugin runtimes available")}),et.map(r=>e.jsx("option",{value:r.runtimeId,children:r.description?`${r.name} — ${r.description}`:r.name},`${r.pluginId}:${r.runtimeId}`))]})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:n("agents.permissionsTitle","Permissions")}),e.jsx("p",{className:"config-description",children:n("agents.permissionsDescription","Per-agent settings override project defaults. Each category controls a separate approval gate.")}),J===void 0?e.jsxs("div",{className:"agent-permission-inherit-banner",children:[e.jsx("span",{children:n("agents.inheritingProjectDefault","Inheriting project default — no per-agent override set")}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void pt({presetId:"custom",rules:{git_write:se?.git_write??"allow",file_write_delete:se?.file_write_delete??"allow",command_execution:se?.command_execution??"allow",network_api:se?.network_api??"allow",task_agent_mutation:se?.task_agent_mutation??"allow"}}),children:n("agents.customizeForAgent","Customize for this agent")})]}):null,e.jsx(Ea,{mode:"agent-override",value:J,projectDefault:se,onChange:r=>{pt(r)}})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:n("agents.heartbeatSettingsTitle","Heartbeat Settings")}),e.jsx("p",{className:"config-description",children:n("agents.heartbeatSettingsDesc","Configure how this agent's heartbeat is monitored. Leave a field empty to use system defaults.")}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field agent-heartbeat-auto-claim-card",children:[e.jsxs("div",{className:"agent-heartbeat-preset-row",children:[e.jsxs("div",{children:[e.jsx("label",{className:"agent-heartbeat-preset-label",children:n("agents.coordinationOnlyAgent","Coordination-only agent")}),e.jsx("span",{className:"config-hint",children:n("agents.coordinationOnlyHint","Disables auto-claim and removes the candidate section from heartbeat prompts. Recommended for routing/CEO-style agents.")})]}),e.jsx("button",{type:"button",className:"btn btn-sm agent-heartbeat-preset-btn",onClick:()=>{v(!1),ae(r=>({...r,autoClaimCandidatesInPrompt:"0"})),me()},children:n("agents.applyPreset","Apply preset")})]}),e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-autoClaimRelevantTasks",children:[e.jsx("input",{id:"hb-autoClaimRelevantTasks",type:"checkbox",checked:x,onChange:r=>{v(r.target.checked),me()}}),n("agents.autoClaimRelevantTasks","Auto-Claim Relevant Tasks")]}),e.jsx("span",{className:"config-hint",children:n("agents.autoClaimHint","When enabled (default), no-task heartbeats scan open unowned work and auto-claim tasks aligned with this agent's role and soul.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-enabled",children:[e.jsx("input",{id:"hb-enabled",type:"checkbox",checked:A,onChange:r=>{Ls(r.target.checked),me()}}),n("agents.heartbeatEnabled","Heartbeat Enabled")]}),e.jsx("span",{className:"config-hint",children:n("agents.heartbeatEnabledHint","When enabled, this agent receives scheduled heartbeat runs based on its interval.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-runMissedHeartbeatOnStartup",children:[e.jsx("input",{id:"hb-runMissedHeartbeatOnStartup",type:"checkbox",checked:d,onChange:r=>{z(r.target.checked),me()}}),n("agents.runMissedHeartbeat","Run Missed Heartbeat On Startup")]}),e.jsx("span",{className:"config-hint",children:n("agents.runMissedHeartbeatHint","When enabled, if the server was down across this agent's scheduled heartbeat tick, fire a single catch-up heartbeat at startup. Default: off.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-allowParallelExecution",children:[e.jsx("input",{id:"hb-allowParallelExecution",type:"checkbox",checked:$,onChange:r=>{Ce(r.target.checked),me()}}),n("agents.allowParallelExecution","Allow Parallel Execution")]}),e.jsx("span",{className:"config-hint",children:n("agents.allowParallelExecutionHint","When disabled, the heartbeat and task execution paths serialize for this agent (heartbeat will not start while the agent's task is executing, and vice versa). Permanent agents only.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-skipHeartbeatWhenIdle",children:[e.jsx("input",{id:"hb-skipHeartbeatWhenIdle",type:"checkbox",checked:de,onChange:r=>{ve(r.target.checked),me()}}),n("agents.skipHeartbeatWhenIdle","Skip heartbeat when idle")]}),e.jsx("span",{className:"config-hint",children:n("agents.skipHeartbeatWhenIdleHint","When enabled, scheduled (timer) heartbeats are skipped while this agent has no assigned task. The agent still wakes immediately when a task is assigned or you trigger a run manually. Default: off.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-heartbeatScopeDiscipline",children:n("agents.heartbeatScopeDiscipline","Heartbeat Scope Discipline")}),e.jsxs("select",{id:"hb-heartbeatScopeDiscipline",className:"select",value:je,onChange:r=>{const f=r.target.value;ye(f==="strict"||f==="lite"||f==="off"?f:""),me()},children:[e.jsx("option",{value:"",children:n("agents.inheritProjectDefault","Inherit project default")}),e.jsx("option",{value:"strict",children:n("agents.strict","Strict")}),e.jsx("option",{value:"lite",children:n("agents.lite","Lite")}),e.jsx("option",{value:"off",children:n("agents.off","Off")})]}),e.jsx("span",{className:"config-hint",children:n("agents.scopeDisciplineHint","Strict — coordination-focused; higher per-tick tokens. Lite — pre-2026-05-11 behavior. Off — minimal procedure.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-heartbeatPromptTemplate",children:n("agents.heartbeatPromptTemplate","Heartbeat Prompt Template")}),e.jsxs("select",{id:"hb-heartbeatPromptTemplate",className:"select",value:be,onChange:r=>{const f=r.target.value;O(f==="default"||f==="compact"?f:""),me()},children:[e.jsx("option",{value:"",children:n("agents.inheritProjectDefault","Inherit project default")}),e.jsx("option",{value:"default",children:n("agents.templateDefault","Default")}),e.jsx("option",{value:"compact",children:n("agents.templateCompact","Compact")})]})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-heartbeatIntervalMs",children:n("agents.heartbeatIntervalLabel","Heartbeat Interval (s)")}),e.jsx("input",{id:"hb-heartbeatIntervalMs",type:"text",inputMode:"numeric",className:oe("input",!!K.heartbeatIntervalMs&&"input--error"),placeholder:String(Vt/1e3),value:F.heartbeatIntervalMs??"",onChange:r=>yt("heartbeatIntervalMs",r.target.value)}),K.heartbeatIntervalMs?e.jsx("span",{className:"config-error",children:K.heartbeatIntervalMs}):e.jsx("span",{className:"config-hint",children:n("agents.heartbeatIntervalHint","How often heartbeats are checked. Leave empty for system default ({{seconds}}s / {{label}}).",{seconds:Vt/1e3,label:Wa})})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-heartbeatTimeoutMs",children:n("agents.heartbeatTimeoutLabel","Heartbeat Timeout (s)")}),e.jsx("input",{id:"hb-heartbeatTimeoutMs",type:"text",inputMode:"numeric",className:oe("input",!!K.heartbeatTimeoutMs&&"input--error"),placeholder:"60",value:F.heartbeatTimeoutMs??"",onChange:r=>yt("heartbeatTimeoutMs",r.target.value)}),K.heartbeatTimeoutMs?e.jsx("span",{className:"config-error",children:K.heartbeatTimeoutMs}):e.jsx("span",{className:"config-hint",children:n("agents.heartbeatTimeoutHint","Time without heartbeat before agent is considered unresponsive. Leave empty for system default (60s)")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-maxConcurrentRuns",children:n("agents.maxConcurrentRunsLabel","Max Concurrent Runs")}),e.jsx("input",{id:"hb-maxConcurrentRuns",type:"text",inputMode:"numeric",className:oe("input",!!K.maxConcurrentRuns&&"input--error"),placeholder:"1",value:F.maxConcurrentRuns??"",onChange:r=>yt("maxConcurrentRuns",r.target.value)}),K.maxConcurrentRuns?e.jsx("span",{className:"config-error",children:K.maxConcurrentRuns}):e.jsx("span",{className:"config-hint",children:n("agents.maxConcurrentRunsHint","Maximum simultaneous heartbeat runs for this agent. Leave empty for system default (1).")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-messageResponseMode",children:n("agents.messageResponseModeLabel","Message Response Mode")}),e.jsxs("select",{id:"hb-messageResponseMode",className:oe("select",!!K.messageResponseMode&&"input--error"),value:F.messageResponseMode??"",onChange:r=>yt("messageResponseMode",r.target.value),children:[e.jsx("option",{value:"",children:n("agents.systemDefaultOnHeartbeat","System Default (On Heartbeat)")}),e.jsx("option",{value:"on-heartbeat",children:n("agents.onHeartbeat","On Heartbeat")}),e.jsx("option",{value:"immediate",children:n("agents.immediate","Immediate")})]}),K.messageResponseMode?e.jsx("span",{className:"config-error",children:K.messageResponseMode}):e.jsx("span",{className:"config-hint",children:n("agents.messageResponseModeHint","How this agent responds to incoming messages. 'Immediate' wakes the agent as soon as a message arrives. 'On Heartbeat' defers processing to the next scheduled heartbeat.")})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:n("agents.budgetSettingsTitle","Budget Settings")}),e.jsx("p",{className:"config-description",children:n("agents.budgetSettingsDesc","Configure token budget limits for this agent. Leave all fields empty to disable budget tracking.")}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"budget-tokenBudget",children:n("agents.tokenBudgetLabel","Token Budget")}),e.jsx("input",{id:"budget-tokenBudget",type:"text",inputMode:"numeric",className:oe("input",!!K.tokenBudget&&"input--error"),placeholder:n("agents.noLimit","No limit"),value:B.tokenBudget??"",onChange:r=>Nt("tokenBudget",r.target.value)}),K.tokenBudget?e.jsx("span",{className:"config-error",children:K.tokenBudget}):e.jsx("span",{className:"config-hint",children:n("agents.tokenBudgetHint","Total token cap (input + output) for this agent. Leave empty for no limit.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"budget-usageThreshold",children:n("agents.usageThresholdLabel","Usage Threshold (%)")}),e.jsx("input",{id:"budget-usageThreshold",type:"text",inputMode:"numeric",className:oe("input",!!K.usageThreshold&&"input--error"),placeholder:"80",value:B.usageThreshold??"",onChange:r=>Nt("usageThreshold",r.target.value)}),K.usageThreshold?e.jsx("span",{className:"config-error",children:K.usageThreshold}):e.jsx("span",{className:"config-hint",children:n("agents.usageThresholdHint","Warning threshold as a percentage. Agent warns when usage reaches this level. Default: 80%.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"budget-budgetPeriod",children:n("agents.budgetPeriodLabel","Budget Period")}),e.jsxs("select",{id:"budget-budgetPeriod",className:oe("select",!!K.budgetPeriod&&"input--error"),value:B.budgetPeriod??"",onChange:r=>Nt("budgetPeriod",r.target.value),children:[e.jsx("option",{value:"",children:n("agents.noReset","No reset (lifetime)")}),e.jsx("option",{value:"daily",children:n("agents.daily","Daily")}),e.jsx("option",{value:"weekly",children:n("agents.weekly","Weekly")}),e.jsx("option",{value:"monthly",children:n("agents.monthly","Monthly")})]}),K.budgetPeriod?e.jsx("span",{className:"config-error",children:K.budgetPeriod}):e.jsx("span",{className:"config-hint",children:n("agents.budgetPeriodHint","How often the budget counter resets. Leave empty for lifetime budget.")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"budget-resetDay",children:n("agents.resetDayLabel","Reset Day")}),e.jsx("input",{id:"budget-resetDay",type:"text",inputMode:"numeric",className:oe("input",!!K.resetDay&&"input--error"),placeholder:n("agents.auto","Auto"),value:B.resetDay??"",onChange:r=>Nt("resetDay",r.target.value)}),K.resetDay?e.jsx("span",{className:"config-error",children:K.resetDay}):e.jsx("span",{className:"config-hint",children:B.budgetPeriod==="weekly"?n("agents.resetDayWeekly","Day of week (0=Sunday to 6=Saturday) for reset."):B.budgetPeriod==="monthly"?n("agents.resetDayMonthly","Day of month (1-31) for reset."):n("agents.resetDayHint","Day for reset (weekly: 0-6, monthly: 1-31). Leave empty for automatic.")})]}),Pe?.budgetLimit!=null&&e.jsxs("div",{className:"config-field",children:[e.jsx("label",{children:n("agents.currentUsage","Current Usage")}),e.jsxs("div",{className:"budget-progress-container",children:[e.jsx("div",{className:"budget-progress-bar",children:e.jsx("div",{className:oe("budget-progress-bar__fill",(Pe.usagePercent??0)>=100?"budget-progress-bar__fill--red":(Pe.usagePercent??0)>=80?"budget-progress-bar__fill--amber":"budget-progress-bar__fill--green"),style:{width:`${Math.min(Pe.usagePercent??0,100)}%`}})}),e.jsx("span",{className:"budget-progress-label",children:n("agents.budgetUsageDisplay","{{used}} / {{limit}} tokens ({{percent}}% used)",{used:(Pe.currentUsage??0).toLocaleString(),limit:(Pe.budgetLimit??0).toLocaleString(),percent:Math.round(Pe.usagePercent??0)})})]})]}),Pe?.budgetLimit!=null&&e.jsx("div",{className:"config-field",children:e.jsx("button",{className:"btn btn-reset-budget",onClick:()=>void Ts(),disabled:Ue,children:Ue?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:14,className:"animate-spin"}),n("agents.resetting","Resetting…")]}):e.jsxs(e.Fragment,{children:[e.jsx(Ft,{size:14}),n("agents.resetBudgetUsage","Reset Budget Usage")]})})})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:n("agents.bundleTitle","Instruction Bundle")}),e.jsx("p",{className:"config-description",children:n("agents.bundleDescription","Configure the agent's instruction bundle. Leave empty to use inline instructions only.")}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-mode",children:n("agents.bundleModeLabel","Bundle Mode")}),e.jsxs("select",{id:"bundle-mode",className:"select",value:y,onChange:r=>ie(r.target.value),children:[e.jsx("option",{value:"",children:n("agents.bundleNone","None (use inline instructions)")}),e.jsx("option",{value:"managed",children:n("agents.bundleManaged","Managed (system-managed directory)")}),e.jsx("option",{value:"external",children:n("agents.bundleExternal","External (user-specified path)")})]}),e.jsxs("span",{className:"config-hint",children:[y==="managed"&&n("agents.bundleManagedHint","Files will be stored in a system-managed directory within .fusion/agents/"),y==="external"&&n("agents.bundleExternalHint","Specify an external directory path for the instruction files"),!y&&n("agents.bundleSelectMode","Select a mode to enable instruction bundling")]})]}),y&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-entry-file",children:n("agents.bundleEntryFileLabel","Entry File")}),e.jsx("input",{id:"bundle-entry-file",type:"text",className:"input",placeholder:"AGENTS.md",value:he,onChange:r=>We(r.target.value)}),e.jsx("span",{className:"config-hint",children:n("agents.bundleEntryFileHint","Primary instructions file name (default: AGENTS.md)")})]}),y==="external"&&e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-external-path",children:n("agents.bundleExternalPathLabel","External Path")}),e.jsx("input",{id:"bundle-external-path",type:"text",className:"input",placeholder:n("agents.bundleExternalPathPlaceholder","e.g. .fusion/agents/my-agent"),value:Ee,onChange:r=>Me(r.target.value)}),e.jsx("span",{className:"config-hint",children:n("agents.bundleExternalPathHint","Absolute or relative path to the external directory")})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-files",children:n("agents.bundleFilesLabel","Files (comma-separated)")}),e.jsx("input",{id:"bundle-files",type:"text",className:"input",placeholder:"AGENTS.md, PROMPTS.md",value:ce.join(", "),onChange:r=>Le(r.target.value.split(",").map(f=>f.trim()).filter(Boolean))}),e.jsx("span",{className:"config-hint",children:n("agents.bundleFilesHint","List of file names in the bundle directory")})]})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:n("agents.advancedSettingsTitle","Advanced Settings")}),e.jsx("p",{className:"config-description",children:n("agents.advancedSettingsDesc","Advanced configuration options for this agent. Leave a field empty to use system defaults.")}),e.jsx("div",{className:"config-fields",children:rt.map(r=>{const f=!!K[r.key];return e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:`adv-${r.key}`,children:r.label}),r.type==="select"?e.jsxs("select",{id:`adv-${r.key}`,className:oe("select",f&&"input--error"),value:I[r.key]??"",onChange:E=>Xt(r.key,E.target.value),children:[e.jsx("option",{value:"",children:n("agents.systemDefault","System Default")}),r.options?.map(E=>e.jsx("option",{value:E.value,children:E.label},E.value))]}):e.jsx("input",{id:`adv-${r.key}`,type:"text",inputMode:r.type==="number"?"numeric":void 0,className:oe("input",f&&"input--error"),placeholder:r.placeholder,value:I[r.key]??"",onChange:E=>Xt(r.key,E.target.value)}),f&&e.jsx("span",{className:"config-error",children:K[r.key]}),!f&&r.hint&&e.jsx("span",{className:"config-hint",children:r.hint})]},r.key)})}),e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!Re||Be,onClick:()=>void Ds(),children:Be?e.jsxs(e.Fragment,{children:[e.jsx(G,{size:16,className:"animate-spin"}),n("common.saving","Saving…")]}):e.jsxs(e.Fragment,{children:[e.jsx(ge,{size:16}),n("agents.saveSettings","Save Settings")]})}),ts&&e.jsxs("span",{className:oe("config-saved-indicator",Tt&&"config-saved-indicator--error"),children:[Be?e.jsx(G,{size:14,className:"animate-spin"}):e.jsx(ge,{size:14}),ts]})]})]}),e.jsx(ln,{agent:t,projectId:i,addToast:l,onSaved:o}),e.jsxs("div",{className:"config-section config-section--danger",children:[e.jsx("h3",{children:n("agents.dangerZone","Danger Zone")}),e.jsx("p",{className:"config-description",children:n("agents.dangerZoneDesc","Permanently delete this agent from the project.")}),e.jsx("div",{className:"config-fields",children:e.jsxs("div",{className:"config-field",children:[e.jsxs("button",{className:"btn btn--danger",disabled:!Kt||!h,onClick:()=>void h?.(),children:[e.jsx(lt,{size:16}),n("agents.deleteAgent","Delete Agent")]}),e.jsx("span",{className:"config-danger-note",children:Kt?n("agents.deletionPermanent","Deletion is permanent and cannot be undone."):n("agents.deletionNotAvailable","Agent deletion is only available when state is idle or paused (current state: {{state}}).",{state:t.state})})]})})]}),e.jsx(Pa,{isOpen:T,onClose:()=>V(!1),onUseDraft:Pt,projectId:i,existingAgents:q,mode:"edit",existingAgentConfig:bt})]})}function cn({agentId:t,projectId:i,onChildClick:l}){const{t:o}=ke("app"),[s,h]=a.useState([]),[N,n]=a.useState(!0);return a.useEffect(()=>{n(!0),ua(t,i).then(h).finally(()=>n(!1))},[t,i]),N?e.jsxs("div",{className:"detail-section",children:[e.jsx("div",{className:"detail-section-header",children:e.jsx("h3",{children:o("agents.employeesTitle","Employees")})}),e.jsxs("div",{className:"detail-section-body detail-section-body--loading",children:[e.jsx(G,{size:16,className:"spin"}),e.jsx("span",{className:"text-muted",children:o("agents.loadingEmployees","Loading employees...")})]})]}):e.jsxs("div",{className:"detail-section",children:[e.jsxs("div",{className:"detail-section-header",children:[e.jsx("h3",{children:o("agents.employeesTitle","Employees")}),e.jsxs("span",{className:"text-muted",children:["(",s.length,")"]})]}),e.jsx("div",{className:"detail-section-body",children:s.length===0?e.jsxs("div",{className:"agent-empty agent-empty--padded",children:[e.jsx(ks,{size:32,opacity:.3}),e.jsx("p",{children:o("agents.noEmployees","No employees")}),e.jsx("p",{className:"text-muted",children:o("agents.noEmployeesDesc","This agent has no employees")})]}):e.jsx("div",{className:"agent-tree__children",children:s.map(g=>{const u=qt[g.state];return e.jsxs("div",{className:"agent-tree__node agent-is-child",onClick:()=>l?.(g.id),role:"button",tabIndex:0,onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&(j.key===" "&&j.preventDefault(),l?.(g.id))},style:{cursor:l?"pointer":"default"},children:[e.jsx("span",{className:"agent-tree__icon",children:g.icon??"🤖"}),e.jsx("span",{className:"agent-tree__name",children:g.name}),e.jsx("span",{className:"agent-tree__badge",style:{background:u?.bg??"var(--state-idle-bg)",color:u?.text??"var(--state-idle-text)",border:`1px solid ${u?.border??"var(--state-idle-border)"}`},children:g.state})]},g.id)})})})]})}export{xn as AgentDetailView,Ye as relativeTime};