module.exports=[56891,e=>{"use strict";var t=e.i(33405),r=e.i(22734),s=e.i(46786),n=e.i(14747),i=e.i(92997),o=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 i=e.replace(/\x1b\[[0-9;]*m/g,""),o=i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\d+/g,"\\d+").substring(0,100),a=0;try{a=s.filter(e=>new RegExp(o).test(e)).length}catch{a=s.filter(e=>e.includes(i.substring(0,50))).length}a>1&&(n+=(a-1)*50),r.length>0&&(n+=50);let l=e.match(/\[(\d{2}):(\d{2}):(\d{2})\.\d{3}\]/);if(l){let e=new Date,t=new Date;t.setHours(parseInt(l[1],10)),t.setMinutes(parseInt(l[2],10)),t.setSeconds(parseInt(l[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
`,i=`fix/${e.category}-${Date.now()}`;return await c(`git checkout -b ${i}`),await c(`gh pr create --title "${s}" --body "${n}" --head ${i}`),`✅ Created PR: ${s}

Branch: ${i}

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 i of t)if(i.isDirectory()){let t=(0,n.join)(e,i.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:i=!1,timeRangeMinutes:o=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&&k(`Fix My App: Connected to downstream MCPs: ${y.join(", ")}`),v&&!1===l&&(l=!0),w&&!1===c&&(c=!0);let S=await x();S&&k("Fix My App: Recommending dev3000-nextjs-dev MCP for Next.js-specific analysis");let C=h(t);if(!C){let e=p();if(0===e.length)return{content:[{type:"text",text:"❌ No active dev3000 sessions found. Make sure dev3000 is running!"}]};if(k(`fix_my_app: Found ${e.length} sessions`),1===e.length){if(C=h(t=e[0].projectName),k(`fix_my_app: Auto-selected single session: ${t}, logPath: ${C}`),!C)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&&i){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)(C))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)(C,"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: ${C}`),E.push(`📊 Total log entries: ${e.length}`),E.push("");let i=new Date,h=new Date(i.getTime()-60*o*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")),x={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,P=e.filter(e=>g.some(t=>t.test(e))),M=P.length>A,F=(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||M)if(0===A&&M)E.push(`No errors in last ${o} minutes, but found ${P.length} errors in full log.`),E.push(""),E.push("Older errors (outside time range):"),P.slice(-5).forEach(t=>{let r=F(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=F(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=F(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=F(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=F(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"),k(`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 O(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 j(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),i=/CRITICAL|FATAL/i.test(r)?"critical":"error";s.push({error:r,category:"server",severity:i,priorityScore:u(r,"server",e,t),interactions:e})}for(let r of e.browserErrors){let e=n(r),i=/CRITICAL|FATAL/i.test(r)?"critical":"error";s.push({error:r,category:"browser",severity:i,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 ${o} 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 L=e.filter(e=>e.includes("[SCREENSHOT]")||e.includes("Screenshot captured"));if(L.length>0&&(E.push(""),E.push(`📸 **SCREENSHOTS CAPTURED** (${L.length} total):`),L.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 I(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 i="navigation"===e.captureTrigger?"Navigation complete":"load"===e.captureTrigger?"Load complete":"View all frames";E.push(`📹 **${i}**: ${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((x.totalRenders>0||"performance"===s||"all"===s)&&(x.unnecessaryRenders.length>0||x.slowComponents.length>0)&&(E.push(""),E.push("⚛️ **REACT PERFORMANCE ANALYSIS (react-scan):**"),x.unnecessaryRenders.length>0&&(E.push(`🔄 **Unnecessary Re-renders Detected (${x.unnecessaryRenders.length}):**`),x.unnecessaryRenders.slice(-5).forEach(e=>{E.push(`• ${e}`)}),E.push("")),x.slowComponents.length>0&&(E.push(`🐌 **Slow Components Found (${x.slowComponents.length}):**`),x.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;k(`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=F(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",i=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:i?i[1]:new Date().toISOString(),category:s,message:t,interactions:r,severity:n}}),i=[];n.forEach(e=>{("hydration"===e.category||e.message.includes("hydration"))&&i.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"))&&i.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"))&&i.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 o={};l&&(o.nextjs=await O(v.join(" "))),c&&(o.chrome=await j(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&&o.nextjs&&(r.phase1.actions.push(...o.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&&o.chrome&&r.phase1.actions.push(...o.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:i,suggestedIntegrations:o,workflowPlan:r,summary:{totalErrors:A,criticalErrors:N,hasIntegrations:l||c,estimatedFixTime:D(A,l||c)}};return{content:[{type:"text",text:JSON.stringify(a,null,2)}]}}let U=await b("profile_performance");return(S||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(""),S&&(E.push("**Next.js Framework Analysis:**"),(await O(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 j(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 k(`Capability Discovery: Using cached capabilities for ${e} (${t.capabilities.length} functions)`),t.capabilities;k(`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}),k(`Capability Discovery: Successfully discovered ${t.length} capabilities for ${e}`),t;let r=await C(e);return m.set(e,{timestamp:Date.now(),capabilities:r}),k(`Capability Discovery: Using fallback inference for ${e} (${r.length} functions)`),r}catch(t){return k(`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:i,readFileSync:o}=await e.A(23970);if(!i(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(!i(l))return[];let c=n(l),u=[];for(let e of c.slice(-5))try{let r=`${l}/${e}`,s=o(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 i=t.exec(e);for(;null!==i;){let o=i[1];if(y.some(e=>o.toLowerCase().includes(e))){i=t.exec(e);continue}let a=n.some(e=>o.toLowerCase().includes(e)),l=S(o,s,a);r.push({function:o,description:void 0,category:a?"advanced":"basic",reason:l}),i=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 k(`MCP Introspection: Failed to introspect ${t} - ${e}`),[]}}function S(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 C(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:S(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:S(e,t,!0)});return k(`Capability Inference: Generated ${r.length} inferred capabilities for ${e}`),r}async function b(e){try{if(!(await A()).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 k(`Chrome DevTools delegation check failed: ${e}`),!1}}async function x(){try{if(!(await A()).includes("dev3000-nextjs-dev"))return!1;return(await v("dev3000-nextjs-dev")).some(e=>"advanced"===e.category)}catch(e){return k(`NextJS delegation check failed: ${e}`),!1}}let E={"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"]},$={"nextjs-dev":[3001,3002,8080,8081],"chrome-devtools":[9222,9223,9224,3003]};async function T(){let e=[];try{process.platform;let{stdout:t}=await c("ps aux"),r=t.toLowerCase();for(let[t,s]of Object.entries(E))for(let n of s)if(r.includes(n.toLowerCase())){e.includes(t)||(e.push(t),k(`MCP Discovery: Found ${t} MCP via process detection [${n}]`));break}}catch(e){k(`MCP Discovery: Process detection failed - ${e instanceof Error?e.message:String(e)}`)}return e}async function R(){let e=[];for(let[t,r]of Object.entries($))for(let s of r)try{if((await fetch(`http://localhost:${s}/health`,{method:"GET",signal:AbortSignal.timeout(2e3)})).ok){e.push(t),k(`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,i)=>{let o=setTimeout(()=>{r.close(),i(Error("timeout"))},1e3);r.on("open",()=>{clearTimeout(o),r.close(),e.push(t),k(`MCP Discovery: Found ${t} MCP via WebSocket ping on port ${s}`),n(null)}),r.on("error",()=>{clearTimeout(o),i(Error("connection failed"))})});break}catch{}}return e}async function A(t){k("MCP Discovery: Starting proactive MCP discovery",t);let r=new Set;for(let e of(await T()))r.add(e);try{let s=`/Users/${process.env.USER}/Library/Caches/claude-cli-nodejs`,{readdirSync:n,existsSync:i}=await e.A(23970);if(i(s)){let e=n(s).find(e=>e.includes(process.cwd().replace(/\//g,"-")));if(e){let o=`${s}/${e}`,a=`${o}/mcp-logs-dev3000-chrome-devtools`;i(a)&&n(a).length>0&&(r.add("dev3000-chrome-devtools"),k("MCP Discovery: Found dev3000-chrome-devtools via Claude cache logs",t));let l=`${o}/mcp-logs-dev3000-nextjs-dev`;i(l)&&n(l).length>0&&(r.add("dev3000-nextjs-dev"),k("MCP Discovery: Found dev3000-nextjs-dev via Claude cache logs",t))}}}catch(e){k("MCP Discovery: Claude cache check failed, falling back to port detection",t)}if(0===r.size)for(let e of(k("MCP Discovery: No MCPs found via process or cache detection, trying port pinging",t),await R()))r.add(e);let s=Array.from(r);return s.length>0?k(`MCP Discovery: Successfully discovered MCPs [${s.join(", ")}]`,t):k("MCP Discovery: No MCPs detected - will run in standalone mode",t),s}async function N({mcpName:e}={}){let t=[];t.push("🔍 **MCP CAPABILITY INSPECTOR**"),t.push("");try{let r=await A();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 i=m.get(e);if(i){let e=Date.now()-i.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 I(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,i=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(!i){let t=e[r].match(/After:\s+(http:\/\/\S+)/);t&&(i=t[1])}if(n&&i){m.set(s,{before:n,after:i});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 i=(0,n.join)(l,e[t-1]),a=(0,n.join)(l,e[t]);try{let n=o.PNG.sync.read((0,r.readFileSync)(i)),l=o.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 i=0;i<s;i++)for(let s=0;s<r;s++){let o=r*i+s<<2,a=Math.abs(e.data[o]-t.data[o]),l=Math.abs(e.data[o+1]-t.data[o+1]),c=Math.abs(e.data[o+2]-t.data[o+2]);(a>30||l>30||c>30)&&n[i]++}let i=n.map(e=>e/r*100),o=0,a=0;for(let e=0;e<s;e++)i[e]>50?o=Math.max(o,++a):a=0;let l=0;for(let e=5;e<s-5;e++){let t=i.slice(e-5,e).reduce((e,t)=>e+t,0)/5,r=i[e],s=i.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++)i[e]>5&&i[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=o>20,S=l>=3,C=u||S&&!w&&(v>500||y<10),b=!C&&(w||m>5&&g<2&&m>2*g||v<200&&y>10),x=p.reduce((e,t)=>e+t,0),E=r*s;return{isLayoutShift:b,shiftScore:x/E*.1,isOverlayNoise:C}}(n,l);if(c.isOverlayNoise){k(`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;k(`Pixel Diff Hydration: Detected true layout shift at ${n}ms (score: ${c.shiftScore.toFixed(4)})`);let i=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:${i}/api/screenshots/${e[t-1]}`,afterFrameUrl:`http://localhost:${i}/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 k(`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 k(`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,i={NAV:"Navigation header (<nav>)",HEADER:"Page header (<header>)",BUTTON:"Button (<button>)",A:"Link (<a>)"}[t.toUpperCase()]||t,o="low",a="Minor visual adjustment";s&&n?(o="high",a=`🚨 CRITICAL: ${i} shifted during initial load - highly visible and disruptive to user interaction`):s?(o="medium",a=`⚠️ ${i} shifted - affects navigation/interaction`):n&&(o="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:o,element:i,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=o.PNG.sync.read((0,r.readFileSync)(t)),a=o.PNG.sync.read((0,r.readFileSync)(s));if(n.width!==a.width||n.height!==a.height)continue;let l=new o.PNG({width:n.width,height:n.height}),c=(0,i.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 k(e,t){try{let s=process.env.HOME||process.env.USERPROFILE;if(!s)return;let i=(0,n.join)(s,".d3k","logs");(0,r.existsSync)(i)||(0,r.mkdirSync)(i,{recursive:!0});let o=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 i=(0,n.join)(t,s[0]);return JSON.parse((0,r.readFileSync)(i,"utf8")).projectName||null}catch{return null}}();if(!o)return;let a=(0,n.join)(i,`dev3000-${o}-d3k.log`),l=new Date().toISOString(),c=`[${l}] [D3K] ${e}
`;(0,r.appendFileSync)(a,c)}catch(e){}}function P(e,t){let r=e.includes("nextjs-dev"),s=e.includes("chrome-devtools");if(e.length>0){k(`MCP Detection: Available MCPs [${e.join(", ")}]`,t);let n=[];r&&n.push("Next.js"),s&&n.push("Chrome DevTools"),n.length>0?k(`MCP Integration: Activated integrations [${n.join(", ")}]`,t):k("MCP Integration: No compatible MCPs detected - running in standalone mode",t)}else k("MCP Detection: No MCPs provided - running in standalone mode",t);return{integrateNextjs:r,integrateChromeDevtools:s}}function D(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 O(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:M(t.function,e)}));return k(`Dynamic Suggestions: Generated ${r.length} Next.js suggestions from ${t.length} discovered capabilities`),r}catch(e){return k(`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 j(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:M(t.function,e)}));return k(`Dynamic Suggestions: Generated ${r.length} Chrome DevTools suggestions from ${t.length} discovered capabilities`),r}catch(e){return k(`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 M(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 F({availableMcps:e,focusArea:t="all",errorContext:r}){let s=[];k(`Workflow Creation: Creating integrated workflow with focus area [${t}]${r?`, error context [${r}]`:""}`);let n=e||[];e&&0!==e.length||(k("Workflow Creation: No MCPs provided, starting proactive discovery"),n=await A());let{integrateNextjs:i,integrateChromeDevtools:o}=P(n);s.push("🎼 **INTELLIGENT DEBUGGING ORCHESTRATOR**"),s.push(`🔍 Available MCPs: ${n.length>0?n.join(", "):"none (will attempt discovery)"}`),s.push(`⚡ Integrations: ${i?"✅ Next.js":"❌ Next.js"} | ${o?"✅ Chrome DevTools":"❌ Chrome DevTools"}`),r&&s.push(`🎯 Error Context: ${r}`),s.push("");let a=i?await O(r):[],l=o?await j(r):[];if(!i&&!o)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=${i}, integrateChromeDevtools=${o}, returnRawData=true)`),s.push("  → Get comprehensive error analysis with interaction data"),s.push(""),i&&(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("")),o&&(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"),i&&(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"),o&&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"),i&&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"),o&&(s.push("• Use chrome-devtools to monitor console for error resolution"),s.push("• Take before/after screenshots to verify UI fixes")),i&&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:**"),i&&o?(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")):i?(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")):o&&(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=D(5,i||o);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 L(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 U(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 };
        }
      })()
    `,i=await new Promise((e,t)=>{let r=new l.default(s),i=null,o=!1,a=setTimeout(()=>{o||(o=!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),o=!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),o=!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){i=s++,r.send(JSON.stringify({id:i,method:"Runtime.evaluate",params:{expression:n,returnByValue:!0}}));return}if(null!==i&&c.id===i)if(clearTimeout(a),o=!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),o||(o=!0,t(e))})}catch(e){clearTimeout(a),o=!0,r.close(),t(e)}}),r.on("error",e=>{clearTimeout(a),o||(o=!0,t(e))})});if("error"in i)return{content:[{type:"text",text:`❌ **ERROR EXTRACTING COMPONENT**

${i.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(!i.success)return{content:[{type:"text",text:"❌ **FAILED TO EXTRACT COMPONENT**\n\nUnexpected result format."}]};let{componentName:o,sourceCode:a}=i,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:** ${o}`),y.push(""),"Anonymous"!==o&&(c.push(`function ${o}`),c.push(`const ${o} =`),c.push(`export default function ${o}`)),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 _(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 i=JSON.parse((0,r.readFileSync)(n.sessionFile,"utf-8")),o=i.appPort,a=i.serverCommand,l=i.cwd;if(!o)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."}]};k(`Restart Dev Server: Starting restart for project [${n.projectName}] on port ${o} with command [${a}]`);let u=(await A(n.projectName)).includes("nextjs-dev");if(k(`Restart Dev Server: Has nextjs-dev MCP: ${u}`),u)try{k("Restart Dev Server: Attempting to use nextjs-dev MCP restart");let e=await N({mcpName:"nextjs-dev"}),t=e.content[0]&&"text"in e.content[0]?e.content[0].text:"";if(t.includes("restart")||t.includes("reload"))return k("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."}]};k("Restart Dev Server: nextjs-dev MCP doesn't have restart capability, falling back")}catch(e){k(`Restart Dev Server: Failed to check nextjs-dev capabilities - ${e}`)}if(k("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 k("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 :${o} | xargs kill 2>/dev/null || true`;k(`Restart Dev Server: Executing kill command: ${d}`);try{await c(d),k("Restart Dev Server: Kill command executed successfully")}catch(e){k(`Restart Dev Server: Kill command failed (may be ok) - ${e}`)}await new Promise(e=>setTimeout(e,2e3));let h=`lsof -ti :${o}`,f=!1;try{let{stdout:e}=await c(h);f=""===e.trim(),k(`Restart Dev Server: Port check result - free: ${f}`)}catch{f=!0,k("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 ${o}. There may be a process that couldn't be killed.

Try manually killing the process:
\`\`\`bash
lsof -ti :${o} | xargs kill -9
\`\`\``}]};k("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(),k(`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 :${o}`);if(""!==t.trim())return k("Restart Dev Server: Server successfully restarted and running on port"),{content:[{type:"text",text:`✅ **DEV SERVER RESTARTED**

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

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

💡 The server has been restarted while keeping dev3000's monitoring, screenshots, and logging intact.`}]};k("Restart Dev Server: Server process spawned but not yet listening on port (may still be starting)")}catch{k("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: ${o}

The server is restarting. Check the dev3000 logs to see when it's ready.`}]}}catch(e){return k(`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 k(`Restart Dev Server: Error - ${e}`),{content:[{type:"text",text:`❌ **ERROR**

${e instanceof Error?e.message:String(e)}`}]}}}async function G(e){let{depth:t=1,limit:s=3,projectName:n}=e;try{let e=p(),i=n?e.find(e=>e.projectName===n):e[0];if(!i)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 o=JSON.parse((0,r.readFileSync)(i.sessionFile,"utf-8")),a=o.cdpUrl?.replace("http://","ws://"),c=o.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."}]};k(`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++,i=JSON.stringify({id:n,method:e,params:t}),o=e=>{let t=JSON.parse(e.toString());t.id===n&&(d.off("message",o),t.error?s(Error(t.error.message)):r(t.result))};d.on("message",o),d.send(i),setTimeout(()=>{d.off("message",o),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,k(`Crawl App: Processing depth ${v} with ${e.length} URLs`),e))if(!g.has(t)){g.add(t);try{k(`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++));k(`Crawl App: Found ${r.length} links on ${t}, added ${n} to queue (limit: ${s})`)}catch(e){k(`Crawl App: Error visiting ${t} - ${e}`)}}if(v++,"all"===t&&0===y.length)break}d.close();let S=Array.from(m).sort(),C="all"===t?v-1:Math.min(v-1,w);return k(`Crawl App: Complete - discovered ${S.length} URLs at depth ${C}`),{content:[{type:"text",text:`🕷️ **APP CRAWL COMPLETE**

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

📍 **DISCOVERED URLs:**
${S.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 k(`Crawl App: Error - ${e}`),{content:[{type:"text",text:`❌ **CRAWL FAILED**

${e instanceof Error?e.message:String(e)}`}]}}}async function B(e){let{name:t}=e;k(`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 k(`Get Skill: CLI error for "${t}": ${r}`),{content:[{type:"text",text:`❌ ${r.trim()}`}]};return k(`Get Skill: Found skill "${t}" (${e.length} chars)`),{content:[{type:"text",text:e}]}}catch(r){let e=r instanceof Error?r.message:String(r);k(`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 V({action:t,params:r={},session:i,headed:o=!1,profile:a}){try{let l,c,u=await e.A(95496);if(!u.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{getProjectDir:d}=await e.A(5282),p=a??(0,n.join)(d(),"chrome-profile"),h=process.env.CDP_URL;if(!h)try{let{existsSync:t,readFileSync:r}=await e.A(23970),s=(0,n.join)(d(),"session.json");t(s)&&(h=JSON.parse(r(s,"utf8")).cdpUrl)}catch{}if(h){let e=h.match(/:(\d+)\//);e&&(l=parseInt(e[1],10))}let f={session:i,headed:o,profile:p,cdpPort:l};switch(t){case"open":{let e="string"==typeof r.url?r.url:"about:blank";c=await u.openUrl(e,f);break}case"click":{let e="string"==typeof r.target?r.target:"@e1";c=await u.click(e,f);break}case"type":{let e="string"==typeof r.text?r.text:"";c=await u.type(e,f);break}case"fill":{let e="string"==typeof r.target?r.target:"",t="string"==typeof r.value?r.value:"";c=await u.fill(e,t,f);break}case"scroll":{let e=r.direction||"down",t="number"==typeof r.amount?r.amount:void 0;c=await u.scroll(e,t,f);break}case"screenshot":{let e=(0,n.join)((0,s.homedir)(),".d3k","screenshots"),t=new Date().toISOString().replace(/[:.]/g,"-"),i=(0,n.join)(e,`agent-browser-${t}.png`),o=!0===r.fullPage;c=await u.screenshot(i,{...f,fullPage:o});break}case"snapshot":{let e=!1!==r.interactive,t=!0===r.compact,s=await u.snapshot({...f,interactive:e,compact:t});c={elements:s.elements,elementCount:s.elements.length,raw:s.raw.substring(0,5e3)};break}case"close":c=await u.close(f);break;case"reload":c=await u.reload(f);break;case"back":c=await u.back(f);break;case"evaluate":{let e="string"==typeof r.expression?r.expression:"";c=await u.evaluate(e,f);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(c,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.** For browser automation, use the d3k CLI:\n```bash\nd3k agent-browser --cdp 9222 <command>\n```\nThis connects to d3k's existing Chrome browser. NEVER install Playwright or Chromium - d3k already has a browser open.\n\ndev3000 provides unified error context from server logs + browser console + network, automatic screenshots on errors, and framework-aware diagnostics (Next.js, Svelte).",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```",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:"⚠️ DANGEROUS: Restarts the development server. This is RARELY needed and often causes d3k to crash.\n\n**BEFORE using this tool, consider:**\n• HMR handles most code changes automatically - just wait a moment\n• Browser reload (Cmd+R) clears most cached state\n• 'use cache' in Next.js auto-invalidates when source files change\n• Restarting often fails and causes d3k to exit, disrupting the user's session\n\n**Only use for:**\n• Changes to next.config.js/ts (rare)\n• Changes to middleware.ts (rare)\n• Changes to .env files (rare)\n\n**DO NOT use for:**\n• Clearing RSC cache (HMR handles this)\n• Testing if a fix worked (just reload the page)\n• Any regular code changes\n\n**Ask the user first** before using this tool. They may prefer to manually restart d3k themselves.",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",_deprecated_agent_browser_action:"REMOVED - Use d3k CLI: `d3k agent-browser --cdp 9222 <command>` instead. This connects to d3k's existing Chrome browser without needing to install anything."},"analyzeVisualDiff",()=>L,"calculateEstimatedTime",()=>D,"crawlApp",()=>G,"createIntegratedWorkflow",()=>F,"detectMcpIntegrations",()=>P,"discoverAvailableMcps",()=>A,"executeAgentBrowserAction",()=>V,"findActiveSessions",()=>p,"findComponentSource",()=>U,"fixMyApp",()=>f,"generateChromeDevtoolsSuggestions",()=>j,"generateNextjsSuggestions",()=>O,"getLogPath",()=>h,"getMcpCapabilities",()=>N,"getSkill",()=>B,"restartDevServer",()=>_],56891)}];

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