ultracode 5.3.0 → 5.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/analysis-tool-handlers-H2RXLDPX.js +817 -0
- package/dist/chunks/analysis-tool-handlers-RJZAR6VT.js +817 -0
- package/dist/chunks/analysis-tool-handlers-Z2RF24T7.js +13 -0
- package/dist/chunks/autodoc-tool-handlers-CV5JEQUA.js +1112 -0
- package/dist/chunks/autodoc-tool-handlers-EHTNCH6I.js +1112 -0
- package/dist/chunks/autodoc-tool-handlers-MECXQJ2K.js +138 -0
- package/dist/chunks/chaos-CO7TOBOJ.js +18 -0
- package/dist/chunks/chaos-VM2PXERO.js +1573 -0
- package/dist/chunks/chaos-W3XRVJ7K.js +1564 -0
- package/dist/chunks/chunk-6K37BWK5.js +439 -0
- package/dist/chunks/chunk-EALTCYHZ.js +10 -0
- package/dist/chunks/chunk-FTBE7VMY.js +316 -0
- package/dist/chunks/chunk-KBW6LRQP.js +322 -0
- package/dist/chunks/chunk-NKUHX4CU.js +5 -0
- package/dist/chunks/chunk-NZFF4DQ4.js +3179 -0
- package/dist/chunks/chunk-RGP5UVQ7.js +3179 -0
- package/dist/chunks/chunk-RMZXFGQZ.js +322 -0
- package/dist/chunks/chunk-UG44F23Y.js +316 -0
- package/dist/chunks/chunk-V2SCB5H5.js +4403 -0
- package/dist/chunks/chunk-V6JAQNM3.js +1 -0
- package/dist/chunks/chunk-XFGXM4CR.js +4403 -0
- package/dist/chunks/dev-agent-JVIGBMHQ.js +1 -0
- package/dist/chunks/dev-agent-TRVP5U6N.js +1624 -0
- package/dist/chunks/dev-agent-Y5G5WKQ4.js +1624 -0
- package/dist/chunks/graph-storage-factory-AYZ57YSL.js +13 -0
- package/dist/chunks/graph-storage-factory-GTAIJEI5.js +1 -0
- package/dist/chunks/graph-storage-factory-T2WO5QVG.js +13 -0
- package/dist/chunks/incremental-updater-KDIQGAUU.js +14 -0
- package/dist/chunks/incremental-updater-OJRSTO3Q.js +1 -0
- package/dist/chunks/incremental-updater-SBEBH7KF.js +14 -0
- package/dist/chunks/indexer-agent-H3QIEL3Z.js +21 -0
- package/dist/chunks/indexer-agent-KHF5JMV7.js +21 -0
- package/dist/chunks/indexer-agent-SHJD6Z77.js +1 -0
- package/dist/chunks/indexing-pipeline-J6Z4BHKF.js +1 -0
- package/dist/chunks/indexing-pipeline-OY3337QN.js +249 -0
- package/dist/chunks/indexing-pipeline-WCXIDMAP.js +249 -0
- package/dist/chunks/merge-agent-LSUBDJB2.js +2481 -0
- package/dist/chunks/merge-agent-MJEW3HWU.js +2481 -0
- package/dist/chunks/merge-agent-O45OXF33.js +11 -0
- package/dist/chunks/merge-tool-handlers-BDSVNQVZ.js +277 -0
- package/dist/chunks/merge-tool-handlers-HP7DRBXJ.js +1 -0
- package/dist/chunks/merge-tool-handlers-RUJAKE3D.js +277 -0
- package/dist/chunks/pattern-tool-handlers-L62W3CXR.js +1549 -0
- package/dist/chunks/pattern-tool-handlers-SAHX2CVW.js +13 -0
- package/dist/chunks/query-agent-3TWDFIMT.js +191 -0
- package/dist/chunks/query-agent-HXQ3BMMF.js +191 -0
- package/dist/chunks/query-agent-USMC2GNG.js +1 -0
- package/dist/chunks/semantic-agent-MQCAWIAB.js +6381 -0
- package/dist/chunks/semantic-agent-NDGR3NAK.js +6381 -0
- package/dist/chunks/semantic-agent-S4ZL6GZC.js +137 -0
- package/dist/index.js +17 -17
- package/dist/roslyn-addon/.build-hash +1 -1
- package/dist/roslyn-addon/ILGPU.Algorithms.dll +0 -0
- package/dist/roslyn-addon/ILGPU.dll +0 -0
- package/dist/roslyn-addon/UltraCode.CSharp.deps.json +35 -0
- package/dist/roslyn-addon/UltraCode.CSharp.dll +0 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {a as a$l,b as b$h,c as c$e,d as d$9}from'./chunks/chunk-NI6OXODU.js';import {a as a$k,b as b$g,c as c$d,d as d$8,e as e$4,f as f$4,g as g$3,h as h$3,i as i$1,j,k}from'./chunks/chunk-VDY3Y3CS.js';import {a as a$i,b as b$e}from'./chunks/chunk-E4J4VT3N.js';import {c as c$a,e as e$2,d as d$6,b as b$b,a as a$g}from'./chunks/chunk-4AQ32P62.js';import {c as c$c,a as a$j,b as b$f}from'./chunks/chunk-X5UEWXAX.js';import {a as a$f}from'./chunks/chunk-LSMEFSBT.js';import {a as a$h,b as b$d,g as g$2,h as h$2,d as d$7,e as e$3,f as f$3,c as c$b}from'./chunks/chunk-TY3VEX4Z.js';import {a as a$e}from'./chunks/chunk-TPG7SMKQ.js';import {a}from'./chunks/chunk-W5ZEGGQZ.js';import {a as a$1,d as d$3,b as b$6,c as c$7}from'./chunks/chunk-RPKK6MZA.js';import {a as a$6}from'./chunks/chunk-TLK5HT5K.js';import {b as b$1,a as a$b}from'./chunks/chunk-DWXELIG2.js';export{a as getCurrentIndexingDirectory}from'./chunks/chunk-DWXELIG2.js';import'./chunks/chunk-QBFXI33X.js';import {a as a$7,b as b$5,c as c$6}from'./chunks/chunk-XJZYVQKD.js';import {d as d$4}from'./chunks/chunk-GJZGCWYM.js';import {b as b$4,c as c$3,a as a$a}from'./chunks/chunk-IWVAUDA7.js';import'./chunks/chunk-NC7PZJZ6.js';import {a as a$2}from'./chunks/chunk-7YC4KTAW.js';import {a as a$9,b as b$7}from'./chunks/chunk-V5VLOVE7.js';import {c as c$9,a as a$d,d as d$5,b as b$9}from'./chunks/chunk-MDUFK62Y.js';import {c as c$2,d as d$2,f,h}from'./chunks/chunk-3HWOZJ5W.js';import {a as a$5,c as c$1,b as b$3,e as e$1}from'./chunks/chunk-MVBDCRHL.js';import'./chunks/chunk-RK5TLU72.js';import'./chunks/chunk-LESND2CW.js';import'./chunks/chunk-QUO46LUP.js';import'./chunks/chunk-3IFLFBQ4.js';import {b as b$2,c as c$4}from'./chunks/chunk-SMIWBMYP.js';import'./chunks/chunk-IFKMF76K.js';import'./chunks/chunk-3X7W3DL2.js';import {H,d,F,q,v,o,n,w,p as p$1}from'./chunks/chunk-GVQNDMAK.js';import {c,a as a$3}from'./chunks/chunk-PZF7YC35.js';import'./chunks/chunk-ZEXJPUWO.js';import'./chunks/chunk-Y3FFUMCO.js';import'./chunks/chunk-R7SWWANK.js';import {c as c$8}from'./chunks/chunk-SOG7QA72.js';import'./chunks/chunk-2VECFQM2.js';import {a as a$8}from'./chunks/chunk-F3VMUQ7O.js';import {p,m,i}from'./chunks/chunk-QZQIPXIR.js';import'./chunks/chunk-6TB4AWV5.js';import {f as f$2}from'./chunks/chunk-TIQ5PADN.js';import {b,c as c$5}from'./chunks/chunk-AIZJT6AG.js';import'./chunks/chunk-NWQZW3Y6.js';import {g as g$1,a as a$4,d as d$1,e,b as b$a}from'./chunks/chunk-KXUWGHHN.js';import {G,h as h$1,a as a$c,f as f$1,b as b$8,q as q$1,v as v$1,o as o$1,r}from'./chunks/chunk-2KIPXYOB.js';import'./chunks/chunk-OG62YNVF.js';import {R,Q,I,G as G$1,F as F$1,M}from'./chunks/chunk-4BI7EBPQ.js';import {b as b$c}from'./chunks/chunk-ODGQBXBD.js';import'./chunks/chunk-NUFRM6SI.js';import'./chunks/chunk-F45ISXCP.js';import'./chunks/chunk-POFMGITV.js';import'./chunks/chunk-DXB73IDG.js';import {appendFileSync,existsSync,mkdirSync,statSync,renameSync,readdirSync,unlinkSync,readFileSync,writeFileSync,rmSync,copyFileSync}from'fs';import de,{normalize,resolve,join,dirname,isAbsolute,extname}from'path';import {fileURLToPath}from'url';import {Server}from'@modelcontextprotocol/sdk/server/index.js';import {StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import {ListPromptsRequestSchema,GetPromptRequestSchema,ListToolsRequestSchema,CallToolRequestSchema}from'@modelcontextprotocol/sdk/types.js';import {exec,spawnSync,spawn}from'child_process';import {promisify}from'util';import {appendFile}from'fs/promises';import ie,{homedir}from'os';import ga from'p-limit';import {createServer}from'net';import {EventEmitter}from'events';import {z}from'zod';import {nanoid}from'nanoid';R();g$1();var De={maxMemoryMB:1024,maxCpuPercent:80,maxConcurrentAgents:10,maxTaskQueueSize:100},le={taskQueueLimit:100,loadBalancingStrategy:"least-loaded",complexityThreshold:8,mandatoryDelegation:true,maxConcurrency:100,memoryLimit:128,priority:10};function mi(){let o=b$a(),e=o.conductor??{},t=e.resourceConstraints?.maxConcurrentAgents??o.mcp.agents?.maxConcurrent??De.maxConcurrentAgents,n={maxMemoryMB:e.resourceConstraints?.maxMemoryMB??De.maxMemoryMB,maxCpuPercent:e.resourceConstraints?.maxCpuPercent??De.maxCpuPercent,maxConcurrentAgents:t,maxTaskQueueSize:e.resourceConstraints?.maxTaskQueueSize??De.maxTaskQueueSize},r=e.maxConcurrency??le.maxConcurrency,s=e.memoryLimit??le.memoryLimit,a=e.priority??le.priority,c={resourceConstraints:n,taskQueueLimit:e.taskQueueLimit??le.taskQueueLimit,loadBalancingStrategy:e.loadBalancingStrategy??le.loadBalancingStrategy,complexityThreshold:e.complexityThreshold??le.complexityThreshold,mandatoryDelegation:e.mandatoryDelegation??le.mandatoryDelegation,maxConcurrency:r,memoryLimit:s,priority:a};return {capabilities:{maxConcurrency:r,memoryLimit:s,priority:a},config:c}}function gi(o){if(!o.payload||typeof o.payload!="object")return o.type==="direct";let e=o.payload;return e.directImplementation===true||e.bypassDelegation===true||o.type==="direct"}g$1();R();function hi(o){return typeof o.on=="function"}function Sn(){return typeof globalThis.Bun<"u"}var Xe=class extends b$7{agents=new Map;config;pendingTasks=new Map;directImplementationAttempts=0;agentLoadCache=new Map;LOAD_CACHE_TTL=5e3;performanceMetrics={totalTasks:0,avgProcessingTime:0,overheadReduction:0,cacheHitRate:0};heartbeatRunning=false;healthMonitorRunning=false;performanceLoopRunning=false;HEARTBEAT_INTERVAL_MS=1e4;HEALTH_CHECK_INTERVAL_MS=3e4;PERFORMANCE_INTERVAL_MS=6e4;AGENT_STALE_MS=6e4;agentLastSeen=new Map;stopped=false;lastRequestTime=Date.now();IDLE_THRESHOLD_MS=6e4;constructor(e={}){let t=mi(),n={maxConcurrency:e.maxConcurrency??t.capabilities.maxConcurrency,memoryLimit:e.memoryLimit??t.capabilities.memoryLimit,priority:e.priority??t.capabilities.priority};super("coordinator",n);let r={maxMemoryMB:e.resourceConstraints?.maxMemoryMB??t.config.resourceConstraints.maxMemoryMB,maxCpuPercent:e.resourceConstraints?.maxCpuPercent??t.config.resourceConstraints.maxCpuPercent,maxConcurrentAgents:e.resourceConstraints?.maxConcurrentAgents??t.config.resourceConstraints.maxConcurrentAgents,maxTaskQueueSize:e.resourceConstraints?.maxTaskQueueSize??t.config.resourceConstraints.maxTaskQueueSize};this.config={resourceConstraints:r,maxConcurrency:n.maxConcurrency,memoryLimit:n.memoryLimit,priority:n.priority,taskQueueLimit:e.taskQueueLimit??t.config.taskQueueLimit,loadBalancingStrategy:e.loadBalancingStrategy??t.config.loadBalancingStrategy,complexityThreshold:e.complexityThreshold??t.config.complexityThreshold,mandatoryDelegation:e.mandatoryDelegation!==void 0?e.mandatoryDelegation:t.config.mandatoryDelegation};}async onInitialize(){let e=Date.now();I.t("CONDUCTOR","init_start",{thresh:this.config.complexityThreshold,mandatory:true}),I.t("CONDUCTOR","health_monitor_start",{}),this.startHealthMonitoring(),I.t("CONDUCTOR","health_monitor_done",{dur:Date.now()-e}),I.t("CONDUCTOR","heartbeat_start",{}),this.startHeartbeat(),I.t("CONDUCTOR","delegation_init",{}),this.initializeDelegationEnforcement(),I.t("CONDUCTOR","perf_opts_init",{}),this.initializePerformanceOptimizations(),I.t("CONDUCTOR","init_done",{dur:Date.now()-e});}async onShutdown(){I.i("CONDUCTOR","shutdown_start",{agents:this.agents.size}),this.stopped=true,this.healthMonitorTimer&&(clearInterval(this.healthMonitorTimer),this.healthMonitorTimer=void 0),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0),this.performanceTimer&&(clearInterval(this.performanceTimer),this.performanceTimer=void 0),I.i("CONDUCTOR","shutdown_stats",{blocked:this.directImplementationAttempts});let e=Array.from(this.agents.values()).map(t=>t.shutdown().catch(n=>I.e("CONDUCTOR","agent_shutdown_fail",{agent:t.id,err:String(n)})));await Promise.all(e),this.agents.clear(),this.agentLastSeen.clear(),this.agentLoadCache.clear(),this.pendingTasks.clear();}canProcessTask(e){return this.pendingTasks.size<this.config.taskQueueLimit}async processTask(e){throw I.i("CONDUCTOR","process_task",{task:e.id,type:e.type}),new Error("[CONDUCTOR] Direct task processing is not supported. Use registered agents.")}initializeDelegationEnforcement(){let e=this.process.bind(this);this.process=async t=>{if(this.checkDirectImplementation(t))throw this.directImplementationAttempts++,I.w("CONDUCTOR","direct_blocked",{attempt:this.directImplementationAttempts,task:t.id}),new Error("CONDUCTOR VIOLATION: Direct implementation is FORBIDDEN. All tasks MUST be delegated to dev-agent or Dora. This is attempt #"+this.directImplementationAttempts);return e(t)};}checkDirectImplementation(e){return gi(e)}register(e){if(this.agents.size>=this.config.resourceConstraints.maxConcurrentAgents)throw new Error(`Maximum number of agents (${this.config.resourceConstraints.maxConcurrentAgents}) reached`);this.agents.set(e.id,e),I.i("CONDUCTOR","agent_registered",{agent:e.id,type:e.type}),hi(e)&&(e.on("task:completed",this.handleTaskCompleted.bind(this)),e.on("task:failed",this.handleTaskFailed.bind(this))),this.emit("agent:registered",e.id);}unregister(e){this.agents.get(e)&&(this.agents.delete(e),I.i("CONDUCTOR","agent_unregistered",{agent:e}),this.emit("agent:unregistered",e));}getAgent(e){return this.agents.get(e)}getAgentsByType(e){return Array.from(this.agents.values()).filter(t=>t.type===e)}getAgentByType(e){let t=this.getAgentsByType(e);return t.length===0&&I.d("CONDUCTOR","agent_not_found",{type:e,registered:Array.from(this.agents.keys()),types:Array.from(this.agents.values()).map(n=>n.type)}),t[0]}isIdle(){return Date.now()-this.lastRequestTime>this.IDLE_THRESHOLD_MS}markActivity(){this.lastRequestTime=Date.now();}healthMonitorTimer;heartbeatTimer;performanceTimer;startHealthMonitoring(){this.healthMonitorRunning||(this.healthMonitorRunning=true,!Sn()&&(this.healthMonitorTimer=setInterval(()=>{if(!this.stopped)try{this.checkAgentHealth();}catch(e){I.e("CONDUCTOR","health_check_fail",{err:String(e)});}},this.HEALTH_CHECK_INTERVAL_MS)));}checkAgentHealth(){let e=this.isIdle();for(let[t,n]of this.agents)if(n.status==="error"&&(I.w("CONDUCTOR","agent_error_state",{agent:t,type:n.type}),this.emit("agent:unhealthy",t)),!e)try{let s=("getMetrics"in n&&typeof n.getMetrics=="function"?n.getMetrics():void 0)?.lastActivity??Date.now();this.agentLastSeen.set(t,s),Date.now()-s>this.AGENT_STALE_MS&&I.d("CONDUCTOR","agent_stale",{agent:t,lastMs:Date.now()-s});}catch{}}startHeartbeat(){this.heartbeatRunning||(this.heartbeatRunning=true,!Sn()&&(this.heartbeatTimer=setInterval(()=>{if(!this.stopped&&!this.isIdle())try{this.emit("heartbeat",{agentId:this.id,timestamp:Date.now(),agents:this.agents.size});}catch(e){I.e("CONDUCTOR","heartbeat_fail",{err:String(e)});}},this.HEARTBEAT_INTERVAL_MS)));}async handleMessage(e){switch(e.type){case "register":I.d("CONDUCTOR","msg_register",{from:e.from});break;case "health":I.t("CONDUCTOR","msg_health",{from:e.from});break;default:{let t=this.agents.get(e.to);t&&await t.receive(e);}}}handleTaskCompleted(e){I.d("CONDUCTOR","task_completed",{task:e.task.id,agent:e.agentId}),this.emit("task:routed:completed",e);}handleTaskFailed(e){I.e("CONDUCTOR","task_failed",{task:e.task.id,agent:e.agentId,err:String(e.error)}),this.emit("task:routed:failed",e);}initializePerformanceOptimizations(){I.t("CONDUCTOR","perf_init_start",{}),this.startPerformanceLoop(),I.t("CONDUCTOR","perf_init_done",{});}startPerformanceLoop(){this.performanceLoopRunning||(this.performanceLoopRunning=true,!Sn()&&(this.performanceTimer=setInterval(()=>{if(!this.stopped&&!this.isIdle())try{this.updatePerformanceMetrics(),this.cleanupCaches();}catch(e){I.e("CONDUCTOR","perf_loop_fail",{err:String(e)});}},this.PERFORMANCE_INTERVAL_MS)));}updatePerformanceMetrics(){let e=this.agentLoadCache.size,t=this.performanceMetrics.totalTasks;t>0&&(this.performanceMetrics.cacheHitRate=e/t,this.performanceMetrics.overheadReduction=Math.min(40,e/t*100)),this.performanceMetrics.totalTasks>0&&this.performanceMetrics.totalTasks%100===0&&I.i("CONDUCTOR","perf_stats",{overhead:this.performanceMetrics.overheadReduction,tasks:this.performanceMetrics.totalTasks});}cleanupCaches(){let e=Date.now();for(let[t,n]of this.agentLoadCache)e-n.timestamp>this.LOAD_CACHE_TTL&&this.agentLoadCache.delete(t);}getPerformanceMetrics(){return {...this.performanceMetrics}}getPendingTasksCount(){return this.pendingTasks.size}getAllAgentMetrics(){let e={};for(let[,t]of this.agents){let n=t.getMetrics();e[t.type]=n;}return e}};G();promisify(exec);R();G();var fi="AUTODOC.md",Ee=class o{config;pendingUpdates=new Map;debounceControllers=new Map;subscriptionId=null;isProcessing=false;moduleCache=new Map;moduleCacheControllers=new Map;autodocEnabled=null;autodocCheckTime=0;static AUTODOC_CHECK_TTL=300*1e3;llmAvailabilityChecked=false;llmAvailabilityResult=false;constructor(e){this.config={debounceMs:e.debounceMs??5e3,minDebounceMs:e.minDebounceMs??3e3,maxDebounceMs:e.maxDebounceMs??15e3,rootDir:e.rootDir,enabled:e.enabled??true,useLlm:e.useLlm,llmConfig:e.llmConfig??{provider:"ollama"}};}async shouldUseLlm(){if(this.config.useLlm!==void 0)return this.config.useLlm;if(!this.llmAvailabilityChecked){this.llmAvailabilityChecked=true;try{let{detectLLMProviders:e}=await import('./chunks/llm-provider-ZCW4DWD3.js'),{recommended:t}=await e();this.llmAvailabilityResult=!!t,this.llmAvailabilityResult&&I.i("AUTODOCWATCH","llm_auto_detected",{provider:t?.name});}catch{this.llmAvailabilityResult=false;}}return this.llmAvailabilityResult}async checkAutodocEnabled(){let e=Date.now();if(this.autodocEnabled!==null&&e-this.autodocCheckTime<o.AUTODOC_CHECK_TTL)return this.autodocEnabled;let t=join(this.config.rootDir,".autodoc");return this.autodocEnabled=await h$1(t),this.autodocCheckTime=e,I.d("AUTODOCWATCH","check_autodoc_dir",{rootDir:this.config.rootDir,autodocDir:t,exists:this.autodocEnabled}),this.autodocEnabled}invalidateAutodocCache(){this.autodocEnabled=null,this.autodocCheckTime=0;}async start(){if(!this.config.enabled){I.i("AUTODOCWATCH","watcher_disabled");return}if(this.subscriptionId){I.w("AUTODOCWATCH","already_started");return}let e=await this.checkAutodocEnabled();e||I.i("AUTODOCWATCH","autodoc_folder_not_found",{root_dir:this.config.rootDir,hint:"Create .autodoc folder or run autodoc_generate to enable automatic documentation"}),this.subscriptionId=a$2.subscribe("autodoc-watcher",/^(index:complete|index:completed|semantic:new_entities)$/,this.handleEvent.bind(this)),a$c((t,n)=>{if(n==="write"){let r=de.extname(t).toLowerCase();[".ts",".js",".tsx",".jsx",".mjs",".cjs"].includes(r)&&this.handleFileChange(t);}}),I.i("AUTODOCWATCH","watcher_started",{root_dir:this.config.rootDir,debounce_ms:this.config.debounceMs,autodoc_enabled:e}),e&&(async()=>{await b(5e3);try{await this.scanAndCreateMissingAutodocs();}catch(t){I.e("AUTODOCWATCH","initial_scan_error",{error:String(t)});}})();}async scanAndCreateMissingAutodocs(){I.i("AUTODOCWATCH","scanning_for_missing_autodocs",{root:this.config.rootDir});try{let{scanModules:e}=await import('./chunks/doc-generator-65KNH633.js'),t=await e(this.config.rootDir,{maxDepth:4,concurrency:8}),n=0;for(let r of t){let s=de.join(r.path,"AUTODOC.md");if(!await h$1(s)){let c=await this.shouldUseLlm();I.i("AUTODOCWATCH","creating_missing_autodoc",{module:r.name,path:r.path,useLlm:c});let l;if(c){let{generateModuleDescriptionLLM:u}=await import('./chunks/autodoc-updater-KRV7WGQW.js'),p=await u(r,{useLlm:c,llmConfig:this.config.llmConfig});p&&(r.description=p,l={exportDescs:r._llmExportDescs,fileDescs:r._llmFileDescs});}let d=await c$8(r,c$9,l);I.i("AUTODOCWATCH","writing_autodoc",{module:r.name,path:s,contentLength:d.length,hasModuleDesc:!!r.description,hasExportDescs:!!l?.exportDescs&&Object.keys(l.exportDescs).length>0,hasFileDescs:!!l?.fileDescs&&Object.keys(l.fileDescs).length>0,source:"initial_scan"}),await f$1(s,d),n++,a$2.publish("autodoc:created",{modulePath:r.path,autodocPath:s,isNew:!0,source:"initial_scan"},"autodoc-watcher");}}n>0?(I.i("AUTODOCWATCH","initial_scan_created",{count:n,total_modules:t.length}),f$2.logUsageStats()):I.d("AUTODOCWATCH","initial_scan_all_exist",{total_modules:t.length});}catch(e){I.e("AUTODOCWATCH","scan_modules_error",{error:String(e)});}}stop(){this.subscriptionId&&(a$2.unsubscribe(this.subscriptionId),this.subscriptionId=null),a$c(null);for(let e of this.debounceControllers.values())e.abort();this.debounceControllers.clear(),this.pendingUpdates.clear();for(let e of this.moduleCacheControllers.values())e.abort();this.moduleCacheControllers.clear(),this.moduleCache.clear(),I.i("AUTODOCWATCH","watcher_stopped");}async handleEvent(e){let t=e.data;switch(e.topic){case "index:complete":t&&typeof t=="object"&&"filePath"in t&&t.filePath&&(I.d("AUTODOCWATCH","index_complete_event",{file:t.filePath}),await this.handleFileChange(t.filePath));break;case "semantic:new_entities":if(Array.isArray(t)){let n=new Set;for(let r of t)r&&typeof r=="object"&&"filePath"in r&&r.filePath&&n.add(r.filePath);I.d("AUTODOCWATCH","new_entities_event",{files:n.size});for(let r of n)await this.handleFileChange(r);}break;case "index:completed":await this.handleIndexCompleted(t);break}}async handleFileChange(e){if(!e)return;let t=de.extname(e).toLowerCase();if(![".ts",".js",".tsx",".jsx",".mjs",".cjs"].includes(t)||e.includes(".test.")||e.includes(".spec."))return;let n=await a$d(e,this.config.rootDir);if(!n){I.d("AUTODOCWATCH","no_module_found",{file:e});return}I.d("AUTODOCWATCH","file_change_detected",{file:e,module:n});let r=Date.now(),s=this.pendingUpdates.get(n);s||(s={modulePath:n,changedFiles:new Set,firstChangeAt:r,lastChangeAt:r},this.pendingUpdates.set(n,s)),s.changedFiles.add(e),s.lastChangeAt=r,this.scheduleUpdate(n);}scheduleUpdate(e){let t=this.debounceControllers.get(e);t&&t.abort();let n=this.pendingUpdates.get(e);if(!n)return;let r=n.changedFiles.size,s=this.config.debounceMs,a=Math.min(this.config.maxDebounceMs,Math.max(this.config.minDebounceMs,s+r*1e3)),c=Date.now()-n.firstChangeAt,l=Math.max(0,this.config.maxDebounceMs-c),d=Math.min(a,l);if(d<=0){this.processUpdate(e);return}let u=new AbortController;this.debounceControllers.set(e,u),(async()=>(await b(d),u.signal.aborted||this.processUpdate(e)))(),I.d("AUTODOCWATCH","update_scheduled",{module_path:e,changed_files:r,delay_ms:d});}async processUpdate(e){let t=this.pendingUpdates.get(e);if(t){if(this.pendingUpdates.delete(e),this.debounceControllers.delete(e),this.isProcessing){for(let n of t.changedFiles)await this.handleFileChange(n);return}this.isProcessing=true;try{I.i("AUTODOCWATCH","processing_update",{module_path:e,changed_files:t.changedFiles.size});let n=de.join(e,fi),r=await h$1(n),s=await this.checkAutodocEnabled();if(!r){if(s){let u=await this.shouldUseLlm();I.i("AUTODOCWATCH","creating_new_autodoc",{module_path:e,useLlm:u});let p=await this.getModuleInfo(e),m;if(u){let{generateModuleDescriptionLLM:v}=await import('./chunks/autodoc-updater-KRV7WGQW.js'),A=await v(p,{useLlm:u,llmConfig:this.config.llmConfig});A&&(p.description=A,m={exportDescs:p._llmExportDescs,fileDescs:p._llmFileDescs});}let h=await c$8(p,c$9,m);I.i("AUTODOCWATCH","writing_autodoc",{module:p.name,path:n,contentLength:h.length,hasModuleDesc:!!p.description,hasExportDescs:!!m?.exportDescs&&Object.keys(m.exportDescs).length>0,hasFileDescs:!!m?.fileDescs&&Object.keys(m.fileDescs).length>0,source:"processUpdate_new"}),await f$1(n,h),I.i("AUTODOCWATCH","autodoc_created",{module_path:e,autodoc_path:n,usedLlm:u}),a$2.publish("autodoc:created",{modulePath:e,autodocPath:n,isNew:!0},"autodoc-watcher");return}I.d("AUTODOCWATCH","autodoc_not_found_disabled",{module_path:e,hint:"Create .autodoc folder to enable auto-generation"});return}let a=await b$8(n),c=await this.getModuleInfo(e),l=await this.shouldUseLlm(),d=await d$5(a,c,Array.from(t.changedFiles),{useLlm:l,llmConfig:this.config.llmConfig});d!==a&&(await f$1(n,d),I.i("AUTODOCWATCH","autodoc_updated",{module_path:e,changed_files:t.changedFiles.size}),a$2.publish("autodoc:updated",{modulePath:e,autodocPath:n,changedFiles:Array.from(t.changedFiles)},"autodoc-watcher"));}catch(n){I.e("AUTODOCWATCH","update_failed",{module_path:e,error:String(n)});}finally{this.isProcessing=false;}}}async handleIndexCompleted(e){if(this.invalidateAutodocCache(),!await this.checkAutodocEnabled()){I.d("AUTODOCWATCH","index_completed_autodoc_disabled");return}I.i("AUTODOCWATCH","index_completed_scanning",{dir:e.directory||this.config.rootDir});try{let{scanModules:n}=await import('./chunks/doc-generator-65KNH633.js'),r=await n(this.config.rootDir,{maxDepth:4,concurrency:8}),s=0;for(let a of r){let c=de.join(a.path,fi);if(!await h$1(c)){let d=await this.shouldUseLlm();I.i("AUTODOCWATCH","creating_autodoc_for_new_module",{module:a.name,useLlm:d});let u;if(d){let{generateModuleDescriptionLLM:m}=await import('./chunks/autodoc-updater-KRV7WGQW.js'),h=await m(a,{useLlm:d,llmConfig:this.config.llmConfig});h&&(a.description=h,u={exportDescs:a._llmExportDescs,fileDescs:a._llmFileDescs});}let p=await c$8(a,c$9,u);I.i("AUTODOCWATCH","writing_autodoc",{module:a.name,path:c,contentLength:p.length,hasModuleDesc:!!a.description,hasExportDescs:!!u?.exportDescs&&Object.keys(u.exportDescs).length>0,hasFileDescs:!!u?.fileDescs&&Object.keys(u.fileDescs).length>0,source:"index_completed"}),await f$1(c,p),s++,a$2.publish("autodoc:created",{modulePath:a.path,autodocPath:c,isNew:!0,source:"index_completed"},"autodoc-watcher");}}s>0?(I.i("AUTODOCWATCH","index_completed_created",{count:s,total_modules:r.length}),f$2.logUsageStats()):I.d("AUTODOCWATCH","index_completed_all_exist",{total_modules:r.length});}catch(n){I.e("AUTODOCWATCH","index_completed_error",{error:String(n)});}}async getModuleInfo(e){let t=this.moduleCache.get(e);if(t)return t;let n=de.basename(e),r=de.join(e,"index.ts"),s=await h$1(r),a=s?await b$9(r):[],c=[];try{let p=await q$1(e,{withFileTypes:!0});for(let m of p)m.isFile()&&/\.(ts|js|tsx|jsx|mjs|cjs)$/.test(m.name)&&!m.name.includes(".test.")&&!m.name.includes(".spec.")&&c.push(m.name);}catch{}let l={name:n,path:e,files:c,hasIndex:s,exports:a};this.moduleCache.set(e,l);let d=this.moduleCacheControllers.get(e);d&&d.abort();let u=new AbortController;return this.moduleCacheControllers.set(e,u),(async()=>(await b(300*1e3),u.signal.aborted||(this.moduleCache.delete(e),this.moduleCacheControllers.delete(e))))(),l}async forceUpdate(e){let t={modulePath:e,changedFiles:new Set(["force-update"]),firstChangeAt:Date.now(),lastChangeAt:Date.now()};this.pendingUpdates.set(e,t),await this.processUpdate(e);}getStatus(){return {enabled:this.config.enabled,running:this.subscriptionId!==null,pendingUpdates:this.pendingUpdates.size,config:this.config}}},Je=null;function Qe(o){if(!Je&&o&&(Je=new Ee(o)),!Je)throw new Error("AutoDocWatcher not initialized. Provide config on first call.");return Je}function yi(o=process.argv.slice(2)){let e={configPath:void 0,helpRequested:false,versionRequested:false,setupRequested:false,noAutoIndex:false,pipeServerMode:false,quietMode:false,positionalArgs:[]};o[0]==="setup"&&(e.setupRequested=true);for(let t=0;t<o.length;t++){let n=o[t];if(!(e.setupRequested&&t===0))if(n==="--config"){let r=o[++t];r||(console.error("Error: --config requires a path argument"),console.error("Usage: ultracode [--config <path>] <directory>"),process.exit(1)),e.configPath=r;}else if(n.startsWith("--config=")){let r=n.slice(9);r||(console.error("Error: --config requires a non-empty path"),console.error("Usage: ultracode [--config <path>] <directory>"),process.exit(1)),e.configPath=r;}else if(n==="--help"||n==="-h")e.helpRequested=true;else if(n==="--version"||n==="-v")e.versionRequested=true;else if(n==="--no-auto-index")e.noAutoIndex=true;else if(n==="--stdio")e.pipeServerMode=false;else if(n==="--pipe")e.pipeServerMode=true,e.quietMode=true,process.env.MCP_QUIET_MODE="true";else if(n==="-d"||n==="--directory"){let r=o[++t];r&&e.positionalArgs.push(r);}else if(n.startsWith("-d=")||n.startsWith("--directory=")){let r=n.includes("=")?n.split("=")[1]:void 0;r&&e.positionalArgs.push(r);}else n.startsWith("-")?(console.error(`Unknown option: ${n}`),console.error("Usage: ultracode [--config <path>] [-d] <directory>"),process.exit(1)):e.positionalArgs.push(n);}return e}function Si(){console.error(`UltraCode Server
|
|
2
|
+
import {a as a$l,b as b$h,c as c$e,d as d$a}from'./chunks/chunk-NI6OXODU.js';import {a as a$k,b as b$g,c as c$d,d as d$9,e as e$4,f as f$4,g as g$4,h as h$3,i as i$1,j,k}from'./chunks/chunk-VDY3Y3CS.js';import {a as a$i,b as b$e}from'./chunks/chunk-E4J4VT3N.js';import {c as c$a,e as e$2,d as d$7,b as b$b,a as a$g}from'./chunks/chunk-4AQ32P62.js';import {c as c$c,a as a$j,b as b$f}from'./chunks/chunk-X5UEWXAX.js';import {a as a$f}from'./chunks/chunk-LSMEFSBT.js';import {a as a$h,b as b$d,g as g$3,h as h$2,d as d$8,e as e$3,f as f$3,c as c$b}from'./chunks/chunk-TY3VEX4Z.js';import {a as a$e}from'./chunks/chunk-TPG7SMKQ.js';import {a}from'./chunks/chunk-W5ZEGGQZ.js';import {a as a$1,d as d$4,b as b$5,c as c$7}from'./chunks/chunk-RPKK6MZA.js';import {a as a$5}from'./chunks/chunk-TLK5HT5K.js';import {b as b$1,a as a$b}from'./chunks/chunk-DWXELIG2.js';export{a as getCurrentIndexingDirectory}from'./chunks/chunk-DWXELIG2.js';import'./chunks/chunk-QBFXI33X.js';import {a as a$6,b as b$4,c as c$6}from'./chunks/chunk-V6JAQNM3.js';import {d as d$5}from'./chunks/chunk-GJZGCWYM.js';import {b as b$3,c as c$3,a as a$a}from'./chunks/chunk-IWVAUDA7.js';import'./chunks/chunk-NC7PZJZ6.js';import {a as a$2}from'./chunks/chunk-7YC4KTAW.js';import {a as a$9,b as b$7}from'./chunks/chunk-V5VLOVE7.js';import {c as c$9,a as a$d,d as d$6,b as b$9}from'./chunks/chunk-MDUFK62Y.js';import {c as c$2,d as d$2,f,h}from'./chunks/chunk-3HWOZJ5W.js';import {c as c$1,e as e$1,d as d$3,a as a$8,b as b$6,g as g$2}from'./chunks/chunk-6K37BWK5.js';import'./chunks/chunk-RK5TLU72.js';import'./chunks/chunk-LESND2CW.js';import'./chunks/chunk-QUO46LUP.js';import'./chunks/chunk-3IFLFBQ4.js';import {b as b$2,c as c$4}from'./chunks/chunk-SMIWBMYP.js';import'./chunks/chunk-IFKMF76K.js';import'./chunks/chunk-3X7W3DL2.js';import {H,d,F,q,v,o,n,w,p as p$1}from'./chunks/chunk-GVQNDMAK.js';import {c,a as a$3}from'./chunks/chunk-PZF7YC35.js';import'./chunks/chunk-ZEXJPUWO.js';import'./chunks/chunk-Y3FFUMCO.js';import'./chunks/chunk-R7SWWANK.js';import {c as c$8}from'./chunks/chunk-SOG7QA72.js';import'./chunks/chunk-2VECFQM2.js';import {a as a$7}from'./chunks/chunk-F3VMUQ7O.js';import {p,m,i}from'./chunks/chunk-QZQIPXIR.js';import'./chunks/chunk-6TB4AWV5.js';import {f as f$2}from'./chunks/chunk-TIQ5PADN.js';import {b,c as c$5}from'./chunks/chunk-AIZJT6AG.js';import'./chunks/chunk-NWQZW3Y6.js';import {g as g$1,a as a$4,d as d$1,e,b as b$a}from'./chunks/chunk-KXUWGHHN.js';import {G,h as h$1,a as a$c,f as f$1,b as b$8,q as q$1,v as v$1,o as o$1,r}from'./chunks/chunk-2KIPXYOB.js';import'./chunks/chunk-OG62YNVF.js';import {R,Q,I,G as G$1,F as F$1,M}from'./chunks/chunk-4BI7EBPQ.js';import {b as b$c}from'./chunks/chunk-ODGQBXBD.js';import'./chunks/chunk-NUFRM6SI.js';import'./chunks/chunk-F45ISXCP.js';import'./chunks/chunk-POFMGITV.js';import'./chunks/chunk-DXB73IDG.js';import {appendFileSync,existsSync,mkdirSync,statSync,renameSync,readdirSync,unlinkSync,readFileSync,writeFileSync,rmSync,copyFileSync}from'fs';import de,{normalize,resolve,join,dirname,isAbsolute,extname}from'path';import {fileURLToPath}from'url';import {Server}from'@modelcontextprotocol/sdk/server/index.js';import {StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import {ListPromptsRequestSchema,GetPromptRequestSchema,ListToolsRequestSchema,CallToolRequestSchema}from'@modelcontextprotocol/sdk/types.js';import {exec,spawnSync,spawn}from'child_process';import {promisify}from'util';import {appendFile}from'fs/promises';import ie,{homedir}from'os';import fa from'p-limit';import {createServer}from'net';import {EventEmitter}from'events';import {z}from'zod';import {nanoid}from'nanoid';R();g$1();var De={maxMemoryMB:1024,maxCpuPercent:80,maxConcurrentAgents:10,maxTaskQueueSize:100},le={taskQueueLimit:100,loadBalancingStrategy:"least-loaded",complexityThreshold:8,mandatoryDelegation:true,maxConcurrency:100,memoryLimit:128,priority:10};function hi(){let o=b$a(),e=o.conductor??{},t=e.resourceConstraints?.maxConcurrentAgents??o.mcp.agents?.maxConcurrent??De.maxConcurrentAgents,n={maxMemoryMB:e.resourceConstraints?.maxMemoryMB??De.maxMemoryMB,maxCpuPercent:e.resourceConstraints?.maxCpuPercent??De.maxCpuPercent,maxConcurrentAgents:t,maxTaskQueueSize:e.resourceConstraints?.maxTaskQueueSize??De.maxTaskQueueSize},r=e.maxConcurrency??le.maxConcurrency,s=e.memoryLimit??le.memoryLimit,a=e.priority??le.priority,c={resourceConstraints:n,taskQueueLimit:e.taskQueueLimit??le.taskQueueLimit,loadBalancingStrategy:e.loadBalancingStrategy??le.loadBalancingStrategy,complexityThreshold:e.complexityThreshold??le.complexityThreshold,mandatoryDelegation:e.mandatoryDelegation??le.mandatoryDelegation,maxConcurrency:r,memoryLimit:s,priority:a};return {capabilities:{maxConcurrency:r,memoryLimit:s,priority:a},config:c}}function fi(o){if(!o.payload||typeof o.payload!="object")return o.type==="direct";let e=o.payload;return e.directImplementation===true||e.bypassDelegation===true||o.type==="direct"}g$1();R();function yi(o){return typeof o.on=="function"}function bn(){return typeof globalThis.Bun<"u"}var Xe=class extends b$7{agents=new Map;config;pendingTasks=new Map;directImplementationAttempts=0;agentLoadCache=new Map;LOAD_CACHE_TTL=5e3;performanceMetrics={totalTasks:0,avgProcessingTime:0,overheadReduction:0,cacheHitRate:0};heartbeatRunning=false;healthMonitorRunning=false;performanceLoopRunning=false;HEARTBEAT_INTERVAL_MS=1e4;HEALTH_CHECK_INTERVAL_MS=3e4;PERFORMANCE_INTERVAL_MS=6e4;AGENT_STALE_MS=6e4;agentLastSeen=new Map;stopped=false;lastRequestTime=Date.now();IDLE_THRESHOLD_MS=6e4;constructor(e={}){let t=hi(),n={maxConcurrency:e.maxConcurrency??t.capabilities.maxConcurrency,memoryLimit:e.memoryLimit??t.capabilities.memoryLimit,priority:e.priority??t.capabilities.priority};super("coordinator",n);let r={maxMemoryMB:e.resourceConstraints?.maxMemoryMB??t.config.resourceConstraints.maxMemoryMB,maxCpuPercent:e.resourceConstraints?.maxCpuPercent??t.config.resourceConstraints.maxCpuPercent,maxConcurrentAgents:e.resourceConstraints?.maxConcurrentAgents??t.config.resourceConstraints.maxConcurrentAgents,maxTaskQueueSize:e.resourceConstraints?.maxTaskQueueSize??t.config.resourceConstraints.maxTaskQueueSize};this.config={resourceConstraints:r,maxConcurrency:n.maxConcurrency,memoryLimit:n.memoryLimit,priority:n.priority,taskQueueLimit:e.taskQueueLimit??t.config.taskQueueLimit,loadBalancingStrategy:e.loadBalancingStrategy??t.config.loadBalancingStrategy,complexityThreshold:e.complexityThreshold??t.config.complexityThreshold,mandatoryDelegation:e.mandatoryDelegation!==void 0?e.mandatoryDelegation:t.config.mandatoryDelegation};}async onInitialize(){let e=Date.now();I.t("CONDUCTOR","init_start",{thresh:this.config.complexityThreshold,mandatory:true}),I.t("CONDUCTOR","health_monitor_start",{}),this.startHealthMonitoring(),I.t("CONDUCTOR","health_monitor_done",{dur:Date.now()-e}),I.t("CONDUCTOR","heartbeat_start",{}),this.startHeartbeat(),I.t("CONDUCTOR","delegation_init",{}),this.initializeDelegationEnforcement(),I.t("CONDUCTOR","perf_opts_init",{}),this.initializePerformanceOptimizations(),I.t("CONDUCTOR","init_done",{dur:Date.now()-e});}async onShutdown(){I.i("CONDUCTOR","shutdown_start",{agents:this.agents.size}),this.stopped=true,this.healthMonitorTimer&&(clearInterval(this.healthMonitorTimer),this.healthMonitorTimer=void 0),this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0),this.performanceTimer&&(clearInterval(this.performanceTimer),this.performanceTimer=void 0),I.i("CONDUCTOR","shutdown_stats",{blocked:this.directImplementationAttempts});let e=Array.from(this.agents.values()).map(t=>t.shutdown().catch(n=>I.e("CONDUCTOR","agent_shutdown_fail",{agent:t.id,err:String(n)})));await Promise.all(e),this.agents.clear(),this.agentLastSeen.clear(),this.agentLoadCache.clear(),this.pendingTasks.clear();}canProcessTask(e){return this.pendingTasks.size<this.config.taskQueueLimit}async processTask(e){throw I.i("CONDUCTOR","process_task",{task:e.id,type:e.type}),new Error("[CONDUCTOR] Direct task processing is not supported. Use registered agents.")}initializeDelegationEnforcement(){let e=this.process.bind(this);this.process=async t=>{if(this.checkDirectImplementation(t))throw this.directImplementationAttempts++,I.w("CONDUCTOR","direct_blocked",{attempt:this.directImplementationAttempts,task:t.id}),new Error("CONDUCTOR VIOLATION: Direct implementation is FORBIDDEN. All tasks MUST be delegated to dev-agent or Dora. This is attempt #"+this.directImplementationAttempts);return e(t)};}checkDirectImplementation(e){return fi(e)}register(e){if(this.agents.size>=this.config.resourceConstraints.maxConcurrentAgents)throw new Error(`Maximum number of agents (${this.config.resourceConstraints.maxConcurrentAgents}) reached`);this.agents.set(e.id,e),I.i("CONDUCTOR","agent_registered",{agent:e.id,type:e.type}),yi(e)&&(e.on("task:completed",this.handleTaskCompleted.bind(this)),e.on("task:failed",this.handleTaskFailed.bind(this))),this.emit("agent:registered",e.id);}unregister(e){this.agents.get(e)&&(this.agents.delete(e),I.i("CONDUCTOR","agent_unregistered",{agent:e}),this.emit("agent:unregistered",e));}getAgent(e){return this.agents.get(e)}getAgentsByType(e){return Array.from(this.agents.values()).filter(t=>t.type===e)}getAgentByType(e){let t=this.getAgentsByType(e);return t.length===0&&I.d("CONDUCTOR","agent_not_found",{type:e,registered:Array.from(this.agents.keys()),types:Array.from(this.agents.values()).map(n=>n.type)}),t[0]}isIdle(){return Date.now()-this.lastRequestTime>this.IDLE_THRESHOLD_MS}markActivity(){this.lastRequestTime=Date.now();}healthMonitorTimer;heartbeatTimer;performanceTimer;startHealthMonitoring(){this.healthMonitorRunning||(this.healthMonitorRunning=true,!bn()&&(this.healthMonitorTimer=setInterval(()=>{if(!this.stopped)try{this.checkAgentHealth();}catch(e){I.e("CONDUCTOR","health_check_fail",{err:String(e)});}},this.HEALTH_CHECK_INTERVAL_MS)));}checkAgentHealth(){let e=this.isIdle();for(let[t,n]of this.agents)if(n.status==="error"&&(I.w("CONDUCTOR","agent_error_state",{agent:t,type:n.type}),this.emit("agent:unhealthy",t)),!e)try{let s=("getMetrics"in n&&typeof n.getMetrics=="function"?n.getMetrics():void 0)?.lastActivity??Date.now();this.agentLastSeen.set(t,s),Date.now()-s>this.AGENT_STALE_MS&&I.d("CONDUCTOR","agent_stale",{agent:t,lastMs:Date.now()-s});}catch{}}startHeartbeat(){this.heartbeatRunning||(this.heartbeatRunning=true,!bn()&&(this.heartbeatTimer=setInterval(()=>{if(!this.stopped&&!this.isIdle())try{this.emit("heartbeat",{agentId:this.id,timestamp:Date.now(),agents:this.agents.size});}catch(e){I.e("CONDUCTOR","heartbeat_fail",{err:String(e)});}},this.HEARTBEAT_INTERVAL_MS)));}async handleMessage(e){switch(e.type){case "register":I.d("CONDUCTOR","msg_register",{from:e.from});break;case "health":I.t("CONDUCTOR","msg_health",{from:e.from});break;default:{let t=this.agents.get(e.to);t&&await t.receive(e);}}}handleTaskCompleted(e){I.d("CONDUCTOR","task_completed",{task:e.task.id,agent:e.agentId}),this.emit("task:routed:completed",e);}handleTaskFailed(e){I.e("CONDUCTOR","task_failed",{task:e.task.id,agent:e.agentId,err:String(e.error)}),this.emit("task:routed:failed",e);}initializePerformanceOptimizations(){I.t("CONDUCTOR","perf_init_start",{}),this.startPerformanceLoop(),I.t("CONDUCTOR","perf_init_done",{});}startPerformanceLoop(){this.performanceLoopRunning||(this.performanceLoopRunning=true,!bn()&&(this.performanceTimer=setInterval(()=>{if(!this.stopped&&!this.isIdle())try{this.updatePerformanceMetrics(),this.cleanupCaches();}catch(e){I.e("CONDUCTOR","perf_loop_fail",{err:String(e)});}},this.PERFORMANCE_INTERVAL_MS)));}updatePerformanceMetrics(){let e=this.agentLoadCache.size,t=this.performanceMetrics.totalTasks;t>0&&(this.performanceMetrics.cacheHitRate=e/t,this.performanceMetrics.overheadReduction=Math.min(40,e/t*100)),this.performanceMetrics.totalTasks>0&&this.performanceMetrics.totalTasks%100===0&&I.i("CONDUCTOR","perf_stats",{overhead:this.performanceMetrics.overheadReduction,tasks:this.performanceMetrics.totalTasks});}cleanupCaches(){let e=Date.now();for(let[t,n]of this.agentLoadCache)e-n.timestamp>this.LOAD_CACHE_TTL&&this.agentLoadCache.delete(t);}getPerformanceMetrics(){return {...this.performanceMetrics}}getPendingTasksCount(){return this.pendingTasks.size}getAllAgentMetrics(){let e={};for(let[,t]of this.agents){let n=t.getMetrics();e[t.type]=n;}return e}};G();promisify(exec);R();G();var Si="AUTODOC.md",Ee=class o{config;pendingUpdates=new Map;debounceControllers=new Map;subscriptionId=null;isProcessing=false;moduleCache=new Map;moduleCacheControllers=new Map;autodocEnabled=null;autodocCheckTime=0;static AUTODOC_CHECK_TTL=300*1e3;llmAvailabilityChecked=false;llmAvailabilityResult=false;constructor(e){this.config={debounceMs:e.debounceMs??5e3,minDebounceMs:e.minDebounceMs??3e3,maxDebounceMs:e.maxDebounceMs??15e3,rootDir:e.rootDir,enabled:e.enabled??true,useLlm:e.useLlm,llmConfig:e.llmConfig??{provider:"ollama"}};}async shouldUseLlm(){if(this.config.useLlm!==void 0)return this.config.useLlm;if(!this.llmAvailabilityChecked){this.llmAvailabilityChecked=true;try{let{detectLLMProviders:e}=await import('./chunks/llm-provider-ZCW4DWD3.js'),{recommended:t}=await e();this.llmAvailabilityResult=!!t,this.llmAvailabilityResult&&I.i("AUTODOCWATCH","llm_auto_detected",{provider:t?.name});}catch{this.llmAvailabilityResult=false;}}return this.llmAvailabilityResult}async checkAutodocEnabled(){let e=Date.now();if(this.autodocEnabled!==null&&e-this.autodocCheckTime<o.AUTODOC_CHECK_TTL)return this.autodocEnabled;let t=join(this.config.rootDir,".autodoc");return this.autodocEnabled=await h$1(t),this.autodocCheckTime=e,I.d("AUTODOCWATCH","check_autodoc_dir",{rootDir:this.config.rootDir,autodocDir:t,exists:this.autodocEnabled}),this.autodocEnabled}invalidateAutodocCache(){this.autodocEnabled=null,this.autodocCheckTime=0;}async start(){if(!this.config.enabled){I.i("AUTODOCWATCH","watcher_disabled");return}if(this.subscriptionId){I.w("AUTODOCWATCH","already_started");return}let e=await this.checkAutodocEnabled();e||I.i("AUTODOCWATCH","autodoc_folder_not_found",{root_dir:this.config.rootDir,hint:"Create .autodoc folder or run autodoc_generate to enable automatic documentation"}),this.subscriptionId=a$2.subscribe("autodoc-watcher",/^(index:complete|index:completed|semantic:new_entities)$/,this.handleEvent.bind(this)),a$c((t,n)=>{if(n==="write"){let r=de.extname(t).toLowerCase();[".ts",".js",".tsx",".jsx",".mjs",".cjs"].includes(r)&&this.handleFileChange(t);}}),I.i("AUTODOCWATCH","watcher_started",{root_dir:this.config.rootDir,debounce_ms:this.config.debounceMs,autodoc_enabled:e}),e&&(async()=>{await b(5e3);try{await this.scanAndCreateMissingAutodocs();}catch(t){I.e("AUTODOCWATCH","initial_scan_error",{error:String(t)});}})();}async scanAndCreateMissingAutodocs(){I.i("AUTODOCWATCH","scanning_for_missing_autodocs",{root:this.config.rootDir});try{let{scanModules:e}=await import('./chunks/doc-generator-65KNH633.js'),t=await e(this.config.rootDir,{maxDepth:4,concurrency:8}),n=0;for(let r of t){let s=de.join(r.path,"AUTODOC.md");if(!await h$1(s)){let c=await this.shouldUseLlm();I.i("AUTODOCWATCH","creating_missing_autodoc",{module:r.name,path:r.path,useLlm:c});let l;if(c){let{generateModuleDescriptionLLM:u}=await import('./chunks/autodoc-updater-KRV7WGQW.js'),p=await u(r,{useLlm:c,llmConfig:this.config.llmConfig});p&&(r.description=p,l={exportDescs:r._llmExportDescs,fileDescs:r._llmFileDescs});}let d=await c$8(r,c$9,l);I.i("AUTODOCWATCH","writing_autodoc",{module:r.name,path:s,contentLength:d.length,hasModuleDesc:!!r.description,hasExportDescs:!!l?.exportDescs&&Object.keys(l.exportDescs).length>0,hasFileDescs:!!l?.fileDescs&&Object.keys(l.fileDescs).length>0,source:"initial_scan"}),await f$1(s,d),n++,a$2.publish("autodoc:created",{modulePath:r.path,autodocPath:s,isNew:!0,source:"initial_scan"},"autodoc-watcher");}}n>0?(I.i("AUTODOCWATCH","initial_scan_created",{count:n,total_modules:t.length}),f$2.logUsageStats()):I.d("AUTODOCWATCH","initial_scan_all_exist",{total_modules:t.length});}catch(e){I.e("AUTODOCWATCH","scan_modules_error",{error:String(e)});}}stop(){this.subscriptionId&&(a$2.unsubscribe(this.subscriptionId),this.subscriptionId=null),a$c(null);for(let e of this.debounceControllers.values())e.abort();this.debounceControllers.clear(),this.pendingUpdates.clear();for(let e of this.moduleCacheControllers.values())e.abort();this.moduleCacheControllers.clear(),this.moduleCache.clear(),I.i("AUTODOCWATCH","watcher_stopped");}async handleEvent(e){let t=e.data;switch(e.topic){case "index:complete":t&&typeof t=="object"&&"filePath"in t&&t.filePath&&(I.d("AUTODOCWATCH","index_complete_event",{file:t.filePath}),await this.handleFileChange(t.filePath));break;case "semantic:new_entities":if(Array.isArray(t)){let n=new Set;for(let r of t)r&&typeof r=="object"&&"filePath"in r&&r.filePath&&n.add(r.filePath);I.d("AUTODOCWATCH","new_entities_event",{files:n.size});for(let r of n)await this.handleFileChange(r);}break;case "index:completed":await this.handleIndexCompleted(t);break}}async handleFileChange(e){if(!e)return;let t=de.extname(e).toLowerCase();if(![".ts",".js",".tsx",".jsx",".mjs",".cjs"].includes(t)||e.includes(".test.")||e.includes(".spec."))return;let n=await a$d(e,this.config.rootDir);if(!n){I.d("AUTODOCWATCH","no_module_found",{file:e});return}I.d("AUTODOCWATCH","file_change_detected",{file:e,module:n});let r=Date.now(),s=this.pendingUpdates.get(n);s||(s={modulePath:n,changedFiles:new Set,firstChangeAt:r,lastChangeAt:r},this.pendingUpdates.set(n,s)),s.changedFiles.add(e),s.lastChangeAt=r,this.scheduleUpdate(n);}scheduleUpdate(e){let t=this.debounceControllers.get(e);t&&t.abort();let n=this.pendingUpdates.get(e);if(!n)return;let r=n.changedFiles.size,s=this.config.debounceMs,a=Math.min(this.config.maxDebounceMs,Math.max(this.config.minDebounceMs,s+r*1e3)),c=Date.now()-n.firstChangeAt,l=Math.max(0,this.config.maxDebounceMs-c),d=Math.min(a,l);if(d<=0){this.processUpdate(e);return}let u=new AbortController;this.debounceControllers.set(e,u),(async()=>(await b(d),u.signal.aborted||this.processUpdate(e)))(),I.d("AUTODOCWATCH","update_scheduled",{module_path:e,changed_files:r,delay_ms:d});}async processUpdate(e){let t=this.pendingUpdates.get(e);if(t){if(this.pendingUpdates.delete(e),this.debounceControllers.delete(e),this.isProcessing){for(let n of t.changedFiles)await this.handleFileChange(n);return}this.isProcessing=true;try{I.i("AUTODOCWATCH","processing_update",{module_path:e,changed_files:t.changedFiles.size});let n=de.join(e,Si),r=await h$1(n),s=await this.checkAutodocEnabled();if(!r){if(s){let u=await this.shouldUseLlm();I.i("AUTODOCWATCH","creating_new_autodoc",{module_path:e,useLlm:u});let p=await this.getModuleInfo(e),m;if(u){let{generateModuleDescriptionLLM:v}=await import('./chunks/autodoc-updater-KRV7WGQW.js'),A=await v(p,{useLlm:u,llmConfig:this.config.llmConfig});A&&(p.description=A,m={exportDescs:p._llmExportDescs,fileDescs:p._llmFileDescs});}let h=await c$8(p,c$9,m);I.i("AUTODOCWATCH","writing_autodoc",{module:p.name,path:n,contentLength:h.length,hasModuleDesc:!!p.description,hasExportDescs:!!m?.exportDescs&&Object.keys(m.exportDescs).length>0,hasFileDescs:!!m?.fileDescs&&Object.keys(m.fileDescs).length>0,source:"processUpdate_new"}),await f$1(n,h),I.i("AUTODOCWATCH","autodoc_created",{module_path:e,autodoc_path:n,usedLlm:u}),a$2.publish("autodoc:created",{modulePath:e,autodocPath:n,isNew:!0},"autodoc-watcher");return}I.d("AUTODOCWATCH","autodoc_not_found_disabled",{module_path:e,hint:"Create .autodoc folder to enable auto-generation"});return}let a=await b$8(n),c=await this.getModuleInfo(e),l=await this.shouldUseLlm(),d=await d$6(a,c,Array.from(t.changedFiles),{useLlm:l,llmConfig:this.config.llmConfig});d!==a&&(await f$1(n,d),I.i("AUTODOCWATCH","autodoc_updated",{module_path:e,changed_files:t.changedFiles.size}),a$2.publish("autodoc:updated",{modulePath:e,autodocPath:n,changedFiles:Array.from(t.changedFiles)},"autodoc-watcher"));}catch(n){I.e("AUTODOCWATCH","update_failed",{module_path:e,error:String(n)});}finally{this.isProcessing=false;}}}async handleIndexCompleted(e){if(this.invalidateAutodocCache(),!await this.checkAutodocEnabled()){I.d("AUTODOCWATCH","index_completed_autodoc_disabled");return}I.i("AUTODOCWATCH","index_completed_scanning",{dir:e.directory||this.config.rootDir});try{let{scanModules:n}=await import('./chunks/doc-generator-65KNH633.js'),r=await n(this.config.rootDir,{maxDepth:4,concurrency:8}),s=0;for(let a of r){let c=de.join(a.path,Si);if(!await h$1(c)){let d=await this.shouldUseLlm();I.i("AUTODOCWATCH","creating_autodoc_for_new_module",{module:a.name,useLlm:d});let u;if(d){let{generateModuleDescriptionLLM:m}=await import('./chunks/autodoc-updater-KRV7WGQW.js'),h=await m(a,{useLlm:d,llmConfig:this.config.llmConfig});h&&(a.description=h,u={exportDescs:a._llmExportDescs,fileDescs:a._llmFileDescs});}let p=await c$8(a,c$9,u);I.i("AUTODOCWATCH","writing_autodoc",{module:a.name,path:c,contentLength:p.length,hasModuleDesc:!!a.description,hasExportDescs:!!u?.exportDescs&&Object.keys(u.exportDescs).length>0,hasFileDescs:!!u?.fileDescs&&Object.keys(u.fileDescs).length>0,source:"index_completed"}),await f$1(c,p),s++,a$2.publish("autodoc:created",{modulePath:a.path,autodocPath:c,isNew:!0,source:"index_completed"},"autodoc-watcher");}}s>0?(I.i("AUTODOCWATCH","index_completed_created",{count:s,total_modules:r.length}),f$2.logUsageStats()):I.d("AUTODOCWATCH","index_completed_all_exist",{total_modules:r.length});}catch(n){I.e("AUTODOCWATCH","index_completed_error",{error:String(n)});}}async getModuleInfo(e){let t=this.moduleCache.get(e);if(t)return t;let n=de.basename(e),r=de.join(e,"index.ts"),s=await h$1(r),a=s?await b$9(r):[],c=[];try{let p=await q$1(e,{withFileTypes:!0});for(let m of p)m.isFile()&&/\.(ts|js|tsx|jsx|mjs|cjs)$/.test(m.name)&&!m.name.includes(".test.")&&!m.name.includes(".spec.")&&c.push(m.name);}catch{}let l={name:n,path:e,files:c,hasIndex:s,exports:a};this.moduleCache.set(e,l);let d=this.moduleCacheControllers.get(e);d&&d.abort();let u=new AbortController;return this.moduleCacheControllers.set(e,u),(async()=>(await b(300*1e3),u.signal.aborted||(this.moduleCache.delete(e),this.moduleCacheControllers.delete(e))))(),l}async forceUpdate(e){let t={modulePath:e,changedFiles:new Set(["force-update"]),firstChangeAt:Date.now(),lastChangeAt:Date.now()};this.pendingUpdates.set(e,t),await this.processUpdate(e);}getStatus(){return {enabled:this.config.enabled,running:this.subscriptionId!==null,pendingUpdates:this.pendingUpdates.size,config:this.config}}},Je=null;function Qe(o){if(!Je&&o&&(Je=new Ee(o)),!Je)throw new Error("AutoDocWatcher not initialized. Provide config on first call.");return Je}function bi(o=process.argv.slice(2)){let e={configPath:void 0,helpRequested:false,versionRequested:false,setupRequested:false,noAutoIndex:false,pipeServerMode:false,quietMode:false,positionalArgs:[]};o[0]==="setup"&&(e.setupRequested=true);for(let t=0;t<o.length;t++){let n=o[t];if(!(e.setupRequested&&t===0))if(n==="--config"){let r=o[++t];r||(console.error("Error: --config requires a path argument"),console.error("Usage: ultracode [--config <path>] <directory>"),process.exit(1)),e.configPath=r;}else if(n.startsWith("--config=")){let r=n.slice(9);r||(console.error("Error: --config requires a non-empty path"),console.error("Usage: ultracode [--config <path>] <directory>"),process.exit(1)),e.configPath=r;}else if(n==="--help"||n==="-h")e.helpRequested=true;else if(n==="--version"||n==="-v")e.versionRequested=true;else if(n==="--no-auto-index")e.noAutoIndex=true;else if(n==="--stdio")e.pipeServerMode=false;else if(n==="--pipe")e.pipeServerMode=true,e.quietMode=true,process.env.MCP_QUIET_MODE="true";else if(n==="-d"||n==="--directory"){let r=o[++t];r&&e.positionalArgs.push(r);}else if(n.startsWith("-d=")||n.startsWith("--directory=")){let r=n.includes("=")?n.split("=")[1]:void 0;r&&e.positionalArgs.push(r);}else n.startsWith("-")?(console.error(`Unknown option: ${n}`),console.error("Usage: ultracode [--config <path>] [-d] <directory>"),process.exit(1)):e.positionalArgs.push(n);}return e}function wi(){console.error(`UltraCode Server
|
|
3
3
|
|
|
4
4
|
Usage:
|
|
5
5
|
ultracode [options] <directory>
|
|
@@ -28,32 +28,32 @@ Examples:
|
|
|
28
28
|
ultracode setup
|
|
29
29
|
ultracode setup --provider ollama
|
|
30
30
|
ultracode --version
|
|
31
|
-
`);}function
|
|
32
|
-
`}writeLog(e){if(e.level<this.config.logLevel)return;this.buf.push(this.format(e));let t=Date.now();(this.buf.length>=this.BUF_CAP||t-this.lastDrain>=this.STALE_MS)&&(this.flushAsync(),this.lastDrain=t);}trace(e,t,n,r){this.log(N.TRACE,e,t,n,r);}traceTime(e,t,n,r){let s=Date.now()-n,a=process.uptime()*1e3;this.log(N.TRACE,e,`[+${a.toFixed(0)}ms] ${t} (${s}ms)`,r);}traceStart(e,t){let n=Date.now(),r=process.uptime()*1e3;return this.log(N.TRACE,e,`[+${r.toFixed(0)}ms] \u25B6 START: ${t}`),()=>{let s=Date.now()-n,a=process.uptime()*1e3;this.log(N.TRACE,e,`[+${a.toFixed(0)}ms] \u25C0 END: ${t} (${s}ms)`);}}debug(e,t,n,r){this.log(N.DEBUG,e,t,n,r);}info(e,t,n,r){this.log(N.INFO,e,t,n,r);}warn(e,t,n,r){this.log(N.WARN,e,t,n,r);}error(e,t,n,r,s){let a=s?.stack||(this.config.enableStackTrace?new Error().stack:void 0);this.log(N.ERROR,e,t,n,r,a);}critical(e,t,n,r,s){let a=s?.stack||(this.config.enableStackTrace?new Error().stack:void 0);this.log(N.CRITICAL,e,t,n,r,a);}log(e,t,n,r,s,a){this.writeLog({timestamp:this.localIso(),level:e,category:t,message:n,data:r,stackTrace:a,requestId:s});}localIso(){let e=new Date,t=e.getTimezoneOffset(),r=new Date(e.getTime()-t*6e4).toISOString().slice(0,-1),s=-t,a=s>=0?"+":"-",c=Math.abs(s),l=String(Math.floor(c/60)).padStart(2,"0"),d=String(c%60).padStart(2,"0");return `${r}${a}${l}:${d}`}mcpRequest(e,t,n){this.info("MCP_REQUEST",`Incoming MCP request: ${e}`,{method:e,params:t},n);}mcpResponse(e,t,n,r){this.writeLog({timestamp:new Date().toISOString(),level:N.INFO,category:"MCP_RESPONSE",message:`MCP response: ${e}`,data:{method:e,result:t},requestId:r,duration:n});}mcpError(e,t,n){this.error("MCP_ERROR",`MCP request failed: ${e}`,{method:e,error:t.message},n,t);}agentActivity(e,t,n,r){this.debug("AGENT_ACTIVITY",`Agent ${e}: ${t}`,{agentId:e,...n},r);}parseActivity(e,t,n,r,s){this.info("PARSE_ACTIVITY",`Parsed ${e}`,{filePath:e,language:t,entitiesFound:n,duration:r},s);}queryActivity(e,t,n,r){this.info("QUERY_ACTIVITY","Query executed",{query:e.substring(0,200),results:t,duration:n},r);}performanceMetrics(e,t,n){this.debug("PERFORMANCE",`Performance metrics for ${e}`,t,n);}systemEvent(e,t){this.info("SYSTEM",e,t);}incident(e,t,n,r){r?this.error("INCIDENT",e,{...t,error:r.message},n,r):this.warn("INCIDENT",e,t,n);}recovery(e,t,n){this.info("RECOVERY",e,t,n);}},
|
|
33
|
-
`);for(let l of c){let d=l.trim();if(!d||d.startsWith("#")||d.startsWith("!"))continue;let u=d;u.endsWith("/")?u=`**/${u}**`:u.includes("/")?!u.startsWith("/")&&!u.startsWith("**/")&&(u=`**/${u}`):u=`**/${u}`,u.startsWith("/")&&(u=u.slice(1)),e.push(u);}I.d("AUTOINDEX","gitignore_loaded",{cnt:c.filter(l=>l.trim()&&!l.startsWith("#")).length});}}catch{}return e}async function Me(o,e,t,n){let r=typeof n=="boolean"?{incremental:n}:n??{},s=r.incremental??false,a=Pe(),c=Date.now();I.t("INDEXER","auto_index_start",{offset:c-t.processStartTime}),tt(true,o);let l=s?"incremental":"full";I.i("INDEXER","auto_index",{mode:l,dir:o,req:a});let d=0,u,p,m,h=true;try{if(r.reset){let S=await t.getGraphStorage();S.setProject(o),await S.clear(),I.d("INDEXER","storage_cleared",{dir:o});}let v=await
|
|
34
|
-
`);if(e===-1)return null;let t=this.buffer.slice(0,e);return this.buffer=this.buffer.slice(e+1),t.trim()?JSON.parse(t):null}clear(){this.buffer="";}}
|
|
35
|
-
`);if(d===-1)return;let u=this.readBuffer.buffer.slice(0,d),p=this.readBuffer.buffer.slice(d+1);if(u.startsWith(
|
|
36
|
-
`;this.socket.write(r,s=>{s?n(s):t();});})}},at=class{server=null;pipePath;constructor(e){this.pipePath=e??Ss();}async waitForConnection(){if(process.platform!=="win32"&&existsSync(this.pipePath))try{unlinkSync(this.pipePath);}catch{}return new Promise((e,t)=>{this.server=createServer(n=>{let r=new st(n);e(r);}),this.server.on("error",n=>{n.code==="EADDRINUSE"&&(I.e("PIPE","EADDRINUSE: pipe already in use by another server instance, exiting",{pipe:this.pipePath}),process.exit(1)),t(n);}),this.server.listen(this.pipePath);})}async start(e){if(process.platform!=="win32"&&existsSync(this.pipePath))try{unlinkSync(this.pipePath);}catch{}return new Promise((t,n)=>{this.server=createServer(r=>{let s=new st(r);e(s);}),this.server.on("error",r=>{r.code==="EADDRINUSE"&&(I.e("PIPE","EADDRINUSE: pipe already in use by another server instance, exiting",{pipe:this.pipePath}),process.exit(1)),n(r);}),this.server.listen(this.pipePath,()=>{t();});})}async close(){if(this.server&&(this.server.close(),this.server=null),process.platform!=="win32"&&existsSync(this.pipePath))try{unlinkSync(this.pipePath);}catch{}}getPath(){return this.pipePath}};R();var ws=1048576,Pn=o=>Math.round(o/ws);function _s(){return typeof globalThis.Bun<"u"}var Mn=class{constructor(e){this.capacity=e;this.buf=new Array(e);}buf;head=0;len=0;push(e){this.buf[this.head]=e,this.head=(this.head+1)%this.capacity,this.len<this.capacity&&this.len++;}latest(){if(this.len===0)return null;let e=(this.head-1+this.capacity)%this.capacity;return this.buf[e]}since(e){if(this.len===0)return [];let t=this.len<this.capacity?0:this.head,n=0,r=this.len;for(;n<r;){let a=n+r>>>1,c=(t+a)%this.capacity;this.buf[c].timestamp<e?n=a+1:r=a;}let s=[];for(let a=n;a<this.len;a++)s.push(this.buf[(t+a)%this.capacity]);return s}get size(){return this.len}},Rn=class o extends EventEmitter{constraints;allocations=new Map;snapshots;monitoring=false;tickTimer;pollingIntervalMs=1e3;static POLL_FLOOR=1e3;static POLL_CEILING=1e4;throttled=false;throttleThreshold=.8;constructor(e){super();let t=ie.totalmem()/(1024*1024*1024),n=ie.cpus().length,r=Math.min(Math.max(4096,Math.floor(t*512)),16384);this.constraints=e??{maxMemoryMB:r,maxCpuPercent:95,maxConcurrentAgents:Math.min(20,n*3),maxTaskQueueSize:200},this.snapshots=new Mn(60),I.i("RESOURCEMGR","init",{memMB:this.constraints.maxMemoryMB,maxAgents:this.constraints.maxConcurrentAgents});}startMonitoring(){this.monitoring||(this.monitoring=true,this.emit("monitoring:started"),!_s()&&(this.tick(),this.tickTimer=setInterval(()=>this.tick(),2e3)));}stopMonitoring(){this.monitoring&&(this.monitoring=false,this.pollingIntervalMs=1e3,this.tickTimer&&(clearInterval(this.tickTimer),this.tickTimer=void 0),this.emit("monitoring:stopped"));}requestAllocation(e,t,n,r=5){let s=this.sumAllocated();return s.memory+t>this.constraints.maxMemoryMB?(this.emit("allocation:denied",{agentId:e,reason:"memory_exceeded",requested:t,available:this.constraints.maxMemoryMB-s.memory}),false):s.cpu+n>this.constraints.maxCpuPercent?(this.emit("allocation:denied",{agentId:e,reason:"cpu_exceeded",requested:n,available:this.constraints.maxCpuPercent-s.cpu}),false):(this.allocations.set(e,{agentId:e,memoryMB:t,cpuPercent:n,priority:r}),this.emit("allocation:granted",{agentId:e,memoryMB:t,cpuPercent:n}),true)}releaseAllocation(e){let t=this.allocations.get(e);t&&(this.allocations.delete(e),this.emit("allocation:released",t));}getCurrentUsage(){return this.snapshots.latest()}getHistory(e=60){return this.snapshots.since(Date.now()-e*1e3)}isSystemThrottled(){return this.throttled}getAvailableResources(){let e=this.sumAllocated();return {memoryMB:Math.max(0,this.constraints.maxMemoryMB-e.memory),cpuPercent:Math.max(0,this.constraints.maxCpuPercent-e.cpu)}}suggestAllocation(e){let t=this.getAvailableResources();if(t.memoryMB<50||t.cpuPercent<5)return null;let n=e/10;return {memoryMB:Math.min(Math.floor(t.memoryMB*n*.5),256),cpuPercent:Math.min(Math.floor(t.cpuPercent*n*.5),25)}}requestGarbageCollection(){global.gc?(I.i("RESOURCEMGR","gc_forced"),global.gc(),this.emit("gc:completed")):I.w("RESOURCEMGR","gc_not_exposed",{hint:"run with --expose-gc"});}adjustForCodebaseSize(e,t){let n=this.constraints.maxMemoryMB,r=this.constraints.maxConcurrentAgents;e>1e4?(n=Math.min(this.constraints.maxMemoryMB*3,16384),r=2,I.i("RESOURCEMGR","xlarge_codebase",{files:e,memMB:n,agents:r})):e>5e3?(n=Math.min(this.constraints.maxMemoryMB*2,12288),r=Math.max(4,Math.floor(r/2)),I.i("RESOURCEMGR","vlarge_codebase",{files:e,memMB:n,agents:r})):e>2e3&&(n=Math.min(this.constraints.maxMemoryMB*1.5,8192),I.i("RESOURCEMGR","large_codebase",{files:e,memMB:n})),this.constraints.maxMemoryMB=n,this.constraints.maxConcurrentAgents=r;let s={fileCount:e,projectSizeMB:t,newMemoryLimit:n,newAgentLimit:r};this.emit("resources:adjusted",s),a$2.publish("resources:adjusted",s,"resource-manager",6e4);}getConstraints(){return {...this.constraints}}tick(){if(!this.monitoring)return;this.captureSnapshot();let e=this.evaluatePressure();e>.8?this.pollingIntervalMs=o.POLL_FLOOR:e<.3?this.pollingIntervalMs=Math.min(o.POLL_CEILING,Math.round(this.pollingIntervalMs*1.5)):this.pollingIntervalMs=2e3;}captureSnapshot(){let e=ie.totalmem(),t=ie.freemem(),n=e-t,r=ie.cpus().length,s={timestamp:Date.now(),memory:{total:Pn(e),used:Pn(n),free:Pn(t),percentage:n/e*100},cpu:{cores:r,usage:this.estimateCpuUsage(),loadAverage:ie.loadavg()},io:{pendingReads:0,pendingWrites:0}};this.snapshots.push(s),this.emit("snapshot:captured",s);}estimateCpuUsage(){let e=ie.loadavg(),t=Array.isArray(e)&&typeof e[0]=="number"?e[0]:0,n=ie.cpus().length||1;return Math.min(100,t/n*100)}evaluatePressure(){let e=this.getCurrentUsage();if(!e)return 0;let t=e.memory.percentage/100,n=e.cpu.usage/100,r=Math.max(t,n),s=this.throttleThreshold*100,a=e.memory.percentage>s,c=e.cpu.usage>s,l=a||c;return l&&!this.throttled?(this.throttled=true,I.w("RESOURCEMGR","throttle_on",{mem:a,cpu:c}),this.emit("throttle:enabled",{memory:a,cpu:c}),a&&this.requestGarbageCollection()):!l&&this.throttled&&(this.throttled=false,I.i("RESOURCEMGR","throttle_off"),this.emit("throttle:disabled")),e.memory.percentage>90&&this.emit("memory:critical",e.memory),e.cpu.usage>90&&this.emit("cpu:critical",e.cpu),r}sumAllocated(){let e=0,t=0;for(let n of this.allocations.values())e+=n.memoryMB,t+=n.cpuPercent;return {memory:e,cpu:t}}},Ie=new Rn;H();z.object({repositoryPath:z.string().optional().describe("Path to Git repository (defaults to current directory)")});z.object({branch:z.string().describe("Name of the branch to switch to"),repositoryPath:z.string().optional().describe("Path to Git repository (defaults to current directory)")});z.object({repositoryPath:z.string().optional().describe("Path to Git repository (defaults to current directory)")});z.object({keep:z.number().optional().describe("Number of most recently used branches to keep (defaults to config value)")});z.object({fromBranch:z.string().describe("Source branch name"),toBranch:z.string().describe("Target branch name")});var qi=[{name:"list_branches",description:"[BRANCH] List all indexed branches for the current repository. Shows branch names, last accessed time, database size, and metadata (entity count, last commit, etc.).",inputSchema:{type:"object",properties:{repositoryPath:{type:"string",description:"Path to Git repository (defaults to current directory)"}}}},{name:"switch_branch",description:"[BRANCH] Switch active branch for indexing. Changes the database context to the specified branch. Note: You may need to reindex if switching to a branch that hasn't been indexed yet.",inputSchema:{type:"object",properties:{branch:{type:"string",description:"Name of the branch to switch to"},repositoryPath:{type:"string",description:"Path to Git repository (defaults to current directory)"}},required:["branch"]}},{name:"get_branch_status",description:"[BRANCH] Get detailed status of the current branch including last commit hash, entity count, relationship count, and database information.",inputSchema:{type:"object",properties:{repositoryPath:{type:"string",description:"Path to Git repository (defaults to current directory)"}}}},{name:"cleanup_branches",description:"[BRANCH] Cleanup old branch databases using LRU eviction strategy. Removes least recently used branches while keeping the specified number of most recent branches.",inputSchema:{type:"object",properties:{keep:{type:"number",description:"Number of most recently used branches to keep (defaults to config value)"}}}},{name:"get_changed_files",description:"[BRANCH] Get list of files changed between two branches. Useful for determining scope of changes before switching branches or for incremental reindexing.",inputSchema:{type:"object",properties:{fromBranch:{type:"string",description:"Source branch name"},toBranch:{type:"string",description:"Target branch name"}},required:["fromBranch","toBranch"]}}];var In=z.object({paths:z.array(z.string()).nonempty().optional().describe("Directories or files to scan. Relative paths resolve against the server root."),pattern:z.string().optional().describe("Glob pattern to apply within each path (default **/*)."),ignore:z.array(z.string()).optional().describe("Glob patterns to exclude from scanning."),formats:z.array(z.string().regex(/^[^.]+$/)).optional().describe("File extensions to include without dots (e.g. ['ts','js'])."),minLines:z.number().int().min(1).optional().describe("Minimum lines per clone block."),maxLines:z.number().int().min(1).optional().describe("Maximum lines per clone block."),minTokens:z.number().int().min(1).optional().describe("Minimum tokens per clone (interpreted as lines)."),ignoreCase:z.boolean().optional().describe("Lowercase tokens before comparison.")}),kn=z.object({filePath:z.string().describe("File to analyze for refactoring"),focusArea:z.string().optional().describe("Specific entity name to focus on"),entityId:z.string().optional().describe("Exact entity ID to analyze"),startLine:z.number().int().min(1).optional().describe("1-based start line for manual selection"),endLine:z.number().int().min(1).optional().describe("1-based end line (exclusive)")}).refine(o=>o.startLine==null&&o.endLine==null||o.startLine!=null&&o.endLine!=null&&o.startLine<o.endLine,{message:"startLine and endLine must both be provided and startLine < endLine",path:["startLine"]}),On=z.object({metric:z.enum(["complexity","changes","coupling","all"]).optional().default("complexity").describe("Metric: complexity, changes, coupling, or all"),limit:z.number().optional().default(10).describe("Maximum hotspots to return"),includeHistoricalMetrics:z.boolean().optional().default(true).describe("Use Prolly Tree history for changeFrequency calculation"),lookbackDays:z.number().optional().default(30).describe("Number of days to look back for change frequency")}),Ln=z.object({projectPath:z.string().optional().describe("Project directory path"),scope:z.enum(["file","module","project"]).optional().default("project").describe("Analysis scope"),stateIdentifiers:z.array(z.string()).optional().describe("Specific state identifiers to analyze (e.g., ['token', 'userId'])"),autoDetect:z.boolean().optional().default(true).describe("Automatically detect state patterns"),format:z.enum(["summary","detailed","json"]).optional().default("summary").describe("Output format: summary (AI-friendly), detailed (human), json (raw)"),maxDepth:z.number().optional().default(10).describe("Maximum trace depth"),excludePatterns:z.array(z.string()).optional().describe("File patterns to exclude")});var Nn=z.object({filePath:z.string().describe("Path to the file to list entities from"),entityTypes:z.array(z.string()).describe("Types of entities to list").optional(),projectPath:a}),jn=z.object({entityId:z.string().optional().describe("Exact entity ID to find relationships for"),entityName:z.string().optional().describe("Name of the entity to find relationships for"),filePath:z.string().optional().describe("Optional file path hint to disambiguate entity"),depth:z.number().optional().default(1).describe("Depth of relationship traversal"),relationshipTypes:z.array(z.string()).optional().describe("Types of relationships to include"),projectPath:a}).refine(o=>!!(o.entityId||o.entityName),{message:"Provide either entityId or entityName",path:["entityId"]}),Un=z.object({query:z.string().describe("Natural language or structured query"),limit:z.number().describe("Maximum number of results").optional().default(10),branch:z.string().optional().describe("Branch name (null = main branch)"),projectPath:a});var Fn=z.object({projectPath:z.string().optional().describe("Project directory path"),metric:z.enum(["pagerank","louvain","centrality","bus_factor"]).describe("Type of graph metric to compute"),topN:z.number().optional().default(20).describe("Number of top results to return (for pagerank, centrality)"),minCommunitySize:z.number().optional().default(2).describe("Minimum community size to include (for louvain)"),persist:z.boolean().optional().default(false).describe("Persist computed metrics to entity metadata for use in semantic search ranking")});var zn=z.object({query:z.string().optional().describe("Optional search query"),limit:z.number().optional().default(100).describe("Maximum entities to return"),projectPath:a}),Gn=z.object({projectPath:a}),Bn=z.object({minEntities:z.number().optional().default(1).describe("Minimum entity count for healthy status"),minRelationships:z.number().optional().default(0).describe("Minimum relationship count for healthy status"),sample:z.number().optional().default(1).describe("Sample size to fetch for verification"),projectPath:a}),Hn=z.object({}),Wn=z.object({topic:z.string().min(1).describe("Exact knowledge bus topic to clear (use wildcards via knowledgeBus.query for inspection)")});var $i=["node_modules/**",".git/**","dist/**","build/**","out/**",".next/**",".nuxt/**","coverage/**",".nyc_output/**","__pycache__/**","*.pyc",".pytest_cache/**","venv/**","env/**",".venv/**",".env/**","vendor/**","target/**",".gradle/**",".idea/**",".vscode/**","**/.memory_bank/**","tmp/**","temp/**","**/tmp/**","**/temp/**","*.log","*.tmp","*.cache","**/*.md","*.zip","*.tar","*.tar.gz","*.tgz","*.gz","*.bz2","*.xz","*.7z","*.rar","*.zst",".DS_Store","Thumbs.db"],qn=z.object({directory:z.string().describe("Directory to index").optional(),incremental:z.boolean().describe("Perform incremental indexing").optional().default(false),reset:z.boolean().describe("Clear existing graph before indexing").optional().default(false),excludePatterns:z.array(z.string()).describe("Patterns to exclude").optional().default($i),fullScan:z.boolean().optional().default(false)}),$n=z.object({directory:z.string().describe("Directory to index after reset").optional(),excludePatterns:z.array(z.string()).describe("Patterns to exclude during indexing").optional().default([]),fullScan:z.boolean().optional().default(false)}),Vn=z.object({});var Yn=z.object({sourceBranch:z.string().describe("Source branch name (where changes come from), e.g. 'feature/caching'"),targetBranch:z.string().optional().describe("Target branch name (where to merge), e.g. 'main'. Defaults to current branch."),dryRun:z.boolean().optional().default(true).describe("Preview only, don't apply changes (default: true)"),autoResolve:z.boolean().optional().default(false).describe("Auto-resolve compatible conflicts (default: false)"),includeAISuggestions:z.boolean().optional().default(true).describe("Generate AI suggestions for conflicts (default: true)")}),Xn=z.object({branchA:z.string().describe("First branch name"),branchB:z.string().describe("Second branch name")}),Jn=z.object({conflictId:z.string().describe("ID of the conflict to get suggestions for (from analyze_merge_conflicts)"),branchA:z.string().describe("First branch name"),branchB:z.string().describe("Second branch name")}),Qn=z.object({});var Kn=z.object({entityId:z.string().describe("ID of entity to modify"),newCode:z.string().describe("New code to replace entity"),preserveComments:z.boolean().optional().default(true).describe("Preserve leading comments"),updateImports:z.boolean().optional().default(true).describe("Update imports if signature changed"),preview:z.boolean().optional().default(true).describe("Preview changes before applying"),skipValidation:z.boolean().optional().default(false).describe("Skip validation checks")}),Zn=z.object({source:z.string().describe("Source file or directory path"),target:z.string().describe("Target path"),preview:z.boolean().optional().default(true).describe("Preview before copying"),updateGraph:z.boolean().optional().default(true).describe("Update graph with copied entities")}),er=z.object({oldPath:z.string().describe("Current file path"),newPath:z.string().describe("New file path"),preview:z.boolean().optional().default(true).describe("Preview before renaming"),updateImports:z.boolean().optional().default(true).describe("Update imports across project"),updateGraph:z.boolean().optional().default(true).describe("Update graph with new paths")}),tr=z.object({filePath:z.string().describe("File to split"),entityIds:z.array(z.string()).describe("Entity IDs to extract to separate files"),preview:z.boolean().optional().default(true).describe("Preview before splitting"),updateGraph:z.boolean().optional().default(true).describe("Update graph with new file locations")}),nr=z.object({files:z.array(z.string()).min(2).describe("Files to combine into one"),targetPath:z.string().describe("Target file path for combined result"),preview:z.boolean().optional().default(true).describe("Preview before synthesizing"),deleteOriginals:z.boolean().optional().default(false).describe("Delete original files after synthesis"),updateGraph:z.boolean().optional().default(true).describe("Update graph with merged entities")}),rr=z.object({filePath:z.string().describe("Absolute path for the new file to create"),content:z.string().describe("Content to write to the file"),createDirectories:z.boolean().optional().default(true).describe("Create parent directories if they don't exist"),updateGraph:z.boolean().optional().default(true).describe("Parse and add entities to graph after creation"),overwrite:z.boolean().optional().default(false).describe("Overwrite file if it already exists")}),ir=z.object({entityId:z.string().optional().describe("Entity ID to rename (preferred)"),entityName:z.string().optional().describe("Entity name to rename (if entityId not provided)"),filePath:z.string().optional().describe("File path hint for disambiguation"),newName:z.string().describe("New name for the symbol"),updateReferences:z.boolean().optional().default(true).describe("Update all references to this symbol"),preview:z.boolean().optional().default(true).describe("Preview changes before applying")}),or=z.object({entityId:z.string().optional().describe("Parent entity ID (class/interface) to add member to"),filePath:z.string().describe("File path where to add the member"),memberCode:z.string().describe("Code for the new member (method, property, etc.)"),position:z.enum(["start","end","after"]).optional().default("end").describe("Where to insert the member"),afterMember:z.string().optional().describe("Member name to insert after (when position='after')"),preview:z.boolean().optional().default(true).describe("Preview changes before applying"),updateGraph:z.boolean().optional().default(true).describe("Update graph with new member")});var sr=z.object({description:z.string().describe("Description of the snapshot"),files:z.array(z.string()).optional().describe("Files to include in snapshot (all if not specified)")}),ar=z.object({snapshotId:z.string().describe("Snapshot ID to rollback to")}),cr=z.object({limit:z.number().optional().default(10).describe("Maximum number of snapshots to return")}),lr=z.object({olderThanDays:z.number().optional().default(30).describe("Delete snapshots older than N days")});var dr=z.object({projectPath:z.string().optional().describe("Project directory path"),category:z.enum(["sql_injection","xss","command_injection","path_traversal","ssrf","prototype_pollution","all"]).optional().default("all").describe("Vulnerability category to analyze, or 'all' for full scan"),maxDepth:z.number().optional().default(15).describe("Maximum path depth for flow tracing"),includeTests:z.boolean().optional().default(false).describe("Include test files in analysis"),offset:z.number().optional().default(0).describe("Number of vulnerabilities to skip (for pagination)"),limit:z.number().optional().default(20).describe("Maximum vulnerabilities to return (max 200)")});var Vi=[{name:"trace_flow",description:"[PLAN] Static analysis: trace execution from A\u2192B. Use when: 'How does code get from login() to saveUser()?', 'What paths lead to handleError()?'. Finds ALL possible paths with state changes, conditions, async boundaries. Returns confidence-scored paths + optional Mermaid diagrams. Supports highlightRecentChanges to annotate recently modified nodes. Example: trace_flow(from='handleRequest', to='sendEmail', highlightRecentChanges=true). \u{1F4D6} get_help(topic='tracing') for guide.",inputSchema:{type:"object",properties:{from:{type:"string",description:"Starting point (function/method name or semantic query)"},to:{type:"string",description:"Ending point (function/method name or semantic query)"},trackStates:{type:"boolean",description:"Track state changes along paths",default:true},trackConditions:{type:"boolean",description:"Track conditions/branches",default:true},maxDepth:{type:"number",description:"Maximum traversal depth",default:15},format:{type:"string",enum:["sequence","tree","graph","mermaid"],description:"Output format",default:"sequence"},highlightRecentChanges:{type:"boolean",description:"Annotate trace nodes with recently-changed status (Prolly Tree)",default:false},recentCommitsCount:{type:"number",description:"Number of recent commits to consider for highlighting",default:10},projectPath:{type:"string",description:"Project directory path. If not specified, uses current project. Supports absolute paths or relative to CWD."}},required:["from","to"]}},{name:"trace_backwards",description:"[PLAN] Static analysis: why isn't method called? Use when: 'Why doesn't processPayment() run?', 'What blocks saveUser()?'. Questions: 'why_not_called' (find blockers), 'what_affects' (dependencies), 'dependencies' (full graph). Returns callers, blocking conditions, state deps, diagnosis. Supports highlightRecentChanges to annotate recently modified callers. Example: trace_backwards(target='sendNotification', question='why_not_called', highlightRecentChanges=true). \u{1F4D6} get_help(topic='tracing').",inputSchema:{type:"object",properties:{target:{type:"string",description:"Target method/function to analyze"},question:{type:"string",enum:["why_not_called","what_affects","dependencies"],description:"Type of analysis"},depth:{type:"number",description:"Backward traversal depth",default:15},includeStates:{type:"boolean",description:"Include state dependencies",default:true},includeEffects:{type:"boolean",description:"Include side effects",default:true},highlightRecentChanges:{type:"boolean",description:"Annotate trace nodes with recently-changed status (Prolly Tree)",default:false},recentCommitsCount:{type:"number",description:"Number of recent commits to consider for highlighting",default:10},projectPath:{type:"string",description:"Project directory path. If not specified, uses current project. Supports absolute paths or relative to CWD."}},required:["target","question"]}},{name:"trace_data_flow",description:"[PLAN] Static analysis: trace data flow from sources\u2192target state. Use when: 'How does user input affect isValid?', 'What data feeds into price calculation?'. Identifies sources, transformations, branching, builds behavior matrix. Example: trace_data_flow(entryPoint='handleSubmit', targetState='form.errors'). \u{1F4D6} get_help(topic='tracing').",inputSchema:{type:"object",properties:{entryPoint:{type:"string",description:"Entry point function"},targetState:{type:"string",description:"Target state to trace"},dataSources:{type:"array",items:{type:"string"},description:"Data sources to analyze (auto-detected if not specified)"},trackTransformations:{type:"boolean",description:"Track data transformations",default:true},projectPath:{type:"string",description:"Project directory path. If not specified, uses current project. Supports absolute paths or relative to CWD."}},required:["entryPoint","targetState"]}},{name:"analyze_state_impact",description:"[PLAN] Analyze the impact of a state variable across different scenarios. Shows usages, reachable/blocked paths per scenario, conflicts, and ripple effects.",inputSchema:{type:"object",properties:{state:{type:"string",description:"State variable to analyze"},scenarios:{type:"array",items:{type:"object",properties:{value:{},label:{type:"string"}},required:["value","label"]},description:"Scenarios to analyze",minItems:1},scope:{type:"string",description:"Scope of analysis (semantic query)"},projectPath:{type:"string",description:"Project directory path. If not specified, uses current project. Supports absolute paths or relative to CWD."}},required:["state","scenarios"]}},{name:"find_decision_points",description:"[PLAN] Find all decision points in a scenario's execution flow. Types: validation, api_response, state_mutation, guard, loop, error_handling, feature_flag. Returns grouped by impact with Mermaid flowchart.",inputSchema:{type:"object",properties:{scenario:{type:"string",description:"Scenario to analyze"},includeGuards:{type:"boolean",description:"Include guard conditions",default:true},includeEffects:{type:"boolean",description:"Include side effects",default:true},groupBy:{type:"string",enum:["impact","location","type"],description:"How to group results",default:"impact"},projectPath:{type:"string",description:"Project directory path. If not specified, uses current project. Supports absolute paths or relative to CWD."}},required:["scenario"]}}];function g(o){let e=z.toJSONSchema(o);return e.type||(e.type="object"),e}function we(){return [{name:"get_help",description:"[INFO] Get detailed documentation and guides about UltraCode. Essential reading before using tools. Topics: 'quick-start', 'tool-reference', 'workflows', 'tracing', 'autodoc', 'patterns', 'security'. Agent-specific: 'explore' (fast search), 'planning' (risk assessment), 'modification' (safe code changes). Use category matching your role for optimized guidance.",inputSchema:g(z.object({topic:z.enum(["quick-start","tool-reference","workflows","tracing","autodoc","explore","planning","modification","patterns","security"]).describe("Documentation topic to read. Use explore/planning/modification for agent-specific guides.")}))},{name:"get_tools_for_task",description:"[INFO] Recommend relevant tools for your task. Describe what you want to do (e.g. 'find duplicates', 'refactor safely', 'understand data flow') and get ranked tool suggestions. Optionally specify your agent type (explore/plan/modify) for filtered recommendations. Returns top 10 tools with scores and reasons.",inputSchema:g(z.object({task:z.string().describe("What you want to do (e.g. 'find duplicates', 'trace execution path')"),agentType:z.enum(["explore","plan","modify","analyze","any"]).optional().describe("Your agent type for filtered recommendations")}))},{name:"index",description:"[INDEX] \u26A0\uFE0F USUALLY NOT NEEDED! GitWatcher indexes automatically: incremental on file changes, full on branch switch and first setup. Manual call only to force full reindex or if indexing failed. Multi-agent parsing for TS/JS/Python/Go/Rust/Java/C++. Example: index(directory='D:\\\\project'). \u{1F4D6} get_help(topic='quick-start').",inputSchema:g(qn)},{name:"clean_index",description:"[INDEX] Reset graph and then perform a full index",inputSchema:g($n)},{name:"get_members",description:"[EXPLORE] List parsed entities within a single file (imports, functions, classes, etc.); use as the entry point to discover stable entity identifiers before running relationship queries.",inputSchema:g(Nn)},{name:"list_entity_relationships",description:"[EXPLORE] List outgoing relationships for an entity (imports, references, containment). Provide either the entity id (preferred) or name+file path to inspect its dependencies.",inputSchema:g(jn)},{name:"query",description:"[EXPLORE] Query the code graph using natural language or structured queries",inputSchema:g(Un)},{name:"semantic_search",description:"[EXPLORE] Search codebase by MEANING using natural language (5-10x faster than Grep). Understands 'auth functions', 'error handlers', 'API endpoints'. Returns rich metadata: complexity, control flow, documentation status. Supports filters: minCyclomatic, hasExceptions, hasAwaits, hasDocumentation. Supports changedInLastCommits/changedSinceMs to narrow to recently changed code. Examples: 'data processing minCyclomatic=10' (complex code), 'API hasAwaits=true changedInLastCommits=5' (recently changed async code). \u{1F4D6} Run get_help(topic='quick-start') for full guide.",inputSchema:g(a$h)},{name:"find_similar_code",description:"[EXPLORE] Find code similar to a given snippet using semantic analysis",inputSchema:g(b$d)},{name:"cross_language_search",description:"[EXPLORE] Search across multiple programming languages",inputSchema:g(g$2)},{name:"pattern_search",description:"[EXPLORE] Advanced multi-mode search: entity (regex on names/types), content (search inside code), semantic (meaning), hybrid (combined). Framework-aware (filter by React/Vue/Angular). SIMD-accelerated. Supports changedInLastCommits/changedSinceMs history filters. Use when semantic_search isn't enough. Examples: pattern_search(pattern='handle.*Error', mode='entity'), pattern_search(pattern='useState', mode='content', changedInLastCommits=5). \u{1F4D6} get_help(topic='tool-reference').",inputSchema:g(h$2)},{name:"analyze_code_impact",description:"[PLAN] Impact analysis: what breaks if I change X? Find all entities/files depending on a symbol. Use BEFORE refactoring/deletion to prevent regressions. Supports highlightRecentChanges to annotate volatile dependencies. Workflow: 1) get_members(file='utils.ts') to get entity IDs, 2) analyze_code_impact(entityId='...', highlightRecentChanges=true). Returns dependent files, functions, risk score, volatility ratio. \u{1F4D6} get_help(topic='workflows').",inputSchema:g(d$7)},{name:"find_duplicates",description:"[ANALYZE] Find duplicate or similar code blocks across the codebase using semantic similarity",inputSchema:g(e$3)},{name:"jscpd_detect_clones",description:"[ANALYZE] Run JSCPD clone detection using a lightweight tokenizer",inputSchema:g(In)},{name:"suggest_refactoring",description:"[ANALYZE] Get refactoring suggestions for improving code quality",inputSchema:g(kn)},{name:"analyze_hotspots",description:"[PLAN] Find code hotspots based on complexity, changes, or coupling",inputSchema:g(On)},{name:"find_related_concepts",description:"[ANALYZE] Find conceptually related code to a given entity",inputSchema:g(f$3)},{name:"analyze_state_chaos",description:"[ANALYZE] Analyze state management chaos in any codebase (TypeScript, C#, etc.). Detects scattered state, race conditions, C# anti-patterns (async-void, mutable-static, god-service), and suggests refactoring strategies.",inputSchema:g(Ln)},{name:"analyze_swagger_impact",description:"[PLAN] Analyze impact of Swagger/OpenAPI spec changes. Shows affected controllers (producers), generated clients (consumers), and generated types. Assesses breaking change risk. Use before modifying swagger files or controllers that produce API. \u{1F4D6} get_help(topic='workflows').",inputSchema:g(c$b)},{name:"graph_metrics",description:"[PLAN] Graph-based architecture metrics: PageRank (entity importance), Louvain (community/module detection), centrality (hub/authority/bridge roles), bus factor (knowledge concentration risk). Use persist=true to store PageRank/Louvain in entity metadata for semantic search boosting. Workflow: graph_metrics({metric:'pagerank', topN:10}) \u2192 top-10 most important entities.",inputSchema:g(Fn)},{name:"detect_technology_stack",description:"[EXPLORE] Automatically detect languages, frameworks, build tools, and dependencies. Useful for understanding project context. Can generate tech context for embeddings.",inputSchema:g(c$c)},{name:"detect_patterns",description:"[ANALYZE] Detect anti-patterns, best-patterns, code smells, and optimization opportunities. Uses structural analysis + semantic validation (embedding similarity with curated examples) to dramatically reduce false positives. Supports 100+ rules across 6 languages. Filters: category, tags, severity, minConfidence. Categories: anti-pattern (bad practices), best-pattern (good practices), code-smell (structural issues), optimization (performance improvements with Big-O). Example: detect_patterns({category:'optimization', tags:['performance']}). \u{1F4D6} get_help(topic='patterns')",inputSchema:g(a$i)},{name:"check_entity_patterns",description:"[ANALYZE] Check specific entity for anti-patterns, best-patterns, and optimization opportunities. Returns matched patterns with confidence scores, Big-O analysis, and improvement suggestions.",inputSchema:g(b$e)},{name:"taint_analysis",description:"[SECURITY] Interprocedural taint analysis: trace untrusted data from sources (req.body, process.env, fetch) to sinks (eval, exec, innerHTML, db.query) and detect missing sanitization. Categories: sql_injection, xss, command_injection, path_traversal, ssrf, prototype_pollution. Returns vulnerability flows with severity, confidence, and fix suggestions. Supports offset/limit pagination for large results. Example: taint_analysis({category:'sql_injection', offset:0, limit:10}).",inputSchema:g(dr)},{name:"get_graph",description:"[INFO] Get the code graph with all entities and relationships",inputSchema:g(zn)},{name:"get_graph_stats",description:"[INFO] Get statistics about the code graph",inputSchema:g(Gn)},{name:"reset_graph",description:"[SYSTEM] Clear all graph data (entities, relationships, files)",inputSchema:g(z.object({}))},{name:"get_graph_health",description:"[INFO] Health check for graph storage (totals + sample)",inputSchema:g(Bn)},{name:"get_metrics",description:"[INFO] Get system metrics and agent performance statistics",inputSchema:g(z.object({}))},{name:"get_version",description:"[INFO] Get MCP server version information and runtime details",inputSchema:g(z.object({}))},{name:"get_agent_metrics",description:"[INFO] Collect runtime telemetry for conductor and registered agents",inputSchema:g(Vn)},{name:"get_bus_stats",description:"[INFO] Inspect knowledge bus statistics (topics, entries, subscriptions)",inputSchema:g(Hn)},{name:"clear_bus_topic",description:"[SYSTEM] Remove cached knowledge entries for a specific topic",inputSchema:g(Wn)},{name:"get_watcher_status",description:"[INFO] Get FileWatcher and GitWatcher status for diagnostics. Shows if background workers are running for incremental parsing and embedding generation.",inputSchema:{type:"object",properties:{},required:[]}},{name:"create_snapshot",description:"[MODIFY] Create a version snapshot for rollback. Uses git stash if available, otherwise .backup/ directory. Returns snapshot ID for rollback.",inputSchema:g(sr)},{name:"undo",description:"[MODIFY] Rollback to a previous snapshot by ID. Restores all files to their snapshot state.",inputSchema:g(ar)},{name:"list_snapshots",description:"[MODIFY] List available snapshots with creation time and description.",inputSchema:g(cr)},{name:"cleanup_snapshots",description:"[MODIFY] Delete old snapshots to free disk space.",inputSchema:g(lr)},{name:"modify_code",description:"[MODIFY] Safe code modification with auto-snapshot, validation, rollback. Modifies specific entity by ID (get ID via get_members first). Preview mode by default (no changes). Set apply=true for real changes. Workflow: 1) get_members(file='...'), 2) modify_code(entityId='...', newCode='...', preview=false, apply=true). Auto-validates syntax, updates embeddings. \u{1F4D6} get_help(topic='workflows').",inputSchema:g(Kn)},{name:"copy_file",description:"[MODIFY] Copy file or directory with automatic graph updates. Streaming for large files. Token-efficient alternative to reading full content.",inputSchema:g(Zn)},{name:"rename_file",description:"[MODIFY] Rename file with automatic import updates across project. Updates graph and embeddings. Token-efficient alternative to read-write pattern.",inputSchema:g(er)},{name:"split_file",description:"[MODIFY] Extract entities from a file into separate files. Useful for refactoring large files. Updates graph with new locations.",inputSchema:g(tr)},{name:"synthesize_files",description:"[MODIFY] Combine multiple files into one. Merges entities in graph. Can optionally delete originals. Token-efficient way to consolidate code.",inputSchema:g(nr)},{name:"create_file",description:"[MODIFY] Create a new file with content. Automatically parses and adds entities to graph. Unified naming with UltrasharpTools.",inputSchema:g(rr)},{name:"rename_symbol",description:"[MODIFY] Safe rename across project: updates ALL references automatically. Works on variables, functions, classes, etc. Find via entity ID (get_members) or name+file. Creates snapshot before changes. Example: rename_symbol(entityName='oldName', newName='newName', filePath='src/utils.ts'). Much safer than manual find-replace. \u{1F4D6} get_help(topic='workflows').",inputSchema:g(ir)},{name:"add_member",description:"[MODIFY] Add a new member (method, property, field) to a class or interface. Supports precise positioning. Unified naming with UltrasharpTools.",inputSchema:g(or)},{name:"validate_file",description:"[ANALYZE] Validate code file using appropriate linter (oxlint for JS/TS, Pylint for Python). Supports automatic fixes with fixable parameter and auto-detection of linter based on project config (biome.json, .eslintrc). Returns problems categorized by severity.",inputSchema:g(a$j)},{name:"validate_directory",description:"[ANALYZE] Validate all code files in directory with batch processing. Supports automatic fixes with fixable parameter and auto-detection of linter. Returns aggregated validation report.",inputSchema:g(b$f)},{name:"semantic_merge",description:"[MERGE] AI-powered semantic merge of git branches. Automatically finds merge-base, reads files from branches, performs semantic 3-way merge, and writes results as unstaged changes. Supports dry-run mode and auto-resolve.",inputSchema:g(Yn)},{name:"analyze_merge_conflicts",description:"[MERGE] Analyze potential merge conflicts between two branches without performing the merge. Returns conflicts with severity classification and affected code units.",inputSchema:g(Xn)},{name:"get_merge_suggestions",description:"[MERGE] Get AI-generated suggestions for resolving a specific merge conflict. Requires conflict ID from analyze_merge_conflicts.",inputSchema:g(Jn)},{name:"get_semantic_merge_info",description:"[MERGE] Get information about semantic merge capabilities, supported features, and usage examples.",inputSchema:g(Qn)},{name:"autodoc_init",description:"[DOC] Initialize AutoDoc semantic documentation layer. Configure language, docs directory, and enable/disable.",inputSchema:g(a$k)},{name:"autodoc_save",description:"[DOC] Save a markdown documentation file. Parses sections, extracts references to code entities, and indexes for search.",inputSchema:g(b$g)},{name:"autodoc_get",description:"[DOC] Get documentation by ID or file path. Returns parsed sections with metadata.",inputSchema:g(c$d)},{name:"autodoc_search",description:"[DOC] Search documentation by text query. Returns matching sections with relevance scores.",inputSchema:g(d$8)},{name:"autodoc_validate",description:"[DOC] Validate documentation references. Checks that all code entity references point to existing entities.",inputSchema:g(e$4)},{name:"autodoc_status",description:"[DOC] Get AutoDoc status including statistics on documents, references, and broken links.",inputSchema:g(f$4)},{name:"autodoc_sync",description:"[DOC] Sync documentation with code changes. Validates references and marks outdated docs.",inputSchema:g(g$3)},{name:"autodoc_generate",description:"[DOC] Auto-generate documentation for the codebase. Creates .autodoc/ for general docs and README.md in each module folder.",inputSchema:g(h$3)},{name:"autodoc_changelog",description:"[DOC] View documentation change history. Shows what docs were affected by code changes.",inputSchema:g(i$1)},{name:"autodoc_install_hooks",description:"[DOC] Install or uninstall git pre-commit hooks for documentation validation. Ensures references are valid before commits.",inputSchema:g(j)},{name:"autodoc_detect_language",description:"[DOC] Detect documentation language from code comments and existing docs. Supports en, ru, zh.",inputSchema:g(k)},...qi,...Vi,{name:"get_entity_history",description:"[HISTORY] Get change history for a specific entity across commits. Shows when entity was added, modified, or deleted.",inputSchema:g(a$l)},{name:"diff_commits",description:"[HISTORY] Compare two graph commits and show differences (added, modified, deleted entities).",inputSchema:g(b$h)},{name:"checkout_commit",description:"[HISTORY] View graph state at a specific commit (time travel). Retrieve entity snapshots from historical versions.",inputSchema:g(c$e)},{name:"list_commits",description:"[HISTORY] List graph commits (version history). Shows commit hashes, messages, entity counts, and timestamps.",inputSchema:g(d$9)}]}R();var Cs=z.object({filePath:z.string(),projectPath:a,entityTypes:z.array(z.string()).optional(),offset:z.number().optional().default(0),limit:z.number().optional().default(a$1.entities)}),ct=class extends d$3{parseArgs(e){return Cs.parse(e)}async execute(e){let t=this.context.normalizeInputPath(e.filePath),n=await this.ensureGraphStorageForProject(e.projectPath),r={filePath:t};e.entityTypes&&(r.entityType=e.entityTypes);let s=await n.findEntities({filters:r,limit:5e3}),a=Math.min(e.limit,200),c=b$6(s,e.offset,a);return {content:[{type:"text",text:JSON.stringify({file:t,count:c.data.length,pagination:c.pagination,entities:c.data.map(l=>({id:l.id,name:l.name,type:l.type,location:l.location,signature:l.metadata?.signature}))},null,2)}]}}},As=z.object({entityId:z.string().optional(),entityName:z.string().optional(),projectPath:a,relationshipTypes:z.array(z.string()).optional(),direction:z.enum(["incoming","outgoing","both"]).optional().default("both"),offset:z.number().optional().default(0),limit:z.number().optional().default(a$1.relationships)}),lt=class extends d$3{parseArgs(e){return As.parse(e)}async execute(e){let t=await this.ensureGraphStorageForProject(e.projectPath),n=e.entityId,r="provided";if(!n&&e.entityName){let d=await t.findEntities({filters:{name:e.entityName},limit:1});I.w("TOOL","list_rels_findEntity",{name:e.entityName,found:d.length,sample:d.slice(0,3).map(u=>({id:u.id?.slice(0,12),name:u.name,type:u.type,file:u.filePath?.split(/[/\\]/).pop()}))}),d.length>0&&d[0]&&(n=d[0].id,r="byName");}if(!n)return I.w("TOOL","list_rels_not_found",{entityId:e.entityId,entityName:e.entityName}),{content:[{type:"text",text:JSON.stringify({error:"Entity not found"})}]};I.w("TOOL","list_rels_query",{entityId:n.slice(0,16),resolvedFrom:r,direction:e.direction});let s=await t.getRelationshipsForEntity(n);I.w("TOOL","list_rels_result",{entityId:n.slice(0,16),totalRels:s.length,sample:s.slice(0,5).map(d=>({from:d.fromId?.slice(0,12),to:d.toId?.slice(0,12),type:d.type}))});let a=s;e.direction==="outgoing"?a=s.filter(d=>d.fromId===n):e.direction==="incoming"&&(a=s.filter(d=>d.toId===n)),e.relationshipTypes&&(a=a.filter(d=>e.relationshipTypes.includes(d.type)));let c=Math.min(e.limit,200),l=b$6(a,e.offset,c);return {content:[{type:"text",text:JSON.stringify({entityId:n,count:l.data.length,pagination:l.pagination,relationships:l.data},null,2)}]}}},vs=z.object({query:z.string(),projectPath:a,type:z.enum(["entities","relationships","both"]).optional().default("both"),offset:z.number().optional().default(0),limit:z.number().optional().default(50)}),dt=class extends d$3{parseArgs(e){return vs.parse(e)}async execute(e){let t=await this.ensureGraphStorageForProject(e.projectPath),n=Math.min(e.limit,200),r={},s={};if(e.type==="entities"||e.type==="both"){let a=await t.searchEntities({namePattern:e.query,limit:1e3}),c=b$6(a,e.offset,n);r.entities=c.data,s.entities=c.pagination;}if(e.type==="relationships"||e.type==="both"){let a=await t.findRelationships({filters:{},limit:1e3}),c=b$6(a,e.offset,n);r.relationships=c.data,s.relationships=c.pagination;}return {content:[{type:"text",text:JSON.stringify({query:e.query,entitiesFound:r.entities?.length||0,relationshipsFound:r.relationships?.length||0,pagination:s,results:r},null,2)}]}}};var Ts=z.object({task:z.string().describe("Description of what you want to do (e.g. 'find duplicates', 'refactor safely')"),agentType:z.enum(["explore","plan","modify","analyze","any"]).optional().describe("Your agent type for filtered recommendations")}),pt=class extends d$3{parseArgs(e){return Ts.parse(e)}async execute(e){let{task:t,agentType:n}=e,r=we(),s=t.toLowerCase(),a=[],c=p=>{let m=p.match(/^\[([^\]]+)\]/);return !m||!m[1]?[]:[m[1]]},l={"find duplicates":{keywords:["duplicate","similar","clone"],tools:["semantic_search","find_duplicates","jscpd_detect_clones"]},"refactor safely":{keywords:["refactor","safe","impact"],tools:["analyze_code_impact","create_snapshot","modify_code","rename_symbol"]},search:{keywords:["search","find","locate"],tools:["semantic_search","pattern_search","find_similar_code"]},"understand flow":{keywords:["flow","trace","path","execution"],tools:["trace_flow","trace_backwards","trace_data_flow"]},rename:{keywords:["rename"],tools:["rename_symbol","rename_file"]},"check impact":{keywords:["impact","break","depend","affect"],tools:["analyze_code_impact","trace_backwards"]},modify:{keywords:["modify","change","edit"],tools:["modify_code","create_snapshot","analyze_code_impact"]},complex:{keywords:["complex","hotspot","technical debt"],tools:["analyze_hotspots","semantic_search"]},"find anti-patterns":{keywords:["anti-pattern","antipattern","bad practice","smell","code smell"],tools:["detect_patterns","analyze_hotspots"]},"optimize performance":{keywords:["optimize","performance","slow","fast","speed","memory"],tools:["detect_patterns","analyze_hotspots"]},"code quality":{keywords:["quality","pattern","best practice","review"],tools:["detect_patterns","suggest_refactoring","analyze_hotspots"]},"security analysis":{keywords:["security","taint","vulnerability","injection","xss","sanitize"],tools:["taint_analysis","detect_patterns"]},"architecture metrics":{keywords:["pagerank","community","bus factor","centrality","metric","important","architecture"],tools:["graph_metrics","analyze_hotspots"]}};for(let p of r){let m=0,h=[],v=c(p.description),A=p.description.toLowerCase(),C=s.split(/\s+/).filter(f=>f.length>3);for(let f of C)(A.includes(f)||p.name.includes(f))&&(m+=3,h.push(`matches '${f}'`));for(let[f,_]of Object.entries(l))_.keywords.some(T=>s.includes(T))&&_.tools.includes(p.name)&&(m+=5,h.push(`recommended for '${f}'`));if(n&&n!=="any"){let _={explore:["EXPLORE","INFO"],plan:["PLAN","ANALYZE"],modify:["MODIFY"],analyze:["ANALYZE"]}[n]||[];v.some(S=>_.includes(S))&&(m+=2,h.push(`matches agent type '${n}'`));}p.name==="index"&&s.includes("start")&&(m+=10,h.push("required first step")),p.name==="get_help"&&(m+=1),m>0&&a.push({name:p.name,description:p.description,tags:v,score:m,reason:h.join(", ")});}a.sort((p,m)=>m.score-p.score);let u=a.slice(0,10).map((p,m)=>({rank:m+1,tool:p.name,tags:p.tags,score:p.score,reason:p.reason,description:p.description.substring(0,200)+(p.description.length>200?"...":"")}));return {content:[{type:"text",text:JSON.stringify({success:true,task:t,agentType:n||"any",recommendations:u,tip:u.length===0?"No specific tools found. Try 'semantic_search' or 'get_help' for general guidance.":`Found ${u.length} relevant tools. Start with #1 (highest score).`},null,2)}]}}};R();var Ds=z.object({projectPath:a}),ut=class extends d$3{parseArgs(e){return Ds.parse(e)}async execute(e){return await(await this.ensureGraphStorageForProject(e.projectPath)).clear(),{content:[{type:"text",text:JSON.stringify({success:true,message:"Graph reset completed"})}]}}},Es=z.object({directory:z.string().optional(),projectPath:a}),mt=class extends d$3{parseArgs(e){return Es.parse(e)}async execute(e){let t=this.resolveProjectPath(e);if(await(await this.ensureGraphStorageForProject(t)).clear(),process.env.MCP_DEBUG_DISABLE_SEMANTIC!=="1")try{let d=(await this.ensureSemanticAgentForProject(t))?.getVectorStore?.();d&&await d.clear();}catch(l){let d=a$8(l);I.w("CLEANINDEX","sem_reinit_fail",{err:d.message,stack:d.stack});}let r=this.context.getConductor();await r.initialize();let s=r.getAgentByType?.("dev");if(!s)throw new Error("DevAgent not available for indexing");let a={id:`clean-index-${Date.now()}`,type:"index",priority:9,payload:{directory:t,incremental:false,excludePatterns:[]},createdAt:Date.now()},c=await s.process(a);return {content:[{type:"text",text:JSON.stringify({success:true,message:"Clean index completed",result:c},null,2)}]}}},Ps=z.object({projectPath:a,entityTypes:z.array(z.string()).optional(),offset:z.number().optional().default(0),limit:z.number().optional().default(a$1.graphNodes),includeRelationships:z.boolean().optional().default(true)}),gt=class extends d$3{parseArgs(e){return Ps.parse(e)}async execute(e){let t=await this.ensureGraphStorageForProject(e.projectPath),n=Math.min(e.limit,200),r=await t.findEntities({filters:e.entityTypes?{entityType:e.entityTypes}:{},limit:5e3}),s=b$6(r,e.offset,n),a={data:[],pagination:{offset:0,limit:0,total:0,hasMore:false}};if(e.includeRelationships&&s.data.length>0){let c=s.data.map(d=>d.id),l=await t.findRelationships({filters:{fromId:c},limit:5e3});a=b$6(l,0,n);}return {content:[{type:"text",text:JSON.stringify({entities:s.data.length,relationships:a.data.length,pagination:{entities:s.pagination,relationships:a.pagination},data:{entities:s.data,relationships:a.data}},null,2)}]}}},Ms=z.object({projectPath:a}),ht=class extends d$3{parseArgs(e){return Ms.parse(e)}async execute(e){let t=await this.ensureGraphStorageForProject(e.projectPath),n=await t.getStatistics(),r=null;try{let s=t;typeof s.getCooccurrenceOps=="function"&&(r=await s.getCooccurrenceOps().getStats());}catch{}return {content:[{type:"text",text:JSON.stringify({...n,cooccurrence:r},null,2)}]}}},Rs=z.object({projectPath:a}),ft=class extends d$3{parseArgs(e){return Rs.parse(e)}async execute(e){let t=await this.ensureGraphStorageForProject(e.projectPath),n=await t.getStatistics(),r=this.context.getSQLiteManager(),s;try{let c=await t.getAllEntities(),l=c.filter(d=>d.metadata?.swaggerType==="api_spec");if(l.length>0){let d=[],p=(await t.getAllRelationships()).filter(h=>h.type==="generated_from");for(let h of l){let v=h.updatedAt;for(let A of p)if(A.metadata?.toFile===h.filePath||A.toId.includes(h.filePath)){let C=c.find(f=>f.id===A.fromId);C&&v>C.updatedAt&&d.push(`Generated code may be out of sync: ${h.filePath} updated after ${C.filePath}`);}}let m=l.filter(h=>h.metadata?.isActiveContract).length;s={swaggerFilesFound:l.length,activeContracts:m,staleWarnings:d};}}catch{}let a={status:"healthy",database:{path:r?.getDatabasePath?.()||"unknown",entities:n.totalEntities||0,relationships:n.totalRelationships||0,files:n.totalFiles||0}};return s&&(a.swagger=s),{content:[{type:"text",text:JSON.stringify(a,null,2)}]}}};var Xi=z.object({topic:z.enum(["quick-start","tool-reference","workflows","tracing","autodoc","explore","planning","modification","patterns","security"]).describe("Documentation topic")}),yt=class extends d$3{parseArgs(e){return Xi.parse(e)}async execute(e){let{topic:t}=Xi.parse(e);try{let n=dirname(fileURLToPath(import.meta.url)),r=join(n,".."),s=join(r,"prompts"),c={"quick-start":"quick-start.md","tool-reference":"tool-reference.md",workflows:"workflows.md",tracing:"tracing-guide.md",autodoc:"autodoc-guide.md",explore:"explore-guide.md",planning:"planning-guide.md",modification:"modification-guide.md",patterns:"patterns-guide.md",security:"security-guide.md"}[t];if(!c)throw new Error(`Unknown topic: ${t}`);let l=join(s,c),d=readFileSync(l,"utf-8");return {content:[{type:"text",text:JSON.stringify({success:!0,topic:t,documentation:d,message:`\u{1F4D6} ${t} documentation loaded. Read this guide to understand how to use UltraCode effectively.`},null,2)}]}}catch(n){let r=n instanceof Error?n.message:String(n);return {content:[{type:"text",text:JSON.stringify({success:false,error:`Failed to load documentation for topic '${t}': ${r}`,availableTopics:["quick-start","tool-reference","workflows","tracing","autodoc","explore","planning","modification","patterns","security"]},null,2)}]}}}};R();var Ls=[".ts",".tsx",".js",".jsx",".py",".go",".rs",".kt",".swift",".c",".cpp",".java",".cs"],Ns=z.object({directory:z.string().optional(),incremental:z.boolean().optional().default(false),reset:z.boolean().optional().default(false),excludePatterns:z.array(z.string()).optional().default([]),fullScan:z.boolean().optional().default(false)}),St=class extends d$3{parseArgs(e){return Ns.parse(e)}async execute(e){let t=this.resolveProjectPath(e);if(Cn()){let a=et();return {content:[{type:"text",text:JSON.stringify({success:false,error:"Indexing already in progress",currentDirectory:a.directory,elapsedSeconds:a.elapsedSeconds,message:"Please wait for the current indexing operation to complete"},null,2)}]}}let n=this.context.createAutoIndexContext(),r=this.getExtensions(),s=await Me(t,r,n,{incremental:e.incremental,reset:e.reset,extraExcludePatterns:e.excludePatterns?.length?e.excludePatterns:void 0,fullScan:e.fullScan});return this.formatResult(s)}getExtensions(){return this.context.config.indexing?.autoIndexExtensions??Ls}formatResult(e){let t={success:e.success,message:e.success?"Indexing completed":"Indexing completed with warnings",entityCount:e.entityCount,durationMs:e.duration};return e.embeddingStats&&(t.embeddings=e.embeddingStats),e.embeddingPerformance&&(t.embeddingPerformance=e.embeddingPerformance),e.oversizedWarning?.aiMessage&&(t.warning=e.oversizedWarning.aiMessage,t.oversizedEntities={count:e.oversizedWarning.oversizedCount,maxTokens:e.oversizedWarning.maxTokens}),I.i("INDEXTOOL","index_complete",{dir:"via_auto_indexer",entities:e.entityCount,durMs:e.duration}),{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}};R();var js=z.object({includeSystem:z.boolean().optional().default(true),includeGraph:z.boolean().optional().default(true),includeAgents:z.boolean().optional().default(false)}),bt=class extends d$3{parseArgs(e){return js.parse(e)}async execute(e){let t={timestamp:new Date().toISOString()};if(e.includeSystem){let{memoryUsage:n}=await import('process'),r=n();t.system={memory:{heapUsed:Math.round(r.heapUsed/1024/1024),heapTotal:Math.round(r.heapTotal/1024/1024),external:Math.round(r.external/1024/1024),rss:Math.round(r.rss/1024/1024),unit:"MB"},uptime:Math.round(process.uptime()),nodeVersion:process.version};}if(e.includeGraph)try{let r=await(await this.context.getGraphStorage()).getStatistics();t.graph=r;}catch{t.graph={error:"Graph storage not available"};}if(e.includeAgents){let n=this.context.getConductor();t.agents=n.getAllAgentMetrics();}return {content:[{type:"text",text:JSON.stringify(t,null,2)}]}}},Us=z.object({detailed:z.boolean().optional().default(false)}),wt=class extends d$3{parseArgs(e){return Us.parse(e)}async execute(e){let{readJSON:t}=await import('./chunks/file-ops-HXOTPMZ7.js'),{join:n}=await import('path');try{let r=this.resolveProjectPath({}),s=n(r,"package.json"),a="unknown",c="ultracode";try{let d=await t(s);a=d.version||a,c=d.name||c;}catch{}let l={name:c,version:a};return e.detailed&&(l.details={nodeVersion:process.version,platform:process.platform,arch:process.arch,pid:process.pid,cwd:process.cwd()},l.features={semanticSearch:!0,multiLanguage:!0,branchManagement:!!await this.context.getBranchManager(),snapshots:!!this.context.getSnapshotManager()}),{content:[{type:"text",text:JSON.stringify(l,null,2)}]}}catch(r){let s=a$8(r);return {content:[{type:"text",text:JSON.stringify({error:s.message})}]}}}},Fs=z.object({agentType:z.string().optional(),includeHistory:z.boolean().optional().default(false)}),_t=class extends d$3{parseArgs(e){return Fs.parse(e)}async execute(e){let n=this.context.getConductor().getAllAgentMetrics(),r;e.agentType?r=n[e.agentType]??{error:`Agent '${e.agentType}' not found`}:r=n;let s=Date.now()-300*1e3,a=Object.values(n),c={totalAgents:Object.keys(n).length,activeAgents:a.filter(l=>l.lastActivity>s).length,totalTasksProcessed:a.reduce((l,d)=>l+d.tasksProcessed,0)};return {content:[{type:"text",text:JSON.stringify({summary:c,agents:r},null,2)}]}}},zs=z.object({topic:z.string().optional(),includeMessages:z.boolean().optional().default(false),messageLimit:z.number().optional().default(10)}),xt=class extends d$3{parseArgs(e){return zs.parse(e)}async execute(e){let t=this.context.getKnowledgeBus();if(!t)return {content:[{type:"text",text:JSON.stringify({error:"Knowledge bus not available"})}]};let n=t.getStats?.()||{topicCount:0,entryCount:0,subscriptionCount:0,messageQueueSize:0},r={totalTopics:n.topicCount,totalMessages:n.entryCount,topics:{summary:{topicCount:n.topicCount,entryCount:n.entryCount,subscriptionCount:n.subscriptionCount,messageQueueSize:n.messageQueueSize}}};if(e.topic&&(r.topics[e.topic]={info:"Topic-specific stats not available in current API"}),e.includeMessages&&t.getRecentMessages){let s=await t.getRecentMessages();r.recentMessages=s;}return {content:[{type:"text",text:JSON.stringify(r,null,2)}]}}},Gs=z.object({topic:z.string(),confirm:z.boolean().optional().default(false)}),Ct=class extends d$3{parseArgs(e){return Gs.parse(e)}async execute(e){if(!e.confirm)return {content:[{type:"text",text:JSON.stringify({warning:"This will clear all messages in the topic",topic:e.topic,hint:"Set confirm: true to proceed"})}]};let t=this.context.getKnowledgeBus();if(!t)return {content:[{type:"text",text:JSON.stringify({error:"Knowledge bus not available"})}]};try{return await t.clearTopic?.(e.topic),{content:[{type:"text",text:JSON.stringify({success:!0,topic:e.topic,message:"Topic cleared successfully"})}]}}catch(n){let r=a$8(n);return {content:[{type:"text",text:JSON.stringify({error:r.message})}]}}}},Bs=z.object({}),At=class extends d$3{parseArgs(e){return Bs.parse(e)}async execute(e){try{let{AgentType:t}=await import('./chunks/agent-6ZDOOVGS.js'),r=this.context.getConductor().getAgentByType?.(t.DEV);I.d("METRICS","watcher_status_diag",{hasDevAgent:!!r,hasGetIndexerAgent:!!r?.getIndexerAgent});let s=r?.getIndexerAgent?.()??void 0;I.d("METRICS","watcher_status_diag2",{hasIndexerAgent:!!s,indexerAgentType:s?typeof s:"undefined"});let a={timestamp:new Date().toISOString(),indexerAgentExists:!!s,fileWatcher:null,gitWatcher:null,repositoryPath:null};if(s){a.fileWatcher=s.getFileWatcherStatus?.()??{exists:!1,reason:"Method not available"};let c=s.getGitWatcher?.();c?a.gitWatcher={exists:!0,isWatching:c.isWatching?.()??!1,currentBranch:c.getBranch?.()??"unknown"}:a.gitWatcher={exists:!1};let l=s.getBranchManager?.();a.branchManager={exists:!!l},a.repositoryPath=s.currentRepositoryPath??null,a.indexingStats=s.getIndexingStats?.()??{};}return {content:[{type:"text",text:JSON.stringify(a,null,2)}]}}catch(t){let n=a$8(t);return {content:[{type:"text",text:JSON.stringify({error:n.message,stack:n.stack?.split(`
|
|
37
|
-
`).slice(0,5)})}]}}}};var
|
|
31
|
+
`);}function _i(o){let e=fileURLToPath(o),t=dirname(e),n=join(t,"..","scripts");if(existsSync(n)||(n=join(t,"scripts")),process.platform==="win32"){let s=join(n,"setup-semantic-embedding.ps1");if(existsSync(s)){let a=spawnSync("pwsh",["-ExecutionPolicy","Bypass","-File",s],{stdio:"inherit",windowsHide:true});if(a.error){let c=spawnSync("powershell",["-ExecutionPolicy","Bypass","-File",s],{stdio:"inherit",windowsHide:true});process.exit(c.status??1);}else process.exit(a.status??0);}else console.error(`Setup script not found: ${s}`),process.exit(1);}else {let s=join(n,"setup-embeddings-interactive.sh");if(existsSync(s)){let a=spawnSync("bash",[s],{stdio:"inherit"});process.exit(a.status??0);}else console.error(`Setup script not found: ${s}`),process.exit(1);}process.exit(1);}g$1();R();var N={TRACE:-1,DEBUG:0,INFO:1,WARN:2,ERROR:3,CRITICAL:4},xi=Object.fromEntries(Object.entries(N).map(([o,e])=>[e,o]));H();var qo=10*1024*1024,Ci={logDir:d(),maxFileSize:qo,maxFiles:20,logLevel:N.TRACE,enableRotation:true,enableTimestamp:true,enableStackTrace:true};R();R();H();var Zo=Ci,Cn=class{config;currentLogFile;logDir;buf=[];BUF_CAP=50;STALE_MS=500;lastDrain=Date.now();constructor(e={}){this.config={...Zo,...e},this.logDir=resolve(this.config.logDir),this.ensureDir(),this.currentLogFile=this.logFilePath();}flushSync(){if(this.buf.length===0)return;this.shouldRotate()&&(this.rotate(),this.currentLogFile=this.logFilePath());let e=this.buf.join("");this.buf.length=0,this.lastDrain=Date.now();try{appendFileSync(this.currentLogFile,e,"utf8");}catch(t){console.error("Failed to write log (sync):",t);}}flushAsync(){if(this.buf.length===0)return;this.shouldRotate()&&(this.rotate(),this.currentLogFile=this.logFilePath());let e=this.buf.join("");this.buf.length=0,this.lastDrain=Date.now(),appendFile(this.currentLogFile,e).catch(t=>{console.error("Failed to write log:",t);});}stopFlushLoop(){this.flushSync();}flush(){this.flushSync();}registerExitHandlers(){let e=()=>this.flushSync();process.on("exit",e),process.on("SIGINT",e),process.on("SIGTERM",e),process.on("uncaughtException",t=>{this.error("PROCESS","Uncaught exception",{error:t.message,stack:t.stack}),this.flushSync();});}ensureDir(){existsSync(this.logDir)||mkdirSync(this.logDir,{recursive:true});}logFilePath(){let e=new Date().toLocaleDateString("sv");return join(this.logDir,`mcp-server-${e}.log`)}shouldRotate(){return !this.config.enableRotation||!existsSync(this.currentLogFile)?false:statSync(this.currentLogFile).size>=this.config.maxFileSize}rotate(){if(!existsSync(this.currentLogFile))return;let e=new Date().toISOString().replace(/[:.]/g,"-"),t=this.currentLogFile.replace(".log",`-${e}.log`);try{renameSync(this.currentLogFile,t),this.pruneOld();}catch(n){console.error("Failed to rotate log file:",n);}}pruneOld(){try{let e=readdirSync(this.logDir).filter(t=>t.startsWith("mcp-server-")&&t.endsWith(".log")).map(t=>{let n=join(this.logDir,t);return {name:t,path:n,mtime:statSync(n).mtime}}).sort((t,n)=>n.mtime.getTime()-t.mtime.getTime());for(let t=this.config.maxFiles;t<e.length;t++)try{unlinkSync(e[t].path);}catch(n){console.error(`Failed to delete old log file ${e[t].name}:`,n);}}catch(e){console.error("Failed to cleanup old logs:",e);}}format(e){let t=this.config.enableTimestamp?`[${e.timestamp}] `:"",n=`[${xi[e.level]??"UNKNOWN"}]`,r=`[${e.category}]`,s=e.requestId?` [${e.requestId}]`:"",a=e.data!==void 0&&e.data!==null?` DATA: ${JSON.stringify(e.data,null,2)}`:"",c=e.duration!==void 0?` DURATION: ${e.duration}ms`:"",l=e.stackTrace&&this.config.enableStackTrace?` STACK: ${e.stackTrace}`:"";return `${t}${n} ${r}${s} ${e.message}${a}${c}${l}
|
|
32
|
+
`}writeLog(e){if(e.level<this.config.logLevel)return;this.buf.push(this.format(e));let t=Date.now();(this.buf.length>=this.BUF_CAP||t-this.lastDrain>=this.STALE_MS)&&(this.flushAsync(),this.lastDrain=t);}trace(e,t,n,r){this.log(N.TRACE,e,t,n,r);}traceTime(e,t,n,r){let s=Date.now()-n,a=process.uptime()*1e3;this.log(N.TRACE,e,`[+${a.toFixed(0)}ms] ${t} (${s}ms)`,r);}traceStart(e,t){let n=Date.now(),r=process.uptime()*1e3;return this.log(N.TRACE,e,`[+${r.toFixed(0)}ms] \u25B6 START: ${t}`),()=>{let s=Date.now()-n,a=process.uptime()*1e3;this.log(N.TRACE,e,`[+${a.toFixed(0)}ms] \u25C0 END: ${t} (${s}ms)`);}}debug(e,t,n,r){this.log(N.DEBUG,e,t,n,r);}info(e,t,n,r){this.log(N.INFO,e,t,n,r);}warn(e,t,n,r){this.log(N.WARN,e,t,n,r);}error(e,t,n,r,s){let a=s?.stack||(this.config.enableStackTrace?new Error().stack:void 0);this.log(N.ERROR,e,t,n,r,a);}critical(e,t,n,r,s){let a=s?.stack||(this.config.enableStackTrace?new Error().stack:void 0);this.log(N.CRITICAL,e,t,n,r,a);}log(e,t,n,r,s,a){this.writeLog({timestamp:this.localIso(),level:e,category:t,message:n,data:r,stackTrace:a,requestId:s});}localIso(){let e=new Date,t=e.getTimezoneOffset(),r=new Date(e.getTime()-t*6e4).toISOString().slice(0,-1),s=-t,a=s>=0?"+":"-",c=Math.abs(s),l=String(Math.floor(c/60)).padStart(2,"0"),d=String(c%60).padStart(2,"0");return `${r}${a}${l}:${d}`}mcpRequest(e,t,n){this.info("MCP_REQUEST",`Incoming MCP request: ${e}`,{method:e,params:t},n);}mcpResponse(e,t,n,r){this.writeLog({timestamp:new Date().toISOString(),level:N.INFO,category:"MCP_RESPONSE",message:`MCP response: ${e}`,data:{method:e,result:t},requestId:r,duration:n});}mcpError(e,t,n){this.error("MCP_ERROR",`MCP request failed: ${e}`,{method:e,error:t.message},n,t);}agentActivity(e,t,n,r){this.debug("AGENT_ACTIVITY",`Agent ${e}: ${t}`,{agentId:e,...n},r);}parseActivity(e,t,n,r,s){this.info("PARSE_ACTIVITY",`Parsed ${e}`,{filePath:e,language:t,entitiesFound:n,duration:r},s);}queryActivity(e,t,n,r){this.info("QUERY_ACTIVITY","Query executed",{query:e.substring(0,200),results:t,duration:n},r);}performanceMetrics(e,t,n){this.debug("PERFORMANCE",`Performance metrics for ${e}`,t,n);}systemEvent(e,t){this.info("SYSTEM",e,t);}incident(e,t,n,r){r?this.error("INCIDENT",e,{...t,error:r.message},n,r):this.warn("INCIDENT",e,t,n);}recovery(e,t,n){this.info("RECOVERY",e,t,n);}},es=new Cn;es.registerExitHandlers();function Pe(){return `req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}function Ti(){G$1({logDir:d(),minLevel:"I",consoleOutput:false});}function Di(o){F$1().setProjectHash(o);}var ne=new Map,Ze=null,ts=o=>{};function ns(){return false}function rs(){}function An(){return ne.size>0}function Ei(o){let e=o.toLowerCase().replace(/\\/g,"/");for(let[t]of ne)if(t.toLowerCase().replace(/\\/g,"/")===e)return true;return false}function et(){if(ne.size===0)return {inProgress:false,directory:null,elapsedSeconds:null,allProjects:[]};let[o,e]=ne.entries().next().value||[null,null];return {inProgress:true,directory:o,elapsedSeconds:e?Math.round((Date.now()-e.startTime)/1e3):null,allProjects:Array.from(ne.keys())}}function tt(o,e){let t=e||Ze||"unknown";o?(ne.set(t,{startTime:Date.now(),directory:t}),Ze=t):(ne.delete(t),Ze===t&&(Ze=null),ne.size===0&&void 0);}var Pi=["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/out/**","**/.next/**","**/.nuxt/**","**/coverage/**","**/__pycache__/**","**/.pytest_cache/**","**/venv/**","**/.venv/**","**/vendor/**","**/target/**","**/bin/**","**/obj/**","**/.vs/**","**/.idea/**","**/.vscode/**","**/packages/**","**/fixtures/**","**/testdata/**","**/mocks/**","**/__mocks__/**","**/external-tools/**","**/third_party/**","**/third-party/**","**/thirdparty/**","**/archives/**","**/archive/**","**/backups/**","**/backup/**","**/tmp/**","**/temp/**"];async function vn(o,e){try{let{glob:t}=await import('./chunks/esm-TZ6IXGRA.js'),r=`**/*.{${e.map(a=>a.replace(/^\./,"")).join(",")}}`,s=await t(r,{cwd:o,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.git/**","**/vendor/**","**/target/**","**/__pycache__/**"],maxDepth:5,absolute:!1});if(s.length>0){let a=s[0];return {supported:!0,detectedExt:"."+a.split(".").pop(),sampleFile:a}}return {supported:!1}}catch(t){return I.w("AUTOINDEX","detect_fail",{err:t.message}),{supported:false}}}async function Mi(o,e){try{let{glob:t}=await import('./chunks/esm-TZ6IXGRA.js'),r=`**/*.{${e.map(a=>a.replace(/^\./,"")).join(",")}}`;return (await t(r,{cwd:o,nodir:!0,ignore:Pi,stat:!1,absolute:!1})).length}catch{return -1}}async function is(o){let e=[...Pi,"**/*.mock.json","**/*.mock.ts","**/*.mock.js","**/*.zip","**/*.tar","**/*.tar.gz","**/*.tgz","**/*.rar","**/*.7z","**/*.exe","**/*.dll","**/*.so","**/*.dylib","**/*.bin","**/*.iso","**/*.img","**/*.dmg","**/*.wasm","**/*.min.js","**/*.min.css","**/*.bundle.js","**/*.chunk.js","**/package-lock.json","**/yarn.lock","**/pnpm-lock.yaml","**/*.lock","**/*.jpg","**/*.jpeg","**/*.png","**/*.gif","**/*.ico","**/*.svg","**/*.mp3","**/*.mp4","**/*.wav","**/*.avi","**/*.mov","**/*.pdf","**/*.db","**/*.sqlite","**/*.sqlite3"];try{let{join:t}=await import('path'),n=t(o,".gitignore"),{readTextSync:r,existsSync:s}=await import('./chunks/file-ops-HXOTPMZ7.js');if(s(n)){let c=r(n).split(`
|
|
33
|
+
`);for(let l of c){let d=l.trim();if(!d||d.startsWith("#")||d.startsWith("!"))continue;let u=d;u.endsWith("/")?u=`**/${u}**`:u.includes("/")?!u.startsWith("/")&&!u.startsWith("**/")&&(u=`**/${u}`):u=`**/${u}`,u.startsWith("/")&&(u=u.slice(1)),e.push(u);}I.d("AUTOINDEX","gitignore_loaded",{cnt:c.filter(l=>l.trim()&&!l.startsWith("#")).length});}}catch{}return e}async function Me(o,e,t,n){let r=typeof n=="boolean"?{incremental:n}:n??{},s=r.incremental??false,a=Pe(),c=Date.now();I.t("INDEXER","auto_index_start",{offset:c-t.processStartTime}),tt(true,o);let l=s?"incremental":"full";I.i("INDEXER","auto_index",{mode:l,dir:o,req:a});let d=0,u,p,m,h=true;try{if(r.reset){let S=await t.getGraphStorage();S.setProject(o),await S.clear(),I.d("INDEXER","storage_cleared",{dir:o});}let v=await is(o);if(r.extraExcludePatterns?.length&&v.push(...r.extraExcludePatterns),I.d("INDEXER","exclude_patterns",{cnt:v.length,exts:e.join(",")}),t.setCurrentIndexingDirectory(o),process.env.MCP_DEBUG_DISABLE_SEMANTIC!=="1"){I.t("INDEXER","semantic_init_start",{});try{let S=Date.now(),T=await t.getSemanticAgent();I.t("INDEXER","semantic_init_done",{dur:Date.now()-S}),s?I.d("INDEXER","keep_index",{reason:"incremental"}):(I.t("INDEXER","drop_index_start",{}),await T.dropVectorIndex(),I.t("INDEXER","drop_index_done",{}));}catch(S){I.w("INDEXER","semantic_init_fail",{err:S.message});}}let A={id:`auto-index-${Date.now()}`,type:"index",priority:8,payload:{directory:o,incremental:s,excludePatterns:v,includeExtensions:e},createdAt:Date.now()},C=await t.getDevAgent();await t.getDoraAgent();let f=await C.process(A),_=((Date.now()-c)/1e3).toFixed(1);if(f?.success!==!1){let S=f?.entitiesExtracted??f?.data?.entityCount??f?.data?.entities??0;d=typeof S=="number"?S:parseInt(String(S),10)||0,I.i("INDEXER","auto_index_done",{entities:d,dur:Date.now()-c,req:a});try{let b=C?.getEmbeddingStats?.();b&&b.total>0&&(I.i("EMBEDDING","emb_summary",{total:b.total,dur:`${(b.durationMs/1e3).toFixed(1)}s`,speed:`${b.speedPerSec}/s`,workers:b.workers,batches:b.batches}),p={totalEmbeddings:b.total,durationSeconds:Math.round(b.durationMs/1e3*10)/10,embeddingsPerSecond:b.speedPerSec,workersUsed:b.workers});}catch{}if(process.env.MCP_DEBUG_DISABLE_SEMANTIC!=="1")try{let b=(await t.getSemanticAgent()).getLastOversizedWarning?.();b?.hasWarning&&(m={aiMessage:b.aiMessage,oversizedCount:b.oversizedCount,maxTokens:b.maxTokens});}catch{}let T=t,F=o,L=s,Q=d,ae=c;(async()=>{if(process.env.MCP_DEBUG_DISABLE_SEMANTIC!=="1")try{let b=await(await T.getSemanticAgent()).generateEmbeddingsFromStorage();b&&I.i("INDEXER","embed_finalize_bg",{generated:b.generated,skipped:b.skipped});}catch(R){I.w("INDEXER","embed_finalize_fail",{err:R.message});}try{let R=await T.getGraphStorage();if(L){let b=Math.max(1,Math.ceil(Q/3));await R.recordIncrementalChanges(b),I.i("INDEXER","tracking_recorded",{files:b});}else await R.resetIncrementalTracking(),I.i("INDEXER","tracking_reset",{reason:"full_rebuild"});}catch(R){I.w("INDEXER","tracking_fail",{err:R.message});}try{let b=T.getConductor().getAgentByType("dev"),je=b?.getIndexerAgent?.()??void 0;je?.setRepositoryPath?(await je.setRepositoryPath(F),I.i("INDEXER","watcher_started",{dir:F})):I.w("INDEXER","watcher_skip",{reason:b?je?"no setRepositoryPath":"no IndexerAgent":"no DevAgent"});}catch(R){I.w("INDEXER","watcher_fail",{err:R.message});}try{await(await T.getGraphStorage()).flush(),I.d("INDEXER","storage_flushed");}catch(R){I.w("INDEXER","storage_flush_fail",{err:R.message});}a$2.publish("index:completed",{directory:F,incremental:L,entityCount:Q,duration:Date.now()-ae},"auto-indexer"),I.d("INDEXER","post_index_bg_done",{elapsed:Date.now()-ae});})();}else h=!1,I.w("INDEXER","auto_index_warn",{dur:_,req:a});}catch(v){h=false;let A=((Date.now()-c)/1e3).toFixed(1);I.e("INDEXER","auto_index_fail",{dur:A,err:v.message,req:a});}finally{tt(false);}return {success:h,entityCount:d,duration:Date.now()-c,embeddingStats:u,embeddingPerformance:p,oversizedWarning:m}}R();var ds="manifest.json",Ni=".ultracode-installed.json";function ji(){let o=fileURLToPath(import.meta.url),e=dirname(o),t=dirname(e);return join(t,"claude-skills")}function Ui(){return join(homedir(),".claude","skills")}function Fi(){return join(homedir(),".claude")}function Ii(o){let e=o.split(".").map(t=>parseInt(t,10)||0);return (e[0]||0)*1e4+(e[1]||0)*100+(e[2]||0)}function ps(o,e){return Ii(o)-Ii(e)}function us(){let o=join(ji(),ds);if(!existsSync(o))return null;try{let e=readFileSync(o,"utf-8");return JSON.parse(e)}catch{return null}}function ms(){let o=join(Fi(),Ni);if(!existsSync(o))return null;try{let e=readFileSync(o,"utf-8");return JSON.parse(e)}catch{return null}}function gs(o,e){let t=Fi();existsSync(t)||mkdirSync(t,{recursive:true});let n={...o,installedAt:new Date().toISOString(),installedFrom:e},r=join(t,Ni);writeFileSync(r,JSON.stringify(n,null,2),"utf-8");}function hs(o,e){return e?ps(o.version,e.version)>0?{needsUpdate:true,reason:`version_upgrade:${e.version}->${o.version}`}:o.updatedAt!==e.updatedAt?{needsUpdate:true,reason:`content_updated:${e.updatedAt}->${o.updatedAt}`}:{needsUpdate:false,reason:"up_to_date"}:{needsUpdate:true,reason:"not_installed"}}function zi(o,e){existsSync(e)||mkdirSync(e,{recursive:true});let t=readdirSync(o);for(let n of t){let r=join(o,n),s=join(e,n);statSync(r).isDirectory()?zi(r,s):copyFileSync(r,s);}}function fs(o,e){if(!o)return [];let t=Ui(),n=new Set(e.skills.map(s=>s.name)),r=[];for(let s of o.skills)if(!n.has(s.name)){let a=join(t,s.name);if(existsSync(a))try{rmSync(a,{recursive:!0,force:!0}),r.push(s.name);}catch{}}return r}async function Gi(){let o=ji(),e=Ui(),t=us();if(!t)return I.w("SKILLS","manifest_not_found",{path:o}),{action:"skipped",version:"unknown",skills:[],reason:"manifest_not_found"};let n=ms(),r=hs(t,n);if(!r.needsUpdate)return I.t("SKILLS","up_to_date",{version:t.version}),{action:"skipped",version:t.version,skills:t.skills.map(l=>l.name),reason:r.reason};if(!existsSync(e))try{mkdirSync(e,{recursive:!0});}catch(l){return I.e("SKILLS","mkdir_failed",{path:e,err:l.message}),{action:"skipped",version:t.version,skills:[],reason:`mkdir_failed: ${l.message}`}}let s=fs(n,t),a=[];for(let l of t.skills){let d=join(o,l.name),u=join(e,l.name);if(!existsSync(d)){I.w("SKILLS","skill_source_not_found",{skill:l.name});continue}try{existsSync(u)&&rmSync(u,{recursive:!0,force:!0}),zi(d,u),a.push(l.name);}catch(p){I.e("SKILLS","skill_install_failed",{skill:l.name,err:p.message});}}gs(t,o);let c=n?"updated":"installed";return I.i("SKILLS",c,{version:t.version,skills:a,reason:r.reason,removed:s.length>0?s:void 0}),{action:c,version:t.version,skills:a,reason:r.reason,removed:s.length>0?s:void 0}}R();H();var it=class{sessionId;clientId;createdAt;_projectPath;_branch;_indexingInProgress=false;_lastActivityAt;constructor(e){this.sessionId=e.sessionId??bs(),this.clientId=e.clientId??0,this.createdAt=Date.now(),this._lastActivityAt=this.createdAt,this._projectPath=normalize(resolve(e.projectPath)),this._branch=v(this._projectPath),this.ensureProjectInitialized(),I.i("SESSION","created",{sid:this.sessionId,cid:this.clientId,proj:this._projectPath,branch:this._branch});}get projectPath(){return this._projectPath}get branch(){return this._branch}get projectHash(){return q(this._projectPath)}getStoragePaths(){return o(this._projectPath)}getProjectDir(){return n(this._projectPath)}switchProject(e,t){let n=normalize(resolve(e));if(n===this._projectPath&&(!t||t===this._branch))return;let r=this._projectPath,s=this._branch;this._projectPath=n,this._branch=t??v(n),this._lastActivityAt=Date.now(),this.ensureProjectInitialized(),I.i("SESSION","switched",{sid:this.sessionId,from:`${r}@${s}`,to:`${this._projectPath}@${this._branch}`});}resolvePath(e){return e?e.startsWith("/")||/^[A-Za-z]:/.test(e)?normalize(resolve(e)):normalize(resolve(this._projectPath,e)):this._projectPath}get isIndexing(){return this._indexingInProgress}startIndexing(){this._indexingInProgress=true,this._lastActivityAt=Date.now(),I.i("SESSION","indexing_start",{sid:this.sessionId,proj:this._projectPath});}finishIndexing(){this._indexingInProgress=false,this._lastActivityAt=Date.now(),I.i("SESSION","indexing_done",{sid:this.sessionId,proj:this._projectPath});}markActivity(){this._lastActivityAt=Date.now();}get idleTimeMs(){return Date.now()-this._lastActivityAt}getInfo(){return {path:this._projectPath,hash:this.projectHash,branch:this._branch,isIndexed:this.checkProjectIndexed(),lastAccessedAt:this._lastActivityAt}}ensureProjectInitialized(){let e=w(this._projectPath),t=`${e}/session-marker.json`;try{let n={sessionId:this.sessionId,clientId:this.clientId,projectPath:this._projectPath,branch:this._branch,createdAt:new Date(this.createdAt).toISOString(),lastActivityAt:new Date(this._lastActivityAt).toISOString()};writeFileSync(t,JSON.stringify(n,null,2));}catch{}I.t("SESSION","proj_init",{sid:this.sessionId,dir:e});}checkProjectIndexed(){let e=this.getStoragePaths();return existsSync(e.graphDbPath)}},Re=new Map,ot=new Map;function Hi(o){Re.set(o.sessionId,o);let e=o.projectPath,t=ot.get(e);t||(t=new Set,ot.set(e,t)),t.add(o.sessionId),I.i("SESSION","registered",{sid:o.sessionId,total:Re.size});}function Wi(o){let e=Re.get(o);if(e){let t=ot.get(e.projectPath);t&&(t.delete(o),t.size===0&&ot.delete(e.projectPath));}Re.delete(o),I.i("SESSION","unregistered",{sid:o,total:Re.size});}var Bi=0;function bs(){Bi++;let o=Date.now().toString(36),e=Math.random().toString(36).substring(2,6);return `ses-${o}-${e}-${Bi}`}R();function ws(){return process.platform==="win32"?"\\\\.\\pipe\\UltraCode_Core":"/tmp/ultracode-core.sock"}var Pn=class{buffer="";append(e){this.buffer+=e.toString();}readMessage(){let e=this.buffer.indexOf(`
|
|
34
|
+
`);if(e===-1)return null;let t=this.buffer.slice(0,e);return this.buffer=this.buffer.slice(e+1),t.trim()?JSON.parse(t):null}clear(){this.buffer="";}},$i="ULTRACODE_CWD:",st=class{constructor(e){this.socket=e;}readBuffer=new Pn;started=false;onmessage;onerror;onclose;async readInitMessage(e=2e3){if(this.started)throw new Error("readInitMessage must be called before start()");return console.error(`[pipe-transport] readInitMessage started, timeout=${e}ms`),new Promise(t=>{let n=false,r=l=>{clearTimeout(l),this.socket.removeListener("data",a);},s=(l,d)=>{n||(n=true,r(d),t(l));},a=l=>{this.readBuffer.append(l);let d=this.readBuffer.buffer.indexOf(`
|
|
35
|
+
`);if(d===-1)return;let u=this.readBuffer.buffer.slice(0,d),p=this.readBuffer.buffer.slice(d+1);if(u.startsWith($i)){let m=u.slice($i.length).trim();console.error(`[pipe-transport] Got init message, cwd=${m}, remaining=${p.length} bytes`),this.readBuffer.buffer=p,s(m||void 0,c);}else console.error(`[pipe-transport] First line is not init message: ${u.slice(0,50)}...`),s(void 0,c);};this.socket.on("data",a);let c=setTimeout(()=>{console.error(`[pipe-transport] readInitMessage timeout after ${e}ms`),s(void 0,c);},e);})}async start(){if(this.started)throw new Error("PipeClientTransport already started");this.started=true,this.socket.on("data",e=>{this.readBuffer.append(e),this.processReadBuffer();}),this.socket.on("error",e=>{this.onerror?.(e);}),this.socket.on("close",()=>{this.readBuffer.clear(),this.onclose?.();}),this.processReadBuffer();}processReadBuffer(){for(;;)try{let e=this.readBuffer.readMessage();if(e===null)break;this.onmessage?.(e);}catch(e){this.onerror?.(e);}}async close(){this.socket.end(),this.readBuffer.clear(),this.onclose?.();}send(e){return new Promise((t,n)=>{let r=`${JSON.stringify(e)}
|
|
36
|
+
`;this.socket.write(r,s=>{s?n(s):t();});})}},at=class{server=null;pipePath;constructor(e){this.pipePath=e??ws();}async waitForConnection(){if(process.platform!=="win32"&&existsSync(this.pipePath))try{unlinkSync(this.pipePath);}catch{}return new Promise((e,t)=>{this.server=createServer(n=>{let r=new st(n);e(r);}),this.server.on("error",n=>{n.code==="EADDRINUSE"&&(I.e("PIPE","EADDRINUSE: pipe already in use by another server instance, exiting",{pipe:this.pipePath}),process.exit(1)),t(n);}),this.server.listen(this.pipePath);})}async start(e){if(process.platform!=="win32"&&existsSync(this.pipePath))try{unlinkSync(this.pipePath);}catch{}return new Promise((t,n)=>{this.server=createServer(r=>{let s=new st(r);e(s);}),this.server.on("error",r=>{r.code==="EADDRINUSE"&&(I.e("PIPE","EADDRINUSE: pipe already in use by another server instance, exiting",{pipe:this.pipePath}),process.exit(1)),n(r);}),this.server.listen(this.pipePath,()=>{t();});})}async close(){if(this.server&&(this.server.close(),this.server=null),process.platform!=="win32"&&existsSync(this.pipePath))try{unlinkSync(this.pipePath);}catch{}}getPath(){return this.pipePath}};R();var xs=1048576,Mn=o=>Math.round(o/xs);function Cs(){return typeof globalThis.Bun<"u"}var Rn=class{constructor(e){this.capacity=e;this.buf=new Array(e);}buf;head=0;len=0;push(e){this.buf[this.head]=e,this.head=(this.head+1)%this.capacity,this.len<this.capacity&&this.len++;}latest(){if(this.len===0)return null;let e=(this.head-1+this.capacity)%this.capacity;return this.buf[e]}since(e){if(this.len===0)return [];let t=this.len<this.capacity?0:this.head,n=0,r=this.len;for(;n<r;){let a=n+r>>>1,c=(t+a)%this.capacity;this.buf[c].timestamp<e?n=a+1:r=a;}let s=[];for(let a=n;a<this.len;a++)s.push(this.buf[(t+a)%this.capacity]);return s}get size(){return this.len}},In=class o extends EventEmitter{constraints;allocations=new Map;snapshots;monitoring=false;tickTimer;pollingIntervalMs=1e3;static POLL_FLOOR=1e3;static POLL_CEILING=1e4;throttled=false;throttleThreshold=.8;constructor(e){super();let t=ie.totalmem()/(1024*1024*1024),n=ie.cpus().length,r=Math.min(Math.max(4096,Math.floor(t*512)),16384);this.constraints=e??{maxMemoryMB:r,maxCpuPercent:95,maxConcurrentAgents:Math.min(20,n*3),maxTaskQueueSize:200},this.snapshots=new Rn(60),I.i("RESOURCEMGR","init",{memMB:this.constraints.maxMemoryMB,maxAgents:this.constraints.maxConcurrentAgents});}startMonitoring(){this.monitoring||(this.monitoring=true,this.emit("monitoring:started"),!Cs()&&(this.tick(),this.tickTimer=setInterval(()=>this.tick(),2e3)));}stopMonitoring(){this.monitoring&&(this.monitoring=false,this.pollingIntervalMs=1e3,this.tickTimer&&(clearInterval(this.tickTimer),this.tickTimer=void 0),this.emit("monitoring:stopped"));}requestAllocation(e,t,n,r=5){let s=this.sumAllocated();return s.memory+t>this.constraints.maxMemoryMB?(this.emit("allocation:denied",{agentId:e,reason:"memory_exceeded",requested:t,available:this.constraints.maxMemoryMB-s.memory}),false):s.cpu+n>this.constraints.maxCpuPercent?(this.emit("allocation:denied",{agentId:e,reason:"cpu_exceeded",requested:n,available:this.constraints.maxCpuPercent-s.cpu}),false):(this.allocations.set(e,{agentId:e,memoryMB:t,cpuPercent:n,priority:r}),this.emit("allocation:granted",{agentId:e,memoryMB:t,cpuPercent:n}),true)}releaseAllocation(e){let t=this.allocations.get(e);t&&(this.allocations.delete(e),this.emit("allocation:released",t));}getCurrentUsage(){return this.snapshots.latest()}getHistory(e=60){return this.snapshots.since(Date.now()-e*1e3)}isSystemThrottled(){return this.throttled}getAvailableResources(){let e=this.sumAllocated();return {memoryMB:Math.max(0,this.constraints.maxMemoryMB-e.memory),cpuPercent:Math.max(0,this.constraints.maxCpuPercent-e.cpu)}}suggestAllocation(e){let t=this.getAvailableResources();if(t.memoryMB<50||t.cpuPercent<5)return null;let n=e/10;return {memoryMB:Math.min(Math.floor(t.memoryMB*n*.5),256),cpuPercent:Math.min(Math.floor(t.cpuPercent*n*.5),25)}}requestGarbageCollection(){global.gc?(I.i("RESOURCEMGR","gc_forced"),global.gc(),this.emit("gc:completed")):I.w("RESOURCEMGR","gc_not_exposed",{hint:"run with --expose-gc"});}adjustForCodebaseSize(e,t){let n=this.constraints.maxMemoryMB,r=this.constraints.maxConcurrentAgents;e>1e4?(n=Math.min(this.constraints.maxMemoryMB*3,16384),r=2,I.i("RESOURCEMGR","xlarge_codebase",{files:e,memMB:n,agents:r})):e>5e3?(n=Math.min(this.constraints.maxMemoryMB*2,12288),r=Math.max(4,Math.floor(r/2)),I.i("RESOURCEMGR","vlarge_codebase",{files:e,memMB:n,agents:r})):e>2e3&&(n=Math.min(this.constraints.maxMemoryMB*1.5,8192),I.i("RESOURCEMGR","large_codebase",{files:e,memMB:n})),this.constraints.maxMemoryMB=n,this.constraints.maxConcurrentAgents=r;let s={fileCount:e,projectSizeMB:t,newMemoryLimit:n,newAgentLimit:r};this.emit("resources:adjusted",s),a$2.publish("resources:adjusted",s,"resource-manager",6e4);}getConstraints(){return {...this.constraints}}tick(){if(!this.monitoring)return;this.captureSnapshot();let e=this.evaluatePressure();e>.8?this.pollingIntervalMs=o.POLL_FLOOR:e<.3?this.pollingIntervalMs=Math.min(o.POLL_CEILING,Math.round(this.pollingIntervalMs*1.5)):this.pollingIntervalMs=2e3;}captureSnapshot(){let e=ie.totalmem(),t=ie.freemem(),n=e-t,r=ie.cpus().length,s={timestamp:Date.now(),memory:{total:Mn(e),used:Mn(n),free:Mn(t),percentage:n/e*100},cpu:{cores:r,usage:this.estimateCpuUsage(),loadAverage:ie.loadavg()},io:{pendingReads:0,pendingWrites:0}};this.snapshots.push(s),this.emit("snapshot:captured",s);}estimateCpuUsage(){let e=ie.loadavg(),t=Array.isArray(e)&&typeof e[0]=="number"?e[0]:0,n=ie.cpus().length||1;return Math.min(100,t/n*100)}evaluatePressure(){let e=this.getCurrentUsage();if(!e)return 0;let t=e.memory.percentage/100,n=e.cpu.usage/100,r=Math.max(t,n),s=this.throttleThreshold*100,a=e.memory.percentage>s,c=e.cpu.usage>s,l=a||c;return l&&!this.throttled?(this.throttled=true,I.w("RESOURCEMGR","throttle_on",{mem:a,cpu:c}),this.emit("throttle:enabled",{memory:a,cpu:c}),a&&this.requestGarbageCollection()):!l&&this.throttled&&(this.throttled=false,I.i("RESOURCEMGR","throttle_off"),this.emit("throttle:disabled")),e.memory.percentage>90&&this.emit("memory:critical",e.memory),e.cpu.usage>90&&this.emit("cpu:critical",e.cpu),r}sumAllocated(){let e=0,t=0;for(let n of this.allocations.values())e+=n.memoryMB,t+=n.cpuPercent;return {memory:e,cpu:t}}},Ie=new In;H();z.object({repositoryPath:z.string().optional().describe("Path to Git repository (defaults to current directory)")});z.object({branch:z.string().describe("Name of the branch to switch to"),repositoryPath:z.string().optional().describe("Path to Git repository (defaults to current directory)")});z.object({repositoryPath:z.string().optional().describe("Path to Git repository (defaults to current directory)")});z.object({keep:z.number().optional().describe("Number of most recently used branches to keep (defaults to config value)")});z.object({fromBranch:z.string().describe("Source branch name"),toBranch:z.string().describe("Target branch name")});var Vi=[{name:"list_branches",description:"[BRANCH] List all indexed branches for the current repository. Shows branch names, last accessed time, database size, and metadata (entity count, last commit, etc.).",inputSchema:{type:"object",properties:{repositoryPath:{type:"string",description:"Path to Git repository (defaults to current directory)"}}}},{name:"switch_branch",description:"[BRANCH] Switch active branch for indexing. Changes the database context to the specified branch. Note: You may need to reindex if switching to a branch that hasn't been indexed yet.",inputSchema:{type:"object",properties:{branch:{type:"string",description:"Name of the branch to switch to"},repositoryPath:{type:"string",description:"Path to Git repository (defaults to current directory)"}},required:["branch"]}},{name:"get_branch_status",description:"[BRANCH] Get detailed status of the current branch including last commit hash, entity count, relationship count, and database information.",inputSchema:{type:"object",properties:{repositoryPath:{type:"string",description:"Path to Git repository (defaults to current directory)"}}}},{name:"cleanup_branches",description:"[BRANCH] Cleanup old branch databases using LRU eviction strategy. Removes least recently used branches while keeping the specified number of most recent branches.",inputSchema:{type:"object",properties:{keep:{type:"number",description:"Number of most recently used branches to keep (defaults to config value)"}}}},{name:"get_changed_files",description:"[BRANCH] Get list of files changed between two branches. Useful for determining scope of changes before switching branches or for incremental reindexing.",inputSchema:{type:"object",properties:{fromBranch:{type:"string",description:"Source branch name"},toBranch:{type:"string",description:"Target branch name"}},required:["fromBranch","toBranch"]}}];var kn=z.object({paths:z.array(z.string()).nonempty().optional().describe("Directories or files to scan. Relative paths resolve against the server root."),pattern:z.string().optional().describe("Glob pattern to apply within each path (default **/*)."),ignore:z.array(z.string()).optional().describe("Glob patterns to exclude from scanning."),formats:z.array(z.string().regex(/^[^.]+$/)).optional().describe("File extensions to include without dots (e.g. ['ts','js'])."),minLines:z.number().int().min(1).optional().describe("Minimum lines per clone block."),maxLines:z.number().int().min(1).optional().describe("Maximum lines per clone block."),minTokens:z.number().int().min(1).optional().describe("Minimum tokens per clone (interpreted as lines)."),ignoreCase:z.boolean().optional().describe("Lowercase tokens before comparison.")}),On=z.object({filePath:z.string().describe("File to analyze for refactoring"),focusArea:z.string().optional().describe("Specific entity name to focus on"),entityId:z.string().optional().describe("Exact entity ID to analyze"),startLine:z.number().int().min(1).optional().describe("1-based start line for manual selection"),endLine:z.number().int().min(1).optional().describe("1-based end line (exclusive)")}).refine(o=>o.startLine==null&&o.endLine==null||o.startLine!=null&&o.endLine!=null&&o.startLine<o.endLine,{message:"startLine and endLine must both be provided and startLine < endLine",path:["startLine"]}),Ln=z.object({metric:z.enum(["complexity","changes","coupling","all"]).optional().default("complexity").describe("Metric: complexity, changes, coupling, or all"),limit:z.number().optional().default(10).describe("Maximum hotspots to return"),includeHistoricalMetrics:z.boolean().optional().default(true).describe("Use Prolly Tree history for changeFrequency calculation"),lookbackDays:z.number().optional().default(30).describe("Number of days to look back for change frequency")}),Nn=z.object({projectPath:z.string().optional().describe("Project directory path"),scope:z.enum(["file","module","project"]).optional().default("project").describe("Analysis scope"),stateIdentifiers:z.array(z.string()).optional().describe("Specific state identifiers to analyze (e.g., ['token', 'userId'])"),autoDetect:z.boolean().optional().default(true).describe("Automatically detect state patterns"),format:z.enum(["summary","detailed","json"]).optional().default("summary").describe("Output format: summary (AI-friendly), detailed (human), json (raw)"),maxDepth:z.number().optional().default(10).describe("Maximum trace depth"),excludePatterns:z.array(z.string()).optional().describe("File patterns to exclude")});var jn=z.object({filePath:z.string().describe("Path to the file to list entities from"),entityTypes:z.array(z.string()).describe("Types of entities to list").optional(),projectPath:a}),Un=z.object({entityId:z.string().optional().describe("Exact entity ID to find relationships for"),entityName:z.string().optional().describe("Name of the entity to find relationships for"),filePath:z.string().optional().describe("Optional file path hint to disambiguate entity"),depth:z.number().optional().default(1).describe("Depth of relationship traversal"),relationshipTypes:z.array(z.string()).optional().describe("Types of relationships to include"),projectPath:a}).refine(o=>!!(o.entityId||o.entityName),{message:"Provide either entityId or entityName",path:["entityId"]}),Fn=z.object({query:z.string().describe("Natural language or structured query"),limit:z.number().describe("Maximum number of results").optional().default(10),branch:z.string().optional().describe("Branch name (null = main branch)"),projectPath:a});var zn=z.object({projectPath:z.string().optional().describe("Project directory path"),metric:z.enum(["pagerank","louvain","centrality","bus_factor"]).describe("Type of graph metric to compute"),topN:z.number().optional().default(20).describe("Number of top results to return (for pagerank, centrality)"),minCommunitySize:z.number().optional().default(2).describe("Minimum community size to include (for louvain)"),persist:z.boolean().optional().default(false).describe("Persist computed metrics to entity metadata for use in semantic search ranking")});var Gn=z.object({query:z.string().optional().describe("Optional search query"),limit:z.number().optional().default(100).describe("Maximum entities to return"),projectPath:a}),Bn=z.object({projectPath:a}),Hn=z.object({minEntities:z.number().optional().default(1).describe("Minimum entity count for healthy status"),minRelationships:z.number().optional().default(0).describe("Minimum relationship count for healthy status"),sample:z.number().optional().default(1).describe("Sample size to fetch for verification"),projectPath:a}),Wn=z.object({}),qn=z.object({topic:z.string().min(1).describe("Exact knowledge bus topic to clear (use wildcards via knowledgeBus.query for inspection)")});var Yi=["node_modules/**",".git/**","dist/**","build/**","out/**",".next/**",".nuxt/**","coverage/**",".nyc_output/**","__pycache__/**","*.pyc",".pytest_cache/**","venv/**","env/**",".venv/**",".env/**","vendor/**","target/**",".gradle/**",".idea/**",".vscode/**","**/.memory_bank/**","tmp/**","temp/**","**/tmp/**","**/temp/**","*.log","*.tmp","*.cache","**/*.md","*.zip","*.tar","*.tar.gz","*.tgz","*.gz","*.bz2","*.xz","*.7z","*.rar","*.zst",".DS_Store","Thumbs.db"],$n=z.object({directory:z.string().describe("Directory to index").optional(),incremental:z.boolean().describe("Perform incremental indexing").optional().default(false),reset:z.boolean().describe("Clear existing graph before indexing").optional().default(false),excludePatterns:z.array(z.string()).describe("Patterns to exclude").optional().default(Yi),fullScan:z.boolean().optional().default(false)}),Vn=z.object({directory:z.string().describe("Directory to index after reset").optional(),excludePatterns:z.array(z.string()).describe("Patterns to exclude during indexing").optional().default([]),fullScan:z.boolean().optional().default(false)}),Yn=z.object({});var Xn=z.object({sourceBranch:z.string().describe("Source branch name (where changes come from), e.g. 'feature/caching'"),targetBranch:z.string().optional().describe("Target branch name (where to merge), e.g. 'main'. Defaults to current branch."),dryRun:z.boolean().optional().default(true).describe("Preview only, don't apply changes (default: true)"),autoResolve:z.boolean().optional().default(false).describe("Auto-resolve compatible conflicts (default: false)"),includeAISuggestions:z.boolean().optional().default(true).describe("Generate AI suggestions for conflicts (default: true)")}),Jn=z.object({branchA:z.string().describe("First branch name"),branchB:z.string().describe("Second branch name")}),Qn=z.object({conflictId:z.string().describe("ID of the conflict to get suggestions for (from analyze_merge_conflicts)"),branchA:z.string().describe("First branch name"),branchB:z.string().describe("Second branch name")}),Kn=z.object({});var Zn=z.object({entityId:z.string().describe("ID of entity to modify"),newCode:z.string().describe("New code to replace entity"),preserveComments:z.boolean().optional().default(true).describe("Preserve leading comments"),updateImports:z.boolean().optional().default(true).describe("Update imports if signature changed"),preview:z.boolean().optional().default(true).describe("Preview changes before applying"),skipValidation:z.boolean().optional().default(false).describe("Skip validation checks")}),er=z.object({source:z.string().describe("Source file or directory path"),target:z.string().describe("Target path"),preview:z.boolean().optional().default(true).describe("Preview before copying"),updateGraph:z.boolean().optional().default(true).describe("Update graph with copied entities")}),tr=z.object({oldPath:z.string().describe("Current file path"),newPath:z.string().describe("New file path"),preview:z.boolean().optional().default(true).describe("Preview before renaming"),updateImports:z.boolean().optional().default(true).describe("Update imports across project"),updateGraph:z.boolean().optional().default(true).describe("Update graph with new paths")}),nr=z.object({filePath:z.string().describe("File to split"),entityIds:z.array(z.string()).describe("Entity IDs to extract to separate files"),preview:z.boolean().optional().default(true).describe("Preview before splitting"),updateGraph:z.boolean().optional().default(true).describe("Update graph with new file locations")}),rr=z.object({files:z.array(z.string()).min(2).describe("Files to combine into one"),targetPath:z.string().describe("Target file path for combined result"),preview:z.boolean().optional().default(true).describe("Preview before synthesizing"),deleteOriginals:z.boolean().optional().default(false).describe("Delete original files after synthesis"),updateGraph:z.boolean().optional().default(true).describe("Update graph with merged entities")}),ir=z.object({filePath:z.string().describe("Absolute path for the new file to create"),content:z.string().describe("Content to write to the file"),createDirectories:z.boolean().optional().default(true).describe("Create parent directories if they don't exist"),updateGraph:z.boolean().optional().default(true).describe("Parse and add entities to graph after creation"),overwrite:z.boolean().optional().default(false).describe("Overwrite file if it already exists")}),or=z.object({entityId:z.string().optional().describe("Entity ID to rename (preferred)"),entityName:z.string().optional().describe("Entity name to rename (if entityId not provided)"),filePath:z.string().optional().describe("File path hint for disambiguation"),newName:z.string().describe("New name for the symbol"),updateReferences:z.boolean().optional().default(true).describe("Update all references to this symbol"),preview:z.boolean().optional().default(true).describe("Preview changes before applying")}),sr=z.object({entityId:z.string().optional().describe("Parent entity ID (class/interface) to add member to"),filePath:z.string().describe("File path where to add the member"),memberCode:z.string().describe("Code for the new member (method, property, etc.)"),position:z.enum(["start","end","after"]).optional().default("end").describe("Where to insert the member"),afterMember:z.string().optional().describe("Member name to insert after (when position='after')"),preview:z.boolean().optional().default(true).describe("Preview changes before applying"),updateGraph:z.boolean().optional().default(true).describe("Update graph with new member")});var ar=z.object({description:z.string().describe("Description of the snapshot"),files:z.array(z.string()).optional().describe("Files to include in snapshot (all if not specified)")}),cr=z.object({snapshotId:z.string().describe("Snapshot ID to rollback to")}),lr=z.object({limit:z.number().optional().default(10).describe("Maximum number of snapshots to return")}),dr=z.object({olderThanDays:z.number().optional().default(30).describe("Delete snapshots older than N days")});var pr=z.object({projectPath:z.string().optional().describe("Project directory path"),category:z.enum(["sql_injection","xss","command_injection","path_traversal","ssrf","prototype_pollution","all"]).optional().default("all").describe("Vulnerability category to analyze, or 'all' for full scan"),maxDepth:z.number().optional().default(15).describe("Maximum path depth for flow tracing"),includeTests:z.boolean().optional().default(false).describe("Include test files in analysis"),offset:z.number().optional().default(0).describe("Number of vulnerabilities to skip (for pagination)"),limit:z.number().optional().default(20).describe("Maximum vulnerabilities to return (max 200)")});var Xi=[{name:"trace_flow",description:"[PLAN] Static analysis: trace execution from A\u2192B. Use when: 'How does code get from login() to saveUser()?', 'What paths lead to handleError()?'. Finds ALL possible paths with state changes, conditions, async boundaries. Returns confidence-scored paths + optional Mermaid diagrams. Supports highlightRecentChanges to annotate recently modified nodes. Example: trace_flow(from='handleRequest', to='sendEmail', highlightRecentChanges=true). \u{1F4D6} get_help(topic='tracing') for guide.",inputSchema:{type:"object",properties:{from:{type:"string",description:"Starting point (function/method name or semantic query)"},to:{type:"string",description:"Ending point (function/method name or semantic query)"},trackStates:{type:"boolean",description:"Track state changes along paths",default:true},trackConditions:{type:"boolean",description:"Track conditions/branches",default:true},maxDepth:{type:"number",description:"Maximum traversal depth",default:15},format:{type:"string",enum:["sequence","tree","graph","mermaid"],description:"Output format",default:"sequence"},highlightRecentChanges:{type:"boolean",description:"Annotate trace nodes with recently-changed status (Prolly Tree)",default:false},recentCommitsCount:{type:"number",description:"Number of recent commits to consider for highlighting",default:10},projectPath:{type:"string",description:"Project directory path. If not specified, uses current project. Supports absolute paths or relative to CWD."}},required:["from","to"]}},{name:"trace_backwards",description:"[PLAN] Static analysis: why isn't method called? Use when: 'Why doesn't processPayment() run?', 'What blocks saveUser()?'. Questions: 'why_not_called' (find blockers), 'what_affects' (dependencies), 'dependencies' (full graph). Returns callers, blocking conditions, state deps, diagnosis. Supports highlightRecentChanges to annotate recently modified callers. Example: trace_backwards(target='sendNotification', question='why_not_called', highlightRecentChanges=true). \u{1F4D6} get_help(topic='tracing').",inputSchema:{type:"object",properties:{target:{type:"string",description:"Target method/function to analyze"},question:{type:"string",enum:["why_not_called","what_affects","dependencies"],description:"Type of analysis"},depth:{type:"number",description:"Backward traversal depth",default:15},includeStates:{type:"boolean",description:"Include state dependencies",default:true},includeEffects:{type:"boolean",description:"Include side effects",default:true},highlightRecentChanges:{type:"boolean",description:"Annotate trace nodes with recently-changed status (Prolly Tree)",default:false},recentCommitsCount:{type:"number",description:"Number of recent commits to consider for highlighting",default:10},projectPath:{type:"string",description:"Project directory path. If not specified, uses current project. Supports absolute paths or relative to CWD."}},required:["target","question"]}},{name:"trace_data_flow",description:"[PLAN] Static analysis: trace data flow from sources\u2192target state. Use when: 'How does user input affect isValid?', 'What data feeds into price calculation?'. Identifies sources, transformations, branching, builds behavior matrix. Example: trace_data_flow(entryPoint='handleSubmit', targetState='form.errors'). \u{1F4D6} get_help(topic='tracing').",inputSchema:{type:"object",properties:{entryPoint:{type:"string",description:"Entry point function"},targetState:{type:"string",description:"Target state to trace"},dataSources:{type:"array",items:{type:"string"},description:"Data sources to analyze (auto-detected if not specified)"},trackTransformations:{type:"boolean",description:"Track data transformations",default:true},projectPath:{type:"string",description:"Project directory path. If not specified, uses current project. Supports absolute paths or relative to CWD."}},required:["entryPoint","targetState"]}},{name:"analyze_state_impact",description:"[PLAN] Analyze the impact of a state variable across different scenarios. Shows usages, reachable/blocked paths per scenario, conflicts, and ripple effects.",inputSchema:{type:"object",properties:{state:{type:"string",description:"State variable to analyze"},scenarios:{type:"array",items:{type:"object",properties:{value:{},label:{type:"string"}},required:["value","label"]},description:"Scenarios to analyze",minItems:1},scope:{type:"string",description:"Scope of analysis (semantic query)"},projectPath:{type:"string",description:"Project directory path. If not specified, uses current project. Supports absolute paths or relative to CWD."}},required:["state","scenarios"]}},{name:"find_decision_points",description:"[PLAN] Find all decision points in a scenario's execution flow. Types: validation, api_response, state_mutation, guard, loop, error_handling, feature_flag. Returns grouped by impact with Mermaid flowchart.",inputSchema:{type:"object",properties:{scenario:{type:"string",description:"Scenario to analyze"},includeGuards:{type:"boolean",description:"Include guard conditions",default:true},includeEffects:{type:"boolean",description:"Include side effects",default:true},groupBy:{type:"string",enum:["impact","location","type"],description:"How to group results",default:"impact"},projectPath:{type:"string",description:"Project directory path. If not specified, uses current project. Supports absolute paths or relative to CWD."}},required:["scenario"]}}];function g(o){let e=z.toJSONSchema(o);return e.type||(e.type="object"),e}function we(){return [{name:"get_help",description:"[INFO] Get detailed documentation and guides about UltraCode. Essential reading before using tools. Topics: 'quick-start', 'tool-reference', 'workflows', 'tracing', 'autodoc', 'patterns', 'security'. Agent-specific: 'explore' (fast search), 'planning' (risk assessment), 'modification' (safe code changes). Use category matching your role for optimized guidance.",inputSchema:g(z.object({topic:z.enum(["quick-start","tool-reference","workflows","tracing","autodoc","explore","planning","modification","patterns","security"]).describe("Documentation topic to read. Use explore/planning/modification for agent-specific guides.")}))},{name:"get_tools_for_task",description:"[INFO] Recommend relevant tools for your task. Describe what you want to do (e.g. 'find duplicates', 'refactor safely', 'understand data flow') and get ranked tool suggestions. Optionally specify your agent type (explore/plan/modify) for filtered recommendations. Returns top 10 tools with scores and reasons.",inputSchema:g(z.object({task:z.string().describe("What you want to do (e.g. 'find duplicates', 'trace execution path')"),agentType:z.enum(["explore","plan","modify","analyze","any"]).optional().describe("Your agent type for filtered recommendations")}))},{name:"index",description:"[INDEX] \u26A0\uFE0F USUALLY NOT NEEDED! GitWatcher indexes automatically: incremental on file changes, full on branch switch and first setup. Manual call only to force full reindex or if indexing failed. Multi-agent parsing for TS/JS/Python/Go/Rust/Java/C++. Example: index(directory='D:\\\\project'). \u{1F4D6} get_help(topic='quick-start').",inputSchema:g($n)},{name:"clean_index",description:"[INDEX] Reset graph and then perform a full index",inputSchema:g(Vn)},{name:"get_members",description:"[EXPLORE] List parsed entities within a single file (imports, functions, classes, etc.); use as the entry point to discover stable entity identifiers before running relationship queries.",inputSchema:g(jn)},{name:"list_entity_relationships",description:"[EXPLORE] List outgoing relationships for an entity (imports, references, containment). Provide either the entity id (preferred) or name+file path to inspect its dependencies.",inputSchema:g(Un)},{name:"query",description:"[EXPLORE] Query the code graph using natural language or structured queries",inputSchema:g(Fn)},{name:"semantic_search",description:"[EXPLORE] Search codebase by MEANING using natural language (5-10x faster than Grep). Understands 'auth functions', 'error handlers', 'API endpoints'. Returns rich metadata: complexity, control flow, documentation status. Supports filters: minCyclomatic, hasExceptions, hasAwaits, hasDocumentation. Supports changedInLastCommits/changedSinceMs to narrow to recently changed code. Examples: 'data processing minCyclomatic=10' (complex code), 'API hasAwaits=true changedInLastCommits=5' (recently changed async code). \u{1F4D6} Run get_help(topic='quick-start') for full guide.",inputSchema:g(a$h)},{name:"find_similar_code",description:"[EXPLORE] Find code similar to a given snippet using semantic analysis",inputSchema:g(b$d)},{name:"cross_language_search",description:"[EXPLORE] Search across multiple programming languages",inputSchema:g(g$3)},{name:"pattern_search",description:"[EXPLORE] Advanced multi-mode search: entity (regex on names/types), content (search inside code), semantic (meaning), hybrid (combined). Framework-aware (filter by React/Vue/Angular). SIMD-accelerated. Supports changedInLastCommits/changedSinceMs history filters. Use when semantic_search isn't enough. Examples: pattern_search(pattern='handle.*Error', mode='entity'), pattern_search(pattern='useState', mode='content', changedInLastCommits=5). \u{1F4D6} get_help(topic='tool-reference').",inputSchema:g(h$2)},{name:"analyze_code_impact",description:"[PLAN] Impact analysis: what breaks if I change X? Find all entities/files depending on a symbol. Use BEFORE refactoring/deletion to prevent regressions. Supports highlightRecentChanges to annotate volatile dependencies. Workflow: 1) get_members(file='utils.ts') to get entity IDs, 2) analyze_code_impact(entityId='...', highlightRecentChanges=true). Returns dependent files, functions, risk score, volatility ratio. \u{1F4D6} get_help(topic='workflows').",inputSchema:g(d$8)},{name:"find_duplicates",description:"[ANALYZE] Find duplicate or similar code blocks across the codebase using semantic similarity",inputSchema:g(e$3)},{name:"jscpd_detect_clones",description:"[ANALYZE] Run JSCPD clone detection using a lightweight tokenizer",inputSchema:g(kn)},{name:"suggest_refactoring",description:"[ANALYZE] Get refactoring suggestions for improving code quality",inputSchema:g(On)},{name:"analyze_hotspots",description:"[PLAN] Find code hotspots based on complexity, changes, or coupling",inputSchema:g(Ln)},{name:"find_related_concepts",description:"[ANALYZE] Find conceptually related code to a given entity",inputSchema:g(f$3)},{name:"analyze_state_chaos",description:"[ANALYZE] Analyze state management chaos in any codebase (TypeScript, C#, etc.). Detects scattered state, race conditions, C# anti-patterns (async-void, mutable-static, god-service), and suggests refactoring strategies.",inputSchema:g(Nn)},{name:"analyze_swagger_impact",description:"[PLAN] Analyze impact of Swagger/OpenAPI spec changes. Shows affected controllers (producers), generated clients (consumers), and generated types. Assesses breaking change risk. Use before modifying swagger files or controllers that produce API. \u{1F4D6} get_help(topic='workflows').",inputSchema:g(c$b)},{name:"graph_metrics",description:"[PLAN] Graph-based architecture metrics: PageRank (entity importance), Louvain (community/module detection), centrality (hub/authority/bridge roles), bus factor (knowledge concentration risk). Use persist=true to store PageRank/Louvain in entity metadata for semantic search boosting. Workflow: graph_metrics({metric:'pagerank', topN:10}) \u2192 top-10 most important entities.",inputSchema:g(zn)},{name:"detect_technology_stack",description:"[EXPLORE] Automatically detect languages, frameworks, build tools, and dependencies. Useful for understanding project context. Can generate tech context for embeddings.",inputSchema:g(c$c)},{name:"detect_patterns",description:"[ANALYZE] Detect anti-patterns, best-patterns, code smells, and optimization opportunities. Uses structural analysis + semantic validation (embedding similarity with curated examples) to dramatically reduce false positives. Supports 100+ rules across 6 languages. Filters: category, tags, severity, minConfidence. Categories: anti-pattern (bad practices), best-pattern (good practices), code-smell (structural issues), optimization (performance improvements with Big-O). Example: detect_patterns({category:'optimization', tags:['performance']}). \u{1F4D6} get_help(topic='patterns')",inputSchema:g(a$i)},{name:"check_entity_patterns",description:"[ANALYZE] Check specific entity for anti-patterns, best-patterns, and optimization opportunities. Returns matched patterns with confidence scores, Big-O analysis, and improvement suggestions.",inputSchema:g(b$e)},{name:"taint_analysis",description:"[SECURITY] Interprocedural taint analysis: trace untrusted data from sources (req.body, process.env, fetch) to sinks (eval, exec, innerHTML, db.query) and detect missing sanitization. Categories: sql_injection, xss, command_injection, path_traversal, ssrf, prototype_pollution. Returns vulnerability flows with severity, confidence, and fix suggestions. Supports offset/limit pagination for large results. Example: taint_analysis({category:'sql_injection', offset:0, limit:10}).",inputSchema:g(pr)},{name:"get_graph",description:"[INFO] Get the code graph with all entities and relationships",inputSchema:g(Gn)},{name:"get_graph_stats",description:"[INFO] Get statistics about the code graph",inputSchema:g(Bn)},{name:"reset_graph",description:"[SYSTEM] Clear all graph data (entities, relationships, files)",inputSchema:g(z.object({}))},{name:"get_graph_health",description:"[INFO] Health check for graph storage (totals + sample)",inputSchema:g(Hn)},{name:"get_metrics",description:"[INFO] Get system metrics and agent performance statistics",inputSchema:g(z.object({}))},{name:"get_version",description:"[INFO] Get MCP server version information and runtime details",inputSchema:g(z.object({}))},{name:"get_agent_metrics",description:"[INFO] Collect runtime telemetry for conductor and registered agents",inputSchema:g(Yn)},{name:"get_bus_stats",description:"[INFO] Inspect knowledge bus statistics (topics, entries, subscriptions)",inputSchema:g(Wn)},{name:"clear_bus_topic",description:"[SYSTEM] Remove cached knowledge entries for a specific topic",inputSchema:g(qn)},{name:"get_watcher_status",description:"[INFO] Get FileWatcher and GitWatcher status for diagnostics. Shows if background workers are running for incremental parsing and embedding generation.",inputSchema:{type:"object",properties:{},required:[]}},{name:"create_snapshot",description:"[MODIFY] Create a version snapshot for rollback. Uses git stash if available, otherwise .backup/ directory. Returns snapshot ID for rollback.",inputSchema:g(ar)},{name:"undo",description:"[MODIFY] Rollback to a previous snapshot by ID. Restores all files to their snapshot state.",inputSchema:g(cr)},{name:"list_snapshots",description:"[MODIFY] List available snapshots with creation time and description.",inputSchema:g(lr)},{name:"cleanup_snapshots",description:"[MODIFY] Delete old snapshots to free disk space.",inputSchema:g(dr)},{name:"modify_code",description:"[MODIFY] Safe code modification with auto-snapshot, validation, rollback. Modifies specific entity by ID (get ID via get_members first). Preview mode by default (no changes). Set apply=true for real changes. Workflow: 1) get_members(file='...'), 2) modify_code(entityId='...', newCode='...', preview=false, apply=true). Auto-validates syntax, updates embeddings. \u{1F4D6} get_help(topic='workflows').",inputSchema:g(Zn)},{name:"copy_file",description:"[MODIFY] Copy file or directory with automatic graph updates. Streaming for large files. Token-efficient alternative to reading full content.",inputSchema:g(er)},{name:"rename_file",description:"[MODIFY] Rename file with automatic import updates across project. Updates graph and embeddings. Token-efficient alternative to read-write pattern.",inputSchema:g(tr)},{name:"split_file",description:"[MODIFY] Extract entities from a file into separate files. Useful for refactoring large files. Updates graph with new locations.",inputSchema:g(nr)},{name:"synthesize_files",description:"[MODIFY] Combine multiple files into one. Merges entities in graph. Can optionally delete originals. Token-efficient way to consolidate code.",inputSchema:g(rr)},{name:"create_file",description:"[MODIFY] Create a new file with content. Automatically parses and adds entities to graph. Unified naming with UltrasharpTools.",inputSchema:g(ir)},{name:"rename_symbol",description:"[MODIFY] Safe rename across project: updates ALL references automatically. Works on variables, functions, classes, etc. Find via entity ID (get_members) or name+file. Creates snapshot before changes. Example: rename_symbol(entityName='oldName', newName='newName', filePath='src/utils.ts'). Much safer than manual find-replace. \u{1F4D6} get_help(topic='workflows').",inputSchema:g(or)},{name:"add_member",description:"[MODIFY] Add a new member (method, property, field) to a class or interface. Supports precise positioning. Unified naming with UltrasharpTools.",inputSchema:g(sr)},{name:"validate_file",description:"[ANALYZE] Validate code file using appropriate linter (oxlint for JS/TS, Pylint for Python). Supports automatic fixes with fixable parameter and auto-detection of linter based on project config (biome.json, .eslintrc). Returns problems categorized by severity.",inputSchema:g(a$j)},{name:"validate_directory",description:"[ANALYZE] Validate all code files in directory with batch processing. Supports automatic fixes with fixable parameter and auto-detection of linter. Returns aggregated validation report.",inputSchema:g(b$f)},{name:"semantic_merge",description:"[MERGE] AI-powered semantic merge of git branches. Automatically finds merge-base, reads files from branches, performs semantic 3-way merge, and writes results as unstaged changes. Supports dry-run mode and auto-resolve.",inputSchema:g(Xn)},{name:"analyze_merge_conflicts",description:"[MERGE] Analyze potential merge conflicts between two branches without performing the merge. Returns conflicts with severity classification and affected code units.",inputSchema:g(Jn)},{name:"get_merge_suggestions",description:"[MERGE] Get AI-generated suggestions for resolving a specific merge conflict. Requires conflict ID from analyze_merge_conflicts.",inputSchema:g(Qn)},{name:"get_semantic_merge_info",description:"[MERGE] Get information about semantic merge capabilities, supported features, and usage examples.",inputSchema:g(Kn)},{name:"autodoc_init",description:"[DOC] Initialize AutoDoc semantic documentation layer. Configure language, docs directory, and enable/disable.",inputSchema:g(a$k)},{name:"autodoc_save",description:"[DOC] Save a markdown documentation file. Parses sections, extracts references to code entities, and indexes for search.",inputSchema:g(b$g)},{name:"autodoc_get",description:"[DOC] Get documentation by ID or file path. Returns parsed sections with metadata.",inputSchema:g(c$d)},{name:"autodoc_search",description:"[DOC] Search documentation by text query. Returns matching sections with relevance scores.",inputSchema:g(d$9)},{name:"autodoc_validate",description:"[DOC] Validate documentation references. Checks that all code entity references point to existing entities.",inputSchema:g(e$4)},{name:"autodoc_status",description:"[DOC] Get AutoDoc status including statistics on documents, references, and broken links.",inputSchema:g(f$4)},{name:"autodoc_sync",description:"[DOC] Sync documentation with code changes. Validates references and marks outdated docs.",inputSchema:g(g$4)},{name:"autodoc_generate",description:"[DOC] Auto-generate documentation for the codebase. Creates .autodoc/ for general docs and README.md in each module folder.",inputSchema:g(h$3)},{name:"autodoc_changelog",description:"[DOC] View documentation change history. Shows what docs were affected by code changes.",inputSchema:g(i$1)},{name:"autodoc_install_hooks",description:"[DOC] Install or uninstall git pre-commit hooks for documentation validation. Ensures references are valid before commits.",inputSchema:g(j)},{name:"autodoc_detect_language",description:"[DOC] Detect documentation language from code comments and existing docs. Supports en, ru, zh.",inputSchema:g(k)},...Vi,...Xi,{name:"get_entity_history",description:"[HISTORY] Get change history for a specific entity across commits. Shows when entity was added, modified, or deleted.",inputSchema:g(a$l)},{name:"diff_commits",description:"[HISTORY] Compare two graph commits and show differences (added, modified, deleted entities).",inputSchema:g(b$h)},{name:"checkout_commit",description:"[HISTORY] View graph state at a specific commit (time travel). Retrieve entity snapshots from historical versions.",inputSchema:g(c$e)},{name:"list_commits",description:"[HISTORY] List graph commits (version history). Shows commit hashes, messages, entity counts, and timestamps.",inputSchema:g(d$a)}]}R();var vs=z.object({filePath:z.string(),projectPath:a,entityTypes:z.array(z.string()).optional(),offset:z.number().optional().default(0),limit:z.number().optional().default(a$1.entities)}),ct=class extends d$4{parseArgs(e){return vs.parse(e)}async execute(e){let t=this.context.normalizeInputPath(e.filePath),n=await this.ensureGraphStorageForProject(e.projectPath),r={filePath:t};e.entityTypes&&(r.entityType=e.entityTypes);let s=await n.findEntities({filters:r,limit:5e3}),a=Math.min(e.limit,200),c=b$5(s,e.offset,a);return {content:[{type:"text",text:JSON.stringify({file:t,count:c.data.length,pagination:c.pagination,entities:c.data.map(l=>({id:l.id,name:l.name,type:l.type,location:l.location,signature:l.metadata?.signature}))},null,2)}]}}},Ts=z.object({entityId:z.string().optional(),entityName:z.string().optional(),projectPath:a,relationshipTypes:z.array(z.string()).optional(),direction:z.enum(["incoming","outgoing","both"]).optional().default("both"),offset:z.number().optional().default(0),limit:z.number().optional().default(a$1.relationships)}),lt=class extends d$4{parseArgs(e){return Ts.parse(e)}async execute(e){let t=await this.ensureGraphStorageForProject(e.projectPath),n=e.entityId,r="provided";if(!n&&e.entityName){let d=await t.findEntities({filters:{name:e.entityName},limit:1});I.w("TOOL","list_rels_findEntity",{name:e.entityName,found:d.length,sample:d.slice(0,3).map(u=>({id:u.id?.slice(0,12),name:u.name,type:u.type,file:u.filePath?.split(/[/\\]/).pop()}))}),d.length>0&&d[0]&&(n=d[0].id,r="byName");}if(!n)return I.w("TOOL","list_rels_not_found",{entityId:e.entityId,entityName:e.entityName}),{content:[{type:"text",text:JSON.stringify({error:"Entity not found"})}]};I.w("TOOL","list_rels_query",{entityId:n.slice(0,16),resolvedFrom:r,direction:e.direction});let s=await t.getRelationshipsForEntity(n);I.w("TOOL","list_rels_result",{entityId:n.slice(0,16),totalRels:s.length,sample:s.slice(0,5).map(d=>({from:d.fromId?.slice(0,12),to:d.toId?.slice(0,12),type:d.type}))});let a=s;e.direction==="outgoing"?a=s.filter(d=>d.fromId===n):e.direction==="incoming"&&(a=s.filter(d=>d.toId===n)),e.relationshipTypes&&(a=a.filter(d=>e.relationshipTypes.includes(d.type)));let c=Math.min(e.limit,200),l=b$5(a,e.offset,c);return {content:[{type:"text",text:JSON.stringify({entityId:n,count:l.data.length,pagination:l.pagination,relationships:l.data},null,2)}]}}},Ds=z.object({query:z.string(),projectPath:a,type:z.enum(["entities","relationships","both"]).optional().default("both"),offset:z.number().optional().default(0),limit:z.number().optional().default(50)}),dt=class extends d$4{parseArgs(e){return Ds.parse(e)}async execute(e){let t=await this.ensureGraphStorageForProject(e.projectPath),n=Math.min(e.limit,200),r={},s={};if(e.type==="entities"||e.type==="both"){let a=await t.searchEntities({namePattern:e.query,limit:1e3}),c=b$5(a,e.offset,n);r.entities=c.data,s.entities=c.pagination;}if(e.type==="relationships"||e.type==="both"){let a=await t.findRelationships({filters:{},limit:1e3}),c=b$5(a,e.offset,n);r.relationships=c.data,s.relationships=c.pagination;}return {content:[{type:"text",text:JSON.stringify({query:e.query,entitiesFound:r.entities?.length||0,relationshipsFound:r.relationships?.length||0,pagination:s,results:r},null,2)}]}}};var Es=z.object({task:z.string().describe("Description of what you want to do (e.g. 'find duplicates', 'refactor safely')"),agentType:z.enum(["explore","plan","modify","analyze","any"]).optional().describe("Your agent type for filtered recommendations")}),pt=class extends d$4{parseArgs(e){return Es.parse(e)}async execute(e){let{task:t,agentType:n}=e,r=we(),s=t.toLowerCase(),a=[],c=p=>{let m=p.match(/^\[([^\]]+)\]/);return !m||!m[1]?[]:[m[1]]},l={"find duplicates":{keywords:["duplicate","similar","clone"],tools:["semantic_search","find_duplicates","jscpd_detect_clones"]},"refactor safely":{keywords:["refactor","safe","impact"],tools:["analyze_code_impact","create_snapshot","modify_code","rename_symbol"]},search:{keywords:["search","find","locate"],tools:["semantic_search","pattern_search","find_similar_code"]},"understand flow":{keywords:["flow","trace","path","execution"],tools:["trace_flow","trace_backwards","trace_data_flow"]},rename:{keywords:["rename"],tools:["rename_symbol","rename_file"]},"check impact":{keywords:["impact","break","depend","affect"],tools:["analyze_code_impact","trace_backwards"]},modify:{keywords:["modify","change","edit"],tools:["modify_code","create_snapshot","analyze_code_impact"]},complex:{keywords:["complex","hotspot","technical debt"],tools:["analyze_hotspots","semantic_search"]},"find anti-patterns":{keywords:["anti-pattern","antipattern","bad practice","smell","code smell"],tools:["detect_patterns","analyze_hotspots"]},"optimize performance":{keywords:["optimize","performance","slow","fast","speed","memory"],tools:["detect_patterns","analyze_hotspots"]},"code quality":{keywords:["quality","pattern","best practice","review"],tools:["detect_patterns","suggest_refactoring","analyze_hotspots"]},"security analysis":{keywords:["security","taint","vulnerability","injection","xss","sanitize"],tools:["taint_analysis","detect_patterns"]},"architecture metrics":{keywords:["pagerank","community","bus factor","centrality","metric","important","architecture"],tools:["graph_metrics","analyze_hotspots"]}};for(let p of r){let m=0,h=[],v=c(p.description),A=p.description.toLowerCase(),C=s.split(/\s+/).filter(f=>f.length>3);for(let f of C)(A.includes(f)||p.name.includes(f))&&(m+=3,h.push(`matches '${f}'`));for(let[f,_]of Object.entries(l))_.keywords.some(T=>s.includes(T))&&_.tools.includes(p.name)&&(m+=5,h.push(`recommended for '${f}'`));if(n&&n!=="any"){let _={explore:["EXPLORE","INFO"],plan:["PLAN","ANALYZE"],modify:["MODIFY"],analyze:["ANALYZE"]}[n]||[];v.some(S=>_.includes(S))&&(m+=2,h.push(`matches agent type '${n}'`));}p.name==="index"&&s.includes("start")&&(m+=10,h.push("required first step")),p.name==="get_help"&&(m+=1),m>0&&a.push({name:p.name,description:p.description,tags:v,score:m,reason:h.join(", ")});}a.sort((p,m)=>m.score-p.score);let u=a.slice(0,10).map((p,m)=>({rank:m+1,tool:p.name,tags:p.tags,score:p.score,reason:p.reason,description:p.description.substring(0,200)+(p.description.length>200?"...":"")}));return {content:[{type:"text",text:JSON.stringify({success:true,task:t,agentType:n||"any",recommendations:u,tip:u.length===0?"No specific tools found. Try 'semantic_search' or 'get_help' for general guidance.":`Found ${u.length} relevant tools. Start with #1 (highest score).`},null,2)}]}}};R();var Ps=z.object({projectPath:a}),ut=class extends d$4{parseArgs(e){return Ps.parse(e)}async execute(e){return await(await this.ensureGraphStorageForProject(e.projectPath)).clear(),{content:[{type:"text",text:JSON.stringify({success:true,message:"Graph reset completed"})}]}}},Ms=z.object({directory:z.string().optional(),projectPath:a}),mt=class extends d$4{parseArgs(e){return Ms.parse(e)}async execute(e){let t=this.resolveProjectPath(e);if(await(await this.ensureGraphStorageForProject(t)).clear(),process.env.MCP_DEBUG_DISABLE_SEMANTIC!=="1")try{let d=(await this.ensureSemanticAgentForProject(t))?.getVectorStore?.();d&&await d.clear();}catch(l){let d=a$7(l);I.w("CLEANINDEX","sem_reinit_fail",{err:d.message,stack:d.stack});}let r=this.context.getConductor();await r.initialize();let s=r.getAgentByType?.("dev");if(!s)throw new Error("DevAgent not available for indexing");let a={id:`clean-index-${Date.now()}`,type:"index",priority:9,payload:{directory:t,incremental:false,excludePatterns:[]},createdAt:Date.now()},c=await s.process(a);return {content:[{type:"text",text:JSON.stringify({success:true,message:"Clean index completed",result:c},null,2)}]}}},Rs=z.object({projectPath:a,entityTypes:z.array(z.string()).optional(),offset:z.number().optional().default(0),limit:z.number().optional().default(a$1.graphNodes),includeRelationships:z.boolean().optional().default(true)}),gt=class extends d$4{parseArgs(e){return Rs.parse(e)}async execute(e){let t=await this.ensureGraphStorageForProject(e.projectPath),n=Math.min(e.limit,200),r=await t.findEntities({filters:e.entityTypes?{entityType:e.entityTypes}:{},limit:5e3}),s=b$5(r,e.offset,n),a={data:[],pagination:{offset:0,limit:0,total:0,hasMore:false}};if(e.includeRelationships&&s.data.length>0){let c=s.data.map(d=>d.id),l=await t.findRelationships({filters:{fromId:c},limit:5e3});a=b$5(l,0,n);}return {content:[{type:"text",text:JSON.stringify({entities:s.data.length,relationships:a.data.length,pagination:{entities:s.pagination,relationships:a.pagination},data:{entities:s.data,relationships:a.data}},null,2)}]}}},Is=z.object({projectPath:a}),ht=class extends d$4{parseArgs(e){return Is.parse(e)}async execute(e){let t=await this.ensureGraphStorageForProject(e.projectPath),n=await t.getStatistics(),r=null;try{let s=t;typeof s.getCooccurrenceOps=="function"&&(r=await s.getCooccurrenceOps().getStats());}catch{}return {content:[{type:"text",text:JSON.stringify({...n,cooccurrence:r},null,2)}]}}},ks=z.object({projectPath:a}),ft=class extends d$4{parseArgs(e){return ks.parse(e)}async execute(e){let t=await this.ensureGraphStorageForProject(e.projectPath),n=await t.getStatistics(),r=this.context.getSQLiteManager(),s;try{let c=await t.getAllEntities(),l=c.filter(d=>d.metadata?.swaggerType==="api_spec");if(l.length>0){let d=[],p=(await t.getAllRelationships()).filter(h=>h.type==="generated_from");for(let h of l){let v=h.updatedAt;for(let A of p)if(A.metadata?.toFile===h.filePath||A.toId.includes(h.filePath)){let C=c.find(f=>f.id===A.fromId);C&&v>C.updatedAt&&d.push(`Generated code may be out of sync: ${h.filePath} updated after ${C.filePath}`);}}let m=l.filter(h=>h.metadata?.isActiveContract).length;s={swaggerFilesFound:l.length,activeContracts:m,staleWarnings:d};}}catch{}let a={status:"healthy",database:{path:r?.getDatabasePath?.()||"unknown",entities:n.totalEntities||0,relationships:n.totalRelationships||0,files:n.totalFiles||0}};return s&&(a.swagger=s),{content:[{type:"text",text:JSON.stringify(a,null,2)}]}}};var Qi=z.object({topic:z.enum(["quick-start","tool-reference","workflows","tracing","autodoc","explore","planning","modification","patterns","security"]).describe("Documentation topic")}),yt=class extends d$4{parseArgs(e){return Qi.parse(e)}async execute(e){let{topic:t}=Qi.parse(e);try{let n=dirname(fileURLToPath(import.meta.url)),r=join(n,".."),s=join(r,"prompts"),c={"quick-start":"quick-start.md","tool-reference":"tool-reference.md",workflows:"workflows.md",tracing:"tracing-guide.md",autodoc:"autodoc-guide.md",explore:"explore-guide.md",planning:"planning-guide.md",modification:"modification-guide.md",patterns:"patterns-guide.md",security:"security-guide.md"}[t];if(!c)throw new Error(`Unknown topic: ${t}`);let l=join(s,c),d=readFileSync(l,"utf-8");return {content:[{type:"text",text:JSON.stringify({success:!0,topic:t,documentation:d,message:`\u{1F4D6} ${t} documentation loaded. Read this guide to understand how to use UltraCode effectively.`},null,2)}]}}catch(n){let r=n instanceof Error?n.message:String(n);return {content:[{type:"text",text:JSON.stringify({success:false,error:`Failed to load documentation for topic '${t}': ${r}`,availableTopics:["quick-start","tool-reference","workflows","tracing","autodoc","explore","planning","modification","patterns","security"]},null,2)}]}}}};R();var js=[".ts",".tsx",".js",".jsx",".py",".go",".rs",".kt",".swift",".c",".cpp",".java",".cs"],Us=z.object({directory:z.string().optional(),incremental:z.boolean().optional().default(false),reset:z.boolean().optional().default(false),excludePatterns:z.array(z.string()).optional().default([]),fullScan:z.boolean().optional().default(false)}),St=class extends d$4{parseArgs(e){return Us.parse(e)}async execute(e){let t=this.resolveProjectPath(e);if(An()){let a=et();return {content:[{type:"text",text:JSON.stringify({success:false,error:"Indexing already in progress",currentDirectory:a.directory,elapsedSeconds:a.elapsedSeconds,message:"Please wait for the current indexing operation to complete"},null,2)}]}}let n=this.context.createAutoIndexContext(),r=this.getExtensions(),s=await Me(t,r,n,{incremental:e.incremental,reset:e.reset,extraExcludePatterns:e.excludePatterns?.length?e.excludePatterns:void 0,fullScan:e.fullScan});return this.formatResult(s)}getExtensions(){return this.context.config.indexing?.autoIndexExtensions??js}formatResult(e){let t={success:e.success,message:e.success?"Indexing completed":"Indexing completed with warnings",entityCount:e.entityCount,durationMs:e.duration};return e.embeddingStats&&(t.embeddings=e.embeddingStats),e.embeddingPerformance&&(t.embeddingPerformance=e.embeddingPerformance),e.oversizedWarning?.aiMessage&&(t.warning=e.oversizedWarning.aiMessage,t.oversizedEntities={count:e.oversizedWarning.oversizedCount,maxTokens:e.oversizedWarning.maxTokens}),I.i("INDEXTOOL","index_complete",{dir:"via_auto_indexer",entities:e.entityCount,durMs:e.duration}),{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}};R();var Fs=z.object({includeSystem:z.boolean().optional().default(true),includeGraph:z.boolean().optional().default(true),includeAgents:z.boolean().optional().default(false)}),bt=class extends d$4{parseArgs(e){return Fs.parse(e)}async execute(e){let t={timestamp:new Date().toISOString()};if(e.includeSystem){let{memoryUsage:n}=await import('process'),r=n();t.system={memory:{heapUsed:Math.round(r.heapUsed/1024/1024),heapTotal:Math.round(r.heapTotal/1024/1024),external:Math.round(r.external/1024/1024),rss:Math.round(r.rss/1024/1024),unit:"MB"},uptime:Math.round(process.uptime()),nodeVersion:process.version};}if(e.includeGraph)try{let r=await(await this.context.getGraphStorage()).getStatistics();t.graph=r;}catch{t.graph={error:"Graph storage not available"};}if(e.includeAgents){let n=this.context.getConductor();t.agents=n.getAllAgentMetrics();}return {content:[{type:"text",text:JSON.stringify(t,null,2)}]}}},zs=z.object({detailed:z.boolean().optional().default(false)}),wt=class extends d$4{parseArgs(e){return zs.parse(e)}async execute(e){let{readJSON:t}=await import('./chunks/file-ops-HXOTPMZ7.js'),{join:n}=await import('path');try{let r=this.resolveProjectPath({}),s=n(r,"package.json"),a="unknown",c="ultracode";try{let d=await t(s);a=d.version||a,c=d.name||c;}catch{}let l={name:c,version:a};return e.detailed&&(l.details={nodeVersion:process.version,platform:process.platform,arch:process.arch,pid:process.pid,cwd:process.cwd()},l.features={semanticSearch:!0,multiLanguage:!0,branchManagement:!!await this.context.getBranchManager(),snapshots:!!this.context.getSnapshotManager()}),{content:[{type:"text",text:JSON.stringify(l,null,2)}]}}catch(r){let s=a$7(r);return {content:[{type:"text",text:JSON.stringify({error:s.message})}]}}}},Gs=z.object({agentType:z.string().optional(),includeHistory:z.boolean().optional().default(false)}),_t=class extends d$4{parseArgs(e){return Gs.parse(e)}async execute(e){let n=this.context.getConductor().getAllAgentMetrics(),r;e.agentType?r=n[e.agentType]??{error:`Agent '${e.agentType}' not found`}:r=n;let s=Date.now()-300*1e3,a=Object.values(n),c={totalAgents:Object.keys(n).length,activeAgents:a.filter(l=>l.lastActivity>s).length,totalTasksProcessed:a.reduce((l,d)=>l+d.tasksProcessed,0)};return {content:[{type:"text",text:JSON.stringify({summary:c,agents:r},null,2)}]}}},Bs=z.object({topic:z.string().optional(),includeMessages:z.boolean().optional().default(false),messageLimit:z.number().optional().default(10)}),xt=class extends d$4{parseArgs(e){return Bs.parse(e)}async execute(e){let t=this.context.getKnowledgeBus();if(!t)return {content:[{type:"text",text:JSON.stringify({error:"Knowledge bus not available"})}]};let n=t.getStats?.()||{topicCount:0,entryCount:0,subscriptionCount:0,messageQueueSize:0},r={totalTopics:n.topicCount,totalMessages:n.entryCount,topics:{summary:{topicCount:n.topicCount,entryCount:n.entryCount,subscriptionCount:n.subscriptionCount,messageQueueSize:n.messageQueueSize}}};if(e.topic&&(r.topics[e.topic]={info:"Topic-specific stats not available in current API"}),e.includeMessages&&t.getRecentMessages){let s=await t.getRecentMessages();r.recentMessages=s;}return {content:[{type:"text",text:JSON.stringify(r,null,2)}]}}},Hs=z.object({topic:z.string(),confirm:z.boolean().optional().default(false)}),Ct=class extends d$4{parseArgs(e){return Hs.parse(e)}async execute(e){if(!e.confirm)return {content:[{type:"text",text:JSON.stringify({warning:"This will clear all messages in the topic",topic:e.topic,hint:"Set confirm: true to proceed"})}]};let t=this.context.getKnowledgeBus();if(!t)return {content:[{type:"text",text:JSON.stringify({error:"Knowledge bus not available"})}]};try{return await t.clearTopic?.(e.topic),{content:[{type:"text",text:JSON.stringify({success:!0,topic:e.topic,message:"Topic cleared successfully"})}]}}catch(n){let r=a$7(n);return {content:[{type:"text",text:JSON.stringify({error:r.message})}]}}}},Ws=z.object({}),At=class extends d$4{parseArgs(e){return Ws.parse(e)}async execute(e){try{let{AgentType:t}=await import('./chunks/agent-6ZDOOVGS.js'),r=this.context.getConductor().getAgentByType?.(t.DEV);I.d("METRICS","watcher_status_diag",{hasDevAgent:!!r,hasGetIndexerAgent:!!r?.getIndexerAgent});let s=r?.getIndexerAgent?.()??void 0;I.d("METRICS","watcher_status_diag2",{hasIndexerAgent:!!s,indexerAgentType:s?typeof s:"undefined"});let a={timestamp:new Date().toISOString(),indexerAgentExists:!!s,fileWatcher:null,gitWatcher:null,repositoryPath:null};if(s){a.fileWatcher=s.getFileWatcherStatus?.()??{exists:!1,reason:"Method not available"};let c=s.getGitWatcher?.();c?a.gitWatcher={exists:!0,isWatching:c.isWatching?.()??!1,currentBranch:c.getBranch?.()??"unknown"}:a.gitWatcher={exists:!1};let l=s.getBranchManager?.();a.branchManager={exists:!!l},a.repositoryPath=s.currentRepositoryPath??null,a.indexingStats=s.getIndexingStats?.()??{};}return {content:[{type:"text",text:JSON.stringify(a,null,2)}]}}catch(t){let n=a$7(t);return {content:[{type:"text",text:JSON.stringify({error:n.message,stack:n.stack?.split(`
|
|
37
|
+
`).slice(0,5)})}]}}}};var gr=class{handlers=new Map;lazyHandlers=new Map;constructor(){this.registerDefaultHandlers();}register(e,t){this.handlers.set(e,t);}registerLazy(e,t){this.lazyHandlers.set(e,t);}async getHandler(e,t){let n=this.handlers.get(e);if(n)return new n(t);let r=this.lazyHandlers.get(e);if(r){let s=await r();return this.handlers.set(e,s),this.lazyHandlers.delete(e),new s(t)}throw new Error(`Unknown tool: ${e}`)}has(e){return this.handlers.has(e)||this.lazyHandlers.has(e)}getRegisteredTools(){return [...this.handlers.keys(),...this.lazyHandlers.keys()]}registerDefaultHandlers(){this.register("get_help",yt),this.register("get_tools_for_task",pt),this.register("index",St),this.register("reset_graph",ut),this.register("clean_index",mt),this.register("get_graph",gt),this.register("get_graph_stats",ht),this.register("get_graph_health",ft),this.register("get_members",ct),this.register("list_entity_relationships",lt),this.register("query",dt),this.register("get_metrics",bt),this.register("get_version",wt),this.register("get_agent_metrics",_t),this.register("get_bus_stats",xt),this.register("clear_bus_topic",Ct),this.register("get_watcher_status",At);let e=()=>import('./chunks/semantic-tool-handlers-FGIV2BCK.js');this.registerLazy("semantic_search",async()=>(await e()).SemanticSearchToolHandler),this.registerLazy("find_similar_code",async()=>(await e()).FindSimilarCodeToolHandler),this.registerLazy("find_duplicates",async()=>(await e()).DetectCodeClonesToolHandler),this.registerLazy("jscpd_detect_clones",async()=>(await e()).JscpdDetectClonesToolHandler),this.registerLazy("cross_language_search",async()=>(await e()).CrossLanguageSearchToolHandler),this.registerLazy("pattern_search",async()=>(await e()).PatternSearchToolHandler);let t=()=>import('./chunks/analysis-tool-handlers-Z2RF24T7.js');this.registerLazy("suggest_refactoring",async()=>(await t()).SuggestRefactoringToolHandler),this.registerLazy("analyze_hotspots",async()=>(await t()).AnalyzeHotspotsToolHandler),this.registerLazy("find_related_concepts",async()=>(await t()).FindRelatedConceptsToolHandler),this.registerLazy("analyze_state_chaos",async()=>(await t()).AnalyzeStateChaosToolHandler),this.registerLazy("analyze_code_impact",async()=>(await t()).AnalyzeCodeImpactToolHandler),this.registerLazy("analyze_swagger_impact",async()=>(await t()).AnalyzeSwaggerImpactToolHandler),this.registerLazy("detect_technology_stack",async()=>(await t()).DetectTechnologyStackToolHandler);let n=()=>import('./chunks/branch-tool-handlers-4EXB6BUG.js');this.registerLazy("list_branches",async()=>(await n()).ListBranchesToolHandler),this.registerLazy("switch_branch",async()=>(await n()).SwitchBranchToolHandler),this.registerLazy("get_branch_status",async()=>(await n()).GetBranchStatusToolHandler),this.registerLazy("cleanup_branches",async()=>(await n()).CleanupBranchesToolHandler),this.registerLazy("get_changed_files",async()=>(await n()).GetChangedFilesToolHandler);let r=()=>import('./chunks/snapshot-tool-handlers-3R5YSLIW.js');this.registerLazy("create_snapshot",async()=>(await r()).CreateSnapshotToolHandler),this.registerLazy("undo",async()=>(await r()).RollbackSnapshotToolHandler),this.registerLazy("list_snapshots",async()=>(await r()).ListSnapshotsToolHandler),this.registerLazy("cleanup_snapshots",async()=>(await r()).CleanupSnapshotsToolHandler);let s=()=>import('./chunks/file-tool-handlers-EYMPPZFE.js');this.registerLazy("modify_code",async()=>(await s()).ModifyEntityCodeToolHandler),this.registerLazy("copy_file",async()=>(await s()).CopyFileToolHandler),this.registerLazy("rename_file",async()=>(await s()).RenameFileToolHandler),this.registerLazy("split_file",async()=>(await s()).SplitFileToolHandler),this.registerLazy("synthesize_files",async()=>(await s()).SynthesizeFilesToolHandler),this.registerLazy("create_file",async()=>(await s()).CreateFileToolHandler),this.registerLazy("rename_symbol",async()=>(await s()).RenameSymbolToolHandler),this.registerLazy("add_member",async()=>(await s()).AddMemberToolHandler);let a=()=>import('./chunks/validation-tool-handlers-TRYEWDFR.js');this.registerLazy("validate_file",async()=>(await a()).ValidateFileToolHandler),this.registerLazy("validate_directory",async()=>(await a()).ValidateDirectoryToolHandler);let c=()=>import('./chunks/merge-tool-handlers-HP7DRBXJ.js');this.registerLazy("semantic_merge",async()=>(await c()).SemanticMergeToolHandler),this.registerLazy("analyze_merge_conflicts",async()=>(await c()).AnalyzeMergeConflictsToolHandler),this.registerLazy("get_merge_suggestions",async()=>(await c()).GetMergeSuggestionsToolHandler),this.registerLazy("get_semantic_merge_info",async()=>(await c()).GetSemanticMergeInfoToolHandler);let l=()=>import('./chunks/tracing-tool-handlers-YSSSJYYY.js');this.registerLazy("trace_flow",async()=>(await l()).TraceFlowToolHandler),this.registerLazy("trace_backwards",async()=>(await l()).TraceBackwardsToolHandler),this.registerLazy("trace_data_flow",async()=>(await l()).TraceDataFlowToolHandler),this.registerLazy("analyze_state_impact",async()=>(await l()).AnalyzeStateImpactToolHandler),this.registerLazy("find_decision_points",async()=>(await l()).FindDecisionPointsToolHandler);let d=()=>import('./chunks/autodoc-tool-handlers-MECXQJ2K.js');this.registerLazy("autodoc_init",async()=>(await d()).AutoDocInitToolHandler),this.registerLazy("autodoc_save",async()=>(await d()).AutoDocSaveToolHandler),this.registerLazy("autodoc_get",async()=>(await d()).AutoDocGetToolHandler),this.registerLazy("autodoc_search",async()=>(await d()).AutoDocSearchToolHandler),this.registerLazy("autodoc_validate",async()=>(await d()).AutoDocValidateToolHandler),this.registerLazy("autodoc_status",async()=>(await d()).AutoDocStatusToolHandler),this.registerLazy("autodoc_sync",async()=>(await d()).AutoDocSyncToolHandler),this.registerLazy("autodoc_generate",async()=>(await d()).AutoDocGenerateToolHandler),this.registerLazy("autodoc_changelog",async()=>(await d()).AutoDocChangelogToolHandler),this.registerLazy("autodoc_install_hooks",async()=>(await d()).AutoDocInstallHooksToolHandler),this.registerLazy("autodoc_detect_language",async()=>(await d()).AutoDocDetectLanguageToolHandler);let u=()=>import('./chunks/taint-tool-handlers-ZZFKTKPF.js');this.registerLazy("taint_analysis",async()=>(await u()).TaintAnalysisToolHandler);let p=()=>import('./chunks/graph-metrics-tool-handlers-Z6W57TRV.js');this.registerLazy("graph_metrics",async()=>(await p()).GraphMetricsToolHandler);let m=()=>import('./chunks/pattern-tool-handlers-SAHX2CVW.js');this.registerLazy("detect_patterns",async()=>(await m()).DetectPatternsToolHandler),this.registerLazy("check_entity_patterns",async()=>(await m()).CheckEntityPatternsToolHandler);let h=()=>import('./chunks/history-tool-handlers-BNA2R4VF.js');this.registerLazy("get_entity_history",async()=>(await h()).GetEntityHistoryToolHandler),this.registerLazy("diff_commits",async()=>(await h()).DiffCommitsToolHandler),this.registerLazy("checkout_commit",async()=>(await h()).CheckoutCommitToolHandler),this.registerLazy("list_commits",async()=>(await h()).ListCommitsToolHandler);}},Oe=new gr;function Zi(o){try{let e=fileURLToPath(o),t=dirname(e),n=join(t,"../package.json"),r=JSON.parse(readFileSync(n,"utf-8"));return {name:r.name||"ultracode",version:r.version||"unknown",description:r.description||"",homepage:r.homepage||"",repository:r.repository?.url||"",nodeVersion:process.version,platform:process.platform,arch:process.arch}}catch(e){return {name:"ultracode",version:"unknown",description:"Multi-agent LiteRAG MCP server for advanced code graph analysis",homepage:"https://github.com/faxenoff/ultracode",repository:"git+https://github.com/faxenoff/ultracode.git",nodeVersion:process.version,platform:process.platform,arch:process.arch,error:e instanceof Error?e.message:"Failed to read package.json"}}}function hr(o){return o.startsWith("~/")||o==="~"?join(homedir(),o.slice(1)):o}R();G();var Tt=class{constructor(e,t,n){this.graphStorage=e;this.vectorStore=t;this.previewManager=n;}async copy(e,t,n={}){let{preview:r=true,updateGraph:s=true}=n;return r?{success:true,preview:await this.previewManager.previewFileOperation("copy",{source:e,target:t}),filesAffected:[],operation:"copy"}:(await v$1(e)).isDirectory()?this.copyDirectory(e,t,s):this.copyFile(e,t,s)}async rename(e,t,n={}){let{preview:r$1=true,updateImports:s=true,updateGraph:a=true}=n;if(r$1)return {success:true,preview:await this.previewManager.previewFileOperation("rename",{oldPath:e,newPath:t}),filesAffected:[],operation:"rename"};await o$1(dirname(t),{recursive:true});let c=await b$8(e);await f$1(t,c);let l=0;a&&(l=await this.updateFilePathInGraph(e,t));let d=0;return a&&this.vectorStore&&(d=await this.updateEmbeddingsFilePath(e,t)),s&&await this.updateImportsAcrossProject(e,t),await r(e),{success:true,filesAffected:[e,t],operation:"rename",entitiesAffected:l,embeddingsUpdated:d}}async split(e,t,n={}){let{preview:r=true,updateGraph:s=true}=n;if(r)return {success:true,preview:await this.previewManager.previewFileOperation("split",{filePath:e,entityIds:t}),filesAffected:[],operation:"split"};let c=(await Promise.all(t.map(p=>this.graphStorage.getEntity(p)))).filter(p=>p!==null),d=(await b$8(e)).split(`
|
|
38
38
|
`),u=[];for(let p of c){let m=d.slice(p.location.start.line-1,p.location.end.line).join(`
|
|
39
39
|
`),h=join(dirname(e),`${p.name}${extname(e)}`);await f$1(h,m,"utf-8"),s&&await this.graphStorage.updateEntity(p.id,{filePath:h,location:{start:{line:1,column:0,index:0},end:{line:m.split(`
|
|
40
40
|
`).length,column:0,index:m.length}}}),u.push(h);}return await this.removeEntitiesFromFile(e,t),{success:true,filesAffected:[e,...u],operation:"split",entitiesAffected:c.length}}async synthesize(e,t,n={}){let{preview:r=true,deleteOriginals:s=false,updateGraph:a=true}=n;if(r)return {success:true,preview:await this.previewManager.previewFileOperation("synthesize",{files:e,targetPath:t}),filesAffected:[],operation:"synthesize"};let c=[];for(let p of e){let m=await b$8(p);c.push(m);}let l=c.join(`
|
|
41
41
|
|
|
42
42
|
`);await o$1(dirname(t),{recursive:true}),await f$1(t,l,"utf-8");let d=0;a&&(d=await this.mergeEntitiesInGraph(e,t));let u=0;if(a&&this.vectorStore&&(u=await this.mergeEmbeddings(e,t)),s){let{unlink:p}=await import('fs/promises');for(let m of e)await p(m);}return {success:true,filesAffected:[...e,t],operation:"synthesize",entitiesAffected:d,embeddingsUpdated:u}}async copyFile(e,t,n){if(await o$1(dirname(t),{recursive:true}),(await v$1(e)).size>1024*1024)await a$g(e,t);else {let{copyFile:c}=await import('./chunks/file-ops-HXOTPMZ7.js');await c(e,t);}let s=0,a=0;return n&&(s=await this.duplicateEntitiesInGraph(e,t),this.vectorStore&&(a=await this.duplicateEmbeddings(e,t))),{success:true,filesAffected:[e,t],operation:"copy",entitiesAffected:s,embeddingsUpdated:a}}async copyDirectory(e,t,n){let s=this;async function a(l,d){let u=await q$1(l,{withFileTypes:true}),p=[],m=[];for(let C of u){let f=join(l,C.name),_=join(d,C.name);C.isDirectory()?(await o$1(_,{recursive:true}),m.push(a(f,_))):p.push({src:f,dest:_});}let h=[],v=0,A=0;for(let C=0;C<p.length;C+=8){let f=p.slice(C,C+8),_=await Promise.all(f.map(async({src:S,dest:T})=>s.copyFile(S,T,n)));for(let S of _)h.push(...S.filesAffected),v+=S.entitiesAffected||0,A+=S.embeddingsUpdated||0;}if(m.length>0){let C=await Promise.all(m);for(let f of C)h.push(...f.filesAffected),v+=f.entitiesAffected,A+=f.embeddingsUpdated;}return {filesAffected:h,entitiesAffected:v,embeddingsUpdated:A}}let c=await a(e,t);return {success:true,filesAffected:c.filesAffected,operation:"copy",entitiesAffected:c.entitiesAffected,embeddingsUpdated:c.embeddingsUpdated}}async updateFilePathInGraph(e,t){let n=await this.graphStorage.findEntities({filters:{filePath:e}});return await Promise.all(n.map(r=>this.graphStorage.updateEntity(r.id,{filePath:t}))),n.length}async duplicateEntitiesInGraph(e,t){let n=await this.graphStorage.findEntities({filters:{filePath:e}});if(n.length===0)return 0;let r=Date.now(),s=n.map(a=>({...a,id:nanoid(),filePath:t,createdAt:r,updatedAt:r}));return await this.graphStorage.insertEntities(s),n.length}async mergeEntitiesInGraph(e,t){let n=0;for(let r of e){let s=await this.graphStorage.findEntities({filters:{filePath:r}});await Promise.all(s.map(a=>this.graphStorage.updateEntity(a.id,{filePath:t}))),n+=s.length;}return n}async updateEmbeddingsFilePath(e,t){return I.w("FILEOPS","emb_path_not_impl"),0}async duplicateEmbeddings(e,t){return I.w("FILEOPS","emb_dup_not_impl"),0}async mergeEmbeddings(e,t){return I.w("FILEOPS","emb_merge_not_impl"),0}async updateImportsAcrossProject(e,t){let n=await this.findImporters(e);for(let r of n){let a=(await b$8(r.filePath)).replace(new RegExp(`from ['"]${e}['"]`,"g"),`from '${t}'`);await f$1(r.filePath,a,"utf-8");}}async findImporters(e){return (await this.graphStorage.findEntities({filters:{entityType:"import"}})).filter(n=>n.metadata.importData?.source===e)}async removeEntitiesFromFile(e,t){let r=(await Promise.all(t.map(c=>this.graphStorage.getEntity(c)))).filter(c=>c!==null);if(r.length===0)return;let a=(await b$8(e)).split(`
|
|
43
43
|
`);r.sort((c,l)=>l.location.start.line-c.location.start.line);for(let c of r)a.splice(c.location.start.line-1,c.location.end.line-c.location.start.line+1);await f$1(e,a.join(`
|
|
44
|
-
`),"utf-8");}};H();var
|
|
44
|
+
`),"utf-8");}};H();var yr=class{config;_versionManager=null;_codeModifier=null;_fileOperations=null;_codeValidator=null;_technologyDetector=null;_patternSearch=null;_autoDocManager=null;_autodocEmbeddingsGenerated=false;_autodocEmbeddingsSubscriptionId=null;constructor(e){this.config=e;}get directory(){return this.config.directory}async getGraphStorage(){return d$3()}getConductor(){return this.config.getConductor()}getGlobalVectorStore(){return this.config.getGlobalVectorStore()}async getVersionManager(){return this._versionManager||(this._versionManager=new c$a({workingDirectory:this.config.directory}),await this._versionManager.initialize()),this._versionManager}async getCodeModifier(){if(!this._codeModifier){let e=await this.getGraphStorage(),t=this.getGlobalVectorStore();this._codeModifier=new e$2(e,t,this.config.directory),await this._codeModifier.initialize();}return this._codeModifier}async getFileOperations(){if(!this._fileOperations){let e=await this.getGraphStorage(),t=this.getGlobalVectorStore(),n=new d$7(e,t);await n.initialize(),this._fileOperations=new Tt(e,t,n);}return this._fileOperations}async getCodeValidator(){return this._codeValidator||(this._codeValidator=new b$b),this._codeValidator}async getTechnologyDetector(){if(!this._technologyDetector){let e=await this.getGraphStorage();this._technologyDetector=new a$e(e,this.config.directory);}return this._technologyDetector}async getPatternSearch(){if(!this._patternSearch){let e=await this.getGraphStorage(),t=this.getGlobalVectorStore(),n=await this.getTechnologyDetector();this._patternSearch=new a$f(e,t,n),await this._patternSearch.initialize();}return this._patternSearch}isAutoDocEnabled(){let e=join(this.config.directory,".autodoc");return existsSync(e)}async getAutoDocManager(){if(!this.isAutoDocEnabled())return null;if(!this._autoDocManager){let e=p$1(),t=join(dirname(e.graphDbPath),"autodoc.db");this._autoDocManager=b$c(t);let n=await this.getGraphStorage();await this._autoDocManager.initialize(n);let r=n.getProjectContext();if(this._autoDocManager.setProjectContext(r),!this._autoDocManager.getConfig()){let s=join(this.config.directory,".autodoc");this._autoDocManager.setConfig({enabled:true,language:"en",docsDir:s}),this.runAutoDocSync(this._autoDocManager,s).catch(()=>{});}}return this._autoDocManager}async runAutoDocSync(e,t){let{log:n}=await import('./chunks/logging-SYNNMFLN.js');this.subscribeToIndexCompleted(e,n);try{let{syncDiskToDb:r}=await import('./chunks/file-sync-X6FXAJ5R.js'),s=await r(t,c=>e.getDocumentsByFile(c),(c,l)=>e.saveDocument(c,l),4);n.i("AUTODOC","sync_autodoc_folder",{added:s.added.length,updated:s.updated.length,errors:s.errors.length});let a=join(this.config.directory,"src");if(existsSync(a)){let c=await r(a,l=>e.getDocumentsByFile(l),(l,d)=>e.saveDocument(l,d),4);n.i("AUTODOC","sync_src_modules",{added:c.added.length,updated:c.updated.length,errors:c.errors.length});}}catch(r){n.w("AUTODOC","sync_failed",{error:r.message});}}subscribeToIndexCompleted(e,t){if(this._autodocEmbeddingsGenerated||this._autodocEmbeddingsSubscriptionId)return;let n=t,r=async()=>{if(!this._autodocEmbeddingsGenerated){n.i("AUTODOC","embeddings_triggered_by_event",{event:"index:completed"});try{await this.generateAutoDocEmbeddings(e),this._autodocEmbeddingsGenerated=!0,this._autodocEmbeddingsSubscriptionId&&(a$2.unsubscribe(this._autodocEmbeddingsSubscriptionId),this._autodocEmbeddingsSubscriptionId=null);}catch(a){n.w("AUTODOC","embeddings_failed",{error:a.message});}}};this._autodocEmbeddingsSubscriptionId=a$2.subscribe("autodoc-embeddings","index:completed",r),n.d("AUTODOC","embeddings_subscribed",{event:"index:completed"});let s=a$2.query("index:completed");s.length>0&&(n.i("AUTODOC","embeddings_fallback",{reason:"index_already_completed",events:s.length}),r().catch(a=>{n.w("AUTODOC","embeddings_fallback_failed",{error:a.message});}));}async generateAutoDocEmbeddings(e){let{log:t}=await import('./chunks/logging-SYNNMFLN.js'),n,r;try{n=await this.getSemanticAgent(),r=n?.getVectorStore?.();}catch(p){t.w("AUTODOC","embeddings_skipped",{reason:"SemanticAgent not available",error:p.message});return}if(!n||!r){t.d("AUTODOC","embeddings_skipped",{reason:"Missing semanticAgent or vectorStore",hasAgent:!!n,hasStore:!!r});return}let s=n,a=r,c=await e.getAllDocuments();if(c.length===0)return;t.i("AUTODOC","embeddings_start",{totalDocs:c.length});let l=0,d=0,u=20;for(let p=0;p<c.length;p+=u){let m=c.slice(p,p+u);for(let h of m)try{if(!h.content||h.content.length<10){d++;continue}let v=`${h.title}
|
|
45
45
|
|
|
46
|
-
${h.content}`,A=await s.generateEmbedding(v);A&&(await a.insert({id:h.id,content:v.slice(0,1e3),vector:A,metadata:{type:"autodoc",docType:h.type,filePath:h.filePath,section:h.section,title:h.title,createdAt:Date.now()}}),l++);}catch{d++;}p+u<c.length&&await b(100);}if(t.i("AUTODOC","embeddings_complete",{generated:l,skipped:d,total:c.length}),l>0){t.i("AUTODOC","flushing_to_disk");let p=r;typeof p.flushAndSave=="function"&&await p.flushAndSave(),t.i("AUTODOC","embeddings_saved_to_disk");}}async getSemanticAgent(){if(this.config.getSemanticAgentFn)return this.config.getSemanticAgentFn();throw new Error("SemanticAgent getter not configured")}reset(){this._autodocEmbeddingsSubscriptionId&&(a$2.unsubscribe(this._autodocEmbeddingsSubscriptionId),this._autodocEmbeddingsSubscriptionId=null),this._autodocEmbeddingsGenerated=false,this._versionManager=null,this._codeModifier=null,this._fileOperations=null,this._codeValidator=null,this._technologyDetector=null,this._patternSearch=null,this._autoDocManager=null;}},
|
|
46
|
+
${h.content}`,A=await s.generateEmbedding(v);A&&(await a.insert({id:h.id,content:v.slice(0,1e3),vector:A,metadata:{type:"autodoc",docType:h.type,filePath:h.filePath,section:h.section,title:h.title,createdAt:Date.now()}}),l++);}catch{d++;}p+u<c.length&&await b(100);}if(t.i("AUTODOC","embeddings_complete",{generated:l,skipped:d,total:c.length}),l>0){t.i("AUTODOC","flushing_to_disk");let p=r;typeof p.flushAndSave=="function"&&await p.flushAndSave(),t.i("AUTODOC","embeddings_saved_to_disk");}}async getSemanticAgent(){if(this.config.getSemanticAgentFn)return this.config.getSemanticAgentFn();throw new Error("SemanticAgent getter not configured")}reset(){this._autodocEmbeddingsSubscriptionId&&(a$2.unsubscribe(this._autodocEmbeddingsSubscriptionId),this._autodocEmbeddingsSubscriptionId=null),this._autodocEmbeddingsGenerated=false,this._versionManager=null,this._codeModifier=null,this._fileOperations=null,this._codeValidator=null,this._technologyDetector=null,this._patternSearch=null,this._autoDocManager=null;}},to=null;function no(o){return to=new yr(o),to}R();var Ne=false;var X={conductor:null,layeredIndexManager:null};function ro(o){X={...X,...o};}async function Le(o){if(!Ne){Ne=true,I.i("SHUTDOWN","shutdown_start",{signal:o});try{await c$3(),I.i("SHUTDOWN","ovms_shutdown_ok");}catch(e){I.e("SHUTDOWN","ovms_shutdown_fail",{err:String(e)});}try{await a$a(),I.i("SHUTDOWN","mlx_shutdown_ok");}catch(e){I.e("SHUTDOWN","mlx_shutdown_fail",{err:String(e)});}try{await c$4(),I.i("SHUTDOWN","GPU Client Shutdown Complete");}catch(e){I.e("SHUTDOWN","Shutdown error",{error:String(e)});}try{await d$5(),I.i("SHUTDOWN","FAISS Provider Shutdown Complete");}catch(e){I.e("SHUTDOWN","Shutdown error",{error:String(e)});}X.conductor&&(await X.conductor.shutdown(),I.i("SHUTDOWN","Conductor Shutdown Complete")),X.layeredIndexManager&&(await X.layeredIndexManager.shutdown(),I.i("SHUTDOWN","LayeredIndexManager Shutdown Complete"));try{await g$2(),I.i("SHUTDOWN","GraphStorage closed");}catch(e){I.e("SHUTDOWN","GraphStorage close error",{err:String(e)});}Ie.stopMonitoring(),I.i("SHUTDOWN","Resource Manager Stopped"),I.i("SHUTDOWN","MCP Server Shutdown Complete",{signal:o}),process.exit(0);}}function io(o){process.on("SIGINT",()=>{Le("SIGINT");}),process.on("SIGTERM",()=>{Le("SIGTERM");}),process.on("beforeExit",async e=>{e===0&&!Ne&&await Le("beforeExit");}),o?.pipeMode?I.i("SHUTDOWN","pipe mode: stdin close handlers skipped"):(process.stdin.on("close",()=>{Ne||(I.i("SHUTDOWN","stdin closed (parent exited), shutting down..."),Le("stdin-close"));}),process.stdin.on("end",()=>{Ne||(I.i("SHUTDOWN","stdin ended (parent exited), shutting down..."),Le("stdin-end"));}));}function oo(){process.on("SIGUSR1",async()=>{try{let o={pid:process.pid,memory:process.memoryUsage(),uptime:process.uptime()};X.conductor&&(o.conductor={pendingTasks:X.conductor.getPendingTasksCount(),agents:Array.from(X.conductor.agents.values()).map(e=>{let t=e.getMetrics();return {id:e.id,type:e.type,status:e.status,memMB:e.getMemoryUsage(),queue:e.getTaskQueue().length,lastActivity:t.lastActivity}})}),I.w("INCIDENT","SIGUSR1 dump",o);}catch(o){I.w("INCIDENT","sigusr1_dump_fail",{err:String(o)});}});}R();R();var Zs="http://127.0.0.1:11434/api/tags",so=5e3;async function Sr(){try{let o=await fetch(Zs,{method:"GET"});if(o.ok){let t=(await o.json()).models||[],n=t.map(s=>s.name||s.model||"").filter(Boolean),r=n.some(s=>s.includes("granite-embedding"));return {isRunning:!0,hasModels:t.length>0,models:n,hasGranite:r}}}catch{}return {isRunning:false,hasModels:false,models:[],hasGranite:false}}async function ea(){try{return I.i("OLLAMA","start_attempt"),spawn("ollama",["serve"],{detached:!0,stdio:"ignore",shell:!0,windowsHide:!0}).unref(),I.d("OLLAMA","waiting_startup",{wait_ms:so}),await b(so),(await Sr()).isRunning?(I.i("OLLAMA","service_started"),!0):(I.w("OLLAMA","start_timeout"),!1)}catch(o){return I.w("OLLAMA","start_failed",{error:o.message}),false}}async function ao(o=true){let e=await Sr();return e.isRunning?(I.i("OLLAMA","service_running",{models:e.models.length,has_granite:e.hasGranite}),e):o?(I.i("OLLAMA","autostart_begin"),await ea()?await Sr():(I.w("OLLAMA","autostart_failed",{hint:"install from ollama.com or run 'ollama serve'"}),e)):(I.d("OLLAMA","autostart_disabled"),e)}function co(o){return o.isRunning?o.hasModels?o.hasGranite?`\u2705 Ollama \u0437\u0430\u043F\u0443\u0449\u0435\u043D \u0441 granite-embedding (${o.models.length} \u043C\u043E\u0434\u0435\u043B\u0435\u0439)`:`\u26A0\uFE0F Ollama \u0437\u0430\u043F\u0443\u0449\u0435\u043D, \u043D\u043E granite-embedding \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D. \u0423\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u043E: ${o.models.join(", ")}`:"\u26A0\uFE0F Ollama \u0437\u0430\u043F\u0443\u0449\u0435\u043D, \u043D\u043E \u043C\u043E\u0434\u0435\u043B\u0438 \u043D\u0435 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u044B. \u0417\u0430\u043F\u0443\u0441\u0442\u0438\u0442\u0435: ollama pull granite-embedding":"\u274C Ollama \u043D\u0435 \u0437\u0430\u043F\u0443\u0449\u0435\u043D. \u0417\u0430\u043F\u0443\u0441\u0442\u0438\u0442\u0435 setup-embedding \u0434\u043B\u044F \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438 \u043F\u0440\u043E\u0432\u0430\u0439\u0434\u0435\u0440\u0430 \u044D\u043C\u0431\u0435\u0434\u0434\u0438\u043D\u0433\u043E\u0432"}function lo(o){o.embeddingEnabled&&(o.embeddingProvider!=="auto"&&o.embeddingProvider!=="ollama"||(I.t("STARTUP",`[+${Date.now()-o.processStartTime}ms] \u25B6 Launching async: Ollama check`),I.i("STARTUP","ollama_check_bg"),(async()=>{try{let e=Date.now();I.t("STARTUP","ollama_start");let t=await ao(!0);I.t("STARTUP","ollama_end",{elapsed:Date.now()-e});let n=co(t);I.i("STARTUP","ollama_status",{msg:n}),t.isRunning?!t.hasGranite&&t.hasModels&&I.i("STARTUP","granite_missing"):I.i("STARTUP","ollama_not_running");}catch(e){I.w("STARTUP","Ollama check failed, will use auto-detection",{error:e.message}),I.w("STARTUP","ollama_check_fail");}})()));}function po(o){!o.embeddingEnabled||o.pipeServerMode||(I.t("STARTUP","orphan_emb_start"),(async()=>{try{let e=Date.now(),t=await o.getSemanticAgent();if(I.t("STARTUP","semantic_agent_got",{elapsed:Date.now()-e}),!t)return;let{getGraphStorage:n}=await import('./chunks/graph-storage-factory-GTAIJEI5.js'),r=await n(),a=(await r.findEntities({limit:1})).length>0?(await r.findEntities({limit:1e5})).length:0;if(a===0)return;let c=await t.getVectorStore()?.count()??0,l=a-c;if(l>10){if(t.isEmbeddingGenerationInProgress()){I.w("STARTUP","[SKIPPED] generation already in progress",{missing:l});return}if(t.wasGenerationRecentlyCompleted(3e4)){I.w("STARTUP","[SKIPPED] generation recently completed",{missing:l});return}I.i("STARTUP",`Found ${l} entities without embeddings, generating in background`,{missing:l}),I.t("STARTUP","emb_gen_start",{missing:l}),I.i("STARTUP","Resuming embedding generation",{missing:l,entityCount:a,embeddingCount:c});let d=Date.now();t.generateEmbeddingsFromStorage().then(u=>{I.t("STARTUP","emb_gen_end",{elapsed:Date.now()-d}),I.i("STARTUP","Background embedding complete",{generated:u.generated,skipped:u.skipped});}).catch(u=>{I.e("EMBEDDING","bg_gen_fail",{err:u.message});});}else I.t("STARTUP","orphan_emb_skip",{missing:l});}catch(e){I.w("STARTUP","bg_emb_check_fail",{err:e.message});}})());}R();H();function br(){let o=new Date,e=-o.getTimezoneOffset(),t=e>=0?"+":"-",n=String(Math.floor(Math.abs(e)/60)).padStart(2,"0"),r=String(Math.abs(e)%60).padStart(2,"0");return `${new Date(o.getTime()-o.getTimezoneOffset()*6e4).toISOString().slice(0,-1)}${t}${n}:${r}`}function oa(){let o=new Date;return new Date(o.getTime()-o.getTimezoneOffset()*6e4).toISOString().slice(0,10)}function wr(o){try{let e=d();existsSync(e)||mkdirSync(e,{recursive:!0});let t=oa(),n=join(e,`mcp-server-${t}.log`);appendFileSync(n,o+`
|
|
47
47
|
`);}catch{process.stderr.write(o+`
|
|
48
|
-
`);}}var
|
|
49
|
-
${o.stack}`;
|
|
50
|
-
${n.stack}`;
|
|
51
|
-
Node ${ge.nodeVersion} (${ge.platform} ${ge.arch})`),process.exit(0));Mt.length<1&&Mt.push(process.cwd());
|
|
52
|
-
`),process.exit(1);}}
|
|
48
|
+
`);}}var uo={},_r=Date.now();function mo(o){_r=o;}function _e(o){uo[o]=Date.now();let e=Date.now()-_r;I.t("STARTUP",`[+${e}ms] \u25B6 START: ${o}`);}function xe(o){let e=Date.now()-(uo[o]||Date.now()),t=Date.now()-_r;return I.t("STARTUP",`[+${t}ms] \u25C0 END: ${o} (${e}ms)`),I.i("STARTUP","timer_end",{name:o,dur:e}),e}R();Q();p();c();process.argv.includes("--pipe")&&(process.env.MCP_QUIET_MODE="true");(()=>{let o=typeof globalThis.Bun<"u",e=process.env.MCP_QUIET_MODE==="true";if(o&&e){let t=()=>{};console.error=t,console.warn=t,console.log=t,console.info=t,console.debug=t;}else if(e){let t=()=>{};console.error=t,console.warn=t,console.log=t,console.info=t,console.debug=t;}})();function sa(){let o={...process.env,NODE_ENV:process.env.NODE_ENV||"development",MCP_EMBEDDING_ENABLED:process.env.MCP_EMBEDDING_ENABLED||"true",MCP_EMBEDDING_PROVIDER:process.env.MCP_EMBEDDING_PROVIDER||"transformers",MCP_EMBEDDING_FALLBACK:process.env.MCP_EMBEDDING_FALLBACK||"true"};return globalThis.env=o,o}sa();global.knowledgeBus=a$2;process.on("uncaughtException",(o,e)=>{let n=`[${br()}] [FATAL] [CRASH] Uncaught exception (${e}): ${o.message}
|
|
49
|
+
${o.stack}`;wr(n),console.error(n),(async()=>{let r=Date.now();for(;Date.now()-r<100;)await b(10);process.exit(1);})();});process.on("unhandledRejection",(o,e)=>{let t=br(),n=o instanceof Error?o:new Error(String(o)),r=`[${t}] [FATAL] [CRASH] Unhandled rejection: ${n.message}
|
|
50
|
+
${n.stack}`;wr(r),console.error(r);});var me=Date.now();mo(me);_e("initHasher");await a$3();xe("initHasher");_e("initializeStorageDirs");F();xe("initializeStorageDirs");var ya=bi(),{configPath:ho,helpRequested:Sa,versionRequested:ba,setupRequested:wa,noAutoIndex:fo,pipeServerMode:Pt,quietMode:_a,positionalArgs:Mt}=ya;Sa&&(wi(),process.exit(0));wa&&_i(import.meta.url);var ge=Zi(import.meta.url);ba&&(console.error(`${ge.name} ${ge.version}
|
|
51
|
+
Node ${ge.nodeVersion} (${ge.platform} ${ge.arch})`),process.exit(0));Mt.length<1&&Mt.push(process.cwd());ho&&a$4.setOverridePath(ho);var x=normalize(resolve(hr(Mt[0])));var xo=Mt.slice(1),Ar=[],xa=xo.length>0;for(let o of xo){let e=o.trim();if(e)try{Ar.push({raw:e,parsed:JSON.parse(e)});}catch(t){process.stderr.write(`[Debug] Failed to parse JSON: ${t instanceof Error?t.message:String(t)}
|
|
52
|
+
`),process.exit(1);}}xa&&(process.env.MCP_DEBUG_MODE=process.env.MCP_DEBUG_MODE??"1",process.env.PARSER_DISABLE_CACHE||(process.env.PARSER_DISABLE_CACHE="1"),process.env.MCP_DEBUG_DISABLE_SEMANTIC=process.env.MCP_DEBUG_DISABLE_SEMANTIC??"1");function Ca(o){if(!o)return;let e=hr(o),t=isAbsolute(e)?e:resolve(x,e);return normalize(t)}_e("initializeConfig");var se=d$1();xe("initializeConfig");var yo=e(se);if(!yo.valid){if(!_a){console.error("[Config] Configuration validation failed:");for(let o of yo.errors)console.error(` - ${o}`);}process.exit(1);}b$1(x);Ti();Di(q(x));I.i("STARTUP","init",{dir:x,dbPath:se.database.path??"default",cwd:process.cwd()});I.i("STORAGE","graph_init",{type:"libsql"});var Aa=m();c$1({dimensions:Aa});_e("initializeGraphStorage");await e$1();xe("initializeGraphStorage");var So=null,va=Date.now();try{So=b$2().start(),So.then(e=>{I.i("GPU","worker_started",{dur:Date.now()-va,ok:e});}).catch(e=>{I.e("GPU","worker_start_fail",{err:e.message});}),I.i("GPU","worker_init",{blocking:!1});}catch(o){I.e("GPU","worker_init_fail",{err:o.message});}var xr=c$2(x);xr&&d$2()&&f(xr).then(o=>{I.i("ROSLYN","addon_started",{sln:xr,available:!!o});}).catch(o=>{I.e("ROSLYN","addon_start_fail",{err:o.message});});var Ta=await d$3(),Co=v(x);Ta.setProject(x,Co);I.i("STORAGE","project_set",{proj:q(x),branch:Co});I.i("SYSTEM","mcp_starting",{dir:x,node:process.version,plat:process.platform,env:se.environment});var bo=se.conductor.resourceConstraints,Ao=i(),Da=Ao?.embedding?.platform,Ea=se.mcp.embedding?.provider,vo=Da||Ea||"auto",Pa=a$5(Ao,se);Pa.catch(o=>{I.w("WARMUP","Background warmup failed (will retry later)",{err:o.message});});Pt||Ie.startMonitoring();I.i("SYSTEM","resource_mgr",{memMB:bo.maxMemoryMB,cpu:bo.maxCpuPercent,provider:vo});vo==="ovms-native"&&(await b$3({enabled:true,autoStart:true,restPort:8083,grpcPort:9001,healthCheckIntervalMs:3e4,startupTimeoutMs:12e4})?I.i("OVMS","started",{port:8083,grpc:9001}):I.e("OVMS","start_fail",{hint:"run setup-embedding"}));_e("registerAllAgents");var Rt=a$6();await b$4(Rt);xe("registerAllAgents");I.i("SYSTEM","di_ready",{agents:"all"});var oe=null;function J(){return oe||(oe=new Xe(se.conductor??{}),ro({conductor:oe})),oe}var Ma=null,Cr=null;function vr(){return Cr||(Cr=no({directory:x,getConductor:J,getGlobalVectorStore:()=>Ma,getSemanticAgentFn:()=>Ce()})),Cr}var wo=null;async function Ce(){let o=a$b();I.t("AGENT","get_semantic",{dir:o??"none"});let e=J();await e.initialize();let t=await c$6(Rt,e,"semantic"),n=t;if(t&&typeof n.reinitializeForProject=="function"&&o){let s=n.getVectorStore?.()?.getProjectContext?.(),a=q(o);s?.projectHash!==a&&(I.w("AGENT","project_mismatch",{cur:s?.projectHash,exp:a}),await n.reinitializeForProject(o));}return t}async function Tr(){let o=J();return await o.initialize(),await c$6(Rt,o,"dev")}async function To(){let o=J();return await o.initialize(),await c$6(Rt,o,"dora")}function Do(o){let e=new Server({name:ge.name,version:ge.version},{capabilities:{tools:{listChanged:true},prompts:{listChanged:true}}});return e.setRequestHandler(ListPromptsRequestSchema,async()=>({prompts:[{name:"quick-start",description:"Quick start guide for UltraCode - when and how to use tools"},{name:"tool-reference",description:"Complete reference of all 50+ tools with parameters and examples"},{name:"workflows",description:"Common workflows: analyze project, search & refactor, find duplicates, git integration"},{name:"tracing-guide",description:"Code tracing guide - trace_flow, trace_backwards, data flow analysis, state impact"},{name:"autodoc-guide",description:"AutoDoc guide - automatic documentation layer with semantic search, code-doc linking"},{name:"explore-guide",description:"Explore Agent guide - fast codebase reconnaissance, search & navigation optimized for speed"},{name:"planning-guide",description:"Planning Agent guide - risk assessment, impact analysis, tracing for safe refactoring"},{name:"modification-guide",description:"Modification Agent guide - safe code changes with snapshots, validation, and auto-rollback"},{name:"patterns-guide",description:"Pattern detection guide \u2014 anti-patterns, best-practices, code smells, optimization with semantic validation"}]})),e.setRequestHandler(GetPromptRequestSchema,async t=>{let{name:n}=t.params,r=join(dirname(fileURLToPath(import.meta.url)),"..","prompts"),s=join(r,`${n}.md`);try{let a=readFileSync(s,"utf-8");return {description:`UltraCode - ${n}`,messages:[{role:"user",content:{type:"text",text:a}}]}}catch{throw new Error(`Prompt not found: ${n}`)}}),e.setRequestHandler(ListToolsRequestSchema,async()=>({tools:we()})),e.setRequestHandler(CallToolRequestSchema,async t=>{let{name:n,arguments:r}=t.params,s=Pe(),a=Date.now();return I.i("MCP","request",{tool:n,req:s,sid:o?.sessionId,proj:o?.projectPath,args:Eo(r)}),Po(n,r,s,a,o)}),e}var Ra=Do();async function Ia(o,e,t,n){let r=false,s=new Promise((a,c)=>{let l=Date.now();(async()=>{for(;!r&&Date.now()-l<e;)await b(100);if(!r){let u=new Error(`${t} timed out after ${e}ms`);I.e("MCP","timeout",{label:t,ms:e,req:n}),c(u);}})();});try{return await Promise.race([o,s])}finally{r=true;}}function Eo(o){if(!o||typeof o!="object")return "";let e=o,t=[];for(let[n,r]of Object.entries(e))r!=null&&(typeof r=="string"?t.push(`${n}=${r.length>60?r.slice(0,60)+"\u2026":r}`):Array.isArray(r)?t.push(`${n}=[${r.length}]`):(typeof r=="boolean"||typeof r=="number")&&t.push(`${n}=${r}`));return t.join(" ")}var ka=fa(1),Oa=new Set(["taint_analysis","graph_metrics","analyze_hotspots","analyze_code_impact","suggest_refactoring","analyze_state_chaos","analyze_swagger_impact","louvain_communities","pagerank","centrality_analysis","bus_factor"]);function La(o,e){let t=0;for(let r of e.content)t+=Buffer.byteLength(r.text,"utf8");return t<=5e4?e:{content:e.content.map(r=>{if(Buffer.byteLength(r.text,"utf8")<=5e4)return r;try{let a=JSON.parse(r.text),c=c$7(a,5e4),l=JSON.parse(c.text);return l._responseMeta={truncated:!0,originalSizeBytes:c.originalSize,truncatedSizeBytes:c.truncatedSize,hint:`Response from ${o} was truncated. Use 'offset' and 'limit' parameters for pagination.`},{type:"text",text:JSON.stringify(l,null,2)}}catch{return {type:"text",text:r.text.slice(0,5e4)+`
|
|
53
53
|
|
|
54
|
-
[TRUNCATED by enforceResponseLimit \u2014 use offset/limit for ${o}]`}}})}}async function
|
|
54
|
+
[TRUNCATED by enforceResponseLimit \u2014 use offset/limit for ${o}]`}}})}}async function Po(o,e,t,n,r){let s=new Set(["index","clean_index","reset_graph","get_version","get_metrics","get_agent_metrics","get_bus_stats","get_graph_stats","get_graph_health"]),a=e,c=a?.directory||a?.projectPath,l=(c?r?.resolvePath(c)??c:r?.projectPath)??x;if(Ei(l)&&!s.has(o)){let d=et(),u=`\u23F3 Indexing is currently in progress for this project. Please wait and retry.
|
|
55
55
|
|
|
56
56
|
\u{1F4C2} Directory: ${l}
|
|
57
57
|
\u23F1\uFE0F Elapsed: ${d.elapsedSeconds||0} seconds
|
|
58
58
|
|
|
59
|
-
Tip: You can work with other projects while this one is indexing.`;return I.i("INDEXER","tool_blocked",{tool:o,dir:l,elapsed:d.elapsedSeconds??0}),{content:[{type:"text",text:JSON.stringify({success:false,errorType:"indexing_in_progress",error:"Indexing is currently in progress for this project. Please retry after indexing completes.",message:u,status:{directory:l,elapsedSeconds:d.elapsedSeconds,otherProjectsBlocked:false},retryAfterSeconds:10},null,2)}]}}try{let d=r?.projectPath??l??x;r?.markActivity(),J().markActivity();let u={requestId:t,config:se,session:r,projectPath:d,getConductor:J,getGraphStorage:async()=>{let p=await b$3(),m=v(d);return p.setProject(d,m),p},getSQLiteManager:()=>null,getSemanticAgent:Ce,getBranchManager:async()=>{let p=J();return await p.initialize(),p.getAgentByType?.("dev")?.getIndexerAgent?.()?.getBranchManager?.()||null},getSnapshotManager:async()=>await Ar().getVersionManager(),getKnowledgeBus:()=>a$2,getServiceContainer:()=>Ar(),normalizeInputPath:_a,withTimeout:Ma,createAutoIndexContext:Tr};if(Oe.has(o))return Ia.has(o)?await Ra(async()=>{let h=await(await Oe.getHandler(o,u)).handle(e);return ka(o,h)}):(await Oe.getHandler(o,u)).handle(e);throw new Error(`Unknown tool: ${o}. Available tools: ${Oe.getRegisteredTools().join(", ")}`)}catch(d){let u=d instanceof Error?d.message:String(d);return d instanceof a$9?(I.w("AGENT","busy",{agent:d.details.agentId,tool:o,req:t}),{content:[{type:"text",text:JSON.stringify({success:false,errorType:"agent_busy",error:u,details:d.details},null,2)}]}):(I.e("MCP","error",{tool:o,req:t,err:u}),{content:[{type:"text",text:JSON.stringify({success:false,error:u},null,2)}]})}}async function Oa(o){for(let{parsed:e,raw:t}of o){let n=(()=>{try{return CallToolRequestSchema.parse(e)}catch(h){throw I.e("DEBUG","invalid_payload",{raw:t}),h}})(),{name:r,arguments:s}=n.params,c=e?.id,l=typeof c=="string"||typeof c=="number"?c:Pe(),d=typeof l=="string"?l:String(l);J().markActivity(),I.i("MCP","request",{tool:r,req:d,args:To(s)});let p=await Do(r,s,d);console.error(JSON.stringify({jsonrpc:"2.0",id:l,result:p},null,2));}}no({pipeMode:Pt});ro();function Tr(){return {getSemanticAgent:Ce,getDevAgent:vr,getDoraAgent:Ao,getConductor:J,getGraphStorage:b$3,setCurrentIndexingDirectory:b$1,processStartTime:me}}async function La(o){Fi().catch(s=>{I.w("SKILLS","install_failed",{err:s.message});}),I.i("STARTUP","server_starting",{dir:o.directory}),I.i("STARTUP","architecture",{type:"multi_agent_literag"}),I.i("STARTUP","constraints",{mem:"1GB",cpu:"80%",agents:10});let e=o.config.mcp?.embedding?.enabled??false,t=o.config.mcp?.embedding?.provider??"auto";if(ao({embeddingEnabled:e,embeddingProvider:t,processStartTime:o.processStartTime}),co({embeddingEnabled:e,pipeServerMode:o.pipeServerMode,processStartTime:o.processStartTime,getSemanticAgent:Ce}),I.t("STARTUP","autodoc_check",{ms:Date.now()-o.processStartTime}),o.config.mcp?.autodoc?.watcherEnabled??true){I.t("STARTUP","autodoc_init",{ms:Date.now()-o.processStartTime});try{let s=o.config.mcp?.autodoc?.useLlm;if(s===void 0)try{let{detectLLMProviders:l}=await import('./chunks/llm-provider-ZCW4DWD3.js'),{recommended:d}=await l();s=!!d,s&&I.i("AUTODOC","llm_auto_detected",{provider:d?.name});}catch{s=!1;}let a={rootDir:o.directory,enabled:!0,debounceMs:o.config.mcp?.autodoc?.debounceMs??45e3,minDebounceMs:o.config.mcp?.autodoc?.minDebounceMs??3e4,maxDebounceMs:o.config.mcp?.autodoc?.maxDebounceMs??6e4,useLlm:s,llmConfig:o.config.mcp?.autodoc?.llmConfig};Qe(a).start(),I.i("AUTODOC","watcher_started",{dir:o.directory,debounce:a.debounceMs??0,useLlm:s}),(async()=>{await b(2e3);try{let l=await Ar().getAutoDocManager();l&&I.i("AUTODOC","manager_initialized",{enabled:!!l.getConfig()?.enabled});}catch{}})();}catch(s){I.w("AUTODOC","watcher_failed",{err:s.message});}}let r=300*1e3;(async()=>{for(await b(6e4);;){await b(r);let s=process.memoryUsage();if(c$5(true)){let a=process.memoryUsage(),c=Math.round((s.heapUsed-a.heapUsed)/1024/1024);M("MAIN",{event:"periodic_gc",freedMB:c});}}})();}async function Na(){let o=Date.now();I.t("STARTUP","main_started",{ms:o-me});let e=a$4.getInstance().getConfig();La({config:e,directory:x,pipeServerMode:Pt,processStartTime:me});let t;if(Pt){let A=function(){let f=++p;u=true,I.i("PIPE","shutdown_scheduled",{delay:h$1,clients:0,gen:f}),(async()=>{let _=Date.now();for(;u&&p===f&&Date.now()-_<h$1;)await b(50);u&&p===f&&d===0&&v$1();})();},C=function(){u&&(u=false,p++,I.i("PIPE","shutdown_cancelled",{reason:"client_reconnected"}));};let c=new at,l=0,d=0,u=false,p=0,m=false,h$1=2e3;async function v$1(){if(!m){m=true,I.i("PIPE","shutdown_start",{reason:"all_clients_disconnected"});try{if(await c.close(),I.i("PIPE","server_closed",{}),oe){I.t("PIPE","wait_pending",{});let f=0,T=3e4/100;for(;f<T;){let F=0;for(let L of oe.agents.values())F+=L.getTaskQueue().length;if(F===0)break;f%50===0&&I.t("PIPE","pending_tasks",{cnt:F}),await b(100),f++;}I.i("PIPE","agents_idle",{});}try{I.t("OVMS","shutdown_start",{}),await c$3(),I.i("OVMS","shutdown_ok",{});}catch(f){I.e("OVMS","shutdown_err",{err:String(f)});}try{I.t("GPU","shutdown_start",{}),await c$4(),I.i("GPU","shutdown_ok",{});}catch(f){I.e("GPU","shutdown_err",{err:String(f)});}try{I.t("FAISS","shutdown_start",{}),await d$4(),I.i("FAISS","shutdown_ok",{});}catch(f){I.e("FAISS","shutdown_err",{err:String(f)});}try{I.t("ROSLYN","shutdown_start",{}),await h(),I.i("ROSLYN","shutdown_ok",{});}catch(f){I.e("ROSLYN","shutdown_err",{err:String(f)});}oe&&(I.t("CONDUCTOR","shutdown_start",{}),await oe.shutdown(),I.i("CONDUCTOR","shutdown_ok",{})),So&&(I.t("INDEXER","shutdown_start",{}),await So.shutdown(),I.i("INDEXER","shutdown_ok",{}));try{I.t("STORAGE","shutdown_start",{}),await e$1(),I.i("STORAGE","shutdown_ok",{});}catch(f){I.e("STORAGE","shutdown_err",{err:String(f)});}Ie.stopMonitoring(),I.i("PIPE","shutdown_complete",{exitCode:0}),process.exit(0);}catch(f){I.e("PIPE","shutdown_err",{err:f.message}),process.exit(1);}}}I.i("PIPE","starting",{path:c.getPath(),mode:"multi-client"}),await c.start(async f=>{if(m){I.w("PIPE","reject_during_shutdown",{reason:"shutdown_in_progress"}),f.close();return}l++,d++;let _=l;C();let S=x;try{let L=await f.readInitMessage(2e3);L&&(S=normalize(resolve(L)),I.i("PIPE","client_cwd",{client:_,cwd:S}));}catch(L){I.w("PIPE","init_msg_fail",{client:_,err:L.message});}let T=new it({projectPath:S,clientId:_});Gi(T),I.i("PIPE","client_connected",{client:_,active:d,sid:T.sessionId,proj:T.projectPath});let F=vo(T);f.onclose=()=>{d--,Bi(T.sessionId),I.i("PIPE","client_disconnected",{client:_,active:d,sid:T.sessionId}),d===0&&A();},await F.connect(f),I.i("PIPE","client_ready",{client:_,active:d,sid:T.sessionId}),S!==x&&setImmediate(async()=>{try{let L=e.indexing;if(!(L?.autoIndex??!0)){I.t("INDEXER","autoindex_disabled_client",{client:_});return}let ae=await b$3(),R=q(S),b=v(S);ae.setProject(S,b);let Pr=(await ae.getStatistics()).totalEntities??0;if(Pr>0){I.i("INDEXER","client_project_indexed",{client:_,proj:R,entities:Pr});return}let Mr=L?.autoIndexExtensions??[".ts",".tsx",".js",".jsx",".py",".go",".rs",".kt",".swift",".c",".cpp",".java",".cs"],Rr=await An(S,Mr);if(!Rr.supported){I.i("INDEXER","client_no_files",{client:_,dir:S});return}I.i("INDEXER","client_autoindex_start",{client:_,dir:S,ext:Rr.detectedExt}),b$1(S),await Me(S,Mr,Tr(),!1),I.i("INDEXER","client_autoindex_done",{client:_,dir:S});}catch(L){I.e("INDEXER","client_autoindex_fail",{client:_,err:L.message});}});}),t="pipe-multi",I.i("MCP","server_ready",{dir:x,transport:t,tools:we().length});}else {I.t("STARTUP","stdio_connect",{ms:Date.now()-me});let c=new StdioServerTransport;t="stdio";let l=Date.now();await Pa.connect(c),I.t("STARTUP","stdio_connected",{ms:Date.now()-me,dur:Date.now()-l}),I.i("MCP","server_ready",{dir:x,transport:t,tools:we().length});}if(Cr.length>0){try{await vr(),await Ao(),process.env.MCP_DEBUG_DISABLE_SEMANTIC!=="1"&&await Ce(),await Oa(Cr),I.i("DEBUG","requests_complete",{}),process.exit(0);}catch(c){I.e("DEBUG","request_failed",{err:c instanceof Error?c.message:String(c)}),process.exit(1);}return}b$1(x),I.i("STARTUP","agents_registered",{}),I.t("STARTUP","autoindex_check",{ms:Date.now()-me});let n=e.indexing,r=!go&&(n?.autoIndex??true);if(I.t("INDEXER","autoindex_config",{shouldAutoIndex:r,noAutoIndex:go}),r){let c=n?.autoIndexExtensions??[".ts",".tsx",".js",".jsx",".py",".go",".rs",".kt",".swift",".c",".cpp",".java",".cs"];setImmediate(async()=>{try{let l=await b$3(),d=q(x),u=v(x);I.t("INDEXER","check_index",{dir:x,hash:d,branch:u}),l.setProject(x,u);let p=await l.getStatistics(),m=p.totalEntities??0;I.t("INDEXER","stats",{entities:m,rels:p.totalRelationships,files:p.totalFiles});let h=!1,v$1=.4;if(m>0){let C=await Ei(x,c),f=p.totalFiles??0,S=(await l.getIncrementalTrackingInfo()).incrementalChangesCount,T=f>0?S/f:0;if(T>v$1)I.i("INDEXER","cumulative_threshold",{changes:S,files:f,pct:(T*100).toFixed(1),threshold:(v$1*100).toFixed(0)}),h=!1;else {let F=C-f,L=f>0?F/f*100:0;if(C>0&&(F>10||L>20))I.i("INDEXER","index_incomplete",{indexed:f,disk:C,missing:F,changes:S}),h=!0;else {I.i("INDEXER","index_exists",{entities:m,files:f,disk:C,changes:S});try{let Q=await vr();I.i("DEVAGENT","init_for_incremental",{hasAgent:!!Q});let ae=await Ce();I.i("SEMANTIC","init_for_incremental",{hasAgent:!!ae});let b=Q?.getIndexerAgent?.()??null;b?.setRepositoryPath?(b.setProjectContext&&b.setProjectContext(x),await b.setRepositoryPath(x),I.i("INDEXER","watcher_started_existing",{dir:x})):I.w("INDEXER","watcher_no_agent",{hasAgent:!!b,reason:"DevAgent.getIndexerAgent() returned null"});}catch(Q){I.w("INDEXER","watcher_start_fail",{err:Q.message});}return}}}let A=await An(x,c);if(!A.supported){I.i("INDEXER","no_files",{dir:x});return}I.i("INDEXER","project_detected",{ext:A.detectedExt??"unknown",sample:A.sampleFile??"none"}),await Me(x,c,Tr(),h);}catch(l){I.e("INDEXER","autoindex_failed",{err:l.message});}});}}Na().catch(o=>{I.e("STARTUP","server_failed",{err:o.message}),process.exit(1);});export{es as areTimersSuspended,et as getIndexingStatus,Cn as isIndexing,Ti as isProjectIndexing,Zo as registerAsyncLoopStarter,ts as resumeTimers,tt as setIndexingState};
|
|
59
|
+
Tip: You can work with other projects while this one is indexing.`;return I.i("INDEXER","tool_blocked",{tool:o,dir:l,elapsed:d.elapsedSeconds??0}),{content:[{type:"text",text:JSON.stringify({success:false,errorType:"indexing_in_progress",error:"Indexing is currently in progress for this project. Please retry after indexing completes.",message:u,status:{directory:l,elapsedSeconds:d.elapsedSeconds,otherProjectsBlocked:false},retryAfterSeconds:10},null,2)}]}}try{let d=r?.projectPath??l??x;r?.markActivity(),J().markActivity();let u={requestId:t,config:se,session:r,projectPath:d,getConductor:J,getGraphStorage:async()=>{let p=await d$3(),m=v(d);return p.setProject(d,m),p},getSQLiteManager:()=>null,getSemanticAgent:Ce,getBranchManager:async()=>{let p=J();return await p.initialize(),p.getAgentByType?.("dev")?.getIndexerAgent?.()?.getBranchManager?.()||null},getSnapshotManager:async()=>await vr().getVersionManager(),getKnowledgeBus:()=>a$2,getServiceContainer:()=>vr(),normalizeInputPath:Ca,withTimeout:Ia,createAutoIndexContext:Dr};if(Oe.has(o)){let p=a$8(d);return Oa.has(o)?await ka(()=>b$6(p,async()=>{let h=await(await Oe.getHandler(o,u)).handle(e);return La(o,h)})):b$6(p,async()=>(await Oe.getHandler(o,u)).handle(e))}throw new Error(`Unknown tool: ${o}. Available tools: ${Oe.getRegisteredTools().join(", ")}`)}catch(d){let u=d instanceof Error?d.message:String(d);return d instanceof a$9?(I.w("AGENT","busy",{agent:d.details.agentId,tool:o,req:t}),{content:[{type:"text",text:JSON.stringify({success:false,errorType:"agent_busy",error:u,details:d.details},null,2)}]}):(I.e("MCP","error",{tool:o,req:t,err:u}),{content:[{type:"text",text:JSON.stringify({success:false,error:u},null,2)}]})}}async function Na(o){for(let{parsed:e,raw:t}of o){let n=(()=>{try{return CallToolRequestSchema.parse(e)}catch(h){throw I.e("DEBUG","invalid_payload",{raw:t}),h}})(),{name:r,arguments:s}=n.params,c=e?.id,l=typeof c=="string"||typeof c=="number"?c:Pe(),d=typeof l=="string"?l:String(l);J().markActivity(),I.i("MCP","request",{tool:r,req:d,args:Eo(s)});let p=await Po(r,s,d);console.error(JSON.stringify({jsonrpc:"2.0",id:l,result:p},null,2));}}io({pipeMode:Pt});oo();function Dr(){return {getSemanticAgent:Ce,getDevAgent:Tr,getDoraAgent:To,getConductor:J,getGraphStorage:d$3,setCurrentIndexingDirectory:b$1,processStartTime:me}}async function ja(o){Gi().catch(s=>{I.w("SKILLS","install_failed",{err:s.message});}),I.i("STARTUP","server_starting",{dir:o.directory}),I.i("STARTUP","architecture",{type:"multi_agent_literag"}),I.i("STARTUP","constraints",{mem:"1GB",cpu:"80%",agents:10});let e=o.config.mcp?.embedding?.enabled??false,t=o.config.mcp?.embedding?.provider??"auto";if(lo({embeddingEnabled:e,embeddingProvider:t,processStartTime:o.processStartTime}),po({embeddingEnabled:e,pipeServerMode:o.pipeServerMode,processStartTime:o.processStartTime,getSemanticAgent:Ce}),I.t("STARTUP","autodoc_check",{ms:Date.now()-o.processStartTime}),o.config.mcp?.autodoc?.watcherEnabled??true){I.t("STARTUP","autodoc_init",{ms:Date.now()-o.processStartTime});try{let s=o.config.mcp?.autodoc?.useLlm;if(s===void 0)try{let{detectLLMProviders:l}=await import('./chunks/llm-provider-ZCW4DWD3.js'),{recommended:d}=await l();s=!!d,s&&I.i("AUTODOC","llm_auto_detected",{provider:d?.name});}catch{s=!1;}let a={rootDir:o.directory,enabled:!0,debounceMs:o.config.mcp?.autodoc?.debounceMs??45e3,minDebounceMs:o.config.mcp?.autodoc?.minDebounceMs??3e4,maxDebounceMs:o.config.mcp?.autodoc?.maxDebounceMs??6e4,useLlm:s,llmConfig:o.config.mcp?.autodoc?.llmConfig};Qe(a).start(),I.i("AUTODOC","watcher_started",{dir:o.directory,debounce:a.debounceMs??0,useLlm:s}),(async()=>{await b(2e3);try{let l=await vr().getAutoDocManager();l&&I.i("AUTODOC","manager_initialized",{enabled:!!l.getConfig()?.enabled});}catch{}})();}catch(s){I.w("AUTODOC","watcher_failed",{err:s.message});}}let r=300*1e3;(async()=>{for(await b(6e4);;){await b(r);let s=process.memoryUsage();if(c$5(true)){let a=process.memoryUsage(),c=Math.round((s.heapUsed-a.heapUsed)/1024/1024);M("MAIN",{event:"periodic_gc",freedMB:c});}}})();}async function Ua(){let o=Date.now();I.t("STARTUP","main_started",{ms:o-me});let e=a$4.getInstance().getConfig();ja({config:e,directory:x,pipeServerMode:Pt,processStartTime:me});let t;if(Pt){let A=function(){let f=++p;u=true,I.i("PIPE","shutdown_scheduled",{delay:h$1,clients:0,gen:f}),(async()=>{let _=Date.now();for(;u&&p===f&&Date.now()-_<h$1;)await b(50);u&&p===f&&d===0&&v$1();})();},C=function(){u&&(u=false,p++,I.i("PIPE","shutdown_cancelled",{reason:"client_reconnected"}));};let c=new at,l=0,d=0,u=false,p=0,m=false,h$1=2e3;async function v$1(){if(!m){m=true,I.i("PIPE","shutdown_start",{reason:"all_clients_disconnected"});try{if(await c.close(),I.i("PIPE","server_closed",{}),oe){I.t("PIPE","wait_pending",{});let f=0,T=3e4/100;for(;f<T;){let F=0;for(let L of oe.agents.values())F+=L.getTaskQueue().length;if(F===0)break;f%50===0&&I.t("PIPE","pending_tasks",{cnt:F}),await b(100),f++;}I.i("PIPE","agents_idle",{});}try{I.t("OVMS","shutdown_start",{}),await c$3(),I.i("OVMS","shutdown_ok",{});}catch(f){I.e("OVMS","shutdown_err",{err:String(f)});}try{I.t("GPU","shutdown_start",{}),await c$4(),I.i("GPU","shutdown_ok",{});}catch(f){I.e("GPU","shutdown_err",{err:String(f)});}try{I.t("FAISS","shutdown_start",{}),await d$5(),I.i("FAISS","shutdown_ok",{});}catch(f){I.e("FAISS","shutdown_err",{err:String(f)});}try{I.t("ROSLYN","shutdown_start",{}),await h(),I.i("ROSLYN","shutdown_ok",{});}catch(f){I.e("ROSLYN","shutdown_err",{err:String(f)});}oe&&(I.t("CONDUCTOR","shutdown_start",{}),await oe.shutdown(),I.i("CONDUCTOR","shutdown_ok",{})),wo&&(I.t("INDEXER","shutdown_start",{}),await wo.shutdown(),I.i("INDEXER","shutdown_ok",{}));try{I.t("STORAGE","shutdown_start",{}),await g$2(),I.i("STORAGE","shutdown_ok",{});}catch(f){I.e("STORAGE","shutdown_err",{err:String(f)});}Ie.stopMonitoring(),I.i("PIPE","shutdown_complete",{exitCode:0}),process.exit(0);}catch(f){I.e("PIPE","shutdown_err",{err:f.message}),process.exit(1);}}}I.i("PIPE","starting",{path:c.getPath(),mode:"multi-client"}),await c.start(async f=>{if(m){I.w("PIPE","reject_during_shutdown",{reason:"shutdown_in_progress"}),f.close();return}l++,d++;let _=l;C();let S=x;try{let L=await f.readInitMessage(2e3);L&&(S=normalize(resolve(L)),I.i("PIPE","client_cwd",{client:_,cwd:S}));}catch(L){I.w("PIPE","init_msg_fail",{client:_,err:L.message});}let T=new it({projectPath:S,clientId:_});Hi(T),I.i("PIPE","client_connected",{client:_,active:d,sid:T.sessionId,proj:T.projectPath});let F=Do(T);f.onclose=()=>{d--,Wi(T.sessionId),I.i("PIPE","client_disconnected",{client:_,active:d,sid:T.sessionId}),d===0&&A();},await F.connect(f),I.i("PIPE","client_ready",{client:_,active:d,sid:T.sessionId}),S!==x&&setImmediate(async()=>{try{let L=e.indexing;if(!(L?.autoIndex??!0)){I.t("INDEXER","autoindex_disabled_client",{client:_});return}let ae=await d$3(),R=q(S),b=v(S);ae.setProject(S,b);let Mr=(await ae.getStatistics()).totalEntities??0;if(Mr>0){I.i("INDEXER","client_project_indexed",{client:_,proj:R,entities:Mr});return}let Rr=L?.autoIndexExtensions??[".ts",".tsx",".js",".jsx",".py",".go",".rs",".kt",".swift",".c",".cpp",".java",".cs"],Ir=await vn(S,Rr);if(!Ir.supported){I.i("INDEXER","client_no_files",{client:_,dir:S});return}I.i("INDEXER","client_autoindex_start",{client:_,dir:S,ext:Ir.detectedExt}),b$1(S),await Me(S,Rr,Dr(),!1),I.i("INDEXER","client_autoindex_done",{client:_,dir:S});}catch(L){I.e("INDEXER","client_autoindex_fail",{client:_,err:L.message});}});}),t="pipe-multi",I.i("MCP","server_ready",{dir:x,transport:t,tools:we().length});}else {I.t("STARTUP","stdio_connect",{ms:Date.now()-me});let c=new StdioServerTransport;t="stdio";let l=Date.now();await Ra.connect(c),I.t("STARTUP","stdio_connected",{ms:Date.now()-me,dur:Date.now()-l}),I.i("MCP","server_ready",{dir:x,transport:t,tools:we().length});}if(Ar.length>0){try{await Tr(),await To(),process.env.MCP_DEBUG_DISABLE_SEMANTIC!=="1"&&await Ce(),await Na(Ar),I.i("DEBUG","requests_complete",{}),process.exit(0);}catch(c){I.e("DEBUG","request_failed",{err:c instanceof Error?c.message:String(c)}),process.exit(1);}return}b$1(x),I.i("STARTUP","agents_registered",{}),I.t("STARTUP","autoindex_check",{ms:Date.now()-me});let n=e.indexing,r=!fo&&(n?.autoIndex??true);if(I.t("INDEXER","autoindex_config",{shouldAutoIndex:r,noAutoIndex:fo}),r){let c=n?.autoIndexExtensions??[".ts",".tsx",".js",".jsx",".py",".go",".rs",".kt",".swift",".c",".cpp",".java",".cs"];setImmediate(async()=>{try{let l=await d$3(),d=q(x),u=v(x);I.t("INDEXER","check_index",{dir:x,hash:d,branch:u}),l.setProject(x,u);let p=await l.getStatistics(),m=p.totalEntities??0;I.t("INDEXER","stats",{entities:m,rels:p.totalRelationships,files:p.totalFiles});let h=!1,v$1=.4;if(m>0){let C=await Mi(x,c),f=p.totalFiles??0,S=(await l.getIncrementalTrackingInfo()).incrementalChangesCount,T=f>0?S/f:0;if(T>v$1)I.i("INDEXER","cumulative_threshold",{changes:S,files:f,pct:(T*100).toFixed(1),threshold:(v$1*100).toFixed(0)}),h=!1;else {let F=C-f,L=f>0?F/f*100:0;if(C>0&&(F>10||L>20))I.i("INDEXER","index_incomplete",{indexed:f,disk:C,missing:F,changes:S}),h=!0;else {I.i("INDEXER","index_exists",{entities:m,files:f,disk:C,changes:S});try{let Q=await Tr();I.i("DEVAGENT","init_for_incremental",{hasAgent:!!Q});let ae=await Ce();I.i("SEMANTIC","init_for_incremental",{hasAgent:!!ae});let b=Q?.getIndexerAgent?.()??null;b?.setRepositoryPath?(b.setProjectContext&&b.setProjectContext(x),await b.setRepositoryPath(x),I.i("INDEXER","watcher_started_existing",{dir:x})):I.w("INDEXER","watcher_no_agent",{hasAgent:!!b,reason:"DevAgent.getIndexerAgent() returned null"});}catch(Q){I.w("INDEXER","watcher_start_fail",{err:Q.message});}return}}}let A=await vn(x,c);if(!A.supported){I.i("INDEXER","no_files",{dir:x});return}I.i("INDEXER","project_detected",{ext:A.detectedExt??"unknown",sample:A.sampleFile??"none"}),await Me(x,c,Dr(),h);}catch(l){I.e("INDEXER","autoindex_failed",{err:l.message});}});}}Ua().catch(o=>{I.e("STARTUP","server_failed",{err:o.message}),process.exit(1);});export{ns as areTimersSuspended,et as getIndexingStatus,An as isIndexing,Ei as isProjectIndexing,ts as registerAsyncLoopStarter,rs as resumeTimers,tt as setIndexingState};
|