@runfusion/fusion 0.2.6 → 0.3.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 (56) hide show
  1. package/dist/bin.js +8488 -6999
  2. package/dist/client/assets/{AgentDetailView-BMrHuWGs.css → AgentDetailView-C1b9PC5l.css} +1 -1
  3. package/dist/client/assets/{AgentDetailView-CBdzWtd-.js → AgentDetailView-CJIxNRq-.js} +3 -3
  4. package/dist/client/assets/{AgentsView-DPlnCa_B.js → AgentsView-BS17exn3.js} +5 -5
  5. package/dist/client/assets/ChatView-BUlq3WNJ.js +1 -0
  6. package/dist/client/assets/{DevServerView-BY5cGz23.js → DevServerView-qMPpnXRb.js} +2 -2
  7. package/dist/client/assets/DirectoryPicker-CTwgv9LY.js +1 -0
  8. package/dist/client/assets/DirectoryPicker-DzKVmxOf.css +1 -0
  9. package/dist/client/assets/{DocumentsView-lQwJmc4G.js → DocumentsView-DOz1KFGN.js} +1 -1
  10. package/dist/client/assets/{InsightsView-DUiZZ0z8.js → InsightsView-CHZTJUic.js} +2 -2
  11. package/dist/client/assets/MemoryView-V0QdeO3e.js +2 -0
  12. package/dist/client/assets/{NodesView-DgyM-ktg.js → NodesView-BtGNRj2z.js} +1 -1
  13. package/dist/client/assets/PiExtensionsManager-D9Ye2Vak.js +11 -0
  14. package/dist/client/assets/PiExtensionsManager-kgTOHPE9.css +1 -0
  15. package/dist/client/assets/PluginManager-DRiIqol2.css +1 -0
  16. package/dist/client/assets/PluginManager-LeHp0jJ_.js +1 -0
  17. package/dist/client/assets/{RoadmapsView-ANn2jmsU.js → RoadmapsView-C413ISVU.js} +2 -2
  18. package/dist/client/assets/SettingsModal--vWmKBpT.css +1 -0
  19. package/dist/client/assets/SettingsModal-BZLL2xAP.js +31 -0
  20. package/dist/client/assets/SettingsModal-CDWvhvrd.css +1 -0
  21. package/dist/client/assets/SettingsModal-olTBmYJs.js +1 -0
  22. package/dist/client/assets/SetupWizardModal-BMa6p24b.css +1 -0
  23. package/dist/client/assets/{SetupWizardModal-UxlAtKWA.js → SetupWizardModal-WdaR2eQQ.js} +1 -1
  24. package/dist/client/assets/SkillsView-BcE57w8i.js +1 -0
  25. package/dist/client/assets/{folder-open-J7yPbaCt.js → folder-open-Ec4hU1xL.js} +1 -1
  26. package/dist/client/assets/index-CCYdhck-.js +616 -0
  27. package/dist/client/assets/index-lJ5WOmO9.css +1 -0
  28. package/dist/client/assets/{upload-B_grq4hM.js → upload-BksRDuGJ.js} +1 -1
  29. package/dist/client/assets/users-EFU4n9Qr.js +6 -0
  30. package/dist/client/index.html +2 -2
  31. package/dist/extension.js +1271 -205
  32. package/dist/pi-claude-cli/index.ts +72 -28
  33. package/dist/pi-claude-cli/package.json +1 -1
  34. package/dist/pi-claude-cli/src/__tests__/event-bridge.test.ts +34 -0
  35. package/dist/pi-claude-cli/src/__tests__/mcp-config.test.ts +22 -0
  36. package/dist/pi-claude-cli/src/__tests__/prompt-builder.test.ts +72 -10
  37. package/dist/pi-claude-cli/src/__tests__/provider.test.ts +9 -9
  38. package/dist/pi-claude-cli/src/event-bridge.ts +17 -6
  39. package/dist/pi-claude-cli/src/mcp-config.ts +36 -3
  40. package/dist/pi-claude-cli/src/prompt-builder.ts +111 -7
  41. package/dist/pi-claude-cli/src/provider.ts +18 -2
  42. package/package.json +6 -5
  43. package/skill/fusion/SKILL.md +6 -1
  44. package/skill/fusion/references/engine-tools.md +54 -0
  45. package/skill/fusion/references/extension-tools.md +83 -84
  46. package/skill/fusion/references/fusion-capabilities.md +33 -31
  47. package/dist/client/assets/ChatView-BXzYysNG.js +0 -1
  48. package/dist/client/assets/DirectoryPicker-DZ90eSBn.js +0 -1
  49. package/dist/client/assets/MemoryView-DvSmMN6G.js +0 -2
  50. package/dist/client/assets/PiExtensionsManager-K7HQ08L4.css +0 -1
  51. package/dist/client/assets/PiExtensionsManager-wxB-q06A.js +0 -11
  52. package/dist/client/assets/PluginManager-LH02ybSH.js +0 -1
  53. package/dist/client/assets/PluginManager-tCFMZMLL.css +0 -1
  54. package/dist/client/assets/SkillsView-DEjGh7wW.js +0 -1
  55. package/dist/client/assets/index-BdJsO65L.css +0 -1
  56. package/dist/client/assets/index-CHoVMPAA.js +0 -649
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentDetailView-CBdzWtd-.js","assets/vendor-react-K0fH_qHe.js","assets/index-CHoVMPAA.js","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/index-BdJsO65L.css","assets/upload-B_grq4hM.js","assets/folder-open-J7yPbaCt.js","assets/AgentDetailView-BMrHuWGs.css"])))=>i.map(i=>d[i]);
2
- import{c as Fe,s as lt,A as xe,C as Se,Z as ot,B as De,g as Re,a as tt,b as Ae,d as ct,e as dt,f as ut,h as mt,i as ht,u as ze,j as gt,P as pt,k as ft,l as Oe,G as bt,S as vt,L as Te,T as Me,R as $e,F as qe,X as He,m as xt,n as yt,o as wt,p as ie,q as Ve,r as jt,t as kt,v as Nt,w as It,x as Ct,y as We,z as St,D as nt,H as Et,E as ke,I as Ke,J as Ue,K as At,M as Tt,N as Ne,O as Mt,Q as Be,U as _t,V as Ge,W as Pt,_ as Rt}from"./index-CHoVMPAA.js";import{r as s,j as e}from"./vendor-react-K0fH_qHe.js";import{U as st}from"./upload-B_grq4hM.js";import{F as $t}from"./folder-open-J7yPbaCt.js";/**
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentDetailView-CJIxNRq-.js","assets/vendor-react-K0fH_qHe.js","assets/index-CCYdhck-.js","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/index-lJ5WOmO9.css","assets/upload-BksRDuGJ.js","assets/folder-open-Ec4hU1xL.js","assets/AgentDetailView-C1b9PC5l.css"])))=>i.map(i=>d[i]);
2
+ import{c as Fe,s as rt,A as xe,C as Se,Z as lt,B as De,g as Re,a as et,b as Ae,d as ot,e as ct,f as dt,h as ut,i as mt,u as ze,j as ht,P as gt,k as pt,l as Oe,G as ft,S as bt,L as Te,T as Me,R as $e,F as qe,X as He,m as vt,n as xt,o as yt,p as de,q as Ve,r as wt,t as jt,v as kt,w as Nt,x as It,y as We,z as Ct,D as tt,H as St,E as ke,I as Ke,J as Ue,K as Et,M as At,N as Ne,O as Tt,Q as Be,U as Mt,V as _t,W as Pt,_ as Rt}from"./index-CCYdhck-.js";import{r as s,j as e}from"./vendor-react-K0fH_qHe.js";import{U as nt}from"./upload-BksRDuGJ.js";import{F as $t}from"./folder-open-Ec4hU1xL.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 Fe,s as lt,A as xe,C as Se,Z as ot,B as De,g as Re,a as tt,b as Ae,d
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 Ot=[["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"}]],qt=Fe("sliders-horizontal",Ot),Qe=200;function Ht(a,l){const[f,m]=s.useState([]),[c,d]=s.useState(!1),r=s.useRef(null),u=s.useRef(0),o=s.useRef(a),g=s.useRef(l);return(o.current!==a||g.current!==l)&&(o.current=a,g.current=l,u.current++,r.current&&(r.current(),r.current=null),m([]),d(!1)),s.useEffect(()=>{if(!a){m([]),d(!1);return}const N=u.current;let x=`/api/tasks/${encodeURIComponent(a)}/logs/stream`;l&&(x+=`?projectId=${encodeURIComponent(l)}`);const I=lt(x,{events:{"agent:log":p=>{if(u.current===N)try{const w=JSON.parse(p.data),C={type:w.type??"text",text:w.text??w.content??"",timestamp:w.timestamp,content:w.content};m(A=>{const E=[C,...A];return E.length>Qe?E.slice(0,Qe):E})}catch{}}},onOpen:()=>{u.current===N&&d(!0)},onError:()=>{u.current===N&&d(!1)}});return r.current=I,()=>{I(),r.current=null,u.current===N&&d(!1)}},[a,l]),{entries:f,isConnected:c}}function Vt({agent:a,projectId:l,onSelect:f}){const{entries:m,isConnected:c}=Ht(a.taskId,l),d=a.lastHeartbeatAt?Math.floor((Date.now()-new Date(a.lastHeartbeatAt).getTime())/1e3):0,r=()=>{f&&f(a.id)},u=o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),r())};return e.jsxs("div",{className:"live-agent-card",onClick:r,onKeyDown:u,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:m.length===0?e.jsx("div",{className:"live-agent-card-empty",children:c?"Waiting for output...":"Connecting..."}):m.slice(0,20).map((o,g)=>e.jsx("div",{className:"live-agent-card-line",children:o.text},g))}),e.jsxs("div",{className:"live-agent-card-footer",children:[e.jsx("span",{className:"text-secondary",children:Wt(d)}),c&&e.jsx(xe,{size:12,className:"live-agent-streaming-dot"})]})]})}function Wt(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 Kt({agents:a,projectId:l,onAgentSelect:f}){const m=Array.from(new Map(a.map(c=>[c.id,c])).values());return m.length===0?null:e.jsxs("div",{className:"active-agents-panel",children:[e.jsxs("div",{className:"active-agents-panel-header",children:[e.jsx(xe,{size:16}),e.jsxs("span",{children:["Active Agents (",m.length,")"]})]}),e.jsx("div",{className:"active-agents-grid",children:m.map(c=>e.jsx(Vt,{agent:c,projectId:l,onSelect:f},c.id))})]})}const Ut=[{icon:xe,label:"Active Agents",valueKey:"activeCount",className:"agent-metric-card--active"},{icon:Dt,label:"Assigned Tasks",valueKey:"assignedTaskCount",className:"agent-metric-card--tasks"},{icon:Se,label:"Success Rate",valueKey:"successRate",className:"agent-metric-card--success"},{icon:ot,label:"Total Runs",valueKey:"completedRuns",className:"agent-metric-card--runs"}];function Bt({stats:a}){return a?e.jsx("div",{className:"agent-metrics-bar",children:Ut.map(l=>{const f=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:f}),e.jsx("span",{className:"agent-metric-label",children:l.label})]})]},l.label)})}):null}function Je(a){return typeof a=="number"&&Number.isFinite(a)?a:0}function ve(a){return a.toLocaleString()}function Gt({agents:a}){const{rows:l,totalInputTokens:f,totalOutputTokens:m,totalTokens:c}=s.useMemo(()=>{const r=a.map(u=>{const o=Je(u.totalInputTokens),g=Je(u.totalOutputTokens);return{id:u.id,name:u.name,inputTokens:o,outputTokens:g,totalTokens:o+g}}).sort((u,o)=>o.totalTokens-u.totalTokens||u.name.localeCompare(o.name)||u.id.localeCompare(o.id));return{rows:r,totalInputTokens:r.reduce((u,o)=>u+o.inputTokens,0),totalOutputTokens:r.reduce((u,o)=>u+o.outputTokens,0),totalTokens:r.reduce((u,o)=>u+o.totalTokens,0)}},[a]),d=c>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:ve(f)})]}),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:ve(m)})]}),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:ve(c)})]})]}),d?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:ve(r.inputTokens)}),e.jsx("td",{children:ve(r.outputTokens)}),e.jsx("td",{className:"agent-token-stats-panel__total-cell",children:ve(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 Ie({title:a="No agents found",description:l="Create an agent to get started",ctaLabel:f="Create Agent",onCtaClick:m}){return e.jsxs("div",{className:"agent-empty",children:[e.jsx(De,{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}),m?e.jsx("button",{type:"button",className:"btn btn--primary",onClick:m,children:f}):null]})}const at="fn-agent-tree-expanded";function Xe(a){try{const l=Re(at,a);if(l){const f=JSON.parse(l);return new Set(Array.isArray(f)?f:[])}}catch{}return new Set}function Qt(a,l){try{tt(at,JSON.stringify([...a]),l)}catch{}}function Jt(a,l){const f=new Map,m=new Map;for(const d of a)if(f.set(d.id,d),d.reportsTo){const r=m.get(d.reportsTo)??[];r.push(d),m.set(d.reportsTo,r)}function c(d,r){const u=m.get(d.id)??[],o=l.has(d.id)?u.map(g=>c(g,r+1)):[];return{agent:d,children:o,depth:r}}return a.filter(d=>!d.reportsTo||!f.has(d.reportsTo)).map(d=>c(d,0))}function Xt(a,l){const[f,m]=s.useState(()=>Xe(l));s.useEffect(()=>{m(Xe(l))},[l]);const c=s.useMemo(()=>Jt(a,f),[a,f]),d=s.useCallback(o=>{m(g=>{const b=new Set(g);return b.has(o)?b.delete(o):b.add(o),Qt(b,l),b})},[l]),r=s.useCallback(o=>f.has(o),[f]),u=s.useCallback(o=>a.filter(g=>g.reportsTo===o),[a]);return{rootNodes:c,toggleExpand:d,isExpanded:r,getChildren:u,isLoading:!1}}const Ze=3,_e=1e3;function Zt({isOpen:a,onClose:l,onGenerated:f,projectId:m}){const[c,d]=s.useState(""),[r,u]=s.useState({type:"input"}),[o,g]=s.useState(null),[b,N]=s.useState(!1),x=s.useRef(null),I=s.useRef(null);s.useEffect(()=>{a&&r.type==="input"&&I.current?.focus()},[a,r.type]),s.useEffect(()=>{if(!a&&x.current){const j=x.current;x.current=null,Ae(j,m).catch(()=>{})}},[a,m]),s.useEffect(()=>{if(!a)return;const j=T=>{T.key==="Escape"&&p()};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[a]);const p=s.useCallback(()=>{if(x.current){const j=x.current;x.current=null,Ae(j,m).catch(()=>{})}d(""),u({type:"input"}),g(null),N(!1),l()},[l,m]),w=s.useCallback(async()=>{if(!(!c.trim()||c.trim().length<Ze)){g(null),u({type:"loading"});try{const{sessionId:j}=await ct(c.trim(),m);x.current=j;const{spec:T}=await dt(j,m);u({type:"preview",spec:T,sessionId:j})}catch(j){const T=j instanceof Error?j.message:"Failed to generate agent specification";T.includes("429")||T.toLowerCase().includes("rate limit")?g("Too many requests. Please wait a moment and try again."):g(T),u({type:"input"}),x.current=null}}},[c,m]),C=s.useCallback(async()=>{if(x.current){const j=x.current;x.current=null;try{await Ae(j,m)}catch{}}await w()},[w,m]),A=s.useCallback(()=>{r.type==="preview"&&(x.current=null,f(r.spec),d(""),u({type:"input"}),g(null),N(!1),l())},[r,f,l]);if(!a)return null;const E=c.trim().length>=Ze&&c.trim().length<=_e;return e.jsx("div",{className:"agent-dialog-overlay",onClick:j=>{j.target===j.currentTarget&&p()},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:p,"aria-label":"Close",children:"×"})]}),e.jsxs("div",{className:"agent-dialog-body",children:[o&&e.jsx("div",{className:"agent-dialog-error-banner",children:o}),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:c,onChange:j=>d(j.target.value),onKeyDown:j=>{j.key==="Enter"&&!j.shiftKey&&E&&(j.preventDefault(),w())},maxLength:_e,"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:[c.length,"/",_e]})]})]})]}),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:()=>N(!b),children:b?"Collapse":"Expand"})]}),e.jsxs("div",{className:`agent-generation-prompt-box${b?"":" agent-generation-prompt-box--collapsed"}`,children:[r.spec.systemPrompt,!b&&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:p,children:"Cancel"}),r.type==="input"&&e.jsx("button",{className:"btn btn--primary",onClick:()=>void w(),disabled:!E,children:"Generate"}),r.type==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn",onClick:()=>void C(),children:"Regenerate"}),e.jsx("button",{className:"btn btn--primary",onClick:A,children:"Use This"})]})]})]})})}const Yt=`# Soul: Chief Executive Officer
17
+ */const Ot=[["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"}]],qt=Fe("sliders-horizontal",Ot),Ge=200;function Ht(a,l){const[f,m]=s.useState([]),[c,d]=s.useState(!1),r=s.useRef(null),u=s.useRef(0),o=s.useRef(a),g=s.useRef(l);return(o.current!==a||g.current!==l)&&(o.current=a,g.current=l,u.current++,r.current&&(r.current(),r.current=null),m([]),d(!1)),s.useEffect(()=>{if(!a){m([]),d(!1);return}const N=u.current;let x=`/api/tasks/${encodeURIComponent(a)}/logs/stream`;l&&(x+=`?projectId=${encodeURIComponent(l)}`);const I=rt(x,{events:{"agent:log":p=>{if(u.current===N)try{const w=JSON.parse(p.data),C={type:w.type??"text",text:w.text??w.content??"",timestamp:w.timestamp,content:w.content};m(A=>{const E=[C,...A];return E.length>Ge?E.slice(0,Ge):E})}catch{}}},onOpen:()=>{u.current===N&&d(!0)},onError:()=>{u.current===N&&d(!1)}});return r.current=I,()=>{I(),r.current=null,u.current===N&&d(!1)}},[a,l]),{entries:f,isConnected:c}}function Vt({agent:a,projectId:l,onSelect:f}){const{entries:m,isConnected:c}=Ht(a.taskId,l),d=a.lastHeartbeatAt?Math.floor((Date.now()-new Date(a.lastHeartbeatAt).getTime())/1e3):0,r=()=>{f&&f(a.id)},u=o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),r())};return e.jsxs("div",{className:"live-agent-card",onClick:r,onKeyDown:u,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:m.length===0?e.jsx("div",{className:"live-agent-card-empty",children:c?"Waiting for output...":"Connecting..."}):m.slice(0,20).map((o,g)=>e.jsx("div",{className:"live-agent-card-line",children:o.text},g))}),e.jsxs("div",{className:"live-agent-card-footer",children:[e.jsx("span",{className:"text-secondary",children:Wt(d)}),c&&e.jsx(xe,{size:12,className:"live-agent-streaming-dot"})]})]})}function Wt(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 Kt({agents:a,projectId:l,onAgentSelect:f}){const m=Array.from(new Map(a.map(c=>[c.id,c])).values());return m.length===0?null:e.jsxs("div",{className:"active-agents-panel",children:[e.jsxs("div",{className:"active-agents-panel-header",children:[e.jsx(xe,{size:16}),e.jsxs("span",{children:["Active Agents (",m.length,")"]})]}),e.jsx("div",{className:"active-agents-grid",children:m.map(c=>e.jsx(Vt,{agent:c,projectId:l,onSelect:f},c.id))})]})}const Ut=[{icon:xe,label:"Active Agents",valueKey:"activeCount",className:"agent-metric-card--active"},{icon:Dt,label:"Assigned Tasks",valueKey:"assignedTaskCount",className:"agent-metric-card--tasks"},{icon:Se,label:"Success Rate",valueKey:"successRate",className:"agent-metric-card--success"},{icon:lt,label:"Total Runs",valueKey:"completedRuns",className:"agent-metric-card--runs"}];function Bt({stats:a}){return a?e.jsx("div",{className:"agent-metrics-bar",children:Ut.map(l=>{const f=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:f}),e.jsx("span",{className:"agent-metric-label",children:l.label})]})]},l.label)})}):null}function Qe(a){return typeof a=="number"&&Number.isFinite(a)?a:0}function ve(a){return a.toLocaleString()}function Gt({agents:a}){const{rows:l,totalInputTokens:f,totalOutputTokens:m,totalTokens:c}=s.useMemo(()=>{const r=a.map(u=>{const o=Qe(u.totalInputTokens),g=Qe(u.totalOutputTokens);return{id:u.id,name:u.name,inputTokens:o,outputTokens:g,totalTokens:o+g}}).sort((u,o)=>o.totalTokens-u.totalTokens||u.name.localeCompare(o.name)||u.id.localeCompare(o.id));return{rows:r,totalInputTokens:r.reduce((u,o)=>u+o.inputTokens,0),totalOutputTokens:r.reduce((u,o)=>u+o.outputTokens,0),totalTokens:r.reduce((u,o)=>u+o.totalTokens,0)}},[a]),d=c>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:ve(f)})]}),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:ve(m)})]}),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:ve(c)})]})]}),d?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:ve(r.inputTokens)}),e.jsx("td",{children:ve(r.outputTokens)}),e.jsx("td",{className:"agent-token-stats-panel__total-cell",children:ve(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 Ie({title:a="No agents found",description:l="Create an agent to get started",ctaLabel:f="Create Agent",onCtaClick:m}){return e.jsxs("div",{className:"agent-empty",children:[e.jsx(De,{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}),m?e.jsx("button",{type:"button",className:"btn btn--primary",onClick:m,children:f}):null]})}const st="fn-agent-tree-expanded";function Je(a){try{const l=Re(st,a);if(l){const f=JSON.parse(l);return new Set(Array.isArray(f)?f:[])}}catch{}return new Set}function Qt(a,l){try{et(st,JSON.stringify([...a]),l)}catch{}}function Jt(a,l){const f=new Map,m=new Map;for(const d of a)if(f.set(d.id,d),d.reportsTo){const r=m.get(d.reportsTo)??[];r.push(d),m.set(d.reportsTo,r)}function c(d,r){const u=m.get(d.id)??[],o=l.has(d.id)?u.map(g=>c(g,r+1)):[];return{agent:d,children:o,depth:r}}return a.filter(d=>!d.reportsTo||!f.has(d.reportsTo)).map(d=>c(d,0))}function Xt(a,l){const[f,m]=s.useState(()=>Je(l));s.useEffect(()=>{m(Je(l))},[l]);const c=s.useMemo(()=>Jt(a,f),[a,f]),d=s.useCallback(o=>{m(g=>{const b=new Set(g);return b.has(o)?b.delete(o):b.add(o),Qt(b,l),b})},[l]),r=s.useCallback(o=>f.has(o),[f]),u=s.useCallback(o=>a.filter(g=>g.reportsTo===o),[a]);return{rootNodes:c,toggleExpand:d,isExpanded:r,getChildren:u,isLoading:!1}}const Xe=3,_e=1e3;function Zt({isOpen:a,onClose:l,onGenerated:f,projectId:m}){const[c,d]=s.useState(""),[r,u]=s.useState({type:"input"}),[o,g]=s.useState(null),[b,N]=s.useState(!1),x=s.useRef(null),I=s.useRef(null);s.useEffect(()=>{a&&r.type==="input"&&I.current?.focus()},[a,r.type]),s.useEffect(()=>{if(!a&&x.current){const j=x.current;x.current=null,Ae(j,m).catch(()=>{})}},[a,m]),s.useEffect(()=>{if(!a)return;const j=T=>{T.key==="Escape"&&p()};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[a]);const p=s.useCallback(()=>{if(x.current){const j=x.current;x.current=null,Ae(j,m).catch(()=>{})}d(""),u({type:"input"}),g(null),N(!1),l()},[l,m]),w=s.useCallback(async()=>{if(!(!c.trim()||c.trim().length<Xe)){g(null),u({type:"loading"});try{const{sessionId:j}=await ot(c.trim(),m);x.current=j;const{spec:T}=await ct(j,m);u({type:"preview",spec:T,sessionId:j})}catch(j){const T=j instanceof Error?j.message:"Failed to generate agent specification";T.includes("429")||T.toLowerCase().includes("rate limit")?g("Too many requests. Please wait a moment and try again."):g(T),u({type:"input"}),x.current=null}}},[c,m]),C=s.useCallback(async()=>{if(x.current){const j=x.current;x.current=null;try{await Ae(j,m)}catch{}}await w()},[w,m]),A=s.useCallback(()=>{r.type==="preview"&&(x.current=null,f(r.spec),d(""),u({type:"input"}),g(null),N(!1),l())},[r,f,l]);if(!a)return null;const E=c.trim().length>=Xe&&c.trim().length<=_e;return e.jsx("div",{className:"agent-dialog-overlay",onClick:j=>{j.target===j.currentTarget&&p()},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:p,"aria-label":"Close",children:"×"})]}),e.jsxs("div",{className:"agent-dialog-body",children:[o&&e.jsx("div",{className:"agent-dialog-error-banner",children:o}),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:c,onChange:j=>d(j.target.value),onKeyDown:j=>{j.key==="Enter"&&!j.shiftKey&&E&&(j.preventDefault(),w())},maxLength:_e,"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:[c.length,"/",_e]})]})]})]}),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:()=>N(!b),children:b?"Collapse":"Expand"})]}),e.jsxs("div",{className:`agent-generation-prompt-box${b?"":" agent-generation-prompt-box--collapsed"}`,children:[r.spec.systemPrompt,!b&&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:p,children:"Cancel"}),r.type==="input"&&e.jsx("button",{className:"btn btn--primary",onClick:()=>void w(),disabled:!E,children:"Generate"}),r.type==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn",onClick:()=>void C(),children:"Regenerate"}),e.jsx("button",{className:"btn btn--primary",onClick:A,children:"Use This"})]})]})]})})}const Yt=`# Soul: Chief Executive Officer
18
18
 
19
19
  I am a strategic leader who connects every decision to business outcomes.
20
20
 
@@ -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 wn({value:a,onChange:l,projectId:f,disabled:m=!1,id:c,label:d="Skills"}){const[r,u]=s.useState([]),[o,g]=s.useState(!0);s.useEffect(()=>{let p=!1;return g(!0),ut(f).then(w=>{p||u(w)}).catch(()=>{p||u([])}).finally(()=>{p||g(!1)}),()=>{p=!0}},[f]);const b=p=>{a.includes(p)||l([...a,p])},N=p=>{l(a.filter(w=>w!==p))},x=p=>r.find(C=>C.id===p)?.name??p,I=r.filter(p=>!a.includes(p.id));return e.jsxs("div",{className:"skill-multiselect","data-testid":"skill-multiselect",children:[d&&e.jsx("label",{htmlFor:c?`${c}-select`:void 0,className:"skill-multiselect-label",children:d}),a.length>0&&e.jsx("div",{className:"skill-multiselect-chips","data-testid":"skill-chips",children:a.map(p=>e.jsxs("span",{className:"skill-chip","data-testid":`skill-chip-${p}`,children:[e.jsx("span",{className:"skill-chip-name",children:x(p)}),e.jsx("button",{type:"button",className:"skill-chip-remove",onClick:()=>N(p),disabled:m,"aria-label":`Remove ${x(p)}`,"data-testid":`remove-skill-${p}`,children:"×"})]},p))}),e.jsx("div",{className:"skill-multiselect-add",children:o?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:c?`${c}-select`:void 0,className:"select skill-multiselect-dropdown",value:"",onChange:p=>{p.target.value&&(b(p.target.value),p.target.value="")},disabled:m,"data-testid":"skill-dropdown",children:[e.jsx("option",{value:"",children:"Add a skill…"}),I.map(p=>e.jsx("option",{value:p.id,children:p.name},p.id))]})})]})}const Ye=[{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:"✦"}],jn=new Set(["triage","executor","reviewer","merger","scheduler","engineer","custom"]);function kn({isOpen:a,onClose:l,onCreated:f,projectId:m}){const[c,d]=s.useState(0),[r,u]=s.useState("presets"),[o,g]=s.useState(""),[b,N]=s.useState(""),[x,I]=s.useState(""),[p,w]=s.useState("custom"),[C,A]=s.useState(""),[E,j]=s.useState(""),[T,W]=s.useState(""),[X,H]=s.useState(""),[L,re]=s.useState(""),[_,M]=s.useState({model:"",thinkingLevel:"off",maxTurns:1e3}),[k,K]=s.useState(null),[Z,ue]=s.useState([]),[z,me]=s.useState(!1),[U,Y]=s.useState(null),[P,B]=s.useState(!1),[$,ee]=s.useState([]),[le,F]=s.useState(!1),[G,R]=s.useState([]),[V,ne]=s.useState([]),[Q,se]=s.useState([]),[ae,he]=s.useState(!1);s.useEffect(()=>{a&&(F(!0),mt().then(n=>{ee(n.models),R(n.favoriteProviders),ne(n.favoriteModels)}).catch(()=>{}).finally(()=>F(!1)))},[a]),s.useEffect(()=>{a&&(he(!0),se([]),ht(void 0,m).then(n=>{se(n)}).catch(()=>{se([])}).finally(()=>he(!1)))},[a,m]);const J=_.model.includes("/")?_.model:"",ye=s.useCallback(n=>{const t=jn.has(n.role)?n.role:"custom";g(n.title),N(n.description),I(n.icon),w(t),W(n.systemPrompt),M(i=>({...i,thinkingLevel:n.thinkingLevel,maxTurns:n.maxTurns})),B(!1),d(1)},[]),we=s.useCallback(n=>{M(t=>({...t,model:n}))},[]),O=s.useCallback(async n=>{const t=G,h=t.includes(n)?t.filter(v=>v!==n):[n,...t];R(h);try{await ze({favoriteProviders:h,favoriteModels:V})}catch{R(t)}},[G,V]),D=s.useCallback(async n=>{const t=V,h=t.includes(n)?t.filter(v=>v!==n):[n,...t];ne(h);try{await ze({favoriteProviders:G,favoriteModels:h})}catch{ne(t)}},[G,V]),be=s.useCallback(n=>{K(n.id),g(n.name),I(n.icon),N(n.description??n.title),w(n.role),H(n.soul??""),W(n.instructionsText??""),d(1)},[]);if(!a)return null;const oe=()=>{d(0),u("presets"),g(""),N(""),I(""),w("custom"),A(""),j(""),W(""),H(""),re(""),M({model:"",thinkingLevel:"off",maxTurns:1e3}),K(null),ue([]),Y(null),B(!1),l()},je=async()=>{if(o.trim()){me(!0),Y(null);try{const n={};_.model.trim()&&(n.model=_.model.trim()),_.thinkingLevel!=="off"&&(n.thinkingLevel=_.thinkingLevel),_.maxTurns!==1e3&&(n.maxTurns=_.maxTurns),await ft({name:o.trim(),role:p,...b.trim()?{title:b.trim()}:{},...x.trim()?{icon:x.trim()}:{},...C.trim()?{reportsTo:C.trim()}:{},...E.trim()?{instructionsPath:E.trim()}:{},...T.trim()?{instructionsText:T.trim()}:{},...X.trim()?{soul:X.trim()}:{},...L.trim()?{memory:L.trim()}:{},...Object.keys(n).length>0?{runtimeConfig:n}:{},...Z.length>0?{metadata:{skills:Z}}:{}},m),oe(),f()}catch(n){Y(n instanceof Error?n.message:"Failed to create agent")}finally{me(!1)}}},ge=Ye.find(n=>n.value===p),te=C.trim(),ce=te?Q.find(n=>n.id===te):void 0;return e.jsxs("div",{className:"agent-dialog-overlay",onClick:n=>{n.target===n.currentTarget&&oe()},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:oe,"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===c?" active":n<c?" completed":""}`,"aria-label":`Step ${n+1}`},n))}),e.jsxs("div",{className:"agent-dialog-body",children:[c===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:()=>u("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:()=>u("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:yn.map(n=>e.jsxs("button",{type:"button",className:`agent-preset-card${k===n.id?" selected":""}`,"data-testid":`preset-${n.id}`,onClick:()=>be(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 ",!k&&e.jsx("span",{className:"agent-dialog-required",children:"*"})]}),e.jsx("input",{id:"agent-name",type:"text",className:"input",placeholder:"e.g. Frontend Reviewer",value:o,onChange:n=>g(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-field",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:b,onChange:n=>N(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:x,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:Ye.map(n=>e.jsxs("button",{type:"button",className:`agent-role-option${p===n.value?" selected":""}`,onClick:()=>w(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:C,onChange:n=>A(n.target.value),disabled:ae,children:[e.jsx("option",{value:"",children:"No manager"}),Q.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:X,onChange:n=>H(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:L,onChange:n=>re(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:E,onChange:n=>j(n.target.value)})]}),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:T,onChange:n=>W(n.target.value)})]})]}),e.jsxs("div",{className:"agent-dialog-ai-generate",children:[e.jsxs("button",{type:"button",className:"btn btn--ai-generate",onClick:()=>B(!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"})]})]})]}),c===1&&e.jsxs("div",{children:[e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx("label",{children:"Model"}),le?e.jsx("div",{className:"agent-dialog-loading",children:"Loading models…"}):e.jsx(gt,{id:"agent-model",label:"Model",value:J,onChange:we,models:$,placeholder:"Select a model…",favoriteProviders:G,onToggleFavorite:O,favoriteModels:V,onToggleModelFavorite:D})]}),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:_.thinkingLevel,onChange:n=>M(t=>({...t,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:_.maxTurns,onChange:n=>M(t=>({...t,maxTurns:Math.max(1,parseInt(n.target.value,10)||1)}))})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx(wn,{id:"agent-skills",label:"Skills",value:Z,onChange:ue,projectId:m}),e.jsx("p",{className:"agent-dialog-optional agent-dialog-skills-hint",children:"Optional skills to assign to this agent"})]})]}),c===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:[x&&e.jsx("span",{className:"agent-dialog-icon-prefix",children:x}),o]})]}),b&&e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Title"}),e.jsx("span",{children:b})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Role"}),e.jsxs("span",{children:[ge?.icon," ",ge?.label]})]}),te&&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:ce?`${ce.name} (${ce.id})`:te})]}),E.trim()&&e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Instructions File"}),e.jsx("span",{children:E.trim()})]}),T.trim()&&e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Inline Instructions"}),e.jsxs("span",{children:[T.trim().length," chars"]})]}),X.trim()&&e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Soul"}),e.jsxs("span",{children:[X.trim().length," chars"]})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Model"}),e.jsx("span",{children:J?e.jsxs(e.Fragment,{children:[e.jsx(pt,{provider:J.split("/")[0],size:"sm"})," ",(()=>{const n=J.indexOf("/"),t=J.slice(0,n),i=J.slice(n+1);return $.find(v=>v.provider===t&&v.id===i)?.name||J})()]}):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:_.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:_.maxTurns})]}),Z.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:[Z.length," skill",Z.length!==1?"s":""," selected"]})]})]}),U&&e.jsx("p",{className:"agent-dialog-error",children:U})]})]}),e.jsxs("div",{className:"agent-dialog-footer",children:[c>0&&e.jsx("button",{className:"btn",onClick:()=>d(n=>n-1),disabled:z,children:"Back"}),e.jsx("button",{className:"btn",onClick:oe,disabled:z,children:"Cancel"}),c<2?e.jsx("button",{className:"btn btn--primary",onClick:()=>d(n=>n+1),disabled:c===0&&!o.trim()&&!k,children:"Next"}):e.jsx("button",{className:"btn btn--primary",onClick:()=>void je(),disabled:z||!o.trim(),children:z?"Creating...":"Create"})]})]}),e.jsx(Zt,{isOpen:P,onClose:()=>B(!1),onGenerated:ye,projectId:m})]})}function Nn(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 f=l[1].split(/\r?\n/),m=l[2]??"",c={name:""},d=[];let r=!1;for(const u of f){const g=u.trimEnd().trim();if(!g)continue;if(g.startsWith("skills:")){r=!0;continue}if(r&&g.startsWith("- ")){d.push(g.slice(2).trim());continue}r=!1;const[b,...N]=g.split(":"),I=N.join(":").trim().replace(/^['"]|['"]$/g,"");b==="name"&&(c.name=I),b==="title"&&(c.title=I),b==="icon"&&(c.icon=I),b==="role"&&(c.role=I),b==="reportsTo"&&(c.reportsTo=I)}if(!c.name)throw new Error("Missing required field: name");return d.length>0&&(c.skills=d),m.trim().length>0&&(c.instructionBody=m),c}function In({isOpen:a,onClose:l,onImported:f,projectId:m}){const[c,d]=s.useState("input"),[r,u]=s.useState("paste"),[o,g]=s.useState(""),[b,N]=s.useState([]),[x,I]=s.useState("Unknown"),[p,w]=s.useState([]),[C,A]=s.useState([]),[E,j]=s.useState([]),[T,W]=s.useState([]),[X,H]=s.useState(!1),[L,re]=s.useState(!1),[_,M]=s.useState(null),[k,K]=s.useState(null),[Z,ue]=s.useState(null),z=s.useRef(null),me=s.useRef(null),[U,Y]=s.useState([]),[P,B]=s.useState(""),[$,ee]=s.useState(null),[le,F]=s.useState(!1),[G,R]=s.useState(null),V=s.useRef(!1);s.useEffect(()=>{r==="browse"&&!V.current&&!le&&(V.current=!0,F(!0),R(null),Oe().then(n=>{n.error?R(n.error):n.companies.length>0?Y(n.companies):R("No companies available")}).catch(n=>{R(n instanceof Error?n.message:"Failed to load companies")}).finally(()=>{F(!1)}))},[r,le]);const ne=s.useCallback(()=>{V.current=!0,R(null),Y([]),ee(null),F(!0),Oe().then(n=>{n.error?R(n.error):n.companies.length>0?Y(n.companies):R("No companies available")}).catch(n=>{R(n instanceof Error?n.message:"Failed to load companies")}).finally(()=>{F(!1)})},[]),Q=s.useCallback(()=>{d("input"),u("paste"),g(""),N([]),I("Unknown"),w([]),A([]),j([]),W([]),H(!1),re(!1),M(null),K(null),ue(null),Y([]),B(""),ee(null),F(!1),R(null),V.current=!1},[]),se=s.useCallback(()=>{Q(),l()},[Q,l]),ae=s.useCallback(n=>{const t=n.target.files?.[0];if(!t)return;const i=new FileReader;i.onload=h=>{const v=h.target?.result;u("file"),N([]),g(v),M(null)},i.onerror=()=>{M("Failed to read file")},i.readAsText(t),n.target.value=""},[]),he=s.useCallback(async n=>{const t=Array.from(n.target.files??[]);if(t.length!==0)try{const i=t.filter(v=>(v.webkitRelativePath||v.name).toLowerCase().endsWith("agents.md")).sort((v,S)=>{const de=v.webkitRelativePath||v.name,pe=S.webkitRelativePath||S.name;return de.localeCompare(pe)});if(i.length===0){M("Selected directory has no AGENTS.md files");return}const h=[];for(const v of i){const S=await v.text();h.push(Nn(S))}u("directory"),N(h),g(""),M(null)}catch{M("Failed to parse AGENTS.md files from selected directory")}finally{n.target.value=""}},[]);function J(n){if(!m)return`/api${n}`;const t=n.includes("?")?"&":"?";return`/api${n}${t}projectId=${encodeURIComponent(m)}`}const ye=s.useCallback(async()=>{if(r==="directory"&&b.length===0){M("Please select a directory containing AGENTS.md files");return}if(r==="browse"&&!$){M("Please select a company from the catalog");return}if(r!=="directory"&&r!=="browse"&&!o.trim()){M("Please provide manifest content");return}H(!0),M(null);try{let n;r==="directory"?n={agents:b,dryRun:!0}:r==="browse"&&$?n={importSource:"companies.sh",companySlug:$.slug,dryRun:!0}:n={manifest:o,dryRun:!0};const t=await fetch(J("/agents/import"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!t.ok){const S=await t.json();throw new Error(S.error??`Parse failed (${t.status})`)}const i=await t.json(),h=i.agents&&i.agents.length>0?i.agents:i.created.map(S=>({name:S,role:"custom"})),v=Array.isArray(i.skills)?i.skills:[];I(i.companyName??"Unknown"),w(h),A(v),j(h.map(S=>S.name)),W(v.map(S=>S.name)),d("preview")}catch(n){M(n instanceof Error?n.message:"Failed to parse manifest")}finally{H(!1)}},[r,b,o,$,m]),we=s.useCallback(async()=>{re(!0),ue(null);try{let n;r==="directory"?n={agents:b,skipExisting:!0,selectedAgents:E,selectedSkills:T}:r==="browse"&&$?n={importSource:"companies.sh",companySlug:$.slug,skipExisting:!0,selectedAgents:E,selectedSkills:T}:n={manifest:o,skipExisting:!0,selectedAgents:E,selectedSkills:T};const t=await fetch(J("/agents/import"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!t.ok){const h=await t.json();throw new Error(h.error??`Import failed (${t.status})`)}const i=await t.json();K(i),d("result"),f()}catch(n){ue(n instanceof Error?n.message:"Failed to import agents")}finally{re(!1)}},[r,b,o,$,E,T,m,f]),O=E.length,D=T.length,be=`${O} Agent${O!==1?"s":""}`,oe=`${D} Skill${D!==1?"s":""}`,je=O>0&&D>0?`${be} + ${oe}`:D>0?oe:be,ge=O>0&&D>0?`Importing ${O} agent${O!==1?"s":""} and ${D} skill${D!==1?"s":""}...`:D>0?`Importing ${D} skill${D!==1?"s":""}...`:`Importing ${O} agent${O!==1?"s":""}...`,te=n=>{j(t=>t.includes(n)?t.filter(i=>i!==n):[...t,n])},ce=n=>{W(t=>t.includes(n)?t.filter(i=>i!==n):[...t,n])};return a?e.jsx("div",{className:"agent-dialog-overlay",onClick:n=>{n.target===n.currentTarget&&se()},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:se,"aria-label":"Close",children:"×"})]}),e.jsxs("div",{className:"agent-dialog-body",children:[c==="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:z,type:"file",accept:".md,.txt",onChange:ae,className:"agent-import-file-input","aria-label":"Upload agent manifest file"}),e.jsx("input",{ref:me,type:"file",webkitdirectory:"",multiple:!0,onChange:he,className:"agent-import-file-input","aria-label":"Select directory"}),e.jsxs("button",{type:"button",className:"btn agent-import-upload-btn",onClick:()=>z.current?.click(),children:[e.jsx(st,{size:16}),"Choose File"]}),e.jsxs("button",{type:"button",className:"btn agent-import-upload-btn",onClick:()=>me.current?.click(),children:[e.jsx($t,{size:16}),"Select Directory"]}),e.jsxs("button",{type:"button",className:"btn agent-import-upload-btn",onClick:()=>{u("browse"),N([]),g(""),ee(null),M(null)},children:[e.jsx(bt,{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(vt,{size:16,className:"agent-import-browse-search-icon"}),e.jsx("input",{type:"text",className:"agent-import-browse-search-input",placeholder:"Search companies...",value:P,onChange:n=>B(n.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:()=>ee(null),children:"Change"})]})]}),le&&e.jsxs("div",{className:"agent-import-browse-loading",children:[e.jsx(Te,{size:20,className:"spin"}),e.jsx("span",{children:"Loading companies..."})]}),G&&e.jsxs("div",{className:"agent-import-browse-error",children:[e.jsx(Me,{size:16}),e.jsx("span",{children:G}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:ne,children:[e.jsx($e,{size:14}),"Retry"]})]}),!le&&!G&&e.jsxs("div",{className:"agent-import-browse-list",children:[U.filter(n=>P===""||n.name.toLowerCase().includes(P.toLowerCase())||(n.tagline?.toLowerCase().includes(P.toLowerCase())??!1)).map(n=>e.jsxs("div",{className:`agent-import-browse-item ${$?.slug===n.slug?"agent-import-browse-item--selected":""}`,onClick:()=>ee(n),role:"button",tabIndex:0,onKeyDown:t=>{(t.key==="Enter"||t.key===" ")&&ee(n)},children:[e.jsxs("div",{className:"agent-import-browse-item-header",children:[e.jsx("span",{className:"agent-import-browse-item-name",children:n.name}),n.installs!==void 0&&e.jsxs("span",{className:"agent-import-browse-item-installs",children:[n.installs.toLocaleString()," installs"]})]}),n.tagline&&e.jsx("span",{className:"agent-import-browse-item-tagline",children:n.tagline}),n.repo&&e.jsx("span",{className:"agent-import-browse-item-repo",children:n.repo})]},n.slug)),U.filter(n=>P===""||n.name.toLowerCase().includes(P.toLowerCase())||(n.tagline?.toLowerCase().includes(P.toLowerCase())??!1)).length===0&&e.jsx("p",{className:"agent-import-browse-empty",children:P?"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.`}];function wn({value:a,onChange:l,projectId:f,disabled:m=!1,id:c,label:d="Skills"}){const[r,u]=s.useState([]),[o,g]=s.useState(!0);s.useEffect(()=>{let p=!1;return g(!0),dt(f).then(w=>{p||u(w)}).catch(()=>{p||u([])}).finally(()=>{p||g(!1)}),()=>{p=!0}},[f]);const b=p=>{a.includes(p)||l([...a,p])},N=p=>{l(a.filter(w=>w!==p))},x=p=>r.find(C=>C.id===p)?.name??p,I=r.filter(p=>!a.includes(p.id));return e.jsxs("div",{className:"skill-multiselect","data-testid":"skill-multiselect",children:[d&&e.jsx("label",{htmlFor:c?`${c}-select`:void 0,className:"skill-multiselect-label",children:d}),a.length>0&&e.jsx("div",{className:"skill-multiselect-chips","data-testid":"skill-chips",children:a.map(p=>e.jsxs("span",{className:"skill-chip","data-testid":`skill-chip-${p}`,children:[e.jsx("span",{className:"skill-chip-name",children:x(p)}),e.jsx("button",{type:"button",className:"skill-chip-remove",onClick:()=>N(p),disabled:m,"aria-label":`Remove ${x(p)}`,"data-testid":`remove-skill-${p}`,children:"×"})]},p))}),e.jsx("div",{className:"skill-multiselect-add",children:o?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:c?`${c}-select`:void 0,className:"select skill-multiselect-dropdown",value:"",onChange:p=>{p.target.value&&(b(p.target.value),p.target.value="")},disabled:m,"data-testid":"skill-dropdown",children:[e.jsx("option",{value:"",children:"Add a skill…"}),I.map(p=>e.jsx("option",{value:p.id,children:p.name},p.id))]})})]})}const Ze=[{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:"✦"}],jn=new Set(["triage","executor","reviewer","merger","scheduler","engineer","custom"]);function kn({isOpen:a,onClose:l,onCreated:f,projectId:m}){const[c,d]=s.useState(0),[r,u]=s.useState("presets"),[o,g]=s.useState(""),[b,N]=s.useState(""),[x,I]=s.useState(""),[p,w]=s.useState("custom"),[C,A]=s.useState(""),[E,j]=s.useState(""),[T,W]=s.useState(""),[X,H]=s.useState(""),[L,ie]=s.useState(""),[_,M]=s.useState({model:"",thinkingLevel:"off",maxTurns:1e3}),[k,K]=s.useState(null),[Z,ue]=s.useState([]),[z,me]=s.useState(!1),[U,Y]=s.useState(null),[P,B]=s.useState(!1),[$,ee]=s.useState([]),[re,F]=s.useState(!1),[G,R]=s.useState([]),[V,ne]=s.useState([]),[Q,se]=s.useState([]),[ae,he]=s.useState(!1);s.useEffect(()=>{a&&(F(!0),ut().then(n=>{ee(n.models),R(n.favoriteProviders),ne(n.favoriteModels)}).catch(()=>{}).finally(()=>F(!1)))},[a]),s.useEffect(()=>{a&&(he(!0),se([]),mt(void 0,m).then(n=>{se(n)}).catch(()=>{se([])}).finally(()=>he(!1)))},[a,m]);const J=_.model.includes("/")?_.model:"",ye=s.useCallback(n=>{const t=jn.has(n.role)?n.role:"custom";g(n.title),N(n.description),I(n.icon),w(t),W(n.systemPrompt),M(i=>({...i,thinkingLevel:n.thinkingLevel,maxTurns:n.maxTurns})),B(!1),d(1)},[]),we=s.useCallback(n=>{M(t=>({...t,model:n}))},[]),O=s.useCallback(async n=>{const t=G,h=t.includes(n)?t.filter(v=>v!==n):[n,...t];R(h);try{await ze({favoriteProviders:h,favoriteModels:V})}catch{R(t)}},[G,V]),D=s.useCallback(async n=>{const t=V,h=t.includes(n)?t.filter(v=>v!==n):[n,...t];ne(h);try{await ze({favoriteProviders:G,favoriteModels:h})}catch{ne(t)}},[G,V]),be=s.useCallback(n=>{K(n.id),g(n.name),I(n.icon),N(n.description??n.title),w(n.role),H(n.soul??""),W(n.instructionsText??""),d(1)},[]);if(!a)return null;const le=()=>{d(0),u("presets"),g(""),N(""),I(""),w("custom"),A(""),j(""),W(""),H(""),ie(""),M({model:"",thinkingLevel:"off",maxTurns:1e3}),K(null),ue([]),Y(null),B(!1),l()},je=async()=>{if(o.trim()){me(!0),Y(null);try{const n={};_.model.trim()&&(n.model=_.model.trim()),_.thinkingLevel!=="off"&&(n.thinkingLevel=_.thinkingLevel),_.maxTurns!==1e3&&(n.maxTurns=_.maxTurns),await pt({name:o.trim(),role:p,...b.trim()?{title:b.trim()}:{},...x.trim()?{icon:x.trim()}:{},...C.trim()?{reportsTo:C.trim()}:{},...E.trim()?{instructionsPath:E.trim()}:{},...T.trim()?{instructionsText:T.trim()}:{},...X.trim()?{soul:X.trim()}:{},...L.trim()?{memory:L.trim()}:{},...Object.keys(n).length>0?{runtimeConfig:n}:{},...Z.length>0?{metadata:{skills:Z}}:{}},m),le(),f()}catch(n){Y(n instanceof Error?n.message:"Failed to create agent")}finally{me(!1)}}},ge=Ze.find(n=>n.value===p),te=C.trim(),oe=te?Q.find(n=>n.id===te):void 0;return e.jsxs("div",{className:"agent-dialog-overlay",onClick:n=>{n.target===n.currentTarget&&le()},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:le,"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===c?" active":n<c?" completed":""}`,"aria-label":`Step ${n+1}`},n))}),e.jsxs("div",{className:"agent-dialog-body",children:[c===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:()=>u("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:()=>u("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:yn.map(n=>e.jsxs("button",{type:"button",className:`agent-preset-card${k===n.id?" selected":""}`,"data-testid":`preset-${n.id}`,onClick:()=>be(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 ",!k&&e.jsx("span",{className:"agent-dialog-required",children:"*"})]}),e.jsx("input",{id:"agent-name",type:"text",className:"input",placeholder:"e.g. Frontend Reviewer",value:o,onChange:n=>g(n.target.value)})]}),e.jsxs("div",{className:"agent-dialog-field",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:b,onChange:n=>N(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:x,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:Ze.map(n=>e.jsxs("button",{type:"button",className:`agent-role-option${p===n.value?" selected":""}`,onClick:()=>w(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:C,onChange:n=>A(n.target.value),disabled:ae,children:[e.jsx("option",{value:"",children:"No manager"}),Q.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:X,onChange:n=>H(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:L,onChange:n=>ie(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:E,onChange:n=>j(n.target.value)})]}),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:T,onChange:n=>W(n.target.value)})]})]}),e.jsxs("div",{className:"agent-dialog-ai-generate",children:[e.jsxs("button",{type:"button",className:"btn btn--ai-generate",onClick:()=>B(!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"})]})]})]}),c===1&&e.jsxs("div",{children:[e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx("label",{children:"Model"}),re?e.jsx("div",{className:"agent-dialog-loading",children:"Loading models…"}):e.jsx(ht,{id:"agent-model",label:"Model",value:J,onChange:we,models:$,placeholder:"Select a model…",favoriteProviders:G,onToggleFavorite:O,favoriteModels:V,onToggleModelFavorite:D})]}),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:_.thinkingLevel,onChange:n=>M(t=>({...t,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:_.maxTurns,onChange:n=>M(t=>({...t,maxTurns:Math.max(1,parseInt(n.target.value,10)||1)}))})]}),e.jsxs("div",{className:"agent-dialog-field",children:[e.jsx(wn,{id:"agent-skills",label:"Skills",value:Z,onChange:ue,projectId:m}),e.jsx("p",{className:"agent-dialog-optional agent-dialog-skills-hint",children:"Optional skills to assign to this agent"})]})]}),c===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:[x&&e.jsx("span",{className:"agent-dialog-icon-prefix",children:x}),o]})]}),b&&e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Title"}),e.jsx("span",{children:b})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Role"}),e.jsxs("span",{children:[ge?.icon," ",ge?.label]})]}),te&&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:oe?`${oe.name} (${oe.id})`:te})]}),E.trim()&&e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Instructions File"}),e.jsx("span",{children:E.trim()})]}),T.trim()&&e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Inline Instructions"}),e.jsxs("span",{children:[T.trim().length," chars"]})]}),X.trim()&&e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Soul"}),e.jsxs("span",{children:[X.trim().length," chars"]})]}),e.jsxs("div",{className:"agent-dialog-summary-row",children:[e.jsx("span",{className:"agent-dialog-summary-row-label",children:"Model"}),e.jsx("span",{children:J?e.jsxs(e.Fragment,{children:[e.jsx(gt,{provider:J.split("/")[0],size:"sm"})," ",(()=>{const n=J.indexOf("/"),t=J.slice(0,n),i=J.slice(n+1);return $.find(v=>v.provider===t&&v.id===i)?.name||J})()]}):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:_.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:_.maxTurns})]}),Z.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:[Z.length," skill",Z.length!==1?"s":""," selected"]})]})]}),U&&e.jsx("p",{className:"agent-dialog-error",children:U})]})]}),e.jsxs("div",{className:"agent-dialog-footer",children:[c>0&&e.jsx("button",{className:"btn",onClick:()=>d(n=>n-1),disabled:z,children:"Back"}),e.jsx("button",{className:"btn",onClick:le,disabled:z,children:"Cancel"}),c<2?e.jsx("button",{className:"btn btn--primary",onClick:()=>d(n=>n+1),disabled:c===0&&!o.trim()&&!k,children:"Next"}):e.jsx("button",{className:"btn btn--primary",onClick:()=>void je(),disabled:z||!o.trim(),children:z?"Creating...":"Create"})]})]}),e.jsx(Zt,{isOpen:P,onClose:()=>B(!1),onGenerated:ye,projectId:m})]})}function Nn(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 f=l[1].split(/\r?\n/),m=l[2]??"",c={name:""},d=[];let r=!1;for(const u of f){const g=u.trimEnd().trim();if(!g)continue;if(g.startsWith("skills:")){r=!0;continue}if(r&&g.startsWith("- ")){d.push(g.slice(2).trim());continue}r=!1;const[b,...N]=g.split(":"),I=N.join(":").trim().replace(/^['"]|['"]$/g,"");b==="name"&&(c.name=I),b==="title"&&(c.title=I),b==="icon"&&(c.icon=I),b==="role"&&(c.role=I),b==="reportsTo"&&(c.reportsTo=I)}if(!c.name)throw new Error("Missing required field: name");return d.length>0&&(c.skills=d),m.trim().length>0&&(c.instructionBody=m),c}function In({isOpen:a,onClose:l,onImported:f,projectId:m}){const[c,d]=s.useState("input"),[r,u]=s.useState("paste"),[o,g]=s.useState(""),[b,N]=s.useState([]),[x,I]=s.useState("Unknown"),[p,w]=s.useState([]),[C,A]=s.useState([]),[E,j]=s.useState([]),[T,W]=s.useState([]),[X,H]=s.useState(!1),[L,ie]=s.useState(!1),[_,M]=s.useState(null),[k,K]=s.useState(null),[Z,ue]=s.useState(null),z=s.useRef(null),me=s.useRef(null),[U,Y]=s.useState([]),[P,B]=s.useState(""),[$,ee]=s.useState(null),[re,F]=s.useState(!1),[G,R]=s.useState(null),V=s.useRef(!1);s.useEffect(()=>{r==="browse"&&!V.current&&!re&&(V.current=!0,F(!0),R(null),Oe().then(n=>{n.error?R(n.error):n.companies.length>0?Y(n.companies):R("No companies available")}).catch(n=>{R(n instanceof Error?n.message:"Failed to load companies")}).finally(()=>{F(!1)}))},[r,re]);const ne=s.useCallback(()=>{V.current=!0,R(null),Y([]),ee(null),F(!0),Oe().then(n=>{n.error?R(n.error):n.companies.length>0?Y(n.companies):R("No companies available")}).catch(n=>{R(n instanceof Error?n.message:"Failed to load companies")}).finally(()=>{F(!1)})},[]),Q=s.useCallback(()=>{d("input"),u("paste"),g(""),N([]),I("Unknown"),w([]),A([]),j([]),W([]),H(!1),ie(!1),M(null),K(null),ue(null),Y([]),B(""),ee(null),F(!1),R(null),V.current=!1},[]),se=s.useCallback(()=>{Q(),l()},[Q,l]),ae=s.useCallback(n=>{const t=n.target.files?.[0];if(!t)return;const i=new FileReader;i.onload=h=>{const v=h.target?.result;u("file"),N([]),g(v),M(null)},i.onerror=()=>{M("Failed to read file")},i.readAsText(t),n.target.value=""},[]),he=s.useCallback(async n=>{const t=Array.from(n.target.files??[]);if(t.length!==0)try{const i=t.filter(v=>(v.webkitRelativePath||v.name).toLowerCase().endsWith("agents.md")).sort((v,S)=>{const ce=v.webkitRelativePath||v.name,pe=S.webkitRelativePath||S.name;return ce.localeCompare(pe)});if(i.length===0){M("Selected directory has no AGENTS.md files");return}const h=[];for(const v of i){const S=await v.text();h.push(Nn(S))}u("directory"),N(h),g(""),M(null)}catch{M("Failed to parse AGENTS.md files from selected directory")}finally{n.target.value=""}},[]);function J(n){if(!m)return`/api${n}`;const t=n.includes("?")?"&":"?";return`/api${n}${t}projectId=${encodeURIComponent(m)}`}const ye=s.useCallback(async()=>{if(r==="directory"&&b.length===0){M("Please select a directory containing AGENTS.md files");return}if(r==="browse"&&!$){M("Please select a company from the catalog");return}if(r!=="directory"&&r!=="browse"&&!o.trim()){M("Please provide manifest content");return}H(!0),M(null);try{let n;r==="directory"?n={agents:b,dryRun:!0}:r==="browse"&&$?n={importSource:"companies.sh",companySlug:$.slug,dryRun:!0}:n={manifest:o,dryRun:!0};const t=await fetch(J("/agents/import"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!t.ok){const S=await t.json();throw new Error(S.error??`Parse failed (${t.status})`)}const i=await t.json(),h=i.agents&&i.agents.length>0?i.agents:i.created.map(S=>({name:S,role:"custom"})),v=Array.isArray(i.skills)?i.skills:[];I(i.companyName??"Unknown"),w(h),A(v),j(h.map(S=>S.name)),W(v.map(S=>S.name)),d("preview")}catch(n){M(n instanceof Error?n.message:"Failed to parse manifest")}finally{H(!1)}},[r,b,o,$,m]),we=s.useCallback(async()=>{ie(!0),ue(null);try{let n;r==="directory"?n={agents:b,skipExisting:!0,selectedAgents:E,selectedSkills:T}:r==="browse"&&$?n={importSource:"companies.sh",companySlug:$.slug,skipExisting:!0,selectedAgents:E,selectedSkills:T}:n={manifest:o,skipExisting:!0,selectedAgents:E,selectedSkills:T};const t=await fetch(J("/agents/import"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!t.ok){const h=await t.json();throw new Error(h.error??`Import failed (${t.status})`)}const i=await t.json();K(i),d("result"),f()}catch(n){ue(n instanceof Error?n.message:"Failed to import agents")}finally{ie(!1)}},[r,b,o,$,E,T,m,f]),O=E.length,D=T.length,be=`${O} Agent${O!==1?"s":""}`,le=`${D} Skill${D!==1?"s":""}`,je=O>0&&D>0?`${be} + ${le}`:D>0?le:be,ge=O>0&&D>0?`Importing ${O} agent${O!==1?"s":""} and ${D} skill${D!==1?"s":""}...`:D>0?`Importing ${D} skill${D!==1?"s":""}...`:`Importing ${O} agent${O!==1?"s":""}...`,te=n=>{j(t=>t.includes(n)?t.filter(i=>i!==n):[...t,n])},oe=n=>{W(t=>t.includes(n)?t.filter(i=>i!==n):[...t,n])};return a?e.jsx("div",{className:"agent-dialog-overlay",onClick:n=>{n.target===n.currentTarget&&se()},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:se,"aria-label":"Close",children:"×"})]}),e.jsxs("div",{className:"agent-dialog-body",children:[c==="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:z,type:"file",accept:".md,.txt",onChange:ae,className:"agent-import-file-input","aria-label":"Upload agent manifest file"}),e.jsx("input",{ref:me,type:"file",webkitdirectory:"",multiple:!0,onChange:he,className:"agent-import-file-input","aria-label":"Select directory"}),e.jsxs("button",{type:"button",className:"btn agent-import-upload-btn",onClick:()=>z.current?.click(),children:[e.jsx(nt,{size:16}),"Choose File"]}),e.jsxs("button",{type:"button",className:"btn agent-import-upload-btn",onClick:()=>me.current?.click(),children:[e.jsx($t,{size:16}),"Select Directory"]}),e.jsxs("button",{type:"button",className:"btn agent-import-upload-btn",onClick:()=>{u("browse"),N([]),g(""),ee(null),M(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(bt,{size:16,className:"agent-import-browse-search-icon"}),e.jsx("input",{type:"text",className:"agent-import-browse-search-input",placeholder:"Search companies...",value:P,onChange:n=>B(n.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:()=>ee(null),children:"Change"})]})]}),re&&e.jsxs("div",{className:"agent-import-browse-loading",children:[e.jsx(Te,{size:20,className:"spin"}),e.jsx("span",{children:"Loading companies..."})]}),G&&e.jsxs("div",{className:"agent-import-browse-error",children:[e.jsx(Me,{size:16}),e.jsx("span",{children:G}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:ne,children:[e.jsx($e,{size:14}),"Retry"]})]}),!re&&!G&&e.jsxs("div",{className:"agent-import-browse-list",children:[U.filter(n=>P===""||n.name.toLowerCase().includes(P.toLowerCase())||(n.tagline?.toLowerCase().includes(P.toLowerCase())??!1)).map(n=>e.jsxs("div",{className:`agent-import-browse-item ${$?.slug===n.slug?"agent-import-browse-item--selected":""}`,onClick:()=>ee(n),role:"button",tabIndex:0,onKeyDown:t=>{(t.key==="Enter"||t.key===" ")&&ee(n)},children:[e.jsxs("div",{className:"agent-import-browse-item-header",children:[e.jsx("span",{className:"agent-import-browse-item-name",children:n.name}),n.installs!==void 0&&e.jsxs("span",{className:"agent-import-browse-item-installs",children:[n.installs.toLocaleString()," installs"]})]}),n.tagline&&e.jsx("span",{className:"agent-import-browse-item-tagline",children:n.tagline}),n.repo&&e.jsx("span",{className:"agent-import-browse-item-repo",children:n.repo})]},n.slug)),U.filter(n=>P===""||n.name.toLowerCase().includes(P.toLowerCase())||(n.tagline?.toLowerCase().includes(P.toLowerCase())??!1)).length===0&&e.jsx("p",{className:"agent-import-browse-empty",children:P?"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:o,onChange:n=>{u("paste"),N([]),g(n.target.value),M(null)},rows:8,"aria-label":"Manifest content"})]}),e.jsxs("p",{className:"agent-import-file-hint",children:["Current input: ",r]}),_&&e.jsxs("p",{className:"agent-dialog-error",children:[e.jsx(Me,{size:14}),_]})]}),c==="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:x})]}),e.jsxs("div",{className:"agent-import-count",children:[e.jsx(qe,{size:14}),e.jsxs("span",{children:[p.length," agent",p.length!==1?"s":""," found"]})]}),p.length>0&&e.jsxs("div",{className:"agent-import-selection-controls",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>j(p.map(n=>n.name)),children:"Select all agents"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>j([]),children:"Clear agents"})]}),p.length>0?e.jsx("div",{className:"agent-import-agent-list",children:p.map((n,t)=>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 ${n.name}`,checked:E.includes(n.name),onChange:()=>te(n.name)})}),e.jsx("span",{className:"agent-import-agent-icon",children:n.icon||"🤖"}),e.jsxs("div",{className:"agent-import-agent-details",children:[e.jsx("span",{className:"agent-import-agent-name",children:n.name}),e.jsxs("span",{className:"agent-import-agent-meta",children:[n.title&&e.jsxs("span",{className:"agent-import-agent-title",children:[n.title," · "]}),e.jsx("span",{className:"agent-import-agent-role",children:n.role}),n.reportsTo&&e.jsxs("span",{className:"agent-import-agent-reports",children:[" · reports to ",n.reportsTo]}),n.skills&&n.skills.length>0&&e.jsxs("span",{className:"agent-import-agent-model",children:[" · skills: ",n.skills.join(", ")]})]}),n.instructionsText&&e.jsxs("span",{className:"agent-import-agent-instructions",children:[n.instructionsText.slice(0,100),n.instructionsText.length>100?"...":""]})]})]},t))}):e.jsx("p",{className:"agent-import-empty",children:"No agents found in the manifest."}),C.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:[C.length," skill",C.length!==1?"s":""," found"]})]}),e.jsxs("div",{className:"agent-import-selection-controls",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>W(C.map(n=>n.name)),children:"Select all skills"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>W([]),children:"Clear skills"})]}),e.jsx("div",{className:"agent-import-skill-list",children:C.map((n,t)=>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 ${n.name}`,checked:T.includes(n.name),onChange:()=>ce(n.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:n.name}),n.description&&e.jsx("span",{className:"agent-import-skill-description",children:n.description})]})]},`${n.name}-${t}`))})]}),Z&&e.jsxs("p",{className:"agent-dialog-error",children:[e.jsx(Me,{size:14}),Z]})]}),c==="result"&&k&&e.jsxs("div",{className:"agent-import-result",children:[e.jsx("div",{className:"agent-import-result-icon",children:e.jsx(Se,{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:k.companyName??"Unknown"})]}),e.jsxs("div",{className:"agent-import-result-stats",children:[k.created.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--success",children:e.jsxs("span",{children:[k.created.length," created"]})}),k.skipped.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--skipped",children:e.jsxs("span",{children:[k.skipped.length," skipped (already exist)"]})}),k.errors.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--error",children:e.jsxs("span",{children:[k.errors.length," error",k.errors.length!==1?"s":""]})})]}),k.created.length>0&&e.jsx("div",{className:"agent-import-result-agents",children:k.created.map((n,t)=>e.jsxs("div",{className:"agent-import-result-agent",children:[e.jsx(Se,{size:12}),e.jsx("span",{children:n.name})]},t))}),k.errors.length>0&&e.jsx("div",{className:"agent-import-result-errors",children:k.errors.map((n,t)=>e.jsxs("div",{className:"agent-import-result-error",children:[e.jsx(He,{size:12}),e.jsxs("span",{children:[n.name,": ",n.error]})]},t))}),k.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:[k.skills.imported.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--success",children:e.jsxs("span",{children:[k.skills.imported.length," skill",k.skills.imported.length!==1?"s":""," imported"]})}),k.skills.skipped.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--skipped",children:e.jsxs("span",{children:[k.skills.skipped.length," skill",k.skills.skipped.length!==1?"s":""," skipped (already exist)"]})}),k.skills.errors.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--error",children:e.jsxs("span",{children:[k.skills.errors.length," skill",k.skills.errors.length!==1?"s":""," error",k.skills.errors.length!==1?"s":""]})}),k.skills.imported.length===0&&k.skills.skipped.length===0&&k.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"})})]}),k.skills.imported.length>0&&e.jsx("div",{className:"agent-import-result-agents",children:k.skills.imported.map((n,t)=>e.jsxs("div",{className:"agent-import-result-agent",children:[e.jsx(Se,{size:12}),e.jsx("span",{children:n.name})]},t))}),k.skills.errors.length>0&&e.jsx("div",{className:"agent-import-result-errors",children:k.skills.errors.map((n,t)=>e.jsxs("div",{className:"agent-import-result-error",children:[e.jsx(He,{size:12}),e.jsxs("span",{children:[n.name,": ",n.error]})]},t))})]})]})]}),e.jsxs("div",{className:"agent-dialog-footer",children:[c==="preview"&&e.jsx("button",{className:"btn",onClick:()=>d("input"),disabled:L,children:"Back"}),e.jsx("button",{className:"btn",onClick:se,disabled:L,children:c==="result"?"Close":"Cancel"}),c==="input"&&e.jsx("button",{className:"btn btn--primary",onClick:()=>void ye(),disabled:X||(r==="directory"?b.length===0:r==="browse"?!$:!o.trim()),children:X?e.jsxs(e.Fragment,{children:[e.jsx(Te,{size:14,className:"spin"}),"Parsing..."]}):"Preview"}),c==="preview"&&e.jsx("button",{className:"btn btn--primary",onClick:()=>void we(),disabled:L||O===0&&D===0,children:L?e.jsxs(e.Fragment,{children:[e.jsx(Te,{size:14,className:"spin"}),ge]}):`Import ${je}`})]})]})}):null}const Cn=s.lazy(()=>Rt(()=>import("./AgentDetailView-CBdzWtd-.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8])).then(a=>({default:a.AgentDetailView}))),Ce=[{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:"✦"}],Pe=[.1,.25,.5,1,2,3,5,10];function Ee(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 et(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 it({node:a,onSelect:l,onToggle:f,isExpanded:m,getChildCount:c,getHealthStatus:d,getRoleIcon:r,getSkillBadges:u}){const{agent:o,children:g,depth:b}=a,N=c(o.id),x=m(o.id),I=d(o),p=Ee(o.state);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`agent-tree__node${o.reportsTo?" agent-is-child":""} agent-tree__indent--${Math.min(b,4)}`,children:[e.jsx("button",{className:`agent-tree__toggle${N===0?" agent-tree__toggle--leaf":""}`,onClick:()=>N>0&&f(o.id),title:N>0?x?"Collapse":"Expand":"No employees","aria-label":N>0?x?"Collapse":"Expand":"No employees",children:N>0?x?e.jsx(At,{size:16}):e.jsx(nt,{size:16}):e.jsx(De,{size:14})}),e.jsxs("div",{className:"agent-tree__content",onClick:()=>l(o.id),role:"button",tabIndex:0,onKeyDown:w=>w.key==="Enter"&&l(o.id),children:[e.jsx("span",{className:"agent-tree__icon",children:r(o.role)}),e.jsx("span",{className:"agent-tree__name",children:o.name}),e.jsx("span",{className:`agent-tree__badge ${p}`,children:o.state}),e.jsx("span",{className:"agent-tree__health",style:{color:I.color},title:I.label,children:I.icon}),N>0&&e.jsxs("span",{className:"agent-tree__count text-secondary",children:["(",N,")"]}),(()=>{const w=u(o);return w.length===0?null:e.jsxs("span",{className:"agent-tree__skill",title:w.join(", "),children:[w[0],w.length>1&&` +${w.length-1}`]})})()]})]}),x&&g.length>0&&e.jsx("div",{className:"agent-tree__children",children:g.map(w=>e.jsx(it,{node:w,onSelect:l,onToggle:f,isExpanded:m,getChildCount:c,getHealthStatus:d,getRoleIcon:r,getSkillBadges:u},w.agent.id))})]})}function rt({node:a,onSelect:l,getHealthStatus:f,getRoleIcon:m,getSkillBadges:c}){const{agent:d,children:r}=a,u=f(d),o=Ee(d.state);return e.jsxs("div",{className:`org-chart-node${r.length>0?" org-chart-node--has-children":""}`,children:[e.jsxs("div",{className:"org-chart-node-card",onClick:()=>l(d.id),role:"button",tabIndex:0,onKeyDown:g=>g.key==="Enter"&&l(d.id),children:[e.jsxs("div",{className:"org-chart-node__header",children:[e.jsx("span",{className:"org-chart-node__icon",children:m(d.role)}),e.jsx("span",{className:"org-chart-node__name",children:d.name})]}),e.jsxs("div",{className:"org-chart-node__meta",children:[e.jsx("span",{className:`org-chart-node__badge ${o}`,children:d.state}),e.jsxs("span",{className:"org-chart-node__health",style:{color:u.color},title:u.label,children:[u.icon,!u.stateDerived&&e.jsx("span",{className:"text-secondary",children:u.label})]}),(()=>{const g=c(d);if(g.length===0)return null;const b=g.slice(0,2),N=g.length-2;return e.jsxs(e.Fragment,{children:[b.map(x=>e.jsx("span",{className:"org-chart-node__skill",children:x},x)),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":`${d.name} employees`,children:r.map(g=>e.jsx(rt,{node:g,onSelect:l,getHealthStatus:f,getRoleIcon:m,getSkillBadges:c},g.agent.id))})]})}function Sn({addToast:a,projectId:l}){const[f,m]=s.useState(!1),[c,d]=s.useState("all"),{agents:r,activeAgents:u,stats:o,isLoading:g,loadAgents:b}=xt(l,{filterState:c,showSystemAgents:f}),[N,x]=s.useState(!1),[I,p]=s.useState(!1),[w,C]=s.useState(null),[A,E]=s.useState(()=>{if(typeof window>"u")return"list";const t=Re("fn-agent-view",l);return t==="list"||t==="board"||t==="tree"||t==="org"?t:"list"}),[j,T]=s.useState([]),[W,X]=s.useState(!1),[H,L]=s.useState(!1),re=s.useRef(null),_=s.useRef(null),M=s.useId();s.useEffect(()=>{const t=Re("fn-agent-view",l);if(t==="list"||t==="board"||t==="tree"||t==="org"){E(t);return}E("list")},[l]),s.useEffect(()=>{tt("fn-agent-view",A,l)},[A,l]);const[k,K]=s.useState(null),Z=s.useRef(null),[ue,z]=s.useState(null),[me,U]=s.useState(null),[Y,P]=s.useState({}),[B,$]=s.useState(1),[ee,le]=s.useState(!1),[F,G]=s.useState(new Set),R=s.useRef(!0);s.useEffect(()=>(R.current=!0,()=>{R.current=!1}),[]),s.useEffect(()=>{yt(l).then(t=>{R.current&&$(t.heartbeatMultiplier??1)}).catch(()=>{})},[l]);const V=s.useCallback(async t=>{const i=Number.isFinite(t)&&t>0?t:1;$(i),le(!0);try{await wt({heartbeatMultiplier:i},l),a(`Heartbeat speed set to ×${i.toFixed(1)}`,"success")}catch(h){a(`Failed to save heartbeat multiplier: ${ie(h)}`,"error")}finally{R.current&&le(!1)}},[l,a]),ne=Xt(r,l),Q=s.useMemo(()=>r.filter(t=>f||!Ve(t)),[r,f]),se=s.useMemo(()=>{if(f)return j;const t=i=>Ve(i.agent)?null:{...i,children:i.children.map(t).filter(h=>h!==null)};return j.map(t).filter(i=>i!==null)},[j,f]);s.useEffect(()=>{if(A!=="org")return;let t=!1;return X(!0),jt(l,{includeEphemeral:f}).then(i=>{t||T(i)}).catch(i=>{t||(a(`Failed to load org chart: ${ie(i)}`,"error"),T([]))}).finally(()=>{t||X(!1)}),()=>{t=!0}},[A,l,f,a]),s.useEffect(()=>{const t=setInterval(()=>{b()},3e4);return()=>{clearInterval(t)}},[b]),s.useEffect(()=>{if(!H)return;const t=h=>{const v=h.target;v&&(re.current?.contains(v)||_.current?.contains(v)||L(!1))},i=h=>{h.key==="Escape"&&(L(!1),_.current?.focus())};return document.addEventListener("mousedown",t),document.addEventListener("touchstart",t),document.addEventListener("keydown",i),()=>{document.removeEventListener("mousedown",t),document.removeEventListener("touchstart",t),document.removeEventListener("keydown",i)}},[H]);const ae=async(t,i)=>{if(!F.has(t)){G(h=>new Set(h).add(t));try{if(await _t(t,i,l),a(`Agent state updated to ${i}`,"success"),i==="active")try{await Ge(t,l)}catch(h){a(`Agent activated, but failed to start run: ${ie(h)}`,"error")}b()}catch(h){a(`Failed to update state: ${ie(h)}`,"error")}finally{G(h=>{const v=new Set(h);return v.delete(t),v})}}},he=async(t,i)=>{if(confirm(`Delete agent "${i}"? This cannot be undone.`))try{await Pt(t,l),a(`Agent "${i}" deleted`,"success"),b()}catch(h){a(`Failed to delete agent: ${ie(h)}`,"error")}},J=async(t,i)=>{const h=r.find(v=>v.id===t);if(h){if(h.role===i){K(null);return}try{await Ne(t,{role:i},l),a(`Agent role updated to ${Ce.find(v=>v.value===i)?.label??i}`,"success"),K(null),b()}catch(v){a(`Failed to update role: ${ie(v)}`,"error")}}},ye=(t,i)=>{t.key==="Escape"&&K(null)},we=async(t,i)=>{me===t.id&&(U(null),P(h=>{const v={...h};return delete v[t.id],v})),z(t.id);try{await Ne(t.id,{runtimeConfig:{...t.runtimeConfig??{},heartbeatIntervalMs:i}},l),a(`Heartbeat interval updated to ${Be(i)} for ${t.name}`,"success"),b()}catch(h){a(`Failed to update heartbeat interval: ${ie(h)}`,"error")}finally{z(null)}},O=async t=>{const i=Y[t.id]??"";if(i.trim()===""){a("Please enter a heartbeat interval in minutes","error");return}const h=Number(i);if(isNaN(h)){a("Heartbeat interval must be a valid number","error");return}if(h<=0){a("Heartbeat interval must be greater than 0","error");return}if(h>=1&&h<5){z(t.id);try{await Ne(t.id,{runtimeConfig:{...t.runtimeConfig??{},heartbeatIntervalMs:Mt}},l),a(`Heartbeat interval set to 5 minutes (minimum). ${h} minute${h!==1?"s":""} was below the 5-minute minimum.`,"success"),U(null),P(S=>{const de={...S};return delete de[t.id],de}),b()}catch(S){a(`Failed to update heartbeat interval: ${ie(S)}`,"error")}finally{z(null)}return}const v=Math.round(h*6e4);z(t.id);try{await Ne(t.id,{runtimeConfig:{...t.runtimeConfig??{},heartbeatIntervalMs:v}},l),a(`Heartbeat interval updated to ${Be(v)} for ${t.name}`,"success"),U(null),P(S=>{const de={...S};return delete de[t.id],de}),b()}catch(S){a(`Failed to update heartbeat interval: ${ie(S)}`,"error")}finally{z(null)}},D=t=>{const i=We(t.runtimeConfig?.heartbeatIntervalMs),h=Math.round(i/6e4);U(t.id),P(v=>({...v,[t.id]:String(h)}))},be=s.useCallback(()=>{C(null)},[]),oe=s.useCallback(t=>{C(t)},[]),je=async(t,i)=>{try{await Ge(t,l,{source:"on_demand",triggerDetail:"Triggered from dashboard"}),a(`Heartbeat run started for ${i}`,"success"),b()}catch(h){a(`Failed to start heartbeat run: ${ie(h)}`,"error")}},ge=t=>Ce.find(i=>i.value===t)?.label??t,te=t=>Ce.find(i=>i.value===t)?.icon??"◆",ce=t=>Array.isArray(t.metadata?.skills)?t.metadata.skills:[],n=t=>Tt(t);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(De,{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${A==="list"?" active":""}`,onClick:()=>E("list"),title:"List view","aria-label":"List view","aria-pressed":A==="list",children:e.jsx(kt,{size:16})}),e.jsx("button",{className:`view-toggle-btn${A==="board"?" active":""}`,onClick:()=>E("board"),title:"Board view","aria-label":"Board view","aria-pressed":A==="board",children:e.jsx(xe,{size:16})}),e.jsx("button",{className:`view-toggle-btn${A==="tree"?" active":""}`,onClick:()=>E("tree"),title:"Tree view","aria-label":"Tree view","aria-pressed":A==="tree",children:e.jsx(Nt,{size:16})}),e.jsx("button",{className:`view-toggle-btn${A==="org"?" active":""}`,onClick:()=>E("org"),title:"Org Chart view","aria-label":"Org Chart view","aria-pressed":A==="org",children:e.jsx(zt,{size:16})})]}),e.jsxs("div",{className:"agents-view-primary-actions",children:[e.jsx("button",{ref:_,className:`btn-icon agent-controls-trigger${H?" agent-controls-trigger--active":""}`,onClick:()=>L(t=>!t),title:"Controls","aria-label":"Controls","aria-haspopup":"dialog","aria-expanded":H,"aria-controls":M,children:e.jsx(qt,{size:16})}),e.jsx("button",{className:"btn-icon",onClick:()=>void b(),title:"Refresh","aria-label":"Refresh",children:e.jsx($e,{size:16,className:g?"spin":void 0})}),e.jsxs("button",{className:"btn btn--primary",onClick:()=>{x(!0),L(!1)},children:[e.jsx(It,{size:16}),"New Agent"]})]})]})]}),H&&e.jsxs("div",{ref:re,id:M,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(Ct,{size:14}),e.jsxs("select",{className:"agent-state-filter-select",value:c,onChange:t=>d(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:f,onChange:t=>m(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:()=>{p(!0),L(!1)},children:[e.jsx(st,{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:B,onChange:t=>{const i=Number(t.target.value);V(Number.isFinite(i)&&i>0?i:1)},disabled:ee}),e.jsxs("span",{className:"heartbeat-multiplier-value",children:["×",B.toFixed(1)]}),e.jsx("select",{className:"heartbeat-multiplier-preset",value:String(Pe.reduce((t,i)=>Math.abs(i-B)<Math.abs(t-B)?i:t,Pe[0])),onChange:t=>{const i=Number(t.target.value);V(Number.isFinite(i)&&i>0?i:1)},disabled:ee,"aria-label":"Heartbeat speed preset",children:Pe.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(Gt,{agents:Q})]}),e.jsxs("div",{className:"agents-view-content",children:[e.jsx(Bt,{stats:o}),e.jsx(kn,{isOpen:N,onClose:()=>x(!1),onCreated:()=>{x(!1),b()},projectId:l}),e.jsx(In,{isOpen:I,onClose:()=>p(!1),onImported:()=>void b(),projectId:l}),A==="tree"?e.jsx("div",{className:"agent-tree__view",children:Q.length===0?e.jsx(Ie,{onCtaClick:()=>x(!0)}):ne.rootNodes.map(t=>e.jsx(it,{node:t,onSelect:C,onToggle:ne.toggleExpand,isExpanded:ne.isExpanded,getChildCount:i=>ne.getChildren(i).length,getHealthStatus:n,getRoleIcon:te,getSkillBadges:ce},t.agent.id))}):A==="org"?e.jsx("div",{className:"agent-org-chart","data-testid":"agent-org-chart",children:W?e.jsxs("div",{className:"agent-org-chart__loading",role:"status","aria-live":"polite",children:[e.jsx($e,{size:18,className:"spin"}),e.jsx("span",{children:"Loading org chart..."})]}):se.length===0?e.jsx(Ie,{onCtaClick:()=>x(!0)}):se.map(t=>e.jsx(rt,{node:t,onSelect:C,getHealthStatus:n,getRoleIcon:te,getSkillBadges:ce},t.agent.id))}):A==="board"?e.jsx("div",{className:"agent-board",children:Q.length===0?e.jsx(Ie,{onCtaClick:()=>x(!0)}):Q.map(t=>{const i=n(t),h=Ee(t.state),v=et("agent-board-card",t.state);return e.jsx("div",{className:`agent-board-card ${v}`,children:e.jsxs("div",{className:"agent-board-clickable",onClick:()=>C(t.id),role:"button",tabIndex:0,onKeyDown:S=>S.key==="Enter"&&C(t.id),children:[e.jsxs("div",{className:"agent-board-header",children:[e.jsx("span",{className:"agent-board-icon",children:te(t.role)}),e.jsx("span",{className:"agent-board-badge badge text-secondary",children:ge(t.role)}),e.jsx("span",{className:`agent-board-badge badge ${h}`,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:i.color},title:i.label,children:[i.icon,!i.stateDerived&&` ${i.label}`]})]})},t.id)})}):e.jsx("div",{className:"agent-list",children:Q.length===0?e.jsx(Ie,{onCtaClick:()=>x(!0)}):Q.map(t=>{const i=n(t),h=Ee(t.state),v=et("agent-card",t.state),S=We(t.runtimeConfig?.heartbeatIntervalMs),de=St(S),pe=ue===t.id;return e.jsxs("div",{className:`agent-card ${v}`,children:[e.jsxs("div",{className:"agent-card-header",children:[e.jsxs("div",{className:"agent-info agent-info--clickable",onClick:()=>C(t.id),role:"button",tabIndex:0,onKeyDown:y=>y.key==="Enter"&&C(t.id),children:[k===t.id?e.jsx("select",{ref:Z,className:"select agent-role-select",value:t.role,onChange:y=>void J(t.id,y.target.value),onKeyDown:y=>ye(y,t.id),onBlur:()=>K(null),autoFocus:!0,children:Ce.map(y=>e.jsxs("option",{value:y.value,children:[y.icon," ",y.label]},y.value))}):e.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:y=>{y.stopPropagation(),K(t.id)},title:"Click to change role",role:"button",tabIndex:0,onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.stopPropagation(),K(t.id))},children:te(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(nt,{size:20,className:"agent-card-chevron"})]}),e.jsxs("div",{className:"agent-badges",children:[e.jsx("span",{className:`badge ${h}`,children:t.state}),e.jsxs("span",{className:"badge",style:{color:i.color},title:i.label,children:[i.icon,!i.stateDerived&&` ${i.label}`]}),e.jsx("span",{className:"badge text-secondary",children:ge(t.role)}),(()=>{const y=ce(t);if(y.length===0)return null;const q=y.slice(0,2),fe=y.length-2;return e.jsxs(e.Fragment,{children:[q.map(Le=>e.jsx("span",{className:"badge badge-skill",children:Le},Le)),fe>0&&e.jsxs("span",{className:"badge badge-skill",children:["+",fe]})]})})()]})]}),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:"}),me===t.id?e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"input agent-heartbeat-custom-input",value:Y[t.id]??"",onChange:y=>P(q=>({...q,[t.id]:y.target.value})),onKeyDown:y=>{y.key==="Enter"?O(t):y.key==="Escape"&&(U(null),P(q=>{const fe={...q};return delete fe[t.id],fe}))},disabled:pe,"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 O(t),disabled:pe,title:"Save custom interval",children:"Save"}),e.jsx("button",{className:"btn btn--sm",onClick:()=>{U(null),P(y=>{const q={...y};return delete q[t.id],q})},disabled:pe,title:"Cancel custom interval",children:"Cancel"})]}):e.jsx(e.Fragment,{children:e.jsxs("select",{className:"select agent-heartbeat-select",value:S,onChange:y=>{const q=y.target.value;q==="__custom__"?D(t):we(t,Number(q))},disabled:pe,"aria-label":`Set heartbeat interval for ${t.name}`,children:[de.map(y=>e.jsx("option",{value:y.value,children:y.label},y.value)),Et.some(y=>y.value===S)&&e.jsx("option",{value:"__custom__",children:"Custom..."})]})}),pe&&e.jsx("span",{className:"agent-heartbeat-saving text-secondary",children:"Saving…"}),t.lastHeartbeatAt&&(()=>{const y=new Date(t.lastHeartbeatAt),q=new Date(y.getTime()+S),fe=t.state==="active"||t.state==="running";return e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"agent-heartbeat-last text-secondary",title:y.toLocaleString(),children:["Last: ",y.toLocaleTimeString()]}),fe&&e.jsxs("span",{className:"agent-heartbeat-next text-secondary",title:q.toLocaleString(),children:["Next: ",q.toLocaleTimeString()]})]})})()]})]}),e.jsxs("div",{className:"agent-card-actions",children:[t.state==="idle"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void ae(t.id,"active"),disabled:F.has(t.id),title:"Activate",children:[e.jsx(ke,{size:14})," Start"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void he(t.id,t.name),title:"Delete",children:[e.jsx(Ke,{size:14})," Delete"]})]}),t.state==="active"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void je(t.id,t.name),disabled:F.has(t.id),title:"Run Now","aria-label":`Run now for ${t.name}`,children:[e.jsx(xe,{size:14})," Run Now"]}),e.jsxs("button",{className:"btn btn--sm",onClick:()=>void ae(t.id,"paused"),disabled:F.has(t.id),title:"Pause",children:[e.jsx(Ue,{size:14})," Pause"]})]}),t.state==="paused"&&e.jsxs("button",{className:"btn btn--sm",onClick:()=>void ae(t.id,"active"),disabled:F.has(t.id),title:"Resume",children:[e.jsx(ke,{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(xe,{size:14})," Running"]}),e.jsxs("button",{className:"btn btn--sm",onClick:()=>void ae(t.id,"paused"),disabled:F.has(t.id),title:"Pause",children:[e.jsx(Ue,{size:14})," Pause"]})]}),t.state==="error"&&e.jsxs("button",{className:"btn btn--sm",onClick:()=>void ae(t.id,"active"),disabled:F.has(t.id),title:"Retry",children:[e.jsx(ke,{size:14})," Retry"]}),t.state==="terminated"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void ae(t.id,"active"),disabled:F.has(t.id),title:"Start",children:[e.jsx(ke,{size:14})," Start"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void he(t.id,t.name),title:"Delete",children:[e.jsx(Ke,{size:14})," Delete"]})]}),e.jsx("button",{className:"btn btn--sm agent-card-details-btn",onClick:()=>C(t.id),title:`View details for ${t.name}`,"aria-label":`View details for ${t.name}`,children:"View Details"})]})]},t.id)})}),e.jsx(Kt,{agents:u,projectId:l,onAgentSelect:C})]}),w&&e.jsx(s.Suspense,{fallback:null,children:e.jsx(Cn,{agentId:w,projectId:l,onClose:be,addToast:a,onChildClick:oe})})]})}const _n=Object.freeze(Object.defineProperty({__proto__:null,AgentsView:Sn},Symbol.toStringTag,{value:"Module"}));export{_n as A,wn as S};
522
+ Agent instructions go here...`,value:o,onChange:n=>{u("paste"),N([]),g(n.target.value),M(null)},rows:8,"aria-label":"Manifest content"})]}),e.jsxs("p",{className:"agent-import-file-hint",children:["Current input: ",r]}),_&&e.jsxs("p",{className:"agent-dialog-error",children:[e.jsx(Me,{size:14}),_]})]}),c==="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:x})]}),e.jsxs("div",{className:"agent-import-count",children:[e.jsx(qe,{size:14}),e.jsxs("span",{children:[p.length," agent",p.length!==1?"s":""," found"]})]}),p.length>0&&e.jsxs("div",{className:"agent-import-selection-controls",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>j(p.map(n=>n.name)),children:"Select all agents"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>j([]),children:"Clear agents"})]}),p.length>0?e.jsx("div",{className:"agent-import-agent-list",children:p.map((n,t)=>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 ${n.name}`,checked:E.includes(n.name),onChange:()=>te(n.name)})}),e.jsx("span",{className:"agent-import-agent-icon",children:n.icon||"🤖"}),e.jsxs("div",{className:"agent-import-agent-details",children:[e.jsx("span",{className:"agent-import-agent-name",children:n.name}),e.jsxs("span",{className:"agent-import-agent-meta",children:[n.title&&e.jsxs("span",{className:"agent-import-agent-title",children:[n.title," · "]}),e.jsx("span",{className:"agent-import-agent-role",children:n.role}),n.reportsTo&&e.jsxs("span",{className:"agent-import-agent-reports",children:[" · reports to ",n.reportsTo]}),n.skills&&n.skills.length>0&&e.jsxs("span",{className:"agent-import-agent-model",children:[" · skills: ",n.skills.join(", ")]})]}),n.instructionsText&&e.jsxs("span",{className:"agent-import-agent-instructions",children:[n.instructionsText.slice(0,100),n.instructionsText.length>100?"...":""]})]})]},t))}):e.jsx("p",{className:"agent-import-empty",children:"No agents found in the manifest."}),C.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:[C.length," skill",C.length!==1?"s":""," found"]})]}),e.jsxs("div",{className:"agent-import-selection-controls",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>W(C.map(n=>n.name)),children:"Select all skills"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>W([]),children:"Clear skills"})]}),e.jsx("div",{className:"agent-import-skill-list",children:C.map((n,t)=>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 ${n.name}`,checked:T.includes(n.name),onChange:()=>oe(n.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:n.name}),n.description&&e.jsx("span",{className:"agent-import-skill-description",children:n.description})]})]},`${n.name}-${t}`))})]}),Z&&e.jsxs("p",{className:"agent-dialog-error",children:[e.jsx(Me,{size:14}),Z]})]}),c==="result"&&k&&e.jsxs("div",{className:"agent-import-result",children:[e.jsx("div",{className:"agent-import-result-icon",children:e.jsx(Se,{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:k.companyName??"Unknown"})]}),e.jsxs("div",{className:"agent-import-result-stats",children:[k.created.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--success",children:e.jsxs("span",{children:[k.created.length," created"]})}),k.skipped.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--skipped",children:e.jsxs("span",{children:[k.skipped.length," skipped (already exist)"]})}),k.errors.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--error",children:e.jsxs("span",{children:[k.errors.length," error",k.errors.length!==1?"s":""]})})]}),k.created.length>0&&e.jsx("div",{className:"agent-import-result-agents",children:k.created.map((n,t)=>e.jsxs("div",{className:"agent-import-result-agent",children:[e.jsx(Se,{size:12}),e.jsx("span",{children:n.name})]},t))}),k.errors.length>0&&e.jsx("div",{className:"agent-import-result-errors",children:k.errors.map((n,t)=>e.jsxs("div",{className:"agent-import-result-error",children:[e.jsx(He,{size:12}),e.jsxs("span",{children:[n.name,": ",n.error]})]},t))}),k.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:[k.skills.imported.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--success",children:e.jsxs("span",{children:[k.skills.imported.length," skill",k.skills.imported.length!==1?"s":""," imported"]})}),k.skills.skipped.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--skipped",children:e.jsxs("span",{children:[k.skills.skipped.length," skill",k.skills.skipped.length!==1?"s":""," skipped (already exist)"]})}),k.skills.errors.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--error",children:e.jsxs("span",{children:[k.skills.errors.length," skill",k.skills.errors.length!==1?"s":""," error",k.skills.errors.length!==1?"s":""]})}),k.skills.imported.length===0&&k.skills.skipped.length===0&&k.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"})})]}),k.skills.imported.length>0&&e.jsx("div",{className:"agent-import-result-agents",children:k.skills.imported.map((n,t)=>e.jsxs("div",{className:"agent-import-result-agent",children:[e.jsx(Se,{size:12}),e.jsx("span",{children:n.name})]},t))}),k.skills.errors.length>0&&e.jsx("div",{className:"agent-import-result-errors",children:k.skills.errors.map((n,t)=>e.jsxs("div",{className:"agent-import-result-error",children:[e.jsx(He,{size:12}),e.jsxs("span",{children:[n.name,": ",n.error]})]},t))})]})]})]}),e.jsxs("div",{className:"agent-dialog-footer",children:[c==="preview"&&e.jsx("button",{className:"btn",onClick:()=>d("input"),disabled:L,children:"Back"}),e.jsx("button",{className:"btn",onClick:se,disabled:L,children:c==="result"?"Close":"Cancel"}),c==="input"&&e.jsx("button",{className:"btn btn--primary",onClick:()=>void ye(),disabled:X||(r==="directory"?b.length===0:r==="browse"?!$:!o.trim()),children:X?e.jsxs(e.Fragment,{children:[e.jsx(Te,{size:14,className:"spin"}),"Parsing..."]}):"Preview"}),c==="preview"&&e.jsx("button",{className:"btn btn--primary",onClick:()=>void we(),disabled:L||O===0&&D===0,children:L?e.jsxs(e.Fragment,{children:[e.jsx(Te,{size:14,className:"spin"}),ge]}):`Import ${je}`})]})]})}):null}const Cn=s.lazy(()=>Rt(()=>import("./AgentDetailView-CJIxNRq-.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8])).then(a=>({default:a.AgentDetailView}))),Ce=[{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:"✦"}],Pe=[.1,.25,.5,1,2,3,5,10];function Ee(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 Ye(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 at({node:a,onSelect:l,onToggle:f,isExpanded:m,getChildCount:c,getHealthStatus:d,getRoleIcon:r,getSkillBadges:u}){const{agent:o,children:g,depth:b}=a,N=c(o.id),x=m(o.id),I=d(o),p=Ee(o.state);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`agent-tree__node${o.reportsTo?" agent-is-child":""} agent-tree__indent--${Math.min(b,4)}`,children:[e.jsx("button",{className:`agent-tree__toggle${N===0?" agent-tree__toggle--leaf":""}`,onClick:()=>N>0&&f(o.id),title:N>0?x?"Collapse":"Expand":"No employees","aria-label":N>0?x?"Collapse":"Expand":"No employees",children:N>0?x?e.jsx(Et,{size:16}):e.jsx(tt,{size:16}):e.jsx(De,{size:14})}),e.jsxs("div",{className:"agent-tree__content",onClick:()=>l(o.id),role:"button",tabIndex:0,onKeyDown:w=>w.key==="Enter"&&l(o.id),children:[e.jsx("span",{className:"agent-tree__icon",children:r(o.role)}),e.jsx("span",{className:"agent-tree__name",children:o.name}),e.jsx("span",{className:`agent-tree__badge ${p}`,children:o.state}),e.jsx("span",{className:"agent-tree__health",style:{color:I.color},title:I.label,children:I.icon}),N>0&&e.jsxs("span",{className:"agent-tree__count text-secondary",children:["(",N,")"]}),(()=>{const w=u(o);return w.length===0?null:e.jsxs("span",{className:"agent-tree__skill",title:w.join(", "),children:[w[0],w.length>1&&` +${w.length-1}`]})})()]})]}),x&&g.length>0&&e.jsx("div",{className:"agent-tree__children",children:g.map(w=>e.jsx(at,{node:w,onSelect:l,onToggle:f,isExpanded:m,getChildCount:c,getHealthStatus:d,getRoleIcon:r,getSkillBadges:u},w.agent.id))})]})}function it({node:a,onSelect:l,getHealthStatus:f,getRoleIcon:m,getSkillBadges:c}){const{agent:d,children:r}=a,u=f(d),o=Ee(d.state);return e.jsxs("div",{className:`org-chart-node${r.length>0?" org-chart-node--has-children":""}`,children:[e.jsxs("div",{className:"org-chart-node-card",onClick:()=>l(d.id),role:"button",tabIndex:0,onKeyDown:g=>g.key==="Enter"&&l(d.id),children:[e.jsxs("div",{className:"org-chart-node__header",children:[e.jsx("span",{className:"org-chart-node__icon",children:m(d.role)}),e.jsx("span",{className:"org-chart-node__name",children:d.name})]}),e.jsxs("div",{className:"org-chart-node__meta",children:[e.jsx("span",{className:`org-chart-node__badge ${o}`,children:d.state}),e.jsxs("span",{className:"org-chart-node__health",style:{color:u.color},title:u.label,children:[u.icon,!u.stateDerived&&e.jsx("span",{className:"text-secondary",children:u.label})]}),(()=>{const g=c(d);if(g.length===0)return null;const b=g.slice(0,2),N=g.length-2;return e.jsxs(e.Fragment,{children:[b.map(x=>e.jsx("span",{className:"org-chart-node__skill",children:x},x)),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":`${d.name} employees`,children:r.map(g=>e.jsx(it,{node:g,onSelect:l,getHealthStatus:f,getRoleIcon:m,getSkillBadges:c},g.agent.id))})]})}function Sn({addToast:a,projectId:l}){const[f,m]=s.useState(!1),[c,d]=s.useState("all"),{agents:r,activeAgents:u,stats:o,isLoading:g,loadAgents:b}=vt(l,{filterState:c,showSystemAgents:f}),[N,x]=s.useState(!1),[I,p]=s.useState(!1),[w,C]=s.useState(null),[A,E]=s.useState(()=>{if(typeof window>"u")return"list";const t=Re("fn-agent-view",l);return t==="list"||t==="board"||t==="tree"||t==="org"?t:"list"}),[j,T]=s.useState([]),[W,X]=s.useState(!1),[H,L]=s.useState(!1),ie=s.useRef(null),_=s.useRef(null),M=s.useId();s.useEffect(()=>{const t=Re("fn-agent-view",l);if(t==="list"||t==="board"||t==="tree"||t==="org"){E(t);return}E("list")},[l]),s.useEffect(()=>{et("fn-agent-view",A,l)},[A,l]);const[k,K]=s.useState(null),Z=s.useRef(null),[ue,z]=s.useState(null),[me,U]=s.useState(null),[Y,P]=s.useState({}),[B,$]=s.useState(1),[ee,re]=s.useState(!1),[F,G]=s.useState(new Set),R=s.useRef(!0);s.useEffect(()=>(R.current=!0,()=>{R.current=!1}),[]),s.useEffect(()=>{xt(l).then(t=>{R.current&&$(t.heartbeatMultiplier??1)}).catch(()=>{})},[l]);const V=s.useCallback(async t=>{const i=Number.isFinite(t)&&t>0?t:1;$(i),re(!0);try{await yt({heartbeatMultiplier:i},l),a(`Heartbeat speed set to ×${i.toFixed(1)}`,"success")}catch(h){a(`Failed to save heartbeat multiplier: ${de(h)}`,"error")}finally{R.current&&re(!1)}},[l,a]),ne=Xt(r,l),Q=s.useMemo(()=>r.filter(t=>f||!Ve(t)),[r,f]),se=s.useMemo(()=>{if(f)return j;const t=i=>Ve(i.agent)?null:{...i,children:i.children.map(t).filter(h=>h!==null)};return j.map(t).filter(i=>i!==null)},[j,f]);s.useEffect(()=>{if(A!=="org")return;let t=!1;return X(!0),wt(l,{includeEphemeral:f}).then(i=>{t||T(i)}).catch(i=>{t||(a(`Failed to load org chart: ${de(i)}`,"error"),T([]))}).finally(()=>{t||X(!1)}),()=>{t=!0}},[A,l,f,a]),s.useEffect(()=>{const t=setInterval(()=>{b()},3e4);return()=>{clearInterval(t)}},[b]),s.useEffect(()=>{if(!H)return;const t=h=>{const v=h.target;v&&(ie.current?.contains(v)||_.current?.contains(v)||L(!1))},i=h=>{h.key==="Escape"&&(L(!1),_.current?.focus())};return document.addEventListener("mousedown",t),document.addEventListener("touchstart",t),document.addEventListener("keydown",i),()=>{document.removeEventListener("mousedown",t),document.removeEventListener("touchstart",t),document.removeEventListener("keydown",i)}},[H]);const ae=async(t,i)=>{if(!F.has(t)){G(h=>new Set(h).add(t));try{await Mt(t,i,l),a(`Agent state updated to ${i}`,"success"),b()}catch(h){a(`Failed to update state: ${de(h)}`,"error")}finally{G(h=>{const v=new Set(h);return v.delete(t),v})}}},he=async(t,i)=>{if(confirm(`Delete agent "${i}"? This cannot be undone.`))try{await _t(t,l),a(`Agent "${i}" deleted`,"success"),b()}catch(h){a(`Failed to delete agent: ${de(h)}`,"error")}},J=async(t,i)=>{const h=r.find(v=>v.id===t);if(h){if(h.role===i){K(null);return}try{await Ne(t,{role:i},l),a(`Agent role updated to ${Ce.find(v=>v.value===i)?.label??i}`,"success"),K(null),b()}catch(v){a(`Failed to update role: ${de(v)}`,"error")}}},ye=(t,i)=>{t.key==="Escape"&&K(null)},we=async(t,i)=>{me===t.id&&(U(null),P(h=>{const v={...h};return delete v[t.id],v})),z(t.id);try{await Ne(t.id,{runtimeConfig:{...t.runtimeConfig??{},heartbeatIntervalMs:i}},l),a(`Heartbeat interval updated to ${Be(i)} for ${t.name}`,"success"),b()}catch(h){a(`Failed to update heartbeat interval: ${de(h)}`,"error")}finally{z(null)}},O=async t=>{const i=Y[t.id]??"";if(i.trim()===""){a("Please enter a heartbeat interval in minutes","error");return}const h=Number(i);if(isNaN(h)){a("Heartbeat interval must be a valid number","error");return}if(h<=0){a("Heartbeat interval must be greater than 0","error");return}if(h>=1&&h<5){z(t.id);try{await Ne(t.id,{runtimeConfig:{...t.runtimeConfig??{},heartbeatIntervalMs:Tt}},l),a(`Heartbeat interval set to 5 minutes (minimum). ${h} minute${h!==1?"s":""} was below the 5-minute minimum.`,"success"),U(null),P(S=>{const ce={...S};return delete ce[t.id],ce}),b()}catch(S){a(`Failed to update heartbeat interval: ${de(S)}`,"error")}finally{z(null)}return}const v=Math.round(h*6e4);z(t.id);try{await Ne(t.id,{runtimeConfig:{...t.runtimeConfig??{},heartbeatIntervalMs:v}},l),a(`Heartbeat interval updated to ${Be(v)} for ${t.name}`,"success"),U(null),P(S=>{const ce={...S};return delete ce[t.id],ce}),b()}catch(S){a(`Failed to update heartbeat interval: ${de(S)}`,"error")}finally{z(null)}},D=t=>{const i=We(t.runtimeConfig?.heartbeatIntervalMs),h=Math.round(i/6e4);U(t.id),P(v=>({...v,[t.id]:String(h)}))},be=s.useCallback(()=>{C(null)},[]),le=s.useCallback(t=>{C(t)},[]),je=async(t,i)=>{try{await Pt(t,l,{source:"on_demand",triggerDetail:"Triggered from dashboard"}),a(`Heartbeat run started for ${i}`,"success"),b()}catch(h){a(`Failed to start heartbeat run: ${de(h)}`,"error")}},ge=t=>Ce.find(i=>i.value===t)?.label??t,te=t=>Ce.find(i=>i.value===t)?.icon??"◆",oe=t=>Array.isArray(t.metadata?.skills)?t.metadata.skills:[],n=t=>At(t);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(De,{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${A==="list"?" active":""}`,onClick:()=>E("list"),title:"List view","aria-label":"List view","aria-pressed":A==="list",children:e.jsx(jt,{size:16})}),e.jsx("button",{className:`view-toggle-btn${A==="board"?" active":""}`,onClick:()=>E("board"),title:"Board view","aria-label":"Board view","aria-pressed":A==="board",children:e.jsx(xe,{size:16})}),e.jsx("button",{className:`view-toggle-btn${A==="tree"?" active":""}`,onClick:()=>E("tree"),title:"Tree view","aria-label":"Tree view","aria-pressed":A==="tree",children:e.jsx(kt,{size:16})}),e.jsx("button",{className:`view-toggle-btn${A==="org"?" active":""}`,onClick:()=>E("org"),title:"Org Chart view","aria-label":"Org Chart view","aria-pressed":A==="org",children:e.jsx(zt,{size:16})})]}),e.jsxs("div",{className:"agents-view-primary-actions",children:[e.jsx("button",{ref:_,className:`btn-icon agent-controls-trigger${H?" agent-controls-trigger--active":""}`,onClick:()=>L(t=>!t),title:"Controls","aria-label":"Controls","aria-haspopup":"dialog","aria-expanded":H,"aria-controls":M,children:e.jsx(qt,{size:16})}),e.jsx("button",{className:"btn-icon",onClick:()=>void b(),title:"Refresh","aria-label":"Refresh",children:e.jsx($e,{size:16,className:g?"spin":void 0})}),e.jsxs("button",{className:"btn btn--primary",onClick:()=>{x(!0),L(!1)},children:[e.jsx(Nt,{size:16}),"New Agent"]})]})]})]}),H&&e.jsxs("div",{ref:ie,id:M,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(It,{size:14}),e.jsxs("select",{className:"agent-state-filter-select",value:c,onChange:t=>d(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:f,onChange:t=>m(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:()=>{p(!0),L(!1)},children:[e.jsx(nt,{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:B,onChange:t=>{const i=Number(t.target.value);V(Number.isFinite(i)&&i>0?i:1)},disabled:ee}),e.jsxs("span",{className:"heartbeat-multiplier-value",children:["×",B.toFixed(1)]}),e.jsx("select",{className:"heartbeat-multiplier-preset",value:String(Pe.reduce((t,i)=>Math.abs(i-B)<Math.abs(t-B)?i:t,Pe[0])),onChange:t=>{const i=Number(t.target.value);V(Number.isFinite(i)&&i>0?i:1)},disabled:ee,"aria-label":"Heartbeat speed preset",children:Pe.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(Gt,{agents:Q})]}),e.jsxs("div",{className:"agents-view-content",children:[e.jsx(Bt,{stats:o}),e.jsx(kn,{isOpen:N,onClose:()=>x(!1),onCreated:()=>{x(!1),b()},projectId:l}),e.jsx(In,{isOpen:I,onClose:()=>p(!1),onImported:()=>void b(),projectId:l}),A==="tree"?e.jsx("div",{className:"agent-tree__view",children:Q.length===0?e.jsx(Ie,{onCtaClick:()=>x(!0)}):ne.rootNodes.map(t=>e.jsx(at,{node:t,onSelect:C,onToggle:ne.toggleExpand,isExpanded:ne.isExpanded,getChildCount:i=>ne.getChildren(i).length,getHealthStatus:n,getRoleIcon:te,getSkillBadges:oe},t.agent.id))}):A==="org"?e.jsx("div",{className:"agent-org-chart","data-testid":"agent-org-chart",children:W?e.jsxs("div",{className:"agent-org-chart__loading",role:"status","aria-live":"polite",children:[e.jsx($e,{size:18,className:"spin"}),e.jsx("span",{children:"Loading org chart..."})]}):se.length===0?e.jsx(Ie,{onCtaClick:()=>x(!0)}):se.map(t=>e.jsx(it,{node:t,onSelect:C,getHealthStatus:n,getRoleIcon:te,getSkillBadges:oe},t.agent.id))}):A==="board"?e.jsx("div",{className:"agent-board",children:Q.length===0?e.jsx(Ie,{onCtaClick:()=>x(!0)}):Q.map(t=>{const i=n(t),h=Ee(t.state),v=Ye("agent-board-card",t.state);return e.jsx("div",{className:`agent-board-card ${v}`,children:e.jsxs("div",{className:"agent-board-clickable",onClick:()=>C(t.id),role:"button",tabIndex:0,onKeyDown:S=>S.key==="Enter"&&C(t.id),children:[e.jsxs("div",{className:"agent-board-header",children:[e.jsx("span",{className:"agent-board-icon",children:te(t.role)}),e.jsx("span",{className:"agent-board-badge badge text-secondary",children:ge(t.role)}),e.jsx("span",{className:`agent-board-badge badge ${h}`,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:i.color},title:i.label,children:[i.icon,!i.stateDerived&&` ${i.label}`]})]})},t.id)})}):e.jsx("div",{className:"agent-list",children:Q.length===0?e.jsx(Ie,{onCtaClick:()=>x(!0)}):Q.map(t=>{const i=n(t),h=Ee(t.state),v=Ye("agent-card",t.state),S=We(t.runtimeConfig?.heartbeatIntervalMs),ce=Ct(S),pe=ue===t.id;return e.jsxs("div",{className:`agent-card ${v}`,children:[e.jsxs("div",{className:"agent-card-header",children:[e.jsxs("div",{className:"agent-info agent-info--clickable",onClick:()=>C(t.id),role:"button",tabIndex:0,onKeyDown:y=>y.key==="Enter"&&C(t.id),children:[k===t.id?e.jsx("select",{ref:Z,className:"select agent-role-select",value:t.role,onChange:y=>void J(t.id,y.target.value),onKeyDown:y=>ye(y,t.id),onBlur:()=>K(null),autoFocus:!0,children:Ce.map(y=>e.jsxs("option",{value:y.value,children:[y.icon," ",y.label]},y.value))}):e.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:y=>{y.stopPropagation(),K(t.id)},title:"Click to change role",role:"button",tabIndex:0,onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.stopPropagation(),K(t.id))},children:te(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(tt,{size:20,className:"agent-card-chevron"})]}),e.jsxs("div",{className:"agent-badges",children:[e.jsx("span",{className:`badge ${h}`,children:t.state}),e.jsxs("span",{className:"badge",style:{color:i.color},title:i.label,children:[i.icon,!i.stateDerived&&` ${i.label}`]}),e.jsx("span",{className:"badge text-secondary",children:ge(t.role)}),(()=>{const y=oe(t);if(y.length===0)return null;const q=y.slice(0,2),fe=y.length-2;return e.jsxs(e.Fragment,{children:[q.map(Le=>e.jsx("span",{className:"badge badge-skill",children:Le},Le)),fe>0&&e.jsxs("span",{className:"badge badge-skill",children:["+",fe]})]})})()]})]}),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:"}),me===t.id?e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"input agent-heartbeat-custom-input",value:Y[t.id]??"",onChange:y=>P(q=>({...q,[t.id]:y.target.value})),onKeyDown:y=>{y.key==="Enter"?O(t):y.key==="Escape"&&(U(null),P(q=>{const fe={...q};return delete fe[t.id],fe}))},disabled:pe,"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 O(t),disabled:pe,title:"Save custom interval",children:"Save"}),e.jsx("button",{className:"btn btn--sm",onClick:()=>{U(null),P(y=>{const q={...y};return delete q[t.id],q})},disabled:pe,title:"Cancel custom interval",children:"Cancel"})]}):e.jsx(e.Fragment,{children:e.jsxs("select",{className:"select agent-heartbeat-select",value:S,onChange:y=>{const q=y.target.value;q==="__custom__"?D(t):we(t,Number(q))},disabled:pe,"aria-label":`Set heartbeat interval for ${t.name}`,children:[ce.map(y=>e.jsx("option",{value:y.value,children:y.label},y.value)),St.some(y=>y.value===S)&&e.jsx("option",{value:"__custom__",children:"Custom..."})]})}),pe&&e.jsx("span",{className:"agent-heartbeat-saving text-secondary",children:"Saving…"}),t.lastHeartbeatAt&&(()=>{const y=new Date(t.lastHeartbeatAt),q=new Date(y.getTime()+S),fe=t.state==="active"||t.state==="running";return e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"agent-heartbeat-last text-secondary",title:y.toLocaleString(),children:["Last: ",y.toLocaleTimeString()]}),fe&&e.jsxs("span",{className:"agent-heartbeat-next text-secondary",title:q.toLocaleString(),children:["Next: ",q.toLocaleTimeString()]})]})})()]})]}),e.jsxs("div",{className:"agent-card-actions",children:[t.state==="idle"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void ae(t.id,"active"),disabled:F.has(t.id),title:"Activate",children:[e.jsx(ke,{size:14})," Start"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void he(t.id,t.name),title:"Delete",children:[e.jsx(Ke,{size:14})," Delete"]})]}),t.state==="active"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void je(t.id,t.name),disabled:F.has(t.id),title:"Run Now","aria-label":`Run now for ${t.name}`,children:[e.jsx(xe,{size:14})," Run Now"]}),e.jsxs("button",{className:"btn btn--sm",onClick:()=>void ae(t.id,"paused"),disabled:F.has(t.id),title:"Pause",children:[e.jsx(Ue,{size:14})," Pause"]})]}),t.state==="paused"&&e.jsxs("button",{className:"btn btn--sm",onClick:()=>void ae(t.id,"active"),disabled:F.has(t.id),title:"Resume",children:[e.jsx(ke,{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(xe,{size:14})," Running"]}),e.jsxs("button",{className:"btn btn--sm",onClick:()=>void ae(t.id,"paused"),disabled:F.has(t.id),title:"Pause",children:[e.jsx(Ue,{size:14})," Pause"]})]}),t.state==="error"&&e.jsxs("button",{className:"btn btn--sm",onClick:()=>void ae(t.id,"active"),disabled:F.has(t.id),title:"Retry",children:[e.jsx(ke,{size:14})," Retry"]}),t.state==="terminated"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void ae(t.id,"active"),disabled:F.has(t.id),title:"Start",children:[e.jsx(ke,{size:14})," Start"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void he(t.id,t.name),title:"Delete",children:[e.jsx(Ke,{size:14})," Delete"]})]}),e.jsx("button",{className:"btn btn--sm agent-card-details-btn",onClick:()=>C(t.id),title:`View details for ${t.name}`,"aria-label":`View details for ${t.name}`,children:"View Details"})]})]},t.id)})}),e.jsx(Kt,{agents:u,projectId:l,onAgentSelect:C})]}),w&&e.jsx(s.Suspense,{fallback:null,children:e.jsx(Cn,{agentId:w,projectId:l,onClose:be,addToast:a,onChildClick:le})})]})}const _n=Object.freeze(Object.defineProperty({__proto__:null,AgentsView:Sn},Symbol.toStringTag,{value:"Module"}));export{_n as A,wn as S};
@@ -0,0 +1 @@
1
+ import{r as s,j as e}from"./vendor-react-K0fH_qHe.js";import{i as ze,aw as mt,g as gt,ax as ft,a as pt,ay as xt,az as St,aA as bt,aB as vt,aC as wt,aD as kt,s as Nt,aE as Ct,aF as jt,f as Mt,a5 as yt,a6 as Tt,w as Le,S as At,I as Ge,ai as $t,aG as Et,B as Me,a2 as Ue,a3 as qe,aH as Pt,aI as Dt,aJ as Rt,aK as Lt,aL as _t,aM as zt,h as It,j as Ft}from"./index-CCYdhck-.js";import"./vendor-xterm-DzcZoU0P.js";const _e="kb-chat-active-session";function Ot(n){const i=n?.toolCalls;if(!Array.isArray(i))return;const c=i.map(l=>{if(!l||typeof l!="object")return null;const r=l,f=typeof r.toolName=="string"?r.toolName:"";if(!f)return null;const S=r.args;return{toolName:f,...S&&typeof S=="object"?{args:S}:{},isError:!!r.isError,result:r.result,status:"completed"}}).filter(l=>l!==null);return c.length>0?c:void 0}function Je(n){return{id:n.id,sessionId:n.sessionId,role:n.role,content:n.content,thinkingOutput:n.thinkingOutput,toolCalls:Ot(n.metadata),createdAt:n.createdAt}}function Vt(n){const[i,c]=s.useState([]),[l,r]=s.useState(null),[f,S]=s.useState(!0),[j,b]=s.useState([]),[ee,F]=s.useState(!1),[O,_]=s.useState(!1),[de,P]=s.useState(""),[V,y]=s.useState(""),[xe,D]=s.useState([]),[p,R]=s.useState(""),[te,K]=s.useState(""),[T,B]=s.useState(!0),[Q,ie]=s.useState(new Map),w=s.useRef(null),W=s.useRef(!1),Y=s.useRef(""),Se=s.useRef(i),H=s.useRef(l),Ne=s.useRef(O);Se.current=i,H.current=l,Ne.current=O,s.useEffect(()=>{Y.current=p},[p]);const le=s.useRef(new Set),se=s.useRef(0),Ce=s.useRef(n);Ce.current!==n&&(Ce.current=n,se.current++),s.useEffect(()=>{const u=se.current;ze(void 0,n).then(m=>{if(se.current!==u)return;const h=new Map;for(const x of m)h.set(x.id,x);ie(h)}).catch(()=>{})},[n]);const ne=s.useCallback(async()=>{S(!0);try{const m=[...(await mt(n)).sessions].sort((h,x)=>new Date(x.updatedAt).getTime()-new Date(h.updatedAt).getTime());c(m)}catch{}finally{S(!1)}},[n]);s.useEffect(()=>{ne()},[ne]);const X=s.useRef(()=>{});s.useEffect(()=>{if(f)return;const u=gt(_e,n);u&&i.find(h=>h.id===u)&&X.current(u)},[f,i,n]);const z=s.useCallback(async(u,m)=>{F(!0);try{const h=await ft(u,{limit:50,...m},n),x=h.messages.map(Je);m?.offset&&m.offset>0?b(q=>[...x,...q]):b(x),B(h.messages.length>=50)}catch{}finally{F(!1)}},[n]),ue=s.useCallback(u=>{w.current&&(w.current.close(),w.current=null);const m=i.find(h=>h.id===u);r(m||null),P(""),y(""),D([]),_(!1),B(!0),u?z(u):b([]),u?pt(_e,u,n):xt(_e,n)},[i,z,n]);X.current=ue;const he=s.useCallback(async u=>{const m=await St(u,n),h={id:m.session.id,title:m.session.title,agentId:m.session.agentId,status:m.session.status,modelProvider:m.session.modelProvider,modelId:m.session.modelId,createdAt:m.session.createdAt,updatedAt:m.session.updatedAt};return c(x=>[h,...x]),r(h),b([]),P(""),y(""),D([]),_(!1),B(!0),h},[n]),me=s.useCallback(async u=>{await bt(u,{status:"archived"},n),c(m=>m.filter(h=>h.id!==u)),l?.id===u&&(r(null),b([]))},[l,n]),re=s.useCallback(async u=>{l?.id===u&&w.current&&(w.current.close(),w.current=null),await vt(u,n),c(m=>m.filter(h=>h.id!==u)),l?.id===u&&(r(null),b([]))},[l,n]),ge=s.useCallback(async()=>{!l||!T||await z(l.id,{offset:j.length})},[l,T,z,j.length]),ae=s.useCallback(()=>{l&&(W.current=!0,w.current?.close(),w.current=null,wt(l.id,n).catch(()=>{}),_(!1),P(""),y(""),D([]))},[l,n]),G=s.useCallback(()=>{Y.current="",R("")},[]),U=s.useCallback(u=>{if(!l)return;if(O){Y.current=u,R(u);return}W.current=!1,w.current&&(w.current.close(),w.current=null);const m=`temp-${Date.now()}`,h={id:m,sessionId:l.id,role:"user",content:u,createdAt:new Date().toISOString()};b(g=>[...g,h]),P(""),y(""),D([]),_(!0);let x="",q="",C=[];const ve={onThinking:g=>{q+=g,y(q)},onText:g=>{x+=g,P(x)},onToolStart:g=>{C=[...C,{toolName:g.toolName,args:g.args,isError:!1,status:"running"}],D(C)},onToolEnd:g=>{const k=[...C];for(let v=k.length-1;v>=0;v--){const o=k[v];if(o?.toolName===g.toolName&&o.status==="running"){k[v]={...o,status:"completed",isError:g.isError,result:g.result},C=k,D(k);return}}C=[...k,{toolName:g.toolName,isError:g.isError,result:g.result,status:"completed"}],D(C)},onDone:g=>{const k={id:g.messageId||`msg-${Date.now()}`,sessionId:l.id,role:"assistant",content:x,thinkingOutput:q,toolCalls:C.length>0?C:void 0,createdAt:new Date().toISOString()};le.current.add(k.id),b(o=>[...o,k]),P(""),y(""),D([]),_(!1),w.current=null,setTimeout(()=>{le.current.delete(k.id)},1e3),ne();const v=Y.current.trim();v&&(Y.current="",R(""),U(v))},onError:g=>{if(b(k=>k.filter(v=>v.id!==m)),P(""),y(""),D([]),_(!1),w.current=null,console.error("[useChat] Stream error:",g),!W.current){const k=Y.current.trim();k&&(Y.current="",R(""),U(k))}}};w.current=kt(l.id,u,ve,n)},[l,O,n,ne]),be=te?i.filter(u=>u.title?.toLowerCase().includes(te.toLowerCase())||u.agentId.toLowerCase().includes(te.toLowerCase())):i;return s.useEffect(()=>{const u=se.current,m=n?`?projectId=${encodeURIComponent(n)}`:"",h=()=>se.current!==u,x=v=>{if(h())return;const o=JSON.parse(v.data);c(N=>N.some(L=>L.id===o.id)?N:[o,...N])},q=v=>{if(h())return;const o=JSON.parse(v.data);c(N=>[...N.map($=>$.id===o.id?o:$)]),H.current?.id===o.id&&r(o)},C=v=>{if(h())return;const{id:o}=JSON.parse(v.data);c(N=>N.filter(L=>L.id!==o)),H.current?.id===o&&(r(null),b([]))},ve=v=>{if(h())return;const o=JSON.parse(v.data),N=Je(o);le.current.has(N.id)||H.current?.id===N.sessionId&&!Ne.current&&b(L=>L.some($=>$.id===N.id)?L:[...L,N])},g=v=>{if(h())return;const{id:o}=JSON.parse(v.data);b(N=>N.filter(L=>L.id!==o))};return Nt(`/api/events${m}`,{events:{"chat:session:created":x,"chat:session:updated":q,"chat:session:deleted":C,"chat:message:added":ve,"chat:message:deleted":g}})},[n]),s.useEffect(()=>()=>{w.current&&(w.current.close(),w.current=null)},[]),{sessions:i,activeSession:l,sessionsLoading:f,messages:j,messagesLoading:ee,isStreaming:O,streamingText:de,streamingThinking:V,streamingToolCalls:xe,pendingMessage:p,selectSession:ue,createSession:he,archiveSession:me,deleteSession:re,sendMessage:U,stopStreaming:ae,clearPendingMessage:G,loadMoreMessages:ge,hasMoreMessages:T,searchQuery:te,setSearchQuery:K,filteredSessions:be,refreshSessions:ne,agentsMap:Q}}function Ke(n){const i=new Date(n),l=new Date().getTime()-i.getTime(),r=Math.floor(l/1e3),f=Math.floor(r/60),S=Math.floor(f/60),j=Math.floor(S/24);return r<60?"just now":f<60?`${f}m ago`:S<24?`${S}h ago`:j<7?`${j}d ago`:i.toLocaleDateString()}function Qe(n,i){if(!n||!i)return null;const c=i.toLowerCase();if(c.includes("claude")){let r=i.replace(/^claude[- ]/i,"Claude ").replace(/sonnet[- ](\d+)[- ](\d+)/i,"Sonnet $1.$2").replace(/sonnet[- ](\d+)/i,"Sonnet $1").replace(/haiku[- ](\d+)/i,"Haiku $1").replace(/opus[- ](\d+)/i,"Opus $1").replace(/sonnet/i,"Sonnet").replace(/haiku/i,"Haiku").replace(/opus/i,"Opus").replace(/-/g," ").trim();return r=r.replace(/\s+/g," "),r.length>30?r.slice(0,30)+"…":r}if(c.includes("gpt")||c.includes("openai")){const r=i.replace(/^gpt-4-turbo$/i,"GPT-4 Turbo").replace(/^gpt-4o-mini$/i,"GPT-4o Mini").replace(/^gpt-4o$/i,"GPT-4o").replace(/^gpt-4$/i,"GPT-4").replace(/^gpt-o1-preview$/i,"GPT-o1 Preview").replace(/^gpt-o1-mini$/i,"GPT-o1 Mini").replace(/^gpt-o1$/i,"GPT-o1").replace(/^gpt/i,"GPT").trim();return r.length>30?r.slice(0,30)+"…":r}if(c.includes("gemini")){const r=i.replace(/^gemini[- ]/i,"Gemini ").replace(/pro[- ](\d+)[- ](\d+)/i,"Pro $1.$2").replace(/pro[- ](\d+)/i,"Pro $1").replace(/-/g," ").replace(/\s+/g," ").trim();return r.length>30?r.slice(0,30)+"…":r}const l=i.replace(/-/g," ").replace(/^\w/,r=>r.toUpperCase()).replace(/\s+/g," ").trim();return l.length>30?l.slice(0,30)+"…":l}function ye(n,i){return n.length>i?`${n.slice(0,i)}…`:n}function Bt(n){if(!n)return null;const i=Object.entries(n);return i.length===0?null:i.map(([c,l])=>{let r="";if(typeof l=="string")r=l;else try{r=JSON.stringify(l)}catch{r=String(l)}return`${c}=${ye(r,50)}`}).join(", ")}function Ht(n){if(n===void 0)return null;if(typeof n=="string")return ye(n,200);try{return ye(JSON.stringify(n),200)}catch{return ye(String(n),200)}}function We(n){return!n||n.length===0?null:e.jsxs("div",{className:"chat-tool-calls","data-testid":"chat-tool-calls",children:[e.jsxs("div",{className:"chat-tool-calls-header",children:[e.jsx(zt,{size:12,"aria-hidden":"true"}),e.jsx("span",{children:"Tool calls"})]}),n.map((i,c)=>{const l=i.status==="running",r=i.status==="completed"&&i.isError,f=Bt(i.args),S=Ht(i.result),j=l?f:S?`result: ${S}`:f?`args: ${f}`:null,b=l?"running":r?"error":"completed";return e.jsxs("details",{className:`chat-tool-call${l?" chat-tool-call--running":""}${r?" chat-tool-call--error":""}`,open:l,children:[e.jsxs("summary",{children:[e.jsx("span",{className:"chat-tool-call-status-dot","aria-hidden":"true"}),e.jsx("span",{className:"chat-tool-call-name",children:i.toolName}),j&&e.jsx("span",{className:"chat-tool-call-preview",title:j,children:j}),e.jsx("span",{className:"chat-tool-call-status-text",children:b})]}),e.jsxs("div",{className:"chat-tool-call-content",children:[f&&e.jsxs("div",{className:"chat-tool-call-row",children:[e.jsx("span",{className:"chat-tool-call-label",children:"args"}),e.jsx("span",{className:"chat-tool-call-value",children:f})]}),S&&e.jsxs("div",{className:`chat-tool-call-row${r?" chat-tool-call-row--error":""}`,children:[e.jsx("span",{className:"chat-tool-call-label",children:"result"}),e.jsx("span",{className:"chat-tool-call-value",children:S})]})]})]},`${i.toolName}-${c}`)})]})}const Gt={pre:({children:n,...i})=>e.jsx("pre",{...i,className:"chat-markdown-pre",children:n}),table:({children:n,...i})=>e.jsx("table",{...i,className:"chat-markdown-table",children:n})},Te="__fn_agent__";function Ye(n){const i=/(^|[\s])\/([^\s]*)$/.exec(n);if(!i)return null;const c=i[1]??"",l=i[2]??"",r=i.index+c.length;return{filter:l,start:r,end:n.length}}function Ut(n,i){const c=n.slice(0,i),l=/(^|[\s\n])@([\w-]*)$/.exec(c);if(!l)return null;const r=l[2]??"",f=c.length-r.length-1;return{filter:r,start:f,end:i}}function qt({projectId:n,onClose:i,onCreate:c}){const[l,r]=s.useState("agent"),[f,S]=s.useState([]),[j,b]=s.useState(!0),[ee,F]=s.useState(""),[O,_]=s.useState([]),[de,P]=s.useState(!0),[V,y]=s.useState("");s.useEffect(()=>{let p=!1;return b(!0),ze(void 0,n).then(R=>{p||S(R)}).catch(()=>{p||S([])}).finally(()=>{p||b(!1)}),()=>{p=!0}},[n]),s.useEffect(()=>{P(!0),It().then(p=>{_(p.models)}).catch(()=>{_([])}).finally(()=>{P(!1)})},[]);const xe=p=>{if(p.preventDefault(),l==="agent"){if(!ee)return;c({agentId:ee});return}if(!V)return;const R=V.indexOf("/");if(R<=0)return;const te=V.slice(0,R),K=V.slice(R+1);c({agentId:Te,modelProvider:te,modelId:K})},D=l==="agent"?!ee:!V;return e.jsx("div",{className:"chat-new-dialog-backdrop",onClick:i,role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"chat-new-dialog",onClick:p=>p.stopPropagation(),children:[e.jsx("h3",{children:"New Chat"}),e.jsxs("div",{className:"chat-new-dialog-mode-toggle","data-testid":"chat-new-dialog-mode-toggle",children:[e.jsx("button",{type:"button",className:`chat-new-dialog-mode-btn${l==="agent"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-agent",onClick:()=>{r("agent"),y("")},children:"Agent"}),e.jsx("button",{type:"button",className:`chat-new-dialog-mode-btn${l==="model"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-model",onClick:()=>{r("model"),F("")},children:"Model"})]}),e.jsxs("form",{onSubmit:xe,children:[l==="agent"&&e.jsxs("label",{className:"chat-new-dialog-model-label",children:["Agent",j?e.jsx("div",{className:"chat-new-dialog-loading",children:"Loading agents..."}):f.length===0?e.jsx("div",{className:"chat-new-dialog-empty",children:"No agents available"}):e.jsx("div",{className:"chat-new-dialog-agent-list",children:f.map(p=>e.jsxs("button",{type:"button",className:`chat-new-dialog-agent-item${ee===p.id?" chat-new-dialog-agent-item--selected":""}`,onClick:()=>F(p.id),"data-testid":`agent-option-${p.id}`,children:[e.jsx(Me,{size:16}),e.jsx("span",{className:"chat-new-dialog-agent-name",children:p.name}),e.jsx("span",{className:"chat-new-dialog-agent-role",children:p.role})]},p.id))})]}),l==="model"&&e.jsx("div",{className:"chat-new-dialog-model-dropdown","data-testid":"chat-new-dialog-model-section",children:de?e.jsx("div",{className:"chat-new-dialog-loading",children:"Loading models..."}):e.jsx(Ft,{models:O,value:V,onChange:y,label:"Model",placeholder:"Select a model"})}),e.jsxs("div",{className:"chat-new-dialog-actions",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:i,children:"Cancel"}),e.jsx("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:D,children:"Create"})]})]})]})})}function Yt({projectId:n,addToast:i}){const{activeSession:c,sessionsLoading:l,messages:r,messagesLoading:f,isStreaming:S,streamingText:j,streamingThinking:b,streamingToolCalls:ee,selectSession:F,createSession:O,archiveSession:_,deleteSession:de,sendMessage:P,stopStreaming:V,pendingMessage:y,clearPendingMessage:xe,searchQuery:D,setSearchQuery:p,filteredSessions:R}=Vt(n),[te,K]=s.useState(!1),[T,B]=s.useState(""),[Q,ie]=s.useState(null),[w,W]=s.useState(null),[Y,Se]=s.useState(!0),[H,Ne]=s.useState(new Map),[le,se]=s.useState([]),[Ce,ne]=s.useState(!0),[X,z]=s.useState(!1),[ue,he]=s.useState(""),[me,re]=s.useState(0),[ge,ae]=s.useState(""),[G,U]=s.useState(!1),[be,u]=s.useState(0),[m,h]=s.useState(-1),[x,q]=s.useState(!0),[C,ve]=s.useState(()=>new Set),[,g]=s.useState(!1),[k,v]=s.useState({top:0,left:0}),o=Ct({projectId:n}),N=s.useCallback(t=>{if(!t||!o.mentionActive)return;const a=t.getBoundingClientRect();v({top:a.top-260,left:a.left+8})},[o.mentionActive]),L=s.useRef(null),$=s.useRef(null),Xe=s.useRef(null),E=s.useRef(null),we=s.useRef(0),J=jt()==="mobile",I=s.useMemo(()=>{const t=ue.trim().toLowerCase();return(t?le.filter(d=>d.name.toLowerCase().includes(t)):le).slice(0,10)},[le,ue]),fe=s.useMemo(()=>Array.from(H.values()),[H]),ce=s.useMemo(()=>{const t=ge.trim().toLowerCase();return t?fe.filter(a=>a.name.toLowerCase().includes(t)):fe},[fe,ge]),Ie=s.useMemo(()=>{const t=new Map;for(const a of fe)t.set(a.name.toLowerCase(),a);return t},[fe]);s.useEffect(()=>{re(0)},[I]),s.useEffect(()=>{u(0)},[ge,G]),s.useEffect(()=>()=>{$.current!==null&&window.clearTimeout($.current)},[]),s.useEffect(()=>{L.current?.scrollIntoView({behavior:"smooth"})},[r,j]),s.useEffect(()=>{const t=()=>ie(null);if(Q)return document.addEventListener("click",t),()=>document.removeEventListener("click",t)},[Q]),s.useEffect(()=>{let t=!1;const a=n;return ze(void 0,n).then(d=>{if(t||a!==n)return;const M=new Map;for(const A of d)M.set(A.id,A);Ne(M)}).catch(()=>{}),()=>{t=!0}},[n]),s.useEffect(()=>{let t=!1;return ne(!0),Mt(n).then(a=>{t||se(a)}).catch(()=>{t||se([])}).finally(()=>{t||ne(!1)}),()=>{t=!0}},[n]);const Ze=s.useCallback(async t=>{try{await O(t),K(!1),J&&Se(!1)}catch{i("Failed to create chat session","error")}},[O,i,J]),Ae=s.useCallback(()=>{const t=T.trim();!t||!c||(B(""),z(!1),he(""),U(!1),ae(""),h(-1),P(t))},[T,c,P]),$e=s.useCallback(t=>{B(a=>{const d=Ye(a);if(!d)return a;const M=`/skill:${t.name} `,A=a.slice(0,d.start)+M+a.slice(d.end);return window.requestAnimationFrame(()=>{E.current&&(E.current.style.height="auto",E.current.style.height=`${Math.min(E.current.scrollHeight,120)}px`,E.current.focus())}),A}),z(!1),he(""),re(0)},[]),Ee=s.useCallback(t=>{const a=E.current;if(!a||m<0)return;const d=a.selectionStart??we.current,M=a.selectionEnd??d,A=Math.max(d,M),ke=Math.min(m,A),oe=`${`@${t.name.replace(/\s+/g,"_")}`} `,Re=T.slice(0,ke)+oe+T.slice(A),pe=ke+oe.length;B(Re),U(!1),ae(""),u(0),h(-1),window.requestAnimationFrame(()=>{E.current&&(E.current.style.height="auto",E.current.style.height=`${Math.min(E.current.scrollHeight,120)}px`,E.current.focus(),E.current.setSelectionRange(pe,pe))})},[m,T]),et=s.useCallback(t=>{const a=/@([\w-]+)/g,d=[];let M=0,A=a.exec(t);for(;A;){const[ke,He=""]=A,oe=A.index;oe>M&&d.push(t.slice(M,oe));const Re=He.replace(/_/g," ").toLowerCase(),pe=Ie.get(Re);pe?d.push(e.jsxs("span",{className:"chat-mention-chip",children:["@",pe.name.replace(/\s+/g,"_")]},`${pe.id}-${oe}`)):d.push(ke),M=oe+ke.length,A=a.exec(t)}return M<t.length&&d.push(t.slice(M)),d.length===0?t:d},[Ie]),tt=s.useCallback(t=>{if(we.current=t.currentTarget.selectionStart??we.current,o.mentionActive&&o.files.length>0){if(o.handleKeyDown(t,T),t.key==="Enter"||t.key==="Tab"){const a=o.files[o.selectedIndex];if(a){const d=o.selectFile(a,T);B(d),o.dismissMention(),g(!1)}}return}if(G&&t.key==="ArrowDown"){t.preventDefault(),ce.length>0&&u(a=>(a+1)%ce.length);return}if(G&&t.key==="ArrowUp"){t.preventDefault(),ce.length>0&&u(a=>a===0?ce.length-1:a-1);return}if(G&&t.key==="Enter"){t.preventDefault();const a=ce[be]??ce[0];a&&Ee(a);return}if(G&&t.key==="Escape"){t.preventDefault(),U(!1),ae(""),h(-1);return}if(X&&t.key==="ArrowDown"){t.preventDefault(),I.length>0&&re(a=>(a+1)%I.length);return}if(X&&t.key==="ArrowUp"){t.preventDefault(),I.length>0&&re(a=>a===0?I.length-1:a-1);return}if(X&&(t.key==="Enter"||t.key==="Tab")&&I.length>0){t.preventDefault();const a=I[me]??I[0];a&&$e(a);return}if(X&&t.key==="Escape"){t.preventDefault(),z(!1);return}t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),Ae())},[G,ce,be,Ee,X,I,me,$e,Ae,o,T]),je=s.useCallback((t,a)=>{const d=Ut(t,a);if(d){U(!0),ae(d.filter),h(d.start);return}U(!1),ae(""),h(-1)},[]),st=s.useCallback(t=>{const a=t.target,d=a.value,M=a.selectionStart??d.length;we.current=M,B(d);const A=Ye(d);A?(z(!0),he(A.filter)):(z(!1),he("")),je(d,M),o.detectMention(d,M),g(o.mentionActive),o.mentionActive&&N(a),a.style.height="auto",a.style.height=`${Math.min(a.scrollHeight,120)}px`},[je]),Pe=s.useCallback(t=>{const a=t.currentTarget,d=a.selectionStart??a.value.length;we.current=d,je(a.value,d),o.detectMention(a.value,d),g(o.mentionActive),o.mentionActive&&N(a)},[je,o,N]),nt=s.useCallback(t=>{t.key!=="Escape"&&Pe(t)},[Pe]),at=s.useCallback(()=>{$.current!==null&&window.clearTimeout($.current),$.current=window.setTimeout(()=>{z(!1),U(!1),ae(""),h(-1),g(!1),o.dismissMention(),$.current=null},120)},[o]),it=s.useCallback(()=>{$.current!==null&&(window.clearTimeout($.current),$.current=null)},[]),lt=s.useCallback(async t=>{ie(null);try{await _(t),i("Conversation archived","success")}catch{i("Failed to archive conversation","error")}},[_,i]),rt=s.useCallback(async t=>{W(null),ie(null);try{await de(t),i("Conversation deleted","success")}catch{i("Failed to delete conversation","error")}},[de,i]),ct=s.useCallback(t=>{F(t),J&&Se(!1)},[F,J]),ot=s.useCallback(()=>{F(""),Se(!0)},[F]),dt=()=>e.jsxs("div",{className:"chat-empty-state",children:[e.jsx(_t,{size:48,strokeWidth:1.5}),e.jsx("h2",{children:"Start a new conversation"}),e.jsxs("button",{className:"btn btn-primary",onClick:()=>K(!0),children:[e.jsx(Le,{size:16}),"New Chat"]})]}),Z=Qe(c?.modelProvider,c?.modelId),Fe=c?.agentId===Te?Z??"Fusion":c?.title||H.get(c?.agentId??"")?.name||c?.agentId||"Chat",ut=!!(Z&&Z!==Fe),De=H.get(c?.agentId??"")?.name||(c?.agentId===Te?Z??"Fusion":c?.agentId?.slice(0,30)??"Fusion"),Oe=!!(Z&&Z!==De),ht=y.length>50?`${y.slice(0,50)}…`:y,Ve=s.useCallback(t=>{ve(a=>{const d=new Set(a);return d.has(t)?d.delete(t):d.add(t),d})},[]),Be=s.useCallback((t,a=!1)=>(J?a:a||!x)?e.jsx("div",{className:"chat-message-content chat-message-content--plain",children:t}):e.jsx("div",{className:"chat-message-content chat-message-content--markdown",children:e.jsx(yt,{remarkPlugins:[Tt],components:Gt,children:t})}),[J,x]);return e.jsxs("div",{className:"chat-view",children:[e.jsxs("div",{className:`chat-sidebar${Y?"":" chat-sidebar--hidden"}`,children:[e.jsx("div",{className:"chat-sidebar-header",children:e.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>K(!0),"data-testid":"chat-new-btn",children:[e.jsx(Le,{size:14}),"New Chat"]})}),e.jsx("div",{className:"chat-sidebar-search",children:e.jsxs("div",{className:"chat-sidebar-search-wrapper",children:[e.jsx(At,{size:14,className:"chat-sidebar-search-icon"}),e.jsx("input",{type:"text",className:"chat-sidebar-search",placeholder:"Search conversations...",value:D,onChange:t=>p(t.target.value),"data-testid":"chat-search-input"})]})}),e.jsx("div",{className:"chat-session-list chat-sidebar-list",children:l?e.jsx("div",{style:{padding:"12px",color:"var(--text-secondary)",fontSize:"13px"},children:"Loading..."}):R.length===0?e.jsx("div",{style:{padding:"12px",color:"var(--text-secondary)",fontSize:"13px"},children:"No conversations yet"}):R.map(t=>e.jsxs("div",{className:`chat-session-item${c?.id===t.id?" chat-session-item--active":""}`,onClick:()=>ct(t.id),onContextMenu:a=>{a.preventDefault(),ie({sessionId:t.id,x:a.clientX,y:a.clientY})},"data-testid":`chat-session-${t.id}`,children:[e.jsx("button",{className:"chat-session-delete-btn",onClick:a=>{a.stopPropagation(),W(t.id)},"data-testid":"chat-session-delete-btn","aria-label":"Delete conversation",children:e.jsx(Ge,{size:14})}),e.jsx("div",{className:"chat-session-title",children:t.title||"Untitled"}),e.jsx("div",{className:"chat-session-preview",children:t.lastMessagePreview||"No messages"}),e.jsxs("div",{className:"chat-session-meta",children:[e.jsx("span",{children:H.get(t.agentId)?.name||(t.agentId===Te?Qe(t.modelProvider,t.modelId)??"Fusion":t.agentId.slice(0,30))}),e.jsx("span",{children:t.updatedAt?Ke(t.updatedAt):""})]})]},t.id))}),e.jsx("div",{className:"chat-sidebar-footer",children:e.jsxs("button",{className:"btn btn-sm btn-primary chat-sidebar-footer-btn",onClick:()=>K(!0),"data-testid":"chat-new-btn-mobile",children:[e.jsx(Le,{size:14}),"New Chat"]})})]}),Q&&e.jsxs("div",{className:"chat-session-context-menu",style:{top:Q.y,left:Q.x},onClick:t=>t.stopPropagation(),children:[e.jsxs("button",{onClick:()=>lt(Q.sessionId),"data-testid":"chat-context-archive",children:[e.jsx($t,{size:14}),"Archive"]}),e.jsxs("button",{onClick:()=>{ie(null),W(Q.sessionId)},"data-testid":"chat-context-delete",children:[e.jsx(Ge,{size:14}),"Delete"]})]}),w&&e.jsx("div",{className:"chat-new-dialog-backdrop",onClick:()=>W(null),children:e.jsxs("div",{className:"chat-new-dialog",onClick:t=>t.stopPropagation(),children:[e.jsx("h3",{children:"Delete Conversation?"}),e.jsx("p",{style:{fontSize:"14px",color:"var(--text-secondary)",marginBottom:"16px"},children:"This action cannot be undone. All messages in this conversation will be permanently deleted."}),e.jsxs("div",{className:"chat-new-dialog-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:()=>W(null),children:"Cancel"}),e.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>void rt(w),children:"Delete"})]})]})}),e.jsxs("div",{className:"chat-thread",children:[(c||!J)&&e.jsxs("div",{className:"chat-thread-header",children:[J&&c&&e.jsx("button",{className:"btn-icon",onClick:ot,"data-testid":"chat-back-btn",children:e.jsx(Et,{size:16})}),e.jsx(Me,{size:16}),e.jsx("span",{className:"chat-thread-header-title",children:Fe}),ut&&e.jsx("span",{className:"chat-model-tag",children:Z}),c&&e.jsxs("div",{className:"chat-render-mode-toggle",role:"group","aria-label":"Assistant response render mode",children:[e.jsx("button",{type:"button",className:`chat-render-mode-btn${x?" chat-render-mode-btn--active":""}`,"aria-pressed":x,"aria-label":"Render assistant responses as markdown","data-testid":"chat-render-mode-markdown",onClick:()=>q(!0),children:"Markdown"}),e.jsx("button",{type:"button",className:`chat-render-mode-btn${x?"":" chat-render-mode-btn--active"}`,"aria-pressed":!x,"aria-label":"Render assistant responses as plain text","data-testid":"chat-render-mode-plain",onClick:()=>q(!1),children:"Plain"})]})]}),e.jsxs("div",{className:"chat-messages",ref:Xe,children:[f?e.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"13px"},children:"Loading messages..."}):r.length===0&&!c?dt():r.length===0&&c?e.jsx("div",{style:{color:"var(--text-secondary)",fontSize:"13px"},children:"No messages yet. Start the conversation!"}):e.jsxs(e.Fragment,{children:[r.map(t=>{const a=t.role==="assistant",d=C.has(t.id);return e.jsxs("div",{className:`chat-message chat-message--${t.role}`,"data-testid":`chat-message-${t.id}`,children:[a&&e.jsxs("div",{className:"chat-message-avatar",children:[e.jsx(Me,{size:14}),e.jsx("span",{children:De}),Oe&&e.jsx("span",{className:"chat-model-tag",children:Z}),J&&e.jsx("button",{type:"button",className:`btn btn-icon chat-message-render-toggle${d?" chat-message-render-toggle--plain":""}`,"data-testid":"chat-message-render-toggle","aria-label":d?"Show rendered markdown":"Show plain text",onClick:()=>Ve(t.id),children:d?e.jsx(Ue,{size:14}):e.jsx(qe,{size:14})})]}),a?Be(t.content,d):e.jsx("div",{className:"chat-message-content",children:et(t.content)}),We(t.toolCalls),t.thinkingOutput&&e.jsxs("details",{className:"chat-message-thinking",children:[e.jsx("summary",{children:"Thinking"}),e.jsx("pre",{className:"chat-message-thinking-content",children:t.thinkingOutput})]}),e.jsx("div",{className:"chat-message-time",children:Ke(t.createdAt)})]},t.id)}),S&&e.jsxs("div",{className:"chat-message chat-message--assistant chat-message--streaming",children:[e.jsxs("div",{className:"chat-message-avatar",children:[e.jsx(Me,{size:14}),e.jsx("span",{children:De}),Oe&&e.jsx("span",{className:"chat-model-tag",children:Z}),J&&e.jsx("button",{type:"button",className:`btn btn-icon chat-message-render-toggle${C.has("__streaming__")?" chat-message-render-toggle--plain":""}`,"data-testid":"chat-message-render-toggle","aria-label":C.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>Ve("__streaming__"),children:C.has("__streaming__")?e.jsx(Ue,{size:14}):e.jsx(qe,{size:14})})]}),j?Be(j,C.has("__streaming__")):e.jsx("div",{className:"chat-message-content chat-message-content--waiting",children:b?"Thinking…":"Connecting…"}),We(ee),b&&e.jsxs("details",{className:"chat-message-thinking",children:[e.jsx("summary",{children:"Thinking"}),e.jsx("pre",{className:"chat-message-thinking-content",children:b})]}),e.jsxs("div",{className:"chat-typing-indicator",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]})]})]}),e.jsx("div",{ref:L})]}),c&&e.jsxs("div",{className:"chat-input-area",children:[X&&e.jsx("div",{className:"chat-skill-menu","data-testid":"chat-skill-menu",role:"listbox","aria-label":"Skill suggestions",children:Ce?e.jsx("div",{className:"chat-skill-menu-empty",children:"Loading skills…"}):I.length===0?e.jsx("div",{className:"chat-skill-menu-empty",children:ue?"No skills found":"No skills available"}):I.map((t,a)=>e.jsxs("button",{type:"button",role:"option","aria-selected":a===me,className:`chat-skill-menu-item${a===me?" chat-skill-menu-item--highlighted":""}`,onMouseDown:d=>d.preventDefault(),onMouseEnter:()=>re(a),onClick:()=>$e(t),children:[e.jsx("span",{className:"chat-skill-menu-item-name",children:t.name}),e.jsx("span",{className:"chat-skill-menu-item-description",title:t.relativePath,children:t.relativePath})]},t.id))}),e.jsxs("div",{className:"chat-input-wrapper",children:[e.jsx("textarea",{ref:E,className:"chat-input-textarea",placeholder:"Type a message...",value:T,onChange:st,onKeyDown:tt,onKeyUp:nt,onClick:Pe,onBlur:at,onFocus:it,rows:1,"data-testid":"chat-input"}),e.jsx(Pt,{agents:fe,filter:ge,highlightedIndex:be,visible:G,onSelect:Ee,position:"below"}),e.jsx(Dt,{visible:o.mentionActive&&!G,position:k,files:o.files,selectedIndex:o.selectedIndex,onSelect:t=>{const a=o.selectFile(t,T);B(a),o.dismissMention(),g(!1),E.current?.focus()},loading:o.loading}),y&&e.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[e.jsx("span",{children:`Queued: ${ht}`}),e.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:xe,children:"×"})]})]}),S?e.jsx("button",{className:"chat-input-stop",onClick:V,"aria-label":"Stop generation","data-testid":"chat-stop-btn",children:e.jsx(Rt,{size:14})}):e.jsx("button",{className:"chat-input-send",onClick:()=>void Ae(),disabled:!T.trim(),"data-testid":"chat-send-btn",children:e.jsx(Lt,{size:16})})]})]}),te&&e.jsx(qt,{projectId:n,onClose:()=>K(!1),onCreate:Ze})]})}export{Yt as ChatView};