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