modular-studio 1.0.6 → 1.1.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.
- package/dist/assets/Badge-Bsy2H_p2.js +1 -0
- package/dist/assets/GraphPanel-D4X3faxA.js +47 -0
- package/dist/assets/{Input-ndEGQSgx.js → Input-Dyb88Erk.js} +1 -1
- package/dist/assets/KnowledgeTab-BccWz7Np.js +5 -0
- package/dist/assets/MemoryTab-Y_66cE01.js +16 -0
- package/dist/assets/QualificationTab-Dm9dEIpM.js +1 -0
- package/dist/assets/ReviewTab-BrfXSyyf.js +104 -0
- package/dist/assets/{Section-CgmwAj_2.js → Section-68XDCFTl.js} +1 -1
- package/dist/assets/TestTab-CLKRT63X.js +42 -0
- package/dist/assets/{ToolsTab-C10Ulm8b.js → ToolsTab-xumi9Uds.js} +1 -1
- package/dist/assets/icons-CS8RUPBi.js +1 -0
- package/dist/assets/index-B2bm0161.css +1 -0
- package/dist/assets/index-C626nWuA.js +422 -0
- package/dist/assets/services-BDk6yY4o.js +369 -0
- package/dist/index.html +4 -4
- package/dist-server/bin/modular-mcp.js +1 -0
- package/dist-server/server/index.d.ts.map +1 -1
- package/dist-server/server/index.js +30 -0
- package/dist-server/server/mcp/manager.d.ts +3 -0
- package/dist-server/server/mcp/manager.d.ts.map +1 -1
- package/dist-server/server/mcp/manager.js +64 -3
- package/dist-server/server/migrations/index.d.ts +11 -0
- package/dist-server/server/migrations/index.d.ts.map +1 -0
- package/dist-server/server/migrations/index.js +57 -0
- package/dist-server/server/routes/analytics.d.ts +3 -0
- package/dist-server/server/routes/analytics.d.ts.map +1 -0
- package/dist-server/server/routes/analytics.js +24 -0
- package/dist-server/server/routes/connectors/airtable.d.ts +7 -0
- package/dist-server/server/routes/connectors/airtable.d.ts.map +1 -0
- package/dist-server/server/routes/connectors/airtable.js +119 -0
- package/dist-server/server/routes/connectors/confluence.d.ts +7 -0
- package/dist-server/server/routes/connectors/confluence.d.ts.map +1 -0
- package/dist-server/server/routes/connectors/confluence.js +176 -0
- package/dist-server/server/routes/connectors/github.d.ts +7 -0
- package/dist-server/server/routes/connectors/github.d.ts.map +1 -0
- package/dist-server/server/routes/connectors/github.js +195 -0
- package/dist-server/server/routes/connectors/gmail.d.ts +7 -0
- package/dist-server/server/routes/connectors/gmail.d.ts.map +1 -0
- package/dist-server/server/routes/connectors/gmail.js +115 -0
- package/dist-server/server/routes/connectors/google-docs.d.ts +10 -0
- package/dist-server/server/routes/connectors/google-docs.d.ts.map +1 -0
- package/dist-server/server/routes/connectors/google-docs.js +165 -0
- package/dist-server/server/routes/connectors/google-drive.d.ts +7 -0
- package/dist-server/server/routes/connectors/google-drive.d.ts.map +1 -0
- package/dist-server/server/routes/connectors/google-drive.js +163 -0
- package/dist-server/server/routes/connectors/google-sheets.d.ts +7 -0
- package/dist-server/server/routes/connectors/google-sheets.d.ts.map +1 -0
- package/dist-server/server/routes/connectors/google-sheets.js +90 -0
- package/dist-server/server/routes/connectors/hubspot.d.ts +7 -0
- package/dist-server/server/routes/connectors/hubspot.d.ts.map +1 -0
- package/dist-server/server/routes/connectors/hubspot.js +134 -0
- package/dist-server/server/routes/connectors/index.d.ts +6 -0
- package/dist-server/server/routes/connectors/index.d.ts.map +1 -0
- package/dist-server/server/routes/connectors/index.js +38 -0
- package/dist-server/server/routes/connectors/jira.d.ts +7 -0
- package/dist-server/server/routes/connectors/jira.d.ts.map +1 -0
- package/dist-server/server/routes/connectors/jira.js +151 -0
- package/dist-server/server/routes/connectors/linear.d.ts +7 -0
- package/dist-server/server/routes/connectors/linear.d.ts.map +1 -0
- package/dist-server/server/routes/connectors/linear.js +154 -0
- package/dist-server/server/routes/connectors/notion.d.ts +10 -0
- package/dist-server/server/routes/connectors/notion.d.ts.map +1 -0
- package/dist-server/server/routes/connectors/notion.js +201 -0
- package/dist-server/server/routes/connectors/plane.d.ts +10 -0
- package/dist-server/server/routes/connectors/plane.d.ts.map +1 -0
- package/dist-server/server/routes/connectors/plane.js +189 -0
- package/dist-server/server/routes/connectors/shared.d.ts +25 -0
- package/dist-server/server/routes/connectors/shared.d.ts.map +1 -0
- package/dist-server/server/routes/connectors/shared.js +202 -0
- package/dist-server/server/routes/connectors/slack.d.ts +7 -0
- package/dist-server/server/routes/connectors/slack.d.ts.map +1 -0
- package/dist-server/server/routes/connectors/slack.js +153 -0
- package/dist-server/server/routes/cost.d.ts +3 -0
- package/dist-server/server/routes/cost.d.ts.map +1 -0
- package/dist-server/server/routes/cost.js +113 -0
- package/dist-server/server/routes/graph.d.ts +11 -0
- package/dist-server/server/routes/graph.d.ts.map +1 -0
- package/dist-server/server/routes/graph.js +213 -0
- package/dist-server/server/routes/lessons.d.ts.map +1 -1
- package/dist-server/server/routes/lessons.js +119 -5
- package/dist-server/server/routes/llm.d.ts.map +1 -1
- package/dist-server/server/routes/llm.js +85 -18
- package/dist-server/server/routes/metaprompt-v2.d.ts +3 -0
- package/dist-server/server/routes/metaprompt-v2.d.ts.map +1 -0
- package/dist-server/server/routes/metaprompt-v2.js +104 -0
- package/dist-server/server/routes/qualification.d.ts.map +1 -1
- package/dist-server/server/routes/qualification.js +61 -11
- package/dist-server/server/routes/skills-search.d.ts.map +1 -1
- package/dist-server/server/routes/skills-search.js +10 -0
- package/dist-server/server/routes/tool-analytics.d.ts +3 -0
- package/dist-server/server/routes/tool-analytics.d.ts.map +1 -0
- package/dist-server/server/routes/tool-analytics.js +47 -0
- package/dist-server/server/services/adapters/sqliteAdapter.d.ts +1 -0
- package/dist-server/server/services/adapters/sqliteAdapter.d.ts.map +1 -1
- package/dist-server/server/services/adapters/sqliteAdapter.js +78 -48
- package/dist-server/server/services/credentialStore.d.ts +10 -0
- package/dist-server/server/services/credentialStore.d.ts.map +1 -0
- package/dist-server/server/services/credentialStore.js +123 -0
- package/dist-server/server/services/hindsightClient.d.ts.map +1 -1
- package/dist-server/server/services/hindsightClient.js +1 -0
- package/dist-server/server/services/lessonExtractor.d.ts +2 -0
- package/dist-server/server/services/lessonExtractor.d.ts.map +1 -1
- package/dist-server/server/services/lessonExtractor.js +7 -2
- package/dist-server/server/services/repoIndexer.d.ts +7 -1
- package/dist-server/server/services/repoIndexer.d.ts.map +1 -1
- package/dist-server/server/services/repoIndexer.js +295 -94
- package/dist-server/server/services/sqliteStore.d.ts +64 -0
- package/dist-server/server/services/sqliteStore.d.ts.map +1 -1
- package/dist-server/server/services/sqliteStore.js +238 -0
- package/dist-server/src/config.d.ts +2 -0
- package/dist-server/src/config.d.ts.map +1 -0
- package/dist-server/src/config.js +3 -0
- package/dist-server/src/graph/db.d.ts +46 -0
- package/dist-server/src/graph/db.d.ts.map +1 -0
- package/dist-server/src/graph/db.js +241 -0
- package/dist-server/src/graph/extractors/code.d.ts +12 -0
- package/dist-server/src/graph/extractors/code.d.ts.map +1 -0
- package/dist-server/src/graph/extractors/code.js +239 -0
- package/dist-server/src/graph/extractors/cross-type.d.ts +16 -0
- package/dist-server/src/graph/extractors/cross-type.d.ts.map +1 -0
- package/dist-server/src/graph/extractors/cross-type.js +67 -0
- package/dist-server/src/graph/extractors/markdown.d.ts +29 -0
- package/dist-server/src/graph/extractors/markdown.d.ts.map +1 -0
- package/dist-server/src/graph/extractors/markdown.js +224 -0
- package/dist-server/src/graph/extractors/yaml.d.ts +15 -0
- package/dist-server/src/graph/extractors/yaml.d.ts.map +1 -0
- package/dist-server/src/graph/extractors/yaml.js +104 -0
- package/dist-server/src/graph/index.d.ts +62 -0
- package/dist-server/src/graph/index.d.ts.map +1 -0
- package/dist-server/src/graph/index.js +67 -0
- package/dist-server/src/graph/packer.d.ts +19 -0
- package/dist-server/src/graph/packer.d.ts.map +1 -0
- package/dist-server/src/graph/packer.js +134 -0
- package/dist-server/src/graph/resolver.d.ts +12 -0
- package/dist-server/src/graph/resolver.d.ts.map +1 -0
- package/dist-server/src/graph/resolver.js +81 -0
- package/dist-server/src/graph/scanner.d.ts +34 -0
- package/dist-server/src/graph/scanner.d.ts.map +1 -0
- package/dist-server/src/graph/scanner.js +252 -0
- package/dist-server/src/graph/traverser.d.ts +17 -0
- package/dist-server/src/graph/traverser.d.ts.map +1 -0
- package/dist-server/src/graph/traverser.js +185 -0
- package/dist-server/src/graph/types.d.ts +117 -0
- package/dist-server/src/graph/types.d.ts.map +1 -0
- package/dist-server/src/graph/types.js +63 -0
- package/dist-server/src/metaprompt/v2/assembler.d.ts +3 -0
- package/dist-server/src/metaprompt/v2/assembler.d.ts.map +1 -0
- package/dist-server/src/metaprompt/v2/assembler.js +261 -0
- package/dist-server/src/metaprompt/v2/context-strategist.d.ts +3 -0
- package/dist-server/src/metaprompt/v2/context-strategist.d.ts.map +1 -0
- package/dist-server/src/metaprompt/v2/context-strategist.js +173 -0
- package/dist-server/src/metaprompt/v2/evaluator.d.ts +3 -0
- package/dist-server/src/metaprompt/v2/evaluator.d.ts.map +1 -0
- package/dist-server/src/metaprompt/v2/evaluator.js +281 -0
- package/dist-server/src/metaprompt/v2/index.d.ts +41 -0
- package/dist-server/src/metaprompt/v2/index.d.ts.map +1 -0
- package/dist-server/src/metaprompt/v2/index.js +90 -0
- package/dist-server/src/metaprompt/v2/parser.d.ts +3 -0
- package/dist-server/src/metaprompt/v2/parser.d.ts.map +1 -0
- package/dist-server/src/metaprompt/v2/parser.js +138 -0
- package/dist-server/src/metaprompt/v2/pattern-selector.d.ts +3 -0
- package/dist-server/src/metaprompt/v2/pattern-selector.d.ts.map +1 -0
- package/dist-server/src/metaprompt/v2/pattern-selector.js +154 -0
- package/dist-server/src/metaprompt/v2/researcher.d.ts +3 -0
- package/dist-server/src/metaprompt/v2/researcher.d.ts.map +1 -0
- package/dist-server/src/metaprompt/v2/researcher.js +194 -0
- package/dist-server/src/metaprompt/v2/tool-discovery.d.ts +74 -0
- package/dist-server/src/metaprompt/v2/tool-discovery.d.ts.map +1 -0
- package/dist-server/src/metaprompt/v2/tool-discovery.js +290 -0
- package/dist-server/src/metaprompt/v2/types.d.ts +154 -0
- package/dist-server/src/metaprompt/v2/types.d.ts.map +1 -0
- package/dist-server/src/metaprompt/v2/types.js +2 -0
- package/dist-server/src/services/contradictionDetector.js +1 -1
- package/dist-server/src/services/llmService.d.ts +61 -0
- package/dist-server/src/services/llmService.d.ts.map +1 -0
- package/dist-server/src/services/llmService.js +222 -0
- package/dist-server/src/store/knowledgeBase.d.ts +5 -1
- package/dist-server/src/store/knowledgeBase.d.ts.map +1 -1
- package/dist-server/src/store/knowledgeBase.js +0 -1
- package/dist-server/src/store/mcp-registry.d.ts +29 -0
- package/dist-server/src/store/mcp-registry.d.ts.map +1 -0
- package/dist-server/src/store/mcp-registry.js +1303 -0
- package/dist-server/src/types/registry.types.d.ts +13 -0
- package/dist-server/src/types/registry.types.d.ts.map +1 -0
- package/dist-server/src/types/registry.types.js +2 -0
- package/dist-server/tsconfig.server.tsbuildinfo +1 -1
- package/package.json +118 -105
- package/scripts/cleanup-worktrees.ps1 +29 -0
- package/dist/assets/Badge-DrUmDAXz.js +0 -1
- package/dist/assets/KnowledgeTab-CxlC76Rf.js +0 -4
- package/dist/assets/MemoryTab-CUScYWs9.js +0 -16
- package/dist/assets/QualificationTab-BqnWSQHm.js +0 -1
- package/dist/assets/ReviewTab-DKYl6cR9.js +0 -103
- package/dist/assets/TestTab-iJ2vCf9l.js +0 -33
- package/dist/assets/icons-MKpPNvV8.js +0 -1
- package/dist/assets/index-B_ip7Amg.css +0 -1
- package/dist/assets/index-gBy3427k.js +0 -143
- package/dist/assets/services-CTWXQK6j.js +0 -356
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/services-BDk6yY4o.js","assets/stores-CeKWz7ou.js","assets/vendor-D1h_O76p.js","assets/TestTab-CLKRT63X.js","assets/conversationStore-CkfEU2eV.js","assets/icons-CS8RUPBi.js","assets/markdown-DWF7F0i0.js","assets/QualificationTab-Dm9dEIpM.js","assets/Badge-Bsy2H_p2.js","assets/Input-Dyb88Erk.js","assets/KnowledgeTab-BccWz7Np.js","assets/ToolsTab-xumi9Uds.js","assets/MemoryTab-Y_66cE01.js","assets/Section-68XDCFTl.js","assets/ReviewTab-BrfXSyyf.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as h,j as e,a as ze,c as hs}from"./vendor-D1h_O76p.js";import{u as I,a as ie,A as Z,R as gs,M as pt,b as Ie,c as Q,d as me,g as xs,s as ys,e as X,K as bs,O as ks,f as ws,D as vs,h as Ae,i as Ss,j as js,k as ce,_ as fe,P as Cs,l as Ns,m as Ee}from"./services-BDk6yY4o.js";import{c as Ne}from"./stores-CeKWz7ou.js";import{X as ae,C as Oe,a as re,A as Es,G as Ts,R as Ms,U as $s,S as tt,b as It,M as At,c as _s,P as Pt,Z as he,B as st,d as Dt,H as Fs,e as Is,T as Rt,F as As,f as Lt,D as nt,g as Ps,h as Be,i as Xe,j as Ds,k as Rs,l as zt,m as Ls,n as Ge,W as Ot,o as zs,p as ot,q as Os,r as Bs,s as We,t as Gs,u as Ws,v as Ks,w as Bt,I as qs,x as ye,y as Hs,z as Us,E as Gt,J as Wt,K as Ys,L as Js,N as Vs,O as rt,Q as te,V as ee,Y as Ke,_ as je,$ as Kt,a0 as at,a1 as oe,a2 as Qs,a3 as Ce,a4 as De,a5 as Zs,a6 as Xs,a7 as en,a8 as tn,a9 as sn,aa as qt,ab as nn,ac as on,ad as it,ae as rn,af as an,ag as Ht,ah as Ut,ai as Yt,aj as Jt,ak as mt,al as ln,am as cn,an as dn,ao as Vt,ap as un,aq as pn,ar as mn,as as fn,at as hn,au as gn,av as xn,aw as yn,ax as bn}from"./icons-CS8RUPBi.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))o(r);new MutationObserver(r=>{for(const a of r)if(a.type==="childList")for(const i of a.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&o(i)}).observe(document,{childList:!0,subtree:!0});function n(r){const a={};return r.integrity&&(a.integrity=r.integrity),r.referrerPolicy&&(a.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?a.credentials="include":r.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function o(r){if(r.ep)return;r.ep=!0;const a=n(r);fetch(r.href,a)}})();const kn=typeof localStorage<"u"?localStorage.getItem("modular-theme"):null,Re=Ne((t,s)=>({theme:kn==="light"?"light":"dark",toggleTheme:()=>{const n=s().theme==="dark"?"light":"dark";localStorage.setItem("modular-theme",n),t({theme:n})}})),wn={bg:"#111114",surface:"rgba(28, 28, 32, 0.9)",surfaceOpaque:"#1c1c20",surfaceElevated:"#25252a",surfaceHover:"#1f1f24",border:"#2a2a30",borderSubtle:"#222226",textPrimary:"#f0f0f0",textSecondary:"#888",textMuted:"#666",textDim:"#555",textFaint:"#444",inputBg:"#141417",badgeBg:"#25252a",dotGrid:"#222228",minimapBg:"#111114",minimapMask:"rgba(17,17,20,0.8)",minimapNode:"#25252a",controlsBg:"#1c1c20",controlsBorder:"#2a2a30",tileActiveBg:"#25252a",tileHoverBg:"#1f1f24",tileBg:"#1c1c20",tileBorderHover:"#3a3a40",agentBg:"#151210",agentBorder:"#2d2720",agentLabel:"#9a8e82",agentMeta:"#6d6058",agentArrow:"#6d6058",agentLineNum:"#2d2720",agentText:"#8a7e72",tokenLabel:"#999",tokenDivider:"#777",tokenTrackBg:"#25252a",jackRingBase:"#0a0a0a",jackLabelOnRing:"#999",jackLabelBeside:"#666",cableShadow:"rgba(0,0,0,0.4)",cableHighlight:"rgba(255,255,255,0.06)",responseBg:"rgba(28, 28, 32, 0.9)",responseText:"#bbb",statusSuccess:"#00ff88",statusError:"#ff3344",statusWarning:"#ffaa00",statusInfo:"#3498db",statusSuccessBg:"rgba(0,255,136,0.07)",statusErrorBg:"rgba(255,51,68,0.08)",statusWarningBg:"rgba(255,170,0,0.08)",statusSuccessGlow:"0 0 6px rgba(0,255,136,0.5)",statusErrorGlow:"0 0 6px rgba(255,51,68,0.5)",statusWarningGlow:"0 0 6px rgba(255,170,0,0.5)",cableSkills:"#f1c40f",cableMcp:"#2ecc71",cableKnowledge:"#e74c3c"},vn={bg:"#f0f1f3",surface:"rgba(255,255,255,0.95)",surfaceOpaque:"#ffffff",surfaceElevated:"#eeeef2",surfaceHover:"#f5f5f8",border:"#ccccd4",borderSubtle:"#dddde2",textPrimary:"#1a1a20",textSecondary:"#3a3a45",textMuted:"#555560",textDim:"#5c5c66",textFaint:"#71717a",inputBg:"#f5f5f8",badgeBg:"#e5e5ea",dotGrid:"#d0d0d8",minimapBg:"#f0f1f3",minimapMask:"rgba(240,241,243,0.8)",minimapNode:"#dddde2",controlsBg:"#ffffff",controlsBorder:"#ccccd4",tileActiveBg:"#e8e8ee",tileHoverBg:"#f0f0f5",tileBg:"#ffffff",tileBorderHover:"#bbbbc4",agentBg:"#f8f8fa",agentBorder:"#dddde2",agentLabel:"#555560",agentMeta:"#888890",agentArrow:"#888890",agentLineNum:"#ccccd4",agentText:"#666670",tokenLabel:"#555560",tokenDivider:"#888890",tokenTrackBg:"#dddde2",jackRingBase:"#e8e8ee",jackLabelOnRing:"#555",jackLabelBeside:"#777",cableShadow:"rgba(0,0,0,0.12)",cableHighlight:"rgba(255,255,255,0.3)",responseBg:"rgba(255,255,255,0.95)",responseText:"#444",statusSuccess:"#16a34a",statusError:"#dc2626",statusWarning:"#ca8a04",statusInfo:"#2563eb",statusSuccessBg:"rgba(22,163,74,0.08)",statusErrorBg:"rgba(220,38,38,0.08)",statusWarningBg:"rgba(202,138,4,0.08)",statusSuccessGlow:"0 0 6px rgba(22,163,74,0.3)",statusErrorGlow:"0 0 6px rgba(220,38,38,0.3)",statusWarningGlow:"0 0 6px rgba(202,138,4,0.3)",cableSkills:"#B45309",cableMcp:"#16a34a",cableKnowledge:"#dc2626"};function q(){const t=Re(n=>n.theme);return{...t==="dark"?wn:vn,isDark:t==="dark"}}function Sn(t,s){const n=[];return t.selectedModel!==s.selectedModel&&n.push({category:"meta",field:"model",type:"modified",before:t.selectedModel,after:s.selectedModel,description:`Model: ${t.selectedModel} → ${s.selectedModel}`}),t.agentConfig.temperature!==s.agentConfig.temperature&&n.push({category:"meta",field:"temperature",type:"modified",before:t.agentConfig.temperature,after:s.agentConfig.temperature,description:`Temperature: ${t.agentConfig.temperature} → ${s.agentConfig.temperature}`}),t.agentConfig.maxTokens!==s.agentConfig.maxTokens&&n.push({category:"meta",field:"maxTokens",type:"modified",before:t.agentConfig.maxTokens,after:s.agentConfig.maxTokens,description:`Max tokens: ${t.agentConfig.maxTokens} → ${s.agentConfig.maxTokens}`}),t.agentConfig.planningMode!==s.agentConfig.planningMode&&n.push({category:"meta",field:"planningMode",type:"modified",before:t.agentConfig.planningMode,after:s.agentConfig.planningMode,description:`Planning mode: ${t.agentConfig.planningMode} → ${s.agentConfig.planningMode}`}),n}function jn(t,s){const n=[],o=t.instructionState,r=s.instructionState;return o.persona!==r.persona&&n.push({category:"persona",field:"persona",type:"modified",before:o.persona,after:r.persona,description:"Persona updated"}),o.tone!==r.tone&&n.push({category:"persona",field:"tone",type:"modified",before:o.tone,after:r.tone,description:`Tone: ${o.tone} → ${r.tone}`}),o.expertise!==r.expertise&&n.push({category:"persona",field:"expertise",type:"modified",before:o.expertise,after:r.expertise,description:`Expertise: ${o.expertise} → ${r.expertise}`}),o.objectives.primary!==r.objectives.primary&&n.push({category:"persona",field:"primary-objective",type:"modified",before:o.objectives.primary,after:r.objectives.primary,description:"Primary objective changed"}),t.prompt!==s.prompt&&n.push({category:"persona",field:"prompt",type:"modified",before:t.prompt,after:s.prompt,description:"Prompt changed"}),n}function Cn(t,s){const n=[],o=t.instructionState.constraints,r=s.instructionState.constraints,a=["neverMakeUp","askBeforeActions","stayInScope","useOnlyTools","limitWords","wordLimit","customConstraints","scopeDefinition"];for(const i of a)o[i]!==r[i]&&n.push({category:"constraints",field:i,type:"modified",before:o[i],after:r[i],description:`"${i}" changed`});return n}function Nn(t,s){const n=[],o=new Map(t.workflowSteps.map(a=>[a.id,a])),r=new Map(s.workflowSteps.map(a=>[a.id,a]));for(const[a,i]of r){const l=o.get(a);l?JSON.stringify(l)!==JSON.stringify(i)&&n.push({category:"workflow",field:a,type:"modified",before:l,after:i,description:`Step "${i.label}" modified`}):n.push({category:"workflow",field:a,type:"added",after:i,description:`Step "${i.label}" added`})}for(const[a,i]of o)r.has(a)||n.push({category:"workflow",field:a,type:"removed",before:i,description:`Step "${i.label}" removed`});return n}function En(t,s){const n=[],o=new Map(t.channels.map(a=>[a.sourceId,a])),r=new Map(s.channels.map(a=>[a.sourceId,a]));for(const[a,i]of r){const l=o.get(a);l?(l.depth!==i.depth||l.enabled!==i.enabled)&&n.push({category:"knowledge",field:a,type:"modified",before:l,after:i,description:`"${i.name}" modified`}):n.push({category:"knowledge",field:a,type:"added",after:i,description:`"${i.name}" added`})}for(const[a,i]of o)r.has(a)||n.push({category:"knowledge",field:a,type:"removed",before:i,description:`"${i.name}" removed`});return n}function Tn(t,s){const n=[],o=new Set(t.skills.filter(l=>l.added).map(l=>l.id)),r=new Set(s.skills.filter(l=>l.added).map(l=>l.id));for(const l of s.skills.filter(c=>c.added&&!o.has(c.id)))n.push({category:"tools",field:`skill:${l.id}`,type:"added",after:l,description:`Skill "${l.name}" added`});for(const l of t.skills.filter(c=>c.added&&!r.has(c.id)))n.push({category:"tools",field:`skill:${l.id}`,type:"removed",before:l,description:`Skill "${l.name}" removed`});const a=new Set(t.mcpServers.filter(l=>l.added).map(l=>l.id)),i=new Set(s.mcpServers.filter(l=>l.added).map(l=>l.id));for(const l of s.mcpServers.filter(c=>c.added&&!a.has(c.id)))n.push({category:"tools",field:`mcp:${l.id}`,type:"added",after:l,description:`MCP "${l.name}" added`});for(const l of t.mcpServers.filter(c=>c.added&&!i.has(c.id)))n.push({category:"tools",field:`mcp:${l.id}`,type:"removed",before:l,description:`MCP "${l.name}" removed`});return n}function ft(t){const s={},n={added:0,removed:0,modified:0};for(const o of t)s[o.category]=(s[o.category]??0)+1,n[o.type]++;return{totalChanges:t.length,categoryCounts:s,changeTypes:n}}function Mn(t,s,n,o){if(!t||!s)return{versionA:n,versionB:o,changes:[],summary:ft([])};const r=[...Sn(t,s),...jn(t,s),...Cn(t,s),...Nn(t,s),...En(t,s),...Tn(t,s)];return{versionA:n,versionB:o,changes:r,summary:ft(r)}}const $n={meta:"Model & Config",persona:"Persona & Objectives",constraints:"Constraints",workflow:"Workflow",knowledge:"Knowledge",tools:"Tools & MCP"},ht={added:{bg:"rgba(0,200,100,0.08)",text:"#00c864",prefix:"+"},removed:{bg:"rgba(255,60,60,0.08)",text:"#ff4444",prefix:"−"},modified:{bg:"rgba(255,160,0,0.1)",text:"#ffa000",prefix:"~"}},_n=["meta","persona","constraints","workflow","knowledge","tools"];function Te(t){return t==null?"(empty)":typeof t=="boolean"?t?"on":"off":typeof t=="object"?JSON.stringify(t,null,2):String(t)}function Fn({change:t,t:s}){const n=ht[t.type]??ht.modified;return e.jsxs("div",{className:"rounded-md p-2.5 mb-1.5",style:{background:n.bg},children:[e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-[11px] font-bold font-mono",style:{color:n.text},children:n.prefix}),e.jsx("span",{className:"text-[12px] font-medium",style:{color:s.textPrimary},children:t.description})]}),t.type==="modified"&&e.jsxs("div",{className:"mt-1.5 grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"rounded p-1.5",style:{background:"rgba(255,60,60,0.06)"},children:[e.jsx("div",{className:"text-[10px] mb-0.5",style:{color:s.textFaint},children:"BEFORE"}),e.jsx("div",{className:"text-[11px] font-mono break-all",style:{color:"#ff6666"},children:Te(t.before)})]}),e.jsxs("div",{className:"rounded p-1.5",style:{background:"rgba(0,200,100,0.06)"},children:[e.jsx("div",{className:"text-[10px] mb-0.5",style:{color:s.textFaint},children:"AFTER"}),e.jsx("div",{className:"text-[11px] font-mono break-all",style:{color:"#00c864"},children:Te(t.after)})]})]}),t.type==="added"&&t.after!==void 0&&e.jsx("div",{className:"mt-1 text-[11px] font-mono break-all",style:{color:"#00c864"},children:Te(t.after)}),t.type==="removed"&&t.before!==void 0&&e.jsx("div",{className:"mt-1 text-[11px] font-mono break-all",style:{color:"#ff6666"},children:Te(t.before)})]})}function In({category:t,changes:s,collapsed:n,onToggle:o,t:r}){const a=s.length>0;return e.jsxs("div",{className:"rounded-lg border overflow-hidden",style:{borderColor:r.border},children:[e.jsxs("button",{type:"button",onClick:o,className:"w-full flex items-center justify-between px-3 py-2 cursor-pointer border-none",style:{background:a?r.surfaceElevated:r.surface},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[n?e.jsx(Oe,{size:12}):e.jsx(re,{size:12}),e.jsx("span",{className:"text-[12px] font-semibold",style:{color:r.textPrimary},children:$n[t]}),a&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full font-bold",style:{background:"#FE5000",color:"white"},children:s.length})]}),!a&&e.jsx("span",{className:"text-[11px]",style:{color:r.textFaint},children:"No changes"})]}),!n&&a&&e.jsx("div",{className:"px-3 py-2",style:{background:r.surface},children:s.map(i=>e.jsx(Fn,{change:i,t:r},`${i.category}-${i.field}`))})]})}function An({diff:t,t:s}){const{totalChanges:n,changeTypes:o}=t.summary;return n===0?e.jsx("p",{className:"text-[12px]",style:{color:s.textFaint},children:"These versions are identical."}):e.jsxs("div",{className:"flex items-center gap-3 text-[12px]",children:[e.jsxs("span",{style:{color:s.textSecondary},children:[n," change",n!==1?"s":""]}),o.added>0&&e.jsxs("span",{style:{color:"#00c864"},children:["+",o.added," added"]}),o.removed>0&&e.jsxs("span",{style:{color:"#ff4444"},children:["−",o.removed," removed"]}),o.modified>0&&e.jsxs("span",{style:{color:"#ffa000"},children:[o.modified," modified"]})]})}function Pn({versionA:t,versionB:s,onClose:n}){const o=q(),[r,a]=h.useState(new Set),i=h.useMemo(()=>Mn(t.snapshot,s.snapshot,t.version,s.version),[t,s]),l=c=>{a(u=>{const d=new Set(u);return d.has(c)?d.delete(c):d.add(c),d})};return e.jsx("div",{className:"fixed inset-0 z-[200] flex items-center justify-center",style:{background:"rgba(0,0,0,0.65)"},onClick:c=>{c.target===c.currentTarget&&n()},children:e.jsxs("div",{className:"w-[600px] max-h-[80vh] flex flex-col rounded-xl border shadow-2xl",style:{background:o.surface,borderColor:o.border},children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b shrink-0",style:{borderColor:o.border},children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[13px] font-bold",style:{color:o.textPrimary,fontFamily:"'Geist Mono', monospace"},children:["v",t.version," → v",s.version]}),e.jsx(An,{diff:i,t:o})]}),e.jsx("button",{type:"button",onClick:n,className:"flex items-center justify-center w-7 h-7 rounded-md cursor-pointer border-none bg-transparent",style:{color:o.textMuted},"aria-label":"Close diff view",children:e.jsx(ae,{size:14})})]}),e.jsx("div",{className:"overflow-y-auto flex-1 p-4 flex flex-col gap-2",children:_n.map(c=>e.jsx(In,{category:c,changes:i.changes.filter(u=>u.category===c),collapsed:r.has(c),onToggle:()=>l(c),t:o},c))})]})})}function Dn({onSettingsClick:t,onBack:s,onImport:n}){const o=I(g=>g.running),r=I(g=>g.run),a=I(g=>g.agentMeta),i=ie(g=>g.currentVersion),l=ie(g=>g.versions),c=ie(g=>g.restoreVersion),u=ie(g=>g.agentId),d=ie(g=>g.loadVersions),p=ie(g=>g.saveStatus),j=Re(g=>g.toggleTheme),[w,y]=h.useState(!1),[S,E]=h.useState(null),[C,k]=h.useState(null),m=h.useRef(null),x=q();return h.useEffect(()=>{u&&l.length===0&&d()},[u,d]),h.useEffect(()=>{const g=R=>{m.current&&!m.current.contains(R.target)&&y(!1)};if(w)return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[w]),e.jsxs("div",{className:"flex items-center h-[48px] px-4 gap-3 shrink-0 border-b select-none",style:{background:x.surface,backdropFilter:"blur(12px)",borderColor:x.border,position:"relative",zIndex:50},children:[s&&e.jsx("button",{type:"button",onClick:s,className:"flex items-center justify-center w-8 h-8 rounded-md cursor-pointer border-none bg-transparent hover:bg-[#FE500015]",style:{color:x.textSecondary},"aria-label":"Back to library",title:"Back to library",children:e.jsx(Es,{size:16})}),e.jsxs("div",{className:"flex items-center gap-2 mr-4",children:[e.jsx("div",{className:"w-2 h-2 rounded-full",style:{background:"#FE5000",boxShadow:"0 0 8px rgba(254,80,0,0.4)"},"aria-hidden":"true"}),e.jsx("h1",{className:"text-[17px] font-bold tracking-[3px] uppercase m-0",style:{fontFamily:"'Geist Mono', monospace",color:x.textPrimary},children:"MODULAR"})]}),a.name&&e.jsxs("div",{className:"flex items-center gap-2 mx-4",children:[e.jsx("span",{className:"text-[15px] font-semibold",style:{color:x.textPrimary},children:a.name}),e.jsxs("div",{className:"relative",ref:m,children:[e.jsxs("button",{type:"button",onClick:()=>y(!w),"aria-expanded":w,"aria-haspopup":"menu","aria-label":`Version ${i} dropdown menu`,title:"Select version",className:"flex items-center gap-1 px-2 py-1 rounded-md cursor-pointer border-none text-[13px] font-semibold",style:{background:x.surfaceElevated,color:x.textSecondary,fontFamily:"'Geist Mono', monospace",border:`1px solid ${x.border}`},children:["v",i,e.jsx(re,{size:10})]}),w&&e.jsx("div",{className:"absolute top-full right-0 mt-1 w-64 rounded-lg border shadow-lg overflow-hidden",style:{background:x.surface,borderColor:x.border,boxShadow:"0 4px 12px rgba(0,0,0,0.15)",zIndex:100},children:e.jsxs("div",{className:"p-2 max-h-80 overflow-y-auto",children:[l.slice().reverse().map(g=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-md hover:bg-opacity-50",style:{background:g.version===i?"rgba(254, 80, 0, 0.1)":"transparent"},children:[e.jsxs("div",{className:"flex flex-col min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-[13px] font-bold",style:{fontFamily:"'Geist Mono', monospace",color:g.version===i?"#FE5000":x.textPrimary},children:["v",g.version]}),g.version===i&&e.jsx("span",{className:"text-[10px] px-1 py-0.5 rounded text-white bg-green-600",children:"CURRENT"})]}),e.jsx("span",{className:"text-[11px] truncate",style:{color:x.textMuted},children:g.label||"Checkpoint"}),e.jsx("span",{className:"text-[10px]",style:{color:x.textFaint},children:new Date(g.timestamp).toLocaleString()})]}),g.version!==i&&e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsxs("button",{type:"button",onClick:()=>{l.find(M=>M.version===i)&&(E(g),y(!1))},title:`Compare v${g.version} with current`,"aria-label":`Compare version ${g.version} with current`,className:"flex items-center gap-1 px-2 py-1 rounded text-[11px] font-medium border-none cursor-pointer",style:{background:x.surfaceElevated,color:x.textSecondary,border:`1px solid ${x.border}`},children:[e.jsx(Ts,{size:10,"aria-hidden":"true"}),"Compare"]}),e.jsxs("button",{type:"button",onClick:()=>{k(g.version),y(!1)},title:`Restore version ${g.version}`,className:"flex items-center gap-1 px-2 py-1 rounded text-[11px] font-medium border-none cursor-pointer",style:{background:"#FE5000",color:"white"},children:[e.jsx(Ms,{size:10}),"Restore"]})]})]},g.id)),l.length===0&&e.jsx("div",{className:"p-4 text-center",children:e.jsx("div",{className:"text-[12px]",style:{color:x.textFaint},children:"No versions yet"})})]})})]})]}),u&&e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-medium px-2 py-1 rounded",style:{color:p==="saved"?"#16a34a":p==="saving"?"#ca8a04":p==="error"?"#dc2626":x.textMuted},title:p==="saved"?"All changes saved":p==="saving"?"Saving…":p==="error"?"Save failed":"Unsaved changes",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{background:p==="saved"?"#16a34a":p==="saving"?"#ca8a04":p==="error"?"#dc2626":"#6b7280"}}),p==="saved"?"Saved":p==="saving"?"Saving…":p==="error"?"Save failed":"Unsaved"]}),e.jsx("div",{className:"flex-1"}),n&&e.jsxs("button",{type:"button",onClick:n,className:"flex items-center justify-center gap-1.5 h-8 px-3 rounded-lg text-[12px] font-medium cursor-pointer border-none",style:{background:"transparent",color:x.textSecondary,border:`1px solid ${x.border}`},"aria-label":"Import agent from file",title:"Import agent",onMouseEnter:g=>{g.currentTarget.style.color=x.textPrimary,g.currentTarget.style.borderColor=x.textDim},onMouseLeave:g=>{g.currentTarget.style.color=x.textSecondary,g.currentTarget.style.borderColor=x.border},children:[e.jsx($s,{size:12,"aria-hidden":"true"}),"Import"]}),e.jsx("button",{type:"button",onClick:t,className:"flex items-center justify-center w-11 h-11 rounded-md cursor-pointer border-none bg-transparent hover-accent-text focus-visible:outline focus-visible:outline-2",style:{color:x.textDim},"aria-label":"LLM settings",title:"LLM settings",children:e.jsx(tt,{size:14})}),e.jsx("button",{type:"button",onClick:j,className:"flex items-center justify-center w-11 h-11 rounded-md cursor-pointer border-none bg-transparent hover-accent-text focus-visible:outline focus-visible:outline-2",style:{color:x.textDim},"aria-label":x.isDark?"Switch to light mode":"Switch to dark mode",title:x.isDark?"Switch to light mode":"Switch to dark mode",children:x.isDark?e.jsx(It,{size:14}):e.jsx(At,{size:14})}),e.jsxs("button",{type:"button",onClick:r,title:o?"Stop execution":"Run agent",className:"flex items-center justify-center gap-1.5 h-8 px-4 rounded-lg text-[14px] font-semibold tracking-wider uppercase cursor-pointer border-none",style:{background:o?"#CC4000":"#FE5000",color:"#fff",boxShadow:o?"0 0 12px rgba(254,80,0,0.5)":"0 0 8px rgba(254,80,0,0.25)",opacity:o?.8:1,animation:o?"run-pulse-ring 1.5s ease infinite":"none",transition:"background 0.2s ease, opacity 0.2s ease"},children:[o?e.jsx(_s,{size:12,fill:"white"}):e.jsx(Pt,{size:12,fill:"white"}),o?"Stop":"Run",e.jsx("span",{className:"text-[13px] opacity-60 tracking-normal font-normal ml-1",children:o?"click to cancel":"Ctrl+Enter"})]}),C&&e.jsx("div",{className:"fixed inset-0 z-[200] flex items-center justify-center",style:{background:"rgba(0,0,0,0.6)"},onClick:()=>k(null),children:e.jsxs("div",{className:"flex flex-col gap-4 rounded-xl p-6",style:{background:x.surface,border:`1px solid ${x.border}`,boxShadow:"0 16px 40px rgba(0,0,0,0.4)",minWidth:320,maxWidth:400},onClick:g=>g.stopPropagation(),children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("span",{className:"text-[15px] font-bold",style:{color:x.textPrimary},children:["Restore v",C,"?"]}),e.jsx("span",{className:"text-[13px]",style:{color:x.textMuted},children:"This will replace your current agent config. This action cannot be undone."})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx("button",{type:"button",onClick:()=>k(null),className:"px-4 py-2 rounded-lg text-[13px] font-semibold cursor-pointer border-none",style:{background:x.surfaceElevated,color:x.textSecondary,border:`1px solid ${x.border}`},children:"Cancel"}),e.jsx("button",{type:"button",onClick:()=>{c(C),k(null)},className:"px-4 py-2 rounded-lg text-[13px] font-semibold cursor-pointer border-none",style:{background:"#FE5000",color:"white"},children:"Restore"})]})]})}),S&&(()=>{const g=l.find(R=>R.version===i);return g?e.jsx(Pn,{versionA:S,versionB:g,onClose:()=>E(null)}):null})()]})}function Rn(){const t=I(i=>i.totalTokens),s=I(i=>i.tokenBudget),n=q(),o=t(),r=Math.min(o/s*100,100);let a=n.statusSuccess;return r>80?a=n.statusError:r>55&&(a=n.statusWarning),e.jsxs("div",{className:"w-full px-4 py-2 flex items-center gap-3 shrink-0 border-t",style:{background:n.surfaceOpaque,borderColor:n.border},children:[e.jsx("span",{className:"text-[12px] tracking-wider uppercase shrink-0 font-medium",style:{fontFamily:"'Geist Mono', monospace",color:n.tokenLabel},children:"Token Budget"}),e.jsx("div",{className:"flex-1 h-[6px] rounded-full overflow-hidden",style:{background:n.tokenTrackBg},children:e.jsx("div",{className:"h-full rounded-full transition-all duration-300",style:{width:`${r}%`,background:`linear-gradient(90deg, ${a}cc, ${a})`,boxShadow:`0 0 6px ${a}30`}})}),e.jsx("span",{className:"text-[13px] shrink-0 tabular-nums",style:{fontFamily:"'Geist Mono', monospace",color:a,minWidth:56,textAlign:"right",whiteSpace:"nowrap"},children:o>=1e3?`${(o/1e3).toFixed(1)}K`:o}),e.jsxs("span",{className:"text-[13px] shrink-0",style:{fontFamily:"'Geist Mono', monospace",color:n.tokenDivider,minWidth:64,whiteSpace:"nowrap"},children:["/ ",s>=1e3?`${(s/1e3).toFixed(0)}K`:s]})]})}const gt=`${Z}/knowledge`,ge=Ne(t=>({tree:[],loaded:!1,scanning:!1,error:null,lastDir:"",scanDirectory:async s=>{t({scanning:!0,error:null});try{const o=await(await fetch(`${gt}/scan?dir=${encodeURIComponent(s)}&depth=3`)).json();o.status==="ok"&&o.data?t({tree:o.data,loaded:!0,scanning:!1,lastDir:s}):t({scanning:!1,error:o.error??"Scan failed"})}catch(n){t({scanning:!1,error:n instanceof Error?n.message:"Network error"})}},readFile:async s=>{try{const o=await(await fetch(`${gt}/read?path=${encodeURIComponent(s)}`)).json();return o.status==="ok"&&o.data?o.data:null}catch{return null}}}));function Ln(t){return t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function Qt(t,s){if(!s)return!0;const n=s.toLowerCase();return!!(t.name.toLowerCase().includes(n)||t.path.toLowerCase().includes(n)||t.children?.some(o=>Qt(o,s)))}function Zt({node:t,depth:s,onAdd:n,filter:o}){const[r,a]=h.useState(s<1||!!o),i=t.type==="directory"&&t.children&&t.children.length>0,l=q();return Qt(t,o)?e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 py-1.5 px-2 rounded cursor-pointer transition-colors",style:{paddingLeft:8+s*16},onMouseEnter:c=>{c.currentTarget.style.background=l.surfaceHover},onMouseLeave:c=>{c.currentTarget.style.background="transparent"},children:[i?e.jsx("button",{type:"button",onClick:()=>a(!r),className:"w-4 h-4 flex items-center justify-center text-[12px] cursor-pointer border-none bg-transparent",style:{color:l.textMuted},"aria-label":r?"Collapse folder":"Expand folder",children:r?"▼":"▶"}):e.jsx("span",{className:"w-4"}),e.jsx("div",{className:"w-[6px] h-[6px] rounded-full shrink-0",style:{background:t.type==="directory"?"#f1c40f":"#3498db"}}),e.jsx("span",{className:"flex-1 text-[13px] truncate",style:{fontFamily:"'Geist Mono', monospace",color:l.textPrimary},children:t.name}),t.tokenEstimate&&e.jsx("span",{className:"text-[13px] shrink-0",style:{fontFamily:"'Geist Mono', monospace",color:l.textDim},children:Ln(t.tokenEstimate)}),t.type==="file"&&e.jsx("button",{type:"button",onClick:()=>n(t),className:"px-2 py-0.5 rounded text-[12px] tracking-[1px] uppercase cursor-pointer border transition-colors shrink-0",style:{fontFamily:"'Geist Mono', monospace",background:"transparent",borderColor:l.border,color:l.textMuted},onMouseEnter:c=>{c.currentTarget.style.borderColor="#FE5000",c.currentTarget.style.color="#FE5000"},onMouseLeave:c=>{c.currentTarget.style.borderColor=l.border,c.currentTarget.style.color=l.textMuted},"aria-label":`Add ${t.name}`,children:"+ ADD"})]}),i&&r&&t.children.map(c=>e.jsx(Zt,{node:c,depth:s+1,onAdd:n,filter:o},c.path))]}):null}function zn(){const t=I(m=>m.showFilePicker),s=I(m=>m.setShowFilePicker),n=I(m=>m.addFileChannel),o=ge(m=>m.tree),r=ge(m=>m.loaded),a=ge(m=>m.scanning),i=ge(m=>m.scanDirectory),l=ge(m=>m.readFile),c=ge(m=>m.lastDir),[u,d]=h.useState(""),[p,j]=h.useState(""),w=h.useRef(null),y=h.useRef(null),S=q();h.useEffect(()=>{t&&(d(""),j(c),setTimeout(()=>w.current?.focus(),100))},[t,c]),h.useEffect(()=>{if(!t)return;const m=x=>{x.key==="Escape"&&s(!1)};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[t,s]);const E=h.useCallback(m=>{if(m.key!=="Tab"||!y.current)return;const x=y.current.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(x.length===0)return;const g=x[0],R=x[x.length-1];m.shiftKey?document.activeElement===g&&(m.preventDefault(),R.focus()):document.activeElement===R&&(m.preventDefault(),g.focus())},[]);if(!t)return null;const C=async m=>{if(m.type!=="file")return;const x=c.replace(/\\/g,"/")+"/"+m.path,g=await l(x);g&&n(g)},k=()=>{p.trim()&&i(p.trim())};return e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:()=>s(!1),children:[e.jsx("div",{className:"absolute inset-0",style:{background:"rgba(0,0,0,0.7)"}}),e.jsxs("div",{ref:y,role:"dialog","aria-modal":"true","aria-label":"Add Knowledge Source",className:"relative w-[560px] max-h-[70vh] flex flex-col rounded-lg overflow-hidden",style:{background:S.surfaceOpaque,border:`1px solid ${S.border}`,boxShadow:"0 24px 48px rgba(0,0,0,0.8)",animation:"modal-in 0.2s ease-out"},onClick:m=>m.stopPropagation(),onKeyDown:E,children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b",style:{borderColor:S.border},children:[e.jsx("span",{className:"text-[13px] font-bold tracking-[3px] uppercase",style:{fontFamily:"'Geist Mono', monospace",color:S.textPrimary},children:"ADD KNOWLEDGE SOURCE"}),e.jsx("button",{type:"button",onClick:()=>s(!1),className:"text-[17px] cursor-pointer border-none bg-transparent",style:{color:S.textMuted},onMouseEnter:m=>{m.currentTarget.style.color="#FE5000"},onMouseLeave:m=>{m.currentTarget.style.color=S.textMuted},"aria-label":"Close file picker",children:"✕"})]}),e.jsxs("div",{className:"px-4 py-2 border-b flex items-center gap-2",style:{borderColor:S.border},children:[e.jsx("input",{type:"text",value:p,onChange:m=>j(m.target.value),onKeyDown:m=>{m.key==="Enter"&&k()},placeholder:"Directory path to scan...",className:"flex-1 outline-none text-[13px]",style:{background:S.inputBg,border:`1px solid ${S.border}`,borderRadius:4,color:S.textPrimary,fontFamily:"'Geist Mono', monospace",padding:"6px 10px"},"aria-label":"Directory path to scan"}),e.jsx("button",{type:"button",onClick:k,disabled:a,className:"px-3 py-1 rounded text-[12px] tracking-wide uppercase cursor-pointer border-none",style:{background:"#FE5000",color:"#fff",opacity:a?.6:1},"aria-label":"Scan directory",children:a?"Scanning...":"Scan"})]}),e.jsx("div",{className:"px-4 py-2 border-b",style:{borderColor:S.borderSubtle},children:e.jsx("input",{ref:w,type:"text",value:u,onChange:m=>d(m.target.value),placeholder:"Filter results...",className:"w-full outline-none text-[13px]",style:{background:S.inputBg,border:`1px solid ${S.border}`,borderRadius:4,color:S.textPrimary,fontFamily:"'Geist Mono', monospace",padding:"6px 10px"},onFocus:m=>{m.currentTarget.style.borderColor="#FE500050"},onBlur:m=>{m.currentTarget.style.borderColor=S.border},"aria-label":"Filter knowledge sources"})}),e.jsx("div",{className:"flex-1 overflow-y-auto py-2 px-1",children:r&&o.length>0?o.map(m=>e.jsx(Zt,{node:m,depth:0,onAdd:x=>{C(x)},filter:u},m.path)):r&&o.length===0?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("span",{className:"text-[13px]",style:{color:S.textDim},children:"No files found. Try scanning a directory."})}):e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("span",{className:"text-[13px]",style:{color:S.textDim},children:"Enter a directory path and click Scan to browse files."})})})]})]})}const xe=Ne((t,s)=>({skills:[],loaded:!1,loading:!1,error:void 0,loadSkills:async()=>{if(!s().loading){t({loading:!0,error:void 0});try{const n=await fetch(`${Z}/claude-config/skills`);if(!n.ok){t({loaded:!0,loading:!1,error:`Failed to load skills (${n.status})`});return}const r=(await n.json())?.data??[];t({skills:r.map(a=>({...a,enabled:!0})),loaded:!0,loading:!1})}catch{t({loaded:!0,loading:!1,error:"Backend unavailable. Start the server with `npm run server` on port 4800."})}}},toggleSkill:n=>{t({skills:s().skills.map(o=>o.id===n?{...o,enabled:!o.enabled}:o)})}})),lt={presentation:Vs,mic:Js,cloud:Ys,code:Wt,"bar-chart-3":Gt,anchor:Us,"git-branch":Xe,palette:Hs,search:ye,image:qs,"book-open":Bt,hexagon:Ks,workflow:Ws,map:Gs,sparkles:We,compass:Bs,waves:Os,box:ot,layout:zs,wrench:Ot,cpu:Ge,triangle:Ls,"pen-tool":zt,mail:Rs,hash:Ds,github:Xe,"file-text":Be,flame:Ps,database:nt,globe:Lt,folder:As,target:Rt,"clipboard-list":Is,"hard-drive":Fs,shield:Dt,brain:st};function qe({icon:t,size:s=14,...n}){const o=lt[t];return o?e.jsx(o,{size:s,...n}):e.jsx(rt,{size:s,...n})}function On({icon:t,size:s=14,...n}){const o=lt[t];return o?e.jsx(o,{size:s,...n}):e.jsx(he,{size:s,...n})}function Bn({icon:t,size:s=14,...n}){const o=lt[t];return o?e.jsx(o,{size:s,...n}):e.jsx(he,{size:s,...n})}function ct({open:t,onClose:s,title:n,searchPlaceholder:o,width:r=520,hideSearch:a,children:i}){const[l,c]=h.useState(""),u=h.useRef(null),d=h.useRef(null),p=q();h.useEffect(()=>{t&&(c(""),setTimeout(()=>u.current?.focus(),100))},[t]),h.useEffect(()=>{if(!t)return;const w=y=>{y.key==="Escape"&&s()};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[t,s]);const j=h.useCallback(w=>{if(w.key!=="Tab"||!d.current)return;const y=d.current.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(y.length===0)return;const S=y[0],E=y[y.length-1];w.shiftKey?document.activeElement===S&&(w.preventDefault(),E.focus()):document.activeElement===E&&(w.preventDefault(),S.focus())},[]);return t?ze.createPortal(e.jsxs("div",{className:"fixed inset-0 z-[200] flex items-center justify-center",onClick:s,children:[e.jsx("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm"}),e.jsxs("div",{ref:d,role:"dialog","aria-modal":"true","aria-label":n,className:"relative max-h-[70vh] flex flex-col rounded-xl overflow-hidden",style:{width:r,background:p.surface,border:`1px solid ${p.border}`,borderRadius:"12px",boxShadow:"0 24px 48px rgba(0,0,0,0.6)",animation:"modal-in 0.2s ease-out"},onClick:w=>w.stopPropagation(),onKeyDown:j,children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-4",style:{borderBottom:`1px solid ${p.border}`},children:[e.jsx("span",{className:"text-[14px] font-semibold",style:{color:p.textPrimary,fontFamily:"'Geist Sans', sans-serif"},children:n}),e.jsx("button",{type:"button",onClick:s,className:"p-1 rounded-md cursor-pointer border-none bg-transparent transition-colors",style:{color:p.textDim},"aria-label":"Close",onMouseEnter:w=>{w.currentTarget.style.background="#ef444420",w.currentTarget.style.color="#ef4444"},onMouseLeave:w=>{w.currentTarget.style.background="transparent",w.currentTarget.style.color=p.textDim},children:e.jsx(ae,{size:16})})]}),!a&&e.jsx("div",{className:"px-5 py-3",style:{borderBottom:`1px solid ${p.borderSubtle}`},children:e.jsxs("div",{className:"relative",children:[e.jsx(ye,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2",style:{color:p.textDim}}),e.jsx("input",{ref:u,type:"text",value:l,onChange:w=>c(w.target.value),placeholder:o??"Search...",className:"w-full outline-none text-[13px] pl-9 pr-3 py-1.5 rounded-lg",style:{background:p.inputBg,border:`1px solid ${p.border}`,color:p.textPrimary,fontFamily:"'Geist Sans', sans-serif"},"aria-label":"Search"})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto py-2",children:i(l)})]})]}),document.body):null}const we=new Map,Me=new Set,Xt=new Set;let He=!1,$e=null;function Gn(t){const s=t.includes(":")?t.split(":").pop():t;return s.includes("/")?s.split("/").pop():s}function Wn(){return He?Promise.resolve():$e||($e=fetch(`${Z}/health/skills`).then(t=>t.json()).then(t=>{t.status==="ok"&&Array.isArray(t.data)&&t.data.forEach(s=>Xt.add(s.id)),He=!0}).catch(()=>{He=!0}),$e)}function Kn(t){return t==="ok"?"#2ecc71":t==="warning"?"#f39c12":t==="error"?"#e74c3c":"#888"}function dt({skillPath:t}){const s=q(),n=Gn(t),[o,r]=h.useState(()=>we.get(n)??null),[a,i]=h.useState(()=>!we.has(n)&&!Me.has(n)),[l,c]=h.useState(null);if(h.useEffect(()=>{if(we.has(n)){r(we.get(n)),i(!1);return}if(Me.has(n)){i(!1);return}let w=!1;return Wn().then(()=>{if(!w){if(!Xt.has(n)){Me.add(n),i(!1);return}fetch(`${Z}/health/skills/${encodeURIComponent(n)}`).then(y=>y.status===404?(Me.add(n),w||i(!1),null):y.json()).then(y=>{w||y===null||(y.status==="ok"&&y.data&&(we.set(n,y.data),r(y.data)),i(!1))}).catch(()=>{w||i(!1)})}}),()=>{w=!0}},[n]),!a&&o===null)return null;const u=a&&o===null,d=o?.securityIssues.some(w=>w.includes("undocumented"))??!1,p=[{key:"SEC",label:"SEC",color:o?o.securityIssues.length===0?"#2ecc71":"#e74c3c":"#888",tooltip:o?o.securityIssues.length===0?"Security: No issues":`Security: ${o.securityIssues.length} issue${o.securityIssues.length>1?"s":""}`:"Security: Loading..."},{key:"DEP",label:"DEP",color:o?o.outdatedDeps.length===0?"#2ecc71":"#f39c12":"#888",tooltip:o?o.outdatedDeps.length===0?"Dependencies: Up to date":`Dependencies: ${o.outdatedDeps.length} outdated`:"Dependencies: Loading..."},{key:"DOC",label:"DOC",color:o?d?"#e74c3c":"#2ecc71":"#888",tooltip:o?d?"Docs: Missing SKILL.md / README":"Docs: Present":"Docs: Loading..."}],j=Kn(o?.status??null);return e.jsxs("div",{style:{position:"relative",display:"inline-flex",alignItems:"center",gap:3},children:[u?e.jsx(te,{size:8,style:{color:"#888"},className:"animate-spin"}):e.jsx("span",{style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:j,flexShrink:0}}),p.map(w=>e.jsxs("div",{style:{position:"relative",display:"inline-flex",alignItems:"center",gap:2,cursor:"default"},onMouseEnter:()=>c(w.key),onMouseLeave:()=>c(null),children:[e.jsx("span",{style:{fontSize:12,fontFamily:"'Geist Mono', monospace",fontWeight:600,color:u?"#888":w.color,lineHeight:1},children:w.label}),l===w.key&&e.jsx("div",{style:{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%)",marginBottom:4,background:s.surfaceOpaque,border:`1px solid ${s.border}`,borderRadius:4,padding:"2px 6px",whiteSpace:"nowrap",fontSize:12,color:s.textPrimary,boxShadow:"0 4px 12px rgba(0,0,0,0.4)",zIndex:100,pointerEvents:"none"},children:w.tooltip})]},w.key))]})}const qn={content:"Content",analysis:"Analysis",development:"Development",domain:"Domain"},Hn=["content","analysis","development","domain"];function Un(t,s){const n=`${t} ${s}`.toLowerCase();return/analysis|insight|research|intel|feedback/.test(n)?"analysis":/code|dev|api|build|test|automation|github/.test(n)?"development":/content|write|presentation|slides|copy/.test(n)?"content":"domain"}function Yn(){const t=I(C=>C.showSkillPicker),s=I(C=>C.setShowSkillPicker),n=I(C=>C.skills),o=I(C=>C.addSkill),r=I(C=>C.upsertSkill),a=xe(C=>C.skills),i=xe(C=>C.loaded),l=xe(C=>C.loading),c=xe(C=>C.loadSkills),u=xe(C=>C.toggleSkill),d=q(),[p,j]=h.useState(()=>new Set);h.useEffect(()=>{t&&!i&&!l&&c()},[t,i,l,c]),h.useEffect(()=>{t&&j(new Set)},[t]),h.useEffect(()=>{if(a.length!==0)for(const C of a)r({id:C.id,name:C.name,description:C.description||"Installed skill"})},[a,r]);const w=h.useMemo(()=>{const C=new Set(n.filter(m=>m.added).map(m=>m.id)),k=new Map(n.map(m=>[m.id,m]));for(const m of a)k.has(m.id)||k.set(m.id,{id:m.id,name:m.name,icon:"zap",enabled:m.enabled,added:C.has(m.id),description:m.description||"Installed skill",category:Un(m.name,m.description||"")});return Array.from(k.values())},[n,a]),y=(C,k)=>{k||j(m=>{const x=new Set(m);return x.has(C)?x.delete(C):x.add(C),x})},S=()=>{p.forEach(C=>{o(C);const k=a.find(m=>m.id===C);k&&!k.enabled&&u(C)}),j(new Set),s(!1)},E=()=>{j(new Set),s(!1)};return e.jsx(ct,{open:t,onClose:E,title:"Select Skills",searchPlaceholder:"Search skills...",children:C=>{const k=w.filter(x=>{if(!C)return!0;const g=C.toLowerCase();return x.name.toLowerCase().includes(g)||x.description.toLowerCase().includes(g)}),m=Hn.map(x=>({category:x,label:qn[x],skills:k.filter(g=>g.category===x)})).filter(x=>x.skills.length>0);return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx("div",{className:"flex-1 overflow-y-auto",children:m.map(x=>e.jsxs("div",{children:[e.jsx("div",{className:"px-5 py-1.5",children:e.jsx("span",{className:"text-[12px] font-medium tracking-wider uppercase",style:{color:d.textDim},children:x.label})}),x.skills.map(g=>{const R=p.has(g.id),M=g.added;return e.jsxs("div",{className:`flex items-center gap-3 px-5 py-2.5 ${M?"cursor-default":"hover-row cursor-pointer"}`,style:{background:R?"#FE500012":"transparent"},onClick:()=>y(g.id,M),children:[e.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center shrink-0",style:{background:d.surfaceElevated},children:e.jsx(On,{icon:g.icon,size:16,style:{color:d.textSecondary}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[17px] font-medium",style:{color:d.textPrimary},children:g.name}),g.skillUrl?.startsWith("https://skills.sh/")&&e.jsx(dt,{skillPath:g.skillUrl.replace("https://skills.sh/","").split("/").pop()??""})]}),e.jsx("span",{className:"text-[14px]",style:{color:d.textDim},children:g.description})]}),M?e.jsxs("span",{className:"flex items-center gap-1 text-[14px] px-2.5 py-1 rounded-md",style:{color:d.statusSuccess,background:d.statusSuccessBg},children:[e.jsx(ee,{size:12})," Added"]}):e.jsx("div",{className:"w-4 h-4 rounded border-2 flex items-center justify-center shrink-0",style:{borderColor:R?"#FE5000":d.border,background:R?"#FE5000":"transparent"},children:R&&e.jsx(ee,{size:10,style:{color:"#fff"}})})]},g.id)})]},x.category))}),e.jsxs("div",{className:"flex items-center justify-end gap-3 px-5 py-3",style:{borderTop:`1px solid ${d.border}`,background:d.surfaceOpaque},children:[e.jsx("button",{type:"button",onClick:E,className:"px-4 py-2 text-[14px] rounded-lg cursor-pointer border",style:{background:"transparent",border:`1px solid ${d.border}`,color:d.textSecondary},children:"Cancel"}),e.jsxs("button",{type:"button",onClick:S,disabled:p.size===0,className:"px-4 py-2 text-[14px] rounded-lg cursor-pointer border-none",style:{background:p.size>0?"#FE5000":d.surfaceElevated,color:p.size>0?"#fff":d.textDim,opacity:p.size>0?1:.5,cursor:p.size>0?"pointer":"not-allowed"},children:["Add ",p.size>0?`${p.size} skill${p.size===1?"":"s"}`:"skills"]})]})]})}})}function es({content:t,children:s,position:n="top",delay:o=300}){const r=q(),[a,i]=h.useState(!1),[l,c]=h.useState({x:0,y:0}),u=h.useRef(void 0),d=h.useRef(null),p=()=>{u.current=setTimeout(()=>{if(!d.current)return;const y=d.current.getBoundingClientRect();c({x:y.left+y.width/2,y:n==="top"?y.top-8:y.bottom+8}),i(!0)},o)},j=()=>{clearTimeout(u.current),i(!1)},w=r.isDark?"#333":"#222";return e.jsxs(e.Fragment,{children:[e.jsx("span",{ref:d,onMouseEnter:p,onMouseLeave:j,className:"inline-flex",children:s}),a&&ze.createPortal(e.jsxs("div",{className:"fixed z-[300] pointer-events-none px-2.5 py-1.5 rounded text-[12px]",style:{left:l.x,top:l.y,transform:n==="top"?"translate(-50%, -100%)":"translate(-50%, 0)",background:w,color:"#fff",fontFamily:"'Geist Mono', monospace",boxShadow:"0 2px 8px rgba(0,0,0,0.3)",maxWidth:250,whiteSpace:"normal",lineHeight:1.4},children:[t,e.jsx("div",{style:{position:"absolute",left:"50%",transform:"translateX(-50%)",...n==="top"?{bottom:-4,borderLeft:"5px solid transparent",borderRight:"5px solid transparent",borderTop:`5px solid ${w}`}:{top:-4,borderLeft:"5px solid transparent",borderRight:"5px solid transparent",borderBottom:`5px solid ${w}`},width:0,height:0}})]}),document.body)]})}function Jn(){const t=I(f=>f.showMarketplace),s=I(f=>f.activeMarketplaceTab),n=I(f=>f.setShowMarketplace),o=I(f=>f.registrySkills),r=I(f=>f.installRegistrySkill),a=I(f=>f.upsertSkill),i=I(f=>f.skills),[l,c]=h.useState(""),[u,d]=h.useState("all"),[p,j]=h.useState(null),[w,y]=h.useState(null),[S,E]=h.useState(()=>new Set),[C,k]=h.useState([]),[m,x]=h.useState(!1),[g,R]=h.useState(null),[M,L]=h.useState(null),O=h.useRef(null),_=h.useRef(null),$=q(),G=new Set(Array.isArray(i)?i.filter(f=>f.added).map(f=>f.id??""):[]),v=h.useCallback(f=>{if(f.key!=="Tab"||!_.current)return;const B=_.current.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(B.length===0)return;const H=B[0],Y=B[B.length-1];f.shiftKey?document.activeElement===H&&(f.preventDefault(),Y.focus()):document.activeElement===Y&&(f.preventDefault(),H.focus())},[]);h.useEffect(()=>{t&&(c(""),d("all"),j(null),y(null),k([]),x(!1),R(null),L(null),setTimeout(()=>O.current?.focus(),100))},[t]),h.useEffect(()=>{if(!t)return;const f=B=>{B.key==="Escape"&&n(!1)};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[t,n]);const K=h.useCallback(f=>{n(!0,f),c(""),d("all"),k([]),R(null),x(!1)},[n]),b=h.useCallback((f,B,H)=>{j(f),L(null),setTimeout(()=>{r(f,B,H),j(null)},1200)},[r]),P=h.useCallback(async f=>{y(f.id);try{const B=await fetch(`${Z}/skills/install`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({skillId:f.id})});if(!B.ok)throw new Error(`HTTP ${B.status}`);E(H=>new Set(H).add(f.id)),a({id:f.id,name:f.name,description:`Installed from skills.sh (${f.repo})`,skillUrl:f.url})}catch(B){R(B instanceof Error?B.message:"Install failed")}finally{y(null)}},[a]);h.useEffect(()=>{if(!t||s!=="skills"){x(!1),k([]),R(null);return}const f=l.trim();if(f.length<2){x(!1),k([]),R(null);return}const B=new AbortController,H=setTimeout(async()=>{x(!0),R(null);try{const Y=await fetch(`${Z}/skills/search?q=${encodeURIComponent(f)}`,{signal:B.signal});if(!Y.ok)throw new Error(`HTTP ${Y.status}`);const J=await Y.json();k(Array.isArray(J.data)?J.data:[]),R(J.error??null)}catch(Y){if(B.signal.aborted)return;k([]),R(Y instanceof Error?Y.message:"Search failed")}finally{B.signal.aborted||x(!1)}},300);return()=>{B.abort(),clearTimeout(H)}},[s,l,t]);const T=()=>{if(typeof window>"u")return 4;const f=window.innerWidth;return f<=1024?2:f<=1440?3:4},[F,z]=h.useState(T);if(h.useEffect(()=>{const f=()=>z(T());return window.addEventListener("resize",f),()=>window.removeEventListener("resize",f)},[]),!t)return null;const A=(f,B)=>{if(!l)return!0;const H=l.toLowerCase();return f.toLowerCase().includes(H)||B.toLowerCase().includes(H)},N=o.filter(f=>A(f.name,f.description)&&(u==="all"||f.category===u)),W=gs.filter(f=>A(f.name,f.description)),U={display:"grid",gridTemplateColumns:`repeat(${F}, 1fr)`,gap:12,padding:16,alignContent:"start"};return e.jsx(e.Fragment,{children:e.jsxs("div",{style:{position:"fixed",top:0,left:0,right:0,bottom:0,zIndex:50,display:"flex",alignItems:"center",justifyContent:"center"},onClick:()=>n(!1),children:[e.jsx("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm"}),e.jsxs("div",{ref:_,role:"dialog","aria-modal":"true","aria-label":"Marketplace",style:{position:"relative",display:"flex",flexDirection:"column",borderRadius:"12px",overflow:"hidden",isolation:"isolate",zIndex:1,width:"90vw",maxWidth:1600,height:"80vh",background:$.surface,border:`1px solid ${$.border}`,boxShadow:"0 24px 48px rgba(0,0,0,0.6)",animation:"modal-in 0.2s ease-out"},onClick:f=>f.stopPropagation(),onKeyDown:v,children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"12px 16px",borderBottom:`1px solid ${$.border}`},children:[e.jsx("span",{style:{fontSize:17,fontWeight:600,flexShrink:0,color:$.textPrimary,fontFamily:"'Geist Mono', monospace"},children:"Marketplace"}),e.jsxs("div",{style:{position:"relative",width:240,flexShrink:0},children:[e.jsx(ye,{size:13,style:{position:"absolute",left:10,top:"50%",transform:"translateY(-50%)",color:$.textDim}}),e.jsx("input",{ref:O,type:"text",value:l,onChange:f=>c(f.target.value),placeholder:"Search...",style:{width:"100%",outline:"none",fontSize:14,paddingLeft:32,paddingRight:12,paddingTop:6,paddingBottom:6,borderRadius:6,background:$.inputBg,border:`1px solid ${$.border}`,color:$.textPrimary,fontFamily:"'Geist Sans', sans-serif"}})]}),e.jsx("div",{style:{display:"flex",alignItems:"center",marginLeft:"auto",borderBottom:`1px solid ${$.borderSubtle}`},children:["skills","mcp","presets"].map(f=>e.jsx("button",{type:"button",onClick:()=>K(f),style:{padding:"6px 12px",fontSize:13,fontWeight:500,letterSpacing:"0.025em",textTransform:"uppercase",cursor:"pointer",border:"none",color:s===f?"#FE5000":$.textDim,borderBottom:s===f?"2px solid #FE5000":"2px solid transparent",background:"transparent",marginBottom:-1,transition:"color 150ms ease"},children:f==="mcp"?"MCP Servers":f==="presets"?"Presets":"Skills"},f))}),e.jsx(es,{content:"Close marketplace (Esc)",children:e.jsx("button",{type:"button",onClick:()=>n(!1),className:"transition-colors",style:{padding:4,borderRadius:6,cursor:"pointer",border:"none",background:"transparent",flexShrink:0,color:$.textDim},"aria-label":"Close marketplace",onMouseEnter:f=>{f.currentTarget.style.background="#ef444420",f.currentTarget.style.color="#ef4444"},onMouseLeave:f=>{f.currentTarget.style.background="transparent",f.currentTarget.style.color=$.textDim},children:e.jsx(ae,{size:16})})})]}),s==="skills"&&e.jsxs("div",{style:{display:"flex",alignItems:"center",padding:"8px 16px",borderBottom:`1px solid ${$.borderSubtle}`,gap:12,flexWrap:"wrap"},children:[e.jsx("div",{style:{display:"flex",alignItems:"center",gap:4,flexWrap:"wrap",flex:1},children:pt.map(f=>e.jsx("button",{type:"button",onClick:()=>d(f.id),style:{fontSize:12,padding:"2px 10px",borderRadius:9999,cursor:"pointer",border:"none",fontWeight:500,background:u===f.id?"#FE5000":$.surfaceElevated,color:u===f.id?"#fff":$.textSecondary,transition:"background 150ms ease, color 150ms ease"},children:f.label},f.id))}),e.jsx("div",{style:{display:"flex",alignItems:"center",gap:12,flexShrink:0},children:Object.entries(Ie).map(([f,B])=>e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:4,fontSize:13,color:$.textDim},children:[e.jsx("span",{style:{width:6,height:6,borderRadius:"50%",background:B.color,display:"inline-block",flexShrink:0}}),B.label]},f))})]}),s==="mcp"&&e.jsx("div",{style:{display:"flex",alignItems:"center",padding:"8px 16px",gap:4,flexWrap:"wrap",borderBottom:`1px solid ${$.borderSubtle}`},children:pt.map(f=>e.jsx("button",{type:"button",onClick:()=>d(f.id),style:{fontSize:12,padding:"2px 10px",borderRadius:9999,cursor:"pointer",border:"none",fontWeight:500,background:u===f.id?"#FE5000":$.surfaceElevated,color:u===f.id?"#fff":$.textSecondary,transition:"background 150ms ease, color 150ms ease"},children:f.label},f.id))}),e.jsxs("div",{style:{flex:1,overflowY:"auto"},children:[s==="skills"&&e.jsxs(e.Fragment,{children:[N.length>0&&e.jsx("div",{style:U,children:N.map(f=>e.jsx(Vn,{skill:f,isInLibrary:G.has(f.id),installing:p===f.id,dropdownOpen:M===f.id,onToggleDropdown:()=>L(M===f.id?null:f.id),onInstall:b,t:$},f.id))}),N.length===0&&!m&&!g&&C.length===0&&e.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"48px 0"},children:e.jsx("span",{style:{fontSize:14,color:$.textFaint},children:"No skills match your search"})}),(l.trim().length>=2||m||g||C.length>0)&&e.jsx("div",{style:{padding:"16px 16px 8px",borderTop:`1px solid ${$.borderSubtle}`},children:e.jsx("span",{style:{fontSize:12,letterSpacing:"0.05em",textTransform:"uppercase",color:$.textDim,fontFamily:"'Geist Mono', monospace"},children:"From skill.sh"})}),m&&e.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"24px 0"},children:e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6,fontSize:13,color:$.textDim},children:[e.jsx(te,{size:12,style:{animation:"spin 1s linear infinite"}}),"Searching skill.sh..."]})}),!m&&g&&e.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"24px 16px"},children:e.jsx("span",{style:{fontSize:13,color:$.statusError},children:"skill.sh search unavailable"})}),!m&&!g&&C.length>0&&e.jsx("div",{style:{...U,paddingTop:0},children:C.map(f=>e.jsx(Qn,{skill:f,installing:w===f.id,installed:S.has(f.id),onInstall:()=>P(f),t:$},f.id))}),!m&&!g&&l.trim().length>=2&&C.length===0&&e.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"24px 16px"},children:e.jsx("span",{style:{fontSize:13,color:$.textFaint},children:"No results from skill.sh"})})]}),s==="mcp"&&e.jsxs("div",{style:{textAlign:"center",padding:40},children:[e.jsx("p",{style:{color:$.textDim,marginBottom:12},children:"Browse and connect MCP servers"}),e.jsx("button",{onClick:()=>{n(!1),I.getState().setShowConnectionPicker(!0)},style:{background:"#FE5000",color:"#fff",border:"none",borderRadius:6,padding:"8px 16px",cursor:"pointer",fontFamily:"'Geist Mono', monospace"},children:"Open Connection Picker"})]}),s==="presets"&&e.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[W.map(f=>e.jsx(Zn,{preset:f,t:$,onLoad:()=>n(!1)},f.id)),W.length===0&&e.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"48px 0"},children:e.jsx("span",{style:{fontSize:14,color:$.textFaint},children:"No presets match your search"})})]})]})]})]})})}function Vn({skill:t,isInLibrary:s,installing:n,dropdownOpen:o,onToggleDropdown:r,onInstall:a,t:i}){const[l,c]=h.useState(!1),[u,d]=h.useState("claude"),[p,j]=h.useState("project"),w=s||t.installed;return e.jsxs("div",{style:{background:i.surfaceElevated,border:`1px solid ${w?i.borderSubtle:i.border}`,borderRadius:6,padding:"10px 12px",display:"flex",flexDirection:"column",gap:5,opacity:w?.55:1,position:"relative",transition:"border-color 150ms ease",minHeight:120},onMouseEnter:y=>{w||(y.currentTarget.style.borderColor="#FE500050")},onMouseLeave:y=>{y.currentTarget.style.borderColor=w?i.borderSubtle:i.border},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:6},children:[e.jsx("span",{style:{fontSize:13,fontWeight:600,color:i.textPrimary,fontFamily:"'Geist Mono', monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:t.name}),e.jsxs("span",{style:{fontSize:13,color:i.textDim,background:i.badgeBg,borderRadius:3,padding:"1px 4px",whiteSpace:"nowrap",flexShrink:0,fontFamily:"'Geist Mono', monospace"},children:[t.installs>=1e3?`${(t.installs/1e3).toFixed(1)}k`:t.installs,"↓"]})]}),e.jsx("span",{style:{fontSize:12,color:i.textDim,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontFamily:"'Geist Sans', sans-serif"},children:t.author}),e.jsxs("div",{style:{flex:1},children:[e.jsx("span",{style:{fontSize:12,color:i.textMuted,fontFamily:"'Geist Sans', sans-serif",lineHeight:1.4,display:l?"block":"-webkit-box",WebkitLineClamp:l?"unset":2,WebkitBoxOrient:"vertical",overflow:l?"visible":"hidden"},children:t.description}),e.jsx("button",{type:"button",onClick:()=>c(!l),style:{background:"none",border:"none",padding:0,cursor:"pointer",color:i.textDim,display:"inline-flex",alignItems:"center",marginTop:1},children:l?e.jsx(Ke,{size:9}):e.jsx(re,{size:9})})]}),e.jsx(dt,{skillPath:t.id}),e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginTop:2},children:[e.jsx("div",{style:{display:"flex",gap:4,alignItems:"center"},children:t.runtimes.map(y=>e.jsx("span",{title:Ie[y].label,style:{width:7,height:7,borderRadius:"50%",background:Ie[y].color,display:"inline-block",flexShrink:0}},y))}),w?e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:3,fontSize:13,color:i.statusSuccess,background:i.statusSuccessBg,borderRadius:4,padding:"2px 6px"},children:[e.jsx(ee,{size:9})," In Library"]}):n?e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:3,fontSize:13,color:"#FE5000",background:"#FE500010",borderRadius:4,padding:"2px 6px"},children:[e.jsx(te,{size:9,className:"animate-spin"})," Installing"]}):e.jsxs("button",{type:"button",onClick:r,style:{fontSize:13,padding:"2px 8px",borderRadius:4,cursor:"pointer",border:`1px solid ${o?"#FE5000":i.border}`,color:o?"#FE5000":i.textSecondary,background:"transparent",display:"inline-flex",alignItems:"center",gap:3,transition:"border-color 150ms ease, color 150ms ease"},onMouseEnter:y=>{y.currentTarget.style.borderColor="#FE5000",y.currentTarget.style.color="#FE5000"},onMouseLeave:y=>{o||(y.currentTarget.style.borderColor=i.border,y.currentTarget.style.color=i.textSecondary)},onFocus:y=>{y.currentTarget.style.borderColor="#FE5000",y.currentTarget.style.color="#FE5000"},onBlur:y=>{o||(y.currentTarget.style.borderColor=i.border,y.currentTarget.style.color=i.textSecondary)},children:["Install ",e.jsx(re,{size:8})]})]}),o&&e.jsxs("div",{style:{position:"absolute",right:0,top:"calc(100% + 4px)",background:i.surfaceOpaque,border:`1px solid ${i.border}`,boxShadow:"0 8px 24px rgba(0,0,0,0.5)",borderRadius:6,padding:10,zIndex:100,width:220,display:"flex",flexDirection:"column",gap:8},children:[e.jsxs("div",{children:[e.jsx("span",{style:{fontSize:13,fontWeight:600,color:i.textDim,fontFamily:"'Geist Mono', monospace",textTransform:"uppercase",letterSpacing:"0.05em"},children:"Target"}),e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:4},children:["all",...t.runtimes].map(y=>e.jsx("button",{type:"button",onClick:()=>d(y),style:{fontSize:13,padding:"2px 6px",borderRadius:4,cursor:"pointer",border:"none",background:u===y?"#FE5000":i.surfaceElevated,color:u===y?"#fff":i.textSecondary,fontWeight:500},children:y==="all"?"All":Ie[y].label},y))})]}),e.jsxs("div",{children:[e.jsx("span",{style:{fontSize:13,fontWeight:600,color:i.textDim,fontFamily:"'Geist Mono', monospace",textTransform:"uppercase",letterSpacing:"0.05em"},children:"Scope"}),e.jsx("div",{style:{display:"flex",gap:4,marginTop:4},children:["project","global"].map(y=>e.jsx("button",{type:"button",onClick:()=>j(y),style:{fontSize:13,padding:"2px 6px",borderRadius:4,cursor:"pointer",border:"none",background:p===y?"#FE5000":i.surfaceElevated,color:p===y?"#fff":i.textSecondary,fontWeight:500,textTransform:"capitalize"},children:y},y))})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4,background:i.inputBg,borderRadius:4,padding:"4px 6px"},children:[e.jsx(je,{size:9,style:{color:i.textDim,flexShrink:0}}),e.jsxs("code",{style:{fontSize:12,color:i.textMuted,fontFamily:"'Geist Mono', monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.installCmd," --target ",u," --scope ",p]})]}),e.jsx("button",{type:"button",onClick:()=>a(t.id,u,p),style:{width:"100%",padding:"6px",borderRadius:4,border:"none",background:"#FE5000",color:"#fff",fontSize:12,fontWeight:600,cursor:"pointer"},children:"Confirm Install"})]})]})}function Qn({skill:t,installing:s,installed:n,onInstall:o,t:r}){const[a,i]=h.useState(!1),l=t.url.replace("https://skills.sh/","");return e.jsxs("div",{style:{background:r.surfaceElevated,border:`1px solid ${r.border}`,borderRadius:6,padding:"10px 12px",display:"flex",flexDirection:"column",gap:5,position:"relative",transition:"border-color 150ms ease",minHeight:120},onMouseEnter:c=>{c.currentTarget.style.borderColor="#FE500050"},onMouseLeave:c=>{c.currentTarget.style.borderColor=r.border},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:6},children:[e.jsx("span",{style:{fontSize:13,fontWeight:600,color:r.textPrimary,fontFamily:"'Geist Mono', monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1},children:t.name}),e.jsxs("span",{style:{fontSize:13,color:r.textDim,background:r.badgeBg,borderRadius:3,padding:"1px 4px",whiteSpace:"nowrap",flexShrink:0,fontFamily:"'Geist Mono', monospace"},children:[t.installs,"↓"]})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[e.jsx("span",{style:{fontSize:12,color:r.textDim,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,fontFamily:"'Geist Sans', sans-serif"},children:t.repo}),e.jsx(es,{content:"View on skills.sh",children:e.jsx("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",style:{color:r.textDim,flexShrink:0,display:"inline-flex"},"aria-label":`Open ${t.name} on skills.sh`,onMouseEnter:c=>{c.currentTarget.style.color="#FE5000"},onMouseLeave:c=>{c.currentTarget.style.color=r.textDim},onFocus:c=>{c.currentTarget.style.color="#FE5000"},onBlur:c=>{c.currentTarget.style.color=r.textDim},children:e.jsx(Kt,{size:10})})})]}),e.jsxs("div",{style:{flex:1},children:[e.jsx("span",{style:{fontSize:12,color:r.textMuted,fontFamily:"'Geist Sans', sans-serif",lineHeight:1.4,display:a?"block":"-webkit-box",WebkitLineClamp:a?"unset":2,WebkitBoxOrient:"vertical",overflow:a?"visible":"hidden"},children:t.url}),e.jsx("button",{type:"button",onClick:()=>i(!a),style:{background:"none",border:"none",padding:0,cursor:"pointer",color:r.textDim,display:"inline-flex",alignItems:"center",marginTop:1},children:a?e.jsx(Ke,{size:9}):e.jsx(re,{size:9})})]}),e.jsx(dt,{skillPath:l}),e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginTop:2},children:[e.jsx(he,{size:10,style:{color:r.textDim}}),n?e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:3,fontSize:13,color:r.statusSuccess,background:r.statusSuccessBg,borderRadius:4,padding:"2px 6px"},children:[e.jsx(ee,{size:9})," Installed"]}):s?e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:3,fontSize:13,color:"#FE5000",background:"#FE500010",borderRadius:4,padding:"2px 6px"},children:[e.jsx(te,{size:9,className:"animate-spin"})," Installing"]}):e.jsxs("button",{type:"button",onClick:o,style:{fontSize:13,padding:"2px 8px",borderRadius:4,cursor:"pointer",border:`1px solid ${r.border}`,color:"#FE5000",background:"#FE500010",display:"inline-flex",alignItems:"center",gap:3},children:[e.jsx(at,{size:9})," Install"]})]})]})}function Zn({preset:t,t:s,onLoad:n}){return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"0 16px",minHeight:56,borderBottom:`1px solid ${s.borderSubtle}`,transition:"background 100ms ease"},onMouseEnter:o=>{o.currentTarget.style.background=s.surfaceHover},onMouseLeave:o=>{o.currentTarget.style.background="transparent"},children:[e.jsx("div",{style:{width:24,height:24,borderRadius:4,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,background:"#FE500010"},children:e.jsx(Bn,{icon:t.icon,size:14,style:{color:"#FE5000"}})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:14,fontWeight:500,color:s.textPrimary},children:t.name}),e.jsx("div",{style:{fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2,color:s.textMuted},title:t.description,spellCheck:!1,children:t.description}),e.jsxs("div",{style:{display:"flex",gap:4,marginTop:2},children:[t.skills.slice(0,3).map(o=>e.jsx("span",{style:{fontSize:12,padding:"0 4px",borderRadius:2,color:s.cableSkills,background:s.cableSkills+"10"},children:o},o)),t.mcpServers.slice(0,2).map(o=>e.jsx("span",{style:{fontSize:12,padding:"0 4px",borderRadius:2,color:s.cableMcp,background:s.cableMcp+"10"},children:o},o))]})]}),e.jsx("button",{type:"button",onClick:n,style:{fontSize:12,padding:"4px 8px",borderRadius:6,cursor:"pointer",flexShrink:0,background:"transparent",border:`1px solid ${s.border}`,color:s.textSecondary,whiteSpace:"nowrap",minWidth:80,transition:"border-color 150ms ease, color 150ms ease, background 150ms ease"},onMouseEnter:o=>{o.currentTarget.style.borderColor="#FE5000",o.currentTarget.style.color="#fff",o.currentTarget.style.background="#FE5000"},onMouseLeave:o=>{o.currentTarget.style.borderColor=s.border,o.currentTarget.style.color=s.textSecondary,o.currentTarget.style.background="transparent"},onFocus:o=>{o.currentTarget.style.borderColor="#FE5000",o.currentTarget.style.color="#fff",o.currentTarget.style.background="#FE5000"},onBlur:o=>{o.currentTarget.style.borderColor=s.border,o.currentTarget.style.color=s.textSecondary,o.currentTarget.style.background="transparent"},children:"Load Preset"})]})}const Ue=(t="none")=>{switch(t){case"oauth":return{bg:"#FE500010",color:"#FE5000",text:"OAuth"};case"api-key":return{bg:"#3498db10",color:"#3498db",text:"API Key"};default:return{bg:"#2ecc7110",color:"#2ecc71",text:"Local"}}};function Ye({status:t}){const s=t==="connected"?"#00cc66":t==="connecting"?"#f5a623":t==="error"?"#ff4444":"#555",n=t==="connected"?"Connected":t==="connecting"?"Connecting…":t==="error"?"Error":"Disconnected";return e.jsx("span",{className:t==="connecting"?"animate-pulse":"",style:{display:"inline-block",width:7,height:7,borderRadius:"50%",background:s,flexShrink:0},title:n})}function xt({title:t,collapsed:s,onToggle:n,t:o}){return e.jsxs("div",{className:"flex items-center gap-2 px-5 py-3 cursor-pointer select-none border-t transition-colors",onClick:n,style:{borderColor:o.borderSubtle},onMouseEnter:r=>{r.currentTarget.style.background=o.isDark?"#ffffff08":"#00000008"},onMouseLeave:r=>{r.currentTarget.style.background="transparent"},children:[s?e.jsx(Oe,{size:14,style:{color:o.textSecondary}}):e.jsx(re,{size:14,style:{color:o.textSecondary}}),e.jsx("span",{className:"text-[13px] font-semibold",style:{color:o.textPrimary,fontFamily:"'Geist Sans', sans-serif"},children:t})]})}function Xn(){const t=I(b=>b.showConnectionPicker),s=I(b=>b.setShowConnectionPicker),n=I(b=>b.connectors),o=I(b=>b.upsertMcpServer),r=q(),[a,i]=h.useState({}),[l,c]=h.useState({}),[u,d]=h.useState({}),[p,j]=h.useState(!1),[w,y]=h.useState(!1),[S,E]=h.useState("All"),[C,k]=h.useState({}),m=Q(b=>b.servers),x=Q(b=>b.addServer),g=me.filter(b=>b.authMethod==="oauth"&&!!b.url),R=["All",...Array.from(new Set(me.map(b=>b.category)))];h.useEffect(()=>{t&&g.forEach(b=>{xs(b.url).then(P=>{i(T=>({...T,[b.url]:P.connected}))}).catch(()=>{})})},[t]);const M=async b=>{c(P=>({...P,[b.url]:!0})),d(P=>({...P,[b.url]:""}));try{await ys(b.url),i(T=>({...T,[b.url]:!0})),await x({id:b.id,name:b.name,type:"http",command:"",args:[],env:{},url:b.url,headers:{},autoConnect:!0}),await o({id:b.id,name:b.name,description:b.description,connected:!0}),await Q.getState().loadServers()}catch(P){d(T=>({...T,[b.url]:P.message}))}finally{c(P=>({...P,[b.url]:!1}))}},L=b=>{const P=me.find(T=>T.id===b);P&&k(T=>({...T,[b]:{entry:P,expanded:!T[b]?.expanded,configValues:T[b]?.configValues||{}}}))},O=(b,P,T)=>{k(F=>({...F,[b]:{...F[b],configValues:{...F[b]?.configValues,[P]:T}}}))},_=async b=>{const T=C[b.id]?.configValues||{};await o({id:b.id,name:b.name,description:b.description,connected:!1});const F={};b.configFields&&b.configFields.length>0&&b.configFields.forEach(z=>{const A=T[z.key];A&&(F[z.key]=A)}),await x({id:b.id,name:b.name,type:b.transport==="stdio"?"stdio":"http",command:b.command||"",args:b.defaultArgs||[],env:F,autoConnect:!0,...b.url?{url:b.url}:{}}),k(z=>({...z,[b.id]:{...z[b.id],expanded:!1}}))},$=b=>m.some(P=>P.id===b)||n.some(P=>P.mcpServerId===b),G=b=>m.find(T=>T.id===b)?.status??"disconnected",v=b=>{const P=a[b.url]??!1,T=l[b.url]??!1,F=u[b.url],z=$(b.id),A=Ue("oauth");return e.jsxs("div",{className:"flex items-center gap-3 px-4 py-1.5 hover-row cursor-default",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center shrink-0",style:{background:r.surfaceElevated},children:e.jsx(qe,{icon:b.icon,size:16,style:{color:r.textSecondary}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ye,{status:P?"connected":"disconnected"}),e.jsx("span",{className:"text-[13px] font-medium",style:{color:r.textPrimary},children:b.name}),e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full uppercase",style:{background:A.bg,color:A.color,fontFamily:"'Geist Mono', monospace",fontWeight:600},children:A.text})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[11px]",style:{color:r.textDim},children:b.description}),F&&e.jsx("span",{className:"text-[10px] ml-2",style:{color:"#ff4444"},children:F})]})]}),z&&P?e.jsxs("span",{className:"flex items-center gap-1 text-[11px] px-2.5 py-1 rounded-md",style:{color:r.statusSuccess,background:r.statusSuccessBg},children:[e.jsx(ee,{size:12})," Connected"]}):e.jsxs("button",{type:"button",onClick:()=>M(b),disabled:T,className:"flex items-center gap-1.5 text-[11px] px-3 py-1 rounded-md cursor-pointer border-none transition-colors",style:{background:"#FE500018",color:"#FE5000",fontWeight:600,opacity:T?.7:1},onMouseEnter:N=>{N.currentTarget.style.background="#FE500030"},onMouseLeave:N=>{N.currentTarget.style.background="#FE500018"},children:[T?e.jsx(te,{size:12,className:"animate-spin"}):e.jsx(oe,{size:12}),T?"Connecting...":"Connect"]})]},b.id)},K=b=>{if(b.authMethod==="oauth"){const A=a[b.url]??!1,N=Ue("oauth");return e.jsxs("div",{className:"flex items-center gap-3 px-4 py-1.5 hover-row cursor-default",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center shrink-0",style:{background:r.surfaceElevated},children:e.jsx(qe,{icon:b.icon,size:16,style:{color:r.textSecondary}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ye,{status:A?"connected":"disconnected"}),e.jsx("span",{className:"text-[13px] font-medium",style:{color:r.textPrimary},children:b.name}),e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full uppercase",style:{background:N.bg,color:N.color,fontFamily:"'Geist Mono', monospace",fontWeight:600},children:N.text})]}),e.jsx("span",{className:"text-[11px]",style:{color:r.textDim},children:b.description})]}),e.jsxs("button",{type:"button",onClick:()=>b.url&&M(b),className:"flex items-center gap-1.5 text-[11px] px-3 py-1 rounded-md cursor-pointer border-none transition-colors",style:{background:"#FE500018",color:"#FE5000",fontWeight:600},onMouseEnter:W=>{W.currentTarget.style.background="#FE500030"},onMouseLeave:W=>{W.currentTarget.style.background="#FE500018"},children:[e.jsx(oe,{size:12}),"Connect via OAuth"]})]},b.id)}const P=$(b.id),T=Ue(b.authMethod),F=C[b.id],z=b.configFields&&b.configFields.length>0;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3 px-4 py-1.5 hover-row cursor-default",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center shrink-0",style:{background:r.surfaceElevated},children:e.jsx(qe,{icon:b.icon,size:16,style:{color:r.textSecondary}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ye,{status:G(b.id)}),e.jsx("span",{className:"text-[13px] font-medium",style:{color:r.textPrimary},children:b.name}),e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full uppercase",style:{background:T.bg,color:T.color,fontFamily:"'Geist Mono', monospace",fontWeight:600},children:T.text})]}),e.jsx("span",{className:"text-[11px]",style:{color:r.textDim},children:b.description})]}),P?e.jsxs("span",{className:"flex items-center gap-1 text-[11px] px-2.5 py-1 rounded-md",style:{color:r.statusSuccess,background:r.statusSuccessBg},children:[e.jsx(ee,{size:12})," Added"]}):e.jsxs("button",{type:"button",onClick:()=>z?L(b.id):_(b),className:"flex items-center gap-1.5 text-[11px] px-3 py-1 rounded-md cursor-pointer border-none",style:{background:"#FE500018",color:"#FE5000",fontWeight:600},children:[e.jsx(oe,{size:12}),"Add"]})]}),z&&F?.expanded&&e.jsxs("div",{className:"px-4 py-3 ml-11 mr-4 mb-2 rounded-lg",style:{background:r.surfaceElevated},children:[e.jsx("div",{className:"text-[12px] font-medium mb-2",style:{color:r.textPrimary},children:"Configuration"}),e.jsxs("div",{className:"space-y-2",children:[b.configFields.map(A=>e.jsxs("div",{children:[e.jsxs("label",{className:"text-[11px]",style:{color:r.textDim},children:[A.label," ",A.required&&"*"]}),e.jsx("input",{type:A.type==="password"||A.key.toLowerCase().includes("token")||A.key.toLowerCase().includes("key")?"password":"text",placeholder:A.placeholder,value:F.configValues[A.key]||"",onChange:N=>O(b.id,A.key,N.target.value),className:"w-full mt-1 px-2 py-1 text-[12px] rounded border outline-none",style:{background:r.inputBg,border:`1px solid ${r.border}`,color:r.textPrimary,fontFamily:"'Geist Mono', monospace"}})]},A.key)),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs("button",{type:"button",onClick:()=>_(b),disabled:b.configFields.some(A=>A.required&&!F.configValues[A.key]),className:"flex items-center gap-1 text-[11px] px-3 py-1.5 rounded-md cursor-pointer border-none",style:{background:"#FE5000",color:"white",fontWeight:600,opacity:b.configFields.some(A=>A.required&&!F.configValues[A.key])?.5:1},children:[e.jsx(ee,{size:12}),"Save & Add"]}),e.jsx("button",{type:"button",onClick:()=>L(b.id),className:"text-[11px] px-3 py-1.5 rounded-md cursor-pointer border-none",style:{background:r.border,color:r.textDim},children:"Cancel"})]})]})]})]},b.id)};return e.jsx(ct,{open:t,onClose:()=>s(!1),title:"Add Connection",searchPlaceholder:"Search connections...",width:600,children:b=>{const P=b?.toLowerCase()??"",T=g.filter(z=>!P||z.name.toLowerCase().includes(P)||z.description.toLowerCase().includes(P)),F=me.filter(z=>{const A=!P||z.name.toLowerCase().includes(P)||z.description.toLowerCase().includes(P)||z.tags&&z.tags.some(W=>W.toLowerCase().includes(P)),N=S==="All"||z.category===S;return A&&N});return e.jsxs(e.Fragment,{children:[T.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(xt,{title:"Quick Connect",collapsed:p,onToggle:()=>j(!p),t:r}),!p&&e.jsx("div",{className:"pb-2",children:T.map(v)})]}),e.jsx(xt,{title:"MCP Library",collapsed:w,onToggle:()=>y(!w),t:r}),!w&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex gap-1 px-5 py-2 overflow-x-auto",children:R.map(z=>e.jsx("button",{type:"button",onClick:()=>E(z),className:"text-[11px] px-2 py-1 rounded-md cursor-pointer border-none whitespace-nowrap transition-colors",style:{background:S===z?"#FE5000":"transparent",color:S===z?"white":r.textDim,fontFamily:"'Geist Mono', monospace",fontWeight:600},onMouseEnter:A=>{S!==z&&(A.currentTarget.style.background="#FE500015",A.currentTarget.style.color="#FE5000")},onMouseLeave:A=>{S!==z&&(A.currentTarget.style.background="transparent",A.currentTarget.style.color=r.textDim)},children:z},z))}),e.jsx("div",{className:"max-h-[400px] overflow-y-auto pb-2",children:F.map(K)})]})]})}})}const eo=[{id:"github",name:"GitHub",icon:"🐙",description:"Issues, PRs, and code search",authMethod:"api-key",supportedSurfaces:["knowledge","tool"],routeId:"github",authFields:[{key:"apiKey",label:"Personal Access Token",type:"password",placeholder:"ghp_...",required:!0}]},{id:"slack",name:"Slack",icon:"💬",description:"Channels, messages, and search",authMethod:"api-key",supportedSurfaces:["knowledge","tool","output"],routeId:"slack",authFields:[{key:"apiKey",label:"Bot Token",type:"password",placeholder:"xoxb-...",required:!0}]},{id:"notion",name:"Notion",icon:"📄",description:"Databases, pages, and workspace search",authMethod:"api-key",supportedSurfaces:["knowledge","tool"],routeId:"notion",authFields:[{key:"apiKey",label:"API Key",type:"password",placeholder:"secret_...",required:!0}]},{id:"jira",name:"Jira",icon:"🎫",description:"Issues, sprints, and project boards",authMethod:"api-key",supportedSurfaces:["knowledge","tool"],routeId:"jira",authFields:[{key:"apiKey",label:"API Token",type:"password",placeholder:"ATATT3x...",required:!0},{key:"email",label:"Email",type:"text",placeholder:"user@company.com",required:!0},{key:"domain",label:"Domain",type:"text",placeholder:"company.atlassian.net",required:!0}]},{id:"hubspot",name:"HubSpot",icon:"🧲",description:"CRM contacts, deals, tickets",authMethod:"api-key",supportedSurfaces:["knowledge","tool"],routeId:"hubspot",authFields:[{key:"apiKey",label:"Private App Token",type:"password",placeholder:"pat-...",required:!0}]},{id:"airtable",name:"Airtable",icon:"📊",description:"Bases, tables, and records",authMethod:"api-key",supportedSurfaces:["knowledge","tool"],routeId:"airtable",authFields:[{key:"apiKey",label:"Personal Access Token",type:"password",placeholder:"pat...",required:!0}]},{id:"confluence",name:"Confluence",icon:"📚",description:"Spaces, pages, and content",authMethod:"api-key",supportedSurfaces:["knowledge"],routeId:"confluence",authFields:[{key:"apiKey",label:"API Token",type:"password",placeholder:"ATATT3x...",required:!0},{key:"email",label:"Email",type:"text",placeholder:"user@company.com",required:!0},{key:"domain",label:"Domain",type:"text",placeholder:"company.atlassian.net",required:!0}]},{id:"linear",name:"Linear",icon:"📐",description:"Issues, projects, and cycles",authMethod:"api-key",supportedSurfaces:["knowledge","tool"],routeId:"linear",authFields:[{key:"apiKey",label:"API Key",type:"password",placeholder:"lin_api_...",required:!0}]},{id:"google-docs",name:"Google Docs",icon:"📝",description:"Documents and shared drives",authMethod:"oauth",supportedSurfaces:["knowledge"],routeId:"google-docs",authFields:[]},{id:"google-sheets",name:"Google Sheets",icon:"📊",description:"Spreadsheets and structured data",authMethod:"oauth",supportedSurfaces:["knowledge","tool"],routeId:"google-sheets",authFields:[]},{id:"google-drive",name:"Google Drive",icon:"📁",description:"Files and folders",authMethod:"oauth",supportedSurfaces:["knowledge"],routeId:"google-drive",authFields:[]},{id:"gmail",name:"Gmail",icon:"✉️",description:"Emails and threads",authMethod:"oauth",supportedSurfaces:["knowledge","output"],routeId:"gmail",authFields:[]},{id:"plane",name:"Plane",icon:"✈️",description:"Issues, cycles, and modules",authMethod:"api-key",supportedSurfaces:["knowledge","tool"],routeId:"plane",authFields:[{key:"apiKey",label:"API Key",type:"password",placeholder:"plane_api_...",required:!0},{key:"baseUrl",label:"Instance URL",type:"url",placeholder:"https://app.plane.so",required:!0}]}];function to(){const t=I(m=>m.showConnectorPicker),s=I(m=>m.setShowConnectorPicker),n=I(m=>m.connectors),o=I(m=>m.addConnector),r=q(),[a,i]=h.useState(null),[l,c]=h.useState({}),[u,d]=h.useState({}),[p,j]=h.useState({}),[w,y]=h.useState({}),S=m=>n.some(x=>x.service===m),E=h.useCallback(async m=>{const x=l[m.id]??{};d(g=>({...g,[m.id]:!0})),j(g=>({...g,[m.id]:"idle"})),y(g=>({...g,[m.id]:""}));try{const R=await(await fetch(`${Z}/connectors/v2/${m.routeId}/test`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(x)})).json();R.status==="ok"?j(M=>({...M,[m.id]:"ok"})):(j(M=>({...M,[m.id]:"error"})),y(M=>({...M,[m.id]:R.error||"Test failed"})))}catch{j(g=>({...g,[m.id]:"error"})),y(g=>({...g,[m.id]:"Network error"}))}finally{d(g=>({...g,[m.id]:!1}))}},[l]),C=h.useCallback(m=>{o({id:`conn-${m.id}-${Date.now()}`,service:m.id,name:m.name,mcpServerId:"",direction:"both",enabled:!0,config:l[m.id]??{},status:"connected",authMethod:m.authMethod,surfaces:m.supportedSurfaces}),i(null),j(x=>({...x,[m.id]:"idle"}))},[o,l]),k=m=>{const x=S(m.id),g=a===m.id,R=u[m.id],M=p[m.id],L=w[m.id],O=m.authMethod==="oauth";return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 cursor-pointer",onClick:()=>!x&&i(g?null:m.id),style:{opacity:x?.5:1},children:[e.jsx("span",{className:"text-xl",children:m.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[13px] font-medium",style:{color:r.textPrimary},children:m.name}),e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full uppercase",style:{background:m.authMethod==="api-key"?"#3498db10":"#FE500010",color:m.authMethod==="api-key"?"#3498db":"#FE5000",fontFamily:"'Geist Mono', monospace",fontWeight:600},children:m.authMethod==="api-key"?"API Key":"OAuth"}),m.supportedSurfaces.map(_=>e.jsx("span",{className:"text-[9px] px-1 py-0.5 rounded",style:{background:r.isDark?"#ffffff10":"#00000008",color:r.textFaint},children:_},_))]}),e.jsx("span",{className:"text-[11px]",style:{color:r.textDim},children:m.description})]}),x?e.jsxs("span",{className:"flex items-center gap-1 text-[11px] px-2 py-1 rounded",style:{color:"#2ecc71",background:"#2ecc7110"},children:[e.jsx(ee,{size:12})," Connected"]}):e.jsx("span",{className:"text-[11px] px-2 py-1 rounded",style:{color:r.textDim,background:r.surfaceElevated},children:g?"▾":"Configure"})]}),g&&!x&&e.jsx("div",{className:"px-4 py-3 mx-4 mb-2 rounded-lg space-y-3",style:{background:r.surfaceElevated},children:O?e.jsx("div",{className:"text-[12px]",style:{color:r.textDim},children:"OAuth connectors require server-side configuration. Coming soon."}):e.jsxs(e.Fragment,{children:[m.authFields.map(_=>e.jsxs("div",{children:[e.jsxs("label",{className:"text-[11px] font-medium",style:{color:r.textDim},children:[_.label," ",_.required&&e.jsx("span",{style:{color:"#ef4444"},children:"*"})]}),e.jsx("input",{type:_.type==="password"?"password":"text",placeholder:_.placeholder,value:l[m.id]?.[_.key]??"",onChange:$=>c(G=>({...G,[m.id]:{...G[m.id],[_.key]:$.target.value}})),className:"w-full mt-1 px-2.5 py-1.5 text-[12px] rounded border outline-none",style:{background:r.inputBg,border:`1px solid ${r.border}`,color:r.textPrimary,fontFamily:"'Geist Mono', monospace"}})]},_.key)),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsxs("button",{type:"button",onClick:()=>E(m),disabled:R||m.authFields.some(_=>_.required&&!l[m.id]?.[_.key]),className:"flex items-center gap-1.5 px-3 py-1.5 rounded text-[12px] font-semibold border-none cursor-pointer",style:{background:"#2ecc71",color:"#fff",opacity:R?.6:1},children:[R?e.jsx(te,{size:12,className:"animate-spin"}):e.jsx(Qs,{size:12}),"Test Connection"]}),M==="ok"&&e.jsxs("button",{type:"button",onClick:()=>C(m),className:"flex items-center gap-1.5 px-3 py-1.5 rounded text-[12px] font-semibold border-none cursor-pointer",style:{background:"#FE5000",color:"#fff"},children:[e.jsx(oe,{size:12})," Add Connector"]})]}),M==="ok"&&e.jsxs("div",{className:"flex items-center gap-1 text-[11px]",style:{color:"#2ecc71"},children:[e.jsx(Ce,{size:12})," Connection verified"]}),M==="error"&&L&&e.jsxs("div",{className:"flex items-center gap-1 text-[11px]",style:{color:"#ef4444"},children:[e.jsx(De,{size:12})," ",L]})]})})]},m.id)};return e.jsx(ct,{open:t,onClose:()=>{s(!1),i(null)},title:"Connect API Service",searchPlaceholder:"Search connectors...",children:m=>{const x=m?.toLowerCase()??"",g=eo.filter(L=>!x||L.name.toLowerCase().includes(x)||L.description.toLowerCase().includes(x)||L.id.includes(x)),R=g.filter(L=>L.authMethod==="api-key"),M=g.filter(L=>L.authMethod==="oauth");return e.jsxs(e.Fragment,{children:[R.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-5 pt-3 pb-1 text-[11px] tracking-[0.12em] uppercase",style:{color:r.textDim,fontFamily:"'Geist Mono', monospace"},children:"API Key Authentication"}),R.map(k)]}),M.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-5 pt-3 pb-1 text-[11px] tracking-[0.12em] uppercase",style:{color:r.textDim,fontFamily:"'Geist Mono', monospace"},children:"OAuth (Coming Soon)"}),M.map(k)]})]})}})}const so=[{id:"providers",label:"Providers"},{id:"mcp",label:"MCP Servers"},{id:"general",label:"General"}];function Le(t,s){switch(t){case"connected":return s.statusSuccess;case"configured":return s.statusWarning;case"error":return s.statusError;default:return s.textMuted}}function no({provider:t}){const s=q(),[n,o]=h.useState(!1),[r,a]=h.useState(!1),[i,l]=h.useState(t.apiKey||""),[c,u]=h.useState(t.baseUrl),[d,p]=h.useState(null),j=X($=>$.setProviderKey),w=X($=>$.setProviderAuthMethod),y=X($=>$.setProviderBaseUrl),S=X($=>$.testConnection),E=X($=>$.testing[t.id]),C=X($=>$.deleteProvider),k=X($=>$.saveProvider),m=t.id.startsWith("custom-"),x=t.id==="openai",g=x&&t.authMethod==="oauth",R=t.id==="anthropic"?"Claude":t.name,M=Array.isArray(t.models)?t.models:[];h.useEffect(()=>{t.apiKey&&t.apiKey.trim().length>0&&l(t.apiKey),u(t.baseUrl)},[t.apiKey,t.baseUrl]);const L=h.useCallback(()=>{j(t.id,i),y(t.id,c),k(t.id)},[t.id,i,c,j,y,k]),O=h.useCallback(async()=>{L();const $=await S(t.id);p($)},[t.id,L,S]),_={background:s.inputBg,border:`1px solid ${s.border}`,color:s.textPrimary,fontFamily:"'Geist Sans', sans-serif"};return e.jsxs("div",{style:{background:n?s.surfaceElevated:"transparent",borderBottom:`1px solid ${s.borderSubtle}`},children:[e.jsxs("div",{role:"button",tabIndex:0,className:"nodrag nowheel w-full flex items-center gap-3 px-4 py-3 cursor-pointer border-none bg-transparent text-left",onClick:()=>o(!n),style:{color:s.textPrimary},children:[e.jsx("div",{className:"w-2 h-2 rounded-full shrink-0",style:{background:Le(t.status,s),boxShadow:`0 0 6px ${Le(t.status,s)}40`}}),e.jsx("div",{className:"w-6 h-6 rounded-md flex items-center justify-center shrink-0",style:{background:t.color+"20"},children:e.jsx(Ge,{size:14,style:{color:t.color}})}),e.jsx("span",{className:"text-[14px] font-semibold flex-1",style:{fontFamily:"'Geist Mono', monospace"},children:R}),e.jsx("span",{className:"text-[12px]",style:{color:s.textMuted},children:t.status==="connected"?`${M.length} models`:t.status})]}),n&&e.jsxs("div",{className:"px-4 pb-4 flex flex-col gap-3",children:[x&&e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{className:"text-[12px] tracking-wider uppercase",style:{color:s.textMuted,fontFamily:"'Geist Mono', monospace"},children:"Auth Mode"}),e.jsxs("select",{value:t.authMethod,onChange:$=>w(t.id,$.target.value),className:"nodrag nowheel w-full text-[14px] px-3 py-2 rounded-lg outline-none",style:_,children:[e.jsx("option",{value:"api-key",children:"API Key"}),e.jsx("option",{value:"oauth",children:"Local Session (experimental)"})]})]}),t.authMethod==="claude-agent-sdk"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 text-[14px] px-3 py-2.5 rounded-lg",style:{background:s.badgeBg,border:`1px solid ${s.borderSubtle}`},children:[e.jsx(je,{size:14,style:{color:t.color}}),e.jsx("span",{style:{color:s.textSecondary},children:"Authenticates via your Claude Code login — no API key needed."})]}),t.status==="connected"&&e.jsxs("div",{className:"flex items-center gap-2 text-[14px] px-3 py-2 rounded-lg",style:{background:s.statusSuccessBg,border:`1px solid ${s.statusSuccess}30`,color:s.statusSuccess},children:[e.jsx(Ce,{size:14}),e.jsxs("span",{children:["Authenticated",t.lastError?` — ${t.lastError}`:" via Claude Code"]})]}),t.status==="error"&&e.jsxs("div",{className:"flex items-center gap-2 text-[14px] px-3 py-2 rounded-lg",style:{background:s.statusErrorBg,border:`1px solid ${s.statusError}30`,color:s.statusError},children:[e.jsx(De,{size:14}),e.jsx("span",{children:t.lastError||"Not authenticated — install Claude Code and run claude login"})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{className:"text-[12px] tracking-wider uppercase",style:{color:s.textMuted,fontFamily:"'Geist Mono', monospace"},children:"Available Models"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:M.map($=>e.jsx("span",{className:"text-[12px] px-2 py-0.5 rounded",style:{background:t.color+"15",color:t.color,fontFamily:"'Geist Mono', monospace"},children:$.label},$.id))})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsxs("button",{type:"button",onClick:O,disabled:E,className:"nodrag nowheel flex items-center gap-1.5 text-[14px] px-3 py-1.5 rounded-lg cursor-pointer font-semibold border-none",style:{background:"#FE5000",color:"#fff",opacity:E?.6:1},children:[E?e.jsx(te,{size:12,className:"animate-spin"}):e.jsx(qt,{size:12}),"Check Status"]}),e.jsx("button",{type:"button",onClick:O,disabled:E,className:"nodrag nowheel flex items-center gap-1 text-[13px] px-2.5 py-1.5 rounded-lg cursor-pointer border-none",style:{color:s.textSecondary,background:s.badgeBg,opacity:E?.6:1},children:"Refresh Models"})]})]}):e.jsxs(e.Fragment,{children:[g?e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-start gap-2 text-[14px] px-3 py-2.5 rounded-lg",style:{background:s.badgeBg,border:`1px solid ${s.borderSubtle}`},children:[e.jsx(je,{size:14,style:{color:t.color,marginTop:1}}),e.jsx("span",{style:{color:s.textSecondary},children:"Codex browser sign-in (guided): open OpenAI dashboard, create key, and complete login flow."})]}),e.jsx("button",{type:"button",onClick:async()=>{try{const G=await(await fetch(`${Z}/auth/codex/start`,{method:"POST"})).json(),v=G?.data?.sessionId,K=G?.data?.authUrl;if(!v||!K)return;window.open(K,"_blank","noopener,noreferrer");const b=window.prompt("Paste your OpenAI API key to complete Codex login");if(!b)return;const F=(await(await fetch(`${Z}/auth/codex/complete/${v}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:b.trim()})})).json())?.data?.apiKey;if(!F)return;j(t.id,F),l(F),y(t.id,c),k(t.id),await O()}catch{}},className:"nodrag nowheel flex items-center justify-center gap-1.5 text-[14px] px-3 py-2 rounded-lg cursor-pointer font-semibold border-none",style:{background:"#FE5000",color:"#fff"},children:"Sign in with Codex"})]}):e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{className:"text-[12px] tracking-wider uppercase",style:{color:s.textMuted,fontFamily:"'Geist Mono', monospace"},children:"API Key"}),e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:r?"text":"password",value:i,onChange:$=>l($.target.value),onBlur:L,placeholder:t._hasStoredKey?"Key stored on server":"sk-...",className:"nodrag nowheel w-full text-[14px] px-3 py-2 pr-9 rounded-lg outline-none",style:_}),e.jsx("button",{type:"button",onClick:()=>a(!r),className:"nodrag nowheel absolute right-2 top-1/2 -translate-y-1/2 cursor-pointer border-none bg-transparent p-0.5",style:{color:s.textDim},children:r?e.jsx(nn,{size:14}):e.jsx(on,{size:14})})]})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{className:"text-[12px] tracking-wider uppercase",style:{color:s.textMuted,fontFamily:"'Geist Mono', monospace"},children:"Base URL"}),e.jsx("input",{type:"text",value:c,onChange:$=>u($.target.value),onBlur:L,className:"nodrag nowheel w-full text-[14px] px-3 py-2 rounded-lg outline-none",style:_})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsxs("button",{type:"button",onClick:O,disabled:E,className:"nodrag nowheel flex items-center gap-1.5 text-[14px] px-3 py-1.5 rounded-lg cursor-pointer font-semibold border-none",style:{background:"#FE5000",color:"#fff",opacity:E?.6:1},children:[E?e.jsx(te,{size:12,className:"animate-spin"}):e.jsx(rt,{size:12}),"Test Connection"]}),e.jsx("button",{type:"button",onClick:O,disabled:E,className:"nodrag nowheel flex items-center gap-1 text-[13px] px-2.5 py-1.5 rounded-lg cursor-pointer border-none",style:{color:s.textSecondary,background:s.badgeBg,opacity:E?.6:1},children:"Refresh Models"}),t.keyPageUrl&&!g&&e.jsxs("a",{href:t.keyPageUrl,target:"_blank",rel:"noopener noreferrer",className:"nodrag nowheel flex items-center gap-1 text-[13px] px-2 py-1.5 rounded-lg no-underline",style:{color:s.textSecondary,background:s.badgeBg},children:[e.jsx(Kt,{size:10}),"Get API Key"]}),m&&e.jsxs("button",{type:"button",onClick:()=>C(t.id),className:"nodrag nowheel flex items-center gap-1 text-[13px] px-2 py-1.5 rounded-lg cursor-pointer border-none ml-auto",style:{color:s.statusError,background:s.statusErrorBg},children:[e.jsx(it,{size:10}),"Remove"]})]}),d&&e.jsxs("div",{className:"flex items-center gap-2 text-[14px] px-3 py-2 rounded-lg",style:{background:d.ok?s.statusSuccessBg:s.statusErrorBg,border:`1px solid ${d.ok?s.statusSuccess+"30":s.statusError+"30"}`,color:d.ok?s.statusSuccess:s.statusError},children:[d.ok?e.jsx(Ce,{size:14}):e.jsx(De,{size:14}),d.ok?`Connected${d.models?` — ${d.models.length} models available`:""}`:d.error||"Connection failed"]})]}),t.headerNote&&e.jsx("span",{className:"text-[12px]",style:{color:s.textFaint},children:t.headerNote})]})]})}function oo(){const t=q(),s=X(o=>o.providers),n=X(o=>o.addCustomProvider);return e.jsxs("div",{className:"flex flex-col",children:[e.jsx("div",{className:"flex flex-col",children:s.filter((o,r,a)=>a.findIndex(i=>i.id===o.id)===r).map(o=>e.jsx(no,{provider:o},o.id))}),e.jsx("div",{className:"p-4",children:e.jsxs("button",{type:"button",onClick:n,className:"nodrag nowheel flex items-center gap-2 text-[14px] px-3 py-2 rounded-lg cursor-pointer w-full justify-center",style:{border:`1px dashed ${t.border}`,background:"transparent",color:t.textMuted},children:[e.jsx(oe,{size:12}),"Add Custom Provider"]})})]})}function ro({server:t}){const s=q(),[n,o]=h.useState(!1),r=Q(u=>u.connectServer),a=Q(u=>u.disconnectServer),i=Q(u=>u.removeServer),l=I(u=>u.removeMcpServer),c=h.useCallback(()=>{t.status==="connected"?a(t.id):r(t.id)},[t.id,t.status,r,a]);return e.jsxs("div",{style:{borderBottom:`1px solid ${s.borderSubtle}`},children:[e.jsxs("div",{className:"nodrag nowheel w-full flex items-center gap-3 px-4 py-3",children:[e.jsx("div",{className:"w-2 h-2 rounded-full shrink-0",style:{background:Le(t.status,s),boxShadow:`0 0 6px ${Le(t.status,s)}40`}}),e.jsx(rn,{size:14,style:{color:s.textDim}}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"text-[14px] font-semibold",style:{color:s.textPrimary,fontFamily:"'Geist Mono', monospace"},children:[t.name,t.mcpStatus&&t.mcpStatus!=="enabled"&&e.jsx("span",{className:"text-[12px] px-1.5 py-0.5 rounded ml-2 uppercase",style:{fontFamily:"'Geist Mono', monospace",fontWeight:600,background:t.mcpStatus==="deferred"?s.statusWarningBg:s.statusErrorBg,color:t.mcpStatus==="deferred"?s.statusWarning:s.statusError},children:t.mcpStatus})]}),e.jsx("div",{className:"text-[12px]",style:{color:s.textMuted},children:t.status==="connected"?`Connected · ${t.tools.length} tool${t.tools.length!==1?"s":""}${t.uptime?` · ${Math.round(t.uptime/1e3)}s uptime`:""}`:t.status==="connecting"?"Connecting…":t.status==="error"?t.lastError||"Connection error":"Disconnected"})]}),e.jsxs("button",{type:"button",onClick:u=>{u.stopPropagation(),c()},className:"nodrag nowheel flex items-center gap-1 text-[13px] px-2.5 py-1 rounded-lg cursor-pointer border-none",style:{background:t.status==="connected"?s.statusErrorBg:s.statusSuccessBg,color:t.status==="connected"?s.statusError:s.statusSuccess},children:[t.status==="connecting"?e.jsx(te,{size:10,className:"animate-spin"}):t.status==="connected"?e.jsx(qt,{size:10}):e.jsx(rt,{size:10}),t.status==="connecting"?"Connecting...":t.status==="connected"?"Disconnect":"Reconnect"]}),e.jsx("button",{type:"button",onClick:()=>{i(t.id),l(t.id)},className:"nodrag nowheel flex items-center gap-1 text-[13px] px-2 py-1 rounded-lg cursor-pointer border-none",style:{color:s.statusError,background:s.statusErrorBg},title:"Remove server",children:e.jsx(it,{size:10})})]}),t.tools.length>0&&e.jsxs("div",{className:"px-4 pb-3",children:[e.jsxs("button",{type:"button",onClick:()=>o(!n),className:"nodrag nowheel flex items-center gap-1 text-[12px] cursor-pointer border-none bg-transparent",style:{color:s.textDim},children:[n?e.jsx(re,{size:12}):e.jsx(Oe,{size:12}),"View Tools (",t.tools.length,")"]}),n&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:t.tools.map(u=>e.jsx("span",{className:"text-[12px] px-2 py-0.5 rounded",style:{background:"#FE500015",color:"#FE5000",fontFamily:"'Geist Mono', monospace"},title:u.description,children:u.name},u.name))})]})]})}function ao(){const t=q(),s=I(_=>_.mcpServers),n=Q(_=>_.servers),o=Q(_=>_.loaded),r=Q(_=>_.loading),a=Q(_=>_.loadServers),i=Q(_=>_.addServer),l=Q(_=>_.error),c=I(_=>_.upsertMcpServer),u=s.map(_=>{const $=n.find(G=>G.id===_.id);return{..._,status:$?.status||"disconnected",tools:$?.tools||[],lastError:$?.lastError||void 0,command:$?.command||_.description||"",args:$?.args||[],env:$?.env||{}}}),d=n.filter(_=>!s.some($=>$.id===_.id)).map(_=>({..._,isRuntimeOnly:!0})),p=[...u,...d],[j,w]=h.useState(!1),[y,S]=h.useState(""),[E,C]=h.useState(""),[k,m]=h.useState(""),[x,g]=h.useState(""),[R,M]=h.useState(!1);h.useEffect(()=>{!o&&!r&&a()},[o,r,a]);const L=h.useCallback(async()=>{if(!(!y.trim()||!E.trim())){M(!0);try{const _=k.split(`
|
|
3
|
+
`).filter(v=>v.trim()).map(v=>v.trim()),$={};x.split(`
|
|
4
|
+
`).forEach(v=>{const[K,...b]=v.split("=");K?.trim()&&b.length>0&&($[K.trim()]=b.join("=").trim())});const G=await i({name:y.trim(),command:E.trim(),args:_,env:$});G&&c({id:G.id,name:G.name,description:G.command,connected:G.status==="connected"}),S(""),C(""),m(""),g(""),w(!1)}finally{M(!1)}}},[y,E,k,x,i,c]),O={background:t.inputBg,border:`1px solid ${t.border}`,color:t.textPrimary,fontFamily:"'Geist Sans', sans-serif"};return e.jsxs("div",{className:"flex flex-col",children:[e.jsx("div",{className:"mx-4 mt-3 mb-1 px-3 py-2 rounded-lg text-[12px]",style:{background:t.surfaceElevated,color:t.textMuted,border:`1px solid ${t.borderSubtle}`},children:"Configure new connections in the Connection Picker. This tab shows runtime status."}),r&&e.jsxs("div",{className:"px-4 py-8 text-center text-[14px]",style:{color:t.textMuted},children:[e.jsx(te,{size:16,className:"animate-spin mx-auto mb-2"}),"Loading MCP servers..."]}),l&&e.jsx("div",{className:"mx-4 mt-3 px-3 py-2 rounded-lg text-[14px]",style:{background:t.statusErrorBg,color:t.statusError,border:`1px solid ${t.statusError}30`},children:l}),o&&p.map(_=>e.jsx(ro,{server:_},_.id)),o&&p.length===0&&!j&&e.jsx("div",{className:"px-4 py-8 text-center text-[14px]",style:{color:t.textMuted},children:"No MCP servers configured. Add a server below."}),j&&e.jsxs("div",{className:"p-4",style:{borderTop:`1px solid ${t.borderSubtle}`,background:t.surfaceElevated},children:[e.jsx("div",{className:"text-[14px] font-semibold mb-3",style:{color:t.textPrimary,fontFamily:"'Geist Mono', monospace"},children:"Add MCP Server"}),e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{className:"text-[12px] tracking-wider uppercase",style:{color:t.textMuted,fontFamily:"'Geist Mono', monospace"},children:"Name"}),e.jsx("input",{type:"text",value:y,onChange:_=>S(_.target.value),placeholder:"My MCP Server",className:"nodrag nowheel w-full text-[14px] px-3 py-2 rounded-lg outline-none",style:O})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{className:"text-[12px] tracking-wider uppercase",style:{color:t.textMuted,fontFamily:"'Geist Mono', monospace"},children:"Command"}),e.jsx("input",{type:"text",value:E,onChange:_=>C(_.target.value),placeholder:"uv",className:"nodrag nowheel w-full text-[14px] px-3 py-2 rounded-lg outline-none",style:O})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{className:"text-[12px] tracking-wider uppercase",style:{color:t.textMuted,fontFamily:"'Geist Mono', monospace"},children:"Arguments (one per line)"}),e.jsx("textarea",{value:k,onChange:_=>m(_.target.value),placeholder:`tool
|
|
5
|
+
run
|
|
6
|
+
--python
|
|
7
|
+
/path/to/server.py`,className:"nodrag nowheel w-full text-[14px] px-3 py-2 rounded-lg outline-none resize-none",style:{...O,minHeight:"60px"},rows:3})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{className:"text-[12px] tracking-wider uppercase",style:{color:t.textMuted,fontFamily:"'Geist Mono', monospace"},children:"Environment (key=value, one per line)"}),e.jsx("textarea",{value:x,onChange:_=>g(_.target.value),placeholder:`API_KEY=your_key
|
|
8
|
+
DEBUG=1`,className:"nodrag nowheel w-full text-[14px] px-3 py-2 rounded-lg outline-none resize-none",style:{...O,minHeight:"60px"},rows:3})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:L,disabled:R||!y.trim()||!E.trim(),className:"nodrag nowheel flex items-center gap-1.5 text-[14px] px-3 py-1.5 rounded-lg cursor-pointer font-semibold border-none",style:{background:"#FE5000",color:"#fff",opacity:R||!y.trim()||!E.trim()?.6:1},children:[R?e.jsx(te,{size:12,className:"animate-spin"}):e.jsx(oe,{size:12}),"Add Server"]}),e.jsx("button",{type:"button",onClick:()=>w(!1),className:"nodrag nowheel text-[14px] px-3 py-1.5 rounded-lg cursor-pointer border-none",style:{color:t.textMuted,background:t.badgeBg},children:"Cancel"})]})]})]}),o&&!j&&e.jsx("div",{className:"p-4",children:e.jsxs("button",{type:"button",onClick:()=>w(!0),className:"nodrag nowheel flex items-center gap-2 text-[14px] px-3 py-2 rounded-lg cursor-pointer w-full justify-center",style:{border:`1px dashed ${t.border}`,background:"transparent",color:t.textMuted},children:[e.jsx(oe,{size:12}),"Add MCP Server"]})})]})}function io(){const t=q(),s=Re(k=>k.theme),n=Re(k=>k.toggleTheme),[o,r]=h.useState(()=>localStorage.getItem("modular-edge-style")||"smoothstep"),[a,i]=h.useState(()=>localStorage.getItem("modular-grid-snap")!=="false"),[l,c]=h.useState(()=>localStorage.getItem("modular-minimap")!=="false"),[u,d]=h.useState(()=>localStorage.getItem("modular-bg-style")||"dots"),p=(k,m)=>localStorage.setItem(k,m),j=[{id:"system",label:"System",icon:Zs},{id:"light",label:"Light",icon:It},{id:"dark",label:"Dark",icon:At}],w=[{id:"smoothstep",label:"SmoothStep",icon:Xs},{id:"bezier",label:"Bezier",icon:Xe},{id:"step",label:"Step",icon:en}],y=[{id:"dots",label:"Dots"},{id:"lines",label:"Lines"},{id:"none",label:"None"}],S={color:t.textMuted,fontFamily:"'Geist Mono', monospace"},E={borderBottom:`1px solid ${t.borderSubtle}`},C=k=>{(k==="light"?"light":"dark")!==s&&n(),p("modular-theme",k)};return e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3",style:E,children:[e.jsx("span",{className:"text-[12px] tracking-wider uppercase",style:S,children:"Theme"}),e.jsx("div",{className:"flex gap-1",children:j.map(k=>{const m=k.id==="system"&&s==="dark"&&localStorage.getItem("modular-theme")==="system"||k.id===s;return e.jsxs("button",{type:"button",onClick:()=>C(k.id),className:"nodrag nowheel flex items-center gap-1 text-[13px] px-2.5 py-1 rounded-md cursor-pointer border-none",style:{background:m?"#FE500020":t.badgeBg,color:m?"#FE5000":t.textDim},children:[e.jsx(k.icon,{size:11}),k.label]},k.id)})})]}),e.jsxs("div",{className:"flex items-center justify-between px-4 py-3",style:E,children:[e.jsx("span",{className:"text-[12px] tracking-wider uppercase",style:S,children:"Edge Routing"}),e.jsx("div",{className:"flex gap-1",children:w.map(k=>e.jsxs("button",{type:"button",onClick:()=>{r(k.id),p("modular-edge-style",k.id)},className:"nodrag nowheel flex items-center gap-1 text-[13px] px-2.5 py-1 rounded-md cursor-pointer border-none",style:{background:o===k.id?"#FE500020":t.badgeBg,color:o===k.id?"#FE5000":t.textDim},children:[e.jsx(k.icon,{size:11}),k.label]},k.id))})]}),e.jsxs("div",{className:"flex items-center justify-between px-4 py-3",style:E,children:[e.jsx("span",{className:"text-[12px] tracking-wider uppercase",style:S,children:"Grid Snap"}),e.jsx("button",{type:"button",onClick:()=>{const k=!a;i(k),p("modular-grid-snap",String(k))},className:"nodrag nowheel w-9 h-5 rounded-full cursor-pointer border-none relative transition-colors",style:{background:a?"#FE5000":t.badgeBg},children:e.jsx("div",{className:"absolute top-0.5 w-4 h-4 rounded-full transition-transform",style:{background:"#fff",left:a?"18px":"2px",boxShadow:"0 1px 3px rgba(0,0,0,0.3)"}})})]}),e.jsxs("div",{className:"flex items-center justify-between px-4 py-3",style:E,children:[e.jsx("span",{className:"text-[12px] tracking-wider uppercase",style:S,children:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(tn,{size:11})," Minimap"]})}),e.jsx("button",{type:"button",onClick:()=>{const k=!l;c(k),p("modular-minimap",String(k))},className:"nodrag nowheel w-9 h-5 rounded-full cursor-pointer border-none relative transition-colors",style:{background:l?"#FE5000":t.badgeBg},children:e.jsx("div",{className:"absolute top-0.5 w-4 h-4 rounded-full transition-transform",style:{background:"#fff",left:l?"18px":"2px",boxShadow:"0 1px 3px rgba(0,0,0,0.3)"}})})]}),e.jsxs("div",{className:"flex items-center justify-between px-4 py-3",style:E,children:[e.jsx("span",{className:"text-[12px] tracking-wider uppercase",style:S,children:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(sn,{size:11})," Background"]})}),e.jsx("div",{className:"flex gap-1",children:y.map(k=>e.jsx("button",{type:"button",onClick:()=>{d(k.id),p("modular-bg-style",k.id)},className:"nodrag nowheel text-[13px] px-2.5 py-1 rounded-md cursor-pointer border-none",style:{background:u===k.id?"#FE500020":t.badgeBg,color:u===k.id?"#FE5000":t.textDim},children:k.label},k.id))})]})]})}function lo({open:t,onClose:s}){const n=q(),o=I(c=>c.activeSettingsTab),[r,a]=h.useState(o||"providers");h.useEffect(()=>{t&&o&&a(o)},[t,o]);const i=h.useRef(null),l=h.useCallback(c=>{if(c.key!=="Tab"||!i.current)return;const u=i.current.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(u.length===0)return;const d=u[0],p=u[u.length-1];c.shiftKey?document.activeElement===d&&(c.preventDefault(),p.focus()):document.activeElement===p&&(c.preventDefault(),d.focus())},[]);return h.useEffect(()=>{if(!t)return;const c=u=>{u.key==="Escape"&&s()};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[t,s]),t?e.jsxs("div",{className:"fixed inset-0 z-[9999] flex items-center justify-center",onClick:s,children:[e.jsx("div",{className:"absolute inset-0",style:{background:n.isDark?"rgba(0,0,0,0.7)":"rgba(0,0,0,0.35)",backdropFilter:"blur(12px)"}}),e.jsxs("div",{ref:i,role:"dialog","aria-modal":"true","aria-label":"Settings",className:"relative w-[560px] max-h-[80vh] rounded-xl overflow-hidden flex flex-col",style:{background:n.surfaceOpaque,border:`1px solid ${n.border}`,boxShadow:"0 24px 48px rgba(0,0,0,0.4)"},onClick:c=>c.stopPropagation(),onKeyDown:l,children:[e.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 border-b shrink-0",style:{borderColor:n.borderSubtle},children:[e.jsx("span",{className:"text-[14px] tracking-wider uppercase flex-1 font-bold",style:{color:n.textPrimary,fontFamily:"'Geist Mono', monospace"},children:"Settings"}),e.jsx("button",{type:"button",onClick:s,className:"nodrag nowheel cursor-pointer border-none bg-transparent p-1 rounded-md",style:{color:n.textDim},"aria-label":"Close settings",children:e.jsx(ae,{size:14})})]}),e.jsx("div",{className:"flex gap-1 px-4 pt-2 border-b shrink-0 overflow-x-auto",style:{borderColor:n.borderSubtle,scrollbarWidth:"none"},children:so.map(c=>e.jsx("button",{type:"button",onClick:()=>a(c.id),className:"nodrag nowheel text-[13px] tracking-wider uppercase px-3 py-2 cursor-pointer border-none bg-transparent font-semibold",style:{color:r===c.id?"#FE5000":n.textDim,borderBottom:r===c.id?"2px solid #FE5000":"2px solid transparent",fontFamily:"'Geist Mono', monospace",marginBottom:"-1px"},children:c.label},c.id))}),e.jsxs("div",{className:"flex-1 overflow-y-auto",style:{scrollbarWidth:"thin"},children:[r==="providers"&&e.jsx(oo,{}),r==="mcp"&&e.jsx(ao,{}),r==="general"&&e.jsx(io,{})]})]})]}):null}const ts="modular-agent-library-v1";function Je(){return`${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function co(){try{const t=localStorage.getItem(ts);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s:[]}catch{return[]}}function yt(t){try{localStorage.setItem(ts,JSON.stringify(t))}catch{}}const uo=Ne((t,s)=>({agents:[],agentLibrary:co(),sharedFacts:[],edges:[],activeAgentId:null,addAgent:n=>t(o=>({agents:[...o.agents,{...n,factIds:[],knowledgeSourceIds:[],mcpServerIds:[],skillIds:[]}]})),addAgentFromLibrary:n=>{const o=s().agentLibrary.find(a=>a.id===n);if(!o)return;s().addAgent({id:`${o.id}-${Date.now()}`,name:o.name,description:o.description,avatar:o.avatar,version:o.version});const r=s().agents[s().agents.length-1]?.id;r&&s().updateAgent(r,{mcpServerIds:o.mcpServerIds,skillIds:o.skillIds})},addAgentFromBackend:n=>{(async()=>{try{const o=await fetch(`${Z}/agents/${encodeURIComponent(n)}`);if(!o.ok)return;const r=await o.json(),a=r.data??r,i=a.agentMeta??{};s().addAgent({id:`${n}-${Date.now()}`,name:i.name||n,description:i.description||"",avatar:i.avatar||"bot",version:a.version||"1.0.0"});const l=s().agents[s().agents.length-1]?.id;if(!l)return;s().updateAgent(l,{mcpServerIds:(a.mcpServers??[]).map(c=>c.id),skillIds:(a.skills??[]).map(c=>c.id)})}catch{}})()},upsertLibraryAgent:n=>t(o=>{const r=o.agentLibrary.some(a=>a.id===n.id)?o.agentLibrary.map(a=>a.id===n.id?n:a):[...o.agentLibrary,n];return yt(r),{agentLibrary:r}}),removeLibraryAgent:n=>t(o=>{const r=o.agentLibrary.filter(a=>a.id!==n);return yt(r),{agentLibrary:r}}),removeAgent:n=>t(o=>({agents:o.agents.filter(r=>r.id!==n),edges:o.edges.filter(r=>r.fromAgentId!==n&&r.toAgentId!==n)})),updateAgent:(n,o)=>t(r=>({agents:r.agents.map(a=>a.id===n?{...a,...o}:a)})),setActiveAgent:n=>t({activeAgentId:n}),addSharedFact:(n,o,r,a=[])=>{const i=`sf-${Je()}`;return t(l=>({sharedFacts:[...l.sharedFacts,{id:i,content:n,scope:o,originAgentId:r,sharedWith:[],tags:a,timestamp:Date.now()}]})),i},removeSharedFact:n=>t(o=>({sharedFacts:o.sharedFacts.filter(r=>r.id!==n)})),propagateFact:(n,o)=>t(r=>({sharedFacts:r.sharedFacts.map(a=>a.id===n?{...a,sharedWith:[...new Set([...a.sharedWith,...o])]}:a),edges:[...r.edges,...o.filter(a=>!r.edges.some(i=>i.type==="fact_propagation"&&i.fromAgentId===r.sharedFacts.find(l=>l.id===n)?.originAgentId&&i.toAgentId===a)).map(a=>({id:`edge-${Je()}`,fromAgentId:r.sharedFacts.find(i=>i.id===n)?.originAgentId||"",toAgentId:a,type:"fact_propagation",label:"shared fact"}))]})),markFactPromoted:(n,o,r)=>t(a=>({sharedFacts:a.sharedFacts.map(i=>i.id===n?{...i,promotedTo:{agentId:o,target:r,at:Date.now()}}:i)})),addEdge:n=>t(o=>({edges:[...o.edges,{...n,id:`edge-${Je()}`}]})),removeEdge:n=>t(o=>({edges:o.edges.filter(r=>r.id!==n)})),getAgentFacts:n=>s().sharedFacts.filter(o=>o.originAgentId===n),getSharedFactsForAgent:n=>s().sharedFacts.filter(o=>o.scope==="global"||o.originAgentId===n||o.sharedWith.includes(n))}));function po(t){return{...t}}const mo={"claude-opus-4":"claude-opus-4","claude-sonnet-4":"claude-sonnet-4","claude-haiku-3.5":"claude-haiku-3.5","gpt-4o":"gpt-4o","gpt-4.1":"gpt-4.1"};function ss(t,s){if(!t||!t.persona&&!t.objectives.primary&&!t.constraints.customConstraints)return s||"You are an analyst combining multiple knowledge sources to produce structured output.";const n=[];t.persona&&n.push(`You are ${t.persona}.`),t.tone!=="neutral"&&n.push(`Use a ${t.tone} tone.`),t.objectives.primary&&n.push(`
|
|
9
|
+
Primary objective: ${t.objectives.primary}`),t.objectives.successCriteria.length>0&&n.push("Success criteria: "+t.objectives.successCriteria.join("; "));const o=[];return t.constraints.neverMakeUp&&o.push("Never make up information"),t.constraints.askBeforeActions&&o.push("Ask before taking actions"),t.constraints.stayInScope&&o.push(`Stay in scope${t.constraints.scopeDefinition?": "+t.constraints.scopeDefinition:""}`),t.constraints.useOnlyTools&&o.push("Only use provided tools"),t.constraints.limitWords&&o.push(`Keep responses under ${t.constraints.wordLimit} words`),t.constraints.customConstraints&&o.push(t.constraints.customConstraints),o.length>0&&n.push(`
|
|
10
|
+
Constraints:
|
|
11
|
+
`+o.map(r=>`- ${r}`).join(`
|
|
12
|
+
`)),s&&n.push(`
|
|
13
|
+
`+s),n.join(`
|
|
14
|
+
`)}function be(t){const s=t.channels.filter(E=>E.enabled),n=mo[t.selectedModel]??t.selectedModel,o=t.agentMeta.name||wo(t.prompt,s),r=t.agentMeta.description||vo(t.prompt,s),a=t.skills.filter(E=>E.enabled&&E.added),i=t.mcpServers.filter(E=>E.enabled&&E.added),l=a.map(E=>E.name),c=i.map(E=>({name:E.name,transport:"stdio",command:`npx @${E.name.toLowerCase().replace(/\s+/g,"")}hq/mcp`})),u=s.map(E=>E.path),d=t.outputFormats.length>0?t.outputFormats:[t.outputFormat],p=[],j=ss(t.instructionState,t.prompt);p.push(j);const w=t.agentConfig?.temperature??.7,y=t.agentConfig?.planningMode??"single-shot",S=[...(t.connectors??[]).filter(E=>E.enabled).map(E=>({service:E.service,direction:E.direction,config:E.config,type:"connector"})),...(t.mcpServers??[]).filter(E=>E.enabled!==!1).map(E=>({service:E.name||E.id,type:"mcp",id:E.id}))];return{name:o,description:r,model:n,icon:t.agentMeta.icon||"brain",category:t.agentMeta.category||"general",temperature:w,planningMode:y,tools:l,mcp_servers:c,reads:u,output_format:d,token_budget:t.tokenBudget,prompt:t.prompt,system:p.join(`
|
|
15
|
+
|
|
16
|
+
`),connections:S}}function ne(t){return t.includes(`
|
|
17
|
+
`)||t.includes(":")||t.includes("#")||t.includes('"')?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:t}function fo(t){const s=["---"];if(s.push(`name: ${ne(t.name)}`),s.push(`description: ${ne(t.description)}`),s.push(`model: ${t.model}`),s.push(`temperature: ${t.temperature}`),s.push(`icon: ${t.icon}`),s.push(`category: ${t.category}`),t.tools.length>0){s.push("tools:");for(const n of t.tools)s.push(` - ${n}`)}if(t.mcp_servers.length>0){s.push("mcp_servers:");for(const n of t.mcp_servers)s.push(` - name: ${ne(n.name)}`),s.push(` transport: ${n.transport}`),n.command&&s.push(` command: ${ne(n.command)}`)}if(t.reads.length>0){s.push("reads:");for(const n of t.reads)s.push(` - ${ne(n)}`)}if(t.output_format.length>0){s.push("output_format:");for(const n of t.output_format)s.push(` - ${n}`)}return s.push(`token_budget: ${t.token_budget}`),s.push("---"),s.join(`
|
|
18
|
+
`)}function ho(t,s){const n=s.channels.filter(l=>l.enabled),o=s.instructionState,r=s.workflowSteps,a=[""];if(o?.persona&&(a.push("## Persona"),a.push(o.persona),o.tone!=="neutral"&&a.push(`
|
|
19
|
+
Tone: ${o.tone}`),o.expertise!==3&&a.push(`Expertise level: ${o.expertise}/5`),a.push("")),a.push("## Role"),a.push(t.system),a.push(""),o?.objectives.primary){if(a.push("## Objectives"),a.push(`**Primary:** ${o.objectives.primary}`),o.objectives.successCriteria.length>0){a.push(`
|
|
20
|
+
**Success Criteria:**`);for(const l of o.objectives.successCriteria)a.push(`- ${l}`)}if(o.objectives.failureModes.length>0){a.push(`
|
|
21
|
+
**Failure Modes:**`);for(const l of o.objectives.failureModes)a.push(`- ${l}`)}a.push("")}if(o){const l=[];if(o.constraints.neverMakeUp&&l.push("Never make up information"),o.constraints.askBeforeActions&&l.push("Ask before taking actions"),o.constraints.stayInScope&&l.push(`Stay in scope${o.constraints.scopeDefinition?": "+o.constraints.scopeDefinition:""}`),o.constraints.useOnlyTools&&l.push("Only use provided tools"),o.constraints.limitWords&&l.push(`Keep responses under ${o.constraints.wordLimit} words`),o.constraints.customConstraints&&l.push(o.constraints.customConstraints),l.length>0){a.push("## Constraints");for(const c of l)a.push(`- ${c}`);a.push("")}}if(t.prompt&&(a.push("## Default Prompt"),a.push(t.prompt),a.push("")),a.push("## Workflow"),r&&r.length>0)r.forEach((l,c)=>{const u=`${c+1}. ${l.label}`,d=l.action?` — ${l.action}`:"",p=l.condition!=="always"&&l.conditionText?` (${l.condition} ${l.conditionText})`:"";a.push(`${u}${d}${p}`)});else if(n.length>0){a.push("1. Read all knowledge sources");const l=new Map;for(const u of n){const d=u.knowledgeType;l.has(d)||l.set(d,[]),l.get(d).push(u)}let c=2;for(const[u,d]of l){const p=bs[u];if(p){const j=d.map(w=>w.name).join(", ");a.push(`${c}. Process ${p.label.toLowerCase()} sources: ${j}`),c++}}a.push(`${c}. Synthesize findings`),a.push(`${c+1}. Generate output`)}else a.push("1. Analyze the provided context"),a.push("2. Identify patterns and key insights"),a.push("3. Synthesize findings"),a.push("4. Generate output");a.push("");const i=s.outputFormats.map(l=>ks.find(u=>u.id===l)?.label??l);if(a.push("## Output Format"),a.push(i.length>0?i.join(", "):"Markdown"),a.push(""),s.knowledgeContent&&s.knowledgeContent.length>0){a.push("## Knowledge Sources");for(const l of s.knowledgeContent)a.push(`- **${l.name}** (${l.knowledgeType}, ${l.tokens} tokens) — \`${l.path}\``),s.portable&&l.content&&(a.push(""),a.push(" ```"),a.push(l.content.split(`
|
|
22
|
+
`).map(c=>" "+c).join(`
|
|
23
|
+
`)),a.push(" ```"),a.push(""));a.push("")}if(s.facts&&s.facts.length>0){a.push("## Extracted Insights");for(const l of s.facts)a.push(`- ${l.text}`);a.push("")}if(s.performanceSummary){const l=s.performanceSummary;a.push("## Agent Performance Summary"),a.push(`- Knowledge: ${l.knowledgeSources} source${l.knowledgeSources!==1?"s":""}, ${l.knowledgeTokens.toLocaleString()} tokens optimized context`),a.push(`- Lessons: ${l.lessonsCount} learned behavior${l.lessonsCount!==1?"s":""} (avg confidence ${Math.round(l.avgConfidence*100)}%)`),l.avgCostPerRun>0&&a.push(`- Cost: Est. $${l.avgCostPerRun.toFixed(4)}/query (${l.topModel}, ${Math.round(l.cacheHitPct*100)}% cached)`),a.push(`- Quality: ${l.qualityScore!==null?`${l.qualityScore}/100`:"N/A"} (qualified on ${l.testCasesCount} test case${l.testCasesCount!==1?"s":""})`),a.push("")}return a.join(`
|
|
24
|
+
`)}function ns(t){const s=be(t),n=fo(s),o=ho(s,t);return n+`
|
|
25
|
+
`+o}function os(t){const s=be(t),n=[];if(n.push(`name: ${ne(s.name)}`),n.push(`model: ${s.model}`),s.tools.length>0){n.push("tools:");for(const r of s.tools)n.push(` - ${r}`)}if(s.mcp_servers.length>0){n.push("mcp:");for(const r of s.mcp_servers)n.push(` ${r.name.toLowerCase().replace(/\s+/g,"-")}:`),r.command&&n.push(` command: ${ne(r.command)}`)}if(s.reads.length>0){n.push("context_files:");for(const r of s.reads)n.push(` - ${ne(r)}`)}const o=ss(t.instructionState,t.prompt);if(o){n.push("instructions: |");for(const r of o.split(`
|
|
26
|
+
`))n.push(` ${r}`)}return n.join(`
|
|
27
|
+
`)+`
|
|
28
|
+
`}function go(t){const s=be(t),n={name:s.name,model:s.model,instructions:s.system,tools:s.tools,mcp_servers:s.mcp_servers.map(o=>({name:o.name,transport:o.transport})),context_files:s.reads};return JSON.stringify(n,null,2)}function xo(t){const s=be(t),n={};for(const r of s.mcp_servers)n[r.name.toLowerCase().replace(/\s+/g,"-")]={command:r.command||""};const o={template:s.name,agent:"claude-code",context_files:s.reads,mcp_config:n,tools:s.tools,output_format:s.output_format};return JSON.stringify(o,null,2)}function yo(t){const s=be(t),n=s.name.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,""),o=[];if(o.push("agents:"),o.push(` ${n}:`),o.push(` model: ${s.model}`),o.push(` temperature: ${s.temperature}`),s.tools.length>0){o.push(" skills:");for(const r of s.tools)o.push(` - ${r}`)}if(s.mcp_servers.length>0){o.push(" mcp:"),o.push(" servers:");for(const r of s.mcp_servers){const a=r.name.toLowerCase().replace(/\s+/g,"-");o.push(` ${a}:`),r.command&&o.push(` command: ${ne(r.command)}`)}}if(s.reads.length>0){o.push(" context:");for(const r of s.reads)o.push(` - ${ne(r)}`)}return o.join(`
|
|
29
|
+
`)+`
|
|
30
|
+
`}function bo(t){const s=be(t),n=t.outputTemplateConfig?Object.fromEntries(Object.entries(t.outputTemplateConfig).map(([a,i])=>[a,po(i)])):void 0,o=t.knowledgeContent?t.knowledgeContent.map(a=>({sourceId:a.sourceId,name:a.name,path:a.path,knowledgeType:a.knowledgeType,depth:a.depth,tokens:a.tokens,...t.portable&&a.content?{content:a.content}:{}})):s.reads.map(a=>({path:a})),r={modular_version:"1.0",agent:{name:s.name,description:s.description,model:s.model,temperature:s.temperature,system_prompt:s.system,planning_mode:s.planningMode,skills:s.tools,mcp_servers:s.mcp_servers,output_formats:s.output_format,token_budget:s.token_budget,connections:s.connections,...t.instructionState?{instructionState:t.instructionState}:{},...t.workflowSteps&&t.workflowSteps.length>0?{workflowSteps:t.workflowSteps}:{},...n&&Object.keys(n).length>0?{output:{templates:n}}:{}},knowledge:o};return t.pipelineSnapshot&&(r.pipeline_snapshot=t.pipelineSnapshot),t.facts&&t.facts.length>0&&(r.facts=t.facts),t.performanceSummary&&(r.performanceSummary=t.performanceSummary),JSON.stringify(r,null,2)}function ya(t){return ns(t)}function ba(t){return os(t)}function rs(t,s){switch(t){case"claude":return ns(s);case"amp":return os(s);case"codex":return go(s);case"vibe-kanban":return xo(s);case"openclaw":return yo(s);case"generic":return bo(s)}}const as={claude:{name:"Claude Code",ext:".md",mime:"text/markdown"},amp:{name:"Amp",ext:".yaml",mime:"text/yaml"},codex:{name:"Codex",ext:".json",mime:"application/json"},"vibe-kanban":{name:"Vibe Kanban",ext:".json",mime:"application/json"},openclaw:{name:"OpenClaw",ext:".yaml",mime:"text/yaml"},generic:{name:"Generic JSON",ext:".json",mime:"application/json"}};function is(t,s,n=".md"){const o={".md":"text/markdown",".json":"application/json",".yaml":"text/yaml"},r=new Blob([t],{type:o[n]||"text/plain"}),a=URL.createObjectURL(r),i=document.createElement("a");i.href=a,i.download=`${s}${n}`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(a)}function ko(t){const s=(t.agentMeta.name||"modular-agent").toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,""),n=["claude","amp","codex","vibe-kanban","openclaw","generic"];for(const o of n){const r=rs(o,t),a=as[o],i=o==="claude"?s:`${s}-${o}`;is(r,i,a.ext)}}function wo(t,s){if(t){const n=t.split(/\s+/).slice(0,4).join("-").toLowerCase().replace(/[^a-z0-9-]/g,"");if(n.length>3)return n}return s.length>0?s[0].name.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,""):"modular-agent"}function vo(t,s){return t&&t.length>10?t.length>80?t.slice(0,77)+"...":t:`Analysis using ${s.length} sources via Modular`}function So(){const t=I.getState();Q.getState();const s={version:"1.0",kind:"agent",identity:{name:t.agentMeta.name||"modular-agent",display_name:t.agentMeta.name||void 0,description:t.agentMeta.description||void 0,avatar:t.agentMeta.avatar||void 0,author:"Modular Studio",tags:t.agentMeta.tags?.length>0?t.agentMeta.tags:void 0,agent_version:"1.0.0"},instructions:{},context:{}},n={};t.instructionState.persona&&(n.persona=t.instructionState.persona),t.instructionState.tone!=="neutral"&&(n.tone=t.instructionState.tone),t.instructionState.expertise!==3&&(n.expertise=t.instructionState.expertise);const o=[];if(t.instructionState.constraints.neverMakeUp&&o.push("Never fabricate information or make up facts"),t.instructionState.constraints.askBeforeActions&&o.push("Ask for permission before taking significant actions"),t.instructionState.constraints.stayInScope&&o.push(`Stay within defined scope: ${t.instructionState.constraints.scopeDefinition||"as specified"}`),t.instructionState.constraints.useOnlyTools&&o.push("Only use explicitly provided tools and capabilities"),t.instructionState.constraints.limitWords&&o.push(`Keep responses under ${t.instructionState.constraints.wordLimit} words`),t.instructionState.constraints.customConstraints&&o.push(t.instructionState.constraints.customConstraints),o.length>0&&(n.constraints=o),t.instructionState.objectives.primary){const c={primary:t.instructionState.objectives.primary};t.instructionState.objectives.successCriteria.length>0&&(c.success_criteria=t.instructionState.objectives.successCriteria),t.instructionState.objectives.failureModes.length>0&&(c.failure_modes=t.instructionState.objectives.failureModes),n.objectives=c}t.instructionState.constraints.scopeDefinition&&(n.scope=t.instructionState.constraints.scopeDefinition),s.instructions=n;const r={},a=t.channels.filter(c=>c.enabled);a.length>0&&(r.knowledge=a.map(c=>({type:"file",ref:c.path||c.name,knowledge_type:c.knowledgeType,depth:c.depth})));const i=t.skills.filter(c=>c.enabled);i.length>0&&(r.skills=i.map(c=>({ref:c.name,source:"registry"})));const l=t.mcpServers.filter(c=>c.enabled);return l.length>0&&(r.mcp_servers=l.map(c=>({name:c.name,description:c.description,transport:"stdio",command:void 0,env:void 0}))),s.context=r,t.workflowSteps.length>0&&(s.workflow={steps:t.workflowSteps.map(c=>({id:c.id,action:c.action,tool:c.tool||void 0,condition:c.condition!=="always"?c.condition:void 0}))}),Pe(s)}function Pe(t,s=0){const n=" ".repeat(s);return Array.isArray(t)?t.map(o=>`${n}- ${Pe(o,0).trim()}`).join(`
|
|
31
|
+
`):typeof t=="object"&&t!==null?Object.entries(t).filter(([,o])=>o!=null).map(([o,r])=>{if(Array.isArray(r))return r.length===0?null:`${n}${o}:
|
|
32
|
+
${Pe(r,s+1)}`;if(typeof r=="object")return`${n}${o}:
|
|
33
|
+
${Pe(r,s+1)}`;{const a=typeof r=="string"&&(r.includes(`
|
|
34
|
+
`)||r.includes(":")||r.includes("#"))?`"${r.replace(/"/g,'\\"')}"`:String(r);return`${n}${o}: ${a}`}}).filter(Boolean).join(`
|
|
35
|
+
`):String(t)}const bt=[{id:"brain",Icon:st},{id:"code",Icon:Wt},{id:"search",Icon:ye},{id:"bar-chart-3",Icon:Gt},{id:"pen-tool",Icon:zt},{id:"file-text",Icon:Be},{id:"globe",Icon:Lt},{id:"layers",Icon:an},{id:"zap",Icon:he},{id:"database",Icon:nt},{id:"shield",Icon:Dt},{id:"settings",Icon:tt},{id:"sparkles",Icon:We},{id:"target",Icon:Rt},{id:"book-open",Icon:Bt},{id:"lightbulb",Icon:Ht},{id:"terminal",Icon:je},{id:"box",Icon:ot},{id:"layout-grid",Icon:Ut},{id:"cpu",Icon:Ge}],jo=["coding","research","analysis","writing","data","design","domain-specific","general"],kt=[{id:"claude",name:"Claude Code",ext:".md",Icon:je},{id:"amp",name:"Amp",ext:".yaml",Icon:he},{id:"codex",name:"Codex",ext:".json",Icon:Ge},{id:"vibe-kanban",name:"Vibe Kanban",ext:".json",Icon:Ut},{id:"openclaw",name:"OpenClaw",ext:".yaml",Icon:Yt},{id:"generic",name:"Generic JSON",ext:".json",Icon:ot}];function Co(){const t=I(f=>f.showSaveModal),s=I(f=>f.setShowSaveModal),n=I(f=>f.agentMeta),o=I(f=>f.setAgentMeta),r=I(f=>f.channels),a=I(f=>f.selectedModel),i=I(f=>f.outputFormat),l=I(f=>f.outputFormats),c=I(f=>f.prompt),u=I(f=>f.tokenBudget),d=I(f=>f.mcpServers),p=I(f=>f.skills),j=I(f=>f.exportTarget),w=I(f=>f.setExportTarget),y=I(f=>f.agentConfig),S=I(f=>f.connectors),E=I(f=>f.instructionState),C=I(f=>f.workflowSteps),k=uo(f=>f.upsertLibraryAgent),[m,x]=h.useState(!1),[g,R]=h.useState(!1),[M,L]=h.useState(!0),[O,_]=h.useState(null),$=h.useRef(null),G=h.useRef(null),v=q(),K=h.useCallback(f=>{if(f.key!=="Tab"||!G.current)return;const B=G.current.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(B.length===0)return;const H=B[0],Y=B[B.length-1];f.shiftKey?document.activeElement===H&&(f.preventDefault(),Y.focus()):document.activeElement===Y&&(f.preventDefault(),H.focus())},[]);h.useEffect(()=>{t?(R(!0),setTimeout(()=>$.current?.focus(),100)):R(!1)},[t]),h.useEffect(()=>{if(!t)return;const f=B=>{B.key==="Escape"&&s(!1)};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[t,s]);const b=h.useMemo(()=>({channels:r,selectedModel:a,outputFormat:i,outputFormats:l,prompt:c,tokenBudget:u,mcpServers:d,skills:p,agentMeta:n,agentConfig:y,connectors:S,instructionState:E,workflowSteps:C}),[r,a,i,l,c,u,d,p,n,y,S,E,C]),P=h.useMemo(()=>rs(j,b),[b,j]),T=f=>{L(!1),w(f),setTimeout(()=>L(!0),30)},F=()=>{const f=n.name||"modular-agent",B=f.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"");k({id:B,name:f,description:n.description||"Saved from builder",avatar:n.avatar||"bot",version:"1.0.0",mcpServerIds:d.filter(J=>J.added).map(J=>J.id),skillIds:p.filter(J=>J.added).map(J=>J.id)});const H=ws();_(null),fetch(`${Z}/agents/${encodeURIComponent(B)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(H)}).then(J=>{J.ok||_(`Failed to save agent to library (${J.status}). File downloaded as fallback.`)}).catch(()=>{_("Failed to save agent to library — server unreachable. File downloaded as fallback.")});const Y=as[j];is(P,B,Y.ext)},z=async()=>{await navigator.clipboard.writeText(P),x(!0),setTimeout(()=>x(!1),2e3)},A=()=>{ko(b)},N=()=>{const f=So(),H=(n.name||"modular-agent").toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,""),Y=new Blob([f],{type:"text/yaml;charset=utf-8"}),J=URL.createObjectURL(Y),de=document.createElement("a");de.href=J,de.download=`${H}.yaml`,document.body.appendChild(de),de.click(),document.body.removeChild(de),URL.revokeObjectURL(J)};if(!t)return null;const W=bt.find(f=>f.id===n.icon),U=kt.find(f=>f.id===j);return e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",onClick:()=>s(!1),children:[e.jsx("div",{className:"absolute inset-0",style:{background:"rgba(0,0,0,0.7)",backdropFilter:"blur(4px)",opacity:g?1:0,transition:"opacity 0.15s ease"}}),e.jsxs("div",{ref:G,role:"dialog","aria-modal":"true","aria-label":"Save as agent",className:"relative flex flex-col rounded-xl overflow-hidden",style:{width:880,maxHeight:"85vh",background:v.surface,border:`1px solid ${v.border}`,boxShadow:"0 24px 48px rgba(0,0,0,0.4)",opacity:g?1:0,transform:g?"scale(1)":"scale(0.97)",transition:"opacity 0.15s ease, transform 0.15s ease"},onClick:f=>f.stopPropagation(),onKeyDown:K,children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3.5",style:{borderBottom:`1px solid ${v.borderSubtle}`},children:[e.jsx("span",{className:"text-[14px] font-bold tracking-[3px] uppercase",style:{fontFamily:"'Geist Mono', monospace",color:v.textPrimary},children:"SAVE AS AGENT"}),e.jsx("button",{type:"button",onClick:()=>s(!1),className:"p-1 rounded-md cursor-pointer border-none",style:{background:"transparent",color:v.textMuted},"aria-label":"Close",children:e.jsx(ae,{size:16})})]}),e.jsx("div",{className:"flex gap-2 px-5 py-3",style:{borderBottom:`1px solid ${v.borderSubtle}`},children:kt.map(f=>{const B=j===f.id;return e.jsxs("button",{type:"button",onClick:()=>T(f.id),className:"flex flex-col items-center gap-1 rounded-lg cursor-pointer border-none",style:{width:80,padding:"8px 4px",background:B?"#FE500012":"transparent",border:B?"1.5px solid #FE5000":`1.5px solid ${v.borderSubtle}`,transition:"all 0.12s ease"},children:[e.jsx(f.Icon,{size:18,style:{color:B?"#FE5000":v.textMuted}}),e.jsx("span",{className:"text-[12px] font-semibold leading-tight text-center",style:{fontFamily:"'Geist Mono', monospace",color:B?"#FE5000":v.textSecondary},children:f.name}),e.jsx("span",{className:"text-[13px] px-1.5 py-0.5 rounded",style:{fontFamily:"'Geist Mono', monospace",background:B?"#FE500020":v.badgeBg,color:B?"#FE5000":v.textDim},children:f.ext})]},f.id)})}),e.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[e.jsxs("div",{className:"flex flex-col",style:{width:340,borderRight:`1px solid ${v.borderSubtle}`},children:[e.jsxs("div",{className:"flex-1 overflow-y-auto p-5 flex flex-col gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"text-[13px] font-semibold uppercase tracking-wider",style:{color:v.textMuted,fontFamily:"'Geist Mono', monospace"},children:"Agent Name"}),e.jsx("input",{ref:$,type:"text",value:n.name,onChange:f=>o({name:f.target.value}),placeholder:"my-analysis-agent",className:"w-full outline-none text-[17px] rounded-lg px-3 py-2 nodrag",style:{background:v.inputBg,border:`1px solid ${v.border}`,color:v.textPrimary,fontFamily:"'Geist Sans', sans-serif"}})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"text-[13px] font-semibold uppercase tracking-wider",style:{color:v.textMuted,fontFamily:"'Geist Mono', monospace"},children:"Description"}),e.jsx("textarea",{value:n.description,onChange:f=>o({description:f.target.value}),placeholder:"Deep research and synthesis agent...",className:"w-full outline-none text-[17px] rounded-lg px-3 py-2 resize-none",rows:3,style:{background:v.inputBg,border:`1px solid ${v.border}`,color:v.textPrimary,fontFamily:"'Geist Sans', sans-serif",lineHeight:1.5}})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"text-[13px] font-semibold uppercase tracking-wider",style:{color:v.textMuted,fontFamily:"'Geist Mono', monospace"},children:"Icon"}),e.jsx("div",{className:"grid grid-cols-10 gap-1",children:bt.map(({id:f,Icon:B})=>e.jsx("button",{type:"button",onClick:()=>o({icon:f}),className:"flex items-center justify-center w-7 h-7 rounded-md cursor-pointer border-none",style:{background:n.icon===f?"#FE500020":"transparent",border:n.icon===f?"1px solid #FE500040":"1px solid transparent",color:n.icon===f?"#FE5000":v.textMuted,transition:"all 0.1s ease"},children:e.jsx(B,{size:14})},f))})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"text-[13px] font-semibold uppercase tracking-wider",style:{color:v.textMuted,fontFamily:"'Geist Mono', monospace"},children:"Category"}),e.jsx("select",{value:n.category,onChange:f=>o({category:f.target.value}),className:"w-full outline-none text-[17px] rounded-lg px-3 py-2 cursor-pointer",style:{background:v.inputBg,border:`1px solid ${v.border}`,color:v.textPrimary,fontFamily:"'Geist Sans', sans-serif"},children:jo.map(f=>e.jsx("option",{value:f,children:f.charAt(0).toUpperCase()+f.slice(1).replace("-"," ")},f))})]})]}),O&&e.jsx("div",{className:"mx-5 mt-3 px-3 py-2 rounded-lg text-[12px]",role:"alert",style:{background:"rgba(220,38,38,0.12)",border:"1px solid rgba(220,38,38,0.4)",color:"#f87171"},children:O}),e.jsxs("div",{className:"flex flex-col gap-2 px-5 py-4",style:{borderTop:`1px solid ${v.borderSubtle}`},children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("button",{type:"button",onClick:F,className:"flex items-center justify-center gap-1.5 flex-1 py-2 rounded-lg text-[14px] font-semibold tracking-wider uppercase cursor-pointer border-none",style:{background:"#FE5000",color:"#fff",boxShadow:"0 0 8px rgba(254,80,0,0.25)"},children:[e.jsx(at,{size:13}),"Download"]}),e.jsxs("button",{type:"button",onClick:z,className:"flex items-center justify-center gap-1.5 flex-1 py-2 rounded-lg text-[14px] font-semibold tracking-wider uppercase cursor-pointer",style:{background:"transparent",border:`1px solid ${v.border}`,color:m?v.statusSuccess:v.textSecondary,transition:"color 0.15s ease"},children:[m?e.jsx(ee,{size:13}):e.jsx(Jt,{size:13}),m?"Copied":"Copy"]})]}),e.jsxs("button",{type:"button",onClick:A,className:"flex items-center justify-center gap-1.5 w-full py-2 rounded-lg text-[14px] font-semibold tracking-wider uppercase cursor-pointer",style:{background:"transparent",border:`1px solid ${v.borderSubtle}`,color:v.textMuted},children:[e.jsx(Yt,{size:13}),"Export All Targets"]}),e.jsxs("button",{type:"button",onClick:N,className:"flex items-center justify-center gap-1.5 w-full py-2 rounded-lg text-[14px] font-semibold tracking-wider uppercase cursor-pointer",style:{background:"transparent",border:`1px solid ${v.borderSubtle}`,color:v.textMuted},children:[e.jsx(Be,{size:13}),"Export as YAML"]})]})]}),e.jsxs("div",{className:"flex flex-col flex-1",style:{background:v.isDark?"#0d0d10":"#f5f5f8"},children:[e.jsxs("div",{className:"flex items-center justify-between px-5 py-3",style:{borderBottom:`1px solid ${v.borderSubtle}`},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[W&&e.jsx(W.Icon,{size:14,style:{color:"#FE5000"}}),e.jsx("span",{className:"text-[14px] font-bold tracking-[2px] uppercase",style:{fontFamily:"'Geist Mono', monospace",color:v.textMuted},children:"Preview"}),e.jsxs("span",{className:"text-[13px] px-1.5 py-0.5 rounded",style:{fontFamily:"'Geist Mono', monospace",background:"#FE500018",color:"#FE5000"},children:[U.name," ",U.ext]})]}),e.jsxs("span",{className:"text-[12px]",style:{fontFamily:"'Geist Mono', monospace",color:v.textDim},children:[P.split(`
|
|
36
|
+
`).length," lines"]})]}),e.jsx("div",{className:"flex-1 overflow-auto p-4",style:{opacity:M?1:0,transition:"opacity 0.12s ease"},children:e.jsx("pre",{className:"text-[14px] leading-relaxed whitespace-pre-wrap break-all m-0",style:{fontFamily:"'Geist Mono', monospace",color:v.textSecondary},children:P.split(`
|
|
37
|
+
`).map((f,B)=>e.jsxs("div",{className:"flex",children:[e.jsx("span",{className:"inline-block text-right select-none shrink-0",style:{width:32,color:v.textFaint,marginRight:12},children:B+1}),e.jsx("span",{style:{color:No(f,j,v)},children:f||" "})]},B))})})]})]})]})]})}function No(t,s,n){return t.trim()?s==="codex"||s==="vibe-kanban"||s==="generic"?/^\s*"\w[\w_-]*"\s*:/.test(t)?"#67d4e8":/:\s*"[^"]*"\s*,?$/.test(t)?"#a8d4a0":/:\s*(\d+\.?\d*|true|false|null)\s*,?$/.test(t)?"#d4a86a":n.textSecondary:t==="---"?"#FE5000":t.startsWith("##")||t.startsWith("# ")?n.textPrimary:/^\s*#/.test(t)?n.isDark?"#666":"#999":/^\s*\w[\w_-]*\s*:/.test(t)?"#67d4e8":/^\s+-\s/.test(t)||/^\d+\./.test(t)?n.textSecondary:n.textMuted:n.textMuted}const Ve=h.forwardRef(function({variant:s="secondary",size:n="md",icon:o,iconRight:r,loading:a,children:i,className:l="",style:c,disabled:u,...d},p){const j=q(),w={sm:28,md:32},y={sm:"0 8px",md:"0 14px"},S={sm:12,md:13},C={primary:{bg:"#FE5000",color:"#fff",border:"transparent",hoverBg:"#e54700"},secondary:{bg:j.surfaceElevated,color:j.textSecondary,border:j.border,hoverBg:j.isDark?"#2a2a30":"#eee"},ghost:{bg:"transparent",color:j.textSecondary,border:"transparent",hoverBg:j.isDark?"#ffffff08":"#00000008"},danger:{bg:j.statusErrorBg,color:j.statusError,border:"transparent",hoverBg:j.isDark?"#ff4d4f20":"#ff4d4f15"}}[s];return e.jsxs("button",{ref:p,type:"button",disabled:u||a,className:`ds-btn flex items-center justify-center gap-1.5 rounded-lg cursor-pointer border font-semibold tracking-wide uppercase nodrag ${l}`,style:{height:w[n],padding:y[n],fontSize:S[n],fontFamily:"'Geist Mono', monospace",background:C.bg,color:C.color,borderColor:C.border,opacity:u?.5:1,cursor:u?"not-allowed":"pointer",transition:"background 0.15s, opacity 0.15s",...c},onMouseEnter:k=>{u||(k.currentTarget.style.background=C.hoverBg)},onMouseLeave:k=>{k.currentTarget.style.background=C.bg},...d,children:[a?e.jsx("span",{className:"animate-spin text-[12px]",children:"⟳"}):o,i,r]})});function wt({icon:t,title:s,subtitle:n,action:o,className:r=""}){const a=q();return e.jsxs("div",{className:`flex flex-col items-center justify-center text-center py-8 px-4 ${r}`,children:[e.jsx("div",{className:"mb-3 opacity-30",style:{color:a.textFaint},children:t}),e.jsx("h3",{className:"text-[17px] font-semibold mb-1",style:{color:a.textPrimary,fontFamily:"'Geist Mono', monospace",fontSize:13},children:s}),n&&e.jsx("p",{className:"text-[14px] max-w-xs mb-4",style:{color:a.textMuted,fontSize:12,lineHeight:1.4},children:n}),o&&e.jsx("div",{children:o})]})}function ls({size:t="md",className:s=""}){const n=q(),o={sm:12,md:16,lg:24};return e.jsx("div",{className:`animate-spin rounded-full border-2 border-solid ${s}`,style:{width:o[t],height:o[t],borderColor:`${n.border} ${n.border} #FE5000 ${n.border}`},role:"status","aria-label":"Loading"})}function Eo({open:t,onClose:s,title:n,children:o,footer:r,width:a=520}){const i=q(),l=h.useRef(null),c=n?`modal-title-${n.toLowerCase().replace(/\s+/g,"-")}`:void 0;return h.useEffect(()=>{if(!t)return;const u=d=>{d.key==="Escape"&&s()};return document.addEventListener("keydown",u),()=>document.removeEventListener("keydown",u)},[t,s]),h.useEffect(()=>{t&&l.current?.focus()},[t]),t?ze.createPortal(e.jsxs("div",{className:"fixed inset-0 z-[200] flex items-center justify-center",onClick:s,children:[e.jsx("div",{className:"absolute inset-0",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(4px)"}}),e.jsxs("div",{ref:l,role:"dialog","aria-modal":"true","aria-labelledby":c,tabIndex:-1,onClick:u=>u.stopPropagation(),className:"relative flex flex-col rounded-xl overflow-hidden outline-none",style:{width:a,maxWidth:"90vw",maxHeight:"80vh",background:i.surfaceOpaque,border:`1px solid ${i.border}`,boxShadow:`0 16px 48px ${i.isDark?"rgba(0,0,0,0.6)":"rgba(0,0,0,0.15)"}`},children:[n&&e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 shrink-0",style:{borderBottom:`1px solid ${i.borderSubtle}`},children:[e.jsx("span",{id:c,className:"text-[17px] font-bold",style:{fontFamily:"'Geist Mono', monospace",color:i.textPrimary},children:n}),e.jsx("button",{type:"button",onClick:s,"aria-label":"Close dialog",className:"flex items-center justify-center w-7 h-7 rounded-md cursor-pointer border-none bg-transparent",style:{color:i.textDim},children:e.jsx(ae,{size:14,"aria-hidden":"true"})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:o}),r&&e.jsx("div",{className:"flex items-center justify-end gap-2 px-4 py-3 shrink-0",style:{borderTop:`1px solid ${i.borderSubtle}`},children:r})]})]}),document.body):null}function To({options:t,value:s,onChange:n,label:o,placeholder:r="Select...",size:a="md"}){const i=q(),[l,c]=h.useState(!1),[u,d]=h.useState({x:0,y:0,w:0}),p=h.useRef(null),j=t.find(S=>S.value===s),w={sm:28,md:32};h.useEffect(()=>{if(!l)return;const S=()=>c(!1);return document.addEventListener("click",S),()=>document.removeEventListener("click",S)},[l]);const y=()=>{if(!p.current)return;const S=p.current.getBoundingClientRect();d({x:S.left,y:S.bottom+4,w:S.width}),c(!l)};return e.jsxs("div",{className:"flex flex-col gap-1",children:[o&&e.jsx("label",{className:"text-[13px] tracking-wider uppercase font-semibold",style:{color:i.textMuted,fontFamily:"'Geist Mono', monospace"},children:o}),e.jsxs("button",{ref:p,type:"button",onClick:S=>{S.stopPropagation(),y()},className:"flex items-center justify-between gap-2 w-full rounded-lg cursor-pointer border outline-none nodrag",style:{height:w[a],padding:"0 10px",fontSize:13,fontFamily:"'Geist Mono', monospace",background:i.inputBg,borderColor:i.border,color:j?i.textPrimary:i.textMuted},children:[e.jsxs("span",{className:"flex items-center gap-1.5 truncate",children:[j?.icon,j?.label||r]}),e.jsx(re,{size:12,style:{color:i.textDim,transform:l?"rotate(180deg)":"none",transition:"transform 0.15s"}})]}),l&&ze.createPortal(e.jsx("div",{className:"fixed z-[250] rounded-lg overflow-hidden py-1",style:{left:u.x,top:u.y,width:u.w,background:i.surfaceElevated,border:`1px solid ${i.border}`,boxShadow:`0 8px 24px ${i.isDark?"rgba(0,0,0,0.5)":"rgba(0,0,0,0.12)"}`,maxHeight:200,overflowY:"auto"},onClick:S=>S.stopPropagation(),children:t.map(S=>e.jsxs("button",{type:"button",onClick:()=>{n(S.value),c(!1)},className:"flex items-center gap-2 w-full px-3 py-1.5 text-[13px] text-left cursor-pointer border-none bg-transparent",style:{fontFamily:"'Geist Mono', monospace",color:S.value===s?"#FE5000":i.textSecondary,background:S.value===s?"#FE500008":"transparent"},onMouseEnter:E=>E.currentTarget.style.background=i.isDark?"#ffffff08":"#00000005",onMouseLeave:E=>E.currentTarget.style.background=S.value===s?"#FE500008":"transparent",children:[S.icon,e.jsx("span",{className:"flex-1 truncate",children:S.label}),S.value===s&&e.jsx(ee,{size:10})]},S.value))}),document.body)]})}const vt="rgba(99,102,241,0.4)",Qe="#6366f1",St="rgba(99,102,241,0.12)";function Mo({id:t,name:s,description:n,tags:o,onUse:r}){const a=q(),i={background:a.surfaceOpaque,border:`1px dashed ${vt}`,boxShadow:`0 2px 8px ${a.isDark?"rgba(0,0,0,0.2)":"rgba(0,0,0,0.04)"}`};return e.jsx("div",{role:"button",tabIndex:0,title:`Use ${s} template`,className:"cursor-pointer rounded-lg overflow-hidden transition-all duration-200 hover:shadow-lg",onClick:()=>r(t),onKeyDown:l=>{(l.key==="Enter"||l.key===" ")&&r(t)},style:i,onMouseEnter:l=>{l.currentTarget.style.borderColor=Qe},onMouseLeave:l=>{l.currentTarget.style.borderColor=vt},children:e.jsxs("div",{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[e.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{background:St},children:e.jsx(We,{size:14,style:{color:Qe}})}),e.jsx("h3",{className:"text-base font-semibold truncate",style:{color:a.textPrimary,fontFamily:"'Geist Sans', sans-serif"},children:s})]}),e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded shrink-0 ml-2 font-medium uppercase tracking-wide",style:{background:St,color:Qe,fontFamily:"'Geist Mono', monospace"},children:"Template"})]}),e.jsx("p",{className:"text-sm line-clamp-2 mb-3",style:{color:a.textSecondary},children:n||"No description"}),o.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1",children:[o.slice(0,3).map(l=>e.jsx("span",{className:"text-[11px] px-1.5 py-0.5 rounded",style:{background:a.surfaceElevated,color:a.textDim,fontFamily:"'Geist Mono', monospace"},children:l},l)),o.length>3&&e.jsxs("span",{className:"text-[11px] px-1.5 py-0.5 rounded",style:{background:a.surfaceElevated,color:a.textFaint},children:["+",o.length-3]})]})]})})}const $o=[{value:"modified",label:"Last Modified"},{value:"name",label:"Name (A–Z)"},{value:"created",label:"Created"}],jt=Object.entries(vs).map(([t,s])=>({id:t,name:s.agentMeta.name,description:s.agentMeta.description,tags:s.agentMeta.tags}));let _o=0;function Fo({onSelectAgent:t,onNewAgent:s}){const[n,o]=h.useState([]),[r,a]=h.useState(!0),[i,l]=h.useState(null),[c,u]=h.useState(""),[d,p]=h.useState(""),[j,w]=h.useState("modified"),[y,S]=h.useState(null),[E,C]=h.useState(null),[k,m]=h.useState(null),[x,g]=h.useState([]),R=h.useRef(null),M=q();h.useEffect(()=>(R.current&&clearTimeout(R.current),R.current=setTimeout(()=>p(c),300),()=>{R.current&&clearTimeout(R.current)}),[c]);const L=h.useCallback((T,F)=>{const z=++_o;g(A=>[...A,{id:z,type:T,message:F}]),setTimeout(()=>g(A=>A.filter(N=>N.id!==z)),3500)},[]),O=h.useCallback(T=>{const{loadDemoPreset:F}=I.getState();F(T),s()},[s]),_=h.useMemo(()=>{const T=d.trim().toLowerCase();return T?jt.filter(F=>F.name.toLowerCase().includes(T)||F.description.toLowerCase().includes(T)):jt},[d]),$=h.useCallback(async()=>{try{a(!0),l(null);const T=await fetch(`${Z}/agents`);if(!T.ok)throw new Error("Failed to load agents");const F=await T.json(),z=F.data??F??[];o(z.map(A=>({id:A.id,name:A.agentMeta?.name||A.id,description:A.agentMeta?.description||"",avatar:A.agentMeta?.avatar||"",tags:A.agentMeta?.tags||[],updatedAt:A.savedAt||new Date().toISOString()})))}catch(T){l(T instanceof Error?T.message:"Unknown error")}finally{a(!1)}},[]);h.useEffect(()=>{$()},[$]);const G=()=>{const{resetAgent:T}=I.getState();T(),s()},v=async()=>{if(y){C(y.id),S(null);try{if(!(await fetch(`${Z}/agents/${encodeURIComponent(y.id)}`,{method:"DELETE"})).ok)throw new Error("Delete failed");o(F=>F.filter(z=>z.id!==y.id)),L("success",`"${y.name}" deleted`)}catch{L("error",`Failed to delete "${y.name}"`)}finally{C(null)}}},K=async(T,F)=>{F.stopPropagation(),m(T.id);try{const z=await fetch(`${Z}/agents/${encodeURIComponent(T.id)}`);if(!z.ok)throw new Error("Failed to load agent");const A=await z.json(),N=A.data??A,W=`agent-${Date.now()}`,U={...N,id:W,savedAt:new Date().toISOString(),agentMeta:{...N.agentMeta,name:`${N.agentMeta?.name||T.name} (Copy)`}};if(!(await fetch(`${Z}/agents`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(U)})).ok)throw new Error("Failed to save clone");L("success",`Cloned as "${U.agentMeta.name}"`),t(W)}catch{L("error",`Failed to clone "${T.name}"`)}finally{m(null)}},b=h.useMemo(()=>{const T=d.trim().toLowerCase();let F=T?n.filter(z=>z.name.toLowerCase().includes(T)||z.description.toLowerCase().includes(T)):n;return j==="name"?F=[...F].sort((z,A)=>z.name.localeCompare(A.name)):j==="modified"?F=[...F].sort((z,A)=>new Date(A.updatedAt).getTime()-new Date(z.updatedAt).getTime()):j==="created"&&(F=[...F].sort((z,A)=>{const N=parseInt(z.id.replace("agent-",""))||0,W=parseInt(A.id.replace("agent-",""))||0;return N-W})),F},[n,d,j]),P=T=>{const F=new Date(T),A=Math.floor((new Date().getTime()-F.getTime())/(1e3*60*60));return A<1?"Just now":A<24?`${A}h ago`:A<168?`${Math.floor(A/24)}d ago`:F.toLocaleDateString()};return r?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(ls,{size:"lg"})}):i?e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(wt,{icon:e.jsx(mt,{size:32}),title:"Failed to Load Agents",subtitle:i})}):e.jsxs("div",{className:"flex flex-col h-full overflow-hidden",style:{background:M.bg},children:[e.jsxs("div",{className:"px-6 py-4 border-b",style:{borderColor:M.border},children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold mb-1",style:{color:M.textPrimary},children:"Agent Library"}),e.jsx("p",{className:"text-sm",style:{color:M.textSecondary},children:"Build, test, and export AI agents with full context engineering."})]}),e.jsxs(Ve,{onClick:G,variant:"primary",size:"md",title:"Create new agent",className:"flex items-center gap-2",children:[e.jsx(oe,{size:16}),"New Agent"]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(ye,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 pointer-events-none",style:{color:M.textDim}}),e.jsx("input",{type:"text",placeholder:"Search agents…",value:c,onChange:T=>u(T.target.value),className:"w-full pl-8 pr-3 py-1.5 rounded-lg outline-none",style:{background:M.inputBg,border:`1px solid ${M.border}`,color:M.textPrimary,fontFamily:"'Geist Sans', sans-serif",fontSize:13}})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[e.jsx(ln,{size:12,style:{color:M.textDim}}),e.jsx("div",{style:{width:160},children:e.jsx(To,{options:$o,value:j,onChange:w,size:"sm"})})]})]})]}),e.jsxs("div",{className:"flex-1 overflow-auto p-6",children:[n.length===0&&!d&&!r&&e.jsxs("div",{className:"mb-6 flex items-start gap-4 p-5 rounded-xl",style:{background:M.isDark?"rgba(254,80,0,0.07)":"rgba(254,80,0,0.05)",border:`1px solid ${M.isDark?"rgba(254,80,0,0.25)":"rgba(254,80,0,0.2)"}`},children:[e.jsx(cn,{size:28,style:{color:"#FE5000",flexShrink:0,marginTop:2},"aria-hidden":"true"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-base font-bold mb-1",style:{color:M.textPrimary,fontFamily:"'Geist Sans', sans-serif"},children:"Welcome to Modular Studio"}),e.jsx("div",{className:"text-sm mb-3",style:{color:M.textSecondary},children:"Build knowledge-rich AI agents with full context engineering. Start from a template below or create your own."}),e.jsxs("button",{type:"button",onClick:G,className:"flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-semibold border-none cursor-pointer",style:{background:"#FE5000",color:"#fff"},children:[e.jsx(oe,{size:14,"aria-hidden":"true"}),"Get Started"]})]})]}),_.length===0&&b.length===0&&d?e.jsx(wt,{icon:e.jsx(ye,{size:32}),title:"No results match your search",subtitle:`No results for "${d}" — try a different keyword`}):_.length===0&&b.length===0?null:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[_.map(T=>e.jsx(Mo,{...T,onUse:O},T.id)),b.map(T=>e.jsx("div",{role:"button",tabIndex:0,title:`Open ${T.name}`,className:"cursor-pointer rounded-lg overflow-hidden transition-all duration-200 hover:shadow-lg",onClick:()=>t(T.id),onKeyDown:F=>{(F.key==="Enter"||F.key===" ")&&t(T.id)},style:{background:M.surfaceOpaque,border:`1px solid ${M.border}`,boxShadow:`0 2px 8px ${M.isDark?"rgba(0,0,0,0.3)":"rgba(0,0,0,0.06)"}`},onMouseEnter:F=>{F.currentTarget.style.borderColor="#FE5000"},onMouseLeave:F=>{F.currentTarget.style.borderColor=M.border},children:e.jsxs("div",{className:"p-4",children:[e.jsxs("div",{className:"flex items-start gap-3 mb-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0",style:{background:"#FE500015"},children:e.jsx(mt,{size:16,style:{color:"#FE5000"}})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:"text-base font-semibold mb-1 truncate",style:{color:M.textPrimary,fontFamily:"'Geist Sans', sans-serif"},children:T.name}),e.jsx("p",{className:"text-sm line-clamp-2",style:{color:M.textSecondary},children:T.description||"No description"})]})]}),T.tags&&T.tags.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-1 mb-3",children:[T.tags.slice(0,3).map(F=>e.jsx("span",{className:"text-[11px] px-1.5 py-0.5 rounded",style:{background:M.surfaceElevated,color:M.textDim,fontFamily:"'Geist Mono', monospace"},children:F},F)),T.tags.length>3&&e.jsxs("span",{className:"text-[11px] px-1.5 py-0.5 rounded",style:{background:M.surfaceElevated,color:M.textFaint},children:["+",T.tags.length-3]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs",style:{color:M.textDim},children:[e.jsx(dn,{size:12}),e.jsx("span",{style:{fontFamily:"'Geist Mono', monospace"},children:P(T.updatedAt)})]}),e.jsxs("div",{className:"flex items-center gap-1",onClick:F=>F.stopPropagation(),children:[e.jsx("button",{type:"button",title:"Clone agent","aria-label":`Clone ${T.name}`,disabled:k===T.id,onClick:F=>K(T,F),className:"flex items-center justify-center w-6 h-6 rounded cursor-pointer border-none bg-transparent transition-colors",style:{color:k===T.id?M.textFaint:M.textDim},onMouseEnter:F=>{F.currentTarget.style.color="#FE5000"},onMouseLeave:F=>{F.currentTarget.style.color=k===T.id?M.textFaint:M.textDim},children:k===T.id?e.jsx("span",{className:"animate-spin text-[10px]","aria-hidden":"true",children:"⟳"}):e.jsx(Jt,{size:13,"aria-hidden":"true"})}),e.jsx("button",{type:"button",title:"Delete agent","aria-label":`Delete ${T.name}`,disabled:E===T.id,onClick:F=>{F.stopPropagation(),S(T)},className:"flex items-center justify-center w-6 h-6 rounded cursor-pointer border-none bg-transparent transition-colors",style:{color:E===T.id?M.textFaint:M.textDim},onMouseEnter:F=>{F.currentTarget.style.color="#ff4d4f"},onMouseLeave:F=>{F.currentTarget.style.color=E===T.id?M.textFaint:M.textDim},children:E===T.id?e.jsx("span",{className:"animate-spin text-[10px]","aria-hidden":"true",children:"⟳"}):e.jsx(it,{size:13,"aria-hidden":"true"})})]})]})]})},T.id))]})]}),e.jsx(Eo,{open:!!y,onClose:()=>S(null),title:"Delete Agent",width:400,footer:e.jsxs(e.Fragment,{children:[e.jsx(Ve,{variant:"secondary",size:"sm",onClick:()=>S(null),children:"Cancel"}),e.jsx(Ve,{variant:"danger",size:"sm",onClick:v,children:"Delete"})]}),children:e.jsxs("div",{className:"px-4 py-4 text-sm",style:{color:M.textSecondary},children:["Are you sure you want to delete"," ",e.jsxs("span",{className:"font-semibold",style:{color:M.textPrimary},children:['"',y?.name,'"']}),"? This action cannot be undone."]})}),e.jsx("div",{className:"fixed bottom-5 right-5 z-[300] flex flex-col gap-2 pointer-events-none",children:x.map(T=>e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium pointer-events-auto",style:{background:M.surfaceOpaque,border:`1px solid ${T.type==="success"?"#22c55e40":"#ff4d4f40"}`,color:M.textPrimary,boxShadow:`0 4px 16px ${M.isDark?"rgba(0,0,0,0.4)":"rgba(0,0,0,0.12)"}`,fontFamily:"'Geist Sans', sans-serif"},children:[T.type==="success"?e.jsx(Ce,{size:15,style:{color:"#22c55e",flexShrink:0}}):e.jsx(De,{size:15,style:{color:"#ff4d4f",flexShrink:0}}),T.message]},T.id))})]})}const Io={full:0,detail:1,summary:2,headlines:3,mention:4},Ao={opus:"claude-opus-4",sonnet:"claude-sonnet-4",haiku:"claude-haiku-3.5","claude-opus-4":"claude-opus-4","claude-sonnet-4":"claude-sonnet-4","claude-haiku-3.5":"claude-haiku-3.5","gpt-4o":"gpt-4o","gpt-4.1":"gpt-4.1"},Ct=new Set(["markdown","html-slides","email","code","csv","json","diagram","slack"]);function Po(t){const s=t.trim();return s.startsWith("{")?Do(s):s.startsWith("---")?Ro(s):Lo(s)}function Do(t){let s;try{s=JSON.parse(t)}catch{return{}}if(s.modular_version&&s.agent){const o=s.agent,r=le({...o,system:o.system_prompt,reads:o.knowledge?.map(a=>a.path),output_format:o.output_formats,token_budget:o.token_budget});return r.detectedFormat="generic",o.instructionState&&(r.instructionState=o.instructionState),o.workflowSteps&&(r.workflowSteps=o.workflowSteps),r}if(s.template&&s.context_files){const o=le({name:s.template,reads:s.context_files,tools:s.tools,output_format:s.output_format});return o.detectedFormat="vibe-kanban",o}if(s.instructions&&!s.system){const o=le({...s,system:s.instructions,reads:s.context_files||s.reads});return o.detectedFormat="codex",o}const n=le(s);return n.detectedFormat="generic",n}function Ro(t){const{frontmatter:s,body:n}=zo(t),o=le(s);if(o.detectedFormat="claude",!o.prompt){const l=n.match(/## Default Prompt\n([\s\S]*?)(?=\n## |$)/);l&&(o.prompt=l[1].trim())}if(!o.prompt){const l=n.match(/(?:##? Role)\n([\s\S]*?)(?=\n##? |$)/);l&&(o.prompt=l[1].trim())}if(!o.channels||o.channels.length===0){const l=Bo(n);l.length>0&&(o.channels=l)}const r=n.match(/## Persona\n([\s\S]*?)(?=\n## |$)/),a=n.match(/## Constraints\n([\s\S]*?)(?=\n## |$)/),i=n.match(/## Objectives\n([\s\S]*?)(?=\n## |$)/);return(r||a||i)&&(o.instructionState={persona:r?r[1].trim():"",tone:"neutral",expertise:3,constraints:{neverMakeUp:!1,askBeforeActions:!1,stayInScope:!1,useOnlyTools:!1,limitWords:!1,wordLimit:500,customConstraints:a?a[1].trim():"",scopeDefinition:""},objectives:{primary:i?i[1].trim():"",successCriteria:[],failureModes:[]},rawPrompt:"",autoSync:!0}),o}function Lo(t){const s=cs(t);if(s.agents&&typeof s.agents=="object"&&!Array.isArray(s.agents)){const o=s.agents,r=Object.keys(o)[0];if(r){const a=o[r],i=le({name:r.replace(/-/g," "),model:a.model,temperature:a.temperature,tools:a.skills,reads:a.context});return i.detectedFormat="openclaw",i}}if(s.mcp&&typeof s.mcp=="object"&&!Array.isArray(s.mcp)){const o=le({...s,system:s.instructions,reads:s.context_files});return o.detectedFormat="amp",o}const n=le(s);return n.detectedFormat="amp",n}function le(t){const s={},n={name:se(t.name)||"",description:se(t.description)||"",icon:se(t.icon)||"brain",category:se(t.category)||"general",tags:Array.isArray(t.tags)?t.tags:[],avatar:se(t.avatar)||""};if(s.agentMeta=n,t.model){const a=se(t.model);s.selectedModel=Ao[a]??a}t.token_budget!==void 0&&(s.tokenBudget=Number(t.token_budget));const o=t.modular;if(o?.tokenBudget!==void 0&&(s.tokenBudget=Number(o.tokenBudget)),Array.isArray(t.output_format)){const a=t.output_format.filter(i=>Ct.has(i));a.length>0&&(s.outputFormat=a[0])}else if(t.output_format){const a=se(t.output_format);Ct.has(a)&&(s.outputFormat=a)}!s.outputFormat&&o?.outputFormat&&(s.outputFormat=o.outputFormat),Array.isArray(t.reads)&&(s.channels=t.reads.map((a,i)=>{const l=void 0;return{sourceId:l?.id??`imported-${i}`,name:l?.name??a.split("/").filter(Boolean).pop()??a,path:a,category:l?.category??"knowledge",knowledgeType:l?Ae(l.path):Ae(a),enabled:!0,depth:0,baseTokens:l?.tokenEstimate??5e3}})),!s.channels&&o?.channels&&(s.channels=o.channels.map((a,i)=>{const l=Oo(a.type)?a.type:Ae(a.path),c=Io[a.depth?.toLowerCase()]??0,u=(a.path,void 0);return{sourceId:u?.id??`imported-${i}`,name:u?.name??a.path.split("/").filter(Boolean).pop()??a.path,path:a.path,category:u?.category??"knowledge",knowledgeType:l,enabled:!0,depth:c,baseTokens:u?.tokenEstimate??5e3}})),!s.prompt&&t.system&&(s.prompt=se(t.system)),t.prompt&&(s.prompt=se(t.prompt));const r=se(t.system);if(r){const a=Go(r);s.instructionState={persona:a.persona,tone:"neutral",expertise:3,constraints:{neverMakeUp:!1,askBeforeActions:!1,stayInScope:!1,useOnlyTools:!1,limitWords:!1,wordLimit:500,customConstraints:a.constraints,scopeDefinition:""},objectives:{primary:a.objective,successCriteria:[],failureModes:[]},rawPrompt:"",autoSync:!0}}return s}function se(t){return typeof t=="string"?t:t==null?"":String(t)}function zo(t){const s=t.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);return s?{frontmatter:cs(s[1]),body:s[2]}:{frontmatter:{},body:t}}function cs(t){const s={},n=t.split(`
|
|
38
|
+
`);let o="",r=null,a=null,i=null,l="",c=0,u=[];const d=()=>{if(l&&u.length>0){const p=r||s;p[l]=u.join(`
|
|
39
|
+
`),l="",u=[]}};for(const p of n){if(l)if(p.search(/\S/)>=c&&p.trim()!==""){u.push(p.slice(c));continue}else d();const j=p.match(/^(\w[\w_-]*)\s*:\s*(.*)$/);if(j){i&&a&&(a.push(i),i=null),a=null,r=null;const w=j[1],y=j[2].trim();y===""||y==="|"?y==="|"?(l=w,c=2,u=[]):(o=w,r={},s[w]=r):y.startsWith("[")&&y.endsWith("]")?s[w]=y.slice(1,-1).split(",").map(S=>S.trim()).filter(Boolean):s[w]=pe(y);continue}if(r){const w=p.match(/^ (\w[\w_-]*)\s*:\s*(.*)$/);if(w){i&&a&&(a.push(i),i=null);const y=w[1],S=w[2].trim();S===""||S==="|"?S==="|"?(l=y,c=4,u=[]):(a=[],r[y]=a):(a=null,r[y]=pe(S));continue}if(a){const y=p.match(/^ - (.+)$/);if(y&&!y[1].includes(":")){i&&(a.push(i),i=null),a.push(pe(y[1].trim()));continue}}if(a){const y=p.match(/^ - (\w[\w_-]*)\s*:\s*(.*)$/);if(y){i&&a.push(i),i={[y[1]]:pe(y[2])};continue}const S=p.match(/^ (\w[\w_-]*)\s*:\s*(.*)$/);if(S&&i){i[S[1]]=pe(S[2]);continue}}}if(!r){const w=p.match(/^ - (.+)$/);if(w&&a){if(!w[1].includes(":"))a.push(pe(w[1].trim()));else{const S=w[1].match(/^(\w[\w_-]*)\s*:\s*(.*)$/);S&&(i&&a.push(i),i={[S[1]]:pe(S[2])})}continue}const y=p.match(/^(\w[\w_-]*)\s*:$/);if(y){o=y[1],a=[],s[o]=a;continue}}}return d(),i&&a&&a.push(i),s}function pe(t){return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Oo(t){return["ground-truth","signal","evidence","framework","hypothesis","guideline"].includes(t)}function Bo(t){const s=[],n=t.split(`
|
|
40
|
+
`);let o=0;for(const r of n){const a=r.match(/[-*]\s+(?:\*\*.*?\*\*:?\s*)?([A-Za-z0-9_/-]+(?:\/\*)?)/);if(a){const i=a[1];i.includes("/")&&(s.push({sourceId:`body-${o}`,name:i.split("/").filter(Boolean).pop()??i,path:i,category:"knowledge",knowledgeType:Ae(i),enabled:!0,depth:0,baseTokens:5e3}),o++)}}return s}function Go(t){const s=t.replace(/\r\n/g,`
|
|
41
|
+
`).trim();if(!s)return{persona:"",constraints:"",objective:""};const n=s.split(/\n\s*\n/).map(C=>C.trim()).filter(Boolean),r=s.split(`
|
|
42
|
+
`).map(C=>C.trim()).filter(Boolean).map(C=>{const k=C.match(/^[-*]\s+(.+)$/);if(k)return k[1].trim();const m=C.match(/^\d+\.\s+(.+)$/);return m?m[1].trim():""}).filter(Boolean),a=/\b(never|always|must|must not|do not|don't|forbidden|required|only|avoid|without)\b/i,i=/\b(objective|goal|task|deliver|ensure|help|outcome|success|mission)\b/i,l=r.filter(C=>a.test(C)),c=r.filter(C=>!a.test(C)&&i.test(C)),u=s.match(/(?:^|\n)(?:#+\s*)?(?:objective|objectives|goal|goals|mission)\s*:?\s*\n?([\s\S]*?)(?=\n(?:#+\s*)?[A-Za-z][^\n]*:\s*|\n\s*\n|$)/i),d=s.match(/(?:^|\n)(?:#+\s*)?(?:constraint|constraints|guardrails|rules)\s*:?\s*\n?([\s\S]*?)(?=\n(?:#+\s*)?[A-Za-z][^\n]*:\s*|\n\s*\n|$)/i),p=u?.[1]?.split(`
|
|
43
|
+
`).map(C=>C.replace(/^[-*]\s+/,"").trim()).find(Boolean)??"",j=d?.[1]?.split(`
|
|
44
|
+
`).map(C=>C.replace(/^[-*]\s+/,"").trim()).filter(Boolean).join(`
|
|
45
|
+
`)??"",y=(n.find(C=>{const k=C.toLowerCase();return!(/^(constraints?|guardrails?|rules|objectives?|goals?|mission)\s*:/.test(k)||i.test(C)||a.test(C))})??n[0]??"").split(new RegExp("(?<=[.!?])\\s+")).map(C=>C.trim()).find(Boolean)??"",S=p||c[0]||n.find(C=>i.test(C))||"",E=j||l.join(`
|
|
46
|
+
`);return{persona:y,constraints:E,objective:typeof S=="string"?S.trim():""}}class Wo extends h.Component{state={hasError:!1,error:null};static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,n){console.error(`[ErrorBoundary${this.props.label?`:${this.props.label}`:""}]`,s,n.componentStack)}render(){return this.state.hasError?this.props.fallback?this.props.fallback:e.jsxs("div",{style:{padding:24,margin:16,borderRadius:8,background:"#fee2e220",border:"1px solid #ef444440",textAlign:"center"},children:[e.jsxs("div",{style:{fontSize:14,fontWeight:600,color:"#ef4444",marginBottom:8},children:["Something went wrong",this.props.label?` in ${this.props.label}`:""]}),e.jsx("div",{style:{fontSize:12,color:"#888",marginBottom:12},children:this.state.error?.message||"Unknown error"}),e.jsx("button",{onClick:()=>this.setState({hasError:!1,error:null}),style:{padding:"6px 16px",borderRadius:6,border:"1px solid #ef4444",background:"transparent",color:"#ef4444",cursor:"pointer",fontSize:13},children:"Try again"})]}):this.props.children}}function Ko(){const t=q(),s=X(r=>r.providers),n=I(r=>r.setShowSettings);return s.some(r=>r.models&&r.models.length>0&&(r.status==="connected"||r.authMethod==="claude-agent-sdk"))?null:e.jsxs("div",{style:{margin:"0 0 16px",padding:"14px 20px",borderRadius:10,background:"linear-gradient(135deg, #FE500015 0%, #FE500008 100%)",border:"1px solid #FE500030",display:"flex",alignItems:"center",gap:14},children:[e.jsx("div",{style:{width:40,height:40,borderRadius:10,background:"#FE500020",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:e.jsx(Vt,{size:20,style:{color:"#FE5000"}})}),e.jsxs("div",{style:{flex:1},children:[e.jsx("div",{style:{fontSize:14,fontWeight:600,color:t.textPrimary,marginBottom:2},children:"Set up an AI provider to get started"}),e.jsx("div",{style:{fontSize:12,color:t.textSecondary},children:"Add an API key for Anthropic, OpenAI, or any compatible provider. Or use Claude Code for zero-config access."})]}),e.jsxs("button",{onClick:()=>n(!0,"providers"),style:{display:"flex",alignItems:"center",gap:6,padding:"8px 16px",borderRadius:8,border:"none",background:"#FE5000",color:"#fff",fontSize:13,fontWeight:600,cursor:"pointer",flexShrink:0},children:[e.jsx(tt,{size:14}),"Configure Provider"]}),e.jsxs("button",{onClick:()=>n(!0,"providers"),title:"Quick: use Claude Code (no API key needed)",style:{display:"flex",alignItems:"center",gap:4,padding:"8px 12px",borderRadius:8,border:`1px solid ${t.border}`,background:"transparent",color:t.textSecondary,fontSize:12,cursor:"pointer",flexShrink:0},children:[e.jsx(he,{size:12}),"Claude Code"]})]})}const qo=h.forwardRef(function({label:s,labelAction:n,error:o,showCount:r,maxChars:a,value:i,className:l="",style:c,...u},d){const p=q(),j=typeof i=="string"?i.length:0;return e.jsxs("div",{className:"flex flex-col gap-1",children:[(s||r||n)&&e.jsxs("div",{className:"flex items-center justify-between",children:[s&&e.jsx("label",{className:"text-[13px] tracking-wider uppercase font-semibold",style:{color:p.textMuted,fontFamily:"'Geist Mono', monospace"},children:s}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&e.jsxs("span",{className:"text-[13px]",style:{color:a&&j>a?p.statusError:p.textFaint},children:[j,a?` / ${a}`:""]}),n]})]}),e.jsx("textarea",{ref:d,value:i,className:`w-full px-3 py-2.5 rounded-md outline-none resize-none nowheel nodrag ${l}`,style:{background:p.inputBg,border:`1px solid ${o?p.statusError:p.border}`,color:p.textPrimary,fontFamily:"'Geist Sans', sans-serif",fontSize:16,lineHeight:1.5,minHeight:64,...c},...u}),o&&e.jsx("span",{className:"text-[13px]",style:{color:p.statusError},children:o})]})});function Ho(t,s,n){return`You are an expert AI agent architect. Given a user's rough description of an agent they want to build, produce a COMPLETE agent configuration as JSON.
|
|
47
|
+
|
|
48
|
+
You have access to these MCP servers (pick ONLY from this list):
|
|
49
|
+
<mcp_servers>
|
|
50
|
+
${t}
|
|
51
|
+
</mcp_servers>
|
|
52
|
+
|
|
53
|
+
You have access to these skills (pick ONLY from this list):
|
|
54
|
+
<skills>
|
|
55
|
+
${s}
|
|
56
|
+
</skills>
|
|
57
|
+
|
|
58
|
+
The user has these REAL knowledge sources already connected (indexed repos, documents, files):
|
|
59
|
+
<connected_knowledge>
|
|
60
|
+
${n}
|
|
61
|
+
</connected_knowledge>
|
|
62
|
+
|
|
63
|
+
Produce a JSON response with this EXACT structure:
|
|
64
|
+
{
|
|
65
|
+
"agentMeta": {
|
|
66
|
+
"name": "<short agent name>",
|
|
67
|
+
"description": "<one-line description>",
|
|
68
|
+
"avatar": "<icon id: bot|brain|zap|flame|lightbulb|target|rocket|shield|microscope|chart|palette|file|drama|star|gem|bird|bug|cat|dog|heart>",
|
|
69
|
+
"tags": ["<tag1>", "<tag2>"]
|
|
70
|
+
},
|
|
71
|
+
"instructionState": {
|
|
72
|
+
"persona": "<2-4 sentence persona using 'You are...' framing>",
|
|
73
|
+
"tone": "<formal|neutral|casual>",
|
|
74
|
+
"expertise": <1-5>,
|
|
75
|
+
"constraints": {
|
|
76
|
+
"neverMakeUp": <true|false>,
|
|
77
|
+
"askBeforeActions": <true|false>,
|
|
78
|
+
"stayInScope": <true|false>,
|
|
79
|
+
"useOnlyTools": <true|false>,
|
|
80
|
+
"limitWords": <true|false>,
|
|
81
|
+
"wordLimit": <number or 0>,
|
|
82
|
+
"customConstraints": ["<constraint>"],
|
|
83
|
+
"scopeDefinition": "<what agent handles and does NOT handle>"
|
|
84
|
+
},
|
|
85
|
+
"objectives": {
|
|
86
|
+
"primary": "<primary goal>",
|
|
87
|
+
"successCriteria": ["<criterion>"],
|
|
88
|
+
"failureModes": ["<failure to avoid>"]
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
"workflowSteps": [
|
|
92
|
+
{
|
|
93
|
+
"label": "<step name>",
|
|
94
|
+
"action": "<what the agent does>",
|
|
95
|
+
"condition": false,
|
|
96
|
+
"loop": false
|
|
97
|
+
}
|
|
98
|
+
],
|
|
99
|
+
"mcpServerIds": ["<mcp-id from the list above>"],
|
|
100
|
+
"skillIds": ["<skill-id from the list above>"],
|
|
101
|
+
"knowledgeSelections": [
|
|
102
|
+
{
|
|
103
|
+
"sourceId": "<exact sourceId from connected_knowledge>",
|
|
104
|
+
"type": "<ground-truth|signal|evidence|framework|hypothesis|guideline>",
|
|
105
|
+
"depth": <0-4>,
|
|
106
|
+
"reason": "<why this source is relevant>"
|
|
107
|
+
}
|
|
108
|
+
],
|
|
109
|
+
"knowledgeGaps": [
|
|
110
|
+
{
|
|
111
|
+
"name": "<what's missing>",
|
|
112
|
+
"type": "<ground-truth|signal|evidence|framework|hypothesis|guideline>",
|
|
113
|
+
"description": "<what the user should connect and why>"
|
|
114
|
+
}
|
|
115
|
+
],
|
|
116
|
+
"memoryConfig": {
|
|
117
|
+
"maxMessages": <10-50>,
|
|
118
|
+
"summarizeAfter": <5-25>,
|
|
119
|
+
"summarizeEnabled": <true|false>,
|
|
120
|
+
"suggestedFacts": ["<pre-loaded fact for long-term memory>"]
|
|
121
|
+
},
|
|
122
|
+
"outputSuggestions": ["<notion|slack|html-slides|email|github|hubspot>"]
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
Rules:
|
|
126
|
+
1. Pick MCP servers and skills ONLY from the provided lists — use exact IDs
|
|
127
|
+
2. Suggest 2-6 MCP servers and 1-4 skills that are genuinely useful for this agent
|
|
128
|
+
3. Generate 3-8 workflow steps that form a coherent process
|
|
129
|
+
4. **Knowledge: select from REAL connected sources using their exact sourceId**
|
|
130
|
+
- Set the appropriate knowledge type (ground-truth for specs, signal for feedback, etc.)
|
|
131
|
+
- Set depth: 0=Full, 1=Detail(75%), 2=Summary(50%), 3=Headlines(25%), 4=Mention(10%)
|
|
132
|
+
- If no connected sources exist or none are relevant, leave knowledgeSelections empty
|
|
133
|
+
5. **Knowledge gaps: suggest what REAL documents/repos the user should connect**
|
|
134
|
+
- Be specific: "Odfjell fleet spec PDF" not "Company documentation"
|
|
135
|
+
- Only suggest gaps that would genuinely improve the agent
|
|
136
|
+
6. Be opinionated — make real choices, don't hedge
|
|
137
|
+
7. Memory config: enable summarization for conversational agents, disable for one-shot tools
|
|
138
|
+
|
|
139
|
+
Output ONLY the JSON object. No markdown fences, no explanation.`}async function Uo(t,s,n,o){if(!t.trim())throw new Error("Describe the agent you want to build");const r=X.getState(),a=r.providers.filter(g=>(g.status==="connected"||g.status==="configured")&&Array.isArray(g.models)&&g.models.length>0),i=r.providers.find(g=>g.id===r.selectedProviderId&&a.includes(g))||a[0];if(!i)throw new Error("No provider with models available. Connect a provider and refresh models in Settings.");const l=i.models[0],c=typeof l=="string"?l:l?.id||"";if(!c)throw new Error(`Provider ${i.name} has no selectable model.`);const u=i.authMethod==="claude-agent-sdk",d=s?.filter(g=>g.added).map(g=>g.id)||[],p=n?.filter(g=>g.added).map(g=>g.id)||[],j=d.length>0?me.filter(g=>d.includes(g.id)):[],w=p.length>0?Ss.filter(g=>p.includes(g.id)):[],y=j.length>0?j.map(g=>`${g.id}: ${g.description}`).join(`
|
|
140
|
+
`):"none",S=w.length>0?w.map(g=>`${g.id}: ${g.description}`).join(`
|
|
141
|
+
`):"none",E=o||[],C=E.length>0?E.map(g=>`- sourceId: "${g.sourceId}" | name: "${g.name}" | path: "${g.path||"(no path)"}" | type: ${g.knowledgeType||"unclassified"} | tokens: ${g.baseTokens} | depth: ${g.depth}`).join(`
|
|
142
|
+
`):"No knowledge sources connected yet. Suggest what the user should add in knowledgeGaps.",k=Ho(y,S,C),m=u?await js({prompt:t,model:c,systemPrompt:k,maxTurns:1}):await ce({providerId:i.id,model:c,messages:[{role:"system",content:k},{role:"user",content:t}],temperature:.4,maxTokens:4096});let x;try{x=JSON.parse(m)}catch{}if(!x){const g=m.match(/```(?:json)?\s*([\s\S]*?)```/);if(g)try{x=JSON.parse(g[1].trim())}catch{}}if(!x){const g=m.match(/\{[\s\S]*\}/);if(g)try{x=JSON.parse(g[0])}catch{}}if(!x)throw new Error("Could not parse generated agent config");return Yo(x,E),x}function Yo(t,s){if(s.length===0)return;function n(i){const l=t.instructionState.constraints.customConstraints;Array.isArray(l)?l.push(i):typeof l=="string"?t.instructionState.constraints.customConstraints=l?`${l}
|
|
143
|
+
${i}`:i:t.instructionState.constraints.customConstraints=[i]}const o=s.filter(i=>i.repoMeta);if(o.length>0){const i=o.map(c=>{const u=c.repoMeta,d=u.stack.length>0?u.stack.join(", "):"unknown stack";return`${u.name} (${d})`});t.instructionState.persona+=` You have deep access to ${i.join(" and ")}.`,n("Explore connected codebases autonomously — read files, check structure, trace dependencies before asking the user for information.");const l=o.flatMap(c=>c.repoMeta.features).filter(Boolean);if(l.length>0){const c=[...new Set(l)];t.instructionState.persona+=` Key capabilities include: ${c.join(", ")}.`}}const r=new Map;for(const i of s){if(!i.knowledgeType)continue;const l=r.get(i.knowledgeType)??[];l.push(i.name),r.set(i.knowledgeType,l)}const a={"ground-truth":i=>`Do not contradict information from: ${i}`,signal:i=>`When interpreting ${i}, look for underlying user needs, not surface requests`,guideline:i=>`Follow the conventions and rules defined in: ${i}`};for(const[i,l]of r){const c=a[i];c&&n(c(l.join(", ")))}}const Jo={"knowledge-clients-odfjell":["odfjell","bow optima","bow olympus","bow orion","michelle","chemical tanker"],"knowledge-clients-kcc":["kcc","klaveness","baru","balzani","baleen","combination carrier"],"knowledge-competitors-stormgeo":["stormgeo","storm geo","competitor"],"knowledge-competitors-dtn":["dtn","competitor"],"knowledge-competitors-sofar":["sofar","competitor"],"knowledge-competitors-wni":["wni","weathernews","competitor"],"knowledge-competitors-napa":["napa","competitor"],"knowledge-products":["product","feature","navigation report","live","fleet"],"knowledge-products-nr":["navigation report","nr","post-voyage","voyage report"],"knowledge-products-feedback":["feedback","user feedback","nps"],"discovery-eu-ets":["eu ets","carbon","emission","ets","co2","regulation","fueleu"],"discovery-weather-routing":["weather routing","route optimization","weather"],"discovery-fleet-dashboard":["fleet","dashboard","fleet view"],"discovery-cii-monitor":["cii","carbon intensity","rating"],"intel-competitive":["competitive","competitor","benchmark","versus","vs"],"intel-maritime":["maritime","shipping","vessel","marine"],"odfjell-savings":["savings","fuel savings","optimization","odfjell"],"voyage-prep":["voyage prep","voyage preparation","tce","charter"],"signals-odfjell":["odfjell feedback","odfjell signal","michelle said"],roadmap:["roadmap","prioritize","quarter","q1","q2","q3","q4","planning"],"sales-prep-events":["event","conference","meeting prep","pitch"],"cmo-company-profiles":["company profile","company intel","research company"]};function Vo(t,s,n=3){if(!t||t.length<5)return[];const o=t.toLowerCase(),r=new Set(s.map(c=>c.sourceId)),a=[],i=[];for(const[c,u]of Object.entries(Jo))if(!r.has(c)){for(const d of u)if(o.includes(d)){const p=a.find(j=>j.id===c);if(p){i.push({source:p,reason:`Prompt mentions "${d}"`});break}}}if(s.length>0){const c=s.some(p=>p.knowledgeType==="ground-truth"&&p.enabled),u=s.some(p=>p.knowledgeType==="signal"&&p.enabled),d=s.some(p=>p.knowledgeType==="evidence"&&p.enabled);if(!c&&!r.has("knowledge-products")){const p=a.find(j=>j.id==="knowledge-products");p&&i.push({source:p,reason:"No Ground Truth — add Products?"})}if(u&&!d&&!r.has("intel-competitive")){const p=a.find(j=>j.id==="intel-competitive");p&&i.push({source:p,reason:"Signals without Evidence"})}}const l=new Set;return i.filter(c=>l.has(c.source.id)?!1:(l.add(c.source.id),!0)).slice(0,n)}const Qo=`
|
|
144
|
+
## Example 1: PM Agent (Teresa Torres / RICE)
|
|
145
|
+
Input: "Build a PM agent for SaaS B2B that uses Teresa Torres' continuous discovery approach and RICE prioritization. It will analyze customer interviews and Zoom transcripts to extract feature requests and map opportunities."
|
|
146
|
+
|
|
147
|
+
Output:
|
|
148
|
+
{
|
|
149
|
+
"role": "Product Manager",
|
|
150
|
+
"domain": "SaaS B2B",
|
|
151
|
+
"named_experts": ["Teresa Torres"],
|
|
152
|
+
"named_methodologies": ["RICE"],
|
|
153
|
+
"implied_methodologies": ["opportunity mapping", "customer interview analysis", "JTBD"],
|
|
154
|
+
"tools_requested": ["Zoom", "Filesystem"],
|
|
155
|
+
"documents": [
|
|
156
|
+
{ "path": "customer-interviews/", "inferred_type": "signal", "size_estimate": "large" },
|
|
157
|
+
{ "path": "zoom-transcripts/", "inferred_type": "signal", "size_estimate": "large" }
|
|
158
|
+
],
|
|
159
|
+
"success_criteria": ["Features trace to customer evidence", "Opportunities mapped before solutions"],
|
|
160
|
+
"constraints": ["Do not jump from pain point to solution without opportunity mapping"],
|
|
161
|
+
"output_expectations": ["Opportunity solution tree", "RICE-scored backlog"]
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
## Example 2: Legal Agent
|
|
165
|
+
Input: "I need a contract review agent for our legal team. It should apply IRAC analysis methodology to contracts, flag risk clauses, and follow Tina Turner's risk classification framework. Clients include Fortune 500 companies."
|
|
166
|
+
|
|
167
|
+
Output:
|
|
168
|
+
{
|
|
169
|
+
"role": "Legal Analyst",
|
|
170
|
+
"domain": "Contract Review",
|
|
171
|
+
"named_experts": ["Tina Turner"],
|
|
172
|
+
"named_methodologies": ["IRAC"],
|
|
173
|
+
"implied_methodologies": ["risk classification", "clause analysis"],
|
|
174
|
+
"tools_requested": ["Filesystem"],
|
|
175
|
+
"documents": [],
|
|
176
|
+
"success_criteria": ["All risk clauses flagged", "IRAC applied to each clause"],
|
|
177
|
+
"constraints": ["Do not provide legal advice, only analysis"],
|
|
178
|
+
"output_expectations": ["Contract risk report", "Flagged clauses list"]
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
NOTE: "Tina Turner" appears as a risk classification framework author — treat as named expert.
|
|
182
|
+
"Fortune 500 companies" are CLIENTS/STAKEHOLDERS — NOT named experts.
|
|
183
|
+
|
|
184
|
+
## Example 3: Engineering Agent
|
|
185
|
+
Input: "Create a code review agent that follows Google's engineering practices, applies the DORA metrics framework, and uses Martin Fowler's refactoring catalog. It should review PRs and suggest improvements."
|
|
186
|
+
|
|
187
|
+
Output:
|
|
188
|
+
{
|
|
189
|
+
"role": "Senior Software Engineer",
|
|
190
|
+
"domain": "Code Review",
|
|
191
|
+
"named_experts": ["Martin Fowler"],
|
|
192
|
+
"named_methodologies": ["DORA metrics", "Google engineering practices"],
|
|
193
|
+
"implied_methodologies": ["code smell detection", "refactoring patterns"],
|
|
194
|
+
"tools_requested": ["GitHub", "Filesystem"],
|
|
195
|
+
"documents": [],
|
|
196
|
+
"success_criteria": ["Every suggestion references specific refactoring pattern", "DORA impact assessed"],
|
|
197
|
+
"constraints": ["Do not approve PRs with critical issues"],
|
|
198
|
+
"output_expectations": ["PR review with inline comments", "DORA impact assessment"]
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
## Example 4: Marketing Agent
|
|
202
|
+
Input: "Build a content marketing agent using Seth Godin's permission marketing principles and the AIDA framework. It should create email campaigns and analyze conversion funnels for our e-commerce platform."
|
|
203
|
+
|
|
204
|
+
Output:
|
|
205
|
+
{
|
|
206
|
+
"role": "Content Marketing Strategist",
|
|
207
|
+
"domain": "E-commerce Marketing",
|
|
208
|
+
"named_experts": ["Seth Godin"],
|
|
209
|
+
"named_methodologies": ["AIDA", "permission marketing"],
|
|
210
|
+
"implied_methodologies": ["conversion funnel analysis", "email segmentation"],
|
|
211
|
+
"tools_requested": ["email platform", "analytics"],
|
|
212
|
+
"documents": [],
|
|
213
|
+
"success_criteria": ["Campaigns respect permission principles", "AIDA structure applied"],
|
|
214
|
+
"constraints": ["No unsolicited contact", "Must track consent"],
|
|
215
|
+
"output_expectations": ["Email campaign drafts", "Funnel analysis report"]
|
|
216
|
+
}
|
|
217
|
+
`,Zo=`You are a precision extractor for AI agent specifications. Given a user's description of an agent they want, extract structured entities as JSON.
|
|
218
|
+
|
|
219
|
+
CRITICAL RULES:
|
|
220
|
+
1. named_experts: ONLY people referenced as sources of METHODOLOGY, FRAMEWORK, or APPROACH. NOT clients, NOT stakeholders, NOT companies.
|
|
221
|
+
2. named_methodologies: Explicitly named frameworks (RICE, JTBD, IRAC, DORA, AIDA, etc.)
|
|
222
|
+
3. implied_methodologies: Methods SUGGESTED by the task description but not named (e.g., "prioritize features" implies RICE/ICE/MoSCoW)
|
|
223
|
+
4. Return ONLY a valid JSON object — no markdown, no explanation.
|
|
224
|
+
|
|
225
|
+
${Qo}
|
|
226
|
+
|
|
227
|
+
Now extract from the user's input.`;function Xo(t){try{return JSON.parse(t)}catch{}const s=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(s)try{return JSON.parse(s[1].trim())}catch{}const n=t.match(/\{[\s\S]*\}/);if(n)try{return JSON.parse(n[0])}catch{}return null}function er(t){return{role:t.role??"",domain:t.domain??"",named_experts:t.named_experts??[],named_methodologies:t.named_methodologies??[],implied_methodologies:t.implied_methodologies??[],tools_requested:t.tools_requested??[],documents:t.documents??[],success_criteria:t.success_criteria??[],constraints:t.constraints??[],output_expectations:t.output_expectations??[]}}async function tr(t,s){const n=await ce({providerId:s.providerId,model:s.model,messages:[{role:"system",content:Zo},{role:"user",content:t}],temperature:.1,maxTokens:2048}),o=Xo(n);if(!o)throw new Error(`Parser: could not parse LLM response as JSON. Raw: ${n.slice(0,200)}`);return er(o)}function ds(t){try{return JSON.parse(t)}catch{}const s=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(s)try{return JSON.parse(s[1].trim())}catch{}const n=t.match(/\{[\s\S]*\}/);if(n)try{return JSON.parse(n[0])}catch{}return null}async function Nt(t){try{const{fetchAgentSdkCompletion:s}=await fe(async()=>{const{fetchAgentSdkCompletion:o}=await import("./services-BDk6yY4o.js").then(r=>r.Z);return{fetchAgentSdkCompletion:o}},__vite__mapDeps([0,1,2])),n=await s({prompt:`Search the web for: "${t}". Return ONLY the key findings as a concise summary (max 500 words). Focus on framework steps, methodology mechanics, scoring criteria.`,maxTurns:3});return n&&n.length>20?n:null}catch{return null}}const sr=`You are a research analyst. Given a person's name and domain context, decompose their framework into executable steps.
|
|
228
|
+
|
|
229
|
+
Return ONLY a JSON object with this structure:
|
|
230
|
+
{
|
|
231
|
+
"expert_name": "...",
|
|
232
|
+
"framework_name": "...",
|
|
233
|
+
"core_concept": "...",
|
|
234
|
+
"steps": [
|
|
235
|
+
{
|
|
236
|
+
"step": "Step name",
|
|
237
|
+
"input": "What data goes in",
|
|
238
|
+
"process": "Exact procedure with specific criteria",
|
|
239
|
+
"output": "Named artifact with defined format"
|
|
240
|
+
}
|
|
241
|
+
],
|
|
242
|
+
"decision_rules": ["If X then Y", "Override: when Z..."],
|
|
243
|
+
"artifacts": ["Artifact 1", "Artifact 2"],
|
|
244
|
+
"research_confidence": "high|medium|low",
|
|
245
|
+
"research_note": "Optional note if confidence < high"
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
CRITICAL:
|
|
249
|
+
- Steps must have SPECIFIC inputs/outputs/procedures — not "apply best practices"
|
|
250
|
+
- If you cannot find a canonical framework for this person, set confidence to "low" and explain in research_note
|
|
251
|
+
- Do NOT invent frameworks. If unknown, say so.`,nr=`You are a research analyst. Given a methodology/framework name, decompose it into executable mechanics.
|
|
252
|
+
|
|
253
|
+
Return ONLY a JSON object with this structure:
|
|
254
|
+
{
|
|
255
|
+
"name": "...",
|
|
256
|
+
"purpose": "...",
|
|
257
|
+
"mechanics": {
|
|
258
|
+
"inputs": ["input1", "input2"],
|
|
259
|
+
"formula": "optional formula string",
|
|
260
|
+
"scoring": {
|
|
261
|
+
"dimension": { "description": "...", "scale": "..." }
|
|
262
|
+
},
|
|
263
|
+
"output": "Specific artifact",
|
|
264
|
+
"decision_rules": ["Rule 1", "Rule 2"]
|
|
265
|
+
},
|
|
266
|
+
"research_confidence": "high|medium|low",
|
|
267
|
+
"research_note": "Optional"
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
CRITICAL: Include exact scoring scales, formulas, and decision thresholds where they exist.`;async function or(t,s,n,o){const r=o?`
|
|
271
|
+
|
|
272
|
+
Search context found:
|
|
273
|
+
${o}`:`
|
|
274
|
+
|
|
275
|
+
(No web search available — use training knowledge, flag confidence accordingly)`,a=await ce({providerId:n.providerId,model:n.model,messages:[{role:"system",content:sr},{role:"user",content:`Expert: ${t}
|
|
276
|
+
Domain context: ${s}${r}`}],temperature:.2,maxTokens:2048}),i=ds(a);return i?{expert_name:i.expert_name??t,framework_name:i.framework_name??`${t} framework`,core_concept:i.core_concept??"",steps:i.steps??[],decision_rules:i.decision_rules??[],artifacts:i.artifacts??[],research_confidence:i.research_confidence??"medium",research_note:i.research_note}:{expert_name:t,framework_name:`${t} (unresolved)`,core_concept:"",steps:[],decision_rules:[],artifacts:[],research_confidence:"low",research_note:`⚠️ Could not parse research result for ${t}. Included as expertise reference only.`}}async function rr(t,s,n){const o=n?`
|
|
277
|
+
|
|
278
|
+
Search context found:
|
|
279
|
+
${n}`:`
|
|
280
|
+
|
|
281
|
+
(No web search available — use training knowledge, flag confidence accordingly)`,r=await ce({providerId:s.providerId,model:s.model,messages:[{role:"system",content:nr},{role:"user",content:`Methodology: ${t}${o}`}],temperature:.2,maxTokens:2048}),a=ds(r);return a?{name:a.name??t,purpose:a.purpose??"",mechanics:a.mechanics??{inputs:[],output:"",decision_rules:[]},research_confidence:a.research_confidence??"medium",research_note:a.research_note}:{name:t,purpose:"",mechanics:{inputs:[],output:"",decision_rules:[]},research_confidence:"low",research_note:`⚠️ Could not parse research result for ${t}.`}}function ar(t){const s=[],n=t.filter(o=>o.purpose.toLowerCase().includes("prioriti")||o.name.match(/RICE|ICE|MoSCoW|Kano/i));return n.length>1&&s.push({concern:"feature prioritization",frameworks:n.map(o=>o.name),resolution:`Use ${n[0].name} as primary. Others can serve as cross-checks or quick validation.`}),s}async function ir(t,s){const n=[],o=[];for(const l of t.named_experts){const c=await Nt(`${l} framework methodology core steps`);c||n.push(`⚠️ Web search unavailable for ${l}. Using training knowledge. Verify framework accuracy.`);const u=await or(l,t.domain,s,c);o.push(u)}const r=[],a=[...t.named_methodologies,...t.implied_methodologies];for(const l of a){const c=await Nt(`${l} framework scoring criteria steps`),u=await rr(l,s,c);t.implied_methodologies.includes(l)&&!t.named_methodologies.includes(l)&&(u.research_note=(u.research_note?u.research_note+" ":"")+"(inferred — confirm with user if critical)"),r.push(u)}const i=ar(r);return{expert_frameworks:o,methodology_frameworks:r,conflicts:i,research_notes:n}}function lr(t){try{return JSON.parse(t)}catch{}const s=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(s)try{return JSON.parse(s[1].trim())}catch{}const n=t.match(/\{[\s\S]*\}/);if(n)try{return JSON.parse(n[0])}catch{}return null}function cr(t,s){const n=[t.role,t.domain,...t.success_criteria,...t.output_expectations,...t.constraints].join(" ").toLowerCase(),o={prompt_chaining:0,routing:0,parallelization:0,orchestrator_workers:0,evaluator_optimizer:0,hybrid:0};n.match(/step.?by.?step|first.*then.*finally|sequential|pipeline|extract.*then.*prioritize/)&&(o.prompt_chaining+=3),s.expert_frameworks.length>=2&&(o.prompt_chaining+=2),t.output_expectations.length>=2&&(o.prompt_chaining+=1),n.match(/different types? of|depending on|classify|categorize|triage/)&&(o.routing+=3),n.match(/route|dispatch|handle.*(differently|separately)/)&&(o.routing+=2),n.match(/multiple (perspectives|angles|criteria)|cross.?reference|simultaneously/)&&(o.parallelization+=3),n.match(/evaluate.*from.*angles|compare.*frameworks/)&&(o.parallelization+=2),s.methodology_frameworks.length>=3&&(o.parallelization+=1),n.match(/dynamic|figure out|whatever.?is.?needed|unpredictable|complex.*multi/)&&(o.orchestrator_workers+=3),n.match(/break.*down|delegate|coordinate/)&&(o.orchestrator_workers+=2),n.match(/iterate|refine|polish|high.?quality|draft.*review|critique/)&&(o.evaluator_optimizer+=3),n.match(/improve|feedback.?loop|revise/)&&(o.evaluator_optimizer+=2);const r=Object.values(o).sort((a,i)=>i-a);return r[0]>0&&r[1]>0&&r[1]>=r[0]*.6&&(o.hybrid=r[0]+1),Object.values(o).every(a=>a===0)&&(o.prompt_chaining=1),o}const dr=`You select the optimal agentic workflow pattern for an AI agent based on Anthropic's taxonomy.
|
|
282
|
+
|
|
283
|
+
Patterns:
|
|
284
|
+
- prompt_chaining: Fixed sequential steps, each output feeds next. Quality gates between steps.
|
|
285
|
+
- routing: Input classification → specialized handling. Different input types need different processes.
|
|
286
|
+
- parallelization: Independent subtasks run simultaneously, or multiple perspectives aggregated.
|
|
287
|
+
- orchestrator_workers: Central LLM dynamically breaks down tasks and delegates to workers.
|
|
288
|
+
- evaluator_optimizer: Generate → critique → refine loop. Iterative quality improvement.
|
|
289
|
+
- hybrid: Combination of patterns (specify which).
|
|
290
|
+
|
|
291
|
+
Return ONLY a JSON object:
|
|
292
|
+
{
|
|
293
|
+
"pattern": "<pattern_name>",
|
|
294
|
+
"justification": "<one sentence explaining why>",
|
|
295
|
+
"suggested_steps": ["<high-level step 1>", "<step 2>", ...]
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
Base your selection on the task shape, not on what sounds impressive. Most tasks are prompt_chaining. Only use complex patterns when the task genuinely requires them.`;async function ur(t,s,n){const o=cr(t,s),r=Object.entries(o).sort(([,d],[,p])=>p-d)[0][0],a=[...s.expert_frameworks.map(d=>`${d.expert_name}: ${d.framework_name} (${d.steps.length} steps)`),...s.methodology_frameworks.map(d=>`${d.name}: ${d.purpose}`)].join(`
|
|
299
|
+
`),i=await ce({providerId:n.providerId,model:n.model,messages:[{role:"system",content:dr},{role:"user",content:`Role: ${t.role}
|
|
300
|
+
Domain: ${t.domain}
|
|
301
|
+
Success criteria: ${t.success_criteria.join(", ")}
|
|
302
|
+
Output expectations: ${t.output_expectations.join(", ")}
|
|
303
|
+
Constraints: ${t.constraints.join(", ")}
|
|
304
|
+
|
|
305
|
+
Frameworks to incorporate:
|
|
306
|
+
${a}
|
|
307
|
+
|
|
308
|
+
Heuristic suggestion: ${r} (score: ${o[r]})
|
|
309
|
+
All scores: ${JSON.stringify(o)}
|
|
310
|
+
|
|
311
|
+
Select the best pattern and explain why.`}],temperature:.2,maxTokens:1024}),l=lr(i);if(!l||!l.pattern)return{pattern:r,justification:`Selected based on heuristic scoring. Top signal: ${r} (score ${o[r]}).`,suggested_steps:["Extract and classify input data",...s.expert_frameworks.map(d=>`Apply ${d.framework_name}`),...s.methodology_frameworks.slice(0,3).map(d=>`Apply ${d.name}`),"Self-check and validate output"]};const u=["prompt_chaining","routing","parallelization","orchestrator_workers","evaluator_optimizer","hybrid"].includes(l.pattern)?l.pattern:r;return{pattern:u,justification:l.justification??`Selected ${u} based on task analysis.`,suggested_steps:l.suggested_steps??[]}}function pr(t){try{return JSON.parse(t)}catch{}const s=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(s)try{return JSON.parse(s[1].trim())}catch{}const n=t.match(/\{[\s\S]*\}|\[[\s\S]*\]/);if(n)try{return JSON.parse(n[0])}catch{}return null}function Et(t){const n={small:500,medium:2e3,large:8e3,"very large":2e4}[t.size_estimate.toLowerCase()]??2e3;return t.inferred_type==="signal"||t.path.match(/transcript|meeting|interview/i)?n*1.5:t.path.match(/compressed|summary/i)?Math.floor(n*.5):n}const mr=`You classify documents for an AI agent's context window. Each document gets one category:
|
|
312
|
+
|
|
313
|
+
- always_loaded: Needed in every interaction. Small reference data (org charts, glossaries, key definitions). < ~2000 tokens.
|
|
314
|
+
- on_demand: Large or situationally needed. Transcripts, full reports. Agent fetches via tool when needed.
|
|
315
|
+
- compressed: Useful background but too large raw. Summarize for context, full available via tool.
|
|
316
|
+
- never_loaded: Not relevant to agent's purpose, or duplicates another document.
|
|
317
|
+
|
|
318
|
+
Return ONLY a JSON array:
|
|
319
|
+
[
|
|
320
|
+
{
|
|
321
|
+
"path": "...",
|
|
322
|
+
"category": "always_loaded|on_demand|compressed|never_loaded",
|
|
323
|
+
"reasoning": "Why this classification",
|
|
324
|
+
"estimated_tokens": <number>
|
|
325
|
+
}
|
|
326
|
+
]
|
|
327
|
+
|
|
328
|
+
Rules:
|
|
329
|
+
- Be aggressive about on_demand for large files. Transcripts are ALWAYS on_demand.
|
|
330
|
+
- Compressed summaries (.compressed.md) can be always_loaded if small enough.
|
|
331
|
+
- If two documents overlap significantly, mark the less useful one as never_loaded.`;async function fr(t,s,n){if(t.documents.length===0)return{classified_documents:[],total_always_loaded_tokens:0,token_budget:s};const o=t.documents.map((u,d)=>`${d+1}. path: "${u.path}" | type: ${u.inferred_type} | size: ${u.size_estimate}`).join(`
|
|
332
|
+
`),r=await ce({providerId:n.providerId,model:n.model,messages:[{role:"system",content:mr},{role:"user",content:`Agent role: ${t.role}
|
|
333
|
+
Agent domain: ${t.domain}
|
|
334
|
+
Token budget: ${s}
|
|
335
|
+
|
|
336
|
+
Documents to classify:
|
|
337
|
+
${o}`}],temperature:.1,maxTokens:2048}),a=pr(r);let i;Array.isArray(a)?i=a.map((u,d)=>{const p=t.documents[d]??{path:u.path??"",inferred_type:"unknown"},w=["always_loaded","on_demand","compressed","never_loaded"].includes(u.category)?u.category:"on_demand";return{path:u.path??p.path,inferred_type:p.inferred_type,category:w,reasoning:u.reasoning??"",estimated_tokens:u.estimated_tokens??Et(p)}}):i=t.documents.map(u=>{const d=Et(u);let p="on_demand";return u.path.match(/compressed|summary|overview|glossary|structure/i)&&d<2e3?p="always_loaded":u.path.match(/transcript|meeting|interview/i)?p="on_demand":d>5e3?p="compressed":d<=2e3&&(p="always_loaded"),{path:u.path,inferred_type:u.inferred_type,category:p,reasoning:"Heuristic classification (LLM parse failed)",estimated_tokens:d}}),i=hr(i,s);const l=i.filter(u=>u.category==="always_loaded").reduce((u,d)=>u+d.estimated_tokens,0),c={classified_documents:i,total_always_loaded_tokens:l,token_budget:s};return l>s*.8&&(c.token_budget_warning=`⚠️ Always-loaded context uses ${Math.round(l/s*100)}% of token budget (${l}/${s}). Consider increasing budget or moving documents to on-demand retrieval.`),c}function hr(t,s){const n=s*.6;let o=t.filter(i=>i.category==="always_loaded"),r=o.reduce((i,l)=>i+l.estimated_tokens,0);if(r<=n)return t;const a=[...o].sort((i,l)=>l.estimated_tokens-i.estimated_tokens);for(const i of a){if(r<=n)break;const l=t.find(c=>c.path===i.path);l&&(l.category="on_demand",l.reasoning+=" [Auto-demoted: exceeded 60% token budget threshold]",r-=l.estimated_tokens)}return t}function gr(t){try{return JSON.parse(t)}catch{}const s=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(s)try{return JSON.parse(s[1].trim())}catch{}const n=t.match(/\{[\s\S]*\}/);if(n)try{return JSON.parse(n[0])}catch{}return null}const xr={persistence:"Continue working until the task is fully complete. Do not stop at an intermediate step or ask the user to continue unless you are genuinely blocked.",tool_discipline:"Use available tools to verify information. Do not guess, hallucinate, or assume data you could look up. If a tool call fails, report the failure rather than making up a result.",planning:"Before each major step, briefly state what you are about to do and why. After completing a step, reflect: did it produce what was expected? If not, adjust before proceeding."},Tt={questions:["Does every recommendation trace to specific evidence (quote, data, observation)?","Did I apply each framework as concrete steps, not just mention it?","Are there any claims I made without tool verification?","Is the output actionable by someone who has no prior context?","Did I flag uncertainties and assumptions explicitly?"],action:'If any answer is "no", fix it before delivering.'};function yr(t){const s=[];for(const n of t.expert_frameworks)s.push(`EXPERT: ${n.expert_name} — ${n.framework_name}
|
|
338
|
+
Core: ${n.core_concept}
|
|
339
|
+
Steps:
|
|
340
|
+
${n.steps.map((o,r)=>` ${r+1}. ${o.step}
|
|
341
|
+
Input: ${o.input}
|
|
342
|
+
Process: ${o.process}
|
|
343
|
+
Output: ${o.output}`).join(`
|
|
344
|
+
`)}
|
|
345
|
+
Decision rules: ${n.decision_rules.join("; ")}
|
|
346
|
+
Artifacts: ${n.artifacts.join(", ")}
|
|
347
|
+
Confidence: ${n.research_confidence}${n.research_note?` — ${n.research_note}`:""}`);for(const n of t.methodology_frameworks)s.push(`METHODOLOGY: ${n.name}
|
|
348
|
+
Purpose: ${n.purpose}
|
|
349
|
+
Inputs: ${n.mechanics.inputs.join(", ")}
|
|
350
|
+
${n.mechanics.formula?`Formula: ${n.mechanics.formula}`:""}
|
|
351
|
+
${n.mechanics.scoring?`Scoring: ${JSON.stringify(n.mechanics.scoring,null,2)}`:""}
|
|
352
|
+
Output: ${n.mechanics.output}
|
|
353
|
+
Decision rules: ${n.mechanics.decision_rules.join("; ")}
|
|
354
|
+
Confidence: ${n.research_confidence}${n.research_note?` — ${n.research_note}`:""}`);return t.conflicts.length>0&&s.push(`CONFLICTS:
|
|
355
|
+
${t.conflicts.map(n=>`- ${n.concern}: ${n.frameworks.join(" vs ")} → ${n.resolution}`).join(`
|
|
356
|
+
`)}`),s.join(`
|
|
357
|
+
|
|
358
|
+
`)}const br=`You assemble AI agent configurations from decomposed frameworks. Your output must operationalize every framework as executable workflow steps.
|
|
359
|
+
|
|
360
|
+
Return ONLY a JSON object:
|
|
361
|
+
{
|
|
362
|
+
"persona": "<max 3 sentences. WHO the agent is. No framework names. No methodology lists.>",
|
|
363
|
+
"role": "<one sentence: what the agent does>",
|
|
364
|
+
"workflow_steps": [
|
|
365
|
+
{
|
|
366
|
+
"number": 1,
|
|
367
|
+
"name": "[Framework]: [Action verb]",
|
|
368
|
+
"pattern": "chaining|routing|parallel|orchestrator|evaluator",
|
|
369
|
+
"input": "Explicit reference to data source or prior step output",
|
|
370
|
+
"process": "Exact procedure with scoring criteria, scales, decision trees. NOT 'apply best practices'.",
|
|
371
|
+
"output": "Named artifact with defined format (table, tree, scorecard, etc.)",
|
|
372
|
+
"decision_rules": ["If X then Y", "Override: when Z..."],
|
|
373
|
+
"tools_used": ["tool1"]
|
|
374
|
+
}
|
|
375
|
+
],
|
|
376
|
+
"context_strategy": "<brief description of document access approach>",
|
|
377
|
+
"output_schema": {
|
|
378
|
+
"primary_artifact": {
|
|
379
|
+
"name": "...",
|
|
380
|
+
"format": "Table|Tree|Narrative|Scorecard",
|
|
381
|
+
"required_fields": ["field1", "field2"]
|
|
382
|
+
},
|
|
383
|
+
"secondary_artifacts": [{ "name": "...", "format": "..." }],
|
|
384
|
+
"meta": {
|
|
385
|
+
"confidence_flags": "Required — tag uncertain items",
|
|
386
|
+
"source_citations": "Required — link claims to evidence"
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
CRITICAL RULES:
|
|
392
|
+
1. Every decomposed framework MUST produce at least one workflow step with concrete mechanics
|
|
393
|
+
2. Steps reference inputs explicitly ("pain point table from step 2", NOT "the data")
|
|
394
|
+
3. Process fields have scoring scales, formulas, classification criteria — NOT vague phrases
|
|
395
|
+
4. No duplicate content between persona and workflow
|
|
396
|
+
5. Persona is max 3 sentences, no framework names
|
|
397
|
+
6. Always end with a Self-Check step
|
|
398
|
+
7. If a framework has low confidence, add ⚠️ in the step name`;async function kr(t,s,n,o,r){const a=yr(s),i=o.classified_documents.length>0?o.classified_documents.map(d=>`- ${d.path}: ${d.category} (${d.estimated_tokens} tokens) — ${d.reasoning}`).join(`
|
|
399
|
+
`):"No documents provided.",l=await ce({providerId:r.providerId,model:r.model,messages:[{role:"system",content:br},{role:"user",content:`Build an agent config from these inputs:
|
|
400
|
+
|
|
401
|
+
ROLE: ${t.role}
|
|
402
|
+
DOMAIN: ${t.domain}
|
|
403
|
+
SUCCESS CRITERIA: ${t.success_criteria.join(", ")}
|
|
404
|
+
CONSTRAINTS: ${t.constraints.join(", ")}
|
|
405
|
+
OUTPUT EXPECTATIONS: ${t.output_expectations.join(", ")}
|
|
406
|
+
|
|
407
|
+
WORKFLOW PATTERN: ${n.pattern} — ${n.justification}
|
|
408
|
+
SUGGESTED STEPS: ${n.suggested_steps.join(" → ")}
|
|
409
|
+
|
|
410
|
+
DECOMPOSED FRAMEWORKS:
|
|
411
|
+
${a}
|
|
412
|
+
|
|
413
|
+
DOCUMENT STRATEGY:
|
|
414
|
+
${i}
|
|
415
|
+
|
|
416
|
+
TOOLS AVAILABLE: ${t.tools_requested.join(", ")||"Filesystem, Web Search"}
|
|
417
|
+
|
|
418
|
+
Generate the agent config. Every framework above MUST become at least one workflow step with specific mechanics.`}],temperature:.3,maxTokens:4096}),c=gr(l);if(!c)throw new Error(`Assembler: could not parse LLM response. Raw: ${l.slice(0,300)}`);return{persona:c.persona??`You are a ${t.role} specializing in ${t.domain}.`,role:c.role??`${t.role} for ${t.domain}`,workflow_steps:wr(c.workflow_steps??[],s,Tt),context_strategy:c.context_strategy??vr(o),output_schema:Sr(c.output_schema,t),agentic_pillars:xr,self_check:Tt}}function wr(t,s,n){const o=new Set,r=new Set;for(const i of t){const l=i.name.toLowerCase();for(const c of s.expert_frameworks)(l.includes(c.expert_name.toLowerCase())||l.includes(c.framework_name.toLowerCase()))&&o.add(c.expert_name);for(const c of s.methodology_frameworks)l.includes(c.name.toLowerCase())&&r.add(c.name)}for(const i of s.expert_frameworks)if(!o.has(i.expert_name)&&i.steps.length>0){const l=i.research_confidence==="low"?"⚠️ ":"";t.push({number:t.length+1,name:`${l}${i.framework_name} (${i.expert_name})`,pattern:"chaining",input:i.steps[0].input,process:i.steps.map(c=>`${c.step}: ${c.process}`).join(`
|
|
419
|
+
`),output:i.steps[i.steps.length-1].output,decision_rules:i.decision_rules,tools_used:[]})}for(const i of s.methodology_frameworks)if(!r.has(i.name)){const l=i.research_confidence==="low"?"⚠️ ":"";t.push({number:t.length+1,name:`${l}${i.name}`,pattern:"chaining",input:i.mechanics.inputs.join(", "),process:[i.mechanics.formula?`Formula: ${i.mechanics.formula}`:"",i.mechanics.scoring?`Scoring: ${Object.entries(i.mechanics.scoring).map(([c,u])=>`${c}: ${u.description} (${u.scale})`).join("; ")}`:""].filter(Boolean).join(`
|
|
420
|
+
`),output:i.mechanics.output,decision_rules:i.mechanics.decision_rules,tools_used:[]})}return t.some(i=>i.name.toLowerCase().includes("self-check")||i.name.toLowerCase().includes("self check"))||t.push({number:t.length+1,name:"Self-Check",pattern:"evaluator",input:"All prior step outputs",process:n.questions.map(i=>`- ${i}`).join(`
|
|
421
|
+
`),output:"Validated output — all checks pass before delivery",decision_rules:[n.action],tools_used:[]}),t.forEach((i,l)=>{i.number=l+1}),t}function vr(t){if(t.classified_documents.length===0)return"No documents — agent works from conversation input.";const s=t.classified_documents.filter(r=>r.category==="always_loaded"),n=t.classified_documents.filter(r=>r.category==="on_demand"),o=[];return s.length>0&&o.push(`Always loaded: ${s.map(r=>r.path).join(", ")}`),n.length>0&&o.push(`Fetch on demand: ${n.map(r=>r.path).join(", ")}`),o.join(". ")}function Sr(t,s){return t?.primary_artifact?.name&&t.primary_artifact.required_fields?.length>0?t:{primary_artifact:{name:s.output_expectations[0]??"Analysis Report",format:"Table",required_fields:s.output_expectations.length>0?s.output_expectations:["Finding","Evidence","Recommendation","Priority","Confidence"]},secondary_artifacts:s.output_expectations.slice(1).map(n=>({name:n,format:"Narrative"})),meta:{confidence_flags:"Required — tag uncertain items",source_citations:"Required — link claims to evidence"}}}function jr(t){try{return JSON.parse(t)}catch{}const s=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(s)try{return JSON.parse(s[1].trim())}catch{}const n=t.match(/\{[\s\S]*\}/);if(n)try{return JSON.parse(n[0])}catch{}return null}function Cr(t,s,n){const o=[],r=n.workflow_steps.map(a=>`${a.name} ${a.process} ${a.output}`).join(" ").toLowerCase();for(const a of s.expert_frameworks)r.includes(a.expert_name.toLowerCase())||r.includes(a.framework_name.toLowerCase())||o.push(`${a.expert_name} (${a.framework_name})`);for(const a of s.methodology_frameworks)r.includes(a.name.toLowerCase())||o.push(a.name);return o.length===0?{passed:!0}:{passed:!1,issue:`Missing from workflow steps: ${o.join(", ")}`,fix_applied:"Added missing framework steps during assembly post-processing"}}function Mt(t){const s=[/apply\s+best\s+practices/i,/use\s+appropriate\s+methods/i,/leverage\s+(your\s+)?expertise/i,/utilize\s+(your\s+)?knowledge/i,/as\s+needed/i,/when\s+appropriate/i],n=[];for(const o of t.workflow_steps){const r=`${o.process} ${o.input} ${o.output}`;for(const a of s)if(a.test(r)){n.push(`Step ${o.number} "${o.name}": matches "${a.source}"`);break}}return n.length===0?{passed:!0}:{passed:!1,issue:`Vague language in steps: ${n.join("; ")}`}}function Nr(t){const s=t.persona.split(/[.!?]+/).map(a=>a.trim().toLowerCase()).filter(a=>a.length>20),n=t.workflow_steps.map(a=>a.process).join(" ").toLowerCase(),o=t.role.toLowerCase(),r=[];for(const a of s)(n.includes(a)||o.includes(a))&&r.push(a.slice(0,60)+"...");return r.length===0?{passed:!0}:{passed:!1,issue:`Persona/workflow duplication: ${r.join("; ")}`}}function Er(t){if(t.classified_documents.length===0)return{passed:!0};const s=t.total_always_loaded_tokens/t.token_budget;return s<=.6?{passed:!0}:{passed:!1,issue:`Always-loaded context is ${Math.round(s*100)}% of budget (${t.total_always_loaded_tokens}/${t.token_budget}). Should be ≤60%.`,fix_applied:"Documents were auto-demoted during context strategy phase"}}function Tr(t){const s=[];return t.agentic_pillars.persistence||s.push("persistence"),t.agentic_pillars.tool_discipline||s.push("tool_discipline"),t.agentic_pillars.planning||s.push("planning"),s.length===0?{passed:!0}:{passed:!1,issue:`Missing agentic pillars: ${s.join(", ")}`}}function Mr(t){const s=t.output_schema;return s.primary_artifact?.name&&s.primary_artifact?.required_fields?.length>0?{passed:!0}:{passed:!1,issue:"Output schema missing specific fields or artifact definition"}}function $r(t,s){const n=[];n.push("---"),n.push(`name: ${s.role||"Generated Agent"}`),n.push(`description: ${t.role}`),n.push("---"),n.push(""),n.push("## Persona"),n.push(t.persona),n.push(""),n.push("## Agentic Directives"),n.push(`- **Persistence:** ${t.agentic_pillars.persistence}`),n.push(`- **Tool Discipline:** ${t.agentic_pillars.tool_discipline}`),n.push(`- **Planning:** ${t.agentic_pillars.planning}`),n.push(""),n.push("## Workflow");for(const o of t.workflow_steps){if(n.push(`### Step ${o.number}: ${o.name}`),n.push(`**Input:** ${o.input}`),n.push("**Process:**"),n.push(o.process),n.push(`**Output:** ${o.output}`),o.decision_rules.length>0){n.push("**Decision Rules:**");for(const r of o.decision_rules)n.push(`- ${r}`)}o.tools_used.length>0&&n.push(`**Tools:** ${o.tools_used.join(", ")}`),n.push("")}if(n.push("## Output Schema"),n.push(`**Primary:** ${t.output_schema.primary_artifact.name} (${t.output_schema.primary_artifact.format})`),n.push(`**Required fields:** ${t.output_schema.primary_artifact.required_fields.join(", ")}`),t.output_schema.secondary_artifacts.length>0){n.push("**Secondary:**");for(const o of t.output_schema.secondary_artifacts)n.push(`- ${o.name} (${o.format})`)}n.push(""),t.context_strategy&&(n.push("## Context Strategy"),n.push(t.context_strategy),n.push("")),n.push("## Self-Check");for(const o of t.self_check.questions)n.push(`- ${o}`);return n.push(`**Action:** ${t.self_check.action}`),n.join(`
|
|
422
|
+
`)}async function _r(t,s,n,o,r){const a={framework_coverage:Cr(t,s,n),specificity:Mt(n),persona_duplication:Nr(n),context_efficiency:Er(o),agentic_completeness:Tr(n),output_specificity:Mr(n)},i=[],l=Object.entries(a).filter(([,d])=>!d.passed);if(a.specificity&&!a.specificity.passed){const d=n.workflow_steps.filter(p=>{const j=`${p.process} ${p.input} ${p.output}`;return/apply\s+best\s+practices|use\s+appropriate|leverage\s+expertise|utilize\s+knowledge|as\s+needed|when\s+appropriate/i.test(j)});if(d.length>0)try{const p=await ce({providerId:r.providerId,model:r.model,messages:[{role:"system",content:"Rewrite these workflow step processes to be specific and actionable. Replace ALL vague language with concrete procedures, scoring criteria, or decision rules. Return a JSON array of {number, process} objects."},{role:"user",content:JSON.stringify(d.map(w=>({number:w.number,name:w.name,process:w.process})))}],temperature:.2,maxTokens:2048}),j=jr(p);if(j&&Array.isArray(j)){for(const w of j){const y=n.workflow_steps.find(S=>S.number===w.number);y&&w.process&&(y.process=w.process)}a.specificity=Mt(n),a.specificity.passed&&(a.specificity.fix_applied="Vague language replaced via LLM refinement")}}catch{i.push("Specificity auto-fix failed — vague language remains in some steps")}}for(const[d,p]of l)!p.passed&&!p.fix_applied&&i.push(`${d}: ${p.issue}`);for(const d of s.expert_frameworks)d.research_confidence==="low"&&i.push(`⚠️ Low confidence on ${d.expert_name}'s framework — verify accuracy`);const c=Object.values(a).every(d=>d.passed),u=$r(n,t);return{passed:c,criteria_results:a,final_yaml:u,warnings:i}}const Fr={"web scraping":["mcp-firecrawl","mcp-fetch","mcp-puppeteer"],"web search":["mcp-brave-search","mcp-tavily","mcp-exa"],search:["mcp-brave-search","mcp-tavily","mcp-exa"],github:["mcp-github","github-remote"],git:["mcp-git"],database:["mcp-postgres","mcp-mysql","mcp-sqlite"],sql:["mcp-postgres","mcp-mysql","mcp-sqlite"],slack:["mcp-slack"],email:["mcp-gmail","mcp-smtp"],notion:["mcp-notion"],monitoring:["mcp-sentry","mcp-datadog","mcp-grafana"],analytics:["mcp-posthog","mcp-mixpanel"],"competitive analysis":["mcp-firecrawl","mcp-brave-search","mcp-exa"],research:["mcp-brave-search","mcp-tavily","mcp-exa","mcp-fetch"],"code review":["mcp-github","github-remote"],"project management":["mcp-linear","mcp-clickup","mcp-jira"],documentation:["mcp-notion","mcp-confluence"],"customer support":["mcp-zendesk","mcp-intercom","mcp-freshdesk"],crm:["mcp-hubspot","mcp-salesforce"],payments:["mcp-stripe"],ecommerce:["mcp-shopify"],browser:["mcp-puppeteer","mcp-playwright"],"file system":["mcp-filesystem"],memory:["mcp-memory"],docker:["mcp-docker"],kubernetes:["mcp-kubernetes"]},Ir={notion:"notion",hubspot:"hubspot",crm:"hubspot",slack:"slack",github:"github","google drive":"google-drive"},Ar={notion:{name:"Notion",description:"Native Notion integration — faster than MCP",authMethod:"oauth"},hubspot:{name:"HubSpot",description:"Native HubSpot CRM integration",authMethod:"api-key"},slack:{name:"Slack",description:"Native Slack integration — send messages and read channels",authMethod:"oauth"},github:{name:"GitHub",description:"Native GitHub integration — repos, PRs, issues",authMethod:"oauth"},"google-drive":{name:"Google Drive",description:"Native Google Drive integration — read and write files",authMethod:"oauth"},granola:{name:"Granola",description:"Native Granola meeting notes integration",authMethod:"api-key"}};function us(t){const s=[...t.tools_requested,t.domain,t.role].filter(Boolean).map(n=>n.toLowerCase());return[...new Set(s)]}function Pr(t,s){const n=s.toLowerCase(),o=t.name.toLowerCase(),r=t.description.toLowerCase(),a=t.tags.some(i=>i.toLowerCase().includes(n)||n.includes(i.toLowerCase()));return o===n?.9:o.includes(n)?.7:r.includes(n)||a?.5:0}function $t(t,s,n,o){return{id:t.id,name:t.name,description:t.description,source:"mcp",matchReason:`Matched: ${s} (${o})`,matchTerm:s,relevanceScore:n,npmPackage:t.npmPackage,tags:t.tags,category:t.category,configFields:t.configFields,authMethod:t.authMethod}}function Dr(t,s){const n=new Set(s),o=us(t),r=new Map;for(const a of o){const i=Fr[a]??[];for(const l of i){if(n.has(l)||r.has(l))continue;const c=me.find(u=>u.id===l);c&&r.set(l,$t(c,a,1,"semantic"))}for(const l of me){if(n.has(l.id)||r.has(l.id))continue;const c=Pr(l,a);c>0&&r.set(l.id,$t(l,a,c,"fuzzy"))}}return Array.from(r.values()).sort((a,i)=>i.relevanceScore-a.relevanceScore)}function Rr(t,s){const n=new Set(s),o=us(t),r=new Map;for(const a of o){const i=Ir[a];if(!i||n.has(i)||r.has(i))continue;const l=Ar[i];l&&r.set(i,{id:i,name:l.name,description:l.description,source:"connector",matchReason:`Matched: ${a} (connector)`,matchTerm:a,relevanceScore:1,service:i,authMethod:l.authMethod})}return Array.from(r.values())}let _e=null;const Lr=600*1e3;async function zr(t){if(_e&&Date.now()-_e.ts<Lr)return _e.data;try{const s=await fetch("/api/skills/catalog",{signal:t??AbortSignal.timeout(8e3)});if(!s.ok)return[];const n=await s.json();if(n.status==="ok"&&n.data){const o=n.data.map(r=>({id:r.name,name:r.name,repo:r.repo??"",installs:r.installs??"0",url:r.url??""}));return _e={data:o,ts:Date.now()},o}return[]}catch{return[]}}async function Or(t,s,n){const o=new Set(s),r=[...t.tools_requested,t.domain,t.role].filter(Boolean).slice(0,6);if(r.length===0)return[];const a=new Map,i=AbortSignal.timeout(1e4);let l=[];try{l=await zr(n)}catch{return[]}const c=3;for(let u=0;u<r.length&&!i.aborted;u+=c){u>0&&await new Promise(p=>setTimeout(p,200));const d=r.slice(u,u+c);await Promise.allSettled(d.map(async p=>{if(i.aborted)return;const j=p.toLowerCase();for(const w of l){if(o.has(w.id)||a.has(w.id))continue;const y=w.name.toLowerCase().replace(/-/g," "),S=j.split(" ").filter(Boolean);(y===j||y.includes(j)||S.some(C=>C.length>3&&y.includes(C)))&&a.set(w.id,{id:w.id,name:w.name,description:`${w.name} skill from ${w.repo}`,source:"skill",matchReason:`Matched: ${j} (skill)`,matchTerm:j,relevanceScore:y===j?.9:y.includes(j)?.75:.6,owner:w.repo.split("/")[0],repo:w.repo,url:w.url,installCmd:`npx skills add ${w.id} -g`,installs:w.installs})}}))}return Array.from(a.values()).sort((u,d)=>d.relevanceScore-u.relevanceScore)}async function Br(t,s,n){const o=Dr(t,s.mcpIds),r=Rr(t,s.connectorIds),a=await Or(t,s.skillIds,n).catch(()=>[]),i=[...o,...r,...a];for(const d of i)d.source==="connector"&&d.service&&o.some(j=>j.id.includes(d.service))&&(d.matchReason=`${d.matchReason} (preferred over MCP)`);i.sort((d,p)=>p.relevanceScore-d.relevanceScore);const l=i.filter(d=>d.source==="mcp").slice(0,3),c=i.filter(d=>d.source==="connector").slice(0,2),u=i.filter(d=>d.source==="skill").slice(0,3);return[...l,...c,...u]}function ve(t){return{providerId:t.providerId,model:t.sonnetModel}}function Gr(t){return{providerId:t.providerId,model:t.opusModel}}async function Wr(t,s){if(!t.trim())throw new Error("Agent description cannot be empty");const n={},o=s.tokenBudget??4e3,r=s.onPhaseComplete??(()=>{}),a=s.onPhaseWarning??((S,E)=>console.warn(`[V2:${S}] ${E}`));let i=Date.now();const l=await tr(t,ve(s));n.parse=Date.now()-i,r("parse",n.parse);const c=Br(l,s.installed??{skillIds:[],mcpIds:[],connectorIds:[]}).catch(S=>(a("tool_discovery",S instanceof Error?S.message:String(S)),[]));i=Date.now();const u=await ir(l,ve(s));n.research=Date.now()-i,r("research",n.research),i=Date.now();const d=await ur(l,u,ve(s));n.pattern=Date.now()-i,r("pattern",n.pattern),i=Date.now();const p=await fr(l,o,ve(s));n.context=Date.now()-i,r("context",n.context),i=Date.now();const j=await kr(l,u,d,p,Gr(s));n.assemble=Date.now()-i,r("assemble",n.assemble),i=Date.now();const w=await _r(l,u,j,p,ve(s));n.evaluate=Date.now()-i,r("evaluate",n.evaluate),n.total=Object.values(n).reduce((S,E)=>S+E,0)-(n.total??0);const y=await c;return r("tool_discovery",0),{parsed:l,research:u,pattern:d,context:p,assembled:j,evaluation:w,timing:n,discoveredTools:y}}const Se=["parse","tool_discovery","research","pattern","context","assemble","evaluate"];function Kr(t){return{yaml:t.evaluation.final_yaml,passed:t.evaluation.passed,warnings:t.evaluation.warnings,timing:t.timing,parsed:{role:t.parsed.role,domain:t.parsed.domain,named_experts:t.parsed.named_experts,named_methodologies:t.parsed.named_methodologies},pattern:{pattern:t.pattern.pattern,justification:t.pattern.justification,suggested_steps:t.pattern.suggested_steps},research:{expert_count:t.research.expert_frameworks.length,methodology_count:t.research.methodology_frameworks.length,conflicts:t.research.conflicts,notes:t.research.research_notes},evaluation:t.evaluation.criteria_results,discoveredTools:t.discoveredTools??[]}}function qr({prompt:t,onComplete:s,onError:n,tokenBudget:o}){const r=q(),[a,i]=h.useState(Se.map(k=>({phase:k,status:"pending"}))),[l,c]=h.useState("start"),[u,d]=h.useState(null),[p,j]=h.useState(!1),[w,y]=h.useState(0),S=h.useCallback(async()=>{if(p)return;j(!0),d(null),i(Se.map(M=>({phase:M,status:"pending"}))),c("start");const k=X.getState(),m=k.providers.find(M=>M.id===k.selectedProviderId)??k.providers.find(M=>M.models&&M.models.length>0);if(!m){n("No provider configured — add one in Settings"),j(!1);return}const x=m.models?.[0],g=typeof x=="object"&&x!==null?x.id:typeof x=="string"?x:"claude-sonnet-4-20250514",R=m.authMethod==="claude-agent-sdk";i(M=>M.map((L,O)=>O===0?{...L,status:"running"}:L));try{const M={providerId:m.id,sonnetModel:g,opusModel:R?"claude-opus-4-20250514":g,tokenBudget:o??4e3,onPhaseComplete:($,G)=>{c($),i(v=>{const K=Se.indexOf($);return v.map((b,P)=>P===K?{...b,status:"complete",elapsed:G}:P===K+1&&b.status==="pending"?{...b,status:"running"}:b)})},onPhaseWarning:($,G)=>{i(v=>{const K=Se.indexOf($);return v.map((b,P)=>P===K?{...b,status:"warning",warningMessage:G}:b)})}},L=await Wr(t,M);i($=>$.map(G=>({...G,status:"complete",toolCount:G.phase==="tool_discovery"?L.discoveredTools?.length??0:G.toolCount})));const O=Object.values(L.timing).reduce(($,G)=>$+G,0);y(O);const _=Kr(L);d(_),s(_)}catch(M){const L=M instanceof Error?M.message:"Pipeline failed";n(L),i(O=>O.map(_=>_.status==="running"?{..._,status:"failed"}:_))}finally{j(!1)}},[t,o,s,n,p]),C=a.filter(k=>k.status==="complete").length/Se.length*100;return e.jsxs("div",{style:{background:r.surfaceElevated,borderRadius:12,padding:24,border:`1px solid ${r.border}`},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:20},children:[e.jsxs("div",{children:[e.jsx("h3",{style:{margin:0,color:r.textPrimary,fontSize:16,fontWeight:600},children:"Research-Augmented Generation"}),e.jsx("p",{style:{margin:"4px 0 0",color:r.textSecondary,fontSize:13},children:"7-phase pipeline: parse → tools → research → pattern → context → assemble → evaluate"})]}),!p&&!u&&e.jsx("button",{onClick:S,style:{background:"#FE5000",color:"#fff",border:"none",borderRadius:8,padding:"10px 20px",fontSize:14,fontWeight:600,cursor:"pointer"},children:"Generate V2 Agent"}),w>0&&e.jsxs("span",{style:{color:r.textSecondary,fontSize:12},children:["Total: ",(w/1e3).toFixed(1),"s"]})]}),(p||u)&&e.jsx("div",{style:{background:r.border,borderRadius:6,height:6,marginBottom:20,overflow:"hidden"},children:e.jsx("div",{style:{background:"#FE5000",height:"100%",width:`${C}%`,borderRadius:6,transition:"width 0.3s ease"}})}),(p||u)&&e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:a.map(k=>{const m=Cs[k.phase],x=k.status==="running",g=k.status==="complete",R=k.status==="failed",M=k.status==="warning";return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"10px 14px",borderRadius:8,background:x?"#FE500010":"transparent",border:x?"1px solid #FE500030":"1px solid transparent",opacity:k.status==="pending"?.4:1,transition:"all 0.2s ease"},children:[e.jsx("span",{style:{fontSize:18,minWidth:24,textAlign:"center"},children:g?"✅":R?"❌":M?"⚠️":x?"⏳":m?.icon??"○"}),e.jsxs("div",{style:{flex:1},children:[e.jsx("div",{style:{fontWeight:600,fontSize:14,color:r.textPrimary},children:m?.label??k.phase}),e.jsx("div",{style:{fontSize:12,color:r.textSecondary,marginTop:2},children:m?.description??""}),M&&k.warningMessage&&e.jsxs("div",{style:{fontSize:11,color:"#f59e0b",marginTop:4},children:["⚠ ",k.warningMessage]})]}),k.phase==="tool_discovery"&&k.status==="complete"&&k.toolCount!=null&&e.jsx("span",{style:{fontSize:11,padding:"2px 8px",borderRadius:10,background:k.toolCount>0?"#FE500020":r.surfaceElevated,color:k.toolCount>0?"#FE5000":r.textSecondary,fontWeight:600,border:`1px solid ${k.toolCount>0?"#FE500040":r.border}`},children:k.toolCount>0?`💡 ${k.toolCount} tool${k.toolCount!==1?"s":""}`:"No matches"}),k.elapsed!=null&&k.phase!=="tool_discovery"&&e.jsxs("span",{style:{fontSize:12,color:r.textSecondary,fontFamily:"monospace"},children:[(k.elapsed/1e3).toFixed(1),"s"]})]},k.phase)})}),u&&e.jsxs("div",{style:{marginTop:20,padding:16,borderRadius:8,background:r.surface,border:`1px solid ${r.border}`},children:[e.jsx("h4",{style:{margin:"0 0 12px",color:r.textPrimary,fontSize:15,fontWeight:600},children:u.passed?"✅ Generation passed all checks":"⚠️ Generation completed with warnings"}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,marginBottom:16},children:[e.jsx(Fe,{label:"Role",value:u.parsed.role,color:r.textPrimary,bg:r.surfaceElevated}),e.jsx(Fe,{label:"Domain",value:u.parsed.domain,color:r.textPrimary,bg:r.surfaceElevated}),e.jsx(Fe,{label:"Experts Researched",value:u.parsed.named_experts.join(", ")||"None",color:r.textPrimary,bg:r.surfaceElevated}),e.jsx(Fe,{label:"Methodologies",value:u.parsed.named_methodologies.join(", ")||"None",color:r.textPrimary,bg:r.surfaceElevated})]}),e.jsxs("div",{style:{padding:12,borderRadius:8,background:r.surfaceElevated,marginBottom:12},children:[e.jsxs("div",{style:{fontSize:13,fontWeight:600,color:r.textPrimary,marginBottom:4},children:["Workflow Pattern: ",u.pattern.pattern.replace(/_/g," ")]}),e.jsx("div",{style:{fontSize:12,color:r.textSecondary},children:Ns[u.pattern.pattern]??u.pattern.justification})]}),e.jsxs("div",{style:{marginBottom:12},children:[e.jsx("div",{style:{fontSize:13,fontWeight:600,color:r.textPrimary,marginBottom:8},children:"Quality Checks"}),e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:Object.entries(u.evaluation).map(([k,m])=>e.jsxs("span",{style:{fontSize:11,padding:"4px 8px",borderRadius:4,background:m.passed?"#10b98120":"#ef444420",color:m.passed?"#10b981":"#ef4444",fontWeight:500},children:[m.passed?"✓":"✗"," ",k.replace(/_/g," ")]},k))})]}),u.warnings.length>0&&e.jsxs("div",{style:{padding:12,borderRadius:8,background:"#fef3c720",border:"1px solid #fbbf2440"},children:[e.jsxs("div",{style:{fontSize:13,fontWeight:600,color:"#f59e0b",marginBottom:6},children:["Warnings (",u.warnings.length,")"]}),u.warnings.map((k,m)=>e.jsxs("div",{style:{fontSize:12,color:r.textSecondary,marginBottom:4},children:["• ",k]},m))]}),u.research.notes.length>0&&e.jsxs("div",{style:{marginTop:12,padding:12,borderRadius:8,background:r.surfaceElevated},children:[e.jsx("div",{style:{fontSize:13,fontWeight:600,color:r.textPrimary,marginBottom:6},children:"Research Notes"}),u.research.notes.map((k,m)=>e.jsx("div",{style:{fontSize:12,color:r.textSecondary,marginBottom:4},children:k},m))]})]})]})}function Fe({label:t,value:s,color:n,bg:o}){return e.jsxs("div",{style:{padding:10,borderRadius:6,background:o},children:[e.jsx("div",{style:{fontSize:11,fontWeight:500,color:"#888",marginBottom:2},children:t}),e.jsx("div",{style:{fontSize:13,fontWeight:600,color:n},children:s})]})}const _t=8;function Hr({tools:t,onNavigateToKnowledge:s,skillsLoading:n}){const o=q(),r=Q(N=>N.addServer),[a,i]=h.useState(!1),[l,c]=h.useState(!1),[u,d]=h.useState(new Set),[p,j]=h.useState(new Set),[w,y]=h.useState(!1),S=Q(N=>new Set(N.servers.map(W=>W.id))),E=I(N=>new Set((N.connectors??[]).filter(W=>W.enabled).map(W=>W.id))),C=xe(N=>new Set(N.skills.filter(W=>W.enabled).map(W=>W.id))),k=h.useMemo(()=>t.filter(N=>N.source==="mcp"?!S.has(N.id):N.source==="connector"?!E.has(N.id):N.source==="skill"?!C.has(N.id):!0),[t,S,E,C]);if(l||k.length===0&&!n)return null;const m=k.filter(N=>N.source==="mcp"),x=k.filter(N=>N.source==="connector"),g=k.filter(N=>N.source==="skill"),R=[...m,...x,...g],M=Math.max(0,R.length-_t);let L=_t;function O(N){if(w||L<=0)return w?{shown:N,hidden:[]}:{shown:[],hidden:N};const W=N.slice(0,L),U=N.slice(L);return L=Math.max(0,L-N.length),{shown:W,hidden:U}}const{shown:_,hidden:$}=O(m),{shown:G,hidden:v}=O(x),{shown:K,hidden:b}=O(g),P=async N=>{if(!p.has(N.id)){d(W=>new Set(W).add(N.id)),fetch("/api/tool-analytics/accepted",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({toolId:N.id,source:N.source})}).catch(()=>{});try{await r({id:N.id,name:N.name,command:"npx",args:["-y",N.npmPackage??N.id],env:{}}),j(W=>new Set(W).add(N.id))}finally{d(W=>{const U=new Set(W);return U.delete(N.id),U})}}},T=async N=>{if(!p.has(N.id)){d(W=>new Set(W).add(N.id)),fetch("/api/tool-analytics/accepted",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({toolId:N.id,source:N.source})}).catch(()=>{});try{await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({skillId:N.id})}),j(W=>new Set(W).add(N.id))}finally{d(W=>{const U=new Set(W);return U.delete(N.id),U})}}},F={background:o.surface,border:`1px solid ${o.border}`,borderRadius:8,padding:"10px 14px",display:"flex",alignItems:"flex-start",gap:12},z=N=>({fontSize:12,fontWeight:600,padding:"4px 10px",borderRadius:6,border:"1px solid #FE5000",background:N==="primary"?"#FE500015":"transparent",color:N==="primary"?"#FE5000":o.textSecondary,cursor:"pointer",fontFamily:"'Geist Sans', sans-serif",whiteSpace:"nowrap",flexShrink:0});function A(N){if(N.source==="mcp"){const f=N.configFields?.some(Y=>Y.required),B=p.has(N.id),H=u.has(N.id);return e.jsxs("div",{style:F,children:[e.jsx("div",{style:{fontSize:18,lineHeight:1,paddingTop:2,flexShrink:0},children:"🔧"}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[e.jsx("span",{style:{fontSize:13,fontWeight:600,color:o.textPrimary,fontFamily:"'Geist Sans', sans-serif"},children:N.name}),f&&e.jsx("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:4,background:"#fbbf2420",color:"#f59e0b",fontWeight:500},children:"Requires API key"})]}),e.jsx("div",{style:{fontSize:12,color:o.textSecondary,marginTop:2,lineHeight:1.4},children:N.description}),e.jsx("div",{style:{fontSize:11,color:o.textDim,marginTop:4},children:N.matchReason})]}),e.jsx("button",{type:"button",disabled:B||H,onClick:()=>P(N),style:{...z("primary"),opacity:B||H?.6:1,display:"flex",alignItems:"center",gap:4},children:B?"✓ Added":H?"…":e.jsxs(e.Fragment,{children:[e.jsx(oe,{size:11})," Add to MCP"]})})]},N.id)}if(N.source==="connector")return e.jsxs("div",{style:F,children:[e.jsx("div",{style:{fontSize:18,lineHeight:1,paddingTop:2,flexShrink:0},children:"🔗"}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("span",{style:{fontSize:13,fontWeight:600,color:o.textPrimary,fontFamily:"'Geist Sans', sans-serif"},children:N.name}),e.jsx("div",{style:{fontSize:12,color:o.textSecondary,marginTop:2,lineHeight:1.4},children:N.description}),e.jsx("div",{style:{fontSize:11,color:o.textDim,marginTop:4},children:N.matchReason})]}),e.jsxs("button",{type:"button",onClick:()=>s?.(),style:{...z("primary"),display:"flex",alignItems:"center",gap:4},children:[e.jsx(un,{size:11})," Connect"]})]},N.id);const W=p.has(N.id),U=u.has(N.id);return e.jsxs("div",{style:F,children:[e.jsx("div",{style:{fontSize:18,lineHeight:1,paddingTop:2,flexShrink:0},children:"⚡"}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[e.jsx("span",{style:{fontSize:13,fontWeight:600,color:o.textPrimary,fontFamily:"'Geist Sans', sans-serif"},children:N.name}),N.installs&&N.installs!=="0"&&e.jsxs("span",{style:{fontSize:10,color:o.textDim},children:[N.installs," installs"]})]}),e.jsx("div",{style:{fontSize:12,color:o.textSecondary,marginTop:2,lineHeight:1.4},children:N.description}),e.jsx("div",{style:{fontSize:11,color:o.textDim,marginTop:4},children:N.matchReason})]}),e.jsx("button",{type:"button",disabled:W||U,onClick:()=>T(N),style:{...z("primary"),opacity:W||U?.6:1,display:"flex",alignItems:"center",gap:4},children:W?"✓ Installed":U?"…":e.jsxs(e.Fragment,{children:[e.jsx(at,{size:11})," Install"]})})]},N.id)}return e.jsxs("div",{style:{marginTop:16,background:o.surfaceElevated,border:`1px solid ${o.border}`,borderRadius:12,overflow:"hidden"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:a?"none":`1px solid ${o.border}`},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("span",{style:{fontSize:14},children:"🔌"}),e.jsx("span",{style:{fontSize:14,fontWeight:600,color:o.textPrimary,fontFamily:"'Geist Sans', sans-serif"},children:"Suggested Tools"}),e.jsx("span",{style:{fontSize:11,padding:"2px 7px",borderRadius:10,background:"#FE500020",color:"#FE5000",fontWeight:600},children:k.length})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("button",{type:"button",onClick:()=>c(!0),style:{background:"none",border:"none",cursor:"pointer",color:o.textDim,padding:4,display:"flex",alignItems:"center"},title:"Dismiss all suggestions",children:e.jsx(ae,{size:13})}),e.jsx("button",{type:"button",onClick:()=>i(!a),style:{background:"none",border:"none",cursor:"pointer",color:o.textDim,padding:4,display:"flex",alignItems:"center"},children:a?e.jsx(re,{size:14}):e.jsx(Ke,{size:14})})]})]}),!a&&e.jsxs("div",{style:{padding:"12px 16px",display:"flex",flexDirection:"column",gap:20},children:[_.length>0&&e.jsxs("section",{children:[e.jsx("div",{style:{fontSize:11,fontWeight:700,color:o.textDim,textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:8},children:"MCP Servers"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:_.map(A)})]}),G.length>0&&e.jsxs("section",{children:[e.jsx("div",{style:{fontSize:11,fontWeight:700,color:o.textDim,textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:4},children:"Connectors"}),e.jsx("div",{style:{fontSize:11,color:"#10b981",fontWeight:500,marginBottom:8},children:"Native — faster than MCP"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:G.map(A)})]}),K.length>0&&e.jsxs("section",{children:[e.jsx("div",{style:{fontSize:11,fontWeight:700,color:o.textDim,textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:8},children:"Skills"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:K.map(A)})]}),!w&&M>0&&e.jsxs("button",{type:"button",onClick:()=>y(!0),style:{background:"transparent",border:`1px solid ${o.border}`,borderRadius:6,color:o.textSecondary,fontSize:12,padding:"6px 12px",cursor:"pointer",fontFamily:"'Geist Sans', sans-serif",alignSelf:"flex-start"},children:["Show ",M," more"]}),w&&e.jsxs(e.Fragment,{children:[$.length>0&&e.jsx("section",{children:e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:$.map(A)})}),v.length>0&&e.jsx("section",{children:e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:v.map(A)})}),b.length>0&&e.jsx("section",{children:e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:b.map(A)})})]}),n&&e.jsxs("div",{style:{fontSize:12,color:o.textDim,display:"flex",alignItems:"center",gap:6,fontFamily:"'Geist Sans', sans-serif"},children:[e.jsx("span",{style:{animation:"spin 1s linear infinite",display:"inline-block"},children:"⟳"}),"Searching skills marketplace..."]})]})]})}function Ur(){const t=q(),s=ie(d=>d.agentId)??"",[n,o]=h.useState(null),[r,a]=h.useState(!1),[i,l]=h.useState(!1);h.useEffect(()=>{if(s){a(!0);try{Promise.allSettled([fetch(`/api/qualification/${s}/history`).then(d=>d.json()),fetch(`/api/cost/${s}/summary`).then(d=>d.json()),fetch(`/api/lessons/${s}`).then(d=>d.json())]).then(([d,p,j])=>{const w=d.status==="fulfilled"?d.value:null,y=p.status==="fulfilled"?p.value:null,S=j.status==="fulfilled"?j.value:null,E=w?.data??[],C=E.length>0?E[E.length-1]?.globalScore??null:null,k=y?.data??{},m=S?.instincts??[],x=m.filter(L=>L.status==="approved"),g=x.length>0?x.reduce((L,O)=>L+(O.confidence??0),0)/x.length:0,R=Date.now()-10080*60*1e3,M=m.filter(L=>new Date(L.lastSeenAt??0).getTime()>R).length;o({qualityScore:C,avgCostPerRun:k.avgCostPerRun??0,cacheHitPct:k.cacheHitPct??0,lessonCount:x.length,avgConfidence:g,lessonsThisWeek:M})}).finally(()=>a(!1))}catch{a(!1)}}},[s]);const c=n!==null&&(n.qualityScore!==null||n.avgCostPerRun>0||n.lessonCount>0),u={background:t.surface,border:`1px solid ${t.border}`,borderRadius:8,padding:"12px 16px",fontFamily:"'Geist Sans', sans-serif"};return e.jsxs("div",{style:u,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mn,{size:14,style:{color:"#FE5000"}}),e.jsx("span",{className:"text-sm font-semibold",style:{color:t.textPrimary},children:"📊 Agent Health"})]}),e.jsx("button",{type:"button",onClick:()=>l(!i),className:"border-none bg-transparent cursor-pointer p-0.5",style:{color:t.textDim},children:i?e.jsx(re,{size:14}):e.jsx(Ke,{size:14})})]}),!i&&(r?e.jsx("p",{className:"text-xs m-0",style:{color:t.textDim},children:"Loading health metrics…"}):c?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap gap-4",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-xs",style:{color:t.textDim},children:"Quality "}),e.jsx("span",{className:"text-xs font-semibold",style:{color:t.textPrimary},children:n.qualityScore!==null?`${n.qualityScore}/100`:"N/A"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs",style:{color:t.textDim},children:"Cost "}),e.jsx("span",{className:"text-xs font-semibold",style:{color:t.textPrimary},children:n.avgCostPerRun>0?`$${n.avgCostPerRun.toFixed(4)}/run`:"N/A"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs",style:{color:t.textDim},children:"Learning "}),e.jsx("span",{className:"text-xs font-semibold",style:{color:t.textPrimary},children:n.lessonCount>0?`${n.lessonCount} lesson${n.lessonCount!==1?"s":""} (${Math.round(n.avgConfidence*100)}% avg)`:"No lessons yet"})]})]}),(n.lessonsThisWeek>0||n.cacheHitPct>0)&&e.jsxs("div",{className:"flex gap-4 mt-2",children:[n.lessonsThisWeek>0&&e.jsxs("span",{className:"text-xs",style:{color:t.textDim},children:["🧠 ",n.lessonsThisWeek," lesson",n.lessonsThisWeek!==1?"s":""," this week"]}),n.cacheHitPct>0&&e.jsxs("span",{className:"text-xs",style:{color:t.textDim},children:["💰 ",Math.round(n.cacheHitPct*100),"% saved via caching"]})]})]}):e.jsx("p",{className:"text-xs m-0",style:{color:t.textDim},children:"Run tests to see agent health metrics"}))]})}const Ft=1e4,Ze=20,Yr=50,Jr=3;function et({onValidationChange:t,onNavigateToNext:s,onNavigateToKnowledge:n}){const o=q(),r=I(D=>D.prompt),a=I(D=>D.setPrompt),i=I(D=>D.hydrateFromGenerated),l=I(D=>D.setKnowledgeGaps),c=I(D=>D.channels),u=I(D=>D.mcpServers),d=I(D=>D.skills),p=X(D=>D.providers),j=p.some(D=>(D.status==="connected"||D.status==="configured")&&(D._hasStoredKey||D._hasStoredAccessToken||!!D.apiKey?.trim()||D.authMethod==="claude-agent-sdk")),[w,y]=h.useState(null),[S,E]=h.useState(!1),[C,k]=h.useState(!1),[m,x]=h.useState(null),[g,R]=h.useState(null),M=h.useRef(void 0),L=h.useRef(void 0),O=h.useRef(new Set),[_,$]=h.useState([]),[G,v]=h.useState(!0),[K,b]=h.useState(!1),[P,T]=h.useState(null),F=p.some(D=>D.authMethod==="claude-agent-sdk"&&(D.status==="connected"||D.status==="configured")),z={color:o.textPrimary,fontFamily:"'Geist Sans', sans-serif"},A={color:o.textSecondary,lineHeight:1.5},N={minHeight:"200px",fontFamily:"'Geist Sans', sans-serif",fontSize:"14px",lineHeight:1.6},W={background:o.surface,border:`1px solid ${o.border}`},U={color:"#FE5000",marginTop:2,flexShrink:0},f=r.length>=Ze;h.useEffect(()=>{const D=!f&&S?`Please enter at least ${Ze} characters`:null;y(D),t?.(f)},[f,S,t]);const B=h.useCallback(()=>{M.current&&clearTimeout(M.current),M.current=setTimeout(()=>{},500)},[]);h.useEffect(()=>{if(L.current&&clearTimeout(L.current),c.length>=Jr||r.length<Yr){$([]);return}return L.current=setTimeout(()=>{const ue=Vo(r,c);$(ue.filter(ke=>!O.current.has(ke.source.id)))},500),()=>{L.current&&clearTimeout(L.current)}},[r,c]);const H=D=>{O.current.add(D),$(ue=>ue.filter(ke=>ke.source.id!==D))},Y=D=>{H(D),n?.()},J=D=>{a(D),B()},de=()=>{E(!0)},ut=async()=>{if(!r.trim()){y("Please enter a description before generating"),E(!0);return}k(!0),x(null),R(null);try{const D=await Uo(r,u,d,c);l(D.knowledgeGaps||[]),i(D),R(D),setTimeout(()=>{s?.()},2e3)}catch(D){x(D instanceof Error?D.message:"Generation failed")}finally{k(!1)}};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ur,{}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-semibold mb-2 m-0",style:z,children:"Describe Your Agent"}),e.jsx("p",{className:"text-sm",style:A,children:"Start by describing what you want your agent to do. Be specific about its role, capabilities, and the types of tasks it should handle."})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"agent-description",className:"block text-sm font-medium mb-3",style:{color:o.textPrimary},children:"Agent Description"}),e.jsx(qo,{id:"agent-description",value:r,onChange:D=>J(D.target.value),onBlur:de,placeholder:"Describe your agent in detail... For example: 'A customer support agent that helps users with technical issues. It should have access to documentation, be able to create support tickets, and escalate complex issues to human agents. The agent should be friendly but professional, and always verify user identity before sharing sensitive information.'",rows:8,style:N,maxLength:Ft}),e.jsxs("div",{className:"flex justify-between items-center mt-2",children:[e.jsx("div",{children:w&&e.jsx("div",{className:"text-sm text-red-500",children:w})}),e.jsxs("div",{className:"text-sm text-right",style:{color:o.textSecondary},"aria-live":"polite",children:[r.length," / ",Ft]})]}),_.length>0&&e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"text-xs mb-2",style:{color:o.textSecondary,fontFamily:"'Inter', 'Geist Sans', sans-serif"},children:"Suggested knowledge sources:"}),e.jsx("div",{className:"flex flex-wrap gap-2",role:"list","aria-label":"Knowledge source suggestions",children:_.map(D=>e.jsxs("div",{role:"listitem",className:"flex items-center gap-1 px-3 py-1 rounded-full text-xs border",style:{background:"#FE500010",borderColor:"#FE500040",color:o.textPrimary},children:[e.jsx("button",{type:"button",onClick:()=>Y(D.source.id),className:"font-medium hover:underline",style:{color:"#FE5000",fontFamily:"'Inter', 'Geist Sans', sans-serif",background:"none",border:"none",cursor:"pointer",padding:0},title:`Add ${D.source.name} to knowledge sources`,children:D.source.name}),e.jsxs("span",{style:{color:o.textSecondary},children:["· ",D.reason]}),e.jsx("button",{type:"button",onClick:()=>H(D.source.id),"aria-label":`Dismiss ${D.source.name} suggestion`,className:"ml-1 opacity-60 hover:opacity-100",style:{background:"none",border:"none",cursor:"pointer",padding:0,color:o.textSecondary,display:"flex",alignItems:"center"},children:e.jsx(ae,{size:10})})]},D.source.id))})]}),r.trim().length>=Ze&&e.jsxs("div",{className:"mt-6",children:[e.jsxs("div",{className:"flex items-center gap-3 p-4 rounded-lg",style:{background:F&&G?"#FE500010":o.surfaceElevated,border:`1px solid ${F&&G?"#FE500040":o.border}`,cursor:F?"pointer":"not-allowed",opacity:F?1:.7},onClick:()=>{F&&!K&&!C&&v(!G)},title:F?void 0:"Requires Claude Code authentication — connect via Settings > Providers",children:[F?e.jsx(he,{size:18,style:{color:G?"#FE5000":o.textSecondary}}):e.jsx(pn,{size:18,style:{color:o.textDim}}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"text-sm font-semibold",style:{color:F?o.textPrimary:o.textDim},children:["Research-Augmented Generation (V2)",!F&&e.jsx("span",{className:"ml-2 text-[11px] font-normal px-1.5 py-0.5 rounded",style:{background:o.surfaceElevated,color:o.textDim,border:`1px solid ${o.border}`},children:"Requires Claude Code auth"})]}),e.jsx("div",{className:"text-xs mt-1",style:{color:o.textSecondary},children:F?"Names experts and methodologies? V2 will research and decompose them into executable workflow steps — not just mention them.":"Connect Claude Code in Settings > Providers to unlock Research-Augmented Generation."})]}),F&&e.jsx("div",{style:{width:40,height:22,borderRadius:11,background:G?"#FE5000":o.border,position:"relative",transition:"background 0.2s"},children:e.jsx("div",{style:{width:18,height:18,borderRadius:9,background:"#fff",position:"absolute",top:2,left:G?20:2,transition:"left 0.2s",boxShadow:"0 1px 3px rgba(0,0,0,0.2)"}})})]}),G&&e.jsxs("div",{className:"mt-4",children:[e.jsx(qr,{prompt:r,tokenBudget:4e3,onComplete:D=>{T(D),b(!1);try{const ue=D.pattern.suggested_steps||[],ke={agentMeta:{name:D.parsed.role||"Generated Agent",description:`${D.parsed.domain} agent`,avatar:"bot",tags:[D.parsed.domain,D.pattern.pattern.replace(/_/g," ")].filter(Boolean)},instructionState:{persona:`You are a ${D.parsed.role} specializing in ${D.parsed.domain}.`,tone:"neutral",expertise:4,constraints:{neverMakeUp:!0,askBeforeActions:!0,stayInScope:!0,useOnlyTools:!1,limitWords:!1,wordLimit:0,customConstraints:[],scopeDefinition:""},objectives:{primary:r,successCriteria:[],failureModes:[]}},workflowSteps:ue.map((ms,fs)=>({label:ms,action:`step_${fs+1}`,condition:!1,loop:!1})),mcpServerIds:[],skillIds:[],knowledgeSelections:[],knowledgeGaps:[],memoryConfig:{maxMessages:20,summarizeAfter:10,summarizeEnabled:!0,suggestedFacts:[]},outputSuggestions:[]};i(ke)}catch(ue){console.warn("[V2] Failed to hydrate stores:",ue)}setTimeout(()=>{s?.()},3e3)},onError:D=>{x(D),b(!1)}}),P?.discoveredTools&&P.discoveredTools.length>0&&e.jsx(Hr,{tools:P.discoveredTools,onNavigateToKnowledge:n})]})]}),(!G||!F)&&e.jsx("div",{className:"mt-6 mb-4 text-center",children:e.jsx("p",{className:"text-sm px-4",style:{color:o.textSecondary,lineHeight:1.5},children:"Generate will use AI to create a complete agent configuration from your description — including persona, constraints, objectives, workflow, and tool selection."})}),(!G||!F)&&e.jsx("div",{className:"mt-4 flex justify-center",children:e.jsx("button",{type:"button",onClick:ut,disabled:C||!r.trim()||!j,title:j?C?"Generating configuration":r.trim()?"Generate full agent config":"Enter description first":"Set up a provider in Settings first",className:"flex items-center gap-3 px-8 py-4 rounded-lg transition-colors font-semibold text-base",style:{background:C||!r.trim()||!j?"#CC4000":"#FE5000",color:"#FFFFFF",border:"none",fontFamily:"'Geist Sans', sans-serif",opacity:C||!r.trim()||!j?.6:1,cursor:C||!r.trim()||!j?"default":"pointer"},onMouseEnter:D=>{!C&&r.trim()&&(D.currentTarget.style.background="#E54800")},onMouseLeave:D=>{!C&&r.trim()&&(D.currentTarget.style.background="#FE5000")},children:C?e.jsxs(e.Fragment,{children:[e.jsx(te,{size:20,className:"animate-spin motion-reduce:animate-none"}),"Generating Agent..."]}):g?e.jsxs(e.Fragment,{children:[e.jsx(ee,{size:20}),"Agent Generated!"]}):e.jsxs(e.Fragment,{children:[e.jsx(We,{size:20}),"Generate Agent"]})})}),m&&e.jsx("div",{className:"mt-3 p-4 rounded-lg",style:{background:"#fee2e210",border:"1px solid #ef444430"},children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("div",{style:{flex:1},children:[e.jsx("div",{className:"text-sm font-semibold",style:{color:"#ef4444",marginBottom:4},children:m.includes("401")?"🔑 Authentication failed":m.includes("429")?"⏳ Rate limit hit":m.includes("No provider")?"⚙️ No provider configured":"❌ Generation failed"}),e.jsx("div",{className:"text-xs",style:{color:"#888"},children:m})]}),e.jsx("button",{type:"button",onClick:()=>{x(null),ut()},className:"text-xs px-3 py-1.5 rounded border-none cursor-pointer",style:{background:"#ef4444",color:"#fff",fontWeight:600,flexShrink:0},children:"Retry"})]})}),g&&e.jsx("div",{className:"mt-3 p-4 rounded",style:{background:"#f0fdf4",border:"1px solid #bbf7d0"},children:e.jsxs("div",{className:"text-sm text-green-800",children:[e.jsxs("div",{className:"font-semibold mb-2",children:['✅ Agent "',g.agentMeta.name,'" generated successfully!']}),e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsxs("div",{children:["• ",g.workflowSteps?.length||0," workflow steps configured"]}),e.jsxs("div",{children:["• ",g.skillIds?.length||0," skills selected"]}),e.jsxs("div",{children:["• ",g.mcpServerIds?.length||0," MCP tools configured"]}),g.knowledgeGaps&&g.knowledgeGaps.length>0&&e.jsxs("div",{children:["• ",g.knowledgeGaps.length," knowledge gap",g.knowledgeGaps.length!==1?"s":""," identified"]})]}),e.jsx("div",{className:"mt-2 text-xs text-green-600",children:"Advancing to next tab..."})]})})]}),e.jsx("div",{className:"rounded-lg p-5 bg-surface border border-border",style:W,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ht,{size:16,style:U}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-sm mb-2 m-0",style:{color:o.textPrimary},children:"Writing Tips"}),e.jsxs("ul",{className:"text-sm space-y-1",style:{color:o.textSecondary},children:[e.jsx("li",{children:"• Be specific about the agent's role and responsibilities"}),e.jsx("li",{children:"• Mention the types of inputs and outputs you expect"}),e.jsx("li",{children:"• Include any domain expertise or specialized knowledge required"}),e.jsx("li",{children:"• Describe the tone and communication style you want"}),e.jsx("li",{children:"• Note any constraints or limitations the agent should respect"})]})]})]})})]})}const Vr=24,Qr=88,Zr={position:"fixed",bottom:Qr,right:Vr,height:44,borderRadius:22,background:"#FE5000",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:8,paddingLeft:16,paddingRight:16,zIndex:50,transition:"all 0.2s ease",boxShadow:"0 4px 12px rgba(254, 80, 0, 0.3), 0 2px 4px rgba(0, 0, 0, 0.1)"};function Xr({onClick:t,isVisible:s}){const n=q();return s?e.jsxs("button",{type:"button","aria-label":"Test Agent — switch to Test tab",title:"Test Agent",onClick:t,style:Zr,onMouseEnter:o=>{o.currentTarget.style.transform="scale(1.05)",o.currentTarget.style.boxShadow="0 6px 16px rgba(254, 80, 0, 0.4), 0 2px 4px rgba(0, 0, 0, 0.1)"},onMouseLeave:o=>{o.currentTarget.style.transform="scale(1)",o.currentTarget.style.boxShadow="0 4px 12px rgba(254, 80, 0, 0.3), 0 2px 4px rgba(0, 0, 0, 0.1)"},onFocus:o=>{o.currentTarget.style.outline=`2px solid ${n.isDark?"#FF6B1A":"#FE5000"}`,o.currentTarget.style.outlineOffset="2px"},onBlur:o=>{o.currentTarget.style.outline="none"},children:[e.jsx(fn,{size:18,color:"#fff","aria-hidden":"true"}),e.jsx("span",{style:{color:"#fff",fontWeight:600,fontSize:13,fontFamily:"'Geist Sans', sans-serif",letterSpacing:"0.02em"},children:"Test Agent"})]}):null}const ea=h.lazy(()=>fe(()=>import("./TestTab-CLKRT63X.js"),__vite__mapDeps([3,2,4,1,0,5,6])).then(t=>({default:t.TestTab}))),ta=h.lazy(()=>fe(()=>import("./QualificationTab-Dm9dEIpM.js"),__vite__mapDeps([7,2,0,1,8,9,5])).then(t=>({default:t.QualificationTab}))),sa=h.lazy(()=>fe(()=>import("./KnowledgeTab-BccWz7Np.js").then(t=>t.K),__vite__mapDeps([10,0,1,2,5])).then(t=>({default:t.KnowledgeTab}))),na=h.lazy(()=>fe(()=>import("./ToolsTab-xumi9Uds.js"),__vite__mapDeps([11,2,0,1,5])).then(t=>({default:t.ToolsTab}))),oa=h.lazy(()=>fe(()=>import("./MemoryTab-Y_66cE01.js"),__vite__mapDeps([12,2,0,1,9,13,5])).then(t=>({default:t.MemoryTab}))),ra=h.lazy(()=>fe(()=>import("./ReviewTab-BrfXSyyf.js"),__vite__mapDeps([14,2,0,1,4,8,9,5,13])).then(t=>({default:t.ReviewTab}))),V=[{id:"describe",label:"Describe",icon:Be,component:et},{id:"knowledge",label:"Knowledge",icon:nt,component:sa},{id:"tools",label:"Tools",icon:Ot,component:na},{id:"memory",label:"Memory",icon:st,component:oa},{id:"review",label:"Review",icon:hn,component:ra},{id:"test",label:"Test",icon:Pt,component:ea},{id:"qualification",label:"Qualification",icon:gn,component:ta}],aa=1024;function ia(){const t=q();return e.jsx("div",{className:"flex items-center justify-center h-32",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ls,{size:"md"}),e.jsx("span",{style:{color:t.textSecondary},children:"Loading..."})]})})}function la(){const t=q(),s=I(v=>v.prompt.length),n=I(v=>v.channels.length),o=I(v=>v.mcpServers.length),r=I(v=>v.skills.length),a=I(v=>v.agentMeta.name),i=Ee(v=>v.session.strategy),l=Ee(v=>v.facts.length),c=Ee(v=>v.longTerm.enabled),u=Ee(v=>v.working.content),[d,p]=h.useState("describe"),[j,w]=h.useState(!1),[y,S]=h.useState(!1),E=h.useRef([]),C=h.useRef(null),k=h.useRef(null),m=V.find(v=>v.id===d)?.component||et,x=V.findIndex(v=>v.id===d),g=()=>{const v=k.current;if(!v)return;const{scrollLeft:K,scrollWidth:b,clientWidth:P}=v;w(K>0),S(K<b-P-1)};h.useEffect(()=>{const v=()=>{if(window.innerWidth>=aa){w(!1),S(!1);return}g()};return v(),window.addEventListener("resize",v),()=>window.removeEventListener("resize",v)},[]),h.useEffect(()=>{if(C.current){const v=C.current.querySelector("[data-skip-target]"),K=C.current.querySelector("h2, h3, h4"),b=v||K||C.current;b&&b.focus()}},[d]),h.useEffect(()=>{const v=localStorage.getItem("mcp-oauth-completed"),K=localStorage.getItem("mcp-oauth-return-tab");v==="true"&&K&&V.some(b=>b.id===K)&&(p(K),localStorage.removeItem("mcp-oauth-completed"),localStorage.removeItem("mcp-oauth-return-tab"))},[]);const R=()=>{x<V.length-1&&p(V[x+1].id)},M=()=>{x>0&&p(V[x-1].id)},L=()=>{p("test"),setTimeout(()=>{const v=["[data-test-chat-input]",'textarea[placeholder*="message"]','input[placeholder*="message"]','textarea[placeholder*="chat"]','input[placeholder*="chat"]',"textarea",'input[type="text"]'];for(const K of v){const b=document.querySelector(K);if(b){b.focus();break}}},100)},O=(v,K)=>{switch(v.key){case"ArrowLeft":{v.preventDefault();const b=K===0?V.length-1:K-1;E.current[b]?.focus(),p(V[b].id);break}case"ArrowRight":{v.preventDefault();const b=K===V.length-1?0:K+1;E.current[b]?.focus(),p(V[b].id);break}case"Home":v.preventDefault(),E.current[0]?.focus(),p(V[0].id);break;case"End":{v.preventDefault();const b=V.length-1;E.current[b]?.focus(),p(V[b].id);break}}},_=(v,K)=>K&&v==="#FE5000"?"#FF6B1A":v,$=v=>{switch(v){case"describe":return s>20;case"knowledge":return n>0;case"tools":return o>0||r>0;case"memory":return i!=="summarize_and_recent"||l>0||c||u.length>0;case"review":return a!==""&&a.length>0;default:return!1}},G={left:{background:`linear-gradient(to right, ${t.surface} 0%, transparent 100%)`},right:{background:`linear-gradient(to left, ${t.surface} 0%, transparent 100%)`}};return e.jsxs("div",{role:"main",className:"flex-1 flex flex-col overflow-hidden min-h-0",style:{background:t.bg},children:[e.jsx("a",{href:"#main-content",className:"sr-only focus:not-sr-only focus:absolute focus:top-4 focus:left-4 focus:z-50 focus:px-3 focus:py-2 focus:rounded",style:{background:t.surface,color:t.textPrimary,textDecoration:"none",outline:`2px solid ${_("#FE5000",t.isDark)}`},children:"Skip to main content"}),e.jsxs("nav",{"aria-label":"Agent wizard steps",className:"relative flex border-b shrink-0",style:{background:t.surface,borderColor:t.border},children:[j&&e.jsx("div",{className:"absolute left-0 top-0 bottom-0 w-8 pointer-events-none z-10",style:G.left,"aria-hidden":"true"}),y&&e.jsx("div",{className:"absolute right-0 top-0 bottom-0 w-8 pointer-events-none z-10",style:G.right,"aria-hidden":"true"}),e.jsx("div",{ref:k,role:"tablist",className:"flex w-full overflow-x-auto lg:overflow-x-visible tab-scrollbar-hidden",onScroll:g,children:V.map((v,K)=>{const b=v.icon,P=v.id===d,T=K<x,F=$(v.id),z=_("#FE5000",t.isDark),A=N=>{switch(N){case"describe":return"Define your agent";case"knowledge":return"Add data sources";case"tools":return"Select capabilities";case"memory":return"Configure memory";case"review":return"Review and edit";case"test":return"Test and debug";case"qualification":return"Export and deploy";default:return v.label}};return e.jsxs("button",{ref:N=>{E.current[K]=N},type:"button",role:"tab","aria-selected":P,"aria-controls":`tabpanel-${v.id}`,tabIndex:P?0:-1,onClick:()=>p(v.id),onKeyDown:N=>O(N,K),title:A(v.id),className:"flex items-center gap-2 px-6 py-4 text-sm font-medium border-none cursor-pointer transition-colors min-h-[44px] whitespace-nowrap",style:{background:"transparent",color:P?z:t.textSecondary,borderBottom:P?`2px solid ${z}`:"2px solid transparent"},onMouseEnter:N=>{P||(N.currentTarget.style.color=z,N.currentTarget.style.background=t.isDark?"#FE500010":"#FE500005")},onMouseLeave:N=>{P||(N.currentTarget.style.color=t.textSecondary,N.currentTarget.style.background="transparent")},onFocus:N=>{P||(N.currentTarget.style.color=z,N.currentTarget.style.background=t.isDark?"#FE500010":"#FE500005")},onBlur:N=>{P||(N.currentTarget.style.color=t.textSecondary,N.currentTarget.style.background="transparent")},children:[e.jsx(b,{size:16,style:{color:T?"#2ecc71":P?z:t.textDim},"aria-hidden":"true"}),e.jsx("span",{style:{fontFamily:"'Geist Sans', sans-serif"},children:v.label}),F&&e.jsx(ee,{size:12,style:{color:"#2ecc71"},"aria-hidden":"true"}),e.jsxs("span",{className:"sr-only",children:[P&&", selected",T&&", completed",F&&", task completed",". Use arrow keys to navigate tabs."]})]},v.id)})})]}),e.jsx("div",{ref:C,id:"main-content",role:"tabpanel","aria-labelledby":`tab-${d}`,tabIndex:0,className:`flex-1 min-h-0 focus:outline-none ${d==="test"?"overflow-hidden":"overflow-y-auto"}`,"data-skip-target":!0,children:e.jsxs("div",{className:d==="test"?"h-full":"w-full max-w-screen-2xl mx-auto px-4 sm:px-6 lg:px-8 xl:px-12 py-6 pb-16",children:[e.jsx(Ko,{}),e.jsx(Wo,{label:d,children:e.jsx(h.Suspense,{fallback:e.jsx(ia,{}),children:d==="describe"?e.jsx(et,{onNavigateToNext:R,onNavigateToKnowledge:()=>p("knowledge")}):e.jsx(m,{})})},d)]})}),x>0&&e.jsx("button",{type:"button",onClick:M,"aria-label":`Go to previous step: ${V[x-1].label}`,className:"fixed flex items-center justify-center w-10 h-10 rounded-full border-none cursor-pointer transition-all duration-200",style:{position:"fixed",left:"16px",top:"50%",transform:"translateY(-50%)",zIndex:30,background:t.isDark?`${t.surface}CC`:`${t.surface}CC`,color:t.textPrimary,boxShadow:"0 4px 12px rgba(0,0,0,0.1)"},onMouseEnter:v=>{v.currentTarget.style.background=t.isDark?`${t.surface}E6`:`${t.surface}E6`,v.currentTarget.style.transform="translateY(-50%) scale(1.05)"},onMouseLeave:v=>{v.currentTarget.style.background=t.isDark?`${t.surface}CC`:`${t.surface}CC`,v.currentTarget.style.transform="translateY(-50%) scale(1)"},onFocus:v=>{v.currentTarget.style.background=t.isDark?`${t.surface}E6`:`${t.surface}E6`,v.currentTarget.style.transform="translateY(-50%) scale(1.05)"},onBlur:v=>{v.currentTarget.style.background=t.isDark?`${t.surface}CC`:`${t.surface}CC`,v.currentTarget.style.transform="translateY(-50%) scale(1)"},title:`Previous: ${V[x-1].label}`,children:e.jsx(xn,{size:20})}),x<V.length-1&&e.jsx("button",{type:"button",onClick:R,"aria-label":`Go to next step: ${V[x+1].label}`,className:"fixed flex items-center justify-center w-10 h-10 rounded-full border-none cursor-pointer transition-all duration-200",style:{position:"fixed",right:"16px",top:"50%",transform:"translateY(-50%)",zIndex:30,background:t.isDark?`${t.surface}CC`:`${t.surface}CC`,color:t.textPrimary,boxShadow:"0 4px 12px rgba(0,0,0,0.1)"},onMouseEnter:v=>{v.currentTarget.style.background=t.isDark?`${t.surface}E6`:`${t.surface}E6`,v.currentTarget.style.transform="translateY(-50%) scale(1.05)"},onMouseLeave:v=>{v.currentTarget.style.background=t.isDark?`${t.surface}CC`:`${t.surface}CC`,v.currentTarget.style.transform="translateY(-50%) scale(1)"},onFocus:v=>{v.currentTarget.style.background=t.isDark?`${t.surface}E6`:`${t.surface}E6`,v.currentTarget.style.transform="translateY(-50%) scale(1.05)"},onBlur:v=>{v.currentTarget.style.background=t.isDark?`${t.surface}CC`:`${t.surface}CC`,v.currentTarget.style.transform="translateY(-50%) scale(1)"},title:`Next: ${V[x+1].label}`,children:e.jsx(Oe,{size:20})}),e.jsx(Xr,{onClick:L,isVisible:d!=="test"})]})}const ps=Ne(t=>({toasts:[],addToast:(s,n="info")=>{const o=`toast-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;return t(r=>({toasts:[...r.toasts,{id:o,type:n,message:s}]})),setTimeout(()=>{t(r=>({toasts:r.toasts.filter(a=>a.id!==o)}))},5e3),o},removeToast:s=>t(n=>({toasts:n.toasts.filter(o=>o.id!==s)}))})),ca={success:e.jsx(Ce,{size:16}),error:e.jsx(bn,{size:16}),warning:e.jsx(Vt,{size:16}),info:e.jsx(yn,{size:16})},da={success:{bg:"rgba(22,163,74,0.12)",border:"rgba(22,163,74,0.4)",icon:"#16a34a"},error:{bg:"rgba(220,38,38,0.12)",border:"rgba(220,38,38,0.4)",icon:"#dc2626"},warning:{bg:"rgba(234,179,8,0.12)",border:"rgba(234,179,8,0.4)",icon:"#ca8a04"},info:{bg:"rgba(59,130,246,0.12)",border:"rgba(59,130,246,0.4)",icon:"#3b82f6"}};function ua({toast:t}){const s=ps(o=>o.removeToast),n=da[t.type];return e.jsxs("div",{role:"alert","aria-live":"assertive",className:"flex items-start gap-3 px-4 py-3 rounded-lg text-[13px] font-medium shadow-lg",style:{background:n.bg,border:`1px solid ${n.border}`,color:"#f0f0f0",minWidth:240,maxWidth:380,backdropFilter:"blur(8px)"},children:[e.jsx("span",{style:{color:n.icon,flexShrink:0,marginTop:1},children:ca[t.type]}),e.jsx("span",{className:"flex-1 leading-snug",children:t.message}),e.jsx("button",{type:"button",onClick:()=>s(t.id),"aria-label":"Dismiss notification",className:"flex items-center justify-center w-5 h-5 rounded cursor-pointer border-none bg-transparent shrink-0 opacity-60 hover:opacity-100",style:{color:"#f0f0f0"},children:e.jsx(ae,{size:12})})]})}function pa(){const t=ps(s=>s.toasts);return t.length===0?null:e.jsx("div",{"aria-label":"Notifications",className:"fixed bottom-4 right-4 flex flex-col gap-2",style:{zIndex:9999},children:t.map(s=>e.jsx(ua,{toast:s},s.id))})}function ma(){const t=q(),[s,n]=h.useState("library"),o=I(x=>x.showFilePicker),r=I(x=>x.setShowFilePicker),a=I(x=>x.setShowSkillPicker),i=I(x=>x.setShowConnectionPicker),l=I(x=>x.setShowMarketplace),c=I(x=>x.run),u=I(x=>x.running),d=I(x=>x.showSettings),p=I(x=>x.setShowSettings),j=Q(x=>x.loadServers),w=I(x=>x.loadAgent),y=ie(x=>x.saveStatus),S=h.useRef(null),E=h.useCallback(x=>{const g=x.target.files?.[0];if(!g)return;const R=new FileReader;R.onload=M=>{const L=M.target?.result;if(!L)return;const O=Po(L),_=I.getState();if(O.channels){_.clearChannels();for(const $ of O.channels)_.addChannel($)}O.selectedModel&&_.setModel(O.selectedModel),O.outputFormat&&_.setOutputFormat(O.outputFormat),O.prompt&&_.setPrompt(O.prompt),O.tokenBudget&&_.setTokenBudget(O.tokenBudget),O.agentMeta&&_.setAgentMeta(O.agentMeta),O.instructionState&&_.setInstructionState(O.instructionState),O.workflowSteps&&_.setWorkflowSteps(O.workflowSteps)},R.readAsText(g),x.target.value=""},[]);h.useEffect(()=>{const x=g=>{(g.metaKey||g.ctrlKey)&&g.key==="k"&&(g.preventDefault(),r(!o)),(g.metaKey||g.ctrlKey)&&g.key==="Enter"&&(g.preventDefault(),u||c()),g.key==="Escape"&&(r(!1),a(!1),i(!1),l(!1),p(!1),I.getState().setShowSaveModal(!1))};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[r,o,a,i,l,c,u]),h.useEffect(()=>{j()},[j]);const C=x=>{w(x),n("editor")},k=()=>{n("editor")},m=()=>{y==="unsaved"&&!window.confirm("You have unsaved changes. Leave anyway?")||n("library")};return e.jsxs("div",{"data-theme":t.isDark?"dark":"light",className:"w-full h-full flex flex-col overflow-hidden",style:{background:t.bg},children:[e.jsx("input",{ref:S,type:"file",accept:".md,.yaml,.yml,.json",onChange:E,style:{display:"none"},"aria-hidden":"true"}),s==="library"?e.jsx(Fo,{onSelectAgent:C,onNewAgent:k}):e.jsxs(e.Fragment,{children:[e.jsx(Dn,{onSettingsClick:()=>p(!0,"providers"),onBack:m,onImport:()=>S.current?.click()}),e.jsx(la,{})]}),e.jsx("div",{"aria-live":"polite",id:"canvas-announcements",style:{position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:"0"}}),e.jsx(Rn,{}),e.jsx(zn,{}),e.jsx(Yn,{}),e.jsx(Xn,{}),e.jsx(to,{}),e.jsx(Jn,{}),e.jsx(lo,{open:d,onClose:()=>p(!1)}),e.jsx(Co,{}),e.jsx(pa,{})]})}hs.createRoot(document.getElementById("root")).render(e.jsx(h.StrictMode,{children:e.jsx(ma,{})}));export{Ve as B,Eo as M,To as S,es as T,qo as a,ge as b,xe as c,is as d,rs as e,dt as f,ya as g,ba as h,bo as i,q as u};
|