module.exports=[1177,e=>{"use strict";async function t(e,t,o,s,r){console.log(`[Step 0] Creating d3k sandbox for ${o}...`),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: ${!!s}`),r&&!process.env.VERCEL_OIDC_TOKEN&&(process.env.VERCEL_OIDC_TOKEN=r,console.log("[Step 0] Set VERCEL_OIDC_TOKEN from workflow context"));let a=await createD3kSandboxUtil({repoUrl:e,branch:t,projectDir:"",packageManager:"pnpm",debug:!0});console.log("[Step 0] Sandbox created successfully"),console.log(`[Step 0] Dev URL: ${a.devUrl}`),console.log(`[Step 0] MCP URL: ${a.mcpUrl}`),console.log("[Step 0] Getting Chromium path for screenshots...");let n="/tmp/chromium";try{let e=await runSandboxCommand(a.sandbox,"node",["-e","require('@sparticuz/chromium').executablePath().then(p => console.log(p))"]);0===e.exitCode&&e.stdout.trim()&&(n=e.stdout.trim(),console.log(`[Step 0] Chromium path: ${n}`))}catch{console.log(`[Step 0] Could not get chromium path, using default: ${n}`)}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: ${n}"
      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: ${n} --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 "${n}" \\
        --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(a.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 l=null;try{let e=await captureScreenshotInSandbox(a.sandbox,"http://localhost:3000",n,"before");e&&(l=await uploadScreenshot(e,"before",o))}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 i=null,c=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 r=await runSandboxCommand(a.sandbox,"bash",["-c",e]);t=r.stdout,o=r.stderr,s=r.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}`),c=`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{i=JSON.parse(t.text),console.log("[Step 0] Successfully parsed CLS data as JSON")}catch{i={rawOutput:t.text},console.log("[Step 0] CLS data stored as rawOutput (not JSON)")}break}}i?console.log("[Step 0] CLS data captured:",JSON.stringify(i).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){c=`Failed to parse MCP response: ${e instanceof Error?e.message:String(e)}`,console.log(`[Step 0] ${c}`),console.log(`[Step 0] Raw stdout: ${t.substring(0,1e3)}`),i={rawMcpOutput:t.substring(0,1e4),parseError:c},console.log("[Step 0] Using raw stdout as fallback CLS data")}else 0!==s&&!c&&(c=`MCP command failed with exit code ${s}`,console.log(`[Step 0] ${c}`),o&&console.log(`[Step 0] stderr: ${o}`))}catch(e){c=`MCP execution error: ${e instanceof Error?e.message:String(e)}`,console.log(`[Step 0] ${c}`)}i||(console.log("[Step 0] WARNING: No CLS data captured, creating placeholder to prevent Step 1 timeout"),i={warning:"MCP fix_my_app did not return data",mcpError:c||"Unknown error",sandboxDevUrl:a.devUrl,sandboxMcpUrl:a.mcpUrl}),console.log(`[Step 0] Final clsData truthy check: ${!!i}`),console.log("[Step 0] === Dumping sandbox logs before returning ===");try{let e=await runSandboxCommand(a.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 p=null;try{let e=await runSandboxCommand(a.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()?(p=e.stdout.trim(),console.log(`[Step 0] Git diff captured (${p.length} chars)`),console.log(`[Step 0] Git diff preview:
${p.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)}`)}return{mcpUrl:a.mcpUrl,devUrl:a.devUrl,bypassToken:a.bypassToken,clsData:i,mcpError:c,beforeScreenshotUrl:l,chromiumPath:n,gitDiff:p}}async function o(e,t,o,s,r,a){if(console.log(`[Step 1] Received clsData: ${s?"truthy":"falsy"}, type: ${typeof s}`),s&&console.log(`[Step 1] clsData preview: ${JSON.stringify(s).substring(0,200)}`),s)return console.log("[Step 1] ✅ Using CLS data captured in Step 0 (skipping MCP calls)"),a&&console.log(`[Step 1] Before screenshot from Step 0: ${a}`),{logAnalysis:JSON.stringify(s,null,2),beforeScreenshotUrl:a||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 n=!!o,l=o||e,i=n?e:null;console.log(`[Step 1] Fetching logs from: ${l}`),console.log(`[Step 1] Using sandbox: ${n?"yes":"no"}`),i&&console.log(`[Step 1] MCP URL: ${i}`),console.log(`[Step 1] Bypass token: ${t?"provided":"not provided"}`);try{let e=t?`${l}?x-vercel-protection-bypass=${t}`:l;if(console.log(`[Step 1] Final URL: ${e.replace(t||"","***")}`),n&&i){console.log("[Step 1] Using d3k MCP server to capture CLS metrics and errors..."),console.log("[Step 1] Validating d3k MCP server access...");let t=new AbortController,o=setTimeout(()=>t.abort(),3e4);try{let e=await fetch(`${i}/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:t.signal});if(clearTimeout(o),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")),r=o.some(e=>e.includes("nextjs")),a=o.includes("fix_my_app");console.log(`[Step 1] Chrome DevTools MCP: ${s?"✅":"❌"}`),console.log(`[Step 1] Next.js DevTools MCP: ${r?"✅":"❌"}`),console.log(`[Step 1] fix_my_app tool: ${a?"✅":"❌"}`)}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(s){clearTimeout(o);let e=s instanceof Error?s.message:String(s),t=s instanceof Error&&"AbortError"===s.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 s=new AbortController,r=setTimeout(()=>s.abort(),3e4);try{let t=await fetch(`${i}/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:s.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 a=null;console.log("[Step 1] Capturing 'before' screenshot...");let n=new AbortController,c=setTimeout(()=>n.abort(),3e4);try{let e=await fetch(`${i}/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:n.signal});if(clearTimeout(c),e.ok){let t=await e.text();for(let e of t.split("\n"))if(e.startsWith("data: "))try{let t=JSON.parse(e.substring(6));if(t.result?.content){for(let e of t.result.content)if("image"===e.type&&e.data){let t=Buffer.from(e.data,"base64"),o=new Date().toISOString().replace(/[:.]/g,"-"),s=`screenshot-before-${o}.png`;a=(await put(s,t,{access:"public",contentType:"image/png"})).url,console.log(`[Step 1] ✅ Before screenshot uploaded: ${a}`)}}}catch{}a||(console.log("[Step 1] Screenshot response received but no image data found"),console.log(`[Step 1] Response preview: ${t.substring(0,500)}`))}else console.log(`[Step 1] Screenshot request failed: ${e.status}`)}catch(t){clearTimeout(c);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,d=setTimeout(()=>p.abort(),15e3);try{let e=await fetch(`${i}/api/logs`,{signal:p.signal});if(clearTimeout(d),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(d);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 g=new AbortController,u=setTimeout(()=>g.abort(),18e4);try{let e=await fetch(`${i}/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:g.signal});if(clearTimeout(u),!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="",r=0,n=0;for(let e of o)if(e.startsWith("data: ")){r++;try{let t=JSON.parse(e.substring(6));if(console.log(`[Step 1] Parsed JSON line ${r}:`,JSON.stringify(t).substring(0,200)),t.result?.content)for(let e of t.result.content)"text"===e.type&&(n++,s+=e.text,console.log(`[Step 1] Added text content block ${n}, 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 ${r}: ${t instanceof Error?t.message:String(t)}`),console.log(`[Step 1] Problem line: ${e.substring(0,200)}`)}}return console.log(`[Step 1] Processed ${r} data lines, ${n} 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 ${l}

${s}`,beforeScreenshotUrl:a}}catch(e){clearTimeout(u),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 o=createGateway({apiKey:process.env.AI_GATEWAY_API_KEY,baseURL:"https://ai-gateway.vercel.sh/v1/ai"})("anthropic/claude-sonnet-4-20250514"),s=`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:o,prompt:s,toolChoice:"auto",maxTokens:4e3});return console.log(`[Step 1] Browser automation response (first 500 chars): ${r.substring(0,500)}...`),{logAnalysis:`Browser Automation Analysis for ${l}

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

Note: Browser automation failed, using fallback HTTP fetch.

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

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

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

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

Error: ${e}

This may indicate the dev server is not accessible or has crashed.`,beforeScreenshotUrl:null}}}}async function s(e,t){console.log("[Step 2] Invoking AI agent to analyze logs...");let o=createGateway({apiKey:process.env.AI_GATEWAY_API_KEY,baseURL:"https://ai-gateway.vercel.sh/v1/ai"})("anthropic/claude-sonnet-4-20250514"),s=`You are a skilled software engineer debugging an application.

The dev server is running at: ${t}

Here's the log analysis from the MCP fix_my_app tool:
${e}

Your task:
1. Identify the most critical error or issue from the logs
2. Determine the root cause
3. Propose a specific code fix with file paths and changes
4. Create a git-style unified diff that can be applied with 'git apply'
5. Explain why this fix will resolve the issue

Format your response EXACTLY as follows:

## Issue
[Brief description of the issue]

## Root Cause
[Explanation of what's causing the issue]

## Proposed Fix
[High-level explanation of the fix]

## Git Patch
\`\`\`diff
[Full unified diff format that can be applied with 'git apply' or 'patch']
[Include file paths, line numbers, and exact changes]
[Example format:]
[diff --git a/path/to/file.ts b/path/to/file.ts]
[index abc123..def456 100644]
[--- a/path/to/file.ts]
[+++ b/path/to/file.ts]
[@@ -10,7 +10,7 @@ function example() {]
[ unchanged line]
[-  old line to remove]
[+  new line to add]
[ unchanged line]
\`\`\`

## Reasoning
[Why this fix will work]

IMPORTANT:
- The Git Patch section must be a valid unified diff that can be applied directly with 'git apply'.
- If no errors are found, respond with "✅ **SYSTEM HEALTHY** - No errors found" and do NOT include a Git Patch section.
- Only include a Git Patch if there are actual issues that need fixing.`,{text:r}=await generateText({model:o,prompt:s});return console.log(`[Step 2] AI agent response (first 500 chars): ${r.substring(0,500)}...`),r}async function r(e,t,o,s,r,a){console.log("[Step 3] Uploading fix proposal to blob storage..."),r&&console.log(`[Step 3] Including before screenshot: ${r}`),a&&console.log(`[Step 3] Including git diff (${a.length} chars)`);let n=r?`## Before Screenshot

This screenshot was captured when the sandbox dev server first loaded, proving the page rendered successfully.

![Before Screenshot](${r})

---

`:"",l=a?`## Actual Git Diff from Sandbox

The following diff shows the actual changes made by d3k in the sandbox environment:

\`\`\`diff
${a}
\`\`\`

---

`:"",i=new Date().toISOString(),c=`# Fix Proposal for ${t}

**Generated**: ${i}

**Powered by**: [dev3000](https://github.com/vercel-labs/dev3000) with Claude Code

**Dev Server**: ${s}

---

${n}${l}## Original Log Analysis

\`\`\`
${o}
\`\`\`

---

${e}

---

## Attribution

This fix proposal was automatically generated by [dev3000](https://github.com/vercel-labs/dev3000),
an AI-powered debugging tool that analyzes your application logs and suggests fixes.

**Co-Authored-By**: Claude (dev3000) <noreply@anthropic.com>

### About dev3000

dev3000 monitors your development server, captures errors in real-time, and uses AI to:
- Analyze error logs and stack traces
- Identify root causes
- Generate actionable fix proposals with git patches
- Suggest specific code changes

Learn more at https://github.com/vercel-labs/dev3000
`,p=i.replace(/[:.]/g,"-"),d=`fix-${t}-${p}.md`,g=await put(d,c,{access:"public",contentType:"text/markdown"});return console.log(`[Step 3] Fix proposal uploaded to: ${g.url}`),{success:!0,projectName:t,fixProposal:e,blobUrl:g.url,beforeScreenshotUrl:r||null,message:"Fix analysis completed and uploaded to blob storage"}}async function a(e,t,o,s,r,a){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 p=`dev3000-fix-${a}-${Date.now()}`;console.log(`[Step 4] Branch name: ${p}`);let d=await fetch(`https://api.github.com/repos/${o}/${s}/git/ref/heads/${r}`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/vnd.github.v3+json"}});if(!d.ok){let e=await d.text();return console.error(`[Step 4] Failed to get base branch: ${e}`),{success:!1,error:`Failed to get base branch: ${d.status}`}}let g=(await d.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/${p}`,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: ${p}`),c)){console.log(`[Step 4] Processing file: ${e.path}`);let t=await fetch(`https://api.github.com/repos/${o}/${s}/contents/${e.path}?ref=${p}`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/vnd.github.v3+json"}}),r="",l="";if(t.ok){let e=await t.json();l=e.sha,r=Buffer.from(e.content,"base64").toString("utf-8")}else console.log("[Step 4] File doesn't exist, will create new file");let i=applyPatchChanges(r,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 ${a}`,content:Buffer.from(i).toString("base64"),branch:p,...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>`,f=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: ${a} - Automated fix from dev3000`,head:p,base:r,body:h})});if(!f.ok){let e=await f.text();return console.error(`[Step 4] Failed to create PR: ${e}`),{success:!1,error:`Failed to create PR: ${f.status}`}}let m=await f.json();return console.log(`[Step 4] Created PR: ${m.html_url}`),{success:!0,prUrl:m.html_url,prNumber:m.number,branch:p}}catch(e){return console.error("[Step 4] Error creating PR:",e),{success:!1,error:e instanceof Error?e.message:String(e)}}}async function n(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",()=>s,"cleanupSandbox",()=>n,"createD3kSandbox",()=>t,"createGitHubPR",()=>a,"fetchRealLogs",()=>o,"uploadToBlob",()=>r])}];

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