@netlify/agent-runner-cli 1.26.0 → 1.28.0

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.
package/dist/bin.js CHANGED
@@ -1,129 +1,132 @@
1
1
  #!/usr/bin/env node
2
- import Ke from"process";import Jt from"minimist";import{createRequire as Yt}from"module";import{createTracerProvider as Xe}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as he}from"@netlify/otel/opentelemetry";import{withActiveSpan as We}from"@netlify/otel";import{OTLPTraceExporter as ze}from"@opentelemetry/exporter-trace-otlp-grpc";var _e=(e,t)=>Xe({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new he(new oe),new he(new ze)]});function J(e,t,n){return console.log(`\u23F3 TRACE: ${t} starting...`),We(e,t,n)}var oe=class{export(t,n){for(let r of t)this.logSpan(r);n({code:1})}async shutdown(){}forceFlush(){return Promise.resolve()}logSpan(t){let n=(t.endTime[0]-t.startTime[0])*1e3+(t.endTime[1]-t.startTime[1])/1e6,r=t.attributes,o=[];for(let[i,l]of Object.entries(r))i.includes("duration")&&typeof l=="number"?o.push(`${i}=${l.toFixed(2)}ms`):o.push(`${i}=${l}`);let s=t.status?.code===2?"\u274C":"\u2705",a=o.length>0?` [${o.join(", ")}]`:"";console.log(`${s} TRACE: ${t.name} completed in ${n.toFixed(2)}ms${a}`),t.status?.code===2&&t.status.message&&console.log(` \u274C Error: ${t.status.message}`)}};var Ze=["error","failed","exception","fatal","panic","abort","crash"];function ye(e){let t=e.split(`
3
- `),n=[],r=-1,o=0;for(;o<t.length;){let i=t[o].slice(0,500).toLowerCase();if(Ze.some(d=>i.includes(d))){let d=Math.max(0,o-10,r+1),c=Math.min(t.length-1,o+20),f=[];for(let m=d;m<=c;m++)f.push(t[m]);n.push(f.join(`
4
- `)),r=c,o=c+1}else o++}if(n.length===0)return e;let s=n.map((a,i)=>`<extracted_error_chunk order="${i+1}">
5
- ${a}
2
+ import dt from"process";import gr from"minimist";import{createRequire as ar}from"module";import{createTracerProvider as mt}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as ke}from"@netlify/otel/opentelemetry";import{withActiveSpan as gt}from"@netlify/otel";import{OTLPTraceExporter as ht}from"@opentelemetry/exporter-trace-otlp-grpc";function _(e){let t=!process.env.VITEST;return{log:(...r)=>{t&&console.log(`[AR]-[${e}]`,...r)},error:(...r)=>{t&&console.error(`[AR]-[${e}]`,...r)},warn:(...r)=>{t&&console.warn(`[AR]-[${e}]`,...r)},info:(...r)=>{t&&console.info(`[AR]-[${e}]`,...r)},debug:(...r)=>{t&&console.debug(`[AR]-[${e}]`,...r)}}}var _e=_("tracing"),be=(e,t,r)=>mt({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new ke(new ye),new ke(new ht({url:r}))]});function se(e,t,r){return _e.log(`\u23F3 TRACE: ${t} starting...`),gt(e,t,r)}var ye=class{export(t,r){for(let n of t)this.logSpan(n);r({code:1})}async shutdown(){}forceFlush(){return Promise.resolve()}logSpan(t){let r=(t.endTime[0]-t.startTime[0])*1e3+(t.endTime[1]-t.startTime[1])/1e6,n=t.attributes,o=[];for(let[a,i]of Object.entries(n))a.includes("duration")&&typeof i=="number"?o.push(`${a}=${i.toFixed(2)}ms`):o.push(`${a}=${i}`);let s=t.status?.code===2?"\u274C":"\u2705",l=o.length>0?` [${o.join(", ")}]`:"";_e.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${l}`),t.status?.code===2&&t.status.message&&_e.log(` \u274C Error: ${t.status.message}`)}};var _t=["error","failed","exception","fatal","panic","abort","crash"];function $e(e){let t=e.split(`
3
+ `),r=[],n=-1,o=0;for(;o<t.length;){let a=t[o].slice(0,500).toLowerCase();if(_t.some(p=>a.includes(p))){let p=Math.max(0,o-10,n+1),c=Math.min(t.length-1,o+20),h=[];for(let m=p;m<=c;m++)h.push(t[m]);r.push(h.join(`
4
+ `)),n=c,o=c+1}else o++}if(r.length===0)return e;let s=r.map((l,a)=>`<extracted_error_chunk order="${a+1}">
5
+ ${l}
6
6
  </extracted_error_chunk>`).join(`
7
7
 
8
- `);return s.length>e.length*.8?e:s}import ne from"process";import{getTracer as It}from"@netlify/otel";import X from"process";var se=X.env.NETLIFY_API_URL,ie=X.env.NETLIFY_API_TOKEN,W=async(e,t={})=>{if(!se||!ie)throw new Error("No API URL or token");let n=new URL(e,se),r={...t,headers:{...t.headers,Authorization:`Bearer ${ie}`}};X.env.AGENT_RUNNERS_DEBUG==="true"&&(r.headers["x-nf-debug-logging"]="true"),t.json&&(r.headers||={},r.headers["Content-Type"]="application/json",r.body=JSON.stringify(t.json));let o=await fetch(n,r),s=o.ok&&o.status<=299;if(X.env.AGENT_RUNNERS_DEBUG==="true")console.log(`[DEBUG] Response headers for ${n}:`),o.headers.forEach((i,l)=>{console.log(` ${l}: ${i}`)});else{let i=o.headers.get("x-nf-request-id");console.log(`Request ID for ${n}: ${i||"N/A"}`)}if(s||console.error(`Got status ${o.status} for request ${n}`),t.raw){if(!s)throw o;return o}let a=await(o.headers.get("content-type")?.includes("application/json")?o.json():o.text());if(!s)throw a;return a},Ee=e=>{console.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(se=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(ie=e.constants.NETLIFY_API_TOKEN)},z=(e,t)=>W(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),q=(e,t,n)=>W(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:n});var Te=(e,t)=>W(`/api/v1/agent_runners/${e}/sessions/${t}`),xe=(e,t,n)=>W(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":n}});var Ne=async({netlify:e,config:t})=>{let n,r,o,s,a=e.constants?.SITE_ID;if(!a)throw new Error("No site id");let i=async()=>{clearTimeout(o),console.log("Requesting AI gateway information");let l=await xe(a,t.id,t.sessionId);if({token:n,url:s}=l,r=l.expires_at?l.expires_at*1e3:void 0,console.log("Got AI gateway information",{token:!!n,expiresAt:r,url:s}),r){let d=r-Date.now()-6e4;d>0&&(o=setTimeout(()=>{i()},d))}};return await i(),{get url(){return s},get token(){return n}}};import we from"process";import{execa as Qe,execaCommand as lr}from"execa";var et={preferLocal:!0},Ie=(e,t,n)=>{let[r,o]=tt(t,n),s={...et,...o},a=Qe(e,r,s);return rt(a,s),a};var tt=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},rt=(e,t)=>{t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0||(e.stdout?.pipe(we.stdout),e.stderr?.pipe(we.stderr))};var Z="netlify-agent-runner-context.md",ae="task-history",le="netlify-context",D=".netlify",$="other",L="personal";var U="enterprise",j="free",Ce=[L,"pro",U,j];var nt=e=>new Promise(t=>{setTimeout(t,e)}),Re=(e,t=3e3)=>{let n=!1,r=null,o=[],s=null,a=(...i)=>{if(n)return r=i,new Promise(c=>{o.push(c)});n=!0;let l,d=new Promise(c=>{l=c});return s=(async()=>{await Promise.resolve();let c=await e(...i);for(l(c);;){if(await nt(t),!r)return n=!1,s=null,c;let f=r,m=o;r=null,o=[],c=await e(...f),m.forEach(y=>{y(c)})}})(),d};return a.flush=async()=>{if((n||r)&&s)return await s,a.flush()},a},Q=(e,t,n=!1)=>{let r=null,o=null,s=null,a=function(...i){o=i,s=this;let l=n&&!r;clearTimeout(r),r=setTimeout(()=>{r=null,n||(e.apply(s,o),o=null,s=null)},t),l&&(e.apply(s,o),o=null,s=null)};return a.cancel=()=>{clearTimeout(r),r=null,o=null,s=null},a.flush=()=>{if(r){clearTimeout(r);let i=o,l=s;r=null,o=null,s=null,e.apply(l,i)}},a},ee=(e,t=!0)=>{if(e)try{return JSON.parse(e)}catch(n){t&&console.error("Could not parse JSON",n)}},Ae=(e,t)=>{let o=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let i=`--${t}${o}`;if(i.length>55)return"";let l=60-i.length;if(l<=0)return"";if(l>=s.length+6){let d=Math.min(l-s.length,e.length);return`${s}${e.slice(0,d)}`}return e.slice(0,l)},ot=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!Ce.some(t=>t in e),ve=()=>{let e={},t={codex:process.env.NETLIFY_FF_AGENT_RUNNER_CODEX_VERSION,claude:process.env.NETLIFY_FF_AGENT_RUNNER_CLAUDE_VERSION,gemini:process.env.NETLIFY_FF_AGENT_RUNNER_GEMINI_VERSION};return Object.entries(t).forEach(([n,r])=>{if(r){let o=`NETLIFY_FF_AGENT_RUNNER_${n.toUpperCase()}_VERSION`;try{let s=JSON.parse(r);ot(s)&&(e[n]=s)}catch(s){let i=s instanceof SyntaxError?"Invalid JSON":s.message;console.error(`Could not parse ${n} model version override from ${o}: ${i}`)}}}),e};import{Buffer as Se}from"buffer";var Pe=async({config:e,netlify:t})=>{let n=await it(t),{hasChanges:r}=n,{status:o}=n;if(!r)return{hasChanges:!1};let s=await at(t,o);await t.utils.run("git",["add",".",...s]);let i=(await t.utils.run("git",["diff","--staged"])).stdout;if(r=!!i,!r)return{hasChanges:!1};let d=(await t.utils.run("git",["diff","--staged","--binary"])).stdout,c,f;if(e.sha){await t.utils.run("git",["commit","-m","Agent runner"]),c=(await t.utils.run("git",["diff",e.sha,"HEAD"])).stdout;let g=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"])).stdout;c!==g&&(f=Se.from(g).toString("base64"))}let m={hasChanges:!0,diff:i,resultDiff:c};return i!==d&&(m.diffBinary=Se.from(d).toString("base64")),f&&(m.resultDiffBinary=f),m},st=["?? mise.toml",/\?\? .+?\.log/],it=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
9
- `).filter(o=>!st.some(s=>s instanceof RegExp?s.test(o):o===s))).length!==0,status:t.stdout}};var Oe=async e=>{let{stdout:t}=await e.utils.run("git",["rev-parse","HEAD"]);return t.trim()},ke=async e=>{let{stdout:t}=await e.utils.run("git",["rev-list","--max-parents=0","HEAD"]);return t.trim()},at=async(e,t="")=>{let n=[".netlify","mise.toml","node_modules"],r=[],o=n.map(async a=>{try{return await e.utils.run("git",["check-ignore","-v",a]),null}catch{return`:!${a}`}});return(await Promise.all(o)).forEach(a=>{a&&r.push(a)}),t.split(`
10
- `).forEach(a=>{let i=a.match(/\?\? (.+?)\.log$/)?.[1];i&&r.push(`:!${i}.log`)}),r};import lt from"fs/promises";import ct from"os";import te from"path";import M from"process";var ut=({catchError:e,runCmd:t,error:n,result:r,runnerName:o})=>(console.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!n,hadExistingResult:!!r,resultLength:r?r.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),r?(console.log("Preserving existing result despite catch handler being triggered"),n?{error:n,result:r}:{error:"Process completed with errors but result was captured",result:r}):(console.log("Setting result to undefined because no valid result was captured"),{error:n||`${o} failed`,result:void 0}));async function ce({config:e,netlify:t,persistSteps:n,aiGateway:r}){let o=e,{accountType:s,prompt:a,modelVersionOverrides:i}=o,{model:l}=o;if(r){let{token:T,url:_}=r;if(!T||!_)throw new Error("No token or url provided from AI Gateway");let p=dt[s];if(!p)throw new Error(`Claude is not supported for the account type ${s}`);if(l&&!p?.models?.[l])throw new Error(`${l} is not supported for account type ${s}`);if(i?.claude){let u=i?.claude?.[s];u&&(l=u)}M.env.ANTHROPIC_API_KEY=T,M.env.ANTHROPIC_BASE_URL=_}else if(!M.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let d=[],c=[],f={},m=0,y=0,E,g,N=te.join(M.cwd(),"node_modules"),v=[te.join(M.env.NODE_PATH||N,".bin/claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...l?["--model",l]:[],"-p",a],S=`${M.env.NVM_BIN}/node`;console.log(`Running ${S} ${v.join(" ")}`);let C=t.utils.run(S,v,{all:!0,env:M.env});C.stdin?.end();let w=Q(()=>{n?.({steps:d,duration:y})},250),x=(T,_)=>{let p={...T,id:m};m+=1,c.push(p),d.push(p),_||w.flush(),w(),_&&w.flush()},R="";return C.all?.on("data",T=>{if(R+=T.toString(),!T.includes(`
11
- `))return;let _=R.split(`
12
- `).filter(Boolean).map(p=>{try{return JSON.parse(p)}catch{console.log("Could not parse line",p)}return null}).filter(Boolean);R="",_.forEach(p=>{Array.isArray(p?.message?.content)?p.message.content.forEach(u=>{switch(u.type){case"text":{u.text&&x({message:u.text});break}case"image":{typeof u.source=="object"&&u.source&&u.source.type==="base64"&&u.source.media_type?x({message:`![](data:${u.source.media_type};base64,${u.source.data})`}):console.log(`Unsupported image type ${u.source?.type}`,u.source);break}case"tool_use":{if(u.name==="Task"){let h=u.input?.description&&`\`${u.input.description}\``;x({title:[u.name,h].filter(Boolean).join(" ")})}else u.id&&(f[u.id]=u);w.flush();break}case"tool_result":{let h=u.tool_use_id?f[u.tool_use_id]:void 0,b;if(h){let F=h.input?.file_path&&te.relative(M.cwd(),h.input.file_path),I=F&&`\`${F}\``;b=[h.name,I].filter(Boolean).join(" ")}let Y=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(h?.name||""),P;if(typeof u.content=="string")P=u.content;else if(Array.isArray(u.content)){let F=[];u.content.forEach(I=>{I?.type==="text"&&typeof I.text=="string"?F.push(I.text):I?.type==="image"&&typeof I.source=="object"&&I.source?I.source.type==="base64"&&I.source.media_type?F.push(`![](data:${I.source.media_type};base64,${I.source.data})`):console.log(`Unsupported image type ${I.source.type}`,I.source):console.log(`Unsupported block type ${I?.type}`)}),P=F.join(`
13
-
14
- `)}Y&&P&&(P=`\`\`\`
15
- ${P.trim()}
16
- \`\`\``),x({title:b,message:P},!0);break}case"thinking":{u.thinking&&x({title:"Thinking",message:u.thinking},!0);break}default:console.log(`Message content type is not supported ${u.type}`,u)}}):p?.type==="result"&&(y=p.duration_ms||0,p.is_error?g=p.result:E=p.result,[c,d].forEach(u=>{u[u.length-1]?.message===E&&u.pop()}))})}),await C.catch(T=>{({error:g,result:E}=ut({catchError:T,runCmd:C,error:g,result:E,runnerName:"Claude"}))}),w.flush(),{steps:c,duration:y,result:E,error:g}}var be=async()=>{let e=te.join(ct.homedir(),".claude");await lt.rm(e,{recursive:!0,force:!0})},dt={[U]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:64e3},"claude-3-haiku-20240307":{maxTokens:4096},"claude-opus-4-20250514":{maxTokens:32e3},"claude-sonnet-4-20250514":{maxTokens:64e3}}},pro:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[L]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[j]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}},[$]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}}};import pt from"fs/promises";import ft from"os";import ue from"path";import H from"process";var mt=({catchError:e,runCmd:t,error:n,result:r,runnerName:o})=>(console.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!n,hadExistingResult:!!r,resultLength:r?r.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),r?(console.log("Preserving existing result despite catch handler being triggered"),n?{error:n,result:r}:{error:"Process completed with errors but result was captured",result:r}):(console.log("Setting result to undefined because no valid result was captured"),{error:n||`${o} failed`,result:void 0}));async function de({config:e,netlify:t,persistSteps:n,sendSteps:r,aiGateway:o}){let{accountType:s,prompt:a,modelVersionOverrides:i}=e,{model:l}=e;if(o){let{token:x,url:R}=o;if(!x||!R)throw new Error("No token or url provided from AI Gateway");let T=gt[s];if(!T)throw new Error(`Codex is not supported for the account type ${s}`);if(l&&!T?.models?.[l])throw new Error(`${l} is not supported for account type ${s}`);if(i?.codex){let _=i?.codex?.[s];_&&(l=_)}H.env.OPENAI_API_KEY=x,H.env.OPENAI_BASE_URL=R}else if(!H.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let d=[],c=[],f={},m=0,y=0,E,g,N=ue.join(H.cwd(),"node_modules"),v=[ue.join(H.env.NODE_PATH||N,".bin/codex"),"--approval-mode","full-auto",o?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...l?["--model",l]:[],"-q",a].filter(Boolean),S=`${H.env.NVM_BIN}/node`;console.log(`Running ${S} ${v.join(" ")}`);let C=t.utils.run(S,v,{all:!0,env:{...H.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),w="";return C.all.on("data",x=>{if(w+=x.toString(),!x.includes(`
17
- `))return;let R=w.toString().split(`
18
- `).filter(Boolean).map(p=>{try{return JSON.parse(p)}catch{console.log("Could not parse line",p)}return null}).filter(Boolean);w="";let T=[],_=!1;R.forEach(p=>{if(p?.duration_ms&&(y=p.duration_ms,_=!0),p?.type==="local_shell_call")f[p.call_id]=p;else if(p?.type==="local_shell_call_output"){let u=_t(f[p.call_id],p);u.id=m,m+=1,u&&(c.push(u),d.push(u),T.push(u),_=!0)}else p?.type==="message"&&p.role==="assistant"?E=p.content.map(u=>u.text).join(`
19
- `):p?.type==="message"&&p.role==="system"&&(g=p.content.map(u=>u.text).join(`
20
- `))}),_&&(n?.({steps:d,duration:y}),r?.({steps:T,duration:y}))}),await C.catch(x=>{({error:g,result:E}=mt({catchError:x,runCmd:C,error:g,result:E,runnerName:"Codex"}))}),{steps:c,duration:y,result:E,error:g}}var Fe=async()=>{let e=ue.join(ft.homedir(),".codex");await pt.rm(e,{recursive:!0,force:!0})},gt={[U]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},o1:{maxTokens:1e5},"o1-mini":{maxTokens:65536},"o3-mini":{maxTokens:1e5},"gpt-image-1":{},"dall-e-2":{},"dall-e-3":{}}},[L]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768}}},pro:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768}}},[j]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},"o3-mini":{maxTokens:16e3}}},[$]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},"o3-mini":{maxTokens:16e3}}}},ht=new Set(["bash","-lc"]),_t=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let n=e.action?.command?.filter(s=>!ht.has(s)),r=n?`Running \`${n.join(" ")}\``:void 0,o;try{o=JSON.parse(t.output).output?.trim(),o&&(o=`\`\`\`
8
+ `);return s.length>e.length*.8?e:s}import fe from"process";import{getTracer as Kt}from"@netlify/otel";import ie from"process";var Ee=ie.env.NETLIFY_API_URL,Te=ie.env.NETLIFY_API_TOKEN,te=_("api"),ae=async(e,t={})=>{if(!Ee||!Te)throw new Error("No API URL or token");let r=new URL(e,Ee),n={...t,headers:{...t.headers,Authorization:`Bearer ${Te}`}};ie.env.AGENT_RUNNERS_DEBUG==="true"&&(n.headers["x-nf-debug-logging"]="true"),t.json&&(n.headers||={},n.headers["Content-Type"]="application/json",n.body=JSON.stringify(t.json));let o=await fetch(r,n),s=o.ok&&o.status<=299;if(ie.env.AGENT_RUNNERS_DEBUG==="true")te.log(`Response headers for ${r}:`),o.headers.forEach((a,i)=>{te.log(` ${i}: ${a}`)});else{let a=o.headers.get("x-nf-request-id");te.log(`Request ID for ${r}: ${a||"N/A"}`)}if(s||te.error(`Got status ${o.status} for request ${r}`),t.raw){if(!s)throw o;return o}let l=await(o.headers.get("content-type")?.includes("application/json")?o.json():o.text());if(!s)throw l;return l},Fe=e=>{te.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Ee=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Te=e.constants.NETLIFY_API_TOKEN)},le=(e,t)=>ae(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),J=(e,t,r)=>ae(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var Le=(e,t)=>ae(`/api/v1/agent_runners/${e}/sessions/${t}`),De=(e,t,r)=>ae(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}});var Ue=_("ai_gateway"),je=async({netlify:e,config:t})=>{let r,n,o,s,l=e.constants?.SITE_ID;if(!l)throw new Error("No site id");let a=async()=>{clearTimeout(o),Ue.log("Requesting AI gateway information");let i=await De(l,t.id,t.sessionId);if({token:r,url:s}=i,n=i.expires_at?i.expires_at*1e3:void 0,Ue.log("Got AI gateway information",{token:!!r,expiresAt:n,url:s}),n){let p=n-Date.now()-6e4;p>0&&(o=setTimeout(()=>{a()},p))}};return await a(),{get url(){return s},get token(){return r}}};import Ye from"process";import{execa as yt,execaCommand as $r}from"execa";var Lr=_("shell"),Et={preferLocal:!0},Ge=(e,t,r)=>{let[n,o]=Tt(t,r),s={...Et,...o},l=yt(e,n,s);return xt(l,s),l};var Tt=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},xt=(e,t)=>{t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0||(e.stdout?.pipe(Ye.stdout),e.stderr?.pipe(Ye.stderr))};var Me="netlify-agent-runner-context.md",xe="task-history",we="netlify-context",$=".netlify",re="results.md",Ne="assets",U="other",j="personal";var Y="enterprise",G="free",Be=[j,"pro",Y,G];var He=_("utils"),wt=e=>new Promise(t=>{setTimeout(t,e)}),qe=(e,t=3e3)=>{let r=!1,n=null,o=[],s=null,l=(...a)=>{if(r)return n=a,new Promise(c=>{o.push(c)});r=!0;let i,p=new Promise(c=>{i=c});return s=(async()=>{await Promise.resolve();let c=await e(...a);for(i(c);;){if(await wt(t),!n)return r=!1,s=null,c;let h=n,m=o;n=null,o=[],c=await e(...h),m.forEach(y=>{y(c)})}})(),p};return l.flush=async()=>{if((r||n)&&s)return await s,l.flush()},l},ue=(e,t,r=!1)=>{let n=null,o=null,s=null,l=function(...a){o=a,s=this;let i=r&&!n;clearTimeout(n),n=setTimeout(()=>{n=null,r||(e.apply(s,o),o=null,s=null)},t),i&&(e.apply(s,o),o=null,s=null)};return l.cancel=()=>{clearTimeout(n),n=null,o=null,s=null},l.flush=()=>{if(n){clearTimeout(n);let a=o,i=s;n=null,o=null,s=null,e.apply(i,a)}},l},ce=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(n){t&&(r?.error?r.error("Could not parse JSON",n):He.error("Could not parse JSON",n))}},Ve=(e,t)=>{let o=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let a=`--${t}${o}`;if(a.length>55)return"";let i=60-a.length;if(i<=0)return"";if(i>=s.length+6){let p=Math.min(i-s.length,e.length);return`${s}${e.slice(0,p)}`}return e.slice(0,i)},Nt=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!Be.some(t=>t in e),Ke=()=>{let e={},t={codex:process.env.NETLIFY_FF_AGENT_RUNNER_CODEX_VERSION,claude:process.env.NETLIFY_FF_AGENT_RUNNER_CLAUDE_VERSION,gemini:process.env.NETLIFY_FF_AGENT_RUNNER_GEMINI_VERSION};return Object.entries(t).forEach(([r,n])=>{if(n){let o=`NETLIFY_FF_AGENT_RUNNER_${r.toUpperCase()}_VERSION`;try{let s=JSON.parse(n);Nt(s)&&(e[r]=s)}catch(s){let a=s instanceof SyntaxError?"Invalid JSON":s.message;He.error(`Could not parse ${r} model version override from ${o}: ${a}`)}}}),e};import{Buffer as We}from"buffer";var Je=async({config:e,netlify:t})=>{let r=await It(t),{hasChanges:n}=r,{status:o}=r;if(!n)return{hasChanges:!1};let s=await Ct(t,o);await t.utils.run("git",["add",".",...s]);let l={stdio:["ignore","pipe","pipe"]},i=(await t.utils.run("git",["diff","--staged"],l)).stdout;if(n=!!i,!n)return{hasChanges:!1};let c=(await t.utils.run("git",["diff","--staged","--binary"],l)).stdout,h,m;if(e.sha){await t.utils.run("git",["commit","-m","Agent runner"]),h=(await t.utils.run("git",["diff",e.sha,"HEAD"],l)).stdout;let g=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"],l)).stdout;h!==g&&(m=We.from(g).toString("base64"))}let y={hasChanges:!0,diff:i,resultDiff:h};return i!==c&&(y.diffBinary=We.from(c).toString("base64")),m&&(y.resultDiffBinary=m),y},Rt=["?? mise.toml",/\?\? .+?\.log/],It=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
9
+ `).filter(o=>!Rt.some(s=>s instanceof RegExp?s.test(o):o===s))).length!==0,status:t.stdout}};var Xe=async e=>{let{stdout:t}=await e.utils.run("git",["rev-parse","HEAD"]);return t.trim()},ze=async e=>{let{stdout:t}=await e.utils.run("git",["rev-list","--max-parents=0","HEAD"]);return t.trim()},Ct=async(e,t="")=>{let r=[".netlify","mise.toml","node_modules"],n=[],o=r.map(async l=>{try{return await e.utils.run("git",["check-ignore","-v",l]),null}catch{return`:!${l}`}});return(await Promise.all(o)).forEach(l=>{l&&n.push(l)}),t.split(`
10
+ `).forEach(l=>{let a=l.match(/\?\? (.+?)\.log$/)?.[1];a&&n.push(`:!${a}.log`)}),n};import vt from"fs/promises";import St from"os";import pe from"path";import H from"process";import Re from"path";import At from"fs/promises";var Ie=_("agent-output-utils");async function X({initialResult:e,agentName:t,hasError:r}){let n="",o=Re.join(process.cwd(),$,re);try{let s=await At.readFile(o,"utf-8");s&&(n=s,Ie.log(`Pulled result from ${Re.relative(process.cwd(),o)}`))}catch{Ie.log(`No results file found at ${Re.relative(process.cwd(),o)}`)}return n||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function z({error:e}){let t=e&&typeof e=="object"?JSON.stringify(e):e,r=t?.replace(/\s+/g," ").trim()||"",n="";return r?.includes("ai gateway is not available for your account")?n="AI Gateway is currently not available on your account. Please confirm your account meets the criteria for using Agent Runners and AI Gateway and that your account has remaining AI Gateway inference credits available. Reach out to Netlify support if this is unexpected.":r?.includes("error when talking to gemini api")?n="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":r?.includes("connection closed prematurely while waiting for the model")&&(n="The agent's models were currently overloaded. Please try again or use a different available agent."),n&&Ie.log(`Providing updated error messsage: ${n}, replacing original error: ${t}`),r||void 0}var M=_("runner_claude"),Pt="Claude Code",Ot=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(M.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(M.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(M.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0}));async function Ce({config:e,netlify:t,persistSteps:r,aiGateway:n}){let o=e,{accountType:s,prompt:l,modelVersionOverrides:a}=o,{model:i}=o;if(n){let{token:N,url:f}=n;if(!N||!f)throw new Error("No token or url provided from AI Gateway");let d=kt[s];if(!d)throw new Error(`Claude is not supported for the account type ${s}`);if(i&&!d?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(a?.claude){let u=a?.claude?.[s];u&&(i=u)}H.env.ANTHROPIC_API_KEY=N,H.env.ANTHROPIC_BASE_URL=f}else if(!H.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let p=[],c=[],h={},m=0,y=0,x,T,g=pe.join(H.cwd(),"node_modules"),I=[pe.join(H.env.NODE_PATH||g,".bin/claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...i?["--model",i]:[],"-p",l],C=`${H.env.NVM_BIN}/node`;M.log(`Running ${C} ${I.join(" ")}`);let S=t.utils.run(C,I,{all:!0,env:H.env});S.stdin?.end();let R=ue(()=>{r?.({steps:p,duration:y})},250),w=(N,f)=>{let d={...N,id:m};m+=1,c.push(d),p.push(d),f||R.flush(),R(),f&&R.flush()},A="";return S.all?.on("data",N=>{if(A+=N.toString(),!N.includes(`
11
+ `))return;let f=A.split(`
12
+ `).filter(Boolean).map(d=>{try{return JSON.parse(d)}catch{M.log("Could not parse line",d)}return null}).filter(Boolean);A="",f.forEach(d=>{Array.isArray(d?.message?.content)?d.message.content.forEach(u=>{switch(u.type){case"text":{u.text&&w({message:u.text});break}case"image":{typeof u.source=="object"&&u.source&&u.source.type==="base64"&&u.source.media_type?w({message:`![](data:${u.source.media_type};base64,${u.source.data})`}):M.log(`Unsupported image type ${u.source?.type}`,u.source);break}case"tool_use":{if(u.name==="Task"){let E=u.input?.description&&`\`${u.input.description}\``;w({title:[u.name,E].filter(Boolean).join(" ")})}else u.id&&(h[u.id]=u);R.flush();break}case"tool_result":{let E=u.tool_use_id?h[u.tool_use_id]:void 0,L;if(E){let D=E.input?.file_path&&pe.relative(H.cwd(),E.input.file_path),v=D&&`\`${D}\``;L=[E.name,v].filter(Boolean).join(" ")}let B=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(E?.name||""),b;if(typeof u.content=="string")b=u.content;else if(Array.isArray(u.content)){let D=[];u.content.forEach(v=>{v?.type==="text"&&typeof v.text=="string"?D.push(v.text):v?.type==="image"&&typeof v.source=="object"&&v.source?v.source.type==="base64"&&v.source.media_type?D.push(`![](data:${v.source.media_type};base64,${v.source.data})`):M.log(`Unsupported image type ${v.source.type}`,v.source):M.log(`Unsupported block type ${v?.type}`)}),b=D.join(`
13
+
14
+ `)}B&&b&&(b=`\`\`\`
15
+ ${b.trim()}
16
+ \`\`\``),w({title:L,message:b},!0);break}case"thinking":{u.thinking&&w({title:"Thinking",message:u.thinking},!0);break}default:M.log(`Message content type is not supported ${u.type}`,u)}}):d?.type==="result"&&(y=d.duration_ms||0,d.is_error?T=d.result:x=d.result,[c,p].forEach(u=>{u[u.length-1]?.message===x&&u.pop()}))})}),await S.catch(N=>{({error:T,result:x}=Ot({catchError:N,runCmd:S,error:T,result:x,runnerName:"Claude"}))}),R.flush(),{steps:c,duration:y,result:await X({initialResult:x,agentName:Pt,hasError:!!T}),error:z({error:T})}}var Ze=async()=>{let e=pe.join(St.homedir(),".claude");await vt.rm(e,{recursive:!0,force:!0})},kt={[Y]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:64e3},"claude-3-haiku-20240307":{maxTokens:4096},"claude-opus-4-20250514":{maxTokens:32e3},"claude-sonnet-4-20250514":{maxTokens:64e3}}},pro:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[j]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[G]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}},[U]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}}};import bt from"fs/promises";import $t from"os";import Ae from"path";import W from"process";var Z=_("runner_codex"),Ft="Codex CLI",Lt=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(Z.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(Z.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(Z.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0}));async function ve({config:e,netlify:t,persistSteps:r,sendSteps:n,aiGateway:o}){let{accountType:s,prompt:l,modelVersionOverrides:a}=e,{model:i}=e;if(o){let{token:w,url:A}=o;if(!w||!A)throw new Error("No token or url provided from AI Gateway");let N=Dt[s];if(!N)throw new Error(`Codex is not supported for the account type ${s}`);if(i&&!N?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(a?.codex){let f=a?.codex?.[s];f&&(i=f)}W.env.OPENAI_API_KEY=w,W.env.OPENAI_BASE_URL=A}else if(!W.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let p=[],c=[],h={},m=0,y=0,x,T,g=Ae.join(W.cwd(),"node_modules"),I=[Ae.join(W.env.NODE_PATH||g,".bin/codex"),"--approval-mode","full-auto",o?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...i?["--model",i]:[],"-q",l].filter(Boolean),C=`${W.env.NVM_BIN}/node`;Z.log(`Running ${C} ${I.join(" ")}`);let S=t.utils.run(C,I,{all:!0,env:{...W.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),R="";return S.all.on("data",w=>{if(R+=w.toString(),!w.includes(`
17
+ `))return;let A=R.toString().split(`
18
+ `).filter(Boolean).map(d=>{try{return JSON.parse(d)}catch{Z.log("Could not parse line",d)}return null}).filter(Boolean);R="";let N=[],f=!1;A.forEach(d=>{if(d?.duration_ms&&(y=d.duration_ms,f=!0),d?.type==="local_shell_call")h[d.call_id]=d;else if(d?.type==="local_shell_call_output"){let u=jt(h[d.call_id],d);u.id=m,m+=1,u&&(c.push(u),p.push(u),N.push(u),f=!0)}else d?.type==="message"&&d.role==="assistant"?x=d.content.map(u=>u.text).join(`
19
+ `):d?.type==="message"&&d.role==="system"&&(T=d.content.map(u=>u.text).join(`
20
+ `))}),f&&(r?.({steps:p,duration:y}),n?.({steps:N,duration:y}))}),await S.catch(w=>{({error:T,result:x}=Lt({catchError:w,runCmd:S,error:T,result:x,runnerName:"Codex"}))}),{steps:c,duration:y,result:await X({initialResult:x,agentName:Ft,hasError:!!T}),error:z({error:T})}}var Qe=async()=>{let e=Ae.join($t.homedir(),".codex");await bt.rm(e,{recursive:!0,force:!0})},Dt={[Y]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},o1:{maxTokens:1e5},"o1-mini":{maxTokens:65536},"o3-mini":{maxTokens:1e5},"gpt-image-1":{},"dall-e-2":{},"dall-e-3":{}}},[j]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768}}},pro:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768}}},[G]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},"o3-mini":{maxTokens:16e3}}},[U]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},"o3-mini":{maxTokens:16e3}}}},Ut=new Set(["bash","-lc"]),jt=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!Ut.has(s)),n=r?`Running \`${r.join(" ")}\``:void 0,o;try{o=JSON.parse(t.output).output?.trim(),o&&(o=`\`\`\`
21
21
  ${o.trim()}
22
- \`\`\``)}catch(s){console.error("Could not decode outputMsg",s,t.output)}return{title:r,message:o}};import yt from"fs/promises";import Et from"os";import re from"path";import G from"process";var Tt=({catchError:e,runCmd:t,error:n,result:r,runnerName:o})=>(console.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!n,hadExistingResult:!!r,resultLength:r?r.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),r?(console.log("Preserving existing result despite catch handler being triggered"),n?{error:n,result:r}:{error:"Process completed with errors but result was captured",result:r}):(console.log("Setting result to undefined because no valid result was captured"),{error:n||`${o} failed`,result:void 0})),xt={list_directory:"List",read_file:"Read",write_file:"Write",glob:"Find",search_file_content:"Find",replace:"Edit",run_shell_command:"Run",web_fetch:"Web Fetch",web_search:"Web Search",read_many_files:"Read Many",save_memory:"Memorize"};async function pe({config:e,netlify:t,persistSteps:n,sendSteps:r,aiGateway:o}){let{accountType:s,prompt:a,modelVersionOverrides:i}=e,{model:l}=e;if(o){let{token:_,url:p}=o;if(!_||!p)throw new Error("No token or url provided from AI Gateway");let u=Nt[s];if(!u)throw new Error(`Gemini is not supported for the account type ${s}`);if(l&&!u?.models?.[l])throw new Error(`${l} is not supported for account type ${s}`);if(i?.gemini){let h=i?.gemini?.[s];h&&(l=h)}G.env.GEMINI_API_KEY=_,G.env.GOOGLE_GEMINI_BASE_URL=p}else if(!G.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let d=[],c=[],f=[],m={},y=0,E=0,g,N,v=re.join(G.cwd(),"node_modules"),S=[re.join(G.env.NODE_PATH||v,".bin/gemini"),...l?["--model",l]:[],"--yolo","-p",a],C=`${G.env.NVM_BIN}/node`;console.log(`Running ${C} ${S.join(" ")}`);let w=t.utils.run(C,S,{all:!0,env:G.env});w.stdin?.end();let x=Q(()=>{n?.({steps:d,duration:E}),r?.({steps:c,duration:E}),c=[]},250),R=(_,p)=>{_.id=y,y+=1,f.push(_),d.push(_),c.push(_),p||x.flush(),x(),p&&x.flush()},T="";return w.all.on("data",_=>{if(T+=_.toString(),!_.includes(`
23
- `))return;let p=T.toString().split(`
24
- `).filter(Boolean).map(u=>{try{if(u.startsWith("[API Error")){let h=u.match(/\[api error: (.+?)]$/i)?.[1];return{type:"error",value:ee(h,!1)?.error?.message||h||"Gemini encountered error"}}return JSON.parse(u)}catch{}return null}).filter(Boolean);T="",p.forEach(u=>{switch(u.type){case"thought":{let h=u.value;R({title:h?.subject??"Thinking...",message:h?.description},!0);break}case"content":{u.value&&R({message:u.value});break}case"tool_call_request":{let h=u.value,b=xt[h.name]??h.name,Y=h.args?.path||h.args?.absolute_path,P=Y&&re.relative(G.cwd(),Y),F=h.args?.command,Je={title:[b,P&&`\`${P}\``,F&&`\`${F}\``].filter(Boolean).join(" ")};m[h.callId]=Je,x.flush();break}case"tool_result":{let h=u.value,b=m[h.callId];if(b){let Y=[h.resultDisplay,h.responseParts?.functionResponse?.response?.output].find(P=>typeof P=="string"&&P);Y&&(b.message=`\`\`\`
25
- ${Y.trim()}
26
- \`\`\``),R(b,!0)}break}case"result":{E=u.duration_ms,g=u.value,[f,d,c].forEach(h=>{h[h.length-1]?.message===g&&h.pop()});break}case"error":{N=u.value;break}case"finished":break;default:{console.warn("Unhandled message type:",u.type);break}}})}),await w.catch(_=>{({error:N,result:g}=Tt({catchError:_,runCmd:w,error:N,result:g,runnerName:"Gemini"}))}),x.flush(),{steps:f,duration:E,result:g,error:N}}var De=async()=>{let e=re.join(Et.homedir(),".gemini");await yt.rm(e,{recursive:!0,force:!0})},Nt={[U]:{models:{"gemini-1.5-flash":{maxTokens:8192},"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-1.5-pro":{maxTokens:8192},"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:65536},"gemini-2.5-flash-lite":{maxTokens:65536},"gemini-2.5-pro":{maxTokens:65536},"imagen-4.0-generate-001":{},"veo-3.0-generate-preview":{}}},pro:{models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[L]:{models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[j]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}},[$]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}}};var wt={codex:{runner:de,clean:Fe},claude:{runner:ce,clean:be},gemini:{runner:pe,clean:De}},$e=wt;var Le=async({config:e,apiThrottle:t,apiToken:n})=>{let r=It();return J(r,"init-stage",async o=>{let s=performance.now();o?.setAttributes({"init.runner":e.runner,"init.id":e.id,"init.sessionId":e.sessionId,"init.hasRepo":e.hasRepo,"init.useGateway":e.useGateway,"init.validateAgent":e.validateAgent});let a=$e[e.runner];if(!a)throw o?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let i=Ct({apiToken:n});Ee(i);let l=e.useGateway?await Ne({netlify:i,config:e}):void 0;o?.setAttributes({"init.aiGateway.created":!!l}),e.validateAgent&&e.errorLogsPath&&o?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let d=Re(({steps:m=[],duration:y})=>{let E=[...m];return m.length=0,q(e.id,e.sessionId,{steps:E,duration:y})},t),c;e.hasRepo?e.sha?(c=e.sha,o?.setAttributes({"init.sha.source":"provided"})):(c=await Oe(i),await z(e.id,{sha:c}),o?.setAttributes({"init.sha.source":"current_commit"})):(c=await ke(i),o?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let f=performance.now()-s;return o?.setAttributes({"init.sha":c||"unknown","init.duration.ms":f,"init.status":"success"}),{aiGateway:l,context:i,persistSteps:d,runner:a,sha:c}})},Ct=({apiToken:e})=>({constants:{NETLIFY_API_HOST:ne.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||ne.env.NETLIFY_API_TOKEN,SITE_ID:ne.env.SITE_ID,FUNCTIONS_DIST:ne.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:Ie}});import Rt from"crypto";import V from"fs/promises";import O from"path";import k from"process";var At=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:k.env.NETLIFY_TEAM_ID,userId:k.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:k.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},vt=()=>{let e=Object.keys(k.env).sort();return{nodeVersion:k.version,envVars:e}},St=10,Pt=async e=>{let{name:t,ext:n}=O.parse(e),r=e,o=O.join(k.cwd(),D,r),s=0;for(;await Ot(o);){if(s>=St)throw new Error("Failed to generate context file");r=`${t}-${Rt.randomUUID().slice(0,5)}${n}`,o=O.join(k.cwd(),D,r),s+=1}return r},Ot=async e=>{try{return await V.access(e),!0}catch{return!1}},kt=async()=>{try{console.log("Fetching Netlify features context...");let e=await fetch("https://docs.netlify.com/ai-context/context-consumers",{signal:AbortSignal.timeout(1e4)});if(!e.ok)throw new Error(`Failed to fetch context consumers: ${e.status} ${e.statusText}`);let t=await e.json();if(!t||typeof t!="object"||!Array.isArray(t.consumers))return console.warn("Invalid response structure: missing or invalid consumers array"),null;let n=t.consumers.find(r=>r&&typeof r=="object"&&r.key==="catchall-consumer");return n?!n.contextScopes||typeof n.contextScopes!="object"?(console.warn("Catchall consumer missing or invalid contextScopes"),null):n:(console.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?console.warn("Netlify features context request timed out"):console.warn("Failed to fetch Netlify features context:",e.message),null}},bt=async(e,t)=>{try{let n=await fetch(e,{signal:AbortSignal.timeout(1e4)});if(!n.ok)throw new Error(`Failed to fetch ${e}: ${n.status} ${n.statusText}`);let r=await n.text();return await V.writeFile(t,r,"utf-8"),!0}catch(n){return n.name==="AbortError"?console.warn(`Download timeout for ${e}`):console.warn(`Failed to download context file ${e}:`,n.message),!1}},Ft=async()=>{let e=await kt();if(!e)return[];let t=O.join(k.cwd(),D,le);await V.mkdir(t,{recursive:!0});let n=Object.entries(e.contextScopes).map(async([s,a])=>{if(!a||typeof a!="object"||!a.endpoint||!a.scope)return console.warn(`Invalid scope data for ${s}, skipping...`),null;let i=`${s}.md`,l=O.join(t,i),d=O.join(D,le,i);return console.log(`Downloading ${a.scope} context...`),await bt(a.endpoint,l)?(console.log(`Downloaded: ${d}`),{scope:a.scope,path:d,key:s}):null});return(await Promise.all(n)).filter(s=>s!==null)},Ue=async({cliPath:e,netlify:t,config:n})=>{let r=At(t),o=vt(),s=await Pt(Z),a=O.join(k.cwd(),D);await V.mkdir(a,{recursive:!0});let i=O.join(D,s),l=O.join(k.cwd(),i),d=`# Agent Context
27
-
28
- In Netlify documentation and interfaces, the terms "site" and "project" refer to the same thing.
29
-
30
- If you need to start a local development server in order to fulfill the request, try using the Netlify CLI over by running the shell command '${e} dev'. This will start a local HTTP server on port 8888, including live-reloading of any changes and, most critically, it offers local emulation for all Netlify features.
31
-
32
- ## Netlify Site
33
- - Site ID: ${r.siteId}
34
- - Account ID: ${r.accountId}
35
- - User ID: ${r.userId}
36
- - Site Slug: ${r.siteSlug}
37
- - Netlify Functions directory: ${r.functionsDir}
38
- - Running Node Version: ${o.nodeVersion}
39
-
40
- The available environment variables are set globally (e.g. \`echo $VARIABLE_NAME\` can be used to check if a var is set).:
41
-
42
- ## Attachments
43
-
44
- - for requests that require work with attachments or assets, take into account that uploaded attachments are stored in .netlify/assets folder
45
- - move assets from .netlify/assets folder to the project assets folder if they are referenced in a code or applied changes
46
-
47
- ## Netlify CLI
48
- 'netlify-cli' npm package is already available as a global package.
49
- Don't try to install it, in case you want to use it, use the global package.
50
-
51
- `;n.siteContext&&n.siteContext.length!==0&&(d+=`
52
- # Project Guidelines
53
- <project_guidelines>
54
- ${n.siteContext.filter(f=>f.site_context).map(f=>typeof f.site_context=="string"?f.site_context:typeof f.site_context=="object"?JSON.stringify(f.site_context):"").join(`
55
-
56
- `)}
57
- </project_guidelines>
58
- `);let c=await Ft();if(c.length>0&&(d+=`
59
- # Netlify Features Context
22
+ \`\`\``)}catch(s){Z.error("Could not decode outputMsg",s,t.output)}return{title:n,message:o}};import Yt from"fs/promises";import Gt from"os";import de from"path";import q from"process";var ne=_("runner_gemini"),Mt="Gemini CLI",Bt=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(ne.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(ne.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(ne.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0})),Ht={list_directory:"List",read_file:"Read",write_file:"Write",glob:"Find",search_file_content:"Find",replace:"Edit",run_shell_command:"Run",web_fetch:"Web Fetch",web_search:"Web Search",read_many_files:"Read Many",save_memory:"Memorize"};async function Se({config:e,netlify:t,persistSteps:r,sendSteps:n,aiGateway:o}){let{accountType:s,prompt:l,modelVersionOverrides:a}=e,{model:i}=e;if(o){let{token:f,url:d}=o;if(!f||!d)throw new Error("No token or url provided from AI Gateway");let u=qt[s];if(!u)throw new Error(`Gemini is not supported for the account type ${s}`);if(i&&!u?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(a?.gemini){let E=a?.gemini?.[s];E&&(i=E)}q.env.GEMINI_API_KEY=f,q.env.GOOGLE_GEMINI_BASE_URL=d}else if(!q.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let p=[],c=[],h=[],m={},y=0,x=0,T,g,I=de.join(q.cwd(),"node_modules"),C=[de.join(q.env.NODE_PATH||I,".bin/gemini"),...i?["--model",i]:[],"--yolo","-p",l],S=`${q.env.NVM_BIN}/node`;ne.log(`Running ${S} ${C.join(" ")}`);let R=t.utils.run(S,C,{all:!0,env:q.env});R.stdin?.end();let w=ue(()=>{r?.({steps:p,duration:x}),n?.({steps:c,duration:x}),c=[]},250),A=(f,d)=>{f.id=y,y+=1,h.push(f),p.push(f),c.push(f),d||w.flush(),w(),d&&w.flush()},N="";return R.all.on("data",f=>{if(N+=f.toString(),!f.includes(`
23
+ `))return;let d=N.toString().split(`
24
+ `).filter(Boolean).map(u=>{try{if(u.startsWith("[API Error")){let E=u.match(/\[api error: (.+?)]$/i)?.[1];return{type:"error",value:ce(E,!1)?.error?.message||E||"Gemini encountered error"}}return JSON.parse(u)}catch{}return null}).filter(Boolean);N="",d.forEach(u=>{switch(u.type){case"thought":{let E=u.value;A({title:E?.subject??"Thinking...",message:E?.description},!0);break}case"content":{u.value&&A({message:u.value});break}case"tool_call_request":{let E=u.value,L=Ht[E.name]??E.name,B=E.args?.path||E.args?.absolute_path,b=B&&de.relative(q.cwd(),B),D=E.args?.command,ft={title:[L,b&&`\`${b}\``,D&&`\`${D}\``].filter(Boolean).join(" ")};m[E.callId]=ft,w.flush();break}case"tool_result":{let E=u.value,L=m[E.callId];if(L){let B=[E.resultDisplay,E.responseParts?.functionResponse?.response?.output].find(b=>typeof b=="string"&&b);B&&(L.message=`\`\`\`
25
+ ${B.trim()}
26
+ \`\`\``),A(L,!0)}break}case"result":{x=u.duration_ms,T=u.value,[h,p,c].forEach(E=>{E[E.length-1]?.message===T&&E.pop()});break}case"error":{g=u.value;break}case"finished":break;default:{ne.warn("Unhandled message type:",u.type);break}}})}),await R.catch(f=>{({error:g,result:T}=Bt({catchError:f,runCmd:R,error:g,result:T,runnerName:"Gemini"}))}),w.flush(),{steps:h,duration:x,result:await X({initialResult:T,agentName:Mt,hasError:!!g}),error:z({error:g})}}var et=async()=>{let e=de.join(Gt.homedir(),".gemini");await Yt.rm(e,{recursive:!0,force:!0})},qt={[Y]:{models:{"gemini-1.5-flash":{maxTokens:8192},"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-1.5-pro":{maxTokens:8192},"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:65536},"gemini-2.5-flash-lite":{maxTokens:65536},"gemini-2.5-pro":{maxTokens:65536},"imagen-4.0-generate-001":{},"veo-3.0-generate-preview":{}}},pro:{models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[j]:{models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[G]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}},[U]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}}};var Vt={codex:{runner:ve,clean:Qe},claude:{runner:Ce,clean:Ze},gemini:{runner:Se,clean:et}},tt=Vt;var rt=async({config:e,apiThrottle:t,apiToken:r})=>{let n=Kt();return se(n,"init-stage",async o=>{let s=performance.now();o?.setAttributes({"init.runner":e.runner,"init.id":e.id,"init.sessionId":e.sessionId,"init.hasRepo":e.hasRepo,"init.useGateway":e.useGateway,"init.validateAgent":e.validateAgent});let l=tt[e.runner];if(!l)throw o?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let a=Wt({apiToken:r});Fe(a);let i=e.useGateway?await je({netlify:a,config:e}):void 0;o?.setAttributes({"init.aiGateway.created":!!i}),e.validateAgent&&e.errorLogsPath&&o?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let p=qe(({steps:m=[],duration:y})=>{let x=[...m];return m.length=0,J(e.id,e.sessionId,{steps:x,duration:y})},t),c;e.hasRepo?e.sha?(c=e.sha,o?.setAttributes({"init.sha.source":"provided"})):(c=await Xe(a),await le(e.id,{sha:c}),o?.setAttributes({"init.sha.source":"current_commit"})):(c=await ze(a),o?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let h=performance.now()-s;return o?.setAttributes({"init.sha":c||"unknown","init.duration.ms":h,"init.status":"success"}),{aiGateway:i,context:a,persistSteps:p,runner:l,sha:c}})},Wt=({apiToken:e})=>({constants:{NETLIFY_API_HOST:fe.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||fe.env.NETLIFY_API_TOKEN,SITE_ID:fe.env.SITE_ID,FUNCTIONS_DIST:fe.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:Ge}});import Jt from"crypto";import V from"fs/promises";import k from"path";import F from"process";var P=_("context"),Xt=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:F.env.NETLIFY_TEAM_ID,userId:F.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:F.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},zt=10,Zt=async e=>{let{name:t,ext:r}=k.parse(e),n=e,o=k.join(F.cwd(),$,n),s=0;for(;await Qt(o);){if(s>=zt)throw new Error("Failed to generate context file");n=`${t}-${Jt.randomUUID().slice(0,5)}${r}`,o=k.join(F.cwd(),$,n),s+=1}return n},Qt=async e=>{try{return await V.access(e),!0}catch{return!1}},er=async()=>{try{P.log("Fetching Netlify features context...");let e=await fetch("https://docs.netlify.com/ai-context/context-consumers",{signal:AbortSignal.timeout(1e4)});if(!e.ok)throw new Error(`Failed to fetch context consumers: ${e.status} ${e.statusText}`);let t=await e.json();if(!t||typeof t!="object"||!Array.isArray(t.consumers))return P.warn("Invalid response structure: missing or invalid consumers array"),null;let r=t.consumers.find(n=>n&&typeof n=="object"&&n.key==="catchall-consumer");return r?!r.contextScopes||typeof r.contextScopes!="object"?(P.warn("Catchall consumer missing or invalid contextScopes"),null):r:(P.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?P.warn("Netlify features context request timed out"):P.warn("Failed to fetch Netlify features context:",e.message),null}},tr=async(e,t)=>{try{let r=await fetch(e,{signal:AbortSignal.timeout(1e4)});if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let n=await r.text();return await V.writeFile(t,n,"utf-8"),!0}catch(r){return r.name==="AbortError"?P.warn(`Download timeout for ${e}`):P.warn(`Failed to download context file ${e}:`,r.message),!1}},me=null,rr=async()=>{if(me)return me;let e=await er();if(!e)return[];let t=k.join(F.cwd(),$,we);await V.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([o,s])=>{if(!s||typeof s!="object"||!s.endpoint||!s.scope)return P.warn(`Invalid scope data for ${o}, skipping...`),null;let l=`${o}.md`,a=k.join(t,l),i=k.join($,we,l);return P.log(`Downloading ${s.scope} context...`),await tr(s.endpoint,a)?(P.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:o}):null});return me=(await Promise.all(r)).filter(o=>o!==null),me},nt=async({cliPath:e,netlify:t,config:r,buildErrorContext:n})=>{let o=Xt(t),s=await Zt(Me),l=k.join(F.cwd(),$);await V.mkdir(l,{recursive:!0});let a=k.join($,s),i=k.join(F.cwd(),a),p=k.join(F.cwd(),$,re);try{await V.unlink(p),P.log(`Deleted old results file: ${p}`)}catch{}let c=n?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
27
+ Your task is to analyze and fix the build errors.
28
+ Don't apply techniques of reverting changes. Apply fixes related to errors.
29
+ Don't try to run build by yourself. Just fix the errors.
60
30
 
61
- If the user request is explicitly related to a specific Netlify feature (e.g., Forms, Identity, Functions, etc.), you MUST review the relevant documentation below in addition to reviewing the project files.
62
- DO NOT force the use of any Netlify feature if the user request does not explicitly require it or if the project has alternative implementations in place already.
31
+ <build_error_context>
32
+ ${c}
33
+ </build_error_context>`:"",h="";r.siteContext&&r.siteContext.length!==0&&(h=`
34
+ <project_rules>
35
+ ${r.siteContext.filter(g=>g.site_context).map(g=>typeof g.site_context=="string"?g.site_context:typeof g.site_context=="object"?JSON.stringify(g.site_context):"").join(`
63
36
 
64
- ${c.map(f=>`- **${f.scope}**: ${f.path}`).join(`
65
37
  `)}
66
-
67
- Refer to these files when working with specific Netlify features.
68
- `),d+=`
69
- Additional Documentation Resources
70
- - Netlify Docs: https://docs.netlify.com
71
- - LLM Resources Index: https://docs.netlify.com/llms.txt
72
- `,n.sessionHistoryContext?.length){let f=O.join(k.cwd(),D,ae);await V.mkdir(f,{recursive:!0});let m=await Promise.all(n.sessionHistoryContext.map(async(y,E)=>{let g=E+1,N=`attempt-${g}.md`,v=O.join(f,N),S=O.join(D,ae,N),C=`# Task History - Attempt ${g}
38
+ </project_rules>
39
+ `);let m="";if(r.sessionHistoryContext?.length){let g=k.join(F.cwd(),$,xe);await V.mkdir(g,{recursive:!0});let I=await Promise.all(r.sessionHistoryContext.map(async(C,S)=>{let R=S+1,w=`attempt-${R}.md`,A=k.join(g,w),N=k.join($,xe,w),f=`# Task History - Attempt ${R}
73
40
 
74
41
  ## Request - what the user asked for
75
- ${y.request}
42
+ ${C.request}
76
43
 
77
44
  ---
78
45
 
79
46
  ## Response - what the agent replied with after its work
80
47
 
81
- ${y.response}
82
- `;return await V.writeFile(v,C,"utf-8"),console.log(`Created history file: ${S}`),S}));d+=`# History of prior work on this task
48
+ ${C.response}
49
+ `;return await V.writeFile(A,f,"utf-8"),P.log(`Created history file: ${N}`),N}));m+=`
50
+ <session_history_context>
51
+ History of prior work on this task.
52
+ You MUST review ALL of the files below as context to understand the context of previous attempts. Use this information to continue the discussion appropriately.
83
53
 
84
- You MUST review ALL of the files below as context to understand the context of previous attempts. Use this information to continue the discussion appropriately.
54
+ ${I.slice(-5).map(C=>`- ${C}`).join(`
55
+ `)}
85
56
 
86
- ${m.map(y=>`- ${y}`).join(`
57
+ </session_history_context>
58
+ `}let y=await rr(),x="";y.length>0&&(x=`
59
+ <netlify_features_context>
60
+ If the user request is explicitly related to a specific Netlify feature (e.g., Netlify Forms, Netlify Functions, etc.), you MUST review the relevant documentation below in addition to reviewing the project files.
61
+ DO NOT force the use of any Netlify feature if the user request does not explicitly require it or if the project has alternative implementations in place already.
62
+
63
+ ${y.map(g=>`- **${g.scope}**: ${g.path}`).join(`
87
64
  `)}
88
- `}return await V.writeFile(l,d,"utf-8"),console.log(`Generated agent context document at: ${l}`),i},je=e=>`The build is currently failing after your changes.
89
- Your task is to analyze and fix the build errors.
90
- Don't apply techniques of reverting changes. Apply fixes related to errors.
91
- Don't try to run build by yourself. Just fix the errors.
92
65
 
93
- ${e}`;var Ye=(e={})=>`
94
- Check for errors and validate the fix
95
-
96
- ${e.errorLogsPath?`Error Check Process:
97
- 1. Read recent errors: \`tail -n 50 ${e.errorLogsPath} 2>/dev/null || echo "0"\` (single check, no monitoring loop)
98
- 2. If errors are found, fix them by modifying the codebase
99
- 3. After fixes, do ONE final check: \`tail -n 20 ${e.errorLogsPath} 2>/dev/null || echo "No recent errors available"\`
100
- 4. Focus only on errors related to your changes
101
- 5. Ignore unrelated operational messages (git, API calls, plugin startup)
102
- 6. NEVER modify ${e.errorLogsPath} - it's read-only
103
- 7. Do NOT use continuous monitoring or repeated tail commands
104
- `:""}
105
-
106
- Fix Strategy:
107
- - Check error logs ONCE, fix issues, then do ONE final verification
108
- - Do NOT revert changes - improve the codebase to make it work
109
- - Do NOT continuously monitor logs or use tail in loops
110
- - Dev server is running in background, no need to run build or dev server yourself
111
- - Complete the validation quickly and decisively
112
-
113
- At the very end, print exactly one line with the verdict:
114
- VALIDATION_RESULT: PASS {"checks": ["error_logs"]}
115
- or
116
- VALIDATION_RESULT: FAIL {"checks": ["error_logs"], "errors": ["<errors>"]}
117
- `;var Dt=(e=Z)=>`Use ${e} to understand the Netlify project context and resources. It also contains history of previous conversations. READ ALL OF IT. Make sure to read it first. Never reveal, cite, or paraphrase private context.`,$t=async({cliPath:e,config:t,netlify:n})=>{let r=await Ue({cliPath:e,netlify:n,config:t});return{context:Dt(r)}},Lt=({config:e})=>{let t=[];return e?.validateAgent&&t.push(Ye(e)),t},Me=async({cliPath:e,config:t,netlify:n,buildErrorContext:r}={})=>{let{context:o}=await $t({cliPath:e,config:t,netlify:n}),s;s=[...Lt({config:t})],r&&(s=[...s,je(r)]);let a=[];return o&&a.push(o),t.prompt&&a.push("New user request comes in the <new_request> tag.",`<new_request>${t.prompt}</new_request>`),s?.length&&a.push(s.join(`
118
-
119
- `)),{prompt:a.join(`
120
-
121
- `)}};var fe=async({cliPath:e,config:t,context:n,buildErrors:r,runner:o,persistSteps:s,aiGateway:a})=>{let{prompt:i}=await Me({cliPath:e,config:t,buildErrorContext:Ut(r),netlify:n}),l={...t,prompt:i},d=await o({aiGateway:a,config:l,netlify:n,persistSteps:s});if(d.error)throw console.error("Runner failed",{stepsCount:d.steps.length,duration:d.duration,error:d.error}),new Error(d.error);return{runnerResult:d}},Ut=e=>!e||e.length===0?"":`
66
+ Refer to these files when working with specific Netlify features.
67
+ </netlify_features_context>
68
+ `);let T=`
69
+ You're an AI agent designed to assist with tasks related to a Netlify project. Please review, understand, and use the context provided to complete the user's request as needed.
70
+
71
+ <request>
72
+ <user_request>
73
+ ${r.prompt}
74
+ </user_request>
75
+ ${c}
76
+ </request>
77
+
78
+ <requirements>
79
+ <responses>
80
+ - Do not speak in first person. You may speak as "the agent".
81
+ - When your work is complete, create a changelog summary in ${l}/${re} that is pull request or changelog blog appropriate for the primary work that was completed.
82
+ - Do not attempt to create git commits, PRs, etc. directly. You can use git to review information if required but the system that runs this agent will handle creating PRs or commits of the changes it performs.
83
+ </responses>
84
+ <attachements>
85
+ - for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${l}/${Ne} folder
86
+ - move assets from ${l}/${Ne} folder to the project assets folder if they are referenced in a code or applied changes
87
+ </attachements>
88
+ ${h}
89
+ </requirements>
90
+
91
+ <extra_context>
92
+ <metadata>
93
+ - Site/Project ID: ${o.siteId}
94
+ - Account/Team ID: ${o.accountId}
95
+ - User ID: ${o.userId}
96
+ - Site/Project Slug: ${o.siteSlug}
97
+ - Netlify Functions directory: ${o.functionsDir}
98
+ </metadata>
99
+ <environment>
100
+ - Node Version: ${F.version||"unknown"}
101
+ - Environment variables are set globally (e.g. \`echo $VARIABLE_NAME\` can be used to check if a var is set).
102
+ - 'netlify-cli' npm package is already available as a global package. Don't try to install it again
103
+ - If you need to start a local development server in order to fulfill the request, try using the Netlify CLI over by running the shell command '${e} dev'. This will start a local HTTP server on port 8888, including live-reloading of any changes and, most critically, it offers local emulation for all Netlify features.
104
+ </environment>
105
+ ${x}
106
+ <docs>
107
+ - Netlify Docs: https://docs.netlify.com
108
+ - LLM Resources Index: https://docs.netlify.com/llms.txt
109
+ </docs>
110
+ </extra_context>
111
+
112
+ ${m}
113
+ `;return await V.writeFile(i,T,"utf-8"),P.log(`Generated agent context document at: ${i}`),T.length>5e5&&(T=`
114
+ You're an AI agent designed to assist with tasks related to a Netlify project. Please review, understand, and use the context provided to complete the user's request as needed.
115
+
116
+ <request>
117
+ <user_request>
118
+ ${r.prompt}
119
+ </user_request>
120
+ ${c}
121
+ </request>
122
+
123
+ Use the following file for the complete context of the ask, the environment, and what's available. ${i} You MUST READ ALL OF IT. Make sure to read it first. Never cite or paraphrase private context.
124
+ `),T};var nr=_("prompt"),ot=async({cliPath:e,config:t,netlify:r,buildErrorContext:n})=>{let o=await nt({cliPath:e,config:t,netlify:r,buildErrorContext:n});return process.env.AGENT_RUNNER_DEBUG&&nr.log("Contextful Prompt:",o),{prompt:o}};var or=_("inference_stage"),Pe=async({cliPath:e,config:t,context:r,buildErrors:n,runner:o,persistSteps:s,aiGateway:l})=>{let{prompt:a}=await ot({cliPath:e,config:t,buildErrorContext:sr(n),netlify:r}),i={...t,prompt:a},p=await o({aiGateway:l,config:i,netlify:r,persistSteps:s});if(await s.flush(),p.error)throw or.error("Runner failed",{stepsCount:p.steps.length,duration:p.duration,error:p.error}),new Error(p.error);return{runnerResult:p}},sr=e=>!e||e.length===0?"":`
122
125
  Deploy failed failed. Here are the errors to review on the latest build:
123
126
 
124
127
  Below are all of the logs with potential issues that we extracted. Some of them may be false positives, discern them carefully and ensure fixes are relevant.
125
128
 
126
129
  ${e.pop()}
127
- `;import jt from"process";var Ge=async({netlify:e,hasRepo:t,skipBuild:n,message:r="Agent Preview",deploySubdomain:o,cliPath:s,filter:a})=>{try{let i=["deploy","--message",`"${r}"`,"--json","--draft","--verbose"];t||(console.log("Deploy: Uploading source zip"),i.push("--upload-source-zip")),o&&i.push("--alias",o),a&&i.push("--filter",a),n?(console.log("Deploy: Skipping build"),i.push("--no-build")):i.push("--context","deploy-preview");let l=s||"netlify";console.log(`Running: ${l} ${i.join(" ")}`);let d=await e.utils.run(l,i,{stdio:["ignore","pipe","pipe"]}),c=JSON.parse(d.stdout.trim());console.log(`
128
- Preview deploy created successfully:`,{deployId:c.deploy_id,deployUrl:c.deploy_url,siteId:c.site_id});let f={deployId:c.deploy_id,previewUrl:c.deploy_url,logsUrl:c.logs,siteId:c.site_id};return t||(f.sourceZipFilename=c.source_zip_filename),f}catch(i){throw console.error("Failed to create preview deploy via CLI:",i),i}};var me=async({cliPath:e,config:t,context:n,result:r,filter:o})=>{let s=await Pe({config:t,netlify:n});if(!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:i,diffBinary:l,resultDiffBinary:d}=s,c=!0;console.log("Preview deploy condition check:",{resultUndefined:r===void 0,resultType:typeof r,hasChanges:c,wouldCreatePreview:r!==void 0&&c});let f=null;if(r!==void 0&&c)try{let m;try{let y=await Te(t.id,t.sessionId);y?.title&&(m=y.title)}catch(y){console.warn("Failed to fetch session title, using fallback message:",y.message)}f=await Ge({cliPath:e,netlify:n,hasRepo:t.hasRepo,message:m,skipBuild:!1,deploySubdomain:Ae(t.id,jt.env.SITE_NAME),filter:o})}catch(m){return console.warn("Failed to create preview deploy (continuing with agent run):",m),{diff:a,resultDiff:i,hasChanges:c,previewInfo:null,diffBinary:l,resultDiffBinary:d,deployError:m instanceof Error?m.message:String(m)}}return console.log("Git status",{hasDiff:!!a,hasChanges:c}),{diff:a,resultDiff:i,hasChanges:c,previewInfo:f,diffBinary:l,resultDiffBinary:d}};async function Be(e,t){let{maxRetries:n,baseDelay:r,onRetry:o}=t,s;for(let a=1;a<=n;a++)try{return await e()}catch(i){if(s=i,a===n)throw s;o&&o(a,s),await new Promise(l=>setTimeout(l,r*a))}throw s}var He=async({config:e,diff:t,result:n,duration:r,resultDiff:o,diffBinary:s,resultDiffBinary:a,previewInfo:i})=>{let l={result_diff:t,result:n||"Done",duration:r,result_diff_binary:s};return i&&i.deployId&&(l.deploy_id=i.deployId),i&&i.sourceZipFilename&&(l.result_zip_file_name=i.sourceZipFilename),o||a?(console.log("Updating total agent result diff"),await z(e.id,{result_diff:o,result_diff_binary:a})):console.log("No total result diff, not updating"),console.log("Updated agent runner with result"),await Be(()=>q(e.id,e.sessionId,l),{maxRetries:3,baseDelay:1e3,onRetry:(d,c)=>{console.error(`Error updating agent runner session (attempt ${d}):`,c),console.log("Retrying...")}}),console.log("Finished updating agent runner with result"),{sessionUpdate:l}};import{getTracer as Mt}from"@netlify/otel";var Gt=Yt(import.meta.url),Bt=Gt("../package.json"),ge=3,Ve=async({config:e,apiToken:t,cliPath:n="netlify",cwd:r,errorLogsPath:o,filter:s})=>{let a;try{await _e(Bt.version,e.id);let i=Mt(),l,{aiGateway:d,context:c,persistSteps:f,runner:m,sha:y}=await Le({config:e,apiToken:t,cliPath:n,cwd:r,errorLogsPath:o,filter:s});a=m.clean,e.sha=y;let{runnerResult:E}=await fe({cliPath:n,config:e,context:c,runner:m.runner,persistSteps:f,aiGateway:d}),g=await me({cliPath:n,config:e,context:c,result:E.result,filter:s}),N=E,v=[];if(g.hasChanges&&g.deployError){console.log("Deploy validation enabled, starting deploy-fix iteration process"),v.push(ye(g.deployError));let T=1;for(;T<=ge&&!g.previewInfo;)await J(i,"stage-deploy",async _=>{_?.setAttributes({"stage.attempt":T});let{runnerResult:p}=await fe({cliPath:n,config:e,context:c,runner:m.runner,persistSteps:f,aiGateway:d,buildErrors:v});N={...p,steps:[...N.steps||[],...p.steps||[]],duration:(N.duration||0)+(p.duration||0)},g=await me({cliPath:n,config:e,context:c,result:p.result,filter:s}),g.deployError&&v.push(g.deployError),T++});T>ge&&!g.previewInfo&&(l=new Error(`Deploy validation failed after ${ge} attempts`))}let{diff:S,resultDiff:C,previewInfo:w,diffBinary:x,resultDiffBinary:R}=g;if(await He({config:e,diff:S,result:N.result,duration:N.duration,resultDiff:C,diffBinary:x,resultDiffBinary:R,previewInfo:w}),l)throw l;await m.clean?.()}catch(i){console.error("Got error while running pipeline",i),await a?.();let l=i instanceof Error&&i.message;throw await q(e.id,e.sessionId,{result:l||"Encountered error when running agent",state:"error"}),i}};import A from"process";var Ht="codex",Vt=e=>(e??[]).filter(t=>t.request&&t.response),qt=e=>(e??[]).filter(t=>t.site_context),qe=()=>{let e=A.env.NETLIFY_AGENT_RUNNER_ID,t=A.env.NETLIFY_AGENT_RUNNER_SESSION_ID;if(!e||!t)throw new Error("ID of agent runner is not provided");let n=A.env.NETLIFY_AGENT_RUNNER_RESULT_BRANCH,r=A.env.NETLIFY_AGENT_RUNNER_PROMPT;if(!r)throw new Error("Prompt is not provided");let o=A.env.NETLIFY_AGENT_RUNNER_AGENT||Ht,s=A.env.NETLIFY_AGENT_RUNNER_MODEL,a=A.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED==="1",i=A.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED==="1",l=A.env.ERROR_LOGS_PATH,d=ee(A.env.NETLIFY_AGENT_RUNNER_CONTEXT),c=Vt(d),f=qt(d),m=A.env.NETLIFY_AGENT_RUNNER_HAS_REPO!=="0",y=!A.env.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED,E=A.env.NETLIFY_AGENT_RUNNER_SHA,g=Kt(),N=ve();return{id:e,sessionId:t,resultBranch:n,prompt:r,runner:o,model:s,validateAgent:a,errorLogsPath:l,sessionHistoryContext:c,siteContext:f,hasRepo:m,useGateway:y,sha:E,accountType:g,validateAgentWithBuild:i,modelVersionOverrides:N}},Kt=()=>{let e=A.env.NETLIFY_TEAM_TYPE;return e?e.includes("personal")?L:e.includes("pro")?"pro":e.startsWith("enterprise")?U:e.startsWith("free")?j:$:$};var K=Jt(Ke.argv.slice(2),{string:["auth","cwd","cli-path","error-logs-path","filter"]});try{let e=qe();await Ve({config:e,apiToken:K.auth,cwd:K.cwd,cliPath:K["cli-path"],errorLogsPath:K["error-logs-path"],filter:K.filter})}catch(e){console.error("Error running agent pipeline:",e),Ke.exit(1)}
130
+ `;import ir from"process";var oe=_("deploy"),st=async({netlify:e,hasRepo:t,skipBuild:r,message:n="Agent Preview",deploySubdomain:o,cliPath:s,filter:l})=>{try{let a=["deploy","--message",`"${n}"`,"--json","--draft","--verbose"];t||(oe.log("Deploy: Uploading source zip"),a.push("--upload-source-zip")),o&&a.push("--alias",o),l&&a.push("--filter",l),r?(oe.log("Deploy: Skipping build"),a.push("--no-build")):a.push("--context","deploy-preview");let i=s||"netlify";oe.log(`Running: ${i} ${a.join(" ")}`);let p=await e.utils.run(i,a,{stdio:["ignore","pipe","pipe"]}),c=JSON.parse(p.stdout.trim());oe.log(`
131
+ Preview deploy created successfully:`,{deployId:c.deploy_id,deployUrl:c.deploy_url,siteId:c.site_id});let h={deployId:c.deploy_id,previewUrl:c.deploy_url,logsUrl:c.logs,siteId:c.site_id};return t||(h.sourceZipFilename=c.source_zip_filename),h}catch(a){throw oe.error("Failed to create preview deploy via CLI:",a),a}};var ge=_("deploy_stage"),Oe=async({cliPath:e,config:t,context:r,result:n,filter:o})=>{let s=await Je({config:t,netlify:r});if(!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:l,resultDiff:a,diffBinary:i,resultDiffBinary:p}=s,c=!0;ge.log("Preview deploy condition check:",{resultUndefined:n===void 0,resultType:typeof n,hasChanges:c,wouldCreatePreview:n!==void 0&&c});let h=null;if(n!==void 0&&c)try{let m;try{let y=await Le(t.id,t.sessionId);y?.title&&(m=y.title)}catch(y){ge.warn("Failed to fetch session title, using fallback message:",y.message)}h=await st({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:m,skipBuild:!1,deploySubdomain:Ve(t.id,ir.env.SITE_NAME),filter:o})}catch(m){return ge.warn("Failed to create preview deploy (continuing with agent run):",m),{diff:l,resultDiff:a,hasChanges:c,previewInfo:null,diffBinary:i,resultDiffBinary:p,deployError:m instanceof Error?m.message:String(m)}}return ge.log("Git status",{hasDiff:!!l,hasChanges:c}),{diff:l,resultDiff:a,hasChanges:c,previewInfo:h,diffBinary:i,resultDiffBinary:p}};async function it(e,t){let{maxRetries:r,baseDelay:n,onRetry:o}=t,s;for(let l=1;l<=r;l++)try{return await e()}catch(a){if(s=a,l===r)throw s;o&&o(l,s),await new Promise(i=>setTimeout(i,n*l))}throw s}var Q=_("cleanup_stage"),at=async({config:e,diff:t,result:r,duration:n,resultDiff:o,diffBinary:s,resultDiffBinary:l,previewInfo:a})=>{let i={result_diff:t,result:r||"Done",duration:n,result_diff_binary:s};return a&&a.deployId&&(i.deploy_id=a.deployId),a&&a.sourceZipFilename&&(i.result_zip_file_name=a.sourceZipFilename),o||l?(Q.log("Updating total agent result diff"),await le(e.id,{result_diff:o,result_diff_binary:l})):Q.log("No total result diff, not updating"),Q.log("Updated agent runner with result"),await it(()=>J(e.id,e.sessionId,i),{maxRetries:3,baseDelay:1e3,onRetry:(p,c)=>{Q.error(`Error updating agent runner session (attempt ${p}):`,c),Q.log("Retrying...")}}),Q.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as lr}from"@netlify/otel";var ur=ar(import.meta.url),cr=ur("../package.json"),lt=_("pipeline_index"),he=3,ut=async({config:e,apiToken:t,cliPath:r="netlify",cwd:n,errorLogsPath:o,filter:s,traceExporterUrl:l})=>{let a;try{await be(cr.version,e.id,l);let i=lr(),p,{aiGateway:c,context:h,persistSteps:m,runner:y,sha:x}=await rt({config:e,apiToken:t,cliPath:r,cwd:n,errorLogsPath:o,filter:s});a=y.clean,e.sha=x;let{runnerResult:T}=await Pe({cliPath:r,config:e,context:h,runner:y.runner,persistSteps:m,aiGateway:c}),g=await Oe({cliPath:r,config:e,context:h,result:T.result,filter:s}),I=T,C=[];if(g.hasChanges&&g.deployError){C.push($e(g.deployError));let f=1;for(;f<=he&&!g.previewInfo;)lt.log(`Deploy attempt had errors. Retrying. ${f}/${he}`),await se(i,"stage-deploy",async d=>{d?.setAttributes({"stage.attempt":f});let{runnerResult:u}=await Pe({cliPath:r,config:e,context:h,runner:y.runner,persistSteps:m,aiGateway:c,buildErrors:C});I={...u,steps:[...I.steps||[],...u.steps||[]],duration:(I.duration||0)+(u.duration||0)},g=await Oe({cliPath:r,config:e,context:h,result:u.result,filter:s}),g.deployError&&C.push(g.deployError),f++});f>he&&!g.previewInfo&&(p=new Error(`Deploy validation failed after ${he} attempts`))}let{diff:S,resultDiff:R,previewInfo:w,diffBinary:A,resultDiffBinary:N}=g;if(await at({config:e,diff:S,result:I.result,duration:I.duration,resultDiff:R,diffBinary:A,resultDiffBinary:N,previewInfo:w}),p)throw p;await y.clean?.()}catch(i){lt.error("Got error while running pipeline",i),await a?.();let p=i instanceof Error&&i.message;throw await J(e.id,e.sessionId,{result:p||"Encountered error when running agent",state:"error"}),i}};import O from"process";var pr="codex",dr=e=>(e??[]).filter(t=>t.request&&t.response),fr=e=>(e??[]).filter(t=>t.site_context),ct=_("config"),pt=()=>{let e=O.env.NETLIFY_AGENT_RUNNER_ID,t=O.env.NETLIFY_AGENT_RUNNER_SESSION_ID;if(!e||!t)throw new Error("ID of agent runner is not provided");let r=O.env.NETLIFY_AGENT_RUNNER_RESULT_BRANCH,n=O.env.NETLIFY_AGENT_RUNNER_PROMPT;if(!n)throw new Error("Prompt is not provided");let o=O.env.NETLIFY_AGENT_RUNNER_AGENT||pr,s=O.env.NETLIFY_AGENT_RUNNER_MODEL,l=O.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED==="1",a=O.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED==="1",i=O.env.ERROR_LOGS_PATH,p=ce(O.env.NETLIFY_AGENT_RUNNER_CONTEXT,!0,ct),c=dr(p),h=fr(p),m=O.env.NETLIFY_AGENT_RUNNER_HAS_REPO!=="0",y=!O.env.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED,x=O.env.NETLIFY_AGENT_RUNNER_SHA,T=mr(),g=Ke(),I={id:e,sessionId:t,resultBranch:r,prompt:n,runner:o,model:s,validateAgent:l,errorLogsPath:i,sessionHistoryContext:c,siteContext:h,hasRepo:m,useGateway:y,sha:x,accountType:T,validateAgentWithBuild:a,modelVersionOverrides:g};return ct.log({fullConfig:I}),I},mr=()=>{let e=O.env.NETLIFY_TEAM_TYPE;return e?e.includes("personal")?j:e.includes("pro")?"pro":e.startsWith("enterprise")?Y:e.startsWith("free")?G:U:U};var hr=_("bin_cmd"),ee=gr(dt.argv.slice(2),{string:["auth","cwd","cli-path","error-logs-path","filter","trace-exporter-url"]});try{let e=pt();await ut({config:e,apiToken:ee.auth,cwd:ee.cwd,cliPath:ee["cli-path"],errorLogsPath:ee["error-logs-path"],filter:ee.filter,traceExporterUrl:ee["trace-exporter-url"]})}catch(e){hr.error("Error running agent pipeline:",e),dt.exit(1)}
129
132
  //# sourceMappingURL=bin.js.map
package/dist/index.d.ts CHANGED
@@ -36,7 +36,8 @@ interface PipelineOptions {
36
36
  cwd?: string;
37
37
  errorLogsPath?: string;
38
38
  filter?: string;
39
+ traceExporterUrl?: string;
39
40
  }
40
- declare const runPipeline: ({ config, apiToken, cliPath, cwd, errorLogsPath, filter, }: PipelineOptions) => Promise<void>;
41
+ declare const runPipeline: ({ config, apiToken, cliPath, cwd, errorLogsPath, filter, traceExporterUrl, }: PipelineOptions) => Promise<void>;
41
42
 
42
43
  export { type Context, type PipelineOptions, runPipeline };
package/dist/index.js CHANGED
@@ -1,128 +1,131 @@
1
- import{createRequire as Ot}from"module";import{createTracerProvider as Ge}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as fe}from"@netlify/otel/opentelemetry";import{withActiveSpan as Ye}from"@netlify/otel";import{OTLPTraceExporter as He}from"@opentelemetry/exporter-trace-otlp-grpc";var me=(e,t)=>Ge({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new fe(new te),new fe(new He)]});function q(e,t,n){return console.log(`\u23F3 TRACE: ${t} starting...`),Ye(e,t,n)}var te=class{export(t,n){for(let r of t)this.logSpan(r);n({code:1})}async shutdown(){}forceFlush(){return Promise.resolve()}logSpan(t){let n=(t.endTime[0]-t.startTime[0])*1e3+(t.endTime[1]-t.startTime[1])/1e6,r=t.attributes,o=[];for(let[i,l]of Object.entries(r))i.includes("duration")&&typeof l=="number"?o.push(`${i}=${l.toFixed(2)}ms`):o.push(`${i}=${l}`);let s=t.status?.code===2?"\u274C":"\u2705",a=o.length>0?` [${o.join(", ")}]`:"";console.log(`${s} TRACE: ${t.name} completed in ${n.toFixed(2)}ms${a}`),t.status?.code===2&&t.status.message&&console.log(` \u274C Error: ${t.status.message}`)}};var Ve=["error","failed","exception","fatal","panic","abort","crash"];function ge(e){let t=e.split(`
2
- `),n=[],r=-1,o=0;for(;o<t.length;){let i=t[o].slice(0,500).toLowerCase();if(Ve.some(d=>i.includes(d))){let d=Math.max(0,o-10,r+1),u=Math.min(t.length-1,o+20),f=[];for(let m=d;m<=u;m++)f.push(t[m]);n.push(f.join(`
3
- `)),r=u,o=u+1}else o++}if(n.length===0)return e;let s=n.map((a,i)=>`<extracted_error_chunk order="${i+1}">
4
- ${a}
1
+ import{createRequire as Zt}from"module";import{createTracerProvider as st}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as ve}from"@netlify/otel/opentelemetry";import{withActiveSpan as it}from"@netlify/otel";import{OTLPTraceExporter as at}from"@opentelemetry/exporter-trace-otlp-grpc";function x(e){let t=!process.env.VITEST;return{log:(...r)=>{t&&console.log(`[AR]-[${e}]`,...r)},error:(...r)=>{t&&console.error(`[AR]-[${e}]`,...r)},warn:(...r)=>{t&&console.warn(`[AR]-[${e}]`,...r)},info:(...r)=>{t&&console.info(`[AR]-[${e}]`,...r)},debug:(...r)=>{t&&console.debug(`[AR]-[${e}]`,...r)}}}var me=x("tracing"),Pe=(e,t,r)=>st({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new ve(new ge),new ve(new at({url:r}))]});function ne(e,t,r){return me.log(`\u23F3 TRACE: ${t} starting...`),it(e,t,r)}var ge=class{export(t,r){for(let n of t)this.logSpan(n);r({code:1})}async shutdown(){}forceFlush(){return Promise.resolve()}logSpan(t){let r=(t.endTime[0]-t.startTime[0])*1e3+(t.endTime[1]-t.startTime[1])/1e6,n=t.attributes,o=[];for(let[a,i]of Object.entries(n))a.includes("duration")&&typeof i=="number"?o.push(`${a}=${i.toFixed(2)}ms`):o.push(`${a}=${i}`);let s=t.status?.code===2?"\u274C":"\u2705",l=o.length>0?` [${o.join(", ")}]`:"";me.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${l}`),t.status?.code===2&&t.status.message&&me.log(` \u274C Error: ${t.status.message}`)}};var lt=["error","failed","exception","fatal","panic","abort","crash"];function ke(e){let t=e.split(`
2
+ `),r=[],n=-1,o=0;for(;o<t.length;){let a=t[o].slice(0,500).toLowerCase();if(lt.some(d=>a.includes(d))){let d=Math.max(0,o-10,n+1),c=Math.min(t.length-1,o+20),h=[];for(let m=d;m<=c;m++)h.push(t[m]);r.push(h.join(`
3
+ `)),n=c,o=c+1}else o++}if(r.length===0)return e;let s=r.map((l,a)=>`<extracted_error_chunk order="${a+1}">
4
+ ${l}
5
5
  </extracted_error_chunk>`).join(`
6
6
 
7
- `);return s.length>e.length*.8?e:s}import ee from"process";import{getTracer as ht}from"@netlify/otel";import K from"process";var re=K.env.NETLIFY_API_URL,ne=K.env.NETLIFY_API_TOKEN,J=async(e,t={})=>{if(!re||!ne)throw new Error("No API URL or token");let n=new URL(e,re),r={...t,headers:{...t.headers,Authorization:`Bearer ${ne}`}};K.env.AGENT_RUNNERS_DEBUG==="true"&&(r.headers["x-nf-debug-logging"]="true"),t.json&&(r.headers||={},r.headers["Content-Type"]="application/json",r.body=JSON.stringify(t.json));let o=await fetch(n,r),s=o.ok&&o.status<=299;if(K.env.AGENT_RUNNERS_DEBUG==="true")console.log(`[DEBUG] Response headers for ${n}:`),o.headers.forEach((i,l)=>{console.log(` ${l}: ${i}`)});else{let i=o.headers.get("x-nf-request-id");console.log(`Request ID for ${n}: ${i||"N/A"}`)}if(s||console.error(`Got status ${o.status} for request ${n}`),t.raw){if(!s)throw o;return o}let a=await(o.headers.get("content-type")?.includes("application/json")?o.json():o.text());if(!s)throw a;return a},he=e=>{console.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(re=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(ne=e.constants.NETLIFY_API_TOKEN)},X=(e,t)=>J(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),M=(e,t,n)=>J(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:n});var ye=(e,t)=>J(`/api/v1/agent_runners/${e}/sessions/${t}`),_e=(e,t,n)=>J(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":n}});var xe=async({netlify:e,config:t})=>{let n,r,o,s,a=e.constants?.SITE_ID;if(!a)throw new Error("No site id");let i=async()=>{clearTimeout(o),console.log("Requesting AI gateway information");let l=await _e(a,t.id,t.sessionId);if({token:n,url:s}=l,r=l.expires_at?l.expires_at*1e3:void 0,console.log("Got AI gateway information",{token:!!n,expiresAt:r,url:s}),r){let d=r-Date.now()-6e4;d>0&&(o=setTimeout(()=>{i()},d))}};return await i(),{get url(){return s},get token(){return n}}};import Ee from"process";import{execa as qe,execaCommand as Xt}from"execa";var Ke={preferLocal:!0},Te=(e,t,n)=>{let[r,o]=Je(t,n),s={...Ke,...o},a=qe(e,r,s);return Xe(a,s),a};var Je=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Xe=(e,t)=>{t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0||(e.stdout?.pipe(Ee.stdout),e.stderr?.pipe(Ee.stderr))};var W="netlify-agent-runner-context.md",oe="task-history",se="netlify-context",$=".netlify",B="other",G="personal";var Y="enterprise",H="free";var We=e=>new Promise(t=>{setTimeout(t,e)}),we=(e,t=3e3)=>{let n=!1,r=null,o=[],s=null,a=(...i)=>{if(n)return r=i,new Promise(u=>{o.push(u)});n=!0;let l,d=new Promise(u=>{l=u});return s=(async()=>{await Promise.resolve();let u=await e(...i);for(l(u);;){if(await We(t),!r)return n=!1,s=null,u;let f=r,m=o;r=null,o=[],u=await e(...f),m.forEach(_=>{_(u)})}})(),d};return a.flush=async()=>{if((n||r)&&s)return await s,a.flush()},a},z=(e,t,n=!1)=>{let r=null,o=null,s=null,a=function(...i){o=i,s=this;let l=n&&!r;clearTimeout(r),r=setTimeout(()=>{r=null,n||(e.apply(s,o),o=null,s=null)},t),l&&(e.apply(s,o),o=null,s=null)};return a.cancel=()=>{clearTimeout(r),r=null,o=null,s=null},a.flush=()=>{if(r){clearTimeout(r);let i=o,l=s;r=null,o=null,s=null,e.apply(l,i)}},a},Ie=(e,t=!0)=>{if(e)try{return JSON.parse(e)}catch(n){t&&console.error("Could not parse JSON",n)}},Ce=(e,t)=>{let o=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let i=`--${t}${o}`;if(i.length>55)return"";let l=60-i.length;if(l<=0)return"";if(l>=s.length+6){let d=Math.min(l-s.length,e.length);return`${s}${e.slice(0,d)}`}return e.slice(0,l)};import{Buffer as Ne}from"buffer";var Re=async({config:e,netlify:t})=>{let n=await Ze(t),{hasChanges:r}=n,{status:o}=n;if(!r)return{hasChanges:!1};let s=await Qe(t,o);await t.utils.run("git",["add",".",...s]);let i=(await t.utils.run("git",["diff","--staged"])).stdout;if(r=!!i,!r)return{hasChanges:!1};let d=(await t.utils.run("git",["diff","--staged","--binary"])).stdout,u,f;if(e.sha){await t.utils.run("git",["commit","-m","Agent runner"]),u=(await t.utils.run("git",["diff",e.sha,"HEAD"])).stdout;let y=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"])).stdout;u!==y&&(f=Ne.from(y).toString("base64"))}let m={hasChanges:!0,diff:i,resultDiff:u};return i!==d&&(m.diffBinary=Ne.from(d).toString("base64")),f&&(m.resultDiffBinary=f),m},ze=["?? mise.toml",/\?\? .+?\.log/],Ze=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
8
- `).filter(o=>!ze.some(s=>s instanceof RegExp?s.test(o):o===s))).length!==0,status:t.stdout}};var Ae=async e=>{let{stdout:t}=await e.utils.run("git",["rev-parse","HEAD"]);return t.trim()},Se=async e=>{let{stdout:t}=await e.utils.run("git",["rev-list","--max-parents=0","HEAD"]);return t.trim()},Qe=async(e,t="")=>{let n=[".netlify","mise.toml","node_modules"],r=[],o=n.map(async a=>{try{return await e.utils.run("git",["check-ignore","-v",a]),null}catch{return`:!${a}`}});return(await Promise.all(o)).forEach(a=>{a&&r.push(a)}),t.split(`
9
- `).forEach(a=>{let i=a.match(/\?\? (.+?)\.log$/)?.[1];i&&r.push(`:!${i}.log`)}),r};import et from"fs/promises";import tt from"os";import Z from"path";import F from"process";var rt=({catchError:e,runCmd:t,error:n,result:r,runnerName:o})=>(console.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!n,hadExistingResult:!!r,resultLength:r?r.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),r?(console.log("Preserving existing result despite catch handler being triggered"),n?{error:n,result:r}:{error:"Process completed with errors but result was captured",result:r}):(console.log("Setting result to undefined because no valid result was captured"),{error:n||`${o} failed`,result:void 0}));async function ie({config:e,netlify:t,persistSteps:n,aiGateway:r}){let o=e,{accountType:s,prompt:a,modelVersionOverrides:i}=o,{model:l}=o;if(r){let{token:x,url:h}=r;if(!x||!h)throw new Error("No token or url provided from AI Gateway");let p=nt[s];if(!p)throw new Error(`Claude is not supported for the account type ${s}`);if(l&&!p?.models?.[l])throw new Error(`${l} is not supported for account type ${s}`);if(i?.claude){let c=i?.claude?.[s];c&&(l=c)}F.env.ANTHROPIC_API_KEY=x,F.env.ANTHROPIC_BASE_URL=h}else if(!F.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let d=[],u=[],f={},m=0,_=0,E,y,w=Z.join(F.cwd(),"node_modules"),A=[Z.join(F.env.NODE_PATH||w,".bin/claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...l?["--model",l]:[],"-p",a],S=`${F.env.NVM_BIN}/node`;console.log(`Running ${S} ${A.join(" ")}`);let N=t.utils.run(S,A,{all:!0,env:F.env});N.stdin?.end();let I=z(()=>{n?.({steps:d,duration:_})},250),T=(x,h)=>{let p={...x,id:m};m+=1,u.push(p),d.push(p),h||I.flush(),I(),h&&I.flush()},R="";return N.all?.on("data",x=>{if(R+=x.toString(),!x.includes(`
10
- `))return;let h=R.split(`
11
- `).filter(Boolean).map(p=>{try{return JSON.parse(p)}catch{console.log("Could not parse line",p)}return null}).filter(Boolean);R="",h.forEach(p=>{Array.isArray(p?.message?.content)?p.message.content.forEach(c=>{switch(c.type){case"text":{c.text&&T({message:c.text});break}case"image":{typeof c.source=="object"&&c.source&&c.source.type==="base64"&&c.source.media_type?T({message:`![](data:${c.source.media_type};base64,${c.source.data})`}):console.log(`Unsupported image type ${c.source?.type}`,c.source);break}case"tool_use":{if(c.name==="Task"){let g=c.input?.description&&`\`${c.input.description}\``;T({title:[c.name,g].filter(Boolean).join(" ")})}else c.id&&(f[c.id]=c);I.flush();break}case"tool_result":{let g=c.tool_use_id?f[c.tool_use_id]:void 0,O;if(g){let b=g.input?.file_path&&Z.relative(F.cwd(),g.input.file_path),C=b&&`\`${b}\``;O=[g.name,C].filter(Boolean).join(" ")}let D=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(g?.name||""),v;if(typeof c.content=="string")v=c.content;else if(Array.isArray(c.content)){let b=[];c.content.forEach(C=>{C?.type==="text"&&typeof C.text=="string"?b.push(C.text):C?.type==="image"&&typeof C.source=="object"&&C.source?C.source.type==="base64"&&C.source.media_type?b.push(`![](data:${C.source.media_type};base64,${C.source.data})`):console.log(`Unsupported image type ${C.source.type}`,C.source):console.log(`Unsupported block type ${C?.type}`)}),v=b.join(`
12
-
13
- `)}D&&v&&(v=`\`\`\`
14
- ${v.trim()}
15
- \`\`\``),T({title:O,message:v},!0);break}case"thinking":{c.thinking&&T({title:"Thinking",message:c.thinking},!0);break}default:console.log(`Message content type is not supported ${c.type}`,c)}}):p?.type==="result"&&(_=p.duration_ms||0,p.is_error?y=p.result:E=p.result,[u,d].forEach(c=>{c[c.length-1]?.message===E&&c.pop()}))})}),await N.catch(x=>{({error:y,result:E}=rt({catchError:x,runCmd:N,error:y,result:E,runnerName:"Claude"}))}),I.flush(),{steps:u,duration:_,result:E,error:y}}var ve=async()=>{let e=Z.join(tt.homedir(),".claude");await et.rm(e,{recursive:!0,force:!0})},nt={[Y]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:64e3},"claude-3-haiku-20240307":{maxTokens:4096},"claude-opus-4-20250514":{maxTokens:32e3},"claude-sonnet-4-20250514":{maxTokens:64e3}}},pro:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[G]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[H]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}},[B]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}}};import ot from"fs/promises";import st from"os";import ae from"path";import j from"process";var it=({catchError:e,runCmd:t,error:n,result:r,runnerName:o})=>(console.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!n,hadExistingResult:!!r,resultLength:r?r.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),r?(console.log("Preserving existing result despite catch handler being triggered"),n?{error:n,result:r}:{error:"Process completed with errors but result was captured",result:r}):(console.log("Setting result to undefined because no valid result was captured"),{error:n||`${o} failed`,result:void 0}));async function le({config:e,netlify:t,persistSteps:n,sendSteps:r,aiGateway:o}){let{accountType:s,prompt:a,modelVersionOverrides:i}=e,{model:l}=e;if(o){let{token:T,url:R}=o;if(!T||!R)throw new Error("No token or url provided from AI Gateway");let x=at[s];if(!x)throw new Error(`Codex is not supported for the account type ${s}`);if(l&&!x?.models?.[l])throw new Error(`${l} is not supported for account type ${s}`);if(i?.codex){let h=i?.codex?.[s];h&&(l=h)}j.env.OPENAI_API_KEY=T,j.env.OPENAI_BASE_URL=R}else if(!j.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let d=[],u=[],f={},m=0,_=0,E,y,w=ae.join(j.cwd(),"node_modules"),A=[ae.join(j.env.NODE_PATH||w,".bin/codex"),"--approval-mode","full-auto",o?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...l?["--model",l]:[],"-q",a].filter(Boolean),S=`${j.env.NVM_BIN}/node`;console.log(`Running ${S} ${A.join(" ")}`);let N=t.utils.run(S,A,{all:!0,env:{...j.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),I="";return N.all.on("data",T=>{if(I+=T.toString(),!T.includes(`
16
- `))return;let R=I.toString().split(`
17
- `).filter(Boolean).map(p=>{try{return JSON.parse(p)}catch{console.log("Could not parse line",p)}return null}).filter(Boolean);I="";let x=[],h=!1;R.forEach(p=>{if(p?.duration_ms&&(_=p.duration_ms,h=!0),p?.type==="local_shell_call")f[p.call_id]=p;else if(p?.type==="local_shell_call_output"){let c=ct(f[p.call_id],p);c.id=m,m+=1,c&&(u.push(c),d.push(c),x.push(c),h=!0)}else p?.type==="message"&&p.role==="assistant"?E=p.content.map(c=>c.text).join(`
18
- `):p?.type==="message"&&p.role==="system"&&(y=p.content.map(c=>c.text).join(`
19
- `))}),h&&(n?.({steps:d,duration:_}),r?.({steps:x,duration:_}))}),await N.catch(T=>{({error:y,result:E}=it({catchError:T,runCmd:N,error:y,result:E,runnerName:"Codex"}))}),{steps:u,duration:_,result:E,error:y}}var Pe=async()=>{let e=ae.join(st.homedir(),".codex");await ot.rm(e,{recursive:!0,force:!0})},at={[Y]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},o1:{maxTokens:1e5},"o1-mini":{maxTokens:65536},"o3-mini":{maxTokens:1e5},"gpt-image-1":{},"dall-e-2":{},"dall-e-3":{}}},[G]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768}}},pro:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768}}},[H]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},"o3-mini":{maxTokens:16e3}}},[B]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},"o3-mini":{maxTokens:16e3}}}},lt=new Set(["bash","-lc"]),ct=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let n=e.action?.command?.filter(s=>!lt.has(s)),r=n?`Running \`${n.join(" ")}\``:void 0,o;try{o=JSON.parse(t.output).output?.trim(),o&&(o=`\`\`\`
7
+ `);return s.length>e.length*.8?e:s}import ce from"process";import{getTracer as jt}from"@netlify/otel";import oe from"process";var he=oe.env.NETLIFY_API_URL,ye=oe.env.NETLIFY_API_TOKEN,Z=x("api"),se=async(e,t={})=>{if(!he||!ye)throw new Error("No API URL or token");let r=new URL(e,he),n={...t,headers:{...t.headers,Authorization:`Bearer ${ye}`}};oe.env.AGENT_RUNNERS_DEBUG==="true"&&(n.headers["x-nf-debug-logging"]="true"),t.json&&(n.headers||={},n.headers["Content-Type"]="application/json",n.body=JSON.stringify(t.json));let o=await fetch(r,n),s=o.ok&&o.status<=299;if(oe.env.AGENT_RUNNERS_DEBUG==="true")Z.log(`Response headers for ${r}:`),o.headers.forEach((a,i)=>{Z.log(` ${i}: ${a}`)});else{let a=o.headers.get("x-nf-request-id");Z.log(`Request ID for ${r}: ${a||"N/A"}`)}if(s||Z.error(`Got status ${o.status} for request ${r}`),t.raw){if(!s)throw o;return o}let l=await(o.headers.get("content-type")?.includes("application/json")?o.json():o.text());if(!s)throw l;return l},Oe=e=>{Z.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(he=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(ye=e.constants.NETLIFY_API_TOKEN)},ie=(e,t)=>se(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),B=(e,t,r)=>se(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var be=(e,t)=>se(`/api/v1/agent_runners/${e}/sessions/${t}`),$e=(e,t,r)=>se(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}});var De=x("ai_gateway"),Fe=async({netlify:e,config:t})=>{let r,n,o,s,l=e.constants?.SITE_ID;if(!l)throw new Error("No site id");let a=async()=>{clearTimeout(o),De.log("Requesting AI gateway information");let i=await $e(l,t.id,t.sessionId);if({token:r,url:s}=i,n=i.expires_at?i.expires_at*1e3:void 0,De.log("Got AI gateway information",{token:!!r,expiresAt:n,url:s}),n){let d=n-Date.now()-6e4;d>0&&(o=setTimeout(()=>{a()},d))}};return await a(),{get url(){return s},get token(){return r}}};import Le from"process";import{execa as ut,execaCommand as xr}from"execa";var Tr=x("shell"),ct={preferLocal:!0},je=(e,t,r)=>{let[n,o]=dt(t,r),s={...ct,...o},l=ut(e,n,s);return pt(l,s),l};var dt=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},pt=(e,t)=>{t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0||(e.stdout?.pipe(Le.stdout),e.stderr?.pipe(Le.stderr))};var Ue="netlify-agent-runner-context.md",_e="task-history",xe="netlify-context",b=".netlify",Q="results.md",Ee="assets",H="other",q="personal";var K="enterprise",V="free";var ft=x("utils"),mt=e=>new Promise(t=>{setTimeout(t,e)}),Me=(e,t=3e3)=>{let r=!1,n=null,o=[],s=null,l=(...a)=>{if(r)return n=a,new Promise(c=>{o.push(c)});r=!0;let i,d=new Promise(c=>{i=c});return s=(async()=>{await Promise.resolve();let c=await e(...a);for(i(c);;){if(await mt(t),!n)return r=!1,s=null,c;let h=n,m=o;n=null,o=[],c=await e(...h),m.forEach(_=>{_(c)})}})(),d};return l.flush=async()=>{if((r||n)&&s)return await s,l.flush()},l},ae=(e,t,r=!1)=>{let n=null,o=null,s=null,l=function(...a){o=a,s=this;let i=r&&!n;clearTimeout(n),n=setTimeout(()=>{n=null,r||(e.apply(s,o),o=null,s=null)},t),i&&(e.apply(s,o),o=null,s=null)};return l.cancel=()=>{clearTimeout(n),n=null,o=null,s=null},l.flush=()=>{if(n){clearTimeout(n);let a=o,i=s;n=null,o=null,s=null,e.apply(i,a)}},l},Ge=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(n){t&&(r?.error?r.error("Could not parse JSON",n):ft.error("Could not parse JSON",n))}},Ye=(e,t)=>{let o=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let a=`--${t}${o}`;if(a.length>55)return"";let i=60-a.length;if(i<=0)return"";if(i>=s.length+6){let d=Math.min(i-s.length,e.length);return`${s}${e.slice(0,d)}`}return e.slice(0,i)};import{Buffer as Be}from"buffer";var He=async({config:e,netlify:t})=>{let r=await ht(t),{hasChanges:n}=r,{status:o}=r;if(!n)return{hasChanges:!1};let s=await yt(t,o);await t.utils.run("git",["add",".",...s]);let l={stdio:["ignore","pipe","pipe"]},i=(await t.utils.run("git",["diff","--staged"],l)).stdout;if(n=!!i,!n)return{hasChanges:!1};let c=(await t.utils.run("git",["diff","--staged","--binary"],l)).stdout,h,m;if(e.sha){await t.utils.run("git",["commit","-m","Agent runner"]),h=(await t.utils.run("git",["diff",e.sha,"HEAD"],l)).stdout;let g=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"],l)).stdout;h!==g&&(m=Be.from(g).toString("base64"))}let _={hasChanges:!0,diff:i,resultDiff:h};return i!==c&&(_.diffBinary=Be.from(c).toString("base64")),m&&(_.resultDiffBinary=m),_},gt=["?? mise.toml",/\?\? .+?\.log/],ht=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
8
+ `).filter(o=>!gt.some(s=>s instanceof RegExp?s.test(o):o===s))).length!==0,status:t.stdout}};var qe=async e=>{let{stdout:t}=await e.utils.run("git",["rev-parse","HEAD"]);return t.trim()},Ke=async e=>{let{stdout:t}=await e.utils.run("git",["rev-list","--max-parents=0","HEAD"]);return t.trim()},yt=async(e,t="")=>{let r=[".netlify","mise.toml","node_modules"],n=[],o=r.map(async l=>{try{return await e.utils.run("git",["check-ignore","-v",l]),null}catch{return`:!${l}`}});return(await Promise.all(o)).forEach(l=>{l&&n.push(l)}),t.split(`
9
+ `).forEach(l=>{let a=l.match(/\?\? (.+?)\.log$/)?.[1];a&&n.push(`:!${a}.log`)}),n};import xt from"fs/promises";import Et from"os";import le from"path";import U from"process";import Te from"path";import _t from"fs/promises";var we=x("agent-output-utils");async function J({initialResult:e,agentName:t,hasError:r}){let n="",o=Te.join(process.cwd(),b,Q);try{let s=await _t.readFile(o,"utf-8");s&&(n=s,we.log(`Pulled result from ${Te.relative(process.cwd(),o)}`))}catch{we.log(`No results file found at ${Te.relative(process.cwd(),o)}`)}return n||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function W({error:e}){let t=e&&typeof e=="object"?JSON.stringify(e):e,r=t?.replace(/\s+/g," ").trim()||"",n="";return r?.includes("ai gateway is not available for your account")?n="AI Gateway is currently not available on your account. Please confirm your account meets the criteria for using Agent Runners and AI Gateway and that your account has remaining AI Gateway inference credits available. Reach out to Netlify support if this is unexpected.":r?.includes("error when talking to gemini api")?n="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":r?.includes("connection closed prematurely while waiting for the model")&&(n="The agent's models were currently overloaded. Please try again or use a different available agent."),n&&we.log(`Providing updated error messsage: ${n}, replacing original error: ${t}`),r||void 0}var L=x("runner_claude"),Tt="Claude Code",wt=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(L.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(L.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(L.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0}));async function Ie({config:e,netlify:t,persistSteps:r,aiGateway:n}){let o=e,{accountType:s,prompt:l,modelVersionOverrides:a}=o,{model:i}=o;if(n){let{token:w,url:f}=n;if(!w||!f)throw new Error("No token or url provided from AI Gateway");let p=It[s];if(!p)throw new Error(`Claude is not supported for the account type ${s}`);if(i&&!p?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(a?.claude){let u=a?.claude?.[s];u&&(i=u)}U.env.ANTHROPIC_API_KEY=w,U.env.ANTHROPIC_BASE_URL=f}else if(!U.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let d=[],c=[],h={},m=0,_=0,I,E,g=le.join(U.cwd(),"node_modules"),S=[le.join(U.env.NODE_PATH||g,".bin/claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...i?["--model",i]:[],"-p",l],R=`${U.env.NVM_BIN}/node`;L.log(`Running ${R} ${S.join(" ")}`);let v=t.utils.run(R,S,{all:!0,env:U.env});v.stdin?.end();let C=ae(()=>{r?.({steps:d,duration:_})},250),T=(w,f)=>{let p={...w,id:m};m+=1,c.push(p),d.push(p),f||C.flush(),C(),f&&C.flush()},N="";return v.all?.on("data",w=>{if(N+=w.toString(),!w.includes(`
10
+ `))return;let f=N.split(`
11
+ `).filter(Boolean).map(p=>{try{return JSON.parse(p)}catch{L.log("Could not parse line",p)}return null}).filter(Boolean);N="",f.forEach(p=>{Array.isArray(p?.message?.content)?p.message.content.forEach(u=>{switch(u.type){case"text":{u.text&&T({message:u.text});break}case"image":{typeof u.source=="object"&&u.source&&u.source.type==="base64"&&u.source.media_type?T({message:`![](data:${u.source.media_type};base64,${u.source.data})`}):L.log(`Unsupported image type ${u.source?.type}`,u.source);break}case"tool_use":{if(u.name==="Task"){let y=u.input?.description&&`\`${u.input.description}\``;T({title:[u.name,y].filter(Boolean).join(" ")})}else u.id&&(h[u.id]=u);C.flush();break}case"tool_result":{let y=u.tool_use_id?h[u.tool_use_id]:void 0,D;if(y){let F=y.input?.file_path&&le.relative(U.cwd(),y.input.file_path),A=F&&`\`${F}\``;D=[y.name,A].filter(Boolean).join(" ")}let j=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(y?.name||""),O;if(typeof u.content=="string")O=u.content;else if(Array.isArray(u.content)){let F=[];u.content.forEach(A=>{A?.type==="text"&&typeof A.text=="string"?F.push(A.text):A?.type==="image"&&typeof A.source=="object"&&A.source?A.source.type==="base64"&&A.source.media_type?F.push(`![](data:${A.source.media_type};base64,${A.source.data})`):L.log(`Unsupported image type ${A.source.type}`,A.source):L.log(`Unsupported block type ${A?.type}`)}),O=F.join(`
12
+
13
+ `)}j&&O&&(O=`\`\`\`
14
+ ${O.trim()}
15
+ \`\`\``),T({title:D,message:O},!0);break}case"thinking":{u.thinking&&T({title:"Thinking",message:u.thinking},!0);break}default:L.log(`Message content type is not supported ${u.type}`,u)}}):p?.type==="result"&&(_=p.duration_ms||0,p.is_error?E=p.result:I=p.result,[c,d].forEach(u=>{u[u.length-1]?.message===I&&u.pop()}))})}),await v.catch(w=>{({error:E,result:I}=wt({catchError:w,runCmd:v,error:E,result:I,runnerName:"Claude"}))}),C.flush(),{steps:c,duration:_,result:await J({initialResult:I,agentName:Tt,hasError:!!E}),error:W({error:E})}}var Ve=async()=>{let e=le.join(Et.homedir(),".claude");await xt.rm(e,{recursive:!0,force:!0})},It={[K]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:64e3},"claude-3-haiku-20240307":{maxTokens:4096},"claude-opus-4-20250514":{maxTokens:32e3},"claude-sonnet-4-20250514":{maxTokens:64e3}}},pro:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[q]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[V]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}},[H]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}}};import Ct from"fs/promises";import Rt from"os";import Ce from"path";import Y from"process";var X=x("runner_codex"),Nt="Codex CLI",At=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(X.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(X.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(X.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0}));async function Re({config:e,netlify:t,persistSteps:r,sendSteps:n,aiGateway:o}){let{accountType:s,prompt:l,modelVersionOverrides:a}=e,{model:i}=e;if(o){let{token:T,url:N}=o;if(!T||!N)throw new Error("No token or url provided from AI Gateway");let w=St[s];if(!w)throw new Error(`Codex is not supported for the account type ${s}`);if(i&&!w?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(a?.codex){let f=a?.codex?.[s];f&&(i=f)}Y.env.OPENAI_API_KEY=T,Y.env.OPENAI_BASE_URL=N}else if(!Y.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let d=[],c=[],h={},m=0,_=0,I,E,g=Ce.join(Y.cwd(),"node_modules"),S=[Ce.join(Y.env.NODE_PATH||g,".bin/codex"),"--approval-mode","full-auto",o?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...i?["--model",i]:[],"-q",l].filter(Boolean),R=`${Y.env.NVM_BIN}/node`;X.log(`Running ${R} ${S.join(" ")}`);let v=t.utils.run(R,S,{all:!0,env:{...Y.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),C="";return v.all.on("data",T=>{if(C+=T.toString(),!T.includes(`
16
+ `))return;let N=C.toString().split(`
17
+ `).filter(Boolean).map(p=>{try{return JSON.parse(p)}catch{X.log("Could not parse line",p)}return null}).filter(Boolean);C="";let w=[],f=!1;N.forEach(p=>{if(p?.duration_ms&&(_=p.duration_ms,f=!0),p?.type==="local_shell_call")h[p.call_id]=p;else if(p?.type==="local_shell_call_output"){let u=Pt(h[p.call_id],p);u.id=m,m+=1,u&&(c.push(u),d.push(u),w.push(u),f=!0)}else p?.type==="message"&&p.role==="assistant"?I=p.content.map(u=>u.text).join(`
18
+ `):p?.type==="message"&&p.role==="system"&&(E=p.content.map(u=>u.text).join(`
19
+ `))}),f&&(r?.({steps:d,duration:_}),n?.({steps:w,duration:_}))}),await v.catch(T=>{({error:E,result:I}=At({catchError:T,runCmd:v,error:E,result:I,runnerName:"Codex"}))}),{steps:c,duration:_,result:await J({initialResult:I,agentName:Nt,hasError:!!E}),error:W({error:E})}}var Je=async()=>{let e=Ce.join(Rt.homedir(),".codex");await Ct.rm(e,{recursive:!0,force:!0})},St={[K]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},o1:{maxTokens:1e5},"o1-mini":{maxTokens:65536},"o3-mini":{maxTokens:1e5},"gpt-image-1":{},"dall-e-2":{},"dall-e-3":{}}},[q]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768}}},pro:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768}}},[V]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},"o3-mini":{maxTokens:16e3}}},[H]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},"o3-mini":{maxTokens:16e3}}}},vt=new Set(["bash","-lc"]),Pt=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!vt.has(s)),n=r?`Running \`${r.join(" ")}\``:void 0,o;try{o=JSON.parse(t.output).output?.trim(),o&&(o=`\`\`\`
20
20
  ${o.trim()}
21
- \`\`\``)}catch(s){console.error("Could not decode outputMsg",s,t.output)}return{title:r,message:o}};import ut from"fs/promises";import dt from"os";import Q from"path";import L from"process";var pt=({catchError:e,runCmd:t,error:n,result:r,runnerName:o})=>(console.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!n,hadExistingResult:!!r,resultLength:r?r.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),r?(console.log("Preserving existing result despite catch handler being triggered"),n?{error:n,result:r}:{error:"Process completed with errors but result was captured",result:r}):(console.log("Setting result to undefined because no valid result was captured"),{error:n||`${o} failed`,result:void 0})),ft={list_directory:"List",read_file:"Read",write_file:"Write",glob:"Find",search_file_content:"Find",replace:"Edit",run_shell_command:"Run",web_fetch:"Web Fetch",web_search:"Web Search",read_many_files:"Read Many",save_memory:"Memorize"};async function ce({config:e,netlify:t,persistSteps:n,sendSteps:r,aiGateway:o}){let{accountType:s,prompt:a,modelVersionOverrides:i}=e,{model:l}=e;if(o){let{token:h,url:p}=o;if(!h||!p)throw new Error("No token or url provided from AI Gateway");let c=mt[s];if(!c)throw new Error(`Gemini is not supported for the account type ${s}`);if(l&&!c?.models?.[l])throw new Error(`${l} is not supported for account type ${s}`);if(i?.gemini){let g=i?.gemini?.[s];g&&(l=g)}L.env.GEMINI_API_KEY=h,L.env.GOOGLE_GEMINI_BASE_URL=p}else if(!L.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let d=[],u=[],f=[],m={},_=0,E=0,y,w,A=Q.join(L.cwd(),"node_modules"),S=[Q.join(L.env.NODE_PATH||A,".bin/gemini"),...l?["--model",l]:[],"--yolo","-p",a],N=`${L.env.NVM_BIN}/node`;console.log(`Running ${N} ${S.join(" ")}`);let I=t.utils.run(N,S,{all:!0,env:L.env});I.stdin?.end();let T=z(()=>{n?.({steps:d,duration:E}),r?.({steps:u,duration:E}),u=[]},250),R=(h,p)=>{h.id=_,_+=1,f.push(h),d.push(h),u.push(h),p||T.flush(),T(),p&&T.flush()},x="";return I.all.on("data",h=>{if(x+=h.toString(),!h.includes(`
22
- `))return;let p=x.toString().split(`
23
- `).filter(Boolean).map(c=>{try{if(c.startsWith("[API Error")){let g=c.match(/\[api error: (.+?)]$/i)?.[1];return{type:"error",value:Ie(g,!1)?.error?.message||g||"Gemini encountered error"}}return JSON.parse(c)}catch{}return null}).filter(Boolean);x="",p.forEach(c=>{switch(c.type){case"thought":{let g=c.value;R({title:g?.subject??"Thinking...",message:g?.description},!0);break}case"content":{c.value&&R({message:c.value});break}case"tool_call_request":{let g=c.value,O=ft[g.name]??g.name,D=g.args?.path||g.args?.absolute_path,v=D&&Q.relative(L.cwd(),D),b=g.args?.command,Be={title:[O,v&&`\`${v}\``,b&&`\`${b}\``].filter(Boolean).join(" ")};m[g.callId]=Be,T.flush();break}case"tool_result":{let g=c.value,O=m[g.callId];if(O){let D=[g.resultDisplay,g.responseParts?.functionResponse?.response?.output].find(v=>typeof v=="string"&&v);D&&(O.message=`\`\`\`
24
- ${D.trim()}
25
- \`\`\``),R(O,!0)}break}case"result":{E=c.duration_ms,y=c.value,[f,d,u].forEach(g=>{g[g.length-1]?.message===y&&g.pop()});break}case"error":{w=c.value;break}case"finished":break;default:{console.warn("Unhandled message type:",c.type);break}}})}),await I.catch(h=>{({error:w,result:y}=pt({catchError:h,runCmd:I,error:w,result:y,runnerName:"Gemini"}))}),T.flush(),{steps:f,duration:E,result:y,error:w}}var ke=async()=>{let e=Q.join(dt.homedir(),".gemini");await ut.rm(e,{recursive:!0,force:!0})},mt={[Y]:{models:{"gemini-1.5-flash":{maxTokens:8192},"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-1.5-pro":{maxTokens:8192},"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:65536},"gemini-2.5-flash-lite":{maxTokens:65536},"gemini-2.5-pro":{maxTokens:65536},"imagen-4.0-generate-001":{},"veo-3.0-generate-preview":{}}},pro:{models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[G]:{models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[H]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}},[B]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}}};var gt={codex:{runner:le,clean:Pe},claude:{runner:ie,clean:ve},gemini:{runner:ce,clean:ke}},Oe=gt;var be=async({config:e,apiThrottle:t,apiToken:n})=>{let r=ht();return q(r,"init-stage",async o=>{let s=performance.now();o?.setAttributes({"init.runner":e.runner,"init.id":e.id,"init.sessionId":e.sessionId,"init.hasRepo":e.hasRepo,"init.useGateway":e.useGateway,"init.validateAgent":e.validateAgent});let a=Oe[e.runner];if(!a)throw o?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let i=yt({apiToken:n});he(i);let l=e.useGateway?await xe({netlify:i,config:e}):void 0;o?.setAttributes({"init.aiGateway.created":!!l}),e.validateAgent&&e.errorLogsPath&&o?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let d=we(({steps:m=[],duration:_})=>{let E=[...m];return m.length=0,M(e.id,e.sessionId,{steps:E,duration:_})},t),u;e.hasRepo?e.sha?(u=e.sha,o?.setAttributes({"init.sha.source":"provided"})):(u=await Ae(i),await X(e.id,{sha:u}),o?.setAttributes({"init.sha.source":"current_commit"})):(u=await Se(i),o?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let f=performance.now()-s;return o?.setAttributes({"init.sha":u||"unknown","init.duration.ms":f,"init.status":"success"}),{aiGateway:l,context:i,persistSteps:d,runner:a,sha:u}})},yt=({apiToken:e})=>({constants:{NETLIFY_API_HOST:ee.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||ee.env.NETLIFY_API_TOKEN,SITE_ID:ee.env.SITE_ID,FUNCTIONS_DIST:ee.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:Te}});import _t from"crypto";import U from"fs/promises";import P from"path";import k from"process";var xt=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:k.env.NETLIFY_TEAM_ID,userId:k.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:k.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},Et=()=>{let e=Object.keys(k.env).sort();return{nodeVersion:k.version,envVars:e}},Tt=10,wt=async e=>{let{name:t,ext:n}=P.parse(e),r=e,o=P.join(k.cwd(),$,r),s=0;for(;await It(o);){if(s>=Tt)throw new Error("Failed to generate context file");r=`${t}-${_t.randomUUID().slice(0,5)}${n}`,o=P.join(k.cwd(),$,r),s+=1}return r},It=async e=>{try{return await U.access(e),!0}catch{return!1}},Ct=async()=>{try{console.log("Fetching Netlify features context...");let e=await fetch("https://docs.netlify.com/ai-context/context-consumers",{signal:AbortSignal.timeout(1e4)});if(!e.ok)throw new Error(`Failed to fetch context consumers: ${e.status} ${e.statusText}`);let t=await e.json();if(!t||typeof t!="object"||!Array.isArray(t.consumers))return console.warn("Invalid response structure: missing or invalid consumers array"),null;let n=t.consumers.find(r=>r&&typeof r=="object"&&r.key==="catchall-consumer");return n?!n.contextScopes||typeof n.contextScopes!="object"?(console.warn("Catchall consumer missing or invalid contextScopes"),null):n:(console.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?console.warn("Netlify features context request timed out"):console.warn("Failed to fetch Netlify features context:",e.message),null}},Nt=async(e,t)=>{try{let n=await fetch(e,{signal:AbortSignal.timeout(1e4)});if(!n.ok)throw new Error(`Failed to fetch ${e}: ${n.status} ${n.statusText}`);let r=await n.text();return await U.writeFile(t,r,"utf-8"),!0}catch(n){return n.name==="AbortError"?console.warn(`Download timeout for ${e}`):console.warn(`Failed to download context file ${e}:`,n.message),!1}},Rt=async()=>{let e=await Ct();if(!e)return[];let t=P.join(k.cwd(),$,se);await U.mkdir(t,{recursive:!0});let n=Object.entries(e.contextScopes).map(async([s,a])=>{if(!a||typeof a!="object"||!a.endpoint||!a.scope)return console.warn(`Invalid scope data for ${s}, skipping...`),null;let i=`${s}.md`,l=P.join(t,i),d=P.join($,se,i);return console.log(`Downloading ${a.scope} context...`),await Nt(a.endpoint,l)?(console.log(`Downloaded: ${d}`),{scope:a.scope,path:d,key:s}):null});return(await Promise.all(n)).filter(s=>s!==null)},$e=async({cliPath:e,netlify:t,config:n})=>{let r=xt(t),o=Et(),s=await wt(W),a=P.join(k.cwd(),$);await U.mkdir(a,{recursive:!0});let i=P.join($,s),l=P.join(k.cwd(),i),d=`# Agent Context
26
-
27
- In Netlify documentation and interfaces, the terms "site" and "project" refer to the same thing.
28
-
29
- If you need to start a local development server in order to fulfill the request, try using the Netlify CLI over by running the shell command '${e} dev'. This will start a local HTTP server on port 8888, including live-reloading of any changes and, most critically, it offers local emulation for all Netlify features.
30
-
31
- ## Netlify Site
32
- - Site ID: ${r.siteId}
33
- - Account ID: ${r.accountId}
34
- - User ID: ${r.userId}
35
- - Site Slug: ${r.siteSlug}
36
- - Netlify Functions directory: ${r.functionsDir}
37
- - Running Node Version: ${o.nodeVersion}
38
-
39
- The available environment variables are set globally (e.g. \`echo $VARIABLE_NAME\` can be used to check if a var is set).:
40
-
41
- ## Attachments
42
-
43
- - for requests that require work with attachments or assets, take into account that uploaded attachments are stored in .netlify/assets folder
44
- - move assets from .netlify/assets folder to the project assets folder if they are referenced in a code or applied changes
45
-
46
- ## Netlify CLI
47
- 'netlify-cli' npm package is already available as a global package.
48
- Don't try to install it, in case you want to use it, use the global package.
49
-
50
- `;n.siteContext&&n.siteContext.length!==0&&(d+=`
51
- # Project Guidelines
52
- <project_guidelines>
53
- ${n.siteContext.filter(f=>f.site_context).map(f=>typeof f.site_context=="string"?f.site_context:typeof f.site_context=="object"?JSON.stringify(f.site_context):"").join(`
54
-
55
- `)}
56
- </project_guidelines>
57
- `);let u=await Rt();if(u.length>0&&(d+=`
58
- # Netlify Features Context
21
+ \`\`\``)}catch(s){X.error("Could not decode outputMsg",s,t.output)}return{title:n,message:o}};import kt from"fs/promises";import Ot from"os";import ue from"path";import M from"process";var te=x("runner_gemini"),bt="Gemini CLI",$t=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(te.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(te.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(te.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0})),Dt={list_directory:"List",read_file:"Read",write_file:"Write",glob:"Find",search_file_content:"Find",replace:"Edit",run_shell_command:"Run",web_fetch:"Web Fetch",web_search:"Web Search",read_many_files:"Read Many",save_memory:"Memorize"};async function Ne({config:e,netlify:t,persistSteps:r,sendSteps:n,aiGateway:o}){let{accountType:s,prompt:l,modelVersionOverrides:a}=e,{model:i}=e;if(o){let{token:f,url:p}=o;if(!f||!p)throw new Error("No token or url provided from AI Gateway");let u=Ft[s];if(!u)throw new Error(`Gemini is not supported for the account type ${s}`);if(i&&!u?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(a?.gemini){let y=a?.gemini?.[s];y&&(i=y)}M.env.GEMINI_API_KEY=f,M.env.GOOGLE_GEMINI_BASE_URL=p}else if(!M.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let d=[],c=[],h=[],m={},_=0,I=0,E,g,S=ue.join(M.cwd(),"node_modules"),R=[ue.join(M.env.NODE_PATH||S,".bin/gemini"),...i?["--model",i]:[],"--yolo","-p",l],v=`${M.env.NVM_BIN}/node`;te.log(`Running ${v} ${R.join(" ")}`);let C=t.utils.run(v,R,{all:!0,env:M.env});C.stdin?.end();let T=ae(()=>{r?.({steps:d,duration:I}),n?.({steps:c,duration:I}),c=[]},250),N=(f,p)=>{f.id=_,_+=1,h.push(f),d.push(f),c.push(f),p||T.flush(),T(),p&&T.flush()},w="";return C.all.on("data",f=>{if(w+=f.toString(),!f.includes(`
22
+ `))return;let p=w.toString().split(`
23
+ `).filter(Boolean).map(u=>{try{if(u.startsWith("[API Error")){let y=u.match(/\[api error: (.+?)]$/i)?.[1];return{type:"error",value:Ge(y,!1)?.error?.message||y||"Gemini encountered error"}}return JSON.parse(u)}catch{}return null}).filter(Boolean);w="",p.forEach(u=>{switch(u.type){case"thought":{let y=u.value;N({title:y?.subject??"Thinking...",message:y?.description},!0);break}case"content":{u.value&&N({message:u.value});break}case"tool_call_request":{let y=u.value,D=Dt[y.name]??y.name,j=y.args?.path||y.args?.absolute_path,O=j&&ue.relative(M.cwd(),j),F=y.args?.command,ot={title:[D,O&&`\`${O}\``,F&&`\`${F}\``].filter(Boolean).join(" ")};m[y.callId]=ot,T.flush();break}case"tool_result":{let y=u.value,D=m[y.callId];if(D){let j=[y.resultDisplay,y.responseParts?.functionResponse?.response?.output].find(O=>typeof O=="string"&&O);j&&(D.message=`\`\`\`
24
+ ${j.trim()}
25
+ \`\`\``),N(D,!0)}break}case"result":{I=u.duration_ms,E=u.value,[h,d,c].forEach(y=>{y[y.length-1]?.message===E&&y.pop()});break}case"error":{g=u.value;break}case"finished":break;default:{te.warn("Unhandled message type:",u.type);break}}})}),await C.catch(f=>{({error:g,result:E}=$t({catchError:f,runCmd:C,error:g,result:E,runnerName:"Gemini"}))}),T.flush(),{steps:h,duration:I,result:await J({initialResult:E,agentName:bt,hasError:!!g}),error:W({error:g})}}var We=async()=>{let e=ue.join(Ot.homedir(),".gemini");await kt.rm(e,{recursive:!0,force:!0})},Ft={[K]:{models:{"gemini-1.5-flash":{maxTokens:8192},"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-1.5-pro":{maxTokens:8192},"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:65536},"gemini-2.5-flash-lite":{maxTokens:65536},"gemini-2.5-pro":{maxTokens:65536},"imagen-4.0-generate-001":{},"veo-3.0-generate-preview":{}}},pro:{models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[q]:{models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[V]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}},[H]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}}};var Lt={codex:{runner:Re,clean:Je},claude:{runner:Ie,clean:Ve},gemini:{runner:Ne,clean:We}},Xe=Lt;var ze=async({config:e,apiThrottle:t,apiToken:r})=>{let n=jt();return ne(n,"init-stage",async o=>{let s=performance.now();o?.setAttributes({"init.runner":e.runner,"init.id":e.id,"init.sessionId":e.sessionId,"init.hasRepo":e.hasRepo,"init.useGateway":e.useGateway,"init.validateAgent":e.validateAgent});let l=Xe[e.runner];if(!l)throw o?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let a=Ut({apiToken:r});Oe(a);let i=e.useGateway?await Fe({netlify:a,config:e}):void 0;o?.setAttributes({"init.aiGateway.created":!!i}),e.validateAgent&&e.errorLogsPath&&o?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let d=Me(({steps:m=[],duration:_})=>{let I=[...m];return m.length=0,B(e.id,e.sessionId,{steps:I,duration:_})},t),c;e.hasRepo?e.sha?(c=e.sha,o?.setAttributes({"init.sha.source":"provided"})):(c=await qe(a),await ie(e.id,{sha:c}),o?.setAttributes({"init.sha.source":"current_commit"})):(c=await Ke(a),o?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let h=performance.now()-s;return o?.setAttributes({"init.sha":c||"unknown","init.duration.ms":h,"init.status":"success"}),{aiGateway:i,context:a,persistSteps:d,runner:l,sha:c}})},Ut=({apiToken:e})=>({constants:{NETLIFY_API_HOST:ce.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||ce.env.NETLIFY_API_TOKEN,SITE_ID:ce.env.SITE_ID,FUNCTIONS_DIST:ce.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:je}});import Mt from"crypto";import G from"fs/promises";import k from"path";import $ from"process";var P=x("context"),Gt=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:$.env.NETLIFY_TEAM_ID,userId:$.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:$.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},Yt=10,Bt=async e=>{let{name:t,ext:r}=k.parse(e),n=e,o=k.join($.cwd(),b,n),s=0;for(;await Ht(o);){if(s>=Yt)throw new Error("Failed to generate context file");n=`${t}-${Mt.randomUUID().slice(0,5)}${r}`,o=k.join($.cwd(),b,n),s+=1}return n},Ht=async e=>{try{return await G.access(e),!0}catch{return!1}},qt=async()=>{try{P.log("Fetching Netlify features context...");let e=await fetch("https://docs.netlify.com/ai-context/context-consumers",{signal:AbortSignal.timeout(1e4)});if(!e.ok)throw new Error(`Failed to fetch context consumers: ${e.status} ${e.statusText}`);let t=await e.json();if(!t||typeof t!="object"||!Array.isArray(t.consumers))return P.warn("Invalid response structure: missing or invalid consumers array"),null;let r=t.consumers.find(n=>n&&typeof n=="object"&&n.key==="catchall-consumer");return r?!r.contextScopes||typeof r.contextScopes!="object"?(P.warn("Catchall consumer missing or invalid contextScopes"),null):r:(P.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?P.warn("Netlify features context request timed out"):P.warn("Failed to fetch Netlify features context:",e.message),null}},Kt=async(e,t)=>{try{let r=await fetch(e,{signal:AbortSignal.timeout(1e4)});if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let n=await r.text();return await G.writeFile(t,n,"utf-8"),!0}catch(r){return r.name==="AbortError"?P.warn(`Download timeout for ${e}`):P.warn(`Failed to download context file ${e}:`,r.message),!1}},de=null,Vt=async()=>{if(de)return de;let e=await qt();if(!e)return[];let t=k.join($.cwd(),b,xe);await G.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([o,s])=>{if(!s||typeof s!="object"||!s.endpoint||!s.scope)return P.warn(`Invalid scope data for ${o}, skipping...`),null;let l=`${o}.md`,a=k.join(t,l),i=k.join(b,xe,l);return P.log(`Downloading ${s.scope} context...`),await Kt(s.endpoint,a)?(P.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:o}):null});return de=(await Promise.all(r)).filter(o=>o!==null),de},Ze=async({cliPath:e,netlify:t,config:r,buildErrorContext:n})=>{let o=Gt(t),s=await Bt(Ue),l=k.join($.cwd(),b);await G.mkdir(l,{recursive:!0});let a=k.join(b,s),i=k.join($.cwd(),a),d=k.join($.cwd(),b,Q);try{await G.unlink(d),P.log(`Deleted old results file: ${d}`)}catch{}let c=n?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
26
+ Your task is to analyze and fix the build errors.
27
+ Don't apply techniques of reverting changes. Apply fixes related to errors.
28
+ Don't try to run build by yourself. Just fix the errors.
59
29
 
60
- If the user request is explicitly related to a specific Netlify feature (e.g., Forms, Identity, Functions, etc.), you MUST review the relevant documentation below in addition to reviewing the project files.
61
- DO NOT force the use of any Netlify feature if the user request does not explicitly require it or if the project has alternative implementations in place already.
30
+ <build_error_context>
31
+ ${c}
32
+ </build_error_context>`:"",h="";r.siteContext&&r.siteContext.length!==0&&(h=`
33
+ <project_rules>
34
+ ${r.siteContext.filter(g=>g.site_context).map(g=>typeof g.site_context=="string"?g.site_context:typeof g.site_context=="object"?JSON.stringify(g.site_context):"").join(`
62
35
 
63
- ${u.map(f=>`- **${f.scope}**: ${f.path}`).join(`
64
36
  `)}
65
-
66
- Refer to these files when working with specific Netlify features.
67
- `),d+=`
68
- Additional Documentation Resources
69
- - Netlify Docs: https://docs.netlify.com
70
- - LLM Resources Index: https://docs.netlify.com/llms.txt
71
- `,n.sessionHistoryContext?.length){let f=P.join(k.cwd(),$,oe);await U.mkdir(f,{recursive:!0});let m=await Promise.all(n.sessionHistoryContext.map(async(_,E)=>{let y=E+1,w=`attempt-${y}.md`,A=P.join(f,w),S=P.join($,oe,w),N=`# Task History - Attempt ${y}
37
+ </project_rules>
38
+ `);let m="";if(r.sessionHistoryContext?.length){let g=k.join($.cwd(),b,_e);await G.mkdir(g,{recursive:!0});let S=await Promise.all(r.sessionHistoryContext.map(async(R,v)=>{let C=v+1,T=`attempt-${C}.md`,N=k.join(g,T),w=k.join(b,_e,T),f=`# Task History - Attempt ${C}
72
39
 
73
40
  ## Request - what the user asked for
74
- ${_.request}
41
+ ${R.request}
75
42
 
76
43
  ---
77
44
 
78
45
  ## Response - what the agent replied with after its work
79
46
 
80
- ${_.response}
81
- `;return await U.writeFile(A,N,"utf-8"),console.log(`Created history file: ${S}`),S}));d+=`# History of prior work on this task
47
+ ${R.response}
48
+ `;return await G.writeFile(N,f,"utf-8"),P.log(`Created history file: ${w}`),w}));m+=`
49
+ <session_history_context>
50
+ History of prior work on this task.
51
+ You MUST review ALL of the files below as context to understand the context of previous attempts. Use this information to continue the discussion appropriately.
82
52
 
83
- You MUST review ALL of the files below as context to understand the context of previous attempts. Use this information to continue the discussion appropriately.
53
+ ${S.slice(-5).map(R=>`- ${R}`).join(`
54
+ `)}
84
55
 
85
- ${m.map(_=>`- ${_}`).join(`
56
+ </session_history_context>
57
+ `}let _=await Vt(),I="";_.length>0&&(I=`
58
+ <netlify_features_context>
59
+ If the user request is explicitly related to a specific Netlify feature (e.g., Netlify Forms, Netlify Functions, etc.), you MUST review the relevant documentation below in addition to reviewing the project files.
60
+ DO NOT force the use of any Netlify feature if the user request does not explicitly require it or if the project has alternative implementations in place already.
61
+
62
+ ${_.map(g=>`- **${g.scope}**: ${g.path}`).join(`
86
63
  `)}
87
- `}return await U.writeFile(l,d,"utf-8"),console.log(`Generated agent context document at: ${l}`),i},De=e=>`The build is currently failing after your changes.
88
- Your task is to analyze and fix the build errors.
89
- Don't apply techniques of reverting changes. Apply fixes related to errors.
90
- Don't try to run build by yourself. Just fix the errors.
91
64
 
92
- ${e}`;var Fe=(e={})=>`
93
- Check for errors and validate the fix
94
-
95
- ${e.errorLogsPath?`Error Check Process:
96
- 1. Read recent errors: \`tail -n 50 ${e.errorLogsPath} 2>/dev/null || echo "0"\` (single check, no monitoring loop)
97
- 2. If errors are found, fix them by modifying the codebase
98
- 3. After fixes, do ONE final check: \`tail -n 20 ${e.errorLogsPath} 2>/dev/null || echo "No recent errors available"\`
99
- 4. Focus only on errors related to your changes
100
- 5. Ignore unrelated operational messages (git, API calls, plugin startup)
101
- 6. NEVER modify ${e.errorLogsPath} - it's read-only
102
- 7. Do NOT use continuous monitoring or repeated tail commands
103
- `:""}
104
-
105
- Fix Strategy:
106
- - Check error logs ONCE, fix issues, then do ONE final verification
107
- - Do NOT revert changes - improve the codebase to make it work
108
- - Do NOT continuously monitor logs or use tail in loops
109
- - Dev server is running in background, no need to run build or dev server yourself
110
- - Complete the validation quickly and decisively
111
-
112
- At the very end, print exactly one line with the verdict:
113
- VALIDATION_RESULT: PASS {"checks": ["error_logs"]}
114
- or
115
- VALIDATION_RESULT: FAIL {"checks": ["error_logs"], "errors": ["<errors>"]}
116
- `;var At=(e=W)=>`Use ${e} to understand the Netlify project context and resources. It also contains history of previous conversations. READ ALL OF IT. Make sure to read it first. Never reveal, cite, or paraphrase private context.`,St=async({cliPath:e,config:t,netlify:n})=>{let r=await $e({cliPath:e,netlify:n,config:t});return{context:At(r)}},vt=({config:e})=>{let t=[];return e?.validateAgent&&t.push(Fe(e)),t},Le=async({cliPath:e,config:t,netlify:n,buildErrorContext:r}={})=>{let{context:o}=await St({cliPath:e,config:t,netlify:n}),s;s=[...vt({config:t})],r&&(s=[...s,De(r)]);let a=[];return o&&a.push(o),t.prompt&&a.push("New user request comes in the <new_request> tag.",`<new_request>${t.prompt}</new_request>`),s?.length&&a.push(s.join(`
117
-
118
- `)),{prompt:a.join(`
119
-
120
- `)}};var ue=async({cliPath:e,config:t,context:n,buildErrors:r,runner:o,persistSteps:s,aiGateway:a})=>{let{prompt:i}=await Le({cliPath:e,config:t,buildErrorContext:Pt(r),netlify:n}),l={...t,prompt:i},d=await o({aiGateway:a,config:l,netlify:n,persistSteps:s});if(d.error)throw console.error("Runner failed",{stepsCount:d.steps.length,duration:d.duration,error:d.error}),new Error(d.error);return{runnerResult:d}},Pt=e=>!e||e.length===0?"":`
65
+ Refer to these files when working with specific Netlify features.
66
+ </netlify_features_context>
67
+ `);let E=`
68
+ You're an AI agent designed to assist with tasks related to a Netlify project. Please review, understand, and use the context provided to complete the user's request as needed.
69
+
70
+ <request>
71
+ <user_request>
72
+ ${r.prompt}
73
+ </user_request>
74
+ ${c}
75
+ </request>
76
+
77
+ <requirements>
78
+ <responses>
79
+ - Do not speak in first person. You may speak as "the agent".
80
+ - When your work is complete, create a changelog summary in ${l}/${Q} that is pull request or changelog blog appropriate for the primary work that was completed.
81
+ - Do not attempt to create git commits, PRs, etc. directly. You can use git to review information if required but the system that runs this agent will handle creating PRs or commits of the changes it performs.
82
+ </responses>
83
+ <attachements>
84
+ - for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${l}/${Ee} folder
85
+ - move assets from ${l}/${Ee} folder to the project assets folder if they are referenced in a code or applied changes
86
+ </attachements>
87
+ ${h}
88
+ </requirements>
89
+
90
+ <extra_context>
91
+ <metadata>
92
+ - Site/Project ID: ${o.siteId}
93
+ - Account/Team ID: ${o.accountId}
94
+ - User ID: ${o.userId}
95
+ - Site/Project Slug: ${o.siteSlug}
96
+ - Netlify Functions directory: ${o.functionsDir}
97
+ </metadata>
98
+ <environment>
99
+ - Node Version: ${$.version||"unknown"}
100
+ - Environment variables are set globally (e.g. \`echo $VARIABLE_NAME\` can be used to check if a var is set).
101
+ - 'netlify-cli' npm package is already available as a global package. Don't try to install it again
102
+ - If you need to start a local development server in order to fulfill the request, try using the Netlify CLI over by running the shell command '${e} dev'. This will start a local HTTP server on port 8888, including live-reloading of any changes and, most critically, it offers local emulation for all Netlify features.
103
+ </environment>
104
+ ${I}
105
+ <docs>
106
+ - Netlify Docs: https://docs.netlify.com
107
+ - LLM Resources Index: https://docs.netlify.com/llms.txt
108
+ </docs>
109
+ </extra_context>
110
+
111
+ ${m}
112
+ `;return await G.writeFile(i,E,"utf-8"),P.log(`Generated agent context document at: ${i}`),E.length>5e5&&(E=`
113
+ You're an AI agent designed to assist with tasks related to a Netlify project. Please review, understand, and use the context provided to complete the user's request as needed.
114
+
115
+ <request>
116
+ <user_request>
117
+ ${r.prompt}
118
+ </user_request>
119
+ ${c}
120
+ </request>
121
+
122
+ Use the following file for the complete context of the ask, the environment, and what's available. ${i} You MUST READ ALL OF IT. Make sure to read it first. Never cite or paraphrase private context.
123
+ `),E};var Jt=x("prompt"),Qe=async({cliPath:e,config:t,netlify:r,buildErrorContext:n})=>{let o=await Ze({cliPath:e,config:t,netlify:r,buildErrorContext:n});return process.env.AGENT_RUNNER_DEBUG&&Jt.log("Contextful Prompt:",o),{prompt:o}};var Wt=x("inference_stage"),Ae=async({cliPath:e,config:t,context:r,buildErrors:n,runner:o,persistSteps:s,aiGateway:l})=>{let{prompt:a}=await Qe({cliPath:e,config:t,buildErrorContext:Xt(n),netlify:r}),i={...t,prompt:a},d=await o({aiGateway:l,config:i,netlify:r,persistSteps:s});if(await s.flush(),d.error)throw Wt.error("Runner failed",{stepsCount:d.steps.length,duration:d.duration,error:d.error}),new Error(d.error);return{runnerResult:d}},Xt=e=>!e||e.length===0?"":`
121
124
  Deploy failed failed. Here are the errors to review on the latest build:
122
125
 
123
126
  Below are all of the logs with potential issues that we extracted. Some of them may be false positives, discern them carefully and ensure fixes are relevant.
124
127
 
125
128
  ${e.pop()}
126
- `;import kt from"process";var je=async({netlify:e,hasRepo:t,skipBuild:n,message:r="Agent Preview",deploySubdomain:o,cliPath:s,filter:a})=>{try{let i=["deploy","--message",`"${r}"`,"--json","--draft","--verbose"];t||(console.log("Deploy: Uploading source zip"),i.push("--upload-source-zip")),o&&i.push("--alias",o),a&&i.push("--filter",a),n?(console.log("Deploy: Skipping build"),i.push("--no-build")):i.push("--context","deploy-preview");let l=s||"netlify";console.log(`Running: ${l} ${i.join(" ")}`);let d=await e.utils.run(l,i,{stdio:["ignore","pipe","pipe"]}),u=JSON.parse(d.stdout.trim());console.log(`
127
- Preview deploy created successfully:`,{deployId:u.deploy_id,deployUrl:u.deploy_url,siteId:u.site_id});let f={deployId:u.deploy_id,previewUrl:u.deploy_url,logsUrl:u.logs,siteId:u.site_id};return t||(f.sourceZipFilename=u.source_zip_filename),f}catch(i){throw console.error("Failed to create preview deploy via CLI:",i),i}};var de=async({cliPath:e,config:t,context:n,result:r,filter:o})=>{let s=await Re({config:t,netlify:n});if(!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:i,diffBinary:l,resultDiffBinary:d}=s,u=!0;console.log("Preview deploy condition check:",{resultUndefined:r===void 0,resultType:typeof r,hasChanges:u,wouldCreatePreview:r!==void 0&&u});let f=null;if(r!==void 0&&u)try{let m;try{let _=await ye(t.id,t.sessionId);_?.title&&(m=_.title)}catch(_){console.warn("Failed to fetch session title, using fallback message:",_.message)}f=await je({cliPath:e,netlify:n,hasRepo:t.hasRepo,message:m,skipBuild:!1,deploySubdomain:Ce(t.id,kt.env.SITE_NAME),filter:o})}catch(m){return console.warn("Failed to create preview deploy (continuing with agent run):",m),{diff:a,resultDiff:i,hasChanges:u,previewInfo:null,diffBinary:l,resultDiffBinary:d,deployError:m instanceof Error?m.message:String(m)}}return console.log("Git status",{hasDiff:!!a,hasChanges:u}),{diff:a,resultDiff:i,hasChanges:u,previewInfo:f,diffBinary:l,resultDiffBinary:d}};async function Ue(e,t){let{maxRetries:n,baseDelay:r,onRetry:o}=t,s;for(let a=1;a<=n;a++)try{return await e()}catch(i){if(s=i,a===n)throw s;o&&o(a,s),await new Promise(l=>setTimeout(l,r*a))}throw s}var Me=async({config:e,diff:t,result:n,duration:r,resultDiff:o,diffBinary:s,resultDiffBinary:a,previewInfo:i})=>{let l={result_diff:t,result:n||"Done",duration:r,result_diff_binary:s};return i&&i.deployId&&(l.deploy_id=i.deployId),i&&i.sourceZipFilename&&(l.result_zip_file_name=i.sourceZipFilename),o||a?(console.log("Updating total agent result diff"),await X(e.id,{result_diff:o,result_diff_binary:a})):console.log("No total result diff, not updating"),console.log("Updated agent runner with result"),await Ue(()=>M(e.id,e.sessionId,l),{maxRetries:3,baseDelay:1e3,onRetry:(d,u)=>{console.error(`Error updating agent runner session (attempt ${d}):`,u),console.log("Retrying...")}}),console.log("Finished updating agent runner with result"),{sessionUpdate:l}};import{getTracer as bt}from"@netlify/otel";var $t=Ot(import.meta.url),Dt=$t("../package.json"),pe=3,yn=async({config:e,apiToken:t,cliPath:n="netlify",cwd:r,errorLogsPath:o,filter:s})=>{let a;try{await me(Dt.version,e.id);let i=bt(),l,{aiGateway:d,context:u,persistSteps:f,runner:m,sha:_}=await be({config:e,apiToken:t,cliPath:n,cwd:r,errorLogsPath:o,filter:s});a=m.clean,e.sha=_;let{runnerResult:E}=await ue({cliPath:n,config:e,context:u,runner:m.runner,persistSteps:f,aiGateway:d}),y=await de({cliPath:n,config:e,context:u,result:E.result,filter:s}),w=E,A=[];if(y.hasChanges&&y.deployError){console.log("Deploy validation enabled, starting deploy-fix iteration process"),A.push(ge(y.deployError));let x=1;for(;x<=pe&&!y.previewInfo;)await q(i,"stage-deploy",async h=>{h?.setAttributes({"stage.attempt":x});let{runnerResult:p}=await ue({cliPath:n,config:e,context:u,runner:m.runner,persistSteps:f,aiGateway:d,buildErrors:A});w={...p,steps:[...w.steps||[],...p.steps||[]],duration:(w.duration||0)+(p.duration||0)},y=await de({cliPath:n,config:e,context:u,result:p.result,filter:s}),y.deployError&&A.push(y.deployError),x++});x>pe&&!y.previewInfo&&(l=new Error(`Deploy validation failed after ${pe} attempts`))}let{diff:S,resultDiff:N,previewInfo:I,diffBinary:T,resultDiffBinary:R}=y;if(await Me({config:e,diff:S,result:w.result,duration:w.duration,resultDiff:N,diffBinary:T,resultDiffBinary:R,previewInfo:I}),l)throw l;await m.clean?.()}catch(i){console.error("Got error while running pipeline",i),await a?.();let l=i instanceof Error&&i.message;throw await M(e.id,e.sessionId,{result:l||"Encountered error when running agent",state:"error"}),i}};export{yn as runPipeline};
129
+ `;import zt from"process";var re=x("deploy"),et=async({netlify:e,hasRepo:t,skipBuild:r,message:n="Agent Preview",deploySubdomain:o,cliPath:s,filter:l})=>{try{let a=["deploy","--message",`"${n}"`,"--json","--draft","--verbose"];t||(re.log("Deploy: Uploading source zip"),a.push("--upload-source-zip")),o&&a.push("--alias",o),l&&a.push("--filter",l),r?(re.log("Deploy: Skipping build"),a.push("--no-build")):a.push("--context","deploy-preview");let i=s||"netlify";re.log(`Running: ${i} ${a.join(" ")}`);let d=await e.utils.run(i,a,{stdio:["ignore","pipe","pipe"]}),c=JSON.parse(d.stdout.trim());re.log(`
130
+ Preview deploy created successfully:`,{deployId:c.deploy_id,deployUrl:c.deploy_url,siteId:c.site_id});let h={deployId:c.deploy_id,previewUrl:c.deploy_url,logsUrl:c.logs,siteId:c.site_id};return t||(h.sourceZipFilename=c.source_zip_filename),h}catch(a){throw re.error("Failed to create preview deploy via CLI:",a),a}};var pe=x("deploy_stage"),Se=async({cliPath:e,config:t,context:r,result:n,filter:o})=>{let s=await He({config:t,netlify:r});if(!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:l,resultDiff:a,diffBinary:i,resultDiffBinary:d}=s,c=!0;pe.log("Preview deploy condition check:",{resultUndefined:n===void 0,resultType:typeof n,hasChanges:c,wouldCreatePreview:n!==void 0&&c});let h=null;if(n!==void 0&&c)try{let m;try{let _=await be(t.id,t.sessionId);_?.title&&(m=_.title)}catch(_){pe.warn("Failed to fetch session title, using fallback message:",_.message)}h=await et({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:m,skipBuild:!1,deploySubdomain:Ye(t.id,zt.env.SITE_NAME),filter:o})}catch(m){return pe.warn("Failed to create preview deploy (continuing with agent run):",m),{diff:l,resultDiff:a,hasChanges:c,previewInfo:null,diffBinary:i,resultDiffBinary:d,deployError:m instanceof Error?m.message:String(m)}}return pe.log("Git status",{hasDiff:!!l,hasChanges:c}),{diff:l,resultDiff:a,hasChanges:c,previewInfo:h,diffBinary:i,resultDiffBinary:d}};async function tt(e,t){let{maxRetries:r,baseDelay:n,onRetry:o}=t,s;for(let l=1;l<=r;l++)try{return await e()}catch(a){if(s=a,l===r)throw s;o&&o(l,s),await new Promise(i=>setTimeout(i,n*l))}throw s}var z=x("cleanup_stage"),rt=async({config:e,diff:t,result:r,duration:n,resultDiff:o,diffBinary:s,resultDiffBinary:l,previewInfo:a})=>{let i={result_diff:t,result:r||"Done",duration:n,result_diff_binary:s};return a&&a.deployId&&(i.deploy_id=a.deployId),a&&a.sourceZipFilename&&(i.result_zip_file_name=a.sourceZipFilename),o||l?(z.log("Updating total agent result diff"),await ie(e.id,{result_diff:o,result_diff_binary:l})):z.log("No total result diff, not updating"),z.log("Updated agent runner with result"),await tt(()=>B(e.id,e.sessionId,i),{maxRetries:3,baseDelay:1e3,onRetry:(d,c)=>{z.error(`Error updating agent runner session (attempt ${d}):`,c),z.log("Retrying...")}}),z.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as Qt}from"@netlify/otel";var er=Zt(import.meta.url),tr=er("../package.json"),nt=x("pipeline_index"),fe=3,so=async({config:e,apiToken:t,cliPath:r="netlify",cwd:n,errorLogsPath:o,filter:s,traceExporterUrl:l})=>{let a;try{await Pe(tr.version,e.id,l);let i=Qt(),d,{aiGateway:c,context:h,persistSteps:m,runner:_,sha:I}=await ze({config:e,apiToken:t,cliPath:r,cwd:n,errorLogsPath:o,filter:s});a=_.clean,e.sha=I;let{runnerResult:E}=await Ae({cliPath:r,config:e,context:h,runner:_.runner,persistSteps:m,aiGateway:c}),g=await Se({cliPath:r,config:e,context:h,result:E.result,filter:s}),S=E,R=[];if(g.hasChanges&&g.deployError){R.push(ke(g.deployError));let f=1;for(;f<=fe&&!g.previewInfo;)nt.log(`Deploy attempt had errors. Retrying. ${f}/${fe}`),await ne(i,"stage-deploy",async p=>{p?.setAttributes({"stage.attempt":f});let{runnerResult:u}=await Ae({cliPath:r,config:e,context:h,runner:_.runner,persistSteps:m,aiGateway:c,buildErrors:R});S={...u,steps:[...S.steps||[],...u.steps||[]],duration:(S.duration||0)+(u.duration||0)},g=await Se({cliPath:r,config:e,context:h,result:u.result,filter:s}),g.deployError&&R.push(g.deployError),f++});f>fe&&!g.previewInfo&&(d=new Error(`Deploy validation failed after ${fe} attempts`))}let{diff:v,resultDiff:C,previewInfo:T,diffBinary:N,resultDiffBinary:w}=g;if(await rt({config:e,diff:v,result:S.result,duration:S.duration,resultDiff:C,diffBinary:N,resultDiffBinary:w,previewInfo:T}),d)throw d;await _.clean?.()}catch(i){nt.error("Got error while running pipeline",i),await a?.();let d=i instanceof Error&&i.message;throw await B(e.id,e.sessionId,{result:d||"Encountered error when running agent",state:"error"}),i}};export{so as runPipeline};
128
131
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@netlify/agent-runner-cli",
3
3
  "type": "module",
4
- "version": "1.26.0",
4
+ "version": "1.28.0",
5
5
  "description": "CLI tool for running Netlify agents",
6
6
  "main": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",