@runfusion/fusion 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/bin.js +1122 -356
  2. package/dist/client/assets/{AgentDetailView-DQBjJSPJ.js → AgentDetailView-B20ApPe1.js} +3 -3
  3. package/dist/client/assets/{AgentsView-xm_3NO4M.css → AgentsView-Bkk-uBij.css} +1 -1
  4. package/dist/client/assets/{AgentsView-DlA0yHBg.js → AgentsView-ChN1tgQ0.js} +17 -17
  5. package/dist/client/assets/ChatView-oPMFwmoc.js +1 -0
  6. package/dist/client/assets/{DevServerView-BVixhlF0.js → DevServerView-DQrVLbK5.js} +1 -1
  7. package/dist/client/assets/{DirectoryPicker-tvBgHxa7.js → DirectoryPicker-DVmy6sLM.js} +1 -1
  8. package/dist/client/assets/{DocumentsView-DVw_wT6V.js → DocumentsView-DHEv-Q2a.js} +1 -1
  9. package/dist/client/assets/{InsightsView-G3MZhwSx.js → InsightsView-ByyY7GX7.js} +2 -2
  10. package/dist/client/assets/{MemoryView-Bl9gx2Dw.js → MemoryView-Udiu0u8R.js} +1 -1
  11. package/dist/client/assets/{NodesView-dwVhD4V2.js → NodesView-CupS-GGc.js} +4 -4
  12. package/dist/client/assets/{PiExtensionsManager-CEHp6_Mj.js → PiExtensionsManager-DXs2xI8K.js} +2 -2
  13. package/dist/client/assets/PluginManager-BCpiZf4_.js +1 -0
  14. package/dist/client/assets/{ResearchView-BvlLYC_1.js → ResearchView-BG9Feaeb.js} +1 -1
  15. package/dist/client/assets/ResearchView-BzRdUzNq.css +1 -0
  16. package/dist/client/assets/{RoadmapsView-DdYXssP2.js → RoadmapsView-BTJtmBnF.js} +2 -2
  17. package/dist/client/assets/SettingsModal-DZ_LaEhd.js +31 -0
  18. package/dist/client/assets/{SettingsModal-CriZP5Lp.css → SettingsModal-DcGFm6NR.css} +1 -1
  19. package/dist/client/assets/{SettingsModal-CGWipm3s.js → SettingsModal-eNCZiHa6.js} +1 -1
  20. package/dist/client/assets/{SetupWizardModal-CKsJduYM.js → SetupWizardModal-yf79TN1L.js} +1 -1
  21. package/dist/client/assets/SkillMultiselect-DDHJnrkn.css +1 -0
  22. package/dist/client/assets/SkillMultiselect-DOj5vX4U.js +1 -0
  23. package/dist/client/assets/SkillsView-CgnCnikX.js +1 -0
  24. package/dist/client/assets/{TodoView-ByXJ90yL.js → TodoView-67BMyICY.js} +2 -2
  25. package/dist/client/assets/{folder-open-CxOUgHDf.js → folder-open-D11gjHGK.js} +1 -1
  26. package/dist/client/assets/index-BLn1R7Ob.css +1 -0
  27. package/dist/client/assets/index-CLAHcGnI.js +656 -0
  28. package/dist/client/assets/{list-checks--sf9u9ox.js → list-checks-CBzPc3GA.js} +1 -1
  29. package/dist/client/assets/{star-CF1f2iPu.js → star-BWcRk8nt.js} +1 -1
  30. package/dist/client/assets/{upload-rOBd4OhB.js → upload-91TM4ljC.js} +1 -1
  31. package/dist/client/assets/{users-De-vFat1.js → users-BAsI___L.js} +1 -1
  32. package/dist/client/index.html +2 -2
  33. package/dist/client/theme-data.css +1 -1
  34. package/dist/client/version.json +1 -1
  35. package/dist/extension.js +479 -74
  36. package/dist/pi-claude-cli/package.json +1 -1
  37. package/package.json +1 -1
  38. package/skill/fusion/references/cli-commands.md +14 -0
  39. package/skill/fusion/references/engine-tools.md +1 -0
  40. package/dist/client/assets/ChatView-DK5CmiAk.js +0 -1
  41. package/dist/client/assets/PluginManager-Dx0mcwat.js +0 -1
  42. package/dist/client/assets/ResearchView-BVJFgfat.css +0 -1
  43. package/dist/client/assets/SettingsModal-Bgjg_4CD.js +0 -31
  44. package/dist/client/assets/SkillsView-C4Tz7CxC.js +0 -1
  45. package/dist/client/assets/index-BCz4ye4p.css +0 -1
  46. package/dist/client/assets/index-D7gT6mCr.js +0 -656
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentDetailView-DQBjJSPJ.js","assets/vendor-react-K0fH_qHe.js","assets/index-D7gT6mCr.js","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/index-BCz4ye4p.css","assets/star-CF1f2iPu.js","assets/list-checks--sf9u9ox.js","assets/upload-rOBd4OhB.js","assets/folder-open-CxOUgHDf.js","assets/AgentDetailView-B5tq9ius.css"])))=>i.map(i=>d[i]);
2
- import{c as Xe,s as yt,A as Me,r as Ge,F as Qe,f as wt,C as Le,Z as jt,B as Ze,g as Je,a as dt,b as He,d as kt,e as Nt,h as Ct,i as ut,j as St,u as et,P as It,k as At,l as mt,m as gt,n as Et,o as Tt,p as Mt,q as Rt,t as Pt,v as _t,w as $t,x as tt,G as Ft,S as Lt,L as qe,T as Ve,R as De,X as nt,y as Dt,z as zt,D as Ot,E as Ht,H as je,I as We,J as qt,K as Vt,M as Wt,N as Kt,O as Ut,Q as Bt,U as ht,V as Gt,W as Pe,Y as st,_ as Qt,$ as Jt,a0 as Xt,a1 as _e,a2 as Zt,a3 as at,a4 as Yt,a5 as en,a6 as tn,a7 as nn}from"./index-D7gT6mCr.js";import{r as s,j as e,a as sn}from"./vendor-react-K0fH_qHe.js";import{U as pt}from"./upload-rOBd4OhB.js";import{F as an}from"./folder-open-CxOUgHDf.js";/**
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentDetailView-B20ApPe1.js","assets/vendor-react-K0fH_qHe.js","assets/index-CLAHcGnI.js","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/index-BLn1R7Ob.css","assets/star-BWcRk8nt.js","assets/SkillMultiselect-DOj5vX4U.js","assets/SkillMultiselect-DDHJnrkn.css","assets/list-checks-CBzPc3GA.js","assets/AgentDetailView-B5tq9ius.css"])))=>i.map(i=>d[i]);
2
+ import{c as Xe,s as yt,A as Me,r as Ge,F as Qe,f as wt,C as De,Z as jt,B as Ze,g as Je,a as dt,b as He,d as kt,e as Nt,h as ut,i as Ct,u as et,P as It,j as St,k as mt,l as gt,m as At,n as Et,o as Tt,p as Mt,q as Rt,t as Pt,v as _t,w as tt,G as Ft,S as $t,L as qe,T as Ve,R as Le,X as nt,x as Dt,y as Lt,z as zt,D as Ot,E as je,H as We,I as Ht,J as qt,K as Vt,M as Wt,N as Kt,O as Ut,Q as ht,U as Bt,V as Pe,W as at,Y as Gt,_ as Qt,$ as Jt,a0 as _e,a1 as Xt,a2 as st,a3 as Zt,a4 as Yt,a5 as en,a6 as tn}from"./index-CLAHcGnI.js";import{r as a,j as e,a as nn}from"./vendor-react-K0fH_qHe.js";import{S as an}from"./SkillMultiselect-DOj5vX4U.js";import{U as pt}from"./upload-91TM4ljC.js";import{F as sn}from"./folder-open-D11gjHGK.js";import"./vendor-xterm-DzcZoU0P.js";/**
3
3
  * @license lucide-react v1.7.0 - ISC
4
4
  *
5
5
  * This source code is licensed under the ISC license.
@@ -14,7 +14,7 @@ import{c as Xe,s as yt,A as Me,r as Ge,F as Qe,f as wt,C as Le,Z as jt,B as Ze,g
14
14
  *
15
15
  * This source code is licensed under the ISC license.
16
16
  * See the LICENSE file in the root directory of this source tree.
17
- */const dn=[["path",{d:"M10 5H3",key:"1qgfaw"}],["path",{d:"M12 19H3",key:"yhmn1j"}],["path",{d:"M14 3v4",key:"1sua03"}],["path",{d:"M16 17v4",key:"1q0r14"}],["path",{d:"M21 12h-9",key:"1o4lsq"}],["path",{d:"M21 19h-5",key:"1rlt1p"}],["path",{d:"M21 5h-7",key:"1oszz2"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M8 12H3",key:"a7s4jb"}]],un=Xe("sliders-horizontal",dn),it=200;function mn(a,l){const[j,h]=s.useState([]),[o,c]=s.useState(!1),r=s.useRef(null),m=s.useRef(0),d=s.useRef(a),x=s.useRef(l);return(d.current!==a||x.current!==l)&&(d.current=a,x.current=l,m.current++,r.current&&(r.current(),r.current=null),h([]),c(!1)),s.useEffect(()=>{if(!a){h([]),c(!1);return}const b=m.current;let N=`/api/tasks/${encodeURIComponent(a)}/logs/stream`;l&&(N+=`?projectId=${encodeURIComponent(l)}`);const I=yt(N,{events:{"agent:log":f=>{if(m.current===b)try{const M=JSON.parse(f.data),E={type:M.type??"text",text:M.text??M.content??"",timestamp:M.timestamp,content:M.content};h(R=>{const y=[E,...R];return y.length>it?y.slice(0,it):y})}catch{}}},onOpen:()=>{m.current===b&&c(!0)},onError:()=>{m.current===b&&c(!1)}});return r.current=I,()=>{I(),r.current=null,m.current===b&&c(!1)}},[a,l]),{entries:j,isConnected:o}}const gn=5e3;function hn({agent:a,projectId:l,onSelect:j,onOpenTaskLogs:h}){const{entries:o,isConnected:c}=mn(a.taskId,l),[r,m]=s.useState(null);s.useEffect(()=>{if(!a.taskId){m(null);return}let R=!1,y;const v=async()=>{try{const C=await wt(a.taskId,l);R||m(C)}catch{}finally{R||(y=setTimeout(v,gn))}};return v(),()=>{R=!0,y&&clearTimeout(y)}},[a.taskId,l]);const d=a.lastHeartbeatAt?Math.floor((Date.now()-new Date(a.lastHeartbeatAt).getTime())/1e3):0,x=(()=>{if(!a.lastHeartbeatAt)return null;const R=Ge(a.runtimeConfig?.heartbeatIntervalMs),y=new Date(a.lastHeartbeatAt).getTime()+R,v=Math.round((y-Date.now())/1e3);return Number.isFinite(v)?v<=0?`Heartbeat overdue ${Ke(-v)}`:`Next heartbeat in ${Ke(v)}`:null})(),p=r?.steps?.[r.currentStep??0],b=r?.steps?.length??0,N=(r?.currentStep??0)+1,I=r?.modelId,f=()=>{j&&j(a.id)},M=R=>{R.stopPropagation(),a.taskId&&h&&h(a.taskId)},E=R=>{(R.key==="Enter"||R.key===" ")&&(R.preventDefault(),f())};return e.jsxs("div",{className:"live-agent-card",onClick:f,onKeyDown:E,role:"button",tabIndex:0,"aria-label":`Select agent ${a.name}`,children:[e.jsxs("div",{className:"live-agent-card-header",children:[e.jsxs("div",{className:"live-agent-card-name",children:[e.jsx("span",{className:"live-agent-pulse"}),e.jsx("span",{children:a.name})]}),a.taskId&&e.jsx("span",{className:"live-agent-task badge",children:a.taskId})]}),e.jsx("div",{className:"live-agent-card-transcript",children:o.length===0?e.jsx("div",{className:"live-agent-card-empty",children:a.taskId?p?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"live-agent-card-status",children:["Step ",N,b?`/${b}`:"",": ",p.name]}),I&&e.jsx("div",{className:"live-agent-card-status-sub",children:I}),e.jsx("div",{className:"live-agent-card-status-sub",children:c?"Waiting for output...":"Connecting to log stream..."})]}):e.jsx("span",{children:c?"Waiting for output...":"Connecting..."}):e.jsx("span",{children:a.state==="running"?"Starting...":"Idle — no task assigned"})}):o.slice(0,20).map((R,y)=>e.jsx("div",{className:"live-agent-card-line",children:R.text},y))}),e.jsxs("div",{className:"live-agent-card-footer",children:[e.jsxs("div",{className:"live-agent-card-footer-meta",children:[e.jsx("span",{className:"text-secondary",title:"Time since last heartbeat",children:Ke(d)}),x&&e.jsx("span",{className:"live-agent-card-next-heartbeat",title:x,children:x})]}),e.jsxs("div",{className:"live-agent-card-footer-actions",children:[a.taskId&&h&&e.jsxs("button",{type:"button",className:"live-agent-card-logs-btn",onClick:M,title:"View live run logs","aria-label":`View live logs for ${a.taskId}`,children:[e.jsx(Qe,{size:12}),e.jsx("span",{children:"Live logs"})]}),c&&e.jsx(Me,{size:12,className:"live-agent-streaming-dot"})]})]})]})}function Ke(a){return a<60?`${a}s`:a<3600?`${Math.floor(a/60)}m ${a%60}s`:`${Math.floor(a/3600)}h ${Math.floor(a%3600/60)}m`}function pn({agents:a,projectId:l,onAgentSelect:j,onOpenTaskLogs:h}){const o=Array.from(new Map(a.map(c=>[c.id,c])).values());return o.length===0?null:e.jsxs("div",{className:"active-agents-panel",children:[e.jsxs("div",{className:"active-agents-panel-header",children:[e.jsx(Me,{size:16}),e.jsxs("span",{children:["Active Agents (",o.length,")"]})]}),e.jsx("div",{className:"active-agents-grid",children:o.map(c=>e.jsx(hn,{agent:c,projectId:l,onSelect:j,onOpenTaskLogs:h},c.id))})]})}const fn=[{icon:Me,label:"Active Agents",valueKey:"activeCount",className:"agent-metric-card--active"},{icon:ln,label:"Assigned Tasks",valueKey:"assignedTaskCount",className:"agent-metric-card--tasks"},{icon:Le,label:"Success Rate",valueKey:"successRate",className:"agent-metric-card--success"},{icon:jt,label:"Total Runs",valueKey:"completedRuns",className:"agent-metric-card--runs"}];function vn({stats:a}){return a?e.jsx("div",{className:"agent-metrics-bar",children:fn.map(l=>{const j=l.valueKey==="successRate"?`${Math.round(a.successRate*100)}%`:a[l.valueKey];return e.jsxs("div",{className:`agent-metric-card ${l.className}`,children:[e.jsx(l.icon,{size:18}),e.jsxs("div",{className:"agent-metric-info",children:[e.jsx("span",{className:"agent-metric-value",children:j}),e.jsx("span",{className:"agent-metric-label",children:l.label})]})]},l.label)})}):null}function rt(a){return typeof a=="number"&&Number.isFinite(a)?a:0}function Te(a){return a.toLocaleString()}function bn({agents:a}){const{rows:l,totalInputTokens:j,totalOutputTokens:h,totalTokens:o}=s.useMemo(()=>{const r=a.map(m=>{const d=rt(m.totalInputTokens),x=rt(m.totalOutputTokens);return{id:m.id,name:m.name,inputTokens:d,outputTokens:x,totalTokens:d+x}}).sort((m,d)=>d.totalTokens-m.totalTokens||m.name.localeCompare(d.name)||m.id.localeCompare(d.id));return{rows:r,totalInputTokens:r.reduce((m,d)=>m+d.inputTokens,0),totalOutputTokens:r.reduce((m,d)=>m+d.outputTokens,0),totalTokens:r.reduce((m,d)=>m+d.totalTokens,0)}},[a]),c=o>0;return e.jsxs("section",{className:"agent-token-stats-panel","aria-label":"Agent token usage statistics",children:[e.jsx("header",{className:"agent-token-stats-panel__header",children:e.jsx("h3",{className:"agent-token-stats-panel__title",children:"Token Usage by Agent"})}),e.jsxs("div",{className:"agent-token-stats-panel__totals",role:"list","aria-label":"Token usage totals",children:[e.jsxs("div",{className:"agent-token-stats-panel__total-card",role:"listitem",children:[e.jsx("span",{className:"agent-token-stats-panel__total-label",children:"Input Tokens"}),e.jsx("span",{className:"agent-token-stats-panel__total-value",children:Te(j)})]}),e.jsxs("div",{className:"agent-token-stats-panel__total-card",role:"listitem",children:[e.jsx("span",{className:"agent-token-stats-panel__total-label",children:"Output Tokens"}),e.jsx("span",{className:"agent-token-stats-panel__total-value",children:Te(h)})]}),e.jsxs("div",{className:"agent-token-stats-panel__total-card",role:"listitem",children:[e.jsx("span",{className:"agent-token-stats-panel__total-label",children:"Combined Tokens"}),e.jsx("span",{className:"agent-token-stats-panel__total-value",children:Te(o)})]})]}),c?e.jsx("div",{className:"agent-token-stats-panel__table-wrapper",children:e.jsxs("table",{className:"agent-token-stats-panel__table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Agent"}),e.jsx("th",{scope:"col",children:"Input"}),e.jsx("th",{scope:"col",children:"Output"}),e.jsx("th",{scope:"col",children:"Total"})]})}),e.jsx("tbody",{children:l.map(r=>e.jsxs("tr",{children:[e.jsxs("th",{scope:"row",className:"agent-token-stats-panel__agent-cell",children:[e.jsx("span",{className:"agent-token-stats-panel__agent-name",children:r.name}),e.jsx("span",{className:"agent-token-stats-panel__agent-id",children:r.id})]}),e.jsx("td",{children:Te(r.inputTokens)}),e.jsx("td",{children:Te(r.outputTokens)}),e.jsx("td",{className:"agent-token-stats-panel__total-cell",children:Te(r.totalTokens)})]},r.id))})]})}):e.jsx("div",{className:"agent-token-stats-panel__empty",role:"status",children:"No token usage recorded yet. Token totals appear here once agents run."})]})}function $e({title:a="No agents found",description:l="Create an agent to get started",ctaLabel:j="Create Agent",onCtaClick:h}){return e.jsxs("div",{className:"agent-empty",children:[e.jsx(Ze,{size:48,opacity:.3,className:"agent-empty-state__icon"}),e.jsx("p",{className:"agent-empty-state__title",children:a}),e.jsx("p",{className:"agent-empty-state__description text-secondary",children:l}),h?e.jsx("button",{type:"button",className:"btn btn-task-create btn-sm",onClick:h,children:j}):null]})}const ft="fn-agent-tree-expanded";function lt(a){try{const l=Je(ft,a);if(l){const j=JSON.parse(l);return new Set(Array.isArray(j)?j:[])}}catch{}return new Set}function xn(a,l){try{dt(ft,JSON.stringify([...a]),l)}catch{}}function yn(a,l){const j=new Map,h=new Map;for(const c of a)if(j.set(c.id,c),c.reportsTo){const r=h.get(c.reportsTo)??[];r.push(c),h.set(c.reportsTo,r)}function o(c,r){const m=h.get(c.id)??[],d=l.has(c.id)?m.map(x=>o(x,r+1)):[];return{agent:c,children:d,depth:r}}return a.filter(c=>!c.reportsTo||!j.has(c.reportsTo)).map(c=>o(c,0))}function wn(a,l){const[j,h]=s.useState(()=>lt(l));s.useEffect(()=>{h(lt(l))},[l]);const o=s.useMemo(()=>yn(a,j),[a,j]),c=s.useCallback(d=>{h(x=>{const p=new Set(x);return p.has(d)?p.delete(d):p.add(d),xn(p,l),p})},[l]),r=s.useCallback(d=>j.has(d),[j]),m=s.useCallback(d=>a.filter(x=>x.reportsTo===d),[a]);return{rootNodes:o,toggleExpand:c,isExpanded:r,getChildren:m,isLoading:!1}}const ot=3,Ue=1e3;function jn({isOpen:a,onClose:l,onGenerated:j,projectId:h}){const[o,c]=s.useState(""),[r,m]=s.useState({type:"input"}),[d,x]=s.useState(null),[p,b]=s.useState(!1),N=s.useRef(null),I=s.useRef(null);s.useEffect(()=>{a&&r.type==="input"&&I.current?.focus()},[a,r.type]),s.useEffect(()=>{if(!a&&N.current){const v=N.current;N.current=null,He(v,h).catch(()=>{})}},[a,h]),s.useEffect(()=>{if(!a)return;const v=C=>{C.key==="Escape"&&f()};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[a]);const f=s.useCallback(()=>{if(N.current){const v=N.current;N.current=null,He(v,h).catch(()=>{})}c(""),m({type:"input"}),x(null),b(!1),l()},[l,h]),M=s.useCallback(async()=>{if(!(!o.trim()||o.trim().length<ot)){x(null),m({type:"loading"});try{const{sessionId:v}=await kt(o.trim(),h);N.current=v;const{spec:C}=await Nt(v,h);m({type:"preview",spec:C,sessionId:v})}catch(v){const C=v instanceof Error?v.message:"Failed to generate agent specification";C.includes("429")||C.toLowerCase().includes("rate limit")?x("Too many requests. Please wait a moment and try again."):x(C),m({type:"input"}),N.current=null}}},[o,h]),E=s.useCallback(async()=>{if(N.current){const v=N.current;N.current=null;try{await He(v,h)}catch{}}await M()},[M,h]),R=s.useCallback(()=>{r.type==="preview"&&(N.current=null,j(r.spec),c(""),m({type:"input"}),x(null),b(!1),l())},[r,j,l]);if(!a)return null;const y=o.trim().length>=ot&&o.trim().length<=Ue;return e.jsx("div",{className:"agent-dialog-overlay",onClick:v=>{v.target===v.currentTarget&&f()},children:e.jsxs("div",{className:"agent-dialog",role:"dialog","aria-modal":"true","aria-label":"Generate agent with AI",children:[e.jsxs("div",{className:"agent-dialog-header",children:[e.jsxs("span",{className:"agent-dialog-header-title",children:[e.jsx("span",{className:"agent-dialog-header-sparkle",children:"✨"}),"Generate Agent"]}),e.jsx("button",{className:"modal-close",onClick:f,"aria-label":"Close",children:"×"})]}),e.jsxs("div",{className:"agent-dialog-body",children:[d&&e.jsx("div",{className:"agent-dialog-error-banner",children:d}),r.type==="input"&&e.jsxs("div",{children:[e.jsx("p",{className:"agent-dialog-info",children:"Describe your agent's role and the AI will generate a complete specification including system prompt, suggested configuration, and more."}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx("label",{htmlFor:"agent-role-description",children:"Role Description"}),e.jsx("textarea",{ref:I,id:"agent-role-description",className:"input agent-dialog-textarea",rows:4,placeholder:'e.g. "Senior frontend code reviewer who specializes in React accessibility"',value:o,onChange:v=>c(v.target.value),onKeyDown:v=>{v.key==="Enter"&&!v.shiftKey&&y&&(v.preventDefault(),M())},maxLength:Ue,"aria-describedby":"role-description-hint"}),e.jsxs("div",{id:"role-description-hint",className:"agent-dialog-hint",children:[e.jsx("span",{children:"Describe what your agent should do"}),e.jsxs("span",{children:[o.length,"/",Ue]})]})]})]}),r.type==="loading"&&e.jsxs("div",{className:"agent-dialog-loading-center",children:[e.jsx("div",{className:"agent-dialog-spinner spin"}),e.jsx("p",{className:"agent-dialog-loading-text",children:"Generating agent specification..."})]}),r.type==="preview"&&e.jsxs("div",{children:[e.jsxs("div",{className:"agent-dialog-summary agent-dialog-summary--spaced",children:[e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label agent-dialog-summary-row-label--fixed",children:"Title"}),e.jsxs("span",{className:"agent-dialog-summary-row-value",children:[r.spec.icon," ",r.spec.title]})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label agent-dialog-summary-row-label--fixed",children:"Role"}),e.jsx("span",{children:r.spec.role})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label agent-dialog-summary-row-label--fixed",children:"Description"}),e.jsx("span",{className:"agent-dialog-summary-row-value agent-dialog-summary-row-value--body",children:r.spec.description})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label agent-dialog-summary-row-label--fixed",children:"Thinking"}),e.jsx("span",{className:"agent-dialog-summary-row-value agent-dialog-summary-row-value--capitalize",children:r.spec.thinkingLevel})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label agent-dialog-summary-row-label--fixed",children:"Max Turns"}),e.jsx("span",{children:r.spec.maxTurns})]})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsxs("label",{children:["System Prompt",e.jsx("button",{type:"button",className:"agent-dialog-expand-btn",onClick:()=>b(!p),children:p?"Collapse":"Expand"})]}),e.jsxs("div",{className:`agent-generation-prompt-box${p?"":" agent-generation-prompt-box--collapsed"}`,children:[r.spec.systemPrompt,!p&&r.spec.systemPrompt.length>500&&e.jsx("div",{className:"agent-generation-prompt-fade"})]})]})]})]}),e.jsxs("div",{className:"agent-dialog-footer",children:[e.jsx("button",{className:"btn",onClick:f,children:"Cancel"}),r.type==="input"&&e.jsx("button",{className:"btn btn-task-create",onClick:()=>void M(),disabled:!y,children:"Generate"}),r.type==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn",onClick:()=>void E(),children:"Regenerate"}),e.jsx("button",{className:"btn btn-task-create",onClick:R,children:"Use This"})]})]})]})})}const kn=`# Soul: Chief Executive Officer
17
+ */const dn=[["path",{d:"M10 5H3",key:"1qgfaw"}],["path",{d:"M12 19H3",key:"yhmn1j"}],["path",{d:"M14 3v4",key:"1sua03"}],["path",{d:"M16 17v4",key:"1q0r14"}],["path",{d:"M21 12h-9",key:"1o4lsq"}],["path",{d:"M21 19h-5",key:"1rlt1p"}],["path",{d:"M21 5h-7",key:"1oszz2"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M8 12H3",key:"a7s4jb"}]],un=Xe("sliders-horizontal",dn),it=200;function mn(s,l){const[j,h]=a.useState([]),[o,u]=a.useState(!1),r=a.useRef(null),m=a.useRef(0),d=a.useRef(s),y=a.useRef(l);return(d.current!==s||y.current!==l)&&(d.current=s,y.current=l,m.current++,r.current&&(r.current(),r.current=null),h([]),u(!1)),a.useEffect(()=>{if(!s){h([]),u(!1);return}const v=m.current;let N=`/api/tasks/${encodeURIComponent(s)}/logs/stream`;l&&(N+=`?projectId=${encodeURIComponent(l)}`);const S=yt(N,{events:{"agent:log":R=>{if(m.current===v)try{const M=JSON.parse(R.data),E={type:M.type??"text",text:M.text??M.content??"",timestamp:M.timestamp,content:M.content};h(T=>{const b=[E,...T];return b.length>it?b.slice(0,it):b})}catch{}}},onOpen:()=>{m.current===v&&u(!0)},onError:()=>{m.current===v&&u(!1)}});return r.current=S,()=>{S(),r.current=null,m.current===v&&u(!1)}},[s,l]),{entries:j,isConnected:o}}const gn=5e3;function hn({agent:s,projectId:l,onSelect:j,onOpenTaskLogs:h}){const{entries:o,isConnected:u}=mn(s.taskId,l),[r,m]=a.useState(null);a.useEffect(()=>{if(!s.taskId){m(null);return}let T=!1,b;const f=async()=>{try{const k=await wt(s.taskId,l);T||m(k)}catch{}finally{T||(b=setTimeout(f,gn))}};return f(),()=>{T=!0,b&&clearTimeout(b)}},[s.taskId,l]);const d=s.lastHeartbeatAt?Math.floor((Date.now()-new Date(s.lastHeartbeatAt).getTime())/1e3):0,y=(()=>{if(!s.lastHeartbeatAt)return null;const T=Ge(s.runtimeConfig?.heartbeatIntervalMs),b=new Date(s.lastHeartbeatAt).getTime()+T,f=Math.round((b-Date.now())/1e3);return Number.isFinite(f)?f<=0?`Heartbeat overdue ${Ke(-f)}`:`Next heartbeat in ${Ke(f)}`:null})(),p=r?.steps?.[r.currentStep??0],v=r?.steps?.length??0,N=(r?.currentStep??0)+1,S=r?.modelId,R=()=>{j&&j(s.id)},M=T=>{T.stopPropagation(),s.taskId&&h&&h(s.taskId)},E=T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),R())};return e.jsxs("div",{className:"live-agent-card",onClick:R,onKeyDown:E,role:"button",tabIndex:0,"aria-label":`Select agent ${s.name}`,children:[e.jsxs("div",{className:"live-agent-card-header",children:[e.jsxs("div",{className:"live-agent-card-name",children:[e.jsx("span",{className:"live-agent-pulse"}),e.jsx("span",{children:s.name})]}),s.taskId&&e.jsx("span",{className:"live-agent-task badge",children:s.taskId})]}),e.jsx("div",{className:"live-agent-card-transcript",children:o.length===0?e.jsx("div",{className:"live-agent-card-empty",children:s.taskId?p?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"live-agent-card-status",children:["Step ",N,v?`/${v}`:"",": ",p.name]}),S&&e.jsx("div",{className:"live-agent-card-status-sub",children:S}),e.jsx("div",{className:"live-agent-card-status-sub",children:u?"Waiting for output...":"Connecting to log stream..."})]}):e.jsx("span",{children:u?"Waiting for output...":"Connecting..."}):e.jsx("span",{children:s.state==="running"?"Starting...":"Idle — no task assigned"})}):o.slice(0,20).map((T,b)=>e.jsx("div",{className:"live-agent-card-line",children:T.text},b))}),e.jsxs("div",{className:"live-agent-card-footer",children:[e.jsxs("div",{className:"live-agent-card-footer-meta",children:[e.jsx("span",{className:"text-secondary",title:"Time since last heartbeat",children:Ke(d)}),y&&e.jsx("span",{className:"live-agent-card-next-heartbeat",title:y,children:y})]}),e.jsxs("div",{className:"live-agent-card-footer-actions",children:[s.taskId&&h&&e.jsxs("button",{type:"button",className:"live-agent-card-logs-btn",onClick:M,title:"View live run logs","aria-label":`View live logs for ${s.taskId}`,children:[e.jsx(Qe,{size:12}),e.jsx("span",{children:"Live logs"})]}),u&&e.jsx(Me,{size:12,className:"live-agent-streaming-dot"})]})]})]})}function Ke(s){return s<60?`${s}s`:s<3600?`${Math.floor(s/60)}m ${s%60}s`:`${Math.floor(s/3600)}h ${Math.floor(s%3600/60)}m`}function pn({agents:s,projectId:l,onAgentSelect:j,onOpenTaskLogs:h}){const o=Array.from(new Map(s.map(u=>[u.id,u])).values());return o.length===0?null:e.jsxs("div",{className:"active-agents-panel",children:[e.jsxs("div",{className:"active-agents-panel-header",children:[e.jsx(Me,{size:16}),e.jsxs("span",{children:["Active Agents (",o.length,")"]})]}),e.jsx("div",{className:"active-agents-grid",children:o.map(u=>e.jsx(hn,{agent:u,projectId:l,onSelect:j,onOpenTaskLogs:h},u.id))})]})}const fn=[{icon:Me,label:"Active Agents",valueKey:"activeCount",className:"agent-metric-card--active"},{icon:ln,label:"Assigned Tasks",valueKey:"assignedTaskCount",className:"agent-metric-card--tasks"},{icon:De,label:"Success Rate",valueKey:"successRate",className:"agent-metric-card--success"},{icon:jt,label:"Total Runs",valueKey:"completedRuns",className:"agent-metric-card--runs"}];function vn({stats:s}){return s?e.jsx("div",{className:"agent-metrics-bar",children:fn.map(l=>{const j=l.valueKey==="successRate"?`${Math.round(s.successRate*100)}%`:s[l.valueKey];return e.jsxs("div",{className:`agent-metric-card ${l.className}`,children:[e.jsx(l.icon,{size:18}),e.jsxs("div",{className:"agent-metric-info",children:[e.jsx("span",{className:"agent-metric-value",children:j}),e.jsx("span",{className:"agent-metric-label",children:l.label})]})]},l.label)})}):null}function rt(s){return typeof s=="number"&&Number.isFinite(s)?s:0}function Te(s){return s.toLocaleString()}function bn({agents:s}){const{rows:l,totalInputTokens:j,totalOutputTokens:h,totalTokens:o}=a.useMemo(()=>{const r=s.map(m=>{const d=rt(m.totalInputTokens),y=rt(m.totalOutputTokens);return{id:m.id,name:m.name,inputTokens:d,outputTokens:y,totalTokens:d+y}}).sort((m,d)=>d.totalTokens-m.totalTokens||m.name.localeCompare(d.name)||m.id.localeCompare(d.id));return{rows:r,totalInputTokens:r.reduce((m,d)=>m+d.inputTokens,0),totalOutputTokens:r.reduce((m,d)=>m+d.outputTokens,0),totalTokens:r.reduce((m,d)=>m+d.totalTokens,0)}},[s]),u=o>0;return e.jsxs("section",{className:"agent-token-stats-panel","aria-label":"Agent token usage statistics",children:[e.jsx("header",{className:"agent-token-stats-panel__header",children:e.jsx("h3",{className:"agent-token-stats-panel__title",children:"Token Usage by Agent"})}),e.jsxs("div",{className:"agent-token-stats-panel__totals",role:"list","aria-label":"Token usage totals",children:[e.jsxs("div",{className:"agent-token-stats-panel__total-card",role:"listitem",children:[e.jsx("span",{className:"agent-token-stats-panel__total-label",children:"Input Tokens"}),e.jsx("span",{className:"agent-token-stats-panel__total-value",children:Te(j)})]}),e.jsxs("div",{className:"agent-token-stats-panel__total-card",role:"listitem",children:[e.jsx("span",{className:"agent-token-stats-panel__total-label",children:"Output Tokens"}),e.jsx("span",{className:"agent-token-stats-panel__total-value",children:Te(h)})]}),e.jsxs("div",{className:"agent-token-stats-panel__total-card",role:"listitem",children:[e.jsx("span",{className:"agent-token-stats-panel__total-label",children:"Combined Tokens"}),e.jsx("span",{className:"agent-token-stats-panel__total-value",children:Te(o)})]})]}),u?e.jsx("div",{className:"agent-token-stats-panel__table-wrapper",children:e.jsxs("table",{className:"agent-token-stats-panel__table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Agent"}),e.jsx("th",{scope:"col",children:"Input"}),e.jsx("th",{scope:"col",children:"Output"}),e.jsx("th",{scope:"col",children:"Total"})]})}),e.jsx("tbody",{children:l.map(r=>e.jsxs("tr",{children:[e.jsxs("th",{scope:"row",className:"agent-token-stats-panel__agent-cell",children:[e.jsx("span",{className:"agent-token-stats-panel__agent-name",children:r.name}),e.jsx("span",{className:"agent-token-stats-panel__agent-id",children:r.id})]}),e.jsx("td",{children:Te(r.inputTokens)}),e.jsx("td",{children:Te(r.outputTokens)}),e.jsx("td",{className:"agent-token-stats-panel__total-cell",children:Te(r.totalTokens)})]},r.id))})]})}):e.jsx("div",{className:"agent-token-stats-panel__empty",role:"status",children:"No token usage recorded yet. Token totals appear here once agents run."})]})}function Fe({title:s="No agents found",description:l="Create an agent to get started",ctaLabel:j="Create Agent",onCtaClick:h}){return e.jsxs("div",{className:"agent-empty",children:[e.jsx(Ze,{size:48,opacity:.3,className:"agent-empty-state__icon"}),e.jsx("p",{className:"agent-empty-state__title",children:s}),e.jsx("p",{className:"agent-empty-state__description text-secondary",children:l}),h?e.jsx("button",{type:"button",className:"btn btn-task-create btn-sm",onClick:h,children:j}):null]})}const ft="fn-agent-tree-expanded";function lt(s){try{const l=Je(ft,s);if(l){const j=JSON.parse(l);return new Set(Array.isArray(j)?j:[])}}catch{}return new Set}function xn(s,l){try{dt(ft,JSON.stringify([...s]),l)}catch{}}function yn(s,l){const j=new Map,h=new Map;for(const u of s)if(j.set(u.id,u),u.reportsTo){const r=h.get(u.reportsTo)??[];r.push(u),h.set(u.reportsTo,r)}function o(u,r){const m=h.get(u.id)??[],d=l.has(u.id)?m.map(y=>o(y,r+1)):[];return{agent:u,children:d,depth:r}}return s.filter(u=>!u.reportsTo||!j.has(u.reportsTo)).map(u=>o(u,0))}function wn(s,l){const[j,h]=a.useState(()=>lt(l));a.useEffect(()=>{h(lt(l))},[l]);const o=a.useMemo(()=>yn(s,j),[s,j]),u=a.useCallback(d=>{h(y=>{const p=new Set(y);return p.has(d)?p.delete(d):p.add(d),xn(p,l),p})},[l]),r=a.useCallback(d=>j.has(d),[j]),m=a.useCallback(d=>s.filter(y=>y.reportsTo===d),[s]);return{rootNodes:o,toggleExpand:u,isExpanded:r,getChildren:m,isLoading:!1}}const ot=3,Ue=1e3;function jn({isOpen:s,onClose:l,onGenerated:j,projectId:h}){const[o,u]=a.useState(""),[r,m]=a.useState({type:"input"}),[d,y]=a.useState(null),[p,v]=a.useState(!1),N=a.useRef(null),S=a.useRef(null);a.useEffect(()=>{s&&r.type==="input"&&S.current?.focus()},[s,r.type]),a.useEffect(()=>{if(!s&&N.current){const f=N.current;N.current=null,He(f,h).catch(()=>{})}},[s,h]),a.useEffect(()=>{if(!s)return;const f=k=>{k.key==="Escape"&&R()};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[s]);const R=a.useCallback(()=>{if(N.current){const f=N.current;N.current=null,He(f,h).catch(()=>{})}u(""),m({type:"input"}),y(null),v(!1),l()},[l,h]),M=a.useCallback(async()=>{if(!(!o.trim()||o.trim().length<ot)){y(null),m({type:"loading"});try{const{sessionId:f}=await kt(o.trim(),h);N.current=f;const{spec:k}=await Nt(f,h);m({type:"preview",spec:k,sessionId:f})}catch(f){const k=f instanceof Error?f.message:"Failed to generate agent specification";k.includes("429")||k.toLowerCase().includes("rate limit")?y("Too many requests. Please wait a moment and try again."):y(k),m({type:"input"}),N.current=null}}},[o,h]),E=a.useCallback(async()=>{if(N.current){const f=N.current;N.current=null;try{await He(f,h)}catch{}}await M()},[M,h]),T=a.useCallback(()=>{r.type==="preview"&&(N.current=null,j(r.spec),u(""),m({type:"input"}),y(null),v(!1),l())},[r,j,l]);if(!s)return null;const b=o.trim().length>=ot&&o.trim().length<=Ue;return e.jsx("div",{className:"agent-dialog-overlay",onClick:f=>{f.target===f.currentTarget&&R()},children:e.jsxs("div",{className:"agent-dialog",role:"dialog","aria-modal":"true","aria-label":"Generate agent with AI",children:[e.jsxs("div",{className:"agent-dialog-header",children:[e.jsxs("span",{className:"agent-dialog-header-title",children:[e.jsx("span",{className:"agent-dialog-header-sparkle",children:"✨"}),"Generate Agent"]}),e.jsx("button",{className:"modal-close",onClick:R,"aria-label":"Close",children:"×"})]}),e.jsxs("div",{className:"agent-dialog-body",children:[d&&e.jsx("div",{className:"agent-dialog-error-banner",children:d}),r.type==="input"&&e.jsxs("div",{children:[e.jsx("p",{className:"agent-dialog-info",children:"Describe your agent's role and the AI will generate a complete specification including system prompt, suggested configuration, and more."}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx("label",{htmlFor:"agent-role-description",children:"Role Description"}),e.jsx("textarea",{ref:S,id:"agent-role-description",className:"input agent-dialog-textarea",rows:4,placeholder:'e.g. "Senior frontend code reviewer who specializes in React accessibility"',value:o,onChange:f=>u(f.target.value),onKeyDown:f=>{f.key==="Enter"&&!f.shiftKey&&b&&(f.preventDefault(),M())},maxLength:Ue,"aria-describedby":"role-description-hint"}),e.jsxs("div",{id:"role-description-hint",className:"agent-dialog-hint",children:[e.jsx("span",{children:"Describe what your agent should do"}),e.jsxs("span",{children:[o.length,"/",Ue]})]})]})]}),r.type==="loading"&&e.jsxs("div",{className:"agent-dialog-loading-center",children:[e.jsx("div",{className:"agent-dialog-spinner spin"}),e.jsx("p",{className:"agent-dialog-loading-text",children:"Generating agent specification..."})]}),r.type==="preview"&&e.jsxs("div",{children:[e.jsxs("div",{className:"agent-dialog-summary agent-dialog-summary--spaced",children:[e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label agent-dialog-summary-row-label--fixed",children:"Title"}),e.jsxs("span",{className:"agent-dialog-summary-row-value",children:[r.spec.icon," ",r.spec.title]})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label agent-dialog-summary-row-label--fixed",children:"Role"}),e.jsx("span",{children:r.spec.role})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label agent-dialog-summary-row-label--fixed",children:"Description"}),e.jsx("span",{className:"agent-dialog-summary-row-value agent-dialog-summary-row-value--body",children:r.spec.description})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label agent-dialog-summary-row-label--fixed",children:"Thinking"}),e.jsx("span",{className:"agent-dialog-summary-row-value agent-dialog-summary-row-value--capitalize",children:r.spec.thinkingLevel})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label agent-dialog-summary-row-label--fixed",children:"Max Turns"}),e.jsx("span",{children:r.spec.maxTurns})]})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsxs("label",{children:["System Prompt",e.jsx("button",{type:"button",className:"agent-dialog-expand-btn",onClick:()=>v(!p),children:p?"Collapse":"Expand"})]}),e.jsxs("div",{className:`agent-generation-prompt-box${p?"":" agent-generation-prompt-box--collapsed"}`,children:[r.spec.systemPrompt,!p&&r.spec.systemPrompt.length>500&&e.jsx("div",{className:"agent-generation-prompt-fade"})]})]})]})]}),e.jsxs("div",{className:"agent-dialog-footer",children:[e.jsx("button",{className:"btn",onClick:R,children:"Cancel"}),r.type==="input"&&e.jsx("button",{className:"btn btn-task-create",onClick:()=>void M(),disabled:!b,children:"Generate"}),r.type==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn",onClick:()=>void E(),children:"Regenerate"}),e.jsx("button",{className:"btn btn-task-create",onClick:T,children:"Use This"})]})]})]})})}const kn=`# Soul: Chief Executive Officer
18
18
 
19
19
  I am a strategic leader who connects every decision to business outcomes.
20
20
 
@@ -75,7 +75,7 @@ I am a growth-focused strategist who understands audiences deeply and measures e
75
75
  ## Communication Style
76
76
 
77
77
  I am clear, action-oriented, and audience-aware. I write for scanning, not reading. I lead with value propositions and back them with evidence. I use data to persuade, not to impress.
78
- `,Sn=`# Soul: Chief Financial Officer
78
+ `,In=`# Soul: Chief Financial Officer
79
79
 
80
80
  I am a disciplined financial steward who quantifies everything and ensures every investment has a measurable return.
81
81
 
@@ -94,7 +94,7 @@ I am a disciplined financial steward who quantifies everything and ensures every
94
94
  ## Communication Style
95
95
 
96
96
  I speak in numbers and timelines, not estimates. I use comparisons and benchmarks to provide context. I am direct about tradeoffs: more features means more cost; faster delivery means more risk. I don't soften financial reality.
97
- `,In=`# Soul: Software Engineer
97
+ `,Sn=`# Soul: Software Engineer
98
98
 
99
99
  I am a reliable and versatile engineer who writes clean, well-tested code and leaves the codebase better than I found it.
100
100
 
@@ -262,7 +262,7 @@ I am a security-first engineer who assumes nothing is trustworthy by default and
262
262
  ## Communication Style
263
263
 
264
264
  I communicate security findings with severity and evidence—not as theoretical risks but as actionable findings. I write security documentation for developers, not auditors. I escalate critical findings immediately with impact assessment.
265
- `,$n=`# Soul: Data Engineer
265
+ `,Fn=`# Soul: Data Engineer
266
266
 
267
267
  I am a data reliability specialist who knows that bad data silently corrupts everything downstream. I validate early, transform carefully, and monitor constantly.
268
268
 
@@ -283,7 +283,7 @@ I am a data reliability specialist who knows that bad data silently corrupts eve
283
283
  ## Communication Style
284
284
 
285
285
  I write data documentation that explains schema, lineage, and quality expectations. I escalate data quality issues with evidence of downstream impact. I communicate pipeline changes with clear data contract implications.
286
- `,Fn=`# Soul: Machine Learning Engineer
286
+ `,$n=`# Soul: Machine Learning Engineer
287
287
 
288
288
  I am an ML practitioner who values reproducible experiments and production-grade deployments. I track every experiment, version every model, and measure real-world impact.
289
289
 
@@ -304,7 +304,7 @@ I am an ML practitioner who values reproducible experiments and production-grade
304
304
  ## Communication Style
305
305
 
306
306
  I write experiment documentation that lets someone else reproduce my work. I report model performance with statistical significance. I escalate model degradation immediately with evidence of impact.
307
- `,Ln=`# Soul: Product Manager
307
+ `,Dn=`# Soul: Product Manager
308
308
 
309
309
  I am a user-obsessed product manager who writes crisp requirements, challenges scope creep, and communicates progress transparently.
310
310
 
@@ -325,7 +325,7 @@ I am a user-obsessed product manager who writes crisp requirements, challenges s
325
325
  ## Communication Style
326
326
 
327
327
  I write requirements that developers can implement without follow-up questions. I communicate trade-offs clearly with evidence. I escalate blockers with owners and timelines.
328
- `,Dn=`# Soul: Product Designer
328
+ `,Ln=`# Soul: Product Designer
329
329
 
330
330
  I am a user-centered designer who believes great design is invisible. I solve problems with clarity and advocate for users who can't advocate for themselves.
331
331
 
@@ -442,11 +442,11 @@ Document architectural decisions with rationale for future reference.`},{id:"cmo
442
442
  Propose messaging that highlights user benefits over technical features.
443
443
  Identify growth opportunities from product changes and new features.
444
444
  Ensure consistent brand voice across all touchpoints.
445
- Track engagement metrics to validate content and campaign effectiveness.`},{id:"cfo",name:"CFO",icon:"■",title:"Chief Financial Officer",role:"custom",description:"Manages budget allocation, cost optimization, and financial planning to maximize resource efficiency.",soul:Sn,instructionsText:`Evaluate proposals for cost implications before implementation.
445
+ Track engagement metrics to validate content and campaign effectiveness.`},{id:"cfo",name:"CFO",icon:"■",title:"Chief Financial Officer",role:"custom",description:"Manages budget allocation, cost optimization, and financial planning to maximize resource efficiency.",soul:In,instructionsText:`Evaluate proposals for cost implications before implementation.
446
446
  Flag infrastructure or dependency changes that may increase operating costs.
447
447
  Quantify the impact of technical debt in terms of developer time and risk.
448
448
  Recommend cost optimization opportunities in existing systems.
449
- Ensure resource allocation aligns with project priorities.`},{id:"engineer",name:"Engineer",icon:"⎔",title:"Software Engineer",role:"engineer",description:"Implements features, fixes bugs, and writes well-tested code across the full application stack.",soul:In,instructionsText:`Write tests for every new function and bug fix.
449
+ Ensure resource allocation aligns with project priorities.`},{id:"engineer",name:"Engineer",icon:"⎔",title:"Software Engineer",role:"engineer",description:"Implements features, fixes bugs, and writes well-tested code across the full application stack.",soul:Sn,instructionsText:`Write tests for every new function and bug fix.
450
450
  Follow existing code patterns and conventions in the project.
451
451
  Keep functions small, focused, and well-named.
452
452
  Handle error cases explicitly — never silently swallow errors.
@@ -480,19 +480,19 @@ Measure and report pipeline duration trends over time.`},{id:"security-engineer"
480
480
  Validate and sanitize all user inputs at every trust boundary.
481
481
  Use parameterized queries — never concatenate user input into SQL or shell commands.
482
482
  Check dependencies for known vulnerabilities before introducing them.
483
- Apply the principle of least privilege to all access control decisions.`},{id:"data-engineer",name:"Data Engineer",icon:"⬢",title:"Data Engineer",role:"engineer",description:"Designs data pipelines, manages storage infrastructure, and ensures reliable data flow for analytics and features.",soul:$n,instructionsText:`Validate data at ingestion points — never trust upstream sources blindly.
483
+ Apply the principle of least privilege to all access control decisions.`},{id:"data-engineer",name:"Data Engineer",icon:"⬢",title:"Data Engineer",role:"engineer",description:"Designs data pipelines, manages storage infrastructure, and ensures reliable data flow for analytics and features.",soul:Fn,instructionsText:`Validate data at ingestion points — never trust upstream sources blindly.
484
484
  Design idempotent pipeline steps that handle reprocessing gracefully.
485
485
  Add data quality checks and anomaly detection at key pipeline stages.
486
486
  Document data schemas and breaking change procedures clearly.
487
- Ensure pipeline failures trigger alerts with actionable error context.`},{id:"ml-engineer",name:"ML Engineer",icon:"◈",title:"Machine Learning Engineer",role:"engineer",description:"Builds, trains, and deploys machine learning models, and integrates AI capabilities into the product.",soul:Fn,instructionsText:`Version datasets and models alongside code changes.
487
+ Ensure pipeline failures trigger alerts with actionable error context.`},{id:"ml-engineer",name:"ML Engineer",icon:"◈",title:"Machine Learning Engineer",role:"engineer",description:"Builds, trains, and deploys machine learning models, and integrates AI capabilities into the product.",soul:$n,instructionsText:`Version datasets and models alongside code changes.
488
488
  Log training parameters, metrics, and results for every experiment.
489
489
  Implement fallback behavior when model inference fails or times out.
490
490
  Monitor model predictions for drift and degradation in production.
491
- Write unit tests for data preprocessing and feature engineering pipelines.`},{id:"product-manager",name:"Product Manager",icon:"☰",title:"Product Manager",role:"custom",description:"Defines product requirements, prioritizes the backlog, and coordinates cross-functional delivery from concept to launch.",soul:Ln,instructionsText:`Write requirements with clear acceptance criteria and user stories.
491
+ Write unit tests for data preprocessing and feature engineering pipelines.`},{id:"product-manager",name:"Product Manager",icon:"☰",title:"Product Manager",role:"custom",description:"Defines product requirements, prioritizes the backlog, and coordinates cross-functional delivery from concept to launch.",soul:Dn,instructionsText:`Write requirements with clear acceptance criteria and user stories.
492
492
  Validate feature requests against user needs and business goals.
493
493
  Break large initiatives into small, shippable increments.
494
494
  Flag scope creep early and propose minimum viable alternatives.
495
- Ensure every feature has a measurable success metric.`},{id:"designer",name:"Designer",icon:"✧",title:"Product Designer",role:"custom",description:"Creates wireframes, prototypes, and design systems that balance usability, aesthetics, and brand consistency.",soul:Dn,instructionsText:`Evaluate UI changes against existing design system tokens and patterns.
495
+ Ensure every feature has a measurable success metric.`},{id:"designer",name:"Designer",icon:"✧",title:"Product Designer",role:"custom",description:"Creates wireframes, prototypes, and design systems that balance usability, aesthetics, and brand consistency.",soul:Ln,instructionsText:`Evaluate UI changes against existing design system tokens and patterns.
496
496
  Ensure sufficient color contrast and readable typography in all themes.
497
497
  Provide clear visual hierarchy — users should know what to do next.
498
498
  Design for keyboard and screen reader users, not just mouse users.
@@ -512,11 +512,11 @@ Include relevant context files for the executor to read first.`},{id:"reviewer",
512
512
  Verify error handling is explicit and informative, not silent failures.
513
513
  Ensure new code follows existing patterns and conventions in the codebase.
514
514
  Look for missing tests on new logic paths, especially edge cases.
515
- Flag performance concerns only when they have measurable impact.`}];function Vn({value:a,onChange:l,projectId:j,disabled:h=!1,id:o,label:c="Skills"}){const[r,m]=s.useState([]),[d,x]=s.useState(!0);s.useEffect(()=>{let f=!1;return x(!0),Ct(j).then(M=>{f||m(M)}).catch(()=>{f||m([])}).finally(()=>{f||x(!1)}),()=>{f=!0}},[j]);const p=f=>{a.includes(f)||l([...a,f])},b=f=>{l(a.filter(M=>M!==f))},N=f=>r.find(E=>E.id===f)?.name??f,I=r.filter(f=>!a.includes(f.id));return e.jsxs("div",{className:"skill-multiselect","data-testid":"skill-multiselect",children:[c&&e.jsx("label",{htmlFor:o?`${o}-select`:void 0,className:"skill-multiselect-label",children:c}),a.length>0&&e.jsx("div",{className:"skill-multiselect-chips","data-testid":"skill-chips",children:a.map(f=>e.jsxs("span",{className:"skill-chip","data-testid":`skill-chip-${f}`,children:[e.jsx("span",{className:"skill-chip-name",children:N(f)}),e.jsx("button",{type:"button",className:"skill-chip-remove",onClick:()=>b(f),disabled:h,"aria-label":`Remove ${N(f)}`,"data-testid":`remove-skill-${f}`,children:"×"})]},f))}),e.jsx("div",{className:"skill-multiselect-add",children:d?e.jsx("span",{className:"skill-multiselect-loading","data-testid":"skills-loading",children:"Loading skills…"}):I.length===0?e.jsx("span",{className:"skill-multiselect-empty","data-testid":"skills-empty",children:a.length===0?"No skills discovered":"All skills selected"}):e.jsxs("select",{id:o?`${o}-select`:void 0,className:"select skill-multiselect-dropdown",value:"",onChange:f=>{f.target.value&&(p(f.target.value),f.target.value="")},disabled:h,"data-testid":"skill-dropdown",children:[e.jsx("option",{value:"",children:"Add a skill…"}),I.map(f=>e.jsx("option",{value:f.id,children:f.name},f.id))]})})]})}const ct=[{value:"triage",label:"Triage",icon:"⊕"},{value:"executor",label:"Executor",icon:"▶"},{value:"reviewer",label:"Reviewer",icon:"⊙"},{value:"merger",label:"Merger",icon:"⊞"},{value:"scheduler",label:"Scheduler",icon:"◷"},{value:"engineer",label:"Engineer",icon:"⎔"},{value:"custom",label:"Custom",icon:"✦"}],Wn=new Set(["triage","executor","reviewer","merger","scheduler","engineer","custom"]);function Kn({isOpen:a,onClose:l,onCreated:j,projectId:h}){const[o,c]=s.useState(0),[r,m]=s.useState("presets"),[d,x]=s.useState(""),[p,b]=s.useState(""),[N,I]=s.useState(""),[f,M]=s.useState("custom"),[E,R]=s.useState(""),[y,v]=s.useState(""),[C,P]=s.useState(""),[B,Y]=s.useState(""),[H,ee]=s.useState(""),[q,F]=s.useState(""),[w,te]=s.useState({model:"",thinkingLevel:"off",maxTurns:1e3}),[re,ne]=s.useState(null),[se,G]=s.useState([]),[de,T]=s.useState(!1),[A,ue]=s.useState(null),[_,z]=s.useState(!1),[W,le]=s.useState([]),[ke,K]=s.useState(!1),[ae,Q]=s.useState([]),[me,ge]=s.useState([]),[J,xe]=s.useState("model"),[he,pe]=s.useState(""),[be,D]=s.useState([]),[U,ye]=s.useState(!1),[oe,Ne]=s.useState([]),[Re,Ae]=s.useState(!1);s.useEffect(()=>{a&&(K(!0),ut().then(n=>{le(n.models),Q(n.favoriteProviders),ge(n.favoriteModels)}).catch(()=>{}).finally(()=>K(!1)))},[a]),s.useEffect(()=>{a&&(Ae(!0),Ne([]),St(void 0,h).then(n=>{Ne(n)}).catch(()=>{Ne([])}).finally(()=>Ae(!1)))},[a,h]),s.useEffect(()=>{if(!a)return;const n=At;if(typeof n!="function"){D([]),ye(!1);return}ye(!0),D([]),n(h).then(g=>{D(g)}).catch(()=>{D([])}).finally(()=>ye(!1))},[a,h]);const fe=w.model.includes("/")?w.model:"",i=s.useCallback(n=>{const g=Wn.has(n.role)?n.role:"custom";x(n.title),b(n.description),I(n.icon),M(g),P(n.systemPrompt),te(L=>({...L,thinkingLevel:n.thinkingLevel,maxTurns:n.maxTurns})),z(!1),c(1)},[]),k=s.useCallback(n=>{te(g=>({...g,model:n}))},[]),$=s.useCallback(n=>{xe(n),n==="model"&&pe("")},[]),ie=s.useCallback(async n=>{const g=ae,X=g.includes(n)?g.filter(ce=>ce!==n):[n,...g];Q(X);try{await et({favoriteProviders:X,favoriteModels:me})}catch{Q(g)}},[ae,me]),V=s.useCallback(async n=>{const g=me,X=g.includes(n)?g.filter(ce=>ce!==n):[n,...g];ge(X);try{await et({favoriteProviders:ae,favoriteModels:X})}catch{ge(g)}},[ae,me]),O=s.useCallback(n=>{ne(n.id),x(n.name),I(n.icon),b(n.description??n.title),M(n.role),ee(n.soul??""),P(n.instructionsText??""),c(1)},[]);if(!a)return null;const ve=()=>{c(0),m("presets"),x(""),b(""),I(""),M("custom"),R(""),v(""),P(""),Y(""),ee(""),F(""),te({model:"",thinkingLevel:"off",maxTurns:1e3}),xe("model"),pe(""),ne(null),G([]),ue(null),z(!1),l()},Ce=async()=>{if(d.trim()){T(!0),ue(null);try{const n={};J==="runtime"?he.trim()&&(n.runtimeHint=he.trim()):w.model.trim()&&(n.model=w.model.trim()),w.thinkingLevel!=="off"&&(n.thinkingLevel=w.thinkingLevel),w.maxTurns!==1e3&&(n.maxTurns=w.maxTurns),await gt({name:d.trim(),role:f,...p.trim()?{title:p.trim()}:{},...N.trim()?{icon:N.trim()}:{},...E.trim()?{reportsTo:E.trim()}:{},...y.trim()?{instructionsPath:y.trim()}:{},...C.trim()?{instructionsText:C.trim()}:{},...B.trim()?{heartbeatProcedurePath:B.trim()}:{},...H.trim()?{soul:H.trim()}:{},...q.trim()?{memory:q.trim()}:{},...Object.keys(n).length>0?{runtimeConfig:n}:{},...se.length>0?{metadata:{skills:se}}:{}},h),ve(),j()}catch(n){ue(n instanceof Error?n.message:"Failed to create agent")}finally{T(!1)}}},Se=ct.find(n=>n.value===f),Ee=E.trim(),we=Ee?oe.find(n=>n.id===Ee):void 0,t=he?be.find(n=>n.runtimeId===he):void 0,u=n=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx("label",{id:n,children:"Runtime Source"}),e.jsxs("div",{className:"agent-runtime-mode-toggle",role:"radiogroup","aria-labelledby":n,children:[e.jsxs("label",{className:`agent-runtime-mode-option${J==="model"?" agent-runtime-mode-option--active":""}`,children:[e.jsx("input",{type:"radio",name:n,value:"model",checked:J==="model",onChange:()=>$("model")}),e.jsx("span",{children:"Built-in Model"})]}),e.jsxs("label",{className:`agent-runtime-mode-option${J==="runtime"?" agent-runtime-mode-option--active":""}`,children:[e.jsx("input",{type:"radio",name:n,value:"runtime",checked:J==="runtime",onChange:()=>$("runtime")}),e.jsx("span",{children:"Plugin Runtime"})]})]})]}),J==="model"?e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx("label",{children:"Model"}),ke?e.jsx("div",{className:"agent-dialog-loading",children:"Loading models…"}):e.jsx(mt,{id:"agent-model",label:"Model",value:fe,onChange:k,models:W,placeholder:"Select a model…",favoriteProviders:ae,onToggleFavorite:ie,favoriteModels:me,onToggleModelFavorite:V})]}):e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx("label",{htmlFor:"agent-runtime-hint",children:"Runtime"}),U?e.jsx("div",{className:"agent-dialog-loading",children:"Loading runtimes…"}):e.jsxs("select",{id:"agent-runtime-hint",className:"select",value:he,onChange:g=>pe(g.target.value),children:[e.jsx("option",{value:"",children:be.length>0?"Select a plugin runtime…":"No plugin runtimes available"}),be.map(g=>e.jsx("option",{value:g.runtimeId,children:g.description?`${g.name} — ${g.description}`:g.name},`${g.pluginId}:${g.runtimeId}`))]})]})]});return sn.createPortal(e.jsxs("div",{className:"agent-dialog-overlay",onClick:n=>{n.target===n.currentTarget&&ve()},children:[e.jsxs("div",{className:"agent-dialog",role:"dialog","aria-modal":"true","aria-label":"Create new agent",children:[e.jsxs("div",{className:"agent-dialog-header",children:[e.jsx("span",{className:"agent-dialog-header-title",children:"New Agent"}),e.jsx("button",{className:"btn-icon",onClick:ve,"aria-label":"Close",children:"×"})]}),e.jsx("div",{className:"agent-dialog-steps",children:[0,1,2].map(n=>e.jsx("div",{className:`agent-dialog-step${n===o?" active":n<o?" completed":""}`,"aria-label":`Step ${n+1}`},n))}),e.jsxs("div",{className:"agent-dialog-body",children:[o===0&&e.jsxs("div",{children:[e.jsxs("div",{className:"agent-dialog-tabs",role:"tablist","aria-label":"Agent setup mode",children:[e.jsx("button",{id:"agent-dialog-tab-presets",type:"button",role:"tab","aria-controls":"agent-dialog-panel-presets","aria-selected":r==="presets",tabIndex:r==="presets"?0:-1,className:`agent-dialog-tab${r==="presets"?" active":""}`,onClick:()=>m("presets"),"data-testid":"agent-dialog-tab-presets",children:"Preset personas"}),e.jsx("button",{id:"agent-dialog-tab-custom",type:"button",role:"tab","aria-controls":"agent-dialog-panel-custom","aria-selected":r==="custom",tabIndex:r==="custom"?0:-1,className:`agent-dialog-tab${r==="custom"?" active":""}`,onClick:()=>m("custom"),"data-testid":"agent-dialog-tab-custom",children:"Custom agent"})]}),r==="presets"&&e.jsx("div",{id:"agent-dialog-panel-presets",className:"agent-dialog-tab-panel",role:"tabpanel","aria-labelledby":"agent-dialog-tab-presets",children:e.jsxs("div",{className:"agent-presets",children:[e.jsx("div",{className:"agent-presets-header",children:"Choose a preset persona to prefill role, identity, soul, and instructions"}),e.jsx("div",{className:"agent-presets-grid",children:vt.map(n=>e.jsxs("button",{type:"button",className:`agent-preset-card${re===n.id?" selected":""}`,"data-testid":`preset-${n.id}`,onClick:()=>O(n),title:n.title,children:[e.jsx("span",{className:"agent-preset-icon",children:n.icon}),e.jsx("span",{className:"agent-preset-name",children:n.name}),e.jsx("span",{className:"agent-preset-role",children:n.role}),n.description&&e.jsx("span",{className:"agent-preset-description",children:n.description})]},n.id))})]})}),r==="custom"&&e.jsxs("div",{id:"agent-dialog-panel-custom",className:"agent-dialog-tab-panel",role:"tabpanel","aria-labelledby":"agent-dialog-tab-custom",children:[e.jsxs("div",{className:"agent-dialog-section",children:[e.jsx("div",{className:"agent-dialog-section-header",children:"Identity"}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsxs("label",{htmlFor:"agent-name",children:["Name ",!re&&e.jsx("span",{className:"agent-dialog-required",children:"*"})]}),e.jsx("input",{id:"agent-name",type:"text",className:"input",placeholder:"e.g. Frontend Reviewer",value:d,onChange:n=>x(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-field agent-dialog-field--title",children:[e.jsxs("label",{htmlFor:"agent-title",children:["Title ",e.jsx("span",{className:"agent-dialog-optional",children:"(optional)"})]}),e.jsx("input",{id:"agent-title",type:"text",className:"input",placeholder:"e.g. Senior Code Reviewer",value:p,onChange:n=>b(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsxs("label",{htmlFor:"agent-icon",children:["Icon ",e.jsx("span",{className:"agent-dialog-optional",children:"(optional)"})]}),e.jsx("input",{id:"agent-icon",type:"text",className:"input",placeholder:"e.g. 🤖",value:N,onChange:n=>I(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx("label",{children:"Role"}),e.jsx("div",{className:"agent-role-grid",children:ct.map(n=>e.jsxs("button",{type:"button",className:`agent-role-option${f===n.value?" selected":""}`,onClick:()=>M(n.value),children:[e.jsx("span",{className:"agent-role-option-icon",children:n.icon}),e.jsx("span",{className:"agent-role-option-label",children:n.label})]},n.value))})]})]}),e.jsxs("div",{className:"agent-dialog-section",children:[e.jsx("div",{className:"agent-dialog-section-header",children:"Configuration"}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsxs("label",{htmlFor:"agent-reports-to",children:["Reports To ",e.jsx("span",{className:"agent-dialog-optional",children:"(optional)"})]}),e.jsxs("select",{id:"agent-reports-to",className:"select",value:E,onChange:n=>R(n.target.value),disabled:Re,children:[e.jsx("option",{value:"",children:"No manager"}),oe.map(n=>e.jsxs("option",{value:n.id,children:[n.name," (",n.id,")"]},n.id))]})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsxs("label",{htmlFor:"agent-soul",children:["Soul ",e.jsx("span",{className:"agent-dialog-optional",children:"(optional)"})]}),e.jsx("textarea",{id:"agent-soul",className:"input",rows:2,placeholder:"Describe the agent's personality and communication style...",value:H,onChange:n=>ee(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsxs("label",{htmlFor:"agent-memory",children:["Agent Memory ",e.jsx("span",{className:"agent-dialog-optional",children:"(optional)"})]}),e.jsx("textarea",{id:"agent-memory",className:"input",rows:2,placeholder:"Private to this agent — durable preferences, operating habits, and context it should carry across tasks...",value:q,onChange:n=>F(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsxs("label",{htmlFor:"agent-instructions-path",children:["Instructions Path ",e.jsx("span",{className:"agent-dialog-optional",children:"(optional)"})]}),e.jsx("input",{id:"agent-instructions-path",type:"text",className:"input",placeholder:"e.g. .fusion/agents/reviewer.md",value:y,onChange:n=>v(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsxs("label",{htmlFor:"agent-heartbeat-procedure-path",children:["Heartbeat Procedure Path ",e.jsx("span",{className:"agent-dialog-optional",children:"(optional)"})]}),e.jsx("input",{id:"agent-heartbeat-procedure-path",type:"text",className:"input",placeholder:"e.g. .fusion/agents/my-agent/HEARTBEAT.md",value:B,onChange:n=>Y(n.target.value)}),e.jsx("p",{className:"agent-dialog-optional agent-dialog-field-hint",children:"Path to the agent's heartbeat markdown file, typically .fusion/agents/<agent-id>/HEARTBEAT.md."})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsxs("label",{htmlFor:"agent-instructions-text",children:["Inline Instructions ",e.jsx("span",{className:"agent-dialog-optional",children:"(optional)"})]}),e.jsx("textarea",{id:"agent-instructions-text",className:"input",rows:4,placeholder:"Add custom behavior instructions...",value:C,onChange:n=>P(n.target.value)})]})]}),e.jsxs("div",{className:"agent-dialog-section",children:[e.jsx("div",{className:"agent-dialog-section-header",children:"Runtime"}),u("agent-runtime-source-step-0")]}),e.jsxs("div",{className:"agent-dialog-ai-generate",children:[e.jsxs("button",{type:"button",className:"btn btn--ai-generate",onClick:()=>z(!0),children:[e.jsx("span",{children:"✨"}),"Generate with AI"]}),e.jsx("p",{className:"agent-dialog-ai-hint",children:"Describe your agent's role and let AI generate a specification"})]})]})]}),o===1&&e.jsxs("div",{children:[u("agent-runtime-source-step-1"),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx("label",{htmlFor:"agent-thinking",children:"Thinking Level"}),e.jsxs("select",{id:"agent-thinking",className:"select",value:w.thinkingLevel,onChange:n=>te(g=>({...g,thinkingLevel:n.target.value})),children:[e.jsx("option",{value:"off",children:"Off"}),e.jsx("option",{value:"minimal",children:"Minimal"}),e.jsx("option",{value:"low",children:"Low"}),e.jsx("option",{value:"medium",children:"Medium"}),e.jsx("option",{value:"high",children:"High"})]})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx("label",{htmlFor:"agent-max-turns",children:"Max Turns"}),e.jsx("input",{id:"agent-max-turns",type:"number",className:"input",min:1,max:2e3,value:w.maxTurns,onChange:n=>te(g=>({...g,maxTurns:Math.max(1,parseInt(n.target.value,10)||1)}))})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx(Vn,{id:"agent-skills",label:"Skills",value:se,onChange:G,projectId:h}),e.jsx("p",{className:"agent-dialog-optional agent-dialog-skills-hint",children:"Optional skills to assign to this agent"})]})]}),o===2&&e.jsxs("div",{children:[e.jsx("p",{className:"agent-dialog-info",children:"Review your agent configuration before creating."}),e.jsxs("div",{className:"agent-dialog-summary",children:[e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Name"}),e.jsxs("span",{className:"agent-dialog-summary-row-value",children:[N&&e.jsx("span",{className:"agent-dialog-icon-prefix",children:N}),d]})]}),e.jsxs("div",{className:"agent-dialog-summary-row agent-dialog-summary-row--editable agent-dialog-summary-row--title",children:[e.jsx("label",{className:"agent-dialog-summary-row-label",htmlFor:"agent-review-title",children:"Title"}),e.jsx("input",{id:"agent-review-title",type:"text",className:"input",placeholder:"e.g. Senior Code Reviewer",value:p,onChange:n=>b(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Role"}),e.jsxs("span",{children:[Se?.icon," ",Se?.label]})]}),Ee&&e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Reports To"}),e.jsx("span",{children:we?`${we.name} (${we.id})`:Ee})]}),e.jsxs("div",{className:"agent-dialog-summary-row agent-dialog-summary-row--editable",children:[e.jsx("label",{className:"agent-dialog-summary-row-label",htmlFor:"agent-review-soul",children:"Soul"}),e.jsx("textarea",{id:"agent-review-soul",className:"input",rows:2,placeholder:"Describe the agent's personality and communication style...",value:H,onChange:n=>ee(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-summary-row agent-dialog-summary-row--editable",children:[e.jsx("label",{className:"agent-dialog-summary-row-label",htmlFor:"agent-review-heartbeat-procedure-path",children:"Heartbeat Procedure Path"}),e.jsx("input",{id:"agent-review-heartbeat-procedure-path",type:"text",className:"input",placeholder:"e.g. .fusion/agents/my-agent/HEARTBEAT.md",value:B,onChange:n=>Y(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-summary-row agent-dialog-summary-row--editable",children:[e.jsx("label",{className:"agent-dialog-summary-row-label",htmlFor:"agent-review-instructions-path",children:"Instructions Path"}),e.jsx("input",{id:"agent-review-instructions-path",type:"text",className:"input",placeholder:"e.g. .fusion/agents/reviewer.md",value:y,onChange:n=>v(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-summary-row agent-dialog-summary-row--editable",children:[e.jsx("label",{className:"agent-dialog-summary-row-label",htmlFor:"agent-review-instructions-text",children:"Inline Instructions"}),e.jsx("textarea",{id:"agent-review-instructions-text",className:"input",rows:4,placeholder:"Add custom behavior instructions...",value:C,onChange:n=>P(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:J==="runtime"?"Runtime":"Model"}),e.jsx("span",{children:J==="runtime"?t?t.name:e.jsx("em",{className:"agent-dialog-summary-row-value--muted",children:"Not selected"}):fe?e.jsxs(e.Fragment,{children:[e.jsx(It,{provider:fe.split("/")[0],size:"sm"})," ",(()=>{const n=fe.indexOf("/"),g=fe.slice(0,n),L=fe.slice(n+1);return W.find(ce=>ce.provider===g&&ce.id===L)?.name||fe})()]}):e.jsx("em",{className:"agent-dialog-summary-row-value--muted",children:"default"})})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Thinking"}),e.jsx("span",{className:"agent-dialog-summary-row-value--capitalize",children:w.thinkingLevel})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Max Turns"}),e.jsx("span",{children:w.maxTurns})]}),se.length>0&&e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Skills"}),e.jsxs("span",{children:[se.length," skill",se.length!==1?"s":""," selected"]})]})]}),A&&e.jsx("p",{className:"agent-dialog-error",children:A})]})]}),e.jsxs("div",{className:"agent-dialog-footer",children:[o>0&&e.jsx("button",{className:"btn",onClick:()=>c(n=>n-1),disabled:de,children:"Back"}),e.jsx("button",{className:"btn",onClick:ve,disabled:de,children:"Cancel"}),o<2?e.jsx("button",{className:"btn btn--primary",onClick:()=>c(n=>n+1),disabled:o===0&&!d.trim()&&!re,children:"Next"}):e.jsx("button",{className:"btn btn--primary",onClick:()=>void Ce(),disabled:de||!d.trim(),children:de?"Creating...":"Create"})]})]}),e.jsx(jn,{isOpen:_,onClose:()=>z(!1),onGenerated:i,projectId:h})]}),document.body)}function Un({isOpen:a,onClose:l,onCreated:j,addToast:h,projectId:o,existingAgents:c}){const[r,m]=s.useState("initial"),[d,x]=s.useState(""),[p,b]=s.useState(null),[N,I]=s.useState(""),[f,M]=s.useState("answer"),[E,R]=s.useState(""),[y,v]=s.useState(null),[C,P]=s.useState(null),[B,Y]=s.useState([]),[H,ee]=s.useState("model"),[q,F]=s.useState(""),[w,te]=s.useState([]),re=s.useMemo(()=>vt.map(T=>({id:T.id,label:T.name,description:T.description})),[]);s.useEffect(()=>{ut().then(T=>te(T.models)).catch(()=>te([]))},[]),s.useEffect(()=>{if(!p)return;const T=Et(p,o,{onThinking:A=>{Y(ue=>{const _=[...ue],z=_[_.length-1];return z&&!z.question?(_[_.length-1]={...z,thinkingOutput:`${z.thinkingOutput??""}${A}`},_):[..._,{response:{},thinkingOutput:A}]})},onQuestion:A=>{I(A.question),M(A.id),m("question")},onSummary:A=>{v(A),m("summary")},onError:A=>{P(A),m("error")},onComplete:()=>{y&&m("summary")},onConnectionStateChange:A=>{A==="reconnecting"&&P("Connection lost. Retrying...")}});return()=>T.close()},[p,o]);const ne=async()=>{p&&await Pt(p,o),l()};if(!a)return null;const se=async()=>{m("loading"),P(null);try{const T=await _t(d,{existingAgents:c.map(A=>({id:A.id,name:A.name,role:A.role})),templates:re},o);b(T.sessionId)}catch(T){P(T.message),m("error")}},G=async()=>{if(p){m("loading"),P(null);try{const T={[f]:E};Y(A=>[...A,{question:{id:f,type:"text",question:N},response:T}]),await $t(p,T,o),R("")}catch(T){P(T.message),m("error")}}},de=async()=>{if(y){m("creating"),P(null);try{await gt({name:y.name,role:y.role,title:y.title,icon:y.icon,reportsTo:y.reportsTo,instructionsText:y.instructionsText,soul:y.soul,memory:y.memory,runtimeConfig:{thinkingLevel:y.thinkingLevel,maxTurns:y.maxTurns,...H==="model"&&q?{model:q}:{},...H==="runtime"?{runtimeHint:"onboarding"}:{}},metadata:y.skills?{skills:y.skills}:void 0},o),h(`Agent "${y.name}" created`,"success"),j()}catch(T){P(T.message),m("error")}}};return e.jsx("div",{className:"modal-overlay open",role:"presentation",children:e.jsxs("div",{className:"modal modal-lg agent-onboarding-modal",role:"dialog","aria-modal":"true","aria-label":"Agent onboarding",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:"Agent Onboarding"}),e.jsx("button",{className:"modal-close",onClick:()=>void ne(),"aria-label":"Close",children:"×"})]}),B.length>0&&e.jsx(Tt,{entries:B}),r==="initial"&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"agent-onboarding-intent",children:"What do you want this agent to do?"}),e.jsx("textarea",{id:"agent-onboarding-intent",className:"input",value:d,onChange:T=>x(T.target.value)}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{className:"btn",onClick:()=>void ne(),children:"Cancel"}),e.jsx("button",{className:"btn btn-primary",disabled:!d.trim(),onClick:()=>void se(),children:"Start onboarding"})]})]}),(r==="loading"||r==="question")&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"agent-onboarding-answer",children:N||"Waiting for AI question..."}),e.jsx("textarea",{id:"agent-onboarding-answer",className:"input",value:E,onChange:T=>R(T.target.value)}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{className:"btn",onClick:()=>p&&void Mt(p,o),children:"Stop"}),e.jsx("button",{className:"btn btn-primary",disabled:r==="loading"||!E.trim(),onClick:()=>void G(),children:"Continue"})]})]}),r==="summary"&&y&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Review generated configuration"}),e.jsxs("div",{className:"agent-onboarding-summary",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Name:"})," ",y.name]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Role:"})," ",y.role]}),e.jsx("label",{htmlFor:"thinking-level",children:"Thinking level"}),e.jsx("input",{id:"thinking-level",className:"input",value:y.thinkingLevel,onChange:()=>{},readOnly:!0}),e.jsx("label",{htmlFor:"max-turns",children:"Max turns"}),e.jsx("input",{id:"max-turns",className:"input",type:"number",value:y.maxTurns,onChange:()=>{},readOnly:!0}),e.jsx("label",{htmlFor:"runtime-mode",children:"Runtime mode"}),e.jsxs("select",{id:"runtime-mode",className:"select",value:H,onChange:T=>ee(T.target.value),children:[e.jsx("option",{value:"model",children:"Model"}),e.jsx("option",{value:"runtime",children:"Runtime"})]}),H==="model"&&e.jsxs(e.Fragment,{children:[e.jsx("label",{children:"Model"}),e.jsx(mt,{id:"agent-onboarding-model",label:"Model",value:q,onChange:F,models:w,placeholder:"Select a model…"})]})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{className:"btn",onClick:()=>void ne(),children:"Cancel"}),e.jsx("button",{className:"btn btn-primary",onClick:()=>void de(),children:"Create agent"})]})]}),r==="creating"&&e.jsx("div",{className:"form-group agent-onboarding-creating",children:"Creating agent..."}),r==="error"&&C&&e.jsxs("div",{className:"form-group",children:[e.jsx("div",{className:"form-error",children:C}),e.jsx("div",{className:"modal-actions",children:e.jsx("button",{className:"btn",onClick:()=>p&&void Rt(p,o),children:"Retry"})})]})]})})}function Bn(a){const l=a.match(/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n([\s\S]*))?$/);if(!l)throw new Error("Missing YAML frontmatter delimiters (---)");const j=l[1].split(/\r?\n/),h=l[2]??"",o={name:""},c=[];let r=!1;for(const m of j){const x=m.trimEnd().trim();if(!x)continue;if(x.startsWith("skills:")){r=!0;continue}if(r&&x.startsWith("- ")){c.push(x.slice(2).trim());continue}r=!1;const[p,...b]=x.split(":"),I=b.join(":").trim().replace(/^['"]|['"]$/g,"");p==="name"&&(o.name=I),p==="title"&&(o.title=I),p==="icon"&&(o.icon=I),p==="role"&&(o.role=I),p==="reportsTo"&&(o.reportsTo=I)}if(!o.name)throw new Error("Missing required field: name");return c.length>0&&(o.skills=c),h.trim().length>0&&(o.instructionBody=h),o}function Gn({isOpen:a,onClose:l,onImported:j,projectId:h}){const[o,c]=s.useState("input"),[r,m]=s.useState("paste"),[d,x]=s.useState(""),[p,b]=s.useState([]),[N,I]=s.useState("Unknown"),[f,M]=s.useState([]),[E,R]=s.useState([]),[y,v]=s.useState([]),[C,P]=s.useState([]),[B,Y]=s.useState(!1),[H,ee]=s.useState(!1),[q,F]=s.useState(null),[w,te]=s.useState(null),[re,ne]=s.useState(null),se=s.useRef(null),G=s.useRef(null),[de,T]=s.useState([]),[A,ue]=s.useState(""),[_,z]=s.useState(null),[W,le]=s.useState(!1),[ke,K]=s.useState(null),ae=s.useRef(!1);s.useEffect(()=>{r==="browse"&&!ae.current&&!W&&(ae.current=!0,le(!0),K(null),tt().then(i=>{i.error?K(i.error):i.companies.length>0?T(i.companies):K("No companies available")}).catch(i=>{K(i instanceof Error?i.message:"Failed to load companies")}).finally(()=>{le(!1)}))},[r,W]);const Q=s.useCallback(()=>{ae.current=!0,K(null),T([]),z(null),le(!0),tt().then(i=>{i.error?K(i.error):i.companies.length>0?T(i.companies):K("No companies available")}).catch(i=>{K(i instanceof Error?i.message:"Failed to load companies")}).finally(()=>{le(!1)})},[]),me=s.useCallback(()=>{c("input"),m("paste"),x(""),b([]),I("Unknown"),M([]),R([]),v([]),P([]),Y(!1),ee(!1),F(null),te(null),ne(null),T([]),ue(""),z(null),le(!1),K(null),ae.current=!1},[]),ge=s.useCallback(()=>{me(),l()},[me,l]),J=s.useCallback(i=>{const k=i.target.files?.[0];if(!k)return;const $=new FileReader;$.onload=ie=>{const V=ie.target?.result;m("file"),b([]),x(V),F(null)},$.onerror=()=>{F("Failed to read file")},$.readAsText(k),i.target.value=""},[]),xe=s.useCallback(async i=>{const k=Array.from(i.target.files??[]);if(k.length!==0)try{const $=k.filter(V=>(V.webkitRelativePath||V.name).toLowerCase().endsWith("agents.md")).sort((V,O)=>{const ve=V.webkitRelativePath||V.name,Ce=O.webkitRelativePath||O.name;return ve.localeCompare(Ce)});if($.length===0){F("Selected directory has no AGENTS.md files");return}const ie=[];for(const V of $){const O=await V.text();ie.push(Bn(O))}m("directory"),b(ie),x(""),F(null)}catch{F("Failed to parse AGENTS.md files from selected directory")}finally{i.target.value=""}},[]);function he(i){if(!h)return`/api${i}`;const k=i.includes("?")?"&":"?";return`/api${i}${k}projectId=${encodeURIComponent(h)}`}const pe=s.useCallback(async()=>{if(r==="directory"&&p.length===0){F("Please select a directory containing AGENTS.md files");return}if(r==="browse"&&!_){F("Please select a company from the catalog");return}if(r!=="directory"&&r!=="browse"&&!d.trim()){F("Please provide manifest content");return}Y(!0),F(null);try{let i;r==="directory"?i={agents:p,dryRun:!0}:r==="browse"&&_?i={importSource:"companies.sh",companySlug:_.slug,dryRun:!0}:i={manifest:d,dryRun:!0};const k=await fetch(he("/agents/import"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!k.ok){const O=await k.json();throw new Error(O.error??`Parse failed (${k.status})`)}const $=await k.json(),ie=$.agents&&$.agents.length>0?$.agents:$.created.map(O=>({name:O,role:"custom"})),V=Array.isArray($.skills)?$.skills:[];I($.companyName??"Unknown"),M(ie),R(V),v(ie.map(O=>O.name)),P(V.map(O=>O.name)),c("preview")}catch(i){F(i instanceof Error?i.message:"Failed to parse manifest")}finally{Y(!1)}},[r,p,d,_,h]),be=s.useCallback(async()=>{ee(!0),ne(null);try{let i;r==="directory"?i={agents:p,skipExisting:!0,selectedAgents:y,selectedSkills:C}:r==="browse"&&_?i={importSource:"companies.sh",companySlug:_.slug,skipExisting:!0,selectedAgents:y,selectedSkills:C}:i={manifest:d,skipExisting:!0,selectedAgents:y,selectedSkills:C};const k=await fetch(he("/agents/import"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!k.ok){const ie=await k.json();throw new Error(ie.error??`Import failed (${k.status})`)}const $=await k.json();te($),c("result"),j()}catch(i){ne(i instanceof Error?i.message:"Failed to import agents")}finally{ee(!1)}},[r,p,d,_,y,C,h,j]),D=y.length,U=C.length,ye=`${D} Agent${D!==1?"s":""}`,oe=`${U} Skill${U!==1?"s":""}`,Ne=D>0&&U>0?`${ye} + ${oe}`:U>0?oe:ye,Re=D>0&&U>0?`Importing ${D} agent${D!==1?"s":""} and ${U} skill${U!==1?"s":""}...`:U>0?`Importing ${U} skill${U!==1?"s":""}...`:`Importing ${D} agent${D!==1?"s":""}...`,Ae=i=>{v(k=>k.includes(i)?k.filter($=>$!==i):[...k,i])},fe=i=>{P(k=>k.includes(i)?k.filter($=>$!==i):[...k,i])};return a?e.jsx("div",{className:"agent-dialog-overlay",onClick:i=>{i.target===i.currentTarget&&ge()},children:e.jsxs("div",{className:"agent-dialog agent-import-dialog",role:"dialog","aria-modal":"true","aria-label":"Import agents",children:[e.jsxs("div",{className:"agent-dialog-header",children:[e.jsx("span",{className:"agent-dialog-header-title",children:"Import Agents"}),e.jsx("button",{className:"modal-close",onClick:ge,"aria-label":"Close",children:"×"})]}),e.jsxs("div",{className:"agent-dialog-body",children:[o==="input"&&e.jsxs("div",{className:"agent-import-input",children:[e.jsx("p",{className:"agent-import-description",children:"Import agents from an Agent Companies package. Browse the companies.sh catalog to discover published agents, upload an AGENTS.md file, select a directory, or paste manifest content."}),e.jsxs("div",{className:"agent-import-file-upload",children:[e.jsx("input",{ref:se,type:"file",accept:".md,.txt",onChange:J,className:"agent-import-file-input","aria-label":"Upload agent manifest file"}),e.jsx("input",{ref:G,type:"file",webkitdirectory:"",multiple:!0,onChange:xe,className:"agent-import-file-input","aria-label":"Select directory"}),e.jsxs("button",{type:"button",className:"btn agent-import-upload-btn",onClick:()=>se.current?.click(),children:[e.jsx(pt,{size:16}),"Choose File"]}),e.jsxs("button",{type:"button",className:"btn agent-import-upload-btn",onClick:()=>G.current?.click(),children:[e.jsx(an,{size:16}),"Select Directory"]}),e.jsxs("button",{type:"button",className:"btn agent-import-upload-btn",onClick:()=>{m("browse"),b([]),x(""),z(null),F(null)},children:[e.jsx(Ft,{size:16}),"Browse Catalog"]}),e.jsx("span",{className:"agent-import-file-hint",children:".md and .txt files supported"})]}),r==="browse"&&e.jsxs("div",{className:"agent-import-browse",children:[e.jsxs("div",{className:"agent-import-browse-header",children:[e.jsxs("div",{className:"agent-import-browse-search",children:[e.jsx(Lt,{size:16,className:"agent-import-browse-search-icon"}),e.jsx("input",{type:"text",className:"agent-import-browse-search-input",placeholder:"Search companies...",value:A,onChange:i=>ue(i.target.value),"aria-label":"Search companies"})]}),_&&e.jsxs("div",{className:"agent-import-browse-selected",children:[e.jsx("span",{className:"agent-import-browse-selected-label",children:"Selected:"}),e.jsx("span",{className:"agent-import-browse-selected-name",children:_.name}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>z(null),children:"Change"})]})]}),W&&e.jsxs("div",{className:"agent-import-browse-loading",children:[e.jsx(qe,{size:20,className:"spin"}),e.jsx("span",{children:"Loading companies..."})]}),ke&&e.jsxs("div",{className:"agent-import-browse-error",children:[e.jsx(Ve,{size:16}),e.jsx("span",{children:ke}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:Q,children:[e.jsx(De,{size:14}),"Retry"]})]}),!W&&!ke&&e.jsxs("div",{className:"agent-import-browse-list",children:[de.filter(i=>A===""||i.name.toLowerCase().includes(A.toLowerCase())||(i.tagline?.toLowerCase().includes(A.toLowerCase())??!1)).map(i=>e.jsxs("div",{className:`agent-import-browse-item ${_?.slug===i.slug?"agent-import-browse-item--selected":""}`,onClick:()=>z(i),role:"button",tabIndex:0,onKeyDown:k=>{(k.key==="Enter"||k.key===" ")&&z(i)},children:[e.jsxs("div",{className:"agent-import-browse-item-header",children:[e.jsx("span",{className:"agent-import-browse-item-name",children:i.name}),i.installs!==void 0&&e.jsxs("span",{className:"agent-import-browse-item-installs",children:[i.installs.toLocaleString()," installs"]})]}),i.tagline&&e.jsx("span",{className:"agent-import-browse-item-tagline",children:i.tagline}),i.repo&&e.jsx("span",{className:"agent-import-browse-item-repo",children:i.repo})]},i.slug)),de.filter(i=>A===""||i.name.toLowerCase().includes(A.toLowerCase())||(i.tagline?.toLowerCase().includes(A.toLowerCase())??!1)).length===0&&e.jsx("p",{className:"agent-import-browse-empty",children:A?"No companies match your search":"No companies available"})]})]}),r!=="browse"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"agent-import-divider",children:e.jsx("span",{children:"or paste manifest content"})}),e.jsx("textarea",{className:"agent-import-textarea",placeholder:`---
515
+ Flag performance concerns only when they have measurable impact.`}],ct=[{value:"triage",label:"Triage",icon:"⊕"},{value:"executor",label:"Executor",icon:"▶"},{value:"reviewer",label:"Reviewer",icon:"⊙"},{value:"merger",label:"Merger",icon:"⊞"},{value:"scheduler",label:"Scheduler",icon:"◷"},{value:"engineer",label:"Engineer",icon:"⎔"},{value:"custom",label:"Custom",icon:"✦"}],Vn=new Set(["triage","executor","reviewer","merger","scheduler","engineer","custom"]);function Wn({isOpen:s,onClose:l,onCreated:j,projectId:h}){const[o,u]=a.useState(0),[r,m]=a.useState("presets"),[d,y]=a.useState(""),[p,v]=a.useState(""),[N,S]=a.useState(""),[R,M]=a.useState("custom"),[E,T]=a.useState(""),[b,f]=a.useState(""),[k,P]=a.useState(""),[B,Y]=a.useState(""),[H,ee]=a.useState(""),[q,$]=a.useState(""),[x,te]=a.useState({model:"",thinkingLevel:"off",maxTurns:1e3}),[re,ne]=a.useState(null),[ae,G]=a.useState([]),[de,A]=a.useState(!1),[I,ue]=a.useState(null),[_,z]=a.useState(!1),[W,le]=a.useState([]),[ke,K]=a.useState(!1),[se,Q]=a.useState([]),[me,ge]=a.useState([]),[J,xe]=a.useState("model"),[he,pe]=a.useState(""),[be,L]=a.useState([]),[U,ye]=a.useState(!1),[oe,Ne]=a.useState([]),[Re,Ae]=a.useState(!1);a.useEffect(()=>{s&&(K(!0),ut().then(n=>{le(n.models),Q(n.favoriteProviders),ge(n.favoriteModels)}).catch(()=>{}).finally(()=>K(!1)))},[s]),a.useEffect(()=>{s&&(Ae(!0),Ne([]),Ct(void 0,h).then(n=>{Ne(n)}).catch(()=>{Ne([])}).finally(()=>Ae(!1)))},[s,h]),a.useEffect(()=>{if(!s)return;const n=St;if(typeof n!="function"){L([]),ye(!1);return}ye(!0),L([]),n(h).then(g=>{L(g)}).catch(()=>{L([])}).finally(()=>ye(!1))},[s,h]);const fe=x.model.includes("/")?x.model:"",i=a.useCallback(n=>{const g=Vn.has(n.role)?n.role:"custom";y(n.title),v(n.description),S(n.icon),M(g),P(n.systemPrompt),te(D=>({...D,thinkingLevel:n.thinkingLevel,maxTurns:n.maxTurns})),z(!1),u(1)},[]),w=a.useCallback(n=>{te(g=>({...g,model:n}))},[]),F=a.useCallback(n=>{xe(n),n==="model"&&pe("")},[]),ie=a.useCallback(async n=>{const g=se,X=g.includes(n)?g.filter(ce=>ce!==n):[n,...g];Q(X);try{await et({favoriteProviders:X,favoriteModels:me})}catch{Q(g)}},[se,me]),V=a.useCallback(async n=>{const g=me,X=g.includes(n)?g.filter(ce=>ce!==n):[n,...g];ge(X);try{await et({favoriteProviders:se,favoriteModels:X})}catch{ge(g)}},[se,me]),O=a.useCallback(n=>{ne(n.id),y(n.name),S(n.icon),v(n.description??n.title),M(n.role),ee(n.soul??""),P(n.instructionsText??""),u(1)},[]);if(!s)return null;const ve=()=>{u(0),m("presets"),y(""),v(""),S(""),M("custom"),T(""),f(""),P(""),Y(""),ee(""),$(""),te({model:"",thinkingLevel:"off",maxTurns:1e3}),xe("model"),pe(""),ne(null),G([]),ue(null),z(!1),l()},Ce=async()=>{if(d.trim()){A(!0),ue(null);try{const n={};J==="runtime"?he.trim()&&(n.runtimeHint=he.trim()):x.model.trim()&&(n.model=x.model.trim()),x.thinkingLevel!=="off"&&(n.thinkingLevel=x.thinkingLevel),x.maxTurns!==1e3&&(n.maxTurns=x.maxTurns),await gt({name:d.trim(),role:R,...p.trim()?{title:p.trim()}:{},...N.trim()?{icon:N.trim()}:{},...E.trim()?{reportsTo:E.trim()}:{},...b.trim()?{instructionsPath:b.trim()}:{},...k.trim()?{instructionsText:k.trim()}:{},...B.trim()?{heartbeatProcedurePath:B.trim()}:{},...H.trim()?{soul:H.trim()}:{},...q.trim()?{memory:q.trim()}:{},...Object.keys(n).length>0?{runtimeConfig:n}:{},...ae.length>0?{metadata:{skills:ae}}:{}},h),ve(),j()}catch(n){ue(n instanceof Error?n.message:"Failed to create agent")}finally{A(!1)}}},Ie=ct.find(n=>n.value===R),Ee=E.trim(),we=Ee?oe.find(n=>n.id===Ee):void 0,t=he?be.find(n=>n.runtimeId===he):void 0,c=n=>e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx("label",{id:n,children:"Runtime Source"}),e.jsxs("div",{className:"agent-runtime-mode-toggle",role:"radiogroup","aria-labelledby":n,children:[e.jsxs("label",{className:`agent-runtime-mode-option${J==="model"?" agent-runtime-mode-option--active":""}`,children:[e.jsx("input",{type:"radio",name:n,value:"model",checked:J==="model",onChange:()=>F("model")}),e.jsx("span",{children:"Built-in Model"})]}),e.jsxs("label",{className:`agent-runtime-mode-option${J==="runtime"?" agent-runtime-mode-option--active":""}`,children:[e.jsx("input",{type:"radio",name:n,value:"runtime",checked:J==="runtime",onChange:()=>F("runtime")}),e.jsx("span",{children:"Plugin Runtime"})]})]})]}),J==="model"?e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx("label",{children:"Model"}),ke?e.jsx("div",{className:"agent-dialog-loading",children:"Loading models…"}):e.jsx(mt,{id:"agent-model",label:"Model",value:fe,onChange:w,models:W,placeholder:"Select a model…",favoriteProviders:se,onToggleFavorite:ie,favoriteModels:me,onToggleModelFavorite:V})]}):e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx("label",{htmlFor:"agent-runtime-hint",children:"Runtime"}),U?e.jsx("div",{className:"agent-dialog-loading",children:"Loading runtimes…"}):e.jsxs("select",{id:"agent-runtime-hint",className:"select",value:he,onChange:g=>pe(g.target.value),children:[e.jsx("option",{value:"",children:be.length>0?"Select a plugin runtime…":"No plugin runtimes available"}),be.map(g=>e.jsx("option",{value:g.runtimeId,children:g.description?`${g.name} — ${g.description}`:g.name},`${g.pluginId}:${g.runtimeId}`))]})]})]});return nn.createPortal(e.jsxs("div",{className:"agent-dialog-overlay",onClick:n=>{n.target===n.currentTarget&&ve()},children:[e.jsxs("div",{className:"agent-dialog",role:"dialog","aria-modal":"true","aria-label":"Create new agent",children:[e.jsxs("div",{className:"agent-dialog-header",children:[e.jsx("span",{className:"agent-dialog-header-title",children:"New Agent"}),e.jsx("button",{className:"btn-icon",onClick:ve,"aria-label":"Close",children:"×"})]}),e.jsx("div",{className:"agent-dialog-steps",children:[0,1,2].map(n=>e.jsx("div",{className:`agent-dialog-step${n===o?" active":n<o?" completed":""}`,"aria-label":`Step ${n+1}`},n))}),e.jsxs("div",{className:"agent-dialog-body",children:[o===0&&e.jsxs("div",{children:[e.jsxs("div",{className:"agent-dialog-tabs",role:"tablist","aria-label":"Agent setup mode",children:[e.jsx("button",{id:"agent-dialog-tab-presets",type:"button",role:"tab","aria-controls":"agent-dialog-panel-presets","aria-selected":r==="presets",tabIndex:r==="presets"?0:-1,className:`agent-dialog-tab${r==="presets"?" active":""}`,onClick:()=>m("presets"),"data-testid":"agent-dialog-tab-presets",children:"Preset personas"}),e.jsx("button",{id:"agent-dialog-tab-custom",type:"button",role:"tab","aria-controls":"agent-dialog-panel-custom","aria-selected":r==="custom",tabIndex:r==="custom"?0:-1,className:`agent-dialog-tab${r==="custom"?" active":""}`,onClick:()=>m("custom"),"data-testid":"agent-dialog-tab-custom",children:"Custom agent"})]}),r==="presets"&&e.jsx("div",{id:"agent-dialog-panel-presets",className:"agent-dialog-tab-panel",role:"tabpanel","aria-labelledby":"agent-dialog-tab-presets",children:e.jsxs("div",{className:"agent-presets",children:[e.jsx("div",{className:"agent-presets-header",children:"Choose a preset persona to prefill role, identity, soul, and instructions"}),e.jsx("div",{className:"agent-presets-grid",children:vt.map(n=>e.jsxs("button",{type:"button",className:`agent-preset-card${re===n.id?" selected":""}`,"data-testid":`preset-${n.id}`,onClick:()=>O(n),title:n.title,children:[e.jsx("span",{className:"agent-preset-icon",children:n.icon}),e.jsx("span",{className:"agent-preset-name",children:n.name}),e.jsx("span",{className:"agent-preset-role",children:n.role}),n.description&&e.jsx("span",{className:"agent-preset-description",children:n.description})]},n.id))})]})}),r==="custom"&&e.jsxs("div",{id:"agent-dialog-panel-custom",className:"agent-dialog-tab-panel",role:"tabpanel","aria-labelledby":"agent-dialog-tab-custom",children:[e.jsxs("div",{className:"agent-dialog-section",children:[e.jsx("div",{className:"agent-dialog-section-header",children:"Identity"}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsxs("label",{htmlFor:"agent-name",children:["Name ",!re&&e.jsx("span",{className:"agent-dialog-required",children:"*"})]}),e.jsx("input",{id:"agent-name",type:"text",className:"input",placeholder:"e.g. Frontend Reviewer",value:d,onChange:n=>y(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-field agent-dialog-field--title",children:[e.jsxs("label",{htmlFor:"agent-title",children:["Title ",e.jsx("span",{className:"agent-dialog-optional",children:"(optional)"})]}),e.jsx("input",{id:"agent-title",type:"text",className:"input",placeholder:"e.g. Senior Code Reviewer",value:p,onChange:n=>v(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsxs("label",{htmlFor:"agent-icon",children:["Icon ",e.jsx("span",{className:"agent-dialog-optional",children:"(optional)"})]}),e.jsx("input",{id:"agent-icon",type:"text",className:"input",placeholder:"e.g. 🤖",value:N,onChange:n=>S(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx("label",{children:"Role"}),e.jsx("div",{className:"agent-role-grid",children:ct.map(n=>e.jsxs("button",{type:"button",className:`agent-role-option${R===n.value?" selected":""}`,onClick:()=>M(n.value),children:[e.jsx("span",{className:"agent-role-option-icon",children:n.icon}),e.jsx("span",{className:"agent-role-option-label",children:n.label})]},n.value))})]})]}),e.jsxs("div",{className:"agent-dialog-section",children:[e.jsx("div",{className:"agent-dialog-section-header",children:"Configuration"}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsxs("label",{htmlFor:"agent-reports-to",children:["Reports To ",e.jsx("span",{className:"agent-dialog-optional",children:"(optional)"})]}),e.jsxs("select",{id:"agent-reports-to",className:"select",value:E,onChange:n=>T(n.target.value),disabled:Re,children:[e.jsx("option",{value:"",children:"No manager"}),oe.map(n=>e.jsxs("option",{value:n.id,children:[n.name," (",n.id,")"]},n.id))]})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsxs("label",{htmlFor:"agent-soul",children:["Soul ",e.jsx("span",{className:"agent-dialog-optional",children:"(optional)"})]}),e.jsx("textarea",{id:"agent-soul",className:"input",rows:2,placeholder:"Describe the agent's personality and communication style...",value:H,onChange:n=>ee(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsxs("label",{htmlFor:"agent-memory",children:["Agent Memory ",e.jsx("span",{className:"agent-dialog-optional",children:"(optional)"})]}),e.jsx("textarea",{id:"agent-memory",className:"input",rows:2,placeholder:"Private to this agent — durable preferences, operating habits, and context it should carry across tasks...",value:q,onChange:n=>$(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsxs("label",{htmlFor:"agent-instructions-path",children:["Instructions Path ",e.jsx("span",{className:"agent-dialog-optional",children:"(optional)"})]}),e.jsx("input",{id:"agent-instructions-path",type:"text",className:"input",placeholder:"e.g. .fusion/agents/reviewer.md",value:b,onChange:n=>f(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsxs("label",{htmlFor:"agent-heartbeat-procedure-path",children:["Heartbeat Procedure Path ",e.jsx("span",{className:"agent-dialog-optional",children:"(optional)"})]}),e.jsx("input",{id:"agent-heartbeat-procedure-path",type:"text",className:"input",placeholder:"e.g. .fusion/agents/my-agent/HEARTBEAT.md",value:B,onChange:n=>Y(n.target.value)}),e.jsx("p",{className:"agent-dialog-optional agent-dialog-field-hint",children:"Path to the agent's heartbeat markdown file, typically .fusion/agents/<agent-id>/HEARTBEAT.md."})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsxs("label",{htmlFor:"agent-instructions-text",children:["Inline Instructions ",e.jsx("span",{className:"agent-dialog-optional",children:"(optional)"})]}),e.jsx("textarea",{id:"agent-instructions-text",className:"input",rows:4,placeholder:"Add custom behavior instructions...",value:k,onChange:n=>P(n.target.value)})]})]}),e.jsxs("div",{className:"agent-dialog-section",children:[e.jsx("div",{className:"agent-dialog-section-header",children:"Runtime"}),c("agent-runtime-source-step-0")]}),e.jsxs("div",{className:"agent-dialog-ai-generate",children:[e.jsxs("button",{type:"button",className:"btn btn--ai-generate",onClick:()=>z(!0),children:[e.jsx("span",{children:"✨"}),"Generate with AI"]}),e.jsx("p",{className:"agent-dialog-ai-hint",children:"Describe your agent's role and let AI generate a specification"})]})]})]}),o===1&&e.jsxs("div",{children:[c("agent-runtime-source-step-1"),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx("label",{htmlFor:"agent-thinking",children:"Thinking Level"}),e.jsxs("select",{id:"agent-thinking",className:"select",value:x.thinkingLevel,onChange:n=>te(g=>({...g,thinkingLevel:n.target.value})),children:[e.jsx("option",{value:"off",children:"Off"}),e.jsx("option",{value:"minimal",children:"Minimal"}),e.jsx("option",{value:"low",children:"Low"}),e.jsx("option",{value:"medium",children:"Medium"}),e.jsx("option",{value:"high",children:"High"})]})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx("label",{htmlFor:"agent-max-turns",children:"Max Turns"}),e.jsx("input",{id:"agent-max-turns",type:"number",className:"input",min:1,max:2e3,value:x.maxTurns,onChange:n=>te(g=>({...g,maxTurns:Math.max(1,parseInt(n.target.value,10)||1)}))})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx(an,{id:"agent-skills",label:"Skills",value:ae,onChange:G,projectId:h}),e.jsx("p",{className:"agent-dialog-optional agent-dialog-skills-hint",children:"Optional skills to assign to this agent"})]})]}),o===2&&e.jsxs("div",{children:[e.jsx("p",{className:"agent-dialog-info",children:"Review your agent configuration before creating."}),e.jsxs("div",{className:"agent-dialog-summary",children:[e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Name"}),e.jsxs("span",{className:"agent-dialog-summary-row-value",children:[N&&e.jsx("span",{className:"agent-dialog-icon-prefix",children:N}),d]})]}),e.jsxs("div",{className:"agent-dialog-summary-row agent-dialog-summary-row--editable agent-dialog-summary-row--title",children:[e.jsx("label",{className:"agent-dialog-summary-row-label",htmlFor:"agent-review-title",children:"Title"}),e.jsx("input",{id:"agent-review-title",type:"text",className:"input",placeholder:"e.g. Senior Code Reviewer",value:p,onChange:n=>v(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Role"}),e.jsxs("span",{children:[Ie?.icon," ",Ie?.label]})]}),Ee&&e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Reports To"}),e.jsx("span",{children:we?`${we.name} (${we.id})`:Ee})]}),e.jsxs("div",{className:"agent-dialog-summary-row agent-dialog-summary-row--editable",children:[e.jsx("label",{className:"agent-dialog-summary-row-label",htmlFor:"agent-review-soul",children:"Soul"}),e.jsx("textarea",{id:"agent-review-soul",className:"input",rows:2,placeholder:"Describe the agent's personality and communication style...",value:H,onChange:n=>ee(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-summary-row agent-dialog-summary-row--editable",children:[e.jsx("label",{className:"agent-dialog-summary-row-label",htmlFor:"agent-review-heartbeat-procedure-path",children:"Heartbeat Procedure Path"}),e.jsx("input",{id:"agent-review-heartbeat-procedure-path",type:"text",className:"input",placeholder:"e.g. .fusion/agents/my-agent/HEARTBEAT.md",value:B,onChange:n=>Y(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-summary-row agent-dialog-summary-row--editable",children:[e.jsx("label",{className:"agent-dialog-summary-row-label",htmlFor:"agent-review-instructions-path",children:"Instructions Path"}),e.jsx("input",{id:"agent-review-instructions-path",type:"text",className:"input",placeholder:"e.g. .fusion/agents/reviewer.md",value:b,onChange:n=>f(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-summary-row agent-dialog-summary-row--editable",children:[e.jsx("label",{className:"agent-dialog-summary-row-label",htmlFor:"agent-review-instructions-text",children:"Inline Instructions"}),e.jsx("textarea",{id:"agent-review-instructions-text",className:"input",rows:4,placeholder:"Add custom behavior instructions...",value:k,onChange:n=>P(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:J==="runtime"?"Runtime":"Model"}),e.jsx("span",{children:J==="runtime"?t?t.name:e.jsx("em",{className:"agent-dialog-summary-row-value--muted",children:"Not selected"}):fe?e.jsxs(e.Fragment,{children:[e.jsx(It,{provider:fe.split("/")[0],size:"sm"})," ",(()=>{const n=fe.indexOf("/"),g=fe.slice(0,n),D=fe.slice(n+1);return W.find(ce=>ce.provider===g&&ce.id===D)?.name||fe})()]}):e.jsx("em",{className:"agent-dialog-summary-row-value--muted",children:"default"})})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Thinking"}),e.jsx("span",{className:"agent-dialog-summary-row-value--capitalize",children:x.thinkingLevel})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Max Turns"}),e.jsx("span",{children:x.maxTurns})]}),ae.length>0&&e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Skills"}),e.jsxs("span",{children:[ae.length," skill",ae.length!==1?"s":""," selected"]})]})]}),I&&e.jsx("p",{className:"agent-dialog-error",children:I})]})]}),e.jsxs("div",{className:"agent-dialog-footer",children:[o>0&&e.jsx("button",{className:"btn",onClick:()=>u(n=>n-1),disabled:de,children:"Back"}),e.jsx("button",{className:"btn",onClick:ve,disabled:de,children:"Cancel"}),o<2?e.jsx("button",{className:"btn btn--primary",onClick:()=>u(n=>n+1),disabled:o===0&&!d.trim()&&!re,children:"Next"}):e.jsx("button",{className:"btn btn--primary",onClick:()=>void Ce(),disabled:de||!d.trim(),children:de?"Creating...":"Create"})]})]}),e.jsx(jn,{isOpen:_,onClose:()=>z(!1),onGenerated:i,projectId:h})]}),document.body)}function Kn({isOpen:s,onClose:l,onCreated:j,addToast:h,projectId:o,existingAgents:u}){const[r,m]=a.useState("initial"),[d,y]=a.useState(""),[p,v]=a.useState(null),[N,S]=a.useState(""),[R,M]=a.useState("answer"),[E,T]=a.useState(""),[b,f]=a.useState(null),[k,P]=a.useState(null),[B,Y]=a.useState([]),[H,ee]=a.useState("model"),[q,$]=a.useState(""),[x,te]=a.useState([]),re=a.useMemo(()=>vt.map(A=>({id:A.id,label:A.name,description:A.description})),[]);a.useEffect(()=>{ut().then(A=>te(A.models)).catch(()=>te([]))},[]),a.useEffect(()=>{if(!p)return;const A=At(p,o,{onThinking:I=>{Y(ue=>{const _=[...ue],z=_[_.length-1];return z&&!z.question?(_[_.length-1]={...z,thinkingOutput:`${z.thinkingOutput??""}${I}`},_):[..._,{response:{},thinkingOutput:I}]})},onQuestion:I=>{S(I.question),M(I.id),m("question")},onSummary:I=>{f(I),m("summary")},onError:I=>{P(I),m("error")},onComplete:()=>{b&&m("summary")},onConnectionStateChange:I=>{I==="reconnecting"&&P("Connection lost. Retrying...")}});return()=>A.close()},[p,o]);const ne=async()=>{p&&await Rt(p,o),l()};if(!s)return null;const ae=async()=>{m("loading"),P(null);try{const A=await Pt(d,{existingAgents:u.map(I=>({id:I.id,name:I.name,role:I.role})),templates:re},o);v(A.sessionId)}catch(A){P(A.message),m("error")}},G=async()=>{if(p){m("loading"),P(null);try{const A={[R]:E};Y(I=>[...I,{question:{id:R,type:"text",question:N},response:A}]),await _t(p,A,o),T("")}catch(A){P(A.message),m("error")}}},de=async()=>{if(b){m("creating"),P(null);try{await gt({name:b.name,role:b.role,title:b.title,icon:b.icon,reportsTo:b.reportsTo,instructionsText:b.instructionsText,soul:b.soul,memory:b.memory,runtimeConfig:{thinkingLevel:b.thinkingLevel,maxTurns:b.maxTurns,...H==="model"&&q?{model:q}:{},...H==="runtime"?{runtimeHint:"onboarding"}:{}},metadata:b.skills?{skills:b.skills}:void 0},o),h(`Agent "${b.name}" created`,"success"),j()}catch(A){P(A.message),m("error")}}};return e.jsx("div",{className:"modal-overlay open",role:"presentation",children:e.jsxs("div",{className:"modal modal-lg agent-onboarding-modal",role:"dialog","aria-modal":"true","aria-label":"Agent onboarding",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:"Agent Onboarding"}),e.jsx("button",{className:"modal-close",onClick:()=>void ne(),"aria-label":"Close",children:"×"})]}),B.length>0&&e.jsx(Et,{entries:B}),r==="initial"&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"agent-onboarding-intent",children:"What do you want this agent to do?"}),e.jsx("textarea",{id:"agent-onboarding-intent",className:"input",value:d,onChange:A=>y(A.target.value)}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{className:"btn",onClick:()=>void ne(),children:"Cancel"}),e.jsx("button",{className:"btn btn-primary",disabled:!d.trim(),onClick:()=>void ae(),children:"Start onboarding"})]})]}),(r==="loading"||r==="question")&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"agent-onboarding-answer",children:N||"Waiting for AI question..."}),e.jsx("textarea",{id:"agent-onboarding-answer",className:"input",value:E,onChange:A=>T(A.target.value)}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{className:"btn",onClick:()=>p&&void Tt(p,o),children:"Stop"}),e.jsx("button",{className:"btn btn-primary",disabled:r==="loading"||!E.trim(),onClick:()=>void G(),children:"Continue"})]})]}),r==="summary"&&b&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Review generated configuration"}),e.jsxs("div",{className:"agent-onboarding-summary",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Name:"})," ",b.name]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Role:"})," ",b.role]}),e.jsx("label",{htmlFor:"thinking-level",children:"Thinking level"}),e.jsx("input",{id:"thinking-level",className:"input",value:b.thinkingLevel,onChange:()=>{},readOnly:!0}),e.jsx("label",{htmlFor:"max-turns",children:"Max turns"}),e.jsx("input",{id:"max-turns",className:"input",type:"number",value:b.maxTurns,onChange:()=>{},readOnly:!0}),e.jsx("label",{htmlFor:"runtime-mode",children:"Runtime mode"}),e.jsxs("select",{id:"runtime-mode",className:"select",value:H,onChange:A=>ee(A.target.value),children:[e.jsx("option",{value:"model",children:"Model"}),e.jsx("option",{value:"runtime",children:"Runtime"})]}),H==="model"&&e.jsxs(e.Fragment,{children:[e.jsx("label",{children:"Model"}),e.jsx(mt,{id:"agent-onboarding-model",label:"Model",value:q,onChange:$,models:x,placeholder:"Select a model…"})]})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{className:"btn",onClick:()=>void ne(),children:"Cancel"}),e.jsx("button",{className:"btn btn-primary",onClick:()=>void de(),children:"Create agent"})]})]}),r==="creating"&&e.jsx("div",{className:"form-group agent-onboarding-creating",children:"Creating agent..."}),r==="error"&&k&&e.jsxs("div",{className:"form-group",children:[e.jsx("div",{className:"form-error",children:k}),e.jsx("div",{className:"modal-actions",children:e.jsx("button",{className:"btn",onClick:()=>p&&void Mt(p,o),children:"Retry"})})]})]})})}function Un(s){const l=s.match(/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n([\s\S]*))?$/);if(!l)throw new Error("Missing YAML frontmatter delimiters (---)");const j=l[1].split(/\r?\n/),h=l[2]??"",o={name:""},u=[];let r=!1;for(const m of j){const y=m.trimEnd().trim();if(!y)continue;if(y.startsWith("skills:")){r=!0;continue}if(r&&y.startsWith("- ")){u.push(y.slice(2).trim());continue}r=!1;const[p,...v]=y.split(":"),S=v.join(":").trim().replace(/^['"]|['"]$/g,"");p==="name"&&(o.name=S),p==="title"&&(o.title=S),p==="icon"&&(o.icon=S),p==="role"&&(o.role=S),p==="reportsTo"&&(o.reportsTo=S)}if(!o.name)throw new Error("Missing required field: name");return u.length>0&&(o.skills=u),h.trim().length>0&&(o.instructionBody=h),o}function Bn({isOpen:s,onClose:l,onImported:j,projectId:h}){const[o,u]=a.useState("input"),[r,m]=a.useState("paste"),[d,y]=a.useState(""),[p,v]=a.useState([]),[N,S]=a.useState("Unknown"),[R,M]=a.useState([]),[E,T]=a.useState([]),[b,f]=a.useState([]),[k,P]=a.useState([]),[B,Y]=a.useState(!1),[H,ee]=a.useState(!1),[q,$]=a.useState(null),[x,te]=a.useState(null),[re,ne]=a.useState(null),ae=a.useRef(null),G=a.useRef(null),[de,A]=a.useState([]),[I,ue]=a.useState(""),[_,z]=a.useState(null),[W,le]=a.useState(!1),[ke,K]=a.useState(null),se=a.useRef(!1);a.useEffect(()=>{r==="browse"&&!se.current&&!W&&(se.current=!0,le(!0),K(null),tt().then(i=>{i.error?K(i.error):i.companies.length>0?A(i.companies):K("No companies available")}).catch(i=>{K(i instanceof Error?i.message:"Failed to load companies")}).finally(()=>{le(!1)}))},[r,W]);const Q=a.useCallback(()=>{se.current=!0,K(null),A([]),z(null),le(!0),tt().then(i=>{i.error?K(i.error):i.companies.length>0?A(i.companies):K("No companies available")}).catch(i=>{K(i instanceof Error?i.message:"Failed to load companies")}).finally(()=>{le(!1)})},[]),me=a.useCallback(()=>{u("input"),m("paste"),y(""),v([]),S("Unknown"),M([]),T([]),f([]),P([]),Y(!1),ee(!1),$(null),te(null),ne(null),A([]),ue(""),z(null),le(!1),K(null),se.current=!1},[]),ge=a.useCallback(()=>{me(),l()},[me,l]),J=a.useCallback(i=>{const w=i.target.files?.[0];if(!w)return;const F=new FileReader;F.onload=ie=>{const V=ie.target?.result;m("file"),v([]),y(V),$(null)},F.onerror=()=>{$("Failed to read file")},F.readAsText(w),i.target.value=""},[]),xe=a.useCallback(async i=>{const w=Array.from(i.target.files??[]);if(w.length!==0)try{const F=w.filter(V=>(V.webkitRelativePath||V.name).toLowerCase().endsWith("agents.md")).sort((V,O)=>{const ve=V.webkitRelativePath||V.name,Ce=O.webkitRelativePath||O.name;return ve.localeCompare(Ce)});if(F.length===0){$("Selected directory has no AGENTS.md files");return}const ie=[];for(const V of F){const O=await V.text();ie.push(Un(O))}m("directory"),v(ie),y(""),$(null)}catch{$("Failed to parse AGENTS.md files from selected directory")}finally{i.target.value=""}},[]);function he(i){if(!h)return`/api${i}`;const w=i.includes("?")?"&":"?";return`/api${i}${w}projectId=${encodeURIComponent(h)}`}const pe=a.useCallback(async()=>{if(r==="directory"&&p.length===0){$("Please select a directory containing AGENTS.md files");return}if(r==="browse"&&!_){$("Please select a company from the catalog");return}if(r!=="directory"&&r!=="browse"&&!d.trim()){$("Please provide manifest content");return}Y(!0),$(null);try{let i;r==="directory"?i={agents:p,dryRun:!0}:r==="browse"&&_?i={importSource:"companies.sh",companySlug:_.slug,dryRun:!0}:i={manifest:d,dryRun:!0};const w=await fetch(he("/agents/import"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!w.ok){const O=await w.json();throw new Error(O.error??`Parse failed (${w.status})`)}const F=await w.json(),ie=F.agents&&F.agents.length>0?F.agents:F.created.map(O=>({name:O,role:"custom"})),V=Array.isArray(F.skills)?F.skills:[];S(F.companyName??"Unknown"),M(ie),T(V),f(ie.map(O=>O.name)),P(V.map(O=>O.name)),u("preview")}catch(i){$(i instanceof Error?i.message:"Failed to parse manifest")}finally{Y(!1)}},[r,p,d,_,h]),be=a.useCallback(async()=>{ee(!0),ne(null);try{let i;r==="directory"?i={agents:p,skipExisting:!0,selectedAgents:b,selectedSkills:k}:r==="browse"&&_?i={importSource:"companies.sh",companySlug:_.slug,skipExisting:!0,selectedAgents:b,selectedSkills:k}:i={manifest:d,skipExisting:!0,selectedAgents:b,selectedSkills:k};const w=await fetch(he("/agents/import"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!w.ok){const ie=await w.json();throw new Error(ie.error??`Import failed (${w.status})`)}const F=await w.json();te(F),u("result"),j()}catch(i){ne(i instanceof Error?i.message:"Failed to import agents")}finally{ee(!1)}},[r,p,d,_,b,k,h,j]),L=b.length,U=k.length,ye=`${L} Agent${L!==1?"s":""}`,oe=`${U} Skill${U!==1?"s":""}`,Ne=L>0&&U>0?`${ye} + ${oe}`:U>0?oe:ye,Re=L>0&&U>0?`Importing ${L} agent${L!==1?"s":""} and ${U} skill${U!==1?"s":""}...`:U>0?`Importing ${U} skill${U!==1?"s":""}...`:`Importing ${L} agent${L!==1?"s":""}...`,Ae=i=>{f(w=>w.includes(i)?w.filter(F=>F!==i):[...w,i])},fe=i=>{P(w=>w.includes(i)?w.filter(F=>F!==i):[...w,i])};return s?e.jsx("div",{className:"agent-dialog-overlay",onClick:i=>{i.target===i.currentTarget&&ge()},children:e.jsxs("div",{className:"agent-dialog agent-import-dialog",role:"dialog","aria-modal":"true","aria-label":"Import agents",children:[e.jsxs("div",{className:"agent-dialog-header",children:[e.jsx("span",{className:"agent-dialog-header-title",children:"Import Agents"}),e.jsx("button",{className:"modal-close",onClick:ge,"aria-label":"Close",children:"×"})]}),e.jsxs("div",{className:"agent-dialog-body",children:[o==="input"&&e.jsxs("div",{className:"agent-import-input",children:[e.jsx("p",{className:"agent-import-description",children:"Import agents from an Agent Companies package. Browse the companies.sh catalog to discover published agents, upload an AGENTS.md file, select a directory, or paste manifest content."}),e.jsxs("div",{className:"agent-import-file-upload",children:[e.jsx("input",{ref:ae,type:"file",accept:".md,.txt",onChange:J,className:"agent-import-file-input","aria-label":"Upload agent manifest file"}),e.jsx("input",{ref:G,type:"file",webkitdirectory:"",multiple:!0,onChange:xe,className:"agent-import-file-input","aria-label":"Select directory"}),e.jsxs("button",{type:"button",className:"btn agent-import-upload-btn",onClick:()=>ae.current?.click(),children:[e.jsx(pt,{size:16}),"Choose File"]}),e.jsxs("button",{type:"button",className:"btn agent-import-upload-btn",onClick:()=>G.current?.click(),children:[e.jsx(sn,{size:16}),"Select Directory"]}),e.jsxs("button",{type:"button",className:"btn agent-import-upload-btn",onClick:()=>{m("browse"),v([]),y(""),z(null),$(null)},children:[e.jsx(Ft,{size:16}),"Browse Catalog"]}),e.jsx("span",{className:"agent-import-file-hint",children:".md and .txt files supported"})]}),r==="browse"&&e.jsxs("div",{className:"agent-import-browse",children:[e.jsxs("div",{className:"agent-import-browse-header",children:[e.jsxs("div",{className:"agent-import-browse-search",children:[e.jsx($t,{size:16,className:"agent-import-browse-search-icon"}),e.jsx("input",{type:"text",className:"agent-import-browse-search-input",placeholder:"Search companies...",value:I,onChange:i=>ue(i.target.value),"aria-label":"Search companies"})]}),_&&e.jsxs("div",{className:"agent-import-browse-selected",children:[e.jsx("span",{className:"agent-import-browse-selected-label",children:"Selected:"}),e.jsx("span",{className:"agent-import-browse-selected-name",children:_.name}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>z(null),children:"Change"})]})]}),W&&e.jsxs("div",{className:"agent-import-browse-loading",children:[e.jsx(qe,{size:20,className:"spin"}),e.jsx("span",{children:"Loading companies..."})]}),ke&&e.jsxs("div",{className:"agent-import-browse-error",children:[e.jsx(Ve,{size:16}),e.jsx("span",{children:ke}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:Q,children:[e.jsx(Le,{size:14}),"Retry"]})]}),!W&&!ke&&e.jsxs("div",{className:"agent-import-browse-list",children:[de.filter(i=>I===""||i.name.toLowerCase().includes(I.toLowerCase())||(i.tagline?.toLowerCase().includes(I.toLowerCase())??!1)).map(i=>e.jsxs("div",{className:`agent-import-browse-item ${_?.slug===i.slug?"agent-import-browse-item--selected":""}`,onClick:()=>z(i),role:"button",tabIndex:0,onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&z(i)},children:[e.jsxs("div",{className:"agent-import-browse-item-header",children:[e.jsx("span",{className:"agent-import-browse-item-name",children:i.name}),i.installs!==void 0&&e.jsxs("span",{className:"agent-import-browse-item-installs",children:[i.installs.toLocaleString()," installs"]})]}),i.tagline&&e.jsx("span",{className:"agent-import-browse-item-tagline",children:i.tagline}),i.repo&&e.jsx("span",{className:"agent-import-browse-item-repo",children:i.repo})]},i.slug)),de.filter(i=>I===""||i.name.toLowerCase().includes(I.toLowerCase())||(i.tagline?.toLowerCase().includes(I.toLowerCase())??!1)).length===0&&e.jsx("p",{className:"agent-import-browse-empty",children:I?"No companies match your search":"No companies available"})]})]}),r!=="browse"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"agent-import-divider",children:e.jsx("span",{children:"or paste manifest content"})}),e.jsx("textarea",{className:"agent-import-textarea",placeholder:`---
516
516
  name: CEO
517
517
  title: Chief Executive Officer
518
518
  reportsTo: null
519
519
  skills:
520
520
  - review
521
521
  ---
522
- Agent instructions go here...`,value:d,onChange:i=>{m("paste"),b([]),x(i.target.value),F(null)},rows:8,"aria-label":"Manifest content"})]}),e.jsxs("p",{className:"agent-import-file-hint",children:["Current input: ",r]}),q&&e.jsxs("p",{className:"agent-dialog-error",children:[e.jsx(Ve,{size:14}),q]})]}),o==="preview"&&e.jsxs("div",{className:"agent-import-preview",children:[e.jsxs("div",{className:"agent-import-company",children:[e.jsx("span",{className:"agent-import-company-label",children:"Company"}),e.jsx("span",{className:"agent-import-company-name",children:N})]}),e.jsxs("div",{className:"agent-import-count",children:[e.jsx(Qe,{size:14}),e.jsxs("span",{children:[f.length," agent",f.length!==1?"s":""," found"]})]}),f.length>0&&e.jsxs("div",{className:"agent-import-selection-controls",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>v(f.map(i=>i.name)),children:"Select all agents"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>v([]),children:"Clear agents"})]}),f.length>0?e.jsx("div",{className:"agent-import-agent-list",children:f.map((i,k)=>e.jsxs("div",{className:"agent-import-agent-item",children:[e.jsx("label",{className:"checkbox-label",children:e.jsx("input",{type:"checkbox","aria-label":`Select agent ${i.name}`,checked:y.includes(i.name),onChange:()=>Ae(i.name)})}),e.jsx("span",{className:"agent-import-agent-icon",children:i.icon||"🤖"}),e.jsxs("div",{className:"agent-import-agent-details",children:[e.jsx("span",{className:"agent-import-agent-name",children:i.name}),e.jsxs("span",{className:"agent-import-agent-meta",children:[i.title&&e.jsxs("span",{className:"agent-import-agent-title",children:[i.title," · "]}),e.jsx("span",{className:"agent-import-agent-role",children:i.role}),i.reportsTo&&e.jsxs("span",{className:"agent-import-agent-reports",children:[" · reports to ",i.reportsTo]}),i.skills&&i.skills.length>0&&e.jsxs("span",{className:"agent-import-agent-model",children:[" · skills: ",i.skills.join(", ")]})]}),i.instructionsText&&e.jsxs("span",{className:"agent-import-agent-instructions",children:[i.instructionsText.slice(0,100),i.instructionsText.length>100?"...":""]})]})]},k))}):e.jsx("p",{className:"agent-import-empty",children:"No agents found in the manifest."}),E.length>0&&e.jsxs("div",{className:"agent-import-skills-section",children:[e.jsxs("div",{className:"agent-import-count",children:[e.jsx(Qe,{size:14}),e.jsxs("span",{children:[E.length," skill",E.length!==1?"s":""," found"]})]}),e.jsxs("div",{className:"agent-import-selection-controls",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>P(E.map(i=>i.name)),children:"Select all skills"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>P([]),children:"Clear skills"})]}),e.jsx("div",{className:"agent-import-skill-list",children:E.map((i,k)=>e.jsxs("div",{className:"agent-import-skill-item",children:[e.jsx("label",{className:"checkbox-label",children:e.jsx("input",{type:"checkbox","aria-label":`Select skill ${i.name}`,checked:C.includes(i.name),onChange:()=>fe(i.name)})}),e.jsx("span",{className:"agent-import-skill-icon",children:"⚡"}),e.jsxs("div",{className:"agent-import-skill-details",children:[e.jsx("span",{className:"agent-import-skill-name",children:i.name}),i.description&&e.jsx("span",{className:"agent-import-skill-description",children:i.description})]})]},`${i.name}-${k}`))})]}),re&&e.jsxs("p",{className:"agent-dialog-error",children:[e.jsx(Ve,{size:14}),re]})]}),o==="result"&&w&&e.jsxs("div",{className:"agent-import-result",children:[e.jsx("div",{className:"agent-import-result-icon",children:e.jsx(Le,{size:32})}),e.jsx("h3",{className:"agent-import-result-title",children:"Import Complete"}),e.jsxs("p",{className:"agent-import-result-company",children:["From ",e.jsx("strong",{children:w.companyName??"Unknown"})]}),e.jsxs("div",{className:"agent-import-result-stats",children:[w.created.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--success",children:e.jsxs("span",{children:[w.created.length," created"]})}),w.skipped.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--skipped",children:e.jsxs("span",{children:[w.skipped.length," skipped (already exist)"]})}),w.errors.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--error",children:e.jsxs("span",{children:[w.errors.length," error",w.errors.length!==1?"s":""]})})]}),w.created.length>0&&e.jsx("div",{className:"agent-import-result-agents",children:w.created.map((i,k)=>e.jsxs("div",{className:"agent-import-result-agent",children:[e.jsx(Le,{size:12}),e.jsx("span",{children:i.name})]},k))}),w.errors.length>0&&e.jsx("div",{className:"agent-import-result-errors",children:w.errors.map((i,k)=>e.jsxs("div",{className:"agent-import-result-error",children:[e.jsx(nt,{size:12}),e.jsxs("span",{children:[i.name,": ",i.error]})]},k))}),w.skills&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"agent-import-result-divider"}),e.jsx("h4",{className:"agent-import-result-section-title",children:"Skills"}),e.jsxs("div",{className:"agent-import-result-stats",children:[w.skills.imported.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--success",children:e.jsxs("span",{children:[w.skills.imported.length," skill",w.skills.imported.length!==1?"s":""," imported"]})}),w.skills.skipped.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--skipped",children:e.jsxs("span",{children:[w.skills.skipped.length," skill",w.skills.skipped.length!==1?"s":""," skipped (already exist)"]})}),w.skills.errors.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--error",children:e.jsxs("span",{children:[w.skills.errors.length," skill",w.skills.errors.length!==1?"s":""," error",w.skills.errors.length!==1?"s":""]})}),w.skills.imported.length===0&&w.skills.skipped.length===0&&w.skills.errors.length===0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--skipped",children:e.jsx("span",{children:"No skills in package"})})]}),w.skills.imported.length>0&&e.jsx("div",{className:"agent-import-result-agents",children:w.skills.imported.map((i,k)=>e.jsxs("div",{className:"agent-import-result-agent",children:[e.jsx(Le,{size:12}),e.jsx("span",{children:i.name})]},k))}),w.skills.errors.length>0&&e.jsx("div",{className:"agent-import-result-errors",children:w.skills.errors.map((i,k)=>e.jsxs("div",{className:"agent-import-result-error",children:[e.jsx(nt,{size:12}),e.jsxs("span",{children:[i.name,": ",i.error]})]},k))})]})]})]}),e.jsxs("div",{className:"agent-dialog-footer",children:[o==="preview"&&e.jsx("button",{className:"btn",onClick:()=>c("input"),disabled:H,children:"Back"}),e.jsx("button",{className:"btn",onClick:ge,disabled:H,children:o==="result"?"Close":"Cancel"}),o==="input"&&e.jsx("button",{className:"btn btn-task-create",onClick:()=>void pe(),disabled:B||(r==="directory"?p.length===0:r==="browse"?!_:!d.trim()),children:B?e.jsxs(e.Fragment,{children:[e.jsx(qe,{size:14,className:"spin"}),"Parsing..."]}):"Preview"}),o==="preview"&&e.jsx("button",{className:"btn btn-task-create",onClick:()=>void be(),disabled:H||D===0&&U===0,children:H?e.jsxs(e.Fragment,{children:[e.jsx(qe,{size:14,className:"spin"}),Re]}):`Import ${Ne}`})]})]})}):null}const Qn=s.lazy(()=>nn(()=>import("./AgentDetailView-DQBjJSPJ.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10])).then(a=>({default:a.AgentDetailView}))),Fe=[{value:"triage",label:"Triage",icon:"⊕"},{value:"executor",label:"Executor",icon:"▶"},{value:"reviewer",label:"Reviewer",icon:"⊙"},{value:"merger",label:"Merger",icon:"⊞"},{value:"scheduler",label:"Scheduler",icon:"◷"},{value:"engineer",label:"Engineer",icon:"⎔"},{value:"custom",label:"Custom",icon:"✦"}],Be=[.1,.25,.5,1,2,3,5,10];function ze(a){switch(a){case"running":return"agent-badge--running";case"active":return"agent-badge--active";case"paused":return"agent-badge--paused";case"error":return"agent-badge--error";case"terminated":return"agent-badge--terminated";case"idle":default:return"agent-badge--idle"}}function Oe(a,l){switch(l){case"running":return`${a}--running`;case"active":return`${a}--active`;case"paused":return`${a}--paused`;case"error":return`${a}--error`;case"terminated":return`${a}--terminated`;case"idle":default:return`${a}--idle`}}function bt({node:a,onSelect:l,onToggle:j,isExpanded:h,getChildCount:o,getHealthStatus:c,getRoleIcon:r,getSkillBadges:m}){const{agent:d,children:x,depth:p}=a,b=o(d.id),N=h(d.id),I=c(d),f=ze(d.state),M=Oe("agent-tree__node",d.state);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`${M}${d.reportsTo?" agent-is-child":""} agent-tree__indent--${Math.min(p,4)}`,children:[e.jsx("button",{className:`agent-tree__toggle${b===0?" agent-tree__toggle--leaf":""}`,onClick:()=>b>0&&j(d.id),title:b>0?N?"Collapse":"Expand":"No employees","aria-label":b>0?N?"Collapse":"Expand":"No employees",children:b>0?N?e.jsx(Jt,{size:16}):e.jsx(ht,{size:16}):e.jsx(Ze,{size:14})}),e.jsxs("div",{className:"agent-tree__content",onClick:()=>l(d.id),role:"button",tabIndex:0,onKeyDown:E=>E.key==="Enter"&&l(d.id),children:[e.jsx("span",{className:"agent-tree__icon",children:r(d.role)}),e.jsx("span",{className:"agent-tree__name",children:d.name}),e.jsx("span",{className:`agent-tree__badge ${f}`,children:d.state}),e.jsx("span",{className:"agent-tree__health",style:{color:I.color},title:I.label,children:I.icon}),b>0&&e.jsxs("span",{className:"agent-tree__count text-secondary",children:["(",b,")"]}),(()=>{const E=m(d);return E.length===0?null:e.jsxs("span",{className:"agent-tree__skill",title:E.join(", "),children:[E[0],E.length>1&&` +${E.length-1}`]})})()]})]}),N&&x.length>0&&e.jsx("div",{className:"agent-tree__children",children:x.map(E=>e.jsx(bt,{node:E,onSelect:l,onToggle:j,isExpanded:h,getChildCount:o,getHealthStatus:c,getRoleIcon:r,getSkillBadges:m},E.agent.id))})]})}function xt({node:a,onSelect:l,getHealthStatus:j,getRoleIcon:h,getSkillBadges:o}){const{agent:c,children:r}=a,m=j(c),d=ze(c.state),x=Oe("org-chart-node-card",c.state);return e.jsxs("div",{className:`org-chart-node${r.length>0?" org-chart-node--has-children":""}`,children:[e.jsxs("div",{className:x,onClick:()=>l(c.id),role:"button",tabIndex:0,onKeyDown:p=>p.key==="Enter"&&l(c.id),children:[e.jsxs("div",{className:"org-chart-node__header",children:[e.jsx("span",{className:"org-chart-node__icon",children:h(c.role)}),e.jsx("span",{className:"org-chart-node__name",children:c.name})]}),e.jsxs("div",{className:"org-chart-node__meta",children:[e.jsx("span",{className:`org-chart-node__badge ${d}`,children:c.state}),e.jsxs("span",{className:"org-chart-node__health",style:{color:m.color},title:m.label,children:[m.icon,!m.stateDerived&&e.jsx("span",{className:"text-secondary",children:m.label})]}),(()=>{const p=o(c);if(p.length===0)return null;const b=p.slice(0,2),N=p.length-2;return e.jsxs(e.Fragment,{children:[b.map(I=>e.jsx("span",{className:"org-chart-node__skill",children:I},I)),N>0&&e.jsxs("span",{className:"org-chart-node__skill",children:["+",N]})]})})()]})]}),r.length>0&&e.jsx("div",{className:"org-chart-children",role:"group","aria-label":`${c.name} employees`,children:r.map(p=>e.jsx(xt,{node:p,onSelect:l,getHealthStatus:j,getRoleIcon:h,getSkillBadges:o},p.agent.id))})]})}function Jn({addToast:a,projectId:l,onOpenTaskLogs:j,agentOnboardingEnabled:h=!1}){const[o,c]=s.useState(!1),[r,m]=s.useState("all"),{agents:d,stats:x,isLoading:p,loadAgents:b}=Dt(l,{filterState:r,showSystemAgents:o}),[N,I]=s.useState(!1),[f,M]=s.useState(!1),[E,R]=s.useState(!1),[y,v]=s.useState(null),[C,P]=s.useState(()=>{if(typeof window>"u")return"list";const t=Je("fn-agent-view",l);return t==="list"||t==="board"||t==="tree"||t==="org"?t:"list"}),[B,Y]=s.useState([]),[H,ee]=s.useState(!1),[q,F]=s.useState(!1),w=s.useRef(null),{confirm:te}=zt(),re=s.useRef(null),ne=s.useId();s.useEffect(()=>{const t=Je("fn-agent-view",l);if(t==="list"||t==="board"||t==="tree"||t==="org"){P(t);return}P("list")},[l]),s.useEffect(()=>{dt("fn-agent-view",C,l)},[C,l]);const[se,G]=s.useState(null),de=s.useRef(null),[T,A]=s.useState(null),[ue,_]=s.useState(null),[z,W]=s.useState({}),[le,ke]=s.useState(1),[K,ae]=s.useState(!1),[Q,me]=s.useState(new Set),[ge,J]=s.useState(new Map),xe=s.useRef(!0);s.useEffect(()=>(xe.current=!0,()=>{xe.current=!1}),[]),s.useEffect(()=>{Ot(l).then(t=>{xe.current&&ke(t.heartbeatMultiplier??1)}).catch(()=>{})},[l]);const he=s.useCallback(async t=>{const u=Number.isFinite(t)&&t>0?t:1;ke(u),ae(!0);try{await Ht({heartbeatMultiplier:u},l),a(`Heartbeat speed set to ×${u.toFixed(1)}`,"success")}catch(n){a(`Failed to save heartbeat multiplier: ${je(n)}`,"error")}finally{xe.current&&ae(!1)}},[l,a]),pe=s.useMemo(()=>ge.size===0?d:d.map(t=>{const u=ge.get(t.id);return u?{...t,state:u}:t}),[d,ge]),be=wn(pe,l),D=s.useMemo(()=>pe.filter(t=>o||!We(t)),[pe,o]),U=s.useMemo(()=>pe.filter(t=>t.state!=="active"&&t.state!=="running"?!1:o||!We(t)),[pe,o]),ye=s.useMemo(()=>{if(o)return B;const t=u=>We(u.agent)?null:{...u,children:u.children.map(t).filter(n=>n!==null)};return B.map(t).filter(u=>u!==null)},[B,o]);s.useEffect(()=>{if(C!=="org")return;let t=!1;return ee(!0),qt(l,{includeEphemeral:o}).then(u=>{t||Y(u)}).catch(u=>{t||(a(`Failed to load org chart: ${je(u)}`,"error"),Y([]))}).finally(()=>{t||ee(!1)}),()=>{t=!0}},[C,l,o,a]),s.useEffect(()=>{const t=setInterval(()=>{b()},3e4);return()=>{clearInterval(t)}},[b]),s.useEffect(()=>{if(!q)return;const t=n=>{const g=n.target;g&&(w.current?.contains(g)||re.current?.contains(g)||F(!1))},u=n=>{n.key==="Escape"&&(F(!1),re.current?.focus())};return document.addEventListener("mousedown",t),document.addEventListener("touchstart",t),document.addEventListener("keydown",u),()=>{document.removeEventListener("mousedown",t),document.removeEventListener("touchstart",t),document.removeEventListener("keydown",u)}},[q]);const oe=async(t,u)=>{if(!Q.has(t)){me(n=>new Set(n).add(t)),J(n=>{const g=new Map(n);return g.set(t,u),g});try{await Yt(t,u,l),a(`Agent state updated to ${u}`,"success"),await b(),J(n=>{const g=new Map(n);return g.delete(t),g})}catch(n){J(g=>{const L=new Map(g);return L.delete(t),L}),a(`Failed to update state: ${je(n)}`,"error")}finally{me(n=>{const g=new Set(n);return g.delete(t),g})}}},Ne=async(t,u)=>{if(await te({title:"Delete Agent",message:`Delete agent "${u}"? This cannot be undone.`,danger:!0}))try{await tn(t,l),a(`Agent "${u}" deleted`,"success"),b()}catch(g){a(`Failed to delete agent: ${je(g)}`,"error")}},Re=async(t,u)=>{const n=d.find(g=>g.id===t);if(n){if(n.role===u){G(null);return}try{await _e(t,{role:u},l),a(`Agent role updated to ${Fe.find(g=>g.value===u)?.label??u}`,"success"),G(null),b()}catch(g){a(`Failed to update role: ${je(g)}`,"error")}}},Ae=(t,u)=>{t.key==="Escape"&&G(null)},fe=async(t,u)=>{ue===t.id&&(_(null),W(n=>{const g={...n};return delete g[t.id],g})),A(t.id);try{await _e(t.id,{runtimeConfig:{...t.runtimeConfig??{},heartbeatIntervalMs:u}},l),a(`Heartbeat interval updated to ${at(u)} for ${t.name}`,"success"),b()}catch(n){a(`Failed to update heartbeat interval: ${je(n)}`,"error")}finally{A(null)}},i=async t=>{const u=z[t.id]??"";if(u.trim()===""){a("Please enter a heartbeat interval in minutes","error");return}const n=Number(u);if(isNaN(n)){a("Heartbeat interval must be a valid number","error");return}if(n<=0){a("Heartbeat interval must be greater than 0","error");return}if(n>=1&&n<5){A(t.id);try{await _e(t.id,{runtimeConfig:{...t.runtimeConfig??{},heartbeatIntervalMs:Zt}},l),a(`Heartbeat interval set to 5 minutes (minimum). ${n} minute${n!==1?"s":""} was below the 5-minute minimum.`,"success"),_(null),W(L=>{const X={...L};return delete X[t.id],X}),b()}catch(L){a(`Failed to update heartbeat interval: ${je(L)}`,"error")}finally{A(null)}return}const g=Math.round(n*6e4);A(t.id);try{await _e(t.id,{runtimeConfig:{...t.runtimeConfig??{},heartbeatIntervalMs:g}},l),a(`Heartbeat interval updated to ${at(g)} for ${t.name}`,"success"),_(null),W(L=>{const X={...L};return delete X[t.id],X}),b()}catch(L){a(`Failed to update heartbeat interval: ${je(L)}`,"error")}finally{A(null)}},k=t=>{const u=Ge(t.runtimeConfig?.heartbeatIntervalMs),n=Math.round(u/6e4);_(t.id),W(g=>({...g,[t.id]:String(n)}))},$=s.useCallback(()=>{v(null)},[]),ie=s.useCallback(t=>{v(t)},[]),V=async(t,u)=>{try{await en(t,l,{source:"on_demand",triggerDetail:"Triggered from dashboard"}),a(`Heartbeat run started for ${u}`,"success"),b()}catch(n){a(`Failed to start heartbeat run: ${je(n)}`,"error")}},O=t=>Fe.find(u=>u.value===t)?.label??t,ve=t=>Fe.find(u=>u.value===t)?.icon??"◆",Ce=t=>Array.isArray(t.metadata?.skills)?t.metadata.skills:[],Se=t=>Xt(t),Ee=p&&d.length===0,we=s.useCallback(()=>{if(h){M(!0);return}I(!0)},[h]);return e.jsxs("div",{className:"agents-view",children:[e.jsxs("div",{className:"agents-view-header",children:[e.jsxs("div",{className:"agents-view-title",children:[e.jsx(Ze,{size:24}),e.jsx("h2",{children:"Agents"})]}),e.jsxs("div",{className:"agents-view-controls",children:[e.jsxs("div",{className:"view-toggle",children:[e.jsx("button",{className:`view-toggle-btn${C==="list"?" active":""}`,onClick:()=>P("list"),title:"List view","aria-label":"List view","aria-pressed":C==="list",children:e.jsx(Vt,{size:16})}),e.jsx("button",{className:`view-toggle-btn${C==="board"?" active":""}`,onClick:()=>P("board"),title:"Board view","aria-label":"Board view","aria-pressed":C==="board",children:e.jsx(Me,{size:16})}),e.jsx("button",{className:`view-toggle-btn${C==="tree"?" active":""}`,onClick:()=>P("tree"),title:"Tree view","aria-label":"Tree view","aria-pressed":C==="tree",children:e.jsx(Wt,{size:16})}),e.jsx("button",{className:`view-toggle-btn${C==="org"?" active":""}`,onClick:()=>P("org"),title:"Org Chart view","aria-label":"Org Chart view","aria-pressed":C==="org",children:e.jsx(cn,{size:16})})]}),e.jsxs("div",{className:"agents-view-primary-actions",children:[e.jsx("button",{ref:re,className:`btn-icon agent-controls-trigger${q?" agent-controls-trigger--active":""}`,onClick:()=>F(t=>!t),title:"Controls","aria-label":"Controls","aria-haspopup":"dialog","aria-expanded":q,"aria-controls":ne,children:e.jsx(un,{size:16})}),e.jsx("button",{className:"btn-icon",onClick:()=>void b(),title:"Refresh","aria-label":"Refresh",children:e.jsx(De,{size:16,className:p?"spin":void 0})}),e.jsxs("button",{className:"btn btn-task-create btn-sm",onClick:()=>{we(),F(!1)},children:[e.jsx(Kt,{size:16}),"New Agent"]})]})]})]}),q&&e.jsxs("div",{ref:w,id:ne,className:"agent-controls-panel agent-controls-panel--scrollable",role:"dialog","aria-label":"Agent controls","aria-modal":"false",children:[e.jsxs("div",{className:"agent-controls",children:[e.jsxs("div",{className:"agent-controls-filters",children:[e.jsxs("div",{className:"agent-state-filter",children:[e.jsx(Ut,{size:14}),e.jsxs("select",{className:"agent-state-filter-select",value:r,onChange:t=>m(t.target.value),"aria-label":"Filter agents by state",children:[e.jsx("option",{value:"all",children:"All States"}),e.jsx("option",{value:"idle",children:"Idle"}),e.jsx("option",{value:"active",children:"Active"}),e.jsx("option",{value:"running",children:"Running"}),e.jsx("option",{value:"paused",children:"Paused"}),e.jsx("option",{value:"error",children:"Error"}),e.jsx("option",{value:"terminated",children:"Terminated"})]})]}),e.jsxs("label",{className:"checkbox-label agent-system-filter",children:[e.jsx("input",{type:"checkbox",checked:o,onChange:t=>c(t.target.checked),"aria-label":"Show system agents"}),"Show system agents"]})]}),e.jsx("div",{className:"agent-controls-actions",children:e.jsxs("button",{className:"btn",onClick:()=>{R(!0),F(!1)},children:[e.jsx(pt,{size:16}),"Import"]})})]}),e.jsx("div",{className:"agent-global-controls",children:e.jsxs("div",{className:"heartbeat-multiplier-group",children:[e.jsxs("div",{className:"heartbeat-multiplier-controls",children:[e.jsx("label",{htmlFor:"globalHeartbeatMultiplier",className:"heartbeat-multiplier-label",children:"Heartbeat Speed"}),e.jsx("input",{id:"globalHeartbeatMultiplier",className:"heartbeat-multiplier-slider touch-target",type:"range",min:.1,max:10,step:.1,value:le,onChange:t=>{const u=Number(t.target.value);he(Number.isFinite(u)&&u>0?u:1)},disabled:K}),e.jsxs("span",{className:"heartbeat-multiplier-value",children:["×",le.toFixed(1)]}),e.jsx("select",{className:"heartbeat-multiplier-preset",value:String(Be.reduce((t,u)=>Math.abs(u-le)<Math.abs(t-le)?u:t,Be[0])),onChange:t=>{const u=Number(t.target.value);he(Number.isFinite(u)&&u>0?u:1)},disabled:K,"aria-label":"Heartbeat speed preset",children:Be.map(t=>e.jsxs("option",{value:String(t),children:["×",t]},t))})]}),e.jsx("small",{className:"text-secondary",children:"Scales all agent heartbeat intervals. ×0.5 = twice as fast, ×2.0 = twice as slow. Default: ×1.0"})]})}),e.jsx(bn,{agents:D})]}),e.jsxs("div",{className:"agents-view-content",children:[e.jsx(vn,{stats:x}),e.jsx(pn,{agents:U,projectId:l,onAgentSelect:v,onOpenTaskLogs:j}),e.jsx(Kn,{isOpen:N,onClose:()=>I(!1),onCreated:()=>{I(!1),b()},projectId:l}),e.jsx(Un,{isOpen:f,onClose:()=>M(!1),onCreated:()=>{M(!1),b()},addToast:a,projectId:l,existingAgents:d}),e.jsx(Gn,{isOpen:E,onClose:()=>R(!1),onImported:()=>void b(),projectId:l}),Ee?e.jsxs("div",{className:"agents-view-loading",role:"status","aria-live":"polite",children:[e.jsx(De,{size:18,className:"spin"}),e.jsx("span",{children:"Loading agents..."})]}):C==="tree"?e.jsx("div",{className:"agent-tree__view",children:D.length===0?e.jsx($e,{onCtaClick:we}):be.rootNodes.map(t=>e.jsx(bt,{node:t,onSelect:v,onToggle:be.toggleExpand,isExpanded:be.isExpanded,getChildCount:u=>be.getChildren(u).length,getHealthStatus:Se,getRoleIcon:ve,getSkillBadges:Ce},t.agent.id))}):C==="org"?e.jsx("div",{className:"agent-org-chart","data-testid":"agent-org-chart",children:H?e.jsxs("div",{className:"agent-org-chart__loading",role:"status","aria-live":"polite",children:[e.jsx(De,{size:18,className:"spin"}),e.jsx("span",{children:"Loading org chart..."})]}):ye.length===0?e.jsx($e,{onCtaClick:we}):ye.map(t=>e.jsx(xt,{node:t,onSelect:v,getHealthStatus:Se,getRoleIcon:ve,getSkillBadges:Ce},t.agent.id))}):C==="board"?e.jsx("div",{className:"agent-board",children:D.length===0?e.jsx($e,{onCtaClick:we}):D.map(t=>{const u=Se(t),n=ze(t.state),g=Oe("agent-board-card",t.state);return e.jsx("div",{className:`agent-board-card ${g}`,children:e.jsxs("div",{className:"agent-board-clickable",onClick:()=>v(t.id),role:"button",tabIndex:0,onKeyDown:L=>L.key==="Enter"&&v(t.id),children:[e.jsxs("div",{className:"agent-board-header",children:[e.jsx("span",{className:"agent-board-icon",children:ve(t.role)}),e.jsx("span",{className:"agent-board-badge badge text-secondary",children:O(t.role)}),e.jsx("span",{className:`agent-board-badge badge ${n}`,children:t.state})]}),e.jsx("div",{className:"agent-board-name",children:t.name}),e.jsx("div",{className:"agent-board-id",children:t.id}),e.jsxs("div",{className:"agent-board-health",style:{color:u.color},title:u.label,children:[u.icon,!u.stateDerived&&` ${u.label}`]})]})},t.id)})}):e.jsx("div",{className:"agent-list",children:D.length===0?e.jsx($e,{onCtaClick:we}):D.map(t=>{const u=Se(t),n=ze(t.state),g=Oe("agent-card",t.state),L=Ge(t.runtimeConfig?.heartbeatIntervalMs),X=Bt(L),ce=T===t.id;return e.jsxs("div",{className:`agent-card ${g}`,children:[e.jsxs("div",{className:"agent-card-header",children:[e.jsxs("div",{className:"agent-info agent-info--clickable",onClick:()=>v(t.id),role:"button",tabIndex:0,onKeyDown:S=>S.key==="Enter"&&v(t.id),children:[se===t.id?e.jsx("select",{ref:de,className:"select agent-role-select",value:t.role,onChange:S=>void Re(t.id,S.target.value),onKeyDown:S=>Ae(S,t.id),onBlur:()=>G(null),autoFocus:!0,children:Fe.map(S=>e.jsxs("option",{value:S.value,children:[S.icon," ",S.label]},S.value))}):e.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:S=>{S.stopPropagation(),G(t.id)},title:"Click to change role",role:"button",tabIndex:0,onKeyDown:S=>{(S.key==="Enter"||S.key===" ")&&(S.stopPropagation(),G(t.id))},children:ve(t.role)}),e.jsxs("div",{className:"agent-meta",children:[e.jsx("span",{className:"agent-name",children:t.name}),e.jsx("span",{className:"agent-id text-secondary",children:t.id})]}),e.jsx(ht,{size:20,className:"agent-card-chevron"})]}),e.jsxs("div",{className:"agent-badges",children:[e.jsx("span",{className:`badge ${n}`,children:t.state}),e.jsxs("span",{className:"badge",style:{color:u.color},title:u.label,children:[u.icon,!u.stateDerived&&` ${u.label}`]}),e.jsx("span",{className:"badge text-secondary",children:O(t.role)}),(()=>{const S=Ce(t);if(S.length===0)return null;const Z=S.slice(0,2),Ie=S.length-2;return e.jsxs(e.Fragment,{children:[Z.map(Ye=>e.jsx("span",{className:"badge badge-skill",children:Ye},Ye)),Ie>0&&e.jsxs("span",{className:"badge badge-skill",children:["+",Ie]})]})})()]})]}),e.jsxs("div",{className:"agent-card-body",children:[t.taskId&&e.jsxs("div",{className:"agent-task",children:[e.jsx("span",{className:"text-secondary",children:"Working on:"}),e.jsx("span",{className:"badge",children:t.taskId})]}),e.jsxs("div",{className:"agent-heartbeat-control",children:[e.jsx("span",{className:"text-secondary",children:"Heartbeat:"}),ue===t.id?e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"input agent-heartbeat-custom-input",value:z[t.id]??"",onChange:S=>W(Z=>({...Z,[t.id]:S.target.value})),onKeyDown:S=>{S.key==="Enter"?i(t):S.key==="Escape"&&(_(null),W(Z=>{const Ie={...Z};return delete Ie[t.id],Ie}))},disabled:ce,"aria-label":`Custom heartbeat interval in minutes for ${t.name}`}),e.jsx("span",{className:"text-secondary",children:"min"}),e.jsx("button",{className:"btn btn--sm",onClick:()=>void i(t),disabled:ce,title:"Save custom interval",children:"Save"}),e.jsx("button",{className:"btn btn--sm",onClick:()=>{_(null),W(S=>{const Z={...S};return delete Z[t.id],Z})},disabled:ce,title:"Cancel custom interval",children:"Cancel"})]}):e.jsx(e.Fragment,{children:e.jsxs("select",{className:"select agent-heartbeat-select",value:L,onChange:S=>{const Z=S.target.value;Z==="__custom__"?k(t):fe(t,Number(Z))},disabled:ce,"aria-label":`Set heartbeat interval for ${t.name}`,children:[X.map(S=>e.jsx("option",{value:S.value,children:S.label},S.value)),Gt.some(S=>S.value===L)&&e.jsx("option",{value:"__custom__",children:"Custom..."})]})}),ce&&e.jsx("span",{className:"agent-heartbeat-saving text-secondary",children:"Saving…"}),t.lastHeartbeatAt&&(()=>{const S=new Date(t.lastHeartbeatAt),Z=new Date(S.getTime()+L),Ie=t.state==="active"||t.state==="running";return e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"agent-heartbeat-last text-secondary",title:S.toLocaleString(),children:["Last: ",S.toLocaleTimeString()]}),Ie&&e.jsxs("span",{className:"agent-heartbeat-next text-secondary",title:Z.toLocaleString(),children:["Next: ",Z.toLocaleTimeString()]})]})})()]})]}),e.jsxs("div",{className:"agent-card-actions",children:[t.state==="idle"&&e.jsxs("button",{className:"btn btn--sm",onClick:()=>void oe(t.id,"active"),disabled:Q.has(t.id),title:"Activate",children:[e.jsx(Pe,{size:14})," Start"]}),t.state==="active"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void V(t.id,t.name),disabled:Q.has(t.id),title:"Run Now","aria-label":`Run now for ${t.name}`,children:[e.jsx(Me,{size:14})," Run Now"]}),e.jsxs("button",{className:"btn btn--sm",onClick:()=>void oe(t.id,"paused"),disabled:Q.has(t.id),title:"Pause",children:[e.jsx(st,{size:14})," Pause"]})]}),t.state==="paused"&&e.jsxs("button",{className:"btn btn--sm",onClick:()=>void oe(t.id,"active"),disabled:Q.has(t.id),title:"Resume",children:[e.jsx(Pe,{size:14})," Resume"]}),t.state==="running"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",disabled:!0,title:"Run in progress","aria-label":`Heartbeat run in progress for ${t.name}`,children:[e.jsx(Me,{size:14})," Running"]}),e.jsxs("button",{className:"btn btn--sm",onClick:()=>void oe(t.id,"paused"),disabled:Q.has(t.id),title:"Pause",children:[e.jsx(st,{size:14})," Pause"]})]}),t.state==="error"&&e.jsxs("button",{className:"btn btn--sm",onClick:()=>void oe(t.id,"active"),disabled:Q.has(t.id),title:"Retry",children:[e.jsx(Pe,{size:14})," Retry"]}),t.state==="terminated"&&e.jsxs("button",{className:"btn btn--sm",onClick:()=>void oe(t.id,"active"),disabled:Q.has(t.id),title:"Start",children:[e.jsx(Pe,{size:14})," Start"]}),e.jsx("button",{className:"btn btn--sm agent-card-details-btn",onClick:()=>v(t.id),title:`View details for ${t.name}`,"aria-label":`View details for ${t.name}`,children:"View Details"}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void Ne(t.id,t.name),title:"Delete",children:[e.jsx(Qt,{size:14})," Delete"]})]})]},t.id)})})]}),y&&e.jsx(s.Suspense,{fallback:null,children:e.jsx(Qn,{agentId:y,projectId:l,onClose:$,addToast:a,onChildClick:ie})})]})}const ts=Object.freeze(Object.defineProperty({__proto__:null,AgentsView:Jn},Symbol.toStringTag,{value:"Module"}));export{ts as A,Vn as S};
522
+ Agent instructions go here...`,value:d,onChange:i=>{m("paste"),v([]),y(i.target.value),$(null)},rows:8,"aria-label":"Manifest content"})]}),e.jsxs("p",{className:"agent-import-file-hint",children:["Current input: ",r]}),q&&e.jsxs("p",{className:"agent-dialog-error",children:[e.jsx(Ve,{size:14}),q]})]}),o==="preview"&&e.jsxs("div",{className:"agent-import-preview",children:[e.jsxs("div",{className:"agent-import-company",children:[e.jsx("span",{className:"agent-import-company-label",children:"Company"}),e.jsx("span",{className:"agent-import-company-name",children:N})]}),e.jsxs("div",{className:"agent-import-count",children:[e.jsx(Qe,{size:14}),e.jsxs("span",{children:[R.length," agent",R.length!==1?"s":""," found"]})]}),R.length>0&&e.jsxs("div",{className:"agent-import-selection-controls",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>f(R.map(i=>i.name)),children:"Select all agents"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>f([]),children:"Clear agents"})]}),R.length>0?e.jsx("div",{className:"agent-import-agent-list",children:R.map((i,w)=>e.jsxs("div",{className:"agent-import-agent-item",children:[e.jsx("label",{className:"checkbox-label",children:e.jsx("input",{type:"checkbox","aria-label":`Select agent ${i.name}`,checked:b.includes(i.name),onChange:()=>Ae(i.name)})}),e.jsx("span",{className:"agent-import-agent-icon",children:i.icon||"🤖"}),e.jsxs("div",{className:"agent-import-agent-details",children:[e.jsx("span",{className:"agent-import-agent-name",children:i.name}),e.jsxs("span",{className:"agent-import-agent-meta",children:[i.title&&e.jsxs("span",{className:"agent-import-agent-title",children:[i.title," · "]}),e.jsx("span",{className:"agent-import-agent-role",children:i.role}),i.reportsTo&&e.jsxs("span",{className:"agent-import-agent-reports",children:[" · reports to ",i.reportsTo]}),i.skills&&i.skills.length>0&&e.jsxs("span",{className:"agent-import-agent-model",children:[" · skills: ",i.skills.join(", ")]})]}),i.instructionsText&&e.jsxs("span",{className:"agent-import-agent-instructions",children:[i.instructionsText.slice(0,100),i.instructionsText.length>100?"...":""]})]})]},w))}):e.jsx("p",{className:"agent-import-empty",children:"No agents found in the manifest."}),E.length>0&&e.jsxs("div",{className:"agent-import-skills-section",children:[e.jsxs("div",{className:"agent-import-count",children:[e.jsx(Qe,{size:14}),e.jsxs("span",{children:[E.length," skill",E.length!==1?"s":""," found"]})]}),e.jsxs("div",{className:"agent-import-selection-controls",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>P(E.map(i=>i.name)),children:"Select all skills"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>P([]),children:"Clear skills"})]}),e.jsx("div",{className:"agent-import-skill-list",children:E.map((i,w)=>e.jsxs("div",{className:"agent-import-skill-item",children:[e.jsx("label",{className:"checkbox-label",children:e.jsx("input",{type:"checkbox","aria-label":`Select skill ${i.name}`,checked:k.includes(i.name),onChange:()=>fe(i.name)})}),e.jsx("span",{className:"agent-import-skill-icon",children:"⚡"}),e.jsxs("div",{className:"agent-import-skill-details",children:[e.jsx("span",{className:"agent-import-skill-name",children:i.name}),i.description&&e.jsx("span",{className:"agent-import-skill-description",children:i.description})]})]},`${i.name}-${w}`))})]}),re&&e.jsxs("p",{className:"agent-dialog-error",children:[e.jsx(Ve,{size:14}),re]})]}),o==="result"&&x&&e.jsxs("div",{className:"agent-import-result",children:[e.jsx("div",{className:"agent-import-result-icon",children:e.jsx(De,{size:32})}),e.jsx("h3",{className:"agent-import-result-title",children:"Import Complete"}),e.jsxs("p",{className:"agent-import-result-company",children:["From ",e.jsx("strong",{children:x.companyName??"Unknown"})]}),e.jsxs("div",{className:"agent-import-result-stats",children:[x.created.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--success",children:e.jsxs("span",{children:[x.created.length," created"]})}),x.skipped.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--skipped",children:e.jsxs("span",{children:[x.skipped.length," skipped (already exist)"]})}),x.errors.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--error",children:e.jsxs("span",{children:[x.errors.length," error",x.errors.length!==1?"s":""]})})]}),x.created.length>0&&e.jsx("div",{className:"agent-import-result-agents",children:x.created.map((i,w)=>e.jsxs("div",{className:"agent-import-result-agent",children:[e.jsx(De,{size:12}),e.jsx("span",{children:i.name})]},w))}),x.errors.length>0&&e.jsx("div",{className:"agent-import-result-errors",children:x.errors.map((i,w)=>e.jsxs("div",{className:"agent-import-result-error",children:[e.jsx(nt,{size:12}),e.jsxs("span",{children:[i.name,": ",i.error]})]},w))}),x.skills&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"agent-import-result-divider"}),e.jsx("h4",{className:"agent-import-result-section-title",children:"Skills"}),e.jsxs("div",{className:"agent-import-result-stats",children:[x.skills.imported.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--success",children:e.jsxs("span",{children:[x.skills.imported.length," skill",x.skills.imported.length!==1?"s":""," imported"]})}),x.skills.skipped.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--skipped",children:e.jsxs("span",{children:[x.skills.skipped.length," skill",x.skills.skipped.length!==1?"s":""," skipped (already exist)"]})}),x.skills.errors.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--error",children:e.jsxs("span",{children:[x.skills.errors.length," skill",x.skills.errors.length!==1?"s":""," error",x.skills.errors.length!==1?"s":""]})}),x.skills.imported.length===0&&x.skills.skipped.length===0&&x.skills.errors.length===0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--skipped",children:e.jsx("span",{children:"No skills in package"})})]}),x.skills.imported.length>0&&e.jsx("div",{className:"agent-import-result-agents",children:x.skills.imported.map((i,w)=>e.jsxs("div",{className:"agent-import-result-agent",children:[e.jsx(De,{size:12}),e.jsx("span",{children:i.name})]},w))}),x.skills.errors.length>0&&e.jsx("div",{className:"agent-import-result-errors",children:x.skills.errors.map((i,w)=>e.jsxs("div",{className:"agent-import-result-error",children:[e.jsx(nt,{size:12}),e.jsxs("span",{children:[i.name,": ",i.error]})]},w))})]})]})]}),e.jsxs("div",{className:"agent-dialog-footer",children:[o==="preview"&&e.jsx("button",{className:"btn",onClick:()=>u("input"),disabled:H,children:"Back"}),e.jsx("button",{className:"btn",onClick:ge,disabled:H,children:o==="result"?"Close":"Cancel"}),o==="input"&&e.jsx("button",{className:"btn btn-task-create",onClick:()=>void pe(),disabled:B||(r==="directory"?p.length===0:r==="browse"?!_:!d.trim()),children:B?e.jsxs(e.Fragment,{children:[e.jsx(qe,{size:14,className:"spin"}),"Parsing..."]}):"Preview"}),o==="preview"&&e.jsx("button",{className:"btn btn-task-create",onClick:()=>void be(),disabled:H||L===0&&U===0,children:H?e.jsxs(e.Fragment,{children:[e.jsx(qe,{size:14,className:"spin"}),Re]}):`Import ${Ne}`})]})]})}):null}const Gn=a.lazy(()=>tn(()=>import("./AgentDetailView-B20ApPe1.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10])).then(s=>({default:s.AgentDetailView}))),$e=[{value:"triage",label:"Triage",icon:"⊕"},{value:"executor",label:"Executor",icon:"▶"},{value:"reviewer",label:"Reviewer",icon:"⊙"},{value:"merger",label:"Merger",icon:"⊞"},{value:"scheduler",label:"Scheduler",icon:"◷"},{value:"engineer",label:"Engineer",icon:"⎔"},{value:"custom",label:"Custom",icon:"✦"}],Be=[.1,.25,.5,1,2,3,5,10];function ze(s){switch(s){case"running":return"agent-badge--running";case"active":return"agent-badge--active";case"paused":return"agent-badge--paused";case"error":return"agent-badge--error";case"terminated":return"agent-badge--terminated";case"idle":default:return"agent-badge--idle"}}function Oe(s,l){switch(l){case"running":return`${s}--running`;case"active":return`${s}--active`;case"paused":return`${s}--paused`;case"error":return`${s}--error`;case"terminated":return`${s}--terminated`;case"idle":default:return`${s}--idle`}}function bt({node:s,onSelect:l,onToggle:j,isExpanded:h,getChildCount:o,getHealthStatus:u,getRoleIcon:r,getSkillBadges:m}){const{agent:d,children:y,depth:p}=s,v=o(d.id),N=h(d.id),S=u(d),R=ze(d.state),M=Oe("agent-tree__node",d.state);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`${M}${d.reportsTo?" agent-is-child":""} agent-tree__indent--${Math.min(p,4)}`,children:[e.jsx("button",{className:`agent-tree__toggle${v===0?" agent-tree__toggle--leaf":""}`,onClick:()=>v>0&&j(d.id),title:v>0?N?"Collapse":"Expand":"No employees","aria-label":v>0?N?"Collapse":"Expand":"No employees",children:v>0?N?e.jsx(Qt,{size:16}):e.jsx(ht,{size:16}):e.jsx(Ze,{size:14})}),e.jsxs("div",{className:"agent-tree__content",onClick:()=>l(d.id),role:"button",tabIndex:0,onKeyDown:E=>E.key==="Enter"&&l(d.id),children:[e.jsx("span",{className:"agent-tree__icon",children:r(d.role)}),e.jsx("span",{className:"agent-tree__name",children:d.name}),e.jsx("span",{className:`agent-tree__badge ${R}`,children:d.state}),e.jsx("span",{className:"agent-tree__health",style:{color:S.color},title:S.label,children:S.icon}),v>0&&e.jsxs("span",{className:"agent-tree__count text-secondary",children:["(",v,")"]}),(()=>{const E=m(d);return E.length===0?null:e.jsxs("span",{className:"agent-tree__skill",title:E.join(", "),children:[E[0],E.length>1&&` +${E.length-1}`]})})()]})]}),N&&y.length>0&&e.jsx("div",{className:"agent-tree__children",children:y.map(E=>e.jsx(bt,{node:E,onSelect:l,onToggle:j,isExpanded:h,getChildCount:o,getHealthStatus:u,getRoleIcon:r,getSkillBadges:m},E.agent.id))})]})}function xt({node:s,onSelect:l,getHealthStatus:j,getRoleIcon:h,getSkillBadges:o}){const{agent:u,children:r}=s,m=j(u),d=ze(u.state),y=Oe("org-chart-node-card",u.state);return e.jsxs("div",{className:`org-chart-node${r.length>0?" org-chart-node--has-children":""}`,children:[e.jsxs("div",{className:y,onClick:()=>l(u.id),role:"button",tabIndex:0,onKeyDown:p=>p.key==="Enter"&&l(u.id),children:[e.jsxs("div",{className:"org-chart-node__header",children:[e.jsx("span",{className:"org-chart-node__icon",children:h(u.role)}),e.jsx("span",{className:"org-chart-node__name",children:u.name})]}),e.jsxs("div",{className:"org-chart-node__meta",children:[e.jsx("span",{className:`org-chart-node__badge ${d}`,children:u.state}),e.jsxs("span",{className:"org-chart-node__health",style:{color:m.color},title:m.label,children:[m.icon,!m.stateDerived&&e.jsx("span",{className:"text-secondary",children:m.label})]}),(()=>{const p=o(u);if(p.length===0)return null;const v=p.slice(0,2),N=p.length-2;return e.jsxs(e.Fragment,{children:[v.map(S=>e.jsx("span",{className:"org-chart-node__skill",children:S},S)),N>0&&e.jsxs("span",{className:"org-chart-node__skill",children:["+",N]})]})})()]})]}),r.length>0&&e.jsx("div",{className:"org-chart-children",role:"group","aria-label":`${u.name} employees`,children:r.map(p=>e.jsx(xt,{node:p,onSelect:l,getHealthStatus:j,getRoleIcon:h,getSkillBadges:o},p.agent.id))})]})}function ta({addToast:s,projectId:l,onOpenTaskLogs:j,agentOnboardingEnabled:h=!1}){const[o,u]=a.useState(!1),[r,m]=a.useState("all"),{agents:d,stats:y,isLoading:p,loadAgents:v}=Dt(l,{filterState:r,showSystemAgents:o}),[N,S]=a.useState(!1),[R,M]=a.useState(!1),[E,T]=a.useState(!1),[b,f]=a.useState(null),[k,P]=a.useState(()=>{if(typeof window>"u")return"list";const t=Je("fn-agent-view",l);return t==="list"||t==="board"||t==="tree"||t==="org"?t:"list"}),[B,Y]=a.useState([]),[H,ee]=a.useState(!1),[q,$]=a.useState(!1),x=a.useRef(null),{confirm:te}=Lt(),re=a.useRef(null),ne=a.useId();a.useEffect(()=>{const t=Je("fn-agent-view",l);if(t==="list"||t==="board"||t==="tree"||t==="org"){P(t);return}P("list")},[l]),a.useEffect(()=>{dt("fn-agent-view",k,l)},[k,l]);const[ae,G]=a.useState(null),de=a.useRef(null),[A,I]=a.useState(null),[ue,_]=a.useState(null),[z,W]=a.useState({}),[le,ke]=a.useState(1),[K,se]=a.useState(!1),[Q,me]=a.useState(new Set),[ge,J]=a.useState(new Map),xe=a.useRef(!0);a.useEffect(()=>(xe.current=!0,()=>{xe.current=!1}),[]),a.useEffect(()=>{zt(l).then(t=>{xe.current&&ke(t.heartbeatMultiplier??1)}).catch(()=>{})},[l]);const he=a.useCallback(async t=>{const c=Number.isFinite(t)&&t>0?t:1;ke(c),se(!0);try{await Ot({heartbeatMultiplier:c},l),s(`Heartbeat speed set to ×${c.toFixed(1)}`,"success")}catch(n){s(`Failed to save heartbeat multiplier: ${je(n)}`,"error")}finally{xe.current&&se(!1)}},[l,s]),pe=a.useMemo(()=>ge.size===0?d:d.map(t=>{const c=ge.get(t.id);return c?{...t,state:c}:t}),[d,ge]),be=wn(pe,l),L=a.useMemo(()=>pe.filter(t=>o||!We(t)),[pe,o]),U=a.useMemo(()=>pe.filter(t=>t.state!=="active"&&t.state!=="running"?!1:o||!We(t)),[pe,o]),ye=a.useMemo(()=>{if(o)return B;const t=c=>We(c.agent)?null:{...c,children:c.children.map(t).filter(n=>n!==null)};return B.map(t).filter(c=>c!==null)},[B,o]);a.useEffect(()=>{if(k!=="org")return;let t=!1;return ee(!0),Ht(l,{includeEphemeral:o}).then(c=>{t||Y(c)}).catch(c=>{t||(s(`Failed to load org chart: ${je(c)}`,"error"),Y([]))}).finally(()=>{t||ee(!1)}),()=>{t=!0}},[k,l,o,s]),a.useEffect(()=>{const t=setInterval(()=>{v()},3e4);return()=>{clearInterval(t)}},[v]),a.useEffect(()=>{if(!q)return;const t=n=>{const g=n.target;g&&(x.current?.contains(g)||re.current?.contains(g)||$(!1))},c=n=>{n.key==="Escape"&&($(!1),re.current?.focus())};return document.addEventListener("mousedown",t),document.addEventListener("touchstart",t),document.addEventListener("keydown",c),()=>{document.removeEventListener("mousedown",t),document.removeEventListener("touchstart",t),document.removeEventListener("keydown",c)}},[q]);const oe=async(t,c)=>{if(!Q.has(t)){me(n=>new Set(n).add(t)),J(n=>{const g=new Map(n);return g.set(t,c),g});try{await Zt(t,c,l),s(`Agent state updated to ${c}`,"success"),await v(),J(n=>{const g=new Map(n);return g.delete(t),g})}catch(n){J(g=>{const D=new Map(g);return D.delete(t),D}),s(`Failed to update state: ${je(n)}`,"error")}finally{me(n=>{const g=new Set(n);return g.delete(t),g})}}},Ne=async(t,c)=>{if(await te({title:"Delete Agent",message:`Delete agent "${c}"? This cannot be undone.`,danger:!0}))try{await en(t,l),s(`Agent "${c}" deleted`,"success"),v()}catch(g){s(`Failed to delete agent: ${je(g)}`,"error")}},Re=async(t,c)=>{const n=d.find(g=>g.id===t);if(n){if(n.role===c){G(null);return}try{await _e(t,{role:c},l),s(`Agent role updated to ${$e.find(g=>g.value===c)?.label??c}`,"success"),G(null),v()}catch(g){s(`Failed to update role: ${je(g)}`,"error")}}},Ae=(t,c)=>{t.key==="Escape"&&G(null)},fe=async(t,c)=>{ue===t.id&&(_(null),W(n=>{const g={...n};return delete g[t.id],g})),I(t.id);try{await _e(t.id,{runtimeConfig:{...t.runtimeConfig??{},heartbeatIntervalMs:c}},l),s(`Heartbeat interval updated to ${st(c)} for ${t.name}`,"success"),v()}catch(n){s(`Failed to update heartbeat interval: ${je(n)}`,"error")}finally{I(null)}},i=async t=>{const c=z[t.id]??"";if(c.trim()===""){s("Please enter a heartbeat interval in minutes","error");return}const n=Number(c);if(isNaN(n)){s("Heartbeat interval must be a valid number","error");return}if(n<=0){s("Heartbeat interval must be greater than 0","error");return}if(n>=1&&n<5){I(t.id);try{await _e(t.id,{runtimeConfig:{...t.runtimeConfig??{},heartbeatIntervalMs:Xt}},l),s(`Heartbeat interval set to 5 minutes (minimum). ${n} minute${n!==1?"s":""} was below the 5-minute minimum.`,"success"),_(null),W(D=>{const X={...D};return delete X[t.id],X}),v()}catch(D){s(`Failed to update heartbeat interval: ${je(D)}`,"error")}finally{I(null)}return}const g=Math.round(n*6e4);I(t.id);try{await _e(t.id,{runtimeConfig:{...t.runtimeConfig??{},heartbeatIntervalMs:g}},l),s(`Heartbeat interval updated to ${st(g)} for ${t.name}`,"success"),_(null),W(D=>{const X={...D};return delete X[t.id],X}),v()}catch(D){s(`Failed to update heartbeat interval: ${je(D)}`,"error")}finally{I(null)}},w=t=>{const c=Ge(t.runtimeConfig?.heartbeatIntervalMs),n=Math.round(c/6e4);_(t.id),W(g=>({...g,[t.id]:String(n)}))},F=a.useCallback(()=>{f(null)},[]),ie=a.useCallback(t=>{f(t)},[]),V=async(t,c)=>{try{await Yt(t,l,{source:"on_demand",triggerDetail:"Triggered from dashboard"}),s(`Heartbeat run started for ${c}`,"success"),v()}catch(n){s(`Failed to start heartbeat run: ${je(n)}`,"error")}},O=t=>$e.find(c=>c.value===t)?.label??t,ve=t=>$e.find(c=>c.value===t)?.icon??"◆",Ce=t=>Array.isArray(t.metadata?.skills)?t.metadata.skills:[],Ie=t=>Jt(t),Ee=p&&d.length===0,we=a.useCallback(()=>{if(h){M(!0);return}S(!0)},[h]);return e.jsxs("div",{className:"agents-view",children:[e.jsxs("div",{className:"agents-view-header",children:[e.jsxs("div",{className:"agents-view-title",children:[e.jsx(Ze,{size:24}),e.jsx("h2",{children:"Agents"})]}),e.jsxs("div",{className:"agents-view-controls",children:[e.jsxs("div",{className:"view-toggle",children:[e.jsx("button",{className:`view-toggle-btn${k==="list"?" active":""}`,onClick:()=>P("list"),title:"List view","aria-label":"List view","aria-pressed":k==="list",children:e.jsx(qt,{size:16})}),e.jsx("button",{className:`view-toggle-btn${k==="board"?" active":""}`,onClick:()=>P("board"),title:"Board view","aria-label":"Board view","aria-pressed":k==="board",children:e.jsx(Me,{size:16})}),e.jsx("button",{className:`view-toggle-btn${k==="tree"?" active":""}`,onClick:()=>P("tree"),title:"Tree view","aria-label":"Tree view","aria-pressed":k==="tree",children:e.jsx(Vt,{size:16})}),e.jsx("button",{className:`view-toggle-btn${k==="org"?" active":""}`,onClick:()=>P("org"),title:"Org Chart view","aria-label":"Org Chart view","aria-pressed":k==="org",children:e.jsx(cn,{size:16})})]}),e.jsxs("div",{className:"agents-view-primary-actions",children:[e.jsx("button",{ref:re,className:`btn-icon agent-controls-trigger${q?" agent-controls-trigger--active":""}`,onClick:()=>$(t=>!t),title:"Controls","aria-label":"Controls","aria-haspopup":"dialog","aria-expanded":q,"aria-controls":ne,children:e.jsx(un,{size:16})}),e.jsx("button",{className:"btn-icon",onClick:()=>void v(),title:"Refresh","aria-label":"Refresh",children:e.jsx(Le,{size:16,className:p?"spin":void 0})}),e.jsxs("button",{className:"btn btn-task-create btn-sm",onClick:()=>{we(),$(!1)},children:[e.jsx(Wt,{size:16}),"New Agent"]})]})]})]}),q&&e.jsxs("div",{ref:x,id:ne,className:"agent-controls-panel agent-controls-panel--scrollable",role:"dialog","aria-label":"Agent controls","aria-modal":"false",children:[e.jsxs("div",{className:"agent-controls",children:[e.jsxs("div",{className:"agent-controls-filters",children:[e.jsxs("div",{className:"agent-state-filter",children:[e.jsx(Kt,{size:14}),e.jsxs("select",{className:"agent-state-filter-select",value:r,onChange:t=>m(t.target.value),"aria-label":"Filter agents by state",children:[e.jsx("option",{value:"all",children:"All States"}),e.jsx("option",{value:"idle",children:"Idle"}),e.jsx("option",{value:"active",children:"Active"}),e.jsx("option",{value:"running",children:"Running"}),e.jsx("option",{value:"paused",children:"Paused"}),e.jsx("option",{value:"error",children:"Error"}),e.jsx("option",{value:"terminated",children:"Terminated"})]})]}),e.jsxs("label",{className:"checkbox-label agent-system-filter",children:[e.jsx("input",{type:"checkbox",checked:o,onChange:t=>u(t.target.checked),"aria-label":"Show system agents"}),"Show system agents"]})]}),e.jsx("div",{className:"agent-controls-actions",children:e.jsxs("button",{className:"btn",onClick:()=>{T(!0),$(!1)},children:[e.jsx(pt,{size:16}),"Import"]})})]}),e.jsx("div",{className:"agent-global-controls",children:e.jsxs("div",{className:"heartbeat-multiplier-group",children:[e.jsxs("div",{className:"heartbeat-multiplier-controls",children:[e.jsx("label",{htmlFor:"globalHeartbeatMultiplier",className:"heartbeat-multiplier-label",children:"Heartbeat Speed"}),e.jsx("input",{id:"globalHeartbeatMultiplier",className:"heartbeat-multiplier-slider touch-target",type:"range",min:.1,max:10,step:.1,value:le,onChange:t=>{const c=Number(t.target.value);he(Number.isFinite(c)&&c>0?c:1)},disabled:K}),e.jsxs("span",{className:"heartbeat-multiplier-value",children:["×",le.toFixed(1)]}),e.jsx("select",{className:"heartbeat-multiplier-preset",value:String(Be.reduce((t,c)=>Math.abs(c-le)<Math.abs(t-le)?c:t,Be[0])),onChange:t=>{const c=Number(t.target.value);he(Number.isFinite(c)&&c>0?c:1)},disabled:K,"aria-label":"Heartbeat speed preset",children:Be.map(t=>e.jsxs("option",{value:String(t),children:["×",t]},t))})]}),e.jsx("small",{className:"text-secondary",children:"Scales all agent heartbeat intervals. ×0.5 = twice as fast, ×2.0 = twice as slow. Default: ×1.0"})]})}),e.jsx(bn,{agents:L})]}),e.jsxs("div",{className:"agents-view-content",children:[e.jsx(vn,{stats:y}),e.jsx(pn,{agents:U,projectId:l,onAgentSelect:f,onOpenTaskLogs:j}),e.jsx(Wn,{isOpen:N,onClose:()=>S(!1),onCreated:()=>{S(!1),v()},projectId:l}),e.jsx(Kn,{isOpen:R,onClose:()=>M(!1),onCreated:()=>{M(!1),v()},addToast:s,projectId:l,existingAgents:d}),e.jsx(Bn,{isOpen:E,onClose:()=>T(!1),onImported:()=>void v(),projectId:l}),Ee?e.jsxs("div",{className:"agents-view-loading",role:"status","aria-live":"polite",children:[e.jsx(Le,{size:18,className:"spin"}),e.jsx("span",{children:"Loading agents..."})]}):k==="tree"?e.jsx("div",{className:"agent-tree__view",children:L.length===0?e.jsx(Fe,{onCtaClick:we}):be.rootNodes.map(t=>e.jsx(bt,{node:t,onSelect:f,onToggle:be.toggleExpand,isExpanded:be.isExpanded,getChildCount:c=>be.getChildren(c).length,getHealthStatus:Ie,getRoleIcon:ve,getSkillBadges:Ce},t.agent.id))}):k==="org"?e.jsx("div",{className:"agent-org-chart","data-testid":"agent-org-chart",children:H?e.jsxs("div",{className:"agent-org-chart__loading",role:"status","aria-live":"polite",children:[e.jsx(Le,{size:18,className:"spin"}),e.jsx("span",{children:"Loading org chart..."})]}):ye.length===0?e.jsx(Fe,{onCtaClick:we}):ye.map(t=>e.jsx(xt,{node:t,onSelect:f,getHealthStatus:Ie,getRoleIcon:ve,getSkillBadges:Ce},t.agent.id))}):k==="board"?e.jsx("div",{className:"agent-board",children:L.length===0?e.jsx(Fe,{onCtaClick:we}):L.map(t=>{const c=Ie(t),n=ze(t.state),g=Oe("agent-board-card",t.state);return e.jsx("div",{className:`agent-board-card ${g}`,children:e.jsxs("div",{className:"agent-board-clickable",onClick:()=>f(t.id),role:"button",tabIndex:0,onKeyDown:D=>D.key==="Enter"&&f(t.id),children:[e.jsxs("div",{className:"agent-board-header",children:[e.jsx("span",{className:"agent-board-icon",children:ve(t.role)}),e.jsx("span",{className:"agent-board-badge badge text-secondary",children:O(t.role)}),e.jsx("span",{className:`agent-board-badge badge ${n}`,children:t.state})]}),e.jsx("div",{className:"agent-board-name",children:t.name}),e.jsx("div",{className:"agent-board-id",children:t.id}),e.jsxs("div",{className:"agent-board-health",style:{color:c.color},title:c.label,children:[c.icon,!c.stateDerived&&` ${c.label}`]})]})},t.id)})}):e.jsx("div",{className:"agent-list",children:L.length===0?e.jsx(Fe,{onCtaClick:we}):L.map(t=>{const c=Ie(t),n=ze(t.state),g=Oe("agent-card",t.state),D=Ge(t.runtimeConfig?.heartbeatIntervalMs),X=Ut(D),ce=A===t.id;return e.jsxs("div",{className:`agent-card ${g}`,children:[e.jsxs("div",{className:"agent-card-header",children:[e.jsxs("div",{className:"agent-info agent-info--clickable",onClick:()=>f(t.id),role:"button",tabIndex:0,onKeyDown:C=>C.key==="Enter"&&f(t.id),children:[ae===t.id?e.jsx("select",{ref:de,className:"select agent-role-select",value:t.role,onChange:C=>void Re(t.id,C.target.value),onKeyDown:C=>Ae(C,t.id),onBlur:()=>G(null),autoFocus:!0,children:$e.map(C=>e.jsxs("option",{value:C.value,children:[C.icon," ",C.label]},C.value))}):e.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:C=>{C.stopPropagation(),G(t.id)},title:"Click to change role",role:"button",tabIndex:0,onKeyDown:C=>{(C.key==="Enter"||C.key===" ")&&(C.stopPropagation(),G(t.id))},children:ve(t.role)}),e.jsxs("div",{className:"agent-meta",children:[e.jsx("span",{className:"agent-name",children:t.name}),e.jsx("span",{className:"agent-id text-secondary",children:t.id})]}),e.jsx(ht,{size:20,className:"agent-card-chevron"})]}),e.jsxs("div",{className:"agent-badges",children:[e.jsx("span",{className:`badge ${n}`,children:t.state}),e.jsxs("span",{className:"badge",style:{color:c.color},title:c.label,children:[c.icon,!c.stateDerived&&` ${c.label}`]}),e.jsx("span",{className:"badge text-secondary",children:O(t.role)}),(()=>{const C=Ce(t);if(C.length===0)return null;const Z=C.slice(0,2),Se=C.length-2;return e.jsxs(e.Fragment,{children:[Z.map(Ye=>e.jsx("span",{className:"badge badge-skill",children:Ye},Ye)),Se>0&&e.jsxs("span",{className:"badge badge-skill",children:["+",Se]})]})})()]})]}),e.jsxs("div",{className:"agent-card-body",children:[t.taskId&&e.jsxs("div",{className:"agent-task",children:[e.jsx("span",{className:"text-secondary",children:"Working on:"}),e.jsx("span",{className:"badge",children:t.taskId})]}),e.jsxs("div",{className:"agent-heartbeat-control",children:[e.jsx("span",{className:"text-secondary",children:"Heartbeat:"}),ue===t.id?e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"input agent-heartbeat-custom-input",value:z[t.id]??"",onChange:C=>W(Z=>({...Z,[t.id]:C.target.value})),onKeyDown:C=>{C.key==="Enter"?i(t):C.key==="Escape"&&(_(null),W(Z=>{const Se={...Z};return delete Se[t.id],Se}))},disabled:ce,"aria-label":`Custom heartbeat interval in minutes for ${t.name}`}),e.jsx("span",{className:"text-secondary",children:"min"}),e.jsx("button",{className:"btn btn--sm",onClick:()=>void i(t),disabled:ce,title:"Save custom interval",children:"Save"}),e.jsx("button",{className:"btn btn--sm",onClick:()=>{_(null),W(C=>{const Z={...C};return delete Z[t.id],Z})},disabled:ce,title:"Cancel custom interval",children:"Cancel"})]}):e.jsx(e.Fragment,{children:e.jsxs("select",{className:"select agent-heartbeat-select",value:D,onChange:C=>{const Z=C.target.value;Z==="__custom__"?w(t):fe(t,Number(Z))},disabled:ce,"aria-label":`Set heartbeat interval for ${t.name}`,children:[X.map(C=>e.jsx("option",{value:C.value,children:C.label},C.value)),Bt.some(C=>C.value===D)&&e.jsx("option",{value:"__custom__",children:"Custom..."})]})}),ce&&e.jsx("span",{className:"agent-heartbeat-saving text-secondary",children:"Saving…"}),t.lastHeartbeatAt&&(()=>{const C=new Date(t.lastHeartbeatAt),Z=new Date(C.getTime()+D),Se=t.state==="active"||t.state==="running";return e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"agent-heartbeat-last text-secondary",title:C.toLocaleString(),children:["Last: ",C.toLocaleTimeString()]}),Se&&e.jsxs("span",{className:"agent-heartbeat-next text-secondary",title:Z.toLocaleString(),children:["Next: ",Z.toLocaleTimeString()]})]})})()]})]}),e.jsxs("div",{className:"agent-card-actions",children:[t.state==="idle"&&e.jsxs("button",{className:"btn btn--sm",onClick:()=>void oe(t.id,"active"),disabled:Q.has(t.id),title:"Activate",children:[e.jsx(Pe,{size:14})," Start"]}),t.state==="active"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void V(t.id,t.name),disabled:Q.has(t.id),title:"Run Now","aria-label":`Run now for ${t.name}`,children:[e.jsx(Me,{size:14})," Run Now"]}),e.jsxs("button",{className:"btn btn--sm",onClick:()=>void oe(t.id,"paused"),disabled:Q.has(t.id),title:"Pause",children:[e.jsx(at,{size:14})," Pause"]})]}),t.state==="paused"&&e.jsxs("button",{className:"btn btn--sm",onClick:()=>void oe(t.id,"active"),disabled:Q.has(t.id),title:"Resume",children:[e.jsx(Pe,{size:14})," Resume"]}),t.state==="running"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",disabled:!0,title:"Run in progress","aria-label":`Heartbeat run in progress for ${t.name}`,children:[e.jsx(Me,{size:14})," Running"]}),e.jsxs("button",{className:"btn btn--sm",onClick:()=>void oe(t.id,"paused"),disabled:Q.has(t.id),title:"Pause",children:[e.jsx(at,{size:14})," Pause"]})]}),t.state==="error"&&e.jsxs("button",{className:"btn btn--sm",onClick:()=>void oe(t.id,"active"),disabled:Q.has(t.id),title:"Retry",children:[e.jsx(Pe,{size:14})," Retry"]}),t.state==="terminated"&&e.jsxs("button",{className:"btn btn--sm",onClick:()=>void oe(t.id,"active"),disabled:Q.has(t.id),title:"Start",children:[e.jsx(Pe,{size:14})," Start"]}),e.jsx("button",{className:"btn btn--sm agent-card-details-btn",onClick:()=>f(t.id),title:`View details for ${t.name}`,"aria-label":`View details for ${t.name}`,children:"View Details"}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void Ne(t.id,t.name),title:"Delete",children:[e.jsx(Gt,{size:14})," Delete"]})]})]},t.id)})})]}),b&&e.jsx(a.Suspense,{fallback:null,children:e.jsx(Gn,{agentId:b,projectId:l,onClose:F,addToast:s,onChildClick:ie})})]})}export{ta as AgentsView};