module.exports=[56891,e=>{"use strict";var t=e.i(33405),r=e.i(22734),s=e.i(46786),n=e.i(14747),o=e.i(92997),i=e.i(85336),a=e.i(24361);e.i(47998);var l=e.i(14173),l=l;let c=(0,a.promisify)(t.exec);function u(e,t,r,s){let n=0;"build"===t?n=1e3:"server"===t?n=500:"browser"===t?n=300:"network"===t?n=200:"warning"===t&&(n=100),/CRITICAL|FATAL|crashed/i.test(e)?n*=2:/ERROR|Exception|FAIL/i.test(e)&&(n*=1.5);let o=e.replace(/\x1b\[[0-9;]*m/g,"").replace(/\d+/g,"\\d+").substring(0,100),i=s.filter(e=>new RegExp(o).test(e)).length;i>1&&(n+=(i-1)*50),r.length>0&&(n+=50);let a=e.match(/\[(\d{2}):(\d{2}):(\d{2})\.\d{3}\]/);if(a){let e=new Date,t=new Date;t.setHours(parseInt(a[1],10)),t.setMinutes(parseInt(a[2],10)),t.setSeconds(parseInt(a[3],10)),(e.getTime()-t.getTime())/1e3/60<1&&(n+=100)}return n}async function d(e,t){try{let t=e.category.toUpperCase(),r=e.error.replace(/\[[^\]]+\]/g,"").trim().substring(0,100),s=`Fix: ${t} - ${r}`,n=`## 🐛 Bug Fix - ${e.category} Error

**Priority Score:** ${e.priorityScore} (${e.severity})

### Error Details
\`\`\`
${e.error}
\`\`\`

${e.interactions.length>0?`### Reproduction Steps
The error occurred after these user interactions:
${e.interactions.map((e,t)=>`${t+1}. ${e}`).join("\n")}

### Verification
After implementing the fix, verify by:
1. Replaying the same interactions using \`execute_browser_action\`
2. Confirming the error no longer appears in logs
3. Checking that functionality works as expected
`:""}

### Suggested Fix
This PR addresses the ${e.severity}-level ${e.category} error detected by dev3000.

${e.suggestedFix||"Please analyze the error and implement the appropriate fix."}

---
🤖 Generated with [dev3000](https://github.com/vercel-labs/dev3000) - AI-powered debugging
`,o=`fix/${e.category}-${Date.now()}`;return await c(`git checkout -b ${o}`),await c(`gh pr create --title "${s}" --body "${n}" --head ${o}`),`✅ Created PR: ${s}

Branch: ${o}

Next steps:
1. Implement the fix in your code
2. Commit and push changes
3. PR is ready for review!`}catch(e){return`❌ Failed to create PR: ${e instanceof Error?e.message:String(e)}

You can manually create a PR with the error details above.`}}function p(){let e=(0,n.join)((0,s.homedir)(),".d3k");if(!(0,r.existsSync)(e))return[];try{let t=(0,r.readdirSync)(e,{withFileTypes:!0}),s=[];for(let o of t)if(o.isDirectory()){let t=(0,n.join)(e,o.name,"session.json");(0,r.existsSync)(t)&&s.push(t)}return s.map(e=>{try{let t=JSON.parse((0,r.readFileSync)(e,"utf-8")),s=(0,r.statSync)(e);return{...t,sessionFile:e,lastModified:s.mtime}}catch{return null}}).filter(e=>{if(!e||!e.pid)return!1;try{return process.kill(e.pid,0),!0}catch{return!1}}).sort((e,t)=>new Date(t.startTime).getTime()-new Date(e.startTime).getTime())}catch(e){return[]}}function h(e){if(e){let t=p().find(t=>t.projectName===e);if(t)return t.logFilePath}let t=process.env.LOG_FILE_PATH;return t||null}async function f({projectName:t,focusArea:s="all",mode:n="snapshot",waitForUserInteraction:o=!1,timeRangeMinutes:i=10,includeTimestampInstructions:a=!0,integrateNextjs:l=!1,integrateChromeDevtools:c=!1,returnRawData:f=!1,createPR:m=!1}){let{getMCPClientManager:g}=await e.A(20654),y=g().getConnectedMCPs(),v=y.includes("nextjs-dev"),w=y.includes("chrome-devtools");y.length>0&&D(`Fix My App: Connected to downstream MCPs: ${y.join(", ")}`),v&&!1===l&&(l=!0),w&&!1===c&&(c=!0);let b=await C();b&&D("Fix My App: Recommending dev3000-nextjs-dev MCP for Next.js-specific analysis");let S=h(t);if(!S){let e=p();if(0===e.length)return{content:[{type:"text",text:"❌ No active dev3000 sessions found. Make sure dev3000 is running!"}]};if(D(`fix_my_app: Found ${e.length} sessions`),1===e.length){if(S=h(t=e[0].projectName),D(`fix_my_app: Auto-selected single session: ${t}, logPath: ${S}`),!S)return{content:[{type:"text",text:`❌ Could not find log file for project "${t}". The session may not be properly initialized yet.`}]}}else{let t=e.map(e=>`• ${e.projectName} (started ${new Date(e.startTime).toLocaleString()})`).join("\n");return{content:[{type:"text",text:`🔍 Found ${e.length} dev3000 sessions. Please specify which project to fix:
${t}

💡 Use: projectName: "your-project-name" parameter`}]}}}let E=[];if("bisect"===n&&o){let e=new Date().toISOString();return E.push("🕐 **TIMESTAMP BISECT MODE ACTIVATED**"),E.push(`📍 Start Time: ${e}`),E.push(""),E.push("🎯 **NOW INTERACT WITH YOUR APP TO REPRODUCE THE ISSUE!**"),E.push("• Click buttons, navigate, submit forms, etc."),E.push("• Reproduce the exact error scenario"),E.push("• When done, run this tool again WITHOUT waitForUserInteraction"),E.push(""),E.push("💡 I'll analyze everything that happens between these timestamps!"),{content:[{type:"text",text:E.join("\n")}]}}try{if(!(0,r.existsSync)(S))return E.push("📋 Log file doesn't exist yet. The dev server may still be starting up."),E.push("💡 Wait a few seconds for the server to generate logs, then try again."),{content:[{type:"text",text:E.join("\n")}]};let e=(0,r.readFileSync)(S,"utf-8").trim().split("\n").filter(Boolean);if(0===e.length)return E.push("📋 Log file is empty. Make sure your app is running and generating logs."),{content:[{type:"text",text:E.join("\n")}]};E.push(`🔍 **FIX MY APP ANALYSIS** - Mode: ${n.toUpperCase()}`),E.push(`📁 Log file: ${S}`),E.push(`📊 Total log entries: ${e.length}`),E.push("");let o=new Date,h=new Date(o.getTime()-60*i*1e3),g=[/ERROR/i,/FAIL/i,/Exception/i,/CRITICAL/i,/FATAL/i,/crashed/i,/undefined/i,/null reference/i,/cannot read/i,/cannot find/i,/not found/i,/timeout/i,/refused/i,/denied/i,/unauthorized/i,/404/,/500/,/503/,/WARN/i,/WARNING/i,/deprecated/i,/slow/i,/retry/i,/RUNTIME\.ERROR/,/hydration.*mismatch/i,/Uncaught/i,/throwOnHydrationMismatch/i],y=e.filter(e=>{let t=e.match(/\[(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)\]/);if(t)return new Date(t[1])>=h;let r=e.match(/\[(\d{2}):(\d{2}):(\d{2})\.(\d{3})\]/);if(r){let e=new Date,t=new Date(e.getFullYear(),e.getMonth(),e.getDate(),parseInt(r[1],10),parseInt(r[2],10),parseInt(r[3],10),parseInt(r[4],10));return t>e&&t.setDate(t.getDate()-1),t>=h}return!0}),v=y.filter(e=>g.some(t=>t.test(e))),w=y.filter(e=>e.includes("react-scan")||e.includes("ReactScan")||e.includes("React render")),C={unnecessaryRenders:w.filter(e=>e.includes("unnecessary")||e.includes("re-render")||e.includes("wasted")),slowComponents:w.filter(e=>e.includes("slow")||e.includes("performance")||/\d+ms/.test(e)),totalRenders:w.filter(e=>e.includes("render")).length},$=[/link rel=preload.*must have.*valid.*as/i,/next\/font/i,/automatically generated/i,/\[NETWORK\].*\b(200|201|204|304)\b\s+(OK|Created|No Content|Not Modified)/i],T=v.filter(e=>!$.some(t=>t.test(e))),R={serverErrors:T.filter(e=>e.includes("[SERVER]")&&(e.includes("ERROR")||e.includes("Exception"))),browserErrors:T.filter(e=>e.includes("[BROWSER]")&&(e.includes("ERROR")||e.includes("CONSOLE ERROR")||e.includes("RUNTIME.ERROR"))),buildErrors:T.filter(e=>e.includes("Failed to compile")||e.includes("Type error")||e.includes("Build failed")),networkErrors:T.filter(e=>!/\b(200|201|204|304)\b/.test(e)&&(e.includes("NETWORK")||e.includes("404")||e.includes("500")||e.includes("timeout"))),warnings:T.filter(e=>/WARN|WARNING|deprecated/i.test(e)&&!/ERROR|Exception|FAIL/i.test(e))},A=T.length,N=A-R.warnings.length,I=e.filter(e=>g.some(t=>t.test(e))),P=I.length>A,O=(e,t)=>{let r=t.indexOf(e);if(-1===r)return[];let s=[];for(let e=r-1;e>=Math.max(0,r-20)&&s.length<5;e--)(t[e].includes("[INTERACTION]")||t[e].includes("[NAVIGATION]")||t[e].includes("[PAGE]"))&&s.unshift(t[e]);return s};if(0!==A||P)if(0===A&&P)E.push(`No errors in last ${i} minutes, but found ${I.length} errors in full log.`),E.push(""),E.push("Older errors (outside time range):"),I.slice(-5).forEach(t=>{let r=O(t,e);if(r.length>0)for(let e of(E.push("  Preceding interactions:"),r))E.push(`    ${e}`);E.push(`  - ${t}`),E.push("")}),E.push("To analyze these errors, increase timeRangeMinutes (e.g., timeRangeMinutes=60)");else{if(E.push(`**${A} ISSUES DETECTED** (${N} critical, ${R.warnings.length} warnings)`),E.push(""),E.push("**ACTION REQUIRED:** Fix the highest-priority error below, then call fix_my_app again to verify."),E.push(""),R.serverErrors.length>0&&(E.push("SERVER ERRORS:"),R.serverErrors.slice(-5).forEach(t=>{let r=O(t,e);if(r.length>0)for(let e of(E.push("  Preceding interactions:"),r))E.push(`    ${e}`);E.push(`  - ${t}`),E.push("")})),R.browserErrors.length>0&&(E.push("BROWSER/CONSOLE ERRORS:"),R.browserErrors.slice(-5).forEach(t=>{let r=O(t,e);if(r.length>0)for(let e of(E.push("  Preceding interactions:"),r))E.push(`    ${e}`);E.push(`  - ${t}`),E.push("")})),R.buildErrors.length>0&&(E.push("BUILD/COMPILATION ERRORS:"),R.buildErrors.slice(-5).forEach(t=>{let r=O(t,e);if(r.length>0)for(let e of(E.push("  Preceding interactions:"),r))E.push(`    ${e}`);E.push(`  - ${t}`),E.push("")})),R.networkErrors.length>0&&(E.push("NETWORK/API ERRORS:"),R.networkErrors.slice(-5).forEach(t=>{let r=O(t,e);if(r.length>0)for(let e of(E.push("  Preceding interactions:"),r))E.push(`    ${e}`);E.push(`  - ${t}`),E.push("")})),R.warnings.length>0&&"all"===s&&(E.push(`WARNINGS (${R.warnings.length} found, showing recent):`),E.push(R.warnings.slice(-3).join("\n")),E.push("")),E.push("---"),E.push("**NEXT: Fix the highest-priority issue, then call fix_my_app again to verify.**"),E.push(""),E.push("Keep calling fix_my_app after each fix until no errors remain."),l||c){let e=[];l&&e.push("Next.js"),c&&e.push("Chrome DevTools"),D(`Fix Analysis: Using active MCP integrations [${e.join(", ")}] for enhanced error analysis`,t),E.push(""),E.push("**Available MCP integrations:**"),l&&(E.push(""),E.push("Next.js MCP (nextjs-dev):"),(await j(v.join(" "))).forEach(e=>{let t=e.params?`(${Object.entries(e.params).map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(", ")})`:"()";E.push(`  • nextjs-dev.${e.function}${t}`),E.push(`    Reason: ${e.reason}`)}),R.serverErrors.length>0&&E.push("  • Check Next.js build/runtime logs for SSR/hydration issues")),c&&(E.push(""),E.push("Chrome DevTools MCP (chrome-devtools):"),(await L(v.join(" "))).forEach(e=>{let t=e.params?`(${Object.entries(e.params).map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(", ")})`:"()";E.push(`  • chrome-devtools.${e.function}${t}`),E.push(`    Reason: ${e.reason}`)}),R.browserErrors.length>0&&E.push("  • Use DOM inspection for UI issues"),R.networkErrors.length>0&&E.push("  • Inspect network requests for detailed error context"))}let r=function(e,t,r){let s=[],n=e=>{let t=r.indexOf(e);if(-1===t)return[];let s=[];for(let e=t-1;e>=Math.max(0,t-20)&&s.length<5;e--)(r[e].includes("[INTERACTION]")||r[e].includes("[NAVIGATION]")||r[e].includes("[PAGE]"))&&s.unshift(r[e]);return s};for(let r of e.buildErrors){let e=n(r);s.push({error:r,category:"build",severity:"critical",priorityScore:u(r,"build",e,t),interactions:e})}for(let r of e.serverErrors){let e=n(r),o=/CRITICAL|FATAL/i.test(r)?"critical":"error";s.push({error:r,category:"server",severity:o,priorityScore:u(r,"server",e,t),interactions:e})}for(let r of e.browserErrors){let e=n(r),o=/CRITICAL|FATAL/i.test(r)?"critical":"error";s.push({error:r,category:"browser",severity:o,priorityScore:u(r,"browser",e,t),interactions:e})}for(let r of e.networkErrors){let e=n(r);s.push({error:r,category:"network",severity:"error",priorityScore:u(r,"network",e,t),interactions:e})}if(0===s.length)for(let r of e.warnings){let e=n(r);s.push({error:r,category:"warning",severity:"warning",priorityScore:u(r,"warning",e,t),interactions:e})}return s.sort((e,t)=>t.priorityScore-e.priorityScore),s[0]||null}(R,T,e);if(r)if(E.push(""),E.push("---"),E.push("**HIGHEST PRIORITY ISSUE (fix this first):**"),E.push(`Priority Score: ${r.priorityScore}`),E.push(`Category: ${r.category.toUpperCase()}`),E.push(`Severity: ${r.severity.toUpperCase()}`),E.push(""),E.push("Error:"),E.push(`  ${r.error}`),r.interactions.length>0&&(E.push(""),E.push("Reproduction steps:"),r.interactions.forEach((e,t)=>{E.push(`  ${t+1}. ${e}`)})),m){E.push(""),E.push("Creating PR branch for this issue...");let e=await d(r,t||"");E.push(e)}else E.push(""),E.push("To create a PR branch for this issue, run: fix_my_app(createPR=true)")}else E.push(`No errors found in last ${i} minutes.`),E.push("Application appears healthy."),a&&"monitor"!==n&&(E.push(""),E.push("Options:"),E.push("• Use mode='bisect' to compare before/after states during testing"),E.push("• Use mode='monitor' for continuous monitoring"),E.push("• Increase timeRangeMinutes to analyze a longer period"));let F=e.filter(e=>e.includes("[SCREENSHOT]")||e.includes("Screenshot captured"));if(F.length>0&&(E.push(""),E.push(`📸 **SCREENSHOTS CAPTURED** (${F.length} total):`),F.slice(-5).forEach(e=>{let t=e.match(/Screenshot captured: (.+)$/);t&&E.push(`• ${t[1]}`)}),E.push(""),E.push("💡 **TIP**: Use analyze_visual_diff tool to compare screenshots and identify changes"),E.push("   (Advanced: screenshots are also accessible via curl if needed)")),"performance"===s||"all"===s){let e=await k(t);if(e.detections.length>0){let r=p().find(e=>e.projectName===t),s=r&&r.sessionFile.match(/"mcpPort":\s*"(\d+)"/)?.[1]||"3684",n=`http://localhost:${s}/video/${e.sessionId}`;E.push(""),e.realCLS?E.push(`🚨 **LAYOUT SHIFT DETECTED** (${e.detections.length} ${1===e.detections.length?"shift":"shifts"} during page load):`):E.push(`🚨 **LOADING JANK DETECTED** (${e.detections.length} layout ${1===e.detections.length?"shift":"shifts"} found):`);let o="navigation"===e.captureTrigger?"Navigation complete":"load"===e.captureTrigger?"Load complete":"View all frames";E.push(`📹 **${o}**: ${n}`),E.push(`🎞️ **Session ID**: ${e.sessionId} (${e.totalFrames} frames)`),E.push(""),e.detections.forEach(e=>{let t="high"===e.severity?"🔴":"medium"===e.severity?"🟡":"🟢";if(e.uxImpact?(E.push(`${t} **${e.timeSinceStart}ms** - ${e.element}`),E.push(`   ${e.uxImpact}`)):E.push(`${t} **${e.timeSinceStart}ms**: ${e.visualDiff.toFixed(1)}% of screen changed (${e.severity} severity)`),e.beforeFrameUrl&&e.afterFrameUrl&&(E.push(`   📸 Before: ${e.beforeFrameUrl}`),E.push(`   📸 After:  ${e.afterFrameUrl}`),E.push(`   💡 Use analyze_visual_diff tool with these URLs to get a detailed description of what changed`),e.element)){let t=e.element.match(/<(\w+)>/);if(t){let e=t[1].toLowerCase();E.push(`   💡 Use find_component_source tool with selector "${e}" to locate the source code`)}}}),E.push(""),e.detections.some(e=>"high"===e.severity)&&e.realCLS&&(E.push("🎯 **WHY DEV3000 CAUGHT THIS BUT CHROME MIGHT NOT:**"),E.push("• dev3000's PerformanceObserver is installed immediately at page load and buffers ALL shifts from the start"),E.push("• Chrome DevTools performance trace may start AFTER initial load, missing early navigation shifts"),E.push("• Our UX-focused detection flags critical element shifts (nav/header) even when CLS score is technically 'good'"),E.push("")),E.push("✅ **DEV3000'S CLS DETECTION IS AUTHORITATIVE**"),E.push("If Chrome DevTools reports CLS: 0.00 but dev3000 detected shifts, TRUST DEV3000."),E.push("• Chrome DevTools trace may start AFTER the shifts occurred"),E.push("• dev3000's PerformanceObserver captures ALL shifts from page start"),E.push("• CLS: 0.00 in Chrome just means the trace missed the early shifts"),E.push(""),E.push("💡 **LAYOUT SHIFT DEBUGGING TIPS:**"),E.push("• Add explicit width/height to images and media"),E.push("• Reserve space for dynamic content (ads, embeds, etc.)"),E.push("• Avoid inserting content above existing content"),E.push("• Use CSS aspect-ratio for responsive elements"),E.push("• Check for web fonts causing text reflow (font-display: swap)"),E.push(`• Raw screenshots: ${e.screenshotDir}`),E.push(""),E.push("📸 **ANALYZING SCREENSHOTS:**"),E.push("• RECOMMENDED: Use analyze_visual_diff tool with before/after URLs (shown above)"),E.push("• The tool provides structured instructions for comparing frames"),E.push("• Advanced: Screenshots are also accessible via curl if needed"),E.push(""),E.push(`🎬 **IMPORTANT**: Share this frame sequence link with the user: ${n}`)}}if((C.totalRenders>0||"performance"===s||"all"===s)&&(C.unnecessaryRenders.length>0||C.slowComponents.length>0)&&(E.push(""),E.push("⚛️ **REACT PERFORMANCE ANALYSIS (react-scan):**"),C.unnecessaryRenders.length>0&&(E.push(`🔄 **Unnecessary Re-renders Detected (${C.unnecessaryRenders.length}):**`),C.unnecessaryRenders.slice(-5).forEach(e=>{E.push(`• ${e}`)}),E.push("")),C.slowComponents.length>0&&(E.push(`🐌 **Slow Components Found (${C.slowComponents.length}):**`),C.slowComponents.slice(-5).forEach(e=>{E.push(`• ${e}`)}),E.push("")),E.push("💡 **REACT OPTIMIZATION TIPS:**"),E.push("• Use React.memo() for components with expensive renders"),E.push("• Use useMemo/useCallback to prevent unnecessary re-renders"),E.push("• Check for unstable prop references (objects/arrays created in render)"),E.push("• Consider using React DevTools Profiler for deeper analysis")),0===A&&"all"===s){let t=e.filter(e=>e.includes("took")&&e.includes("ms"));t.length>0&&(E.push(""),E.push("⚡ **PERFORMANCE INSIGHTS:**"),t.slice(-5).forEach(e=>{E.push(`• ${e}`)}))}if(f){let r;D(`Structured Output: Returning structured data for Claude orchestration with ${A} errors and ${l||c?"active":"no"} integrations`,t);let n=v.map(t=>{let r=O(t,e),s=R.serverErrors.includes(t)?"server":R.browserErrors.includes(t)?"browser":R.buildErrors.includes(t)?"build":R.networkErrors.includes(t)?"network":R.warnings.includes(t)?"warning":"general",n=R.warnings.includes(t)?"warning":t.includes("CRITICAL")||t.includes("FATAL")||t.includes("crashed")?"critical":"error",o=t.match(/\[(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z)\]/)||t.match(/\[(\d{2}:\d{2}:\d{2}\.\d{3})\]/);return{timestamp:o?o[1]:new Date().toISOString(),category:s,message:t,interactions:r,severity:n}}),o=[];n.forEach(e=>{("hydration"===e.category||e.message.includes("hydration"))&&o.push({file:"pages/_app.js or components/[component].tsx",description:"Fix hydration mismatch",code:`// Ensure server and client render the same content
// Use useEffect for client-only logic
useEffect(() => {
  // Client-only code here
}, [])`,reason:"Hydration errors occur when server and client render different content"}),(e.message.includes("TypeError")||e.message.includes("undefined"))&&o.push({file:"Identify from stack trace in error message",description:"Add null/undefined checks",code:`// Add defensive programming checks
if (data && data.property) {
  // Safe to use data.property
}
// Or use optional chaining
const value = data?.property?.nestedProperty`,reason:"Prevent TypeError by checking for undefined/null values"}),(e.message.includes("404")||e.message.includes("not found"))&&o.push({file:"routing configuration or API endpoints",description:"Fix missing route or resource",code:`// Check route configuration
// Ensure API endpoint exists
// Verify file paths are correct`,reason:"404 errors indicate missing resources or incorrect paths"})});let i={};l&&(i.nextjs=await j(v.join(" "))),c&&(i.chrome=await L(v.join(" "))),(l||c)&&(r={phase1:{name:"Data Collection",description:"Parallel data gathering across all available MCPs",actions:[{mcp:"dev3000",function:"fix_my_app",params:{focusArea:s,integrateNextjs:l,integrateChromeDevtools:c,returnRawData:!0},reason:"Get comprehensive error analysis with interaction data"}],estimatedTime:"2-3 minutes"},phase2:{name:"Deep Analysis",description:"Cross-MCP correlation and targeted investigation",actions:[{mcp:"dev3000",function:"fix_my_app",params:{mode:"bisect"},reason:"Regression analysis if needed"}],estimatedTime:"3-5 minutes"},phase3:{name:"Fix & Verify",description:"Implementation and verification across all layers",actions:[{mcp:"dev3000",function:"execute_browser_action",reason:"Replay interactions to verify fixes"}],estimatedTime:"5-10 minutes"}},l&&i.nextjs&&(r.phase1.actions.push(...i.nextjs.filter(e=>"high"===e.priority).map(e=>({mcp:"nextjs-dev",function:e.function,params:e.params,reason:e.reason}))),r.phase3.actions.push({mcp:"nextjs-dev",function:"check_build_status",reason:"Verify build success after fixes"})),c&&i.chrome&&r.phase1.actions.push(...i.chrome.filter(e=>"high"===e.priority).map(e=>({mcp:"chrome-devtools",function:e.function,params:e.params,reason:e.reason}))));let a={errors:n,fixes:o,suggestedIntegrations:i,workflowPlan:r,summary:{totalErrors:A,criticalErrors:N,hasIntegrations:l||c,estimatedFixTime:M(A,l||c)}};return{content:[{type:"text",text:JSON.stringify(a,null,2)}]}}let U=await x("profile_performance");return(b||U)&&(E.push(""),E.push("🔗 **AUGMENTED ANALYSIS AVAILABLE**"),E.push(""),E.push("dev3000 provided the core log analysis above. For deeper insights, consider also gathering:"),E.push(""),b&&(E.push("**Next.js Framework Analysis:**"),(await j(v.join(" "))).slice(0,3).forEach(e=>{E.push(`• \`dev3000-nextjs-dev:${e.function}()\` - ${e.reason}`)}),E.push("")),U&&(E.push("**Browser-Side Analysis:**"),(await L(v.join(" "))).slice(0,3).forEach(e=>{E.push(`• \`dev3000-chrome-devtools:${e.function}()\` - ${e.reason}`)}),E.push("")),E.push("💡 **Best approach:** Use dev3000's log analysis as your foundation, then gather specific additional data as needed for a complete picture.")),{content:[{type:"text",text:E.join("\n")}]}}catch(e){return{content:[{type:"text",text:`Error analyzing logs: ${e instanceof Error?e.message:String(e)}`}]}}}let m=new Map,g={chrome:["inspect","debug","profile","performance","console","devtools","breakpoint","intercept","storage","memory","trace"],nextjs:["build","hydration","ssr","routing","analyze","debug","render","middleware","optimization"]},y=["screenshot","navigate","click","type","scroll","evaluate","simple_script","get_logs","basic_build_status","simple_error_check"];async function v(e){let t=m.get(e);if(t&&Date.now()-t.timestamp<3e5)return D(`Capability Discovery: Using cached capabilities for ${e} (${t.capabilities.length} functions)`),t.capabilities;D(`Capability Discovery: Fetching fresh capabilities for ${e}`);try{let t=await w(e);if(t.length>0)return m.set(e,{timestamp:Date.now(),capabilities:t}),D(`Capability Discovery: Successfully discovered ${t.length} capabilities for ${e}`),t;let r=await S(e);return m.set(e,{timestamp:Date.now(),capabilities:r}),D(`Capability Discovery: Using fallback inference for ${e} (${r.length} functions)`),r}catch(t){return D(`Capability Discovery: Failed to discover capabilities for ${e} - ${t}`),[]}}async function w(t){try{let s=`/Users/${process.env.USER}/Library/Caches/claude-cli-nodejs`,{readdirSync:n,existsSync:o,readFileSync:i}=await e.A(23970);if(!o(s))return[];let a=n(s).find(e=>e.includes(process.cwd().replace(/\//g,"-")));if(!a)return[];let l=`${s}/${a}/mcp-logs-${t}`;if(!o(l))return[];let c=n(l),u=[];for(let e of c.slice(-5))try{let r=`${l}/${e}`,s=i(r,"utf8"),n=function(e,t){let r=[],s=t.includes("chrome")?"chrome":t.includes("nextjs")?"nextjs":"chrome",n=g[s];for(let t of[/"name":\s*"([^"]+)"/g,/(\w+)\s*\([^)]*\)/g,/tool:\s*(\w+)/g,/unknown function[:\s]+(\w+)/gi,/exports\.(\w+)/g]){let o=t.exec(e);for(;null!==o;){let i=o[1];if(y.some(e=>i.toLowerCase().includes(e))){o=t.exec(e);continue}let a=n.some(e=>i.toLowerCase().includes(e)),l=b(i,s,a);r.push({function:i,description:void 0,category:a?"advanced":"basic",reason:l}),o=t.exec(e)}}return r}(s,t);u.push(...n)}catch(e){}var r=u;let d=new Map;for(let e of r){let t=d.get(e.function);(!t||e.description&&!t.description||e.reason.length>t.reason.length)&&d.set(e.function,e)}return Array.from(d.values())}catch(e){return D(`MCP Introspection: Failed to introspect ${t} - ${e}`),[]}}function b(e,t,r){let s=e.toLowerCase();if("chrome"===t){if(s.includes("inspect"))return"Deep DOM inspection with DevTools-level detail";if(s.includes("console"))return"Direct browser console access and manipulation";if(s.includes("debug")||s.includes("breakpoint"))return"JavaScript debugging with breakpoints and call stack";if(s.includes("profile")||s.includes("performance"))return"Advanced performance profiling and analysis";if(s.includes("network")||s.includes("request"))return"Network request interception and analysis";if(s.includes("storage"))return"Browser storage manipulation (cookies, localStorage, etc.)";if(s.includes("trace")||s.includes("memory"))return"Memory usage and execution tracing"}if("nextjs"===t){if(s.includes("build"))return"Advanced Next.js build system analysis";if(s.includes("hydration"))return"Client-server hydration debugging and analysis";if(s.includes("ssr")||s.includes("render"))return"Server-side rendering debugging";if(s.includes("route")||s.includes("routing"))return"Next.js routing system inspection and debugging";if(s.includes("middleware"))return"Next.js middleware analysis and debugging";if(s.includes("optimization")||s.includes("performance"))return"Next.js-specific performance optimization"}return r?`Advanced ${t} capability beyond dev3000's basic automation`:`${t} capability for specialized analysis`}async function S(e){let t=e.includes("chrome")?"chrome":e.includes("nextjs")?"nextjs":"unknown",r=[];if("chrome"===t)for(let e of["inspect_element","access_console","start_performance_profile","intercept_requests","set_breakpoint","take_screenshot","get_dom_snapshot","modify_storage","execute_script"])r.push({function:e,category:y.includes(e)?"basic":"advanced",reason:b(e,t,!0)});if("nextjs"===t)for(let e of["analyze_build_process","debug_server_rendering","debug_hydration","inspect_routing","analyze_next_performance","get_build_info","check_build_status","get_server_logs"])r.push({function:e,category:y.includes(e)?"basic":"advanced",reason:b(e,t,!0)});return D(`Capability Inference: Generated ${r.length} inferred capabilities for ${e}`),r}async function x(e){try{if(!(await I()).includes("dev3000-chrome-devtools"))return!1;if(!e)return!0;return(await v("dev3000-chrome-devtools")).some(t=>t.function.toLowerCase().includes(e.toLowerCase())||"advanced"===t.category)}catch(e){return D(`Chrome DevTools delegation check failed: ${e}`),!1}}async function C(){try{if(!(await I()).includes("dev3000-nextjs-dev"))return!1;return(await v("dev3000-nextjs-dev")).some(e=>"advanced"===e.category)}catch(e){return D(`NextJS delegation check failed: ${e}`),!1}}async function E(e,t){let r=(await v("dev3000-chrome-devtools")).find(t=>t.function.toLowerCase().includes(e.toLowerCase())||t.description?.toLowerCase().includes(e.toLowerCase()));if(!r)throw Error(`Action ${e} cannot be delegated to chrome-devtools`);return{content:[{type:"text",text:`🔗 **ADVANCED BROWSER DEBUGGING AVAILABLE**

For advanced debugging capabilities, use the \`dev3000-chrome-devtools\` MCP:

\`\`\`
dev3000-chrome-devtools:${r.function}(${JSON.stringify(t,null,2)})
\`\`\`

🎯 **Why use chrome-devtools for this:** ${r.reason}

💡 **When to use each tool:**
• **dev3000**: Basic browser automation (screenshots, navigation, clicks, simple scripts)
• **dev3000-chrome-devtools**: Advanced debugging (DOM inspection, breakpoints, performance profiling, network interception)

⚡ **Both tools share the same Chrome instance** - no conflicts or duplicate browsers`}]}}async function $({action:e,params:t={}}){try{if(await x(e))return D(`Browser Action Delegation: Routing '${e}' to chrome-devtools MCP`),await E(e,t);D(`Browser Action Fallback: Using dev3000's execute_browser_action for '${e}'`);let s=p();if(0===s.length)return{content:[{type:"text",text:"❌ No active dev3000 sessions found. Make sure dev3000 is running with a browser!"}]};let n=JSON.parse((0,r.readFileSync)(s[0].sessionFile,"utf-8")),o=n.cdpUrl;if(!o)try{let e=await fetch("http://localhost:9222/json"),t=(await e.json()).find(e=>"page"===e.type&&!e.url.startsWith("chrome://"));t&&(o=t.webSocketDebuggerUrl,D(`CDP Discovery: Found fallback CDP URL ${o}`,s[0].projectName))}catch(e){D(`CDP Discovery: Failed to find fallback CDP URL - ${e}`,s[0].projectName)}if(!o)return{content:[{type:"text",text:`❌ No Chrome DevTools Protocol URL found. Make sure dev3000 is running with browser monitoring enabled (not --servers-only mode). Session CDP URL: ${n.cdpUrl||"null"}`}]};let i=await new Promise((r,s)=>{let n=new l.default(o),i=setTimeout(()=>{n.close(),s(Error(`Browser action '${e}' timed out after 60 seconds. This may indicate an issue with the browser or invalid parameters.`))},6e4);n.on("open",async()=>{try{n.send(JSON.stringify({id:1,method:"Target.getTargets",params:{}}));let a=null,l=2;async function o(e,t,r,s){return new Promise((n,o)=>{let i=r=>{let s=JSON.parse(r.toString());s.id===t&&(e.removeListener("message",i),s.error?o(Error(s.error.message)):n(s.result))};e.on("message",i),e.send(JSON.stringify({id:t,method:r,params:s})),setTimeout(()=>{e.removeListener("message",i),o(Error(`CDP command timeout after 30s: ${r}`))},3e4)})}n.on("message",async c=>{try{let u=JSON.parse(c.toString());if(1===u.id){if(u.error){clearTimeout(i),n.close(),s(Error(`Browser protocol error: ${u.error.message||JSON.stringify(u.error)}. This may occur in sandboxed browser environments where certain CDP commands are restricted.`));return}let e=u.result?.targetInfos?.find(e=>"page"===e.type);if(!e){clearTimeout(i),n.close(),s(Error("No page targets found"));return}a=e.targetId,n.send(JSON.stringify({id:l++,method:"Target.attachToTarget",params:{targetId:a,flatten:!0}}));return}if("Target.attachedToTarget"===u.method){let s;switch(u.params.sessionId,e){case"click":{let e,r;if("string"==typeof t.selector){let s=await o(n,l++,"Runtime.evaluate",{expression:`(() => {
                        const el = document.querySelector(${JSON.stringify(t.selector)});
                        if (!el) return { found: false };
                        const rect = el.getBoundingClientRect();
                        // Calculate center point, rounding to avoid fractional pixels
                        const centerX = Math.round(rect.left + rect.width / 2);
                        const centerY = Math.round(rect.top + rect.height / 2);
                        // Verify what element is at this point
                        const elementAtPoint = document.elementFromPoint(centerX, centerY);
                        const isCorrectElement = elementAtPoint === el || el.contains(elementAtPoint);
                        return {
                          found: true,
                          x: centerX,
                          y: centerY,
                          width: rect.width,
                          height: rect.height,
                          elementAtPoint: elementAtPoint?.tagName + (elementAtPoint?.className ? '.' + elementAtPoint.className : ''),
                          isCorrectElement: isCorrectElement
                        };
                      })()`,returnByValue:!0});if(s.result?.value?.found===!0&&"number"==typeof s.result.value.x&&"number"==typeof s.result.value.y)e=s.result.value.x,r=s.result.value.y,!1===s.result.value.isCorrectElement&&console.warn(`[execute_browser_action] Warning: Center point (${e}, ${r}) is over ${s.result.value.elementAtPoint}, not the target element. This may cause unexpected click behavior. Element size: ${s.result.value.width}x${s.result.value.height}`);else throw Error(`Element not found for selector: ${t.selector}`)}else if("number"==typeof t.x&&"number"==typeof t.y)e=t.x,r=t.y;else throw Error("Click action requires either {x, y} coordinates or a {selector} CSS selector");s=await o(n,l++,"Input.dispatchMouseEvent",{type:"mousePressed",x:e,y:r,button:"left",clickCount:1}),await o(n,l++,"Input.dispatchMouseEvent",{type:"mouseReleased",x:e,y:r,button:"left",clickCount:1});break}case"navigate":if("string"!=typeof t.url)throw Error("Navigate action requires url parameter as string");s=await o(n,l++,"Page.navigate",{url:t.url});break;case"reload":s=await o(n,l++,"Page.reload",{});break;case"screenshot":n.close(),r({warning:"Screenshot action is not recommended!",advice:"Dev3000 automatically captures screenshots during interactions. Instead of manual screenshots, use click/navigate/scroll/type actions to reproduce user workflows, and dev3000 will capture screenshots at optimal times.",suggestion:"Run fix_my_app to see all auto-captured screenshots from your session."});return;case"evaluate":{if("string"!=typeof t.expression)throw Error("Evaluate action requires expression parameter as string");let e=t.expression;if([/eval\s*\(/,/Function\s*\(/,/setTimeout/,/setInterval/,/\.innerHTML\s*=/,/\.outerHTML\s*=/,/document\.write/,/document\.cookie\s*=/,/localStorage\.setItem/,/sessionStorage\.setItem/,/\.src\s*=/,/\.href\s*=/,/location\s*=/,/\.addEventListener/,/\.removeEventListener/,/new\s+Function/,/import\s*\(/,/fetch\s*\(/,/XMLHttpRequest/].some(t=>t.test(e)))throw Error("Expression contains dangerous patterns. Only safe read-only expressions allowed.");s=await o(n,l++,"Runtime.evaluate",{expression:e,returnByValue:!0});break}case"scroll":{let e="number"==typeof t.deltaX?t.deltaX:0,r="number"==typeof t.deltaY?t.deltaY:0;s=await o(n,l++,"Input.dispatchMouseEvent",{type:"mouseWheel",x:"number"==typeof t.x?t.x:500,y:"number"==typeof t.y?t.y:500,deltaX:e,deltaY:r});break}case"type":if("string"!=typeof t.text)throw Error("Type action requires text parameter as string");for(let e of t.text)await o(n,l++,"Input.dispatchKeyEvent",{type:"char",text:e});s={action:"type",text:t.text};break;default:throw Error(`Unsupported action: ${e}`)}n.close(),clearTimeout(i),r(s)}}catch(e){n.close(),clearTimeout(i),s(e instanceof Error?e:Error(`Browser action failed: ${e instanceof Error?e.message:String(e)}`))}}),n.on("error",e=>{clearTimeout(i),s(e)})}catch(e){n.close(),clearTimeout(i),s(e)}}),n.on("error",e=>{clearTimeout(i),s(e)})}),a=`Browser action '${e}' executed successfully. Result: ${JSON.stringify(i,null,2)}`;return await x("inspect_element")&&(a+="\n\n🔗 **ENHANCED BROWSER ANALYSIS AVAILABLE**\n\ndev3000 completed the basic browser action above. For deeper browser insights, consider also:",(await L(e)).filter(t=>{let r=t.function.toLowerCase(),s=e.toLowerCase();return!!("screenshot"===s&&(r.includes("inspect")||r.includes("performance"))||"evaluate"===s&&(r.includes("console")||r.includes("inspect"))||"navigate"===s&&(r.includes("network")||r.includes("performance"))||"click"===s&&(r.includes("console")||r.includes("inspect")))||"high"===t.priority}).slice(0,2).forEach(e=>{a+=`
• \`dev3000-chrome-devtools:${e.function}()\` - ${e.reason}`}),a+="\n\n💡 **Augmented approach:** Use dev3000 for basic automation, chrome-devtools for detailed analysis and debugging."),{content:[{type:"text",text:a}]}}catch(e){return{content:[{type:"text",text:`Browser action failed: ${e instanceof Error?e.message:String(e)}`}]}}}let T={"nextjs-dev":["nextjs-dev","nextjs-dev-mcp","@modelcontextprotocol/server-nextjs-dev","mcp-server-nextjs-dev","nextjs-mcp"],"chrome-devtools":["chrome-devtools","chrome-devtools-mcp","@modelcontextprotocol/server-chrome-devtools","mcp-server-chrome-devtools","chrome-mcp"]},R={"nextjs-dev":[3001,3002,8080,8081],"chrome-devtools":[9222,9223,9224,3003]};async function A(){let e=[];try{process.platform;let{stdout:t}=await c("ps aux"),r=t.toLowerCase();for(let[t,s]of Object.entries(T))for(let n of s)if(r.includes(n.toLowerCase())){e.includes(t)||(e.push(t),D(`MCP Discovery: Found ${t} MCP via process detection [${n}]`));break}}catch(e){D(`MCP Discovery: Process detection failed - ${e instanceof Error?e.message:String(e)}`)}return e}async function N(){let e=[];for(let[t,r]of Object.entries(R))for(let s of r)try{if((await fetch(`http://localhost:${s}/health`,{method:"GET",signal:AbortSignal.timeout(2e3)})).ok){e.push(t),D(`MCP Discovery: Found ${t} MCP via HTTP ping on port ${s}`);break}}catch{try{let r=new l.default(`ws://localhost:${s}`);await new Promise((n,o)=>{let i=setTimeout(()=>{r.close(),o(Error("timeout"))},1e3);r.on("open",()=>{clearTimeout(i),r.close(),e.push(t),D(`MCP Discovery: Found ${t} MCP via WebSocket ping on port ${s}`),n(null)}),r.on("error",()=>{clearTimeout(i),o(Error("connection failed"))})});break}catch{}}return e}async function I(t){D("MCP Discovery: Starting proactive MCP discovery",t);let r=new Set;for(let e of(await A()))r.add(e);try{let s=`/Users/${process.env.USER}/Library/Caches/claude-cli-nodejs`,{readdirSync:n,existsSync:o}=await e.A(23970);if(o(s)){let e=n(s).find(e=>e.includes(process.cwd().replace(/\//g,"-")));if(e){let i=`${s}/${e}`,a=`${i}/mcp-logs-dev3000-chrome-devtools`;o(a)&&n(a).length>0&&(r.add("dev3000-chrome-devtools"),D("MCP Discovery: Found dev3000-chrome-devtools via Claude cache logs",t));let l=`${i}/mcp-logs-dev3000-nextjs-dev`;o(l)&&n(l).length>0&&(r.add("dev3000-nextjs-dev"),D("MCP Discovery: Found dev3000-nextjs-dev via Claude cache logs",t))}}}catch(e){D("MCP Discovery: Claude cache check failed, falling back to port detection",t)}if(0===r.size)for(let e of(D("MCP Discovery: No MCPs found via process or cache detection, trying port pinging",t),await N()))r.add(e);let s=Array.from(r);return s.length>0?D(`MCP Discovery: Successfully discovered MCPs [${s.join(", ")}]`,t):D("MCP Discovery: No MCPs detected - will run in standalone mode",t),s}async function P({mcpName:e}={}){let t=[];t.push("🔍 **MCP CAPABILITY INSPECTOR**"),t.push("");try{let r=await I();if(0===r.length)return t.push("❌ **NO MCPs DETECTED**"),t.push("No dev3000-chrome-devtools or dev3000-nextjs-dev MCPs found."),t.push(""),t.push("💡 **To enable enhanced capabilities:**"),t.push("• Ensure Chrome DevTools MCP is configured: `dev3000-chrome-devtools`"),t.push("• Ensure Next.js Dev MCP is configured: `dev3000-nextjs-dev`"),t.push("• Check that Claude Code has MCPs properly configured"),{content:[{type:"text",text:t.join("\n")}]};t.push(`✅ **DISCOVERED MCPs:** ${r.join(", ")}`),t.push("");let s=e?r.filter(t=>t.includes(e)):r;if(0===s.length&&e)return t.push(`❌ **MCP NOT FOUND:** ${e}`),t.push(`Available MCPs: ${r.join(", ")}`),{content:[{type:"text",text:t.join("\n")}]};for(let e of s){t.push(`📋 **${e.toUpperCase()} CAPABILITIES:**`),t.push("");let r=await v(e);if(0===r.length){t.push("  ❌ No capabilities discovered"),t.push("  💡 This might indicate the MCP is not properly configured or accessible"),t.push("");continue}let s=r.filter(e=>"advanced"===e.category),n=r.filter(e=>"basic"===e.category);t.push(`  🚀 **ADVANCED CAPABILITIES** (${s.length} functions):`),s.length>0?s.forEach(e=>{t.push(`    • \`${e.function}()\` - ${e.reason}`)}):t.push("    No advanced capabilities discovered"),t.push(""),t.push(`  ⚙️ **BASIC CAPABILITIES** (${n.length} functions):`),n.length>0?n.forEach(e=>{t.push(`    • \`${e.function}()\` - ${e.reason}`)}):t.push("    No basic capabilities discovered"),t.push("");let o=m.get(e);if(o){let e=Date.now()-o.timestamp,r=Math.floor(e/6e4);t.push(`  📝 **CACHE INFO:** Discovered ${r} minutes ago`),e>24e4&&t.push("  ⚠️  Cache will refresh soon on next use")}t.push("")}let n=s.reduce(async(e,t)=>{let r=await e,s=await v(t);return r+s.length},Promise.resolve(0));return t.push("🎯 **AUGMENTED DELEGATION STATUS:**"),t.push(`• Total discovered capabilities: ${await n}`),t.push(`• MCPs with advanced capabilities: ${s.filter(async e=>(await v(e)).some(e=>"advanced"===e.category)).length}`),t.push("• Dynamic discovery: ✅ Active (updates automatically)"),t.push("• Cache TTL: 5 minutes"),t.push(""),t.push("💡 **These capabilities are automatically suggested in dev3000's enhanced responses!**"),{content:[{type:"text",text:t.join("\n")}]}}catch(e){return t.push(`❌ **ERROR INSPECTING CAPABILITIES:** ${e instanceof Error?e.message:String(e)}`),t.push(""),t.push("💡 **Troubleshooting:**"),t.push("• Check that MCPs are properly configured in Claude Code"),t.push("• Verify dev3000 can access Claude cache directories"),{content:[{type:"text",text:t.join("\n")}]}}}async function k(e){let t,a,l=process.env.SCREENSHOT_DIR||(0,n.join)((0,s.tmpdir)(),"dev3000-mcp-deps","public","screenshots");if(!(0,r.existsSync)(l))return{detections:[],sessionId:"",totalFrames:0,screenshotDir:l};let c=(0,r.readdirSync)(l).filter(e=>e.includes("-jank-")&&e.endsWith(".png")).sort().reverse();if(0===c.length)return{detections:[],sessionId:"",totalFrames:0,screenshotDir:l};let u=c[0].split("-jank-")[0],d=c.filter(e=>e.startsWith(u)).sort((e,t)=>parseInt(e.match(/-(\d+)ms\.png$/)?.[1]||"0",10)-parseInt(t.match(/-(\d+)ms\.png$/)?.[1]||"0",10));if(d.length<2)return{detections:[],sessionId:u,totalFrames:d.length,screenshotDir:l};let p=(0,n.join)(l,`${u}-metadata.json`);if((0,r.existsSync)(p))try{let e=JSON.parse((0,r.readFileSync)(p,"utf-8"));a=e.captureTrigger,void 0!==e.layoutShifts&&(t={score:e.totalCLS||0,grade:e.clsGrade||"unknown",shifts:e.layoutShifts})}catch{}let f=[],m=new Map;try{let t=h(e);if(t&&(0,r.existsSync)(t)){let e=(0,r.readFileSync)(t,"utf-8").split("\n");for(let t=0;t<e.length;t++){let r=e[t].match(/\[CDP\] CLS #\d+ \(score: [\d.]+, time: (\d+)ms\):/);if(r){let s=parseInt(r[1],10),n=null,o=null;for(let r=t+1;r<Math.min(t+10,e.length);r++){if(!n){let t=e[r].match(/Before:\s+(http:\/\/\S+)/);t&&(n=t[1])}if(!o){let t=e[r].match(/After:\s+(http:\/\/\S+)/);t&&(o=t[1])}if(n&&o){m.set(s,{before:n,after:o});break}}}}}}catch(e){}if(t){if(0===t.shifts.length){let e=d.filter(e=>{let t=e.match(/-(\d+)ms\.png$/);return(t?parseInt(t[1],10):0)<1500}),s=!1;for(let t=1;t<e.length&&t<10;t++){let o=(0,n.join)(l,e[t-1]),a=(0,n.join)(l,e[t]);try{let n=i.PNG.sync.read((0,r.readFileSync)(o)),l=i.PNG.sync.read((0,r.readFileSync)(a));if(n.width!==l.width||n.height!==l.height)continue;let c=function(e,t){let r=e.width,s=e.height,n=Array(s).fill(0);for(let o=0;o<s;o++)for(let s=0;s<r;s++){let i=r*o+s<<2,a=Math.abs(e.data[i]-t.data[i]),l=Math.abs(e.data[i+1]-t.data[i+1]),c=Math.abs(e.data[i+2]-t.data[i+2]);(a>30||l>30||c>30)&&n[o]++}let o=n.map(e=>e/r*100),i=0,a=0;for(let e=0;e<s;e++)o[e]>50?i=Math.max(i,++a):a=0;let l=0;for(let e=5;e<s-5;e++){let t=o.slice(e-5,e).reduce((e,t)=>e+t,0)/5,r=o[e],s=o.slice(e+1,e+5+1).reduce((e,t)=>e+t,0)/5;t<10&&r>60&&s<10&&l++}let c=0;for(let e=0;e<s;e++)o[e]>5&&o[e]<25&&c++;let u=c>.3*s,d=Math.floor(s/8),p=Array(8).fill(0);for(let e=0;e<s;e++){let t=Math.min(Math.floor(e/d),7);p[t]+=n[e]}let h=r*d,f=p.map(e=>e/h*100),m=(f[0]+f[1])/2,g=(f[6]+f[7])/2,y=f.reduce((e,t)=>e+t,0)/f.length,v=f.reduce((e,t)=>e+(t-y)**2,0)/f.length,w=i>20,b=l>=3,S=u||b&&!w&&(v>500||y<10),x=!S&&(w||m>5&&g<2&&m>2*g||v<200&&y>10),C=p.reduce((e,t)=>e+t,0),E=r*s;return{isLayoutShift:x,shiftScore:C/E*.1,isOverlayNoise:S}}(n,l);if(c.isOverlayNoise){D(`Pixel Diff Hydration: Skipping frame ${t} - detected overlay noise (fixed/absolute elements), not true CLS`);continue}if(c.isLayoutShift){s=!0;let r=e[t].match(/-(\d+)ms\.png$/),n=r?parseInt(r[1],10):0;D(`Pixel Diff Hydration: Detected true layout shift at ${n}ms (score: ${c.shiftScore.toFixed(4)})`);let o=process.env.MCP_PORT||"3684";f.push({timestamp:`${n}ms`,timeSinceStart:n,visualDiff:100*c.shiftScore,severity:"high",element:"Hydration-related element",clsScore:c.shiftScore,uxImpact:"🚨 CRITICAL: Fast hydration shift detected - Chrome's observer missed this early shift",beforeFrameUrl:`http://localhost:${o}/api/screenshots/${e[t-1]}`,afterFrameUrl:`http://localhost:${o}/api/screenshots/${e[t]}`})}}catch{}}return s?{detections:f,sessionId:u,totalFrames:d.length,screenshotDir:l,realCLS:{score:.05,grade:"good"}}:{detections:[],sessionId:u,totalFrames:d.length,screenshotDir:l,realCLS:{score:0,grade:t.grade}}}return t.shifts.forEach(e=>{let t=e.sources?.[0]?.node||"unknown",r=e.sources?.[0]?.position;if(!e.sources?.[0]||"unknown"===t||null==r)return void D(`Chrome CLS: Skipping unidentified shift (score: ${e.score.toFixed(4)}) - cannot verify if it's a true CLS or fixed overlay noise`);if("fixed"===r||"absolute"===r)return void D(`Chrome CLS: Filtering out ${t} shift (position: ${r}) - fixed/absolute elements don't cause true layout shifts`);let s=["NAV","HEADER","BUTTON","A"].includes(t.toUpperCase()),n=e.timestamp<1e3,o={NAV:"Navigation header (<nav>)",HEADER:"Page header (<header>)",BUTTON:"Button (<button>)",A:"Link (<a>)"}[t.toUpperCase()]||t,i="low",a="Minor visual adjustment";s&&n?(i="high",a=`🚨 CRITICAL: ${o} shifted during initial load - highly visible and disruptive to user interaction`):s?(i="medium",a=`⚠️ ${o} shifted - affects navigation/interaction`):n&&(i="medium",a="Shift during page load - may cause mis-clicks");let l=Math.round(e.timestamp),c=m.get(l);f.push({timestamp:`${e.timestamp.toFixed(0)}ms`,timeSinceStart:l,visualDiff:100*e.score,severity:i,element:o,clsScore:e.score,uxImpact:a,beforeFrameUrl:c?.before,afterFrameUrl:c?.after})}),{detections:f,sessionId:u,totalFrames:d.length,screenshotDir:l,realCLS:{score:t.score,grade:t.grade}}}for(let e=1;e<d.length;e++){let t=(0,n.join)(l,d[e-1]),s=(0,n.join)(l,d[e]);try{let n=i.PNG.sync.read((0,r.readFileSync)(t)),a=i.PNG.sync.read((0,r.readFileSync)(s));if(n.width!==a.width||n.height!==a.height)continue;let l=new i.PNG({width:n.width,height:n.height}),c=(0,o.default)(n.data,a.data,l.data,n.width,n.height,{threshold:.1}),p=n.width*n.height,h=c/p*100;if(h>1){let t=d[e].match(/-(\d+)ms\.png$/),r=t?parseInt(t[1],10):0;f.push({timestamp:u,timeSinceStart:r,visualDiff:h,severity:h>10?"high":h>5?"medium":"low"})}}catch{}}return{detections:f,sessionId:u,totalFrames:d.length,screenshotDir:l,captureTrigger:a}}function D(e,t){try{let s=process.env.HOME||process.env.USERPROFILE;if(!s)return;let o=(0,n.join)(s,".d3k","logs");(0,r.existsSync)(o)||(0,r.mkdirSync)(o,{recursive:!0});let i=t||function(){try{let e=process.env.HOME||process.env.USERPROFILE;if(!e)return null;let t=(0,n.join)(e,".d3k");if(!(0,r.existsSync)(t))return null;let s=(0,r.readdirSync)(t).filter(e=>e.endsWith(".json"));if(0===s.length)return null;let o=(0,n.join)(t,s[0]);return JSON.parse((0,r.readFileSync)(o,"utf8")).projectName||null}catch{return null}}();if(!i)return;let a=(0,n.join)(o,`dev3000-${i}-d3k.log`),l=new Date().toISOString(),c=`[${l}] [D3K] ${e}
`;(0,r.appendFileSync)(a,c)}catch(e){}}function O(e,t){let r=e.includes("nextjs-dev"),s=e.includes("chrome-devtools");if(e.length>0){D(`MCP Detection: Available MCPs [${e.join(", ")}]`,t);let n=[];r&&n.push("Next.js"),s&&n.push("Chrome DevTools"),n.length>0?D(`MCP Integration: Activated integrations [${n.join(", ")}]`,t):D("MCP Integration: No compatible MCPs detected - running in standalone mode",t)}else D("MCP Detection: No MCPs provided - running in standalone mode",t);return{integrateNextjs:r,integrateChromeDevtools:s}}function M(e,t){let r=Math.ceil(Math.min(2*e,20)*(t?.5:1));return r<=5||r<=60?`${r} minutes`:`${Math.ceil(r/60)} hours`}async function j(e){try{let t=await v("dev3000-nextjs-dev"),r=t.filter(e=>"advanced"===e.category).slice(0,8).map(t=>({function:t.function,reason:t.reason,priority:F(t.function,e)}));return D(`Dynamic Suggestions: Generated ${r.length} Next.js suggestions from ${t.length} discovered capabilities`),r}catch(e){return D(`Dynamic Suggestions: Failed to generate Next.js suggestions - ${e}`),[{function:"analyze_build_process",reason:"Advanced Next.js build system analysis",priority:"high"},{function:"debug_server_rendering",reason:"Server-side rendering debugging",priority:"high"}]}}async function L(e){try{let t=await v("dev3000-chrome-devtools"),r=t.filter(e=>"advanced"===e.category).slice(0,8).map(t=>({function:t.function,reason:t.reason,priority:F(t.function,e)}));return D(`Dynamic Suggestions: Generated ${r.length} Chrome DevTools suggestions from ${t.length} discovered capabilities`),r}catch(e){return D(`Dynamic Suggestions: Failed to generate Chrome DevTools suggestions - ${e}`),[{function:"inspect_element",reason:"Deep DOM inspection with DevTools-level detail",priority:"high"},{function:"access_console",reason:"Direct browser console access and manipulation",priority:"high"}]}}function F(e,t){let r=e.toLowerCase(),s=t?.toLowerCase()||"";for(let{pattern:e,keywords:t}of[{pattern:/hydration/,keywords:["hydration","ssr","render"]},{pattern:/build|compile/,keywords:["build","compile","analyze"]},{pattern:/network|fetch|api/,keywords:["network","request","intercept","performance"]},{pattern:/console|error/,keywords:["console","error","debug"]},{pattern:/click|interaction/,keywords:["dom","element","inspect"]}])if(e.test(s)&&t.some(e=>r.includes(e)))return"high";return["debug","profile","analyze","trace","inspect"].some(e=>r.includes(e))?"medium":"low"}async function U({availableMcps:e,focusArea:t="all",errorContext:r}){let s=[];D(`Workflow Creation: Creating integrated workflow with focus area [${t}]${r?`, error context [${r}]`:""}`);let n=e||[];e&&0!==e.length||(D("Workflow Creation: No MCPs provided, starting proactive discovery"),n=await I());let{integrateNextjs:o,integrateChromeDevtools:i}=O(n);s.push("🎼 **INTELLIGENT DEBUGGING ORCHESTRATOR**"),s.push(`🔍 Available MCPs: ${n.length>0?n.join(", "):"none (will attempt discovery)"}`),s.push(`⚡ Integrations: ${o?"✅ Next.js":"❌ Next.js"} | ${i?"✅ Chrome DevTools":"❌ Chrome DevTools"}`),r&&s.push(`🎯 Error Context: ${r}`),s.push("");let a=o?await j(r):[],l=i?await L(r):[];if(!o&&!i)return s.push("⚠️ **NO INTEGRATIONS DETECTED**"),s.push("Running in standalone mode. For enhanced debugging:"),s.push("• Add 'nextjs-dev' MCP for Next.js-specific analysis"),s.push("• Add 'chrome-devtools' MCP for browser inspection"),s.push(""),s.push("💡 **STANDALONE WORKFLOW:**"),s.push("1. Use fix_my_app(mode='snapshot') to analyze current issues"),s.push("2. Use execute_browser_action to reproduce and verify fixes"),s.push("3. Implement suggested code fixes"),{content:[{type:"text",text:s.join("\n")}]};s.push("🎪 **3-PHASE INTEGRATED WORKFLOW**"),s.push(""),s.push("🕐 **PHASE 1: PARALLEL DATA COLLECTION** (2-3 minutes)"),s.push("Execute these functions in parallel across all available MCPs:"),s.push(""),s.push("📊 **dev3000 (this MCP):**"),s.push(`• fix_my_app(focusArea='${t}', integrateNextjs=${o}, integrateChromeDevtools=${i}, returnRawData=true)`),s.push("  → Get comprehensive error analysis with interaction data"),s.push(""),o&&(s.push("⚛️ **nextjs-dev MCP:**"),a.filter(e=>"high"===e.priority).forEach(e=>{let t=e.params?`(${Object.entries(e.params).map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(", ")})`:"()";s.push(`• ${e.function}${t}`),s.push(`  → ${e.reason}`)}),s.push("")),i&&(s.push("🌐 **chrome-devtools MCP:**"),l.filter(e=>"high"===e.priority).forEach(e=>{let t=e.params?`(${Object.entries(e.params).map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(", ")})`:"()";s.push(`• ${e.function}${t}`),s.push(`  → ${e.reason}`)}),s.push("")),s.push("🕑 **PHASE 2: DEEP TARGETED ANALYSIS** (3-5 minutes)"),s.push("Based on Phase 1 findings, execute these functions sequentially:"),s.push(""),s.push("🔗 **Cross-MCP Correlation:**"),s.push("• Compare dev3000 interaction data with browser console errors"),o&&(s.push("• Correlate dev3000 server errors with Next.js build/runtime logs"),s.push("• Match interaction timestamps with Next.js request handling")),s.push("• Identify root cause by combining all data sources"),s.push(""),s.push("🎯 **Targeted Deep Dive:**"),s.push("• Use fix_my_app(mode='bisect') for regression analysis if needed"),i&&l.filter(e=>"medium"===e.priority).forEach(e=>{let t=e.params?`(${Object.entries(e.params).map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(", ")})`:"()";s.push(`• ${e.function}${t} - ${e.reason}`)}),s.push(""),s.push("🕒 **PHASE 3: FIX IMPLEMENTATION & VERIFICATION** (5-10 minutes)"),s.push("Orchestrated fix implementation with cross-MCP verification:"),s.push(""),s.push("🔧 **Implementation:**"),s.push("• Apply code fixes identified by dev3000 error analysis"),o&&s.push("• Address Next.js-specific issues (hydration, build, etc.)"),s.push("• Use dev3000's interaction data to create comprehensive test scenarios"),s.push(""),s.push("✅ **Verification Workflow:**"),s.push("• Use execute_browser_action to replay exact user interactions that caused errors"),i&&(s.push("• Use chrome-devtools to monitor console for error resolution"),s.push("• Take before/after screenshots to verify UI fixes")),o&&s.push("• Use nextjs-dev to verify build success and runtime stability"),s.push("• Re-run fix_my_app to confirm error resolution"),s.push(""),s.push("🚀 **INTEGRATION BENEFITS:**"),o&&i?(s.push("🎯 **Triple-Stack Coverage:**"),s.push("• dev3000: AI-powered error correlation + interaction replay"),s.push("• nextjs-dev: Framework-specific server-side analysis"),s.push("• chrome-devtools: Precise browser state inspection"),s.push("• Combined: Complete full-stack debugging with 90%+ issue resolution"),s.push(""),s.push("⚡ **Expected Results:**"),s.push("• 3x faster debugging vs using tools individually"),s.push("• AI-powered error correlation across all layers"),s.push("• Systematic fix verification workflow"),s.push("• Comprehensive interaction-based testing")):o?(s.push("🎯 **Server-Side Enhanced Coverage:**"),s.push("• dev3000: Client error analysis + interaction data"),s.push("• nextjs-dev: Server-side logs and build analysis"),s.push("• Combined: Full-stack Next.js debugging coverage")):i&&(s.push("🎯 **Browser-Enhanced Coverage:**"),s.push("• dev3000: Error detection + interaction replay"),s.push("• chrome-devtools: Detailed browser state inspection"),s.push("• Combined: Complete client-side debugging workflow"));let c=M(5,o||i);return s.push(""),s.push(`⏱️ **ESTIMATED TOTAL TIME:** ${c}`),s.push(`🎼 **dev3000 orchestrates ${n.length} MCPs for maximum debugging power!**`),{content:[{type:"text",text:s.join("\n")}]}}async function _(e){let{beforeImageUrl:t,afterImageUrl:r,context:s}=e,n=[];return n.push("🔍 **VISUAL DIFF ANALYSIS**"),n.push(""),n.push("To analyze the visual differences between these two screenshots:"),n.push(""),n.push("**Step 1: Fetch and analyze the BEFORE image**"),n.push(`Use WebFetch with URL: \`${t}\``),n.push('Prompt: "Describe this screenshot in detail, focusing on layout and visible elements"'),n.push(""),n.push("**Step 2: Fetch and analyze the AFTER image**"),n.push(`Use WebFetch with URL: \`${r}\``),n.push('Prompt: "Describe this screenshot in detail, focusing on layout and visible elements"'),n.push(""),n.push("**Step 3: Compare and describe the differences**"),s?n.push(`Focus on: ${s}`):(n.push("Look for:"),n.push("• Elements that appeared or disappeared"),n.push("• Elements that moved or changed position"),n.push("• Elements that changed size or style"),n.push("• New content that pushed existing content")),n.push(""),n.push("**Step 4: Identify the layout shift cause**"),n.push("Describe what visual change occurred that caused the layout shift."),n.push("Be specific about:"),n.push("• Which element(s) changed"),n.push("• What appeared/moved/resized"),n.push("• Why this caused other elements to shift"),{content:[{type:"text",text:n.join("\n")}]}}async function B(e){let{selector:t}=e;try{let e=p();if(0===e.length)return{content:[{type:"text",text:"❌ **NO ACTIVE SESSIONS**\n\nNo active dev3000 sessions found. Make sure your app is running with dev3000."}]};let s=JSON.parse((0,r.readFileSync)(e[0].sessionFile,"utf-8")).cdpUrl;if(!s)try{let e=await fetch("http://localhost:9222/json"),t=(await e.json()).find(e=>"page"===e.type&&!e.url.startsWith("chrome://"));t&&(s=t.webSocketDebuggerUrl)}catch{return{content:[{type:"text",text:"❌ **NO CDP CONNECTION**\n\nFailed to find Chrome DevTools Protocol URL."}]}}if(!s)return{content:[{type:"text",text:"❌ **NO CDP CONNECTION**\n\nNo Chrome DevTools Protocol URL found."}]};let n=`
      (function() {
        try {
          const element = document.querySelector(${JSON.stringify(t)});
          if (!element) {
            return { error: "Element not found with selector: ${t}" };
          }

          // Try to find React Fiber
          const fiberKey = Object.keys(element).find(k => k.startsWith("__reactFiber$"));
          if (!fiberKey) {
            return { error: "No React internals found - element may not be a React component" };
          }

          const fiber = element[fiberKey];
          let componentFunction = null;
          let componentName = "Unknown";

          // Walk up the fiber tree to find a function component
          let current = fiber;
          let depth = 0;

          while (current && depth < 10) {
            if (typeof current.type === 'function') {
              componentFunction = current.type;
              componentName = current.type.name || current.type.displayName || "Anonymous";
              break;
            }
            current = current.return;
            depth++;
          }

          if (!componentFunction) {
            return { error: "Could not find component function in fiber tree" };
          }

          // Get the source code
          const sourceCode = componentFunction.toString();

          return {
            success: true,
            componentName,
            sourceCode
          };
        } catch (error) {
          return { error: error.message };
        }
      })()
    `,o=await new Promise((e,t)=>{let r=new l.default(s),o=null,i=!1,a=setTimeout(()=>{i||(i=!0,r.close(),t(Error("CDP evaluation timeout after 5 seconds")))},5e3);r.on("open",async()=>{try{r.send(JSON.stringify({id:1,method:"Target.getTargets",params:{}}));let s=2;r.on("message",async l=>{let c=JSON.parse(l.toString());if(1===c.id){if(c.error){clearTimeout(a),i=!0,r.close(),t(Error(`Browser protocol error: ${c.error.message||JSON.stringify(c.error)}. This may occur in sandboxed browser environments where certain CDP commands are restricted.`));return}let e=c.result?.targetInfos?.find(e=>"page"===e.type);if(!e){clearTimeout(a),i=!0,r.close(),t(Error("No page targets found"));return}r.send(JSON.stringify({id:s++,method:"Target.attachToTarget",params:{targetId:e.targetId,flatten:!0}}));return}if("Target.attachedToTarget"===c.method){o=s++,r.send(JSON.stringify({id:o,method:"Runtime.evaluate",params:{expression:n,returnByValue:!0}}));return}if(null!==o&&c.id===o)if(clearTimeout(a),i=!0,r.close(),c.error)t(Error(c.error.message));else{let t=c.result?.result?.value;e(t)}}),r.on("error",e=>{clearTimeout(a),i||(i=!0,t(e))})}catch(e){clearTimeout(a),i=!0,r.close(),t(e)}}),r.on("error",e=>{clearTimeout(a),i||(i=!0,t(e))})});if("error"in o)return{content:[{type:"text",text:`❌ **ERROR EXTRACTING COMPONENT**

${o.error}

💡 **TIPS:**
• Make sure the selector matches an element on the page
• Ensure the element is rendered by a React component
• Try a simpler selector like 'nav' or '.header'`}]};if(!o.success)return{content:[{type:"text",text:"❌ **FAILED TO EXTRACT COMPONENT**\n\nUnexpected result format."}]};let{componentName:i,sourceCode:a}=o,c=[],u=/<([A-Z][a-zA-Z0-9]*)/g,d=new Set,h=u.exec(a);for(;null!==h;)d.add(h[1]),h=u.exec(a);let f=/className=["']([^"']+)["']/g,m=new Set,g=f.exec(a);for(;null!==g;)m.add(g[1]),g=f.exec(a);let y=[];if(y.push("🔍 **COMPONENT SOURCE FINDER**"),y.push(""),y.push(`**Selector:** \`${t}\``),y.push(`**Component:** ${i}`),y.push(""),"Anonymous"!==i&&(c.push(`function ${i}`),c.push(`const ${i} =`),c.push(`export default function ${i}`)),d.size>0){let e=Array.from(d).filter(e=>!["Fragment","Suspense","ErrorBoundary"].includes(e));e.length>0&&c.push(`<${e[0]}`)}if(m.size>0){let e=Array.from(m)[0];c.push(`className="${e}"`)}if(0===c.length)y.push("⚠️ **NO UNIQUE PATTERNS FOUND**"),y.push(""),y.push("The component source code doesn't contain distinctive patterns to search for."),y.push("You may need to manually search for the component.");else{for(let e of(y.push("📍 **SEARCH PATTERNS**"),y.push(""),y.push("Use these grep patterns to find the source file:"),y.push(""),c.slice(0,3)))y.push("```"),y.push(`grep -r "${e.replace(/"/g,'\\"')}" .`),y.push("```"),y.push("");y.push("💡 **TIP:** Start with the first pattern. If it returns multiple results, try combining patterns.")}let v=a.substring(0,300);return y.push(""),y.push("**Source Code Preview:**"),y.push("```javascript"),y.push(`${v}...`),y.push("```"),{content:[{type:"text",text:y.join("\n")}]}}catch(e){return{content:[{type:"text",text:`❌ **ERROR**

${e instanceof Error?e.message:String(e)}`}]}}}async function G(e){let{projectName:s}=e;try{let e=p();if(0===e.length)return{content:[{type:"text",text:"❌ **NO ACTIVE SESSIONS**\n\nNo active dev3000 sessions found. Make sure your app is running with dev3000."}]};let n=e[0];if(s){let t=e.find(e=>e.projectName===s);t&&(n=t)}let o=JSON.parse((0,r.readFileSync)(n.sessionFile,"utf-8")),i=o.appPort,a=o.serverCommand,l=o.cwd;if(!i)return{content:[{type:"text",text:"❌ **NO APP PORT FOUND**\n\nSession file doesn't contain app port information."}]};if(!a)return{content:[{type:"text",text:"❌ **NO SERVER COMMAND FOUND**\n\nSession file doesn't contain the original server command. This session may have been created with an older version of dev3000."}]};D(`Restart Dev Server: Starting restart for project [${n.projectName}] on port ${i} with command [${a}]`);let u=(await I(n.projectName)).includes("nextjs-dev");if(D(`Restart Dev Server: Has nextjs-dev MCP: ${u}`),u)try{D("Restart Dev Server: Attempting to use nextjs-dev MCP restart");let e=await P({mcpName:"nextjs-dev"}),t=e.content[0]&&"text"in e.content[0]?e.content[0].text:"";if(t.includes("restart")||t.includes("reload"))return D("Restart Dev Server: nextjs-dev MCP has restart capability, delegating"),{content:[{type:"text",text:"✅ **DELEGATING TO NEXTJS-DEV MCP**\n\nThe nextjs-dev MCP has restart capabilities. Please use the nextjs-dev MCP restart tool directly for better integration with Next.js."}]};D("Restart Dev Server: nextjs-dev MCP doesn't have restart capability, falling back")}catch(e){D(`Restart Dev Server: Failed to check nextjs-dev capabilities - ${e}`)}if(D("Restart Dev Server: Using dev3000 restart mechanism"),"1"===process.env.VERCEL_SANDBOX||"1"===process.env.VERCEL||(0,r.existsSync)("/.dockerenv")||(0,r.existsSync)("/run/.containerenv"))return D("Restart Dev Server: Skipping lsof-based kill in sandbox environment"),{content:[{type:"text",text:`⚠️ **RESTART NOT SUPPORTED IN SANDBOX**

Dev server restart is not supported in sandbox environments (Vercel Sandbox, Docker containers).

The \`lsof\` utility needed for process management is not available.

💡 If running in Vercel Sandbox, the dev server is managed by the sandbox infrastructure.`}]};let d=`lsof -ti :${i} | xargs kill 2>/dev/null || true`;D(`Restart Dev Server: Executing kill command: ${d}`);try{await c(d),D("Restart Dev Server: Kill command executed successfully")}catch(e){D(`Restart Dev Server: Kill command failed (may be ok) - ${e}`)}await new Promise(e=>setTimeout(e,2e3));let h=`lsof -ti :${i}`,f=!1;try{let{stdout:e}=await c(h);f=""===e.trim(),D(`Restart Dev Server: Port check result - free: ${f}`)}catch{f=!0,D("Restart Dev Server: Port is free (lsof returned no results)")}if(!f)return{content:[{type:"text",text:`⚠️ **PORT STILL IN USE**

Failed to free port ${i}. There may be a process that couldn't be killed.

Try manually killing the process:
\`\`\`bash
lsof -ti :${i} | xargs kill -9
\`\`\``}]};D("Restart Dev Server: Port is now free, spawning new server process");try{let e=(0,t.spawn)(a,{stdio:"inherit",shell:!0,detached:!0,cwd:l||process.cwd()});e.unref(),D(`Restart Dev Server: Spawned new server process with PID ${e.pid}`),await new Promise(e=>setTimeout(e,1e3));try{let{stdout:t}=await c(`lsof -ti :${i}`);if(""!==t.trim())return D("Restart Dev Server: Server successfully restarted and running on port"),{content:[{type:"text",text:`✅ **DEV SERVER RESTARTED**

Successfully restarted the development server on port ${i}.

🎯 **STATUS:**
• Old server process: Killed
• New server process: Running (PID ${e.pid})
• Port ${i}: Active
• Browser monitoring: Unchanged
• Logs: Still being captured

💡 The server has been restarted while keeping dev3000's monitoring, screenshots, and logging intact.`}]};D("Restart Dev Server: Server process spawned but not yet listening on port (may still be starting)")}catch{D("Restart Dev Server: Server process spawned but not yet listening on port (may still be starting)")}return{content:[{type:"text",text:`🔄 **DEV SERVER RESTARTING**

Started a new server process (PID ${e.pid}).

⏳ **STATUS:**
• Old server: Killed
• New server: Starting (may take a few moments)
• Command: \`${a}\`
• Port: ${i}

The server is restarting. Check the dev3000 logs to see when it's ready.`}]}}catch(e){return D(`Restart Dev Server: Failed to spawn new server process - ${e}`),{content:[{type:"text",text:`❌ **RESTART FAILED**

Failed to start new server process.

**Error:** ${e instanceof Error?e.message:String(e)}

**Command:** \`${a}\`

The old server was killed but the new one failed to start. You may need to manually restart dev3000.`}]}}}catch(e){return D(`Restart Dev Server: Error - ${e}`),{content:[{type:"text",text:`❌ **ERROR**

${e instanceof Error?e.message:String(e)}`}]}}}async function V(e){let{depth:t=1,limit:s=3,projectName:n}=e;try{let e=p(),o=n?e.find(e=>e.projectName===n):e[0];if(!o)return{content:[{type:"text",text:n?`❌ No active session found for project "${n}". Available projects: ${e.map(e=>e.projectName).join(", ")||"none"}`:"❌ No active dev3000 sessions found. Start dev3000 first with `d3k` in your project directory."}]};let i=JSON.parse((0,r.readFileSync)(o.sessionFile,"utf-8")),a=i.cdpUrl?.replace("http://","ws://"),c=i.appPort||"3000",u=`http://localhost:${c}`;if(!a)return{content:[{type:"text",text:"❌ No Chrome DevTools connection found. Browser monitoring must be active to crawl."}]};D(`Crawl App: Starting crawl at depth ${t} with limit ${s} for ${u}`);let d=new l.default(a);await new Promise((e,t)=>{d.on("open",e),d.on("error",t),setTimeout(()=>t(Error("CDP connection timeout")),5e3)});let h=2e3,f=(e,t={})=>new Promise((r,s)=>{let n=h++,o=JSON.stringify({id:n,method:e,params:t}),i=e=>{let t=JSON.parse(e.toString());t.id===n&&(d.off("message",i),t.error?s(Error(t.error.message)):r(t.result))};d.on("message",i),d.send(o),setTimeout(()=>{d.off("message",i),s(Error("Command timeout"))},1e4)});await f("Runtime.enable"),await f("Page.enable");let m=new Set([u]),g=new Set,y=[u],v=0,w="all"===t?1/0:t;for(;y.length>0&&v<=w;){let e=[...y];for(let t of(y.length=0,D(`Crawl App: Processing depth ${v} with ${e.length} URLs`),e))if(!g.has(t)){g.add(t);try{D(`Crawl App: Visiting ${t}`),await f("Page.navigate",{url:t}),await new Promise(e=>setTimeout(e,2e3));let e=await f("Runtime.evaluate",{expression:`
              Array.from(document.querySelectorAll('a[href]')).map(a => {
                try {
                  const url = new URL(a.href, window.location.href);
                  // Only return same-origin links
                  if (url.origin === window.location.origin) {
                    // Remove hash and query params for deduplication
                    return url.origin + url.pathname;
                  }
                } catch {}
                return null;
              }).filter(Boolean)
            `,returnByValue:!0}),r=e.result?.value||[],n=0;for(let e of r)!m.has(e)&&(m.add(e),v<w&&n<s&&(y.push(e),n++));D(`Crawl App: Found ${r.length} links on ${t}, added ${n} to queue (limit: ${s})`)}catch(e){D(`Crawl App: Error visiting ${t} - ${e}`)}}if(v++,"all"===t&&0===y.length)break}d.close();let b=Array.from(m).sort(),S="all"===t?v-1:Math.min(v-1,w);return D(`Crawl App: Complete - discovered ${b.length} URLs at depth ${S}`),{content:[{type:"text",text:`🕷️ **APP CRAWL COMPLETE**

📊 **SUMMARY:**
• Base URL: ${u}
• Depth: ${S}${"all"===t?" (exhaustive)":""}
• Total URLs: ${b.length}

📍 **DISCOVERED URLs:**
${b.map(e=>`• ${e}`).join("\n")}

💡 **NEXT STEPS:**
• Use fix_my_app to check for errors across all pages
• Use execute_browser_action to test specific pages
• Verify all routes are working correctly`}]}}catch(e){return D(`Crawl App: Error - ${e}`),{content:[{type:"text",text:`❌ **CRAWL FAILED**

${e instanceof Error?e.message:String(e)}`}]}}}async function W(e){let{name:t}=e;D(`Get Skill: Fetching skill "${t}" via CLI`);try{let{stdout:e,stderr:r}=await c(`d3k skill "${t}"`,{timeout:5e3,env:{...process.env,NO_COLOR:"1"}});if(r&&!e)return D(`Get Skill: CLI error for "${t}": ${r}`),{content:[{type:"text",text:`❌ ${r.trim()}`}]};return D(`Get Skill: Found skill "${t}" (${e.length} chars)`),{content:[{type:"text",text:e}]}}catch(r){let e=r instanceof Error?r.message:String(r);D(`Get Skill: Failed to get skill "${t}": ${e}`);try{let{stdout:e}=await c("d3k skill --list",{timeout:5e3,env:{...process.env,NO_COLOR:"1"}});return{content:[{type:"text",text:`❌ Skill "${t}" not found.

${e}`}]}}catch{return{content:[{type:"text",text:`❌ Skill "${t}" not found. Could not list available skills (d3k CLI may not be available).`}]}}}}async function H({action:t,params:r={},session:o,headed:i=!1}){try{let a,l=await e.A(95496);if(!l.isAgentBrowserAvailable())return{content:[{type:"text",text:`❌ agent-browser is not available. Make sure it's installed with: bun add agent-browser && npx agent-browser install`}]};let c={session:o,headed:i};switch(t){case"open":{let e="string"==typeof r.url?r.url:"about:blank";a=await l.openUrl(e,c);break}case"click":{let e="string"==typeof r.target?r.target:"@e1";a=await l.click(e,c);break}case"type":{let e="string"==typeof r.text?r.text:"";a=await l.type(e,c);break}case"fill":{let e="string"==typeof r.target?r.target:"",t="string"==typeof r.value?r.value:"";a=await l.fill(e,t,c);break}case"scroll":{let e=r.direction||"down",t="number"==typeof r.amount?r.amount:void 0;a=await l.scroll(e,t,c);break}case"screenshot":{let e=(0,n.join)((0,s.homedir)(),".d3k","screenshots"),t=new Date().toISOString().replace(/[:.]/g,"-"),o=(0,n.join)(e,`agent-browser-${t}.png`),i=!0===r.fullPage;a=await l.screenshot(o,{...c,fullPage:i});break}case"snapshot":{let e=!1!==r.interactive,t=!0===r.compact,s=await l.snapshot({...c,interactive:e,compact:t});a={elements:s.elements,elementCount:s.elements.length,raw:s.raw.substring(0,5e3)};break}case"close":a=await l.close(c);break;case"reload":a=await l.reload(c);break;case"back":a=await l.back(c);break;default:return{content:[{type:"text",text:`❌ Unsupported agent-browser action: ${t}. Supported: open, click, type, fill, scroll, screenshot, snapshot, close, reload, back`}]}}return{content:[{type:"text",text:`✅ agent-browser ${t} completed:
${JSON.stringify(a,null,2)}`}]}}catch(e){return{content:[{type:"text",text:`❌ agent-browser ${t} failed: ${e instanceof Error?e.message:String(e)}`}]}}}e.s(["TOOL_DESCRIPTIONS",0,{_mcp_coordination:"**dev3000 is an MCP orchestrator for web development.** When both dev3000 and chrome-devtools-mcp are available, prefer dev3000's browser tools (execute_browser_action) as they provide:\n• Unified error context from server logs + browser console + network\n• Automatic screenshots on errors\n• Framework-aware diagnostics (Next.js, Svelte)\n• Coordinated Chrome connection management\n\ndev3000 automatically detects other MCP configurations and avoids conflicts.",fix_my_app:"Diagnoses application errors from dev3000 logs. Returns a prioritized list of issues requiring fixes.\n\n**CRITICAL: You MUST use this tool in a loop until all errors are resolved:**\n\n```\nwhile (errors exist) {\n  1. DIAGNOSE: Call fix_my_app to get current errors\n  2. FIX: Implement a fix for the highest-priority error\n  3. VERIFY: Call fix_my_app again to confirm the error is gone\n  4. REPEAT: Continue until no errors remain\n}\n```\n\n**This tool does NOT fix anything automatically.** It returns diagnostic data. You must:\n- Read the error output\n- Investigate and fix each issue\n- Call this tool again to verify your fix worked\n- Keep looping until the app is healthy\n\n**What it analyzes:**\n• Server logs, browser console, network requests\n• Categorizes: build errors, server crashes, browser errors, network issues, warnings\n• Prioritizes by severity (fix build errors first, then server, then browser, etc.)\n• Shows user interactions that triggered each error\n\n**Parameters:**\n• focusArea: 'build', 'runtime', 'network', 'ui', 'performance', or 'all' (default)\n• mode: 'snapshot' (current state), 'bisect' (before/after comparison), 'monitor' (continuous)\n• timeRangeMinutes: How far back to analyze (default: 10)\n• createPR: If true, creates a PR branch for the highest-priority issue\n\n**Framework support:** Auto-detects Next.js for framework-specific analysis.\n\n**Attribution for commits/PRs:**\n```\nGenerated with Claude Code using d3k (https://d3k.dev)\nCo-Authored-By: Claude <noreply@anthropic.com>\n```",execute_browser_action:"Executes browser actions (click, navigate, scroll, type, reload, evaluate JS) in the dev3000-managed Chrome instance.\n\n**PREFER THIS over standalone chrome-devtools-mcp tools.** dev3000 manages the Chrome connection and avoids CDP conflicts.\n\n**Available actions:**\n• screenshot: Capture current page state\n• navigate: Go to a URL\n• reload: Refresh the current page (triggers CLS recapture)\n• click: Click at coordinates {x, y} or selector\n• scroll: Scroll by {x, y} pixels\n• type: Type text into focused element\n• evaluate: Execute JavaScript (read-only operations recommended)\n\n**Use cases:**\n• Reproducing user interactions that triggered errors\n• Verifying fixes by replaying the error scenario\n• Testing specific UI workflows\n• Taking screenshots for visual verification",analyze_visual_diff:"Compares two screenshots and returns analysis instructions for identifying visual differences.\n\n**What it provides:**\n• Instructions to load both images for comparison\n• Context about what visual changes to look for\n• Guidance on identifying layout shift causes\n\n**Use cases:**\n• Analyzing before/after frames from CLS detection\n• Identifying elements that appeared, moved, or resized\n• Debugging visual regressions",find_component_source:"Maps a DOM element to its React component source code location.\n\n**How it works:**\n1. Inspects the element via Chrome DevTools Protocol\n2. Extracts the React component function source\n3. Identifies unique code patterns (JSX, classNames, etc.)\n4. Returns grep patterns to locate the source file\n\n**Use cases:**\n• Finding which file contains a specific UI element\n• Locating components responsible for layout shifts\n• Tracing DOM elements back to source code",restart_dev_server:"Restarts the development server while preserving dev3000's monitoring infrastructure.\n\n**Restart process:**\n1. Tries nextjs-dev MCP restart if available\n2. Falls back to killing and respawning the server process\n3. Preserves: MCP server, browser connection, log capture, screenshots\n\n**When to use:**\n• After modifying config files (next.config.js, middleware, .env)\n• To clear persistent server state\n• For changes that HMR cannot handle\n\n**Important:**\n• Do NOT manually kill the dev server with pkill/kill commands\n• Do NOT manually start the server with npm/pnpm/yarn\n• Server will be offline briefly during restart\n• Most code changes are handled by HMR - only restart when necessary",crawl_app:"Discovers URLs in the application by crawling links from the homepage.\n\n**Parameters:**\n• depth: How many link levels to follow (1, 2, 3, or 'all')\n• limit: Max links per page (default: 3)\n\n**Behavior:**\n• Starts at localhost homepage\n• Follows same-origin links only\n• Deduplicates discovered URLs\n• Returns list of all found pages\n\n**Use cases:**\n• Discovering all routes before running diagnostics\n• Site-wide testing coverage\n• Verifying all pages load without errors",get_skill:"Get the content of a d3k/Claude Code skill. Skills are prompt templates that provide specialized instructions for specific tasks.\n\n**Parameters:**\n• name: The skill name (e.g., 'vercel-design-guidelines', 'd3k')\n\n**Returns:**\nThe full SKILL.md content which contains instructions on how to perform the skill's task.\n\n**Available skills:**\n• vercel-design-guidelines - Audit web interfaces against Vercel's design guidelines\n• d3k - Core d3k development assistant skill\n\n**Use cases:**\n• Loading design guidelines audit instructions\n• Getting specialized workflow instructions",agent_browser_action:"Execute browser actions using agent-browser (Playwright-based CLI). More reliable than raw CDP in sandbox environments.\n\n**Actions:**\n• open: Open URL {url: string}\n• click: Click element {target: '@ref' or 'selector'}\n• type: Type into focused element {text: string}\n• fill: Fill input field {target, value}\n• scroll: Scroll page {direction: up/down/left/right, amount?}\n• screenshot: Capture screenshot {fullPage?: boolean}\n• snapshot: Get accessibility tree with refs for clicking\n• close: Close browser\n• reload: Reload page\n• back: Navigate back\n\n**Options:**\n• session: Session name for isolation\n• headed: Run with visible browser (default: false)\n\n**Ref-based clicking:**\nSnapshot returns elements with refs like @e1, @e2. Use these refs in click action for reliable element targeting."},"analyzeVisualDiff",()=>_,"calculateEstimatedTime",()=>M,"crawlApp",()=>V,"createIntegratedWorkflow",()=>U,"detectMcpIntegrations",()=>O,"discoverAvailableMcps",()=>I,"executeAgentBrowserAction",()=>H,"executeBrowserAction",()=>$,"findActiveSessions",()=>p,"findComponentSource",()=>B,"fixMyApp",()=>f,"generateChromeDevtoolsSuggestions",()=>L,"generateNextjsSuggestions",()=>j,"getLogPath",()=>h,"getMcpCapabilities",()=>P,"getSkill",()=>W,"restartDevServer",()=>G],56891)}];

//# sourceMappingURL=mcp-server_app_mcp_tools_ts_faf6d7df._.js.map