module.exports=[801177,e=>{"use strict";var t=e.i(680717);async function o(e){let o=`report-${e.id}.json`,s=await (0,t.put)(o,JSON.stringify(e,null,2),{access:"public",contentType:"application/json",addRandomSuffix:!1,allowOverwrite:!0});return console.log(`[Report] Saved report ${e.id} to: ${s.url}`),s.url}async function s(e,t,s,a,r,n){let l,i,c;console.log(`[Step 0] Creating d3k sandbox for ${s}...`),console.log(`[Step 0] Repository: ${e}`),console.log(`[Step 0] Branch: ${t}`),console.log(`[Step 0] VERCEL_OIDC_TOKEN from env: ${!!process.env.VERCEL_OIDC_TOKEN}`),console.log(`[Step 0] VERCEL_OIDC_TOKEN passed as param: ${!!r}`),console.log(`[Step 0] VERCEL_TOKEN available: ${!!process.env.VERCEL_TOKEN}`),console.log(`[Step 0] User access token provided: ${!!a}`),r&&!process.env.VERCEL_OIDC_TOKEN&&(process.env.VERCEL_OIDC_TOKEN=r,console.log("[Step 0] Set VERCEL_OIDC_TOKEN from workflow context"));let d=await createD3kSandboxUtil({repoUrl:e,branch:t,projectDir:"",packageManager:"pnpm",debug:!0});console.log("[Step 0] Sandbox created successfully"),console.log(`[Step 0] Dev URL: ${d.devUrl}`),console.log(`[Step 0] MCP URL: ${d.mcpUrl}`),console.log("[Step 0] Getting Chromium path for screenshots...");let p="/tmp/chromium";try{let e=await runSandboxCommand(d.sandbox,"node",["-e","require('@sparticuz/chromium').executablePath().then(p => console.log(p))"]);0===e.exitCode&&e.stdout.trim()&&(p=e.stdout.trim(),console.log(`[Step 0] Chromium path: ${p}`))}catch{console.log(`[Step 0] Could not get chromium path, using default: ${p}`)}console.log("[Step 0] ===== CHROMIUM CDP TEST (d3k exact command) =====");try{let e=`
      exec 2>&1
      echo "=== Chromium CDP Test (d3k exact command) ==="
      echo "Chromium path: ${p}"
      echo ""

      # Create user-data-dir like d3k does
      USER_DATA_DIR="/tmp/d3k-test-profile"
      mkdir -p "$USER_DATA_DIR"
      echo "1. Created user-data-dir: $USER_DATA_DIR"

      # Create loading page like d3k does
      LOADING_DIR="/tmp/dev3000-loading"
      mkdir -p "$LOADING_DIR"
      cat > "$LOADING_DIR/loading.html" << 'LOADINGHTML'
<!DOCTYPE html>
<html>
<head><title>Loading...</title></head>
<body><h1>Loading dev3000...</h1></body>
</html>
LOADINGHTML
      echo "2. Created loading page: $LOADING_DIR/loading.html"
      echo ""

      # Use EXACT d3k command (from cdp-monitor.ts)
      # Note: d3k does NOT use --remote-debugging-address
      echo "3. Starting Chrome with d3k's exact args..."
      echo "   Command: ${p} --remote-debugging-port=9222 --user-data-dir=$USER_DATA_DIR --no-first-run --no-default-browser-check --disable-component-extensions-with-background-pages --disable-background-networking --disable-sync --metrics-recording-only --disable-default-apps --disable-session-crashed-bubble --disable-restore-session-state --headless=new --no-sandbox --disable-setuid-sandbox --disable-gpu --disable-dev-shm-usage file://$LOADING_DIR/loading.html"

      timeout 15 "${p}" \\
        --remote-debugging-port=9222 \\
        --user-data-dir="$USER_DATA_DIR" \\
        --no-first-run \\
        --no-default-browser-check \\
        --disable-component-extensions-with-background-pages \\
        --disable-background-networking \\
        --disable-sync \\
        --metrics-recording-only \\
        --disable-default-apps \\
        --disable-session-crashed-bubble \\
        --disable-restore-session-state \\
        --headless=new \\
        --no-sandbox \\
        --disable-setuid-sandbox \\
        --disable-gpu \\
        --disable-dev-shm-usage \\
        "file://$LOADING_DIR/loading.html" &
      PID=$!
      echo "   Chrome PID: $PID"
      sleep 3
      echo ""

      echo "4. Checking if Chrome is still running..."
      if ps -p $PID > /dev/null 2>&1; then
        echo "   Chrome is RUNNING after 3s"
        echo ""
        echo "5. Trying CDP (note: d3k doesn't use --remote-debugging-address)..."
        echo "   Trying 127.0.0.1..."
        curl -s --max-time 5 http://127.0.0.1:9222/json/version 2>&1 || echo "   127.0.0.1 failed"
        echo ""
        echo "   Trying localhost..."
        curl -s --max-time 5 http://localhost:9222/json/version 2>&1 || echo "   localhost failed"
        echo ""
        echo "6. Checking what's listening on 9222..."
        ss -tlnp 2>/dev/null | grep 9222 || netstat -tlnp 2>/dev/null | grep 9222 || echo "   Could not check listening ports"
        echo ""
        echo "7. Killing test Chrome..."
        kill $PID 2>/dev/null
      else
        echo "   Chrome DIED within 3s"
        wait $PID 2>/dev/null
        EXIT_CODE=$?
        echo "   Exit code: $EXIT_CODE"
        echo ""
        echo "   Checking for crash logs..."
        ls -la "$USER_DATA_DIR" 2>&1 | head -10 || echo "   No user-data-dir"
      fi
      echo ""
      echo "=== End d3k exact command test ==="
    `,t=await runSandboxCommand(d.sandbox,"bash",["-c",e]);console.log(`[Step 0] d3k Chrome test (exit ${t.exitCode}):
${t.stdout||"(no output)"}`),t.stderr&&console.log(`[Step 0] d3k Chrome test stderr: ${t.stderr}`)}catch(e){console.log(`[Step 0] d3k Chrome test error: ${e instanceof Error?e.message:String(e)}`)}console.log("[Step 0] ===== END d3k EXACT COMMAND TEST ====="),console.log("[Step 0] Capturing BEFORE screenshot...");let g=null;try{let e=await captureScreenshotInSandbox(d.sandbox,"http://localhost:3000",p,"before");e&&(g=await uploadScreenshot(e,"before",s))}catch(e){console.log(`[Step 0] Before screenshot failed: ${e instanceof Error?e.message:String(e)}`)}console.log("[Step 0] Capturing CLS metrics from inside sandbox...");let u=null,h=null;try{let e='curl -s -X POST http://localhost:3684/mcp -H "Content-Type: application/json" -d \'{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"fix_my_app","arguments":{"mode":"snapshot","focusArea":"performance","returnRawData":true}}}\'';console.log("[Step 0] Executing MCP command inside sandbox..."),console.log(`[Step 0] MCP command: ${e.substring(0,200)}...`);let t="",o="",s=-1;try{let a=await runSandboxCommand(d.sandbox,"bash",["-c",e]);t=a.stdout,o=a.stderr,s=a.exitCode,console.log(`[Step 0] MCP command exit code: ${s}`),console.log(`[Step 0] MCP stdout length: ${t.length} bytes`),o&&console.log(`[Step 0] MCP stderr: ${o.substring(0,500)}`)}catch(t){let e=t instanceof Error?t.message:String(t);console.log(`[Step 0] sandbox.runCommand threw: ${e}`),h=`sandbox.runCommand failed: ${e}`}if(0===s&&t)try{let e=JSON.parse(t);if(e.result?.content){for(let t of e.result.content)if("text"===t.type&&t.text){try{u=JSON.parse(t.text),console.log("[Step 0] Successfully parsed CLS data as JSON")}catch{u={rawOutput:t.text},console.log("[Step 0] CLS data stored as rawOutput (not JSON)")}break}}u?console.log("[Step 0] CLS data captured:",JSON.stringify(u).substring(0,500)):(console.log("[Step 0] No CLS data extracted from MCP response"),console.log(`[Step 0] Response structure: ${JSON.stringify(e).substring(0,500)}`))}catch(e){h=`Failed to parse MCP response: ${e instanceof Error?e.message:String(e)}`,console.log(`[Step 0] ${h}`),console.log(`[Step 0] Raw stdout: ${t.substring(0,1e3)}`),u={rawMcpOutput:t.substring(0,1e4),parseError:h},console.log("[Step 0] Using raw stdout as fallback CLS data")}else 0!==s&&!h&&(h=`MCP command failed with exit code ${s}`,console.log(`[Step 0] ${h}`),o&&console.log(`[Step 0] stderr: ${o}`))}catch(e){h=`MCP execution error: ${e instanceof Error?e.message:String(e)}`,console.log(`[Step 0] ${h}`)}u||(console.log("[Step 0] WARNING: No CLS data captured, creating placeholder to prevent Step 1 timeout"),u={warning:"MCP fix_my_app did not return data",mcpError:h||"Unknown error",sandboxDevUrl:d.devUrl,sandboxMcpUrl:d.mcpUrl}),console.log(`[Step 0] Final clsData truthy check: ${!!u}`),console.log("[Step 0] === Dumping sandbox logs before returning ===");try{let e=await runSandboxCommand(d.sandbox,"sh",["-c",'for log in /home/vercel-sandbox/.d3k/logs/*.log; do [ -f "$log" ] && echo "=== $log ===" && tail -100 "$log" || true; done 2>/dev/null || echo "No log files found"']);console.log(e.stdout)}catch(e){console.log(`[Step 0] Failed to dump logs: ${e instanceof Error?e.message:String(e)}`)}console.log("[Step 0] === End sandbox log dump ==="),console.log("[Step 0] Capturing git diff from sandbox...");let m=null;try{let e=await runSandboxCommand(d.sandbox,"sh",["-c","cd /vercel/sandbox && git diff --no-color 2>/dev/null || echo 'No git diff available'"]);0===e.exitCode&&e.stdout.trim()&&"No git diff available"!==e.stdout.trim()?(m=e.stdout.trim(),console.log(`[Step 0] Git diff captured (${m.length} chars)`),console.log(`[Step 0] Git diff preview:
${m.substring(0,500)}...`)):console.log("[Step 0] No git changes detected in sandbox")}catch(e){console.log(`[Step 0] Failed to capture git diff: ${e instanceof Error?e.message:String(e)}`)}console.log("[Step 0] Fetching d3k artifacts from sandbox...");let f=await fetchAndUploadD3kArtifacts(d.sandbox,d.mcpUrl,s),S=n||`report-${Date.now()}`,b=new Date().toISOString();if(f?.metadata){let e=f.metadata;l=e.totalCLS,("good"===e.clsGrade||"needs-improvement"===e.clsGrade||"poor"===e.clsGrade)&&(i=e.clsGrade),e.layoutShifts&&(c=e.layoutShifts.map(e=>({score:e.score,timestamp:e.timestamp,elements:e.sources?.map(e=>e.node||"unknown").filter(Boolean)||[]})))}let $={id:S,projectName:s,timestamp:b,sandboxDevUrl:d.devUrl,sandboxMcpUrl:d.mcpUrl,clsScore:l,clsGrade:i,layoutShifts:c,beforeScreenshotUrl:g||void 0,clsScreenshots:f?.clsScreenshots?.map(e=>({timestamp:e.timestamp,blobUrl:e.blobUrl,label:e.label})),d3kLogs:f?.fullLogs||void 0,agentAnalysis:"Analysis in progress..."};console.log("[Step 0] Saving initial report to blob storage..."),console.log(`[Step 0] Report ID: ${S}`),console.log(`[Step 0] CLS Score: ${l??"not captured"}`),console.log(`[Step 0] CLS Screenshots: ${$.clsScreenshots?.length??0}`),$.d3kLogs&&console.log(`[Step 0] d3k logs: ${$.d3kLogs.length} chars`);let y=await o($);console.log(`[Step 0] Initial report saved: ${y}`),console.log("[Step 0] Running AI agent with sandbox tools...");let w=null;try{let e=u?JSON.stringify(u,null,2):"No CLS data captured";w=await runAgentWithSandboxTools(d.sandbox,d.mcpUrl,d.devUrl,e),console.log(`[Step 0] Agent analysis completed (${w.length} chars)`),$.agentAnalysis=w,$.agentAnalysisModel="anthropic/claude-sonnet-4-20250514",await o($),console.log("[Step 0] Report updated with agent analysis");let t=await runSandboxCommand(d.sandbox,"sh",["-c","cd /vercel/sandbox && git diff --no-color 2>/dev/null || echo 'No git diff available'"]);0===t.exitCode&&t.stdout.trim()&&"No git diff available"!==t.stdout.trim()&&(m=t.stdout.trim(),console.log(`[Step 0] Agent made changes - git diff captured (${m.length} chars)`))}catch(e){console.log(`[Step 0] Agent analysis failed: ${e instanceof Error?e.message:String(e)}`),w=`Agent analysis failed: ${e instanceof Error?e.message:String(e)}`}return{mcpUrl:d.mcpUrl,devUrl:d.devUrl,bypassToken:d.bypassToken,clsData:u,mcpError:h,beforeScreenshotUrl:g,chromiumPath:p,gitDiff:m,d3kArtifacts:f,reportId:S,reportBlobUrl:y,agentAnalysis:w}}async function a(e,o,s,a,r,n){if(console.log(`[Step 1] Received clsData: ${a?"truthy":"falsy"}, type: ${typeof a}`),a&&console.log(`[Step 1] clsData preview: ${JSON.stringify(a).substring(0,200)}`),a)return console.log("[Step 1] ✅ Using CLS data captured in Step 0 (skipping MCP calls)"),n&&console.log(`[Step 1] Before screenshot from Step 0: ${n}`),{logAnalysis:JSON.stringify(a,null,2),beforeScreenshotUrl:n||null};console.log("[Step 1] ⚠️ No CLS data from Step 0, will try MCP calls (may timeout)"),r&&console.log(`[Step 1] Note: MCP error from Step 0: ${r}`);let l=!!s,i=s||e,c=l?e:null;console.log(`[Step 1] Fetching logs from: ${i}`),console.log(`[Step 1] Using sandbox: ${l?"yes":"no"}`),c&&console.log(`[Step 1] MCP URL: ${c}`),console.log(`[Step 1] Bypass token: ${o?"provided":"not provided"}`);try{let e=o?`${i}?x-vercel-protection-bypass=${o}`:i;if(console.log(`[Step 1] Final URL: ${e.replace(o||"","***")}`),l&&c){console.log("[Step 1] Using d3k MCP server to capture CLS metrics and errors..."),console.log("[Step 1] Validating d3k MCP server access...");let o=new AbortController,s=setTimeout(()=>o.abort(),3e4);try{let e=await fetch(`${c}/mcp`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream"},body:JSON.stringify({jsonrpc:"2.0",id:0,method:"tools/list"}),signal:o.signal});if(clearTimeout(s),e.ok){let t=await e.text();try{let e=null;for(let o of t.split("\n"))if(o.startsWith("data: "))try{e=JSON.parse(o.substring(6));break}catch{}e||(e=JSON.parse(t));let o=e.result?.tools?.map(e=>e.name)||[];console.log(`[Step 1] ✅ d3k MCP server accessible`),console.log(`[Step 1] Available tools (${o.length}): ${o.join(", ")}`);let s=o.some(e=>e.includes("chrome-devtools")),a=o.some(e=>e.includes("nextjs")),r=o.includes("fix_my_app");console.log(`[Step 1] Chrome DevTools MCP: ${s?"✅":"❌"}`),console.log(`[Step 1] Next.js DevTools MCP: ${a?"✅":"❌"}`),console.log(`[Step 1] fix_my_app tool: ${r?"✅":"❌"}`)}catch{console.log(`[Step 1] MCP server responded but couldn't parse tools list: ${t.substring(0,200)}`)}}else console.log(`[Step 1] ⚠️  MCP server not accessible: ${e.status}`)}catch(o){clearTimeout(s);let e=o instanceof Error?o.message:String(o),t=o instanceof Error&&"AbortError"===o.name;console.log(`[Step 1] ⚠️  Failed to validate MCP server: ${t?"Timed out after 30s":e}`)}console.log("[Step 1] Navigating browser to app URL...");let a=new AbortController,r=setTimeout(()=>a.abort(),3e4);try{let t=await fetch(`${c}/mcp`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream"},body:JSON.stringify({jsonrpc:"2.0",id:0,method:"tools/call",params:{name:"execute_browser_action",arguments:{action:"navigate",params:{url:e}}}}),signal:a.signal});clearTimeout(r),t.ok?console.log("[Step 1] Browser navigation completed"):console.log(`[Step 1] Browser navigation failed: ${t.status}`)}catch(t){clearTimeout(r);let e=t instanceof Error&&"AbortError"===t.name;console.log(`[Step 1] Browser navigation error: ${e?"Timed out after 30s":t instanceof Error?t.message:String(t)}`)}console.log("[Step 1] Waiting 5s for page load..."),await new Promise(e=>setTimeout(e,5e3));let n=null;console.log("[Step 1] Capturing 'before' screenshot...");let l=new AbortController,d=setTimeout(()=>l.abort(),3e4);try{let e=await fetch(`${c}/mcp`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream"},body:JSON.stringify({jsonrpc:"2.0",id:0,method:"tools/call",params:{name:"chrome-devtools_take_snapshot",arguments:{}}}),signal:l.signal});if(clearTimeout(d),e.ok){let o=await e.text();for(let e of o.split("\n"))if(e.startsWith("data: "))try{let o=JSON.parse(e.substring(6));if(o.result?.content){for(let e of o.result.content)if("image"===e.type&&e.data){let o=Buffer.from(e.data,"base64"),s=new Date().toISOString().replace(/[:.]/g,"-"),a=`screenshot-before-${s}.png`;n=(await (0,t.put)(a,o,{access:"public",contentType:"image/png"})).url,console.log(`[Step 1] ✅ Before screenshot uploaded: ${n}`)}}}catch{}n||(console.log("[Step 1] Screenshot response received but no image data found"),console.log(`[Step 1] Response preview: ${o.substring(0,500)}`))}else console.log(`[Step 1] Screenshot request failed: ${e.status}`)}catch(t){clearTimeout(d);let e=t instanceof Error&&"AbortError"===t.name;console.log(`[Step 1] Screenshot capture error: ${e?"Timed out after 30s":t instanceof Error?t.message:String(t)}`)}console.log("[Step 1] Fetching d3k logs from sandbox to verify it's working...");let p=new AbortController,g=setTimeout(()=>p.abort(),15e3);try{let e=await fetch(`${c}/api/logs`,{signal:p.signal});if(clearTimeout(g),e.ok){let t=await e.text();console.log(`[Step 1] d3k logs (last 1000 chars):
${t.slice(-1e3)}`)}else console.log(`[Step 1] Could not fetch d3k logs: ${e.status}`)}catch(t){clearTimeout(g);let e=t instanceof Error&&"AbortError"===t.name;console.log(`[Step 1] Failed to fetch d3k logs: ${e?"Timed out after 15s":t instanceof Error?t.message:String(t)}`)}console.log("[Step 1] Calling fix_my_app with focusArea='performance'...");let u=new AbortController,h=setTimeout(()=>u.abort(),18e4);try{let e=await fetch(`${c}/mcp`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"fix_my_app",arguments:{mode:"snapshot",focusArea:"performance",timeRangeMinutes:5,returnRawData:!1}}}),signal:u.signal});if(clearTimeout(h),!e.ok)throw Error(`MCP request failed: ${e.status}`);let t=await e.text();console.log(`[Step 1] fix_my_app response length: ${t.length} bytes`),console.log(`[Step 1] fix_my_app response preview (first 500 chars):
${t.substring(0,500)}`);let o=t.split("\n");console.log(`[Step 1] Response split into ${o.length} lines`);let s="",a=0,r=0;for(let e of o)if(e.startsWith("data: ")){a++;try{let t=JSON.parse(e.substring(6));if(console.log(`[Step 1] Parsed JSON line ${a}:`,JSON.stringify(t).substring(0,200)),t.result?.content)for(let e of t.result.content)"text"===e.type&&(r++,s+=e.text,console.log(`[Step 1] Added text content block ${r}, length: ${e.text.length}`));else t.error&&console.log(`[Step 1] ERROR in response: ${JSON.stringify(t.error)}`)}catch(t){console.log(`[Step 1] Failed to parse JSON line ${a}: ${t instanceof Error?t.message:String(t)}`),console.log(`[Step 1] Problem line: ${e.substring(0,200)}`)}}return console.log(`[Step 1] Processed ${a} data lines, ${r} content blocks`),console.log(`[Step 1] Got ${s.length} chars from fix_my_app (performance analysis)`),0===s.length&&console.log(`[Step 1] WARNING: fix_my_app returned NO data. Full response:
${t}`),{logAnalysis:`d3k Performance Analysis for ${i}

${s}`,beforeScreenshotUrl:n}}catch(e){clearTimeout(h),e instanceof Error&&"AbortError"===e.name?console.log("[Step 1] fix_my_app timed out after 3 minutes, using fallback method"):console.log(`[Step 1] fix_my_app error: ${e instanceof Error?e.message:String(e)}`)}}console.log("[Step 1] Using AI Gateway with browser automation...");let s=createGateway({apiKey:process.env.AI_GATEWAY_API_KEY,baseURL:"https://ai-gateway.vercel.sh/v1/ai"})("anthropic/claude-sonnet-4-20250514"),a=`You are a web application debugger with access to browser automation tools via Playwright MCP.

Your task is to visit this URL and capture any errors, warnings, or issues:
${e}

Steps to follow:
1. Use browser_eval with action="start" to start the browser
2. Use browser_eval with action="navigate" and params={url: "${e}"} to navigate to the page
3. Wait a few seconds for the page to fully load and JavaScript to execute
4. Use browser_eval with action="console_messages" to get all browser console output (errors, warnings, logs)
5. Use browser_eval with action="screenshot" to capture a screenshot
6. Use browser_eval with action="close" to close the browser

Analyze the console messages and provide a detailed report including:
- All console errors (with full stack traces if available)
- All console warnings
- HTTP status codes or network errors
- Any visual issues you can identify from the screenshot
- Screenshot URL if captured

Format your response as a clear, structured report that helps identify what's broken in the application.`,{text:r}=await generateText({model:s,prompt:a,toolChoice:"auto",maxTokens:4e3});return console.log(`[Step 1] Browser automation response (first 500 chars): ${r.substring(0,500)}...`),{logAnalysis:`Browser Automation Analysis for ${i}

${r}`,beforeScreenshotUrl:null}}catch(e){console.error("[Step 1] Error with browser automation:",e),console.log("[Step 1] Falling back to simple HTTP fetch...");try{let e=o?`${i}?x-vercel-protection-bypass=${o}`:i,t={"User-Agent":"dev3000-cloud-fix/1.0",Accept:"text/html,application/json,*/*"};o&&(t["x-vercel-protection-bypass"]=o);let s=await fetch(e,{method:"GET",headers:t}),a=await s.text(),r=a.match(/<title[^>]*>([^<]*)<\/title>/i),n=r?r[1].trim():"(no title found)";console.log(`[Step 1] HTTP fallback - Page title: "${n}"`);let l=`Dev Server URL: ${i}
`;return l+=`Page Title: ${n}
HTTP Status: ${s.status} ${s.statusText}

Note: Browser automation failed, using fallback HTTP fetch.

`,s.ok||(l+=`ERROR: HTTP ${s.status} ${s.statusText}

`),a.includes("ReferenceError")||a.includes("Error")||a.includes("error")?l+=`Response body contains error information:
${a.substring(0,5e3)}

`:s.ok?l+="No errors detected in response.\n":l+=`Response body:
${a.substring(0,2e3)}

`,{logAnalysis:l,beforeScreenshotUrl:null}}catch(t){let e=t instanceof Error?t.message:String(t);return{logAnalysis:`Failed to fetch logs from ${i}

Error: ${e}

This may indicate the dev server is not accessible or has crashed.`,beforeScreenshotUrl:null}}}}async function r(e,t,o,s){console.log("[Step 2] Invoking AI agent to analyze logs..."),console.log(`[Step 2] Sandbox available: ${!!o}`),console.log(`[Step 2] MCP URL: ${s||"not provided"}`);let a=createGateway({apiKey:process.env.AI_GATEWAY_API_KEY,baseURL:"https://ai-gateway.vercel.sh/v1/ai"})("anthropic/claude-sonnet-4-20250514"),r=o&&s?createD3kSandboxTools(o,s):void 0,n=`You are a CLS (Cumulative Layout Shift) specialist engineer working with d3k, a development debugging tool. Your ONLY focus is fixing layout shift issues.

${r?`## TOOLS AVAILABLE
You have access to tools to explore and modify the codebase:
- **readFile**: Read source files to understand the code
- **globSearch**: Find files by pattern (e.g., '*.tsx', '**/Header*')
- **grepSearch**: Search for code patterns
- **listDirectory**: Explore project structure
- **findComponentSource**: d3k-specific tool to map DOM elements to React source files
- **writeFile**: Write fixes to files
- **getGitDiff**: Review changes you've made

## WORKFLOW
1. First, understand the CLS issue from the diagnostic data
2. Use findComponentSource or grepSearch to locate the source files
3. Read the relevant files to understand the code
4. Write fixes using writeFile
5. Use getGitDiff to verify your changes
6. Provide a summary of what you fixed`:`## LIMITED MODE
No sandbox access - you can only analyze the diagnostic data and propose fixes.
You cannot read or modify the actual source code.`}

## CLS KNOWLEDGE

CLS (Cumulative Layout Shift) measures visual stability. A good CLS score is 0.1 or less.

### What causes CLS:
1. **Images without dimensions** - <img> tags missing width/height cause layout shifts when images load
2. **Dynamic content insertion** - Content that appears after initial render
3. **Web fonts causing FOIT/FOUT** - Text that shifts when custom fonts load
4. **Async loaded components** - React components rendering after data fetches
5. **Animations that trigger layout** - CSS animations affecting dimensions

### How to fix CLS:
1. **Add width/height to images**: Always specify explicit dimensions or use aspect-ratio
2. **Reserve space**: Use min-height, skeleton loaders, or CSS aspect-ratio
3. **Use font-display**: Prevent font-related shifts with 'optional' or 'swap'
4. **Suspense with sized fallbacks**: Wrap async components with properly sized placeholders
5. **Use transform animations**: Prefer transform/opacity over dimension changes

## OUTPUT FORMAT

After investigating and fixing (if tools available), provide:

## Summary
[Brief description of what was found and fixed]

## CLS Score
[The measured score from diagnostics]

## Root Cause
[What element(s) caused the shift and why]

## Fix Applied
[What changes were made, or proposed changes if no sandbox access]

## Git Diff
\`\`\`diff
[Actual diff from getGitDiff, or proposed diff if no sandbox]
\`\`\`

## RULES
1. ONLY fix CLS/layout shift issues
2. If CLS score is < 0.05, report "✅ NO CLS ISSUES - Score: [score]"
3. Always read files before modifying them
4. Make minimal, targeted fixes`,l=`The dev server is running at: ${t}

Here's the diagnostic data captured from the running application:
${e}

Please investigate and fix any CLS issues.`;if(r){console.log("[Step 2] Running in agentic mode with d3k sandbox tools...");let{text:e,steps:t}=await generateText({model:a,system:n,prompt:l,tools:r,stopWhen:stepCountIs(20)});console.log(`[Step 2] Agent completed in ${t.length} step(s)`),console.log(`[Step 2] AI agent response (first 500 chars): ${e.substring(0,500)}...`);let o=t.flatMap(e=>e.toolCalls||[]);if(o.length>0){let e=o.reduce((e,t)=>(e[t.toolName]=(e[t.toolName]||0)+1,e),{});console.log(`[Step 2] Tool usage: ${JSON.stringify(e)}`)}return e}{console.log("[Step 2] Running in limited mode (no sandbox access)...");let{text:e}=await generateText({model:a,system:n,prompt:l});return console.log(`[Step 2] AI agent response (first 500 chars): ${e.substring(0,500)}...`),e}}async function n(e,t,s,a,r,n,l,i,c,d){let p,g,u,h=i||`report-${Date.now()}`;if(console.log(`[Step 3] Updating report ${h} with agent analysis...`),l?.metadata){let e=l.metadata;p=e.totalCLS,("good"===e.clsGrade||"needs-improvement"===e.clsGrade||"poor"===e.clsGrade)&&(g=e.clsGrade),e.layoutShifts&&(u=e.layoutShifts.map(e=>({score:e.score,timestamp:e.timestamp,elements:e.sources?.map(e=>e.node||"unknown").filter(Boolean)||[]})))}let m={id:h,projectName:t,timestamp:new Date().toISOString(),sandboxDevUrl:a,sandboxMcpUrl:c||void 0,clsScore:p,clsGrade:g,layoutShifts:u,beforeScreenshotUrl:r||void 0,clsScreenshots:l?.clsScreenshots?.map(e=>({timestamp:e.timestamp,blobUrl:e.blobUrl,label:e.label})),agentAnalysis:e,agentAnalysisModel:d||void 0,d3kLogs:l?.fullLogs||void 0};console.log(`[Step 3] Agent analysis length: ${e.length} chars`),console.log(`[Step 3] Agent model: ${m.agentAnalysisModel??"not specified"}`);let f=await o(m);return console.log(`[Step 3] Report updated: ${f}`),{success:!0,projectName:t,fixProposal:e,blobUrl:f,beforeScreenshotUrl:r||null,message:"Fix analysis completed and report updated"}}async function l(e,t,o,s,a,r){console.log(`[Step 4] Creating GitHub PR for ${o}/${s}...`);let n=process.env.GITHUB_TOKEN;if(!n)return console.error("[Step 4] GITHUB_TOKEN not found in environment"),{success:!1,error:"GitHub token not configured"};try{let l=e.match(/```diff\n([\s\S]*?)\n```/);if(!l)return console.error("[Step 4] No git patch found in fix proposal"),{success:!1,error:"No git patch found in fix proposal"};let i=l[1];console.log(`[Step 4] Extracted patch (${i.length} chars)`);let c=parsePatchToFileChanges(i);if(0===c.length)return console.error("[Step 4] Failed to parse any file changes from patch"),{success:!1,error:"Failed to parse file changes from patch"};console.log(`[Step 4] Parsed ${c.length} file change(s)`);let d=`dev3000-fix-${r}-${Date.now()}`;console.log(`[Step 4] Branch name: ${d}`);let p=await fetch(`https://api.github.com/repos/${o}/${s}/git/ref/heads/${a}`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/vnd.github.v3+json"}});if(!p.ok){let e=await p.text();return console.error(`[Step 4] Failed to get base branch: ${e}`),{success:!1,error:`Failed to get base branch: ${p.status}`}}let g=(await p.json()).object.sha;console.log(`[Step 4] Base SHA: ${g}`);let u=await fetch(`https://api.github.com/repos/${o}/${s}/git/refs`,{method:"POST",headers:{Authorization:`Bearer ${n}`,Accept:"application/vnd.github.v3+json","Content-Type":"application/json"},body:JSON.stringify({ref:`refs/heads/${d}`,sha:g})});if(!u.ok){let e=await u.text();return console.error(`[Step 4] Failed to create branch: ${e}`),{success:!1,error:`Failed to create branch: ${u.status}`}}for(let e of(console.log(`[Step 4] Created branch: ${d}`),c)){console.log(`[Step 4] Processing file: ${e.path}`);let t=await fetch(`https://api.github.com/repos/${o}/${s}/contents/${e.path}?ref=${d}`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/vnd.github.v3+json"}}),a="",l="";if(t.ok){let e=await t.json();l=e.sha,a=Buffer.from(e.content,"base64").toString("utf-8")}else console.log("[Step 4] File doesn't exist, will create new file");let i=applyPatchChanges(a,e.changes),c=await fetch(`https://api.github.com/repos/${o}/${s}/contents/${e.path}`,{method:"PUT",headers:{Authorization:`Bearer ${n}`,Accept:"application/vnd.github.v3+json","Content-Type":"application/json"},body:JSON.stringify({message:`Fix: Apply dev3000 fix for ${r}`,content:Buffer.from(i).toString("base64"),branch:d,...l&&{sha:l}})});if(!c.ok){let t=await c.text();return console.error(`[Step 4] Failed to update file ${e.path}: ${t}`),{success:!1,error:`Failed to update file ${e.path}: ${c.status}`}}console.log(`[Step 4] Updated file: ${e.path}`)}let h=`## Automated Fix Proposal

This PR was automatically generated by [dev3000](https://github.com/vercel-labs/dev3000) after analyzing your application.

### Fix Details
View the full analysis: [${t}](${t})

${e}

---

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude (dev3000) <noreply@anthropic.com>`,m=await fetch(`https://api.github.com/repos/${o}/${s}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${n}`,Accept:"application/vnd.github.v3+json","Content-Type":"application/json"},body:JSON.stringify({title:`Fix: ${r} - Automated fix from dev3000`,head:d,base:a,body:h})});if(!m.ok){let e=await m.text();return console.error(`[Step 4] Failed to create PR: ${e}`),{success:!1,error:`Failed to create PR: ${m.status}`}}let f=await m.json();return console.log(`[Step 4] Created PR: ${f.html_url}`),{success:!0,prUrl:f.html_url,prNumber:f.number,branch:d}}catch(e){return console.error("[Step 4] Error creating PR:",e),{success:!1,error:e instanceof Error?e.message:String(e)}}}async function i(e){console.log("[Cleanup] Stopping sandbox...");try{await e(),console.log("[Cleanup] Sandbox stopped successfully")}catch(e){console.error("[Cleanup] Error stopping sandbox:",e)}}e.s(["analyzeLogsWithAgent",()=>r,"cleanupSandbox",()=>i,"createD3kSandbox",()=>s,"createGitHubPR",()=>l,"fetchRealLogs",()=>a,"saveReportToBlob",()=>o,"uploadToBlob",()=>n])}];

//# sourceMappingURL=mcp-server_app_api_cloud_fix-workflow_steps_ts_b65f3271._.js.map