modular-studio 1.0.5 → 1.0.6
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/README.md +122 -122
- package/dist/assets/{Badge-22Ai0eyi.js → Badge-DrUmDAXz.js} +1 -1
- package/dist/assets/{Input-Bgp734xs.js → Input-ndEGQSgx.js} +1 -1
- package/dist/assets/KnowledgeTab-CxlC76Rf.js +4 -0
- package/dist/assets/MemoryTab-CUScYWs9.js +16 -0
- package/dist/assets/QualificationTab-BqnWSQHm.js +1 -0
- package/dist/assets/ReviewTab-DKYl6cR9.js +103 -0
- package/dist/assets/{Section-DoJrmytO.js → Section-CgmwAj_2.js} +1 -1
- package/dist/assets/{TestTab-PDyMF8Fw.js → TestTab-iJ2vCf9l.js} +15 -15
- package/dist/assets/ToolsTab-C10Ulm8b.js +1 -0
- package/dist/assets/icons-MKpPNvV8.js +1 -0
- package/dist/assets/index-B_ip7Amg.css +1 -0
- package/dist/assets/index-gBy3427k.js +143 -0
- package/dist/assets/services-CTWXQK6j.js +356 -0
- package/dist/index.html +18 -18
- package/dist-server/server/index.d.ts.map +1 -1
- package/dist-server/server/index.js +4 -0
- package/dist-server/server/mcp/manager.d.ts.map +1 -1
- package/dist-server/server/mcp/manager.js +16 -2
- package/dist-server/server/routes/agents.d.ts.map +1 -1
- package/dist-server/server/routes/agents.js +27 -0
- package/dist-server/server/routes/cache.d.ts +3 -0
- package/dist-server/server/routes/cache.d.ts.map +1 -0
- package/dist-server/server/routes/cache.js +55 -0
- package/dist-server/server/routes/connectors.d.ts.map +1 -1
- package/dist-server/server/routes/connectors.js +47 -17
- package/dist-server/server/routes/lessons.d.ts +3 -0
- package/dist-server/server/routes/lessons.d.ts.map +1 -0
- package/dist-server/server/routes/lessons.js +46 -0
- package/dist-server/server/routes/memory.d.ts.map +1 -1
- package/dist-server/server/routes/memory.js +31 -0
- package/dist-server/server/routes/qualification.d.ts.map +1 -1
- package/dist-server/server/routes/qualification.js +292 -334
- package/dist-server/server/routes/repo-index.d.ts.map +1 -1
- package/dist-server/server/routes/repo-index.js +7 -0
- package/dist-server/server/routes/skills-search.d.ts.map +1 -1
- package/dist-server/server/routes/skills-search.js +182 -26
- package/dist-server/server/services/adapters/hindsightAdapter.d.ts +28 -0
- package/dist-server/server/services/adapters/hindsightAdapter.d.ts.map +1 -0
- package/dist-server/server/services/adapters/hindsightAdapter.js +63 -0
- package/dist-server/server/services/adapters/postgresAdapter.js +30 -30
- package/dist-server/server/services/adapters/sqliteAdapter.js +29 -29
- package/dist-server/server/services/agentStore.d.ts +2 -1
- package/dist-server/server/services/agentStore.d.ts.map +1 -1
- package/dist-server/server/services/agentStore.js +2 -1
- package/dist-server/server/services/correctionDetector.d.ts +22 -0
- package/dist-server/server/services/correctionDetector.d.ts.map +1 -0
- package/dist-server/server/services/correctionDetector.js +91 -0
- package/dist-server/server/services/hindsightClient.d.ts +15 -0
- package/dist-server/server/services/hindsightClient.d.ts.map +1 -0
- package/dist-server/server/services/hindsightClient.js +47 -0
- package/dist-server/server/services/lessonExtractor.d.ts +19 -0
- package/dist-server/server/services/lessonExtractor.d.ts.map +1 -0
- package/dist-server/server/services/lessonExtractor.js +87 -0
- package/dist-server/server/services/responseCache.d.ts +24 -0
- package/dist-server/server/services/responseCache.d.ts.map +1 -0
- package/dist-server/server/services/responseCache.js +163 -0
- package/dist-server/server/services/sqliteStore.d.ts +8 -0
- package/dist-server/server/services/sqliteStore.d.ts.map +1 -1
- package/dist-server/server/services/sqliteStore.js +53 -13
- package/dist-server/src/store/knowledgeBase.d.ts +1 -0
- package/dist-server/src/store/knowledgeBase.d.ts.map +1 -1
- package/dist-server/src/store/lessonStore.d.ts +26 -0
- package/dist-server/src/store/lessonStore.d.ts.map +1 -0
- package/dist-server/src/store/lessonStore.js +64 -0
- package/dist-server/src/store/memoryStore.d.ts +12 -1
- package/dist-server/src/store/memoryStore.d.ts.map +1 -1
- package/dist-server/src/store/memoryStore.js +9 -0
- package/dist-server/tsconfig.server.tsbuildinfo +1 -1
- package/package.json +105 -104
- package/dist/assets/KnowledgeTab-DABxirZh.js +0 -4
- package/dist/assets/MemoryTab-DZeYElIT.js +0 -16
- package/dist/assets/QualificationTab-Dfpy3J30.js +0 -1
- package/dist/assets/ReviewTab-SD8lQuCc.js +0 -103
- package/dist/assets/ToolsTab-B83qGCmG.js +0 -1
- package/dist/assets/icons-C2EV-le6.js +0 -1
- package/dist/assets/index-DkpMAxX7.css +0 -1
- package/dist/assets/index-q24ug5Qs.js +0 -143
- package/dist/assets/services-BaKotDf0.js +0 -343
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/conversationStore-CkfEU2eV.js","assets/stores-CeKWz7ou.js","assets/vendor-D1h_O76p.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{c as j,p as mn}from"./stores-CeKWz7ou.js";const gn="modulepreload",hn=function(t){return"/"+t},et={},se=function(o,e,n){let s=Promise.resolve();if(e&&e.length>0){let c=function(l){return Promise.all(l.map(d=>Promise.resolve(d).then(m=>({status:"fulfilled",value:m}),m=>({status:"rejected",reason:m}))))};document.getElementsByTagName("link");const r=document.querySelector("meta[property=csp-nonce]"),i=r?.nonce||r?.getAttribute("nonce");s=c(e.map(l=>{if(l=hn(l),l in et)return;et[l]=!0;const d=l.endsWith(".css"),m=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${m}`))return;const u=document.createElement("link");if(u.rel=d?"stylesheet":gn,d||(u.as="script"),u.crossOrigin="",u.href=l,i&&u.setAttribute("nonce",i),document.head.appendChild(u),d)return new Promise((p,g)=>{u.addEventListener("load",p),u.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${l}`)))})}))}function a(r){const i=new Event("vite:preloadError",{cancelable:!0});if(i.payload=r,window.dispatchEvent(i),!i.defaultPrevented)throw r}return s.then(r=>{for(const i of r||[])i.status==="rejected"&&a(i.reason);return o().catch(a)})},We={"ground-truth":{label:"Ground Truth",color:"#e74c3c",icon:"🔴",instruction:"Do not contradict this."},signal:{label:"Signal",color:"#f1c40f",icon:"🟡",instruction:"Interpret — look for the underlying need, not the surface request."},evidence:{label:"Evidence",color:"#3498db",icon:"🔵",instruction:"Cite and weigh against other evidence."},framework:{label:"Framework",color:"#2ecc71",icon:"🟢",instruction:"Use to structure thinking, but not as immutable."},hypothesis:{label:"Hypothesis",color:"#9b59b6",icon:"🟣",instruction:"Help validate or invalidate with evidence and signals."},guideline:{label:"Guideline",color:"#FE5000",icon:"📏",instruction:"Extract and enforce as constraints, workflow rules, and output formatting."}},fn=[[["signal","feedback","user feedback"],"signal"],[["discovery","_temp_"],"hypothesis"],[["roadmap","plans/","plan/"],"framework"],[["intel","competitors","competitive","research","savings-analysis"],"evidence"],[["cmo-handoff","release","demo","newsletter"],"evidence"],[["sales prep","event prep","executive profiler"],"framework"],[["guidelines","contributing","code-style","coding-standards","engineering-rules"],"guideline"],[["products"],"ground-truth",["feedback"]],[["clients/"],"ground-truth",["feedback"]],[["companies"],"evidence"],[["voyage-preparation","navarea-map"],"ground-truth"]],yn=[{patterns:[/^#{1,2}\s*(spec|specification|schema|api|contract|definition|interface)/mi,/\b(MUST|SHALL|REQUIRED)\b/g,/```(json|yaml|graphql|proto|sql)\b/g,/\b(version|v\d+\.\d+)/gi],type:"ground-truth",weight:10,minMatches:2},{patterns:[/\b(user said|customer|feedback|interview|request(ed)?|pain point|frustrat|complain|asked for|wants? to|need(s|ed)?)\b/gi,/\b(nps|csat|satisfaction|churn|retention)\b/gi,/[""][^""]{10,}[""]/g,/\b(quote|verbatim)\b/gi],type:"signal",weight:8,minMatches:2},{patterns:[/\b(analysis|benchmark|comparison|metric|kpi|data|report|finding|result|measured|observed)\b/gi,/\d+(\.\d+)?%/g,/\b(increase|decrease|growth|decline|trend)\b/gi,/\|\s*\w+\s*\|/g],type:"evidence",weight:7,minMatches:2},{patterns:[/\b(framework|methodology|process|template|playbook|checklist|step \d|phase \d|stage \d)\b/gi,/\b(when to|how to|best practice|guideline|principle|pattern)\b/gi,/^\s*[-*]\s*\[[ x]\]/gm,/\b(input|output|trigger|criteria)\b/gi],type:"framework",weight:6,minMatches:2},{patterns:[/\b(hypothesis|proposal|rfc|suggest(ion)?|idea|explore|what if|could we|might|experiment|assumption|validate)\b/gi,/\b(pro(s)?|con(s)?|trade-?off|risk|upside|downside)\b/gi,/\b(option [a-c]|alternative|approach \d)\b/gi],type:"hypothesis",weight:5,minMatches:2},{patterns:[/\b(MUST|SHALL|NEVER|ALWAYS|REQUIRED|FORBIDDEN|DO NOT)\b/g,/\b(convention|standard|guideline|rule|policy|style guide|best practice|coding standard)\b/gi,/\b(naming|branch|commit|pr|pull request)\s*(convention|format|rule|pattern)/gi,/\b(linting|formatting|eslint|prettier|editorconfig)\b/gi],type:"guideline",weight:8,minMatches:2}],kn=[{test:(t,o)=>o==="ground-truth",depth:0},{test:(t,o)=>o==="signal",depth:0},{test:t=>t.length<2e3,depth:0},{test:(t,o)=>o==="hypothesis",depth:1},{test:(t,o)=>o==="evidence"&&t.length>8e3,depth:2},{test:(t,o)=>o==="evidence",depth:1},{test:(t,o)=>o==="framework"&&t.length>8e3,depth:2},{test:(t,o)=>o==="framework",depth:1},{test:(t,o)=>o==="guideline",depth:0}];function wn(t,o){return Le(t,o).knowledgeType}function Le(t,o){const e=t.toLowerCase();for(const[a,r,i]of fn)if(a.some(c=>e.includes(c))){if(i&&i.some(l=>e.includes(l)))continue;const c=ke(o||"",r);return{knowledgeType:r,depth:c,confidence:"high",reason:`Path matches "${a.find(l=>e.includes(l))}"`}}if(o&&o.length>50){const a=[];for(const r of yn){let i=0,c=0;for(const d of r.patterns){d.lastIndex=0;const m=o.match(d);m&&m.length>0&&(c++,i+=m.length)}const l=r.minMatches??1;c>=l&&a.push({type:r.type,score:i*r.weight,matches:c})}if(a.length>0){a.sort((l,d)=>d.score-l.score);const r=a[0],i=r.score>30?"high":r.score>10?"medium":"low",c=ke(o,r.type);return{knowledgeType:r.type,depth:c,confidence:i,reason:`Content analysis: ${r.matches} pattern groups, score ${r.score}`}}}const n=t.split(".").pop()?.toLowerCase();if(n){const a={json:"ground-truth",yaml:"ground-truth",yml:"ground-truth",toml:"ground-truth",sql:"ground-truth",graphql:"ground-truth",proto:"ground-truth",csv:"evidence",tsv:"evidence",xlsx:"evidence",py:"guideline",ts:"guideline",js:"guideline",tsx:"guideline",jsx:"guideline",log:"guideline",txt:"evidence"};if(a[n]){const r=ke(o||"",a[n]);return{knowledgeType:a[n],depth:r,confidence:"low",reason:`File extension .${n}`}}}return{knowledgeType:"evidence",depth:ke(o||"","evidence"),confidence:"low",reason:"Default"}}function ke(t,o){for(const e of kn)if(e.test(t,o))return e.depth;return 1}const Ca=[{id:"markdown",label:"Markdown",icon:"📝",ext:".md"},{id:"html-slides",label:"HTML Slides",icon:"🎯",ext:".html"},{id:"email",label:"Email Draft",icon:"✉️",ext:""},{id:"code",label:"Code",icon:"💻",ext:".py"},{id:"csv",label:"Data Table",icon:"📊",ext:".csv"},{id:"json",label:"JSON",icon:"{}",ext:".json"},{id:"diagram",label:"Diagram",icon:"🔀",ext:".svg"},{id:"slack",label:"Slack Post",icon:"💬",ext:""}];function bn(t){const o=t.toLowerCase();return o.includes("slide")||o.includes("presentation")||o.includes("pitch")||o.includes("deck")?"html-slides":o.includes("email")||o.includes("draft")||o.includes("send to")?"email":o.includes("script")||o.includes("function")||o.includes("code")||o.includes("implement")?"code":o.includes("table")||o.includes("csv")||o.includes("spreadsheet")||o.includes("data")?"csv":o.includes("json")||o.includes("api")||o.includes("schema")?"json":o.includes("diagram")||o.includes("flowchart")||o.includes("architecture")?"diagram":o.includes("slack")||o.includes("post in")?"slack":"markdown"}const Te=[{label:"Full",pct:1},{label:"Detail",pct:.75},{label:"Summary",pct:.5},{label:"Headlines",pct:.25},{label:"Mention",pct:.1}],Aa=10,Pa=100,Ea=10,tt={model:"claude-opus-4",temperature:.7,systemPrompt:"",planningMode:"single-shot",maxTokens:4096};function x(t,o,e,n,s,a=0){return{sourceId:t,name:o,path:e,category:n,knowledgeType:wn(e),depth:a,baseTokens:s}}const vn=[{id:"senior-pm",name:"Senior PM",agentConfig:{model:"claude-opus-4",temperature:.5,planningMode:"chain-of-thought",maxTokens:8192},channels:[x("knowledge-products","Products","00 - Knowledge/Products/","knowledge",16e3,0),x("knowledge-products-feedback","Feedback","00 - Knowledge/Products/Feedback/","knowledge",4800,0),x("signals-odfjell","User feedback / Odfjell","07 - Signals/User feedback/odfjell/","intel",6800,1),x("signals-kcc","User feedback / KCC","07 - Signals/User feedback/kcc/","intel",5200,1),x("signals-general","User feedback / General","07 - Signals/User feedback/general/","intel",7500,1),x("discovery-eu-ets","EU ETS Cost Layer","01 - Discovery/EU ETS Cost Layer/","discovery",3200,2),x("discovery-weather-routing","Weather Routing v2","01 - Discovery/Weather Routing v2/","discovery",4100,2),x("discovery-fleet-dashboard","Fleet Dashboard","01 - Discovery/Fleet Dashboard/","discovery",3500,2),x("roadmap","03 - Roadmap","03 - Roadmap/","knowledge",12e3,1)]},{id:"competitive-intel",name:"Competitive Intel",agentConfig:{model:"claude-opus-4",temperature:.3,planningMode:"react",maxTokens:8192},channels:[x("knowledge-competitors","Competitors","00 - Knowledge/Competitors/","knowledge",22e3,0),x("knowledge-competitors-stormgeo","StormGeo","00 - Knowledge/Competitors/Features/stormgeo/","knowledge",4500,0),x("knowledge-competitors-dtn","DTN","00 - Knowledge/Competitors/Features/dtn/","knowledge",3800,0),x("knowledge-competitors-sofar","Sofar","00 - Knowledge/Competitors/Features/sofar/","knowledge",3200,0),x("knowledge-competitors-wni","WNI","00 - Knowledge/Competitors/Features/wni/","knowledge",3600,0),x("cmo-competitive-intel","05 - Competitive Intel","CMO-Handoff/05 - Competitive Intel/","intel",5800,1),x("intel-competitive","01 - Competitive Intel","05 - Intel/01 - Competitive Intel/","intel",12e3,0)]},{id:"company-intel",name:"Company Intel",channels:[x("knowledge-companies","Companies","00 - Knowledge/Companies/","knowledge",14e3,0),x("cmo-company-profiles","01 - Company Profiles","CMO-Handoff/01 - Company Profiles/","knowledge",28e3,0),x("cmo-charter-structures","02 - Charter Structures","CMO-Handoff/02 - Charter Structures/","knowledge",8500,1)]},{id:"feedback-manager",name:"Feedback Manager",agentConfig:{model:"claude-sonnet-4",temperature:.4,planningMode:"chain-of-thought",maxTokens:4096},channels:[x("knowledge-products-feedback","Feedback","00 - Knowledge/Products/Feedback/","knowledge",4800,0),x("signals-odfjell","User feedback / Odfjell","07 - Signals/User feedback/odfjell/","intel",6800,0),x("signals-kcc","User feedback / KCC","07 - Signals/User feedback/kcc/","intel",5200,0),x("signals-baru","User feedback / Baru","07 - Signals/User feedback/baru/","intel",4500,0),x("signals-general","User feedback / General","07 - Signals/User feedback/general/","intel",7500,0),x("intel-feedback","04 - Feedback Synthesis","05 - Intel/04 - Feedback Synthesis/","intel",4800,1)]},{id:"odfjell-deep-dive",name:"Odfjell Deep Dive",channels:[x("odfjell-savings","odfjell-savings-analysis","odfjell-savings-analysis/","intel",14e3,0),x("knowledge-clients-odfjell","Odfjell","00 - Knowledge/Clients/odfjell/","knowledge",4200,0),x("signals-odfjell","User feedback / Odfjell","07 - Signals/User feedback/odfjell/","intel",6800,0),x("cmo-charter-structures","02 - Charter Structures","CMO-Handoff/02 - Charter Structures/","knowledge",8500,1),x("knowledge-competitors-stormgeo","StormGeo","00 - Knowledge/Competitors/Features/stormgeo/","knowledge",4500,2)]},{id:"voyage-prep-dev",name:"Voyage Prep Dev",channels:[x("voyage-prep","voyage-preparation","voyage-preparation/","discovery",18e3,0),x("temp-voyage","_temp_voyage-briefing","_temp_voyage-briefing/","discovery",6400,0),x("discovery-weather-routing","Weather Routing v2","01 - Discovery/Weather Routing v2/","discovery",4100,1),x("knowledge-products-nr","Navigation Reports","00 - Knowledge/Products/NR/","knowledge",8200,1)]},{id:"event-prep",name:"Event Prep",channels:[x("sales-prep-events","Event Prep","06 - Sales Prep/Event Prep/","agents",9500,0),x("sales-prep-exec","Executive Profiler","06 - Sales Prep/Executive Profiler/","agents",8500,0),x("cmo-event-prep","07 - Event Prep Profiles","CMO-Handoff/07 - Event Prep Profiles/","agents",3500,0),x("cmo-company-profiles","01 - Company Profiles","CMO-Handoff/01 - Company Profiles/","knowledge",28e3,2)]},{id:"maritime-intel",name:"Maritime Intel",channels:[x("intel-maritime","02 - Maritime Intel","05 - Intel/02 - Maritime Intel/","intel",14e3,0),x("navarea-map","navarea-map","navarea-map/","intel",11e3,0),x("intel-research","03 - Research","05 - Intel/03 - Research/","intel",7200,1)]},{id:"discovery-all",name:"Discovery",channels:[x("discovery-eu-ets","EU ETS Cost Layer","01 - Discovery/EU ETS Cost Layer/","discovery",3200,0),x("discovery-weather-routing","Weather Routing v2","01 - Discovery/Weather Routing v2/","discovery",4100,0),x("discovery-cii-monitor","CII Monitor","01 - Discovery/CII Monitor/","discovery",2800,0),x("discovery-fleet-dashboard","Fleet Dashboard","01 - Discovery/Fleet Dashboard/","discovery",3500,0),x("discovery-voyage-compare","Voyage Compare","01 - Discovery/Voyage Compare/","discovery",2600,0),x("discovery-port-insights","Port Insights","01 - Discovery/Port Insights/","discovery",2200,0),x("discovery-api-v2","API v2","01 - Discovery/API v2/","discovery",3800,0),x("discovery-alerts-engine","Alerts Engine","01 - Discovery/Alerts Engine/","discovery",2400,0),x("discovery-bunker-opt","Bunker Optimization","01 - Discovery/Bunker Optimization/","discovery",3100,0),x("discovery-cargo-tracking","Cargo Tracking","01 - Discovery/Cargo Tracking/","discovery",2700,0)]},{id:"all-knowledge",name:"All Knowledge",channels:[x("knowledge","00 - Knowledge","00 - Knowledge/","knowledge",82e3,2),x("knowledge-clients","Clients","00 - Knowledge/Clients/","knowledge",18e3,1),x("knowledge-companies","Companies","00 - Knowledge/Companies/","knowledge",14e3,1),x("knowledge-competitors","Competitors","00 - Knowledge/Competitors/","knowledge",22e3,1),x("knowledge-products","Products","00 - Knowledge/Products/","knowledge",16e3,0),x("knowledge-market","Market","00 - Knowledge/Market/","knowledge",6500,2),x("knowledge-users","Users","00 - Knowledge/Users/","knowledge",5500,2)]}],St=[{id:"mcp-filesystem",name:"Filesystem",npmPackage:"@modelcontextprotocol/server-filesystem",description:"Read, write, and manage local files with configurable access controls",icon:"folder",category:"coding",author:"MCP Official",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","@modelcontextprotocol/server-filesystem"],configFields:[{key:"ALLOWED_DIRS",label:"Allowed Directories (comma-separated)",type:"text",placeholder:"/home/user/projects,/tmp",required:!0}],repo:"https://github.com/modelcontextprotocol/servers",tags:["files","local","read","write"],authMethod:"none"},{id:"mcp-memory",name:"Memory (Knowledge Graph)",npmPackage:"@modelcontextprotocol/server-memory",description:"Persistent knowledge graph memory for agent state and relationships",icon:"brain",category:"data",author:"MCP Official",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","@modelcontextprotocol/server-memory"],configFields:[],repo:"https://github.com/modelcontextprotocol/servers",tags:["memory","knowledge-graph","state","persistence"],authMethod:"none"},{id:"mcp-fetch",name:"Fetch",npmPackage:"@anthropic-ai/mcp-fetch",description:"Fetch web content and convert to markdown for LLM consumption",icon:"download",category:"research",author:"MCP Official",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","@anthropic-ai/mcp-fetch"],configFields:[],repo:"https://github.com/modelcontextprotocol/servers",tags:["web","fetch","scrape","markdown"],authMethod:"none"},{id:"mcp-git",name:"Git",npmPackage:"@modelcontextprotocol/server-git",description:"Read, search, and manipulate Git repositories - log, diff, blame",icon:"git-branch",category:"coding",author:"MCP Official",transport:"stdio",runtimes:["claude","amp","codex"],command:"uvx",defaultArgs:["mcp-server-git"],configFields:[{key:"GIT_REPO_PATH",label:"Repository Path",type:"text",placeholder:"/path/to/repo",required:!1}],repo:"https://github.com/modelcontextprotocol/servers",tags:["git","version-control","diff","log"],authMethod:"none",installHint:{macos:"brew install uv",linux:"curl -LsSf https://astral.sh/uv/install.sh | sh",windows:"pip install uv"}},{id:"mcp-sequential-thinking",name:"Sequential Thinking",npmPackage:"@modelcontextprotocol/server-sequential-thinking",description:"Dynamic and reflective problem-solving through structured thought sequences",icon:"list-ordered",category:"research",author:"MCP Official",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","@modelcontextprotocol/server-sequential-thinking"],configFields:[],repo:"https://github.com/modelcontextprotocol/servers",tags:["thinking","reasoning","chain-of-thought"],authMethod:"none"},{id:"mcp-time",name:"Time",npmPackage:"@modelcontextprotocol/server-time",description:"Get current time and convert between timezones",icon:"clock",category:"data",author:"MCP Official",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","@modelcontextprotocol/server-time"],configFields:[],repo:"https://github.com/modelcontextprotocol/servers",tags:["time","timezone","date"],authMethod:"none"},{id:"mcp-everything",name:"Everything (Test)",npmPackage:"@modelcontextprotocol/server-everything",description:"Reference test server with prompts, resources, and tools for MCP testing",icon:"star",category:"coding",author:"MCP Official",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","@modelcontextprotocol/server-everything"],configFields:[],repo:"https://github.com/modelcontextprotocol/servers",tags:["test","reference","debug"],authMethod:"none"},{id:"mcp-brave-search",name:"Brave Search",npmPackage:"@modelcontextprotocol/server-brave-search",description:"Web and local search powered by Brave Search API",icon:"search",category:"research",author:"MCP Official",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","@modelcontextprotocol/server-brave-search"],configFields:[{key:"BRAVE_API_KEY",label:"API Key",type:"password",placeholder:"BSA...",required:!0}],website:"https://brave.com/search/api/",tags:["search","web","brave"],authMethod:"api-key"},{id:"mcp-tavily",name:"Tavily Search",npmPackage:"tavily-mcp",description:"AI-optimized search engine with structured results and answer extraction",icon:"search",category:"research",author:"Tavily",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","tavily-mcp"],configFields:[{key:"TAVILY_API_KEY",label:"API Key",type:"password",placeholder:"tvly-...",required:!0}],website:"https://tavily.com",tags:["search","ai-search","research"],authMethod:"api-key"},{id:"mcp-exa",name:"Exa Search",npmPackage:"exa-mcp-server",description:"Neural search engine - find similar content, get page contents",icon:"search",category:"research",author:"Exa",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","exa-mcp-server"],configFields:[{key:"EXA_API_KEY",label:"API Key",type:"password",placeholder:"",required:!0}],website:"https://exa.ai",tags:["search","neural-search","semantic"],authMethod:"api-key"},{id:"mcp-firecrawl",name:"Firecrawl",npmPackage:"firecrawl-mcp",description:"Web scraping and crawling - extract structured data from any website",icon:"flame",category:"research",author:"Firecrawl",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","firecrawl-mcp"],configFields:[{key:"FIRECRAWL_API_KEY",label:"API Key",type:"password",placeholder:"fc-...",required:!0}],website:"https://firecrawl.dev",tags:["scraping","crawling","web","extract"],authMethod:"api-key"},{id:"mcp-puppeteer",name:"Puppeteer",npmPackage:"@modelcontextprotocol/server-puppeteer",description:"Browser automation - screenshots, navigation, form filling, scraping",icon:"globe",category:"research",author:"MCP Official",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","@modelcontextprotocol/server-puppeteer"],configFields:[],tags:["browser","automation","screenshots","scraping"],authMethod:"none"},{id:"mcp-playwright",name:"Playwright",npmPackage:"@playwright/mcp",description:"Browser automation with Playwright - cross-browser testing and scraping",icon:"globe",category:"research",author:"Microsoft",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","@playwright/mcp"],configFields:[],tags:["browser","playwright","testing","automation"],authMethod:"none"},{id:"mcp-github",name:"GitHub",npmPackage:"@modelcontextprotocol/server-github",description:"GitHub repos, issues, PRs, code search, and actions",icon:"git-branch",category:"coding",author:"GitHub",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","@modelcontextprotocol/server-github"],configFields:[{key:"GITHUB_TOKEN",label:"Personal Access Token",type:"password",placeholder:"ghp_...",required:!0}],website:"https://github.com",tags:["github","git","issues","pr","code"],authMethod:"api-key"},{id:"github-remote",name:"GitHub (Cloud)",npmPackage:"@modelcontextprotocol/server-github-cloud",description:"GitHub repos, issues, PRs – OAuth via GitHub App",icon:"git-branch",category:"coding",author:"GitHub",transport:"sse",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","@modelcontextprotocol/server-github-cloud"],url:"https://api.githubcopilot.com/mcp/",authMethod:"oauth",configFields:[{key:"client_id",label:"GitHub App Client ID",type:"text",placeholder:"Iv1.1234567890abcdef",required:!0,helpText:"Create a GitHub App at https://github.com/settings/apps/new and copy the Client ID"}],website:"https://github.com",tags:["github","git","issues","pr","code","oauth"]},{id:"mcp-gitlab",name:"GitLab",npmPackage:"@modelcontextprotocol/server-gitlab",description:"GitLab API - projects, issues, merge requests, pipelines",icon:"git-merge",category:"coding",author:"GitLab",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","@modelcontextprotocol/server-gitlab"],configFields:[{key:"GITLAB_TOKEN",label:"Access Token",type:"password",placeholder:"glpat-...",required:!0},{key:"GITLAB_URL",label:"Instance URL",type:"url",placeholder:"https://gitlab.com",required:!1}],tags:["gitlab","git","ci-cd","merge-request"],authMethod:"api-key"},{id:"mcp-linear",name:"Linear",npmPackage:"@linear/mcp-server",description:"Linear project management - issues, projects, cycles, and teams",icon:"target",category:"coding",author:"Linear",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","@linear/mcp-server"],configFields:[{key:"LINEAR_API_KEY",label:"API Key",type:"password",placeholder:"lin_api_...",required:!0}],website:"https://linear.app",tags:["linear","project-management","issues","agile"],authMethod:"api-key"},{id:"mcp-sentry",name:"Sentry",npmPackage:"@sentry/mcp-server",description:"Error tracking and performance monitoring - issues, events, releases",icon:"shield",category:"coding",author:"Sentry",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","@sentry/mcp-server"],configFields:[{key:"SENTRY_AUTH_TOKEN",label:"Auth Token",type:"password",placeholder:"sntrys_...",required:!0}],website:"https://sentry.io",tags:["sentry","errors","monitoring","debugging"],authMethod:"api-key"},{id:"mcp-docker",name:"Docker",npmPackage:"docker-mcp",description:"Manage Docker containers, images, volumes, and networks",icon:"box",category:"coding",author:"Community",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","docker-mcp"],configFields:[],tags:["docker","containers","devops","infrastructure"],authMethod:"none"},{id:"mcp-kubernetes",name:"Kubernetes",npmPackage:"kubernetes-mcp",description:"Kubernetes cluster management - pods, deployments, services, logs",icon:"server",category:"coding",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","kubernetes-mcp"],configFields:[{key:"KUBECONFIG",label:"Kubeconfig Path",type:"text",placeholder:"~/.kube/config",required:!1}],tags:["kubernetes","k8s","devops","orchestration"],authMethod:"none"},{id:"mcp-vercel",name:"Vercel",npmPackage:"@vercel/mcp",description:"Vercel deployments, domains, environment variables, and logs",icon:"triangle",category:"coding",author:"Vercel",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","@vercel/mcp"],configFields:[{key:"VERCEL_TOKEN",label:"Access Token",type:"password",placeholder:"",required:!0}],website:"https://vercel.com",tags:["vercel","deploy","hosting","serverless"],authMethod:"api-key"},{id:"mcp-cloudflare",name:"Cloudflare",npmPackage:"@cloudflare/mcp-server-cloudflare",description:"Cloudflare Workers, KV, R2, D1, and DNS management",icon:"cloud",category:"coding",author:"Cloudflare",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","@cloudflare/mcp-server-cloudflare"],configFields:[{key:"CLOUDFLARE_API_TOKEN",label:"API Token",type:"password",placeholder:"",required:!0}],website:"https://cloudflare.com",tags:["cloudflare","workers","cdn","dns"],authMethod:"api-key"},{id:"mcp-netlify",name:"Netlify",npmPackage:"netlify-mcp",description:"Netlify sites, deploys, functions, and build hooks",icon:"globe",category:"coding",author:"Netlify",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","netlify-mcp"],configFields:[{key:"NETLIFY_TOKEN",label:"Personal Access Token",type:"password",placeholder:"",required:!0}],tags:["netlify","deploy","hosting","jamstack"],authMethod:"api-key"},{id:"mcp-npm",name:"npm Registry",npmPackage:"npm-mcp",description:"Search npm packages, view details, check versions and dependencies",icon:"package",category:"coding",author:"Community",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","npm-mcp"],configFields:[],tags:["npm","packages","dependencies","registry"],authMethod:"none"},{id:"mcp-postgres",name:"PostgreSQL",npmPackage:"@modelcontextprotocol/server-postgres",description:"Query PostgreSQL databases - schema inspection, read/write operations",icon:"database",category:"data",author:"MCP Official",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","@modelcontextprotocol/server-postgres"],configFields:[{key:"DATABASE_URL",label:"Connection String",type:"password",placeholder:"postgresql://user:pass@host:5432/db",required:!0}],tags:["postgres","database","sql","query"],authMethod:"api-key"},{id:"mcp-mysql",name:"MySQL",npmPackage:"mysql-mcp-server",description:"MySQL database operations - queries, schema, migrations",icon:"database",category:"data",author:"Community",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","mysql-mcp-server"],configFields:[{key:"MYSQL_URL",label:"Connection String",type:"password",placeholder:"mysql://user:pass@host:3306/db",required:!0}],tags:["mysql","database","sql"],authMethod:"api-key"},{id:"mcp-sqlite",name:"SQLite",npmPackage:"@modelcontextprotocol/server-sqlite",description:"SQLite database - local file-based SQL with business intelligence",icon:"database",category:"data",author:"MCP Official",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","@modelcontextprotocol/server-sqlite"],configFields:[{key:"SQLITE_PATH",label:"Database File Path",type:"text",placeholder:"/path/to/database.db",required:!0}],tags:["sqlite","database","sql","local"],authMethod:"none"},{id:"mcp-mongodb",name:"MongoDB",npmPackage:"mongodb-mcp-server",description:"MongoDB operations - collections, documents, aggregation pipelines",icon:"database",category:"data",author:"MongoDB",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","mongodb-mcp-server"],configFields:[{key:"MONGODB_URI",label:"Connection URI",type:"password",placeholder:"mongodb+srv://user:pass@cluster.mongodb.net/db",required:!0}],tags:["mongodb","nosql","database","documents"],authMethod:"api-key"},{id:"mcp-redis",name:"Redis",npmPackage:"@modelcontextprotocol/server-redis",description:"Redis key-value store - get, set, scan, pub/sub",icon:"database",category:"data",author:"MCP Official",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","@modelcontextprotocol/server-redis"],configFields:[{key:"REDIS_URL",label:"Connection URL",type:"password",placeholder:"redis://localhost:6379",required:!0}],tags:["redis","cache","key-value","pub-sub"],authMethod:"api-key"},{id:"mcp-supabase",name:"Supabase",npmPackage:"@supabase/mcp-server",description:"Supabase - database, auth, storage, edge functions, realtime",icon:"database",category:"data",author:"Supabase",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","@supabase/mcp-server"],configFields:[{key:"SUPABASE_URL",label:"Project URL",type:"url",placeholder:"https://xxx.supabase.co",required:!0},{key:"SUPABASE_SERVICE_ROLE_KEY",label:"Service Role Key",type:"password",placeholder:"eyJ...",required:!0}],website:"https://supabase.com",tags:["supabase","database","auth","storage","postgres"],authMethod:"api-key"},{id:"mcp-neon",name:"Neon",npmPackage:"@neondatabase/mcp-server-neon",description:"Neon serverless Postgres - branches, queries, schema management",icon:"database",category:"data",author:"Neon",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","@neondatabase/mcp-server-neon"],configFields:[{key:"NEON_API_KEY",label:"API Key",type:"password",placeholder:"",required:!0}],website:"https://neon.tech",tags:["neon","postgres","serverless","database"],authMethod:"api-key"},{id:"mcp-turso",name:"Turso",npmPackage:"@tursodatabase/mcp-server",description:"Turso edge database - SQLite at the edge, libSQL",icon:"database",category:"data",author:"Turso",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","@tursodatabase/mcp-server"],configFields:[{key:"TURSO_DATABASE_URL",label:"Database URL",type:"url",placeholder:"libsql://db-org.turso.io",required:!0},{key:"TURSO_AUTH_TOKEN",label:"Auth Token",type:"password",placeholder:"",required:!0}],website:"https://turso.tech",tags:["turso","sqlite","edge","database"],authMethod:"api-key"},{id:"mcp-pinecone",name:"Pinecone",npmPackage:"@pinecone-database/mcp",description:"Pinecone vector database - upsert, query, delete vectors",icon:"database",category:"data",author:"Pinecone",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","@pinecone-database/mcp"],configFields:[{key:"PINECONE_API_KEY",label:"API Key",type:"password",placeholder:"",required:!0}],website:"https://pinecone.io",tags:["pinecone","vector","embeddings","rag"],authMethod:"api-key"},{id:"mcp-qdrant",name:"Qdrant",npmPackage:"qdrant-mcp",description:"Qdrant vector search - collections, points, filtering, similarity",icon:"database",category:"data",author:"Qdrant",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","qdrant-mcp"],configFields:[{key:"QDRANT_URL",label:"URL",type:"url",placeholder:"http://localhost:6333",required:!0},{key:"QDRANT_API_KEY",label:"API Key",type:"password",placeholder:"",required:!1}],website:"https://qdrant.tech",tags:["qdrant","vector","search","embeddings"],authMethod:"api-key"},{id:"mcp-slack",name:"Slack",npmPackage:"@modelcontextprotocol/server-slack",description:"Slack workspace - channels, messages, threads, search, reactions",icon:"hash",category:"data",author:"Slack",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","@modelcontextprotocol/server-slack"],configFields:[{key:"SLACK_BOT_TOKEN",label:"Bot Token",type:"password",placeholder:"xoxb-...",required:!0},{key:"SLACK_TEAM_ID",label:"Team ID",type:"text",placeholder:"T0...",required:!1}],website:"https://slack.com",tags:["slack","messaging","channels","team"],authMethod:"api-key"},{id:"slack-remote",name:"Slack (Cloud)",npmPackage:"",description:"Slack workspace - OAuth, no bot token needed",icon:"hash",category:"data",author:"Slack",transport:"streamable-http",runtimes:["claude","amp","codex"],command:"",defaultArgs:[],url:"https://mcp.slack.com/sse",authMethod:"oauth",configFields:[{key:"client_id",label:"Slack App Client ID",type:"text",placeholder:"1234567890.1234567890123",required:!0,helpText:"Create a Slack App at https://api.slack.com/apps and copy the Client ID from Basic Information"}],website:"https://slack.com",tags:["slack","messaging","channels","team","oauth"]},{id:"mcp-discord",name:"Discord",npmPackage:"discord-mcp",description:"Discord bot - read messages, manage channels, send notifications",icon:"message-circle",category:"data",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","discord-mcp"],configFields:[{key:"DISCORD_TOKEN",label:"Bot Token",type:"password",placeholder:"",required:!0}],tags:["discord","messaging","bot","community"],authMethod:"api-key"},{id:"mcp-gmail",name:"Gmail",npmPackage:"@gongrzhe/server-gmail-autoauth-mcp",description:"Read, send, search, and manage Gmail with OAuth auto-auth",icon:"mail",category:"data",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","@gongrzhe/server-gmail-autoauth-mcp"],configFields:[{key:"GMAIL_CLIENT_ID",label:"OAuth Client ID",type:"text",placeholder:"...apps.googleusercontent.com",required:!0},{key:"GMAIL_CLIENT_SECRET",label:"OAuth Client Secret",type:"password",placeholder:"GOCSPX-...",required:!0}],tags:["gmail","email","google","oauth"],authMethod:"api-key"},{id:"mcp-email",name:"Email (SMTP/IMAP)",npmPackage:"email-mcp",description:"Send and read emails via SMTP/IMAP - works with any email provider",icon:"mail",category:"data",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","email-mcp"],configFields:[{key:"SMTP_HOST",label:"SMTP Host",type:"text",placeholder:"smtp.gmail.com",required:!0},{key:"SMTP_USER",label:"Username",type:"text",placeholder:"user@example.com",required:!0},{key:"SMTP_PASS",label:"Password",type:"password",placeholder:"",required:!0}],tags:["email","smtp","imap","send"],authMethod:"api-key"},{id:"mcp-twilio",name:"Twilio",npmPackage:"twilio-mcp",description:"Send SMS, make calls, manage phone numbers via Twilio API",icon:"phone",category:"data",author:"Twilio",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","twilio-mcp"],configFields:[{key:"TWILIO_ACCOUNT_SID",label:"Account SID",type:"text",placeholder:"AC...",required:!0},{key:"TWILIO_AUTH_TOKEN",label:"Auth Token",type:"password",placeholder:"",required:!0}],website:"https://twilio.com",tags:["twilio","sms","phone","messaging"],authMethod:"api-key"},{id:"mcp-notion",name:"Notion",npmPackage:"@notionhq/notion-mcp-server",description:"Notion pages, databases, blocks - read, create, update, search",icon:"book-open",category:"writing",author:"Notion",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","@notionhq/notion-mcp-server"],configFields:[{key:"NOTION_TOKEN",label:"Integration Token",type:"password",placeholder:"ntn_...",required:!0}],website:"https://notion.so",tags:["notion","docs","wiki","database","pages"],authMethod:"api-key"},{id:"notion-remote",name:"Notion (Cloud)",npmPackage:"",description:"Notion pages, databases, blocks - OAuth, no API key needed",icon:"book-open",category:"writing",author:"Notion",transport:"streamable-http",runtimes:["claude","amp","codex"],command:"",defaultArgs:[],url:"https://mcp.notion.com/mcp",authMethod:"oauth",configFields:[],website:"https://notion.so",tags:["notion","docs","wiki","database","pages","oauth"],sameServiceAs:"mcp-notion"},{id:"mcp-google-drive",name:"Google Drive",npmPackage:"@modelcontextprotocol/server-gdrive",description:"Google Drive - search, read, create files and folders",icon:"hard-drive",category:"data",author:"MCP Official",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","@modelcontextprotocol/server-gdrive"],configFields:[{key:"GOOGLE_CLIENT_ID",label:"OAuth Client ID",type:"text",placeholder:"",required:!0},{key:"GOOGLE_CLIENT_SECRET",label:"OAuth Client Secret",type:"password",placeholder:"",required:!0}],tags:["google-drive","files","docs","sheets","storage"],authMethod:"api-key"},{id:"mcp-google-sheets",name:"Google Sheets",npmPackage:"google-sheets-mcp",description:"Read and write Google Sheets - cells, ranges, formulas",icon:"table",category:"data",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","google-sheets-mcp"],configFields:[{key:"GOOGLE_CLIENT_ID",label:"OAuth Client ID",type:"text",placeholder:"",required:!0},{key:"GOOGLE_CLIENT_SECRET",label:"OAuth Client Secret",type:"password",placeholder:"",required:!0}],tags:["google-sheets","spreadsheet","data","tables"],authMethod:"api-key"},{id:"mcp-google-calendar",name:"Google Calendar",npmPackage:"google-calendar-mcp",description:"Google Calendar - events, scheduling, availability, reminders",icon:"calendar",category:"data",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","google-calendar-mcp"],configFields:[{key:"GOOGLE_CLIENT_ID",label:"OAuth Client ID",type:"text",placeholder:"",required:!0},{key:"GOOGLE_CLIENT_SECRET",label:"OAuth Client Secret",type:"password",placeholder:"",required:!0}],tags:["google-calendar","events","scheduling","calendar"],authMethod:"api-key"},{id:"mcp-google-maps",name:"Google Maps",npmPackage:"@modelcontextprotocol/server-google-maps",description:"Google Maps - geocoding, directions, places, distance matrix",icon:"map-pin",category:"data",author:"MCP Official",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","@modelcontextprotocol/server-google-maps"],configFields:[{key:"GOOGLE_MAPS_API_KEY",label:"API Key",type:"password",placeholder:"AIza...",required:!0}],tags:["google-maps","geocoding","directions","places"],authMethod:"api-key"},{id:"mcp-confluence",name:"Confluence",npmPackage:"confluence-mcp",description:"Atlassian Confluence - spaces, pages, search, content management",icon:"book-open",category:"writing",author:"Atlassian",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","confluence-mcp"],configFields:[{key:"CONFLUENCE_URL",label:"Instance URL",type:"url",placeholder:"https://your-org.atlassian.net/wiki",required:!0},{key:"CONFLUENCE_TOKEN",label:"API Token",type:"password",placeholder:"",required:!0},{key:"CONFLUENCE_EMAIL",label:"Email",type:"text",placeholder:"user@company.com",required:!0}],tags:["confluence","wiki","docs","atlassian"],authMethod:"api-key"},{id:"mcp-jira",name:"Jira",npmPackage:"jira-mcp",description:"Jira - issues, boards, sprints, epics, JQL search",icon:"clipboard-list",category:"coding",author:"Atlassian",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","jira-mcp"],configFields:[{key:"JIRA_URL",label:"Instance URL",type:"url",placeholder:"https://your-org.atlassian.net",required:!0},{key:"JIRA_EMAIL",label:"Email",type:"text",placeholder:"user@company.com",required:!0},{key:"JIRA_TOKEN",label:"API Token",type:"password",placeholder:"",required:!0}],tags:["jira","issues","agile","boards","atlassian"],authMethod:"api-key"},{id:"mcp-asana",name:"Asana",npmPackage:"asana-mcp",description:"Asana - tasks, projects, sections, comments, assignees",icon:"check-square",category:"coding",author:"Asana",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","asana-mcp"],configFields:[{key:"ASANA_TOKEN",label:"Personal Access Token",type:"password",placeholder:"1/...",required:!0}],website:"https://asana.com",tags:["asana","tasks","project-management"],authMethod:"api-key"},{id:"mcp-todoist",name:"Todoist",npmPackage:"todoist-mcp",description:"Todoist - tasks, projects, labels, filters, productivity",icon:"check-circle",category:"data",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","todoist-mcp"],configFields:[{key:"TODOIST_API_TOKEN",label:"API Token",type:"password",placeholder:"",required:!0}],website:"https://todoist.com",tags:["todoist","tasks","productivity","todo"],authMethod:"api-key"},{id:"mcp-obsidian",name:"Obsidian",npmPackage:"obsidian-mcp",description:"Obsidian vault - read, search, create notes, manage links",icon:"file-text",category:"writing",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","obsidian-mcp"],configFields:[{key:"OBSIDIAN_VAULT_PATH",label:"Vault Path",type:"text",placeholder:"/path/to/vault",required:!0}],tags:["obsidian","notes","markdown","knowledge-base"],authMethod:"none"},{id:"mcp-airtable",name:"Airtable",npmPackage:"airtable-mcp",description:"Airtable bases, tables, records - CRUD operations and views",icon:"table",category:"data",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","airtable-mcp"],configFields:[{key:"AIRTABLE_TOKEN",label:"Personal Access Token",type:"password",placeholder:"pat...",required:!0}],website:"https://airtable.com",tags:["airtable","database","spreadsheet","records"]},{id:"mcp-hubspot",name:"HubSpot",npmPackage:"hubspot-mcp",description:"HubSpot CRM - contacts, companies, deals, tickets, engagement",icon:"hexagon",category:"data",author:"HubSpot",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","hubspot-mcp"],configFields:[{key:"HUBSPOT_ACCESS_TOKEN",label:"Private App Token",type:"password",placeholder:"pat-...",required:!0}],website:"https://hubspot.com",tags:["hubspot","crm","sales","contacts","deals"]},{id:"mcp-salesforce",name:"Salesforce",npmPackage:"salesforce-mcp",description:"Salesforce - SOQL queries, objects, records, reports",icon:"cloud",category:"data",author:"Salesforce",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","salesforce-mcp"],configFields:[{key:"SF_LOGIN_URL",label:"Login URL",type:"url",placeholder:"https://login.salesforce.com",required:!0},{key:"SF_USERNAME",label:"Username",type:"text",placeholder:"",required:!0},{key:"SF_PASSWORD",label:"Password + Security Token",type:"password",placeholder:"",required:!0}],tags:["salesforce","crm","soql","sales"],authMethod:"api-key"},{id:"mcp-stripe",name:"Stripe",npmPackage:"@stripe/mcp",description:"Stripe payments - customers, invoices, subscriptions, products",icon:"credit-card",category:"data",author:"Stripe",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","@stripe/mcp"],configFields:[{key:"STRIPE_SECRET_KEY",label:"Secret Key",type:"password",placeholder:"sk_...",required:!0}],website:"https://stripe.com",tags:["stripe","payments","billing","subscriptions"]},{id:"mcp-shopify",name:"Shopify",npmPackage:"@shopify/dev-mcp",description:"Shopify store - products, orders, customers, inventory",icon:"shopping-bag",category:"data",author:"Shopify",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","@shopify/dev-mcp"],configFields:[{key:"SHOPIFY_STORE_URL",label:"Store URL",type:"url",placeholder:"your-store.myshopify.com",required:!0},{key:"SHOPIFY_ACCESS_TOKEN",label:"Access Token",type:"password",placeholder:"shpat_...",required:!0}],tags:["shopify","ecommerce","products","orders"],authMethod:"api-key"},{id:"mcp-openai",name:"OpenAI",npmPackage:"openai-mcp",description:"OpenAI API - completions, embeddings, DALL-E, Whisper, assistants",icon:"cpu",category:"coding",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","openai-mcp"],configFields:[{key:"OPENAI_API_KEY",label:"API Key",type:"password",placeholder:"sk-...",required:!0}],tags:["openai","gpt","embeddings","dalle","whisper"],authMethod:"api-key"},{id:"mcp-anthropic",name:"Anthropic Claude",npmPackage:"anthropic-mcp",description:"Anthropic API - Claude completions, tool use, system prompts",icon:"cpu",category:"coding",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","anthropic-mcp"],configFields:[{key:"ANTHROPIC_API_KEY",label:"API Key",type:"password",placeholder:"sk-ant-...",required:!0}],tags:["anthropic","claude","ai","llm"],authMethod:"api-key"},{id:"mcp-replicate",name:"Replicate",npmPackage:"replicate-mcp",description:"Replicate - run open-source ML models via API",icon:"cpu",category:"coding",author:"Replicate",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","replicate-mcp"],configFields:[{key:"REPLICATE_API_TOKEN",label:"API Token",type:"password",placeholder:"r8_...",required:!0}],website:"https://replicate.com",tags:["replicate","ml","models","inference"]},{id:"mcp-huggingface",name:"Hugging Face",npmPackage:"huggingface-mcp",description:"Hugging Face - models, datasets, spaces, inference API",icon:"cpu",category:"coding",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","huggingface-mcp"],configFields:[{key:"HF_TOKEN",label:"Access Token",type:"password",placeholder:"hf_...",required:!0}],website:"https://huggingface.co",tags:["huggingface","models","datasets","ml"]},{id:"mcp-aws",name:"AWS",npmPackage:"aws-mcp",description:"AWS services - S3, Lambda, EC2, DynamoDB, CloudWatch",icon:"cloud",category:"coding",author:"AWS",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","aws-mcp"],configFields:[{key:"AWS_ACCESS_KEY_ID",label:"Access Key ID",type:"text",placeholder:"AKIA...",required:!0},{key:"AWS_SECRET_ACCESS_KEY",label:"Secret Access Key",type:"password",placeholder:"",required:!0},{key:"AWS_REGION",label:"Region",type:"text",placeholder:"us-east-1",required:!1}],tags:["aws","s3","lambda","ec2","cloud"],authMethod:"api-key"},{id:"mcp-gcp",name:"Google Cloud",npmPackage:"gcp-mcp",description:"Google Cloud Platform - BigQuery, Cloud Storage, Compute, Pub/Sub",icon:"cloud",category:"coding",author:"Google",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","gcp-mcp"],configFields:[{key:"GOOGLE_APPLICATION_CREDENTIALS",label:"Service Account Key Path",type:"text",placeholder:"/path/to/key.json",required:!0}],tags:["gcp","bigquery","cloud-storage","google-cloud"],authMethod:"none"},{id:"mcp-azure",name:"Azure",npmPackage:"azure-mcp",description:"Azure services - Blob Storage, Functions, Cosmos DB, Key Vault",icon:"cloud",category:"coding",author:"Microsoft",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","azure-mcp"],configFields:[{key:"AZURE_SUBSCRIPTION_ID",label:"Subscription ID",type:"text",placeholder:"",required:!0},{key:"AZURE_TENANT_ID",label:"Tenant ID",type:"text",placeholder:"",required:!0},{key:"AZURE_CLIENT_ID",label:"Client ID",type:"text",placeholder:"",required:!0},{key:"AZURE_CLIENT_SECRET",label:"Client Secret",type:"password",placeholder:"",required:!0}],tags:["azure","cloud","microsoft","blob-storage"],authMethod:"api-key"},{id:"mcp-n8n",name:"n8n",npmPackage:"n8n-mcp",description:"n8n workflow automation - trigger, manage, inspect workflows",icon:"workflow",category:"coding",author:"n8n",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","n8n-mcp"],configFields:[{key:"N8N_URL",label:"Instance URL",type:"url",placeholder:"http://localhost:5678",required:!0},{key:"N8N_API_KEY",label:"API Key",type:"password",placeholder:"",required:!0}],website:"https://n8n.io",tags:["n8n","automation","workflow","integration"]},{id:"mcp-zapier",name:"Zapier",npmPackage:"zapier-mcp",description:"Zapier - trigger Zaps, manage connections, inspect runs",icon:"zap",category:"coding",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","zapier-mcp"],configFields:[{key:"ZAPIER_API_KEY",label:"API Key",type:"password",placeholder:"",required:!0}],tags:["zapier","automation","workflow","zaps"],authMethod:"api-key"},{id:"mcp-make",name:"Make (Integromat)",npmPackage:"make-mcp",description:"Make.com - scenarios, modules, connections, execution history",icon:"workflow",category:"coding",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","make-mcp"],configFields:[{key:"MAKE_API_TOKEN",label:"API Token",type:"password",placeholder:"",required:!0}],tags:["make","integromat","automation","scenarios"],authMethod:"api-key"},{id:"mcp-datadog",name:"Datadog",npmPackage:"datadog-mcp",description:"Datadog - metrics, dashboards, monitors, logs, APM",icon:"bar-chart",category:"data",author:"Datadog",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","datadog-mcp"],configFields:[{key:"DD_API_KEY",label:"API Key",type:"password",placeholder:"",required:!0},{key:"DD_APP_KEY",label:"App Key",type:"password",placeholder:"",required:!0}],website:"https://datadoghq.com",tags:["datadog","monitoring","metrics","apm"]},{id:"mcp-grafana",name:"Grafana",npmPackage:"grafana-mcp",description:"Grafana - dashboards, alerts, data sources, panels",icon:"bar-chart",category:"data",author:"Grafana",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","grafana-mcp"],configFields:[{key:"GRAFANA_URL",label:"Instance URL",type:"url",placeholder:"http://localhost:3000",required:!0},{key:"GRAFANA_API_KEY",label:"API Key",type:"password",placeholder:"",required:!0}],tags:["grafana","dashboards","monitoring","visualization"],authMethod:"api-key"},{id:"mcp-posthog",name:"PostHog",npmPackage:"posthog-mcp",description:"PostHog product analytics - events, funnels, feature flags, surveys",icon:"bar-chart-3",category:"data",author:"PostHog",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","posthog-mcp"],configFields:[{key:"POSTHOG_HOST",label:"Host URL",type:"url",placeholder:"https://app.posthog.com",required:!0},{key:"POSTHOG_API_KEY",label:"Personal API Key",type:"password",placeholder:"phx_...",required:!0}],website:"https://posthog.com",tags:["posthog","analytics","events","product"]},{id:"mcp-mixpanel",name:"Mixpanel",npmPackage:"mixpanel-mcp",description:"Mixpanel - events, funnels, cohorts, user analytics",icon:"bar-chart",category:"data",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","mixpanel-mcp"],configFields:[{key:"MIXPANEL_TOKEN",label:"Project Token",type:"password",placeholder:"",required:!0},{key:"MIXPANEL_API_SECRET",label:"API Secret",type:"password",placeholder:"",required:!1}],tags:["mixpanel","analytics","events","funnels"],authMethod:"api-key"},{id:"mcp-twitter",name:"Twitter / X",npmPackage:"twitter-mcp",description:"Twitter/X - tweets, search, timeline, DMs, analytics",icon:"message-circle",category:"data",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","twitter-mcp"],configFields:[{key:"TWITTER_API_KEY",label:"API Key",type:"password",placeholder:"",required:!0},{key:"TWITTER_API_SECRET",label:"API Secret",type:"password",placeholder:"",required:!0},{key:"TWITTER_ACCESS_TOKEN",label:"Access Token",type:"password",placeholder:"",required:!0},{key:"TWITTER_ACCESS_SECRET",label:"Access Token Secret",type:"password",placeholder:"",required:!0}],tags:["twitter","x","social","tweets"],authMethod:"api-key"},{id:"mcp-youtube",name:"YouTube",npmPackage:"youtube-mcp",description:"YouTube - search videos, get transcripts, channel analytics",icon:"play",category:"research",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","youtube-mcp"],configFields:[{key:"YOUTUBE_API_KEY",label:"API Key",type:"password",placeholder:"AIza...",required:!0}],tags:["youtube","video","transcripts","search"],authMethod:"api-key"},{id:"mcp-spotify",name:"Spotify",npmPackage:"spotify-mcp",description:"Spotify - search tracks, manage playlists, playback control",icon:"music",category:"data",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","spotify-mcp"],configFields:[{key:"SPOTIFY_CLIENT_ID",label:"Client ID",type:"text",placeholder:"",required:!0},{key:"SPOTIFY_CLIENT_SECRET",label:"Client Secret",type:"password",placeholder:"",required:!0}],tags:["spotify","music","playlists","audio"],authMethod:"api-key"},{id:"mcp-figma",name:"Figma",npmPackage:"figma-mcp",description:"Figma - read files, components, styles, export assets",icon:"palette",category:"design",author:"Figma",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","figma-mcp"],configFields:[{key:"FIGMA_ACCESS_TOKEN",label:"Personal Access Token",type:"password",placeholder:"figd_...",required:!0}],website:"https://figma.com",tags:["figma","design","ui","components"]},{id:"mcp-21st-dev",name:"21st.dev Magic",npmPackage:"@21st-dev/magic-mcp",description:"Create crafted UI components inspired by best design engineers",icon:"sparkles",category:"design",author:"21st.dev",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","@21st-dev/magic-mcp"],configFields:[{key:"TWENTYFIRST_API_KEY",label:"API Key",type:"password",placeholder:"",required:!0}],website:"https://21st.dev",tags:["ui","components","design","magic"]},{id:"mcp-cloudinary",name:"Cloudinary",npmPackage:"cloudinary-mcp",description:"Cloudinary - upload, transform, optimize images and videos",icon:"image",category:"design",author:"Cloudinary",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","cloudinary-mcp"],configFields:[{key:"CLOUDINARY_URL",label:"Cloudinary URL",type:"password",placeholder:"cloudinary://api_key:api_secret@cloud_name",required:!0}],tags:["cloudinary","images","media","cdn","transform"],authMethod:"api-key"},{id:"mcp-vault",name:"HashiCorp Vault",npmPackage:"vault-mcp",description:"HashiCorp Vault - secrets management, dynamic credentials",icon:"lock",category:"coding",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","vault-mcp"],configFields:[{key:"VAULT_ADDR",label:"Vault Address",type:"url",placeholder:"http://localhost:8200",required:!0},{key:"VAULT_TOKEN",label:"Token",type:"password",placeholder:"hvs.",required:!0}],tags:["vault","secrets","security","hashicorp"],authMethod:"api-key"},{id:"mcp-1password",name:"1Password",npmPackage:"1password-mcp",description:"1Password - read secrets, vaults, items securely",icon:"lock",category:"data",author:"1Password",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","1password-mcp"],configFields:[{key:"OP_SERVICE_ACCOUNT_TOKEN",label:"Service Account Token",type:"password",placeholder:"ops_...",required:!0}],tags:["1password","secrets","passwords","security"],authMethod:"api-key"},{id:"mcp-snowflake",name:"Snowflake",npmPackage:"snowflake-mcp",description:"Snowflake data warehouse - queries, tables, schemas, warehouses",icon:"database",category:"data",author:"Snowflake",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","snowflake-mcp"],configFields:[{key:"SNOWFLAKE_ACCOUNT",label:"Account",type:"text",placeholder:"org-account",required:!0},{key:"SNOWFLAKE_USER",label:"Username",type:"text",placeholder:"",required:!0},{key:"SNOWFLAKE_PASSWORD",label:"Password",type:"password",placeholder:"",required:!0}],tags:["snowflake","data-warehouse","sql","analytics"],authMethod:"api-key"},{id:"mcp-bigquery",name:"BigQuery",npmPackage:"bigquery-mcp",description:"Google BigQuery - run SQL queries, manage datasets and tables",icon:"database",category:"data",author:"Google",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","bigquery-mcp"],configFields:[{key:"GOOGLE_APPLICATION_CREDENTIALS",label:"Service Account Key Path",type:"text",placeholder:"/path/to/key.json",required:!0},{key:"BIGQUERY_PROJECT_ID",label:"Project ID",type:"text",placeholder:"my-project",required:!0}],tags:["bigquery","sql","analytics","google-cloud"],authMethod:"none"},{id:"mcp-elasticsearch",name:"Elasticsearch",npmPackage:"elasticsearch-mcp",description:"Elasticsearch - search, index, aggregate, analyze data",icon:"search",category:"data",author:"Elastic",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","elasticsearch-mcp"],configFields:[{key:"ELASTICSEARCH_URL",label:"URL",type:"url",placeholder:"http://localhost:9200",required:!0},{key:"ELASTICSEARCH_API_KEY",label:"API Key",type:"password",placeholder:"",required:!1}],tags:["elasticsearch","search","indexing","analytics"],authMethod:"api-key"},{id:"mcp-rabbitmq",name:"RabbitMQ",npmPackage:"rabbitmq-mcp",description:"RabbitMQ - queues, exchanges, publish/consume messages",icon:"send",category:"data",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","rabbitmq-mcp"],configFields:[{key:"RABBITMQ_URL",label:"Connection URL",type:"password",placeholder:"amqp://user:pass@localhost:5672",required:!0}],tags:["rabbitmq","queue","messaging","amqp"],authMethod:"api-key"},{id:"mcp-kafka",name:"Kafka",npmPackage:"kafka-mcp",description:"Apache Kafka - topics, produce/consume, consumer groups",icon:"send",category:"data",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","kafka-mcp"],configFields:[{key:"KAFKA_BROKERS",label:"Brokers (comma-separated)",type:"text",placeholder:"localhost:9092",required:!0}],tags:["kafka","streaming","events","queue"],authMethod:"none"},{id:"mcp-plaid",name:"Plaid",npmPackage:"plaid-mcp",description:"Plaid financial data - bank accounts, transactions, balances",icon:"credit-card",category:"data",author:"Plaid",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","plaid-mcp"],configFields:[{key:"PLAID_CLIENT_ID",label:"Client ID",type:"text",placeholder:"",required:!0},{key:"PLAID_SECRET",label:"Secret",type:"password",placeholder:"",required:!0}],website:"https://plaid.com",tags:["plaid","banking","finance","transactions"]},{id:"mcp-quickbooks",name:"QuickBooks",npmPackage:"quickbooks-mcp",description:"QuickBooks - invoices, expenses, customers, reports",icon:"receipt",category:"data",author:"Intuit",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","quickbooks-mcp"],configFields:[{key:"QUICKBOOKS_CLIENT_ID",label:"Client ID",type:"text",placeholder:"",required:!0},{key:"QUICKBOOKS_CLIENT_SECRET",label:"Client Secret",type:"password",placeholder:"",required:!0}],tags:["quickbooks","accounting","invoices","finance"],authMethod:"api-key"},{id:"mcp-xero",name:"Xero",npmPackage:"xero-mcp",description:"Xero accounting - invoices, contacts, bank transactions, reports",icon:"receipt",category:"data",author:"Xero",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","xero-mcp"],configFields:[{key:"XERO_CLIENT_ID",label:"Client ID",type:"text",placeholder:"",required:!0},{key:"XERO_CLIENT_SECRET",label:"Client Secret",type:"password",placeholder:"",required:!0}],tags:["xero","accounting","invoices","finance"],authMethod:"api-key"},{id:"mcp-wordpress",name:"WordPress",npmPackage:"wordpress-mcp",description:"WordPress - posts, pages, media, comments via REST API",icon:"file-text",category:"writing",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","wordpress-mcp"],configFields:[{key:"WORDPRESS_URL",label:"Site URL",type:"url",placeholder:"https://yoursite.com",required:!0},{key:"WORDPRESS_USER",label:"Username",type:"text",placeholder:"",required:!0},{key:"WORDPRESS_APP_PASSWORD",label:"Application Password",type:"password",placeholder:"",required:!0}],tags:["wordpress","cms","blog","content"],authMethod:"api-key"},{id:"mcp-contentful",name:"Contentful",npmPackage:"contentful-mcp",description:"Contentful - content types, entries, assets, spaces",icon:"file-text",category:"writing",author:"Contentful",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","contentful-mcp"],configFields:[{key:"CONTENTFUL_SPACE_ID",label:"Space ID",type:"text",placeholder:"",required:!0},{key:"CONTENTFUL_ACCESS_TOKEN",label:"Access Token",type:"password",placeholder:"",required:!0}],tags:["contentful","cms","headless","content"],authMethod:"api-key"},{id:"mcp-sanity",name:"Sanity",npmPackage:"sanity-mcp",description:"Sanity CMS - documents, GROQ queries, assets, mutations",icon:"file-text",category:"writing",author:"Sanity",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","sanity-mcp"],configFields:[{key:"SANITY_PROJECT_ID",label:"Project ID",type:"text",placeholder:"",required:!0},{key:"SANITY_TOKEN",label:"API Token",type:"password",placeholder:"",required:!0}],tags:["sanity","cms","headless","groq"],authMethod:"api-key"},{id:"mcp-weather",name:"Weather",npmPackage:"weather-mcp",description:"Weather data - current conditions, forecasts, historical data",icon:"cloud",category:"data",author:"Community",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","weather-mcp"],configFields:[{key:"OPENWEATHER_API_KEY",label:"OpenWeatherMap API Key",type:"password",placeholder:"",required:!0}],tags:["weather","forecast","climate","temperature"],authMethod:"api-key"},{id:"mcp-wolfram",name:"Wolfram Alpha",npmPackage:"wolfram-mcp",description:"Wolfram Alpha computational intelligence - math, science, data",icon:"calculator",category:"research",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","wolfram-mcp"],configFields:[{key:"WOLFRAM_APP_ID",label:"App ID",type:"password",placeholder:"",required:!0}],tags:["wolfram","math","science","computation"],authMethod:"api-key"},{id:"mcp-whois",name:"WHOIS",npmPackage:"whois-mcp",description:"Domain WHOIS lookup - registration, expiry, nameservers",icon:"globe",category:"research",author:"Community",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","whois-mcp"],configFields:[],tags:["whois","domain","dns","lookup"],authMethod:"none"},{id:"mcp-mermaid",name:"Mermaid",npmPackage:"mermaid-mcp",description:"Generate Mermaid diagrams - flowcharts, sequence, gantt, class",icon:"workflow",category:"design",author:"Community",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","mermaid-mcp"],configFields:[],tags:["mermaid","diagrams","flowchart","visualization"],authMethod:"none"},{id:"mcp-screenshot",name:"Screenshot",npmPackage:"screenshot-mcp",description:"Take screenshots of websites - full page, element, viewport",icon:"camera",category:"research",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","screenshot-mcp"],configFields:[],tags:["screenshot","capture","web","image"],authMethod:"none"},{id:"mcp-pdf",name:"PDF Tools",npmPackage:"pdf-mcp",description:"Extract text, tables, and images from PDF documents",icon:"file",category:"data",author:"Community",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","pdf-mcp"],configFields:[],tags:["pdf","extract","text","documents"],authMethod:"none"},{id:"mcp-csv",name:"CSV Tools",npmPackage:"csv-mcp",description:"Parse, query, transform, and generate CSV/TSV files",icon:"table",category:"data",author:"Community",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","csv-mcp"],configFields:[],tags:["csv","tsv","data","tables","transform"],authMethod:"none"},{id:"mcp-s3",name:"S3 / Object Storage",npmPackage:"s3-mcp",description:"S3-compatible storage - list, read, write, delete objects",icon:"hard-drive",category:"data",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","s3-mcp"],configFields:[{key:"S3_ENDPOINT",label:"Endpoint",type:"url",placeholder:"https://s3.amazonaws.com",required:!1},{key:"S3_ACCESS_KEY",label:"Access Key",type:"text",placeholder:"",required:!0},{key:"S3_SECRET_KEY",label:"Secret Key",type:"password",placeholder:"",required:!0},{key:"S3_BUCKET",label:"Bucket Name",type:"text",placeholder:"my-bucket",required:!0}],tags:["s3","storage","objects","bucket"],authMethod:"api-key"},{id:"mcp-ssh",name:"SSH",npmPackage:"ssh-mcp",description:"Execute commands on remote servers via SSH",icon:"terminal",category:"coding",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","ssh-mcp"],configFields:[{key:"SSH_HOST",label:"Host",type:"text",placeholder:"192.168.1.100",required:!0},{key:"SSH_USER",label:"Username",type:"text",placeholder:"root",required:!0},{key:"SSH_KEY_PATH",label:"Private Key Path",type:"text",placeholder:"~/.ssh/id_rsa",required:!1}],tags:["ssh","remote","terminal","server"],authMethod:"none"},{id:"mcp-terraform",name:"Terraform",npmPackage:"terraform-mcp",description:"Terraform - plan, apply, state, modules, resources",icon:"server",category:"coding",author:"HashiCorp",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","terraform-mcp"],configFields:[],tags:["terraform","iac","infrastructure","devops"],authMethod:"none"},{id:"mcp-prometheus",name:"Prometheus",npmPackage:"prometheus-mcp",description:"Prometheus - PromQL queries, metrics, alerts, targets",icon:"bar-chart",category:"data",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","prometheus-mcp"],configFields:[{key:"PROMETHEUS_URL",label:"URL",type:"url",placeholder:"http://localhost:9090",required:!0}],tags:["prometheus","metrics","monitoring","promql"],authMethod:"none"},{id:"mcp-intercom",name:"Intercom",npmPackage:"intercom-mcp",description:"Intercom - conversations, contacts, companies, articles",icon:"message-circle",category:"data",author:"Intercom",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","intercom-mcp"],configFields:[{key:"INTERCOM_TOKEN",label:"Access Token",type:"password",placeholder:"",required:!0}],tags:["intercom","support","chat","crm"],authMethod:"api-key"},{id:"mcp-zendesk",name:"Zendesk",npmPackage:"zendesk-mcp",description:"Zendesk - tickets, users, organizations, search",icon:"headphones",category:"data",author:"Zendesk",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","zendesk-mcp"],configFields:[{key:"ZENDESK_SUBDOMAIN",label:"Subdomain",type:"text",placeholder:"your-org",required:!0},{key:"ZENDESK_EMAIL",label:"Email",type:"text",placeholder:"agent@company.com",required:!0},{key:"ZENDESK_TOKEN",label:"API Token",type:"password",placeholder:"",required:!0}],tags:["zendesk","support","tickets","helpdesk"],authMethod:"api-key"},{id:"mcp-freshdesk",name:"Freshdesk",npmPackage:"freshdesk-mcp",description:"Freshdesk - tickets, contacts, groups, canned responses",icon:"headphones",category:"data",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","freshdesk-mcp"],configFields:[{key:"FRESHDESK_DOMAIN",label:"Domain",type:"text",placeholder:"your-org.freshdesk.com",required:!0},{key:"FRESHDESK_API_KEY",label:"API Key",type:"password",placeholder:"",required:!0}],tags:["freshdesk","support","tickets","helpdesk"],authMethod:"api-key"},{id:"mcp-clickup",name:"ClickUp",npmPackage:"clickup-mcp",description:"ClickUp - tasks, lists, spaces, goals, docs, time tracking",icon:"check-square",category:"coding",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","clickup-mcp"],configFields:[{key:"CLICKUP_TOKEN",label:"Personal API Token",type:"password",placeholder:"pk_...",required:!0}],tags:["clickup","tasks","project-management","productivity"],authMethod:"api-key"},{id:"mcp-trello",name:"Trello",npmPackage:"trello-mcp",description:"Trello - boards, lists, cards, checklists, members",icon:"layout",category:"data",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","trello-mcp"],configFields:[{key:"TRELLO_API_KEY",label:"API Key",type:"password",placeholder:"",required:!0},{key:"TRELLO_TOKEN",label:"Token",type:"password",placeholder:"",required:!0}],tags:["trello","boards","kanban","cards"],authMethod:"api-key"},{id:"mcp-monday",name:"Monday.com",npmPackage:"monday-mcp",description:"Monday.com - boards, items, columns, updates, automations",icon:"layout",category:"data",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","monday-mcp"],configFields:[{key:"MONDAY_API_TOKEN",label:"API Token",type:"password",placeholder:"",required:!0}],tags:["monday","boards","project-management","workflow"],authMethod:"api-key"},{id:"mcp-github-actions",name:"GitHub Actions",npmPackage:"github-actions-mcp",description:"GitHub Actions - workflows, runs, jobs, artifacts, secrets",icon:"play-circle",category:"coding",author:"Community",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","github-actions-mcp"],configFields:[{key:"GITHUB_TOKEN",label:"Personal Access Token",type:"password",placeholder:"ghp_...",required:!0}],tags:["github-actions","ci-cd","workflows","automation"],authMethod:"api-key"},{id:"mcp-circleci",name:"CircleCI",npmPackage:"circleci-mcp",description:"CircleCI - pipelines, jobs, workflows, orbs, insights",icon:"play-circle",category:"coding",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","circleci-mcp"],configFields:[{key:"CIRCLECI_TOKEN",label:"Personal API Token",type:"password",placeholder:"",required:!0}],tags:["circleci","ci-cd","pipelines","automation"],authMethod:"api-key"},{id:"mcp-upstash",name:"Upstash",npmPackage:"@upstash/mcp-server",description:"Upstash - serverless Redis and Kafka, QStash message queue",icon:"database",category:"data",author:"Upstash",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","@upstash/mcp-server"],configFields:[{key:"UPSTASH_REDIS_REST_URL",label:"Redis REST URL",type:"url",placeholder:"",required:!0},{key:"UPSTASH_REDIS_REST_TOKEN",label:"Redis REST Token",type:"password",placeholder:"",required:!0}],website:"https://upstash.com",tags:["upstash","redis","kafka","serverless"]},{id:"mcp-sendgrid",name:"SendGrid",npmPackage:"sendgrid-mcp",description:"SendGrid - send transactional emails, manage templates, contacts",icon:"mail",category:"data",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","sendgrid-mcp"],configFields:[{key:"SENDGRID_API_KEY",label:"API Key",type:"password",placeholder:"SG.",required:!0}],tags:["sendgrid","email","transactional","templates"],authMethod:"api-key"},{id:"mcp-resend",name:"Resend",npmPackage:"resend-mcp",description:"Resend - send emails with React Email templates",icon:"mail",category:"data",author:"Resend",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","resend-mcp"],configFields:[{key:"RESEND_API_KEY",label:"API Key",type:"password",placeholder:"re_...",required:!0}],website:"https://resend.com",tags:["resend","email","react-email","transactional"]},{id:"mcp-openapi",name:"OpenAPI",npmPackage:"openapi-mcp",description:"Load any OpenAPI/Swagger spec and call its endpoints as MCP tools",icon:"globe",category:"coding",author:"Community",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","openapi-mcp"],configFields:[{key:"OPENAPI_SPEC_URL",label:"Spec URL",type:"url",placeholder:"https://api.example.com/openapi.json",required:!0}],tags:["openapi","swagger","rest","api"],authMethod:"none"},{id:"mcp-graphql",name:"GraphQL",npmPackage:"graphql-mcp",description:"Query any GraphQL endpoint - introspection, queries, mutations",icon:"globe",category:"coding",author:"Community",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","graphql-mcp"],configFields:[{key:"GRAPHQL_URL",label:"Endpoint URL",type:"url",placeholder:"https://api.example.com/graphql",required:!0},{key:"GRAPHQL_AUTH_HEADER",label:"Auth Header Value",type:"password",placeholder:"Bearer ...",required:!1}],tags:["graphql","api","query","mutation"],authMethod:"api-key"},{id:"mcp-coda",name:"Coda",npmPackage:"coda-mcp",description:"Coda docs - tables, rows, formulas, pages, automations",icon:"file-text",category:"data",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","coda-mcp"],configFields:[{key:"CODA_API_TOKEN",label:"API Token",type:"password",placeholder:"",required:!0}],tags:["coda","docs","tables","automation"],authMethod:"api-key"},{id:"mcp-segment",name:"Segment",npmPackage:"segment-mcp",description:"Segment - track events, identify users, manage sources & destinations",icon:"bar-chart",category:"data",author:"Twilio",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","segment-mcp"],configFields:[{key:"SEGMENT_WRITE_KEY",label:"Write Key",type:"password",placeholder:"",required:!0}],tags:["segment","analytics","events","cdp"],authMethod:"api-key"},{id:"mcp-amplitude",name:"Amplitude",npmPackage:"amplitude-mcp",description:"Amplitude - events, user analytics, cohorts, retention",icon:"bar-chart",category:"data",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","amplitude-mcp"],configFields:[{key:"AMPLITUDE_API_KEY",label:"API Key",type:"password",placeholder:"",required:!0},{key:"AMPLITUDE_SECRET_KEY",label:"Secret Key",type:"password",placeholder:"",required:!0}],tags:["amplitude","analytics","events","product"],authMethod:"api-key"},{id:"mcp-context7",name:"Context7",npmPackage:"@upstash/context7-mcp",description:"Pull up-to-date library documentation and code examples on demand",icon:"book-open",category:"domain",author:"Upstash",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","@upstash/context7-mcp"],configFields:[],tags:["docs","documentation","libraries","context"],authMethod:"none"},{id:"mcp-aws-kb-retrieval",name:"AWS KB Retrieval",npmPackage:"@modelcontextprotocol/server-aws-kb-retrieval",description:"Retrieve from AWS Bedrock Knowledge Bases using RAG",icon:"database",category:"domain",author:"MCP Official",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","@modelcontextprotocol/server-aws-kb-retrieval"],configFields:[{key:"AWS_ACCESS_KEY_ID",label:"Access Key ID",type:"text",placeholder:"AKIA...",required:!0},{key:"AWS_SECRET_ACCESS_KEY",label:"Secret Access Key",type:"password",placeholder:"",required:!0},{key:"AWS_REGION",label:"Region",type:"text",placeholder:"us-east-1",required:!0}],repo:"https://github.com/modelcontextprotocol/servers",tags:["aws","bedrock","rag","knowledge-base"]},{id:"mcp-everart",name:"EverArt",npmPackage:"@modelcontextprotocol/server-everart",description:"AI image generation with multiple models via EverArt platform",icon:"image",category:"design",author:"MCP Official",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","@modelcontextprotocol/server-everart"],configFields:[{key:"EVERART_API_KEY",label:"API Key",type:"password",placeholder:"",required:!0}],repo:"https://github.com/modelcontextprotocol/servers",tags:["image","generation","ai-art","design"]},{id:"mcp-greptile",name:"Greptile",npmPackage:"@greptile/mcp-server",description:"AI-powered codebase search and understanding",icon:"search",category:"coding",author:"Greptile",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","@greptile/mcp-server"],configFields:[{key:"GREPTILE_API_KEY",label:"API Key",type:"password",placeholder:"",required:!0}],website:"https://greptile.com",tags:["code-search","codebase","ai","understanding"]},{id:"mcp-e2b",name:"E2B Code Interpreter",npmPackage:"@e2b/mcp-server",description:"Sandboxed code execution - run Python, JS, and more in secure cloud sandbox",icon:"terminal",category:"coding",author:"E2B",transport:"stdio",runtimes:["claude","amp","codex"],command:"npx",defaultArgs:["-y","@e2b/mcp-server"],configFields:[{key:"E2B_API_KEY",label:"API Key",type:"password",placeholder:"e2b_...",required:!0}],website:"https://e2b.dev",tags:["sandbox","code-execution","interpreter","python"]},{id:"mcp-hubspot-dev",name:"HubSpot Developer",npmPackage:"@hubspot/mcp-server",description:"HubSpot developer tools - CMS, projects, functions, deploy",icon:"hexagon",category:"domain",author:"HubSpot",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","@hubspot/mcp-server"],configFields:[{key:"HUBSPOT_PORTAL_ID",label:"Portal ID",type:"text",placeholder:"",required:!0}],website:"https://developers.hubspot.com",tags:["hubspot","cms","developer","deploy"]},{id:"mcp-medical-ref",name:"Medical Reference",npmPackage:"medical-ref-mcp",description:"Medical terminology, drug interactions, clinical guidelines lookup",icon:"heart",category:"domain",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","medical-ref-mcp"],configFields:[],tags:["medical","healthcare","drugs","clinical"],authMethod:"none"},{id:"mcp-legal",name:"Legal Research",npmPackage:"legal-mcp",description:"Legal document search - case law, statutes, regulations",icon:"scale",category:"domain",author:"Community",transport:"stdio",runtimes:["claude","amp"],command:"npx",defaultArgs:["-y","legal-mcp"],configFields:[],tags:["legal","law","case-law","regulations"],authMethod:"none"}],Ee=[{id:"web-search",name:"Web Search",description:"Search the web using Brave Search API for real-time information retrieval",icon:"search",category:"research",author:"Anthropic",installs:12400,runtimes:["claude","amp","codex"],installCmd:"npx modular-skills install web-search",installed:!1},{id:"github",name:"GitHub",description:"GitHub operations — repos, issues, PRs, and code search via gh CLI",icon:"git-branch",category:"coding",author:"Anthropic",installs:9800,runtimes:["claude","amp","codex"],installCmd:"npx modular-skills install github",installed:!1},{id:"weather",name:"Weather",description:"Weather data from wttr.in and Open-Meteo for forecasts and conditions",icon:"cloud",category:"data",author:"Community",installs:4200,runtimes:["claude","amp"],installCmd:"npx modular-skills install weather",installed:!1},{id:"coding-agent",name:"Coding Agent",description:"Delegate complex coding tasks to Claude Code or Codex sub-agents",icon:"code",category:"coding",author:"Anthropic",installs:18200,runtimes:["claude","amp","codex"],installCmd:"npx modular-skills install coding-agent",installed:!0,installedTarget:"claude",installedScope:"project"},{id:"openai-whisper",name:"OpenAI Whisper",description:"Transcribe audio files to text using OpenAI Whisper API",icon:"mic",category:"data",author:"OpenAI",installs:6700,runtimes:["claude","amp","codex","openai"],installCmd:"npx modular-skills install openai-whisper",installed:!1},{id:"openai-image-gen",name:"Image Generation",description:"Generate images from text prompts using DALL-E or Stable Diffusion",icon:"image",category:"design",author:"OpenAI",installs:8900,runtimes:["claude","amp","openai"],installCmd:"npx modular-skills install openai-image-gen",installed:!1},{id:"notion-api",name:"Notion API",description:"Full Notion integration — read, create, update pages and databases",icon:"book-open",category:"writing",author:"Notion",installs:7300,runtimes:["claude","amp","codex"],installCmd:"npx modular-skills install notion-api",installed:!1},{id:"hubspot-integration",name:"HubSpot CRM",description:"HubSpot CRM operations — contacts, companies, deals, and pipelines",icon:"hexagon",category:"data",author:"HubSpot",installs:3100,runtimes:["claude","amp"],installCmd:"npx modular-skills install hubspot-integration",installed:!1},{id:"n8n-workflow-patterns",name:"n8n Workflows",description:"Build and manage n8n automation workflows with proven patterns",icon:"workflow",category:"coding",author:"n8n",installs:2800,runtimes:["claude","amp"],installCmd:"npx modular-skills install n8n-workflow-patterns",installed:!1},{id:"maritime-expert",name:"Maritime Expert",description:"Maritime domain expertise — vessel tracking, port ops, cargo management",icon:"anchor",category:"domain",author:"Nimbalyst",installs:1200,runtimes:["claude","amp"],installCmd:"npx modular-skills install maritime-expert",installed:!0,installedTarget:"claude",installedScope:"project"},{id:"feedback-analyzer",name:"Feedback Analyzer",description:"Extract insights from customer feedback — patterns, sentiment, priorities",icon:"bar-chart-3",category:"research",author:"Nimbalyst",installs:2400,runtimes:["claude","amp","codex"],installCmd:"npx modular-skills install feedback-analyzer",installed:!0,installedTarget:"all",installedScope:"global"},{id:"roadmap-builder",name:"Roadmap Builder",description:"Create strategic product roadmaps with OKRs and stakeholder alignment",icon:"map",category:"writing",author:"Community",installs:1800,runtimes:["claude","amp"],installCmd:"npx modular-skills install roadmap-builder",installed:!1},{id:"presentation-generator",name:"Presentation Gen",description:"Generate interactive HTML presentations with animations and styling",icon:"presentation",category:"design",author:"Community",installs:3600,runtimes:["claude","amp","codex"],installCmd:"npx modular-skills install presentation-generator",installed:!0,installedTarget:"claude",installedScope:"project"},{id:"clean-code",name:"Clean Code",description:"Pragmatic coding standards — concise, direct, no over-engineering",icon:"sparkles",category:"coding",author:"Community",installs:5400,runtimes:["claude","amp","codex"],installCmd:"npx modular-skills install clean-code",installed:!1},{id:"html-style",name:"HTML Style",description:"Apply opinionated styling to unstyled HTML with a cohesive design system",icon:"palette",category:"design",author:"Community",installs:2100,runtimes:["claude","amp"],installCmd:"npx modular-skills install html-style",installed:!1},{id:"find-skills",name:"Find Skills",description:"Meta-skill that discovers and recommends other skills for your task",icon:"compass",category:"research",author:"Anthropic",installs:4800,runtimes:["claude","amp","codex"],installCmd:"npx modular-skills install find-skills",installed:!1},{id:"fluidsim",name:"FluidSim",description:"Computational fluid dynamics — Navier-Stokes, shallow water, turbulence",icon:"waves",category:"domain",author:"SciPy",installs:800,runtimes:["claude"],installCmd:"npx modular-skills install fluidsim",installed:!1},{id:"threejs-fundamentals",name:"Three.js",description:"Three.js 3D graphics — scene setup, cameras, lighting, animation",icon:"box",category:"coding",author:"Community",installs:3200,runtimes:["claude","amp","codex"],installCmd:"npx modular-skills install threejs-fundamentals",installed:!1},{id:"web-design-guidelines",name:"Web Design Review",description:"Review UI code against Web Interface Guidelines for best practices",icon:"layout",category:"design",author:"Community",installs:2900,runtimes:["claude","amp"],installCmd:"npx modular-skills install web-design-guidelines",installed:!1},{id:"skill-creator",name:"Skill Creator",description:"Build and package new skills with proper manifests and adapters",icon:"wrench",category:"coding",author:"Anthropic",installs:1500,runtimes:["claude","amp","codex"],installCmd:"npx modular-skills install skill-creator",installed:!1},{id:"vercel-react",name:"Vercel React",description:"React and Next.js performance optimization patterns from Vercel Engineering",icon:"triangle",category:"coding",author:"Vercel",installs:7100,runtimes:["claude","amp","codex"],installCmd:"npx modular-skills install vercel-react",installed:!1},{id:"claude-platform",name:"Claude Platform",description:"Build apps with Claude API — SDK patterns, tool use, streaming",icon:"cpu",category:"coding",author:"Anthropic",installs:11200,runtimes:["claude"],installCmd:"npx modular-skills install claude-platform",installed:!1}];function Sn(t){return{id:t.id,name:t.name,description:t.description,icon:t.icon,category:t.category,author:t.author,transport:t.transport,runtimes:t.runtimes,installCmd:`npx -y ${t.npmPackage}`,command:t.command,defaultArgs:t.defaultArgs,configFields:t.configFields,installed:!1,configured:!1}}const Tn=St.map(Sn),Ia=[{id:"preset-fullstack-dev",name:"Full-Stack Developer",description:"Complete dev setup with GitHub, filesystem, coding agent, and clean code standards",icon:"code",skills:["coding-agent","clean-code","github","threejs-fundamentals"],mcpServers:["mcp-github","mcp-filesystem","mcp-linear"],canvasDescription:"Knowledge → Agent (Claude Opus) → Code Output | Skills: Coding Agent, Clean Code, GitHub | MCP: GitHub, Filesystem, Linear"},{id:"preset-research-analyst",name:"Research Analyst",description:"Web search, scraping, and analysis tools for deep research",icon:"search",skills:["web-search","feedback-analyzer","find-skills"],mcpServers:["mcp-brave-search","mcp-firecrawl","mcp-puppeteer"],canvasDescription:"Web Sources → Agent (Claude Opus) → Markdown Report | Skills: Web Search, Feedback Analyzer | MCP: Brave, Firecrawl, Puppeteer"},{id:"preset-content-writer",name:"Content Writer",description:"Writing-focused setup with Notion, presentation gen, and design review",icon:"pen-tool",skills:["presentation-generator","html-style","web-design-guidelines","notion-api"],mcpServers:["mcp-notion","mcp-slack"],canvasDescription:"Notion Pages → Agent (Claude Sonnet) → HTML/Markdown | Skills: Presentation Gen, HTML Style | MCP: Notion, Slack"},{id:"preset-data-pipeline",name:"Data Pipeline",description:"Database, API, and CRM integrations for data workflows",icon:"database",skills:["hubspot-integration","n8n-workflow-patterns","weather"],mcpServers:["mcp-postgres","mcp-supabase","mcp-hubspot"],canvasDescription:"CRM + DB → Agent (Claude Sonnet) → JSON/CSV | Skills: HubSpot, n8n Workflows | MCP: PostgreSQL, Supabase, HubSpot"},{id:"preset-maritime-ops",name:"Maritime Operations",description:"Maritime domain with vessel tracking, weather data, and fleet management",icon:"anchor",skills:["maritime-expert","weather","feedback-analyzer"],mcpServers:["mcp-slack","mcp-notion"],canvasDescription:"Maritime Knowledge → Agent (Claude Opus) → Reports | Skills: Maritime Expert, Weather | MCP: Slack, Notion"},{id:"preset-design-system",name:"Design System",description:"Design-focused setup with visual review, styling, and presentation tools",icon:"palette",skills:["web-design-guidelines","html-style","presentation-generator","openai-image-gen"],mcpServers:["mcp-puppeteer"],canvasDescription:"Design Specs → Agent (Claude Sonnet) → HTML/CSS | Skills: Web Design, HTML Style, Image Gen | MCP: Puppeteer"},{id:"preset-senior-pm",name:"Senior PM",description:"Discovery synthesis specialist — turns messy brainstorms into prioritized product strategy with RICE framework",icon:"user",skills:["feedback-analyzer","roadmap-builder"],mcpServers:["mcp-notion","mcp-slack"],canvasDescription:"Knowledge + Signals → Agent (Claude Opus) → Synthesis Report | Skills: Feedback Analyzer, Roadmap Builder | MCP: Notion, Slack"},{id:"preset-feedback-manager",name:"Feedback Manager",description:"Feedback lifecycle specialist — organizes, challenges, and maintains the single source of truth for user feedback",icon:"inbox",skills:["feedback-analyzer"],mcpServers:["mcp-gmail","mcp-notion","mcp-slack"],canvasDescription:"Gmail + Signals → Agent (Claude Sonnet) → Feedback Reports | Skills: Feedback Analyzer | MCP: Gmail, Notion, Slack"},{id:"preset-competitor-scraper",name:"Competitor Feature Scraper",description:"Scrapes competitor websites to extract product features, claims, and screenshots for competitive comparison",icon:"search",skills:["web-search"],mcpServers:["mcp-firecrawl"],canvasDescription:"Competitor Knowledge → Agent (Claude Sonnet) → Feature Profiles | Skills: Web Search | MCP: Firecrawl"}],Ma={claude:{label:"Claude",color:"#FE5000"},amp:{label:"Amp",color:"#8B5CF6"},codex:{label:"Codex",color:"#10B981"},openai:{label:"OpenAI",color:"#74AA9C"},gemini:{label:"Gemini",color:"#4285F4"}},_a=[{id:"all",label:"All"},{id:"research",label:"Research"},{id:"coding",label:"Coding"},{id:"data",label:"Data"},{id:"design",label:"Design"},{id:"writing",label:"Writing"},{id:"domain",label:"Domain"}],E="/api";async function Tt(t,o){const e=new TextDecoder;let n="";for(;;){const{done:s,value:a}=await t.read();if(s)break;n+=e.decode(a,{stream:!0});const r=n.split(`
|
|
3
|
+
`);n=r.pop()??"";for(const i of r){const c=i.trim();if(!c||!c.startsWith("data: "))continue;const l=c.slice(6);if(l==="[DONE]"||o(l))return}}}function xt(t){const{prompt:o,model:e,systemPrompt:n,maxTurns:s,onChunk:a,onDone:r,onError:i}=t,c=new AbortController;return fetch(`${E}/agent-sdk/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:o,model:e,systemPrompt:n,maxTurns:s}),signal:c.signal}).then(async l=>{if(!l.ok){const m=await l.text().catch(()=>"");throw new Error(`Agent SDK error ${l.status}: ${m||l.statusText}`)}const d=l.body?.getReader();if(!d)throw new Error("No response body");await Tt(d,m=>{try{const u=JSON.parse(m);if(u.type==="text"&&u.content)a(u.content);else if(u.type==="error")return i(new Error(u.message)),!0}catch{}}),r()}).catch(l=>{l instanceof DOMException&&l.name==="AbortError"||i(l instanceof Error?l:new Error(String(l)))}),c}function Ct(t){const{providerId:o,model:e,messages:n,temperature:s=.7,maxTokens:a=4096,onChunk:r,onDone:i,onError:c}=t,l=new AbortController;return fetch(`${E}/llm/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:o,model:e,messages:n,temperature:s,max_tokens:a}),signal:l.signal}).then(async d=>{if(!d.ok){const u=await d.text().catch(()=>"");throw new Error(`LLM error ${d.status}: ${u||d.statusText}`)}const m=d.body?.getReader();if(!m)throw new Error("No response body");await Tt(m,u=>{try{const p=JSON.parse(u);p.type==="content_block_delta"&&p.delta?.text?r(p.delta.text):p.choices?.[0]?.delta?.content&&r(p.choices[0].delta.content)}catch{}}),i()}).catch(d=>{d instanceof DOMException&&d.name==="AbortError"||c(d instanceof Error?d:new Error(String(d)))}),l}async function $a(t){const{providerId:o,model:e,messages:n,temperature:s=.3,maxTokens:a=2048}=t,r=await fetch(`${E}/llm/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:o,model:e,messages:n,temperature:s,maxTokens:a})});if(!r.ok){const l=await r.text().catch(()=>"");throw new Error(`LLM error ${r.status}: ${l||r.statusText}`)}const i=await r.text(),c=[];for(const l of i.split(`
|
|
4
|
+
`)){if(!l.startsWith("data: "))continue;const d=l.slice(6).trim();if(d==="[DONE]")break;try{const m=JSON.parse(d);m.type==="content_block_delta"&&m.delta?.text?c.push(m.delta.text):m.choices?.[0]?.delta?.content?c.push(m.choices[0].delta.content):m.type==="text"&&m.content&&c.push(m.content)}catch{}}return c.join("").trim()}async function Ra(t){const o=await fetch(`${E}/agent-sdk/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok){const s=await o.text().catch(()=>"");throw new Error(`Agent SDK error ${o.status}: ${s||o.statusText}`)}const e=await o.text(),n=[];for(const s of e.split(`
|
|
5
|
+
`)){if(!s.startsWith("data: "))continue;const a=s.slice(6).trim();if(a==="[DONE]")break;try{const r=JSON.parse(a);r.type==="text"&&r.content&&n.push(r.content)}catch{}}return n.join("").trim()}function I(t){if(!t)return 0;const o=t.match(/```[\s\S]*?```/g),e=o?o.reduce((s,a)=>s+a.length,0):0,n=t.length-e;return Math.ceil(n/4+e/2.5)}function qe(t){const o=t.match(/^[^\n]*?[.!?](?:\s|$)/);return o?o[0].trim():t.split(`
|
|
6
|
+
`)[0].slice(0,200)}function Ue(t){const o=t.split(/\n\s*\n/)[0];return o?o.trim().slice(0,1e3):""}function te(t,o){return`n${t}-${o}`}function ce(t){let o=t.tokens;for(const e of t.children)o+=ce(e);return t.totalTokens=o,o}function Ce(t){let o=1;for(const e of t.children)o+=Ce(e);return o}function Q(t,o){const e=o.split(`
|
|
7
|
+
`);let n=0;const s={nodeId:te(0,n++),title:t,depth:0,text:"",tokens:0,totalTokens:0,children:[]},a=[s];let r=[],i=0;function c(d){const m=r.join(`
|
|
8
|
+
`).trim(),u=a[a.length-1];u.text=m,u.tokens=I(m),u.meta?(u.meta.lineEnd=d,u.meta.firstSentence=qe(m),u.meta.firstParagraph=Ue(m)):m&&(u.meta={lineStart:i,lineEnd:d,firstSentence:qe(m),firstParagraph:Ue(m),sourceType:"markdown"}),r=[]}const l=/^(#{1,6})\s+(.+)$/;for(let d=0;d<e.length;d++){const m=e[d],u=l.exec(m);if(u){c(d-1);const p=u[1].length,g=u[2].trim(),f={nodeId:te(p,n++),title:g,depth:p,text:"",tokens:0,totalTokens:0,children:[],meta:{lineStart:d,lineEnd:d,firstSentence:"",firstParagraph:"",sourceType:"markdown"}};for(;a.length>1&&a[a.length-1].depth>=p;)a.pop();a[a.length-1].children.push(f),a.push(f),i=d+1}else r.push(m)}return c(e.length-1),ce(s),{source:t,sourceType:"markdown",root:s,totalTokens:s.totalTokens,nodeCount:Ce(s),created:Date.now()}}function xn(t,o,e="structured"){let n=0;const s={nodeId:te(0,n++),title:t,depth:0,text:"",tokens:0,totalTokens:0,children:[]},a=new Map;for(const r of o){const i=r.group||"default";a.has(i)||a.set(i,[]),a.get(i).push(r)}for(const[r,i]of a){const c=i.map(d=>`${d.label}: ${d.value}`).join(`
|
|
9
|
+
`),l={nodeId:te(1,n++),title:r==="default"?t:r,depth:1,text:c,tokens:I(c),totalTokens:0,children:[],meta:{firstSentence:i[0]?`${i[0].label}: ${i[0].value}`:"",firstParagraph:c.slice(0,1e3),sourceType:e,fieldGroup:r}};s.children.push(l)}return ce(s),{source:t,sourceType:e,root:s,totalTokens:s.totalTokens,nodeCount:Ce(s),created:Date.now()}}function Cn(t,o,e="chronological",n=10){let s=0;const a={nodeId:te(0,s++),title:t,depth:0,text:"",tokens:0,totalTokens:0,children:[]};if(o.length===0)return ce(a),{source:t,sourceType:e,root:a,totalTokens:0,nodeCount:1,created:Date.now()};const r=n*60*1e3;let i=[o[0]];const c=[];for(let l=1;l<o.length;l++)o[l].timestamp-o[l-1].timestamp>r&&(c.push(i),i=[]),i.push(o[l]);c.push(i);for(const l of c){const m=`${new Date(l[0].timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}`,u=l.map(g=>g.speaker?`${g.speaker}: ${g.text}`:g.text).join(`
|
|
10
|
+
`),p={nodeId:te(1,s++),title:m,depth:1,text:u,tokens:I(u),totalTokens:0,children:[],meta:{firstSentence:l[0].text.slice(0,200),firstParagraph:u.slice(0,1e3),sourceType:e,timestamp:l[0].timestamp}};a.children.push(p)}return ce(a),{source:t,sourceType:e,root:a,totalTokens:a.totalTokens,nodeCount:Ce(a),created:Date.now()}}function nt(t,o,e="flat"){const n={nodeId:"n0-0",title:t,depth:0,text:o.trim(),tokens:I(o),totalTokens:I(o),children:[],meta:{firstSentence:qe(o),firstParagraph:Ue(o),sourceType:e}};return{source:t,sourceType:e,root:n,totalTokens:n.totalTokens,nodeCount:1,created:Date.now()}}const le="<!-- cache-boundary -->";function Ge(t){return t==="anthropic"?"anthropic-prefix":t==="openai"?"openai-auto":t==="google"?"google-context-cache":"none"}function An(t){const{frame:o,hasRepos:e,knowledgeFormatGuide:n,frameworkBlock:s,lessonsBlock:a}=t,r=[o];return a&&r.push(a),e&&n&&r.push(n),s&&r.push(s),r.filter(Boolean)}function Pn(t){const{knowledgeBlock:o,memoryBlock:e,orientationBlock:n}=t;return[o,e,n].filter(Boolean)}function En(t){return{stable:An(t),volatile:Pn(t)}}function In(t,o){const e=t.indexOf(le),n=e>=0?t.slice(0,e):t,s=e>=0?t.slice(e+le.length):"",a=I(n),r=I(s),i=a+r,c=i>0?Math.round(a/i*100):0;return{strategy:o,stableTokens:a,volatileTokens:r,estimatedSavings:c}}function Mn(t){const o=t.indexOf(le);if(o<0)return[{type:"text",text:t,cache_control:{type:"ephemeral"}}];const e=t.slice(0,o),n=t.slice(o+le.length),s=[{type:"text",text:e,cache_control:{type:"ephemeral"}}];return n.trim()&&s.push({type:"text",text:n}),s}const At=/^export\s+(?:default\s+)?(?:async\s+)?(?:declare\s+)?(?:(?:abstract\s+)?class|interface|type|enum|function|(?:const|let|var))\s+(\w+)/,_n=/^\s{2,}(?:(?:public|private|protected|static|async|override|abstract)\s+)*(\w+)\s*(?:<[^>]*>)?\s*\(/,Pt=/^class\s+(\w+)/,Et=/^(?:async\s+)?def\s+(\w+)/,$n=/^ (?:async\s+)?def\s+(\w+)/,Rn=new Set(["if","for","while","switch","catch","return","new","throw","get","set","delete"]);let On=0;function me(t,o,e,n,s,a){return{nodeId:`c${On++}`,title:t,depth:o,text:e,tokens:I(e),totalTokens:0,children:[],meta:{firstSentence:n,firstParagraph:s,sourceType:"code",lineStart:a}}}function It(t){let o=t.tokens;for(const e of t.children)o+=It(e);return t.totalTokens=o,o}function Mt(t){let o=1;for(const e of t.children)o+=Mt(e);return o}function _t(t){const o=t.split(".").pop()?.toLowerCase()??"";return o==="py"?"python":["ts","tsx","js","jsx"].includes(o)?"typescript":"unknown"}function $t(t,o){let e=o-1;for(;e>=0&&t[e].trim()==="";)e--;if(e<0||!t[e].trim().endsWith("*/"))return"";const n=[];for(;e>=0&&!t[e].includes("/**");)n.unshift(t[e]),e--;return e>=0&&n.unshift(t[e]),n.map(s=>s.replace(/^\s*\/\*\*\s?/,"").replace(/^\s*\*\s?/,"").replace(/\s*\*\/\s*$/,"")).filter(s=>s.trim()!=="").join(" ").trim()}function Rt(t,o){let e=0,n=!1;for(let s=o;s<t.length;s++){for(const a of t[s])a==="{"?(e++,n=!0):a==="}"&&e--;if(n&&e===0||!n&&t[s].trim().endsWith(";"))return s}return Math.min(o+10,t.length-1)}function Ot(t,o,e){for(let n=o+1;n<t.length;n++){const s=t[n];if(s.trim()!==""&&s.length-s.trimStart().length<=e)return n-1}return t.length-1}function Fn(t){return/(?:abstract\s+)?class\b/.test(t)?"class":/\binterface\b/.test(t)?"interface":/\btype\b/.test(t)?"type":/\benum\b/.test(t)?"enum":/\bfunction\b/.test(t)?"function":"const"}function Dn(t,o,e){const n=[];for(let s=o+1;s<e;s++){const a=_n.exec(t[s]);if(!a||Rn.has(a[1]))continue;const r=$t(t,s),i=Rt(t,s),c=t.slice(s,i+1).join(`
|
|
11
|
+
`);n.push({name:a[1],signature:t[s].trim(),docstring:r,body:c}),s=i}return n}function Nn(t,o){const e=At.exec(t[o]);if(!e)return null;const n=Fn(t[o]),s=e[1],a=$t(t,o),r=Rt(t,o),i=t.slice(o,r+1).join(`
|
|
12
|
+
`),c=n==="class"?Dn(t,o,r):[];return{name:s,kind:n,signature:t[o].trim(),docstring:a,body:i,lineStart:o,lineEnd:r,isExported:!0,members:c}}function Ln(t){const o=[];for(let e=0;e<t.length;e++){if(!At.test(t[e]))continue;const n=Nn(t,e);n&&(o.push(n),e=n.lineEnd)}return o}function Ft(t,o){let e=o+1;for(;e<t.length&&t[e].trim()==="";)e++;if(e>=t.length)return"";const n=t[e].trim(),s=n.startsWith('"""')?'"""':n.startsWith("'''")?"'''":null;if(!s)return"";if(n.length>6&&n.endsWith(s))return n.slice(3,-3).trim();const a=[n.slice(3)];for(e++;e<t.length&&!t[e].includes(s);)a.push(t[e].trim()),e++;return a.join(" ").trim()}function qn(t,o,e){const n=[];for(let s=o+1;s<=e;s++){const a=$n.exec(t[s]??"");if(!a)continue;const r=Ft(t,s),i=Ot(t,s,4),c=t.slice(s,i+1).join(`
|
|
13
|
+
`);n.push({name:a[1],signature:t[s].trim(),docstring:r,body:c}),s=i}return n}function Un(t,o){const e=Pt.exec(t[o]),n=e?null:Et.exec(t[o]);if(!e&&!n)return null;const s=e?"class":"function",a=e?.[1]??n?.[1]??"",r=Ot(t,o,0),i=Ft(t,o),c=t.slice(o,r+1).join(`
|
|
14
|
+
`),l=s==="class"?qn(t,o,r):[];return{name:a,kind:s,signature:t[o].trim(),docstring:i,body:c,lineStart:o,lineEnd:r,isExported:!0,members:l}}function jn(t){const o=[];for(let e=0;e<t.length;e++){if(!Pt.test(t[e])&&!Et.test(t[e]))continue;const n=Un(t,e);n&&(o.push(n),e=n.lineEnd)}return o}function Kn(t,o){const e=o==="python"?/^(?:import|from)\s+\S/:/^import\s/;return t.filter(n=>e.test(n)).map(n=>n.trim())}function Bn(t,o){const e=t.docstring?`${t.signature}
|
|
15
|
+
${t.docstring}`:t.signature;return me(t.name,o,t.body,t.signature,e)}function Hn(t,o){const e=t.docstring?`${t.signature}
|
|
16
|
+
${t.docstring}`:t.signature,n=me(t.name,o,t.body,t.signature,e,t.lineStart);for(const s of t.members)n.children.push(Bn(s,o+1));return n}function Wn(t,o){const e=t.join(`
|
|
17
|
+
`),n=t.map(s=>s.match(/from\s+['"]([^'"]+)['"]/)?.[1]??s.match(/^from\s+(\S+)/)?.[1]??s.match(/^import\s+(\S+)/)?.[1]??"").filter(Boolean).slice(0,5).join(", ");return me("Imports & Dependencies",o,e,`Imports: ${n}`,e.slice(0,500))}function Ie(t,o,e){const n=o.map(r=>r.name).join(", "),s=o.map(r=>r.signature).join(`
|
|
18
|
+
`),a=me(t,e,s,`${t}: ${n}`,s.slice(0,800));for(const r of o)a.children.push(Hn(r,e+1));return a}function Gn(t,o,e){e.length>0&&t.children.push(Wn(e,1));const n=o.filter(r=>r.kind==="interface"||r.kind==="type"||r.kind==="enum"),s=o.filter(r=>r.kind==="class"),a=o.filter(r=>r.kind==="function"||r.kind==="const");n.length>0&&t.children.push(Ie("Types & Interfaces",n,1)),s.length>0&&t.children.push(Ie("Classes",s,1)),a.length>0&&t.children.push(Ie("Functions & Exports",a,1))}function zn(t,o,e){const n=o.map(r=>r.name),s=n.slice(0,5).join(", "),a=n.length>5?` (+${n.length-5} more)`:"";return{fs:`${e} module: ${s}${a}`,fp:`${t}
|
|
19
|
+
Exports: ${n.join(", ")}
|
|
20
|
+
${o.length} top-level declarations`}}function Yn(t,o){const e=_t(t),n=o.split(`
|
|
21
|
+
`),s=Kn(n,e),a=e==="typescript"?Ln(n):e==="python"?jn(n):[],{fs:r,fp:i}=zn(t,a,e),c=me(t,0,o,r,i);return Gn(c,a,s),It(c),{source:t,sourceType:"code",root:c,totalTokens:c.totalTokens,nodeCount:Mt(c),created:Date.now()}}function Vn(t,o){if(_t(t)==="unknown")return Q(t,o);try{return Yn(t,o)}catch{return Q(t,o)}}const Jn=300*1e3,ge=j((t,o)=>({indexes:{},loading:{},errors:{},indexFile:async e=>{const n=o(),s=n.indexes[e];if(s&&!s.stale&&Date.now()-s.fetchedAt<Jn)return s.index;if(n.loading[e])return s?.index??null;t(a=>({loading:{...a.loading,[e]:!0},errors:{...a.errors,[e]:""}}));try{const r=await(await fetch(`${E}/knowledge/read?path=${encodeURIComponent(e)}`)).json();if(r.status!=="ok"||!r.data)throw new Error(r.error??"Failed to read file");const i=Vn(e,r.data.content),c={index:i,fetchedAt:Date.now(),stale:!1};return t(l=>({indexes:{...l.indexes,[e]:c},loading:{...l.loading,[e]:!1}})),i}catch(a){const r=a instanceof Error?a.message:"Index failed";return t(i=>({loading:{...i.loading,[e]:!1},errors:{...i.errors,[e]:r}})),null}},getIndex:e=>o().indexes[e]?.index??null,indexFiles:async e=>{await Promise.allSettled(e.map(n=>o().indexFile(n)))},invalidate:e=>{t(n=>{const s=n.indexes[e];return s?{indexes:{...n.indexes,[e]:{...s,stale:!0}}}:n})},clearAll:()=>t({indexes:{},loading:{},errors:{}})}));function Dt(t,o,e){if(o===4&&t.depth>0||o===3&&t.depth>e)return null;let n="",s=!1;o===0?n=t.text:o===1?t.children.length===0&&t.meta?.firstParagraph?(n=t.meta.firstParagraph,s=t.text.length>n.length):n=t.text:o===2?(n=t.meta?.firstSentence??"",s=t.text.length>n.length):n="";const a=[];for(const r of t.children){const i=Dt(r,o,e);i&&a.push(i)}return{nodeId:t.nodeId,title:t.title,depth:t.depth,text:n,tokens:I(n),children:a,truncated:s}}function Nt(t){let o=t.tokens+I(t.title);for(const e of t.children)o+=Nt(e);return o}function de(t,o,e){const n=Math.max(0,Math.min(4,o));let a=Dt(t.root,n,2);a||(a={nodeId:t.root.nodeId,title:t.root.title,depth:0,text:"",tokens:0,children:[],truncated:!0});let r=Nt(a);return{source:t.source,filtered:a,totalTokens:r,depthLevel:n,budgetUsed:r,budgetLimit:1/0}}function pe(t){const o=[];t.depth>0&&o.push(`${"#".repeat(t.depth)} ${t.title}`),t.text&&o.push(t.text),t.truncated&&t.depth>0&&o.push(`_[${t.title}: truncated at this depth level]_`);for(const e of t.children)o.push(pe(e));return o.join(`
|
|
22
|
+
|
|
23
|
+
`)}function Lt(t){if(t.length===0)return"";const o=["## Workflow","Follow these steps for every request:",""];return t.forEach((e,n)=>{const s=n+1,a=e.label||`Step ${s}`;let r=`${s}. **${a}:** ${e.action}`;if(e.condition==="if"&&e.conditionText?r+=` *(if ${e.conditionText})*`:e.condition==="unless"&&e.conditionText&&(r+=` *(unless ${e.conditionText})*`),e.tool&&(r+=` [tool: ${e.tool}]`),e.loopTarget){const i=t.findIndex(c=>c.id===e.loopTarget);i>=0&&(r+=` → loop to step ${i+1} (max ${e.loopMax}×)`)}o.push(r)}),o.join(`
|
|
24
|
+
`)}function Qn(t,o,e,n={persona:"",tone:"neutral",expertise:3,constraints:{neverMakeUp:!1,askBeforeActions:!1,stayInScope:!1,useOnlyTools:!1,limitWords:!1,wordLimit:500,customConstraints:"",scopeDefinition:""},objectives:{primary:"",successCriteria:[],failureModes:[]},rawPrompt:"",autoSync:!0},s=[],a={name:"",description:"",icon:"brain",category:"general",tags:[],avatar:"bot"},r=[],i=[]){const c=[],l=t.filter(u=>u.enabled),d=[];if(a.name||e?.name){const u=[];u.push(`Name: ${a.name||e?.name||"Assistant"}`),(a.description||e?.description)&&u.push(`Description: ${a.description||e?.description}`),a.avatar&&u.push(`Avatar: ${a.avatar}`),a.tags&&a.tags.length>0&&u.push(`Tags: ${a.tags.join(", ")}`),d.push(`<identity>
|
|
25
|
+
${u.join(`
|
|
26
|
+
`)}
|
|
27
|
+
</identity>`)}if(n.persona||n.objectives.primary){const u=[];if(n.persona&&u.push(`Persona: ${n.persona}`),n.tone!=="neutral"&&u.push(`Tone: ${n.tone}`),n.expertise!==3){const p=["Beginner","Novice","Intermediate","Advanced","Expert"];u.push(`Expertise Level: ${p[n.expertise-1]} (${n.expertise}/5)`)}n.objectives.primary&&(u.push(`Primary Objective: ${n.objectives.primary}`),n.objectives.successCriteria.length>0&&u.push(`Success Criteria:
|
|
28
|
+
${n.objectives.successCriteria.map(p=>`- ${p}`).join(`
|
|
29
|
+
`)}`),n.objectives.failureModes.length>0&&u.push(`Failure Modes to Avoid:
|
|
30
|
+
${n.objectives.failureModes.map(p=>`- ${p}`).join(`
|
|
31
|
+
`)}`)),d.push(`<instructions>
|
|
32
|
+
${u.join(`
|
|
33
|
+
|
|
34
|
+
`)}
|
|
35
|
+
</instructions>`)}const m=[];if(n.constraints.neverMakeUp&&m.push("Never fabricate information or make up facts"),n.constraints.askBeforeActions&&m.push("Ask for permission before taking significant actions"),n.constraints.stayInScope&&m.push(`Stay within the defined scope: ${n.constraints.scopeDefinition||"as specified"}`),n.constraints.useOnlyTools&&m.push("Only use tools and capabilities that are explicitly provided"),n.constraints.limitWords&&m.push(`Keep responses under ${n.constraints.wordLimit} words`),n.constraints.customConstraints&&m.push(`Additional constraints: ${n.constraints.customConstraints}`),m.length>0&&d.push(`<constraints>
|
|
36
|
+
${m.map(u=>`- ${u}`).join(`
|
|
37
|
+
`)}
|
|
38
|
+
</constraints>`),s.length>0){const u=Lt(s);d.push(`<workflow>
|
|
39
|
+
${u}
|
|
40
|
+
</workflow>`)}if(l.length>0){const u={},p=["ground-truth","signal","evidence","framework","hypothesis","guideline"];for(const y of l)u[y.knowledgeType]||(u[y.knowledgeType]=[]),u[y.knowledgeType].push(y);const g=ge.getState(),f=[];for(const y of p){const k=u[y];if(!k||k.length===0)continue;const h=We[y],w=[];for(const v of k){const C=v.depth||100,M=C/100,T=`${C}%`,P=g.getIndex(v.path);if(P){const _=de(P,0),b=pe(_.filtered);b.trim()?w.push(`<source name="${v.name}" type="${h.label}" depth="${T}" tokens="${_.totalTokens}">
|
|
41
|
+
${b}
|
|
42
|
+
</source>`):w.push(`- ${v.name} (${T}, title only) [${v.path}]`)}else w.push(`- ${v.name} (${T}, ~${Math.round(v.baseTokens*M).toLocaleString()} tokens) [${v.path}]`)}f.push(`[${h.label.toUpperCase()}] ${h.instruction}
|
|
43
|
+
${w.join(`
|
|
44
|
+
`)}`)}d.push(`<knowledge>
|
|
45
|
+
${f.join(`
|
|
46
|
+
|
|
47
|
+
`)}
|
|
48
|
+
</knowledge>`)}if(i.length>0||r.length>0){const u=[];i.length>0&&(u.push("MCP Tools:"),u.push(...i.map(p=>`- ${p.name}: ${p.description||"No description"}`))),r.length>0&&(u.length>0&&u.push(""),u.push("Skills:"),u.push(...r.map(p=>`- ${p.name}: ${p.description||"No description"}`))),d.push(`<tools>
|
|
49
|
+
${u.join(`
|
|
50
|
+
`)}
|
|
51
|
+
</tools>`)}return d.length>0&&c.push({role:"system",content:d.join(`
|
|
52
|
+
|
|
53
|
+
`)}),c.push({role:"user",content:o||"(no prompt provided)"}),c}const ot=/(?:^|[\s`"'([<{])([A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+\.[A-Za-z0-9._-]+)(?=$|[\s`"')\]}>:,;.!?])/g;function ze(t){return t.replace(/\\/g,"/").replace(/\/+/g,"/")}function Zn(t){const o=ze(t),e=o.lastIndexOf("/");return e>0?o.slice(0,e):o}function je(t,o){ot.lastIndex=0;let e;for(;(e=ot.exec(t))!==null;){const n=e[1].replace(/^\.?\//,"");n.includes("/")&&o.add(n)}}function qt(t,o){je(t.title,o),t.text&&je(t.text,o);for(const e of t.children)qt(e,o)}function Xn(t){const o=new Map;for(const e of t){const n=ze(e).replace(/^\.?\//,"");if(!n.includes("/"))continue;const s=n.split("/").filter(Boolean);if(s.length<2)continue;const a=s.length>=3?`${s[0]}/${s[1]}/`:`${s[0]}/`,r=s.length>=3?`${s[2]}${s.length>3?"/":""}`:s[1];o.has(a)||o.set(a,new Set),o.get(a).add(r)}return[...o.entries()].sort(([e],[n])=>e.localeCompare(n)).slice(0,14).map(([e,n])=>{const s=[...n].sort(),a=s.slice(0,8),r=s.length>a.length?", ...":"";return` ${e} -> ${a.join(", ")}${r}`})}function eo(t){const o=t.filter(n=>n.enabled&&n.repoMeta);if(o.length===0)return"";const e=[];for(const n of o){const s=n.repoMeta,a=s.features;if(a.length===0)continue;const r=a[0],c=`src/${r.toLowerCase().replace(/\s+/g,"-")}/index.ts`,l=[`### Example: answering a question about ${s.name}`,`Q: "How does ${r} work?"`,`1. Check Data Flow in "${r}" section → see what files import/depend on each other`,"2. Check Key Files → exports and types tell you the API surface without opening files",`3. Need actual implementation? → \`get_file_contents("${c}")\``];s.baseUrl&&l.push(`4. Need to share a link? → \`${s.baseUrl}{exact_file_path}\``),e.push(l.join(`
|
|
54
|
+
`))}return e.length===0?"":e.join(`
|
|
55
|
+
|
|
56
|
+
`)}function to(t,o){const e=t.filter(d=>d.enabled),n=[],s=e.filter(d=>d.repoMeta);for(const d of s){const m=d.repoMeta,u=d.path?Zn(d.path):"",p=u?e.filter(y=>y.path&&ze(y.path).startsWith(`${u}/`)):[d],g=new Set;for(const y of p){if(y.content&&je(y.content,g),!y.path)continue;const k=o(y.path);k&&qt(k.root,g)}const f=Xn([...g]);n.push(`## ${m.name}`),m.stack.length>0&&n.push(`- Stack: ${m.stack.join(", ")}`),m.baseUrl&&n.push(`- Base URL: ${m.baseUrl}`),n.push(`- ${m.totalFiles} files, key features: ${m.features.join(", ")}`),m.baseUrl&&f.length>0&&(n.push(`- File lookup table (${g.size} paths): use \`${m.baseUrl}{filePath}\``),n.push(...f)),n.push("- You can explore this codebase in depth — read files, trace dependencies, check implementations."),n.push("")}const a=e.filter(d=>!d.repoMeta&&d.content);for(const d of a){const m=We[d.knowledgeType],u=m?m.label:d.knowledgeType;n.push(`## Document: ${d.name}`),n.push(`- Type: ${u}`),n.push("")}if(n.length===0)return"";const r=`You have access to the following codebases and knowledge sources:
|
|
57
|
+
`,i=eo(t),c=i?`
|
|
58
|
+
## How to Use This Knowledge
|
|
59
|
+
${i}
|
|
60
|
+
`:"";return`<orientation>
|
|
61
|
+
${r}
|
|
62
|
+
${n.join(`
|
|
63
|
+
`)}
|
|
64
|
+
${c}Approach:
|
|
65
|
+
- Your knowledge about these codebases is already loaded in your context below. Use it directly.
|
|
66
|
+
- For file contents not in your context, use get_file_contents or read_file tools — NOT the knowledge graph.
|
|
67
|
+
- Do NOT call search_nodes or read_graph to find basic structure — that information is already here.
|
|
68
|
+
- Use each repo's base URL + file path from the lookup table to build exact file links.
|
|
69
|
+
- Explore files and trace dependencies BEFORE asking the user for information.
|
|
70
|
+
</orientation>`}function no(t){const{providerType:o}=t,e=t.knowledgeBlock?ao(t.knowledgeBlock):"";return o&&Ge(o)!=="none"?so({...t,knowledgeBlock:e},o):oo({...t,knowledgeBlock:e})}function oo(t){const{frame:o,orientationBlock:e,hasRepos:n,knowledgeFormatGuide:s,frameworkBlock:a,memoryBlock:r,knowledgeBlock:i,lessonsBlock:c}=t,l=[o];return c&&l.push(c),e&&l.push(e),n&&l.push(s),a&&l.push(a),r&&l.push(r),i&&l.push(i),l.filter(Boolean).join(`
|
|
71
|
+
|
|
72
|
+
`)}function so(t,o){const{stable:e,volatile:n}=En(t),s=Ge(o),a=e.filter(Boolean).join(`
|
|
73
|
+
|
|
74
|
+
`),r=n.filter(Boolean).join(`
|
|
75
|
+
|
|
76
|
+
`);return s==="anthropic-prefix"?[a,le,r].filter(Boolean).join(`
|
|
77
|
+
|
|
78
|
+
`):[a,r].filter(Boolean).join(`
|
|
79
|
+
|
|
80
|
+
`)}function ao(t){if(!t.includes("<knowledge>"))return t;const o=t.match(/<knowledge[^>]*>(.*?)<\/knowledge>/s);if(!o)return t;const e=o[1],n=/<source[^>]*type="([^"]*)"[^>]*>(.*?)<\/source>/gs,s=[],a=[],r={"ground-truth":0,"Ground Truth":0,guideline:1,Guideline:1,framework:2,Framework:2,hypothesis:3,Hypothesis:3,signal:4,Signal:4,evidence:5,Evidence:5};let i=0,c;for(;(c=n.exec(e))!==null;){if(c.index>i){const g=e.slice(i,c.index).trim();g&&a.push(g)}const u=c[1],p=r[u]??3;s.push({type:u,fullMatch:c[0],order:p}),i=c.index+c[0].length}if(i<e.length){const u=e.slice(i).trim();u&&a.push(u)}s.sort((u,p)=>u.order-p.order);const l=[];a.length>0&&l.push(...a),s.length>0&&l.push(...s.map(u=>u.fullMatch));const d=t.match(/<knowledge[^>]*>/);return`${d?d[0]:"<knowledge>"}
|
|
81
|
+
${l.join(`
|
|
82
|
+
|
|
83
|
+
`)}
|
|
84
|
+
</knowledge>`}const B=[{id:"anthropic",name:"Claude",authMethod:"api-key",status:"disconnected",baseUrl:"https://api.anthropic.com/v1",models:[],docsUrl:"https://docs.anthropic.com/en/api",keyPageUrl:"https://console.anthropic.com/settings/keys",pricingUrl:"https://www.anthropic.com/pricing",icon:"Bot",color:"#D4A574",authHeader:"x-api-key",headerNote:"Uses x-api-key header (not Bearer)"},{id:"openai",name:"OpenAI",authMethod:"api-key",status:"disconnected",baseUrl:"https://api.openai.com/v1",models:[],docsUrl:"https://platform.openai.com/docs",keyPageUrl:"https://platform.openai.com/api-keys",pricingUrl:"https://openai.com/pricing",icon:"Sparkles",color:"#10A37F",authHeader:"bearer"},{id:"google",name:"Google AI",authMethod:"api-key",status:"disconnected",baseUrl:"https://generativelanguage.googleapis.com/v1beta",models:[],docsUrl:"https://ai.google.dev/docs",keyPageUrl:"https://aistudio.google.com/app/apikey",pricingUrl:"https://ai.google.dev/pricing",icon:"Gem",color:"#4285F4",authHeader:"query-param",headerNote:"Uses ?key= query parameter"},{id:"claude-agent-sdk",name:"Claude (Agent SDK)",authMethod:"claude-agent-sdk",status:"disconnected",baseUrl:"",apiKey:"",models:[],docsUrl:"https://docs.anthropic.com/en/docs/claude-code/sdk",keyPageUrl:"",icon:"Terminal",color:"#D4A574",authHeader:"bearer",headerNote:"Zero-config — authenticates via Claude Code login"},{id:"openrouter",name:"OpenRouter",authMethod:"api-key",status:"disconnected",baseUrl:"https://openrouter.ai/api/v1",models:[],docsUrl:"https://openrouter.ai/docs",keyPageUrl:"https://openrouter.ai/keys",pricingUrl:"https://openrouter.ai/models",icon:"Route",color:"#6366F1",authHeader:"bearer",headerNote:"HTTP-Referer header recommended"}],Ut="modular-providers";function st(t){const o=t instanceof Error?t.message:String(t);return/failed to fetch|networkerror|load failed/i.test(o)?"Cannot reach backend API. Start server with `npm run server` (port 4800).":o}function ro(t,o){const e=(o||"").trim().replace(/\/+$/,"");return e&&((t==="openai"||e.includes("api.openai.com"))&&!e.endsWith("/v1")?`${e}/v1`:e)}let ne=null,Me=0;const io=3e4,J=new Set,_e=new Map;let $e=!1;async function ue(){const t=Date.now();if(ne!==null&&t-Me<io)return ne;try{ne=(await fetch(`${E}/providers`,{method:"GET",signal:AbortSignal.timeout(2e3)})).ok,Me=t}catch{ne=!1,Me=t}return ne}async function Ye(t){if(!await ue()){J.add(t.id);return}const e=t.id.includes("anthropic")||t.id==="claude-agent-sdk"?"anthropic":t.id.includes("google")?"google":t.id.includes("openrouter")?"openrouter":t.id.includes("openai")?"openai":"custom",n=a=>!a||/^[•]+$/.test(a),s={baseUrl:t.baseUrl,authMethod:t.authMethod,name:t.name,type:e};n(t.apiKey)||(s.apiKey=t.apiKey),n(t.accessToken)||(s.accessToken=t.accessToken),await fetch(`${E}/providers/${t.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)}),J.delete(t.id)}function we(t,o){const e=_e.get(o);e&&clearTimeout(e);const n=setTimeout(()=>{const s=t.find(a=>a.id===o);s&&Ye(s).catch(()=>{J.add(o)}).finally(()=>{_e.delete(o)})},400);_e.set(o,n)}async function Ke(t){if(!($e||J.size===0)){$e=!0;try{if(!await ue())return;const e=[...J];for(const n of e){const s=t.find(a=>a.id===n);if(!s){J.delete(n);continue}try{await Ye(s)}catch{}}}finally{$e=!1}}}function co(){try{const t=localStorage.getItem(Ut);if(!t)return B;const o=JSON.parse(t),e=B.map(a=>{const r=o.find(c=>c.id===a.id);if(!r)return a;const i=r.authMethod??a.authMethod;return{...a,authMethod:i,apiKey:a.apiKey,accessToken:a.accessToken,baseUrl:r.baseUrl??a.baseUrl,status:r.status??a.status}}).concat(o.filter(a=>!B.some(r=>r.id===a.id)).map(a=>{const r=a.authMethod??"api-key";return{...B[B.length-1],...a,authMethod:r,apiKey:"",accessToken:"",id:a.id??"custom-"+Date.now(),name:a.name??"Custom",status:a.status??"disconnected",models:a.models??[{id:"custom-model",label:"Custom Model"}]}})),n=new Set,s=[];for(let a=e.length-1;a>=0;a--)n.has(e[a].id)||(n.add(e[a].id),s.unshift(e[a]));return s}catch{return B}}const lo=new Set(B.map(t=>t.id));function R(t){const o=t.map(e=>{const n=lo.has(e.id);return{id:e.id,name:e.name,baseUrl:e.baseUrl,status:e.status,authMethod:e.authMethod,models:n?void 0:e.models,authHeader:n?void 0:e.authHeader,icon:n?void 0:e.icon,color:n?void 0:e.color,docsUrl:n?void 0:e.docsUrl,keyPageUrl:n?void 0:e.keyPageUrl,headerNote:n?void 0:e.headerNote}});localStorage.setItem(Ut,JSON.stringify(o))}const U=j((t,o)=>({providers:co(),selectedProviderId:"",testing:{},setProviderKey:(e,n)=>{t(s=>{const a=s.providers.map(r=>{if(r.id!==e)return r;const i=!!n.trim(),c=r.authMethod==="oauth"?r.status:i?"configured":"disconnected";return{...r,apiKey:n,status:c}});return R(a),we(a,e),{providers:a}})},setProviderAccessToken:(e,n)=>{t(s=>{const a=s.providers.map(r=>r.id===e?{...r,accessToken:n,status:n.trim()?"configured":r.status}:r);return R(a),we(a,e),{providers:a}})},setProviderAuthMethod:(e,n)=>{t(s=>{const a=s.providers.map(r=>{if(r.id!==e)return r;const i=!!r.apiKey?.trim();return{...r,authMethod:n,status:n==="oauth"||i?"configured":"disconnected",lastError:void 0}});return R(a),we(a,e),{providers:a}})},setProviderBaseUrl:(e,n)=>{t(s=>{const a=ro(e,n),r=s.providers.map(i=>i.id===e?{...i,baseUrl:a}:i);return R(r),we(r,e),{providers:r}})},setProviderStatus:(e,n)=>{t(s=>{const a=s.providers.map(r=>r.id===e?{...r,status:n}:r);return R(a),{providers:a}})},setProviderModels:(e,n)=>{t(s=>{const a=s.providers.map(r=>r.id===e?{...r,models:n}:r);return R(a),{providers:a}})},getProviderForModel:e=>o().providers.find(n=>(Array.isArray(n.models)?n.models:[]).some(s=>s.id===e)),getActiveProvider:()=>o().providers.find(e=>e.id===o().selectedProviderId),getAllModels:()=>o().providers.flatMap(e=>{const n=Array.isArray(e.models)?e.models:[];return n.length===0?[]:e.status==="connected"||e.status==="configured"?n.map(s=>({id:s.id,label:s.label,providerId:e.id,providerName:e.name,providerColor:e.color})):[]}),selectProvider:e=>t({selectedProviderId:e}),testConnection:async e=>{t(n=>({testing:{...n.testing,[e]:!0}}));try{const n=o().providers.find(a=>a.id===e);if(n?.authMethod==="oauth"&&!n.apiKey?.trim()){const a='Codex sign-in not completed yet. Use "Sign in with Codex" first.';return t(r=>({testing:{...r.testing,[e]:!1},providers:r.providers.map(i=>i.id===e?{...i,status:"error",lastError:a}:i)})),R(o().providers),{ok:!1,error:a}}if(n?.authMethod==="claude-agent-sdk")try{const a=await fetch(`${E}/agent-sdk/status`);if(a.status===429)return t(m=>({testing:{...m.testing,[e]:!1}})),{ok:!1,error:"Rate limited — try again in a moment"};const r=await a.json(),i=r?.data,c=i?.authenticated===!0,l=c&&i?.email?`${i.displayName||"User"} (${i.email})`:void 0,d=Array.isArray(i?.models)?i.models.map(m=>({id:m,label:m})):[];return t(m=>({testing:{...m.testing,[e]:!1},providers:m.providers.map(u=>u.id===e?{...u,status:c?"connected":"error",models:d.length>0?d:u.models,lastError:c?l:i?.error||"Not authenticated"}:u)})),R(o().providers),c?{ok:!0,models:d.map(m=>m.id)}:{ok:!1,error:r?.data?.error||"Not authenticated — run `claude` in your terminal first"}}catch(a){const r=st(a);return t(i=>({testing:{...i.testing,[e]:!1},providers:i.providers.map(c=>c.id===e?{...c,status:"error",lastError:r}:c)})),R(o().providers),{ok:!1,error:r}}if(await ue()){const a=o().providers.find(d=>d.id===e),r=a?.apiKey&&!/^[•]+$/.test(a.apiKey);a&&r&&await fetch(`${E}/providers/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:a.apiKey,baseUrl:a.baseUrl})});const i={baseUrl:a?.baseUrl||""};r&&(i.apiKey=a.apiKey);const l=await(await fetch(`${E}/providers/${e}/test`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)})).json();if(l.status==="ok"){const d=l.data?.models??l.models??[],m=d.map(u=>({id:u,label:u}));return t(u=>({testing:{...u.testing,[e]:!1},providers:u.providers.map(p=>p.id===e?{...p,status:"connected",models:m.length?m:p.models,lastError:void 0}:p)})),R(o().providers),{ok:!0,models:d}}else return t(d=>({testing:{...d.testing,[e]:!1},providers:d.providers.map(m=>m.id===e?{...m,status:"error",lastError:l.error}:m)})),R(o().providers),{ok:!1,error:l.error}}else return o().providers.find(r=>r.id===e)?.apiKey?(t(r=>({testing:{...r.testing,[e]:!1},providers:r.providers.map(i=>i.id===e?{...i,status:"connected",lastError:void 0}:i)})),R(o().providers),{ok:!0}):(t(r=>({testing:{...r.testing,[e]:!1}})),{ok:!1,error:"No API key configured"})}catch(n){const s=st(n);return t(a=>({testing:{...a.testing,[e]:!1},providers:a.providers.map(r=>r.id===e?{...r,status:"error",lastError:s}:r)})),R(o().providers),{ok:!1,error:s}}},saveProvider:async e=>{const n=o().providers,s=n.find(a=>a.id===e);if(s){R(n);try{await Ye(s)}catch{J.add(e)}Ke(o().providers).catch(()=>{})}},deleteProvider:e=>{t(n=>{const s=n.providers.filter(a=>a.id!==e);return R(s),{providers:s}}),ue().then(n=>{n&&fetch(`${E}/providers/${e}`,{method:"DELETE"}).catch(()=>{})})},addCustomProvider:()=>{const n={id:"custom-"+Date.now(),name:"Custom Provider",authMethod:"api-key",status:"disconnected",baseUrl:"http://localhost:11434/v1",models:[{id:"custom-model",label:"Custom Model"}],docsUrl:"",keyPageUrl:"",icon:"Server",color:"#888888",authHeader:"bearer",headerNote:"For Ollama, vLLM, or any OpenAI-compatible API"};t(s=>{const a=[...s.providers,n];return R(a),{providers:a}})},loadFromBackend:async()=>{try{const e=await fetch(`${E}/providers`);if(!e.ok)return;const n=await e.json(),s=Array.isArray(n)?n:Array.isArray(n?.data)?n.data:[];if(s.length>0){const a=B.map(p=>{const g=s.find(h=>h.id===p.id);if(!g)return p;const f=g,y=!!f.hasStoredKey,k=!!f.hasStoredAccessToken;return{...p,...g,name:p.id==="anthropic"?"Claude":g.name||p.name,apiKey:y?"":p.apiKey,accessToken:k?"":p.accessToken,_hasStoredKey:y,_hasStoredAccessToken:k,status:y||k?"configured":g.status||p.status,models:Array.isArray(g.models)?g.models:p.models}}),r=s.filter(p=>!B.some(g=>g.id===p.id)).map(p=>({...p,models:Array.isArray(p.models)?p.models:[]})),i=[...a,...r],c=o().selectedProviderId,l=i.find(p=>p.id===c),d=!!(l&&(l.status==="connected"||l.status==="configured")&&Array.isArray(l.models)&&l.models.length>0),m=i.find(p=>(p.status==="connected"||p.status==="configured")&&Array.isArray(p.models)&&p.models.length>0),u=d?c:m?.id||"";t({providers:i,selectedProviderId:u}),R(o().providers),await Ke(o().providers);for(const p of i)(p._hasStoredKey||p._hasStoredAccessToken||p.authMethod==="claude-agent-sdk")&&(p.status==="configured"||p.status==="connected")&&(!Array.isArray(p.models)||p.models.length===0)&&setTimeout(()=>U.getState().testConnection(p.id),200)}}catch{}}}));ue().then(t=>{t&&(U.getState().loadFromBackend(),Ke(U.getState().providers).catch(()=>{}))});const po={agentMeta:{name:"React Code Reviewer",description:"Senior React engineer specializing in code quality, TypeScript best practices, and accessibility compliance",icon:"search",category:"coding",tags:["react","code-review","typescript","accessibility"],avatar:"bug"},instructionState:{persona:"You are a senior React engineer with 8+ years of experience in building production-ready applications. You have deep expertise in TypeScript, modern React patterns, performance optimization, and web accessibility standards.",tone:"formal",expertise:5,constraints:{neverMakeUp:!0,askBeforeActions:!1,stayInScope:!0,useOnlyTools:!1,limitWords:!1,wordLimit:500,customConstraints:"Always provide specific line numbers and actionable suggestions",scopeDefinition:"Code review for React/TypeScript applications with focus on quality, performance, and accessibility"},objectives:{primary:"Provide thorough, actionable code reviews that improve code quality and maintainability",successCriteria:["Identify potential bugs and performance issues","Suggest accessibility improvements","Maintain consistency with React/TypeScript best practices","Provide specific, actionable feedback with examples"],failureModes:["Generic or vague feedback without specific suggestions","Missing critical accessibility issues","Approving code with TypeScript type safety violations","Ignoring performance implications"]},rawPrompt:"",autoSync:!0},workflowSteps:[{id:"step-analyze-diff",label:"Analyze Code Changes",action:"Read and understand the code diff, identifying the scope and purpose of changes",tool:"",condition:"always",conditionValue:""},{id:"step-style-check",label:"Check Code Style",action:"Verify code follows React/TypeScript best practices and coding standards",tool:"skill:clean-code",condition:"always",conditionValue:""},{id:"step-accessibility",label:"Review Accessibility",action:"Check for accessibility violations and suggest improvements for screen readers and keyboard navigation",tool:"",condition:"always",conditionValue:""},{id:"step-categorize-issues",label:"Categorize Issues",action:"Classify identified issues by severity: critical (blocking), major (important), minor (nice-to-have)",tool:"",condition:"always",conditionValue:""},{id:"step-write-review",label:"Write Comprehensive Review",action:"Compose detailed review with specific line references, code examples, and actionable suggestions",tool:"",condition:"always",conditionValue:""}],channels:[{sourceId:"react-style-guide",name:"React Style Guide",path:"docs/react-style-guide.md",category:"knowledge",knowledgeType:"framework",enabled:!0,depth:2,baseTokens:1500},{sourceId:"accessibility-checklist",name:"Accessibility Checklist",path:"docs/accessibility-checklist.md",category:"knowledge",knowledgeType:"evidence",enabled:!0,depth:3,baseTokens:800}],skills:[{id:"clean-code",name:"Clean Code",icon:"✨",enabled:!0,added:!0,description:"Pragmatic coding standards - concise, direct, no over-engineering",category:"development"}],mcpServers:[{id:"github",name:"GitHub",icon:"🐙",connected:!0,enabled:!0,added:!0,capabilities:["input","output"],category:"development",description:"Access GitHub repositories, PRs, and issues"}]},uo={agentMeta:{name:"Senior PM",description:"Senior Product Manager specializing in discovery synthesis, product strategy, and opportunity analysis. Turns messy brainstorms into clear product strategy.",icon:"user",category:"strategy",tags:["discovery","strategy","synthesis","prioritization"],avatar:"target"},instructionState:{persona:"You are a Senior Product Manager with 10+ years building B2B SaaS products. You excel at discovery work, synthesizing messy conversations into clear product strategy, and translating customer/team insights into prioritized roadmap decisions.",tone:"formal",expertise:5,constraints:{neverMakeUp:!0,askBeforeActions:!1,stayInScope:!0,useOnlyTools:!1,limitWords:!1,wordLimit:500,customConstraints:"Strategic but practical — connect dots between insights and execution. Framework-driven — use opportunity solution trees, RICE, impact mapping. Hypothesis-oriented — frame everything as assumptions to validate. Trade-off aware — always consider what we are NOT doing. Customer-outcome focused — start with customer value, not features.",scopeDefinition:"Discovery synthesis, product strategy, opportunity analysis, roadmap prioritization"},objectives:{primary:"Synthesize product team discussions into clear, prioritized product opportunities with actionable next steps",successCriteria:["TL;DR with top 3 takeaways","Key opportunities grouped by theme","Customer pain points identified","Prioritization using RICE or similar framework","Discovery plan with validation steps"],failureModes:["Listing features without strategic context","Missing underlying customer needs behind surface requests","No prioritization or all items marked equal priority","Skipping hypothesis formation and validation planning"]},rawPrompt:"",autoSync:!0},workflowSteps:[{id:"step-tldr",label:"TL;DR",action:"Extract top 3 takeaways in one sentence each",tool:"",condition:"always"},{id:"step-opportunities",label:"Key Opportunities",action:"Identify product ideas/improvements discussed, grouped by theme",tool:"",condition:"always"},{id:"step-pain-points",label:"Customer Pain Points",action:"Extract problems being solved and underlying needs",tool:"",condition:"always"},{id:"step-strategic",label:"Strategic Implications",action:"Analyze how findings affect roadmap and positioning",tool:"",condition:"always"},{id:"step-hypotheses",label:"Assumptions & Hypotheses",action:"Frame beliefs that need validation with evidence and signals",tool:"",condition:"always"},{id:"step-prioritize",label:"Prioritization",action:"Recommend what to tackle first using RICE (Reach, Impact, Confidence, Effort)",tool:"",condition:"always"},{id:"step-discovery-plan",label:"Discovery Plan",action:"Define how to validate key hypotheses — research needed, experiments",tool:"",condition:"always"},{id:"step-risks",label:"Dependencies & Risks",action:"Flag technical, organizational, and market blockers",tool:"",condition:"always"},{id:"step-next-steps",label:"Next Steps",action:"List concrete actions with owners and timelines",tool:"",condition:"always"}],channels:[{sourceId:"knowledge-products",name:"Products",path:"00 - Knowledge/Products/",category:"knowledge",knowledgeType:"ground-truth",enabled:!0,depth:0,baseTokens:16e3},{sourceId:"knowledge-products-feedback",name:"Feedback",path:"00 - Knowledge/Products/Feedback/",category:"knowledge",knowledgeType:"signal",enabled:!0,depth:0,baseTokens:4800},{sourceId:"signals-odfjell",name:"User feedback / Odfjell",path:"07 - Signals/User feedback/odfjell/",category:"intel",knowledgeType:"signal",enabled:!0,depth:1,baseTokens:6800},{sourceId:"signals-kcc",name:"User feedback / KCC",path:"07 - Signals/User feedback/kcc/",category:"intel",knowledgeType:"signal",enabled:!0,depth:1,baseTokens:5200},{sourceId:"signals-general",name:"User feedback / General",path:"07 - Signals/User feedback/general/",category:"intel",knowledgeType:"signal",enabled:!0,depth:1,baseTokens:7500},{sourceId:"discovery-eu-ets",name:"EU ETS Cost Layer",path:"01 - Discovery/EU ETS Cost Layer/",category:"discovery",knowledgeType:"hypothesis",enabled:!0,depth:2,baseTokens:3200},{sourceId:"discovery-weather-routing",name:"Weather Routing v2",path:"01 - Discovery/Weather Routing v2/",category:"discovery",knowledgeType:"hypothesis",enabled:!0,depth:2,baseTokens:4100},{sourceId:"discovery-fleet-dashboard",name:"Fleet Dashboard",path:"01 - Discovery/Fleet Dashboard/",category:"discovery",knowledgeType:"hypothesis",enabled:!0,depth:2,baseTokens:3500},{sourceId:"roadmap",name:"03 - Roadmap",path:"03 - Roadmap/",category:"knowledge",knowledgeType:"framework",enabled:!0,depth:1,baseTokens:12e3}],skills:[{id:"feedback-analyzer",name:"Feedback Analyzer",icon:"📊",enabled:!0,added:!0,description:"Extract insights from customer feedback",category:"analysis"},{id:"roadmap-builder",name:"Roadmap Builder",icon:"🗺️",enabled:!0,added:!0,description:"Create strategic product roadmaps with OKRs",category:"content"}],mcpServers:[{id:"notion",name:"Notion",icon:"📓",connected:!0,enabled:!0,added:!0,capabilities:["input","output"],category:"productivity",description:"Read and write Notion pages and databases"},{id:"slack",name:"Slack",icon:"💬",connected:!0,enabled:!0,added:!0,capabilities:["input","output"],category:"communication",description:"Read and post Slack messages"}]},mo={agentMeta:{name:"Feedback Manager",description:"Feedback lifecycle specialist — organizes, challenges, and maintains the single source of truth for user feedback. Monitors Gmail, connects feedback to product features, proposes improvements.",icon:"inbox",category:"feedback",tags:["feedback","triage","patterns","improvement"],avatar:"chart"},instructionState:{persona:"You are a specialized Product Manager focused on feedback management and intelligence. You maintain the single source of truth for all user feedback, ensuring it's organized, challenged, contextualized with current product features, and continuously refined.",tone:"neutral",expertise:4,constraints:{neverMakeUp:!0,askBeforeActions:!0,stayInScope:!0,useOnlyTools:!1,limitWords:!1,wordLimit:500,customConstraints:`Curious and probing — always ask "why?" and "what's the underlying need?". Pattern-oriented — look for recurring themes. Feature-aware — reference specific product capabilities. Actionable — turn feedback into concrete improvement proposals. Organized — maintain clean, accessible feedback repository.`,scopeDefinition:"Feedback triage, pattern recognition, improvement proposals, repository maintenance"},objectives:{primary:"Process and organize user feedback into actionable insights, maintaining a clean feedback repository with pattern detection and improvement proposals",successCriteria:["New feedback triaged within workflow","Patterns detected across feedback sources","Improvement proposals with rationale and priority","Feedback connected to current product capabilities","Repository organized and deduplicated"],failureModes:["Taking feedback at face value without probing deeper","Missing recurring patterns across sources","No connection between feedback and existing product features","Feedback stored without actionable improvement proposals"]},rawPrompt:"",autoSync:!0},workflowSteps:[{id:"step-initial-analysis",label:"Initial Analysis",action:"Quick pattern detection, sentiment analysis, theme identification, extract key quotes using feedback-analyzer skill",tool:"skill:feedback-analyzer",condition:"always"},{id:"step-triage",label:"Triage",action:"Ask clarifying questions: which product/feature, user role, frequency/severity, blocking vs inconvenient",tool:"",condition:"always"},{id:"step-deep-dive",label:"Deep Dive",action:"Uncover real pain point, identify job-to-be-done, find behavioral patterns, challenge assumptions",tool:"",condition:"always"},{id:"step-strategic-synthesis",label:"Strategic Synthesis",action:"Alignment with product strategy, opportunity sizing, prioritization recommendation",tool:"",condition:"always"},{id:"step-contextualize",label:"Contextualize with Product",action:"Check if capability exists, identify gap/enhancement/misunderstanding, find related features",tool:"",condition:"always"},{id:"step-categorize",label:"Categorize & Store",action:"Tag by product, type (Bug/Enhancement/Feature), user type, severity, frequency, status",tool:"",condition:"always"},{id:"step-patterns",label:"Pattern Recognition",action:"Check against existing patterns, update PATTERNS.md if new theme, flag recurring issues",tool:"",condition:"always"}],channels:[{sourceId:"knowledge-products-feedback",name:"Feedback",path:"00 - Knowledge/Products/Feedback/",category:"knowledge",knowledgeType:"signal",enabled:!0,depth:0,baseTokens:4800},{sourceId:"signals-odfjell",name:"User feedback / Odfjell",path:"07 - Signals/User feedback/odfjell/",category:"intel",knowledgeType:"signal",enabled:!0,depth:0,baseTokens:6800},{sourceId:"signals-kcc",name:"User feedback / KCC",path:"07 - Signals/User feedback/kcc/",category:"intel",knowledgeType:"signal",enabled:!0,depth:0,baseTokens:5200},{sourceId:"signals-baru",name:"User feedback / Baru",path:"07 - Signals/User feedback/baru/",category:"intel",knowledgeType:"signal",enabled:!0,depth:0,baseTokens:4500},{sourceId:"signals-general",name:"User feedback / General",path:"07 - Signals/User feedback/general/",category:"intel",knowledgeType:"signal",enabled:!0,depth:0,baseTokens:7500},{sourceId:"intel-feedback",name:"04 - Feedback Synthesis",path:"05 - Intel/04 - Feedback Synthesis/",category:"intel",knowledgeType:"evidence",enabled:!0,depth:1,baseTokens:4800}],skills:[{id:"feedback-analyzer",name:"Feedback Analyzer",icon:"📊",enabled:!0,added:!0,description:"Extract insights from customer feedback — patterns, sentiment, priorities",category:"analysis"}],mcpServers:[{id:"gmail",name:"Gmail",icon:"📧",connected:!0,enabled:!0,added:!0,capabilities:["input"],category:"communication",description:"Read Gmail OnWatch label for captain feedback"},{id:"notion",name:"Notion",icon:"📓",connected:!0,enabled:!0,added:!0,capabilities:["input","output"],category:"productivity",description:"CSM Team Hub and feedback databases"},{id:"slack",name:"Slack",icon:"💬",connected:!0,enabled:!0,added:!0,capabilities:["output"],category:"communication",description:"Send critical feedback alerts"}]},go={agentMeta:{name:"Competitor Feature Scraper",description:"Systematically scrapes competitor product pages to extract features, claims, screenshots, and target users. Produces structured feature profiles for competitive comparison.",icon:"search",category:"intel",tags:["competitors","scraping","features","intel"],avatar:"microscope"},instructionState:{persona:"You are a specialized competitive intelligence agent that systematically scrapes competitor websites to extract product features, claims, metrics, and screenshots. You produce structured feature profiles that feed into the competitive comparison matrix.",tone:"neutral",expertise:4,constraints:{neverMakeUp:!0,askBeforeActions:!1,stayInScope:!0,useOnlyTools:!0,limitWords:!1,wordLimit:500,customConstraints:'Only extract factual claims from competitor pages — never infer or embellish. Mark unverified claims as "Claimed". Save raw scrape data for re-processing. Respect rate limits (max 10 parallel scrapes).',scopeDefinition:"Competitor product page scraping, feature extraction, structured profile generation"},objectives:{primary:"Scrape competitor websites and produce structured FEATURES.md profiles with feature names, descriptions, claims, screenshots, and taxonomy mapping",successCriteria:["All discoverable product pages scraped","Each feature has name, description, and source URL","Screenshots downloaded for key features","Features mapped to taxonomy categories","Raw scrape data saved for re-processing"],failureModes:["Missing product pages due to incomplete site discovery","Inferring features not actually claimed by competitor","No screenshots captured for visual comparison","Features not mapped to standard taxonomy"]},rawPrompt:"",autoSync:!0},workflowSteps:[{id:"step-setup",label:"Setup",action:"Verify Firecrawl is available, create output directories for competitor",tool:"bash",condition:"always"},{id:"step-discover",label:"Discover Pages",action:"Use Firecrawl map to find all product/feature pages, filter for relevant URLs",tool:"skill:firecrawl",condition:"always"},{id:"step-scrape",label:"Scrape Pages",action:"Scrape each feature page for content + screenshot (up to 10 concurrent)",tool:"skill:firecrawl",condition:"always"},{id:"step-extract",label:"Extract Features",action:"Extract feature name, description, key claims, metrics, target user, screenshot URL",tool:"",condition:"always"},{id:"step-taxonomy",label:"Map to Taxonomy",action:"Read _FEATURE_TAXONOMY.md and map each feature to taxonomy categories",tool:"",condition:"always"},{id:"step-write",label:"Write Profile",action:"Generate structured FEATURES.md with summary table and detailed feature sections",tool:"",condition:"always"}],channels:[{sourceId:"knowledge-competitors",name:"Competitors",path:"00 - Knowledge/Competitors/",category:"knowledge",knowledgeType:"evidence",enabled:!0,depth:0,baseTokens:22e3},{sourceId:"intel-competitive",name:"01 - Competitive Intel",path:"05 - Intel/01 - Competitive Intel/",category:"intel",knowledgeType:"evidence",enabled:!0,depth:0,baseTokens:12e3},{sourceId:"cmo-competitive-intel",name:"05 - Competitive Intel",path:"CMO-Handoff/05 - Competitive Intel/",category:"intel",knowledgeType:"evidence",enabled:!0,depth:1,baseTokens:5800}],skills:[{id:"web-search",name:"Web Search",icon:"🔎",enabled:!0,added:!0,description:"Search the web for competitor information",category:"analysis"}],mcpServers:[{id:"firecrawl",name:"Firecrawl",icon:"🔥",connected:!0,enabled:!0,added:!0,capabilities:["input"],category:"data",description:"Web scraping, crawling, and site mapping"}]},ho={"senior-pm":uo,"feedback-manager":mo,"competitor-scraper":go};let G;function Re(t){return t==="coding"?"development":t==="research"?"analysis":t==="design"||t==="writing"?"content":t==="domain"?"domain":"content"}function at(t){return t==="coding"?"development":t==="research"?"data":t==="writing"?"productivity":"data"}function rt(t,o){return t.map(e=>e.id===o?{...e,enabled:!e.enabled}:e)}function it(t,o){return t.map(e=>e.id===o?{...e,added:!0,enabled:!0}:e)}function ct(t,o){return t.map(e=>e.id===o?{...e,added:!1,enabled:!1}:e)}function jt(t){if(!t.enabled)return 0;const o=Te[t.depth]??Te[0];return Math.round(t.baseTokens*o.pct)}const F=j()(mn((t,o)=>({channels:[],prompt:"",selectedModel:"claude-opus-4",selectedPreset:"",outputFormat:"markdown",outputFormats:["markdown"],tokenBudget:2e5,navigationMode:"tree-aware",running:!1,showFilePicker:!1,showMcpPicker:!1,showSkillPicker:!1,showSaveModal:!1,showConnectorPicker:!1,showConnectionPicker:!1,showMarketplace:!1,activeMarketplaceTab:"skills",showSettings:!1,activeSettingsTab:"providers",response:"",exportTarget:"claude",knowledgeGaps:[],registrySkills:Ee.map(e=>({...e})),registryMcpServers:Tn.map(e=>({...e})),agentConfig:{...tt},agentMeta:{name:"",description:"",icon:"brain",category:"general",tags:[],avatar:"bot"},mcpServers:[],skills:Ee.filter(e=>e.installed).map(e=>({id:e.id,name:e.name,icon:e.icon,enabled:!1,added:!1,description:e.description,category:Re(e.category)})),agents:[],connectors:[],pendingKnowledge:[],suggestedSkills:[],instructionState:{persona:"",tone:"neutral",expertise:3,constraints:{neverMakeUp:!1,askBeforeActions:!1,stayInScope:!1,useOnlyTools:!1,limitWords:!1,wordLimit:500,customConstraints:"",scopeDefinition:""},objectives:{primary:"",successCriteria:[],failureModes:[]},rawPrompt:"",autoSync:!0},workflowSteps:[],outputTemplateConfig:{},agentPattern:"prompt-chain",verification:{enabled:!1,strategy:"none",rules:[],crossRefSources:[],confidenceRequired:!1,autoRetryOnFail:!1,maxRetries:2},errorHandling:{onStepFailure:"abort",retryCount:1,fallbackAction:"",checkpointEnabled:!1,timeoutSeconds:0,gracefulDegradation:!1},evaluation:{enabled:!1,criteria:[],expectedOutputFormat:"",qualityRubric:""},totalTokens:()=>{const{channels:e,prompt:n}=o(),s=e.reduce((r,i)=>r+jt(i),0),a=Math.ceil(n.length/4);return s+a},loadPreset:e=>{const n=vn.find(r=>r.id===e);if(!n)return;const s=n.channels.map(r=>({...r,enabled:!0})),a={...tt,...n.agentConfig};t({channels:s,selectedPreset:e,response:"",agentConfig:a})},setOutputFormat:e=>t({outputFormat:e,outputFormats:[e]}),toggleOutputFormat:e=>{const n=o().outputFormats,s=n.includes(e)?n.filter(a=>a!==e):[...n,e];s.length!==0&&t({outputFormats:s,outputFormat:s[0]})},cycleKnowledgeType:e=>{const n=["ground-truth","signal","evidence","framework","hypothesis","guideline"];t({channels:o().channels.map(s=>{if(s.sourceId!==e)return s;const a=n.indexOf(s.knowledgeType);return{...s,knowledgeType:n[(a+1)%n.length]}})})},addChannel:e=>{const{channels:n}=o();if(n.some(a=>a.sourceId===e.sourceId))return;const s={...e};if(e.path){const a=Le(e.path,e.content);(!e.knowledgeType||e.knowledgeType==="evidence")&&(s.knowledgeType=a.knowledgeType),(e.depth===void 0||e.depth===null)&&(s.depth=a.depth)}t({channels:[...n,{...s,enabled:!0}],selectedPreset:""})},removeChannel:e=>{t({channels:o().channels.filter(n=>n.sourceId!==e),selectedPreset:""})},toggleChannel:e=>{t({channels:o().channels.map(n=>n.sourceId===e?{...n,enabled:!n.enabled}:n)})},setChannelDepth:(e,n)=>{t({channels:o().channels.map(s=>s.sourceId===e?{...s,depth:Math.max(10,Math.min(100,n))}:s)})},setPrompt:e=>{const n=bn(e);t({prompt:e,outputFormat:n})},setModel:e=>t(n=>({selectedModel:e,agentConfig:{...n.agentConfig,model:e}})),setTokenBudget:e=>t({tokenBudget:e}),setNavigationMode:e=>t({navigationMode:e}),setShowFilePicker:e=>t({showFilePicker:e}),setShowMcpPicker:e=>t({showMcpPicker:e}),setShowSkillPicker:e=>t({showSkillPicker:e}),setShowSaveModal:e=>t({showSaveModal:e}),setShowConnectorPicker:e=>t({showConnectorPicker:e}),setShowConnectionPicker:e=>t({showConnectionPicker:e}),setShowMarketplace:(e,n)=>t({showMarketplace:e,...n?{activeMarketplaceTab:n}:{}}),setShowSettings:(e,n)=>t({showSettings:e,...n?{activeSettingsTab:n}:{}}),setAgentMeta:e=>t({agentMeta:{...o().agentMeta,...e}}),setChannelKnowledgeType:(e,n)=>{const s=["ground-truth","signal","evidence","framework","hypothesis","guideline"],a=s[Math.max(0,Math.min(s.length-1,n))];t({channels:o().channels.map(r=>r.sourceId===e?{...r,knowledgeType:a}:r)})},reorderChannels:(e,n)=>{const s=[...o().channels],[a]=s.splice(e,1);s.splice(n,0,a),t({channels:s,selectedPreset:""})},run:async()=>{const{running:e,prompt:n,channels:s}=o();if(e){o().cancelRun();return}const r=U.getState().getActiveProvider(),i=r?.authMethod==="claude-agent-sdk";if(!i&&!r?.apiKey){t({response:"Error: No API key configured. Open Settings → Providers to add your API key."});return}t({running:!0,response:""});const c=o(),l=c.skills.filter(y=>y.enabled),{useMcpStore:d}=await se(async()=>{const{useMcpStore:y}=await Promise.resolve().then(()=>Fe);return{useMcpStore:y}},void 0),m=d.getState().getConnectedTools(),u=Qn(s,n,void 0,c.instructionState,c.workflowSteps,c.agentMeta,l,m),p=o().agentConfig.model;let g="";if(i){const y=u.filter(w=>w.role==="system").map(w=>w.content),k=u.filter(w=>w.role==="user").map(w=>w.content).join(`
|
|
85
|
+
`);G=xt({prompt:k||n,model:p,systemPrompt:y.join(`
|
|
86
|
+
`)||void 0,onChunk:w=>{g+=w,t({response:g})},onDone:()=>{t({running:!1}),G=void 0},onError:w=>{t({running:!1,response:`Error: ${w.message}`}),G=void 0}});return}G=Ct({providerId:r?.id||"",model:p,messages:u,onChunk:y=>{g+=y,t({response:g})},onDone:()=>{t({running:!1}),G=void 0},onError:y=>{t({running:!1,response:`Error: ${y.message}`}),G=void 0}})},cancelRun:()=>{const e=G;e&&e.abort(),t({running:!1}),G=void 0},clearChannels:()=>t({channels:[],selectedPreset:"",response:""}),setAgentModel:e=>t({agentConfig:{...o().agentConfig,model:e}}),setAgentTemperature:e=>t({agentConfig:{...o().agentConfig,temperature:e}}),setAgentSystemPrompt:e=>t({agentConfig:{...o().agentConfig,systemPrompt:e}}),setAgentPlanningMode:e=>t({agentConfig:{...o().agentConfig,planningMode:e}}),setAgentMaxTokens:e=>t({agentConfig:{...o().agentConfig,maxTokens:e}}),toggleMcp:e=>{t({mcpServers:rt(o().mcpServers,e)})},addMcp:e=>{t({mcpServers:it(o().mcpServers,e)})},removeMcp:e=>{t({mcpServers:ct(o().mcpServers,e)})},upsertMcpServer:e=>{if(o().mcpServers.find(s=>s.id===e.id)){t({mcpServers:o().mcpServers.map(s=>s.id===e.id?{...s,name:e.name,description:e.description??s.description,connected:e.connected??s.connected}:s)});return}t({mcpServers:[...o().mcpServers,{id:e.id,name:e.name,icon:"plug",connected:e.connected??!1,enabled:!0,added:!0,capabilities:["input","output"],category:"data",description:e.description??"Custom MCP server"}]})},removeMcpServer:e=>{t({mcpServers:o().mcpServers.filter(n=>n.id!==e)})},toggleSkill:e=>{t({skills:rt(o().skills,e)})},addSkill:e=>{t({skills:it(o().skills,e)})},removeSkill:e=>{t({skills:ct(o().skills,e)})},upsertSkill:e=>{if(o().skills.find(s=>s.id===e.id)){t({skills:o().skills.map(s=>s.id===e.id?{...s,name:e.name||s.name,description:e.description&&e.description.length>0?e.description:s.description,skillUrl:e.skillUrl??s.skillUrl,installedFrom:e.installedFrom??s.installedFrom,installs:e.installs??s.installs}:s)});return}t({skills:[...o().skills,{id:e.id,name:e.name,icon:"zap",enabled:!1,added:!1,description:e.description??"Installed from skills.sh",category:"development",skillUrl:e.skillUrl,installedFrom:e.installedFrom,installs:e.installs}]})},loadAgent:e=>{(async()=>{try{const n=await fetch(`${E}/agents/${encodeURIComponent(e)}`);if(!n.ok)return;const s=await n.json(),a=s.data??s;o().restoreFullState(a);try{const{useMcpStore:r}=await se(async()=>{const{useMcpStore:l}=await Promise.resolve().then(()=>Fe);return{useMcpStore:l}},void 0),i=r.getState(),c=a.mcpServers??[];for(const l of c){if(!l.connected&&!l.enabled)continue;const d=i.servers.find(m=>m.id===l.id);d?d.status!=="connected"&&i.connectServer(l.id):await i.addServer({id:l.id,name:l.name,command:"",args:[],env:{}})&&i.connectServer(l.id)}}catch{}}catch{}})()},restoreFullState:e=>{const n={};if(e.agentMeta){const s=e.agentMeta;n.agentMeta={name:s.name||"",description:s.description||"",icon:s.icon||"brain",category:s.category||"general",tags:s.tags||[],avatar:s.avatar||"bot"}}if(e.instructionState){const s=e.instructionState,a=s.constraints||{},r=s.objectives||{};n.instructionState={persona:s.persona||"",tone:s.tone||"neutral",expertise:s.expertise||3,constraints:{neverMakeUp:a.neverMakeUp??!0,askBeforeActions:a.askBeforeActions??!1,stayInScope:a.stayInScope??!0,useOnlyTools:a.useOnlyTools??!1,limitWords:a.limitWords??!1,wordLimit:a.wordLimit||0,customConstraints:a.customConstraints||"",scopeDefinition:a.scopeDefinition||""},objectives:{primary:r.primary||"",successCriteria:r.successCriteria||[],failureModes:r.failureModes||[]},rawPrompt:s.rawPrompt||"",autoSync:s.autoSync??!0}}e.workflowSteps&&(n.workflowSteps=e.workflowSteps),e.mcpServers&&(n.mcpServers=e.mcpServers),e.skills&&(n.skills=e.skills),e.connectors&&(n.connectors=e.connectors),e.agentConfig&&(n.agentConfig=e.agentConfig),e.exportTarget&&(n.exportTarget=e.exportTarget),e.outputFormat&&(n.outputFormat=e.outputFormat),e.outputFormats&&(n.outputFormats=e.outputFormats),e.tokenBudget&&(n.tokenBudget=e.tokenBudget),e.prompt&&(n.prompt=e.prompt),e.channels&&(n.channels=e.channels),n.selectedPreset="",n.response="",t(n),e.mcpServers&&(async()=>{try{const{useMcpStore:s}=await se(async()=>{const{useMcpStore:a}=await Promise.resolve().then(()=>Fe);return{useMcpStore:a}},void 0);await s.getState().syncFromConfig()}catch{}})()},setInstructionState:e=>{t({instructionState:e})},setWorkflowSteps:e=>{t({workflowSteps:e})},toggleConnector:e=>{t({connectors:o().connectors.map(n=>n.id===e?{...n,enabled:!n.enabled}:n)})},addConnector:e=>{const{connectors:n}=o();n.some(s=>s.id===e.id)||t({connectors:[...n,e]})},removeConnector:e=>{t({connectors:o().connectors.filter(n=>n.id!==e)})},updateConnectorScope:(e,n)=>{t({connectors:o().connectors.map(s=>s.id===e?{...s,hint:n}:s)})},setExportTarget:e=>t({exportTarget:e}),addPendingKnowledge:e=>{t({pendingKnowledge:[...o().pendingKnowledge,e]})},acceptPendingKnowledge:e=>{const n=o().pendingKnowledge.find(a=>a.id===e);if(!n)return;const s={sourceId:`feedback-${e}`,name:n.name,path:"",category:"knowledge",knowledgeType:n.type||"evidence",enabled:!0,depth:0,baseTokens:500};t({channels:[...o().channels,s],pendingKnowledge:o().pendingKnowledge.filter(a=>a.id!==e)})},dismissPendingKnowledge:e=>{t({pendingKnowledge:o().pendingKnowledge.filter(n=>n.id!==e)})},addSuggestedSkill:e=>{t({suggestedSkills:[...o().suggestedSkills,e]})},acceptSuggestedSkill:e=>{t({suggestedSkills:o().suggestedSkills.map(n=>n.id===e?{...n,installing:!0}:n)}),setTimeout(()=>{o().suggestedSkills.find(s=>s.id===e)&&(t({suggestedSkills:o().suggestedSkills.map(s=>s.id===e?{...s,installing:!1,installed:!0}:s)}),setTimeout(()=>{t({suggestedSkills:o().suggestedSkills.filter(s=>s.id!==e)})},1200))},1500)},dismissSuggestedSkill:e=>{t({suggestedSkills:o().suggestedSkills.filter(n=>n.id!==e)})},installRegistrySkill:(e,n,s)=>{const a=o().registrySkills.find(l=>l.id===e),r=o().registrySkills.map(l=>l.id===e?{...l,installed:!0,installedTarget:n,installedScope:s}:l),c=o().skills.some(l=>l.id===e)?o().skills:a?[...o().skills,{id:a.id,name:a.name,icon:a.icon,enabled:!0,added:!0,description:a.description,category:Re(a.category)}]:o().skills;t({registrySkills:r,skills:c})},installRegistryMcp:e=>{const n=o().registryMcpServers.find(i=>i.id===e),s=o().registryMcpServers.map(i=>i.id===e?{...i,installed:!0,configured:!0}:i),r=o().mcpServers.some(i=>i.id===e)?o().mcpServers:n?[...o().mcpServers,{id:n.id,name:n.name,icon:n.icon,connected:!0,enabled:!0,added:!0,capabilities:["input","output"],category:at(n.category),description:n.description}]:o().mcpServers;t({registryMcpServers:s,mcpServers:r})},addFileChannel:e=>{const{channels:n}=o(),s=`file:${e.path}`;if(n.some(i=>i.sourceId===s))return;const a=Le(e.path,e.content),r={sourceId:s,name:e.path.split("/").pop()??e.path,path:e.path,category:"knowledge",knowledgeType:e.knowledgeType||a.knowledgeType,enabled:!0,depth:a.depth,baseTokens:e.tokenEstimate};t({channels:[...n,r],selectedPreset:""})},setInstructionPersona:e=>{t({instructionState:{...o().instructionState,persona:e}})},setInstructionTone:e=>{t({instructionState:{...o().instructionState,tone:e}})},setInstructionExpertise:e=>{t({instructionState:{...o().instructionState,expertise:Math.max(1,Math.min(5,e))}})},setInstructionConstraints:e=>{t({instructionState:{...o().instructionState,constraints:{...o().instructionState.constraints,...e}}})},setInstructionObjectives:e=>{t({instructionState:{...o().instructionState,objectives:{...o().instructionState.objectives,...e}}})},setInstructionRawPrompt:e=>{t({instructionState:{...o().instructionState,rawPrompt:e}})},setInstructionAutoSync:e=>{t({instructionState:{...o().instructionState,autoSync:e}})},addWorkflowStep:e=>{const n={...e,id:`step-${Date.now()}-${Math.random().toString(36).substr(2,9)}`};t({workflowSteps:[...o().workflowSteps,n]})},updateWorkflowStep:(e,n)=>{t({workflowSteps:o().workflowSteps.map(s=>s.id===e?{...s,...n}:s)})},removeWorkflowStep:e=>{t({workflowSteps:o().workflowSteps.filter(n=>n.id!==e)})},reorderWorkflowSteps:(e,n)=>{const s=[...o().workflowSteps],[a]=s.splice(e,1);s.splice(n,0,a),t({workflowSteps:s})},updateInstruction:e=>{t({instructionState:{...o().instructionState,...e}})},updateWorkflowSteps:e=>{const n=e.map((s,a)=>({...s,id:s.id||`step-${Date.now()}-${a}-${Math.random().toString(36).substr(2,5)}`}));t({workflowSteps:n})},setAgentPattern:e=>t({agentPattern:e}),updateVerification:e=>t({verification:{...o().verification,...e}}),updateErrorHandling:e=>t({errorHandling:{...o().errorHandling,...e}}),updateEvaluation:e=>t({evaluation:{...o().evaluation,...e}}),setOutputTemplateConfig:(e,n)=>{t({outputTemplateConfig:{...o().outputTemplateConfig,[e]:n}})},removeOutputTemplateConfig:e=>{const n={...o().outputTemplateConfig};delete n[e],t({outputTemplateConfig:n})},hydrateFromGenerated:e=>{t({agentMeta:{name:e.agentMeta.name||"",description:e.agentMeta.description||"",icon:"brain",category:"general",tags:e.agentMeta.tags||[],avatar:e.agentMeta.avatar||"bot"}}),t({instructionState:{persona:e.instructionState.persona||"",tone:e.instructionState.tone||"neutral",expertise:e.instructionState.expertise||3,constraints:{neverMakeUp:e.instructionState.constraints?.neverMakeUp??!0,askBeforeActions:e.instructionState.constraints?.askBeforeActions??!1,stayInScope:e.instructionState.constraints?.stayInScope??!0,useOnlyTools:e.instructionState.constraints?.useOnlyTools??!1,limitWords:e.instructionState.constraints?.limitWords??!1,wordLimit:e.instructionState.constraints?.wordLimit??0,customConstraints:(e.instructionState.constraints?.customConstraints||[]).join(`
|
|
87
|
+
`),scopeDefinition:e.instructionState.constraints?.scopeDefinition||""},objectives:{primary:e.instructionState.objectives?.primary||"",successCriteria:e.instructionState.objectives?.successCriteria||[],failureModes:e.instructionState.objectives?.failureModes||[]},rawPrompt:"",autoSync:!0}});const n=(e.workflowSteps||[]).map((c,l)=>({id:`gen-step-${l}-${Date.now()}`,label:c.label,action:c.action,tool:"",condition:c.condition?"if":"always",loop:c.loop,maxIterations:c.loop?3:0}));t({workflowSteps:n});const s=(e.mcpServerIds||[]).map(c=>{const l=St.find(d=>d.id===c);return l?{id:l.id,name:l.name,icon:l.icon||"server",connected:!1,enabled:!0,added:!0,capabilities:[],category:at(l.category),description:l.description}:null}).filter(Boolean);t({mcpServers:s});const a=(e.skillIds||[]).map(c=>{const l=Ee.find(d=>d.id===c);return l?{id:l.id,name:l.name,icon:l.icon,enabled:!0,added:!0,description:l.description,category:Re(l.category)}:null}).filter(Boolean);t({skills:a});const r=["ground-truth","signal","evidence","framework","hypothesis","guideline"],i=o().channels;if(e.knowledgeSelections&&e.knowledgeSelections.length>0){const c=i.map(l=>{const d=e.knowledgeSelections.find(g=>g.sourceId===l.sourceId);if(!d)return{...l,enabled:!1};const m=r.indexOf(d.type),u=m>=0?r[m]:l.knowledgeType||"evidence",p=typeof d.depth=="number"&&d.depth>=0&&d.depth<=4?d.depth:l.depth;return{...l,enabled:!0,knowledgeType:u,depth:p}});t({channels:c})}else if(e.knowledgeSuggestions&&e.knowledgeSuggestions.length>0){const c=e.knowledgeSuggestions.map((l,d)=>{const m=r.indexOf(l.type),u=m>=0?r[m]:"evidence";return{sourceId:`gen-knowledge-${d}-${Date.now()}`,name:l.name,path:"",category:"knowledge",knowledgeType:u,enabled:!0,depth:0,baseTokens:2e3}});t({channels:c})}t({knowledgeGaps:e.knowledgeGaps||[]}),t({response:"",selectedPreset:""})},setKnowledgeGaps:e=>{t({knowledgeGaps:e})},loadDemoPreset:e=>{if(!e){const s=po;t({agentMeta:{...s.agentMeta},instructionState:{...s.instructionState},workflowSteps:[...s.workflowSteps],channels:[...s.channels],skills:[...s.skills],mcpServers:[...s.mcpServers],selectedPreset:"",response:""});return}const n=ho[e];n&&t({agentMeta:{...n.agentMeta},instructionState:{...n.instructionState},workflowSteps:[...n.workflowSteps],channels:[...n.channels],skills:[...n.skills],mcpServers:[...n.mcpServers],selectedPreset:"",response:""})},resetAgent:()=>{t({agentMeta:{name:"",description:"",icon:"brain",category:"general",tags:[],avatar:"bot"},instructionState:{persona:"",tone:"neutral",expertise:3,constraints:{neverMakeUp:!1,askBeforeActions:!1,stayInScope:!1,useOnlyTools:!1,limitWords:!1,wordLimit:500,customConstraints:"",scopeDefinition:""},objectives:{primary:"",successCriteria:[],failureModes:[]},rawPrompt:"",autoSync:!0},workflowSteps:[],prompt:"",channels:[],mcpServers:[],skills:[],connectors:[],knowledgeGaps:[],response:"",selectedPreset:""});try{se(()=>import("./conversationStore-CkfEU2eV.js"),__vite__mapDeps([0,1,2])).then(e=>e.useConversationStore.getState().clearMessages())}catch{}},collectContextState:()=>({channels:o().channels,mcpServers:o().mcpServers,skills:o().skills,connectors:o().connectors}),restoreContextState:e=>{t({channels:e.channels,mcpServers:e.mcpServers,skills:e.skills,connectors:e.connectors})}}),{name:"modular-console",partialize:t=>({channels:t.channels,mcpServers:t.mcpServers,skills:t.skills,connectors:t.connectors,agentMeta:t.agentMeta,instructionState:t.instructionState,workflowSteps:t.workflowSteps,selectedModel:t.selectedModel,outputFormat:t.outputFormat,tokenBudget:t.tokenBudget,agentConfig:t.agentConfig}),version:1}));function Kt(t){return t.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")||"modular-agent"}function fo(){const t=F.getState();return{id:Kt(t.agentMeta.name),version:"1.0.0",savedAt:new Date().toISOString(),agentMeta:{...t.agentMeta},instructionState:{...t.instructionState},workflowSteps:t.workflowSteps.map(e=>({...e})),channels:t.channels.map(e=>({...e})),mcpServers:t.mcpServers.map(e=>({...e})),skills:t.skills.map(e=>({...e})),connectors:t.connectors.map(e=>({...e})),agentConfig:{...t.agentConfig},exportTarget:t.exportTarget,outputFormat:t.outputFormat,outputFormats:[...t.outputFormats],tokenBudget:t.tokenBudget,prompt:t.prompt}}const yo=Object.freeze(Object.defineProperty({__proto__:null,agentNameToId:Kt,collectFullState:fo,getEffectiveTokens:jt,useConsoleStore:F},Symbol.toStringTag,{value:"Module"}));function lt(){const t=F.getState();return{agentMeta:{...t.agentMeta},channels:t.channels,mcpServers:t.mcpServers,skills:t.skills,instructionState:{...t.instructionState},workflowSteps:[...t.workflowSteps],agentConfig:{...t.agentConfig},prompt:t.prompt,selectedModel:t.selectedModel}}function dt(t,o){const e=[];t.instructionState.persona!==o.instructionState.persona&&o.instructionState.persona.length>0&&e.push({type:"major",category:"instruction",description:"Persona updated"}),t.instructionState.objectives.primary!==o.instructionState.objectives.primary&&e.push({type:"major",category:"instruction",description:"Primary objective changed"}),t.selectedModel!==o.selectedModel&&e.push({type:"major",category:"model",description:`Model → ${o.selectedModel}`}),t.instructionState.tone!==o.instructionState.tone&&e.push({type:"major",category:"instruction",description:`Tone → ${o.instructionState.tone}`});const n=t.channels.filter(h=>h.enabled).map(h=>h.sourceId),s=o.channels.filter(h=>h.enabled).map(h=>h.sourceId),a=s.filter(h=>!n.includes(h)),r=n.filter(h=>!s.includes(h));a.length>0&&e.push({type:"minor",category:"knowledge",description:`+${a.length} knowledge source(s)`}),r.length>0&&e.push({type:"minor",category:"knowledge",description:`-${r.length} knowledge source(s)`});const i=t.skills.filter(h=>h.added).map(h=>h.id),c=o.skills.filter(h=>h.added).map(h=>h.id),l=c.filter(h=>!i.includes(h)),d=i.filter(h=>!c.includes(h));l.length>0&&e.push({type:"minor",category:"skill",description:`+${l.length} skill(s)`}),d.length>0&&e.push({type:"minor",category:"skill",description:`-${d.length} skill(s)`});const m=t.mcpServers.filter(h=>h.added).map(h=>h.id),u=o.mcpServers.filter(h=>h.added).map(h=>h.id),p=u.filter(h=>!m.includes(h)),g=m.filter(h=>!u.includes(h));if(p.length>0&&e.push({type:"minor",category:"mcp",description:`+${p.length} MCP server(s)`}),g.length>0&&e.push({type:"minor",category:"mcp",description:`-${g.length} MCP server(s)`}),o.workflowSteps.length!==t.workflowSteps.length){const h=o.workflowSteps.length-t.workflowSteps.length;e.push({type:"minor",category:"workflow",description:`${h>0?"+":""}${h} workflow step(s)`})}const f=t.instructionState.objectives.successCriteria.length,y=o.instructionState.objectives.successCriteria.length;y!==f&&e.push({type:"minor",category:"instruction",description:`Success criteria ${y>f?"added":"removed"}`});const k=["neverMakeUp","askBeforeActions","stayInScope","useOnlyTools","limitWords"];for(const h of k)t.instructionState.constraints[h]!==o.instructionState.constraints[h]&&e.push({type:"patch",category:"instruction",description:`Constraint "${h}" toggled`});t.instructionState.constraints.customConstraints!==o.instructionState.constraints.customConstraints&&e.push({type:"patch",category:"instruction",description:"Custom constraints updated"}),t.instructionState.expertise!==o.instructionState.expertise&&e.push({type:"patch",category:"instruction",description:`Expertise level → ${o.instructionState.expertise}`}),t.prompt!==o.prompt&&e.push({type:"patch",category:"prompt",description:"Prompt text changed"});for(const h of o.channels){const w=t.channels.find(v=>v.sourceId===h.sourceId);w&&w.depth!==h.depth&&e.push({type:"patch",category:"knowledge",description:`"${h.name}" depth changed`})}if(o.workflowSteps.length===t.workflowSteps.length)for(let h=0;h<o.workflowSteps.length;h++){const w=t.workflowSteps[h],v=o.workflowSteps[h];if(w&&v&&(w.label!==v.label||w.action!==v.action||w.tool!==v.tool||w.condition!==v.condition)){e.push({type:"patch",category:"workflow",description:`Step "${v.label||h+1}" modified`});break}}return t.agentConfig.temperature!==o.agentConfig.temperature&&e.push({type:"patch",category:"config",description:`Temperature → ${o.agentConfig.temperature}`}),t.agentConfig.maxTokens!==o.agentConfig.maxTokens&&e.push({type:"patch",category:"config",description:`Max tokens → ${o.agentConfig.maxTokens}`}),e}function ko(t,o){const[e,n,s]=t.split(".").map(Number),a=o.some(c=>c.type==="major"),r=o.some(c=>c.type==="minor");if(a){const c={major:e+1,minor:0,patch:0};return{...c,version:`${c.major}.${c.minor}.${c.patch}`}}if(r){const c={major:e,minor:n+1,patch:0};return{...c,version:`${c.major}.${c.minor}.${c.patch}`}}const i={major:e,minor:n,patch:s+1};return{...i,version:`${i.major}.${i.minor}.${i.patch}`}}function pt(t){if(t.length===0)return"No changes";if(t.length===1)return t[0].description;const o=[...new Set(t.map(e=>e.category))];return`${t.length} changes (${o.join(", ")})`}async function ae(t,o={}){const e=await fetch(`/api${t}`,{headers:{"Content-Type":"application/json",...o.headers},...o});if(!e.ok)throw new Error(`API error: ${e.status} ${e.statusText}`);const n=await e.json();if(n.status==="error")throw new Error(n.error);return n.data}async function wo(t,o,e,n,s){const a={id:t,version:e,agentMeta:o.agentMeta,instructionState:o.instructionState,workflowSteps:o.workflowSteps,channels:o.channels,mcpServers:o.mcpServers,skills:o.skills,connectors:[],agentConfig:o.agentConfig,exportTarget:"claude",outputFormat:"markdown",outputFormats:["markdown"],tokenBudget:4e3,prompt:o.prompt,selectedModel:o.selectedModel};await ae(`/agents/${t}/save`,{method:"POST",body:JSON.stringify({state:a,label:n,changeSummary:s})})}const Bt=j((t,o)=>({versions:[],currentVersion:"0.1.0",dirty:!1,autoVersion:!0,maxVersions:50,agentId:null,saveStatus:"saved",latestVersion:()=>{const e=o().versions;return e.length>0?e[e.length-1]:void 0},getVersion:e=>o().versions.find(n=>n.version===e),setAgentId:e=>{t({agentId:e}),e&&o().loadVersions()},loadVersions:async()=>{const{agentId:e}=o();if(e)try{const n=await ae(`/agents/${e}/versions`);t({versions:n||[]})}catch(n){console.error("Failed to load versions:",n)}},saveToServer:async e=>{const{agentId:n,currentVersion:s}=o();if(n){t({saveStatus:"saving"});try{const a=lt();await wo(n,a,s,e),t({saveStatus:"saved",dirty:!1}),await o().loadVersions()}catch(a){console.error("Failed to save agent:",a),t({saveStatus:"error"})}}},checkpoint:async e=>{const n=lt(),s=o().latestVersion()?.snapshot,a=s?dt(s,n):[{type:"minor",category:"init",description:"Initial version"}];if(s&&a.length===0)return;const r=s?ko(o().currentVersion,a):{major:0,minor:1,patch:0,version:"0.1.0"},i={id:`v-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,version:r.version,major:r.major,minor:r.minor,patch:r.patch,timestamp:Date.now(),label:e||pt(a),changes:a,snapshot:n},c=[...o().versions,i].slice(-o().maxVersions);if(t({versions:c,currentVersion:r.version,dirty:!1}),o().agentId)try{await o().saveToServer(e||pt(a))}catch(l){console.error("Failed to save to server:",l),t({saveStatus:"error"})}},restoreVersion:async e=>{const{agentId:n}=o();if(n)try{await ae(`/agents/${n}/versions/${e}/restore`,{method:"POST"});const r=await ae(`/agents/${n}`),i=F.getState();i.clearChannels();for(const c of r.channels||[])i.addChannel(c),c.enabled||i.toggleChannel(c.sourceId);r.prompt&&i.setPrompt(r.prompt),r.selectedModel&&i.setModel(r.selectedModel),r.instructionState&&i.updateInstruction(r.instructionState),r.workflowSteps&&i.updateWorkflowSteps(r.workflowSteps),t({currentVersion:e,dirty:!1,saveStatus:"saved"});return}catch(r){console.error("Server restore failed, falling back to local:",r)}const s=o().getVersion(e);if(!s)return;const a=F.getState();a.clearChannels();for(const r of s.snapshot.channels)a.addChannel(r),r.enabled||a.toggleChannel(r.sourceId);a.setPrompt(s.snapshot.prompt),a.setModel(s.snapshot.selectedModel),a.updateInstruction({persona:s.snapshot.instructionState.persona,tone:s.snapshot.instructionState.tone,expertise:s.snapshot.instructionState.expertise,constraints:s.snapshot.instructionState.constraints,objectives:s.snapshot.instructionState.objectives,rawPrompt:s.snapshot.instructionState.rawPrompt,autoSync:s.snapshot.instructionState.autoSync}),a.updateWorkflowSteps(s.snapshot.workflowSteps),t({currentVersion:s.version,dirty:!1})},deleteVersion:async e=>{const{agentId:n,versions:s}=o(),a=s.find(r=>r.id===e);if(n&&a)try{await ae(`/agents/${n}/versions/${a.version}`,{method:"DELETE"}),await o().loadVersions()}catch(r){console.error("Failed to delete version from server:",r)}else t({versions:s.filter(r=>r.id!==e)})},setAutoVersion:e=>t({autoVersion:e}),setDirty:()=>t({dirty:!0,saveStatus:"unsaved"}),_detectAndVersion:(e,n)=>{if(dt(e,n).length===0)return;const a=o();if((!a.dirty||a.saveStatus!=="unsaved")&&t({dirty:!0,saveStatus:"unsaved"}),!o().autoVersion)return;const r=o().latestVersion();r&&Date.now()-r.timestamp<3e4||o().checkpoint()}}));let be=null,Oe=null;F.subscribe(t=>{const o={agentMeta:t.agentMeta,channels:t.channels,mcpServers:t.mcpServers,skills:t.skills,instructionState:t.instructionState,workflowSteps:t.workflowSteps,agentConfig:t.agentConfig,prompt:t.prompt,selectedModel:t.selectedModel};if(!be){be=o;return}Oe&&clearTimeout(Oe);const e=be;Oe=setTimeout(()=>{Bt.getState()._detectAndVersion(e,o),be=o},1500)});const z=`${E}/mcp`;async function K(t,o){try{const e=await fetch(t,{...o,headers:{"Content-Type":"application/json",...o?.headers}});if(!e.ok)return null;const n=await e.json();return n?.data??n}catch{return null}}const he=j((t,o)=>({servers:[],loaded:!1,loading:!1,error:void 0,loadServers:async()=>{if(o().loading||o().loaded)return;t({loading:!0,error:void 0});const e=await K(z),n=await K(`${E}/claude-config/mcp`);if(!e&&!n){t({servers:[],loaded:!0,loading:!1,error:"Backend unavailable. Start the server with `npm run server` on port 4800."});return}const s=e??[],a=n??[],r=new Set(s.map(c=>c.id)),i=[...s,...a.filter(c=>!r.has(c.id)).map(c=>({id:c.id,name:c.name,type:c.type,command:c.command??"",args:c.args??[],env:c.env??{},url:c.url,headers:c.headers,status:(c.status==="enabled"||c.status==="deferred","disconnected"),tools:[],mcpStatus:c.status}))];t({servers:i,loaded:!0,loading:!1}),await o().syncFromConfig()},syncFromConfig:async()=>{const{useConsoleStore:e}=await se(async()=>{const{useConsoleStore:r}=await Promise.resolve().then(()=>yo);return{useConsoleStore:r}},void 0),n=e.getState().mcpServers,s=o().servers,a=new Set(s.map(r=>r.id));for(const r of n)r.added&&!a.has(r.id)&&await o().addServer({id:r.id,name:r.name,command:"",args:[],env:{}})},addServer:async e=>{const n=o().servers.find(r=>r.id===e.id);if(n)return n;const a=await K(z,{method:"POST",body:JSON.stringify(e)})??{id:e.id??`mcp-${Date.now()}`,name:e.name,type:e.type,command:e.command,args:e.args,env:e.env,url:e.url,headers:e.headers,autoConnect:e.autoConnect,status:"disconnected",tools:[]};return t({servers:[...o().servers,a]}),a},updateServer:async(e,n)=>{const s=await K(`${z}/${e}`,{method:"PUT",body:JSON.stringify(n)});return s&&t({servers:o().servers.map(a=>a.id===e?{...a,...s}:a)}),s},connectServer:async e=>{t({servers:o().servers.map(s=>s.id===e?{...s,status:"connecting"}:s)});const n=await K(`${z}/${e}/connect`,{method:"POST"});t({servers:o().servers.map(s=>s.id===e?{...s,status:n?.status??"error",tools:n?.tools??[],lastError:n?void 0:"Connection failed"}:s)})},disconnectServer:async e=>{await K(`${z}/${e}/disconnect`,{method:"POST"}),t({servers:o().servers.map(n=>n.id===e?{...n,status:"disconnected",tools:[]}:n)})},removeServer:async e=>{await K(`${z}/${e}`,{method:"DELETE"}),t({servers:o().servers.filter(n=>n.id!==e)})},callTool:async(e,n,s)=>(await K(`${z}/${e}/call`,{method:"POST",body:JSON.stringify({toolName:n,arguments:s})}))?.result??null,refreshHealth:async e=>{const n=await K(`${z}/${e}/health`);n&&t({servers:o().servers.map(s=>s.id===e?{...s,status:n.status,tools:n.tools,uptime:n.uptime,lastError:n.lastError}:s)})},getConnectedTools:()=>o().servers.filter(e=>e.status==="connected").flatMap(e=>e.tools)}));let re=null;function bo(){re||(re=setInterval(()=>{const{servers:t,refreshHealth:o}=he.getState();for(const e of t)e.status==="connected"&&o(e.id)},3e4))}function vo(){re&&(clearInterval(re),re=null)}const Fe=Object.freeze(Object.defineProperty({__proto__:null,startHealthPolling:bo,stopHealthPolling:vo,useMcpStore:he},Symbol.toStringTag,{value:"Module"}));async function Oa(t){const e=new URLSearchParams(window.location.search).get("tab")||"describe";localStorage.setItem("mcp-oauth-return-tab",e);const n=await fetch(`${E}/mcp/oauth/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverUrl:t})});if(!n.ok){const a=await n.json().catch(()=>({error:"Request failed"}));throw new Error(a.error||`HTTP ${n.status}`)}const{authUrl:s}=await n.json();return new Promise((a,r)=>{const i=window.open(s,"mcp-oauth","width=600,height=700,popup=yes");if(!i){r(new Error("Popup blocked — allow popups for this site"));return}const c=()=>{window.removeEventListener("message",l),clearInterval(d),clearTimeout(m)},l=u=>{const p=u.data;p?.type&&(p.type==="mcp-oauth-success"?(c(),localStorage.setItem("mcp-oauth-completed","true"),a()):p.type==="mcp-oauth-error"&&(c(),localStorage.removeItem("mcp-oauth-return-tab"),r(new Error(p.error||"OAuth flow failed"))))};window.addEventListener("message",l);const d=setInterval(()=>{i.closed&&(c(),r(new Error("OAuth flow cancelled")))},500),m=setTimeout(()=>{c(),i.close(),r(new Error("OAuth flow timed out"))},3e5)})}async function Fa(t){const o=await fetch(`${E}/mcp/oauth/status?serverUrl=${encodeURIComponent(t)}`);return o.ok?await o.json():{connected:!1}}const ut={strategy:"summarize_and_recent",windowSize:20,summarizeAfter:10,summaryModel:"same",tokenBudget:2e4,maxMessages:20,summarizeEnabled:!0},So={enabled:!0,store:"local_sqlite",embeddingModel:"text-embedding-3-small",recall:{strategy:"top_k",k:5,minScore:.7},write:{mode:"auto_extract",extractTypes:["user_preferences","decisions","facts"]},scope:"per_user",maxEntries:1e3,ttl:null,tokenBudget:5e3,hindsight:{baseUrl:"http://localhost:8888",enabled:!1}},To={enabled:!0,maxTokens:2e3,persist:!1,format:"freeform",content:"",tokenBudget:2e3},xo={enabled:!0,ttlSeconds:3600},Co={isolation:"reset_each_run",allowPromoteToShared:!1,domains:{shared:{enabled:!0},agentPrivate:{enabled:!0},runScratchpad:{enabled:!0}}},Y=j((t,o)=>({session:{...ut},longTerm:{...So},working:{...To},facts:[],sandbox:{...Co},responseCache:{...xo},sessionMemory:{...ut},longTermMemory:[],workingMemory:"",setSessionConfig:e=>{t(n=>{const s={...n.session,...e};"maxMessages"in e&&(s.windowSize=s.maxMessages),"windowSize"in e&&(s.maxMessages=s.windowSize),"summarizeEnabled"in e&&!s.summarizeEnabled&&(s.strategy="sliding_window"),"strategy"in e&&(s.summarizeEnabled=e.strategy==="summarize_and_recent");const a=s;return{session:a,sessionMemory:a}})},setLongTermConfig:e=>{t(n=>({longTerm:{...n.longTerm,...e}}))},setRecallConfig:e=>{t(n=>({longTerm:{...n.longTerm,recall:{...n.longTerm.recall,...e}}}))},setWriteConfig:e=>{t(n=>({longTerm:{...n.longTerm,write:{...n.longTerm.write,...e}}}))},toggleExtractType:e=>{t(n=>{const s=n.longTerm.write.extractTypes,a=s.includes(e)?s.filter(r=>r!==e):[...s,e];return{longTerm:{...n.longTerm,write:{...n.longTerm.write,extractTypes:a}}}})},setWorkingConfig:e=>{t(n=>({working:{...n.working,...e}}))},updateScratchpad:e=>{t(n=>({working:{...n.working,content:e},workingMemory:e}))},addFact:(e,n=[],s="fact",a="shared",r="fact",i)=>{const c={id:`fact-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,content:e,tags:n,type:s,timestamp:Date.now(),domain:a,granularity:r,embeddingPending:!0,...i&&{ownerAgentId:i}};t(l=>{const d=[...l.facts,c];return{facts:d,longTermMemory:d}})},removeFact:e=>{t(n=>{const s=n.facts.filter(a=>a.id!==e);return{facts:s,longTermMemory:s}})},updateFact:(e,n)=>{t(s=>({facts:s.facts.map(a=>a.id===e?{...a,...n}:a)}))},addEpisode:(e,n=[])=>{const s={id:`episode-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,content:e,tags:n,type:"fact",timestamp:Date.now(),domain:"shared",granularity:"episode",embeddingPending:!0};t(a=>{const r=[...a.facts,s];return{facts:r,longTermMemory:r}})},computeEmbeddings:async()=>{const n=o().facts.filter(s=>s.embeddingPending&&!s.embedding);if(n.length!==0)try{const s=await fetch("/api/knowledge/embed",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({texts:n.map(r=>r.content)})});if(!s.ok)return;const a=await s.json();if(!a.embeddings||a.embeddings.length!==n.length)return;t(r=>({facts:r.facts.map(i=>{const c=n.findIndex(l=>l.id===i.id);return c===-1?i:{...i,embedding:a.embeddings[c],embeddingPending:!1}})}))}catch{}},setSandboxConfig:e=>{t(n=>({sandbox:{...n.sandbox,...e}}))},setSandboxDomain:(e,n)=>{t(s=>({sandbox:{...s.sandbox,domains:{...s.sandbox.domains,[e]:{enabled:n}}}}))},setResponseCacheConfig:e=>{t(n=>({responseCache:{...n.responseCache,...e}}))},getFactsByDomain:e=>o().facts.filter(n=>n.domain===e),getRecallableFacts:e=>{const{facts:n,sandbox:s}=o();return n.filter(a=>a.domain==="run_scratchpad"?!1:a.domain==="agent_private"?s.domains.agentPrivate.enabled?!!e&&a.ownerAgentId===e:!1:a.domain==="shared"?s.domains.shared.enabled:!1)},toYaml:()=>{const{session:e,longTerm:n,working:s,facts:a,sandbox:r}=o();return{memory:{session:{strategy:e.strategy,window_size:e.windowSize,summarize_after:e.summarizeAfter,summary_model:e.summaryModel,token_budget:e.tokenBudget},long_term:{enabled:n.enabled,store:n.store,embedding_model:n.embeddingModel,recall:{strategy:n.recall.strategy,k:n.recall.k,min_score:n.recall.minScore},write:{mode:n.write.mode,extract_types:n.write.extractTypes},scope:n.scope,max_entries:n.maxEntries,ttl:n.ttl,token_budget:n.tokenBudget,...a.length>0?{seed_facts:a.map(i=>({content:i.content,type:i.type,tags:i.tags,domain:i.domain,granularity:i.granularity}))}:{}},working:{enabled:s.enabled,max_tokens:s.maxTokens,persist:s.persist,format:s.format,token_budget:s.tokenBudget},sandbox:{isolation:r.isolation,allow_promote_to_shared:r.allowPromoteToShared,domains:{shared:r.domains.shared.enabled,agent_private:r.domains.agentPrivate.enabled,run_scratchpad:r.domains.runScratchpad.enabled}}}}}}));function mt(){return`${Date.now()}-${Math.random().toString(36).slice(2,6)}`}function Ao(t){let o=0,e=0,n=0,s=0,a=0;const r=t.map(c=>c.timestamp),i=r.length>=2?Math.max(...r)-Math.min(...r):0;for(const c of t)c.kind==="llm_call"&&(o+=(c.inputTokens||0)+(c.outputTokens||0),e+=c.costUsd||0),c.kind==="tool_call"&&(n++,c.toolError&&s++),c.kind==="retrieval"&&a++;return{totalTokens:o,totalCostUsd:e,toolCalls:n,toolErrors:s,retrievals:a,durationMs:i}}const D=j((t,o)=>({traces:[],activeTraceId:null,selectedTraceId:null,maxTraces:50,eventVersion:0,startTrace:(e,n)=>{const s=`trace-${mt()}`,a={id:s,conversationId:e,agentVersion:n,startedAt:Date.now(),events:[]};return t(r=>({traces:[...r.traces,a].slice(-r.maxTraces),activeTraceId:s,selectedTraceId:null})),s},addEvent:(e,n)=>t(s=>({traces:s.traces.map(a=>a.id===e?{...a,events:[...a.events,{...n,id:mt(),timestamp:Date.now()}]}:a),eventVersion:s.eventVersion+1})),endTrace:e=>t(n=>({traces:n.traces.map(s=>s.id===e?{...s,summary:Ao(s.events)}:s),activeTraceId:n.activeTraceId})),getTrace:e=>o().traces.find(n=>n.id===e),getActiveTrace:()=>{const e=o().activeTraceId;return e?o().traces.find(n=>n.id===e):void 0},getDisplayTrace:()=>{const{selectedTraceId:e,activeTraceId:n,traces:s}=o(),a=e||n;return a?s.find(r=>r.id===a):void 0},selectTrace:e=>t({selectedTraceId:e}),clearTraces:()=>t({traces:[],activeTraceId:null,selectedTraceId:null})}));function Po(t){const o=t.toLowerCase();return["what is","where is","how does","who is","when did","which","define","explain"].some(s=>o.includes(s))||/["'`].+["'`]/.test(t)||/[A-Z][a-z]+[A-Z]/.test(t)||/[A-Z_]{3,}/.test(t)?"specific":["summarize","summary","overview","what happened","recap","yesterday","last week","last month","today","recently","so far","progress","status update"].some(s=>o.includes(s))?"summary":"exploratory"}const Eo={fact:1,episode:.8,raw:.6};function Io(t,o){if(t.length!==o.length||t.length===0)return 0;let e=0,n=0,s=0;for(let r=0;r<t.length;r++)e+=t[r]*o[r],n+=t[r]*t[r],s+=o[r]*o[r];const a=Math.sqrt(n)*Math.sqrt(s);return a===0?0:e/a}async function Mo(t){try{const o=await fetch("/api/knowledge/embed",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({texts:[t]})});return o.ok?(await o.json()).embeddings?.[0]??null:null}catch{return null}}async function _o(t,o){try{const e=await fetch("/api/memory/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:t,k:o})});if(!e.ok)return[];const n=await e.json();return!Ro(n)||!Array.isArray(n.results)?[]:n.results}catch{return[]}}async function $o(t){try{const o={id:`hs-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,content:t,tags:[],type:"fact",timestamp:Date.now(),domain:"shared",granularity:"fact"};await fetch("/api/memory/facts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})}catch{}}function Ro(t){return typeof t=="object"&&t!==null}async function Oo(t){const o=Date.now(),e=Y.getState(),{longTerm:n,sandbox:s}=e;if(!n.enabled)return{facts:[],contextBlock:"",tokenEstimate:0,durationMs:0};if(n.store==="hindsight")return Fo(t,o);let a=e.getRecallableFacts(t.agentId);s.isolation==="reset_each_run"?a=a.filter(T=>T.domain!=="run_scratchpad"):s.isolation==="clone_from_shared"&&(a=a.filter(T=>T.domain==="shared"));const r=Po(t.userMessage),i={specific:{k:3,granularityBoost:{fact:1.3,episode:.7,raw:.5}},summary:{k:5,granularityBoost:{fact:.8,episode:1.3,raw:.6}},exploratory:{k:8,granularityBoost:{fact:1,episode:1,raw:1}}},{k:c,granularityBoost:l}=i[r],d=a.some(T=>T.embedding&&T.embedding.length>0);let m=null;d&&(m=await Mo(t.userMessage));const u=a.map(T=>{let P;m&&T.embedding&&T.embedding.length>0?P=Io(m,T.embedding):P=qo(T.content,t.userMessage);const _=Eo[T.granularity??"fact"],b=l[T.granularity??"fact"]??1;return{fact:T,score:P*_*b}}),{strategy:p,k:g,minScore:f}=n.recall,y=Math.min(c,g||c);let k;p==="threshold"?k=u.filter(T=>T.score>=f).sort((T,P)=>P.score-T.score):p==="hybrid"?k=u.filter(T=>T.score>=f).sort((T,P)=>P.score-T.score).slice(0,y):k=u.sort((T,P)=>P.score-T.score).slice(0,y);const h=k.map(T=>T.fact),w=Ht(h),v=Math.ceil(w.length/4),C=Date.now()-o;return D.getState().addEvent(t.traceId,{kind:"memory_recall",sourceName:"memory:pre-recall",memoryFactCount:h.length,memoryFactIds:h.map(T=>T.id),memoryDomain:h.length>0?[...new Set(h.map(T=>T.domain))].join(","):void 0,durationMs:C}),{facts:h,contextBlock:w,tokenEstimate:v,durationMs:C}}async function Fo(t,o){const n=Y.getState().longTerm.recall.k,s=await _o(t.userMessage,n),a=Ht(s),r=Math.ceil(a.length/4),i=Date.now()-o;return D.getState().addEvent(t.traceId,{kind:"hindsight_recall",sourceName:"hindsight:pre-recall",memoryFactCount:s.length,memoryFactIds:s.map(c=>c.id),durationMs:i}),{facts:s,contextBlock:a,tokenEstimate:r,durationMs:i}}function Do(t){const o=Date.now(),e=Y.getState(),{longTerm:n,sandbox:s}=e;if(!n.enabled||!t.assistantResponse)return{extracted:[],stored:[],durationMs:0};if(n.store==="hindsight")return No(t,o),{extracted:[],stored:[],durationMs:Date.now()-o};const{write:a}=n;if(a.mode==="explicit")return{extracted:[],stored:[],durationMs:0};const r=Uo(t.assistantResponse,t.userMessage,a.extractTypes),i=Ho(s.isolation,t.sandboxRunId),c=[];for(const m of r){if(m.confidence<.5)continue;const u=Wo(i,s),g={decisions:"decision",user_preferences:"preference",facts:"fact",feedback:"fact",entities:"entity"}[m.type]||m.type;e.addFact(m.content,[m.type],g,u,"fact",t.agentId);const f=Y.getState().facts,y=f[f.length-1];y&&c.push(y)}const l=Date.now()-o;return D.getState().addEvent(t.traceId,{kind:"memory_write",sourceName:"memory:post-write",memoryFactCount:c.length,memoryFactIds:c.map(m=>m.id),memoryDomain:i,durationMs:l}),{extracted:r,stored:c,durationMs:l}}function No(t,o){if(!t.assistantResponse)return;const e=t.assistantResponse.slice(0,2e3);$o(e).then(()=>{D.getState().addEvent(t.traceId,{kind:"hindsight_retain",sourceName:"hindsight:post-write",memoryFactCount:1,durationMs:Date.now()-o})})}function Lo(){const t=Y.getState(),o=t.facts.filter(e=>e.domain==="run_scratchpad").map(e=>e.id);for(const e of o)t.removeFact(e)}function qo(t,o){const e=new Set(t.toLowerCase().split(/\s+/).filter(a=>a.length>2)),n=o.toLowerCase().split(/\s+/).filter(a=>a.length>2);if(n.length===0)return .1;let s=0;for(const a of n)e.has(a)&&s++;return s/n.length}function Ht(t){return t.length===0?"":`<memory_recall>
|
|
88
|
+
Relevant facts from memory:
|
|
89
|
+
${t.map(e=>{const n=e.domain!=="shared"?` [${e.domain}]`:"";return`- [${e.type}]${n} ${e.content}`}).join(`
|
|
90
|
+
`)}
|
|
91
|
+
</memory_recall>`}function Uo(t,o,e){const n=[],s=t.split(/[.!?\n]+/).map(a=>a.trim()).filter(a=>a.length>10);for(const a of s){const r=a.toLowerCase();e.includes("decisions")&&jo(r)?n.push({content:a,type:"decisions",confidence:.7}):e.includes("user_preferences")&&Ko(r,o)?n.push({content:a,type:"user_preferences",confidence:.6}):e.includes("facts")&&Bo(r)&&n.push({content:a,type:"facts",confidence:.5})}return n.slice(0,5)}function jo(t){return["decided","will use","chosen","selected","going with","we should","let's go with"].some(e=>t.includes(e))}function Ko(t,o){const e=o.toLowerCase();return["prefer","like","want","favorite","always use","rather"].some(s=>e.includes(s)||t.includes(s))}function Bo(t){return["is a","are used","works by","consists of","requires","means"].some(e=>t.includes(e))}function Ho(t,o){return o||t==="reset_each_run"?"run_scratchpad":t==="clone_from_shared"?"agent_private":"shared"}function Wo(t,o){return t==="shared"&&!o.allowPromoteToShared?"agent_private":t}function Go(t){const o=[];if(o.push("<provenance>"),t.sources.length>0)for(const e of t.sources)o.push(` <source path="${e.path}" type="${e.type}" sections="${e.sections}" depth="${e.depth}" />`);if(t.derivations.length>0){o.push(" <derivation>");for(const e of t.derivations)o.push(` <step from="${e.from}" method="${e.method}" to="${e.to}" />`);o.push(" </derivation>")}return o.push("</provenance>"),t.conflictResolution&&(o.push(""),o.push("<context_provenance>"),o.push(t.conflictResolution.instructions),o.push("</context_provenance>")),o.join(`
|
|
92
|
+
`)}function gt(t){const o=F.getState(),{instructionState:e,workflowSteps:n,agentMeta:s}=o,a=[];if(s.name){const c=[`Name: ${s.name}`];s.description&&c.push(`Description: ${s.description}`),s.avatar&&c.push(`Avatar: ${s.avatar}`),s.tags?.length&&c.push(`Tags: ${s.tags.join(", ")}`),a.push(`<identity>
|
|
93
|
+
${c.join(`
|
|
94
|
+
`)}
|
|
95
|
+
</identity>`)}if(e.persona||e.objectives.primary){const c=[];if(e.persona&&c.push(`Persona: ${e.persona}`),e.tone!=="neutral"&&c.push(`Tone: ${e.tone}`),e.expertise!==3){const l=["Beginner","Novice","Intermediate","Advanced","Expert"];c.push(`Expertise Level: ${l[e.expertise-1]} (${e.expertise}/5)`)}e.objectives.primary&&(c.push(`Primary Objective: ${e.objectives.primary}`),e.objectives.successCriteria.length>0&&c.push(`Success Criteria:
|
|
96
|
+
${e.objectives.successCriteria.map(l=>`- ${l}`).join(`
|
|
97
|
+
`)}`),e.objectives.failureModes.length>0&&c.push(`Failure Modes to Avoid:
|
|
98
|
+
${e.objectives.failureModes.map(l=>`- ${l}`).join(`
|
|
99
|
+
`)}`)),a.push(`<instructions>
|
|
100
|
+
${c.join(`
|
|
101
|
+
|
|
102
|
+
`)}
|
|
103
|
+
</instructions>`)}const r=[];if(e.constraints.neverMakeUp&&r.push("Never fabricate information or make up facts"),e.constraints.askBeforeActions&&r.push("Ask for permission before taking significant actions"),e.constraints.stayInScope&&r.push(`Stay within the defined scope: ${e.constraints.scopeDefinition||"as specified"}`),e.constraints.useOnlyTools&&r.push("Only use tools and capabilities that are explicitly provided"),e.constraints.limitWords&&r.push(`Keep responses under ${e.constraints.wordLimit} words`),e.constraints.customConstraints&&r.push(`Additional constraints: ${e.constraints.customConstraints}`),r.length>0&&a.push(`<constraints>
|
|
104
|
+
${r.map(c=>`- ${c}`).join(`
|
|
105
|
+
`)}
|
|
106
|
+
</constraints>`),n.length>0){const c=Lt(n);a.push(`<workflow>
|
|
107
|
+
${c}
|
|
108
|
+
</workflow>`)}const i=Yo();if(i&&a.push(i),t){const c=Go(t);a.push(c)}return a.join(`
|
|
109
|
+
|
|
110
|
+
`)}function zo(){return`<knowledge_format>
|
|
111
|
+
The knowledge below is produced by an automated indexing pipeline. Here is how to read it:
|
|
112
|
+
|
|
113
|
+
## Heading Hierarchy = Depth Levels
|
|
114
|
+
- # (H1) = Feature name — top-level grouping
|
|
115
|
+
- ## (H2) = Section: Architecture, Key Files, Data Flow, State Management, Components
|
|
116
|
+
- ### (H3) = Individual file entry with metadata
|
|
117
|
+
|
|
118
|
+
## How to Read a Key File Entry
|
|
119
|
+
Each file under "Key Files" has structured metadata:
|
|
120
|
+
- **Category**: What the file DOES (component=UI, store=state, service=logic, route=endpoint, util=helper, test=tests, config=settings, type=contracts)
|
|
121
|
+
- **Exports**: The public API surface — function/class/constant names this file makes available
|
|
122
|
+
- **Types**: TypeScript interfaces/types defined in this file
|
|
123
|
+
- **Size/Tokens**: File size and estimated token count for budget decisions
|
|
124
|
+
- **Imports**: Direct dependencies of this file
|
|
125
|
+
|
|
126
|
+
## How to Use Data Flow (CRITICAL)
|
|
127
|
+
The "Data Flow" section contains the import graph between files. Each line is:
|
|
128
|
+
source_file → imported_module
|
|
129
|
+
This IS the dependency graph. You do NOT need to open files to trace dependencies.
|
|
130
|
+
Example: if Data Flow shows \`App.tsx → ./providers/AuthProvider\`, you already know App depends on AuthProvider.
|
|
131
|
+
|
|
132
|
+
## Escalation Strategy
|
|
133
|
+
1. **Check the knowledge docs first** — most answers are already here (exports, types, data flow, architecture)
|
|
134
|
+
2. **Use get_file_contents ONLY when you need actual implementation details** — the code itself, not its structure
|
|
135
|
+
3. **Build exact file URLs** using the base URL from orientation + the file path from Key Files
|
|
136
|
+
|
|
137
|
+
## What You Can Answer WITHOUT Reading Files
|
|
138
|
+
- "What does X export?" → Check Exports field
|
|
139
|
+
- "What depends on X?" → Check Data Flow
|
|
140
|
+
- "What state does X manage?" → Check State Management section
|
|
141
|
+
- "What type is X?" → Check Types field
|
|
142
|
+
- "What stack/framework?" → Check Architecture section
|
|
143
|
+
</knowledge_format>`}function Yo(){const t=he.getState().getConnectedTools(),{skills:o}=F.getState(),e=o.filter(l=>l.enabled),s=F.getState().channels.some(l=>l.enabled&&l.repoMeta);if(t.length===0&&e.length===0)return"";const a=[];if(t.length>0){a.push("## Available MCP Tools");for(const l of t)a.push(`- **${l.name}**: ${l.description||"No description"}`)}if(e.length>0){a.length>0&&a.push(""),a.push("## Available Skills");for(const l of e)a.push(`- **${l.name}**: ${l.description||"No description"}`)}a.push(""),a.push("## Tool Usage Patterns");const r=t.filter(l=>/get_file|read_file|file_content/i.test(l.name));r.length>0&&s&&(a.push("### File Access"),a.push("- **FIRST**: Check your loaded knowledge (Key Files, Data Flow, Exports) — most structural questions are answered there"),a.push("- **THEN**: Use file tools ONLY for actual source code / implementation details"),a.push(`- Tool: \`${r[0].name}\` — pass a single file path, NOT a directory`));const i=t.filter(l=>/search|find|grep|query/i.test(l.name)&&!/search_nodes/i.test(l.name));if(i.length>0){a.push("### Search");for(const l of i)a.push(`- \`${l.name}\`: Use for finding files or symbols not in loaded knowledge`)}return t.filter(l=>/search_nodes|read_graph|knowledge_graph/i.test(l.name)).length>0&&s&&(a.push("### Knowledge Graph (Low Priority)"),a.push("- Your loaded knowledge already contains structure, dependencies, and exports"),a.push("- Do NOT use graph tools to find basic repo structure — it is already in your context"),a.push("- Use graph tools ONLY for cross-repo relationship queries not covered by loaded knowledge")),a.push(""),a.push("## Anti-Patterns (NEVER do these)"),r.length>0&&a.push(`- NEVER pass a directory path to \`${r[0].name}\` — it only accepts single files`),s&&(a.push("- NEVER open a file just to check its exports or types — that information is in your loaded knowledge"),a.push("- NEVER fabricate file URLs — use base URL from orientation + exact file path from Key Files"),a.push("- NEVER call search_nodes/read_graph for structure already in your context")),s&&(a.push(""),a.push("## Recommended Workflow"),a.push("1. Check orientation block → find which repo/feature is relevant"),a.push("2. Check loaded knowledge → exports, data flow, types, architecture"),a.push("3. Need implementation details? → `get_file_contents` with exact file path"),a.push("4. Need something not indexed? → search tools"),a.push("5. Need cross-repo relationships? → graph tools")),`<tool_guide>
|
|
144
|
+
${a.join(`
|
|
145
|
+
`)}
|
|
146
|
+
</tool_guide>`}const Vo=[{headingPatterns:[/(naming|branch|commit|file|variable|function|class|component)\s*(naming|convention|format|pattern|rule|standard)/i],contentPatterns:[/\b(format|pattern|example|convention):/i,/\b(feat|fix|chore|docs|refactor|test|style)\//,/\b(camelCase|PascalCase|snake_case|kebab-case|SCREAMING_SNAKE)\b/i],target:"naming"},{headingPatterns:[/^(rules?|constraints?|conventions?|standards?|guidelines?|requirements?|policies?|must|never|always)/i,/^(code\s*style|coding\s*standards?|linting|formatting)/i,/^(security|safety|boundaries)/i],contentPatterns:[/\b(MUST|SHALL|MUST NOT|SHALL NOT|REQUIRED|NEVER|ALWAYS|DO NOT|FORBIDDEN)\b/,/\b(rule|convention|standard|pattern|format):/i,/^[-*]\s*(always|never|do not|must|required|forbidden)/im],target:"constraint"},{headingPatterns:[/^(workflow|process|checklist|steps?|pipeline|review|procedure)/i,/^(before|after)\s*(commit|merge|push|deploy|review|submit)/i,/^(ci|cd|testing|deploy|release)\s*(process|steps|workflow)?/i],contentPatterns:[/\b(step\s*\d|first|then|next|finally|before|after)\b/i,/^\d+\.\s+/m,/^[-*]\s*\[[\sx]?\]/m],target:"workflow"},{headingPatterns:[/^(persona|identity|tone|voice|style|character|vibe)/i,/^(communication|behavior|personality)/i,/^(soul|core\s*truths?|principles?)/i,/who\s*(you|i)\s*a(m|re)/i],contentPatterns:[/\b(tone|voice|style|personality|character):/i,/\bbe\s+(concise|direct|formal|casual|friendly|professional|warm|snarky)/i],target:"persona"},{headingPatterns:[/^(tools?|tooling|stack|tech|preferred\s*stack|dependencies|preferred)/i,/^(use|prefer|recommended)\s*(tools?|frameworks?|libraries?)/i],contentPatterns:[/\b(prefer|use|recommended|required):\s*/i,/\b(npm|yarn|pnpm|pip|cargo|go)\s+(run|install|test|build)\b/i],target:"tool"},{headingPatterns:[/^(output|response|format|template|formatting|structure)/i,/^(how to|writing|documentation)\s*(format|style|write|structure)/i,/^(pr|pull\s*request|commit|changelog|report)\s*(template|format|description)/i],contentPatterns:[/\b(format|template|structure|layout|output|response)\b.*\b(must|should|always)/i,/\b(markdown|json|yaml|table|list|bullet|heading|section)\b/i,/```[\s\S]*?```/],target:"output"}];function Jo(t){const o=[],e=t.split(`
|
|
147
|
+
`);let n="",s=0,a=[];for(const r of e){const i=r.match(/^(#{1,6})\s+(.+)/);i?((n||a.length>0)&&o.push({heading:n,level:s,content:a.join(`
|
|
148
|
+
`).trim()}),s=i[1].length,n=i[2],a=[]):a.push(r)}return(n||a.length>0)&&o.push({heading:n,level:s,content:a.join(`
|
|
149
|
+
`).trim()}),o}function Qo(t,o){return o.headingPatterns.some(s=>s.test(t.heading))?!0:o.contentPatterns.filter(s=>s.test(t.content)).length>=2}function Zo(t){const o=[],e=t.content.split(`
|
|
150
|
+
`);for(const n of e){const s=n.replace(/^[-*]\s*/,"").trim();!s||s.startsWith("#")||s.startsWith("```")||(/\b(MUST|SHALL|NEVER|ALWAYS|DO NOT|FORBIDDEN|REQUIRED|should|must not)\b/i.test(s)||/^(use|prefer|avoid|ensure|keep|maintain|follow|check|run|test|verify|write|create|name)/i.test(s)&&n.match(/^[-*]\s/))&&o.push(s)}return o}function Xo(t){const o=[],e=t.content.split(`
|
|
151
|
+
`);for(const n of e){const s=n.trim(),a=s.match(/^\d+\.\s+(.+)/);if(a){o.push(a[1]);continue}const r=s.match(/^[-*]\s*\[[\sx]?\]\s*(.+)/);r&&o.push(r[1])}if(o.length===0)for(const n of e){const s=n.match(/^[-*]\s+(.+)/);s&&s[1].length>10&&o.push(s[1])}return o}function es(t){const o=[],e=`${t.heading}
|
|
152
|
+
${t.content}`,n=e.match(/branch.*?(?:format|pattern|naming|convention).*?[:`]\s*(.+?)(?:\n|$)/i)||e.match(/(?:feat|fix|chore|hotfix)\/[<\[{]?\w+/);if(n){const i=e.match(/(?:example|e\.g\.|e\.g).*?[:`]\s*(.+?)(?:\n|$)/i);o.push({target:"branch",pattern:n[1]||n[0],example:i?.[1]?.trim()})}const s=e.match(/commit.*?(?:format|pattern|message|convention).*?[:`]\s*(.+?)(?:\n|$)/i)||e.match(/(?:type)\(scope\):\s*description/i);s&&o.push({target:"commit",pattern:s[1]||s[0]});const a=e.match(/file.*?(?:naming|convention|pattern).*?[:`]\s*(.+?)(?:\n|$)/i);a&&o.push({target:"file",pattern:a[1]});const r=e.match(/(?:pr|pull\s*request).*?(?:format|title|naming).*?[:`]\s*(.+?)(?:\n|$)/i);return r&&o.push({target:"pr",pattern:r[1]}),o}function ts(t,o){const e=Jo(t),n={constraints:[],workflowSteps:[],personaHints:[],toolHints:[],outputRules:[],namingPatterns:[],residual:"",source:o},s=[];for(const a of e){let r=!1;for(const i of Vo)if(Qo(a,i)){switch(r=!0,i.target){case"constraint":n.constraints.push(...Zo(a));break;case"workflow":n.workflowSteps.push(...Xo(a));break;case"persona":a.content.trim()&&n.personaHints.push(a.content.trim());break;case"tool":for(const c of a.content.split(`
|
|
153
|
+
`)){const l=c.match(/^[-*]\s+(.+)/);l&&n.toolHints.push(l[1].trim())}break;case"naming":n.namingPatterns.push(...es(a));break;case"output":{for(const l of a.content.split(`
|
|
154
|
+
`)){const d=l.match(/^[-*]\s+(.+)/);d&&d[1].length>10&&n.outputRules.push(d[1].trim())}const c=a.content.match(/```[\s\S]*?```/g);if(c)for(const l of c)n.outputRules.push(l);break}}break}!r&&a.content.trim()&&s.push(a.heading?`${"#".repeat(a.level)} ${a.heading}
|
|
155
|
+
${a.content}`:a.content)}return n.residual=s.join(`
|
|
156
|
+
|
|
157
|
+
`),n}function ve(t,o){const e=t.replace(/\b(must|never|always|should|do not|avoid|use|prefer)\b/gi,"").split(/\s+/).filter(s=>s.length>=3),n=new Set(o.replace(/\b(must|never|always|should|do not|avoid|use|prefer)\b/gi,"").split(/\s+/).filter(s=>s.length>=3));return e.some(s=>n.has(s))}function ns(t){const o=t.flatMap(d=>d.constraints),e=t.flatMap(d=>d.workflowSteps),n=t.flatMap(d=>d.personaHints),s=t.flatMap(d=>d.toolHints),a=t.map(d=>d.residual).filter(Boolean),r=[...new Set(o)],i=[];for(let d=0;d<r.length;d++)for(let m=d+1;m<r.length;m++){const u=r[d].toLowerCase(),p=r[m].toLowerCase();(u.includes("must")&&p.includes("never")&&ve(u,p)||u.includes("never")&&p.includes("must")&&ve(u,p)||u.includes("use ")&&p.includes("avoid ")&&ve(u,p)||u.includes("avoid ")&&p.includes("use ")&&ve(u,p))&&i.push(`⚠️ Conflict: "${r[d]}" vs "${r[m]}"`)}const c=t.flatMap(d=>d.namingPatterns).map(d=>{const m=d.example?` (e.g. ${d.example})`:"";return`${d.target} naming: ${d.pattern}${m}`}),l=[...r,...c];return{conflicts:i,constraintsBlock:l.length>0?`<framework_constraints source="guidelines">
|
|
158
|
+
${l.map(d=>`- ${d}`).join(`
|
|
159
|
+
`)}${i.length>0?`
|
|
160
|
+
|
|
161
|
+
Conflicts detected:
|
|
162
|
+
`+i.join(`
|
|
163
|
+
`):""}
|
|
164
|
+
</framework_constraints>`:"",workflowBlock:e.length>0?`<framework_workflow>
|
|
165
|
+
${e.map((d,m)=>`${m+1}. ${d}`).join(`
|
|
166
|
+
`)}
|
|
167
|
+
</framework_workflow>`:"",personaBlock:n.length>0?`<framework_persona>
|
|
168
|
+
${n.join(`
|
|
169
|
+
|
|
170
|
+
`)}
|
|
171
|
+
</framework_persona>`:"",toolHintsBlock:s.length>0?`<tool_hints>
|
|
172
|
+
${s.map(d=>`- ${d}`).join(`
|
|
173
|
+
`)}
|
|
174
|
+
</tool_hints>`:"",outputBlock:t.flatMap(d=>d.outputRules).length>0?`<output_format>
|
|
175
|
+
Format your responses according to these rules:
|
|
176
|
+
${t.flatMap(d=>d.outputRules).map(d=>d.startsWith("```")?d:`- ${d}`).join(`
|
|
177
|
+
`)}
|
|
178
|
+
</output_format>`:"",residualKnowledge:a.length>0?a.join(`
|
|
179
|
+
|
|
180
|
+
---
|
|
181
|
+
|
|
182
|
+
`):""}}async function os(t,o){const e=ge.getState(),n=D.getState(),s=new Set(["framework","guideline"]),a=t.filter(m=>s.has(m.knowledgeType)),r=t.filter(m=>!s.has(m.knowledgeType));let i="",c,l="";const d=t.filter(m=>m.path);if(d.length>0){const m=Date.now();await e.indexFiles(d.map(u=>u.path)),n.addEvent(o,{kind:"retrieval",sourceName:"pipeline:fetch",query:`${d.length} sources`,resultCount:d.filter(u=>e.getIndex(u.path)!=null).length,durationMs:Date.now()-m})}if(a.length>0){const m=a.map(u=>{let p=u.path?e.getIndex(u.path):null;if(!p&&u.content){const y=`content://${u.contentSourceId||u.sourceId}`;p=Q(y,u.content)}if(!p)return null;const g=de(p,0),f=pe(g.filtered);return f.trim()?ts(f,u.name):null}).filter(u=>u!==null);if(m.length>0){const u=ns(m);i=[u.constraintsBlock,u.workflowBlock,u.personaBlock,u.toolHintsBlock,u.outputBlock].filter(Boolean).join(`
|
|
183
|
+
|
|
184
|
+
`),c={constraints:m.reduce((g,f)=>g+f.constraints.length,0),workflowSteps:m.reduce((g,f)=>g+f.workflowSteps.length,0),personaHints:m.reduce((g,f)=>g+f.personaHints.length,0),toolHints:m.reduce((g,f)=>g+f.toolHints.length,0),outputRules:m.reduce((g,f)=>g+f.outputRules.length,0),namingPatterns:m.reduce((g,f)=>g+f.namingPatterns.length,0),sources:m.map(g=>g.source)},u.residualKnowledge.trim()&&(l=`<knowledge type="framework-residual">
|
|
185
|
+
${u.residualKnowledge}
|
|
186
|
+
</knowledge>`),n.addEvent(o,{kind:"retrieval",sourceName:"pipeline:framework",query:`${m.length} framework sources`,resultCount:m.reduce((g,f)=>g+f.constraints.length+f.workflowSteps.length,0),durationMs:0})}}return{frameworkBlock:i,frameworkSummary:c,regularChannels:r,residualKnowledgeBlock:l}}const ss={"ground-truth":.3,guideline:.15,framework:.15,evidence:.2,signal:.12,hypothesis:.08},as=.03,rs={0:1.5,1:1.2,2:1,3:.6,4:.2};function is(t,o){if(t.length===0)return[];if(o<=0)return t.map(r=>({name:r.name,knowledgeType:r.knowledgeType,allocatedTokens:0,weight:0,cappedBySize:!1}));const e=new Map;for(const r of t)e.has(r.knowledgeType)||e.set(r.knowledgeType,[]),e.get(r.knowledgeType).push(r);const n=[];for(const[r,i]of e){const c=ss[r],l=i.length;for(const d of i){const m=d.depthMultiplier??1,u=c/l*m,p=Math.max(u,as);n.push({name:d.name,knowledgeType:d.knowledgeType,allocatedTokens:0,weight:p,cappedBySize:!1})}}const s=n.reduce((r,i)=>r+i.weight,0);if(s>0)for(const r of n)r.weight=r.weight/s;for(const r of n)r.allocatedTokens=Math.round(r.weight*o);const a=new Map(t.map(r=>[r.name,r]));for(let r=0;r<3;r++){let i=0;const c=[];for(const l of n){const d=a.get(l.name);l.allocatedTokens>d.rawTokens?(i+=l.allocatedTokens-d.rawTokens,l.allocatedTokens=d.rawTokens,l.cappedBySize=!0):l.cappedBySize||c.push(l)}if(i>0&&c.length>0){const l=c.reduce((d,m)=>d+m.weight,0);if(l>0)for(const d of c){const m=Math.round(d.weight/l*i);d.allocatedTokens+=m}}else break}return n}function Ve(t){const o=[];o.push(`Source: ${t.source} (${t.totalTokens} tokens, ${t.nodeCount} nodes)`),o.push("");function e(n,s){if(n.depth===0&&n.children.length>0){for(const l of n.children)e(l,s);return}const a=" ".repeat(s),r=n.totalTokens>0?` [${n.totalTokens} tokens]`:"",i=n.children.length>0?` (${n.children.length} subsections)`:"",c=n.meta?.firstSentence?` — ${n.meta.firstSentence}`:"";o.push(`${a}[${n.nodeId}] ${n.title}${r}${i}${c}`);for(const l of n.children)e(l,s+1)}return e(t.root,0),o.join(`
|
|
187
|
+
`)}function Je(t,o){return`You are selecting which parts of the knowledge base to include in context for a coding task.
|
|
188
|
+
|
|
189
|
+
TASK: ${o.task}
|
|
190
|
+
TOKEN BUDGET: ${o.tokenBudget} tokens available for knowledge
|
|
191
|
+
|
|
192
|
+
Below are the available knowledge sources with their tree structure. Each node shows:
|
|
193
|
+
- [nodeId] Title [total tokens] (subsections) — first sentence
|
|
194
|
+
|
|
195
|
+
YOUR JOB: Select which branches to include and at what depth:
|
|
196
|
+
- depth 0 (Full): Include everything — use for critical sections you need to read carefully
|
|
197
|
+
- depth 1 (Detail): First paragraph per leaf — use for important context
|
|
198
|
+
- depth 2 (Summary): First sentence per section — use for orientation
|
|
199
|
+
- depth 3 (Headlines): Just titles — use for awareness
|
|
200
|
+
- depth 4 (Mention): Skip content — just note it exists
|
|
201
|
+
|
|
202
|
+
RULES:
|
|
203
|
+
- Stay within the token budget (depths reduce tokens: Full=100%, Detail=75%, Summary=50%, Headlines=25%, Mention=10%)
|
|
204
|
+
- Prioritize sections directly relevant to the task
|
|
205
|
+
- Include architectural context at Summary/Headlines even if not directly relevant
|
|
206
|
+
- Be specific about WHY you selected each branch
|
|
207
|
+
|
|
208
|
+
SOURCES:
|
|
209
|
+
${t.join(`
|
|
210
|
+
|
|
211
|
+
---
|
|
212
|
+
|
|
213
|
+
`)}
|
|
214
|
+
|
|
215
|
+
Respond with a JSON array of selections:
|
|
216
|
+
[
|
|
217
|
+
{ "nodeId": "n1-0", "depth": 0, "reason": "Need full implementation details for the order store", "priority": 0 },
|
|
218
|
+
{ "nodeId": "n1-3", "depth": 2, "reason": "Architecture context for understanding the module", "priority": 2 },
|
|
219
|
+
...
|
|
220
|
+
]${o.existingContext?`
|
|
221
|
+
|
|
222
|
+
ALREADY IN CONTEXT (don't duplicate):
|
|
223
|
+
${o.existingContext}`:""}`}function Wt(t,o){if(t.nodeId===o)return t;for(const e of t.children){const n=Wt(e,o);if(n)return n}return null}function Gt(t,o){const e=[];if(o===4)return"";if(o===3){t.depth>0&&e.push(`${"#".repeat(t.depth)} ${t.title}`);for(const n of t.children)n.depth<=2&&e.push(`${"#".repeat(n.depth)} ${n.title}`);return e.join(`
|
|
224
|
+
`)}t.depth>0&&e.push(`${"#".repeat(t.depth)} ${t.title}`),o===0?t.text&&e.push(t.text):o===1?t.children.length===0&&t.meta?.firstParagraph?e.push(t.meta.firstParagraph):t.text&&e.push(t.text):o===2&&t.meta?.firstSentence&&e.push(t.meta.firstSentence);for(const n of t.children){const s=Gt(n,o);s&&e.push(s)}return e.join(`
|
|
225
|
+
|
|
226
|
+
`)}function cs(t,o){const e=[],n=new Map;for(const r of t)n.set(r.source,r);for(const r of o.selections){let i=null;for(const l of t)if(i=Wt(l.root,r.nodeId),i)break;if(!i)continue;const c=Gt(i,r.depth);c.trim()&&e.push({priority:r.priority,nodeId:r.nodeId,content:c,tokens:I(c),depth:r.depth})}e.sort((r,i)=>r.priority-i.priority);const s=e.map(r=>r.content).join(`
|
|
227
|
+
|
|
228
|
+
---
|
|
229
|
+
|
|
230
|
+
`),a=e.map(r=>({nodeId:r.nodeId,tokens:r.tokens,depth:r.depth}));return{content:s,tokens:I(s),breakdown:a}}function xe(t){const o=t.match(/\[[\s\S]*\]/);if(!o)return[];try{const e=JSON.parse(o[0]);return Array.isArray(e)?e.filter(n=>typeof n=="object"&&n!==null&&"nodeId"in n&&"depth"in n&&typeof n.depth=="number").map(n=>({nodeId:n.nodeId,depth:Math.max(0,Math.min(4,n.depth)),reason:n.reason||"",priority:n.priority??2})):[]}catch{return[]}}function ls(t,o){const e=o.length>4e3?o.slice(0,4e3)+"...[truncated]":o;return`You are auditing whether the provided context contains enough information to complete a coding task.
|
|
231
|
+
|
|
232
|
+
TASK: ${t}
|
|
233
|
+
|
|
234
|
+
CURRENT CONTEXT:
|
|
235
|
+
${e}
|
|
236
|
+
|
|
237
|
+
YOUR JOB: Identify what critical information is MISSING from the context to complete this task. Look for:
|
|
238
|
+
- Missing implementation details or code examples
|
|
239
|
+
- Missing architectural context or relationships
|
|
240
|
+
- Missing configuration or setup information
|
|
241
|
+
- Missing error handling or edge case patterns
|
|
242
|
+
|
|
243
|
+
Respond with a JSON array of missing information gaps (maximum 3):
|
|
244
|
+
["Missing error handling patterns for API failures", "Missing database schema for user table", "Missing authentication flow details"]
|
|
245
|
+
|
|
246
|
+
If the context appears complete for the task, respond with: []`}function ds(t){const o=t.match(/\[[\s\S]*?\]/);if(!o)return[];try{const e=JSON.parse(o[0]);return Array.isArray(e)?e.filter(n=>typeof n=="string"&&n.trim().length>0).slice(0,3):[]}catch{return[]}}function ps(t){return`You are writing a hypothetical documentation passage that would perfectly answer this query.
|
|
247
|
+
|
|
248
|
+
QUERY: ${t}
|
|
249
|
+
|
|
250
|
+
Write a comprehensive documentation passage that would ideally exist in a codebase to answer this question. Include:
|
|
251
|
+
- Relevant code examples
|
|
252
|
+
- Implementation details
|
|
253
|
+
- Configuration options
|
|
254
|
+
- Common patterns and best practices
|
|
255
|
+
|
|
256
|
+
Write as if this documentation already exists and covers exactly what the user needs to know:`}function us(t){return t.trim().split(/\s+/).length>=10}function ms(t,o=8){return t.toLowerCase().replace(/[^\w\s]/g,"").replace(/\s+/g," ").trim().split(" ").slice(0,o).join(" ")}function gs(t,o){const e=new Set,n=[];let s=0;for(let a=0;a<t.length;a++){const r=t[a];if(o.has(a)){n.push(r);continue}const i=ms(r);if(i.length<10){n.push(r);continue}if(e.has(i)){s++;continue}e.add(i),n.push(r)}return{result:n,removed:s}}const hs=[/^(as mentioned|as noted|as described|as stated|as shown|as seen)\b/i,/^(it is worth noting|it should be noted|it is important to note|note that)\b/i,/^(in this section|in the following|the following section|this section)\b/i,/^(let's|let us|we will|we'll|we can|we should)\s+(look at|examine|explore|consider|discuss|review|take a look)/i,/^(basically|essentially|fundamentally|generally speaking|in general)\b/i,/^(it goes without saying|needless to say|obviously|of course|clearly)\b/i,/^(furthermore|moreover|additionally|in addition|also|besides|what's more)\s*,?\s*$/i,/^(in conclusion|to summarize|to sum up|in summary|overall)\s*,?\s*$/i];function fs(t){const o=t.trim();if(!o)return 1;let e=0;for(const i of hs)if(i.test(o)){e+=.6;break}const n=o.split(/\s+/).length;n<4&&(e+=.3);const s=new Set(["the","a","an","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","shall","can","this","that","these","those","it","its","to","of","in","for","on","with","at","by","from","as","into","about"]),a=o.toLowerCase().split(/\s+/);return a.filter(i=>s.has(i)).length/a.length>.7&&n>5&&(e+=.2),Math.min(1,e)}function ys(t,o=.5,e){let n=0;const s=[];for(let a=0;a<t.length;a++){const r=t[a];if(e.has(a)){s.push(r);continue}const c=r.split(new RegExp("(?<=[.!?])\\s+")).filter(l=>fs(l)>=o?(n++,!1):!0);c.length>0&&s.push(c.join(" "))}return{result:s,removed:n}}function ks(t){let o=0;return{result:t.replace(/```[\s\S]*?```/g,n=>{const s=n.split(`
|
|
257
|
+
`),a=s[0],r=s[s.length-1],c=s.slice(1,-1).filter(l=>{const d=l.trim();return d.startsWith("//")&&!d.startsWith("///")&&!d.startsWith("//!")||d.startsWith("#")&&!d.startsWith("#!")&&!d.startsWith("# ")?(o++,!1):!!d});return[a,...c,r].join(`
|
|
258
|
+
`)}),removedComments:o}}function ws(t,o={}){const{dedup:e=!0,removeFiller:n=!0,compressCode:s=!0,aggressiveness:a=.5,tokenBudget:r,preservePatterns:i=[]}=o,c=I(t);let l=t,d=0,m=0,u=0;if(s){const k=ks(l);l=k.result,u=k.removedComments}let p=l.split(/\n\s*\n/).filter(k=>k.trim());const g=i.map(k=>new RegExp(k,"i")),f=k=>{const h=new Set;if(g.length===0)return h;for(let w=0;w<k.length;w++)g.some(v=>v.test(k[w]))&&h.add(w);return h};if(e){const k=gs(p,f(p));p=k.result,d=k.removed}if(n){const k=.3+.4*(1-a),h=ys(p,k,f(p));p=h.result,m=h.removed}if(l=p.join(`
|
|
259
|
+
|
|
260
|
+
`),r){let k=I(l);if(k>r){const h=f(p);for(;p.length>1&&k>r;){let w=-1;for(let v=p.length-1;v>=0;v--)if(!h.has(v)){w=v;break}if(w<0)break;p.splice(w,1),l=p.join(`
|
|
261
|
+
|
|
262
|
+
`),k=I(l)}}}const y=I(l);return{content:l,originalTokens:c,compressedTokens:y,ratio:c>0?y/c:1,removals:{duplicates:d,filler:m,codeComments:u}}}function bs(t){switch(t.type){case"markdown":return Q(t.name,t.content||"");case"structured":return xn(t.name,t.fields||[],t.sourceType);case"chronological":return Cn(t.name,t.entries||[],t.sourceType);case"flat":return nt(t.name,t.content||"",t.sourceType);default:return nt(t.name,t.content||"")}}function vs(t,o){const e=Date.now(),n=t.sources.map(bs),s=Date.now()-e,a=n.map(Ve),r=Je(a,{task:t.task,tokenBudget:t.tokenBudget});return{indexes:n,headlines:a,navigationPrompt:r,indexMs:s}}function ht(t,o,e,n,s){const a=Date.now(),r=e.manualSelections||xe(o),i=Date.now()-a,c={source:e.sources.map(y=>y.name).join(", "),selections:r,taskRelevance:e.task},l=cs(t,c),d=Date.now();let m,u={originalTokens:0,compressedTokens:0,ratio:1,removals:{duplicates:0,filler:0,codeComments:0}};if(e.compression?.enabled!==!1&&l.content)if(l.breakdown.map(k=>({content:l.content,priority:r.find(h=>h.nodeId===k.nodeId)?.priority??2})).length>0){const k=ws(l.content,{tokenBudget:e.tokenBudget,aggressiveness:e.compression?.aggressiveness??.5});m=k.content,u={originalTokens:k.originalTokens,compressedTokens:k.compressedTokens,ratio:k.ratio,removals:k.removals}}else m=l.content;else m=l.content,u.originalTokens=I(l.content),u.compressedTokens=u.originalTokens;const p=Date.now()-d,g=n+i+p,f=I(m);return{context:m,tokens:f,utilization:e.tokenBudget>0?f/e.tokenBudget:0,sources:t.map(y=>({name:y.source,type:y.sourceType,totalTokens:y.totalTokens,indexedNodes:y.nodeCount})),navigation:{selections:r,prompt:void 0},compression:u,indexes:t,timing:{indexMs:n,navigationMs:i,compressionMs:p,totalMs:g}}}const Ss=[/\bnot\b/i,/\bhowever\b/i,/\bcontrary to\b/i,/\bunlike\b/i,/\bfails to\b/i,/\bbut\b/i,/\balthough\b/i,/\bwhile\b/i,/\bwhereas\b/i,/\binstead\b/i,/\brather than\b/i,/\bon the other hand\b/i,/\bin contrast\b/i,/\bnevertheless\b/i,/\bnonetheless\b/i,/\bdespite\b/i,/\bin spite of\b/i],Ts=[/\blimitations?\b/i,/\brestrictions?\b/i,/\bchallenges?\b/i,/\bproblems?\b/i,/\bissues?\b/i,/\brisks?\b/i,/\bdisadvantages?\b/i,/\bcons\b/i,/\bweaknesses?\b/i,/\bfailures?\b/i,/\berrors?\b/i,/\bmistakes?\b/i,/\balternatives?\b/i,/\bother approaches?\b/i,/\bdifferent view\b/i,/\bopposing\b/i,/\bcounter\b/i],xs=[/\bresults?\b/i,/\bbenefits?\b/i,/\badvantages?\b/i,/\bpros\b/i,/\bstrengths?\b/i,/\bsuccesses?\b/i,/\bachievements?\b/i,/\bimprovements?\b/i,/\bgains?\b/i,/\bpositive\b/i,/\brecommendations?\b/i,/\bbest practices?\b/i];function ft(t){const o=new Set;return(t.match(/\b[A-Z][a-z]+(?:\s+[A-Z][a-z]*)*\b/g)||[]).forEach(i=>o.add(i.toLowerCase())),(t.match(/"([^"]+)"/g)||[]).forEach(i=>o.add(i.replace(/"/g,"").toLowerCase())),(t.match(/`([^`]+)`/g)||[]).forEach(i=>o.add(i.replace(/`/g,"").toLowerCase())),(t.match(/\*\*([^*]+)\*\*/g)||[]).forEach(i=>o.add(i.replace(/\*\*/g,"").toLowerCase())),(t.match(/\*([^*]+)\*/g)||[]).forEach(i=>o.add(i.replace(/\*/g,"").toLowerCase())),o}function Cs(t,o){const e=ft(t.content),n=ft(o.content);if(e.size===0&&n.size===0)return 0;const s=new Set(Array.from(e).filter(r=>n.has(r))),a=new Set([...Array.from(e),...Array.from(n)]);return s.size/a.size}function As(t){return Ss.some(o=>o.test(t))}function yt(t){const o=t.toLowerCase();return Ts.some(e=>e.test(o))?"contrasting":xs.some(e=>e.test(o))?"supporting":"neutral"}function Ps(t,o,e=.2){const n=[],s=[],a=new Set(t.map(r=>`${r.source}:${r.section}`));for(const r of t){let i=null,c="",l=0;for(const d of o){const m=`${d.source}:${d.section}`;if(m===`${r.source}:${r.section}`||a.has(m))continue;const u=Cs(r,d);if(u<e)continue;let p=0,g="";const f=yt(r.section),y=yt(d.section);f==="supporting"&&y==="contrasting"?(p+=.6,g=`contrasting section types: "${r.section}" vs "${d.section}"`):f==="contrasting"&&y==="supporting"&&(p+=.6,g=`contrasting section types: "${r.section}" vs "${d.section}"`),As(d.content)&&(p+=.4,g?g+=" + negation patterns":g="negation patterns detected"),p+=u*.3,p>l&&(l=p,i=d,c=g)}if(i&&l>.3){const d=`${i.source}:${i.section}`;n.some(m=>`${m.source}:${m.section}`===d)||n.push(i),s.push({supporting:r,contrasting:i,reason:c})}}return{supporting:t,contrasting:n,pairs:s}}function Es(t){return[/\bshould we\b/i,/\bcompare\b/i,/\bwhich is better\b/i,/\bpros and cons\b/i,/\bevaluate\b/i,/\banalyz(e|ation)/i,/\bassess\b/i,/\balternatives?\b/i,/\bdecid[ei](on)?\b/i,/\btrade-?offs?\b/i,/\badvantages?\b/i,/\bdisadvantages?\b/i,/\bvs\.?\s/i,/\bversus\b/i,/\bweigh\b/i].some(e=>e.test(t))}function De(t){const o=t.toLowerCase();return/\b(compare|vs|versus|evaluate|pros and cons|advantages|disadvantages|should we|tradeoffs?|better|worse|choose|decide|recommend)\b/.test(o)?"analytical":o.length<50||/\b(what is|how does|who is|when did|where is|define|definition)\b/.test(o)||/\b(version|spec|api|format|syntax|command)\b/.test(o)?"factual":"exploratory"}function Is(t){switch(t){case"factual":return .9;case"analytical":return .5;case"exploratory":return .7}}function Ms(t,o=500){if(t.tokens<=o)return[{content:t.text,nodeId:t.nodeId,source:"",section:t.title,parentNodeId:void 0,depth:t.depth,knowledgeType:"signal"}];const e=t.text.split(/\n\s*\n/),n=[];let s="",a=0;for(const r of e){const i=s?`${s}
|
|
263
|
+
|
|
264
|
+
${r}`:r;I(i)>o&&s?(n.push({content:s.trim(),nodeId:`${t.nodeId}-${a++}`,source:"",section:`${t.title} (part ${a})`,parentNodeId:t.nodeId,depth:t.depth+1,knowledgeType:"signal"}),s=r):s=i}return s.trim()&&n.push({content:s.trim(),nodeId:`${t.nodeId}-${a}`,source:"",section:`${t.title} (part ${a+1})`,parentNodeId:t.nodeId,depth:t.depth+1,knowledgeType:"signal"}),n}function _s(t){const o=[];for(const{treeIndex:e,knowledgeType:n}of t){const s=[{node:e.root}];for(;s.length>0;){const{node:a,parentId:r}=s.pop();if((a.children.length===0||a.text&&a.text.trim().length>0)&&a.text&&a.text.trim().length>0){const i=Ms(a);for(const c of i)c.source=e.source,c.knowledgeType=n,c.parentNodeId=r,o.push(c)}for(const i of a.children)s.push({node:i,parentId:a.nodeId})}}return o}async function zt(t,o=2){if(t.length===0)return[];const e=[],n=[];for(let c=0;c<t.length;c++)t[c]&&t[c].trim().length>0&&(e.push(c),n.push(t[c]));if(n.length===0)return t.map(()=>[]);const s=100,a=[];for(let c=0;c<n.length;c+=s){const l=n.slice(c,c+s),d=await fetch(`${E}/embeddings/embed`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({texts:l})});if(d.status===503&&o>0)return await new Promise(p=>setTimeout(p,3e3)),zt(t,o-1);if(!d.ok)throw new Error(`Embedding service error: ${d.status} ${d.statusText}`);const m=await d.json();a.push(...m.embeddings||[])}const r={embeddings:a},i=t.map(()=>[]);for(let c=0;c<e.length;c++)i[e[c]]=r.embeddings[c];return i}function ie(t,o){if(t.length!==o.length||t.length===0)return 0;let e=0,n=0,s=0;for(let r=0;r<t.length;r++)e+=t[r]*o[r],n+=t[r]*t[r],s+=o[r]*o[r];const a=Math.sqrt(n)*Math.sqrt(s);return a===0?0:e/a}function $s(t){if(t.length<=1)return 1;const o=t.map(s=>s.embedding).filter(s=>s);if(o.length<=1)return 1;let e=0,n=0;for(let s=0;s<o.length;s++)for(let a=s+1;a<o.length;a++)e+=ie(o[s],o[a]),n++;return n===0?1:1-e/n}function Rs(t,o,e){if(t.length===0)return[];const n=[],s=[...t];let a=0;for(;s.length>0&&a<e;){let r=-1/0,i=-1;for(let d=0;d<s.length;d++){const m=s[d];if(!m.embedding)continue;const u=I(m.content);if(a+u>e)continue;const p=m.relevanceScore;let g=0;for(const y of n)if(y.embedding){const k=ie(m.embedding,y.embedding);g=Math.max(g,k)}const f=o*p-(1-o)*g;f>r&&(r=f,i=d)}if(i===-1)break;const c=s.splice(i,1)[0],l=I(c.content);n.push(c),a+=l}return n}async function Os(t,o,e){const n=Date.now();let s=_s(o);if(s.length===0)return{chunks:[],diversityScore:1,collapseWarning:!1,totalChunks:0,queryType:De(t),retrievalMs:Date.now()-n,embeddingMs:0,budgetUsed:0,budgetTotal:e};const a=Date.now(),r=s.filter(b=>b.content&&b.content.trim().length>0);if(r.length===0)return{chunks:[],diversityScore:1,collapseWarning:!1,totalChunks:s.length,queryType:De(t),retrievalMs:Date.now()-n,embeddingMs:0,budgetUsed:0,budgetTotal:e};s=r;const i=[t,...s.map(b=>b.content)],c=await zt(i),l=Date.now()-a,d=c[0],m=c.slice(1);s.forEach((b,$)=>{b.embedding=m[$]});const u=.3,p=s.map(b=>({...b,relevanceScore:b.embedding?ie(d,b.embedding):0,inclusionReason:"direct"})).filter(b=>b.relevanceScore>u),g=new Map(s.map(b=>[b.nodeId,b])),f=new Map;for(const b of p)if(f.set(b.nodeId,b),b.parentNodeId){const $=g.get(b.parentNodeId);if($&&$.embedding&&!f.has($.nodeId)){const S=b.relevanceScore*.6;S>u&&f.set($.nodeId,{...$,relevanceScore:S,inclusionReason:"parent-expansion"})}}const y=.5,k=.4;for(const b of p)if(b.relevanceScore>y&&b.parentNodeId&&b.embedding){const $=s.filter(S=>S.parentNodeId===b.parentNodeId&&S.nodeId!==b.nodeId&&!f.has(S.nodeId));for(const S of $)if(S.embedding&&ie(b.embedding,S.embedding)>k){const L=ie(d,S.embedding);f.set(S.nodeId,{...S,relevanceScore:L,inclusionReason:"sibling-coherence"})}}const h=De(t),w=Is(h),v=Array.from(f.values()),C=Rs(v,w,e),M=$s(C),T=M<.3,P=C.reduce((b,$)=>b+I($.content),0),_=Date.now()-n;return{chunks:C,diversityScore:M,collapseWarning:T,totalChunks:s.length,queryType:h,retrievalMs:_,embeddingMs:l,budgetUsed:P,budgetTotal:e}}const Yt={"ground-truth":1,evidence:.8,signal:.6,hypothesis:.4},Vt={full:1,summary:.7,headline:.4};function Be(t,o){const e=[],n=[],s=new Map;o.forEach(r=>{s.set(r.name,r),r.path&&s.set(r.path,r)});for(const r of t.sources){const i=s.get(r.name);if(!i)continue;const c=Jt(i.knowledgeType),l=Ls(i.depth);e.push({path:i.path||i.name,type:c,sections:r.indexedNodes,depth:l,method:"tree-index",chunkCount:Math.floor(r.totalTokens/100)}),n.push({from:i.path||i.name,method:"tree-index",to:`index-${r.name}`}),t.compression.ratio<1&&n.push({from:`index-${r.name}`,method:"rtk-compression",to:`compressed-${r.name}`})}const a={weights:Yt,depthWeights:Vt,instructions:Us()};return{sources:e,derivations:n,conflictResolution:a}}function Fs(t){return t.map(o=>{const e=Jt(o.type),n=qs(o.depth),s=Ns(e,n);return{content:o.content,provenance:{source:o.source,section:o.section,type:e,depth:n,method:o.method,confidence:s}}})}function Ds(t){const o=[],e=new Set,n=js(t);for(const[s,a]of Object.entries(n)){if(a.length<2)continue;const r=Ks(a);for(const i of r){const c=i.map(d=>`${d.provenance.source}:${d.provenance.section}`).sort().join("|");if(e.has(c))continue;e.add(c);const l=Bs(i);l&&o.push({conflictingChunks:i,resolution:l})}}return o}function Ns(t,o){const e=Yt[t]||.5,n=Vt[o]||.5;return e*n}function Jt(t){switch(t){case"ground-truth":return"ground-truth";case"evidence":return"evidence";case"signal":return"signal";case"hypothesis":return"hypothesis";default:return"signal"}}function Ls(t){switch(t){case 0:return"full";case 1:return"summary";case 2:return"headline";default:return"summary"}}function qs(t){switch(t){case"full":return"full";case"summary":return"summary";case"headline":return"headline";default:return"summary"}}function Us(){return`When sources conflict, apply this priority order:
|
|
265
|
+
1. Source reliability: ground-truth > evidence > signal > hypothesis
|
|
266
|
+
2. Content depth: full > summary > headline
|
|
267
|
+
3. Recency: prefer more recent information when timestamps are available
|
|
268
|
+
4. Specificity: prefer specific details over general statements
|
|
269
|
+
|
|
270
|
+
When presenting conflicting information, acknowledge the conflict and explain your reasoning based on source reliability.`}function js(t){const o={};for(const e of t){const n=e.provenance.section||"general";o[n]||(o[n]=[]),o[n].push(e)}return o}function Ks(t){const o=[];for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++){const s=t[e],a=t[n];s.provenance.source!==a.provenance.source&&s.provenance.section===a.provenance.section&&Hs(s.content,a.content)<.7&&o.push([s,a])}return o}function Bs(t){let o=t[0],e=o.provenance.confidence;for(const s of t)s.provenance.confidence>e&&(o=s,e=s.provenance.confidence);const n=`Preferred ${o.provenance.type} source (confidence: ${e.toFixed(2)}) over other sources`;return{preferredChunk:o,reason:n,confidence:e}}function Hs(t,o){const e=new Set(t.toLowerCase().split(/\s+/)),n=new Set(o.toLowerCase().split(/\s+/)),s=new Set([...e].filter(r=>n.has(r))),a=new Set([...e,...n]);return s.size/a.size}function oe(t,o,e,n){D.getState().addEvent(t,{kind:"pipeline_stage",durationMs:n,provenanceStages:[{stage:o,timestamp:Date.now(),durationMs:n,data:e}]})}function He(t,o,e,n,s,a){return`<chunk source="${o}" section="${e}" type="${n}" depth="${s}" method="${a}">
|
|
271
|
+
${t}
|
|
272
|
+
</chunk>`}function Ws(t,o){const e=[];if(!t.context)return e;const n=new Map;for(const a of o)n.set(a.name,a),a.path&&n.set(a.path,a);const s=Gs(t.context);for(const a of s){let r;for(const c of t.sources)if(a.content.length>0&&n.has(c.name)){r=n.get(c.name);break}const i=r?Te[r.depth]?.label??"full":"full";e.push({content:a.content,source:r?.path||r?.name||"unknown",section:a.heading||"main",type:r?.knowledgeType||"signal",depth:i,method:"tree-index-pipeline",node:{}})}return e}function Gs(t){const o=t.split(`
|
|
273
|
+
`),e=[];let n="",s=[];for(const a of o){const r=a.match(/^#{1,4}\s+(.+)/);if(r){if(s.length>0){const i=s.join(`
|
|
274
|
+
`).trim();i&&e.push({heading:n,content:i})}n=r[1],s=[]}else s.push(a)}if(s.length>0){const a=s.join(`
|
|
275
|
+
`).trim();a&&e.push({heading:n,content:a})}return e}function zs(t,o,e){const n=Be(t,o);if(!Es(e))return{knowledgeBlock:`<knowledge sources="${t.sources.map(f=>`${f.name} (${f.type}, ${f.totalTokens} tokens, ${f.indexedNodes} nodes)`).join(", ")}">
|
|
276
|
+
${t.context}
|
|
277
|
+
</knowledge>`,provenance:n};const s=Ws(t,o);if(s.length===0)return{knowledgeBlock:`<knowledge sources="${t.sources.map(f=>`${f.name} (${f.type}, ${f.totalTokens} tokens, ${f.indexedNodes} nodes)`).join(", ")}">
|
|
278
|
+
${t.context}
|
|
279
|
+
</knowledge>`,provenance:n};const a=Fs(s),r=Ds(a),i=Ps(s,s),c=i.supporting.map(p=>He(p.content,p.source,p.section,p.type,p.depth,p.method)),l=i.contrasting.map(p=>He(p.content,p.source,p.section,p.type,p.depth,p.method));let d="";if(c.length>0&&(d+=`<supporting>
|
|
280
|
+
${c.join(`
|
|
281
|
+
|
|
282
|
+
`)}
|
|
283
|
+
</supporting>`),l.length>0&&(d&&(d+=`
|
|
284
|
+
|
|
285
|
+
`),d+=`<contrasting>
|
|
286
|
+
${l.join(`
|
|
287
|
+
|
|
288
|
+
`)}
|
|
289
|
+
</contrasting>`),r.length>0){d&&(d+=`
|
|
290
|
+
|
|
291
|
+
`),d+=`<conflicts_resolved>
|
|
292
|
+
`;for(const p of r)d+=`Conflict: ${p.conflictingChunks.map(g=>g.provenance.source).join(" vs ")}
|
|
293
|
+
`,d+=`Resolution: ${p.resolution.reason}
|
|
294
|
+
|
|
295
|
+
`;d+="</conflicts_resolved>"}return d||(d=t.context),{knowledgeBlock:`<knowledge sources="${t.sources.map(p=>`${p.name} (${p.type}, ${p.totalTokens} tokens, ${p.indexedNodes} nodes)`).join(", ")}">
|
|
296
|
+
${d}
|
|
297
|
+
</knowledge>`,provenance:n}}function Ys(t){const o=t.filter(a=>a.enabled);if(o.length===0)return"";const e={},n=["ground-truth","signal","evidence","framework","hypothesis","guideline"];for(const a of o)e[a.knowledgeType]||(e[a.knowledgeType]=[]),e[a.knowledgeType].push(a);const s=[];for(const a of n){const r=e[a];if(!r?.length)continue;const i=We[a],c=r.map(l=>{const d=Te[l.depth];return`- ${l.name} (${d.label}, ~${Math.round(l.baseTokens*d.pct).toLocaleString()} tokens) [${l.path}]`});s.push(`[${i.label.toUpperCase()}] ${i.instruction}
|
|
298
|
+
${c.join(`
|
|
299
|
+
`)}`)}return`<knowledge>
|
|
300
|
+
${s.join(`
|
|
301
|
+
|
|
302
|
+
`)}
|
|
303
|
+
</knowledge>`}async function Se(t,o,e){const n=await fetch(`${E}/llm/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerId:o,model:e,messages:[{role:"system",content:"You are a context navigation agent. Respond with ONLY a JSON array, no markdown, no explanation."},{role:"user",content:t}]}),signal:AbortSignal.timeout(3e4)});if(!n.ok)throw new Error(`Navigation LLM call failed: ${n.status}`);const a=(await n.text()).split(`
|
|
304
|
+
`).filter(i=>i.startsWith("data: ")).map(i=>i.slice(6)).filter(i=>i!=="[DONE]");let r="";for(const i of a)try{const l=JSON.parse(i).choices?.[0]?.delta?.content;l&&(r+=l)}catch{}return r}async function Vs(t,o,e,n,s){const a=D.getState(),r=Date.now();try{const i=t.join(". "),c=Math.floor(n.totalBudget*.2),l=new Set(e.map(f=>f.nodeId)),d=o.map(Ve),m=Je(d,{task:i,tokenBudget:c}),u=await Se(m,n.providerId,n.model),g=xe(u).filter(f=>!l.has(f.nodeId));return a.addEvent(s,{kind:"llm_call",model:n.model,durationMs:Date.now()-r,toolResult:`Gap navigation selected ${g.length} new branches for ${t.length} gaps`}),g}catch(i){return a.addEvent(s,{kind:"error",errorMessage:`Gap navigation failed: ${i instanceof Error?i.message:"Unknown"}`,durationMs:Date.now()-r}),[]}}async function Js(t,o,e,n,s){const a=ge.getState(),r=D.getState(),{userMessage:i,navigationMode:c="tree-aware",providerId:l,model:d}=n,m=t.filter(k=>k.enabled);let u=e,p=null,g=null,f;const y=[];for(const k of o)if(k.content){const h=`content://${k.contentSourceId||k.sourceId}`,w=Q(h,k.content),v=pe(de(w,0).filtered);v.trim()&&y.push({name:k.name,type:"markdown",content:v,sourceType:k.knowledgeType})}else if(k.path){const h=a.getIndex(k.path);if(h){const w=pe(de(h,0).filtered);w.trim()&&y.push({name:k.name,type:"markdown",content:w,sourceType:k.knowledgeType})}}if(c==="tree-aware"&&o.length>0){const k=m.reduce((w,v)=>w+v.baseTokens,0),h=[];for(const w of o)if(w.content){if(w.content.trim().length===0)continue;const v=`content://${w.contentSourceId||w.sourceId}`,C=Q(v,w.content);h.push({treeIndex:C,knowledgeType:w.knowledgeType})}else if(w.path){const v=a.getIndex(w.path);v&&h.push({treeIndex:v,knowledgeType:w.knowledgeType})}if(h.length>0){const w={sources:h.map(v=>({name:v.treeIndex.source,type:v.treeIndex.sourceType,rawTokens:v.treeIndex.totalTokens,included:!0,reason:"Valid indexed source"}))};oe(s,"source_assembly",w);try{if(r.addEvent(s,{kind:"retrieval",sourceName:"tree-aware-retrieval",query:i,resultCount:h.length,durationMs:0}),f=await Os(i,h,k),r.addEvent(s,{kind:"retrieval",sourceName:"tree-aware-retrieval",query:i,resultCount:f.chunks.length,durationMs:f.retrievalMs}),f.chunks.length>0){const v=f.chunks.map(b=>He(b.content,b.source,b.section,b.knowledgeType,b.depth.toString(),"tree-aware")),C=h.map(b=>`${b.treeIndex.source} (${b.knowledgeType}, ${b.treeIndex.totalTokens} tokens, ${b.treeIndex.nodeCount} nodes)`).join(", "),M=`Query type: ${f.queryType}, Diversity: ${f.diversityScore.toFixed(2)}, Total chunks: ${f.totalChunks}`;u=`<knowledge sources="${C}" method="tree-aware" metadata="${M}">
|
|
305
|
+
${v.join(`
|
|
306
|
+
|
|
307
|
+
`)}
|
|
308
|
+
</knowledge>`;const T={query:i,queryType:f.queryType,chunks:f.chunks.map(b=>({source:b.source,section:b.section,relevanceScore:b.relevanceScore||0,inclusionReason:b.inclusionReason||"direct"})),diversityScore:f.diversityScore,totalChunks:f.totalChunks,selectedChunks:f.chunks.length};oe(s,"retrieval",T,f.retrievalMs);const P=v.join(`
|
|
309
|
+
|
|
310
|
+
`),_=I(P);p={context:P,tokens:_,utilization:k>0?_/k:0,sources:h.map(b=>({name:b.treeIndex.source,type:b.treeIndex.sourceType,totalTokens:b.treeIndex.totalTokens,indexedNodes:b.treeIndex.nodeCount})),navigation:{selections:[]},compression:{originalTokens:f.totalChunks>0?h.reduce((b,$)=>b+$.treeIndex.totalTokens,0):0,compressedTokens:_,ratio:k>0?_/Math.max(1,h.reduce((b,$)=>b+$.treeIndex.totalTokens,0)):1,removals:{duplicates:0,filler:0,codeComments:0}},indexes:h.map(b=>b.treeIndex),timing:{indexMs:0,navigationMs:0,compressionMs:f.retrievalMs,totalMs:f.retrievalMs}},p&&(g=Be(p,o)),f.collapseWarning&&r.addEvent(s,{kind:"error",errorMessage:`Low diversity score (${f.diversityScore.toFixed(2)}) - chunks may be too similar`,durationMs:0})}}catch(v){const C=v instanceof Error?v.message:"Unknown error";r.addEvent(s,{kind:"error",errorMessage:`Tree-aware retrieval failed: ${C} — falling back to pipeline`,durationMs:0})}}}if(y.length>0&&(c!=="tree-aware"||!u)){const k=m.reduce((S,O)=>S+O.baseTokens,0),h=new Map;for(const S of o)h.set(S.name,S.depth);const w=y.map(S=>({name:S.name,knowledgeType:S.sourceType??"signal",rawTokens:I(S.content||""),depthMultiplier:rs[h.get(S.name)??2]??1})),v=is(w,k),C=new Map;for(const S of v)C.set(S.name,S.allocatedTokens);const M={totalBudget:k,allocations:v.map(S=>({source:S.name,allocatedTokens:S.allocatedTokens,usedTokens:Math.min(S.allocatedTokens,I(y.find(O=>O.name===S.name)?.content||"")),percentage:S.weight*100,cappedBySize:S.cappedBySize,priority:S.knowledgeType==="ground-truth"?0:S.knowledgeType==="signal"?1:2}))};oe(s,"budget_allocation",M);for(const S of y){const L=(C.get(S.name)??k)*4;S.content&&S.content.length>L&&(S.content=S.content.slice(0,L))}const T=c==="agent-driven",P=vs({task:i,sources:y,tokenBudget:k});r.addEvent(s,{kind:"retrieval",sourceName:"pipeline:index",query:i,resultCount:P.indexes.length,durationMs:P.indexMs});let _="",b=m.filter(S=>S.path&&a.getIndex(S.path)!=null||S.content).map(S=>({nodeId:S.name,depth:S.depth,priority:S.knowledgeType==="ground-truth"?0:S.knowledgeType==="signal"?1:2}));if(T&&P.indexes.length>0){const S=Date.now();try{let O=i;if(us(i))try{const N=ps(i),W=await Se(N,l,d);W.length>20&&(O=W,r.addEvent(s,{kind:"llm_call",model:d,durationMs:Date.now()-S,toolResult:`HyDE generated ${W.length} chars for navigation`}))}catch(N){r.addEvent(s,{kind:"error",errorMessage:`HyDE failed: ${N instanceof Error?N.message:"Unknown"} — using original query`,durationMs:0})}const L=P.indexes.map(Ve),Z=Je(L,{task:O,tokenBudget:k});_=await Se(Z,l,d);const H=xe(_);H.length>0&&(b=H),r.addEvent(s,{kind:"llm_call",model:d,durationMs:Date.now()-S,toolResult:`Agent selected ${H.length} branches`})}catch(O){r.addEvent(s,{kind:"error",errorMessage:`Navigation failed: ${O instanceof Error?O.message:"Unknown"} — using manual depths`,durationMs:Date.now()-S})}}p=ht(P.indexes,_,{task:i,sources:y,tokenBudget:k,manualSelections:_?void 0:b,compression:{enabled:!0,aggressiveness:.5}},P.indexMs),r.addEvent(s,{kind:"retrieval",sourceName:"pipeline:compress",resultCount:p.sources.length,durationMs:p.timing.compressionMs});const $=xe(_);if(T&&$.length>0&&p.context.trim())try{const S=ls(i,p.context),O=await Se(S,l,d),L=ds(O);if(L.length>0){const Z=await Vs(L,P.indexes,$,{providerId:l,model:d,totalBudget:k},s);if(Z.length>0){const H=[...$,...Z],N=JSON.stringify(H);p=ht(P.indexes,N,{task:i,sources:y,tokenBudget:k,manualSelections:void 0,compression:{enabled:!0,aggressiveness:.5}},P.indexMs),r.addEvent(s,{kind:"retrieval",sourceName:"pipeline:re-navigation",resultCount:Z.length,durationMs:0})}}}catch(S){r.addEvent(s,{kind:"error",errorMessage:`Corrective re-navigation failed: ${S instanceof Error?S.message:"Unknown"}`,durationMs:0})}if(p.context.trim()){const S=zs(p,o,i);u=S.knowledgeBlock,g=S.provenance,oe(s,"contradiction_check",{contradictionsFound:0,conflicts:[],annotations:["Contrastive retrieval completed"]})}else p&&(g=Be(p,o))}if(u||(u=Ys(t)),g){r.addEvent(s,{kind:"provenance",provenanceSources:g.sources.map(h=>({path:h.path,type:h.type,sections:h.sections,depth:h.depth,chunkCount:h.chunkCount||0})),provenanceDerivations:g.derivations,resultCount:g.sources.length});const k={sources:g.sources.map(h=>({path:h.path,type:h.type,transformations:[{method:h.method,input:"source_content",output:"processed_chunks"}]})),derivationChain:g.derivations};oe(s,"provenance",k)}return{knowledgeBlock:u,pipelineResult:p,provenance:g,retrievalResult:f}}const Ne=new Map;async function Qs(t){const{url:o,ref:e,subdir:n}=t;if(!o||typeof o!="string")throw new Error("GitHub URL is required");try{const s={url:o,persist:!0};e&&typeof e=="string"&&(s.ref=e),n&&typeof n=="string"&&(s.subdir=n);const a=await fetch(`${E}/repo/index-github`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!a.ok){const p=await a.text();throw new Error(`Failed to index GitHub repo: ${a.status} ${p}`)}const r=await a.json();if(r.status!=="ok"||!r.data)throw new Error(r.error||"Indexing failed");const{data:i}=r,c=i.totalTokens??i.scan?.totalTokens??5e3,l=i.scan,d=Array.isArray(l?.stack)?l.stack:l?.stack&&typeof l.stack=="object"?Object.values(l.stack).filter(p=>typeof p=="string"&&p!=="unknown"&&p!=="none"):[],m=F.getState().addChannel;let u=0;for(const p of i.files){const g=`${i.outputDir}/${p}`,f=p.includes("overview"),y={sourceId:`repo-${p}-${Date.now()}`,name:p.replace(".compressed.md","").replace(".md","").replace(/^\d+-/,""),path:g,category:"knowledge",knowledgeType:"ground-truth",depth:f?1:2,baseTokens:Math.floor(c/i.files.length),repoMeta:{name:i.name||kt(o),totalFiles:l?.totalFiles??i.files.length,stack:d,features:l?.features?.map(k=>k.name)??[],baseUrl:l?.baseUrl}};f&&i.overviewMarkdown&&(y.content=i.overviewMarkdown),m(y),u++}return`Successfully indexed GitHub repository "${kt(o)}". Added ${u} knowledge sources:
|
|
311
|
+
`+i.files.map(p=>`- ${p.replace(".compressed.md","").replace(".md","").replace(/^\d+-/,"")}`).join(`
|
|
312
|
+
`)+`
|
|
313
|
+
|
|
314
|
+
Repository stats: ${l?.totalFiles??i.files.length} files, ${d.length} tech stack items, ${c} tokens`}catch(s){throw new Error(`GitHub indexing failed: ${s instanceof Error?s.message:String(s)}`)}}async function Zs(t){const{path:o}=t;if(!o||typeof o!="string")throw new Error("Local repository path is required");try{const e=await fetch(`${E}/repo/index`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:o})});if(!e.ok){const i=await e.text();throw new Error(`Failed to index local repo: ${e.status} ${i}`)}const n=await e.json();if(n.status!=="ok"||!n.data)throw new Error(n.error||"Indexing failed");const{data:s}=n,a=F.getState().addChannel;let r=0;for(const i of s.files){const c=`${s.outputDir}/${i}`,l={sourceId:`local-repo-${i}-${Date.now()}`,name:i.replace(".compressed.md","").replace(".md","").replace(/^\d+-/,""),path:c,category:"knowledge",knowledgeType:"ground-truth",depth:2,baseTokens:Math.floor((s.totalTokens??5e3)/s.files.length)};a(l),r++}return`Successfully indexed local repository at "${o}". Added ${r} knowledge sources:
|
|
315
|
+
`+s.files.map(i=>`- ${i.replace(".compressed.md","").replace(".md","").replace(/^\d+-/,"")}`).join(`
|
|
316
|
+
`)}catch(e){throw new Error(`Local repository indexing failed: ${e instanceof Error?e.message:String(e)}`)}}async function Xs(t){const{path:o}=t;if(!o||typeof o!="string")throw new Error("Directory path is required");try{const e=await fetch(`${E}/repo/scan`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:o})});if(!e.ok){const i=await e.text();throw new Error(`Failed to scan directory: ${e.status} ${i}`)}const n=await e.json();if(n.status!=="ok"||!n.data)throw new Error(n.error||"Scan failed");const{data:s}=n,a=Array.isArray(s.stack)?s.stack:Object.values(s.stack).filter(i=>typeof i=="string"&&i!=="unknown"&&i!=="none");let r=`Directory scan results for "${o}":
|
|
317
|
+
|
|
318
|
+
`;return r+=`📁 Files: ${s.totalFiles}
|
|
319
|
+
`,r+=`📊 Estimated tokens: ${s.totalTokens}
|
|
320
|
+
|
|
321
|
+
`,a.length>0&&(r+=`🛠️ Tech stack detected:
|
|
322
|
+
${a.map(i=>`- ${i}`).join(`
|
|
323
|
+
`)}
|
|
324
|
+
|
|
325
|
+
`),s.features.length>0&&(r+=`✨ Features found:
|
|
326
|
+
${s.features.map(i=>`- ${i.name}${i.description?": "+i.description:""}`).join(`
|
|
327
|
+
`)}
|
|
328
|
+
|
|
329
|
+
`),r+="Use `index_local_repo` to add this as a knowledge source.",r}catch(e){throw new Error(`Directory scanning failed: ${e instanceof Error?e.message:String(e)}`)}}async function ea(t){const{path:o}=t;if(!o||typeof o!="string")throw new Error("File path is required");try{const e=await fetch(`${E}/knowledge/index`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:o})});if(!e.ok){const i=await e.text();throw new Error(`Failed to index file: ${e.status} ${i}`)}const n=await e.json();if(n.status!=="ok"||!n.data)throw new Error(n.error||"Indexing failed");const{data:s}=n,a=F.getState().addChannel,r={sourceId:`file-${Date.now()}`,name:s.name,path:o,category:"knowledge",knowledgeType:"evidence",depth:1,baseTokens:s.tokens};return a(r),`Successfully indexed "${s.name}" (${s.tokens} tokens) as a knowledge source.`}catch(e){throw new Error(`File indexing failed: ${e instanceof Error?e.message:String(e)}`)}}async function ta(t){const{query:o,limit:e=5}=t;if(!o||typeof o!="string")throw new Error("Search query is required");try{const n=F.getState().channels.filter(g=>g.enabled&&(g.content||g.path));if(n.length===0)return"No knowledge sources indexed yet. Use `index_github_repo` or `index_knowledge_file` to add sources first.";const s=[];for(const g of n){let f=g.content;if(!f&&g.path)if(Ne.has(g.path))f=Ne.get(g.path);else try{const y=await fetch(`${E}/knowledge/read?path=${encodeURIComponent(g.path)}`);y.ok&&(f=await y.text(),Ne.set(g.path,f))}catch(y){console.error(`Failed to fetch content for ${g.path}:`,y)}if(f){const y=f.split(/(?=^#{1,3}\s)/m).filter(k=>k.trim());for(const k of y)k.trim().length>20&&s.push({text:k.trim().slice(0,1024),source:g.name})}}if(s.length===0)return"Knowledge sources exist but have no inline content to search. Try reading specific files with `read_file`.";const a=[o,...s.map(g=>g.text)],r=await fetch(`${E}/embeddings/embed`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({texts:a})});if(!r.ok)throw new Error(`Embedding service error: ${r.status}`);const{embeddings:i}=await r.json(),c=i[0],l=i.slice(1),d=(g,f)=>{let y=0,k=0,h=0;for(let w=0;w<g.length;w++)y+=g[w]*f[w],k+=g[w]**2,h+=f[w]**2;return y/(Math.sqrt(k)*Math.sqrt(h)||1)},m=s.map((g,f)=>({...g,score:d(c,l[f])}));m.sort((g,f)=>f.score-g.score);const u=m.slice(0,Number(e)||5);let p=`Found ${u.length} relevant chunks for "${o}":
|
|
330
|
+
|
|
331
|
+
`;for(const g of u)p+=`**[${g.source}]** (relevance: ${(g.score*100).toFixed(0)}%)
|
|
332
|
+
`,p+=g.text.slice(0,500)+(g.text.length>500?"...":"")+`
|
|
333
|
+
|
|
334
|
+
---
|
|
335
|
+
|
|
336
|
+
`;return p}catch(n){throw new Error(`Knowledge search failed: ${n instanceof Error?n.message:String(n)}`)}}async function na(t){const{path:o}=t;if(!o||typeof o!="string")throw new Error("File path is required");try{const e=await fetch(`${E}/knowledge/read?path=${encodeURIComponent(o)}`);if(!e.ok){const s=await e.text();throw new Error(`Failed to read file: ${e.status} ${s}`)}const n=await e.text();return n.length>8e3?n.substring(0,8e3)+`
|
|
337
|
+
|
|
338
|
+
[Content truncated - file is very large]`:n}catch(e){throw new Error(`File reading failed: ${e instanceof Error?e.message:String(e)}`)}}function kt(t){const o=t.match(/github\.com\/([^\/]+\/[^\/]+)/);return o?o[1]:t}function Qt(){return[{name:"index_github_repo",description:"Clone and index a GitHub repository to make its code available as knowledge context. Returns an overview and feature documentation.",inputSchema:{type:"object",properties:{url:{type:"string",description:"GitHub repository URL"},ref:{type:"string",description:"Git reference (branch, tag, or commit) to clone (optional)"},subdir:{type:"string",description:"Subdirectory to focus on (optional)"}},required:["url"]},execute:Qs},{name:"index_local_repo",description:"Index a local repository to make its code available as knowledge context.",inputSchema:{type:"object",properties:{path:{type:"string",description:"Local repository path"}},required:["path"]},execute:Zs},{name:"scan_directory",description:"Scan a local directory to discover its structure, tech stack, and features.",inputSchema:{type:"object",properties:{path:{type:"string",description:"Directory path to scan"}},required:["path"]},execute:Xs},{name:"index_knowledge_file",description:"Index a markdown or text file to make it available as knowledge context.",inputSchema:{type:"object",properties:{path:{type:"string",description:"Path to the markdown or text file"}},required:["path"]},execute:ea},{name:"search_knowledge",description:"Semantically search across all indexed knowledge sources using embeddings.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query text"},limit:{type:"number",description:"Maximum number of results to return (default: 10)"}},required:["query"]},execute:ta},{name:"read_file",description:"Read the content of a file from an allowed directory.",inputSchema:{type:"object",properties:{path:{type:"string",description:"File path to read"}},required:["path"]},execute:na}]}function Zt(){const t=[],o=he.getState();for(const n of o.servers)if(n.status==="connected")for(const s of n.tools)t.push({name:s.name,description:s.description||"No description",inputSchema:s.inputSchema||{type:"object",properties:{}},origin:{kind:"mcp",serverId:n.id,serverName:n.name}});for(const n of Qt())t.push({name:n.name,description:n.description,inputSchema:n.inputSchema,origin:{kind:"builtin",serverId:"modular-studio",serverName:"Modular Studio"}});const e=new Map;for(const n of t)e.set(n.name,(e.get(n.name)??0)+1);return t.map(n=>(e.get(n.name)??0)>1?{...n,name:`${n.origin.serverId}__${n.name}`}:n)}function Xt(t){return t==="anthropic"||t==="openai"||t==="openrouter"}function oa(t){return t.map(o=>({name:o.name,description:o.description,input_schema:o.inputSchema}))}function sa(t){return t.map(o=>({type:"function",function:{name:o.name,description:o.description,parameters:o.inputSchema}}))}function aa(t,o){const e=t.find(s=>s.name===o);if(e)return e.origin;const n=o.includes("__")?o.split("__").slice(1).join("__"):null;return n?t.find(s=>s.name===n)?.origin??null:null}async function ra(t,o,e){const n=aa(e,t);if(!n)return{result:"",serverId:"",error:`Tool "${t}" not found in registry`};if(n.kind==="builtin"){const r=Qt().find(i=>i.name===t);if(!r)return{result:"",serverId:n.serverId,error:`Built-in tool "${t}" not found`};try{return{result:await r.execute(o),serverId:n.serverId}}catch(i){const c=i instanceof Error?i.message:String(i);return{result:"",serverId:n.serverId,error:c}}}const s=he.getState();try{const a=await s.callTool(n.serverId,t,o);if(a==null)return t==="get_file_contents"?{result:"No content returned. This path may be a directory - use list_directory first, or check the file tree in your context.",serverId:n.serverId}:{result:"Tool returned no result. Check arguments.",serverId:n.serverId};let r;return a&&typeof a=="object"&&"content"in a?(r=a.content.filter(c=>c.type==="text"&&c.text).map(c=>c.text).join(`
|
|
339
|
+
`),r||(r=JSON.stringify(a))):r=typeof a=="string"?a:JSON.stringify(a),{result:r,serverId:n.serverId}}catch(a){const r=a instanceof Error?a.message:String(a);return{result:"",serverId:n.serverId,error:r}}}async function ia(t,o,e,n){const r=U.getState().providers.find(d=>d.id===t)?.type??"openai",i=r==="anthropic"?oa(n):sa(n),c=await fetch(`${E}/llm/chat-tools`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:t,model:o,messages:e,tools:i})});if(!c.ok){const d=await c.text().catch(()=>"");throw new Error(`LLM tool call failed (${c.status}): ${d||c.statusText}`)}const l=await c.json();return r==="anthropic"?ca(l):la(l)}function ca(t){const o=t.content??[],e=t.usage,n=t.stop_reason??"end_turn",s=o.filter(r=>r.type==="text").map(r=>r.text??""),a=o.filter(r=>r.type==="tool_use");return{content:s.join(""),toolCalls:a.map(r=>({id:r.id??`tc-${Date.now()}`,name:r.name??"",args:r.input??{}})),inputTokens:e?.input_tokens??0,outputTokens:e?.output_tokens??0,rawAssistantMessage:{role:"assistant",content:o},stopReason:n}}function la(t){const o=t.choices??[],e=t.usage,n=o[0]?.message,s=o[0]?.finish_reason??"stop";return{content:n?.content??"",toolCalls:(n?.tool_calls??[]).map(a=>{let r={};try{r=JSON.parse(a.function.arguments)}catch{r={_raw:a.function.arguments,_parseError:!0}}return{id:a.id,name:a.function.name,args:r}}),inputTokens:e?.prompt_tokens??0,outputTokens:e?.completion_tokens??0,rawAssistantMessage:{role:"assistant",...n},stopReason:s}}function da(t,o){return t==="anthropic"?[{role:"user",content:o.map(e=>({type:"tool_result",tool_use_id:e.id,content:e.error?`Error: ${e.error}`:e.result,...e.error?{is_error:!0}:{}}))}]:o.map(e=>({role:"tool",tool_call_id:e.id,content:e.error?`Error: ${e.error}`:e.result}))}async function pa(t){const{providerId:o,model:e,messages:n,traceId:s,maxTurns:a=10,callbacks:r}=t,i=D.getState(),d=U.getState().providers.find(y=>y.id===o)?.type??"openai",m=Zt(),u=[];let p=0,g=0;const f=[...n];if(m.length===0||!Xt(d)){r.onError(new Error("No tools available or provider does not support tool calling"));return}try{for(let y=0;y<a;y++){const k=Date.now(),h=await ia(o,e,f,m);if(p+=h.inputTokens,g+=h.outputTokens,i.addEvent(s,{kind:"llm_call",model:e,inputTokens:h.inputTokens,outputTokens:h.outputTokens,durationMs:Date.now()-k}),h.content&&r.onChunk(h.content),h.toolCalls.length===0){r.onDone({turns:y+1,toolCalls:u,totalInputTokens:p,totalOutputTokens:g});return}f.push(h.rawAssistantMessage);const w=[];for(const C of h.toolCalls){r.onToolCallStart(C.name,C.args);const M=Date.now(),T=await ra(C.name,C.args,m),P=Date.now()-M,_={id:C.id,name:C.name,args:C.args,result:T.result,error:T.error,durationMs:P,serverId:T.serverId};w.push(_),u.push(_),i.addEvent(s,{kind:"tool_call",toolName:C.name,toolArgs:C.args,toolResult:(T.error||T.result).slice(0,500),toolError:T.error,mcpServerId:T.serverId,durationMs:P}),r.onToolCallEnd(_)}const v=da(d,w);f.push(...v)}r.onDone({turns:a,toolCalls:u,totalInputTokens:p,totalOutputTokens:g})}catch(y){r.onError(y instanceof Error?y:new Error(String(y)))}}function ua(t,o){return o!=="anthropic"?t:t.map(e=>e.role!=="system"?e:{...e,content:Mn(e.content)})}async function ma(t){const{providerId:o,model:e,messages:n,userMessage:s,systemPrompt:a,traceId:r,onChunk:i}=t,c=D.getState(),l=Zt(),u=U.getState().providers.find(h=>h.id===o)?.type??"openai",p=ua(n,u),g=l.length>0&&Xt(u)&&o!=="claude-agent-sdk";let f=[],y=0,k="";if(g){const h=Date.now();c.addEvent(r,{kind:"llm_call",model:e,inputTokens:p.reduce((w,v)=>w+I(typeof v.content=="string"?v.content:JSON.stringify(v.content)),0)}),await new Promise((w,v)=>{pa({providerId:o,model:e,messages:p,traceId:r,maxTurns:10,callbacks:{onChunk:C=>{k+=C,i(C)},onToolCallStart:(C,M)=>{i(`
|
|
340
|
+
|
|
341
|
+
🔧 Calling **${C}**...
|
|
342
|
+
`)},onToolCallEnd:C=>{C.error?i(`❌ ${C.name} failed: ${C.error}
|
|
343
|
+
`):i(`✅ ${C.name} (${C.durationMs}ms)
|
|
344
|
+
`)},onDone:C=>{f=C.toolCalls,y=C.turns,c.addEvent(r,{kind:"llm_call",model:e,outputTokens:C.totalOutputTokens,durationMs:Date.now()-h}),w()},onError:C=>v(C)}})})}else{const h=Date.now();c.addEvent(r,{kind:"llm_call",model:e,inputTokens:p.reduce((v,C)=>v+I(typeof C.content=="string"?C.content:JSON.stringify(C.content)),0)});let w="";await new Promise((v,C)=>{const M={onChunk:T=>{w+=T,k+=T,i(T)},onDone:()=>{c.addEvent(r,{kind:"llm_call",model:e,outputTokens:I(w),durationMs:Date.now()-h}),v()},onError:T=>C(T)};o==="claude-agent-sdk"?xt({prompt:s,model:e,systemPrompt:a,...M}):Ct({providerId:o,model:e,messages:p,...M})})}return{fullResponse:k,toolCallResults:f,toolTurns:y}}async function wt(t){const{fullResponse:o,userMessage:e,agentId:n,sandboxRunId:s,traceId:a,activeChannels:r,memoryStats:i}=t,c=D.getState(),l=Y.getState();let d=i;if(l.longTerm.enabled&&o){const p=Do({userMessage:e,assistantResponse:o,agentId:n,traceId:a,sandboxRunId:s});d&&(d={...d,writtenFacts:p.stored.length,writeMs:p.durationMs,domains:p.stored.length>0?[...new Set([...d.domains,...p.stored.map(g=>g.domain)])]:d.domains})}c.endTrace(a);const m=[],u=ge.getState();for(const p of r){let g=function(h){h.depth>0&&h.depth<=2&&y.push({nodeId:h.nodeId,title:h.title,depth:h.depth,tokens:h.totalTokens});for(const w of h.children)g(w)},f=p.path?u.getIndex(p.path):null;if(!f&&p.content){const h=`content://${p.contentSourceId||p.sourceId}`;f=Q(h,p.content)}if(!f)continue;const y=[];g(f.root);const k=de(f,p.depth);m.push({name:p.name,path:p.path||`content://${p.contentSourceId||p.sourceId}`,nodeCount:f.nodeCount,totalTokens:f.totalTokens,filteredTokens:k.totalTokens,depth:p.depth,knowledgeType:p.knowledgeType,headings:y})}return{heatmap:m,memoryStats:d}}const en="modular-lessons-v2";function ga(){try{const t=localStorage.getItem(en);return t?JSON.parse(t):[]}catch{return[]}}function X(t){try{localStorage.setItem(en,JSON.stringify(t))}catch{}}function ha(){return`lesson-${Date.now()}-${Math.random().toString(36).slice(2,6)}`}const tn=j((t,o)=>({lessons:ga(),addLesson:e=>{const n={...e,id:ha(),status:"pending",createdAt:Date.now(),appliedCount:0};t(s=>{const a=[...s.lessons,n];return X(a),{lessons:a}})},approveLesson:e=>t(n=>{const s=n.lessons.map(a=>a.id===e?{...a,status:"approved"}:a);return X(s),{lessons:s}}),rejectLesson:e=>t(n=>{const s=n.lessons.map(a=>a.id===e?{...a,status:"rejected"}:a);return X(s),{lessons:s}}),removeLesson:e=>t(n=>{const s=n.lessons.filter(a=>a.id!==e);return X(s),{lessons:s}}),updateLesson:(e,n)=>t(s=>{const a=s.lessons.map(r=>r.id===e?{...r,rule:n}:r);return X(a),{lessons:a}}),incrementApplied:e=>t(n=>{const s=n.lessons.map(a=>a.id===e?{...a,appliedCount:a.appliedCount+1}:a);return X(s),{lessons:s}}),getPendingLessons:e=>o().lessons.filter(n=>n.agentId===e&&n.status==="pending"),getApprovedLessons:e=>o().lessons.filter(n=>n.agentId===e&&n.status==="approved")}));function fa(t){let o=2166136261;for(let e=0;e<t.length;e++)o^=t.charCodeAt(e),o=Math.imul(o,16777619)>>>0;return o.toString(16).padStart(8,"0")}async function ya(t,o,e,n,s){try{const a=await fetch("/api/cache/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:t,agentId:o,model:e,systemPromptHash:n,ttl:s})});if(!a.ok)return null;const r=await a.json();return r.hit&&r.cached?r.cached:null}catch{return null}}async function ka(t,o,e,n,s,a){try{await fetch("/api/cache/store",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:t,response:o,agentId:e,model:n,systemPromptHash:s,ttl:a})})}catch{}}function Da(){const{selectedModel:t,agentConfig:o}=F.getState(),{providers:e}=U.getState(),n=t.indexOf("::"),s=n>0,a=s?t.slice(0,n):"",r=s?t.slice(n+2):t||o.model,{selectedProviderId:i}=U.getState(),c=a||i,l=e.find(u=>u.id===c),d=Array.isArray(l?.models)?l.models:[];if(!l||l.status!=="connected"&&l.status!=="configured"||d.length===0)return{providerId:"",model:"",error:"No provider/model configured. Open Settings → Providers, connect one provider, refresh models, then retry."};const m=d.some(u=>u.id===r);return{providerId:l.id,model:m?r:d[0].id}}async function Na(t){const{userMessage:o,channels:e,history:n,providerId:s,model:a,onChunk:r,onDone:i,onError:c}=t,l=D.getState(),m=Bt.getState().currentVersion||"0.0.0",u=l.startTrace(`chat-${Date.now()}`,m);try{let p=gt();const g=e.filter(A=>A.enabled),{frameworkBlock:f,frameworkSummary:y,regularChannels:k,residualKnowledgeBlock:h}=g.length>0?await os(g,u):{frameworkBlock:"",frameworkSummary:void 0,regularChannels:[],residualKnowledgeBlock:""};let{knowledgeBlock:w,pipelineResult:v,provenance:C,retrievalResult:M}=g.length>0?await Js(e,k,h,{userMessage:o,navigationMode:t.navigationMode,providerId:s,model:a},u):{knowledgeBlock:"",pipelineResult:null,provenance:null,retrievalResult:void 0};const T=(t.connectors||[]).filter(A=>A.enabled&&A.direction!=="write");if(T.length>0){const q=`<connectors>
|
|
345
|
+
Available data connectors (use via MCP tools):
|
|
346
|
+
${T.map(V=>{const Pe=V.hint?` (scope: ${V.hint})`:"";return`- ${V.name} [${V.service}] — ${V.direction}${Pe}`}).join(`
|
|
347
|
+
`)}
|
|
348
|
+
</connectors>`;w=w?`${w}
|
|
349
|
+
|
|
350
|
+
${q}`:q}const P=t.agentId?tn.getState().getApprovedLessons(t.agentId):[];let _="";P.length>0&&(_=`<lessons>
|
|
351
|
+
${P.map(q=>`- [${q.category}] ${q.rule}`).join(`
|
|
352
|
+
`)}
|
|
353
|
+
</lessons>`);const b=Y.getState();let $="",S;if(b.longTerm.enabled){b.sandbox.isolation==="reset_each_run"&&Lo();const A=await Oo({userMessage:o,agentId:t.agentId,traceId:u,sandboxRunId:t.sandboxRunId});A.contextBlock&&($=A.contextBlock),S={recalledFacts:A.facts.length,writtenFacts:0,recallMs:A.durationMs,writeMs:0,recallTokens:A.tokenEstimate,domains:[...new Set(A.facts.map(q=>q.domain))]}}C&&(p=gt(C));const O=to(e,ge.getState().getIndex),L=e.some(A=>A.enabled&&A.repoMeta),H=U.getState().providers.find(A=>A.id===s)?.type??"openai";P.length>0&&l.addEvent(u,{kind:"lesson_applied",memoryFactCount:P.length});const N=no({frame:p,orientationBlock:O,hasRepos:L,knowledgeFormatGuide:zo(),frameworkBlock:f,lessonsBlock:_||void 0,memoryBlock:$,knowledgeBlock:w,providerType:H}),W=I(N),sn=Ge(H),an=In(N,sn);l.addEvent(u,{kind:"cache",cacheMetrics:an});const rn=[{role:"system",content:N},...n.filter(A=>A.content.trim()!=="").map(A=>({role:A.role,content:A.content})),{role:"user",content:o}],{responseCache:fe}=Y.getState(),Qe=fa(N),ye=t.agentId??"default";if(fe.enabled){const A=await ya(o,ye,a,Qe,fe.ttlSeconds);if(A){const q=A.response.length/4*15e-6;l.addEvent(u,{kind:"response_cache_hit",responseCacheHit:!0,responseCacheSavingsUsd:q,responseCacheAgentId:ye,responseCacheModel:a}),r(A.response);const{heatmap:V,memoryStats:Pe}=await wt({fullResponse:A.response,userMessage:o,agentId:t.agentId,sandboxRunId:t.sandboxRunId,traceId:u,activeChannels:g,memoryStats:S});i({traceId:u,pipeline:v,systemTokens:W,totalContextTokens:W,heatmap:V,frameworkSummary:y,memory:Pe});return}l.addEvent(u,{kind:"response_cache_miss",responseCacheHit:!1,responseCacheAgentId:ye,responseCacheModel:a})}const{fullResponse:Ae,toolCallResults:Ze,toolTurns:Xe}=await ma({providerId:s,model:a,messages:rn,userMessage:o,systemPrompt:N,traceId:u,onChunk:r});fe.enabled&&Ae&&ka(o,Ae,ye,a,Qe,fe.ttlSeconds);const{heatmap:cn,memoryStats:ln}=await wt({fullResponse:Ae,userMessage:o,agentId:t.agentId,sandboxRunId:t.sandboxRunId,traceId:u,activeChannels:g,memoryStats:S}),dn=n.filter(A=>A.role==="assistant").at(-1)?.content??"";wa(o,dn,s,a,t.agentId,u);const pn=W+n.reduce((A,q)=>A+I(q.content),0)+I(o),un=M?{queryType:M.queryType,diversityScore:M.diversityScore,collapseWarning:M.collapseWarning,totalChunks:M.totalChunks,selectedChunks:M.chunks.length,budgetUsed:M.budgetUsed,budgetTotal:M.budgetTotal,retrievalMs:M.retrievalMs,embeddingMs:M.embeddingMs,chunks:M.chunks.map(A=>({section:A.section,source:A.source,relevanceScore:A.relevanceScore||0,inclusionReason:A.inclusionReason||"unknown",knowledgeType:A.knowledgeType,tokens:I(A.content)}))}:void 0;i({traceId:u,pipeline:v,systemTokens:W,totalContextTokens:pn,heatmap:cn,frameworkSummary:y,toolCalls:Ze.length>0?Ze:void 0,toolTurns:Xe>0?Xe:void 0,memory:ln,retrieval:un})}catch(p){l.addEvent(u,{kind:"error",errorMessage:p instanceof Error?p.message:"Unknown error"}),l.endTrace(u),c(p instanceof Error?p:new Error("Unknown error"))}}async function wa(t,o,e,n,s,a){try{const r=await fetch("/api/lessons/extract",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({userMessage:t,previousAssistant:o,providerId:e,model:n,agentId:s})});if(!r.ok)return;const i=await r.json();if(!i.lesson)return;const{rule:c,category:l,agentId:d,sourceUserMessage:m,sourcePreviousAssistant:u}=i.lesson;tn.getState().addLesson({rule:c,category:l,agentId:d,sourceUserMessage:m,sourcePreviousAssistant:u}),D.getState().addEvent(a,{kind:"lesson_proposed"})}catch{}}function ba(){return`run-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}const bt={id:"",status:"idle",agents:[],sharedFacts:[],contractFacts:[]},ee=j(t=>({...bt,startRun:(o,e,n)=>t({id:ba(),teamId:e,featureSpec:n,status:"running",agents:o.map(s=>({agentId:s.agentId,name:s.name,status:"waiting",turns:0,facts:[],toolCalls:[],isAgentSdk:s.isAgentSdk})),sharedFacts:[],contractFacts:[],startedAt:Date.now(),completedAt:void 0,error:void 0}),updateAgent:(o,e)=>t(n=>({agents:n.agents.map(s=>s.agentId===o?{...s,...e}:s)})),addFact:(o,e)=>t(n=>e==="shared"?{sharedFacts:[...n.sharedFacts,o]}:e==="contract"?{contractFacts:[...n.contractFacts,o]}:{agents:n.agents.map(s=>s.agentId===e.agentId?{...s,facts:[...s.facts,o]}:s)}),setStatus:(o,e)=>t({status:o,error:e,completedAt:o==="completed"||o==="error"?Date.now():void 0}),reset:()=>t({...bt})}));async function va(t,o){const e=new TextDecoder;let n="";for(;;){const{done:s,value:a}=await t.read();if(s)break;n+=e.decode(a,{stream:!0});const r=n.split(`
|
|
354
|
+
`);n=r.pop()??"";for(const i of r){const c=i.trim();if(!c||!c.startsWith("data: "))continue;const l=c.slice(6);if(l==="[DONE]"||o(l))return}}}function La(t){const o=new AbortController;ee.getState().startRun(t.agents.map(s=>({agentId:s.agentId,name:s.name,isAgentSdk:t.isAgentSdk})),t.teamId);const n={teamId:t.teamId,systemPrompt:t.systemPrompt,task:t.task,providerId:t.providerId,model:t.model,agents:t.agents.map(s=>({agentId:s.agentId,name:s.name,systemPrompt:s.systemPrompt,rolePrompt:s.rolePrompt,repoUrl:s.repoUrl})),tools:t.tools};return fetch(`${E}/runtime/run-team`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:o.signal}).then(async s=>{if(!s.ok){const i=await s.text().catch(()=>"");throw new Error(`Runtime error ${s.status}: ${i||s.statusText}`)}const a=s.body?.getReader();if(!a)throw new Error("No response body");let r=!1;await va(a,i=>{try{const c=JSON.parse(i);if(c.type==="error")return r=!0,ee.getState().setStatus("error",c.error||"Runtime execution failed"),!0;Sa(c)}catch{}}),!r&&ee.getState().status!=="error"&&ee.getState().setStatus("completed")}).catch(s=>{s instanceof DOMException&&s.name==="AbortError"||ee.getState().setStatus("error",s instanceof Error?s.message:String(s))}),o}function Sa(t){const o=ee.getState();switch(t.type){case"start":t.isAgentSdk!==void 0&&o.agents.forEach(e=>{o.updateAgent(e.agentId,{isAgentSdk:t.isAgentSdk})});break;case"turn":t.agentId&&o.updateAgent(t.agentId,{status:"running",turns:t.turn??0,currentMessage:t.message,...t.tokens&&{tokens:t.tokens}});break;case"fact":t.fact&&(t.agentId&&o.addFact(t.fact,{agentId:t.agentId}),o.addFact(t.fact,"shared"));break;case"tool_call":if(t.agentId){const e=o.agents.find(n=>n.agentId===t.agentId);e&&o.updateAgent(t.agentId,{toolCalls:[...e.toolCalls,{tool:t.tool??"",args:t.args??""}]})}break;case"done":t.agentId&&o.updateAgent(t.agentId,{status:"completed",output:t.result,...t.tokens&&{tokens:t.tokens}});break}}async function nn(t,o){const e=await fetch(`${E}/qualification${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!e.ok){const s=await e.json().catch(()=>({error:e.statusText}));throw new Error(s.error||`HTTP ${e.status}`)}return(await e.json()).data}function qa(t){return nn("/generate-suite",t)}function Ua(t,o){return new Promise((e,n)=>{fetch(`${E}/qualification/run`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}).then(s=>{if(!s.ok)return s.json().catch(()=>({error:s.statusText})).then(l=>{n(new Error(l.error||`HTTP ${s.status}`))});const a=s.body?.getReader();if(!a){n(new Error("No response body"));return}const r=new TextDecoder;let i="";const c=()=>{a.read().then(({done:l,value:d})=>{if(l){n(new Error("SSE stream ended without done event"));return}i+=r.decode(d,{stream:!0});const m=i.split(`
|
|
355
|
+
|
|
356
|
+
`);i=m.pop()??"";for(const u of m)if(u.startsWith("data: "))try{const p=JSON.parse(u.slice(6));if(o?.(p),p.type==="done"){e({runId:p.runId,globalScore:p.globalScore,dimensionScores:p.dimensionScores,testResults:p.testResults,patches:p.patches});return}if(p.type==="error"){n(new Error(p.message??"Unknown error"));return}}catch{}c()}).catch(n)};c()}).catch(n)})}function ja(t){return nn("/apply-patches",t)}function vt(){return{status:"unknown",latencyMs:null,toolCount:null,errorMessage:null,checkedAt:0}}const on=j((t,o)=>({mcpHealth:{},skillHealth:{},setMcpHealth:(e,n)=>t(s=>({mcpHealth:{...s.mcpHealth,[e]:n}})),setSkillHealth:(e,n)=>t(s=>({skillHealth:{...s.skillHealth,[e]:n}})),setMcpChecking:e=>t(n=>({mcpHealth:{...n.mcpHealth,[e]:{...n.mcpHealth[e]||vt(),status:"checking"}}})),setSkillChecking:e=>t(n=>({skillHealth:{...n.skillHealth,[e]:{...n.skillHealth[e]||vt(),status:"checking"}}})),clearHealth:()=>t({mcpHealth:{},skillHealth:{}})}));async function Ta(t){const o=on.getState();o.setMcpChecking(t);const e=performance.now();try{const n=await fetch(`${E}/health/mcp/${t}`,{signal:AbortSignal.timeout(15e3)}),s=Math.round(performance.now()-e);if(!n.ok){const m={status:"error",latencyMs:s,toolCount:null,errorMessage:`HTTP ${n.status}: ${n.statusText}`,checkedAt:Date.now()};return o.setMcpHealth(t,m),m}const a=await n.json();let r="healthy",i=null;const c=a.tools?.length??a.toolCount??null,l=a.tools?.map(m=>typeof m=="string"?m:m.name)??void 0;a.status==="error"||a.error?(r="error",i=a.error||a.message||"Server reported error"):a.status==="disconnected"||a.status==="not_configured"?(r="error",i=a.status==="not_configured"?"Not configured — add env vars in Settings":"Disconnected"):s>2e3&&(r="degraded",i=`Slow response: ${s}ms`);const d={status:r,latencyMs:s,toolCount:c,errorMessage:i,checkedAt:Date.now(),tools:l};return o.setMcpHealth(t,d),d}catch(n){const s=Math.round(performance.now()-e),a=n instanceof Error?n.name==="TimeoutError"?"Timeout (10s)":n.message:"Unknown error",r={status:"error",latencyMs:s,toolCount:null,errorMessage:a,checkedAt:Date.now()};return o.setMcpHealth(t,r),r}}async function Ka(t){try{const o=await fetch(`${E}/health/mcp/probe-all`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:t}),signal:AbortSignal.timeout(3e4)});if(o.ok){const e=await o.json(),n=on.getState();for(const s of e.data||[])n.setMcpHealth(s.id,{status:s.status,latencyMs:s.latencyMs,toolCount:s.toolCount,tools:s.tools,errorMessage:s.errorMessage,checkedAt:s.checkedAt});return}}catch{}await Promise.allSettled(t.map(o=>Ta(o)))}export{E as A,La as B,qa as C,ho as D,Ua as E,ja as F,Ea as G,Pa as H,Aa as I,on as J,We as K,Ka as L,_a as M,Ta as N,Ca as O,tn as P,yo as Q,Ia as R,se as _,Bt as a,Ma as b,he as c,St as d,U as e,fo as f,Fa as g,wn as h,Ee as i,Ra as j,$a as k,Y as l,D as m,ee as n,Na as o,gt as p,os as q,Da as r,Oa as s,Js as t,F as u,Oo as v,to as w,ge as x,no as y,zo as z};
|