@runfusion/fusion 0.17.0 → 0.17.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +1729 -789
- package/dist/client/assets/{AgentDetailView-DGqT1oDt.js → AgentDetailView-17J-F0Rl.js} +3 -3
- package/dist/client/assets/{AgentsView-BmemrfrO.js → AgentsView-sbBkb7Wd.js} +45 -45
- package/dist/client/assets/ChatView-BR5cvK_B.js +1 -0
- package/dist/client/assets/{DevServerView-C3Q0XqDA.js → DevServerView-GFFVXHVP.js} +1 -1
- package/dist/client/assets/{DirectoryPicker-BZWVA9ND.js → DirectoryPicker-WPDSBdT6.js} +1 -1
- package/dist/client/assets/{DocumentsView-DO48ivSq.js → DocumentsView-BHpDsIIt.js} +1 -1
- package/dist/client/assets/{InsightsView-CAngTfMf.js → InsightsView-Bxu0TJkt.js} +1 -1
- package/dist/client/assets/{MemoryView-B3rNcAOW.js → MemoryView-CmnzZorw.js} +2 -2
- package/dist/client/assets/{NodesView-BnV1LWa8.js → NodesView-CO9_4hCr.js} +4 -4
- package/dist/client/assets/{PiExtensionsManager-C3_Lw4sa.js → PiExtensionsManager-4e3MlD62.js} +3 -3
- package/dist/client/assets/{PluginManager-Vv3nzrJ1.js → PluginManager-DGN2rvOY.js} +1 -1
- package/dist/client/assets/ResearchView-Dsa6Gykl.js +1 -0
- package/dist/client/assets/{RoadmapsView-BiIpE-b8.js → RoadmapsView-jHTOK0RQ.js} +2 -2
- package/dist/client/assets/{SettingsModal-CK4w8Ztb.js → SettingsModal-4Z8ZJMzD.js} +1 -1
- package/dist/client/assets/SettingsModal-D0kuJpBA.js +31 -0
- package/dist/client/assets/{SetupWizardModal-Dw6N4UvY.js → SetupWizardModal-Bhumd4Rf.js} +1 -1
- package/dist/client/assets/{SkillsView-C1196wgA.js → SkillsView-MHweJTz4.js} +1 -1
- package/dist/client/assets/{folder-open-WVtgE4k3.js → folder-open-BNQW9dE9.js} +1 -1
- package/dist/client/assets/{index-BIJgrHEn.css → index-DEVBHvyW.css} +1 -1
- package/dist/client/assets/index-k_85J1DS.js +682 -0
- package/dist/client/assets/{star-MSImEC8V.js → star-7L86NZrT.js} +1 -1
- package/dist/client/assets/{upload-Dmvy3xXd.js → upload-DsAS6tno.js} +1 -1
- package/dist/client/assets/{users-CncYvHNf.js → users-D3u6f2Rz.js} +1 -1
- package/dist/client/index.html +2 -2
- package/dist/client/version.json +1 -1
- package/dist/extension.js +1239 -527
- package/dist/pi-claude-cli/package.json +1 -1
- package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
- package/package.json +1 -1
- package/dist/client/assets/ChatView-CZQUBFlV.js +0 -1
- package/dist/client/assets/ResearchView-Dfdsuc21.js +0 -1
- package/dist/client/assets/SettingsModal-BN00HYJ2.js +0 -31
- package/dist/client/assets/index-Bv0TGzDH.js +0 -682
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{r as t,j as e}from"./vendor-react-K0fH_qHe.js";import{c as Ze,
|
|
1
|
+
import{r as t,j as e}from"./vendor-react-K0fH_qHe.js";import{c as Ze,dh as Os,di as _s,dj as Is,dk as Vs,L as I,R as Xe,ao as gs,Z as Us,ap as qe,_ as De,a as ys,b as Ss,dl as Js,dm as qs,dn as Gs,b1 as Ws,z as ks,cs as Ks,dp as Ys,I as Z,dq as Zs,dr as Rs,ds as Cs,s as Ee,B as We,W as Te,Y as fs,aK as Re,X as Xs,F as Ce,A as $e,dt as ws,du as Ms,dv as Qs,cm as et,aJ as st,bs as tt,aq as Fs,a1 as at,a4 as nt,a6 as it,dw as Ke,k as As,dx as rt,r as lt,$ as Ts,dy as ct,C as ae,dz as ot,dA as dt,dB as ut,dC as ze,ac as He,ae as Be,af as Oe,aa as Es,dD as mt,dE as ht,i as gt,h as ft,l as xt,dF as Ye,a5 as pt,dG as vt,dH as bt,dI as jt,dJ as Nt,dK as $s,dL as yt,dM as St,dN as kt,a2 as Rt,dO as Ct}from"./index-k_85J1DS.js";import{S as Ls}from"./star-7L86NZrT.js";/**
|
|
2
2
|
* @license lucide-react v1.7.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
@@ -13,6 +13,6 @@ import{r as t,j as e}from"./vendor-react-K0fH_qHe.js";import{c as Ze,de as Os,df
|
|
|
13
13
|
*
|
|
14
14
|
* This source code is licensed under the ISC license.
|
|
15
15
|
* See the LICENSE file in the root directory of this source tree.
|
|
16
|
-
*/const At=[["path",{d:"M16 17h6v-6",key:"t6n2it"}],["path",{d:"m22 17-8.5-8.5-5 5L2 7",key:"x473p"}]],Tt=Ze("trending-down",At);function xs(s){return s<1e3?`${s}ms`:s<6e4?`${(s/1e3).toFixed(1)}s`:s<36e5?`${Math.floor(s/6e4)}m`:`${(s/36e5).toFixed(1)}h`}function Et(s){return`${Math.round(s*100)}%`}function ps(s){const a=Date.now(),n=new Date(s).getTime(),d=a-n;if(d<0){const o=Math.abs(d);return o<6e4?"in a moment":o<36e5?`in ${Math.floor(o/6e4)}m`:o<864e5?`in ${Math.floor(o/36e5)}h`:`in ${Math.floor(o/864e5)}d`}return d<6e4?"just now":d<36e5?`${Math.floor(d/6e4)}m ago`:d<864e5?`${Math.floor(d/36e5)}h ago`:`${Math.floor(d/864e5)}d ago`}function $t(s){switch(s){case"periodic":return"Periodic";case"post-task":return"Post-Task";case"manual":return"Manual";case"user-requested":return"User Requested";default:return s}}function Se(s){return s instanceof Error&&s.message?s.message:String(s)}function Lt(s){switch(s){case"improving":return"↑ Improving";case"declining":return"↓ Declining";case"stable":return"→ Stable";default:return"Insufficient data"}}function Dt(s){switch(s){case"improving":return"trend-improving";case"declining":return"trend-declining";case"stable":return"trend-stable";default:return"trend-insufficient"}}function vs(s,a=5){return e.jsx("span",{className:"rating-stars",children:Array.from({length:a},(n,d)=>e.jsx(Ls,{size:14,className:d<s?"star-filled":"star-empty",fill:d<s?"currentColor":"none"},d))})}function Pt({agentId:s,projectId:a,addToast:n}){const[d,o]=t.useState([]),[m,j]=t.useState(null),[u,N]=t.useState(null),[c,w]=t.useState([]),[L,v]=t.useState(!0),[A,g]=t.useState(!0),[y,f]=t.useState(!1),[J,k]=t.useState(!1),[$,h]=t.useState(null),[p,x]=t.useState(0),[b,D]=t.useState(""),[G,T]=t.useState(""),W=t.useCallback(async()=>{try{const[l,r]=await Promise.all([Os(s,20,a),_s(s,void 0,a)]);o(l),j(r)}catch(l){n(`Failed to load reflections: ${Se(l)}`,"error")}finally{v(!1)}},[s,a,n]),z=t.useCallback(async()=>{try{const[l,r]=await Promise.all([Is(s,a),Vs(s,{limit:50},a)]);N(l),w(r)}catch(l){n(`Failed to load ratings: ${Se(l)}`,"error")}finally{g(!1)}},[s,a,n]);t.useEffect(()=>{W(),z()},[W,z]);const K=async()=>{f(!0);try{if(!await Js(s,a)){n("Not enough history to generate a reflection yet","error");return}n("Reflection generated successfully","success"),v(!0),await W()}catch(l){const r=Se(l),C=r.toLowerCase();C.includes("agent not found")||C.includes("not found")?n("This agent is no longer available. It may have been deleted.","error"):C.includes("insufficient history")?n("Not enough history to generate a reflection yet","error"):n(`Failed to generate reflection: ${r}`,"error")}finally{f(!1)}},F=async l=>{if(l.preventDefault(),p!==0){k(!0);try{await qs(s,{score:p,category:b||void 0,comment:G||void 0,raterType:"user"},a),x(0),D(""),T(""),n("Rating added","success"),await z()}catch(r){n(`Failed to add rating: ${Se(r)}`,"error")}finally{k(!1)}}},H=async l=>{try{await Gs(s,l,a),n("Rating deleted","success"),await z()}catch(r){n(`Failed to delete rating: ${Se(r)}`,"error")}},R=l=>{h(r=>r===l?null:l)};if(L&&A)return e.jsx("div",{className:"reflections-tab",children:e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(I,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading evaluation..."})]})});const V=m&&m.totalTasksCompleted===0&&m.totalTasksFailed===0&&m.recentReflectionCount===0;return e.jsxs("div",{className:"reflections-tab",children:[e.jsxs("div",{className:"reflections-header",children:[e.jsxs("h3",{children:[e.jsx(Le,{size:16}),"Performance, Reflections & Ratings"]}),e.jsx("button",{className:"btn btn-secondary",onClick:K,disabled:y,title:"Generate a manual reflection",children:y?e.jsxs(e.Fragment,{children:[e.jsx(I,{size:14,className:"animate-spin"}),"Reflecting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Xe,{size:14}),"Reflect Now"]})})]}),m&&!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(gs,{size:16,style:{color:"var(--color-success)"}}),m.totalTasksCompleted]}),e.jsx("div",{className:"stat-label",children:"Tasks Completed"})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(Tt,{size:16,style:{color:"var(--color-error)"}}),m.totalTasksFailed]}),e.jsx("div",{className:"stat-label",children:"Tasks Failed"})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(Us,{size:16,style:{color:"var(--in-progress)"}}),xs(m.avgDurationMs)]}),e.jsx("div",{className:"stat-label",children:"Avg Duration"})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(Le,{size:16,style:{color:m.successRate>=.8?"var(--color-success)":m.successRate>=.5?"var(--color-warning)":"var(--color-error)"}}),Et(m.successRate)]}),e.jsx("div",{className:"stat-label",children:"Success Rate"})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(qe,{size:16,style:{color:"var(--color-info)"}}),m.recentReflectionCount]}),e.jsx("div",{className:"stat-label",children:"Reflections"})]})]}),V&&e.jsxs("div",{className:"reflections-no-data",children:[e.jsx(Le,{size:24,opacity:.3}),e.jsx("p",{children:"No performance data yet"})]}),e.jsxs("div",{className:"reflections-ratings-section",children:[e.jsx("h4",{children:"User Ratings"}),A?e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(I,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading ratings..."})]}):e.jsxs(e.Fragment,{children:[u&&e.jsxs("div",{className:"rating-summary-card",children:[e.jsxs("div",{className:"rating-score-display",children:[e.jsx("span",{className:"rating-average",children:u.averageScore.toFixed(1)}),vs(Math.round(u.averageScore))]}),e.jsxs("div",{className:"rating-stats",children:[e.jsxs("span",{className:"rating-count",children:[u.totalRatings," ratings"]}),e.jsx("span",{className:`rating-trend-badge ${Dt(u.trend)}`,children:Lt(u.trend)})]})]}),u&&Object.keys(u.categoryAverages).length>0&&e.jsxs("div",{className:"category-breakdown",children:[e.jsx("h4",{children:"Category Averages"}),Object.entries(u.categoryAverages).map(([l,r])=>e.jsxs("div",{className:"category-item",children:[e.jsx("span",{className:"category-name",children:l}),e.jsx("span",{className:"category-score",children:r.toFixed(1)})]},l))]}),e.jsxs("form",{className:"add-rating-form",onSubmit:F,children:[e.jsx("h4",{children:"Add Rating"}),e.jsx("div",{className:"star-selector",children:[1,2,3,4,5].map(l=>e.jsx("button",{type:"button",className:"star-btn touch-target",onClick:()=>x(l),title:`${l} star${l>1?"s":""}`,children:e.jsx(Ls,{size:24,fill:l<=p?"currentColor":"none",className:l<=p?"star-filled":"star-empty"})},l))}),e.jsxs("select",{value:b,onChange:l=>D(l.target.value),className:"select add-rating-category-select",children:[e.jsx("option",{value:"",children:"Select category..."}),e.jsx("option",{value:"quality",children:"Quality"}),e.jsx("option",{value:"speed",children:"Speed"}),e.jsx("option",{value:"communication",children:"Communication"}),e.jsx("option",{value:"reliability",children:"Reliability"}),e.jsx("option",{value:"other",children:"Other"})]}),e.jsx("textarea",{value:G,onChange:l=>T(l.target.value),placeholder:"Optional comment...",className:"input add-rating-comment-input",rows:3}),e.jsx("button",{type:"submit",className:"btn btn-task-create",disabled:p===0||J,children:J?"Submitting...":"Submit Rating"})]}),e.jsxs("div",{className:"rating-history",children:[e.jsx("h4",{children:"Rating History"}),c.length===0?e.jsx("p",{className:"no-ratings",children:"No ratings yet"}):c.map(l=>e.jsxs("div",{className:"rating-history-item",children:[e.jsxs("div",{className:"rating-item-header",children:[vs(l.score),l.category&&e.jsx("span",{className:"rating-category-badge",children:l.category}),e.jsx("span",{className:"rating-time",children:ps(l.createdAt)}),e.jsx("button",{type:"button",className:"rating-delete-btn touch-target",onClick:()=>void H(l.id),title:"Delete rating",children:e.jsx(De,{size:14})})]}),l.comment&&e.jsx("p",{className:"rating-comment",children:l.comment})]},l.id))]})]})]}),e.jsxs("div",{className:"reflections-list",children:[e.jsx("h4",{children:"Reflection History"}),L?e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(I,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading reflections..."})]}):d.length===0?e.jsxs("div",{className:"reflection-empty",children:[e.jsx(qe,{size:32,opacity:.3}),e.jsx("p",{children:"No reflections yet"}),e.jsx("p",{className:"text-secondary",children:"Trigger a reflection to get started"})]}):e.jsx("div",{className:"reflection-cards",children:d.map(l=>{const r=$===l.id;return e.jsxs("div",{className:`reflection-card ${r?"reflection-card--expanded":""}`,onClick:()=>R(l.id),role:"button",tabIndex:0,onKeyDown:C=>C.key==="Enter"&&R(l.id),children:[e.jsxs("div",{className:"reflection-card-header",children:[e.jsx("span",{className:`reflection-trigger-badge reflection-trigger-${l.trigger}`,children:$t(l.trigger)}),e.jsx("span",{className:"reflection-timestamp",children:ps(l.timestamp)}),e.jsx("span",{className:"reflection-chevron",children:r?e.jsx(ys,{size:16}):e.jsx(Ss,{size:16})})]}),e.jsx("div",{className:"reflection-summary",children:l.summary}),r&&e.jsxs("div",{className:"reflection-details",children:[l.insights.length>0&&e.jsxs("div",{className:"reflection-insights",children:[e.jsxs("h5",{children:[e.jsx(qe,{size:14})," Insights"]}),e.jsx("ul",{children:l.insights.map((C,X)=>e.jsx("li",{children:C},X))})]}),l.suggestedImprovements.length>0&&e.jsxs("div",{className:"reflection-suggestions",children:[e.jsxs("h5",{children:[e.jsx(gs,{size:14})," Suggested Improvements"]}),e.jsx("ul",{children:l.suggestedImprovements.map((C,X)=>e.jsx("li",{children:C},X))})]}),l.metrics&&e.jsxs("div",{className:"reflection-metrics",children:[e.jsx("h5",{children:"Metrics"}),e.jsxs("div",{className:"metrics-grid",children:[l.metrics.tasksCompleted!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:"Tasks:"}),e.jsx("span",{className:"metric-value",children:l.metrics.tasksCompleted})]}),l.metrics.tasksFailed!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:"Failed:"}),e.jsx("span",{className:"metric-value",children:l.metrics.tasksFailed})]}),l.metrics.avgDurationMs!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:"Avg Duration:"}),e.jsx("span",{className:"metric-value",children:xs(l.metrics.avgDurationMs)})]}),l.metrics.errorCount!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:"Errors:"}),e.jsx("span",{className:"metric-value",children:l.metrics.errorCount})]})]})]})]})]},l.id)})})]})]})}function zt({value:s,onChange:a,projectId:n,disabled:d=!1,id:o,label:m="Skills"}){const[j,u]=t.useState([]),[N,c]=t.useState(!0);t.useEffect(()=>{let g=!1;return c(!0),Ws(n).then(y=>{g||u(y)}).catch(()=>{g||u([])}).finally(()=>{g||c(!1)}),()=>{g=!0}},[n]);const w=g=>{s.includes(g)||a([...s,g])},L=g=>{a(s.filter(y=>y!==g))},v=g=>j.find(f=>f.id===g)?.name??g,A=j.filter(g=>!s.includes(g.id));return e.jsxs("div",{className:"skill-multiselect","data-testid":"skill-multiselect",children:[m&&e.jsx("label",{htmlFor:o?`${o}-select`:void 0,className:"skill-multiselect-label",children:m}),s.length>0&&e.jsx("div",{className:"skill-multiselect-chips","data-testid":"skill-chips",children:s.map(g=>e.jsxs("span",{className:"skill-chip","data-testid":`skill-chip-${g}`,children:[e.jsx("span",{className:"skill-chip-name",children:v(g)}),e.jsx("button",{type:"button",className:"skill-chip-remove",onClick:()=>L(g),disabled:d,"aria-label":`Remove ${v(g)}`,"data-testid":`remove-skill-${g}`,children:"×"})]},g))}),e.jsx("div",{className:"skill-multiselect-add",children:N?e.jsx("span",{className:"skill-multiselect-loading","data-testid":"skills-loading",children:"Loading skills…"}):A.length===0?e.jsx("span",{className:"skill-multiselect-empty","data-testid":"skills-empty",children:s.length===0?"No skills discovered":"All skills selected"}):e.jsxs("select",{id:o?`${o}-select`:void 0,className:"select skill-multiselect-dropdown",value:"",onChange:g=>{g.target.value&&(w(g.target.value),g.target.value="")},disabled:d,"data-testid":"skill-dropdown",children:[e.jsx("option",{value:"",children:"Add a skill…"}),A.map(g=>e.jsx("option",{value:g.id,children:g.name},g.id))]})})]})}function ie(...s){return s.filter(Boolean).join(" ")}function pe(s){const a=Date.now(),n=new Date(s).getTime(),d=a-n;if(d<0){const o=Math.abs(d);return o<6e4?"in a moment":o<36e5?`in ${Math.floor(o/6e4)}m`:o<864e5?`in ${Math.floor(o/36e5)}h`:`in ${Math.floor(o/864e5)}d`}return d<6e4?"just now":d<36e5?`${Math.floor(d/6e4)}m ago`:d<864e5?`${Math.floor(d/36e5)}h ago`:`${Math.floor(d/864e5)}d ago`}const Ht=[{id:"dashboard",label:"Dashboard",icon:Ft},{id:"logs",label:"Logs",icon:Ce},{id:"runs",label:"Runs",icon:$e},{id:"tasks",label:"Tasks",icon:ws},{id:"employees",label:"Employees",icon:Ms},{id:"soul",label:"Soul",icon:Qs},{id:"instructions",label:"Instructions",icon:et},{id:"memory",label:"Agent Memory",icon:Ce},{id:"reflections",label:"Evaluation",icon:Le},{id:"config",label:"Settings",icon:st}],Qe={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)"},terminated:{bg:"var(--state-error-bg)",text:"var(--state-error-text)",border:"var(--state-error-border)"}},Pe={completed:{icon:ae,color:"var(--color-success)"},failed:{icon:ct,color:"var(--color-error)"},active:{icon:I,color:"var(--in-progress)"},terminated:{icon:Re,color:"var(--text-muted)"}},bs={"long-term":"Long-term",daily:"Daily",dreams:"Dreams"},Bt={"long-term":"Curated durable decisions, conventions, constraints, and pitfalls for this specific agent.",daily:"Raw daily observations and open loops recorded by this agent.",dreams:"Synthesized patterns and emerging themes distilled from this agent's daily memory."},Ot=Ts(Ke);function _t(s,a){return s.some(n=>n.path===a)?a:s.find(n=>n.layer==="long-term")?.path??s[0]?.path??""}function It({agentId:s,projectId:a,onClose:n,addToast:d,onChildClick:o,inline:m=!1,initialTab:j,initialRunId:u,preferActiveRun:N=!1}){const[c,w]=t.useState(null),{confirm:L}=ks(),[v,A]=t.useState([]),[g,y]=t.useState(!0),[f,J]=t.useState(j??"dashboard"),[k,$]=t.useState(!1),[h,p]=t.useState(!1),[x,b]=t.useState(null),D=t.useRef(null),G=t.useRef(null),T=t.useRef(!1);Ys(G,!m,"fusion:agent-detail-modal-size");const W=t.useRef(n),z=t.useRef(d),K=t.useRef(null),F=t.useRef(!1),H=t.useRef(null),R=t.useRef(0),V=t.useRef(s),l=t.useRef(a);W.current=n,z.current=d,K.current=c;const r=t.useCallback(async()=>{K.current===null&&y(!0);try{const Y=await Ks(s,a);w(Y)}catch(Y){z.current(`Failed to load agent: ${Z(Y)}`,"error"),W.current()}finally{y(!1)}},[s,a]),C=t.useCallback(async()=>{const S=R.current,Y=s,q=a,U=()=>R.current!==S||s!==Y||a!==q;try{if(c?.taskId){b(null),H.current=null;const ue=await Zs(c.taskId,q,{limit:100});if(U())return;A(ue.entries);return}const ce=await Rs(Y,1,q);if(U())return;const te=ce[0]??null;if(b(te),!te){H.current=null,A([]);return}if(H.current===te.id)return;const de=await Cs(Y,te.id,q);if(U())return;A([...de].reverse()),H.current=te.id}catch(ce){if(U())return;console.error("Failed to load agent logs:",ce)}},[c?.taskId,s,a]),X=t.useCallback(S=>{F.current=S},[]);t.useEffect(()=>{r()},[r]),t.useEffect(()=>{const S=setInterval(()=>{r()},3e4);return()=>{clearInterval(S)}},[r]),t.useEffect(()=>{c&&f==="logs"&&C()},[c,f,C]),t.useEffect(()=>{f!=="logs"&&(H.current=null)},[f]),t.useEffect(()=>{if(f!=="logs"||c?.taskId||!x||x.status!=="active")return;const S=R.current,Y=s,q=x.id,U=a?`?projectId=${encodeURIComponent(a)}`:"",ce=Ee(`/api/agents/${encodeURIComponent(Y)}/runs/${encodeURIComponent(q)}/logs/stream${U}`,{events:{"agent:log":te=>{if(R.current===S)try{const de=JSON.parse(te.data);A(ue=>[de,...ue])}catch{}}},onOpen:()=>{R.current===S&&$(!0)},onError:()=>{R.current===S&&$(!1)}});return()=>{ce(),R.current===S&&$(!1)}},[f,c?.taskId,s,a,x]),t.useEffect(()=>{(V.current!==s||l.current!==a)&&(V.current=s,l.current=a,R.current++,A([]),$(!1),b(null),H.current=null,F.current=!1)},[s,a]),t.useEffect(()=>{const S=a?`?projectId=${encodeURIComponent(a)}`:"",Y=R.current;return Ee(`/api/events${S}`,{events:{"agent:updated":q=>{if(R.current===Y)try{const U=JSON.parse(q.data);if(!U||typeof U!="object"||U.id!==s||F.current)return;r()}catch{}}}})},[s,a,r]),t.useEffect(()=>{if(f!=="logs"||!c?.taskId){$(!1);return}const S=R.current,Y=c.taskId,q=a?`?projectId=${encodeURIComponent(a)}`:"",U=Ee(`/api/tasks/${encodeURIComponent(Y)}/logs/stream${q}`,{events:{"agent:log":ce=>{if(R.current===S)try{const te=JSON.parse(ce.data);A(ue=>[te,...ue]);const de=D.current;de&&de.scrollTop<50&&(de.scrollTop=0)}catch{}}},onOpen:()=>{R.current===S&&$(!0)},onError:()=>{R.current===S&&$(!1)}});return()=>{U(),R.current===S&&$(!1)}},[c?.taskId,f,a]);const se=async S=>{if(h||!K.current)return;const Y=K.current.state;if(Y!==S){p(!0),w(q=>q&&{...q,state:S});try{await nt(s,S,a),d(`Agent state updated to ${S}`,"success"),r()}catch(q){w(U=>U&&{...U,state:Y}),d(`Failed to update state: ${Z(q)}`,"error")}finally{p(!1)}}},me=async()=>{if(!(!c||!await L({title:"Delete Agent",message:`Delete agent "${c.name}"? This cannot be undone.`,danger:!0})))try{await it(s,a),d(`Agent "${c.name}" deleted`,"success"),n()}catch(Y){d(`Failed to delete agent: ${Z(Y)}`,"error")}},xe=()=>c?at(c):{label:"Unknown",icon:e.jsx(We,{size:14}),color:"var(--text-muted)",stateDerived:!1},E=()=>{c&&(navigator.clipboard.writeText(c.id),d("Agent ID copied to clipboard","success"))};if(g)return m?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(I,{className:"animate-spin",size:24}),e.jsx("span",{children:"Loading agent..."})]})}):e.jsx("div",{className:"agent-detail-overlay",onMouseDown:S=>{S.target===S.currentTarget&&(T.current=!0)},onMouseUp:S=>{T.current&&S.target===S.currentTarget&&n(),T.current=!1},role:"dialog","aria-modal":"true",children:e.jsx("div",{className:"agent-detail-modal",ref:G,children:e.jsxs("div",{className:"agent-detail-loading",children:[e.jsx(I,{className:"animate-spin",size:24}),e.jsx("span",{children:"Loading agent..."})]})})});if(!c)return null;const _=Qe[c.state],re=xe(),_e=m?"agent-detail-inline":"agent-detail-modal";return e.jsx("div",{className:m?"agent-detail-inline-shell":"agent-detail-overlay",onClick:S=>!m&&S.target===S.currentTarget&&n(),role:m?"region":"dialog","aria-label":m?"Agent detail":void 0,"aria-modal":m?void 0:"true",children:e.jsxs("div",{className:_e,ref:G,children:[e.jsxs("div",{className:"agent-detail-header",children:[e.jsxs("div",{className:"agent-detail-identity",children:[e.jsx("div",{className:"agent-detail-icon",children:e.jsx(We,{size:20})}),e.jsxs("div",{className:"agent-detail-info",children:[e.jsx("h2",{children:c.name}),e.jsxs("div",{className:"agent-detail-badges",children:[e.jsx("span",{className:"badge",style:{background:_.bg,color:_.text,border:`1px solid ${_.border}`},children:c.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:[c.state==="idle"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void se("active"),disabled:h,children:[e.jsx(Te,{size:14}),"Start"]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:me,children:[e.jsx(De,{size:14}),"Delete"]})]}),c.state==="active"&&e.jsxs("button",{className:"btn btn--compact",onClick:()=>void se("paused"),disabled:h,children:[e.jsx(fs,{size:14}),"Pause"]}),c.state==="paused"&&e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void se("active"),disabled:h,children:[e.jsx(Te,{size:14}),"Resume"]}),c.state==="running"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--compact",onClick:()=>void se("paused"),disabled:h,children:[e.jsx(fs,{size:14}),"Pause"]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:()=>void se("terminated"),disabled:h,children:[e.jsx(Re,{size:14}),"Stop"]})]}),c.state==="error"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void se("active"),disabled:h,children:[e.jsx(Te,{size:14}),"Retry"]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:()=>void se("terminated"),disabled:h,children:[e.jsx(Re,{size:14}),"Stop"]})]}),c.state==="terminated"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void se("active"),disabled:h,children:[e.jsx(Te,{size:14}),"Start"]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:me,children:[e.jsx(De,{size:14}),"Delete"]})]})]}),e.jsxs("div",{className:"agent-detail-utility-actions",children:[e.jsx("button",{className:"btn-icon",onClick:()=>void r(),title:"Refresh",children:e.jsx(Xe,{size:16})}),!m&&e.jsx("button",{className:"btn-icon",onClick:n,"aria-label":"Close",title:"Close",children:e.jsx(Xs,{size:20})})]})]})]}),e.jsx("div",{className:"agent-detail-tabs",children:Ht.map(S=>e.jsxs("button",{className:ie("agent-detail-tab",f===S.id&&"active"),onClick:()=>J(S.id),children:[e.jsx(S.icon,{size:16}),S.label]},S.id))}),e.jsxs("div",{className:"agent-detail-content",children:[f==="dashboard"&&e.jsx(Vt,{agent:c,health:re,onChildClick:o,projectId:a}),f==="logs"&&e.jsx(Ut,{logs:v,isStreaming:k,containerRef:D,hasTask:!!c.taskId||v.length>0||x!==null,fallbackLabel:!c.taskId&&x?`Latest run · ${x.id.slice(0,8)}`:null}),f==="runs"&&e.jsx(qt,{addToast:d,agentId:c.id,projectId:a,agentState:c.state,agentName:c.name,initialRunId:u,preferActiveRun:N}),f==="tasks"&&e.jsx(Kt,{agentId:c.id,projectId:a,addToast:d}),f==="employees"&&e.jsx(aa,{agentId:c.id,projectId:a,onChildClick:o}),f==="soul"&&e.jsx(Xt,{agent:c,projectId:a,addToast:d,onSaved:r}),f==="instructions"&&e.jsx(ea,{agent:c,projectId:a,addToast:d,onSaved:r}),f==="memory"&&e.jsx(Qt,{agent:c,projectId:a,addToast:d,onSaved:r}),f==="reflections"&&e.jsx(Pt,{agentId:c.id,projectId:a,addToast:d}),f==="config"&&e.jsx(ta,{agent:c,projectId:a,addToast:d,onSaved:r,onHasChangesChange:X,onDelete:me})]}),!m&&e.jsxs("div",{className:"agent-detail-footer",children:[e.jsx("button",{className:"btn-icon",onClick:E,title:"Copy Agent ID",children:e.jsx(tt,{})}),e.jsx("span",{className:"agent-detail-id",onClick:E,children:c.id}),c.taskId&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"divider",children:"|"}),e.jsx("span",{className:"text-muted",children:"Working on:"}),e.jsxs("a",{href:`/tasks/${c.taskId}`,className:"link",children:[c.taskId,e.jsx(Fs,{size:12})]})]})]})]})})}function Vt({agent:s,health:a,onChildClick:n,projectId:d}){const o=Qe[s.state],[m,j]=t.useState([]),[u,N]=t.useState(!0),[c,w]=t.useState(null),[L,v]=t.useState([]),A=typeof s.runtimeConfig?.runtimeHint=="string"?s.runtimeConfig.runtimeHint:"",g=(()=>{const h=s.runtimeConfig??{};if(A){const p=L.find(x=>x.runtimeId===A);return p?p.name:A}if(h.modelProvider&&h.modelId)return`${h.modelProvider}/${h.modelId}`;if(typeof h.model=="string"&&h.model.includes("/")){const p=h.model.indexOf("/");return h.model.slice(p+1)}return null})();t.useEffect(()=>{Ye(s.id,d).then(w).catch(()=>w(null))},[s.id,d]),t.useEffect(()=>{As(d).then(v).catch(()=>v([]))},[d]),t.useEffect(()=>{let h=!1;return N(!0),rt(s.id,d).then(p=>{if(h)return;const x=p.length>0&&p[0]?.id===s.id?[...p].reverse():p;j(x)}).catch(()=>{h||j([])}).finally(()=>{h||N(!1)}),()=>{h=!0}},[s.id,d]);const y=t.useMemo(()=>{const h=s.completedRuns||[],p=new Date;p.setHours(0,0,0,0);const x=h.filter(D=>new Date(D.startedAt)>=p),b=h.filter(D=>D.status==="completed");return{totalRuns:h.length,todayRuns:x.length,successfulRuns:b.length,successRate:h.length>0?Math.round(b.length/h.length*100):0}},[s]),f=(s.completedRuns||[]).slice(0,5),J=s.state==="active"||s.state==="running",k=lt(s.runtimeConfig?.heartbeatIntervalMs),$=J&&s.lastHeartbeatAt?new Date(new Date(s.lastHeartbeatAt).getTime()+k).toISOString():null;return e.jsxs("div",{className:"dashboard-tab dashboard-summary-layout",children:[c?.isOverBudget&&e.jsxs("div",{className:"budget-warning-banner",role:"alert",children:[e.jsx("span",{children:"⚠️"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Budget Exhausted:"})," This agent has exceeded its token budget and may operate with limited functionality."]})]}),e.jsxs("section",{className:"dashboard-summary-card dashboard-summary-hero",children:[e.jsxs("div",{className:"dashboard-summary-hero__heading",children:[e.jsx(We,{}),e.jsx("h3",{children:"Overview"}),e.jsx("strong",{children:s.name}),e.jsx("span",{className:"inline-badge",style:{background:o.bg,color:o.text},children:s.state})]}),e.jsxs("div",{className:"dashboard-summary-hero__meta",children:[e.jsxs("span",{className:"dashboard-summary-hero__health",title:a.reason??a.label,children:[a.icon," ",a.label]}),e.jsxs("span",{children:["Role: ",s.role]}),e.jsxs("span",{children:[e.jsx("span",{className:"dashboard-summary-label",children:A?"Runtime":"Model"}),e.jsxs("span",{children:[" ",g??"Auto"]})]}),Array.isArray(s.metadata?.skills)&&s.metadata.skills.length>0?e.jsxs("span",{children:["Skills: ",s.metadata.skills.join(", ")]}):e.jsx("span",{children:"Skills: —"})]})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:"Heartbeat & Health"}),e.jsxs("div",{className:"dashboard-summary-grid",children:[e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:"Last heartbeat"}),e.jsx("p",{children:s.lastHeartbeatAt?pe(s.lastHeartbeatAt):"Never"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:"Next expected"}),e.jsx("p",{children:$?pe($):"Not scheduled"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:"Interval"}),e.jsx("p",{children:Ts(k)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:"Status"}),e.jsxs("p",{className:"dashboard-summary-health-row",children:[e.jsx("span",{className:ie("status-dot",s.state==="running"&&"status-dot--running")}),a.label,a.reason&&e.jsxs("span",{className:"text-secondary",style:{marginLeft:"var(--space-xs)",fontSize:"12px"},title:a.reason,children:["(",a.reason,")"]})]})]})]})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:"Current Work"}),s.taskId?e.jsxs("div",{className:"current-task",children:[e.jsx("a",{href:`/tasks/${s.taskId}`,className:"task-badge",children:s.taskId}),e.jsxs("a",{href:`/tasks/${s.taskId}`,className:"btn btn-sm",children:["View Task ",e.jsx(Fs,{size:14})]})]}):e.jsx("p",{className:"text-muted",children:"No active assignment"})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:"Recent Runs"}),e.jsxs("p",{className:"dashboard-summary-label",children:[y.successfulRuns,"/",y.totalRuns," successful (",y.successRate,"%)"]}),f.length===0?e.jsx("p",{className:"text-muted",children:"No runs yet"}):e.jsx("div",{className:"runs-list",children:f.map(h=>{const p=Pe[h.status]||Pe.terminated,x=p.icon;return e.jsxs("div",{className:"run-item",children:[e.jsx(x,{size:14,style:{color:p.color}}),e.jsx("span",{children:pe(h.startedAt)}),e.jsxs("span",{className:"text-muted",children:[Math.max(0,Math.round((new Date(h.endedAt||h.startedAt).getTime()-new Date(h.startedAt).getTime())/1e3)),"s"]})]},h.id)})})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:"Throughput"}),e.jsxs("div",{className:"stats-grid",children:[e.jsxs("div",{className:"stat-card",children:[e.jsx("div",{className:"stat-value",children:y.totalRuns}),e.jsx("div",{className:"stat-label",children:"Total Runs"})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("div",{className:"stat-value",children:y.todayRuns}),e.jsx("div",{className:"stat-label",children:"Runs Today"})]}),e.jsxs("div",{className:"stat-card",children:[e.jsxs("div",{className:"stat-value",children:[y.successRate,"%"]}),e.jsx("div",{className:"stat-label",children:"Success Rate"})]})]})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:"Chain of Command"}),u?e.jsxs("div",{className:"chain-of-command-loading",role:"status","aria-live":"polite",children:[e.jsx(I,{size:14,className:"animate-spin"}),e.jsx("span",{children:"Loading reporting chain..."})]}):m.length<=1?e.jsx("p",{className:"text-muted",children:"No reporting chain"}):e.jsx("div",{className:"chain-of-command-path","aria-label":"Chain of command",children:m.map((h,p)=>{const x=p===m.length-1,b=!x;return e.jsxs("div",{className:"chain-of-command-item",children:[e.jsx("button",{type:"button",className:`chain-of-command-node${x?" chain-of-command-node--current":""}`,onClick:()=>b&&n?.(h.id),disabled:!b||!n,title:x?"Current agent":`View ${h.name}`,children:h.name}),!x&&e.jsx("span",{className:"chain-of-command-separator","aria-hidden":"true",children:"→"})]},h.id)})})]})]})}function Ut({logs:s,isStreaming:a,containerRef:n,hasTask:d,fallbackLabel:o}){return d?e.jsxs("div",{className:"logs-tab",children:[e.jsxs("div",{className:"logs-header",children:[e.jsxs("span",{className:"logs-count",children:[s.length," entries"]}),o&&e.jsx("span",{className:"text-muted logs-fallback-label",children:o}),a&&e.jsxs("span",{className:"streaming-indicator",children:[e.jsx("span",{className:"streaming-dot"}),"Live"]})]}),e.jsx("div",{ref:n,className:"logs-container",children:s.length===0?e.jsxs("div",{className:"logs-empty",children:[e.jsx(Ce,{size:48,opacity:.3}),e.jsx("p",{children:"No log entries yet"}),e.jsx("p",{className:"text-muted",children:a?"Waiting for activity...":"Logs will appear here when the agent is active"})]}):s.map((m,j)=>{const u=j>0?s[j-1]:void 0,N=!u||u.agent!==m.agent;return e.jsx(Jt,{entry:m,showTimestamp:N},`${m.timestamp}-${j}`)})})]}):e.jsx("div",{className:"logs-tab",children:e.jsxs("div",{className:"logs-empty",children:[e.jsx(Ce,{size:48,opacity:.3}),e.jsx("p",{children:"No activity yet"}),e.jsx("p",{className:"text-muted",children:"Agent logs will appear here from the current task or most recent run"})]})})}function Jt({entry:s,showTimestamp:a}){const d=(()=>{switch(s.type){case"tool":return{color:"var(--accent)",borderLeft:"3px solid var(--accent)",background:"var(--log-tool-bg)"};case"tool_result":return{color:"var(--color-success)",borderLeft:"3px solid var(--color-success)",background:"var(--log-success-bg)"};case"tool_error":return{color:"var(--color-error)",borderLeft:"3px solid var(--color-error)",background:"var(--log-error-bg)"};case"thinking":return{color:"var(--text-muted)",fontStyle:"italic",opacity:.7};default:return{color:"var(--text)"}}})(),o=new Date(s.timestamp).toLocaleTimeString();return e.jsxs("div",{className:"log-entry",style:d,children:[a&&e.jsxs("span",{className:"log-timestamp",children:["[",o,"]"]}),s.agent&&e.jsxs("span",{className:"log-agent",children:["[",s.agent,"]"]}),s.type==="tool"&&e.jsx("span",{className:"log-icon",children:"⚡"}),s.type==="tool_result"&&e.jsx("span",{className:"log-icon",children:"✓"}),s.type==="tool_error"&&e.jsx("span",{className:"log-icon",children:"✗"}),e.jsxs("span",{className:"log-text",children:[s.text,s.detail&&e.jsxs("span",{className:"log-detail",children:[" — ",s.detail]})]})]})}function qt({addToast:s,agentId:a,projectId:n,agentState:d,agentName:o,initialRunId:m,preferActiveRun:j}){const[u,N]=t.useState([]),{confirm:c}=ks(),[w,L]=t.useState(!0),[v,A]=t.useState(null),[g,y]=t.useState([]),[f,J]=t.useState(!1),[k,$]=t.useState(null),[h,p]=t.useState(!1),x=t.useRef(!1),b=t.useCallback(async()=>{try{const r=await Rs(a,50,n);N(r)}catch(r){s(`Failed to load runs: ${Z(r)}`,"error")}finally{L(!1)}},[a,n,s]);t.useEffect(()=>{b()},[b]);const D=u.some(r=>r.status==="active"),G=v?u.find(r=>r.id===v)?.status:void 0;t.useEffect(()=>{if(!D)return;const r=setInterval(()=>{b()},5e3);return()=>clearInterval(r)},[D,b]),t.useEffect(()=>{if(!v||G!=="active")return;const r=n?`?projectId=${encodeURIComponent(n)}`:"";return Ee(`/api/agents/${encodeURIComponent(a)}/runs/${encodeURIComponent(v)}/logs/stream${r}`,{events:{"agent:log":C=>{try{const X=JSON.parse(C.data);y(se=>[...se,X])}catch{}}}})},[v,G,a,n]);const T=t.useCallback(async r=>{if(v===r){A(null),y([]),$(null);return}A(r),J(!0),p(!0),y([]),$(null);try{const[C,X]=await Promise.all([Cs(a,r,n),ot(a,r,n)]);y(C),$(X)}catch(C){s(`Failed to load run details: ${Z(C)}`,"error"),y([]),$(null)}finally{J(!1),p(!1)}},[v,a,n,s]);t.useEffect(()=>{x.current=!1},[a,m,j]),t.useEffect(()=>{if(u.length===0||w||x.current)return;const r=m?u.find(C=>C.id===m):j?u.find(C=>C.status==="active"):null;x.current=!0,r&&T(r.id)},[m,j,u,w,T]);const W=async()=>{try{await pt(a,n,{source:"on_demand",triggerDetail:"Triggered from dashboard"}),s(`Heartbeat run started for ${o??a}`,"success"),L(!0),b()}catch(r){s(`Failed to start heartbeat run: ${Z(r)}`,"error")}},z=async()=>{if(await c({title:"Stop Active Run",message:"Stop the active run? The agent's work will be interrupted.",danger:!0}))try{await vt(a,n),s("Run stopped","success"),L(!0),b()}catch(C){s(`Failed to stop run: ${Z(C)}`,"error")}},K=d==="active"||d==="idle";if(w&&u.length===0)return e.jsx("div",{className:"runs-tab",children:e.jsxs("div",{className:"runs-loading-row",children:[e.jsx(I,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading runs..."})]})});if(u.length===0)return e.jsxs("div",{className:"runs-tab",children:[K&&e.jsx("div",{className:"runs-toolbar",children:e.jsxs("button",{className:"btn btn--sm btn-task-create",onClick:()=>void W(),"aria-label":`Run now for ${o??a}`,children:[e.jsx($e,{size:14})," Run Now"]})}),e.jsxs("div",{className:"runs-empty",children:[e.jsx($e,{size:48,opacity:.3}),e.jsx("p",{children:"No runs yet"}),e.jsx("p",{className:"text-muted",children:"Heartbeat runs will appear here"})]})]});const F=[...u].sort((r,C)=>new Date(C.startedAt).getTime()-new Date(r.startedAt).getTime()),H=F.filter(r=>r.status==="active"),R=F.filter(r=>r.status!=="active"),V=r=>r?e.jsxs("div",{className:"run-usage",children:[e.jsxs("span",{children:["Input: ",r.inputTokens.toLocaleString()]}),e.jsxs("span",{children:["Output: ",r.outputTokens.toLocaleString()]}),r.cachedTokens>0&&e.jsxs("span",{children:["Cached: ",r.cachedTokens.toLocaleString()]})]}):null,l=(r,C,X)=>{const se=Pe[r.status]||Pe.completed,me=se.icon,xe=r.endedAt?Gt(new Date(r.startedAt),new Date(r.endedAt)):"In progress",E=v===r.id;return e.jsxs("div",{children:[e.jsxs("div",{className:ie("run-card",X&&"run-card--active",E&&"run-card--selected","run-card--clickable"),onClick:()=>void T(r.id),role:"button",tabIndex:0,"aria-expanded":E,"aria-label":`${X?"Active":""} run ${r.id.slice(0,8)}, ${r.status}`,onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),T(r.id))},children:[e.jsxs("div",{className:"run-header",children:[e.jsxs("div",{className:"run-header-group",children:[E?e.jsx(ys,{size:14}):e.jsx(Ss,{size:14}),X?e.jsxs("span",{className:"run-live-indicator",children:[e.jsx("span",{className:"live-dot"}),"Live Run"]}):e.jsxs("span",{className:"run-id",children:["#",C+1," ",r.id.slice(0,8)]})]}),e.jsxs("div",{className:"run-header-group",children:[r.invocationSource&&e.jsx("span",{className:"badge run-badge--compact",children:r.invocationSource}),X&&e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:_=>{_.preventDefault(),_.stopPropagation(),z()},"aria-label":"Stop active run",children:[e.jsx(Re,{size:12})," Stop"]}),e.jsxs("span",{className:ie("run-status",r.status),children:[e.jsx(me,{size:14,className:se.color}),r.status]}),r.heartbeatProcedureSource==="custom"&&e.jsx("span",{className:"badge run-badge--compact",children:"Heartbeat: custom"})]})]}),e.jsxs("div",{className:"run-details",children:[e.jsxs("span",{children:["Started ",pe(r.startedAt)]}),e.jsx("span",{children:"•"}),e.jsx("span",{children:xe}),r.triggerDetail&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsx("span",{className:"text-muted",children:r.triggerDetail})]})]})]}),E&&e.jsxs("div",{className:"run-logs-container",children:[h?e.jsxs("div",{className:"run-details-loading-state",children:[e.jsx(I,{size:14,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading details..."})]}):k&&e.jsxs("div",{className:"run-output-sections",children:[e.jsx("div",{className:"run-output-section",children:e.jsxs("details",{children:[e.jsx("summary",{className:"run-output-label run-output-summary",children:"System Prompt"}),k.systemPrompt?e.jsx("pre",{className:"run-output-panel",children:k.systemPrompt}):e.jsx("div",{className:"text-muted run-output-empty",children:"System prompt not captured for this run"})]})}),e.jsx("div",{className:"run-output-section",children:e.jsxs("details",{children:[e.jsx("summary",{className:"run-output-label run-output-summary",children:"Execution Prompt"}),k.executionPrompt?e.jsx("pre",{className:"run-output-panel",children:k.executionPrompt}):e.jsx("div",{className:"text-muted run-output-empty",children:"Execution prompt not captured for this run"})]})}),k.usageJson&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:"Token Usage"}),V(k.usageJson)]}),k.stdoutExcerpt&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:"Output"}),e.jsx("pre",{className:"run-output-panel",children:k.stdoutExcerpt.length>2e3?`${k.stdoutExcerpt.slice(0,2e3)}
|
|
16
|
+
*/const At=[["path",{d:"M16 17h6v-6",key:"t6n2it"}],["path",{d:"m22 17-8.5-8.5-5 5L2 7",key:"x473p"}]],Tt=Ze("trending-down",At);function xs(s){return s<1e3?`${s}ms`:s<6e4?`${(s/1e3).toFixed(1)}s`:s<36e5?`${Math.floor(s/6e4)}m`:`${(s/36e5).toFixed(1)}h`}function Et(s){return`${Math.round(s*100)}%`}function ps(s){const a=Date.now(),n=new Date(s).getTime(),d=a-n;if(d<0){const o=Math.abs(d);return o<6e4?"in a moment":o<36e5?`in ${Math.floor(o/6e4)}m`:o<864e5?`in ${Math.floor(o/36e5)}h`:`in ${Math.floor(o/864e5)}d`}return d<6e4?"just now":d<36e5?`${Math.floor(d/6e4)}m ago`:d<864e5?`${Math.floor(d/36e5)}h ago`:`${Math.floor(d/864e5)}d ago`}function $t(s){switch(s){case"periodic":return"Periodic";case"post-task":return"Post-Task";case"manual":return"Manual";case"user-requested":return"User Requested";default:return s}}function Se(s){return s instanceof Error&&s.message?s.message:String(s)}function Lt(s){switch(s){case"improving":return"↑ Improving";case"declining":return"↓ Declining";case"stable":return"→ Stable";default:return"Insufficient data"}}function Dt(s){switch(s){case"improving":return"trend-improving";case"declining":return"trend-declining";case"stable":return"trend-stable";default:return"trend-insufficient"}}function vs(s,a=5){return e.jsx("span",{className:"rating-stars",children:Array.from({length:a},(n,d)=>e.jsx(Ls,{size:14,className:d<s?"star-filled":"star-empty",fill:d<s?"currentColor":"none"},d))})}function Pt({agentId:s,projectId:a,addToast:n}){const[d,o]=t.useState([]),[m,j]=t.useState(null),[u,N]=t.useState(null),[c,w]=t.useState([]),[L,v]=t.useState(!0),[A,g]=t.useState(!0),[y,f]=t.useState(!1),[J,k]=t.useState(!1),[$,h]=t.useState(null),[p,x]=t.useState(0),[b,D]=t.useState(""),[G,T]=t.useState(""),W=t.useCallback(async()=>{try{const[l,r]=await Promise.all([Os(s,20,a),_s(s,void 0,a)]);o(l),j(r)}catch(l){n(`Failed to load reflections: ${Se(l)}`,"error")}finally{v(!1)}},[s,a,n]),z=t.useCallback(async()=>{try{const[l,r]=await Promise.all([Is(s,a),Vs(s,{limit:50},a)]);N(l),w(r)}catch(l){n(`Failed to load ratings: ${Se(l)}`,"error")}finally{g(!1)}},[s,a,n]);t.useEffect(()=>{W(),z()},[W,z]);const Y=async()=>{f(!0);try{if(!await Js(s,a)){n("Not enough history to generate a reflection yet","error");return}n("Reflection generated successfully","success"),v(!0),await W()}catch(l){const r=Se(l),C=r.toLowerCase();C.includes("agent not found")||C.includes("not found")?n("This agent is no longer available. It may have been deleted.","error"):C.includes("insufficient history")?n("Not enough history to generate a reflection yet","error"):n(`Failed to generate reflection: ${r}`,"error")}finally{f(!1)}},F=async l=>{if(l.preventDefault(),p!==0){k(!0);try{await qs(s,{score:p,category:b||void 0,comment:G||void 0,raterType:"user"},a),x(0),D(""),T(""),n("Rating added","success"),await z()}catch(r){n(`Failed to add rating: ${Se(r)}`,"error")}finally{k(!1)}}},H=async l=>{try{await Gs(s,l,a),n("Rating deleted","success"),await z()}catch(r){n(`Failed to delete rating: ${Se(r)}`,"error")}},R=l=>{h(r=>r===l?null:l)};if(L&&A)return e.jsx("div",{className:"reflections-tab",children:e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(I,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading evaluation..."})]})});const V=m&&m.totalTasksCompleted===0&&m.totalTasksFailed===0&&m.recentReflectionCount===0;return e.jsxs("div",{className:"reflections-tab",children:[e.jsxs("div",{className:"reflections-header",children:[e.jsxs("h3",{children:[e.jsx(Le,{size:16}),"Performance, Reflections & Ratings"]}),e.jsx("button",{className:"btn btn-secondary",onClick:Y,disabled:y,title:"Generate a manual reflection",children:y?e.jsxs(e.Fragment,{children:[e.jsx(I,{size:14,className:"animate-spin"}),"Reflecting..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Xe,{size:14}),"Reflect Now"]})})]}),m&&!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(gs,{size:16,style:{color:"var(--color-success)"}}),m.totalTasksCompleted]}),e.jsx("div",{className:"stat-label",children:"Tasks Completed"})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(Tt,{size:16,style:{color:"var(--color-error)"}}),m.totalTasksFailed]}),e.jsx("div",{className:"stat-label",children:"Tasks Failed"})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(Us,{size:16,style:{color:"var(--in-progress)"}}),xs(m.avgDurationMs)]}),e.jsx("div",{className:"stat-label",children:"Avg Duration"})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(Le,{size:16,style:{color:m.successRate>=.8?"var(--color-success)":m.successRate>=.5?"var(--color-warning)":"var(--color-error)"}}),Et(m.successRate)]}),e.jsx("div",{className:"stat-label",children:"Success Rate"})]}),e.jsxs("div",{className:"reflections-stat-card",children:[e.jsxs("div",{className:"stat-value",children:[e.jsx(qe,{size:16,style:{color:"var(--color-info)"}}),m.recentReflectionCount]}),e.jsx("div",{className:"stat-label",children:"Reflections"})]})]}),V&&e.jsxs("div",{className:"reflections-no-data",children:[e.jsx(Le,{size:24,opacity:.3}),e.jsx("p",{children:"No performance data yet"})]}),e.jsxs("div",{className:"reflections-ratings-section",children:[e.jsx("h4",{children:"User Ratings"}),A?e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(I,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading ratings..."})]}):e.jsxs(e.Fragment,{children:[u&&e.jsxs("div",{className:"rating-summary-card",children:[e.jsxs("div",{className:"rating-score-display",children:[e.jsx("span",{className:"rating-average",children:u.averageScore.toFixed(1)}),vs(Math.round(u.averageScore))]}),e.jsxs("div",{className:"rating-stats",children:[e.jsxs("span",{className:"rating-count",children:[u.totalRatings," ratings"]}),e.jsx("span",{className:`rating-trend-badge ${Dt(u.trend)}`,children:Lt(u.trend)})]})]}),u&&Object.keys(u.categoryAverages).length>0&&e.jsxs("div",{className:"category-breakdown",children:[e.jsx("h4",{children:"Category Averages"}),Object.entries(u.categoryAverages).map(([l,r])=>e.jsxs("div",{className:"category-item",children:[e.jsx("span",{className:"category-name",children:l}),e.jsx("span",{className:"category-score",children:r.toFixed(1)})]},l))]}),e.jsxs("form",{className:"add-rating-form",onSubmit:F,children:[e.jsx("h4",{children:"Add Rating"}),e.jsx("div",{className:"star-selector",children:[1,2,3,4,5].map(l=>e.jsx("button",{type:"button",className:"star-btn touch-target",onClick:()=>x(l),title:`${l} star${l>1?"s":""}`,children:e.jsx(Ls,{size:24,fill:l<=p?"currentColor":"none",className:l<=p?"star-filled":"star-empty"})},l))}),e.jsxs("select",{value:b,onChange:l=>D(l.target.value),className:"select add-rating-category-select",children:[e.jsx("option",{value:"",children:"Select category..."}),e.jsx("option",{value:"quality",children:"Quality"}),e.jsx("option",{value:"speed",children:"Speed"}),e.jsx("option",{value:"communication",children:"Communication"}),e.jsx("option",{value:"reliability",children:"Reliability"}),e.jsx("option",{value:"other",children:"Other"})]}),e.jsx("textarea",{value:G,onChange:l=>T(l.target.value),placeholder:"Optional comment...",className:"input add-rating-comment-input",rows:3}),e.jsx("button",{type:"submit",className:"btn btn-task-create",disabled:p===0||J,children:J?"Submitting...":"Submit Rating"})]}),e.jsxs("div",{className:"rating-history",children:[e.jsx("h4",{children:"Rating History"}),c.length===0?e.jsx("p",{className:"no-ratings",children:"No ratings yet"}):c.map(l=>e.jsxs("div",{className:"rating-history-item",children:[e.jsxs("div",{className:"rating-item-header",children:[vs(l.score),l.category&&e.jsx("span",{className:"rating-category-badge",children:l.category}),e.jsx("span",{className:"rating-time",children:ps(l.createdAt)}),e.jsx("button",{type:"button",className:"rating-delete-btn touch-target",onClick:()=>void H(l.id),title:"Delete rating",children:e.jsx(De,{size:14})})]}),l.comment&&e.jsx("p",{className:"rating-comment",children:l.comment})]},l.id))]})]})]}),e.jsxs("div",{className:"reflections-list",children:[e.jsx("h4",{children:"Reflection History"}),L?e.jsxs("div",{className:"reflections-loading-indicator",children:[e.jsx(I,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading reflections..."})]}):d.length===0?e.jsxs("div",{className:"reflection-empty",children:[e.jsx(qe,{size:32,opacity:.3}),e.jsx("p",{children:"No reflections yet"}),e.jsx("p",{className:"text-secondary",children:"Trigger a reflection to get started"})]}):e.jsx("div",{className:"reflection-cards",children:d.map(l=>{const r=$===l.id;return e.jsxs("div",{className:`reflection-card ${r?"reflection-card--expanded":""}`,onClick:()=>R(l.id),role:"button",tabIndex:0,onKeyDown:C=>C.key==="Enter"&&R(l.id),children:[e.jsxs("div",{className:"reflection-card-header",children:[e.jsx("span",{className:`reflection-trigger-badge reflection-trigger-${l.trigger}`,children:$t(l.trigger)}),e.jsx("span",{className:"reflection-timestamp",children:ps(l.timestamp)}),e.jsx("span",{className:"reflection-chevron",children:r?e.jsx(ys,{size:16}):e.jsx(Ss,{size:16})})]}),e.jsx("div",{className:"reflection-summary",children:l.summary}),r&&e.jsxs("div",{className:"reflection-details",children:[l.insights.length>0&&e.jsxs("div",{className:"reflection-insights",children:[e.jsxs("h5",{children:[e.jsx(qe,{size:14})," Insights"]}),e.jsx("ul",{children:l.insights.map((C,X)=>e.jsx("li",{children:C},X))})]}),l.suggestedImprovements.length>0&&e.jsxs("div",{className:"reflection-suggestions",children:[e.jsxs("h5",{children:[e.jsx(gs,{size:14})," Suggested Improvements"]}),e.jsx("ul",{children:l.suggestedImprovements.map((C,X)=>e.jsx("li",{children:C},X))})]}),l.metrics&&e.jsxs("div",{className:"reflection-metrics",children:[e.jsx("h5",{children:"Metrics"}),e.jsxs("div",{className:"metrics-grid",children:[l.metrics.tasksCompleted!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:"Tasks:"}),e.jsx("span",{className:"metric-value",children:l.metrics.tasksCompleted})]}),l.metrics.tasksFailed!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:"Failed:"}),e.jsx("span",{className:"metric-value",children:l.metrics.tasksFailed})]}),l.metrics.avgDurationMs!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:"Avg Duration:"}),e.jsx("span",{className:"metric-value",children:xs(l.metrics.avgDurationMs)})]}),l.metrics.errorCount!==void 0&&e.jsxs("div",{className:"metric",children:[e.jsx("span",{className:"metric-label",children:"Errors:"}),e.jsx("span",{className:"metric-value",children:l.metrics.errorCount})]})]})]})]})]},l.id)})})]})]})}function zt({value:s,onChange:a,projectId:n,disabled:d=!1,id:o,label:m="Skills"}){const[j,u]=t.useState([]),[N,c]=t.useState(!0);t.useEffect(()=>{let g=!1;return c(!0),Ws(n).then(y=>{g||u(y)}).catch(()=>{g||u([])}).finally(()=>{g||c(!1)}),()=>{g=!0}},[n]);const w=g=>{s.includes(g)||a([...s,g])},L=g=>{a(s.filter(y=>y!==g))},v=g=>j.find(f=>f.id===g)?.name??g,A=j.filter(g=>!s.includes(g.id));return e.jsxs("div",{className:"skill-multiselect","data-testid":"skill-multiselect",children:[m&&e.jsx("label",{htmlFor:o?`${o}-select`:void 0,className:"skill-multiselect-label",children:m}),s.length>0&&e.jsx("div",{className:"skill-multiselect-chips","data-testid":"skill-chips",children:s.map(g=>e.jsxs("span",{className:"skill-chip","data-testid":`skill-chip-${g}`,children:[e.jsx("span",{className:"skill-chip-name",children:v(g)}),e.jsx("button",{type:"button",className:"skill-chip-remove",onClick:()=>L(g),disabled:d,"aria-label":`Remove ${v(g)}`,"data-testid":`remove-skill-${g}`,children:"×"})]},g))}),e.jsx("div",{className:"skill-multiselect-add",children:N?e.jsx("span",{className:"skill-multiselect-loading","data-testid":"skills-loading",children:"Loading skills…"}):A.length===0?e.jsx("span",{className:"skill-multiselect-empty","data-testid":"skills-empty",children:s.length===0?"No skills discovered":"All skills selected"}):e.jsxs("select",{id:o?`${o}-select`:void 0,className:"select skill-multiselect-dropdown",value:"",onChange:g=>{g.target.value&&(w(g.target.value),g.target.value="")},disabled:d,"data-testid":"skill-dropdown",children:[e.jsx("option",{value:"",children:"Add a skill…"}),A.map(g=>e.jsx("option",{value:g.id,children:g.name},g.id))]})})]})}function ie(...s){return s.filter(Boolean).join(" ")}function pe(s){const a=Date.now(),n=new Date(s).getTime(),d=a-n;if(d<0){const o=Math.abs(d);return o<6e4?"in a moment":o<36e5?`in ${Math.floor(o/6e4)}m`:o<864e5?`in ${Math.floor(o/36e5)}h`:`in ${Math.floor(o/864e5)}d`}return d<6e4?"just now":d<36e5?`${Math.floor(d/6e4)}m ago`:d<864e5?`${Math.floor(d/36e5)}h ago`:`${Math.floor(d/864e5)}d ago`}const Ht=[{id:"dashboard",label:"Dashboard",icon:Ft},{id:"logs",label:"Logs",icon:Ce},{id:"runs",label:"Runs",icon:$e},{id:"tasks",label:"Tasks",icon:ws},{id:"employees",label:"Employees",icon:Ms},{id:"soul",label:"Soul",icon:Qs},{id:"instructions",label:"Instructions",icon:et},{id:"memory",label:"Agent Memory",icon:Ce},{id:"reflections",label:"Evaluation",icon:Le},{id:"config",label:"Settings",icon:st}],Qe={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)"},terminated:{bg:"var(--state-error-bg)",text:"var(--state-error-text)",border:"var(--state-error-border)"}},Pe={completed:{icon:ae,color:"var(--color-success)"},failed:{icon:ct,color:"var(--color-error)"},active:{icon:I,color:"var(--in-progress)"},terminated:{icon:Re,color:"var(--text-muted)"}},bs={"long-term":"Long-term",daily:"Daily",dreams:"Dreams"},Bt={"long-term":"Curated durable decisions, conventions, constraints, and pitfalls for this specific agent.",daily:"Raw daily observations and open loops recorded by this agent.",dreams:"Synthesized patterns and emerging themes distilled from this agent's daily memory."},Ot=Ts(Ye);function _t(s,a){return s.some(n=>n.path===a)?a:s.find(n=>n.layer==="long-term")?.path??s[0]?.path??""}function It({agentId:s,projectId:a,onClose:n,addToast:d,onChildClick:o,inline:m=!1,initialTab:j,initialRunId:u,preferActiveRun:N=!1}){const[c,w]=t.useState(null),{confirm:L}=ks(),[v,A]=t.useState([]),[g,y]=t.useState(!0),[f,J]=t.useState(j??"dashboard"),[k,$]=t.useState(!1),[h,p]=t.useState(!1),[x,b]=t.useState(null),D=t.useRef(null),G=t.useRef(null),T=t.useRef(!1);Ks(G,!m,"fusion:agent-detail-modal-size");const W=t.useRef(n),z=t.useRef(d),Y=t.useRef(null),F=t.useRef(!1),H=t.useRef(null),R=t.useRef(0),V=t.useRef(s),l=t.useRef(a);W.current=n,z.current=d,Y.current=c;const r=t.useCallback(async()=>{Y.current===null&&y(!0);try{const K=await Ys(s,a);w(K)}catch(K){z.current(`Failed to load agent: ${Z(K)}`,"error"),W.current()}finally{y(!1)}},[s,a]),C=t.useCallback(async()=>{const S=R.current,K=s,q=a,U=()=>R.current!==S||s!==K||a!==q;try{if(c?.taskId){b(null),H.current=null;const ue=await Zs(c.taskId,q,{limit:100});if(U())return;A(ue.entries);return}const ce=await Rs(K,1,q);if(U())return;const te=ce[0]??null;if(b(te),!te){H.current=null,A([]);return}if(H.current===te.id)return;const de=await Cs(K,te.id,q);if(U())return;A([...de].reverse()),H.current=te.id}catch(ce){if(U())return;console.error("Failed to load agent logs:",ce)}},[c?.taskId,s,a]),X=t.useCallback(S=>{F.current=S},[]);t.useEffect(()=>{r()},[r]),t.useEffect(()=>{const S=setInterval(()=>{r()},3e4);return()=>{clearInterval(S)}},[r]),t.useEffect(()=>{c&&f==="logs"&&C()},[c,f,C]),t.useEffect(()=>{f!=="logs"&&(H.current=null)},[f]),t.useEffect(()=>{if(f!=="logs"||c?.taskId||!x||x.status!=="active")return;const S=R.current,K=s,q=x.id,U=a?`?projectId=${encodeURIComponent(a)}`:"",ce=Ee(`/api/agents/${encodeURIComponent(K)}/runs/${encodeURIComponent(q)}/logs/stream${U}`,{events:{"agent:log":te=>{if(R.current===S)try{const de=JSON.parse(te.data);A(ue=>[de,...ue])}catch{}}},onOpen:()=>{R.current===S&&$(!0)},onError:()=>{R.current===S&&$(!1)}});return()=>{ce(),R.current===S&&$(!1)}},[f,c?.taskId,s,a,x]),t.useEffect(()=>{(V.current!==s||l.current!==a)&&(V.current=s,l.current=a,R.current++,A([]),$(!1),b(null),H.current=null,F.current=!1)},[s,a]),t.useEffect(()=>{const S=a?`?projectId=${encodeURIComponent(a)}`:"",K=R.current;return Ee(`/api/events${S}`,{events:{"agent:updated":q=>{if(R.current===K)try{const U=JSON.parse(q.data);if(!U||typeof U!="object"||U.id!==s||F.current)return;r()}catch{}}}})},[s,a,r]),t.useEffect(()=>{if(f!=="logs"||!c?.taskId){$(!1);return}const S=R.current,K=c.taskId,q=a?`?projectId=${encodeURIComponent(a)}`:"",U=Ee(`/api/tasks/${encodeURIComponent(K)}/logs/stream${q}`,{events:{"agent:log":ce=>{if(R.current===S)try{const te=JSON.parse(ce.data);A(ue=>[te,...ue]);const de=D.current;de&&de.scrollTop<50&&(de.scrollTop=0)}catch{}}},onOpen:()=>{R.current===S&&$(!0)},onError:()=>{R.current===S&&$(!1)}});return()=>{U(),R.current===S&&$(!1)}},[c?.taskId,f,a]);const se=async S=>{if(h||!Y.current)return;const K=Y.current.state;if(K!==S){p(!0),w(q=>q&&{...q,state:S});try{await nt(s,S,a),d(`Agent state updated to ${S}`,"success"),r()}catch(q){w(U=>U&&{...U,state:K}),d(`Failed to update state: ${Z(q)}`,"error")}finally{p(!1)}}},me=async()=>{if(!(!c||!await L({title:"Delete Agent",message:`Delete agent "${c.name}"? This cannot be undone.`,danger:!0})))try{await it(s,a),d(`Agent "${c.name}" deleted`,"success"),n()}catch(K){d(`Failed to delete agent: ${Z(K)}`,"error")}},xe=()=>c?at(c):{label:"Unknown",icon:e.jsx(We,{size:14}),color:"var(--text-muted)",stateDerived:!1},E=()=>{c&&(navigator.clipboard.writeText(c.id),d("Agent ID copied to clipboard","success"))};if(g)return m?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(I,{className:"animate-spin",size:24}),e.jsx("span",{children:"Loading agent..."})]})}):e.jsx("div",{className:"agent-detail-overlay",onMouseDown:S=>{S.target===S.currentTarget&&(T.current=!0)},onMouseUp:S=>{T.current&&S.target===S.currentTarget&&n(),T.current=!1},role:"dialog","aria-modal":"true",children:e.jsx("div",{className:"agent-detail-modal",ref:G,children:e.jsxs("div",{className:"agent-detail-loading",children:[e.jsx(I,{className:"animate-spin",size:24}),e.jsx("span",{children:"Loading agent..."})]})})});if(!c)return null;const _=Qe[c.state],re=xe(),_e=m?"agent-detail-inline":"agent-detail-modal";return e.jsx("div",{className:m?"agent-detail-inline-shell":"agent-detail-overlay",onClick:S=>!m&&S.target===S.currentTarget&&n(),role:m?"region":"dialog","aria-label":m?"Agent detail":void 0,"aria-modal":m?void 0:"true",children:e.jsxs("div",{className:_e,ref:G,children:[e.jsxs("div",{className:"agent-detail-header",children:[e.jsxs("div",{className:"agent-detail-identity",children:[e.jsx("div",{className:"agent-detail-icon",children:e.jsx(We,{size:20})}),e.jsxs("div",{className:"agent-detail-info",children:[e.jsx("h2",{children:c.name}),e.jsxs("div",{className:"agent-detail-badges",children:[e.jsx("span",{className:"badge",style:{background:_.bg,color:_.text,border:`1px solid ${_.border}`},children:c.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:[c.state==="idle"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void se("active"),disabled:h,children:[e.jsx(Te,{size:14}),"Start"]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:me,children:[e.jsx(De,{size:14}),"Delete"]})]}),c.state==="active"&&e.jsxs("button",{className:"btn btn--compact",onClick:()=>void se("paused"),disabled:h,children:[e.jsx(fs,{size:14}),"Pause"]}),c.state==="paused"&&e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void se("active"),disabled:h,children:[e.jsx(Te,{size:14}),"Resume"]}),c.state==="running"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--compact",onClick:()=>void se("paused"),disabled:h,children:[e.jsx(fs,{size:14}),"Pause"]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:()=>void se("terminated"),disabled:h,children:[e.jsx(Re,{size:14}),"Stop"]})]}),c.state==="error"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void se("active"),disabled:h,children:[e.jsx(Te,{size:14}),"Retry"]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:()=>void se("terminated"),disabled:h,children:[e.jsx(Re,{size:14}),"Stop"]})]}),c.state==="terminated"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-task-create btn--compact",onClick:()=>void se("active"),disabled:h,children:[e.jsx(Te,{size:14}),"Start"]}),e.jsxs("button",{className:"btn btn--danger btn--compact",onClick:me,children:[e.jsx(De,{size:14}),"Delete"]})]})]}),e.jsxs("div",{className:"agent-detail-utility-actions",children:[e.jsx("button",{className:"btn-icon",onClick:()=>void r(),title:"Refresh",children:e.jsx(Xe,{size:16})}),!m&&e.jsx("button",{className:"btn-icon",onClick:n,"aria-label":"Close",title:"Close",children:e.jsx(Xs,{size:20})})]})]})]}),e.jsx("div",{className:"agent-detail-tabs",children:Ht.map(S=>e.jsxs("button",{className:ie("agent-detail-tab",f===S.id&&"active"),onClick:()=>J(S.id),children:[e.jsx(S.icon,{size:16}),S.label]},S.id))}),e.jsxs("div",{className:"agent-detail-content",children:[f==="dashboard"&&e.jsx(Vt,{agent:c,health:re,onChildClick:o,projectId:a}),f==="logs"&&e.jsx(Ut,{logs:v,isStreaming:k,containerRef:D,hasTask:!!c.taskId||v.length>0||x!==null,fallbackLabel:!c.taskId&&x?`Latest run · ${x.id.slice(0,8)}`:null}),f==="runs"&&e.jsx(qt,{addToast:d,agentId:c.id,projectId:a,agentState:c.state,agentName:c.name,initialRunId:u,preferActiveRun:N}),f==="tasks"&&e.jsx(Yt,{agentId:c.id,projectId:a,addToast:d}),f==="employees"&&e.jsx(aa,{agentId:c.id,projectId:a,onChildClick:o}),f==="soul"&&e.jsx(Xt,{agent:c,projectId:a,addToast:d,onSaved:r}),f==="instructions"&&e.jsx(ea,{agent:c,projectId:a,addToast:d,onSaved:r}),f==="memory"&&e.jsx(Qt,{agent:c,projectId:a,addToast:d,onSaved:r}),f==="reflections"&&e.jsx(Pt,{agentId:c.id,projectId:a,addToast:d}),f==="config"&&e.jsx(ta,{agent:c,projectId:a,addToast:d,onSaved:r,onHasChangesChange:X,onDelete:me})]}),!m&&e.jsxs("div",{className:"agent-detail-footer",children:[e.jsx("button",{className:"btn-icon",onClick:E,title:"Copy Agent ID",children:e.jsx(tt,{})}),e.jsx("span",{className:"agent-detail-id",onClick:E,children:c.id}),c.taskId&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"divider",children:"|"}),e.jsx("span",{className:"text-muted",children:"Working on:"}),e.jsxs("a",{href:`/tasks/${c.taskId}`,className:"link",children:[c.taskId,e.jsx(Fs,{size:12})]})]})]})]})})}function Vt({agent:s,health:a,onChildClick:n,projectId:d}){const o=Qe[s.state],[m,j]=t.useState([]),[u,N]=t.useState(!0),[c,w]=t.useState(null),[L,v]=t.useState([]),A=typeof s.runtimeConfig?.runtimeHint=="string"?s.runtimeConfig.runtimeHint:"",g=(()=>{const h=s.runtimeConfig??{};if(A){const p=L.find(x=>x.runtimeId===A);return p?p.name:A}if(h.modelProvider&&h.modelId)return`${h.modelProvider}/${h.modelId}`;if(typeof h.model=="string"&&h.model.includes("/")){const p=h.model.indexOf("/");return h.model.slice(p+1)}return null})();t.useEffect(()=>{Ke(s.id,d).then(w).catch(()=>w(null))},[s.id,d]),t.useEffect(()=>{As(d).then(v).catch(()=>v([]))},[d]),t.useEffect(()=>{let h=!1;return N(!0),rt(s.id,d).then(p=>{if(h)return;const x=p.length>0&&p[0]?.id===s.id?[...p].reverse():p;j(x)}).catch(()=>{h||j([])}).finally(()=>{h||N(!1)}),()=>{h=!0}},[s.id,d]);const y=t.useMemo(()=>{const h=s.completedRuns||[],p=new Date;p.setHours(0,0,0,0);const x=h.filter(D=>new Date(D.startedAt)>=p),b=h.filter(D=>D.status==="completed");return{totalRuns:h.length,todayRuns:x.length,successfulRuns:b.length,successRate:h.length>0?Math.round(b.length/h.length*100):0}},[s]),f=(s.completedRuns||[]).slice(0,5),J=s.state==="active"||s.state==="running",k=lt(s.runtimeConfig?.heartbeatIntervalMs),$=J&&s.lastHeartbeatAt?new Date(new Date(s.lastHeartbeatAt).getTime()+k).toISOString():null;return e.jsxs("div",{className:"dashboard-tab dashboard-summary-layout",children:[c?.isOverBudget&&e.jsxs("div",{className:"budget-warning-banner",role:"alert",children:[e.jsx("span",{children:"⚠️"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Budget Exhausted:"})," This agent has exceeded its token budget and may operate with limited functionality."]})]}),e.jsxs("section",{className:"dashboard-summary-card dashboard-summary-hero",children:[e.jsxs("div",{className:"dashboard-summary-hero__heading",children:[e.jsx(We,{}),e.jsx("h3",{children:"Overview"}),e.jsx("strong",{children:s.name}),e.jsx("span",{className:"inline-badge",style:{background:o.bg,color:o.text},children:s.state})]}),e.jsxs("div",{className:"dashboard-summary-hero__meta",children:[e.jsxs("span",{className:"dashboard-summary-hero__health",title:a.reason??a.label,children:[a.icon," ",a.label]}),e.jsxs("span",{children:["Role: ",s.role]}),e.jsxs("span",{children:[e.jsx("span",{className:"dashboard-summary-label",children:A?"Runtime":"Model"}),e.jsxs("span",{children:[" ",g??"Auto"]})]}),Array.isArray(s.metadata?.skills)&&s.metadata.skills.length>0?e.jsxs("span",{children:["Skills: ",s.metadata.skills.join(", ")]}):e.jsx("span",{children:"Skills: —"})]})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:"Heartbeat & Health"}),e.jsxs("div",{className:"dashboard-summary-grid",children:[e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:"Last heartbeat"}),e.jsx("p",{children:s.lastHeartbeatAt?pe(s.lastHeartbeatAt):"Never"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:"Next expected"}),e.jsx("p",{children:$?pe($):"Not scheduled"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:"Interval"}),e.jsx("p",{children:Ts(k)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"dashboard-summary-label",children:"Status"}),e.jsxs("p",{className:"dashboard-summary-health-row",children:[e.jsx("span",{className:ie("status-dot",s.state==="running"&&"status-dot--running")}),a.label,a.reason&&e.jsxs("span",{className:"text-secondary",style:{marginLeft:"var(--space-xs)",fontSize:"12px"},title:a.reason,children:["(",a.reason,")"]})]})]})]})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:"Current Work"}),s.taskId?e.jsxs("div",{className:"current-task",children:[e.jsx("a",{href:`/tasks/${s.taskId}`,className:"task-badge",children:s.taskId}),e.jsxs("a",{href:`/tasks/${s.taskId}`,className:"btn btn-sm",children:["View Task ",e.jsx(Fs,{size:14})]})]}):e.jsx("p",{className:"text-muted",children:"No active assignment"})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:"Recent Runs"}),e.jsxs("p",{className:"dashboard-summary-label",children:[y.successfulRuns,"/",y.totalRuns," successful (",y.successRate,"%)"]}),f.length===0?e.jsx("p",{className:"text-muted",children:"No runs yet"}):e.jsx("div",{className:"runs-list",children:f.map(h=>{const p=Pe[h.status]||Pe.terminated,x=p.icon;return e.jsxs("div",{className:"run-item",children:[e.jsx(x,{size:14,style:{color:p.color}}),e.jsx("span",{children:pe(h.startedAt)}),e.jsxs("span",{className:"text-muted",children:[Math.max(0,Math.round((new Date(h.endedAt||h.startedAt).getTime()-new Date(h.startedAt).getTime())/1e3)),"s"]})]},h.id)})})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:"Throughput"}),e.jsxs("div",{className:"stats-grid",children:[e.jsxs("div",{className:"stat-card",children:[e.jsx("div",{className:"stat-value",children:y.totalRuns}),e.jsx("div",{className:"stat-label",children:"Total Runs"})]}),e.jsxs("div",{className:"stat-card",children:[e.jsx("div",{className:"stat-value",children:y.todayRuns}),e.jsx("div",{className:"stat-label",children:"Runs Today"})]}),e.jsxs("div",{className:"stat-card",children:[e.jsxs("div",{className:"stat-value",children:[y.successRate,"%"]}),e.jsx("div",{className:"stat-label",children:"Success Rate"})]})]})]}),e.jsxs("section",{className:"dashboard-summary-card",children:[e.jsx("h3",{children:"Chain of Command"}),u?e.jsxs("div",{className:"chain-of-command-loading",role:"status","aria-live":"polite",children:[e.jsx(I,{size:14,className:"animate-spin"}),e.jsx("span",{children:"Loading reporting chain..."})]}):m.length<=1?e.jsx("p",{className:"text-muted",children:"No reporting chain"}):e.jsx("div",{className:"chain-of-command-path","aria-label":"Chain of command",children:m.map((h,p)=>{const x=p===m.length-1,b=!x;return e.jsxs("div",{className:"chain-of-command-item",children:[e.jsx("button",{type:"button",className:`chain-of-command-node${x?" chain-of-command-node--current":""}`,onClick:()=>b&&n?.(h.id),disabled:!b||!n,title:x?"Current agent":`View ${h.name}`,children:h.name}),!x&&e.jsx("span",{className:"chain-of-command-separator","aria-hidden":"true",children:"→"})]},h.id)})})]})]})}function Ut({logs:s,isStreaming:a,containerRef:n,hasTask:d,fallbackLabel:o}){return d?e.jsxs("div",{className:"logs-tab",children:[e.jsxs("div",{className:"logs-header",children:[e.jsxs("span",{className:"logs-count",children:[s.length," entries"]}),o&&e.jsx("span",{className:"text-muted logs-fallback-label",children:o}),a&&e.jsxs("span",{className:"streaming-indicator",children:[e.jsx("span",{className:"streaming-dot"}),"Live"]})]}),e.jsx("div",{ref:n,className:"logs-container",children:s.length===0?e.jsxs("div",{className:"logs-empty",children:[e.jsx(Ce,{size:48,opacity:.3}),e.jsx("p",{children:"No log entries yet"}),e.jsx("p",{className:"text-muted",children:a?"Waiting for activity...":"Logs will appear here when the agent is active"})]}):s.map((m,j)=>{const u=j>0?s[j-1]:void 0,N=!u||u.agent!==m.agent;return e.jsx(Jt,{entry:m,showTimestamp:N},`${m.timestamp}-${j}`)})})]}):e.jsx("div",{className:"logs-tab",children:e.jsxs("div",{className:"logs-empty",children:[e.jsx(Ce,{size:48,opacity:.3}),e.jsx("p",{children:"No activity yet"}),e.jsx("p",{className:"text-muted",children:"Agent logs will appear here from the current task or most recent run"})]})})}function Jt({entry:s,showTimestamp:a}){const d=(()=>{switch(s.type){case"tool":return{color:"var(--accent)",borderLeft:"3px solid var(--accent)",background:"var(--log-tool-bg)"};case"tool_result":return{color:"var(--color-success)",borderLeft:"3px solid var(--color-success)",background:"var(--log-success-bg)"};case"tool_error":return{color:"var(--color-error)",borderLeft:"3px solid var(--color-error)",background:"var(--log-error-bg)"};case"thinking":return{color:"var(--text-muted)",fontStyle:"italic",opacity:.7};default:return{color:"var(--text)"}}})(),o=new Date(s.timestamp).toLocaleTimeString();return e.jsxs("div",{className:"log-entry",style:d,children:[a&&e.jsxs("span",{className:"log-timestamp",children:["[",o,"]"]}),s.agent&&e.jsxs("span",{className:"log-agent",children:["[",s.agent,"]"]}),s.type==="tool"&&e.jsx("span",{className:"log-icon",children:"⚡"}),s.type==="tool_result"&&e.jsx("span",{className:"log-icon",children:"✓"}),s.type==="tool_error"&&e.jsx("span",{className:"log-icon",children:"✗"}),e.jsxs("span",{className:"log-text",children:[s.text,s.detail&&e.jsxs("span",{className:"log-detail",children:[" — ",s.detail]})]})]})}function qt({addToast:s,agentId:a,projectId:n,agentState:d,agentName:o,initialRunId:m,preferActiveRun:j}){const[u,N]=t.useState([]),{confirm:c}=ks(),[w,L]=t.useState(!0),[v,A]=t.useState(null),[g,y]=t.useState([]),[f,J]=t.useState(!1),[k,$]=t.useState(null),[h,p]=t.useState(!1),x=t.useRef(!1),b=t.useCallback(async()=>{try{const r=await Rs(a,50,n);N(r)}catch(r){s(`Failed to load runs: ${Z(r)}`,"error")}finally{L(!1)}},[a,n,s]);t.useEffect(()=>{b()},[b]);const D=u.some(r=>r.status==="active"),G=v?u.find(r=>r.id===v)?.status:void 0;t.useEffect(()=>{if(!D)return;const r=setInterval(()=>{b()},5e3);return()=>clearInterval(r)},[D,b]),t.useEffect(()=>{if(!v||G!=="active")return;const r=n?`?projectId=${encodeURIComponent(n)}`:"";return Ee(`/api/agents/${encodeURIComponent(a)}/runs/${encodeURIComponent(v)}/logs/stream${r}`,{events:{"agent:log":C=>{try{const X=JSON.parse(C.data);y(se=>[...se,X])}catch{}}}})},[v,G,a,n]);const T=t.useCallback(async r=>{if(v===r){A(null),y([]),$(null);return}A(r),J(!0),p(!0),y([]),$(null);try{const[C,X]=await Promise.all([Cs(a,r,n),ot(a,r,n)]);y(C),$(X)}catch(C){s(`Failed to load run details: ${Z(C)}`,"error"),y([]),$(null)}finally{J(!1),p(!1)}},[v,a,n,s]);t.useEffect(()=>{x.current=!1},[a,m,j]),t.useEffect(()=>{if(u.length===0||w||x.current)return;const r=m?u.find(C=>C.id===m):j?u.find(C=>C.status==="active"):null;x.current=!0,r&&T(r.id)},[m,j,u,w,T]);const W=async()=>{try{await pt(a,n,{source:"on_demand",triggerDetail:"Triggered from dashboard"}),s(`Heartbeat run started for ${o??a}`,"success"),L(!0),b()}catch(r){s(`Failed to start heartbeat run: ${Z(r)}`,"error")}},z=async()=>{if(await c({title:"Stop Active Run",message:"Stop the active run? The agent's work will be interrupted.",danger:!0}))try{await vt(a,n),s("Run stopped","success"),L(!0),b()}catch(C){s(`Failed to stop run: ${Z(C)}`,"error")}},Y=d==="active"||d==="idle";if(w&&u.length===0)return e.jsx("div",{className:"runs-tab",children:e.jsxs("div",{className:"runs-loading-row",children:[e.jsx(I,{size:16,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading runs..."})]})});if(u.length===0)return e.jsxs("div",{className:"runs-tab",children:[Y&&e.jsx("div",{className:"runs-toolbar",children:e.jsxs("button",{className:"btn btn--sm btn-task-create",onClick:()=>void W(),"aria-label":`Run now for ${o??a}`,children:[e.jsx($e,{size:14})," Run Now"]})}),e.jsxs("div",{className:"runs-empty",children:[e.jsx($e,{size:48,opacity:.3}),e.jsx("p",{children:"No runs yet"}),e.jsx("p",{className:"text-muted",children:"Heartbeat runs will appear here"})]})]});const F=[...u].sort((r,C)=>new Date(C.startedAt).getTime()-new Date(r.startedAt).getTime()),H=F.filter(r=>r.status==="active"),R=F.filter(r=>r.status!=="active"),V=r=>r?e.jsxs("div",{className:"run-usage",children:[e.jsxs("span",{children:["Input: ",r.inputTokens.toLocaleString()]}),e.jsxs("span",{children:["Output: ",r.outputTokens.toLocaleString()]}),r.cachedTokens>0&&e.jsxs("span",{children:["Cached: ",r.cachedTokens.toLocaleString()]})]}):null,l=(r,C,X)=>{const se=Pe[r.status]||Pe.completed,me=se.icon,xe=r.endedAt?Gt(new Date(r.startedAt),new Date(r.endedAt)):"In progress",E=v===r.id;return e.jsxs("div",{children:[e.jsxs("div",{className:ie("run-card",X&&"run-card--active",E&&"run-card--selected","run-card--clickable"),onClick:()=>void T(r.id),role:"button",tabIndex:0,"aria-expanded":E,"aria-label":`${X?"Active":""} run ${r.id.slice(0,8)}, ${r.status}`,onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.preventDefault(),T(r.id))},children:[e.jsxs("div",{className:"run-header",children:[e.jsxs("div",{className:"run-header-group",children:[E?e.jsx(ys,{size:14}):e.jsx(Ss,{size:14}),X?e.jsxs("span",{className:"run-live-indicator",children:[e.jsx("span",{className:"live-dot"}),"Live Run"]}):e.jsxs("span",{className:"run-id",children:["#",C+1," ",r.id.slice(0,8)]})]}),e.jsxs("div",{className:"run-header-group",children:[r.invocationSource&&e.jsx("span",{className:"badge run-badge--compact",children:r.invocationSource}),X&&e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:_=>{_.preventDefault(),_.stopPropagation(),z()},"aria-label":"Stop active run",children:[e.jsx(Re,{size:12})," Stop"]}),e.jsxs("span",{className:ie("run-status",r.status),children:[e.jsx(me,{size:14,className:se.color}),r.status]}),r.heartbeatProcedureSource==="custom"&&e.jsx("span",{className:"badge run-badge--compact",children:"Heartbeat: custom"})]})]}),e.jsxs("div",{className:"run-details",children:[e.jsxs("span",{children:["Started ",pe(r.startedAt)]}),e.jsx("span",{children:"•"}),e.jsx("span",{children:xe}),r.triggerDetail&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsx("span",{className:"text-muted",children:r.triggerDetail})]})]})]}),E&&e.jsxs("div",{className:"run-logs-container",children:[h?e.jsxs("div",{className:"run-details-loading-state",children:[e.jsx(I,{size:14,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading details..."})]}):k&&e.jsxs("div",{className:"run-output-sections",children:[e.jsx("div",{className:"run-output-section",children:e.jsxs("details",{children:[e.jsx("summary",{className:"run-output-label run-output-summary",children:"System Prompt"}),k.systemPrompt?e.jsx("pre",{className:"run-output-panel",children:k.systemPrompt}):e.jsx("div",{className:"text-muted run-output-empty",children:"System prompt not captured for this run"})]})}),e.jsx("div",{className:"run-output-section",children:e.jsxs("details",{children:[e.jsx("summary",{className:"run-output-label run-output-summary",children:"Execution Prompt"}),k.executionPrompt?e.jsx("pre",{className:"run-output-panel",children:k.executionPrompt}):e.jsx("div",{className:"text-muted run-output-empty",children:"Execution prompt not captured for this run"})]})}),k.usageJson&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:"Token Usage"}),V(k.usageJson)]}),k.stdoutExcerpt&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:"Output"}),e.jsx("pre",{className:"run-output-panel",children:k.stdoutExcerpt.length>2e3?`${k.stdoutExcerpt.slice(0,2e3)}
|
|
17
17
|
|
|
18
|
-
... (truncated, ${k.stdoutExcerpt.length} chars total)`:k.stdoutExcerpt})]}),k.stderrExcerpt&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label run-output-label--error",children:"Errors"}),e.jsx("pre",{className:"run-output-panel run-output-panel--error",children:k.stderrExcerpt})]}),k.resultJson&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:"Result"}),e.jsx("pre",{className:"run-output-panel",children:JSON.stringify(k.resultJson,null,2)})]}),k.contextSnapshot&&Object.keys(k.contextSnapshot).length>0&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:"Context"}),e.jsx("div",{className:"run-context-grid",children:Object.entries(k.contextSnapshot).map(([_,re])=>e.jsxs("span",{className:"run-context-item",children:[e.jsxs("span",{className:"text-muted",children:[_,":"]})," ",e.jsx("span",{children:String(re)})]},_))})]}),!k.stdoutExcerpt&&!k.stderrExcerpt&&!k.resultJson&&e.jsx("div",{className:"text-muted run-output-empty",children:"No output captured"})]}),e.jsxs("div",{className:"run-agent-logs-section",children:[e.jsx("div",{className:"run-output-label",children:"Agent Logs"}),f?e.jsxs("div",{className:"run-details-loading-state",children:[e.jsx(I,{size:14,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading logs..."})]}):g.length===0?e.jsx("div",{className:"text-muted run-output-empty",children:"No logs available for this run"}):e.jsx(bt,{entries:g,loading:!1})]})]})]},r.id)};return e.jsxs("div",{className:"runs-tab",children:[K&&e.jsxs("div",{className:"runs-toolbar runs-toolbar--between",children:[e.jsxs("span",{className:"runs-toolbar-meta",children:[u.length," run",u.length!==1?"s":"",D&&e.jsxs("span",{className:"run-live-indicator run-live-indicator--with-margin",children:[e.jsx("span",{className:"live-dot"}),"Live"]})]}),e.jsxs("div",{className:"run-header-group",children:[D&&e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void z(),"aria-label":`Stop active run for ${o??a}`,children:[e.jsx(Re,{size:14})," Stop Run"]}),e.jsxs("button",{className:"btn btn--sm btn-task-create",onClick:()=>void W(),"aria-label":`Run now for ${o??a}`,children:[e.jsx($e,{size:14})," Run Now"]})]})]}),H.map((r,C)=>l(r,C,!0)),R.map((r,C)=>l(r,H.length+C,!1))]})}function Gt(s,a){const n=Math.floor((a.getTime()-s.getTime())/1e3);return n<60?`${n}s`:n<3600?`${Math.floor(n/60)}m ${n%60}s`:`${Math.floor(n/3600)}h ${Math.floor(n%3600/60)}m`}const Wt={triage:"Triage",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"};function Yt(s){const a=s.title?.trim()||s.description?.trim()||s.id;return a.length>80?`${a.slice(0,77)}...`:a}function Kt({agentId:s,projectId:a,addToast:n}){const[d,o]=t.useState([]),[m,j]=t.useState(!0);return t.useEffect(()=>{let u=!1;return j(!0),dt(s,a).then(N=>{u||o(N)}).catch(N=>{u||(o([]),n(`Failed to load assigned tasks: ${Z(N)}`,"error"))}).finally(()=>{u||j(!1)}),()=>{u=!0}},[s,a,n]),m?e.jsxs("div",{className:"agent-tasks-empty",children:[e.jsx(I,{size:16,className:"animate-spin"}),e.jsx("p",{children:"Loading assigned tasks..."})]}):d.length===0?e.jsxs("div",{className:"agent-tasks-empty",children:[e.jsx(ws,{size:18}),e.jsx("p",{children:"No tasks assigned to this agent"})]}):e.jsx("div",{className:"agent-tasks-list",children:d.map(u=>e.jsxs("a",{className:"agent-task-item",href:`/tasks/${u.id}`,children:[e.jsxs("div",{className:"agent-task-row",children:[e.jsx("span",{className:"agent-task-id",children:u.id}),e.jsx("span",{className:`agent-task-column column-${u.column}`,children:Wt[u.column]})]}),e.jsx("div",{className:"agent-task-title",title:u.title||u.description||u.id,children:Yt(u)}),e.jsxs("div",{className:"agent-task-status",children:[u.status??"idle"," · Updated ",pe(u.updatedAt)]})]},u.id))})}const ke=[{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 Zt(s){const a={};for(const n of ke){const d=s[n.key]?.trim();if(d){if(n.type==="number"){const o=Number(d);if(Number.isNaN(o)||!Number.isFinite(o)){a[n.key]=`"${n.label}" must be a valid number`;continue}n.min!==void 0&&o<n.min&&(a[n.key]=`"${n.label}" must be at least ${n.min.toLocaleString()}`),n.max!==void 0&&o>n.max&&(a[n.key]=`"${n.label}" must be at most ${n.max.toLocaleString()}`)}if(n.type==="select"){const o=n.options?.map(m=>m.value)??[];o.length>0&&!o.includes(d)&&(a[n.key]=`"${n.label}" must be one of: ${o.join(", ")}`)}}}return a}function Xt({agent:s,projectId:a,addToast:n,onSaved:d}){const[o,m]=t.useState(s.soul??""),[j,u]=t.useState(!1),[N,c]=t.useState(!1),[w,L]=t.useState(!1),v=t.useRef(null);t.useEffect(()=>{m(s.soul??""),c(!1),L(!1)},[s.id,s.soul]),t.useEffect(()=>()=>{v.current&&clearTimeout(v.current)},[]);const A=o!==(s.soul??""),g=async()=>{if(o.length>1e4){n("Soul must be at most 10,000 characters","error");return}u(!0);try{await jt(s.id,o,a),n("Soul saved","success"),c(!0),v.current&&clearTimeout(v.current),v.current=setTimeout(()=>c(!1),3e3),await d()}catch(y){n(`Failed to save soul: ${Z(y)}`,"error")}finally{u(!1)}};return e.jsx("div",{className:"config-tab",children:e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Soul"}),e.jsx("p",{className:"config-description",children:"Define this agent's personality and identity."}),e.jsx("div",{className:"config-fields",children:e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-soul",children:"Agent Soul"}),e.jsx("div",{className:"agent-content-toolbar",children:e.jsxs("div",{className:"agent-content-mode-toggle",children:[e.jsxs("button",{className:`btn btn-sm ${w?"":"btn-primary"}`,onClick:()=>L(!1),disabled:!w,"aria-label":"Edit mode",children:[e.jsx(ze,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${w?"btn-primary":""}`,onClick:()=>L(!0),disabled:w,"aria-label":"Preview mode",children:[e.jsx(He,{size:14}),"Preview"]})]})}),w?o.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(Be,{remarkPlugins:[Oe],children:o})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:"No soul defined yet. Switch to Edit mode to define the agent's personality."}):e.jsx("textarea",{id:"agent-soul",className:"input config-textarea-mono",rows:12,placeholder:"Describe this agent's personality, tone, and behavioral traits...",value:o,onChange:y=>{m(y.target.value),c(!1)}}),!w&&e.jsx("span",{className:"config-hint",children:"Defines the agent's character and identity. Max 10,000 characters."})]})}),!w&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!A||j,onClick:()=>void g(),children:j?e.jsxs(e.Fragment,{children:[e.jsx(I,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ae,{size:16}),"Save Soul"]})}),!A&&N&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ae,{size:14}),"Soul saved"]})]})]})})}function Qt({agent:s,projectId:a,addToast:n,onSaved:d}){const[o,m]=t.useState(s.memory??""),[j,u]=t.useState(!1),[N,c]=t.useState(!1),[w,L]=t.useState(!1),[v,A]=t.useState([]),[g,y]=t.useState(!1),[f,J]=t.useState(""),[k,$]=t.useState(""),[h,p]=t.useState(!1),[x,b]=t.useState(!1),[D,G]=t.useState(!1),[T,W]=t.useState(!1),[z,K]=t.useState(""),F=t.useRef(null),H=t.useRef(null),R=s.state==="running",V=o!==(s.memory??""),l=t.useMemo(()=>v.find(E=>E.path===f),[v,f]),r=l?Bt[l.layer]:"Select a memory file to view or edit.",C=t.useCallback(async E=>{b(!0);try{const _=await mt(s.id,E,a);J(_.path),$(_.content),p(!1),W(!1)}catch(_){n(`Failed to load agent memory file: ${Z(_)}`,"error")}finally{b(!1)}},[s.id,a,n]),X=t.useCallback(async(E="")=>{y(!0);try{const{files:_}=await ht(s.id,a);if(A(_),_.length===0){J(""),$(""),p(!1);return}const re=_t(_,E);await C(re)}catch(_){n(`Failed to load memory files: ${Z(_)}`,"error"),A([]),J(""),$(""),p(!1)}finally{y(!1)}},[s.id,a,n,C]);t.useEffect(()=>{m(s.memory??""),c(!1),L(!1),K(""),W(!1),X()},[s.id,s.memory,X]),t.useEffect(()=>()=>{F.current&&clearTimeout(F.current),H.current&&clearTimeout(H.current)},[]);const se=async()=>{if(o.length>5e4){n("Memory must be at most 50,000 characters","error");return}u(!0);try{await yt(s.id,o,a),n("Memory saved","success"),c(!0),F.current&&clearTimeout(F.current),F.current=setTimeout(()=>c(!1),3e3),await d()}catch(E){n(`Failed to save memory: ${Z(E)}`,"error")}finally{u(!1)}},me=async E=>{if(!(!E||E===f)){if(h){K("Save the current file before switching to another file.");return}K(""),await C(E)}},xe=async()=>{if(f){G(!0);try{await St(s.id,f,k,a),p(!1),W(!0),H.current&&clearTimeout(H.current),H.current=setTimeout(()=>W(!1),3e3),K(""),await X(f),n("Agent memory file saved","success")}catch(E){n(`Failed to save agent memory file: ${Z(E)}`,"error")}finally{G(!1)}}};return e.jsx("div",{className:"config-tab",children:e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Agent Memory"}),e.jsx("p",{className:"config-description",children:"Store context that belongs to this agent only. Workspace memory, daily notes, dreams, and qmd search live in project settings under Project Memory."}),R&&e.jsx("p",{className:"config-hint config-hint--block-spacing",children:"Read-only while this agent is running."}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-memory",children:"Inline Memory"}),e.jsx("span",{className:"config-hint config-hint--block",children:"Short-form memory stored directly on the agent record and injected into prompts."}),e.jsx("div",{className:"agent-content-toolbar",children:e.jsxs("div",{className:"agent-content-mode-toggle",children:[!R&&e.jsxs("button",{className:`btn btn-sm ${w?"":"btn-primary"}`,onClick:()=>L(!1),disabled:!w,"aria-label":"Edit mode",children:[e.jsx(ze,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${w?"btn-primary":""}`,onClick:()=>L(!0),disabled:w,"aria-label":"Preview mode",children:[e.jsx(He,{size:14}),"Preview"]})]})}),w?o.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(Be,{remarkPlugins:[Oe],children:o})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:"No agent memory defined yet. Switch to Edit mode to add memory content."}):e.jsx("textarea",{id:"agent-memory","aria-label":"Agent Memory",className:"input config-textarea-mono",rows:10,placeholder:"Durable preferences, operating habits, and context this agent should carry across tasks...",value:o,readOnly:R,onChange:E=>{m(E.target.value),c(!1)}}),!w&&e.jsx("span",{className:"config-hint",children:"This is the inline memory field on the agent JSON record. Max 50,000 characters."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-memory-file-select",children:"Memory Files"}),e.jsxs("span",{className:"config-hint config-hint--block",children:["Full OpenClaw memory files at ",e.jsxs("code",{children:[".fusion/agent-memory/",s.id,"/"]})," (MEMORY.md, DREAMS.md, and daily notes)."]}),e.jsx("select",{id:"agent-memory-file-select",className:"select",value:f,disabled:g||x||D||v.length===0,onChange:E=>{me(E.target.value)},children:v.length===0?e.jsx("option",{value:"",children:"No memory files found"}):v.map(E=>e.jsxs("option",{value:E.path,children:[bs[E.layer]," • ",E.label]},E.path))}),g&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(I,{size:14,className:"animate-spin"}),"Loading memory files…"]}),l&&e.jsxs("div",{className:"config-hint config-hint--top-spacing",children:[e.jsx("strong",{children:bs[l.layer]})," · ",r,e.jsx("br",{}),l.size.toLocaleString()," bytes · Updated ",pe(l.updatedAt)]}),e.jsx("textarea",{className:"input config-textarea-mono config-textarea-top-spacing",rows:14,placeholder:"Select a memory file to view and edit its content...",value:k,readOnly:R||!f||x,onChange:E=>{$(E.target.value),p(!0),W(!1),K("")}}),x&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(I,{size:14,className:"animate-spin"}),"Loading file content…"]}),z&&e.jsx("span",{className:"config-hint config-hint--top-spacing config-hint--block",children:z})]})]}),e.jsxs("div",{className:"config-actions",children:[!w&&e.jsx("button",{className:"btn btn-task-create",disabled:!V||j||R,onClick:()=>void se(),children:j?e.jsxs(e.Fragment,{children:[e.jsx(I,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ae,{size:16}),"Save Memory"]})}),e.jsx("button",{className:"btn",disabled:!h||D||!f||R,onClick:()=>void xe(),children:D?e.jsxs(e.Fragment,{children:[e.jsx(I,{size:16,className:"animate-spin"}),"Saving file…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ae,{size:16}),"Save Memory File"]})}),!V&&N&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ae,{size:14}),"Memory saved"]}),!h&&T&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ae,{size:14}),"Memory file saved"]})]})]})})}function ea({agent:s,projectId:a,addToast:n,onSaved:d}){const[o,m]=t.useState(s.instructionsText??""),[j,u]=t.useState(s.instructionsPath??""),[N,c]=t.useState(!1),[w,L]=t.useState(""),[v,A]=t.useState(!1),[g,y]=t.useState(!1),[f,J]=t.useState(!1),[k,$]=t.useState(!1),[h,p]=t.useState(!1),[x,b]=t.useState(!1),D=t.useRef(null),G=t.useRef(null);t.useEffect(()=>{const F=j.trim();if(!F){L(""),y(!1);return}A(!0),Es("project",F).then(H=>{L(H.content),y(!1)}).catch(H=>{const R=Z(H);R.includes("ENOENT")||R.includes("Not found")||R.includes("not found")?(L(""),y(!1)):(n(`Failed to load instructions file: ${R}`,"error"),L(""))}).finally(()=>{A(!1)})},[j,n]),t.useEffect(()=>{m(s.instructionsText??""),u(s.instructionsPath??""),p(!1),b(!1),c(!1)},[s.id,s.instructionsText,s.instructionsPath]),t.useEffect(()=>()=>{D.current&&clearTimeout(D.current),G.current&&clearTimeout(G.current)},[]);const T=(()=>{const F=o??"",H=s.instructionsText??"",R=j?.trim()??"",V=s.instructionsPath?.trim()??"";return F!==H||R!==V})(),W=async()=>{J(!0);try{await Nt(s.id,{instructionsText:o||void 0,instructionsPath:j.trim()||void 0},a),n("Instructions saved","success"),p(!0),D.current&&clearTimeout(D.current),D.current=setTimeout(()=>p(!1),3e3),await d()}catch(F){n(`Failed to save instructions: ${Z(F)}`,"error")}finally{J(!1)}},z=async()=>{const F=j.trim();if(!F){n("No instructions file path set","error");return}$(!0);try{await $s("project",F,w),n("Instructions file saved","success"),y(!1),b(!0),G.current&&clearTimeout(G.current),G.current=setTimeout(()=>b(!1),3e3)}catch(H){n(`Failed to save instructions file: ${Z(H)}`,"error")}finally{$(!1)}},K=!!j.trim();return e.jsxs("div",{className:"config-tab",children:[e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Custom Instructions"}),e.jsx("p",{className:"config-description",children:"Append custom instructions to this agent's system prompt at execution time. Use this to customize behavior, coding style, or project conventions without modifying built-in prompts."}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"instructions-text",children:"Inline Instructions"}),e.jsx("div",{className:"agent-content-toolbar",children:e.jsxs("div",{className:"agent-content-mode-toggle",children:[e.jsxs("button",{className:`btn btn-sm ${N?"":"btn-primary"}`,onClick:()=>c(!1),disabled:!N,"aria-label":"Edit mode","data-testid":"instructions-edit-toggle",children:[e.jsx(ze,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${N?"btn-primary":""}`,onClick:()=>c(!0),disabled:N,"aria-label":"Preview mode","data-testid":"instructions-preview-toggle",children:[e.jsx(He,{size:14}),"Preview"]})]})}),N?o.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(Be,{remarkPlugins:[Oe],children:o})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:"No inline instructions defined yet. Switch to Edit mode to add instructions."}):e.jsx("textarea",{id:"instructions-text",className:"input",rows:10,placeholder:"Enter custom instructions to append to this agent's system prompt...",value:o,onChange:F=>{m(F.target.value),p(!1)}}),!N&&e.jsx("span",{className:"config-hint",children:"Markdown formatting supported. Max 50,000 characters."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"instructions-path",children:"Instructions File Path"}),e.jsx("input",{id:"instructions-path",type:"text",className:"input",placeholder:"e.g., .fusion/agents/my-agent-instructions.md",value:j,onChange:F=>{u(F.target.value),p(!1)}}),e.jsx("span",{className:"config-hint",children:"Path to a .md file (relative to project root). Contents are read and appended at execution time."})]})]}),!N&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!T||f,onClick:()=>void W(),children:f?e.jsxs(e.Fragment,{children:[e.jsx(I,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ae,{size:16}),"Save Instructions"]})}),!T&&h&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ae,{size:14}),"Instructions saved"]})]})]}),K&&e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Instructions File Editor"}),e.jsx("p",{className:"config-description",children:"Edit the instructions file directly. Changes are saved separately from the path configuration."}),e.jsx("div",{className:"config-fields",children:e.jsxs("div",{className:"config-field",children:[e.jsxs("div",{className:"config-inline-header",children:[e.jsx("label",{htmlFor:"instructions-file-content",children:"File Content"}),v&&e.jsxs("span",{className:"config-hint config-hint--inline-tight",children:[e.jsx(I,{size:12,className:"animate-spin"}),"Loading..."]}),g&&!v&&e.jsx("span",{className:"config-hint config-hint--warning",children:"Unsaved changes"})]}),e.jsx("textarea",{id:"instructions-file-content",className:"input config-textarea-mono",rows:20,placeholder:"File content will appear here when loaded...",value:w,readOnly:v,onChange:F=>{L(F.target.value),y(!0),b(!1)}}),e.jsx("span",{className:"config-hint",children:"Edit the markdown file content directly. Save separately using the button below."})]})}),e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!g||k,onClick:()=>void z(),children:k?e.jsxs(e.Fragment,{children:[e.jsx(I,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ae,{size:16}),"Save File"]})}),!g&&x&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ae,{size:14}),"File saved"]})]})]})]})}function js(s){const a=s??{},n={};return a.heartbeatIntervalMs!==void 0&&a.heartbeatIntervalMs!==null&&(n.heartbeatIntervalMs=String(Number(a.heartbeatIntervalMs)/1e3)),a.heartbeatTimeoutMs!==void 0&&a.heartbeatTimeoutMs!==null&&(n.heartbeatTimeoutMs=String(Number(a.heartbeatTimeoutMs)/1e3)),a.maxConcurrentRuns!==void 0&&a.maxConcurrentRuns!==null&&(n.maxConcurrentRuns=String(a.maxConcurrentRuns)),(a.messageResponseMode==="immediate"||a.messageResponseMode==="on-heartbeat")&&(n.messageResponseMode=a.messageResponseMode),n}function Ge(s){return s?.enabled!==!1}function Ns(s){const a=(s??{}).budgetConfig,n={};return a&&(a.tokenBudget!==void 0&&a.tokenBudget!==null&&(n.tokenBudget=String(a.tokenBudget)),a.usageThreshold!==void 0&&a.usageThreshold!==null&&(n.usageThreshold=String(Number(a.usageThreshold)*100)),a.budgetPeriod!==void 0&&a.budgetPeriod!==null&&(n.budgetPeriod=String(a.budgetPeriod)),a.resetDay!==void 0&&a.resetDay!==null&&(n.resetDay=String(a.resetDay))),n}function sa({agent:s,projectId:a,addToast:n,onSaved:d}){const[o,m]=t.useState(!1),[j,u]=t.useState(!1),[N,c]=t.useState(!1),[w,L]=t.useState(!1),[v,A]=t.useState(!1),[g,y]=t.useState(""),[f,J]=t.useState(!1),[k,$]=t.useState(null),[h,p]=t.useState(!1),x=t.useRef(null),b=s.heartbeatProcedurePath?.trim(),D=`.fusion/agents/${s.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||s.id.toLowerCase().replace(/[^a-z0-9]+/g,"-")||"agent"}-${s.id.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"agent"}/HEARTBEAT.md`,G=`.fusion/agents/${s.id}/HEARTBEAT.md`,T=s.id.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"agent",W=!!(b&&(b===D||b===G||new RegExp(`^\\.fusion/agents/[^/]+-${T}/HEARTBEAT\\.md$`).test(b))),z=!!b,K=t.useCallback(async V=>{c(!0),$(null);try{const l=await Es("project",V,a);y(l.content),J(!1)}catch(l){const r=Z(l);$(r),n(`Failed to load heartbeat procedure file: ${r}`,"error")}finally{c(!1)}},[n,a]);t.useEffect(()=>{u(!1),A(!1),y(""),J(!1),$(null),c(!1),L(!1),p(!1)},[s.id,b]),t.useEffect(()=>()=>{x.current&&clearTimeout(x.current)},[]);const F=async()=>{b&&(u(!0),await K(b))},H=async()=>{if(b){L(!0);try{await $s("project",b,g,a),J(!1),p(!0),n("Heartbeat procedure file saved","success"),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>p(!1),3e3)}catch(V){n(`Failed to save heartbeat procedure file: ${Z(V)}`,"error")}finally{L(!1)}}},R=async()=>{m(!0);try{const V=await Ct(s.id,a);n(V.procedureFileSeeded?`Heartbeat procedure file ready at ${V.heartbeatProcedurePath}`:`Heartbeat procedure path set to ${V.heartbeatProcedurePath}`,"success"),await d()}catch(V){n(`Failed to upgrade heartbeat procedure: ${Z(V)}`,"error")}finally{m(!1)}};return e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Heartbeat Procedure"}),e.jsxs("p",{className:"config-description",children:["The per-tick procedure this agent runs every wake. Defaults to a per-agent markdown file (for example ",e.jsx("code",{children:".fusion/agents/ceo-agent2736/HEARTBEAT.md"}),") that you can edit. Legacy id-only default paths remain valid. Resets on every tick — no need to restart the agent after editing."]}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsxs("span",{className:"config-hint",children:["Current path: ",e.jsx("code",{children:b||"(none — using built-in default)"})]}),z&&e.jsx("div",{className:"heartbeat-procedure-actions",children:e.jsx("button",{className:"btn btn-sm",onClick:()=>void F(),disabled:N,children:N?e.jsxs(e.Fragment,{children:[e.jsx(I,{size:16,className:"animate-spin"}),"Loading file…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ce,{size:16}),"View Heartbeat Markdown"]})})})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("button",{className:"btn",disabled:o||W,onClick:()=>void R(),"aria-label":"Upgrade agent to default heartbeat procedure file",children:o?e.jsxs(e.Fragment,{children:[e.jsx(I,{size:16,className:"animate-spin"}),"Upgrading…"]}):W?e.jsxs(e.Fragment,{children:[e.jsx(ae,{size:16}),"Already on default"]}):"Upgrade to Default Heartbeat Procedure"}),e.jsxs("span",{className:"config-hint",children:["Sets ",e.jsx("code",{children:"heartbeatProcedurePath"})," to"," ",e.jsx("code",{children:D})," ","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."]})]})]}),j&&z&&b&&e.jsxs("div",{className:"config-fields heartbeat-procedure-viewer",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"heartbeat-procedure-file-content",children:"Heartbeat Procedure File"}),e.jsxs("div",{className:"agent-content-toolbar",children:[e.jsxs("div",{className:"agent-content-mode-toggle",children:[e.jsxs("button",{className:`btn btn-sm ${v?"":"btn-primary"}`,onClick:()=>A(!1),disabled:!v,"aria-label":"Heartbeat file edit mode",children:[e.jsx(ze,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${v?"btn-primary":""}`,onClick:()=>A(!0),disabled:v,"aria-label":"Heartbeat file preview mode",children:[e.jsx(He,{size:14}),"Preview"]})]}),N&&e.jsxs("span",{className:"config-hint heartbeat-procedure-status",children:[e.jsx(I,{size:12,className:"animate-spin"}),"Loading..."]}),f&&!N&&e.jsx("span",{className:"config-hint heartbeat-procedure-status heartbeat-procedure-status--warning",children:"Unsaved changes"})]}),v?g.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(Be,{remarkPlugins:[Oe],children:g})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:"No heartbeat procedure markdown content yet."}):e.jsx("textarea",{id:"heartbeat-procedure-file-content",className:"input",rows:16,value:g,readOnly:N,placeholder:"Heartbeat procedure markdown file content will appear here...",onChange:V=>{y(V.target.value),J(!0),p(!1)}}),k&&e.jsxs("span",{className:"config-error",children:["Failed to load file: ",k]}),e.jsxs("span",{className:"config-hint",children:["This editor writes directly to ",e.jsx("code",{children:b}),"."]})]}),!v&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!f||w||N,onClick:()=>void H(),children:w?e.jsxs(e.Fragment,{children:[e.jsx(I,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ae,{size:16}),"Save Heartbeat File"]})}),!f&&h&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ae,{size:14}),"File saved"]})]})]})]})}function ta({agent:s,projectId:a,addToast:n,onSaved:d,onHasChangesChange:o,onDelete:m}){const[j,u]=t.useState(s.name),[N,c]=t.useState(s.role),[w,L]=t.useState(s.title??""),[v,A]=t.useState(s.icon??""),[g,y]=t.useState(s.reportsTo??""),[f,J]=t.useState([]),[k,$]=t.useState(!1),[h,p]=t.useState(()=>{const i={};for(const P of ke){const O=s.metadata[P.key];O!=null&&(i[P.key]=String(O))}return i}),[x,b]=t.useState(()=>js(s.runtimeConfig)),[D,G]=t.useState(()=>Ge(s.runtimeConfig)),[T,W]=t.useState(()=>Ns(s.runtimeConfig)),[z,K]=t.useState(s.bundleConfig?.mode??""),[F,H]=t.useState(s.bundleConfig?.entryFile??"AGENTS.md"),[R,V]=t.useState(s.bundleConfig?.externalPath??""),[l,r]=t.useState(s.bundleConfig?.files??[]),[C,X]=t.useState(Array.isArray(s.metadata?.skills)?s.metadata.skills:[]),[se,me]=t.useState([]),[xe,E]=t.useState(!1),[_,re]=t.useState([]),[_e,S]=t.useState(!1),Y=(()=>{const i=s.runtimeConfig??{};return i.modelProvider&&i.modelId?`${i.modelProvider}/${i.modelId}`:typeof i.model=="string"&&i.model.includes("/")?i.model:""})(),q=typeof s.runtimeConfig?.runtimeHint=="string"?s.runtimeConfig.runtimeHint:"",[U,ce]=t.useState(q?"runtime":"model"),[te,de]=t.useState(Y),[ue,Ie]=t.useState(q),we=g.trim(),es=t.useMemo(()=>f.filter(i=>i.id!==s.id),[f,s.id]),Ds=!!we&&!es.some(i=>i.id===we);t.useEffect(()=>{let i=!1;return $(!0),gt(void 0,a).then(P=>{i||J(P)}).catch(()=>{i||J([])}).finally(()=>{i||$(!1)}),()=>{i=!0}},[a]),t.useEffect(()=>{E(!0),ft().then(i=>me(i.models)).catch(()=>{}).finally(()=>E(!1))},[]),t.useEffect(()=>{S(!0),As(a).then(re).catch(()=>re([])).finally(()=>S(!1))},[a]);const[he,Ve]=t.useState(null),[ss,ts]=t.useState(!1);t.useEffect(()=>{Ye(s.id,a).then(Ve).catch(()=>Ve(null))},[s.id,a]);const Ps=async()=>{ts(!0);try{await kt(s.id,a),n("Budget usage reset successfully","success");const i=await Ye(s.id,a);Ve(i)}catch(i){n(`Failed to reset budget: ${Z(i)}`,"error")}finally{ts(!1)}},[as,ns]=t.useState(!1),[B,Me]=t.useState({}),[zs,ve]=t.useState(!1),is=s.state==="idle"||s.state==="terminated",je=t.useRef(null),rs=t.useRef(null);t.useEffect(()=>()=>{je.current&&clearTimeout(je.current)},[]);const ge=(()=>{if(j!==s.name||N!==s.role||w!==(s.title??"")||v!==(s.icon??"")||g!==(s.reportsTo??"")||z!==(s.bundleConfig?.mode??"")||F!==(s.bundleConfig?.entryFile??"AGENTS.md")||R!==(s.bundleConfig?.externalPath??"")||JSON.stringify(l)!==JSON.stringify(s.bundleConfig?.files??[]))return!0;for(const ee of ke){const fe=h[ee.key]?.trim()??"",ne=s.metadata[ee.key]!==void 0&&s.metadata[ee.key]!==null?String(s.metadata[ee.key]):"";if(fe!==ne)return!0}const i=s.runtimeConfig??{};if(D!==Ge(s.runtimeConfig))return!0;for(const ee of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns","messageResponseMode"]){const fe=x[ee]?.trim()??"";let ne=i[ee]!==void 0&&i[ee]!==null?String(i[ee]):"";if((ee==="heartbeatIntervalMs"||ee==="heartbeatTimeoutMs")&&ne&&(ne=String(Number(ne)/1e3)),fe!==ne)return!0}const P=i.budgetConfig;for(const ee of["tokenBudget","budgetPeriod","resetDay"]){const fe=T[ee]?.trim()??"",ne=P?.[ee]!==void 0&&P?.[ee]!==null?String(P[ee]):"";if(fe!==ne)return!0}const O=T.usageThreshold?.trim()??"",le=P?.usageThreshold!==void 0&&P?.usageThreshold!==null?String(Number(P.usageThreshold)*100):"";if(O!==le)return!0;const Ne=Array.isArray(s.metadata?.skills)?s.metadata.skills:[];return JSON.stringify(C)!==JSON.stringify(Ne)||U!==(q?"runtime":"model")||te!==Y||ue!==q})(),ls=t.useRef(null);t.useEffect(()=>{o&&ls.current!==ge&&(ls.current=ge,o(ge))},[ge,o]),t.useEffect(()=>()=>{o?.(!1)},[o]),t.useEffect(()=>{const i={id:s.id,updatedAt:s.updatedAt},P=rs.current;(!P||P.id!==i.id||P.updatedAt!==i.updatedAt)&&(ge||(rs.current=i,b(js(s.runtimeConfig)),G(Ge(s.runtimeConfig)),W(Ns(s.runtimeConfig)),de(Y),Ie(q),ce(q?"runtime":"model")))},[s,ge,Y,q]);const cs=(i,P)=>{p(O=>({...O,[i]:P})),ve(!1),B[i]&&Me(O=>{const le={...O};return delete le[i],le})},Fe=(i,P)=>{b(O=>({...O,[i]:P})),ve(!1),B[i]&&Me(O=>{const le={...O};return delete le[i],le})},Hs=i=>{G(i),ve(!1)},Ae=(i,P)=>{W(O=>({...O,[i]:P})),ve(!1),B[i]&&Me(O=>{const le={...O};return delete le[i],le})},Bs=async()=>{const i=Zt(h);for(const[M,oe]of Object.entries({heartbeatIntervalMs:{label:"Heartbeat Interval",min:1},heartbeatTimeoutMs:{label:"Heartbeat Timeout",min:5},maxConcurrentRuns:{label:"Max Concurrent Runs",min:1}})){const ye=x[M]?.trim();if(!ye)continue;const Je=Number(ye);Number.isNaN(Je)||!Number.isFinite(Je)?i[M]=`"${oe.label}" must be a valid number`:Je<oe.min&&(i[M]=`"${oe.label}" must be at least ${oe.min.toLocaleString()}`)}const P=x.messageResponseMode?.trim();P&&!["immediate","on-heartbeat"].includes(P)&&(i.messageResponseMode='"Message Response Mode" must be either immediate or on-heartbeat');const O=T.tokenBudget?.trim();if(O){const M=Number(O);Number.isNaN(M)||!Number.isFinite(M)?i.tokenBudget='"Token Budget" must be a valid number':M<=0&&(i.tokenBudget='"Token Budget" must be greater than 0')}const le=T.usageThreshold?.trim();if(le){const M=Number(le);Number.isNaN(M)||!Number.isFinite(M)?i.usageThreshold='"Usage Threshold" must be a valid number':(M<1||M>100)&&(i.usageThreshold='"Usage Threshold" must be between 1 and 100')}const Ne=T.budgetPeriod?.trim();Ne&&!["daily","weekly","monthly","lifetime"].includes(Ne)&&(i.budgetPeriod='"Budget Period" must be one of: daily, weekly, monthly, lifetime');const ee=T.resetDay?.trim(),fe=Ne||"lifetime";if(ee){const M=Number(ee);Number.isNaN(M)||!Number.isFinite(M)?i.resetDay='"Reset Day" must be a valid number':fe==="weekly"?(M<0||M>6||!Number.isInteger(M))&&(i.resetDay='"Reset Day" must be between 0 (Sunday) and 6 (Saturday) for weekly period'):fe==="monthly"&&(M<1||M>31||!Number.isInteger(M))&&(i.resetDay='"Reset Day" must be between 1 and 31 for monthly period')}if(Object.keys(i).length>0){Me(i),n("Please fix validation errors before saving","error");return}const ne={...s.metadata};for(const M of ke){const oe=h[M.key]?.trim();oe?M.type==="number"?ne[M.key]=Number(oe):ne[M.key]=oe:delete ne[M.key]}C.length>0?ne.skills=C:delete ne.skills;const Q={...s.runtimeConfig};Q.enabled=D;for(const M of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns"]){const oe=x[M]?.trim();if(!oe)delete Q[M];else{const ye=Number(oe);Q[M]=M==="maxConcurrentRuns"?ye:ye*1e3}}const os=x.messageResponseMode?.trim();if(os?Q.messageResponseMode=os:delete Q.messageResponseMode,U==="runtime")ue.trim()?Q.runtimeHint=ue.trim():delete Q.runtimeHint,delete Q.modelProvider,delete Q.modelId,delete Q.model;else if(delete Q.runtimeHint,te.trim()){const M=te.indexOf("/");M!==-1&&(Q.modelProvider=te.slice(0,M),Q.modelId=te.slice(M+1),Q.model=te.trim())}else delete Q.modelProvider,delete Q.modelId,delete Q.model;const be={},ds=T.tokenBudget?.trim(),us=T.usageThreshold?.trim(),ms=T.budgetPeriod?.trim(),hs=T.resetDay?.trim();ds&&(be.tokenBudget=Number(ds)),us&&(be.usageThreshold=Number(us)/100),ms&&(be.budgetPeriod=ms),hs&&(be.resetDay=Number(hs)),Object.keys(be).length>0?Q.budgetConfig=be:delete Q.budgetConfig;let Ue;z&&(Ue={mode:z,entryFile:F||"AGENTS.md",files:l.length>0?l:["AGENTS.md"]},z==="external"&&R.trim()&&(Ue.externalPath=R.trim())),ns(!0);try{await Rt(s.id,{name:j.trim()||void 0,role:N,title:w.trim()||void 0,icon:v.trim()||void 0,reportsTo:g.trim()||void 0,metadata:ne,runtimeConfig:Q,bundleConfig:Ue},a),n("Settings saved","success"),ve(!0),je.current&&clearTimeout(je.current),je.current=setTimeout(()=>ve(!1),3e3),await d()}catch(M){n(`Failed to save settings: ${Z(M)}`,"error")}finally{ns(!1)}};return e.jsxs("div",{className:"config-tab",children:[e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Agent Configuration"}),e.jsx("p",{className:"config-description",children:"Configure agent settings and behavior."}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-name",children:"Name"}),e.jsx("input",{id:"agent-name",type:"text",className:"input",value:j,onChange:i=>u(i.target.value)})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-role",children:"Role"}),e.jsxs("select",{id:"agent-role",className:"select",value:N,onChange:i=>c(i.target.value),children:[e.jsx("option",{value:"triage",children:"Triage"}),e.jsx("option",{value:"executor",children:"Executor"}),e.jsx("option",{value:"reviewer",children:"Reviewer"}),e.jsx("option",{value:"merger",children:"Merger"}),e.jsx("option",{value:"scheduler",children:"Scheduler"}),e.jsx("option",{value:"custom",children:"Custom"})]})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-title",children:"Title"}),e.jsx("input",{id:"agent-title",type:"text",className:"input",placeholder:"e.g. Senior Code Reviewer",value:w,onChange:i=>L(i.target.value)})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-icon",children:"Icon"}),e.jsx("input",{id:"agent-icon",type:"text",className:"input",placeholder:"e.g. 🤖",value:v,onChange:i=>A(i.target.value)})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-reports-to",children:"Reports To"}),e.jsxs("select",{id:"agent-reports-to",className:"select",value:g,onChange:i=>y(i.target.value),disabled:k,children:[e.jsx("option",{value:"",children:"No manager"}),Ds&&e.jsxs("option",{value:we,children:["Unknown manager (",we,")"]}),es.map(i=>e.jsxs("option",{value:i.id,children:[i.name," (",i.id,")"]},i.id))]})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Skills"}),e.jsx("p",{className:"config-description",children:"Assign skills to this agent for specialized behavior."}),e.jsx("div",{className:"config-fields",children:e.jsx("div",{className:"config-field",children:e.jsx(zt,{id:"agent-skills",label:"Skills",value:C,onChange:X,projectId:a})})})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Model"}),e.jsx("p",{className:"config-description",children:"Choose either a built-in model or a plugin runtime for this agent. These options are mutually exclusive."}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{children:"Runtime Source"}),e.jsxs("div",{className:"config-runtime-tabs",role:"tablist","aria-label":"Runtime source",children:[e.jsx("button",{type:"button",className:`config-runtime-tab${U==="model"?" active":""}`,role:"tab","aria-selected":U==="model",tabIndex:U==="model"?0:-1,onClick:()=>{ce("model"),Ie("")},children:"Built-in Model"}),e.jsx("button",{type:"button",className:`config-runtime-tab${U==="runtime"?" active":""}`,role:"tab","aria-selected":U==="runtime",tabIndex:U==="runtime"?0:-1,onClick:()=>ce("runtime"),children:"Plugin Runtime"})]})]}),U==="model"?e.jsx("div",{className:"config-field",children:e.jsx(xt,{models:se,value:te,onChange:de,placeholder:"Use global default",label:"Agent Model",disabled:xe})}):e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-runtime-hint",children:"Runtime"}),_e?e.jsx("span",{className:"config-hint",children:"Loading runtimes…"}):e.jsxs("select",{id:"agent-runtime-hint",className:"select",value:ue,onChange:i=>Ie(i.target.value),children:[e.jsx("option",{value:"",children:_.length>0?"Select a plugin runtime…":"No plugin runtimes available"}),_.map(i=>e.jsx("option",{value:i.runtimeId,children:i.description?`${i.name} — ${i.description}`:i.name},`${i.pluginId}:${i.runtimeId}`))]})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Heartbeat Settings"}),e.jsx("p",{className:"config-description",children:"Configure how this agent's heartbeat is monitored. Leave a field empty to use system defaults."}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-enabled",children:[e.jsx("input",{id:"hb-enabled",type:"checkbox",checked:D,onChange:i=>Hs(i.target.checked)}),"Heartbeat Enabled"]}),e.jsx("span",{className:"config-hint",children:"When enabled, this agent receives scheduled heartbeat runs based on its interval."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-heartbeatIntervalMs",children:"Heartbeat Interval (s)"}),e.jsx("input",{id:"hb-heartbeatIntervalMs",type:"text",inputMode:"numeric",className:ie("input",!!B.heartbeatIntervalMs&&"input--error"),placeholder:String(Ke/1e3),value:x.heartbeatIntervalMs??"",onChange:i=>Fe("heartbeatIntervalMs",i.target.value)}),B.heartbeatIntervalMs?e.jsx("span",{className:"config-error",children:B.heartbeatIntervalMs}):e.jsxs("span",{className:"config-hint",children:["How often heartbeats are checked. Leave empty for system default (",Ke/1e3,"s / ",Ot,")."]})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-heartbeatTimeoutMs",children:"Heartbeat Timeout (s)"}),e.jsx("input",{id:"hb-heartbeatTimeoutMs",type:"text",inputMode:"numeric",className:ie("input",!!B.heartbeatTimeoutMs&&"input--error"),placeholder:"60",value:x.heartbeatTimeoutMs??"",onChange:i=>Fe("heartbeatTimeoutMs",i.target.value)}),B.heartbeatTimeoutMs?e.jsx("span",{className:"config-error",children:B.heartbeatTimeoutMs}):e.jsx("span",{className:"config-hint",children:"Time without heartbeat before agent is considered unresponsive. Leave empty for system default (60s)"})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-maxConcurrentRuns",children:"Max Concurrent Runs"}),e.jsx("input",{id:"hb-maxConcurrentRuns",type:"text",inputMode:"numeric",className:ie("input",!!B.maxConcurrentRuns&&"input--error"),placeholder:"1",value:x.maxConcurrentRuns??"",onChange:i=>Fe("maxConcurrentRuns",i.target.value)}),B.maxConcurrentRuns?e.jsx("span",{className:"config-error",children:B.maxConcurrentRuns}):e.jsx("span",{className:"config-hint",children:"Maximum simultaneous heartbeat runs for this agent. Leave empty for system default (1)."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-messageResponseMode",children:"Message Response Mode"}),e.jsxs("select",{id:"hb-messageResponseMode",className:ie("select",!!B.messageResponseMode&&"input--error"),value:x.messageResponseMode??"",onChange:i=>Fe("messageResponseMode",i.target.value),children:[e.jsx("option",{value:"",children:"System Default (On Heartbeat)"}),e.jsx("option",{value:"on-heartbeat",children:"On Heartbeat"}),e.jsx("option",{value:"immediate",children:"Immediate"})]}),B.messageResponseMode?e.jsx("span",{className:"config-error",children:B.messageResponseMode}):e.jsx("span",{className:"config-hint",children:"How this agent responds to incoming messages. 'Immediate' wakes the agent as soon as a message arrives. 'On Heartbeat' defers processing to the next scheduled heartbeat."})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Budget Settings"}),e.jsx("p",{className:"config-description",children:"Configure token budget limits for this agent. Leave all fields empty to disable budget tracking."}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"budget-tokenBudget",children:"Token Budget"}),e.jsx("input",{id:"budget-tokenBudget",type:"text",inputMode:"numeric",className:ie("input",!!B.tokenBudget&&"input--error"),placeholder:"No limit",value:T.tokenBudget??"",onChange:i=>Ae("tokenBudget",i.target.value)}),B.tokenBudget?e.jsx("span",{className:"config-error",children:B.tokenBudget}):e.jsx("span",{className:"config-hint",children:"Total token cap (input + output) for this agent. Leave empty for no limit."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"budget-usageThreshold",children:"Usage Threshold (%)"}),e.jsx("input",{id:"budget-usageThreshold",type:"text",inputMode:"numeric",className:ie("input",!!B.usageThreshold&&"input--error"),placeholder:"80",value:T.usageThreshold??"",onChange:i=>Ae("usageThreshold",i.target.value)}),B.usageThreshold?e.jsx("span",{className:"config-error",children:B.usageThreshold}):e.jsx("span",{className:"config-hint",children:"Warning threshold as a percentage. Agent warns when usage reaches this level. Default: 80%."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"budget-budgetPeriod",children:"Budget Period"}),e.jsxs("select",{id:"budget-budgetPeriod",className:ie("select",!!B.budgetPeriod&&"input--error"),value:T.budgetPeriod??"",onChange:i=>Ae("budgetPeriod",i.target.value),children:[e.jsx("option",{value:"",children:"No reset (lifetime)"}),e.jsx("option",{value:"daily",children:"Daily"}),e.jsx("option",{value:"weekly",children:"Weekly"}),e.jsx("option",{value:"monthly",children:"Monthly"})]}),B.budgetPeriod?e.jsx("span",{className:"config-error",children:B.budgetPeriod}):e.jsx("span",{className:"config-hint",children:"How often the budget counter resets. Leave empty for lifetime budget."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"budget-resetDay",children:"Reset Day"}),e.jsx("input",{id:"budget-resetDay",type:"text",inputMode:"numeric",className:ie("input",!!B.resetDay&&"input--error"),placeholder:"Auto",value:T.resetDay??"",onChange:i=>Ae("resetDay",i.target.value)}),B.resetDay?e.jsx("span",{className:"config-error",children:B.resetDay}):e.jsx("span",{className:"config-hint",children:T.budgetPeriod==="weekly"?"Day of week (0=Sunday to 6=Saturday) for reset.":T.budgetPeriod==="monthly"?"Day of month (1-31) for reset.":"Day for reset (weekly: 0-6, monthly: 1-31). Leave empty for automatic."})]}),he?.budgetLimit!=null&&e.jsxs("div",{className:"config-field",children:[e.jsx("label",{children:"Current Usage"}),e.jsxs("div",{className:"budget-progress-container",children:[e.jsx("div",{className:"budget-progress-bar",children:e.jsx("div",{className:ie("budget-progress-bar__fill",(he.usagePercent??0)>=100?"budget-progress-bar__fill--red":(he.usagePercent??0)>=80?"budget-progress-bar__fill--amber":"budget-progress-bar__fill--green"),style:{width:`${Math.min(he.usagePercent??0,100)}%`}})}),e.jsxs("span",{className:"budget-progress-label",children:[(he.currentUsage??0).toLocaleString()," / ",(he.budgetLimit??0).toLocaleString()," tokens (",Math.round(he.usagePercent??0),"% used)"]})]})]}),he?.budgetLimit!=null&&e.jsx("div",{className:"config-field",children:e.jsx("button",{className:"btn btn-reset-budget",onClick:()=>void Ps(),disabled:ss,children:ss?e.jsxs(e.Fragment,{children:[e.jsx(I,{size:14,className:"animate-spin"}),"Resetting…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Xe,{size:14}),"Reset Budget Usage"]})})})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Instruction Bundle"}),e.jsx("p",{className:"config-description",children:"Configure the agent's instruction bundle. Leave empty to use inline instructions only."}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-mode",children:"Bundle Mode"}),e.jsxs("select",{id:"bundle-mode",className:"select",value:z,onChange:i=>K(i.target.value),children:[e.jsx("option",{value:"",children:"None (use inline instructions)"}),e.jsx("option",{value:"managed",children:"Managed (system-managed directory)"}),e.jsx("option",{value:"external",children:"External (user-specified path)"})]}),e.jsxs("span",{className:"config-hint",children:[z==="managed"&&"Files will be stored in a system-managed directory within .fusion/agents/",z==="external"&&"Specify an external directory path for the instruction files",!z&&"Select a mode to enable instruction bundling"]})]}),z&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-entry-file",children:"Entry File"}),e.jsx("input",{id:"bundle-entry-file",type:"text",className:"input",placeholder:"AGENTS.md",value:F,onChange:i=>H(i.target.value)}),e.jsx("span",{className:"config-hint",children:"Primary instructions file name (default: AGENTS.md)"})]}),z==="external"&&e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-external-path",children:"External Path"}),e.jsx("input",{id:"bundle-external-path",type:"text",className:"input",placeholder:"e.g. .fusion/agents/my-agent",value:R,onChange:i=>V(i.target.value)}),e.jsx("span",{className:"config-hint",children:"Absolute or relative path to the external directory"})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-files",children:"Files (comma-separated)"}),e.jsx("input",{id:"bundle-files",type:"text",className:"input",placeholder:"AGENTS.md, PROMPTS.md",value:l.join(", "),onChange:i=>r(i.target.value.split(",").map(P=>P.trim()).filter(Boolean))}),e.jsx("span",{className:"config-hint",children:"List of file names in the bundle directory"})]})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Advanced Settings"}),e.jsx("p",{className:"config-description",children:"Advanced configuration options for this agent. Leave a field empty to use system defaults."}),e.jsx("div",{className:"config-fields",children:ke.map(i=>{const P=!!B[i.key];return e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:`adv-${i.key}`,children:i.label}),i.type==="select"?e.jsxs("select",{id:`adv-${i.key}`,className:ie("select",P&&"input--error"),value:h[i.key]??"",onChange:O=>cs(i.key,O.target.value),children:[e.jsx("option",{value:"",children:"System Default"}),i.options?.map(O=>e.jsx("option",{value:O.value,children:O.label},O.value))]}):e.jsx("input",{id:`adv-${i.key}`,type:"text",inputMode:i.type==="number"?"numeric":void 0,className:ie("input",P&&"input--error"),placeholder:i.placeholder,value:h[i.key]??"",onChange:O=>cs(i.key,O.target.value)}),P&&e.jsx("span",{className:"config-error",children:B[i.key]}),!P&&i.hint&&e.jsx("span",{className:"config-hint",children:i.hint})]},i.key)})}),e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!ge||as,onClick:()=>void Bs(),children:as?e.jsxs(e.Fragment,{children:[e.jsx(I,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ae,{size:16}),"Save Settings"]})}),!ge&&zs&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ae,{size:14}),"Settings saved"]})]})]}),e.jsx(sa,{agent:s,projectId:a,addToast:n,onSaved:d}),e.jsxs("div",{className:"config-section config-section--danger",children:[e.jsx("h3",{children:"Danger Zone"}),e.jsx("p",{className:"config-description",children:"Permanently delete this agent from the project."}),e.jsx("div",{className:"config-fields",children:e.jsxs("div",{className:"config-field",children:[e.jsxs("button",{className:"btn btn--danger",disabled:!is||!m,onClick:()=>void m?.(),children:[e.jsx(De,{size:16}),"Delete Agent"]}),e.jsx("span",{className:"config-danger-note",children:is?"Deletion is permanent and cannot be undone.":`Agent deletion is only available when state is idle or terminated (current state: ${s.state}).`})]})})]})]})}function aa({agentId:s,projectId:a,onChildClick:n}){const[d,o]=t.useState([]),[m,j]=t.useState(!0);return t.useEffect(()=>{j(!0),ut(s,a).then(o).finally(()=>j(!1))},[s,a]),m?e.jsxs("div",{className:"detail-section",children:[e.jsx("div",{className:"detail-section-header",children:e.jsx("h3",{children:"Employees"})}),e.jsxs("div",{className:"detail-section-body detail-section-body--loading",children:[e.jsx(I,{size:16,className:"spin"}),e.jsx("span",{className:"text-muted",children:"Loading employees..."})]})]}):e.jsxs("div",{className:"detail-section",children:[e.jsxs("div",{className:"detail-section-header",children:[e.jsx("h3",{children:"Employees"}),e.jsxs("span",{className:"text-muted",children:["(",d.length,")"]})]}),e.jsx("div",{className:"detail-section-body",children:d.length===0?e.jsxs("div",{className:"agent-empty agent-empty--padded",children:[e.jsx(Ms,{size:32,opacity:.3}),e.jsx("p",{children:"No employees"}),e.jsx("p",{className:"text-muted",children:"This agent has no employees"})]}):e.jsx("div",{className:"agent-tree__children",children:d.map(u=>{const N=Qe[u.state];return e.jsxs("div",{className:"agent-tree__node agent-is-child",onClick:()=>n?.(u.id),role:"button",tabIndex:0,onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&(c.key===" "&&c.preventDefault(),n?.(u.id))},style:{cursor:n?"pointer":"default"},children:[e.jsx("span",{className:"agent-tree__icon",children:u.icon??"🤖"}),e.jsx("span",{className:"agent-tree__name",children:u.name}),e.jsx("span",{className:"agent-tree__badge",style:{background:N?.bg??"var(--state-idle-bg)",color:N?.text??"var(--state-idle-text)",border:`1px solid ${N?.border??"var(--state-idle-border)"}`},children:u.state})]},u.id)})})})]})}const la=Object.freeze(Object.defineProperty({__proto__:null,AgentDetailView:It,relativeTime:pe},Symbol.toStringTag,{value:"Module"}));export{la as A,zt as S,pe as r};
|
|
18
|
+
... (truncated, ${k.stdoutExcerpt.length} chars total)`:k.stdoutExcerpt})]}),k.stderrExcerpt&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label run-output-label--error",children:"Errors"}),e.jsx("pre",{className:"run-output-panel run-output-panel--error",children:k.stderrExcerpt})]}),k.resultJson&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:"Result"}),e.jsx("pre",{className:"run-output-panel",children:JSON.stringify(k.resultJson,null,2)})]}),k.contextSnapshot&&Object.keys(k.contextSnapshot).length>0&&e.jsxs("div",{className:"run-output-section",children:[e.jsx("div",{className:"run-output-label",children:"Context"}),e.jsx("div",{className:"run-context-grid",children:Object.entries(k.contextSnapshot).map(([_,re])=>e.jsxs("span",{className:"run-context-item",children:[e.jsxs("span",{className:"text-muted",children:[_,":"]})," ",e.jsx("span",{children:String(re)})]},_))})]}),!k.stdoutExcerpt&&!k.stderrExcerpt&&!k.resultJson&&e.jsx("div",{className:"text-muted run-output-empty",children:"No output captured"})]}),e.jsxs("div",{className:"run-agent-logs-section",children:[e.jsx("div",{className:"run-output-label",children:"Agent Logs"}),f?e.jsxs("div",{className:"run-details-loading-state",children:[e.jsx(I,{size:14,className:"animate-spin"}),e.jsx("span",{className:"text-muted",children:"Loading logs..."})]}):g.length===0?e.jsx("div",{className:"text-muted run-output-empty",children:"No logs available for this run"}):e.jsx(bt,{entries:g,loading:!1})]})]})]},r.id)};return e.jsxs("div",{className:"runs-tab",children:[Y&&e.jsxs("div",{className:"runs-toolbar runs-toolbar--between",children:[e.jsxs("span",{className:"runs-toolbar-meta",children:[u.length," run",u.length!==1?"s":"",D&&e.jsxs("span",{className:"run-live-indicator run-live-indicator--with-margin",children:[e.jsx("span",{className:"live-dot"}),"Live"]})]}),e.jsxs("div",{className:"run-header-group",children:[D&&e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void z(),"aria-label":`Stop active run for ${o??a}`,children:[e.jsx(Re,{size:14})," Stop Run"]}),e.jsxs("button",{className:"btn btn--sm btn-task-create",onClick:()=>void W(),"aria-label":`Run now for ${o??a}`,children:[e.jsx($e,{size:14})," Run Now"]})]})]}),H.map((r,C)=>l(r,C,!0)),R.map((r,C)=>l(r,H.length+C,!1))]})}function Gt(s,a){const n=Math.floor((a.getTime()-s.getTime())/1e3);return n<60?`${n}s`:n<3600?`${Math.floor(n/60)}m ${n%60}s`:`${Math.floor(n/3600)}h ${Math.floor(n%3600/60)}m`}const Wt={triage:"Triage",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"};function Kt(s){const a=s.title?.trim()||s.description?.trim()||s.id;return a.length>80?`${a.slice(0,77)}...`:a}function Yt({agentId:s,projectId:a,addToast:n}){const[d,o]=t.useState([]),[m,j]=t.useState(!0);return t.useEffect(()=>{let u=!1;return j(!0),dt(s,a).then(N=>{u||o(N)}).catch(N=>{u||(o([]),n(`Failed to load assigned tasks: ${Z(N)}`,"error"))}).finally(()=>{u||j(!1)}),()=>{u=!0}},[s,a,n]),m?e.jsxs("div",{className:"agent-tasks-empty",children:[e.jsx(I,{size:16,className:"animate-spin"}),e.jsx("p",{children:"Loading assigned tasks..."})]}):d.length===0?e.jsxs("div",{className:"agent-tasks-empty",children:[e.jsx(ws,{size:18}),e.jsx("p",{children:"No tasks assigned to this agent"})]}):e.jsx("div",{className:"agent-tasks-list",children:d.map(u=>e.jsxs("a",{className:"agent-task-item",href:`/tasks/${u.id}`,children:[e.jsxs("div",{className:"agent-task-row",children:[e.jsx("span",{className:"agent-task-id",children:u.id}),e.jsx("span",{className:`agent-task-column column-${u.column}`,children:Wt[u.column]})]}),e.jsx("div",{className:"agent-task-title",title:u.title||u.description||u.id,children:Kt(u)}),e.jsxs("div",{className:"agent-task-status",children:[u.status??"idle"," · Updated ",pe(u.updatedAt)]})]},u.id))})}const ke=[{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 Zt(s){const a={};for(const n of ke){const d=s[n.key]?.trim();if(d){if(n.type==="number"){const o=Number(d);if(Number.isNaN(o)||!Number.isFinite(o)){a[n.key]=`"${n.label}" must be a valid number`;continue}n.min!==void 0&&o<n.min&&(a[n.key]=`"${n.label}" must be at least ${n.min.toLocaleString()}`),n.max!==void 0&&o>n.max&&(a[n.key]=`"${n.label}" must be at most ${n.max.toLocaleString()}`)}if(n.type==="select"){const o=n.options?.map(m=>m.value)??[];o.length>0&&!o.includes(d)&&(a[n.key]=`"${n.label}" must be one of: ${o.join(", ")}`)}}}return a}function Xt({agent:s,projectId:a,addToast:n,onSaved:d}){const[o,m]=t.useState(s.soul??""),[j,u]=t.useState(!1),[N,c]=t.useState(!1),[w,L]=t.useState(!1),v=t.useRef(null);t.useEffect(()=>{m(s.soul??""),c(!1),L(!1)},[s.id,s.soul]),t.useEffect(()=>()=>{v.current&&clearTimeout(v.current)},[]);const A=o!==(s.soul??""),g=async()=>{if(o.length>1e4){n("Soul must be at most 10,000 characters","error");return}u(!0);try{await jt(s.id,o,a),n("Soul saved","success"),c(!0),v.current&&clearTimeout(v.current),v.current=setTimeout(()=>c(!1),3e3),await d()}catch(y){n(`Failed to save soul: ${Z(y)}`,"error")}finally{u(!1)}};return e.jsx("div",{className:"config-tab",children:e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Soul"}),e.jsx("p",{className:"config-description",children:"Define this agent's personality and identity."}),e.jsx("div",{className:"config-fields",children:e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-soul",children:"Agent Soul"}),e.jsx("div",{className:"agent-content-toolbar",children:e.jsxs("div",{className:"agent-content-mode-toggle",children:[e.jsxs("button",{className:`btn btn-sm ${w?"":"btn-primary"}`,onClick:()=>L(!1),disabled:!w,"aria-label":"Edit mode",children:[e.jsx(ze,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${w?"btn-primary":""}`,onClick:()=>L(!0),disabled:w,"aria-label":"Preview mode",children:[e.jsx(He,{size:14}),"Preview"]})]})}),w?o.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(Be,{remarkPlugins:[Oe],children:o})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:"No soul defined yet. Switch to Edit mode to define the agent's personality."}):e.jsx("textarea",{id:"agent-soul",className:"input config-textarea-mono",rows:12,placeholder:"Describe this agent's personality, tone, and behavioral traits...",value:o,onChange:y=>{m(y.target.value),c(!1)}}),!w&&e.jsx("span",{className:"config-hint",children:"Defines the agent's character and identity. Max 10,000 characters."})]})}),!w&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!A||j,onClick:()=>void g(),children:j?e.jsxs(e.Fragment,{children:[e.jsx(I,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ae,{size:16}),"Save Soul"]})}),!A&&N&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ae,{size:14}),"Soul saved"]})]})]})})}function Qt({agent:s,projectId:a,addToast:n,onSaved:d}){const[o,m]=t.useState(s.memory??""),[j,u]=t.useState(!1),[N,c]=t.useState(!1),[w,L]=t.useState(!1),[v,A]=t.useState([]),[g,y]=t.useState(!1),[f,J]=t.useState(""),[k,$]=t.useState(""),[h,p]=t.useState(!1),[x,b]=t.useState(!1),[D,G]=t.useState(!1),[T,W]=t.useState(!1),[z,Y]=t.useState(""),F=t.useRef(null),H=t.useRef(null),R=s.state==="running",V=o!==(s.memory??""),l=t.useMemo(()=>v.find(E=>E.path===f),[v,f]),r=l?Bt[l.layer]:"Select a memory file to view or edit.",C=t.useCallback(async E=>{b(!0);try{const _=await mt(s.id,E,a);J(_.path),$(_.content),p(!1),W(!1)}catch(_){n(`Failed to load agent memory file: ${Z(_)}`,"error")}finally{b(!1)}},[s.id,a,n]),X=t.useCallback(async(E="")=>{y(!0);try{const{files:_}=await ht(s.id,a);if(A(_),_.length===0){J(""),$(""),p(!1);return}const re=_t(_,E);await C(re)}catch(_){n(`Failed to load memory files: ${Z(_)}`,"error"),A([]),J(""),$(""),p(!1)}finally{y(!1)}},[s.id,a,n,C]);t.useEffect(()=>{m(s.memory??""),c(!1),L(!1),Y(""),W(!1),X()},[s.id,s.memory,X]),t.useEffect(()=>()=>{F.current&&clearTimeout(F.current),H.current&&clearTimeout(H.current)},[]);const se=async()=>{if(o.length>5e4){n("Memory must be at most 50,000 characters","error");return}u(!0);try{await yt(s.id,o,a),n("Memory saved","success"),c(!0),F.current&&clearTimeout(F.current),F.current=setTimeout(()=>c(!1),3e3),await d()}catch(E){n(`Failed to save memory: ${Z(E)}`,"error")}finally{u(!1)}},me=async E=>{if(!(!E||E===f)){if(h){Y("Save the current file before switching to another file.");return}Y(""),await C(E)}},xe=async()=>{if(f){G(!0);try{await St(s.id,f,k,a),p(!1),W(!0),H.current&&clearTimeout(H.current),H.current=setTimeout(()=>W(!1),3e3),Y(""),await X(f),n("Agent memory file saved","success")}catch(E){n(`Failed to save agent memory file: ${Z(E)}`,"error")}finally{G(!1)}}};return e.jsx("div",{className:"config-tab",children:e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Agent Memory"}),e.jsx("p",{className:"config-description",children:"Store context that belongs to this agent only. Workspace memory, daily notes, dreams, and qmd search live in project settings under Project Memory."}),R&&e.jsx("p",{className:"config-hint config-hint--block-spacing",children:"Read-only while this agent is running."}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-memory",children:"Inline Memory"}),e.jsx("span",{className:"config-hint config-hint--block",children:"Short-form memory stored directly on the agent record and injected into prompts."}),e.jsx("div",{className:"agent-content-toolbar",children:e.jsxs("div",{className:"agent-content-mode-toggle",children:[!R&&e.jsxs("button",{className:`btn btn-sm ${w?"":"btn-primary"}`,onClick:()=>L(!1),disabled:!w,"aria-label":"Edit mode",children:[e.jsx(ze,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${w?"btn-primary":""}`,onClick:()=>L(!0),disabled:w,"aria-label":"Preview mode",children:[e.jsx(He,{size:14}),"Preview"]})]})}),w?o.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(Be,{remarkPlugins:[Oe],children:o})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:"No agent memory defined yet. Switch to Edit mode to add memory content."}):e.jsx("textarea",{id:"agent-memory","aria-label":"Agent Memory",className:"input config-textarea-mono",rows:10,placeholder:"Durable preferences, operating habits, and context this agent should carry across tasks...",value:o,readOnly:R,onChange:E=>{m(E.target.value),c(!1)}}),!w&&e.jsx("span",{className:"config-hint",children:"This is the inline memory field on the agent JSON record. Max 50,000 characters."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-memory-file-select",children:"Memory Files"}),e.jsxs("span",{className:"config-hint config-hint--block",children:["Full OpenClaw memory files at ",e.jsxs("code",{children:[".fusion/agent-memory/",s.id,"/"]})," (MEMORY.md, DREAMS.md, and daily notes)."]}),e.jsx("select",{id:"agent-memory-file-select",className:"select",value:f,disabled:g||x||D||v.length===0,onChange:E=>{me(E.target.value)},children:v.length===0?e.jsx("option",{value:"",children:"No memory files found"}):v.map(E=>e.jsxs("option",{value:E.path,children:[bs[E.layer]," • ",E.label]},E.path))}),g&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(I,{size:14,className:"animate-spin"}),"Loading memory files…"]}),l&&e.jsxs("div",{className:"config-hint config-hint--top-spacing",children:[e.jsx("strong",{children:bs[l.layer]})," · ",r,e.jsx("br",{}),l.size.toLocaleString()," bytes · Updated ",pe(l.updatedAt)]}),e.jsx("textarea",{className:"input config-textarea-mono config-textarea-top-spacing",rows:14,placeholder:"Select a memory file to view and edit its content...",value:k,readOnly:R||!f||x,onChange:E=>{$(E.target.value),p(!0),W(!1),Y("")}}),x&&e.jsxs("span",{className:"config-hint config-hint--inline-loader",children:[e.jsx(I,{size:14,className:"animate-spin"}),"Loading file content…"]}),z&&e.jsx("span",{className:"config-hint config-hint--top-spacing config-hint--block",children:z})]})]}),e.jsxs("div",{className:"config-actions",children:[!w&&e.jsx("button",{className:"btn btn-task-create",disabled:!V||j||R,onClick:()=>void se(),children:j?e.jsxs(e.Fragment,{children:[e.jsx(I,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ae,{size:16}),"Save Memory"]})}),e.jsx("button",{className:"btn",disabled:!h||D||!f||R,onClick:()=>void xe(),children:D?e.jsxs(e.Fragment,{children:[e.jsx(I,{size:16,className:"animate-spin"}),"Saving file…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ae,{size:16}),"Save Memory File"]})}),!V&&N&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ae,{size:14}),"Memory saved"]}),!h&&T&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ae,{size:14}),"Memory file saved"]})]})]})})}function ea({agent:s,projectId:a,addToast:n,onSaved:d}){const[o,m]=t.useState(s.instructionsText??""),[j,u]=t.useState(s.instructionsPath??""),[N,c]=t.useState(!1),[w,L]=t.useState(""),[v,A]=t.useState(!1),[g,y]=t.useState(!1),[f,J]=t.useState(!1),[k,$]=t.useState(!1),[h,p]=t.useState(!1),[x,b]=t.useState(!1),D=t.useRef(null),G=t.useRef(null);t.useEffect(()=>{const F=j.trim();if(!F){L(""),y(!1);return}A(!0),Es("project",F).then(H=>{L(H.content),y(!1)}).catch(H=>{const R=Z(H);R.includes("ENOENT")||R.includes("Not found")||R.includes("not found")?(L(""),y(!1)):(n(`Failed to load instructions file: ${R}`,"error"),L(""))}).finally(()=>{A(!1)})},[j,n]),t.useEffect(()=>{m(s.instructionsText??""),u(s.instructionsPath??""),p(!1),b(!1),c(!1)},[s.id,s.instructionsText,s.instructionsPath]),t.useEffect(()=>()=>{D.current&&clearTimeout(D.current),G.current&&clearTimeout(G.current)},[]);const T=(()=>{const F=o??"",H=s.instructionsText??"",R=j?.trim()??"",V=s.instructionsPath?.trim()??"";return F!==H||R!==V})(),W=async()=>{J(!0);try{await Nt(s.id,{instructionsText:o||void 0,instructionsPath:j.trim()||void 0},a),n("Instructions saved","success"),p(!0),D.current&&clearTimeout(D.current),D.current=setTimeout(()=>p(!1),3e3),await d()}catch(F){n(`Failed to save instructions: ${Z(F)}`,"error")}finally{J(!1)}},z=async()=>{const F=j.trim();if(!F){n("No instructions file path set","error");return}$(!0);try{await $s("project",F,w),n("Instructions file saved","success"),y(!1),b(!0),G.current&&clearTimeout(G.current),G.current=setTimeout(()=>b(!1),3e3)}catch(H){n(`Failed to save instructions file: ${Z(H)}`,"error")}finally{$(!1)}},Y=!!j.trim();return e.jsxs("div",{className:"config-tab",children:[e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Custom Instructions"}),e.jsx("p",{className:"config-description",children:"Append custom instructions to this agent's system prompt at execution time. Use this to customize behavior, coding style, or project conventions without modifying built-in prompts."}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"instructions-text",children:"Inline Instructions"}),e.jsx("div",{className:"agent-content-toolbar",children:e.jsxs("div",{className:"agent-content-mode-toggle",children:[e.jsxs("button",{className:`btn btn-sm ${N?"":"btn-primary"}`,onClick:()=>c(!1),disabled:!N,"aria-label":"Edit mode","data-testid":"instructions-edit-toggle",children:[e.jsx(ze,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${N?"btn-primary":""}`,onClick:()=>c(!0),disabled:N,"aria-label":"Preview mode","data-testid":"instructions-preview-toggle",children:[e.jsx(He,{size:14}),"Preview"]})]})}),N?o.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(Be,{remarkPlugins:[Oe],children:o})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:"No inline instructions defined yet. Switch to Edit mode to add instructions."}):e.jsx("textarea",{id:"instructions-text",className:"input",rows:10,placeholder:"Enter custom instructions to append to this agent's system prompt...",value:o,onChange:F=>{m(F.target.value),p(!1)}}),!N&&e.jsx("span",{className:"config-hint",children:"Markdown formatting supported. Max 50,000 characters."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"instructions-path",children:"Instructions File Path"}),e.jsx("input",{id:"instructions-path",type:"text",className:"input",placeholder:"e.g., .fusion/agents/my-agent-instructions.md",value:j,onChange:F=>{u(F.target.value),p(!1)}}),e.jsx("span",{className:"config-hint",children:"Path to a .md file (relative to project root). Contents are read and appended at execution time."})]})]}),!N&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!T||f,onClick:()=>void W(),children:f?e.jsxs(e.Fragment,{children:[e.jsx(I,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ae,{size:16}),"Save Instructions"]})}),!T&&h&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ae,{size:14}),"Instructions saved"]})]})]}),Y&&e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Instructions File Editor"}),e.jsx("p",{className:"config-description",children:"Edit the instructions file directly. Changes are saved separately from the path configuration."}),e.jsx("div",{className:"config-fields",children:e.jsxs("div",{className:"config-field",children:[e.jsxs("div",{className:"config-inline-header",children:[e.jsx("label",{htmlFor:"instructions-file-content",children:"File Content"}),v&&e.jsxs("span",{className:"config-hint config-hint--inline-tight",children:[e.jsx(I,{size:12,className:"animate-spin"}),"Loading..."]}),g&&!v&&e.jsx("span",{className:"config-hint config-hint--warning",children:"Unsaved changes"})]}),e.jsx("textarea",{id:"instructions-file-content",className:"input config-textarea-mono",rows:20,placeholder:"File content will appear here when loaded...",value:w,readOnly:v,onChange:F=>{L(F.target.value),y(!0),b(!1)}}),e.jsx("span",{className:"config-hint",children:"Edit the markdown file content directly. Save separately using the button below."})]})}),e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!g||k,onClick:()=>void z(),children:k?e.jsxs(e.Fragment,{children:[e.jsx(I,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ae,{size:16}),"Save File"]})}),!g&&x&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ae,{size:14}),"File saved"]})]})]})]})}function js(s){const a=s??{},n={};return a.heartbeatIntervalMs!==void 0&&a.heartbeatIntervalMs!==null&&(n.heartbeatIntervalMs=String(Number(a.heartbeatIntervalMs)/1e3)),a.heartbeatTimeoutMs!==void 0&&a.heartbeatTimeoutMs!==null&&(n.heartbeatTimeoutMs=String(Number(a.heartbeatTimeoutMs)/1e3)),a.maxConcurrentRuns!==void 0&&a.maxConcurrentRuns!==null&&(n.maxConcurrentRuns=String(a.maxConcurrentRuns)),(a.messageResponseMode==="immediate"||a.messageResponseMode==="on-heartbeat")&&(n.messageResponseMode=a.messageResponseMode),n}function Ge(s){return s?.enabled!==!1}function Ns(s){const a=(s??{}).budgetConfig,n={};return a&&(a.tokenBudget!==void 0&&a.tokenBudget!==null&&(n.tokenBudget=String(a.tokenBudget)),a.usageThreshold!==void 0&&a.usageThreshold!==null&&(n.usageThreshold=String(Number(a.usageThreshold)*100)),a.budgetPeriod!==void 0&&a.budgetPeriod!==null&&(n.budgetPeriod=String(a.budgetPeriod)),a.resetDay!==void 0&&a.resetDay!==null&&(n.resetDay=String(a.resetDay))),n}function sa({agent:s,projectId:a,addToast:n,onSaved:d}){const[o,m]=t.useState(!1),[j,u]=t.useState(!1),[N,c]=t.useState(!1),[w,L]=t.useState(!1),[v,A]=t.useState(!1),[g,y]=t.useState(""),[f,J]=t.useState(!1),[k,$]=t.useState(null),[h,p]=t.useState(!1),x=t.useRef(null),b=s.heartbeatProcedurePath?.trim(),D=`.fusion/agents/${s.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||s.id.toLowerCase().replace(/[^a-z0-9]+/g,"-")||"agent"}-${s.id.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"agent"}/HEARTBEAT.md`,G=`.fusion/agents/${s.id}/HEARTBEAT.md`,T=s.id.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"agent",W=!!(b&&(b===D||b===G||new RegExp(`^\\.fusion/agents/[^/]+-${T}/HEARTBEAT\\.md$`).test(b))),z=!!b,Y=t.useCallback(async V=>{c(!0),$(null);try{const l=await Es("project",V,a);y(l.content),J(!1)}catch(l){const r=Z(l);$(r),n(`Failed to load heartbeat procedure file: ${r}`,"error")}finally{c(!1)}},[n,a]);t.useEffect(()=>{u(!1),A(!1),y(""),J(!1),$(null),c(!1),L(!1),p(!1)},[s.id,b]),t.useEffect(()=>()=>{x.current&&clearTimeout(x.current)},[]);const F=async()=>{b&&(u(!0),await Y(b))},H=async()=>{if(b){L(!0);try{await $s("project",b,g,a),J(!1),p(!0),n("Heartbeat procedure file saved","success"),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>p(!1),3e3)}catch(V){n(`Failed to save heartbeat procedure file: ${Z(V)}`,"error")}finally{L(!1)}}},R=async()=>{m(!0);try{const V=await Ct(s.id,a);n(V.procedureFileSeeded?`Heartbeat procedure file ready at ${V.heartbeatProcedurePath}`:`Heartbeat procedure path set to ${V.heartbeatProcedurePath}`,"success"),await d()}catch(V){n(`Failed to upgrade heartbeat procedure: ${Z(V)}`,"error")}finally{m(!1)}};return e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Heartbeat Procedure"}),e.jsxs("p",{className:"config-description",children:["The per-tick procedure this agent runs every wake. Defaults to a per-agent markdown file (for example ",e.jsx("code",{children:".fusion/agents/ceo-agent2736/HEARTBEAT.md"}),") that you can edit. Legacy id-only default paths remain valid. Resets on every tick — no need to restart the agent after editing."]}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsxs("span",{className:"config-hint",children:["Current path: ",e.jsx("code",{children:b||"(none — using built-in default)"})]}),z&&e.jsx("div",{className:"heartbeat-procedure-actions",children:e.jsx("button",{className:"btn btn-sm",onClick:()=>void F(),disabled:N,children:N?e.jsxs(e.Fragment,{children:[e.jsx(I,{size:16,className:"animate-spin"}),"Loading file…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ce,{size:16}),"View Heartbeat Markdown"]})})})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("button",{className:"btn",disabled:o||W,onClick:()=>void R(),"aria-label":"Upgrade agent to default heartbeat procedure file",children:o?e.jsxs(e.Fragment,{children:[e.jsx(I,{size:16,className:"animate-spin"}),"Upgrading…"]}):W?e.jsxs(e.Fragment,{children:[e.jsx(ae,{size:16}),"Already on default"]}):"Upgrade to Default Heartbeat Procedure"}),e.jsxs("span",{className:"config-hint",children:["Sets ",e.jsx("code",{children:"heartbeatProcedurePath"})," to"," ",e.jsx("code",{children:D})," ","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."]})]})]}),j&&z&&b&&e.jsxs("div",{className:"config-fields heartbeat-procedure-viewer",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"heartbeat-procedure-file-content",children:"Heartbeat Procedure File"}),e.jsxs("div",{className:"agent-content-toolbar",children:[e.jsxs("div",{className:"agent-content-mode-toggle",children:[e.jsxs("button",{className:`btn btn-sm ${v?"":"btn-primary"}`,onClick:()=>A(!1),disabled:!v,"aria-label":"Heartbeat file edit mode",children:[e.jsx(ze,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${v?"btn-primary":""}`,onClick:()=>A(!0),disabled:v,"aria-label":"Heartbeat file preview mode",children:[e.jsx(He,{size:14}),"Preview"]})]}),N&&e.jsxs("span",{className:"config-hint heartbeat-procedure-status",children:[e.jsx(I,{size:12,className:"animate-spin"}),"Loading..."]}),f&&!N&&e.jsx("span",{className:"config-hint heartbeat-procedure-status heartbeat-procedure-status--warning",children:"Unsaved changes"})]}),v?g.trim()?e.jsx("div",{className:"agent-content-preview markdown-body",children:e.jsx(Be,{remarkPlugins:[Oe],children:g})}):e.jsx("div",{className:"agent-content-preview agent-content-placeholder",children:"No heartbeat procedure markdown content yet."}):e.jsx("textarea",{id:"heartbeat-procedure-file-content",className:"input",rows:16,value:g,readOnly:N,placeholder:"Heartbeat procedure markdown file content will appear here...",onChange:V=>{y(V.target.value),J(!0),p(!1)}}),k&&e.jsxs("span",{className:"config-error",children:["Failed to load file: ",k]}),e.jsxs("span",{className:"config-hint",children:["This editor writes directly to ",e.jsx("code",{children:b}),"."]})]}),!v&&e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!f||w||N,onClick:()=>void H(),children:w?e.jsxs(e.Fragment,{children:[e.jsx(I,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ae,{size:16}),"Save Heartbeat File"]})}),!f&&h&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ae,{size:14}),"File saved"]})]})]})]})}function ta({agent:s,projectId:a,addToast:n,onSaved:d,onHasChangesChange:o,onDelete:m}){const[j,u]=t.useState(s.name),[N,c]=t.useState(s.role),[w,L]=t.useState(s.title??""),[v,A]=t.useState(s.icon??""),[g,y]=t.useState(s.reportsTo??""),[f,J]=t.useState([]),[k,$]=t.useState(!1),[h,p]=t.useState(()=>{const i={};for(const P of ke){const O=s.metadata[P.key];O!=null&&(i[P.key]=String(O))}return i}),[x,b]=t.useState(()=>js(s.runtimeConfig)),[D,G]=t.useState(()=>Ge(s.runtimeConfig)),[T,W]=t.useState(()=>Ns(s.runtimeConfig)),[z,Y]=t.useState(s.bundleConfig?.mode??""),[F,H]=t.useState(s.bundleConfig?.entryFile??"AGENTS.md"),[R,V]=t.useState(s.bundleConfig?.externalPath??""),[l,r]=t.useState(s.bundleConfig?.files??[]),[C,X]=t.useState(Array.isArray(s.metadata?.skills)?s.metadata.skills:[]),[se,me]=t.useState([]),[xe,E]=t.useState(!1),[_,re]=t.useState([]),[_e,S]=t.useState(!1),K=(()=>{const i=s.runtimeConfig??{};return i.modelProvider&&i.modelId?`${i.modelProvider}/${i.modelId}`:typeof i.model=="string"&&i.model.includes("/")?i.model:""})(),q=typeof s.runtimeConfig?.runtimeHint=="string"?s.runtimeConfig.runtimeHint:"",[U,ce]=t.useState(q?"runtime":"model"),[te,de]=t.useState(K),[ue,Ie]=t.useState(q),we=g.trim(),es=t.useMemo(()=>f.filter(i=>i.id!==s.id),[f,s.id]),Ds=!!we&&!es.some(i=>i.id===we);t.useEffect(()=>{let i=!1;return $(!0),gt(void 0,a).then(P=>{i||J(P)}).catch(()=>{i||J([])}).finally(()=>{i||$(!1)}),()=>{i=!0}},[a]),t.useEffect(()=>{E(!0),ft().then(i=>me(i.models)).catch(()=>{}).finally(()=>E(!1))},[]),t.useEffect(()=>{S(!0),As(a).then(re).catch(()=>re([])).finally(()=>S(!1))},[a]);const[he,Ve]=t.useState(null),[ss,ts]=t.useState(!1);t.useEffect(()=>{Ke(s.id,a).then(Ve).catch(()=>Ve(null))},[s.id,a]);const Ps=async()=>{ts(!0);try{await kt(s.id,a),n("Budget usage reset successfully","success");const i=await Ke(s.id,a);Ve(i)}catch(i){n(`Failed to reset budget: ${Z(i)}`,"error")}finally{ts(!1)}},[as,ns]=t.useState(!1),[B,Me]=t.useState({}),[zs,ve]=t.useState(!1),is=s.state==="idle"||s.state==="terminated",je=t.useRef(null),rs=t.useRef(null);t.useEffect(()=>()=>{je.current&&clearTimeout(je.current)},[]);const ge=(()=>{if(j!==s.name||N!==s.role||w!==(s.title??"")||v!==(s.icon??"")||g!==(s.reportsTo??"")||z!==(s.bundleConfig?.mode??"")||F!==(s.bundleConfig?.entryFile??"AGENTS.md")||R!==(s.bundleConfig?.externalPath??"")||JSON.stringify(l)!==JSON.stringify(s.bundleConfig?.files??[]))return!0;for(const ee of ke){const fe=h[ee.key]?.trim()??"",ne=s.metadata[ee.key]!==void 0&&s.metadata[ee.key]!==null?String(s.metadata[ee.key]):"";if(fe!==ne)return!0}const i=s.runtimeConfig??{};if(D!==Ge(s.runtimeConfig))return!0;for(const ee of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns","messageResponseMode"]){const fe=x[ee]?.trim()??"";let ne=i[ee]!==void 0&&i[ee]!==null?String(i[ee]):"";if((ee==="heartbeatIntervalMs"||ee==="heartbeatTimeoutMs")&&ne&&(ne=String(Number(ne)/1e3)),fe!==ne)return!0}const P=i.budgetConfig;for(const ee of["tokenBudget","budgetPeriod","resetDay"]){const fe=T[ee]?.trim()??"",ne=P?.[ee]!==void 0&&P?.[ee]!==null?String(P[ee]):"";if(fe!==ne)return!0}const O=T.usageThreshold?.trim()??"",le=P?.usageThreshold!==void 0&&P?.usageThreshold!==null?String(Number(P.usageThreshold)*100):"";if(O!==le)return!0;const Ne=Array.isArray(s.metadata?.skills)?s.metadata.skills:[];return JSON.stringify(C)!==JSON.stringify(Ne)||U!==(q?"runtime":"model")||te!==K||ue!==q})(),ls=t.useRef(null);t.useEffect(()=>{o&&ls.current!==ge&&(ls.current=ge,o(ge))},[ge,o]),t.useEffect(()=>()=>{o?.(!1)},[o]),t.useEffect(()=>{const i={id:s.id,updatedAt:s.updatedAt},P=rs.current;(!P||P.id!==i.id||P.updatedAt!==i.updatedAt)&&(ge||(rs.current=i,b(js(s.runtimeConfig)),G(Ge(s.runtimeConfig)),W(Ns(s.runtimeConfig)),de(K),Ie(q),ce(q?"runtime":"model")))},[s,ge,K,q]);const cs=(i,P)=>{p(O=>({...O,[i]:P})),ve(!1),B[i]&&Me(O=>{const le={...O};return delete le[i],le})},Fe=(i,P)=>{b(O=>({...O,[i]:P})),ve(!1),B[i]&&Me(O=>{const le={...O};return delete le[i],le})},Hs=i=>{G(i),ve(!1)},Ae=(i,P)=>{W(O=>({...O,[i]:P})),ve(!1),B[i]&&Me(O=>{const le={...O};return delete le[i],le})},Bs=async()=>{const i=Zt(h);for(const[M,oe]of Object.entries({heartbeatIntervalMs:{label:"Heartbeat Interval",min:1},heartbeatTimeoutMs:{label:"Heartbeat Timeout",min:5},maxConcurrentRuns:{label:"Max Concurrent Runs",min:1}})){const ye=x[M]?.trim();if(!ye)continue;const Je=Number(ye);Number.isNaN(Je)||!Number.isFinite(Je)?i[M]=`"${oe.label}" must be a valid number`:Je<oe.min&&(i[M]=`"${oe.label}" must be at least ${oe.min.toLocaleString()}`)}const P=x.messageResponseMode?.trim();P&&!["immediate","on-heartbeat"].includes(P)&&(i.messageResponseMode='"Message Response Mode" must be either immediate or on-heartbeat');const O=T.tokenBudget?.trim();if(O){const M=Number(O);Number.isNaN(M)||!Number.isFinite(M)?i.tokenBudget='"Token Budget" must be a valid number':M<=0&&(i.tokenBudget='"Token Budget" must be greater than 0')}const le=T.usageThreshold?.trim();if(le){const M=Number(le);Number.isNaN(M)||!Number.isFinite(M)?i.usageThreshold='"Usage Threshold" must be a valid number':(M<1||M>100)&&(i.usageThreshold='"Usage Threshold" must be between 1 and 100')}const Ne=T.budgetPeriod?.trim();Ne&&!["daily","weekly","monthly","lifetime"].includes(Ne)&&(i.budgetPeriod='"Budget Period" must be one of: daily, weekly, monthly, lifetime');const ee=T.resetDay?.trim(),fe=Ne||"lifetime";if(ee){const M=Number(ee);Number.isNaN(M)||!Number.isFinite(M)?i.resetDay='"Reset Day" must be a valid number':fe==="weekly"?(M<0||M>6||!Number.isInteger(M))&&(i.resetDay='"Reset Day" must be between 0 (Sunday) and 6 (Saturday) for weekly period'):fe==="monthly"&&(M<1||M>31||!Number.isInteger(M))&&(i.resetDay='"Reset Day" must be between 1 and 31 for monthly period')}if(Object.keys(i).length>0){Me(i),n("Please fix validation errors before saving","error");return}const ne={...s.metadata};for(const M of ke){const oe=h[M.key]?.trim();oe?M.type==="number"?ne[M.key]=Number(oe):ne[M.key]=oe:delete ne[M.key]}C.length>0?ne.skills=C:delete ne.skills;const Q={...s.runtimeConfig};Q.enabled=D;for(const M of["heartbeatIntervalMs","heartbeatTimeoutMs","maxConcurrentRuns"]){const oe=x[M]?.trim();if(!oe)delete Q[M];else{const ye=Number(oe);Q[M]=M==="maxConcurrentRuns"?ye:ye*1e3}}const os=x.messageResponseMode?.trim();if(os?Q.messageResponseMode=os:delete Q.messageResponseMode,U==="runtime")ue.trim()?Q.runtimeHint=ue.trim():delete Q.runtimeHint,delete Q.modelProvider,delete Q.modelId,delete Q.model;else if(delete Q.runtimeHint,te.trim()){const M=te.indexOf("/");M!==-1&&(Q.modelProvider=te.slice(0,M),Q.modelId=te.slice(M+1),Q.model=te.trim())}else delete Q.modelProvider,delete Q.modelId,delete Q.model;const be={},ds=T.tokenBudget?.trim(),us=T.usageThreshold?.trim(),ms=T.budgetPeriod?.trim(),hs=T.resetDay?.trim();ds&&(be.tokenBudget=Number(ds)),us&&(be.usageThreshold=Number(us)/100),ms&&(be.budgetPeriod=ms),hs&&(be.resetDay=Number(hs)),Object.keys(be).length>0?Q.budgetConfig=be:delete Q.budgetConfig;let Ue;z&&(Ue={mode:z,entryFile:F||"AGENTS.md",files:l.length>0?l:["AGENTS.md"]},z==="external"&&R.trim()&&(Ue.externalPath=R.trim())),ns(!0);try{await Rt(s.id,{name:j.trim()||void 0,role:N,title:w.trim()||void 0,icon:v.trim()||void 0,reportsTo:g.trim()||void 0,metadata:ne,runtimeConfig:Q,bundleConfig:Ue},a),n("Settings saved","success"),ve(!0),je.current&&clearTimeout(je.current),je.current=setTimeout(()=>ve(!1),3e3),await d()}catch(M){n(`Failed to save settings: ${Z(M)}`,"error")}finally{ns(!1)}};return e.jsxs("div",{className:"config-tab",children:[e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Agent Configuration"}),e.jsx("p",{className:"config-description",children:"Configure agent settings and behavior."}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-name",children:"Name"}),e.jsx("input",{id:"agent-name",type:"text",className:"input",value:j,onChange:i=>u(i.target.value)})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-role",children:"Role"}),e.jsxs("select",{id:"agent-role",className:"select",value:N,onChange:i=>c(i.target.value),children:[e.jsx("option",{value:"triage",children:"Triage"}),e.jsx("option",{value:"executor",children:"Executor"}),e.jsx("option",{value:"reviewer",children:"Reviewer"}),e.jsx("option",{value:"merger",children:"Merger"}),e.jsx("option",{value:"scheduler",children:"Scheduler"}),e.jsx("option",{value:"custom",children:"Custom"})]})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-title",children:"Title"}),e.jsx("input",{id:"agent-title",type:"text",className:"input",placeholder:"e.g. Senior Code Reviewer",value:w,onChange:i=>L(i.target.value)})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-icon",children:"Icon"}),e.jsx("input",{id:"agent-icon",type:"text",className:"input",placeholder:"e.g. 🤖",value:v,onChange:i=>A(i.target.value)})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-reports-to",children:"Reports To"}),e.jsxs("select",{id:"agent-reports-to",className:"select",value:g,onChange:i=>y(i.target.value),disabled:k,children:[e.jsx("option",{value:"",children:"No manager"}),Ds&&e.jsxs("option",{value:we,children:["Unknown manager (",we,")"]}),es.map(i=>e.jsxs("option",{value:i.id,children:[i.name," (",i.id,")"]},i.id))]})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Skills"}),e.jsx("p",{className:"config-description",children:"Assign skills to this agent for specialized behavior."}),e.jsx("div",{className:"config-fields",children:e.jsx("div",{className:"config-field",children:e.jsx(zt,{id:"agent-skills",label:"Skills",value:C,onChange:X,projectId:a})})})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Model"}),e.jsx("p",{className:"config-description",children:"Choose either a built-in model or a plugin runtime for this agent. These options are mutually exclusive."}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{children:"Runtime Source"}),e.jsxs("div",{className:"config-runtime-tabs",role:"tablist","aria-label":"Runtime source",children:[e.jsx("button",{type:"button",className:`config-runtime-tab${U==="model"?" active":""}`,role:"tab","aria-selected":U==="model",tabIndex:U==="model"?0:-1,onClick:()=>{ce("model"),Ie("")},children:"Built-in Model"}),e.jsx("button",{type:"button",className:`config-runtime-tab${U==="runtime"?" active":""}`,role:"tab","aria-selected":U==="runtime",tabIndex:U==="runtime"?0:-1,onClick:()=>ce("runtime"),children:"Plugin Runtime"})]})]}),U==="model"?e.jsx("div",{className:"config-field",children:e.jsx(xt,{models:se,value:te,onChange:de,placeholder:"Use global default",label:"Agent Model",disabled:xe})}):e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"agent-runtime-hint",children:"Runtime"}),_e?e.jsx("span",{className:"config-hint",children:"Loading runtimes…"}):e.jsxs("select",{id:"agent-runtime-hint",className:"select",value:ue,onChange:i=>Ie(i.target.value),children:[e.jsx("option",{value:"",children:_.length>0?"Select a plugin runtime…":"No plugin runtimes available"}),_.map(i=>e.jsx("option",{value:i.runtimeId,children:i.description?`${i.name} — ${i.description}`:i.name},`${i.pluginId}:${i.runtimeId}`))]})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Heartbeat Settings"}),e.jsx("p",{className:"config-description",children:"Configure how this agent's heartbeat is monitored. Leave a field empty to use system defaults."}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsxs("label",{className:"checkbox-label",htmlFor:"hb-enabled",children:[e.jsx("input",{id:"hb-enabled",type:"checkbox",checked:D,onChange:i=>Hs(i.target.checked)}),"Heartbeat Enabled"]}),e.jsx("span",{className:"config-hint",children:"When enabled, this agent receives scheduled heartbeat runs based on its interval."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-heartbeatIntervalMs",children:"Heartbeat Interval (s)"}),e.jsx("input",{id:"hb-heartbeatIntervalMs",type:"text",inputMode:"numeric",className:ie("input",!!B.heartbeatIntervalMs&&"input--error"),placeholder:String(Ye/1e3),value:x.heartbeatIntervalMs??"",onChange:i=>Fe("heartbeatIntervalMs",i.target.value)}),B.heartbeatIntervalMs?e.jsx("span",{className:"config-error",children:B.heartbeatIntervalMs}):e.jsxs("span",{className:"config-hint",children:["How often heartbeats are checked. Leave empty for system default (",Ye/1e3,"s / ",Ot,")."]})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-heartbeatTimeoutMs",children:"Heartbeat Timeout (s)"}),e.jsx("input",{id:"hb-heartbeatTimeoutMs",type:"text",inputMode:"numeric",className:ie("input",!!B.heartbeatTimeoutMs&&"input--error"),placeholder:"60",value:x.heartbeatTimeoutMs??"",onChange:i=>Fe("heartbeatTimeoutMs",i.target.value)}),B.heartbeatTimeoutMs?e.jsx("span",{className:"config-error",children:B.heartbeatTimeoutMs}):e.jsx("span",{className:"config-hint",children:"Time without heartbeat before agent is considered unresponsive. Leave empty for system default (60s)"})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-maxConcurrentRuns",children:"Max Concurrent Runs"}),e.jsx("input",{id:"hb-maxConcurrentRuns",type:"text",inputMode:"numeric",className:ie("input",!!B.maxConcurrentRuns&&"input--error"),placeholder:"1",value:x.maxConcurrentRuns??"",onChange:i=>Fe("maxConcurrentRuns",i.target.value)}),B.maxConcurrentRuns?e.jsx("span",{className:"config-error",children:B.maxConcurrentRuns}):e.jsx("span",{className:"config-hint",children:"Maximum simultaneous heartbeat runs for this agent. Leave empty for system default (1)."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"hb-messageResponseMode",children:"Message Response Mode"}),e.jsxs("select",{id:"hb-messageResponseMode",className:ie("select",!!B.messageResponseMode&&"input--error"),value:x.messageResponseMode??"",onChange:i=>Fe("messageResponseMode",i.target.value),children:[e.jsx("option",{value:"",children:"System Default (On Heartbeat)"}),e.jsx("option",{value:"on-heartbeat",children:"On Heartbeat"}),e.jsx("option",{value:"immediate",children:"Immediate"})]}),B.messageResponseMode?e.jsx("span",{className:"config-error",children:B.messageResponseMode}):e.jsx("span",{className:"config-hint",children:"How this agent responds to incoming messages. 'Immediate' wakes the agent as soon as a message arrives. 'On Heartbeat' defers processing to the next scheduled heartbeat."})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Budget Settings"}),e.jsx("p",{className:"config-description",children:"Configure token budget limits for this agent. Leave all fields empty to disable budget tracking."}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"budget-tokenBudget",children:"Token Budget"}),e.jsx("input",{id:"budget-tokenBudget",type:"text",inputMode:"numeric",className:ie("input",!!B.tokenBudget&&"input--error"),placeholder:"No limit",value:T.tokenBudget??"",onChange:i=>Ae("tokenBudget",i.target.value)}),B.tokenBudget?e.jsx("span",{className:"config-error",children:B.tokenBudget}):e.jsx("span",{className:"config-hint",children:"Total token cap (input + output) for this agent. Leave empty for no limit."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"budget-usageThreshold",children:"Usage Threshold (%)"}),e.jsx("input",{id:"budget-usageThreshold",type:"text",inputMode:"numeric",className:ie("input",!!B.usageThreshold&&"input--error"),placeholder:"80",value:T.usageThreshold??"",onChange:i=>Ae("usageThreshold",i.target.value)}),B.usageThreshold?e.jsx("span",{className:"config-error",children:B.usageThreshold}):e.jsx("span",{className:"config-hint",children:"Warning threshold as a percentage. Agent warns when usage reaches this level. Default: 80%."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"budget-budgetPeriod",children:"Budget Period"}),e.jsxs("select",{id:"budget-budgetPeriod",className:ie("select",!!B.budgetPeriod&&"input--error"),value:T.budgetPeriod??"",onChange:i=>Ae("budgetPeriod",i.target.value),children:[e.jsx("option",{value:"",children:"No reset (lifetime)"}),e.jsx("option",{value:"daily",children:"Daily"}),e.jsx("option",{value:"weekly",children:"Weekly"}),e.jsx("option",{value:"monthly",children:"Monthly"})]}),B.budgetPeriod?e.jsx("span",{className:"config-error",children:B.budgetPeriod}):e.jsx("span",{className:"config-hint",children:"How often the budget counter resets. Leave empty for lifetime budget."})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"budget-resetDay",children:"Reset Day"}),e.jsx("input",{id:"budget-resetDay",type:"text",inputMode:"numeric",className:ie("input",!!B.resetDay&&"input--error"),placeholder:"Auto",value:T.resetDay??"",onChange:i=>Ae("resetDay",i.target.value)}),B.resetDay?e.jsx("span",{className:"config-error",children:B.resetDay}):e.jsx("span",{className:"config-hint",children:T.budgetPeriod==="weekly"?"Day of week (0=Sunday to 6=Saturday) for reset.":T.budgetPeriod==="monthly"?"Day of month (1-31) for reset.":"Day for reset (weekly: 0-6, monthly: 1-31). Leave empty for automatic."})]}),he?.budgetLimit!=null&&e.jsxs("div",{className:"config-field",children:[e.jsx("label",{children:"Current Usage"}),e.jsxs("div",{className:"budget-progress-container",children:[e.jsx("div",{className:"budget-progress-bar",children:e.jsx("div",{className:ie("budget-progress-bar__fill",(he.usagePercent??0)>=100?"budget-progress-bar__fill--red":(he.usagePercent??0)>=80?"budget-progress-bar__fill--amber":"budget-progress-bar__fill--green"),style:{width:`${Math.min(he.usagePercent??0,100)}%`}})}),e.jsxs("span",{className:"budget-progress-label",children:[(he.currentUsage??0).toLocaleString()," / ",(he.budgetLimit??0).toLocaleString()," tokens (",Math.round(he.usagePercent??0),"% used)"]})]})]}),he?.budgetLimit!=null&&e.jsx("div",{className:"config-field",children:e.jsx("button",{className:"btn btn-reset-budget",onClick:()=>void Ps(),disabled:ss,children:ss?e.jsxs(e.Fragment,{children:[e.jsx(I,{size:14,className:"animate-spin"}),"Resetting…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Xe,{size:14}),"Reset Budget Usage"]})})})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Instruction Bundle"}),e.jsx("p",{className:"config-description",children:"Configure the agent's instruction bundle. Leave empty to use inline instructions only."}),e.jsxs("div",{className:"config-fields",children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-mode",children:"Bundle Mode"}),e.jsxs("select",{id:"bundle-mode",className:"select",value:z,onChange:i=>Y(i.target.value),children:[e.jsx("option",{value:"",children:"None (use inline instructions)"}),e.jsx("option",{value:"managed",children:"Managed (system-managed directory)"}),e.jsx("option",{value:"external",children:"External (user-specified path)"})]}),e.jsxs("span",{className:"config-hint",children:[z==="managed"&&"Files will be stored in a system-managed directory within .fusion/agents/",z==="external"&&"Specify an external directory path for the instruction files",!z&&"Select a mode to enable instruction bundling"]})]}),z&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-entry-file",children:"Entry File"}),e.jsx("input",{id:"bundle-entry-file",type:"text",className:"input",placeholder:"AGENTS.md",value:F,onChange:i=>H(i.target.value)}),e.jsx("span",{className:"config-hint",children:"Primary instructions file name (default: AGENTS.md)"})]}),z==="external"&&e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-external-path",children:"External Path"}),e.jsx("input",{id:"bundle-external-path",type:"text",className:"input",placeholder:"e.g. .fusion/agents/my-agent",value:R,onChange:i=>V(i.target.value)}),e.jsx("span",{className:"config-hint",children:"Absolute or relative path to the external directory"})]}),e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:"bundle-files",children:"Files (comma-separated)"}),e.jsx("input",{id:"bundle-files",type:"text",className:"input",placeholder:"AGENTS.md, PROMPTS.md",value:l.join(", "),onChange:i=>r(i.target.value.split(",").map(P=>P.trim()).filter(Boolean))}),e.jsx("span",{className:"config-hint",children:"List of file names in the bundle directory"})]})]})]})]}),e.jsxs("div",{className:"config-section",children:[e.jsx("h3",{children:"Advanced Settings"}),e.jsx("p",{className:"config-description",children:"Advanced configuration options for this agent. Leave a field empty to use system defaults."}),e.jsx("div",{className:"config-fields",children:ke.map(i=>{const P=!!B[i.key];return e.jsxs("div",{className:"config-field",children:[e.jsx("label",{htmlFor:`adv-${i.key}`,children:i.label}),i.type==="select"?e.jsxs("select",{id:`adv-${i.key}`,className:ie("select",P&&"input--error"),value:h[i.key]??"",onChange:O=>cs(i.key,O.target.value),children:[e.jsx("option",{value:"",children:"System Default"}),i.options?.map(O=>e.jsx("option",{value:O.value,children:O.label},O.value))]}):e.jsx("input",{id:`adv-${i.key}`,type:"text",inputMode:i.type==="number"?"numeric":void 0,className:ie("input",P&&"input--error"),placeholder:i.placeholder,value:h[i.key]??"",onChange:O=>cs(i.key,O.target.value)}),P&&e.jsx("span",{className:"config-error",children:B[i.key]}),!P&&i.hint&&e.jsx("span",{className:"config-hint",children:i.hint})]},i.key)})}),e.jsxs("div",{className:"config-actions",children:[e.jsx("button",{className:"btn btn-task-create",disabled:!ge||as,onClick:()=>void Bs(),children:as?e.jsxs(e.Fragment,{children:[e.jsx(I,{size:16,className:"animate-spin"}),"Saving…"]}):e.jsxs(e.Fragment,{children:[e.jsx(ae,{size:16}),"Save Settings"]})}),!ge&&zs&&e.jsxs("span",{className:"config-saved-indicator",children:[e.jsx(ae,{size:14}),"Settings saved"]})]})]}),e.jsx(sa,{agent:s,projectId:a,addToast:n,onSaved:d}),e.jsxs("div",{className:"config-section config-section--danger",children:[e.jsx("h3",{children:"Danger Zone"}),e.jsx("p",{className:"config-description",children:"Permanently delete this agent from the project."}),e.jsx("div",{className:"config-fields",children:e.jsxs("div",{className:"config-field",children:[e.jsxs("button",{className:"btn btn--danger",disabled:!is||!m,onClick:()=>void m?.(),children:[e.jsx(De,{size:16}),"Delete Agent"]}),e.jsx("span",{className:"config-danger-note",children:is?"Deletion is permanent and cannot be undone.":`Agent deletion is only available when state is idle or terminated (current state: ${s.state}).`})]})})]})]})}function aa({agentId:s,projectId:a,onChildClick:n}){const[d,o]=t.useState([]),[m,j]=t.useState(!0);return t.useEffect(()=>{j(!0),ut(s,a).then(o).finally(()=>j(!1))},[s,a]),m?e.jsxs("div",{className:"detail-section",children:[e.jsx("div",{className:"detail-section-header",children:e.jsx("h3",{children:"Employees"})}),e.jsxs("div",{className:"detail-section-body detail-section-body--loading",children:[e.jsx(I,{size:16,className:"spin"}),e.jsx("span",{className:"text-muted",children:"Loading employees..."})]})]}):e.jsxs("div",{className:"detail-section",children:[e.jsxs("div",{className:"detail-section-header",children:[e.jsx("h3",{children:"Employees"}),e.jsxs("span",{className:"text-muted",children:["(",d.length,")"]})]}),e.jsx("div",{className:"detail-section-body",children:d.length===0?e.jsxs("div",{className:"agent-empty agent-empty--padded",children:[e.jsx(Ms,{size:32,opacity:.3}),e.jsx("p",{children:"No employees"}),e.jsx("p",{className:"text-muted",children:"This agent has no employees"})]}):e.jsx("div",{className:"agent-tree__children",children:d.map(u=>{const N=Qe[u.state];return e.jsxs("div",{className:"agent-tree__node agent-is-child",onClick:()=>n?.(u.id),role:"button",tabIndex:0,onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&(c.key===" "&&c.preventDefault(),n?.(u.id))},style:{cursor:n?"pointer":"default"},children:[e.jsx("span",{className:"agent-tree__icon",children:u.icon??"🤖"}),e.jsx("span",{className:"agent-tree__name",children:u.name}),e.jsx("span",{className:"agent-tree__badge",style:{background:N?.bg??"var(--state-idle-bg)",color:N?.text??"var(--state-idle-text)",border:`1px solid ${N?.border??"var(--state-idle-border)"}`},children:u.state})]},u.id)})})})]})}const la=Object.freeze(Object.defineProperty({__proto__:null,AgentDetailView:It,relativeTime:pe},Symbol.toStringTag,{value:"Module"}));export{la as A,zt as S,pe as r};
|