@netlify/agent-runner-cli 1.20.0 → 1.22.0-alpha.1
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 +55 -54
- package/dist/index.js +55 -54
- package/package.json +1 -1
package/dist/bin.js
CHANGED
|
@@ -1,24 +1,37 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
2
|
+
import Be from"process";import Yt from"minimist";import{createRequire as Ot}from"module";import{createTracerProvider as Me}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as He}from"@netlify/otel/opentelemetry";import{withActiveSpan as qe}from"@netlify/otel";var ge=(e,t)=>Me({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new He(new re)]});function V(e,t,n){return console.log(`\u23F3 TRACE: ${t} starting...`),qe(e,t,n)}var re=class{export(t,n){for(let o of t)this.logSpan(o);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,o=t.attributes,r=[];for(let[i,l]of Object.entries(o))i.includes("duration")&&typeof l=="number"?r.push(`${i}=${l.toFixed(2)}ms`):r.push(`${i}=${l}`);let s=t.status?.code===2?"\u274C":"\u2705",a=r.length>0?` [${r.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}`)}};import ne from"process";import{getTracer as gt}from"@netlify/otel";import X from"process";var se=X.env.NETLIFY_API_URL,ie=X.env.NETLIFY_API_TOKEN,J=async(e,t={})=>{if(!se||!ie)throw new Error("No API URL or token");let n=new URL(e,se),o={...t,headers:{...t.headers,Authorization:`Bearer ${ie}`}};X.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let r=await fetch(n,o),s=r.ok&&r.status<=299;if(X.env.AGENT_RUNNERS_DEBUG==="true"&&(console.log(`[DEBUG] Response headers for ${n}:`),r.headers.forEach((i,l)=>{console.log(` ${l}: ${i}`)})),s||console.error(`Got status ${r.status} for request ${n}`),t.raw){if(!s)throw r;return r}let a=await(r.headers.get("content-type").includes("application/json")?r.json():r.text());if(!s)throw a;return a},_e=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)},W=(e,t)=>J(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),z=(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}`),Te=(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 Ee=async({netlify:e,config:t})=>{let n,o,r,s,a=e.constants?.SITE_ID;if(!a)throw new Error("No site id");let i=async()=>{clearTimeout(r),console.log("Requesting AI gateway information");let l=await Te(a,t.id,t.sessionId);if({token:n,url:s}=l,o=l.expires_at?l.expires_at*1e3:void 0,console.log("Got AI gateway information",{token:!!n,expiresAt:o,url:s}),o){let c=o-Date.now()-6e4;c>0&&(r=setTimeout(()=>{i()},c))}};return await i(),{get url(){return s},get token(){return n}}};import xe from"process";import{execa as Ke,execaCommand as Zt}from"execa";var Ve={preferLocal:!0},we=(e,t,n)=>{let[o,r]=Xe(t,n),s={...Ve,...r},a=Ke(e,o,s);return Je(a,s),a};var Xe=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Je=(e,t)=>{t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0||(e.stdout?.pipe(xe.stdout),e.stderr?.pipe(xe.stderr))};var We=e=>new Promise(t=>{setTimeout(t,e)}),Ne=(e,t=3e3)=>{let n=!1,o=null,r=[],s=null,a=(...i)=>{if(n)return o=i,new Promise(u=>{r.push(u)});n=!0;let l,c=new Promise(u=>{l=u});return s=(async()=>{await Promise.resolve();let u=await e(...i);for(l(u);;){if(await We(t),!o)return n=!1,s=null,u;let m=o,_=r;o=null,r=[],u=await e(...m),_.forEach(d=>{d(u)})}})(),c};return a.flush=async()=>{if((n||o)&&s)return await s,a.flush()},a},Z=(e,t,n=!1)=>{let o=null,r=null,s=null,a=function(...i){r=i,s=this;let l=n&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,n||(e.apply(s,r),r=null,s=null)},t),l&&(e.apply(s,r),r=null,s=null)};return a.cancel=()=>{clearTimeout(o),o=null,r=null,s=null},a.flush=()=>{if(o){clearTimeout(o);let i=r,l=s;o=null,r=null,s=null,e.apply(l,i)}},a},Q=(e,t=!0)=>{if(e)try{return JSON.parse(e)}catch(n){t&&console.error("Could not parse JSON",n)}},Ie=(e,t)=>{let r=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let i=`--${t}${r}`;if(i.length>55)return"";let l=60-i.length;if(l<=0)return"";if(l>=s.length+6){let c=Math.min(l-s.length,e.length);return`${s}${e.slice(0,c)}`}return e.slice(0,l)};import{Buffer as Ae}from"buffer";var Ce=async({config:e,netlify:t})=>{let n=await Ze(t),{hasChanges:o}=n,{status:r}=n;if(!o)return{hasChanges:!1};let s=await Qe(t,r);await t.utils.run("git",["add",".",...s]);let i=(await t.utils.run("git",["diff","--staged"])).stdout;if(o=!!i,!o)return{hasChanges:!1};let c=(await t.utils.run("git",["diff","--staged","--binary"])).stdout,u,m;if(e.sha){await t.utils.run("git",["commit","-m","Agent runner"]),u=(await t.utils.run("git",["diff",e.sha,"HEAD"])).stdout;let T=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"])).stdout;u!==T&&(m=Ae.from(T).toString("base64"))}let _={hasChanges:!0,diff:i,resultDiff:u};return i!==c&&(_.diffBinary=Ae.from(c).toString("base64")),m&&(_.resultDiffBinary=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(`
|
|
3
|
+
`).filter(r=>!ze.some(s=>s instanceof RegExp?s.test(r):r===s))).length!==0,status:t.stdout}};var Re=async e=>{let{stdout:t}=await e.utils.run("git",["rev-parse","HEAD"]);return t.trim()},ve=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"],o=[],r=n.map(async a=>{try{return await e.utils.run("git",["check-ignore","-v",a]),null}catch{return`:!${a}`}});return(await Promise.all(r)).forEach(a=>{a&&o.push(a)}),t.split(`
|
|
4
|
+
`).forEach(a=>{let i=a.match(/\?\? (.+?)\.log$/)?.[1];i&&o.push(`:!${i}.log`)}),o};import et from"fs/promises";import tt from"os";import te from"path";import j from"process";var ee="netlify-agent-runner-context.md",ae="task-history",le="netlify-context",D=".netlify",F="other",$="personal";var L="enterprise",U="free";var ot=({catchError:e,runCmd:t,error:n,result:o,runnerName:r})=>(console.log(`${r} command completed with catch handler triggered`,{hadExistingError:!!n,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(console.log("Preserving existing result despite catch handler being triggered"),n?{error:n,result:o}:{error:"Process completed with errors but result was captured",result:o}):(console.log("Setting result to undefined because no valid result was captured"),{error:n||`${r} failed`,result:void 0}));async function ce({config:e,netlify:t,persistSteps:n,sendSteps:o,aiGateway:r}){let{accountType:s,prompt:a}=e,{model:i}=e;if(r){let{token:h,url:g}=r;if(!h||!g)throw new Error("No token or url provided from AI Gateway");let f=nt[s];if(!f)throw new Error(`Claude is not supported for the account type ${s}`);if(i&&!f?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);j.env.ANTHROPIC_API_KEY=h,j.env.ANTHROPIC_BASE_URL=g}else if(!j.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let l=[],c=[],u=[],m={},_=0,d=0,y,T,P=te.join(j.cwd(),"node_modules"),v=[te.join(j.env.NODE_PATH||P,".bin/claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...i?["--model",i]:[],"-p",a],C=`${j.env.NVM_BIN}/node`;console.log(`Running ${C} ${v.join(" ")}`);let w=t.utils.run(C,v,{all:!0,env:j.env});w.stdin?.end();let E=Z(()=>{n?.({steps:l,duration:d}),o?.({steps:c,duration:d}),c=[]},250),x=(h,g)=>{h.id=_,_+=1,u.push(h),l.push(h),c.push(h),g||E.flush(),E(),g&&E.flush()},A="";return w.all.on("data",h=>{if(A+=h.toString(),!h.includes(`
|
|
5
|
+
`))return;let g=A.split(`
|
|
6
|
+
`).filter(Boolean).map(f=>{try{return JSON.parse(f)}catch{console.log("Could not parse line",f)}return null}).filter(Boolean);A="",g.forEach(f=>{Array.isArray(f?.message?.content)?f.message.content.forEach(p=>{switch(p.type){case"text":{p.text&&x({message:p.text});break}case"image":{typeof p.source=="object"&&p.source.type==="base64"&&p.source.media_type?x({message:``}):console.log(`Unsupported image type ${p.source?.type}`,p.source);break}case"tool_use":{if(p.name==="Task"){let N=p.input?.description&&`\`${p.input.description}\``;x({title:[p.name,N].filter(Boolean).join(" ")})}else m[p.id]=p;E.flush();break}case"tool_result":{let N=m[p.tool_use_id],O;if(N){let B=N.input?.file_path&&te.relative(j.cwd(),N.input.file_path),I=B&&`\`${B}\``;O=[N.name,I].filter(Boolean).join(" ")}let G=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(N?.name),b;if(typeof p.content=="string")b=p.content;else if(Array.isArray(p.content)){let B=[];p.content.forEach(I=>{I?.type==="text"&&typeof I.text=="string"?B.push(I.text):I?.type==="image"&&typeof I.source=="object"?I.source.type==="base64"&&I.source.media_type?B.push(``):console.log(`Unsupported image type ${I.source.type}`,I.source):console.log(`Unsupported block type ${I?.type}`)}),b=B.join(`
|
|
7
|
+
|
|
8
|
+
`)}G&&b&&(b=`\`\`\`
|
|
9
|
+
${b.trim()}
|
|
10
|
+
\`\`\``),x({title:O,message:b},!0);break}case"thinking":{p.thinking&&x({title:"Thinking",message:p.thinking},!0);break}default:console.log(`Message content type is not supported ${p.type}`,p)}}):f?.type==="result"&&(d=f.duration_ms,f.is_error?T=f.result:y=f.result,[u,l,c].forEach(p=>{p[p.length-1]?.message===y&&p.pop()}))})}),await w.catch(h=>{({error:T,result:y}=ot({catchError:h,runCmd:w,error:T,result:y,runnerName:"Claude"}))}),E.flush(),{steps:u,duration:d,result:y,error:T}}var Se=async()=>{let e=te.join(tt.homedir(),".claude");await et.rm(e,{recursive:!0,force:!0})},nt={[L]:{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}}},[$]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[U]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}},[F]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}}};import rt from"fs/promises";import st from"os";import ue from"path";import H from"process";var it=({catchError:e,runCmd:t,error:n,result:o,runnerName:r})=>(console.log(`${r} command completed with catch handler triggered`,{hadExistingError:!!n,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(console.log("Preserving existing result despite catch handler being triggered"),n?{error:n,result:o}:{error:"Process completed with errors but result was captured",result:o}):(console.log("Setting result to undefined because no valid result was captured"),{error:n||`${r} failed`,result:void 0}));async function pe({config:e,netlify:t,persistSteps:n,sendSteps:o,aiGateway:r}){let{accountType:s,prompt:a}=e,{model:i}=e;if(r){let{token:E,url:x}=r;if(!E||!x)throw new Error("No token or url provided from AI Gateway");let A=at[s];if(!A)throw new Error(`Codex is not supported for the account type ${s}`);if(i&&!A?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);H.env.OPENAI_API_KEY=E,H.env.OPENAI_BASE_URL=x}else if(!H.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let l=[],c=[],u={},m=0,_=0,d,y,T=ue.join(H.cwd(),"node_modules"),P=[ue.join(H.env.NODE_PATH||T,".bin/codex"),"--approval-mode","full-auto",r?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...i?["--model",i]:[],"-q",a].filter(Boolean),v=`${H.env.NVM_BIN}/node`;console.log(`Running ${v} ${P.join(" ")}`);let C=t.utils.run(v,P,{all:!0,env:{...H.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),w="";return C.all.on("data",E=>{if(w+=E.toString(),!E.includes(`
|
|
11
|
+
`))return;let x=w.toString().split(`
|
|
12
|
+
`).filter(Boolean).map(g=>{try{return JSON.parse(g)}catch{console.log("Could not parse line",g)}return null}).filter(Boolean);w="";let A=[],h=!1;x.forEach(g=>{if(g?.duration_ms&&(_=g.duration_ms,h=!0),g?.type==="local_shell_call")u[g.call_id]=g;else if(g?.type==="local_shell_call_output"){let f=ct(u[g.call_id],g);f.id=m,m+=1,f&&(c.push(f),l.push(f),A.push(f),h=!0)}else g?.type==="message"&&g.role==="assistant"?d=g.content.map(f=>f.text).join(`
|
|
13
|
+
`):g?.type==="message"&&g.role==="system"&&(y=g.content.map(f=>f.text).join(`
|
|
14
|
+
`))}),h&&(n?.({steps:l,duration:_}),o?.({steps:A,duration:_}))}),await C.catch(E=>{({error:y,result:d}=it({catchError:E,runCmd:C,error:y,result:d,runnerName:"Codex"}))}),{steps:c,duration:_,result:d,error:y}}var Pe=async()=>{let e=ue.join(st.homedir(),".codex");await rt.rm(e,{recursive:!0,force:!0})},at={[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},o1:{maxTokens:1e5},"o1-mini":{maxTokens:65536},"o3-mini":{maxTokens:1e5},"gpt-image-1":{},"dall-e-2":{},"dall-e-3":{}}},[$]:{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}}},[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}}},[F]:{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)),o=n?`Running \`${n.join(" ")}\``:void 0,r;try{r=JSON.parse(t.output).output?.trim(),r&&(r=`\`\`\`
|
|
15
|
+
${r.trim()}
|
|
16
|
+
\`\`\``)}catch(s){console.error("Could not decode outputMsg",s,t.output)}return{title:o,message:r}};import ut from"fs/promises";import pt from"os";import oe from"path";import Y from"process";var dt=({catchError:e,runCmd:t,error:n,result:o,runnerName:r})=>(console.log(`${r} command completed with catch handler triggered`,{hadExistingError:!!n,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(console.log("Preserving existing result despite catch handler being triggered"),n?{error:n,result:o}:{error:"Process completed with errors but result was captured",result:o}):(console.log("Setting result to undefined because no valid result was captured"),{error:n||`${r} 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 de({config:e,netlify:t,persistSteps:n,sendSteps:o,aiGateway:r}){let{accountType:s,prompt:a}=e,{model:i}=e;if(r){let{token:h,url:g}=r;if(!h||!g)throw new Error("No token or url provided from AI Gateway");let f=mt[s];if(!f)throw new Error(`Gemini is not supported for the account type ${s}`);if(i&&!f?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);Y.env.GEMINI_API_KEY=h,Y.env.GOOGLE_GEMINI_BASE_URL=g}else if(!Y.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let l=[],c=[],u=[],m={},_=0,d=0,y,T,P=oe.join(Y.cwd(),"node_modules"),v=[oe.join(Y.env.NODE_PATH||P,".bin/gemini"),...i?["--model",i]:[],"--yolo","-p",a],C=`${Y.env.NVM_BIN}/node`;console.log(`Running ${C} ${v.join(" ")}`);let w=t.utils.run(C,v,{all:!0,env:Y.env});w.stdin?.end();let E=Z(()=>{n?.({steps:l,duration:d}),o?.({steps:c,duration:d}),c=[]},250),x=(h,g)=>{h.id=_,_+=1,u.push(h),l.push(h),c.push(h),g||E.flush(),E(),g&&E.flush()},A="";return w.all.on("data",h=>{if(A+=h.toString(),!h.includes(`
|
|
17
|
+
`))return;let g=A.toString().split(`
|
|
18
|
+
`).filter(Boolean).map(f=>{try{if(f.startsWith("[API Error")){let p=f.match(/\[api error: (.+?)]$/i)?.[1];return{type:"error",value:Q(p,!1)?.error?.message||p||"Gemini encountered error"}}return JSON.parse(f)}catch{}return null}).filter(Boolean);A="",g.forEach(f=>{switch(f.type){case"thought":{let p=f.value;x({title:p?.subject??"Thinking...",message:p?.description},!0);break}case"content":{f.value&&x({message:f.value});break}case"tool_call_request":{let p=f.value,N=ft[p.name]??p.name,O=p.args?.path||p.args?.absolute_path,G=O&&oe.relative(Y.cwd(),O),b=p.args?.command,I={title:[N,G&&`\`${G}\``,b&&`\`${b}\``].filter(Boolean).join(" ")};m[p.callId]=I,E.flush();break}case"tool_result":{let p=f.value,N=m[p.callId];if(N){let O=[p.resultDisplay,p.responseParts?.functionResponse?.response?.output].find(G=>typeof G=="string"&&G);O&&(N.message=`\`\`\`
|
|
19
|
+
${O.trim()}
|
|
20
|
+
\`\`\``),x(N,!0)}break}case"result":{d=f.duration_ms,y=f.value,[u,l,c].forEach(p=>{p[p.length-1]?.message===y&&p.pop()});break}case"error":{T=f.value;break}case"finished":break;default:{console.warn("Unhandled message type:",f.type);break}}})}),await w.catch(h=>{({error:T,result:y}=dt({catchError:h,runCmd:w,error:T,result:y,runnerName:"Gemini"}))}),E.flush(),{steps:u,duration:d,result:y,error:T}}var ke=async()=>{let e=oe.join(pt.homedir(),".gemini");await ut.rm(e,{recursive:!0,force:!0})},mt={[L]:{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}}},[$]:{models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[U]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}},[F]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}}};var ht={codex:{runner:pe,clean:Pe},claude:{runner:ce,clean:Se},gemini:{runner:de,clean:ke}},Oe=ht;var be=async({config:e,apiThrottle:t,apiToken:n})=>{let o=gt();return V(o,"init-stage",async r=>{let s=performance.now();r?.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 r?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let i=_t({apiToken:n});_e(i);let l=e.useGateway?await Ee({netlify:i,config:e}):void 0;r?.setAttributes({"init.aiGateway.created":!!l}),e.validateAgent&&e.errorLogsPath&&r?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let c=Ne(({steps:_=[],duration:d})=>{let y=[..._];return _.length=0,z(e.id,e.sessionId,{steps:y,duration:d})},t),u;e.hasRepo?e.sha?(u=e.sha,r?.setAttributes({"init.sha.source":"provided"})):(u=await Re(i),await W(e.id,{sha:u}),r?.setAttributes({"init.sha.source":"current_commit"})):(u=await ve(i),r?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let m=performance.now()-s;return r?.setAttributes({"init.sha":u||"unknown","init.duration.ms":m,"init.status":"success"}),{aiGateway:l,context:i,persistSteps:c,runner:a,sha:u}})},_t=({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:we}});import yt from"crypto";import q from"fs/promises";import S from"path";import k from"process";var Tt=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}},xt=10,wt=async e=>{let{name:t,ext:n}=S.parse(e),o=e,r=S.join(k.cwd(),D,o),s=0;for(;await Nt(r);){if(s>=xt)throw new Error("Failed to generate context file");o=`${t}-${yt.randomUUID().slice(0,5)}${n}`,r=S.join(k.cwd(),D,o),s+=1}return o},Nt=async e=>{try{return await q.access(e),!0}catch{return!1}},It=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(o=>o&&typeof o=="object"&&o.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}},At=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 o=await n.text();return await q.writeFile(t,o,"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}},Ct=async()=>{let e=await It();if(!e)return[];let t=S.join(k.cwd(),D,le);await q.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=S.join(t,i),c=S.join(D,le,i);return console.log(`Downloading ${a.scope} context...`),await At(a.endpoint,l)?(console.log(`Downloaded: ${c}`),{scope:a.scope,path:c,key:s}):null});return(await Promise.all(n)).filter(s=>s!==null)},De=async({cliPath:e,netlify:t,config:n})=>{let o=Tt(t),r=Et(),s=await wt(ee),a=S.join(k.cwd(),D);await q.mkdir(a,{recursive:!0});let i=S.join(D,s),l=S.join(k.cwd(),i),c=`# Agent Context
|
|
3
21
|
|
|
4
22
|
In Netlify documentation and interfaces, the terms "site" and "project" refer to the same thing.
|
|
5
23
|
|
|
6
24
|
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.
|
|
7
25
|
|
|
8
26
|
## Netlify Site
|
|
9
|
-
|
|
10
27
|
- Site ID: ${o.siteId}
|
|
11
28
|
- Account ID: ${o.accountId}
|
|
12
29
|
- User ID: ${o.userId}
|
|
13
30
|
- Site Slug: ${o.siteSlug}
|
|
14
31
|
- Netlify Functions directory: ${o.functionsDir}
|
|
32
|
+
- Running Node Version: ${r.nodeVersion}
|
|
15
33
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
- Node Version: ${n.nodeVersion}
|
|
19
|
-
|
|
20
|
-
### Available Environment Variables
|
|
21
|
-
${n.envVars.map(u=>`\`${u}\``).join(", ")}
|
|
34
|
+
The available environment variables are set globally (e.g. \`echo $VARIABLE_NAME\` can be used to check if a var is set).:
|
|
22
35
|
|
|
23
36
|
## Attachments
|
|
24
37
|
|
|
@@ -29,39 +42,49 @@ ${n.envVars.map(u=>`\`${u}\``).join(", ")}
|
|
|
29
42
|
'netlify-cli' npm package is already available as a global package.
|
|
30
43
|
Don't try to install it, in case you want to use it, use the global package.
|
|
31
44
|
|
|
32
|
-
|
|
45
|
+
`;n.siteContext&&n.siteContext.length!==0&&(c+=`
|
|
46
|
+
# Project Guidelines
|
|
47
|
+
<project_guidelines>
|
|
48
|
+
${n.siteContext.filter(m=>m.site_context).map(m=>typeof m.site_context=="string"?m.site_context:typeof m.site_context=="object"?JSON.stringify(m.site_context):"").join(`
|
|
49
|
+
|
|
50
|
+
`)}
|
|
51
|
+
</project_guidelines>
|
|
52
|
+
`);let u=await Ct();if(u.length>0&&(c+=`
|
|
53
|
+
# Netlify Features Context
|
|
54
|
+
|
|
55
|
+
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.
|
|
56
|
+
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.
|
|
57
|
+
|
|
58
|
+
${u.map(m=>`- **${m.scope}**: ${m.path}`).join(`
|
|
59
|
+
`)}
|
|
33
60
|
|
|
61
|
+
Refer to these files when working with specific Netlify features.
|
|
62
|
+
`),c+=`
|
|
63
|
+
Additional Documentation Resources
|
|
34
64
|
- Netlify Docs: https://docs.netlify.com
|
|
35
65
|
- LLM Resources Index: https://docs.netlify.com/llms.txt
|
|
36
|
-
|
|
37
|
-
# Project Guidelines
|
|
66
|
+
`,n.sessionHistoryContext?.length){let m=S.join(k.cwd(),D,ae);await q.mkdir(m,{recursive:!0});let _=await Promise.all(n.sessionHistoryContext.map(async(d,y)=>{let T=y+1,P=`attempt-${T}.md`,v=S.join(m,P),C=S.join(D,ae,P),w=`# Task History - Attempt ${T}
|
|
38
67
|
|
|
39
|
-
|
|
68
|
+
## Request - what the user asked for
|
|
69
|
+
${d.request}
|
|
40
70
|
|
|
41
|
-
|
|
42
|
-
|
|
71
|
+
---
|
|
72
|
+
|
|
73
|
+
## Response - what the agent replied with after its work
|
|
43
74
|
|
|
44
|
-
|
|
45
|
-
-
|
|
46
|
-
- <turn> groups a request and its response.
|
|
47
|
-
- <request> is the user request.
|
|
48
|
-
- <response> is the agent result.
|
|
75
|
+
${d.response}
|
|
76
|
+
`;return await q.writeFile(v,w,"utf-8"),console.log(`Created history file: ${C}`),C}));c+=`# History of prior work on this task
|
|
49
77
|
|
|
50
|
-
|
|
78
|
+
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.
|
|
51
79
|
|
|
52
|
-
|
|
53
|
-
${r.sessionHistoryContext.map((u,h)=>`<turn attempt="${h+1}">
|
|
54
|
-
<request>${u.request}</request>
|
|
55
|
-
<response>${u.response}</response>
|
|
56
|
-
</turn>`).join(`
|
|
80
|
+
${_.map(d=>`- ${d}`).join(`
|
|
57
81
|
`)}
|
|
58
|
-
|
|
59
|
-
`),await re.writeFile(l,d,"utf-8"),console.log(`Generated agent context document at: ${l}`),s},me=e=>`The build is currently failing after your previous changes.
|
|
82
|
+
`}return await q.writeFile(l,c,"utf-8"),console.log(`Generated agent context document at: ${l}`),i},Fe=e=>`The build is currently failing after your changes.
|
|
60
83
|
Your task is to analyze and fix the build errors.
|
|
61
84
|
Don't apply techniques of reverting changes. Apply fixes related to errors.
|
|
62
85
|
Don't try to run build by yourself. Just fix the errors.
|
|
63
86
|
|
|
64
|
-
${e}`;var
|
|
87
|
+
${e}`;var $e=(e={})=>`
|
|
65
88
|
Check for errors and validate the fix
|
|
66
89
|
|
|
67
90
|
${e.errorLogsPath?`Error Check Process:
|
|
@@ -85,33 +108,11 @@ ${e}`;var ge=(e={})=>`
|
|
|
85
108
|
VALIDATION_RESULT: PASS {"checks": ["error_logs"]}
|
|
86
109
|
or
|
|
87
110
|
VALIDATION_RESULT: FAIL {"checks": ["error_logs"], "errors": ["<errors>"]}
|
|
88
|
-
|
|
111
|
+
`;var Rt=(e=ee)=>`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.`,vt=async({cliPath:e,config:t,netlify:n})=>{let o=await De({cliPath:e,netlify:n,config:t});return{context:Rt(o)}},St=({config:e})=>{let t=[];return e?.validateAgent&&t.push($e(e)),t},Le=async({cliPath:e,config:t,netlify:n,buildErrorContext:o}={})=>{let{context:r}=await vt({cliPath:e,config:t,netlify:n}),s;s=[...St({config:t})],o&&(s=[...s,Fe(o)]);let a=[];return r&&a.push(r),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(`
|
|
89
112
|
|
|
90
113
|
`)),{prompt:a.join(`
|
|
91
114
|
|
|
92
|
-
`)}};
|
|
93
|
-
`)
|
|
94
|
-
|
|
95
|
-
`))return;let f=I.split(`
|
|
96
|
-
`).filter(Boolean).map(p=>{try{return JSON.parse(p)}catch{console.log("Could not parse line",p)}return null}).filter(Boolean);I="",f.forEach(p=>{Array.isArray(p?.message?.content)?p.message.content.forEach(c=>{switch(c.type){case"text":{c.text&&E({message:c.text});break}case"image":{typeof c.source=="object"&&c.source.type==="base64"&&c.source.media_type?E({message:``}):console.log(`Unsupported image type ${c.source?.type}`,c.source);break}case"tool_use":{if(c.name==="Task"){let N=c.input?.description&&`\`${c.input.description}\``;E({title:[c.name,N].filter(Boolean).join(" ")})}else h[c.id]=c;y.flush();break}case"tool_result":{let N=h[c.tool_use_id],v;if(N){let j=N.input?.file_path&&ee.relative(U.cwd(),N.input.file_path),A=j&&`\`${j}\``;v=[N.name,A].filter(Boolean).join(" ")}let Y=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(N?.name),P;if(typeof c.content=="string")P=c.content;else if(Array.isArray(c.content)){let j=[];c.content.forEach(A=>{A?.type==="text"&&typeof A.text=="string"?j.push(A.text):A?.type==="image"&&typeof A.source=="object"?A.source.type==="base64"&&A.source.media_type?j.push(``):console.log(`Unsupported image type ${A.source.type}`,A.source):console.log(`Unsupported block type ${A?.type}`)}),P=j.join(`
|
|
97
|
-
|
|
98
|
-
`)}Y&&P&&(P=`\`\`\`
|
|
99
|
-
${P.trim()}
|
|
100
|
-
\`\`\``),E({title:v,message:P},!0);break}case"thinking":{c.thinking&&E({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,p.is_error?x=p.result:T=p.result,[u,l,d].forEach(c=>{c[c.length-1]?.message===T&&c.pop()}))})}),await S.catch(m=>{({error:x,result:T}=mt({catchError:m,runCmd:S,error:x,result:T,runnerName:"Claude"}))}),y.flush(),{steps:u,duration:_,result:T,error:x}}var ke=async()=>{let e=ee.join(ft.homedir(),".claude");await pt.rm(e,{recursive:!0,force:!0})},gt={[$]:{default:"claude-3-7-sonnet-20250219",models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:64e3}}},[L]:{default:"claude-sonnet-4-20250514",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:{default:"claude-3-5-haiku-20241022",models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[B]:{default:"claude-3-7-sonnet-20250219",models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}},[D]:{default:"claude-3-7-sonnet-20250219",models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}},[k]:{default:"claude-3-7-sonnet-20250219",models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}}};import ht from"fs/promises";import _t from"os";import le from"path";import G from"process";var Tt=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(console.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(console.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(console.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function ue({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:i,prompt:a}=e,{model:s}=e;if(n){let{token:y,url:E}=n;if(!y||!E)throw new Error("No token or url provided from AI Gateway");let I=Et[i];if(!I)throw new Error(`Codex is not supported for the account type ${i}`);if(s){if(!I?.models?.[s])throw new Error(`${s} is not supported for account type ${i}`)}else s=I.default;G.env.OPENAI_API_KEY=y,G.env.OPENAI_BASE_URL=E}else if(!G.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let l=[],d=[],u={},h=0,g=0,_,T,x=le.join(G.cwd(),"node_modules"),b=[le.join(G.env.NODE_PATH||x,".bin/codex"),"--approval-mode","full-auto",n?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...s?["--model",s]:[],"-q",a].filter(Boolean),C=`${G.env.NVM_BIN}/node`;console.log(`Running ${C} ${b.join(" ")}`);let R=t.utils.run(C,b,{all:!0,env:{...G.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),S="";return R.all.on("data",y=>{if(S+=y.toString(),!y.includes(`
|
|
101
|
-
`))return;let E=S.toString().split(`
|
|
102
|
-
`).filter(Boolean).map(f=>{try{return JSON.parse(f)}catch{console.log("Could not parse line",f)}return null}).filter(Boolean);S="";let I=[],m=!1;E.forEach(f=>{if(f?.duration_ms&&(g=f.duration_ms,m=!0),f?.type==="local_shell_call")u[f.call_id]=f;else if(f?.type==="local_shell_call_output"){let p=xt(u[f.call_id],f);p.id=h,h+=1,p&&(d.push(p),l.push(p),I.push(p),m=!0)}else f?.type==="message"&&f.role==="assistant"?_=f.content.map(p=>p.text).join(`
|
|
103
|
-
`):f?.type==="message"&&f.role==="system"&&(T=f.content.map(p=>p.text).join(`
|
|
104
|
-
`))}),m&&(r?.({steps:l,duration:g}),o?.({steps:I,duration:g}))}),await R.catch(y=>{({error:T,result:_}=Tt({catchError:y,runCmd:R,error:T,result:_,runnerName:"Codex"}))}),{steps:d,duration:g,result:_,error:T}}var Oe=async()=>{let e=le.join(_t.homedir(),".codex");await ht.rm(e,{recursive:!0,force:!0})},Et={[$]:{default:"codex-mini-latest",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:1e5}}},[L]:{default:"codex-mini-latest",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":{}}},pro:{default:"codex-mini-latest",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}}},[B]:{default:"codex-mini-latest",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}}},[D]:{default:"codex-mini-latest",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}}},[k]:{default:"codex-mini-latest",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}}}},yt=new Set(["bash","-lc"]),xt=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(i=>!yt.has(i)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
|
|
105
|
-
${n.trim()}
|
|
106
|
-
\`\`\``)}catch(i){console.error("Could not decode outputMsg",i,t.output)}return{title:o,message:n}};import It from"fs/promises";import Nt from"os";import te from"path";import F from"process";var At=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(console.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(console.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(console.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),St={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:r,sendSteps:o,aiGateway:n}){let{accountType:i,prompt:a}=e,{model:s}=e;if(n){let{token:m,url:f}=n;if(!m||!f)throw new Error("No token or url provided from AI Gateway");let p=wt[i];if(!p)throw new Error(`Gemini is not supported for the account type ${i}`);if(s){if(!p?.models?.[s])throw new Error(`${s} is not supported for account type ${i}`)}else s=p.default;F.env.GEMINI_API_KEY=m,F.env.GOOGLE_GEMINI_BASE_URL=f}else if(!F.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let l=[],d=[],u=[],h={},g=0,_=0,T,x,b=te.join(F.cwd(),"node_modules"),C=[te.join(F.env.NODE_PATH||b,".bin/gemini"),...s?["--model",s]:[],"--yolo","-p",a],R=`${F.env.NVM_BIN}/node`;console.log(`Running ${R} ${C.join(" ")}`);let S=t.utils.run(R,C,{all:!0,env:F.env});S.stdin?.end();let y=Z(()=>{r?.({steps:l,duration:_}),o?.({steps:d,duration:_}),d=[]},250),E=(m,f)=>{m.id=g,g+=1,u.push(m),l.push(m),d.push(m),f||y.flush(),y(),f&&y.flush()},I="";return S.all.on("data",m=>{if(I+=m.toString(),!m.includes(`
|
|
107
|
-
`))return;let f=I.toString().split(`
|
|
108
|
-
`).filter(Boolean).map(p=>{try{if(p.startsWith("[API Error")){let c=p.match(/\[api error: (.+?)]$/i)?.[1];return{type:"error",value:Q(c,!1)?.error?.message||c||"Gemini encountered error"}}return JSON.parse(p)}catch{}return null}).filter(Boolean);I="",f.forEach(p=>{switch(p.type){case"thought":{let c=p.value;E({title:c?.subject??"Thinking...",message:c?.description},!0);break}case"content":{p.value&&E({message:p.value});break}case"tool_call_request":{let c=p.value,N=St[c.name]??c.name,v=c.args?.path||c.args?.absolute_path,Y=v&&te.relative(F.cwd(),v),P=c.args?.command,A={title:[N,Y&&`\`${Y}\``,P&&`\`${P}\``].filter(Boolean).join(" ")};h[c.callId]=A,y.flush();break}case"tool_result":{let c=p.value,N=h[c.callId];if(N){let v=[c.resultDisplay,c.responseParts?.functionResponse?.response?.output].find(Y=>typeof Y=="string"&&Y);v&&(N.message=`\`\`\`
|
|
109
|
-
${v.trim()}
|
|
110
|
-
\`\`\``),E(N,!0)}break}case"result":{_=p.duration_ms,T=p.value,[u,l,d].forEach(c=>{c[c.length-1]?.message===T&&c.pop()});break}case"error":{x=p.value;break}case"finished":break;default:{console.warn("Unhandled message type:",p.type);break}}})}),await S.catch(m=>{({error:x,result:T}=At({catchError:m,runCmd:S,error:x,result:T,runnerName:"Gemini"}))}),y.flush(),{steps:u,duration:_,result:T,error:x}}var be=async()=>{let e=te.join(Nt.homedir(),".gemini");await It.rm(e,{recursive:!0,force:!0})},wt={[$]:{default:"gemini-2.5-flash",models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:65536}}},[L]:{default:"gemini-2.5-pro",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:{default:"gemini-2.0-flash-lite",models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[B]:{default:"gemini-2.5-flash",models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}},[D]:{default:"gemini-2.5-flash",models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}},[k]:{default:"gemini-2.5-flash",models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}}};var Rt={codex:{runner:ue,clean:Oe},claude:{runner:ae,clean:ke},gemini:{runner:ce,clean:be}},De=Rt;var $e=async({config:e,apiThrottle:t,apiToken:r})=>{let o=Ct();return pe(o,"init-stage",async n=>{let i=performance.now();n?.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=De[e.runner];if(!a)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let s=vt({apiToken:r});Ee(s);let l=e.useGateway?await Ie({netlify:s,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!l}),e.validateAgent&&e.errorLogsPath&&n?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let d=Se(({steps:g=[],duration:_})=>{let T=[...g];return g.length=0,z(e.id,e.sessionId,{steps:T,duration:_})},t),u;e.hasRepo?e.sha?(u=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(u=await ve(s),await W(e.id,{sha:u}),n?.setAttributes({"init.sha.source":"current_commit"})):(u=await Pe(s),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let h=performance.now()-i;return n?.setAttributes({"init.sha":u||"unknown","init.duration.ms":h,"init.status":"success"}),{aiGateway:l,context:s,persistSteps:d,runner:a,sha:u}})},vt=({apiToken:e})=>({constants:{NETLIFY_API_HOST:oe.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||oe.env.NETLIFY_API_TOKEN,SITE_ID:oe.env.SITE_ID,FUNCTIONS_DIST:oe.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:Ae}});var Le=async({cliPath:e,config:t,context:r,runner:o,persistSteps:n,aiGateway:i})=>{let{prompt:a}=await K({cliPath:e,config:t,netlify:r}),s={...t,prompt:a},l=await o({aiGateway:i,config:s,netlify:r,persistSteps:n});if(l.error)throw console.error("Runner failed",{stepsCount:l.steps.length,duration:l.duration,error:l.error}),new Error(l.error);return{runnerResult:l}};var Be=async(e,t,r)=>{try{console.log("Running netlify build...");let o=["build","--context","deploy-preview"];r&&o.push("--filter",r);let n=await t.utils.run(e,o);return console.log("Build completed successfully"),{success:!0,stdout:n?.stdout||"",stderr:n?.stderr||""}}catch(o){return console.log("Build failed:",o.message),{success:!1,stdout:o.stdout||"",stderr:o.stderr||"",error:o.message}}},Pt=e=>{if(e.success)return"";let t=[];return e.error&&t.push(`Build Error: ${e.error}`),e.stderr&&t.push(`Build stderr:
|
|
111
|
-
${e.stderr}`),e.stdout&&t.push(`Build stdout:
|
|
112
|
-
${e.stdout}`),t.join(`
|
|
113
|
-
|
|
114
|
-
`)},kt=e=>{let t=[];return t.push("Build validation failed. Here are the build errors you need to fix:"),e.forEach((r,o)=>{t.push(`Build attempt ${o+1}: ${Pt(r)}`)}),t.join(`
|
|
115
|
-
`)},Ue=async({cliPath:e,context:t,initialResult:r,runAgentCallback:o,filter:n})=>{console.log("Starting post-execution build validation");let i=await Be(e,t,n);if(i.success)return console.log("Build validation passed"),{...r,buildValidation:{attempts:0,finalBuildSuccess:!0,buildHistory:[i]}};console.log("Build validation failed, starting build-fix iteration process");let a=[i],s=[],l=0,d=r;for(let u=1;u<=3;u++){console.log(`Build fix attempt ${u}/3`);let h=kt(a);console.log("Running agent to fix build errors"),d=await o({errorContext:h}),s=[...s,...d.steps||[]],l+=d.duration||0;let g=await Be(e,t,n);if(a.push(g),g.success)return console.log(`Build fixed after ${u} attempts`),{...d,steps:s,duration:l,buildValidation:{attempts:u,finalBuildSuccess:!0,buildHistory:a}};console.log(`Build still failing after attempt ${u}`)}return console.log("Build validation failed after 3 attempts"),{...d,steps:s,duration:l,buildValidation:{attempts:3,finalBuildSuccess:!1,buildHistory:a,error:"Build validation failed - unable to fix build errors after 3 attempts"}}};import Ot from"process";var Fe=async({netlify:e,hasRepo:t,skipBuild:r,message:o="Agent Preview",deploySubdomain:n,cliPath:i,filter:a})=>{try{let s=["deploy","--message",`"${o}"`,"--json","--draft"];t||(console.log("Deploy: Uploading source zip"),s.push("--upload-source-zip")),n&&s.push("--alias",n),a&&s.push("--filter",a),r?(console.log("Deploy: Skipping build"),s.push("--no-build")):s.push("--context","deploy-preview");let l=i||"netlify";console.log(`Running: ${l} ${s.join(" ")}`);let d=await e.utils.run(l,s),u=JSON.parse(d.stdout.trim());console.log(`
|
|
116
|
-
Preview deploy created successfully:`,{deployId:u.deploy_id,deployUrl:u.deploy_url,siteId:u.site_id});let h={deployId:u.deploy_id,previewUrl:u.deploy_url,logsUrl:u.logs,siteId:u.site_id};return t||(h.sourceZipFilename=u.source_zip_filename),h}catch(s){throw console.error("Failed to create preview deploy via CLI:",s),s}};var Ye=async({cliPath:e,config:t,context:r,result:o,buildValidation:n,filter:i})=>{let{diff:a,resultDiff:s,hasChanges:l,diffBinary:d,resultDiffBinary:u}=await Ce({config:t,netlify:r});console.log("Preview deploy condition check:",{resultUndefined:o===void 0,resultType:typeof o,hasChanges:l,wouldCreatePreview:o!==void 0&&l});let h=null;if(o!==void 0&&l)try{let g;try{let _=await ye(t.id,t.sessionId);_?.title&&(g=_.title)}catch(_){console.warn("Failed to fetch session title, using fallback message:",_.message)}h=await Fe({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:g,skipBuild:n?.finalBuildSuccess,deploySubdomain:we(t.id,Ot.env.SITE_NAME),filter:i})}catch(g){console.warn("Failed to create preview deploy (continuing with agent run):",g)}return console.log("Git status",{hasDiff:!!a,hasChanges:l}),{diff:a,resultDiff:s,hasChanges:l,previewInfo:h,diffBinary:d,resultDiffBinary:u}};var je=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:i,resultDiffBinary:a,previewInfo:s,cleanRunner:l})=>{let d={result_diff:t,result:r||"Done",duration:o,result_diff_binary:i};return s&&s.deployId&&(d.deploy_id=s.deployId),s&&s.sourceZipFilename&&(d.result_zip_file_name=s.sourceZipFilename),n||a?(console.log("Updating total agent result diff"),await W(e.id,{result_diff:n,result_diff_binary:a})):console.log("No total result diff, not updating"),await l?.(),console.log("Updated agent runner with result"),await z(e.id,e.sessionId,d),{sessionUpdate:d}};var Dt=bt(import.meta.url),$t=Dt("../package.json"),Me=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:i})=>{await de($t.version,e.id);let{aiGateway:a,context:s,persistSteps:l,runner:d,sha:u}=await $e({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:i});e.sha=u;let{runnerResult:h}=await Le({cliPath:r,config:e,context:s,runner:d.runner,persistSteps:l,aiGateway:a}),g=h,_;if(e.validateAgentWithBuild){console.log("Build validation enabled, performing post-execution build validation");let E=await Ue({cliPath:r,config:e,context:s,initialResult:h,filter:i,runAgentCallback:async({errorContext:I})=>{let{prompt:m}=await K({config:{...e,prompt:h.result},buildErrorContext:I,netlify:s});return d.runner({config:{...e,prompt:m},netlify:s,persistSteps:l,aiGateway:a})}});console.log("Build validation completed:",E.buildValidation),g=E,_=E.buildValidation}let T={ok:!0},x=g.result;if(e.validateAgent&&g.result){let E=he(g.result);console.log("Validation result",E),E&&(T=E),x=_e(g.result)}T.ok||console.log("Validation failed",T);let{diff:b,resultDiff:C,previewInfo:R,diffBinary:S,resultDiffBinary:y}=await Ye({cliPath:r,config:e,context:s,result:x,buildValidation:_,filter:i});await je({config:e,diff:b,result:x,duration:g.duration,resultDiff:C,diffBinary:S,resultDiffBinary:y,previewInfo:R,cleanRunner:d.clean})};import w from"process";var Lt="codex",Bt=e=>(e??[]).filter(t=>t.request&&t.response),Ut=e=>(e??[]).filter(t=>t.site_context),Ge=()=>{let e=w.env.NETLIFY_AGENT_RUNNER_ID,t=w.env.NETLIFY_AGENT_RUNNER_SESSION_ID;if(!e||!t)throw new Error("ID of agent runner is not provided");let r=w.env.NETLIFY_AGENT_RUNNER_RESULT_BRANCH,o=w.env.NETLIFY_AGENT_RUNNER_PROMPT;if(!o)throw new Error("Prompt is not provided");let n=w.env.NETLIFY_AGENT_RUNNER_AGENT||Lt,i=w.env.NETLIFY_AGENT_RUNNER_MODEL,a=w.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED==="1",s=w.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED==="1",l=w.env.ERROR_LOGS_PATH,d=Q(w.env.NETLIFY_AGENT_RUNNER_CONTEXT),u=Bt(d),h=Ut(d),g=w.env.NETLIFY_AGENT_RUNNER_HAS_REPO!=="0",_=!w.env.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED,T=w.env.NETLIFY_AGENT_RUNNER_SHA,x=Ft();return{id:e,sessionId:t,resultBranch:r,prompt:o,runner:n,model:i,validateAgent:a,errorLogsPath:l,sessionHistoryContext:u,siteContext:h,hasRepo:g,useGateway:_,sha:T,accountType:x,validateAgentWithBuild:s}},Ft=()=>{let e=w.env.NETLIFY_TEAM_TYPE;return e?e.includes("starter")?D:e.includes("pro")?"pro":e.startsWith("business")?$:e.startsWith("enterprise")?L:e.startsWith("free")?B:k:k};var q=Yt(He.argv.slice(2),{string:["auth","cwd","cli-path","error-logs-path","filter"]});try{let e=Ge();await Me({config:e,apiToken:q.auth,cwd:q.cwd,cliPath:q["cli-path"],errorLogsPath:q["error-logs-path"],filter:q.filter})}catch(e){console.error("Error running agent pipeline:",e),He.exit(1)}
|
|
115
|
+
`)}};var fe=async({cliPath:e,config:t,context:n,buildErrors:o,runner:r,persistSteps:s,aiGateway:a})=>{let{prompt:i}=await Le({cliPath:e,config:t,buildErrorContext:Pt(o),netlify:n}),l={...t,prompt:i},c=await r({aiGateway:a,config:l,netlify:n,persistSteps:s});if(c.error)throw console.error("Runner failed",{stepsCount:c.steps.length,duration:c.duration,error:c.error}),new Error(c.error);return{runnerResult:c}},Pt=e=>{if(!e)return"";let t=[];return t.push("Deploy failed failed. Here are the build errors you need to fix:"),e.forEach((n,o)=>{t.push(`Build attempt ${o+1}: ${n}`)}),t.join(`
|
|
116
|
+
`)};import kt from"process";var Ue=async({netlify:e,hasRepo:t,skipBuild:n,message:o="Agent Preview",deploySubdomain:r,cliPath:s,filter:a})=>{try{let i=["deploy","--message",`"${o}"`,"--json","--draft"];t||(console.log("Deploy: Uploading source zip"),i.push("--upload-source-zip")),r&&i.push("--alias",r),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 c=await e.utils.run(l,i),u=JSON.parse(c.stdout.trim());console.log(`
|
|
117
|
+
Preview deploy created successfully:`,{deployId:u.deploy_id,deployUrl:u.deploy_url,siteId:u.site_id});let m={deployId:u.deploy_id,previewUrl:u.deploy_url,logsUrl:u.logs,siteId:u.site_id};return t||(m.sourceZipFilename=u.source_zip_filename),m}catch(i){throw console.error("Failed to create preview deploy via CLI:",i),i}};var me=async({cliPath:e,config:t,context:n,result:o,filter:r})=>{let s=await Ce({config:t,netlify:n});if(!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:i,diffBinary:l,resultDiffBinary:c}=s,u=!0;console.log("Preview deploy condition check:",{resultUndefined:o===void 0,resultType:typeof o,hasChanges:u,wouldCreatePreview:o!==void 0&&u});let m=null;if(o!==void 0&&u)try{let _;try{let d=await ye(t.id,t.sessionId);d?.title&&(_=d.title)}catch(d){console.warn("Failed to fetch session title, using fallback message:",d.message)}m=await Ue({cliPath:e,netlify:n,hasRepo:t.hasRepo,message:_,skipBuild:!1,deploySubdomain:Ie(t.id,kt.env.SITE_NAME),filter:r})}catch(_){return console.warn("Failed to create preview deploy (continuing with agent run):",_),{diff:a,resultDiff:i,hasChanges:u,previewInfo:null,diffBinary:l,resultDiffBinary:c,deployError:_ instanceof Error?_.message:String(_)}}return console.log("Git status",{hasDiff:!!a,hasChanges:u}),{diff:a,resultDiff:i,hasChanges:u,previewInfo:m,diffBinary:l,resultDiffBinary:c}};var je=async({config:e,diff:t,result:n,duration:o,resultDiff:r,diffBinary:s,resultDiffBinary:a,previewInfo:i,cleanRunner:l})=>{let c={result_diff:t,result:n||"Done",duration:o,result_diff_binary:s};return i&&i.deployId&&(c.deploy_id=i.deployId),i&&i.sourceZipFilename&&(c.result_zip_file_name=i.sourceZipFilename),r||a?(console.log("Updating total agent result diff"),await W(e.id,{result_diff:r,result_diff_binary:a})):console.log("No total result diff, not updating"),await l?.(),console.log("Updated agent runner with result"),await z(e.id,e.sessionId,c),{sessionUpdate:c}};import{getTracer as bt}from"@netlify/otel";var Dt=Ot(import.meta.url),Ft=Dt("../package.json"),he=3,Ye=async({config:e,apiToken:t,cliPath:n="netlify",cwd:o,errorLogsPath:r,filter:s})=>{await ge(Ft.version,e.id);let a=bt(),{aiGateway:i,context:l,persistSteps:c,runner:u,sha:m}=await be({config:e,apiToken:t,cliPath:n,cwd:o,errorLogsPath:r,filter:s});e.sha=m;let{runnerResult:_}=await fe({cliPath:n,config:e,context:l,runner:u.runner,persistSteps:c,aiGateway:i}),d=await me({cliPath:n,config:e,context:l,result:_.result,filter:s}),y=_,T=[];if(d.hasChanges&&d.deployError){console.log("Deploy validation enabled, starting deploy-fix iteration process"),T.push(d.deployError);let x=1;for(;x<=he&&!d.previewInfo;)await V(a,"stage-deploy",async A=>{A?.setAttributes({"stage.attempt":x});let{runnerResult:h}=await fe({cliPath:n,config:e,context:l,runner:u.runner,persistSteps:c,aiGateway:i});y={...h,steps:[...y.steps||[],...h.steps||[]],duration:(y.duration||0)+(h.duration||0)},d=await me({cliPath:n,config:e,context:l,result:h.result,filter:s}),d.deployError&&T.push(d.deployError),x++});x>he&&!d.previewInfo&&console.log(`Deploy validation failed after ${he} attempts`)}let{diff:P,resultDiff:v,previewInfo:C,diffBinary:w,resultDiffBinary:E}=d;await je({config:e,diff:P,result:y.result,duration:y.duration,resultDiff:v,diffBinary:w,resultDiffBinary:E,previewInfo:C,cleanRunner:u.clean})};import R from"process";var $t="codex",Lt=e=>(e??[]).filter(t=>t.request&&t.response),Ut=e=>(e??[]).filter(t=>t.site_context),Ge=()=>{let e=R.env.NETLIFY_AGENT_RUNNER_ID,t=R.env.NETLIFY_AGENT_RUNNER_SESSION_ID;if(!e||!t)throw new Error("ID of agent runner is not provided");let n=R.env.NETLIFY_AGENT_RUNNER_RESULT_BRANCH,o=R.env.NETLIFY_AGENT_RUNNER_PROMPT;if(!o)throw new Error("Prompt is not provided");let r=R.env.NETLIFY_AGENT_RUNNER_AGENT||$t,s=R.env.NETLIFY_AGENT_RUNNER_MODEL,a=R.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED==="1",i=R.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED==="1",l=R.env.ERROR_LOGS_PATH,c=Q(R.env.NETLIFY_AGENT_RUNNER_CONTEXT),u=Lt(c),m=Ut(c),_=R.env.NETLIFY_AGENT_RUNNER_HAS_REPO!=="0",d=!R.env.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED,y=R.env.NETLIFY_AGENT_RUNNER_SHA,T=jt();return{id:e,sessionId:t,resultBranch:n,prompt:o,runner:r,model:s,validateAgent:a,errorLogsPath:l,sessionHistoryContext:u,siteContext:m,hasRepo:_,useGateway:d,sha:y,accountType:T,validateAgentWithBuild:i}},jt=()=>{let e=R.env.NETLIFY_TEAM_TYPE;return e?e.includes("personal")?$:e.includes("pro")?"pro":e.startsWith("enterprise")?L:e.startsWith("free")?U:F:F};var K=Yt(Be.argv.slice(2),{string:["auth","cwd","cli-path","error-logs-path","filter"]});try{let e=Ge();await Ye({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),Be.exit(1)}
|
|
117
118
|
//# sourceMappingURL=bin.js.map
|
package/dist/index.js
CHANGED
|
@@ -1,23 +1,36 @@
|
|
|
1
|
-
import{createRequire as
|
|
1
|
+
import{createRequire as St}from"module";import{createTracerProvider as je}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as Ue}from"@netlify/otel/opentelemetry";import{withActiveSpan as Me}from"@netlify/otel";var fe=(e,t)=>je({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new Ue(new te)]});function q(e,t,n){return console.log(`\u23F3 TRACE: ${t} starting...`),Me(e,t,n)}var te=class{export(t,n){for(let o of t)this.logSpan(o);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,o=t.attributes,r=[];for(let[i,l]of Object.entries(o))i.includes("duration")&&typeof l=="number"?r.push(`${i}=${l.toFixed(2)}ms`):r.push(`${i}=${l}`);let s=t.status?.code===2?"\u274C":"\u2705",a=r.length>0?` [${r.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}`)}};import ee from"process";import{getTracer as pt}from"@netlify/otel";import K from"process";var oe=K.env.NETLIFY_API_URL,ne=K.env.NETLIFY_API_TOKEN,V=async(e,t={})=>{if(!oe||!ne)throw new Error("No API URL or token");let n=new URL(e,oe),o={...t,headers:{...t.headers,Authorization:`Bearer ${ne}`}};K.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let r=await fetch(n,o),s=r.ok&&r.status<=299;if(K.env.AGENT_RUNNERS_DEBUG==="true"&&(console.log(`[DEBUG] Response headers for ${n}:`),r.headers.forEach((i,l)=>{console.log(` ${l}: ${i}`)})),s||console.error(`Got status ${r.status} for request ${n}`),t.raw){if(!s)throw r;return r}let a=await(r.headers.get("content-type").includes("application/json")?r.json():r.text());if(!s)throw a;return a},me=e=>{console.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(oe=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(ne=e.constants.NETLIFY_API_TOKEN)},X=(e,t)=>V(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),J=(e,t,n)=>V(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:n});var he=(e,t)=>V(`/api/v1/agent_runners/${e}/sessions/${t}`),ge=(e,t,n)=>V(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":n}});var ye=async({netlify:e,config:t})=>{let n,o,r,s,a=e.constants?.SITE_ID;if(!a)throw new Error("No site id");let i=async()=>{clearTimeout(r),console.log("Requesting AI gateway information");let l=await ge(a,t.id,t.sessionId);if({token:n,url:s}=l,o=l.expires_at?l.expires_at*1e3:void 0,console.log("Got AI gateway information",{token:!!n,expiresAt:o,url:s}),o){let c=o-Date.now()-6e4;c>0&&(r=setTimeout(()=>{i()},c))}};return await i(),{get url(){return s},get token(){return n}}};import _e from"process";import{execa as Be,execaCommand as Gt}from"execa";var Ge={preferLocal:!0},xe=(e,t,n)=>{let[o,r]=Ye(t,n),s={...Ge,...r},a=Be(e,o,s);return He(a,s),a};var Ye=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},He=(e,t)=>{t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0||(e.stdout?.pipe(_e.stdout),e.stderr?.pipe(_e.stderr))};var qe=e=>new Promise(t=>{setTimeout(t,e)}),Te=(e,t=3e3)=>{let n=!1,o=null,r=[],s=null,a=(...i)=>{if(n)return o=i,new Promise(u=>{r.push(u)});n=!0;let l,c=new Promise(u=>{l=u});return s=(async()=>{await Promise.resolve();let u=await e(...i);for(l(u);;){if(await qe(t),!o)return n=!1,s=null,u;let m=o,y=r;o=null,r=[],u=await e(...m),y.forEach(f=>{f(u)})}})(),c};return a.flush=async()=>{if((n||o)&&s)return await s,a.flush()},a},W=(e,t,n=!1)=>{let o=null,r=null,s=null,a=function(...i){r=i,s=this;let l=n&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,n||(e.apply(s,r),r=null,s=null)},t),l&&(e.apply(s,r),r=null,s=null)};return a.cancel=()=>{clearTimeout(o),o=null,r=null,s=null},a.flush=()=>{if(o){clearTimeout(o);let i=r,l=s;o=null,r=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)}},we=(e,t)=>{let r=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let i=`--${t}${r}`;if(i.length>55)return"";let l=60-i.length;if(l<=0)return"";if(l>=s.length+6){let c=Math.min(l-s.length,e.length);return`${s}${e.slice(0,c)}`}return e.slice(0,l)};import{Buffer as Ie}from"buffer";var Ae=async({config:e,netlify:t})=>{let n=await Ve(t),{hasChanges:o}=n,{status:r}=n;if(!o)return{hasChanges:!1};let s=await Xe(t,r);await t.utils.run("git",["add",".",...s]);let i=(await t.utils.run("git",["diff","--staged"])).stdout;if(o=!!i,!o)return{hasChanges:!1};let c=(await t.utils.run("git",["diff","--staged","--binary"])).stdout,u,m;if(e.sha){await t.utils.run("git",["commit","-m","Agent runner"]),u=(await t.utils.run("git",["diff",e.sha,"HEAD"])).stdout;let T=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"])).stdout;u!==T&&(m=Ie.from(T).toString("base64"))}let y={hasChanges:!0,diff:i,resultDiff:u};return i!==c&&(y.diffBinary=Ie.from(c).toString("base64")),m&&(y.resultDiffBinary=m),y},Ke=["?? mise.toml",/\?\? .+?\.log/],Ve=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
|
|
2
|
+
`).filter(r=>!Ke.some(s=>s instanceof RegExp?s.test(r):r===s))).length!==0,status:t.stdout}};var Ce=async e=>{let{stdout:t}=await e.utils.run("git",["rev-parse","HEAD"]);return t.trim()},Ne=async e=>{let{stdout:t}=await e.utils.run("git",["rev-list","--max-parents=0","HEAD"]);return t.trim()},Xe=async(e,t="")=>{let n=[".netlify","mise.toml","node_modules"],o=[],r=n.map(async a=>{try{return await e.utils.run("git",["check-ignore","-v",a]),null}catch{return`:!${a}`}});return(await Promise.all(r)).forEach(a=>{a&&o.push(a)}),t.split(`
|
|
3
|
+
`).forEach(a=>{let i=a.match(/\?\? (.+?)\.log$/)?.[1];i&&o.push(`:!${i}.log`)}),o};import Je from"fs/promises";import We from"os";import Z from"path";import $ from"process";var z="netlify-agent-runner-context.md",re="task-history",se="netlify-context",b=".netlify",M="other",B="personal";var G="enterprise",Y="free";var ze=({catchError:e,runCmd:t,error:n,result:o,runnerName:r})=>(console.log(`${r} command completed with catch handler triggered`,{hadExistingError:!!n,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(console.log("Preserving existing result despite catch handler being triggered"),n?{error:n,result:o}:{error:"Process completed with errors but result was captured",result:o}):(console.log("Setting result to undefined because no valid result was captured"),{error:n||`${r} failed`,result:void 0}));async function ie({config:e,netlify:t,persistSteps:n,sendSteps:o,aiGateway:r}){let{accountType:s,prompt:a}=e,{model:i}=e;if(r){let{token:h,url:g}=r;if(!h||!g)throw new Error("No token or url provided from AI Gateway");let d=Ze[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}`);$.env.ANTHROPIC_API_KEY=h,$.env.ANTHROPIC_BASE_URL=g}else if(!$.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let l=[],c=[],u=[],m={},y=0,f=0,_,T,R=Z.join($.cwd(),"node_modules"),S=[Z.join($.env.NODE_PATH||R,".bin/claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...i?["--model",i]:[],"-p",a],N=`${$.env.NVM_BIN}/node`;console.log(`Running ${N} ${S.join(" ")}`);let w=t.utils.run(N,S,{all:!0,env:$.env});w.stdin?.end();let x=W(()=>{n?.({steps:l,duration:f}),o?.({steps:c,duration:f}),c=[]},250),E=(h,g)=>{h.id=y,y+=1,u.push(h),l.push(h),c.push(h),g||x.flush(),x(),g&&x.flush()},C="";return w.all.on("data",h=>{if(C+=h.toString(),!h.includes(`
|
|
4
|
+
`))return;let g=C.split(`
|
|
5
|
+
`).filter(Boolean).map(d=>{try{return JSON.parse(d)}catch{console.log("Could not parse line",d)}return null}).filter(Boolean);C="",g.forEach(d=>{Array.isArray(d?.message?.content)?d.message.content.forEach(p=>{switch(p.type){case"text":{p.text&&E({message:p.text});break}case"image":{typeof p.source=="object"&&p.source.type==="base64"&&p.source.media_type?E({message:``}):console.log(`Unsupported image type ${p.source?.type}`,p.source);break}case"tool_use":{if(p.name==="Task"){let I=p.input?.description&&`\`${p.input.description}\``;E({title:[p.name,I].filter(Boolean).join(" ")})}else m[p.id]=p;x.flush();break}case"tool_result":{let I=m[p.tool_use_id],k;if(I){let L=I.input?.file_path&&Z.relative($.cwd(),I.input.file_path),A=L&&`\`${L}\``;k=[I.name,A].filter(Boolean).join(" ")}let F=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(I?.name),O;if(typeof p.content=="string")O=p.content;else if(Array.isArray(p.content)){let L=[];p.content.forEach(A=>{A?.type==="text"&&typeof A.text=="string"?L.push(A.text):A?.type==="image"&&typeof A.source=="object"?A.source.type==="base64"&&A.source.media_type?L.push(``):console.log(`Unsupported image type ${A.source.type}`,A.source):console.log(`Unsupported block type ${A?.type}`)}),O=L.join(`
|
|
6
|
+
|
|
7
|
+
`)}F&&O&&(O=`\`\`\`
|
|
8
|
+
${O.trim()}
|
|
9
|
+
\`\`\``),E({title:k,message:O},!0);break}case"thinking":{p.thinking&&E({title:"Thinking",message:p.thinking},!0);break}default:console.log(`Message content type is not supported ${p.type}`,p)}}):d?.type==="result"&&(f=d.duration_ms,d.is_error?T=d.result:_=d.result,[u,l,c].forEach(p=>{p[p.length-1]?.message===_&&p.pop()}))})}),await w.catch(h=>{({error:T,result:_}=ze({catchError:h,runCmd:w,error:T,result:_,runnerName:"Claude"}))}),x.flush(),{steps:u,duration:f,result:_,error:T}}var Se=async()=>{let e=Z.join(We.homedir(),".claude");await Je.rm(e,{recursive:!0,force:!0})},Ze={[G]:{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}}},[B]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[Y]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}},[M]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}}};import Qe from"fs/promises";import et from"os";import ae from"path";import j from"process";var tt=({catchError:e,runCmd:t,error:n,result:o,runnerName:r})=>(console.log(`${r} command completed with catch handler triggered`,{hadExistingError:!!n,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(console.log("Preserving existing result despite catch handler being triggered"),n?{error:n,result:o}:{error:"Process completed with errors but result was captured",result:o}):(console.log("Setting result to undefined because no valid result was captured"),{error:n||`${r} failed`,result:void 0}));async function le({config:e,netlify:t,persistSteps:n,sendSteps:o,aiGateway:r}){let{accountType:s,prompt:a}=e,{model:i}=e;if(r){let{token:x,url:E}=r;if(!x||!E)throw new Error("No token or url provided from AI Gateway");let C=ot[s];if(!C)throw new Error(`Codex is not supported for the account type ${s}`);if(i&&!C?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);j.env.OPENAI_API_KEY=x,j.env.OPENAI_BASE_URL=E}else if(!j.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let l=[],c=[],u={},m=0,y=0,f,_,T=ae.join(j.cwd(),"node_modules"),R=[ae.join(j.env.NODE_PATH||T,".bin/codex"),"--approval-mode","full-auto",r?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...i?["--model",i]:[],"-q",a].filter(Boolean),S=`${j.env.NVM_BIN}/node`;console.log(`Running ${S} ${R.join(" ")}`);let N=t.utils.run(S,R,{all:!0,env:{...j.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),w="";return N.all.on("data",x=>{if(w+=x.toString(),!x.includes(`
|
|
10
|
+
`))return;let E=w.toString().split(`
|
|
11
|
+
`).filter(Boolean).map(g=>{try{return JSON.parse(g)}catch{console.log("Could not parse line",g)}return null}).filter(Boolean);w="";let C=[],h=!1;E.forEach(g=>{if(g?.duration_ms&&(y=g.duration_ms,h=!0),g?.type==="local_shell_call")u[g.call_id]=g;else if(g?.type==="local_shell_call_output"){let d=rt(u[g.call_id],g);d.id=m,m+=1,d&&(c.push(d),l.push(d),C.push(d),h=!0)}else g?.type==="message"&&g.role==="assistant"?f=g.content.map(d=>d.text).join(`
|
|
12
|
+
`):g?.type==="message"&&g.role==="system"&&(_=g.content.map(d=>d.text).join(`
|
|
13
|
+
`))}),h&&(n?.({steps:l,duration:y}),o?.({steps:C,duration:y}))}),await N.catch(x=>{({error:_,result:f}=tt({catchError:x,runCmd:N,error:_,result:f,runnerName:"Codex"}))}),{steps:c,duration:y,result:f,error:_}}var ve=async()=>{let e=ae.join(et.homedir(),".codex");await Qe.rm(e,{recursive:!0,force:!0})},ot={[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},o1:{maxTokens:1e5},"o1-mini":{maxTokens:65536},"o3-mini":{maxTokens:1e5},"gpt-image-1":{},"dall-e-2":{},"dall-e-3":{}}},[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}}},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}}},[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},"o3-mini":{maxTokens:16e3}}},[M]:{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}}}},nt=new Set(["bash","-lc"]),rt=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let n=e.action?.command?.filter(s=>!nt.has(s)),o=n?`Running \`${n.join(" ")}\``:void 0,r;try{r=JSON.parse(t.output).output?.trim(),r&&(r=`\`\`\`
|
|
14
|
+
${r.trim()}
|
|
15
|
+
\`\`\``)}catch(s){console.error("Could not decode outputMsg",s,t.output)}return{title:o,message:r}};import st from"fs/promises";import it from"os";import Q from"path";import D from"process";var at=({catchError:e,runCmd:t,error:n,result:o,runnerName:r})=>(console.log(`${r} command completed with catch handler triggered`,{hadExistingError:!!n,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(console.log("Preserving existing result despite catch handler being triggered"),n?{error:n,result:o}:{error:"Process completed with errors but result was captured",result:o}):(console.log("Setting result to undefined because no valid result was captured"),{error:n||`${r} failed`,result:void 0})),lt={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 ue({config:e,netlify:t,persistSteps:n,sendSteps:o,aiGateway:r}){let{accountType:s,prompt:a}=e,{model:i}=e;if(r){let{token:h,url:g}=r;if(!h||!g)throw new Error("No token or url provided from AI Gateway");let d=ut[s];if(!d)throw new Error(`Gemini is not supported for the account type ${s}`);if(i&&!d?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);D.env.GEMINI_API_KEY=h,D.env.GOOGLE_GEMINI_BASE_URL=g}else if(!D.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let l=[],c=[],u=[],m={},y=0,f=0,_,T,R=Q.join(D.cwd(),"node_modules"),S=[Q.join(D.env.NODE_PATH||R,".bin/gemini"),...i?["--model",i]:[],"--yolo","-p",a],N=`${D.env.NVM_BIN}/node`;console.log(`Running ${N} ${S.join(" ")}`);let w=t.utils.run(N,S,{all:!0,env:D.env});w.stdin?.end();let x=W(()=>{n?.({steps:l,duration:f}),o?.({steps:c,duration:f}),c=[]},250),E=(h,g)=>{h.id=y,y+=1,u.push(h),l.push(h),c.push(h),g||x.flush(),x(),g&&x.flush()},C="";return w.all.on("data",h=>{if(C+=h.toString(),!h.includes(`
|
|
16
|
+
`))return;let g=C.toString().split(`
|
|
17
|
+
`).filter(Boolean).map(d=>{try{if(d.startsWith("[API Error")){let p=d.match(/\[api error: (.+?)]$/i)?.[1];return{type:"error",value:Ee(p,!1)?.error?.message||p||"Gemini encountered error"}}return JSON.parse(d)}catch{}return null}).filter(Boolean);C="",g.forEach(d=>{switch(d.type){case"thought":{let p=d.value;E({title:p?.subject??"Thinking...",message:p?.description},!0);break}case"content":{d.value&&E({message:d.value});break}case"tool_call_request":{let p=d.value,I=lt[p.name]??p.name,k=p.args?.path||p.args?.absolute_path,F=k&&Q.relative(D.cwd(),k),O=p.args?.command,A={title:[I,F&&`\`${F}\``,O&&`\`${O}\``].filter(Boolean).join(" ")};m[p.callId]=A,x.flush();break}case"tool_result":{let p=d.value,I=m[p.callId];if(I){let k=[p.resultDisplay,p.responseParts?.functionResponse?.response?.output].find(F=>typeof F=="string"&&F);k&&(I.message=`\`\`\`
|
|
18
|
+
${k.trim()}
|
|
19
|
+
\`\`\``),E(I,!0)}break}case"result":{f=d.duration_ms,_=d.value,[u,l,c].forEach(p=>{p[p.length-1]?.message===_&&p.pop()});break}case"error":{T=d.value;break}case"finished":break;default:{console.warn("Unhandled message type:",d.type);break}}})}),await w.catch(h=>{({error:T,result:_}=at({catchError:h,runCmd:w,error:T,result:_,runnerName:"Gemini"}))}),x.flush(),{steps:u,duration:f,result:_,error:T}}var Re=async()=>{let e=Q.join(it.homedir(),".gemini");await st.rm(e,{recursive:!0,force:!0})},ut={[G]:{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}}},[B]:{models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[Y]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}},[M]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}}};var ct={codex:{runner:le,clean:ve},claude:{runner:ie,clean:Se},gemini:{runner:ue,clean:Re}},Pe=ct;var ke=async({config:e,apiThrottle:t,apiToken:n})=>{let o=pt();return q(o,"init-stage",async r=>{let s=performance.now();r?.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=Pe[e.runner];if(!a)throw r?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let i=dt({apiToken:n});me(i);let l=e.useGateway?await ye({netlify:i,config:e}):void 0;r?.setAttributes({"init.aiGateway.created":!!l}),e.validateAgent&&e.errorLogsPath&&r?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let c=Te(({steps:y=[],duration:f})=>{let _=[...y];return y.length=0,J(e.id,e.sessionId,{steps:_,duration:f})},t),u;e.hasRepo?e.sha?(u=e.sha,r?.setAttributes({"init.sha.source":"provided"})):(u=await Ce(i),await X(e.id,{sha:u}),r?.setAttributes({"init.sha.source":"current_commit"})):(u=await Ne(i),r?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let m=performance.now()-s;return r?.setAttributes({"init.sha":u||"unknown","init.duration.ms":m,"init.status":"success"}),{aiGateway:l,context:i,persistSteps:c,runner:a,sha:u}})},dt=({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:xe}});import ft from"crypto";import U from"fs/promises";import v from"path";import P from"process";var mt=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:P.env.NETLIFY_TEAM_ID,userId:P.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:P.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},ht=()=>{let e=Object.keys(P.env).sort();return{nodeVersion:P.version,envVars:e}},gt=10,yt=async e=>{let{name:t,ext:n}=v.parse(e),o=e,r=v.join(P.cwd(),b,o),s=0;for(;await _t(r);){if(s>=gt)throw new Error("Failed to generate context file");o=`${t}-${ft.randomUUID().slice(0,5)}${n}`,r=v.join(P.cwd(),b,o),s+=1}return o},_t=async e=>{try{return await U.access(e),!0}catch{return!1}},xt=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(o=>o&&typeof o=="object"&&o.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}},Tt=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 o=await n.text();return await U.writeFile(t,o,"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}},Et=async()=>{let e=await xt();if(!e)return[];let t=v.join(P.cwd(),b,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=v.join(t,i),c=v.join(b,se,i);return console.log(`Downloading ${a.scope} context...`),await Tt(a.endpoint,l)?(console.log(`Downloaded: ${c}`),{scope:a.scope,path:c,key:s}):null});return(await Promise.all(n)).filter(s=>s!==null)},Oe=async({cliPath:e,netlify:t,config:n})=>{let o=mt(t),r=ht(),s=await yt(z),a=v.join(P.cwd(),b);await U.mkdir(a,{recursive:!0});let i=v.join(b,s),l=v.join(P.cwd(),i),c=`# Agent Context
|
|
2
20
|
|
|
3
21
|
In Netlify documentation and interfaces, the terms "site" and "project" refer to the same thing.
|
|
4
22
|
|
|
5
23
|
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.
|
|
6
24
|
|
|
7
25
|
## Netlify Site
|
|
8
|
-
|
|
9
26
|
- Site ID: ${o.siteId}
|
|
10
27
|
- Account ID: ${o.accountId}
|
|
11
28
|
- User ID: ${o.userId}
|
|
12
29
|
- Site Slug: ${o.siteSlug}
|
|
13
30
|
- Netlify Functions directory: ${o.functionsDir}
|
|
31
|
+
- Running Node Version: ${r.nodeVersion}
|
|
14
32
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
- Node Version: ${n.nodeVersion}
|
|
18
|
-
|
|
19
|
-
### Available Environment Variables
|
|
20
|
-
${n.envVars.map(u=>`\`${u}\``).join(", ")}
|
|
33
|
+
The available environment variables are set globally (e.g. \`echo $VARIABLE_NAME\` can be used to check if a var is set).:
|
|
21
34
|
|
|
22
35
|
## Attachments
|
|
23
36
|
|
|
@@ -28,39 +41,49 @@ ${n.envVars.map(u=>`\`${u}\``).join(", ")}
|
|
|
28
41
|
'netlify-cli' npm package is already available as a global package.
|
|
29
42
|
Don't try to install it, in case you want to use it, use the global package.
|
|
30
43
|
|
|
31
|
-
|
|
44
|
+
`;n.siteContext&&n.siteContext.length!==0&&(c+=`
|
|
45
|
+
# Project Guidelines
|
|
46
|
+
<project_guidelines>
|
|
47
|
+
${n.siteContext.filter(m=>m.site_context).map(m=>typeof m.site_context=="string"?m.site_context:typeof m.site_context=="object"?JSON.stringify(m.site_context):"").join(`
|
|
48
|
+
|
|
49
|
+
`)}
|
|
50
|
+
</project_guidelines>
|
|
51
|
+
`);let u=await Et();if(u.length>0&&(c+=`
|
|
52
|
+
# Netlify Features Context
|
|
53
|
+
|
|
54
|
+
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.
|
|
55
|
+
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.
|
|
56
|
+
|
|
57
|
+
${u.map(m=>`- **${m.scope}**: ${m.path}`).join(`
|
|
58
|
+
`)}
|
|
32
59
|
|
|
60
|
+
Refer to these files when working with specific Netlify features.
|
|
61
|
+
`),c+=`
|
|
62
|
+
Additional Documentation Resources
|
|
33
63
|
- Netlify Docs: https://docs.netlify.com
|
|
34
64
|
- LLM Resources Index: https://docs.netlify.com/llms.txt
|
|
35
|
-
|
|
36
|
-
# Project Guidelines
|
|
65
|
+
`,n.sessionHistoryContext?.length){let m=v.join(P.cwd(),b,re);await U.mkdir(m,{recursive:!0});let y=await Promise.all(n.sessionHistoryContext.map(async(f,_)=>{let T=_+1,R=`attempt-${T}.md`,S=v.join(m,R),N=v.join(b,re,R),w=`# Task History - Attempt ${T}
|
|
37
66
|
|
|
38
|
-
|
|
67
|
+
## Request - what the user asked for
|
|
68
|
+
${f.request}
|
|
39
69
|
|
|
40
|
-
|
|
41
|
-
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## Response - what the agent replied with after its work
|
|
42
73
|
|
|
43
|
-
|
|
44
|
-
-
|
|
45
|
-
- <turn> groups a request and its response.
|
|
46
|
-
- <request> is the user request.
|
|
47
|
-
- <response> is the agent result.
|
|
74
|
+
${f.response}
|
|
75
|
+
`;return await U.writeFile(S,w,"utf-8"),console.log(`Created history file: ${N}`),N}));c+=`# History of prior work on this task
|
|
48
76
|
|
|
49
|
-
|
|
77
|
+
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.
|
|
50
78
|
|
|
51
|
-
|
|
52
|
-
${r.sessionHistoryContext.map((u,h)=>`<turn attempt="${h+1}">
|
|
53
|
-
<request>${u.request}</request>
|
|
54
|
-
<response>${u.response}</response>
|
|
55
|
-
</turn>`).join(`
|
|
79
|
+
${y.map(f=>`- ${f}`).join(`
|
|
56
80
|
`)}
|
|
57
|
-
|
|
58
|
-
`),await te.writeFile(l,d,"utf-8"),console.log(`Generated agent context document at: ${l}`),s},de=e=>`The build is currently failing after your previous changes.
|
|
81
|
+
`}return await U.writeFile(l,c,"utf-8"),console.log(`Generated agent context document at: ${l}`),i},be=e=>`The build is currently failing after your changes.
|
|
59
82
|
Your task is to analyze and fix the build errors.
|
|
60
83
|
Don't apply techniques of reverting changes. Apply fixes related to errors.
|
|
61
84
|
Don't try to run build by yourself. Just fix the errors.
|
|
62
85
|
|
|
63
|
-
${e}`;var
|
|
86
|
+
${e}`;var $e=(e={})=>`
|
|
64
87
|
Check for errors and validate the fix
|
|
65
88
|
|
|
66
89
|
${e.errorLogsPath?`Error Check Process:
|
|
@@ -84,33 +107,11 @@ ${e}`;var pe=(e={})=>`
|
|
|
84
107
|
VALIDATION_RESULT: PASS {"checks": ["error_logs"]}
|
|
85
108
|
or
|
|
86
109
|
VALIDATION_RESULT: FAIL {"checks": ["error_logs"], "errors": ["<errors>"]}
|
|
87
|
-
|
|
110
|
+
`;var wt=(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.`,It=async({cliPath:e,config:t,netlify:n})=>{let o=await Oe({cliPath:e,netlify:n,config:t});return{context:wt(o)}},At=({config:e})=>{let t=[];return e?.validateAgent&&t.push($e(e)),t},De=async({cliPath:e,config:t,netlify:n,buildErrorContext:o}={})=>{let{context:r}=await It({cliPath:e,config:t,netlify:n}),s;s=[...At({config:t})],o&&(s=[...s,be(o)]);let a=[];return r&&a.push(r),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(`
|
|
88
111
|
|
|
89
112
|
`)),{prompt:a.join(`
|
|
90
113
|
|
|
91
|
-
`)}};
|
|
92
|
-
`)
|
|
93
|
-
|
|
94
|
-
`))return;let f=E.split(`
|
|
95
|
-
`).filter(Boolean).map(p=>{try{return JSON.parse(p)}catch{console.log("Could not parse line",p)}return null}).filter(Boolean);E="",f.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.type==="base64"&&c.source.media_type?T({message:``}):console.log(`Unsupported image type ${c.source?.type}`,c.source);break}case"tool_use":{if(c.name==="Task"){let I=c.input?.description&&`\`${c.input.description}\``;T({title:[c.name,I].filter(Boolean).join(" ")})}else h[c.id]=c;x.flush();break}case"tool_result":{let I=h[c.tool_use_id],N;if(I){let D=I.input?.file_path&&W.relative(b.cwd(),I.input.file_path),S=D&&`\`${D}\``;N=[I.name,S].filter(Boolean).join(" ")}let $=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(I?.name),R;if(typeof c.content=="string")R=c.content;else if(Array.isArray(c.content)){let D=[];c.content.forEach(S=>{S?.type==="text"&&typeof S.text=="string"?D.push(S.text):S?.type==="image"&&typeof S.source=="object"?S.source.type==="base64"&&S.source.media_type?D.push(``):console.log(`Unsupported image type ${S.source.type}`,S.source):console.log(`Unsupported block type ${S?.type}`)}),R=D.join(`
|
|
96
|
-
|
|
97
|
-
`)}$&&R&&(R=`\`\`\`
|
|
98
|
-
${R.trim()}
|
|
99
|
-
\`\`\``),T({title:N,message:R},!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,p.is_error?w=p.result:y=p.result,[u,l,d].forEach(c=>{c[c.length-1]?.message===y&&c.pop()}))})}),await A.catch(m=>{({error:w,result:y}=ut({catchError:m,runCmd:A,error:w,result:y,runnerName:"Claude"}))}),x.flush(),{steps:u,duration:_,result:y,error:w}}var Re=async()=>{let e=W.join(lt.homedir(),".claude");await at.rm(e,{recursive:!0,force:!0})},ct={[U]:{default:"claude-3-7-sonnet-20250219",models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:64e3}}},[j]:{default:"claude-sonnet-4-20250514",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:{default:"claude-3-5-haiku-20241022",models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[M]:{default:"claude-3-7-sonnet-20250219",models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}},[F]:{default:"claude-3-7-sonnet-20250219",models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}},[L]:{default:"claude-3-7-sonnet-20250219",models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}}};import dt from"fs/promises";import pt from"os";import se from"path";import B from"process";var ft=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(console.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(console.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(console.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function ie({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:i,prompt:a}=e,{model:s}=e;if(n){let{token:x,url:T}=n;if(!x||!T)throw new Error("No token or url provided from AI Gateway");let E=mt[i];if(!E)throw new Error(`Codex is not supported for the account type ${i}`);if(s){if(!E?.models?.[s])throw new Error(`${s} is not supported for account type ${i}`)}else s=E.default;B.env.OPENAI_API_KEY=x,B.env.OPENAI_BASE_URL=T}else if(!B.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let l=[],d=[],u={},h=0,g=0,_,y,w=se.join(B.cwd(),"node_modules"),P=[se.join(B.env.NODE_PATH||w,".bin/codex"),"--approval-mode","full-auto",n?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...s?["--model",s]:[],"-q",a].filter(Boolean),v=`${B.env.NVM_BIN}/node`;console.log(`Running ${v} ${P.join(" ")}`);let C=t.utils.run(v,P,{all:!0,env:{...B.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),A="";return C.all.on("data",x=>{if(A+=x.toString(),!x.includes(`
|
|
100
|
-
`))return;let T=A.toString().split(`
|
|
101
|
-
`).filter(Boolean).map(f=>{try{return JSON.parse(f)}catch{console.log("Could not parse line",f)}return null}).filter(Boolean);A="";let E=[],m=!1;T.forEach(f=>{if(f?.duration_ms&&(g=f.duration_ms,m=!0),f?.type==="local_shell_call")u[f.call_id]=f;else if(f?.type==="local_shell_call_output"){let p=ht(u[f.call_id],f);p.id=h,h+=1,p&&(d.push(p),l.push(p),E.push(p),m=!0)}else f?.type==="message"&&f.role==="assistant"?_=f.content.map(p=>p.text).join(`
|
|
102
|
-
`):f?.type==="message"&&f.role==="system"&&(y=f.content.map(p=>p.text).join(`
|
|
103
|
-
`))}),m&&(r?.({steps:l,duration:g}),o?.({steps:E,duration:g}))}),await C.catch(x=>{({error:y,result:_}=ft({catchError:x,runCmd:C,error:y,result:_,runnerName:"Codex"}))}),{steps:d,duration:g,result:_,error:y}}var ke=async()=>{let e=se.join(pt.homedir(),".codex");await dt.rm(e,{recursive:!0,force:!0})},mt={[U]:{default:"codex-mini-latest",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:1e5}}},[j]:{default:"codex-mini-latest",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":{}}},pro:{default:"codex-mini-latest",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}}},[M]:{default:"codex-mini-latest",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}}},[F]:{default:"codex-mini-latest",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}}},[L]:{default:"codex-mini-latest",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}}}},gt=new Set(["bash","-lc"]),ht=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(i=>!gt.has(i)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
|
|
104
|
-
${n.trim()}
|
|
105
|
-
\`\`\``)}catch(i){console.error("Could not decode outputMsg",i,t.output)}return{title:o,message:n}};import _t from"fs/promises";import yt from"os";import Z from"path";import O from"process";var Tt=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(console.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(console.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(console.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} 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 ae({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:i,prompt:a}=e,{model:s}=e;if(n){let{token:m,url:f}=n;if(!m||!f)throw new Error("No token or url provided from AI Gateway");let p=Et[i];if(!p)throw new Error(`Gemini is not supported for the account type ${i}`);if(s){if(!p?.models?.[s])throw new Error(`${s} is not supported for account type ${i}`)}else s=p.default;O.env.GEMINI_API_KEY=m,O.env.GOOGLE_GEMINI_BASE_URL=f}else if(!O.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let l=[],d=[],u=[],h={},g=0,_=0,y,w,P=Z.join(O.cwd(),"node_modules"),v=[Z.join(O.env.NODE_PATH||P,".bin/gemini"),...s?["--model",s]:[],"--yolo","-p",a],C=`${O.env.NVM_BIN}/node`;console.log(`Running ${C} ${v.join(" ")}`);let A=t.utils.run(C,v,{all:!0,env:O.env});A.stdin?.end();let x=z(()=>{r?.({steps:l,duration:_}),o?.({steps:d,duration:_}),d=[]},250),T=(m,f)=>{m.id=g,g+=1,u.push(m),l.push(m),d.push(m),f||x.flush(),x(),f&&x.flush()},E="";return A.all.on("data",m=>{if(E+=m.toString(),!m.includes(`
|
|
106
|
-
`))return;let f=E.toString().split(`
|
|
107
|
-
`).filter(Boolean).map(p=>{try{if(p.startsWith("[API Error")){let c=p.match(/\[api error: (.+?)]$/i)?.[1];return{type:"error",value:Se(c,!1)?.error?.message||c||"Gemini encountered error"}}return JSON.parse(p)}catch{}return null}).filter(Boolean);E="",f.forEach(p=>{switch(p.type){case"thought":{let c=p.value;T({title:c?.subject??"Thinking...",message:c?.description},!0);break}case"content":{p.value&&T({message:p.value});break}case"tool_call_request":{let c=p.value,I=xt[c.name]??c.name,N=c.args?.path||c.args?.absolute_path,$=N&&Z.relative(O.cwd(),N),R=c.args?.command,S={title:[I,$&&`\`${$}\``,R&&`\`${R}\``].filter(Boolean).join(" ")};h[c.callId]=S,x.flush();break}case"tool_result":{let c=p.value,I=h[c.callId];if(I){let N=[c.resultDisplay,c.responseParts?.functionResponse?.response?.output].find($=>typeof $=="string"&&$);N&&(I.message=`\`\`\`
|
|
108
|
-
${N.trim()}
|
|
109
|
-
\`\`\``),T(I,!0)}break}case"result":{_=p.duration_ms,y=p.value,[u,l,d].forEach(c=>{c[c.length-1]?.message===y&&c.pop()});break}case"error":{w=p.value;break}case"finished":break;default:{console.warn("Unhandled message type:",p.type);break}}})}),await A.catch(m=>{({error:w,result:y}=Tt({catchError:m,runCmd:A,error:w,result:y,runnerName:"Gemini"}))}),x.flush(),{steps:u,duration:_,result:y,error:w}}var Pe=async()=>{let e=Z.join(yt.homedir(),".gemini");await _t.rm(e,{recursive:!0,force:!0})},Et={[U]:{default:"gemini-2.5-flash",models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:65536}}},[j]:{default:"gemini-2.5-pro",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:{default:"gemini-2.0-flash-lite",models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[M]:{default:"gemini-2.5-flash",models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}},[F]:{default:"gemini-2.5-flash",models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}},[L]:{default:"gemini-2.5-flash",models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}}};var It={codex:{runner:ie,clean:ke},claude:{runner:re,clean:Re},gemini:{runner:ae,clean:Pe}},be=It;var Oe=async({config:e,apiThrottle:t,apiToken:r})=>{let o=St();return ue(o,"init-stage",async n=>{let i=performance.now();n?.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=be[e.runner];if(!a)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let s=wt({apiToken:r});he(s);let l=e.useGateway?await Te({netlify:s,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!l}),e.validateAgent&&e.errorLogsPath&&n?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let d=Ie(({steps:g=[],duration:_})=>{let y=[...g];return g.length=0,J(e.id,e.sessionId,{steps:y,duration:_})},t),u;e.hasRepo?e.sha?(u=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(u=await ve(s),await X(e.id,{sha:u}),n?.setAttributes({"init.sha.source":"current_commit"})):(u=await Ne(s),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let h=performance.now()-i;return n?.setAttributes({"init.sha":u||"unknown","init.duration.ms":h,"init.status":"success"}),{aiGateway:l,context:s,persistSteps:d,runner:a,sha:u}})},wt=({apiToken:e})=>({constants:{NETLIFY_API_HOST:Q.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||Q.env.NETLIFY_API_TOKEN,SITE_ID:Q.env.SITE_ID,FUNCTIONS_DIST:Q.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:Ee}});var $e=async({cliPath:e,config:t,context:r,runner:o,persistSteps:n,aiGateway:i})=>{let{prompt:a}=await q({cliPath:e,config:t,netlify:r}),s={...t,prompt:a},l=await o({aiGateway:i,config:s,netlify:r,persistSteps:n});if(l.error)throw console.error("Runner failed",{stepsCount:l.steps.length,duration:l.duration,error:l.error}),new Error(l.error);return{runnerResult:l}};var De=async(e,t,r)=>{try{console.log("Running netlify build...");let o=["build","--context","deploy-preview"];r&&o.push("--filter",r);let n=await t.utils.run(e,o);return console.log("Build completed successfully"),{success:!0,stdout:n?.stdout||"",stderr:n?.stderr||""}}catch(o){return console.log("Build failed:",o.message),{success:!1,stdout:o.stdout||"",stderr:o.stderr||"",error:o.message}}},At=e=>{if(e.success)return"";let t=[];return e.error&&t.push(`Build Error: ${e.error}`),e.stderr&&t.push(`Build stderr:
|
|
110
|
-
${e.stderr}`),e.stdout&&t.push(`Build stdout:
|
|
111
|
-
${e.stdout}`),t.join(`
|
|
112
|
-
|
|
113
|
-
`)},Ct=e=>{let t=[];return t.push("Build validation failed. Here are the build errors you need to fix:"),e.forEach((r,o)=>{t.push(`Build attempt ${o+1}: ${At(r)}`)}),t.join(`
|
|
114
|
-
`)},Be=async({cliPath:e,context:t,initialResult:r,runAgentCallback:o,filter:n})=>{console.log("Starting post-execution build validation");let i=await De(e,t,n);if(i.success)return console.log("Build validation passed"),{...r,buildValidation:{attempts:0,finalBuildSuccess:!0,buildHistory:[i]}};console.log("Build validation failed, starting build-fix iteration process");let a=[i],s=[],l=0,d=r;for(let u=1;u<=3;u++){console.log(`Build fix attempt ${u}/3`);let h=Ct(a);console.log("Running agent to fix build errors"),d=await o({errorContext:h}),s=[...s,...d.steps||[]],l+=d.duration||0;let g=await De(e,t,n);if(a.push(g),g.success)return console.log(`Build fixed after ${u} attempts`),{...d,steps:s,duration:l,buildValidation:{attempts:u,finalBuildSuccess:!0,buildHistory:a}};console.log(`Build still failing after attempt ${u}`)}return console.log("Build validation failed after 3 attempts"),{...d,steps:s,duration:l,buildValidation:{attempts:3,finalBuildSuccess:!1,buildHistory:a,error:"Build validation failed - unable to fix build errors after 3 attempts"}}};import vt from"process";var Le=async({netlify:e,hasRepo:t,skipBuild:r,message:o="Agent Preview",deploySubdomain:n,cliPath:i,filter:a})=>{try{let s=["deploy","--message",`"${o}"`,"--json","--draft"];t||(console.log("Deploy: Uploading source zip"),s.push("--upload-source-zip")),n&&s.push("--alias",n),a&&s.push("--filter",a),r?(console.log("Deploy: Skipping build"),s.push("--no-build")):s.push("--context","deploy-preview");let l=i||"netlify";console.log(`Running: ${l} ${s.join(" ")}`);let d=await e.utils.run(l,s),u=JSON.parse(d.stdout.trim());console.log(`
|
|
115
|
-
Preview deploy created successfully:`,{deployId:u.deploy_id,deployUrl:u.deploy_url,siteId:u.site_id});let h={deployId:u.deploy_id,previewUrl:u.deploy_url,logsUrl:u.logs,siteId:u.site_id};return t||(h.sourceZipFilename=u.source_zip_filename),h}catch(s){throw console.error("Failed to create preview deploy via CLI:",s),s}};var Fe=async({cliPath:e,config:t,context:r,result:o,buildValidation:n,filter:i})=>{let{diff:a,resultDiff:s,hasChanges:l,diffBinary:d,resultDiffBinary:u}=await Ce({config:t,netlify:r});console.log("Preview deploy condition check:",{resultUndefined:o===void 0,resultType:typeof o,hasChanges:l,wouldCreatePreview:o!==void 0&&l});let h=null;if(o!==void 0&&l)try{let g;try{let _=await _e(t.id,t.sessionId);_?.title&&(g=_.title)}catch(_){console.warn("Failed to fetch session title, using fallback message:",_.message)}h=await Le({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:g,skipBuild:n?.finalBuildSuccess,deploySubdomain:we(t.id,vt.env.SITE_NAME),filter:i})}catch(g){console.warn("Failed to create preview deploy (continuing with agent run):",g)}return console.log("Git status",{hasDiff:!!a,hasChanges:l}),{diff:a,resultDiff:s,hasChanges:l,previewInfo:h,diffBinary:d,resultDiffBinary:u}};var Ue=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:i,resultDiffBinary:a,previewInfo:s,cleanRunner:l})=>{let d={result_diff:t,result:r||"Done",duration:o,result_diff_binary:i};return s&&s.deployId&&(d.deploy_id=s.deployId),s&&s.sourceZipFilename&&(d.result_zip_file_name=s.sourceZipFilename),n||a?(console.log("Updating total agent result diff"),await X(e.id,{result_diff:n,result_diff_binary:a})):console.log("No total result diff, not updating"),await l?.(),console.log("Updated agent runner with result"),await J(e.id,e.sessionId,d),{sessionUpdate:d}};var Rt=Nt(import.meta.url),kt=Rt("../package.json"),ln=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:i})=>{await le(kt.version,e.id);let{aiGateway:a,context:s,persistSteps:l,runner:d,sha:u}=await Oe({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:i});e.sha=u;let{runnerResult:h}=await $e({cliPath:r,config:e,context:s,runner:d.runner,persistSteps:l,aiGateway:a}),g=h,_;if(e.validateAgentWithBuild){console.log("Build validation enabled, performing post-execution build validation");let T=await Be({cliPath:r,config:e,context:s,initialResult:h,filter:i,runAgentCallback:async({errorContext:E})=>{let{prompt:m}=await q({config:{...e,prompt:h.result},buildErrorContext:E,netlify:s});return d.runner({config:{...e,prompt:m},netlify:s,persistSteps:l,aiGateway:a})}});console.log("Build validation completed:",T.buildValidation),g=T,_=T.buildValidation}let y={ok:!0},w=g.result;if(e.validateAgent&&g.result){let T=fe(g.result);console.log("Validation result",T),T&&(y=T),w=me(g.result)}y.ok||console.log("Validation failed",y);let{diff:P,resultDiff:v,previewInfo:C,diffBinary:A,resultDiffBinary:x}=await Fe({cliPath:r,config:e,context:s,result:w,buildValidation:_,filter:i});await Ue({config:e,diff:P,result:w,duration:g.duration,resultDiff:v,diffBinary:A,resultDiffBinary:x,previewInfo:C,cleanRunner:d.clean})};export{ln as runPipeline};
|
|
114
|
+
`)}};var ce=async({cliPath:e,config:t,context:n,buildErrors:o,runner:r,persistSteps:s,aiGateway:a})=>{let{prompt:i}=await De({cliPath:e,config:t,buildErrorContext:Ct(o),netlify:n}),l={...t,prompt:i},c=await r({aiGateway:a,config:l,netlify:n,persistSteps:s});if(c.error)throw console.error("Runner failed",{stepsCount:c.steps.length,duration:c.duration,error:c.error}),new Error(c.error);return{runnerResult:c}},Ct=e=>{if(!e)return"";let t=[];return t.push("Deploy failed failed. Here are the build errors you need to fix:"),e.forEach((n,o)=>{t.push(`Build attempt ${o+1}: ${n}`)}),t.join(`
|
|
115
|
+
`)};import Nt from"process";var Fe=async({netlify:e,hasRepo:t,skipBuild:n,message:o="Agent Preview",deploySubdomain:r,cliPath:s,filter:a})=>{try{let i=["deploy","--message",`"${o}"`,"--json","--draft"];t||(console.log("Deploy: Uploading source zip"),i.push("--upload-source-zip")),r&&i.push("--alias",r),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 c=await e.utils.run(l,i),u=JSON.parse(c.stdout.trim());console.log(`
|
|
116
|
+
Preview deploy created successfully:`,{deployId:u.deploy_id,deployUrl:u.deploy_url,siteId:u.site_id});let m={deployId:u.deploy_id,previewUrl:u.deploy_url,logsUrl:u.logs,siteId:u.site_id};return t||(m.sourceZipFilename=u.source_zip_filename),m}catch(i){throw console.error("Failed to create preview deploy via CLI:",i),i}};var pe=async({cliPath:e,config:t,context:n,result:o,filter:r})=>{let s=await Ae({config:t,netlify:n});if(!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:i,diffBinary:l,resultDiffBinary:c}=s,u=!0;console.log("Preview deploy condition check:",{resultUndefined:o===void 0,resultType:typeof o,hasChanges:u,wouldCreatePreview:o!==void 0&&u});let m=null;if(o!==void 0&&u)try{let y;try{let f=await he(t.id,t.sessionId);f?.title&&(y=f.title)}catch(f){console.warn("Failed to fetch session title, using fallback message:",f.message)}m=await Fe({cliPath:e,netlify:n,hasRepo:t.hasRepo,message:y,skipBuild:!1,deploySubdomain:we(t.id,Nt.env.SITE_NAME),filter:r})}catch(y){return console.warn("Failed to create preview deploy (continuing with agent run):",y),{diff:a,resultDiff:i,hasChanges:u,previewInfo:null,diffBinary:l,resultDiffBinary:c,deployError:y instanceof Error?y.message:String(y)}}return console.log("Git status",{hasDiff:!!a,hasChanges:u}),{diff:a,resultDiff:i,hasChanges:u,previewInfo:m,diffBinary:l,resultDiffBinary:c}};var Le=async({config:e,diff:t,result:n,duration:o,resultDiff:r,diffBinary:s,resultDiffBinary:a,previewInfo:i,cleanRunner:l})=>{let c={result_diff:t,result:n||"Done",duration:o,result_diff_binary:s};return i&&i.deployId&&(c.deploy_id=i.deployId),i&&i.sourceZipFilename&&(c.result_zip_file_name=i.sourceZipFilename),r||a?(console.log("Updating total agent result diff"),await X(e.id,{result_diff:r,result_diff_binary:a})):console.log("No total result diff, not updating"),await l?.(),console.log("Updated agent runner with result"),await J(e.id,e.sessionId,c),{sessionUpdate:c}};import{getTracer as vt}from"@netlify/otel";var Rt=St(import.meta.url),Pt=Rt("../package.json"),de=3,rn=async({config:e,apiToken:t,cliPath:n="netlify",cwd:o,errorLogsPath:r,filter:s})=>{await fe(Pt.version,e.id);let a=vt(),{aiGateway:i,context:l,persistSteps:c,runner:u,sha:m}=await ke({config:e,apiToken:t,cliPath:n,cwd:o,errorLogsPath:r,filter:s});e.sha=m;let{runnerResult:y}=await ce({cliPath:n,config:e,context:l,runner:u.runner,persistSteps:c,aiGateway:i}),f=await pe({cliPath:n,config:e,context:l,result:y.result,filter:s}),_=y,T=[];if(f.hasChanges&&f.deployError){console.log("Deploy validation enabled, starting deploy-fix iteration process"),T.push(f.deployError);let E=1;for(;E<=de&&!f.previewInfo;)await q(a,"stage-deploy",async C=>{C?.setAttributes({"stage.attempt":E});let{runnerResult:h}=await ce({cliPath:n,config:e,context:l,runner:u.runner,persistSteps:c,aiGateway:i});_={...h,steps:[..._.steps||[],...h.steps||[]],duration:(_.duration||0)+(h.duration||0)},f=await pe({cliPath:n,config:e,context:l,result:h.result,filter:s}),f.deployError&&T.push(f.deployError),E++});E>de&&!f.previewInfo&&console.log(`Deploy validation failed after ${de} attempts`)}let{diff:R,resultDiff:S,previewInfo:N,diffBinary:w,resultDiffBinary:x}=f;await Le({config:e,diff:R,result:_.result,duration:_.duration,resultDiff:S,diffBinary:w,resultDiffBinary:x,previewInfo:N,cleanRunner:u.clean})};export{rn as runPipeline};
|
|
116
117
|
//# sourceMappingURL=index.js.map
|