dev3000 0.0.114 → 0.0.116

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/dist/cdp-monitor.d.ts.map +1 -1
  2. package/dist/cdp-monitor.js +20 -28
  3. package/dist/cdp-monitor.js.map +1 -1
  4. package/dist/cli.js +74 -22
  5. package/dist/cli.js.map +1 -1
  6. package/dist/dev-environment.d.ts.map +1 -1
  7. package/dist/dev-environment.js +43 -11
  8. package/dist/dev-environment.js.map +1 -1
  9. package/dist/src/tui-interface-impl.tsx +175 -127
  10. package/dist/tui-interface-impl.d.ts.map +1 -1
  11. package/dist/tui-interface-impl.js +113 -74
  12. package/dist/tui-interface-impl.js.map +1 -1
  13. package/mcp-server/.next/BUILD_ID +1 -1
  14. package/mcp-server/.next/build-manifest.json +2 -2
  15. package/mcp-server/.next/fallback-build-manifest.json +2 -2
  16. package/mcp-server/.next/prerender-manifest.json +3 -3
  17. package/mcp-server/.next/server/app/_global-error.html +2 -2
  18. package/mcp-server/.next/server/app/_global-error.rsc +1 -1
  19. package/mcp-server/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  20. package/mcp-server/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  21. package/mcp-server/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  22. package/mcp-server/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  23. package/mcp-server/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  24. package/mcp-server/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  25. package/mcp-server/.next/server/app/_not-found.html +1 -1
  26. package/mcp-server/.next/server/app/_not-found.rsc +2 -2
  27. package/mcp-server/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
  28. package/mcp-server/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  29. package/mcp-server/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
  30. package/mcp-server/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  31. package/mcp-server/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  32. package/mcp-server/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  33. package/mcp-server/.next/server/app/api/cloud/start-fix/route.js +2 -2
  34. package/mcp-server/.next/server/app/api/cloud/start-fix/route.js.nft.json +1 -1
  35. package/mcp-server/.next/server/app/auth/error/page_client-reference-manifest.js +1 -1
  36. package/mcp-server/.next/server/app/auth/error.html +1 -1
  37. package/mcp-server/.next/server/app/auth/error.rsc +2 -2
  38. package/mcp-server/.next/server/app/auth/error.segments/_full.segment.rsc +2 -2
  39. package/mcp-server/.next/server/app/auth/error.segments/_head.segment.rsc +1 -1
  40. package/mcp-server/.next/server/app/auth/error.segments/_index.segment.rsc +2 -2
  41. package/mcp-server/.next/server/app/auth/error.segments/_tree.segment.rsc +2 -2
  42. package/mcp-server/.next/server/app/auth/error.segments/auth/error/__PAGE__.segment.rsc +1 -1
  43. package/mcp-server/.next/server/app/auth/error.segments/auth/error.segment.rsc +1 -1
  44. package/mcp-server/.next/server/app/auth/error.segments/auth.segment.rsc +1 -1
  45. package/mcp-server/.next/server/app/index.html +1 -1
  46. package/mcp-server/.next/server/app/index.rsc +3 -3
  47. package/mcp-server/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
  48. package/mcp-server/.next/server/app/index.segments/_full.segment.rsc +3 -3
  49. package/mcp-server/.next/server/app/index.segments/_head.segment.rsc +1 -1
  50. package/mcp-server/.next/server/app/index.segments/_index.segment.rsc +2 -2
  51. package/mcp-server/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  52. package/mcp-server/.next/server/app/logs/page.js.nft.json +1 -1
  53. package/mcp-server/.next/server/app/logs/page_client-reference-manifest.js +1 -1
  54. package/mcp-server/.next/server/app/mcp/route.js +2 -2
  55. package/mcp-server/.next/server/app/page.js.nft.json +1 -1
  56. package/mcp-server/.next/server/app/page_client-reference-manifest.js +1 -1
  57. package/mcp-server/.next/server/app/signin/page_client-reference-manifest.js +1 -1
  58. package/mcp-server/.next/server/app/video/[session]/page_client-reference-manifest.js +1 -1
  59. package/mcp-server/.next/server/app/workflows/[id]/report/page_client-reference-manifest.js +1 -1
  60. package/mcp-server/.next/server/app/workflows/new/page.js.nft.json +1 -1
  61. package/mcp-server/.next/server/app/workflows/new/page_client-reference-manifest.js +1 -1
  62. package/mcp-server/.next/server/app/workflows/page.js.nft.json +1 -1
  63. package/mcp-server/.next/server/app/workflows/page_client-reference-manifest.js +1 -1
  64. package/mcp-server/.next/server/chunks/[root-of-the-server]__157de66b._.js +284 -37
  65. package/mcp-server/.next/server/chunks/[root-of-the-server]__157de66b._.js.map +1 -1
  66. package/mcp-server/.next/server/chunks/[root-of-the-server]__730a8fd0._.js +1 -1
  67. package/mcp-server/.next/server/chunks/[root-of-the-server]__730a8fd0._.js.map +1 -1
  68. package/mcp-server/.next/server/chunks/[root-of-the-server]__748f411f._.js +1 -1
  69. package/mcp-server/.next/server/chunks/[root-of-the-server]__748f411f._.js.map +1 -1
  70. package/mcp-server/.next/server/chunks/[root-of-the-server]__8a84f9f4._.js +20 -20
  71. package/mcp-server/.next/server/chunks/[root-of-the-server]__8a84f9f4._.js.map +1 -1
  72. package/mcp-server/.next/server/chunks/[root-of-the-server]__c1681338._.js +3 -0
  73. package/mcp-server/.next/server/chunks/[root-of-the-server]__c1681338._.js.map +1 -0
  74. package/mcp-server/.next/server/chunks/[root-of-the-server]__ec6a1335._.js.map +1 -1
  75. package/mcp-server/.next/server/chunks/bee4f_next_dist_esm_build_templates_app-route_1ece9366.js +5 -5
  76. package/mcp-server/.next/server/chunks/bee4f_next_dist_esm_build_templates_app-route_1ece9366.js.map +1 -1
  77. package/mcp-server/.next/server/chunks/mcp-server_app_api_cloud_fix-workflow_steps_ts_b65f3271._.js +121 -27
  78. package/mcp-server/.next/server/chunks/mcp-server_app_api_cloud_fix-workflow_steps_ts_b65f3271._.js.map +1 -1
  79. package/mcp-server/.next/server/chunks/node_modules__pnpm_85ddbe9c._.js +1 -1
  80. package/mcp-server/.next/server/chunks/node_modules__pnpm_85ddbe9c._.js.map +1 -1
  81. package/mcp-server/.next/server/chunks/ssr/[root-of-the-server]__2e44f0db._.js +3 -0
  82. package/mcp-server/.next/server/chunks/ssr/[root-of-the-server]__2e44f0db._.js.map +1 -0
  83. package/mcp-server/.next/server/chunks/ssr/[root-of-the-server]__3585c949._.js +3 -0
  84. package/mcp-server/.next/server/chunks/ssr/[root-of-the-server]__3585c949._.js.map +1 -0
  85. package/mcp-server/.next/server/chunks/ssr/[root-of-the-server]__477c3bbb._.js +3 -0
  86. package/mcp-server/.next/server/chunks/ssr/[root-of-the-server]__477c3bbb._.js.map +1 -0
  87. package/mcp-server/.next/server/chunks/ssr/{[root-of-the-server]__570677dc._.js → [root-of-the-server]__880839a0._.js} +2 -2
  88. package/mcp-server/.next/server/chunks/ssr/[root-of-the-server]__880839a0._.js.map +1 -0
  89. package/mcp-server/.next/server/chunks/ssr/_41b8f993._.js +3 -0
  90. package/mcp-server/.next/server/chunks/ssr/_41b8f993._.js.map +1 -0
  91. package/mcp-server/.next/server/chunks/ssr/_9ba0ef29._.js +3 -0
  92. package/mcp-server/.next/server/chunks/ssr/_9ba0ef29._.js.map +1 -0
  93. package/mcp-server/.next/server/chunks/ssr/_cd4dc25e._.js.map +1 -1
  94. package/mcp-server/.next/server/chunks/ssr/mcp-server_app_workflows_new_new-workflow-client_tsx_1312c046._.js +2 -2
  95. package/mcp-server/.next/server/chunks/ssr/mcp-server_app_workflows_new_new-workflow-client_tsx_1312c046._.js.map +1 -1
  96. package/mcp-server/.next/server/chunks/ssr/mcp-server_app_workflows_workflows-client_tsx_268cfd4a._.js +7 -0
  97. package/mcp-server/.next/server/chunks/ssr/mcp-server_app_workflows_workflows-client_tsx_268cfd4a._.js.map +1 -0
  98. package/mcp-server/.next/server/chunks/ssr/node_modules__pnpm_961f21c4._.js +3 -0
  99. package/mcp-server/.next/server/chunks/ssr/node_modules__pnpm_961f21c4._.js.map +1 -0
  100. package/mcp-server/.next/server/chunks/ssr/node_modules__pnpm_a82244bf._.js +3 -0
  101. package/mcp-server/.next/server/chunks/ssr/node_modules__pnpm_a82244bf._.js.map +1 -0
  102. package/mcp-server/.next/server/chunks/ssr/{node_modules__pnpm_07527699._.js → node_modules__pnpm_eb98e511._.js} +2 -2
  103. package/mcp-server/.next/server/chunks/ssr/node_modules__pnpm_eb98e511._.js.map +1 -0
  104. package/mcp-server/.next/server/server-reference-manifest.js +1 -1
  105. package/mcp-server/.next/server/server-reference-manifest.json +1 -1
  106. package/mcp-server/.next/static/chunks/000849a6a897f531.css +1 -0
  107. package/mcp-server/.next/static/chunks/048cee2510ddb1a0.js +1 -0
  108. package/mcp-server/.next/static/chunks/0622bd0e093adee7.js +3 -0
  109. package/mcp-server/.next/static/chunks/{46f60efee5f19794.js → 16359f64918a93f3.js} +1 -1
  110. package/mcp-server/.next/static/chunks/1851a3e70d7efc10.js +1 -0
  111. package/mcp-server/.next/static/chunks/{cc6addc4bb10fa11.js → 2ad16eeb719786f1.js} +1 -1
  112. package/mcp-server/.next/static/chunks/57feca7a4e06545e.js +7 -0
  113. package/mcp-server/.next/static/chunks/93db5737a327ab0c.js +6 -0
  114. package/mcp-server/.next/static/chunks/9fd3c715ecfb4d05.js +1 -0
  115. package/mcp-server/.next/static/chunks/b4b1ec6435790587.js +1 -0
  116. package/mcp-server/.next/static/chunks/cfe150cb2048b7e8.js +1 -0
  117. package/mcp-server/app/api/cloud/fix-workflow/steps.ts +359 -28
  118. package/mcp-server/app/api/cloud/fix-workflow/workflow.ts +16 -8
  119. package/mcp-server/app/api/cloud/start-fix/route.ts +2 -2
  120. package/mcp-server/app/api/tools/route.ts +11 -12
  121. package/mcp-server/app/api/workflows/route.ts +45 -1
  122. package/mcp-server/app/mcp/tools.ts +58 -98
  123. package/mcp-server/app/workflows/workflows-client.tsx +259 -100
  124. package/package.json +1 -1
  125. package/src/tui-interface-impl.tsx +175 -127
  126. package/mcp-server/.next/server/chunks/[root-of-the-server]__75d68567._.js +0 -3
  127. package/mcp-server/.next/server/chunks/[root-of-the-server]__75d68567._.js.map +0 -1
  128. package/mcp-server/.next/server/chunks/ssr/[root-of-the-server]__0ff05d72._.js +0 -3
  129. package/mcp-server/.next/server/chunks/ssr/[root-of-the-server]__0ff05d72._.js.map +0 -1
  130. package/mcp-server/.next/server/chunks/ssr/[root-of-the-server]__27cc5956._.js +0 -3
  131. package/mcp-server/.next/server/chunks/ssr/[root-of-the-server]__27cc5956._.js.map +0 -1
  132. package/mcp-server/.next/server/chunks/ssr/[root-of-the-server]__570677dc._.js.map +0 -1
  133. package/mcp-server/.next/server/chunks/ssr/[root-of-the-server]__ef510343._.js +0 -3
  134. package/mcp-server/.next/server/chunks/ssr/[root-of-the-server]__ef510343._.js.map +0 -1
  135. package/mcp-server/.next/server/chunks/ssr/node_modules__pnpm_07527699._.js.map +0 -1
  136. package/mcp-server/.next/server/chunks/ssr/node_modules__pnpm_7cc36047._.js +0 -3
  137. package/mcp-server/.next/server/chunks/ssr/node_modules__pnpm_7cc36047._.js.map +0 -1
  138. package/mcp-server/.next/static/chunks/07848f6bd2a7e5f6.js +0 -3
  139. package/mcp-server/.next/static/chunks/637a66565f27572f.js +0 -6
  140. package/mcp-server/.next/static/chunks/aed4fb5252a4bc95.js +0 -3
  141. package/mcp-server/.next/static/chunks/e8d521464b0c96ca.css +0 -1
  142. package/mcp-server/.next/static/chunks/ff53279afa939907.js +0 -1
  143. package/mcp-server/.next/static/chunks/ffa2ecb6845be49c.js +0 -1
  144. /package/mcp-server/.next/static/{ZvLsxTWoDyQzaSsr_VeX6 → G5taiQ-Jp0B_MdvkQuoIT}/_buildManifest.js +0 -0
  145. /package/mcp-server/.next/static/{ZvLsxTWoDyQzaSsr_VeX6 → G5taiQ-Jp0B_MdvkQuoIT}/_clientMiddlewareManifest.json +0 -0
  146. /package/mcp-server/.next/static/{ZvLsxTWoDyQzaSsr_VeX6 → G5taiQ-Jp0B_MdvkQuoIT}/_ssgManifest.js +0 -0
@@ -1,9 +1,90 @@
1
- module.exports=[1177,e=>{"use strict";async function t(e,t,o,r,s){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: ${!!s}`),console.log(`[Step 0] VERCEL_TOKEN available: ${!!process.env.VERCEL_TOKEN}`),console.log(`[Step 0] User access token provided: ${!!r}`),s&&!process.env.VERCEL_OIDC_TOKEN&&(process.env.VERCEL_OIDC_TOKEN=s,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] Capturing CLS metrics from inside sandbox...");let n=null,l=null;async function i(e,t,o){let r=await e.runCommand({cmd:t,args:o}),s="",a="";for await(let e of r.logs())"stdout"===e.stream?s+=e.data:a+=e.data;return await r.wait(),{exitCode:r.exitCode,stdout:s,stderr:a}}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="",r=-1;try{let s=await i(a.sandbox,"bash",["-c",e]);t=s.stdout,o=s.stderr,r=s.exitCode,console.log(`[Step 0] MCP command exit code: ${r}`),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}`),l=`sandbox.runCommand failed: ${e}`}if(0===r&&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{n=JSON.parse(t.text),console.log("[Step 0] Successfully parsed CLS data");break}catch{n={rawOutput:t.text}}}console.log("[Step 0] CLS data captured:",JSON.stringify(n).substring(0,500))}catch(e){l=`Failed to parse MCP response: ${e instanceof Error?e.message:String(e)}`,console.log(`[Step 0] ${l}`),console.log(`[Step 0] Raw stdout: ${t.substring(0,1e3)}`)}else 0!==r&&!l&&(l=`MCP command failed with exit code ${r}`,console.log(`[Step 0] ${l}`),o&&console.log(`[Step 0] stderr: ${o}`))}catch(e){l=`MCP execution error: ${e instanceof Error?e.message:String(e)}`,console.log(`[Step 0] ${l}`)}console.log("[Step 0] === Dumping sandbox logs before returning ===");try{let e=await i(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)}`)}return console.log("[Step 0] === End sandbox log dump ==="),{mcpUrl:a.mcpUrl,devUrl:a.devUrl,bypassToken:a.bypassToken,clsData:n,mcpError:l}}async function o(e,t,o,r,s){if(r)return console.log("[Step 1] Using CLS data captured in Step 0"),{logAnalysis:JSON.stringify(r,null,2),beforeScreenshotUrl:null};s&&console.log(`[Step 1] Note: MCP error from Step 0: ${s}`);let a=!!o,n=o||e,l=a?e:null;console.log(`[Step 1] Fetching logs from: ${n}`),console.log(`[Step 1] Using sandbox: ${a?"yes":"no"}`),l&&console.log(`[Step 1] MCP URL: ${l}`),console.log(`[Step 1] Bypass token: ${t?"provided":"not provided"}`);try{let e=t?`${n}?x-vercel-protection-bypass=${t}`:n;if(console.log(`[Step 1] Final URL: ${e.replace(t||"","***")}`),a&&l){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(`${l}/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 r=o.some(e=>e.includes("chrome-devtools")),s=o.some(e=>e.includes("nextjs")),a=o.includes("fix_my_app");console.log(`[Step 1] Chrome DevTools MCP: ${r?"✅":"❌"}`),console.log(`[Step 1] Next.js DevTools MCP: ${s?"✅":"❌"}`),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(r){clearTimeout(o);let e=r instanceof Error?r.message:String(r),t=r instanceof Error&&"AbortError"===r.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 r=new AbortController,s=setTimeout(()=>r.abort(),3e4);try{let t=await fetch(`${l}/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:r.signal});clearTimeout(s),t.ok?console.log("[Step 1] Browser navigation completed"):console.log(`[Step 1] Browser navigation failed: ${t.status}`)}catch(t){clearTimeout(s);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 i=new AbortController,c=setTimeout(()=>i.abort(),3e4);try{let e=await fetch(`${l}/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:i.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,"-"),r=`screenshot-before-${o}.png`;a=(await put(r,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,g=setTimeout(()=>p.abort(),15e3);try{let e=await fetch(`${l}/api/logs`,{signal:p.signal});if(clearTimeout(g),e.ok){let t=await e.text();console.log(`[Step 1] d3k logs (last 1000 chars):
2
- ${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 d=new AbortController,u=setTimeout(()=>d.abort(),18e4);try{let e=await fetch(`${l}/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:d.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):
3
- ${t.substring(0,500)}`);let o=t.split("\n");console.log(`[Step 1] Response split into ${o.length} lines`);let r="",s=0,i=0;for(let e of o)if(e.startsWith("data: ")){s++;try{let t=JSON.parse(e.substring(6));if(console.log(`[Step 1] Parsed JSON line ${s}:`,JSON.stringify(t).substring(0,200)),t.result?.content)for(let e of t.result.content)"text"===e.type&&(i++,r+=e.text,console.log(`[Step 1] Added text content block ${i}, 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 ${s}: ${t instanceof Error?t.message:String(t)}`),console.log(`[Step 1] Problem line: ${e.substring(0,200)}`)}}return console.log(`[Step 1] Processed ${s} data lines, ${i} content blocks`),console.log(`[Step 1] Got ${r.length} chars from fix_my_app (performance analysis)`),0===r.length&&console.log(`[Step 1] WARNING: fix_my_app returned NO data. Full response:
4
- ${t}`),{logAnalysis:`d3k Performance Analysis for ${n}
5
-
6
- ${r}`,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"),r=`You are a web application debugger with access to browser automation tools via Playwright MCP.
1
+ module.exports=[1177,e=>{"use strict";async function o(e,o,t,s,r){console.log(`[Step 0] Creating d3k sandbox for ${t}...`),console.log(`[Step 0] Repository: ${e}`),console.log(`[Step 0] Branch: ${o}`),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:o,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=`
2
+ exec 2>&1
3
+ echo "=== Chromium CDP Test (d3k exact command) ==="
4
+ echo "Chromium path: ${n}"
5
+ echo ""
6
+
7
+ # Create user-data-dir like d3k does
8
+ USER_DATA_DIR="/tmp/d3k-test-profile"
9
+ mkdir -p "$USER_DATA_DIR"
10
+ echo "1. Created user-data-dir: $USER_DATA_DIR"
11
+
12
+ # Create loading page like d3k does
13
+ LOADING_DIR="/tmp/dev3000-loading"
14
+ mkdir -p "$LOADING_DIR"
15
+ cat > "$LOADING_DIR/loading.html" << 'LOADINGHTML'
16
+ <!DOCTYPE html>
17
+ <html>
18
+ <head><title>Loading...</title></head>
19
+ <body><h1>Loading dev3000...</h1></body>
20
+ </html>
21
+ LOADINGHTML
22
+ echo "2. Created loading page: $LOADING_DIR/loading.html"
23
+ echo ""
24
+
25
+ # Use EXACT d3k command (from cdp-monitor.ts)
26
+ # Note: d3k does NOT use --remote-debugging-address
27
+ echo "3. Starting Chrome with d3k's exact args..."
28
+ 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"
29
+
30
+ timeout 15 "${n}" \\
31
+ --remote-debugging-port=9222 \\
32
+ --user-data-dir="$USER_DATA_DIR" \\
33
+ --no-first-run \\
34
+ --no-default-browser-check \\
35
+ --disable-component-extensions-with-background-pages \\
36
+ --disable-background-networking \\
37
+ --disable-sync \\
38
+ --metrics-recording-only \\
39
+ --disable-default-apps \\
40
+ --disable-session-crashed-bubble \\
41
+ --disable-restore-session-state \\
42
+ --headless=new \\
43
+ --no-sandbox \\
44
+ --disable-setuid-sandbox \\
45
+ --disable-gpu \\
46
+ --disable-dev-shm-usage \\
47
+ "file://$LOADING_DIR/loading.html" &
48
+ PID=$!
49
+ echo " Chrome PID: $PID"
50
+ sleep 3
51
+ echo ""
52
+
53
+ echo "4. Checking if Chrome is still running..."
54
+ if ps -p $PID > /dev/null 2>&1; then
55
+ echo " Chrome is RUNNING after 3s"
56
+ echo ""
57
+ echo "5. Trying CDP (note: d3k doesn't use --remote-debugging-address)..."
58
+ echo " Trying 127.0.0.1..."
59
+ curl -s --max-time 5 http://127.0.0.1:9222/json/version 2>&1 || echo " 127.0.0.1 failed"
60
+ echo ""
61
+ echo " Trying localhost..."
62
+ curl -s --max-time 5 http://localhost:9222/json/version 2>&1 || echo " localhost failed"
63
+ echo ""
64
+ echo "6. Checking what's listening on 9222..."
65
+ ss -tlnp 2>/dev/null | grep 9222 || netstat -tlnp 2>/dev/null | grep 9222 || echo " Could not check listening ports"
66
+ echo ""
67
+ echo "7. Killing test Chrome..."
68
+ kill $PID 2>/dev/null
69
+ else
70
+ echo " Chrome DIED within 3s"
71
+ wait $PID 2>/dev/null
72
+ EXIT_CODE=$?
73
+ echo " Exit code: $EXIT_CODE"
74
+ echo ""
75
+ echo " Checking for crash logs..."
76
+ ls -la "$USER_DATA_DIR" 2>&1 | head -10 || echo " No user-data-dir"
77
+ fi
78
+ echo ""
79
+ echo "=== End d3k exact command test ==="
80
+ `,o=await runSandboxCommand(a.sandbox,"bash",["-c",e]);console.log(`[Step 0] d3k Chrome test (exit ${o.exitCode}):
81
+ ${o.stdout||"(no output)"}`),o.stderr&&console.log(`[Step 0] d3k Chrome test stderr: ${o.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",t))}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 o="",t="",s=-1;try{let r=await runSandboxCommand(a.sandbox,"bash",["-c",e]);o=r.stdout,t=r.stderr,s=r.exitCode,console.log(`[Step 0] MCP command exit code: ${s}`),console.log(`[Step 0] MCP stdout length: ${o.length} bytes`),t&&console.log(`[Step 0] MCP stderr: ${t.substring(0,500)}`)}catch(o){let e=o instanceof Error?o.message:String(o);console.log(`[Step 0] sandbox.runCommand threw: ${e}`),c=`sandbox.runCommand failed: ${e}`}if(0===s&&o)try{let e=JSON.parse(o);if(e.result?.content){for(let o of e.result.content)if("text"===o.type&&o.text)try{i=JSON.parse(o.text),console.log("[Step 0] Successfully parsed CLS data");break}catch{i={rawOutput:o.text}}}console.log("[Step 0] CLS data captured:",JSON.stringify(i).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: ${o.substring(0,1e3)}`)}else 0!==s&&!c&&(c=`MCP command failed with exit code ${s}`,console.log(`[Step 0] ${c}`),t&&console.log(`[Step 0] stderr: ${t}`))}catch(e){c=`MCP execution error: ${e instanceof Error?e.message:String(e)}`,console.log(`[Step 0] ${c}`)}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:
82
+ ${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 t(e,o,t,s,r,a){if(s)return console.log("[Step 1] Using CLS data captured in Step 0"),a&&console.log(`[Step 1] Before screenshot from Step 0: ${a}`),{logAnalysis:JSON.stringify(s,null,2),beforeScreenshotUrl:a||null};r&&console.log(`[Step 1] Note: MCP error from Step 0: ${r}`);let n=!!t,l=t||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: ${o?"provided":"not provided"}`);try{let e=o?`${l}?x-vercel-protection-bypass=${o}`:l;if(console.log(`[Step 1] Final URL: ${e.replace(o||"","***")}`),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 o=new AbortController,t=setTimeout(()=>o.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:o.signal});if(clearTimeout(t),e.ok){let o=await e.text();try{let e=null;for(let t of o.split("\n"))if(t.startsWith("data: "))try{e=JSON.parse(t.substring(6));break}catch{}e||(e=JSON.parse(o));let t=e.result?.tools?.map(e=>e.name)||[];console.log(`[Step 1] ✅ d3k MCP server accessible`),console.log(`[Step 1] Available tools (${t.length}): ${t.join(", ")}`);let s=t.some(e=>e.includes("chrome-devtools")),r=t.some(e=>e.includes("nextjs")),a=t.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: ${o.substring(0,200)}`)}}else console.log(`[Step 1] ⚠️ MCP server not accessible: ${e.status}`)}catch(s){clearTimeout(t);let e=s instanceof Error?s.message:String(s),o=s instanceof Error&&"AbortError"===s.name;console.log(`[Step 1] ⚠️ Failed to validate MCP server: ${o?"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 o=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),o.ok?console.log("[Step 1] Browser navigation completed"):console.log(`[Step 1] Browser navigation failed: ${o.status}`)}catch(o){clearTimeout(r);let e=o instanceof Error&&"AbortError"===o.name;console.log(`[Step 1] Browser navigation error: ${e?"Timed out after 30s":o instanceof Error?o.message:String(o)}`)}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 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"),t=new Date().toISOString().replace(/[:.]/g,"-"),s=`screenshot-before-${t}.png`;a=(await put(s,o,{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: ${o.substring(0,500)}`))}else console.log(`[Step 1] Screenshot request failed: ${e.status}`)}catch(o){clearTimeout(c);let e=o instanceof Error&&"AbortError"===o.name;console.log(`[Step 1] Screenshot capture error: ${e?"Timed out after 30s":o instanceof Error?o.message:String(o)}`)}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 o=await e.text();console.log(`[Step 1] d3k logs (last 1000 chars):
83
+ ${o.slice(-1e3)}`)}else console.log(`[Step 1] Could not fetch d3k logs: ${e.status}`)}catch(o){clearTimeout(d);let e=o instanceof Error&&"AbortError"===o.name;console.log(`[Step 1] Failed to fetch d3k logs: ${e?"Timed out after 15s":o instanceof Error?o.message:String(o)}`)}console.log("[Step 1] Calling fix_my_app with focusArea='performance'...");let g=new AbortController,h=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(h),!e.ok)throw Error(`MCP request failed: ${e.status}`);let o=await e.text();console.log(`[Step 1] fix_my_app response length: ${o.length} bytes`),console.log(`[Step 1] fix_my_app response preview (first 500 chars):
84
+ ${o.substring(0,500)}`);let t=o.split("\n");console.log(`[Step 1] Response split into ${t.length} lines`);let s="",r=0,n=0;for(let e of t)if(e.startsWith("data: ")){r++;try{let o=JSON.parse(e.substring(6));if(console.log(`[Step 1] Parsed JSON line ${r}:`,JSON.stringify(o).substring(0,200)),o.result?.content)for(let e of o.result.content)"text"===e.type&&(n++,s+=e.text,console.log(`[Step 1] Added text content block ${n}, length: ${e.text.length}`));else o.error&&console.log(`[Step 1] ERROR in response: ${JSON.stringify(o.error)}`)}catch(o){console.log(`[Step 1] Failed to parse JSON line ${r}: ${o instanceof Error?o.message:String(o)}`),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:
85
+ ${o}`),{logAnalysis:`d3k Performance Analysis for ${l}
86
+
87
+ ${s}`,beforeScreenshotUrl:a}}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 t=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.
7
88
 
8
89
  Your task is to visit this URL and capture any errors, warnings, or issues:
9
90
  ${e}
@@ -23,28 +104,29 @@ Analyze the console messages and provide a detailed report including:
23
104
  - Any visual issues you can identify from the screenshot
24
105
  - Screenshot URL if captured
25
106
 
26
- Format your response as a clear, structured report that helps identify what's broken in the application.`,{text:s}=await generateText({model:o,prompt:r,toolChoice:"auto",maxTokens:4e3});return console.log(`[Step 1] Browser automation response (first 500 chars): ${s.substring(0,500)}...`),{logAnalysis:`Browser Automation Analysis for ${n}
107
+ Format your response as a clear, structured report that helps identify what's broken in the application.`,{text:r}=await generateText({model:t,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}
27
108
 
28
- ${s}`,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?`${n}?x-vercel-protection-bypass=${t}`:n,o={"User-Agent":"dev3000-cloud-fix/1.0",Accept:"text/html,application/json,*/*"};t&&(o["x-vercel-protection-bypass"]=t);let r=await fetch(e,{method:"GET",headers:o}),s=await r.text(),a=`Dev Server URL: ${n}
29
- `;return a+=`HTTP Status: ${r.status} ${r.statusText}
109
+ ${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?`${l}?x-vercel-protection-bypass=${o}`:l,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}),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}
110
+ `;return i+=`Page Title: ${n}
111
+ HTTP Status: ${s.status} ${s.statusText}
30
112
 
31
113
  Note: Browser automation failed, using fallback HTTP fetch.
32
114
 
33
- `,r.ok||(a+=`ERROR: HTTP ${r.status} ${r.statusText}
115
+ `,s.ok||(i+=`ERROR: HTTP ${s.status} ${s.statusText}
34
116
 
35
- `),s.includes("ReferenceError")||s.includes("Error")||s.includes("error")?a+=`Response body contains error information:
36
- ${s.substring(0,5e3)}
117
+ `),r.includes("ReferenceError")||r.includes("Error")||r.includes("error")?i+=`Response body contains error information:
118
+ ${r.substring(0,5e3)}
37
119
 
38
- `:r.ok?a+="No errors detected in response.\n":a+=`Response body:
39
- ${s.substring(0,2e3)}
120
+ `:s.ok?i+="No errors detected in response.\n":i+=`Response body:
121
+ ${r.substring(0,2e3)}
40
122
 
41
- `,{logAnalysis:a,beforeScreenshotUrl:null}}catch(t){let e=t instanceof Error?t.message:String(t);return{logAnalysis:`Failed to fetch logs from ${n}
123
+ `,{logAnalysis:i,beforeScreenshotUrl:null}}catch(o){let e=o instanceof Error?o.message:String(o);return{logAnalysis:`Failed to fetch logs from ${l}
42
124
 
43
125
  Error: ${e}
44
126
 
45
- This may indicate the dev server is not accessible or has crashed.`,beforeScreenshotUrl:null}}}}async function r(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"),r=`You are a skilled software engineer debugging an application.
127
+ This may indicate the dev server is not accessible or has crashed.`,beforeScreenshotUrl:null}}}}async function s(e,o){console.log("[Step 2] Invoking AI agent to analyze logs...");let t=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.
46
128
 
47
- The dev server is running at: ${t}
129
+ The dev server is running at: ${o}
48
130
 
49
131
  Here's the log analysis from the MCP fix_my_app tool:
50
132
  ${e}
@@ -89,26 +171,38 @@ Format your response EXACTLY as follows:
89
171
  IMPORTANT:
90
172
  - The Git Patch section must be a valid unified diff that can be applied directly with 'git apply'.
91
173
  - If no errors are found, respond with "✅ **SYSTEM HEALTHY** - No errors found" and do NOT include a Git Patch section.
92
- - Only include a Git Patch if there are actual issues that need fixing.`,{text:s}=await generateText({model:o,prompt:r});return console.log(`[Step 2] AI agent response (first 500 chars): ${s.substring(0,500)}...`),s}async function s(e,t,o,r,s){console.log("[Step 3] Uploading fix proposal to blob storage..."),s&&console.log(`[Step 3] Including before screenshot: ${s}`);let a=s?`## Before Screenshot
174
+ - Only include a Git Patch if there are actual issues that need fixing.`,{text:r}=await generateText({model:t,prompt:s});return console.log(`[Step 2] AI agent response (first 500 chars): ${r.substring(0,500)}...`),r}async function r(e,o,t,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
93
175
 
94
176
  This screenshot was captured when the sandbox dev server first loaded, proving the page rendered successfully.
95
177
 
96
- ![Before Screenshot](${s})
178
+ ![Before Screenshot](${r})
179
+
180
+ ---
181
+
182
+ `:"",l=a?`## Actual Git Diff from Sandbox
183
+
184
+ The following diff shows the actual changes made by d3k in the sandbox environment:
185
+
186
+ \`\`\`diff
187
+ ${a}
188
+ \`\`\`
97
189
 
98
190
  ---
99
191
 
100
- `:"",n=new Date().toISOString(),l=`# Fix Proposal for ${t}
192
+ `:"",i=new Date().toISOString(),c=`# Fix Proposal for ${o}
193
+
194
+ **Generated**: ${i}
101
195
 
102
- **Generated**: ${n}
103
196
  **Powered by**: [dev3000](https://github.com/vercel-labs/dev3000) with Claude Code
104
- **Dev Server**: ${r}
197
+
198
+ **Dev Server**: ${s}
105
199
 
106
200
  ---
107
201
 
108
- ${a}## Original Log Analysis
202
+ ${n}${l}## Original Log Analysis
109
203
 
110
204
  \`\`\`
111
- ${o}
205
+ ${t}
112
206
  \`\`\`
113
207
 
114
208
  ---
@@ -133,12 +227,12 @@ dev3000 monitors your development server, captures errors in real-time, and uses
133
227
  - Suggest specific code changes
134
228
 
135
229
  Learn more at https://github.com/vercel-labs/dev3000
136
- `,i=n.replace(/[:.]/g,"-"),c=`fix-${t}-${i}.md`,p=await put(c,l,{access:"public",contentType:"text/markdown"});return console.log(`[Step 3] Fix proposal uploaded to: ${p.url}`),{success:!0,projectName:t,fixProposal:e,blobUrl:p.url,beforeScreenshotUrl:s||null,message:"Fix analysis completed and uploaded to blob storage"}}async function a(e,t,o,r,s,a){console.log(`[Step 4] Creating GitHub PR for ${o}/${r}...`);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 g=await fetch(`https://api.github.com/repos/${o}/${r}/git/ref/heads/${s}`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/vnd.github.v3+json"}});if(!g.ok){let e=await g.text();return console.error(`[Step 4] Failed to get base branch: ${e}`),{success:!1,error:`Failed to get base branch: ${g.status}`}}let d=(await g.json()).object.sha;console.log(`[Step 4] Base SHA: ${d}`);let u=await fetch(`https://api.github.com/repos/${o}/${r}/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:d})});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}/${r}/contents/${e.path}?ref=${p}`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/vnd.github.v3+json"}}),s="",l="";if(t.ok){let e=await t.json();l=e.sha,s=Buffer.from(e.content,"base64").toString("utf-8")}else console.log("[Step 4] File doesn't exist, will create new file");let i=applyPatchChanges(s,e.changes),c=await fetch(`https://api.github.com/repos/${o}/${r}/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
230
+ `,p=i.replace(/[:.]/g,"-"),d=`fix-${o}-${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:o,fixProposal:e,blobUrl:g.url,beforeScreenshotUrl:r||null,message:"Fix analysis completed and uploaded to blob storage"}}async function a(e,o,t,s,r,a){console.log(`[Step 4] Creating GitHub PR for ${t}/${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/${t}/${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 h=await fetch(`https://api.github.com/repos/${t}/${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(!h.ok){let e=await h.text();return console.error(`[Step 4] Failed to create branch: ${e}`),{success:!1,error:`Failed to create branch: ${h.status}`}}for(let e of(console.log(`[Step 4] Created branch: ${p}`),c)){console.log(`[Step 4] Processing file: ${e.path}`);let o=await fetch(`https://api.github.com/repos/${t}/${s}/contents/${e.path}?ref=${p}`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/vnd.github.v3+json"}}),r="",l="";if(o.ok){let e=await o.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/${t}/${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 o=await c.text();return console.error(`[Step 4] Failed to update file ${e.path}: ${o}`),{success:!1,error:`Failed to update file ${e.path}: ${c.status}`}}console.log(`[Step 4] Updated file: ${e.path}`)}let u=`## Automated Fix Proposal
137
231
 
138
232
  This PR was automatically generated by [dev3000](https://github.com/vercel-labs/dev3000) after analyzing your application.
139
233
 
140
234
  ### Fix Details
141
- View the full analysis: [${t}](${t})
235
+ View the full analysis: [${o}](${o})
142
236
 
143
237
  ${e}
144
238
 
@@ -146,6 +240,6 @@ ${e}
146
240
 
147
241
  🤖 Generated with [Claude Code](https://claude.com/claude-code)
148
242
 
149
- Co-Authored-By: Claude (dev3000) <noreply@anthropic.com>`,f=await fetch(`https://api.github.com/repos/${o}/${r}/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:s,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",()=>r,"cleanupSandbox",()=>n,"createD3kSandbox",()=>t,"createGitHubPR",()=>a,"fetchRealLogs",()=>o,"uploadToBlob",()=>s])}];
243
+ Co-Authored-By: Claude (dev3000) <noreply@anthropic.com>`,f=await fetch(`https://api.github.com/repos/${t}/${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:u})});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",()=>o,"createGitHubPR",()=>a,"fetchRealLogs",()=>t,"uploadToBlob",()=>r])}];
150
244
 
151
245
  //# sourceMappingURL=mcp-server_app_api_cloud_fix-workflow_steps_ts_b65f3271._.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../mcp-server/app/api/cloud/fix-workflow/steps.ts"],"sourcesContent":["/**\n * Step functions for fix-workflow\n * Separated into their own module to avoid workflow bundler issues\n */ /**__internal_workflows{\"steps\":{\"app/api/cloud/fix-workflow/steps.ts\":{\"analyzeLogsWithAgent\":{\"stepId\":\"step//app/api/cloud/fix-workflow/steps.ts//analyzeLogsWithAgent\"},\"cleanupSandbox\":{\"stepId\":\"step//app/api/cloud/fix-workflow/steps.ts//cleanupSandbox\"},\"createD3kSandbox\":{\"stepId\":\"step//app/api/cloud/fix-workflow/steps.ts//createD3kSandbox\"},\"createGitHubPR\":{\"stepId\":\"step//app/api/cloud/fix-workflow/steps.ts//createGitHubPR\"},\"fetchRealLogs\":{\"stepId\":\"step//app/api/cloud/fix-workflow/steps.ts//fetchRealLogs\"},\"uploadToBlob\":{\"stepId\":\"step//app/api/cloud/fix-workflow/steps.ts//uploadToBlob\"}}}}*/;\n/**\n * Step 0: Create d3k sandbox with MCP tools pre-configured\n */ export async function createD3kSandbox(repoUrl, branch, projectName, vercelToken, vercelOidcToken) {\n console.log(`[Step 0] Creating d3k sandbox for ${projectName}...`);\n console.log(`[Step 0] Repository: ${repoUrl}`);\n console.log(`[Step 0] Branch: ${branch}`);\n // Log available token types\n console.log(`[Step 0] VERCEL_OIDC_TOKEN from env: ${!!process.env.VERCEL_OIDC_TOKEN}`);\n console.log(`[Step 0] VERCEL_OIDC_TOKEN passed as param: ${!!vercelOidcToken}`);\n console.log(`[Step 0] VERCEL_TOKEN available: ${!!process.env.VERCEL_TOKEN}`);\n console.log(`[Step 0] User access token provided: ${!!vercelToken}`);\n // Set VERCEL_OIDC_TOKEN if passed from workflow context\n // This is necessary because workflow steps don't automatically inherit environment variables\n if (vercelOidcToken && !process.env.VERCEL_OIDC_TOKEN) {\n process.env.VERCEL_OIDC_TOKEN = vercelOidcToken;\n console.log(`[Step 0] Set VERCEL_OIDC_TOKEN from workflow context`);\n }\n const sandboxResult = await createD3kSandboxUtil({\n repoUrl,\n branch,\n projectDir: \"\",\n packageManager: \"pnpm\",\n debug: true\n });\n console.log(`[Step 0] Sandbox created successfully`);\n console.log(`[Step 0] Dev URL: ${sandboxResult.devUrl}`);\n console.log(`[Step 0] MCP URL: ${sandboxResult.mcpUrl}`);\n // Now capture CLS and errors using MCP from INSIDE the sandbox\n // We must do this in Step 0 while we have the sandbox object\n console.log(`[Step 0] Capturing CLS metrics from inside sandbox...`);\n let clsData = null;\n let mcpError = null;\n // Helper function to properly consume sandbox command output\n // The Vercel Sandbox SDK returns a result object with an async logs() iterator\n async function runSandboxCommand(sandbox, cmd, args) {\n const result = await sandbox.runCommand({\n cmd,\n args\n });\n let stdout = \"\";\n let stderr = \"\";\n for await (const log of result.logs()){\n if (log.stream === \"stdout\") {\n stdout += log.data;\n } else {\n stderr += log.data;\n }\n }\n await result.wait();\n return {\n exitCode: result.exitCode,\n stdout,\n stderr\n };\n }\n try {\n // Call fix_my_app MCP tool via curl from inside the sandbox\n // This avoids network isolation issues - we're calling localhost:3684 from within the sandbox\n const mcpCommand = `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}}}'`;\n console.log(`[Step 0] Executing MCP command inside sandbox...`);\n console.log(`[Step 0] MCP command: ${mcpCommand.substring(0, 200)}...`);\n let stdout = \"\";\n let stderr = \"\";\n let exitCode = -1;\n try {\n const result = await runSandboxCommand(sandboxResult.sandbox, \"bash\", [\n \"-c\",\n mcpCommand\n ]);\n stdout = result.stdout;\n stderr = result.stderr;\n exitCode = result.exitCode;\n console.log(`[Step 0] MCP command exit code: ${exitCode}`);\n console.log(`[Step 0] MCP stdout length: ${stdout.length} bytes`);\n if (stderr) {\n console.log(`[Step 0] MCP stderr: ${stderr.substring(0, 500)}`);\n }\n } catch (runCommandError) {\n const errorMsg = runCommandError instanceof Error ? runCommandError.message : String(runCommandError);\n console.log(`[Step 0] sandbox.runCommand threw: ${errorMsg}`);\n mcpError = `sandbox.runCommand failed: ${errorMsg}`;\n }\n if (exitCode === 0 && stdout) {\n try {\n const mcpResponse = JSON.parse(stdout);\n if (mcpResponse.result?.content) {\n // Extract the actual data from MCP response\n const contentArray = mcpResponse.result.content;\n for (const item of contentArray){\n if (item.type === \"text\" && item.text) {\n // Try to parse the text as JSON if it contains structured data\n try {\n clsData = JSON.parse(item.text);\n console.log(`[Step 0] Successfully parsed CLS data`);\n break;\n } catch {\n // If not JSON, treat as plain text\n clsData = {\n rawOutput: item.text\n };\n }\n }\n }\n }\n console.log(`[Step 0] CLS data captured:`, JSON.stringify(clsData).substring(0, 500));\n } catch (parseError) {\n mcpError = `Failed to parse MCP response: ${parseError instanceof Error ? parseError.message : String(parseError)}`;\n console.log(`[Step 0] ${mcpError}`);\n console.log(`[Step 0] Raw stdout: ${stdout.substring(0, 1000)}`);\n }\n } else if (exitCode !== 0 && !mcpError) {\n mcpError = `MCP command failed with exit code ${exitCode}`;\n console.log(`[Step 0] ${mcpError}`);\n if (stderr) {\n console.log(`[Step 0] stderr: ${stderr}`);\n }\n }\n } catch (error) {\n mcpError = `MCP execution error: ${error instanceof Error ? error.message : String(error)}`;\n console.log(`[Step 0] ${mcpError}`);\n }\n // Dump all sandbox logs before returning for debugging\n console.log(`[Step 0] === Dumping sandbox logs before returning ===`);\n try {\n const logsResult = await runSandboxCommand(sandboxResult.sandbox, \"sh\", [\n \"-c\",\n '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\"'\n ]);\n console.log(logsResult.stdout);\n } catch (logsError) {\n console.log(`[Step 0] Failed to dump logs: ${logsError instanceof Error ? logsError.message : String(logsError)}`);\n }\n console.log(`[Step 0] === End sandbox log dump ===`);\n // Note: We cannot return the cleanup function or sandbox object as they're not serializable\n // Sandbox cleanup will happen automatically when the sandbox times out\n return {\n mcpUrl: sandboxResult.mcpUrl,\n devUrl: sandboxResult.devUrl,\n bypassToken: sandboxResult.bypassToken,\n clsData,\n mcpError\n };\n}\n/**\n * Step 1: Use browser automation to capture real errors\n * Uses d3k MCP server in sandbox (if available) or AI Gateway for browser automation\n */ export async function fetchRealLogs(mcpUrlOrDevUrl, bypassToken, sandboxDevUrl, clsData, mcpError) {\n // If we already have CLS data from Step 0, use it\n if (clsData) {\n console.log(\"[Step 1] Using CLS data captured in Step 0\");\n return {\n logAnalysis: JSON.stringify(clsData, null, 2),\n beforeScreenshotUrl: null\n };\n }\n // If there was an MCP error in Step 0, log it\n if (mcpError) {\n console.log(`[Step 1] Note: MCP error from Step 0: ${mcpError}`);\n }\n // Determine if we're using sandbox MCP or direct dev URL\n const isSandbox = !!sandboxDevUrl;\n const devUrl = sandboxDevUrl || mcpUrlOrDevUrl;\n const mcpUrl = isSandbox ? mcpUrlOrDevUrl : null;\n console.log(`[Step 1] Fetching logs from: ${devUrl}`);\n console.log(`[Step 1] Using sandbox: ${isSandbox ? \"yes\" : \"no\"}`);\n if (mcpUrl) {\n console.log(`[Step 1] MCP URL: ${mcpUrl}`);\n }\n console.log(`[Step 1] Bypass token: ${bypassToken ? \"provided\" : \"not provided\"}`);\n try {\n // Construct URL with bypass token if provided\n const urlWithBypass = bypassToken ? `${devUrl}?x-vercel-protection-bypass=${bypassToken}` : devUrl;\n console.log(`[Step 1] Final URL: ${urlWithBypass.replace(bypassToken || \"\", \"***\")}`);\n if (isSandbox && mcpUrl) {\n // Use d3k MCP server in sandbox - capture CLS metrics and errors\n console.log(\"[Step 1] Using d3k MCP server to capture CLS metrics and errors...\");\n // First, validate MCP server access and list available tools\n // Use a 30-second timeout to avoid hanging the entire workflow\n console.log(\"[Step 1] Validating d3k MCP server access...\");\n const validationController = new AbortController();\n const validationTimeout = setTimeout(()=>validationController.abort(), 30000);\n try {\n const toolsResponse = await fetch(`${mcpUrl}/mcp`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json, text/event-stream\"\n },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: 0,\n method: \"tools/list\"\n }),\n signal: validationController.signal\n });\n clearTimeout(validationTimeout);\n if (toolsResponse.ok) {\n const toolsText = await toolsResponse.text();\n try {\n // Parse SSE response format: \"event: message\\ndata: {...}\\n\\n\"\n let toolsData = null;\n const lines = toolsText.split(\"\\n\");\n for (const line of lines){\n if (line.startsWith(\"data: \")) {\n try {\n toolsData = JSON.parse(line.substring(6));\n break;\n } catch {\n // Continue to next line\n }\n }\n }\n // Fallback: try parsing the whole response as JSON (non-SSE format)\n if (!toolsData) {\n toolsData = JSON.parse(toolsText);\n }\n const toolNames = toolsData.result?.tools?.map((t)=>t.name) || [];\n console.log(`[Step 1] ✅ d3k MCP server accessible`);\n console.log(`[Step 1] Available tools (${toolNames.length}): ${toolNames.join(\", \")}`);\n // Check for expected chrome-devtools and nextjs-dev tools\n const hasChrome = toolNames.some((name)=>name.includes(\"chrome-devtools\"));\n const hasNextjs = toolNames.some((name)=>name.includes(\"nextjs\"));\n const hasFixMyApp = toolNames.includes(\"fix_my_app\");\n console.log(`[Step 1] Chrome DevTools MCP: ${hasChrome ? \"✅\" : \"❌\"}`);\n console.log(`[Step 1] Next.js DevTools MCP: ${hasNextjs ? \"✅\" : \"❌\"}`);\n console.log(`[Step 1] fix_my_app tool: ${hasFixMyApp ? \"✅\" : \"❌\"}`);\n } catch {\n console.log(`[Step 1] MCP server responded but couldn't parse tools list: ${toolsText.substring(0, 200)}`);\n }\n } else {\n console.log(`[Step 1] ⚠️ MCP server not accessible: ${toolsResponse.status}`);\n }\n } catch (error) {\n clearTimeout(validationTimeout);\n const errorMsg = error instanceof Error ? error.message : String(error);\n const isTimeout = error instanceof Error && error.name === \"AbortError\";\n console.log(`[Step 1] ⚠️ Failed to validate MCP server: ${isTimeout ? \"Timed out after 30s\" : errorMsg}`);\n }\n // Navigate to the app to generate logs (with 30s timeout)\n console.log(\"[Step 1] Navigating browser to app URL...\");\n const navController = new AbortController();\n const navTimeout = setTimeout(()=>navController.abort(), 30000);\n try {\n const navResponse = await fetch(`${mcpUrl}/mcp`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json, text/event-stream\"\n },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: 0,\n method: \"tools/call\",\n params: {\n name: \"execute_browser_action\",\n arguments: {\n action: \"navigate\",\n params: {\n url: urlWithBypass\n }\n }\n }\n }),\n signal: navController.signal\n });\n clearTimeout(navTimeout);\n if (navResponse.ok) {\n console.log(\"[Step 1] Browser navigation completed\");\n } else {\n console.log(`[Step 1] Browser navigation failed: ${navResponse.status}`);\n }\n } catch (navError) {\n clearTimeout(navTimeout);\n const isTimeout = navError instanceof Error && navError.name === \"AbortError\";\n console.log(`[Step 1] Browser navigation error: ${isTimeout ? \"Timed out after 30s\" : navError instanceof Error ? navError.message : String(navError)}`);\n }\n // Wait for page to fully load\n console.log(\"[Step 1] Waiting 5s for page load...\");\n await new Promise((resolve)=>setTimeout(resolve, 5000));\n // Capture \"before\" screenshot to prove the page loaded and for later comparison\n let beforeScreenshotUrl = null;\n console.log(\"[Step 1] Capturing 'before' screenshot...\");\n const screenshotController = new AbortController();\n const screenshotTimeout = setTimeout(()=>screenshotController.abort(), 30000);\n try {\n const screenshotResponse = await fetch(`${mcpUrl}/mcp`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json, text/event-stream\"\n },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: 0,\n method: \"tools/call\",\n params: {\n name: \"chrome-devtools_take_snapshot\",\n arguments: {}\n }\n }),\n signal: screenshotController.signal\n });\n clearTimeout(screenshotTimeout);\n if (screenshotResponse.ok) {\n const screenshotText = await screenshotResponse.text();\n // Parse SSE response to get screenshot data\n const lines = screenshotText.split(\"\\n\");\n for (const line of lines){\n if (line.startsWith(\"data: \")) {\n try {\n const json = JSON.parse(line.substring(6));\n if (json.result?.content) {\n for (const content of json.result.content){\n if (content.type === \"image\" && content.data) {\n // Upload base64 image to Vercel Blob\n const imageBuffer = Buffer.from(content.data, \"base64\");\n const timestamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n const filename = `screenshot-before-${timestamp}.png`;\n const blob = await put(filename, imageBuffer, {\n access: \"public\",\n contentType: \"image/png\"\n });\n beforeScreenshotUrl = blob.url;\n console.log(`[Step 1] ✅ Before screenshot uploaded: ${beforeScreenshotUrl}`);\n }\n }\n }\n } catch {\n // Continue parsing other lines\n }\n }\n }\n if (!beforeScreenshotUrl) {\n console.log(`[Step 1] Screenshot response received but no image data found`);\n console.log(`[Step 1] Response preview: ${screenshotText.substring(0, 500)}`);\n }\n } else {\n console.log(`[Step 1] Screenshot request failed: ${screenshotResponse.status}`);\n }\n } catch (error) {\n clearTimeout(screenshotTimeout);\n const isTimeout = error instanceof Error && error.name === \"AbortError\";\n console.log(`[Step 1] Screenshot capture error: ${isTimeout ? \"Timed out after 30s\" : error instanceof Error ? error.message : String(error)}`);\n }\n // Check d3k logs to see if it's capturing data (with 15s timeout)\n console.log(\"[Step 1] Fetching d3k logs from sandbox to verify it's working...\");\n const logsController = new AbortController();\n const logsTimeout = setTimeout(()=>logsController.abort(), 15000);\n try {\n const logsResponse = await fetch(`${mcpUrl}/api/logs`, {\n signal: logsController.signal\n });\n clearTimeout(logsTimeout);\n if (logsResponse.ok) {\n const logsText = await logsResponse.text();\n console.log(`[Step 1] d3k logs (last 1000 chars):\\n${logsText.slice(-1000)}`);\n } else {\n console.log(`[Step 1] Could not fetch d3k logs: ${logsResponse.status}`);\n }\n } catch (error) {\n clearTimeout(logsTimeout);\n const isTimeout = error instanceof Error && error.name === \"AbortError\";\n console.log(`[Step 1] Failed to fetch d3k logs: ${isTimeout ? \"Timed out after 15s\" : error instanceof Error ? error.message : String(error)}`);\n }\n // Call fix_my_app with focusArea='performance' to capture CLS and jank\n console.log(\"[Step 1] Calling fix_my_app with focusArea='performance'...\");\n // Set a 3-minute timeout for the MCP call\n const controller = new AbortController();\n const timeoutId = setTimeout(()=>controller.abort(), 3 * 60 * 1000);\n try {\n const mcpResponse = await fetch(`${mcpUrl}/mcp`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json, text/event-stream\"\n },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: 1,\n method: \"tools/call\",\n params: {\n name: \"fix_my_app\",\n arguments: {\n mode: \"snapshot\",\n focusArea: \"performance\",\n timeRangeMinutes: 5,\n returnRawData: false\n }\n }\n }),\n signal: controller.signal\n });\n clearTimeout(timeoutId);\n if (!mcpResponse.ok) {\n throw new Error(`MCP request failed: ${mcpResponse.status}`);\n }\n // Parse SSE response\n const text = await mcpResponse.text();\n console.log(`[Step 1] fix_my_app response length: ${text.length} bytes`);\n console.log(`[Step 1] fix_my_app response preview (first 500 chars):\\n${text.substring(0, 500)}`);\n const lines = text.split(\"\\n\");\n console.log(`[Step 1] Response split into ${lines.length} lines`);\n let logAnalysis = \"\";\n let linesProcessed = 0;\n let contentBlocks = 0;\n for (const line of lines){\n if (line.startsWith(\"data: \")) {\n linesProcessed++;\n try {\n const json = JSON.parse(line.substring(6));\n console.log(`[Step 1] Parsed JSON line ${linesProcessed}:`, JSON.stringify(json).substring(0, 200));\n if (json.result?.content) {\n for (const content of json.result.content){\n if (content.type === \"text\") {\n contentBlocks++;\n logAnalysis += content.text;\n console.log(`[Step 1] Added text content block ${contentBlocks}, length: ${content.text.length}`);\n }\n }\n } else if (json.error) {\n console.log(`[Step 1] ERROR in response: ${JSON.stringify(json.error)}`);\n }\n } catch (error) {\n console.log(`[Step 1] Failed to parse JSON line ${linesProcessed}: ${error instanceof Error ? error.message : String(error)}`);\n console.log(`[Step 1] Problem line: ${line.substring(0, 200)}`);\n }\n }\n }\n console.log(`[Step 1] Processed ${linesProcessed} data lines, ${contentBlocks} content blocks`);\n console.log(`[Step 1] Got ${logAnalysis.length} chars from fix_my_app (performance analysis)`);\n if (logAnalysis.length === 0) {\n console.log(`[Step 1] WARNING: fix_my_app returned NO data. Full response:\\n${text}`);\n }\n return {\n logAnalysis: `d3k Performance Analysis for ${devUrl}\\n\\n${logAnalysis}`,\n beforeScreenshotUrl\n };\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof Error && error.name === \"AbortError\") {\n console.log(\"[Step 1] fix_my_app timed out after 3 minutes, using fallback method\");\n // Fall through to fallback method below\n } else {\n console.log(`[Step 1] fix_my_app error: ${error instanceof Error ? error.message : String(error)}`);\n // Fall through to fallback method below\n }\n }\n }\n // Fallback: Use AI Gateway with browser automation prompting\n console.log(\"[Step 1] Using AI Gateway with browser automation...\");\n const gateway = createGateway({\n apiKey: process.env.AI_GATEWAY_API_KEY,\n baseURL: \"https://ai-gateway.vercel.sh/v1/ai\"\n });\n const model = gateway(\"anthropic/claude-sonnet-4-20250514\");\n const prompt = `You are a web application debugger with access to browser automation tools via Playwright MCP.\n\nYour task is to visit this URL and capture any errors, warnings, or issues:\n${urlWithBypass}\n\nSteps to follow:\n1. Use browser_eval with action=\"start\" to start the browser\n2. Use browser_eval with action=\"navigate\" and params={url: \"${urlWithBypass}\"} to navigate to the page\n3. Wait a few seconds for the page to fully load and JavaScript to execute\n4. Use browser_eval with action=\"console_messages\" to get all browser console output (errors, warnings, logs)\n5. Use browser_eval with action=\"screenshot\" to capture a screenshot\n6. Use browser_eval with action=\"close\" to close the browser\n\nAnalyze the console messages and provide a detailed report including:\n- All console errors (with full stack traces if available)\n- All console warnings\n- HTTP status codes or network errors\n- Any visual issues you can identify from the screenshot\n- Screenshot URL if captured\n\nFormat your response as a clear, structured report that helps identify what's broken in the application.`;\n const { text } = await generateText({\n model,\n prompt,\n toolChoice: \"auto\",\n // @ts-expect-error - AI SDK types for maxTokens are incomplete\n maxTokens: 4000\n });\n console.log(`[Step 1] Browser automation response (first 500 chars): ${text.substring(0, 500)}...`);\n return {\n logAnalysis: `Browser Automation Analysis for ${devUrl}\\n\\n${text}`,\n beforeScreenshotUrl: null\n };\n } catch (error) {\n console.error(\"[Step 1] Error with browser automation:\", error);\n // Fallback to simple fetch if browser automation fails\n console.log(\"[Step 1] Falling back to simple HTTP fetch...\");\n try {\n const urlWithBypass = bypassToken ? `${devUrl}?x-vercel-protection-bypass=${bypassToken}` : devUrl;\n const headers = {\n \"User-Agent\": \"dev3000-cloud-fix/1.0\",\n Accept: \"text/html,application/json,*/*\"\n };\n if (bypassToken) {\n headers[\"x-vercel-protection-bypass\"] = bypassToken;\n }\n const response = await fetch(urlWithBypass, {\n method: \"GET\",\n headers\n });\n const body = await response.text();\n let logAnalysis = `Dev Server URL: ${devUrl}\\n`;\n logAnalysis += `HTTP Status: ${response.status} ${response.statusText}\\n\\n`;\n logAnalysis += `Note: Browser automation failed, using fallback HTTP fetch.\\n\\n`;\n if (!response.ok) {\n logAnalysis += `ERROR: HTTP ${response.status} ${response.statusText}\\n\\n`;\n }\n if (body.includes(\"ReferenceError\") || body.includes(\"Error\") || body.includes(\"error\")) {\n logAnalysis += `Response body contains error information:\\n${body.substring(0, 5000)}\\n\\n`;\n } else if (!response.ok) {\n logAnalysis += `Response body:\\n${body.substring(0, 2000)}\\n\\n`;\n } else {\n logAnalysis += \"No errors detected in response.\\n\";\n }\n return {\n logAnalysis,\n beforeScreenshotUrl: null\n };\n } catch (fallbackError) {\n const errorMessage = fallbackError instanceof Error ? fallbackError.message : String(fallbackError);\n return {\n logAnalysis: `Failed to fetch logs from ${devUrl}\\n\\nError: ${errorMessage}\\n\\nThis may indicate the dev server is not accessible or has crashed.`,\n beforeScreenshotUrl: null\n };\n }\n }\n}\n/**\n * Step 2: Invoke AI agent to analyze logs and propose fixes\n * Uses AI SDK with AI Gateway for multi-model support\n */ export async function analyzeLogsWithAgent(logAnalysis, devUrl) {\n console.log(\"[Step 2] Invoking AI agent to analyze logs...\");\n // Create AI Gateway instance\n const gateway = createGateway({\n apiKey: process.env.AI_GATEWAY_API_KEY,\n baseURL: \"https://ai-gateway.vercel.sh/v1/ai\"\n });\n // Use Claude Sonnet 4 via AI Gateway\n const model = gateway(\"anthropic/claude-sonnet-4-20250514\");\n const prompt = `You are a skilled software engineer debugging an application.\n\nThe dev server is running at: ${devUrl}\n\nHere's the log analysis from the MCP fix_my_app tool:\n${logAnalysis}\n\nYour task:\n1. Identify the most critical error or issue from the logs\n2. Determine the root cause\n3. Propose a specific code fix with file paths and changes\n4. Create a git-style unified diff that can be applied with 'git apply'\n5. Explain why this fix will resolve the issue\n\nFormat your response EXACTLY as follows:\n\n## Issue\n[Brief description of the issue]\n\n## Root Cause\n[Explanation of what's causing the issue]\n\n## Proposed Fix\n[High-level explanation of the fix]\n\n## Git Patch\n\\`\\`\\`diff\n[Full unified diff format that can be applied with 'git apply' or 'patch']\n[Include file paths, line numbers, and exact changes]\n[Example format:]\n[diff --git a/path/to/file.ts b/path/to/file.ts]\n[index abc123..def456 100644]\n[--- a/path/to/file.ts]\n[+++ b/path/to/file.ts]\n[@@ -10,7 +10,7 @@ function example() {]\n[ unchanged line]\n[- old line to remove]\n[+ new line to add]\n[ unchanged line]\n\\`\\`\\`\n\n## Reasoning\n[Why this fix will work]\n\nIMPORTANT:\n- The Git Patch section must be a valid unified diff that can be applied directly with 'git apply'.\n- If no errors are found, respond with \"✅ **SYSTEM HEALTHY** - No errors found\" and do NOT include a Git Patch section.\n- Only include a Git Patch if there are actual issues that need fixing.`;\n const { text } = await generateText({\n model,\n prompt\n });\n console.log(`[Step 2] AI agent response (first 500 chars): ${text.substring(0, 500)}...`);\n return text;\n}\n/**\n * Step 3: Upload fix proposal to blob storage and return URL\n */ export async function uploadToBlob(fixProposal, projectName, logAnalysis, devUrl, beforeScreenshotUrl) {\n console.log(\"[Step 3] Uploading fix proposal to blob storage...\");\n if (beforeScreenshotUrl) {\n console.log(`[Step 3] Including before screenshot: ${beforeScreenshotUrl}`);\n }\n // Create screenshot section if we have a screenshot\n const screenshotSection = beforeScreenshotUrl ? `## Before Screenshot\n\nThis screenshot was captured when the sandbox dev server first loaded, proving the page rendered successfully.\n\n![Before Screenshot](${beforeScreenshotUrl})\n\n---\n\n` : \"\";\n // Create enhanced markdown with full context and attribution\n const timestamp = new Date().toISOString();\n const enhancedMarkdown = `# Fix Proposal for ${projectName}\n\n**Generated**: ${timestamp}\n**Powered by**: [dev3000](https://github.com/vercel-labs/dev3000) with Claude Code\n**Dev Server**: ${devUrl}\n\n---\n\n${screenshotSection}## Original Log Analysis\n\n\\`\\`\\`\n${logAnalysis}\n\\`\\`\\`\n\n---\n\n${fixProposal}\n\n---\n\n## Attribution\n\nThis fix proposal was automatically generated by [dev3000](https://github.com/vercel-labs/dev3000),\nan AI-powered debugging tool that analyzes your application logs and suggests fixes.\n\n**Co-Authored-By**: Claude (dev3000) <noreply@anthropic.com>\n\n### About dev3000\n\ndev3000 monitors your development server, captures errors in real-time, and uses AI to:\n- Analyze error logs and stack traces\n- Identify root causes\n- Generate actionable fix proposals with git patches\n- Suggest specific code changes\n\nLearn more at https://github.com/vercel-labs/dev3000\n`;\n // Upload to Vercel Blob Storage\n const filenameTimestamp = timestamp.replace(/[:.]/g, \"-\");\n const filename = `fix-${projectName}-${filenameTimestamp}.md`;\n const blob = await put(filename, enhancedMarkdown, {\n access: \"public\",\n contentType: \"text/markdown\"\n });\n console.log(`[Step 3] Fix proposal uploaded to: ${blob.url}`);\n return {\n success: true,\n projectName,\n fixProposal,\n blobUrl: blob.url,\n beforeScreenshotUrl: beforeScreenshotUrl || null,\n message: \"Fix analysis completed and uploaded to blob storage\"\n };\n}\n/**\n * Step 4: Create GitHub PR with the fix\n * Uses GitHub API to create a branch, commit the patch, and open a PR\n */ export async function createGitHubPR(fixProposal, blobUrl, repoOwner, repoName, baseBranch, projectName) {\n console.log(`[Step 4] Creating GitHub PR for ${repoOwner}/${repoName}...`);\n const githubToken = process.env.GITHUB_TOKEN;\n if (!githubToken) {\n console.error(\"[Step 4] GITHUB_TOKEN not found in environment\");\n return {\n success: false,\n error: \"GitHub token not configured\"\n };\n }\n try {\n // Extract the git patch from the fix proposal\n const patchMatch = fixProposal.match(/```diff\\n([\\s\\S]*?)\\n```/);\n if (!patchMatch) {\n console.error(\"[Step 4] No git patch found in fix proposal\");\n return {\n success: false,\n error: \"No git patch found in fix proposal\"\n };\n }\n const patch = patchMatch[1];\n console.log(`[Step 4] Extracted patch (${patch.length} chars)`);\n // Parse the patch to extract file changes\n const fileChanges = parsePatchToFileChanges(patch);\n if (fileChanges.length === 0) {\n console.error(\"[Step 4] Failed to parse any file changes from patch\");\n return {\n success: false,\n error: \"Failed to parse file changes from patch\"\n };\n }\n console.log(`[Step 4] Parsed ${fileChanges.length} file change(s)`);\n // Create a unique branch name\n const branchName = `dev3000-fix-${projectName}-${Date.now()}`;\n console.log(`[Step 4] Branch name: ${branchName}`);\n // Get the base branch SHA\n const baseRef = await fetch(`https://api.github.com/repos/${repoOwner}/${repoName}/git/ref/heads/${baseBranch}`, {\n headers: {\n Authorization: `Bearer ${githubToken}`,\n Accept: \"application/vnd.github.v3+json\"\n }\n });\n if (!baseRef.ok) {\n const error = await baseRef.text();\n console.error(`[Step 4] Failed to get base branch: ${error}`);\n return {\n success: false,\n error: `Failed to get base branch: ${baseRef.status}`\n };\n }\n const baseData = await baseRef.json();\n const baseSha = baseData.object.sha;\n console.log(`[Step 4] Base SHA: ${baseSha}`);\n // Create new branch\n const createBranch = await fetch(`https://api.github.com/repos/${repoOwner}/${repoName}/git/refs`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${githubToken}`,\n Accept: \"application/vnd.github.v3+json\",\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n ref: `refs/heads/${branchName}`,\n sha: baseSha\n })\n });\n if (!createBranch.ok) {\n const error = await createBranch.text();\n console.error(`[Step 4] Failed to create branch: ${error}`);\n return {\n success: false,\n error: `Failed to create branch: ${createBranch.status}`\n };\n }\n console.log(`[Step 4] Created branch: ${branchName}`);\n // For each file, fetch current content, apply changes, and commit\n for (const fileChange of fileChanges){\n console.log(`[Step 4] Processing file: ${fileChange.path}`);\n // Get current file content\n const fileResp = await fetch(`https://api.github.com/repos/${repoOwner}/${repoName}/contents/${fileChange.path}?ref=${branchName}`, {\n headers: {\n Authorization: `Bearer ${githubToken}`,\n Accept: \"application/vnd.github.v3+json\"\n }\n });\n let currentContent = \"\";\n let currentSha = \"\";\n if (fileResp.ok) {\n const fileData = await fileResp.json();\n currentSha = fileData.sha;\n currentContent = Buffer.from(fileData.content, \"base64\").toString(\"utf-8\");\n } else {\n console.log(`[Step 4] File doesn't exist, will create new file`);\n }\n // Apply the patch changes to the content\n const newContent = applyPatchChanges(currentContent, fileChange.changes);\n // Update file\n const updateFile = await fetch(`https://api.github.com/repos/${repoOwner}/${repoName}/contents/${fileChange.path}`, {\n method: \"PUT\",\n headers: {\n Authorization: `Bearer ${githubToken}`,\n Accept: \"application/vnd.github.v3+json\",\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n message: `Fix: Apply dev3000 fix for ${projectName}`,\n content: Buffer.from(newContent).toString(\"base64\"),\n branch: branchName,\n ...currentSha && {\n sha: currentSha\n }\n })\n });\n if (!updateFile.ok) {\n const error = await updateFile.text();\n console.error(`[Step 4] Failed to update file ${fileChange.path}: ${error}`);\n return {\n success: false,\n error: `Failed to update file ${fileChange.path}: ${updateFile.status}`\n };\n }\n console.log(`[Step 4] Updated file: ${fileChange.path}`);\n }\n // Create PR\n const prBody = `## Automated Fix Proposal\n\nThis PR was automatically generated by [dev3000](https://github.com/vercel-labs/dev3000) after analyzing your application.\n\n### Fix Details\nView the full analysis: [${blobUrl}](${blobUrl})\n\n${fixProposal}\n\n---\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)\n\nCo-Authored-By: Claude (dev3000) <noreply@anthropic.com>`;\n const createPR = await fetch(`https://api.github.com/repos/${repoOwner}/${repoName}/pulls`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${githubToken}`,\n Accept: \"application/vnd.github.v3+json\",\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n title: `Fix: ${projectName} - Automated fix from dev3000`,\n head: branchName,\n base: baseBranch,\n body: prBody\n })\n });\n if (!createPR.ok) {\n const error = await createPR.text();\n console.error(`[Step 4] Failed to create PR: ${error}`);\n return {\n success: false,\n error: `Failed to create PR: ${createPR.status}`\n };\n }\n const prData = await createPR.json();\n console.log(`[Step 4] Created PR: ${prData.html_url}`);\n return {\n success: true,\n prUrl: prData.html_url,\n prNumber: prData.number,\n branch: branchName\n };\n } catch (error) {\n console.error(\"[Step 4] Error creating PR:\", error);\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error)\n };\n }\n}\n/**\n * Cleanup step: Stop the sandbox\n */ export async function cleanupSandbox(cleanup) {\n console.log(\"[Cleanup] Stopping sandbox...\");\n try {\n await cleanup();\n console.log(\"[Cleanup] Sandbox stopped successfully\");\n } catch (error) {\n console.error(\"[Cleanup] Error stopping sandbox:\", error);\n // Don't throw - cleanup errors shouldn't fail the workflow\n }\n}\n"],"names":[],"mappings":"sCAMW,eAAe,EAAiB,CAAO,CAAE,CAAM,CAAE,CAAW,CAAE,CAAW,CAAE,CAAe,EACjG,QAAQ,GAAG,CAAC,CAAC,kCAAkC,EAAE,EAAY,GAAG,CAAC,EACjE,QAAQ,GAAG,CAAC,CAAC,qBAAqB,EAAE,EAAA,CAAS,EAC7C,QAAQ,GAAG,CAAC,CAAC,iBAAiB,EAAE,EAAA,CAAQ,EAExC,QAAQ,GAAG,CAAC,CAAC,qCAAqC,EAAE,CAAC,CAAC,QAAQ,GAAG,CAAC,iBAAiB,CAAA,CAAE,EACrF,QAAQ,GAAG,CAAC,CAAC,4CAA4C,EAAE,CAAC,CAAC,EAAA,CAAiB,EAC9E,QAAQ,GAAG,CAAC,CAAC,iCAAiC,EAAE,CAAC,CAAC,QAAQ,GAAG,CAAC,YAAY,CAAA,CAAE,EAC5E,QAAQ,GAAG,CAAC,CAAC,qCAAqC,EAAE,CAAC,CAAC,EAAA,CAAa,EAG/D,GAAmB,CAAC,QAAQ,GAAG,CAAC,iBAAiB,EAAE,CACnD,QAAQ,GAAG,CAAC,iBAAiB,CAAG,EAChC,QAAQ,GAAG,CAAC,CAAC,oDAAoD,CAAC,GAEtE,IAAM,EAAgB,MAAM,qBAAqB,SAC7C,SACA,EACA,WAAY,GACZ,eAAgB,OAChB,MAAO,EACX,GACA,QAAQ,GAAG,CAAC,CAAC,qCAAqC,C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M,CAAC,6BAA6B,EAAE,EAAU,CAAC,EAAE,EAAS,MAAM,CAAC,CAAE,CACxF,OAAQ,OACR,QAAS,CACL,cAAe,CAAC,OAAO,EAAE,EAAA,CAAa,CACtC,OAAQ,iCACR,eAAgB,kBACpB,EACA,KAAM,KAAK,SAAS,CAAC,CACjB,MAAO,CAAC,KAAK,EAAE,EAAY,6BAA6B,CAAC,CACzD,KAAM,EACN,KAAM,EACN,KAAM,CACV,EACJ,GACA,GAAI,CAAC,EAAS,EAAE,CAAE,CACd,IAAM,EAAQ,MAAM,EAAS,IAAI,GAEjC,OADA,QAAQ,KAAK,CAAC,CAAC,8BAA8B,EAAE,EAAA,CAAO,EAC/C,CACH,SAAS,EACT,MAAO,CAAC,qBAAqB,EAAE,EAAS,MAAM,CAAA,CAClD,AADoD,CAExD,CACA,IAAM,EAAS,MAAM,EAAS,IAAI,GAElC,OADA,QAAQ,GAAG,CAAC,CAAC,qBAAqB,EAAE,EAAO,QAAQ,CAAA,CAAE,EAC9C,CACH,SAAS,EACT,MAAO,EAAO,QAAQ,CACtB,SAAU,EAAO,MAAM,CACvB,OAAQ,CACZ,CACJ,CAAE,MAAO,EAAO,CAEZ,OADA,QAAQ,KAAK,CAAC,8BAA+B,GACtC,CACH,SAAS,EACT,MAAO,aAAiB,MAAQ,EAAM,OAAO,CAAG,OAAO,EAC3D,CACJ,CACJ,CAGW,eAAe,EAAe,CAAO,EAC5C,QAAQ,GAAG,CAAC,iCACZ,GAAI,CACA,MAAM,IACN,QAAQ,GAAG,CAAC,yCAChB,CAAE,MAAO,EAAO,CACZ,QAAQ,KAAK,CAAC,oCAAqC,EAEvD,CACJ"}
1
+ {"version":3,"sources":["../../../../mcp-server/app/api/cloud/fix-workflow/steps.ts"],"sourcesContent":["/**\n * Step functions for fix-workflow\n * Separated into their own module to avoid workflow bundler issues\n */ /**__internal_workflows{\"steps\":{\"app/api/cloud/fix-workflow/steps.ts\":{\"analyzeLogsWithAgent\":{\"stepId\":\"step//app/api/cloud/fix-workflow/steps.ts//analyzeLogsWithAgent\"},\"cleanupSandbox\":{\"stepId\":\"step//app/api/cloud/fix-workflow/steps.ts//cleanupSandbox\"},\"createD3kSandbox\":{\"stepId\":\"step//app/api/cloud/fix-workflow/steps.ts//createD3kSandbox\"},\"createGitHubPR\":{\"stepId\":\"step//app/api/cloud/fix-workflow/steps.ts//createGitHubPR\"},\"fetchRealLogs\":{\"stepId\":\"step//app/api/cloud/fix-workflow/steps.ts//fetchRealLogs\"},\"uploadToBlob\":{\"stepId\":\"step//app/api/cloud/fix-workflow/steps.ts//uploadToBlob\"}}}}*/;\n/**\n * Step 0: Create d3k sandbox with MCP tools pre-configured\n * Also captures a \"before\" screenshot of the app\n */ export async function createD3kSandbox(repoUrl, branch, projectName, vercelToken, vercelOidcToken) {\n console.log(`[Step 0] Creating d3k sandbox for ${projectName}...`);\n console.log(`[Step 0] Repository: ${repoUrl}`);\n console.log(`[Step 0] Branch: ${branch}`);\n // Log available token types\n console.log(`[Step 0] VERCEL_OIDC_TOKEN from env: ${!!process.env.VERCEL_OIDC_TOKEN}`);\n console.log(`[Step 0] VERCEL_OIDC_TOKEN passed as param: ${!!vercelOidcToken}`);\n console.log(`[Step 0] VERCEL_TOKEN available: ${!!process.env.VERCEL_TOKEN}`);\n console.log(`[Step 0] User access token provided: ${!!vercelToken}`);\n // Set VERCEL_OIDC_TOKEN if passed from workflow context\n // This is necessary because workflow steps don't automatically inherit environment variables\n if (vercelOidcToken && !process.env.VERCEL_OIDC_TOKEN) {\n process.env.VERCEL_OIDC_TOKEN = vercelOidcToken;\n console.log(`[Step 0] Set VERCEL_OIDC_TOKEN from workflow context`);\n }\n const sandboxResult = await createD3kSandboxUtil({\n repoUrl,\n branch,\n projectDir: \"\",\n packageManager: \"pnpm\",\n debug: true\n });\n console.log(`[Step 0] Sandbox created successfully`);\n console.log(`[Step 0] Dev URL: ${sandboxResult.devUrl}`);\n console.log(`[Step 0] MCP URL: ${sandboxResult.mcpUrl}`);\n // Get the chromium path for screenshots\n console.log(`[Step 0] Getting Chromium path for screenshots...`);\n let chromiumPath = \"/tmp/chromium\";\n try {\n const chromiumResult = await runSandboxCommand(sandboxResult.sandbox, \"node\", [\n \"-e\",\n \"require('@sparticuz/chromium').executablePath().then(p => console.log(p))\"\n ]);\n if (chromiumResult.exitCode === 0 && chromiumResult.stdout.trim()) {\n chromiumPath = chromiumResult.stdout.trim();\n console.log(`[Step 0] Chromium path: ${chromiumPath}`);\n }\n } catch {\n console.log(`[Step 0] Could not get chromium path, using default: ${chromiumPath}`);\n }\n // CRITICAL DIAGNOSTIC: Test Chrome with EXACT d3k command\n // d3k uses: --user-data-dir, no --remote-debugging-address, loading page, etc.\n console.log(`[Step 0] ===== CHROMIUM CDP TEST (d3k exact command) =====`);\n try {\n const chromeTestScript = `\n exec 2>&1\n echo \"=== Chromium CDP Test (d3k exact command) ===\"\n echo \"Chromium path: ${chromiumPath}\"\n echo \"\"\n\n # Create user-data-dir like d3k does\n USER_DATA_DIR=\"/tmp/d3k-test-profile\"\n mkdir -p \"$USER_DATA_DIR\"\n echo \"1. Created user-data-dir: $USER_DATA_DIR\"\n\n # Create loading page like d3k does\n LOADING_DIR=\"/tmp/dev3000-loading\"\n mkdir -p \"$LOADING_DIR\"\n cat > \"$LOADING_DIR/loading.html\" << 'LOADINGHTML'\n<!DOCTYPE html>\n<html>\n<head><title>Loading...</title></head>\n<body><h1>Loading dev3000...</h1></body>\n</html>\nLOADINGHTML\n echo \"2. Created loading page: $LOADING_DIR/loading.html\"\n echo \"\"\n\n # Use EXACT d3k command (from cdp-monitor.ts)\n # Note: d3k does NOT use --remote-debugging-address\n echo \"3. Starting Chrome with d3k's exact args...\"\n echo \" Command: ${chromiumPath} --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\"\n\n timeout 15 \"${chromiumPath}\" \\\\\n --remote-debugging-port=9222 \\\\\n --user-data-dir=\"$USER_DATA_DIR\" \\\\\n --no-first-run \\\\\n --no-default-browser-check \\\\\n --disable-component-extensions-with-background-pages \\\\\n --disable-background-networking \\\\\n --disable-sync \\\\\n --metrics-recording-only \\\\\n --disable-default-apps \\\\\n --disable-session-crashed-bubble \\\\\n --disable-restore-session-state \\\\\n --headless=new \\\\\n --no-sandbox \\\\\n --disable-setuid-sandbox \\\\\n --disable-gpu \\\\\n --disable-dev-shm-usage \\\\\n \"file://$LOADING_DIR/loading.html\" &\n PID=$!\n echo \" Chrome PID: $PID\"\n sleep 3\n echo \"\"\n\n echo \"4. Checking if Chrome is still running...\"\n if ps -p $PID > /dev/null 2>&1; then\n echo \" Chrome is RUNNING after 3s\"\n echo \"\"\n echo \"5. Trying CDP (note: d3k doesn't use --remote-debugging-address)...\"\n echo \" Trying 127.0.0.1...\"\n curl -s --max-time 5 http://127.0.0.1:9222/json/version 2>&1 || echo \" 127.0.0.1 failed\"\n echo \"\"\n echo \" Trying localhost...\"\n curl -s --max-time 5 http://localhost:9222/json/version 2>&1 || echo \" localhost failed\"\n echo \"\"\n echo \"6. Checking what's listening on 9222...\"\n ss -tlnp 2>/dev/null | grep 9222 || netstat -tlnp 2>/dev/null | grep 9222 || echo \" Could not check listening ports\"\n echo \"\"\n echo \"7. Killing test Chrome...\"\n kill $PID 2>/dev/null\n else\n echo \" Chrome DIED within 3s\"\n wait $PID 2>/dev/null\n EXIT_CODE=$?\n echo \" Exit code: $EXIT_CODE\"\n echo \"\"\n echo \" Checking for crash logs...\"\n ls -la \"$USER_DATA_DIR\" 2>&1 | head -10 || echo \" No user-data-dir\"\n fi\n echo \"\"\n echo \"=== End d3k exact command test ===\"\n `;\n const chromeTest = await runSandboxCommand(sandboxResult.sandbox, \"bash\", [\n \"-c\",\n chromeTestScript\n ]);\n console.log(`[Step 0] d3k Chrome test (exit ${chromeTest.exitCode}):\\n${chromeTest.stdout || \"(no output)\"}`);\n if (chromeTest.stderr) console.log(`[Step 0] d3k Chrome test stderr: ${chromeTest.stderr}`);\n } catch (error) {\n console.log(`[Step 0] d3k Chrome test error: ${error instanceof Error ? error.message : String(error)}`);\n }\n console.log(`[Step 0] ===== END d3k EXACT COMMAND TEST =====`);\n // Capture \"BEFORE\" screenshot - this shows the app before any fixes\n console.log(`[Step 0] Capturing BEFORE screenshot...`);\n let beforeScreenshotUrl = null;\n try {\n const beforeBase64 = await captureScreenshotInSandbox(sandboxResult.sandbox, \"http://localhost:3000\", chromiumPath, \"before\");\n if (beforeBase64) {\n beforeScreenshotUrl = await uploadScreenshot(beforeBase64, \"before\", projectName);\n }\n } catch (error) {\n console.log(`[Step 0] Before screenshot failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n // Now capture CLS and errors using MCP from INSIDE the sandbox\n console.log(`[Step 0] Capturing CLS metrics from inside sandbox...`);\n let clsData = null;\n let mcpError = null;\n try {\n // Call fix_my_app MCP tool via curl from inside the sandbox\n // This avoids network isolation issues - we're calling localhost:3684 from within the sandbox\n const mcpCommand = `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}}}'`;\n console.log(`[Step 0] Executing MCP command inside sandbox...`);\n console.log(`[Step 0] MCP command: ${mcpCommand.substring(0, 200)}...`);\n let stdout = \"\";\n let stderr = \"\";\n let exitCode = -1;\n try {\n const result = await runSandboxCommand(sandboxResult.sandbox, \"bash\", [\n \"-c\",\n mcpCommand\n ]);\n stdout = result.stdout;\n stderr = result.stderr;\n exitCode = result.exitCode;\n console.log(`[Step 0] MCP command exit code: ${exitCode}`);\n console.log(`[Step 0] MCP stdout length: ${stdout.length} bytes`);\n if (stderr) {\n console.log(`[Step 0] MCP stderr: ${stderr.substring(0, 500)}`);\n }\n } catch (runCommandError) {\n const errorMsg = runCommandError instanceof Error ? runCommandError.message : String(runCommandError);\n console.log(`[Step 0] sandbox.runCommand threw: ${errorMsg}`);\n mcpError = `sandbox.runCommand failed: ${errorMsg}`;\n }\n if (exitCode === 0 && stdout) {\n try {\n const mcpResponse = JSON.parse(stdout);\n if (mcpResponse.result?.content) {\n // Extract the actual data from MCP response\n const contentArray = mcpResponse.result.content;\n for (const item of contentArray){\n if (item.type === \"text\" && item.text) {\n // Try to parse the text as JSON if it contains structured data\n try {\n clsData = JSON.parse(item.text);\n console.log(`[Step 0] Successfully parsed CLS data`);\n break;\n } catch {\n // If not JSON, treat as plain text\n clsData = {\n rawOutput: item.text\n };\n }\n }\n }\n }\n console.log(`[Step 0] CLS data captured:`, JSON.stringify(clsData).substring(0, 500));\n } catch (parseError) {\n mcpError = `Failed to parse MCP response: ${parseError instanceof Error ? parseError.message : String(parseError)}`;\n console.log(`[Step 0] ${mcpError}`);\n console.log(`[Step 0] Raw stdout: ${stdout.substring(0, 1000)}`);\n }\n } else if (exitCode !== 0 && !mcpError) {\n mcpError = `MCP command failed with exit code ${exitCode}`;\n console.log(`[Step 0] ${mcpError}`);\n if (stderr) {\n console.log(`[Step 0] stderr: ${stderr}`);\n }\n }\n } catch (error) {\n mcpError = `MCP execution error: ${error instanceof Error ? error.message : String(error)}`;\n console.log(`[Step 0] ${mcpError}`);\n }\n // Dump all sandbox logs before returning for debugging\n console.log(`[Step 0] === Dumping sandbox logs before returning ===`);\n try {\n const logsResult = await runSandboxCommand(sandboxResult.sandbox, \"sh\", [\n \"-c\",\n '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\"'\n ]);\n console.log(logsResult.stdout);\n } catch (logsError) {\n console.log(`[Step 0] Failed to dump logs: ${logsError instanceof Error ? logsError.message : String(logsError)}`);\n }\n console.log(`[Step 0] === End sandbox log dump ===`);\n // Capture git diff from sandbox - this shows any changes made by d3k\n console.log(`[Step 0] Capturing git diff from sandbox...`);\n let gitDiff = null;\n try {\n const diffResult = await runSandboxCommand(sandboxResult.sandbox, \"sh\", [\n \"-c\",\n \"cd /vercel/sandbox && git diff --no-color 2>/dev/null || echo 'No git diff available'\"\n ]);\n if (diffResult.exitCode === 0 && diffResult.stdout.trim() && diffResult.stdout.trim() !== \"No git diff available\") {\n gitDiff = diffResult.stdout.trim();\n console.log(`[Step 0] Git diff captured (${gitDiff.length} chars)`);\n console.log(`[Step 0] Git diff preview:\\n${gitDiff.substring(0, 500)}...`);\n } else {\n console.log(`[Step 0] No git changes detected in sandbox`);\n }\n } catch (diffError) {\n console.log(`[Step 0] Failed to capture git diff: ${diffError instanceof Error ? diffError.message : String(diffError)}`);\n }\n // Note: We cannot return the cleanup function or sandbox object as they're not serializable\n // Sandbox cleanup will happen automatically when the sandbox times out\n return {\n mcpUrl: sandboxResult.mcpUrl,\n devUrl: sandboxResult.devUrl,\n bypassToken: sandboxResult.bypassToken,\n clsData,\n mcpError,\n beforeScreenshotUrl,\n chromiumPath,\n gitDiff\n };\n}\n/**\n * Step 1: Use browser automation to capture real errors\n * Uses d3k MCP server in sandbox (if available) or AI Gateway for browser automation\n */ export async function fetchRealLogs(mcpUrlOrDevUrl, bypassToken, sandboxDevUrl, clsData, mcpError, beforeScreenshotUrlFromStep0) {\n // If we already have CLS data from Step 0, use it along with the screenshot\n if (clsData) {\n console.log(\"[Step 1] Using CLS data captured in Step 0\");\n if (beforeScreenshotUrlFromStep0) {\n console.log(`[Step 1] Before screenshot from Step 0: ${beforeScreenshotUrlFromStep0}`);\n }\n return {\n logAnalysis: JSON.stringify(clsData, null, 2),\n beforeScreenshotUrl: beforeScreenshotUrlFromStep0 || null\n };\n }\n // If there was an MCP error in Step 0, log it\n if (mcpError) {\n console.log(`[Step 1] Note: MCP error from Step 0: ${mcpError}`);\n }\n // Determine if we're using sandbox MCP or direct dev URL\n const isSandbox = !!sandboxDevUrl;\n const devUrl = sandboxDevUrl || mcpUrlOrDevUrl;\n const mcpUrl = isSandbox ? mcpUrlOrDevUrl : null;\n console.log(`[Step 1] Fetching logs from: ${devUrl}`);\n console.log(`[Step 1] Using sandbox: ${isSandbox ? \"yes\" : \"no\"}`);\n if (mcpUrl) {\n console.log(`[Step 1] MCP URL: ${mcpUrl}`);\n }\n console.log(`[Step 1] Bypass token: ${bypassToken ? \"provided\" : \"not provided\"}`);\n try {\n // Construct URL with bypass token if provided\n const urlWithBypass = bypassToken ? `${devUrl}?x-vercel-protection-bypass=${bypassToken}` : devUrl;\n console.log(`[Step 1] Final URL: ${urlWithBypass.replace(bypassToken || \"\", \"***\")}`);\n if (isSandbox && mcpUrl) {\n // Use d3k MCP server in sandbox - capture CLS metrics and errors\n console.log(\"[Step 1] Using d3k MCP server to capture CLS metrics and errors...\");\n // First, validate MCP server access and list available tools\n // Use a 30-second timeout to avoid hanging the entire workflow\n console.log(\"[Step 1] Validating d3k MCP server access...\");\n const validationController = new AbortController();\n const validationTimeout = setTimeout(()=>validationController.abort(), 30000);\n try {\n const toolsResponse = await fetch(`${mcpUrl}/mcp`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json, text/event-stream\"\n },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: 0,\n method: \"tools/list\"\n }),\n signal: validationController.signal\n });\n clearTimeout(validationTimeout);\n if (toolsResponse.ok) {\n const toolsText = await toolsResponse.text();\n try {\n // Parse SSE response format: \"event: message\\ndata: {...}\\n\\n\"\n let toolsData = null;\n const lines = toolsText.split(\"\\n\");\n for (const line of lines){\n if (line.startsWith(\"data: \")) {\n try {\n toolsData = JSON.parse(line.substring(6));\n break;\n } catch {\n // Continue to next line\n }\n }\n }\n // Fallback: try parsing the whole response as JSON (non-SSE format)\n if (!toolsData) {\n toolsData = JSON.parse(toolsText);\n }\n const toolNames = toolsData.result?.tools?.map((t)=>t.name) || [];\n console.log(`[Step 1] ✅ d3k MCP server accessible`);\n console.log(`[Step 1] Available tools (${toolNames.length}): ${toolNames.join(\", \")}`);\n // Check for expected chrome-devtools and nextjs-dev tools\n const hasChrome = toolNames.some((name)=>name.includes(\"chrome-devtools\"));\n const hasNextjs = toolNames.some((name)=>name.includes(\"nextjs\"));\n const hasFixMyApp = toolNames.includes(\"fix_my_app\");\n console.log(`[Step 1] Chrome DevTools MCP: ${hasChrome ? \"✅\" : \"❌\"}`);\n console.log(`[Step 1] Next.js DevTools MCP: ${hasNextjs ? \"✅\" : \"❌\"}`);\n console.log(`[Step 1] fix_my_app tool: ${hasFixMyApp ? \"✅\" : \"❌\"}`);\n } catch {\n console.log(`[Step 1] MCP server responded but couldn't parse tools list: ${toolsText.substring(0, 200)}`);\n }\n } else {\n console.log(`[Step 1] ⚠️ MCP server not accessible: ${toolsResponse.status}`);\n }\n } catch (error) {\n clearTimeout(validationTimeout);\n const errorMsg = error instanceof Error ? error.message : String(error);\n const isTimeout = error instanceof Error && error.name === \"AbortError\";\n console.log(`[Step 1] ⚠️ Failed to validate MCP server: ${isTimeout ? \"Timed out after 30s\" : errorMsg}`);\n }\n // Navigate to the app to generate logs (with 30s timeout)\n console.log(\"[Step 1] Navigating browser to app URL...\");\n const navController = new AbortController();\n const navTimeout = setTimeout(()=>navController.abort(), 30000);\n try {\n const navResponse = await fetch(`${mcpUrl}/mcp`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json, text/event-stream\"\n },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: 0,\n method: \"tools/call\",\n params: {\n name: \"execute_browser_action\",\n arguments: {\n action: \"navigate\",\n params: {\n url: urlWithBypass\n }\n }\n }\n }),\n signal: navController.signal\n });\n clearTimeout(navTimeout);\n if (navResponse.ok) {\n console.log(\"[Step 1] Browser navigation completed\");\n } else {\n console.log(`[Step 1] Browser navigation failed: ${navResponse.status}`);\n }\n } catch (navError) {\n clearTimeout(navTimeout);\n const isTimeout = navError instanceof Error && navError.name === \"AbortError\";\n console.log(`[Step 1] Browser navigation error: ${isTimeout ? \"Timed out after 30s\" : navError instanceof Error ? navError.message : String(navError)}`);\n }\n // Wait for page to fully load\n console.log(\"[Step 1] Waiting 5s for page load...\");\n await new Promise((resolve)=>setTimeout(resolve, 5000));\n // Capture \"before\" screenshot to prove the page loaded and for later comparison\n let beforeScreenshotUrl = null;\n console.log(\"[Step 1] Capturing 'before' screenshot...\");\n const screenshotController = new AbortController();\n const screenshotTimeout = setTimeout(()=>screenshotController.abort(), 30000);\n try {\n const screenshotResponse = await fetch(`${mcpUrl}/mcp`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json, text/event-stream\"\n },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: 0,\n method: \"tools/call\",\n params: {\n name: \"chrome-devtools_take_snapshot\",\n arguments: {}\n }\n }),\n signal: screenshotController.signal\n });\n clearTimeout(screenshotTimeout);\n if (screenshotResponse.ok) {\n const screenshotText = await screenshotResponse.text();\n // Parse SSE response to get screenshot data\n const lines = screenshotText.split(\"\\n\");\n for (const line of lines){\n if (line.startsWith(\"data: \")) {\n try {\n const json = JSON.parse(line.substring(6));\n if (json.result?.content) {\n for (const content of json.result.content){\n if (content.type === \"image\" && content.data) {\n // Upload base64 image to Vercel Blob\n const imageBuffer = Buffer.from(content.data, \"base64\");\n const timestamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n const filename = `screenshot-before-${timestamp}.png`;\n const blob = await put(filename, imageBuffer, {\n access: \"public\",\n contentType: \"image/png\"\n });\n beforeScreenshotUrl = blob.url;\n console.log(`[Step 1] ✅ Before screenshot uploaded: ${beforeScreenshotUrl}`);\n }\n }\n }\n } catch {\n // Continue parsing other lines\n }\n }\n }\n if (!beforeScreenshotUrl) {\n console.log(`[Step 1] Screenshot response received but no image data found`);\n console.log(`[Step 1] Response preview: ${screenshotText.substring(0, 500)}`);\n }\n } else {\n console.log(`[Step 1] Screenshot request failed: ${screenshotResponse.status}`);\n }\n } catch (error) {\n clearTimeout(screenshotTimeout);\n const isTimeout = error instanceof Error && error.name === \"AbortError\";\n console.log(`[Step 1] Screenshot capture error: ${isTimeout ? \"Timed out after 30s\" : error instanceof Error ? error.message : String(error)}`);\n }\n // Check d3k logs to see if it's capturing data (with 15s timeout)\n console.log(\"[Step 1] Fetching d3k logs from sandbox to verify it's working...\");\n const logsController = new AbortController();\n const logsTimeout = setTimeout(()=>logsController.abort(), 15000);\n try {\n const logsResponse = await fetch(`${mcpUrl}/api/logs`, {\n signal: logsController.signal\n });\n clearTimeout(logsTimeout);\n if (logsResponse.ok) {\n const logsText = await logsResponse.text();\n console.log(`[Step 1] d3k logs (last 1000 chars):\\n${logsText.slice(-1000)}`);\n } else {\n console.log(`[Step 1] Could not fetch d3k logs: ${logsResponse.status}`);\n }\n } catch (error) {\n clearTimeout(logsTimeout);\n const isTimeout = error instanceof Error && error.name === \"AbortError\";\n console.log(`[Step 1] Failed to fetch d3k logs: ${isTimeout ? \"Timed out after 15s\" : error instanceof Error ? error.message : String(error)}`);\n }\n // Call fix_my_app with focusArea='performance' to capture CLS and jank\n console.log(\"[Step 1] Calling fix_my_app with focusArea='performance'...\");\n // Set a 3-minute timeout for the MCP call\n const controller = new AbortController();\n const timeoutId = setTimeout(()=>controller.abort(), 3 * 60 * 1000);\n try {\n const mcpResponse = await fetch(`${mcpUrl}/mcp`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json, text/event-stream\"\n },\n body: JSON.stringify({\n jsonrpc: \"2.0\",\n id: 1,\n method: \"tools/call\",\n params: {\n name: \"fix_my_app\",\n arguments: {\n mode: \"snapshot\",\n focusArea: \"performance\",\n timeRangeMinutes: 5,\n returnRawData: false\n }\n }\n }),\n signal: controller.signal\n });\n clearTimeout(timeoutId);\n if (!mcpResponse.ok) {\n throw new Error(`MCP request failed: ${mcpResponse.status}`);\n }\n // Parse SSE response\n const text = await mcpResponse.text();\n console.log(`[Step 1] fix_my_app response length: ${text.length} bytes`);\n console.log(`[Step 1] fix_my_app response preview (first 500 chars):\\n${text.substring(0, 500)}`);\n const lines = text.split(\"\\n\");\n console.log(`[Step 1] Response split into ${lines.length} lines`);\n let logAnalysis = \"\";\n let linesProcessed = 0;\n let contentBlocks = 0;\n for (const line of lines){\n if (line.startsWith(\"data: \")) {\n linesProcessed++;\n try {\n const json = JSON.parse(line.substring(6));\n console.log(`[Step 1] Parsed JSON line ${linesProcessed}:`, JSON.stringify(json).substring(0, 200));\n if (json.result?.content) {\n for (const content of json.result.content){\n if (content.type === \"text\") {\n contentBlocks++;\n logAnalysis += content.text;\n console.log(`[Step 1] Added text content block ${contentBlocks}, length: ${content.text.length}`);\n }\n }\n } else if (json.error) {\n console.log(`[Step 1] ERROR in response: ${JSON.stringify(json.error)}`);\n }\n } catch (error) {\n console.log(`[Step 1] Failed to parse JSON line ${linesProcessed}: ${error instanceof Error ? error.message : String(error)}`);\n console.log(`[Step 1] Problem line: ${line.substring(0, 200)}`);\n }\n }\n }\n console.log(`[Step 1] Processed ${linesProcessed} data lines, ${contentBlocks} content blocks`);\n console.log(`[Step 1] Got ${logAnalysis.length} chars from fix_my_app (performance analysis)`);\n if (logAnalysis.length === 0) {\n console.log(`[Step 1] WARNING: fix_my_app returned NO data. Full response:\\n${text}`);\n }\n return {\n logAnalysis: `d3k Performance Analysis for ${devUrl}\\n\\n${logAnalysis}`,\n beforeScreenshotUrl\n };\n } catch (error) {\n clearTimeout(timeoutId);\n if (error instanceof Error && error.name === \"AbortError\") {\n console.log(\"[Step 1] fix_my_app timed out after 3 minutes, using fallback method\");\n // Fall through to fallback method below\n } else {\n console.log(`[Step 1] fix_my_app error: ${error instanceof Error ? error.message : String(error)}`);\n // Fall through to fallback method below\n }\n }\n }\n // Fallback: Use AI Gateway with browser automation prompting\n console.log(\"[Step 1] Using AI Gateway with browser automation...\");\n const gateway = createGateway({\n apiKey: process.env.AI_GATEWAY_API_KEY,\n baseURL: \"https://ai-gateway.vercel.sh/v1/ai\"\n });\n const model = gateway(\"anthropic/claude-sonnet-4-20250514\");\n const prompt = `You are a web application debugger with access to browser automation tools via Playwright MCP.\n\nYour task is to visit this URL and capture any errors, warnings, or issues:\n${urlWithBypass}\n\nSteps to follow:\n1. Use browser_eval with action=\"start\" to start the browser\n2. Use browser_eval with action=\"navigate\" and params={url: \"${urlWithBypass}\"} to navigate to the page\n3. Wait a few seconds for the page to fully load and JavaScript to execute\n4. Use browser_eval with action=\"console_messages\" to get all browser console output (errors, warnings, logs)\n5. Use browser_eval with action=\"screenshot\" to capture a screenshot\n6. Use browser_eval with action=\"close\" to close the browser\n\nAnalyze the console messages and provide a detailed report including:\n- All console errors (with full stack traces if available)\n- All console warnings\n- HTTP status codes or network errors\n- Any visual issues you can identify from the screenshot\n- Screenshot URL if captured\n\nFormat your response as a clear, structured report that helps identify what's broken in the application.`;\n const { text } = await generateText({\n model,\n prompt,\n toolChoice: \"auto\",\n // @ts-expect-error - AI SDK types for maxTokens are incomplete\n maxTokens: 4000\n });\n console.log(`[Step 1] Browser automation response (first 500 chars): ${text.substring(0, 500)}...`);\n return {\n logAnalysis: `Browser Automation Analysis for ${devUrl}\\n\\n${text}`,\n beforeScreenshotUrl: null\n };\n } catch (error) {\n console.error(\"[Step 1] Error with browser automation:\", error);\n // Fallback to simple fetch if browser automation fails\n console.log(\"[Step 1] Falling back to simple HTTP fetch...\");\n try {\n const urlWithBypass = bypassToken ? `${devUrl}?x-vercel-protection-bypass=${bypassToken}` : devUrl;\n const headers = {\n \"User-Agent\": \"dev3000-cloud-fix/1.0\",\n Accept: \"text/html,application/json,*/*\"\n };\n if (bypassToken) {\n headers[\"x-vercel-protection-bypass\"] = bypassToken;\n }\n const response = await fetch(urlWithBypass, {\n method: \"GET\",\n headers\n });\n const body = await response.text();\n // Extract and log page title from HTML\n const titleMatch = body.match(/<title[^>]*>([^<]*)<\\/title>/i);\n const pageTitle = titleMatch ? titleMatch[1].trim() : \"(no title found)\";\n console.log(`[Step 1] HTTP fallback - Page title: \"${pageTitle}\"`);\n let logAnalysis = `Dev Server URL: ${devUrl}\\n`;\n logAnalysis += `Page Title: ${pageTitle}\\n`;\n logAnalysis += `HTTP Status: ${response.status} ${response.statusText}\\n\\n`;\n logAnalysis += `Note: Browser automation failed, using fallback HTTP fetch.\\n\\n`;\n if (!response.ok) {\n logAnalysis += `ERROR: HTTP ${response.status} ${response.statusText}\\n\\n`;\n }\n if (body.includes(\"ReferenceError\") || body.includes(\"Error\") || body.includes(\"error\")) {\n logAnalysis += `Response body contains error information:\\n${body.substring(0, 5000)}\\n\\n`;\n } else if (!response.ok) {\n logAnalysis += `Response body:\\n${body.substring(0, 2000)}\\n\\n`;\n } else {\n logAnalysis += \"No errors detected in response.\\n\";\n }\n return {\n logAnalysis,\n beforeScreenshotUrl: null\n };\n } catch (fallbackError) {\n const errorMessage = fallbackError instanceof Error ? fallbackError.message : String(fallbackError);\n return {\n logAnalysis: `Failed to fetch logs from ${devUrl}\\n\\nError: ${errorMessage}\\n\\nThis may indicate the dev server is not accessible or has crashed.`,\n beforeScreenshotUrl: null\n };\n }\n }\n}\n/**\n * Step 2: Invoke AI agent to analyze logs and propose fixes\n * Uses AI SDK with AI Gateway for multi-model support\n */ export async function analyzeLogsWithAgent(logAnalysis, devUrl) {\n console.log(\"[Step 2] Invoking AI agent to analyze logs...\");\n // Create AI Gateway instance\n const gateway = createGateway({\n apiKey: process.env.AI_GATEWAY_API_KEY,\n baseURL: \"https://ai-gateway.vercel.sh/v1/ai\"\n });\n // Use Claude Sonnet 4 via AI Gateway\n const model = gateway(\"anthropic/claude-sonnet-4-20250514\");\n const prompt = `You are a skilled software engineer debugging an application.\n\nThe dev server is running at: ${devUrl}\n\nHere's the log analysis from the MCP fix_my_app tool:\n${logAnalysis}\n\nYour task:\n1. Identify the most critical error or issue from the logs\n2. Determine the root cause\n3. Propose a specific code fix with file paths and changes\n4. Create a git-style unified diff that can be applied with 'git apply'\n5. Explain why this fix will resolve the issue\n\nFormat your response EXACTLY as follows:\n\n## Issue\n[Brief description of the issue]\n\n## Root Cause\n[Explanation of what's causing the issue]\n\n## Proposed Fix\n[High-level explanation of the fix]\n\n## Git Patch\n\\`\\`\\`diff\n[Full unified diff format that can be applied with 'git apply' or 'patch']\n[Include file paths, line numbers, and exact changes]\n[Example format:]\n[diff --git a/path/to/file.ts b/path/to/file.ts]\n[index abc123..def456 100644]\n[--- a/path/to/file.ts]\n[+++ b/path/to/file.ts]\n[@@ -10,7 +10,7 @@ function example() {]\n[ unchanged line]\n[- old line to remove]\n[+ new line to add]\n[ unchanged line]\n\\`\\`\\`\n\n## Reasoning\n[Why this fix will work]\n\nIMPORTANT:\n- The Git Patch section must be a valid unified diff that can be applied directly with 'git apply'.\n- If no errors are found, respond with \"✅ **SYSTEM HEALTHY** - No errors found\" and do NOT include a Git Patch section.\n- Only include a Git Patch if there are actual issues that need fixing.`;\n const { text } = await generateText({\n model,\n prompt\n });\n console.log(`[Step 2] AI agent response (first 500 chars): ${text.substring(0, 500)}...`);\n return text;\n}\n/**\n * Step 3: Upload fix proposal to blob storage and return URL\n */ export async function uploadToBlob(fixProposal, projectName, logAnalysis, devUrl, beforeScreenshotUrl, gitDiff) {\n console.log(\"[Step 3] Uploading fix proposal to blob storage...\");\n if (beforeScreenshotUrl) {\n console.log(`[Step 3] Including before screenshot: ${beforeScreenshotUrl}`);\n }\n if (gitDiff) {\n console.log(`[Step 3] Including git diff (${gitDiff.length} chars)`);\n }\n // Create screenshot section if we have a screenshot\n const screenshotSection = beforeScreenshotUrl ? `## Before Screenshot\n\nThis screenshot was captured when the sandbox dev server first loaded, proving the page rendered successfully.\n\n![Before Screenshot](${beforeScreenshotUrl})\n\n---\n\n` : \"\";\n // Create git diff section if we have a diff from the sandbox\n const gitDiffSection = gitDiff ? `## Actual Git Diff from Sandbox\n\nThe following diff shows the actual changes made by d3k in the sandbox environment:\n\n\\`\\`\\`diff\n${gitDiff}\n\\`\\`\\`\n\n---\n\n` : \"\";\n // Create enhanced markdown with full context and attribution\n const timestamp = new Date().toISOString();\n const enhancedMarkdown = `# Fix Proposal for ${projectName}\n\n**Generated**: ${timestamp}\n\n**Powered by**: [dev3000](https://github.com/vercel-labs/dev3000) with Claude Code\n\n**Dev Server**: ${devUrl}\n\n---\n\n${screenshotSection}${gitDiffSection}## Original Log Analysis\n\n\\`\\`\\`\n${logAnalysis}\n\\`\\`\\`\n\n---\n\n${fixProposal}\n\n---\n\n## Attribution\n\nThis fix proposal was automatically generated by [dev3000](https://github.com/vercel-labs/dev3000),\nan AI-powered debugging tool that analyzes your application logs and suggests fixes.\n\n**Co-Authored-By**: Claude (dev3000) <noreply@anthropic.com>\n\n### About dev3000\n\ndev3000 monitors your development server, captures errors in real-time, and uses AI to:\n- Analyze error logs and stack traces\n- Identify root causes\n- Generate actionable fix proposals with git patches\n- Suggest specific code changes\n\nLearn more at https://github.com/vercel-labs/dev3000\n`;\n // Upload to Vercel Blob Storage\n const filenameTimestamp = timestamp.replace(/[:.]/g, \"-\");\n const filename = `fix-${projectName}-${filenameTimestamp}.md`;\n const blob = await put(filename, enhancedMarkdown, {\n access: \"public\",\n contentType: \"text/markdown\"\n });\n console.log(`[Step 3] Fix proposal uploaded to: ${blob.url}`);\n return {\n success: true,\n projectName,\n fixProposal,\n blobUrl: blob.url,\n beforeScreenshotUrl: beforeScreenshotUrl || null,\n message: \"Fix analysis completed and uploaded to blob storage\"\n };\n}\n/**\n * Step 4: Create GitHub PR with the fix\n * Uses GitHub API to create a branch, commit the patch, and open a PR\n */ export async function createGitHubPR(fixProposal, blobUrl, repoOwner, repoName, baseBranch, projectName) {\n console.log(`[Step 4] Creating GitHub PR for ${repoOwner}/${repoName}...`);\n const githubToken = process.env.GITHUB_TOKEN;\n if (!githubToken) {\n console.error(\"[Step 4] GITHUB_TOKEN not found in environment\");\n return {\n success: false,\n error: \"GitHub token not configured\"\n };\n }\n try {\n // Extract the git patch from the fix proposal\n const patchMatch = fixProposal.match(/```diff\\n([\\s\\S]*?)\\n```/);\n if (!patchMatch) {\n console.error(\"[Step 4] No git patch found in fix proposal\");\n return {\n success: false,\n error: \"No git patch found in fix proposal\"\n };\n }\n const patch = patchMatch[1];\n console.log(`[Step 4] Extracted patch (${patch.length} chars)`);\n // Parse the patch to extract file changes\n const fileChanges = parsePatchToFileChanges(patch);\n if (fileChanges.length === 0) {\n console.error(\"[Step 4] Failed to parse any file changes from patch\");\n return {\n success: false,\n error: \"Failed to parse file changes from patch\"\n };\n }\n console.log(`[Step 4] Parsed ${fileChanges.length} file change(s)`);\n // Create a unique branch name\n const branchName = `dev3000-fix-${projectName}-${Date.now()}`;\n console.log(`[Step 4] Branch name: ${branchName}`);\n // Get the base branch SHA\n const baseRef = await fetch(`https://api.github.com/repos/${repoOwner}/${repoName}/git/ref/heads/${baseBranch}`, {\n headers: {\n Authorization: `Bearer ${githubToken}`,\n Accept: \"application/vnd.github.v3+json\"\n }\n });\n if (!baseRef.ok) {\n const error = await baseRef.text();\n console.error(`[Step 4] Failed to get base branch: ${error}`);\n return {\n success: false,\n error: `Failed to get base branch: ${baseRef.status}`\n };\n }\n const baseData = await baseRef.json();\n const baseSha = baseData.object.sha;\n console.log(`[Step 4] Base SHA: ${baseSha}`);\n // Create new branch\n const createBranch = await fetch(`https://api.github.com/repos/${repoOwner}/${repoName}/git/refs`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${githubToken}`,\n Accept: \"application/vnd.github.v3+json\",\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n ref: `refs/heads/${branchName}`,\n sha: baseSha\n })\n });\n if (!createBranch.ok) {\n const error = await createBranch.text();\n console.error(`[Step 4] Failed to create branch: ${error}`);\n return {\n success: false,\n error: `Failed to create branch: ${createBranch.status}`\n };\n }\n console.log(`[Step 4] Created branch: ${branchName}`);\n // For each file, fetch current content, apply changes, and commit\n for (const fileChange of fileChanges){\n console.log(`[Step 4] Processing file: ${fileChange.path}`);\n // Get current file content\n const fileResp = await fetch(`https://api.github.com/repos/${repoOwner}/${repoName}/contents/${fileChange.path}?ref=${branchName}`, {\n headers: {\n Authorization: `Bearer ${githubToken}`,\n Accept: \"application/vnd.github.v3+json\"\n }\n });\n let currentContent = \"\";\n let currentSha = \"\";\n if (fileResp.ok) {\n const fileData = await fileResp.json();\n currentSha = fileData.sha;\n currentContent = Buffer.from(fileData.content, \"base64\").toString(\"utf-8\");\n } else {\n console.log(`[Step 4] File doesn't exist, will create new file`);\n }\n // Apply the patch changes to the content\n const newContent = applyPatchChanges(currentContent, fileChange.changes);\n // Update file\n const updateFile = await fetch(`https://api.github.com/repos/${repoOwner}/${repoName}/contents/${fileChange.path}`, {\n method: \"PUT\",\n headers: {\n Authorization: `Bearer ${githubToken}`,\n Accept: \"application/vnd.github.v3+json\",\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n message: `Fix: Apply dev3000 fix for ${projectName}`,\n content: Buffer.from(newContent).toString(\"base64\"),\n branch: branchName,\n ...currentSha && {\n sha: currentSha\n }\n })\n });\n if (!updateFile.ok) {\n const error = await updateFile.text();\n console.error(`[Step 4] Failed to update file ${fileChange.path}: ${error}`);\n return {\n success: false,\n error: `Failed to update file ${fileChange.path}: ${updateFile.status}`\n };\n }\n console.log(`[Step 4] Updated file: ${fileChange.path}`);\n }\n // Create PR\n const prBody = `## Automated Fix Proposal\n\nThis PR was automatically generated by [dev3000](https://github.com/vercel-labs/dev3000) after analyzing your application.\n\n### Fix Details\nView the full analysis: [${blobUrl}](${blobUrl})\n\n${fixProposal}\n\n---\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)\n\nCo-Authored-By: Claude (dev3000) <noreply@anthropic.com>`;\n const createPR = await fetch(`https://api.github.com/repos/${repoOwner}/${repoName}/pulls`, {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${githubToken}`,\n Accept: \"application/vnd.github.v3+json\",\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n title: `Fix: ${projectName} - Automated fix from dev3000`,\n head: branchName,\n base: baseBranch,\n body: prBody\n })\n });\n if (!createPR.ok) {\n const error = await createPR.text();\n console.error(`[Step 4] Failed to create PR: ${error}`);\n return {\n success: false,\n error: `Failed to create PR: ${createPR.status}`\n };\n }\n const prData = await createPR.json();\n console.log(`[Step 4] Created PR: ${prData.html_url}`);\n return {\n success: true,\n prUrl: prData.html_url,\n prNumber: prData.number,\n branch: branchName\n };\n } catch (error) {\n console.error(\"[Step 4] Error creating PR:\", error);\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error)\n };\n }\n}\n/**\n * Cleanup step: Stop the sandbox\n */ export async function cleanupSandbox(cleanup) {\n console.log(\"[Cleanup] Stopping sandbox...\");\n try {\n await cleanup();\n console.log(\"[Cleanup] Sandbox stopped successfully\");\n } catch (error) {\n console.error(\"[Cleanup] Error stopping sandbox:\", error);\n // Don't throw - cleanup errors shouldn't fail the workflow\n }\n}\n"],"names":[],"mappings":"sCAOW,eAAe,EAAiB,CAAO,CAAE,CAAM,CAAE,CAAW,CAAE,CAAW,CAAE,CAAe,EACjG,QAAQ,GAAG,CAAC,CAAC,kCAAkC,EAAE,EAAY,GAAG,CAAC,EACjE,QAAQ,GAAG,CAAC,CAAC,qBAAqB,EAAE,EAAA,CAAS,EAC7C,QAAQ,GAAG,CAAC,CAAC,iBAAiB,EAAE,EAAA,CAAQ,EAExC,QAAQ,GAAG,CAAC,CAAC,qCAAqC,EAAE,CAAC,CAAC,QAAQ,GAAG,CAAC,iBAAiB,CAAA,CAAE,EACrF,QAAQ,GAAG,CAAC,CAAC,4CAA4C,EAAE,CAAC,CAAC,EAAA,CAAiB,EAC9E,QAAQ,GAAG,CAAC,CAAC,iCAAiC,EAAE,CAAC,CAAC,QAAQ,GAAG,CAAC,YAAY,CAAA,CAAE,EAC5E,QAAQ,GAAG,CAAC,CAAC,qCAAqC,EAAE,CAAC,CAAC,EAAA,CAAa,EAG/D,GAAmB,CA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