@netlify/agent-runner-cli 1.30.0 → 1.31.0-alpha
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 +15 -15
- package/dist/index.js +15 -15
- package/package.json +2 -2
package/dist/bin.js
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import De from"process";import
|
|
3
|
-
`),r=[],n=-1,o=0;for(;o<t.length;){let l=t[o].slice(0,500).toLowerCase();if(
|
|
2
|
+
import De from"process";import Cr from"minimist";import{createRequire as yr}from"module";import{createTracerProvider as Nt}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as Fe}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as Ct}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as At}from"@netlify/otel";import{OTLPTraceExporter as St}from"@opentelemetry/exporter-trace-otlp-grpc";function _(e){let t=!process.env.VITEST;return{log:(...r)=>{t&&console.log(`[AR]-[${e}]`,...r)},error:(...r)=>{t&&console.error(`[AR]-[${e}]`,...r)},warn:(...r)=>{t&&console.warn(`[AR]-[${e}]`,...r)},info:(...r)=>{t&&console.info(`[AR]-[${e}]`,...r)},debug:(...r)=>{t&&console.debug(`[AR]-[${e}]`,...r)}}}var xe=_("tracing"),Ue=(e,t,r)=>Nt({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new Fe(new Re),new Fe(new St({url:r}))],instrumentations:[new Ct({skipHeaders:!0})]});function le(e,t,r){return xe.log(`\u23F3 TRACE: ${t} starting...`),At(e,t,r)}var Re=class{export(t,r){for(let n of t)this.logSpan(n);r({code:1})}async shutdown(){}forceFlush(){return Promise.resolve()}logSpan(t){let r=(t.endTime[0]-t.startTime[0])*1e3+(t.endTime[1]-t.startTime[1])/1e6,n=t.attributes,o=[];for(let[l,i]of Object.entries(n))l.includes("duration")&&typeof i=="number"?o.push(`${l}=${i.toFixed(2)}ms`):o.push(`${l}=${i}`);let s=t.status?.code===2?"\u274C":"\u2705",a=o.length>0?` [${o.join(", ")}]`:"";xe.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${a}`),t.status?.code===2&&t.status.message&&xe.log(` \u274C Error: ${t.status.message}`)}};var Pt=["error","failed","exception","fatal","panic","abort","crash"];function Me(e){let t=e.split(`
|
|
3
|
+
`),r=[],n=-1,o=0;for(;o<t.length;){let l=t[o].slice(0,500).toLowerCase();if(Pt.some(d=>l.includes(d))){let d=Math.max(0,o-10,n+1),c=Math.min(t.length-1,o+20),p=[];for(let h=d;h<=c;h++)p.push(t[h]);r.push(p.join(`
|
|
4
4
|
`)),n=c,o=c+1}else o++}if(r.length===0)return e;let s=r.map((a,l)=>`<extracted_error_chunk order="${l+1}">
|
|
5
5
|
${a}
|
|
6
6
|
</extracted_error_chunk>`).join(`
|
|
7
7
|
|
|
8
|
-
`);return s.length>e.length*.8?e:s}import he from"process";import{getTracer as
|
|
9
|
-
`).filter(o=>!
|
|
10
|
-
`).forEach(a=>{let l=a.match(/\?\? (.+?)\.log$/)?.[1];l&&n.push(`:!${l}.log`)}),n};import
|
|
8
|
+
`);return s.length>e.length*.8?e:s}import he from"process";import{getTracer as ir}from"@netlify/otel";import ue from"process";var we=ue.env.NETLIFY_API_URL,Ie=ue.env.NETLIFY_API_TOKEN,re=_("api"),ce=async(e,t={})=>{if(!we||!Ie)throw new Error("No API URL or token");let r=new URL(e,we),n={...t,headers:{...t.headers,Authorization:`Bearer ${Ie}`}};ue.env.AGENT_RUNNERS_DEBUG==="true"&&(n.headers["x-nf-debug-logging"]="true"),t.json&&(n.headers||={},n.headers["Content-Type"]="application/json",n.body=JSON.stringify(t.json));let o=await fetch(r,n),s=o.ok&&o.status<=299;if(ue.env.AGENT_RUNNERS_DEBUG==="true")re.log(`Response headers for ${r}:`),o.headers.forEach((l,i)=>{re.log(` ${i}: ${l}`)});else{let l=o.headers.get("x-request-id")||o.headers.get("x-nf-request-id");re.log(`Request ID for ${r}: ${l||"N/A"}`)}if(s||re.error(`Got status ${o.status} for request ${r}`),t.raw){if(!s)throw o;return o}let a=await(o.headers.get("content-type")?.includes("application/json")?o.json():o.text());if(!s)throw a;return a},Ge=e=>{re.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(we=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Ie=e.constants.NETLIFY_API_TOKEN)},pe=(e,t)=>ce(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),J=(e,t,r)=>ce(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var je=(e,t)=>ce(`/api/v1/agent_runners/${e}/sessions/${t}`),Ye=(e,t,r)=>ce(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}});var Be=_("ai_gateway"),He=async({netlify:e,config:t})=>{let r,n,o,s,a=e.constants?.SITE_ID;if(!a)throw new Error("No site id");let l=async()=>{clearTimeout(o),Be.log("Requesting AI gateway information");let i=await Ye(a,t.id,t.sessionId);if({token:r,url:s}=i,n=i.expires_at?i.expires_at*1e3:void 0,Be.log("Got AI gateway information",{token:!!r,expiresAt:n,url:s}),n){let d=n-Date.now()-6e4;d>0&&(o=setTimeout(()=>{l()},d))}};return await l(),{get url(){return s},get token(){return r}}};import oe from"process";import{execa as Lt,execaCommand as Kr}from"execa";import{Transform as vt}from"stream";var Ot=["NODE_ENV","PATH","HOME","USER","USERNAME","SHELL","PWD","OLDPWD","TMPDIR","TMP","TEMP","LANG","TERM","EDITOR","PAGER","OS","PROCESSOR_ARCHITECTURE","PROCESSOR_IDENTIFIER","SYSTEMROOT","WINDIR","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","APPDATA","LOCALAPPDATA","NODE_OPTIONS","NODE_PATH","NODE_DEBUG","NODE_NO_WARNINGS","npm_config_registry","npm_config_cache","npm_execpath","npm_node_execpath","CI","GITHUB_ACTIONS","GITHUB_WORKSPACE","GITHUB_REPOSITORY","GITHUB_REF","BUILDKITE","BUILDKITE_BRANCH","BUILDKITE_COMMIT","BUILDKITE_BUILD_NUMBER","JENKINS_URL","TRAVIS","CIRCLECI","DISPLAY","COLORTERM","TERM_PROGRAM","TERM_PROGRAM_VERSION","COLUMNS","LINES","HISTSIZE","HISTFILE"];function kt(){return Object.entries(process.env).filter(([e,t])=>!(!t||Ot.includes(e)||t.length<5)).map(([,e])=>e).filter(Boolean)}function Ne(e){if(typeof e!="string")return e;let t=kt();if(t.length===0)return e;let r=e;return t.forEach(n=>{let o=new RegExp(bt(n),"g");r=r.replace(o,"******")}),r}function bt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ne=class extends vt{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,n){let o=t.toString(),s=Ne(o);n(null,s)}};function qe(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(n,o,s){let a=typeof n=="string"?Ne(n):n;return typeof o=="function"?t(a,o):t(a,o,s)},process.stderr.write=function(n,o,s){let a=typeof n=="string"?Ne(n):n;return typeof o=="function"?r(a,o):r(a,o,s)}}var Xr=_("shell"),$t={preferLocal:!0},Ve=(e,t,r)=>{let[n,o]=Dt(t,r),s={...$t,...o},a=Lt(e,n,s);return Ft(a,s),a};var Dt=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Ft=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(oe.env.NETLIFY_MASK_LOGS!=="false"){e.stdout?.pipe(new ne).pipe(oe.stdout),e.stderr?.pipe(new ne).pipe(oe.stderr);return}e.stdout?.pipe(oe.stdout),e.stderr?.pipe(oe.stderr)};var Ke="netlify-agent-runner-context.md",Ce="task-history",Ae="netlify-context",L=".netlify",se="results.md",Se="assets",U="other",M="personal";var G="enterprise",j="free",We=[M,"pro",G,j];var Je=_("utils"),Ut=e=>new Promise(t=>{setTimeout(t,e)}),Xe=(e,t=3e3)=>{let r=!1,n=null,o=[],s=null,a=(...l)=>{if(r)return n=l,new Promise(c=>{o.push(c)});r=!0;let i,d=new Promise(c=>{i=c});return s=(async()=>{await Promise.resolve();let c=await e(...l);for(i(c);;){if(await Ut(t),!n)return r=!1,s=null,c;let p=n,h=o;n=null,o=[],c=await e(...p),h.forEach(E=>{E(c)})}})(),d};return a.flush=async()=>{if((r||n)&&s)return await s,a.flush()},a},de=(e,t,r=!1)=>{let n=null,o=null,s=null,a=function(...l){o=l,s=this;let i=r&&!n;clearTimeout(n),n=setTimeout(()=>{n=null,r||(e.apply(s,o),o=null,s=null)},t),i&&(e.apply(s,o),o=null,s=null)};return a.cancel=()=>{clearTimeout(n),n=null,o=null,s=null},a.flush=()=>{if(n){clearTimeout(n);let l=o,i=s;n=null,o=null,s=null,e.apply(i,l)}},a},fe=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(n){t&&(r?.error?r.error("Could not parse JSON",n):Je.error("Could not parse JSON",n))}},ze=(e,t)=>{let o=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let l=`--${t}${o}`;if(l.length>55)return"";let i=60-l.length;if(i<=0)return"";if(i>=s.length+6){let d=Math.min(i-s.length,e.length);return`${s}${e.slice(0,d)}`}return e.slice(0,i)},Mt=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!We.some(t=>t in e),Ze=()=>{let e={},t={codex:process.env.NETLIFY_FF_AGENT_RUNNER_CODEX_VERSION,claude:process.env.NETLIFY_FF_AGENT_RUNNER_CLAUDE_VERSION,gemini:process.env.NETLIFY_FF_AGENT_RUNNER_GEMINI_VERSION};return Object.entries(t).forEach(([r,n])=>{if(n){let o=`NETLIFY_FF_AGENT_RUNNER_${r.toUpperCase()}_VERSION`;try{let s=JSON.parse(n);Mt(s)&&(e[r]=s)}catch(s){let l=s instanceof SyntaxError?"Invalid JSON":s.message;Je.error(`Could not parse ${r} model version override from ${o}: ${l}`)}}}),e};import{Buffer as Qe}from"buffer";var et=async({config:e,netlify:t})=>{let r=await jt(t),{hasChanges:n}=r,{status:o}=r;if(!n)return{hasChanges:!1};let s=await Yt(t,o);await t.utils.run("git",["add",".",...s]);let a={stdio:["ignore","pipe","pipe"]},i=(await t.utils.run("git",["diff","--staged"],a)).stdout;if(n=!!i,!n)return{hasChanges:!1};let c=(await t.utils.run("git",["diff","--staged","--binary"],a)).stdout,p,h;if(e.sha){await t.utils.run("git",["commit","-m","Agent runner"]),p=(await t.utils.run("git",["diff",e.sha,"HEAD"],a)).stdout;let m=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;p!==m&&(h=Qe.from(m).toString("base64"))}let E={hasChanges:!0,diff:i,resultDiff:p};return i!==c&&(E.diffBinary=Qe.from(c).toString("base64")),h&&(E.resultDiffBinary=h),E},Gt=["?? mise.toml","?? deno.lock",/\?\? .+?\.log/],jt=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
|
|
9
|
+
`).filter(o=>!Gt.some(s=>s instanceof RegExp?s.test(o):o===s))).length!==0,status:t.stdout}};var tt=async e=>{let{stdout:t}=await e.utils.run("git",["rev-parse","HEAD"]);return t.trim()},rt=async e=>{let{stdout:t}=await e.utils.run("git",["rev-list","--max-parents=0","HEAD"]);return t.trim()},Yt=async(e,t="")=>{let r=[".netlify","mise.toml","deno.lock","node_modules"],n=[],o=r.map(async a=>{try{return await e.utils.run("git",["check-ignore","-v",a]),null}catch{return`:!${a}`}});return(await Promise.all(o)).forEach(a=>{a&&n.push(a)}),t.split(`
|
|
10
|
+
`).forEach(a=>{let l=a.match(/\?\? (.+?)\.log$/)?.[1];l&&n.push(`:!${l}.log`)}),n};import Ht from"fs/promises";import qt from"os";import me from"path";import H from"process";import Pe from"path";import Bt from"fs/promises";var ve=_("agent-output-utils");async function X({initialResult:e,agentName:t,hasError:r}){let n="",o=Pe.join(process.cwd(),L,se);try{let s=await Bt.readFile(o,"utf-8");s&&(n=s,ve.log(`Pulled result from ${Pe.relative(process.cwd(),o)}`))}catch{ve.log(`No results file found at ${Pe.relative(process.cwd(),o)}`)}return n||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function z({error:e,agentName:t}){let r=e&&typeof e=="object"?JSON.stringify(e):e,n=r?.replace(/\s+/g," ").trim()||"",o="";return n?.includes("ai gateway is not available for your account")?o="AI Gateway is currently not available on your account. Please confirm your account meets the criteria for using Agent Runners and AI Gateway and that your account has remaining AI Gateway inference credits available. Reach out to Netlify support if this is unexpected.":n?.includes("error when talking to gemini api")?o="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":(n?.includes("connection closed prematurely while waiting for the model")||n?.includes("499")&&t.toLowerCase().includes("gemini"))&&(o="The agent's models were currently overloaded. Please try again or use a different available agent."),o&&ve.log(`Providing updated error messsage: ${o}, replacing original error: ${r}`),o||r||void 0}function Z(e){if(!e)return!1;let r=(e&&typeof e=="object"?JSON.stringify(e):e)?.replace(/\s+/g," ").trim()||"";return!!(r?.includes("error when talking to gemini api")||r?.includes("connection closed prematurely while waiting for the model"))}var Y=_("runner_claude"),nt="Claude Code",Vt=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(Y.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(Y.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(Y.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0}));async function Oe({config:e,netlify:t,persistSteps:r,aiGateway:n}){let o=e,{accountType:s,prompt:a,modelVersionOverrides:l}=o,{model:i}=o;if(n){let{token:w,url:g}=n;if(!w||!g)throw new Error("No token or url provided from AI Gateway");let f=Kt[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}`);if(l?.claude){let u=l?.claude?.[s];u&&(i=u)}H.env.ANTHROPIC_API_KEY=w,H.env.ANTHROPIC_BASE_URL=g}else if(!H.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let d=[],c=[],p={},h=0,E=0,x,T,m=me.join(H.cwd(),"node_modules"),N=[me.join(H.env.NODE_PATH||m,".bin/claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...i?["--model",i]:[],"-p",a],C=`${H.env.NVM_BIN}/node`;Y.log(`Running ${C} ${N.join(" ")}`);let P=t.utils.run(C,N,{all:!0,env:H.env});P.stdin?.end();let I=de(()=>{r?.({steps:d,duration:E})},250),R=(w,g)=>{let f={...w,id:h};h+=1,c.push(f),d.push(f),g||I.flush(),I(),g&&I.flush()},A="";return P.all?.on("data",w=>{if(A+=w.toString(),!w.includes(`
|
|
11
11
|
`))return;let g=A.split(`
|
|
12
12
|
`).filter(Boolean).map(f=>{try{return JSON.parse(f)}catch{Y.log("Could not parse line",f)}return null}).filter(Boolean);A="",g.forEach(f=>{Array.isArray(f?.message?.content)?f.message.content.forEach(u=>{switch(u.type){case"text":{u.text&&R({message:u.text});break}case"image":{typeof u.source=="object"&&u.source&&u.source.type==="base64"&&u.source.media_type?R({message:``}):Y.log(`Unsupported image type ${u.source?.type}`,u.source);break}case"tool_use":{if(u.name==="Task"){let y=u.input?.description&&`\`${u.input.description}\``;R({title:[u.name,y].filter(Boolean).join(" ")})}else u.id&&(p[u.id]=u);I.flush();break}case"tool_result":{let y=u.tool_use_id?p[u.tool_use_id]:void 0,D;if(y){let F=y.input?.file_path&&me.relative(H.cwd(),y.input.file_path),S=F&&`\`${F}\``;D=[y.name,S].filter(Boolean).join(" ")}let B=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(y?.name||""),b;if(typeof u.content=="string")b=u.content;else if(Array.isArray(u.content)){let F=[];u.content.forEach(S=>{S?.type==="text"&&typeof S.text=="string"?F.push(S.text):S?.type==="image"&&typeof S.source=="object"&&S.source?S.source.type==="base64"&&S.source.media_type?F.push(``):Y.log(`Unsupported image type ${S.source.type}`,S.source):Y.log(`Unsupported block type ${S?.type}`)}),b=F.join(`
|
|
13
13
|
|
|
14
14
|
`)}B&&b&&(b=`\`\`\`
|
|
15
15
|
${b.trim()}
|
|
16
|
-
\`\`\``),R({title:D,message:b},!0);break}case"thinking":{u.thinking&&R({title:"Thinking",message:u.thinking},!0);break}default:Y.log(`Message content type is not supported ${u.type}`,u)}}):f?.type==="result"&&(E=f.duration_ms||0,f.is_error?T=f.result:x=f.result,[c,d].forEach(u=>{u[u.length-1]?.message===x&&u.pop()}))})}),await P.catch(w=>{({error:T,result:x}=
|
|
16
|
+
\`\`\``),R({title:D,message:b},!0);break}case"thinking":{u.thinking&&R({title:"Thinking",message:u.thinking},!0);break}default:Y.log(`Message content type is not supported ${u.type}`,u)}}):f?.type==="result"&&(E=f.duration_ms||0,f.is_error?T=f.result:x=f.result,[c,d].forEach(u=>{u[u.length-1]?.message===x&&u.pop()}))})}),await P.catch(w=>{({error:T,result:x}=Vt({catchError:w,runCmd:P,error:T,result:x,runnerName:"Claude"}))}),I.flush(),{steps:c,duration:E,result:await X({initialResult:x,agentName:nt,hasError:!!T}),error:z({error:T,agentName:nt}),isRetryableError:Z(T)}}var ot=async()=>{let e=me.join(qt.homedir(),".claude");await Ht.rm(e,{recursive:!0,force:!0})},Kt={[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}}},[M]:{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}}},[U]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}}};import Wt from"fs/promises";import Jt from"os";import ke from"path";import W from"process";var Q=_("runner_codex"),st="Codex CLI",Xt=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(Q.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(Q.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(Q.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0}));async function be({config:e,netlify:t,persistSteps:r,sendSteps:n,aiGateway:o}){let{accountType:s,prompt:a,modelVersionOverrides:l}=e,{model:i}=e;if(o){let{token:R,url:A}=o;if(!R||!A)throw new Error("No token or url provided from AI Gateway");let w=zt[s];if(!w)throw new Error(`Codex is not supported for the account type ${s}`);if(i&&!w?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(l?.codex){let g=l?.codex?.[s];g&&(i=g)}W.env.OPENAI_API_KEY=R,W.env.OPENAI_BASE_URL=A}else if(!W.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let d=[],c=[],p={},h=0,E=0,x,T,m=ke.join(W.cwd(),"node_modules"),N=[ke.join(W.env.NODE_PATH||m,".bin/codex"),"--approval-mode","full-auto",o?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...i?["--model",i]:[],"-q",a].filter(Boolean),C=`${W.env.NVM_BIN}/node`;Q.log(`Running ${C} ${N.join(" ")}`);let P=t.utils.run(C,N,{all:!0,env:{...W.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),I="";return P.all.on("data",R=>{if(I+=R.toString(),!R.includes(`
|
|
17
17
|
`))return;let A=I.toString().split(`
|
|
18
|
-
`).filter(Boolean).map(f=>{try{return JSON.parse(f)}catch{Q.log("Could not parse line",f)}return null}).filter(Boolean);I="";let w=[],g=!1;A.forEach(f=>{if(f?.duration_ms&&(E=f.duration_ms,g=!0),f?.type==="local_shell_call")p[f.call_id]=f;else if(f?.type==="local_shell_call_output"){let u=
|
|
18
|
+
`).filter(Boolean).map(f=>{try{return JSON.parse(f)}catch{Q.log("Could not parse line",f)}return null}).filter(Boolean);I="";let w=[],g=!1;A.forEach(f=>{if(f?.duration_ms&&(E=f.duration_ms,g=!0),f?.type==="local_shell_call")p[f.call_id]=f;else if(f?.type==="local_shell_call_output"){let u=Qt(p[f.call_id],f);u.id=h,h+=1,u&&(c.push(u),d.push(u),w.push(u),g=!0)}else f?.type==="message"&&f.role==="assistant"?x=f.content.map(u=>u.text).join(`
|
|
19
19
|
`):f?.type==="message"&&f.role==="system"&&(T=f.content.map(u=>u.text).join(`
|
|
20
|
-
`))}),g&&(r?.({steps:d,duration:E}),n?.({steps:w,duration:E}))}),await P.catch(R=>{({error:T,result:x}=
|
|
20
|
+
`))}),g&&(r?.({steps:d,duration:E}),n?.({steps:w,duration:E}))}),await P.catch(R=>{({error:T,result:x}=Xt({catchError:R,runCmd:P,error:T,result:x,runnerName:"Codex"}))}),{steps:c,duration:E,result:await X({initialResult:x,agentName:st,hasError:!!T}),error:z({error:T,agentName:st}),isRetryableError:Z(T)}}var it=async()=>{let e=ke.join(Jt.homedir(),".codex");await Wt.rm(e,{recursive:!0,force:!0})},zt={[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":{}}},[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}}},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}}},[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}}}},Zt=new Set(["bash","-lc"]),Qt=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!Zt.has(s)),n=r?`Running \`${r.join(" ")}\``:void 0,o;try{o=JSON.parse(t.output).output?.trim(),o&&(o=`\`\`\`
|
|
21
21
|
${o.trim()}
|
|
22
|
-
\`\`\``)}catch(s){Q.error("Could not decode outputMsg",s,t.output)}return{title:n,message:o}};import
|
|
22
|
+
\`\`\``)}catch(s){Q.error("Could not decode outputMsg",s,t.output)}return{title:n,message:o}};import er from"fs/promises";import tr from"os";import ge from"path";import q from"process";var ie=_("runner_gemini"),at="Gemini CLI",rr=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(ie.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(ie.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(ie.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0})),nr={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 Le({config:e,netlify:t,persistSteps:r,sendSteps:n,aiGateway:o}){let{accountType:s,prompt:a,modelVersionOverrides:l}=e,{model:i}=e;if(o){let{token:g,url:f}=o;if(!g||!f)throw new Error("No token or url provided from AI Gateway");let u=or[s];if(!u)throw new Error(`Gemini is not supported for the account type ${s}`);if(i&&!u?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(l?.gemini){let y=l?.gemini?.[s];y&&(i=y)}q.env.GEMINI_API_KEY=g,q.env.GOOGLE_GEMINI_BASE_URL=f}else if(!q.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let d=[],c=[],p=[],h={},E=0,x=0,T,m,N=ge.join(q.cwd(),"node_modules"),C=[ge.join(q.env.NODE_PATH||N,".bin/gemini"),...i?["--model",i]:[],"--yolo","-p",a],P=`${q.env.NVM_BIN}/node`;ie.log(`Running ${P} ${C.join(" ")}`);let I=t.utils.run(P,C,{all:!0,env:q.env});I.stdin?.end();let R=de(()=>{r?.({steps:d,duration:x}),n?.({steps:c,duration:x}),c=[]},250),A=(g,f)=>{g.id=E,E+=1,p.push(g),d.push(g),c.push(g),f||R.flush(),R(),f&&R.flush()},w="";return I.all.on("data",g=>{if(w+=g.toString(),!g.includes(`
|
|
23
23
|
`))return;let f=w.toString().split(`
|
|
24
|
-
`).filter(Boolean).map(u=>{try{if(u.startsWith("[API Error")){let y=u.match(/\[api error: (.+?)]$/i)?.[1];return{type:"error",value:fe(y,!1)?.error?.message||y||"Gemini encountered error"}}return JSON.parse(u)}catch{}return null}).filter(Boolean);w="",f.forEach(u=>{switch(u.type){case"thought":{let y=u.value;A({title:y?.subject??"Thinking...",message:y?.description},!0);break}case"content":{u.value&&A({message:u.value});break}case"tool_call_request":{let y=u.value,D=
|
|
24
|
+
`).filter(Boolean).map(u=>{try{if(u.startsWith("[API Error")){let y=u.match(/\[api error: (.+?)]$/i)?.[1];return{type:"error",value:fe(y,!1)?.error?.message||y||"Gemini encountered error"}}return JSON.parse(u)}catch{}return null}).filter(Boolean);w="",f.forEach(u=>{switch(u.type){case"thought":{let y=u.value;A({title:y?.subject??"Thinking...",message:y?.description},!0);break}case"content":{u.value&&A({message:u.value});break}case"tool_call_request":{let y=u.value,D=nr[y.name]??y.name,B=y.args?.path||y.args?.absolute_path,b=B&&ge.relative(q.cwd(),B),F=y.args?.command,It={title:[D,b&&`\`${b}\``,F&&`\`${F}\``].filter(Boolean).join(" ")};h[y.callId]=It,R.flush();break}case"tool_result":{let y=u.value,D=h[y.callId];if(D){let B=[y.resultDisplay,y.responseParts?.functionResponse?.response?.output].find(b=>typeof b=="string"&&b);B&&(D.message=`\`\`\`
|
|
25
25
|
${B.trim()}
|
|
26
|
-
\`\`\``),A(D,!0)}break}case"result":{x=u.duration_ms,T=u.value,[p,d,c].forEach(y=>{y[y.length-1]?.message===T&&y.pop()});break}case"error":{m=u.value;break}case"finished":break;default:{ie.warn("Unhandled message type:",u.type);break}}})}),await I.catch(g=>{({error:m,result:T}=
|
|
26
|
+
\`\`\``),A(D,!0)}break}case"result":{x=u.duration_ms,T=u.value,[p,d,c].forEach(y=>{y[y.length-1]?.message===T&&y.pop()});break}case"error":{m=u.value;break}case"finished":break;default:{ie.warn("Unhandled message type:",u.type);break}}})}),await I.catch(g=>{({error:m,result:T}=rr({catchError:g,runCmd:I,error:m,result:T,runnerName:"Gemini"}))}),R.flush(),{steps:p,duration:x,result:await X({initialResult:T,agentName:at,hasError:!!m}),error:z({error:m,agentName:at}),isRetryableError:Z(m)}}var lt=async()=>{let e=ge.join(tr.homedir(),".gemini");await er.rm(e,{recursive:!0,force:!0})},or={[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}}},[M]:{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}}},[U]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}}};var sr={codex:{runner:be,clean:it},claude:{runner:Oe,clean:ot},gemini:{runner:Le,clean:lt}},ut=sr;var ct=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:n})=>{let o=ir();return le(o,"init-stage",async s=>{let a=performance.now();s?.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,"init.runnerVersion":n||"unknown"});let l=ut[e.runner];if(!l)throw s?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let i=ar({apiToken:r});Ge(i);let d=e.useGateway?await He({netlify:i,config:e}):void 0;s?.setAttributes({"init.aiGateway.created":!!d}),e.validateAgent&&e.errorLogsPath&&s?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let c=Xe(({steps:E=[],duration:x})=>{let T=[...E];return E.length=0,J(e.id,e.sessionId,{steps:T,duration:x})},t),p;e.hasRepo?e.sha?(p=e.sha,s?.setAttributes({"init.sha.source":"provided"})):(p=await tt(i),await pe(e.id,{sha:p}),s?.setAttributes({"init.sha.source":"current_commit"})):(p=await rt(i),s?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let h=performance.now()-a;return s?.setAttributes({"init.sha":p||"unknown","init.duration.ms":h,"init.status":"success"}),{aiGateway:d,context:i,persistSteps:c,runner:l,sha:p}})},ar=({apiToken:e})=>({constants:{NETLIFY_API_HOST:he.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||he.env.NETLIFY_API_TOKEN,SITE_ID:he.env.SITE_ID,FUNCTIONS_DIST:he.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:Ve}});import lr from"crypto";import V from"fs/promises";import k from"path";import $ from"process";var v=_("context"),ur=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:$.env.NETLIFY_TEAM_ID,userId:$.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:$.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},cr=10,pr=async e=>{let{name:t,ext:r}=k.parse(e),n=e,o=k.join($.cwd(),L,n),s=0;for(;await dr(o);){if(s>=cr)throw new Error("Failed to generate context file");n=`${t}-${lr.randomUUID().slice(0,5)}${r}`,o=k.join($.cwd(),L,n),s+=1}return n},dr=async e=>{try{return await V.access(e),!0}catch{return!1}},fr=async()=>{try{v.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 v.warn("Invalid response structure: missing or invalid consumers array"),null;let r=t.consumers.find(n=>n&&typeof n=="object"&&n.key==="catchall-consumer");return r?!r.contextScopes||typeof r.contextScopes!="object"?(v.warn("Catchall consumer missing or invalid contextScopes"),null):r:(v.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?v.warn("Netlify features context request timed out"):v.warn("Failed to fetch Netlify features context:",e.message),null}},mr=async(e,t)=>{try{let r=await fetch(e,{signal:AbortSignal.timeout(1e4)});if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let n=await r.text();return await V.writeFile(t,n,"utf-8"),!0}catch(r){return r.name==="AbortError"?v.warn(`Download timeout for ${e}`):v.warn(`Failed to download context file ${e}:`,r.message),!1}},Ee=null,gr=async()=>{if(Ee)return Ee;let e=await fr();if(!e)return[];let t=k.join($.cwd(),L,Ae);await V.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([o,s])=>{if(!s||typeof s!="object"||!s.endpoint||!s.scope)return v.warn(`Invalid scope data for ${o}, skipping...`),null;let a=`${o}.md`,l=k.join(t,a),i=k.join(L,Ae,a);return v.log(`Downloading ${s.scope} context...`),await mr(s.endpoint,l)?(v.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:o}):null});return Ee=(await Promise.all(r)).filter(o=>o!==null),Ee},pt=async({cliPath:e,netlify:t,config:r,buildErrorContext:n})=>{let o=ur(t),s=await pr(Ke),a=k.join($.cwd(),L);await V.mkdir(a,{recursive:!0});let l=k.join(L,s),i=k.join($.cwd(),l),d=k.join($.cwd(),L,se);try{await V.unlink(d),v.log(`Deleted old results file: ${d}`)}catch{}let c=n?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
|
|
27
27
|
Your task is to analyze and fix the build errors.
|
|
28
28
|
Don't apply techniques of reverting changes. Apply fixes related to errors.
|
|
29
29
|
Don't try to run build by yourself. Just fix the errors.
|
|
@@ -55,7 +55,7 @@ ${C.response}
|
|
|
55
55
|
`)}
|
|
56
56
|
|
|
57
57
|
</session_history_context>
|
|
58
|
-
`}let E=await
|
|
58
|
+
`}let E=await gr(),x="";E.length>0&&(x=`
|
|
59
59
|
<netlify_features_context>
|
|
60
60
|
If the user request is explicitly related to a specific Netlify feature (e.g., Netlify Forms, Netlify Functions, etc.), you MUST review the relevant documentation below in addition to reviewing the project files.
|
|
61
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.
|
|
@@ -121,12 +121,12 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
121
121
|
</request>
|
|
122
122
|
|
|
123
123
|
Use the following file for the complete context of the ask, the environment, and what's available. ${i} You MUST READ ALL OF IT. Make sure to read it first. Never cite or paraphrase private context.
|
|
124
|
-
`),T};var
|
|
124
|
+
`),T};var hr=_("prompt"),dt=async({cliPath:e,config:t,netlify:r,buildErrorContext:n})=>{let o=await pt({cliPath:e,config:t,netlify:r,buildErrorContext:n});return process.env.AGENT_RUNNER_DEBUG&&hr.log("Contextful Prompt:",o),{prompt:o}};var ft=_("inference_stage"),mt=2,_e=async e=>{let{cliPath:t,config:r,context:n,buildErrors:o,runner:s,persistSteps:a,aiGateway:l,attempt:i}=e;qe();let{prompt:d}=await dt({cliPath:t,config:r,buildErrorContext:Er(o),netlify:n}),c={...r,prompt:d},p=await s({aiGateway:l,config:c,netlify:n,persistSteps:a});if(await a.flush(),p.error){if(ft.error("Runner failed",{stepsCount:p.steps.length,duration:p.duration,error:p.error,isRetryableError:p.isRetryableError}),p.error&&p.isRetryableError&&(!i||i<mt))return ft.log(`Retrying inference stage, attempt ${i} of ${mt}...`),await new Promise(E=>setTimeout(E,5e3)),{runnerResult:(await _e({...e,attempt:(i||1)+1})).runnerResult};throw new Error(p.error)}return{runnerResult:p}},Er=e=>!e||e.length===0?"":`
|
|
125
125
|
Deploy failed failed. Here are the errors to review on the latest build:
|
|
126
126
|
|
|
127
127
|
Below are all of the logs with potential issues that we extracted. Some of them may be false positives, discern them carefully and ensure fixes are relevant.
|
|
128
128
|
|
|
129
129
|
${e.pop()}
|
|
130
|
-
`;import
|
|
131
|
-
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(l){throw ae.error("Failed to create preview deploy via CLI:",l),l}};var ye=_("deploy_stage"),$e=async({cliPath:e,config:t,context:r,result:n,filter:o})=>{let s=await et({config:t,netlify:r});if(!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:l,diffBinary:i,resultDiffBinary:d}=s,c=!0;ye.log("Preview deploy condition check:",{resultUndefined:n===void 0,resultType:typeof n,hasChanges:c,wouldCreatePreview:n!==void 0&&c});let p=null;if(n!==void 0&&c)try{let h;try{let E=await je(t.id,t.sessionId);E?.title&&(h=E.title)}catch(E){ye.warn("Failed to fetch session title, using fallback message:",E.message)}p=await gt({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:h,skipBuild:!1,deploySubdomain:ze(t.id,
|
|
130
|
+
`;import _r from"process";var ae=_("deploy"),gt=async({netlify:e,hasRepo:t,skipBuild:r,message:n="Agent Preview",deploySubdomain:o,cliPath:s,filter:a})=>{try{let l=["deploy","--message",`"${n}"`,"--json","--draft","--verbose"];t||(ae.log("Deploy: Uploading source zip"),l.push("--upload-source-zip")),o&&l.push("--alias",o),a&&l.push("--filter",a),r?(ae.log("Deploy: Skipping build"),l.push("--no-build")):l.push("--context","deploy-preview");let i=s||"netlify";ae.log(`Running: ${i} ${l.join(" ")}`);let d=await e.utils.run(i,l,{stdio:["ignore","pipe","pipe"]}),c=JSON.parse(d.stdout.trim());ae.log(`
|
|
131
|
+
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(l){throw ae.error("Failed to create preview deploy via CLI:",l),l}};var ye=_("deploy_stage"),$e=async({cliPath:e,config:t,context:r,result:n,filter:o})=>{let s=await et({config:t,netlify:r});if(!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:l,diffBinary:i,resultDiffBinary:d}=s,c=!0;ye.log("Preview deploy condition check:",{resultUndefined:n===void 0,resultType:typeof n,hasChanges:c,wouldCreatePreview:n!==void 0&&c});let p=null;if(n!==void 0&&c)try{let h;try{let E=await je(t.id,t.sessionId);E?.title&&(h=E.title)}catch(E){ye.warn("Failed to fetch session title, using fallback message:",E.message)}p=await gt({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:h,skipBuild:!1,deploySubdomain:ze(t.id,_r.env.SITE_NAME),filter:o})}catch(h){return ye.warn("Failed to create preview deploy (continuing with agent run):",h),{diff:a,resultDiff:l,hasChanges:c,previewInfo:null,diffBinary:i,resultDiffBinary:d,deployError:h instanceof Error?h.message:String(h)}}return ye.log("Git status",{hasDiff:!!a,hasChanges:c}),{diff:a,resultDiff:l,hasChanges:c,previewInfo:p,diffBinary:i,resultDiffBinary:d}};async function ht(e,t){let{maxRetries:r,baseDelay:n,onRetry:o}=t,s;for(let a=1;a<=r;a++)try{return await e()}catch(l){if(s=l,a===r)throw s;o&&o(a,s),await new Promise(i=>setTimeout(i,n*a))}throw s}var ee=_("cleanup_stage"),Et=async({config:e,diff:t,result:r,duration:n,resultDiff:o,diffBinary:s,resultDiffBinary:a,previewInfo:l})=>{let i={result_diff:t,result:r||"Done",duration:n,result_diff_binary:s};return l&&l.deployId&&(i.deploy_id=l.deployId),l&&l.sourceZipFilename&&(i.result_zip_file_name=l.sourceZipFilename),o||a?(ee.log("Updating total agent result diff"),await pe(e.id,{result_diff:o,result_diff_binary:a})):ee.log("No total result diff, not updating"),ee.log("Updated agent runner with result"),await ht(()=>J(e.id,e.sessionId,i),{maxRetries:3,baseDelay:1e3,onRetry:(d,c)=>{ee.error(`Error updating agent runner session (attempt ${d}):`,c),ee.log("Retrying...")}}),ee.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as Tr}from"@netlify/otel";var xr=yr(import.meta.url),_t=xr("../package.json"),yt=_("pipeline_index"),Te=3,Tt=async({config:e,apiToken:t,cliPath:r="netlify",cwd:n,errorLogsPath:o,filter:s,traceExporterUrl:a})=>{let l;try{await Ue(_t.version,e.id,a);let i=Tr(),d,{aiGateway:c,context:p,persistSteps:h,runner:E,sha:x}=await ct({config:e,apiToken:t,cliPath:r,cwd:n,errorLogsPath:o,filter:s,runnerVersion:_t.version});l=E.clean,e.sha=x;let{runnerResult:T}=await _e({cliPath:r,config:e,context:p,runner:E.runner,persistSteps:h,aiGateway:c}),m=await $e({cliPath:r,config:e,context:p,result:T.result,filter:s}),N=T,C=[];if(m.hasChanges&&m.deployError){C.push(Me(m.deployError));let g=1;for(;g<=Te&&!m.previewInfo;)yt.log(`Deploy attempt had errors. Retrying. ${g}/${Te}`),await le(i,"stage-deploy",async f=>{f?.setAttributes({"stage.attempt":g});let{runnerResult:u}=await _e({cliPath:r,config:e,context:p,runner:E.runner,persistSteps:h,aiGateway:c,buildErrors:C});N={...u,steps:[...N.steps||[],...u.steps||[]],duration:(N.duration||0)+(u.duration||0)},m=await $e({cliPath:r,config:e,context:p,result:u.result,filter:s}),m.deployError&&C.push(m.deployError),g++});g>Te&&!m.previewInfo&&(d=new Error(`Deploy validation failed after ${Te} attempts`))}let{diff:P,resultDiff:I,previewInfo:R,diffBinary:A,resultDiffBinary:w}=m;if(await Et({config:e,diff:P,result:N.result,duration:N.duration,resultDiff:I,diffBinary:A,resultDiffBinary:w,previewInfo:R}),d)throw d;await E.clean?.()}catch(i){yt.error("Got error while running pipeline",i),await l?.();let d=i instanceof Error&&i.message;throw await J(e.id,e.sessionId,{result:d||"Encountered error when running agent",state:"error"}),i}};import O from"process";var Rr="codex",wr=e=>(e??[]).filter(t=>t.request&&t.response),Ir=e=>(e??[]).filter(t=>t.site_context),xt=_("config"),Rt=()=>{let e=O.env.NETLIFY_AGENT_RUNNER_ID,t=O.env.NETLIFY_AGENT_RUNNER_SESSION_ID;if(!e||!t)throw new Error("ID of agent runner is not provided");let r=O.env.NETLIFY_AGENT_RUNNER_RESULT_BRANCH,n=O.env.NETLIFY_AGENT_RUNNER_PROMPT;if(!n)throw new Error("Prompt is not provided");let o=O.env.NETLIFY_AGENT_RUNNER_AGENT||Rr,s=O.env.NETLIFY_AGENT_RUNNER_MODEL,a=O.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED==="1",l=O.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED==="1",i=O.env.ERROR_LOGS_PATH,d=fe(O.env.NETLIFY_AGENT_RUNNER_CONTEXT,!0,xt),c=wr(d),p=Ir(d),h=O.env.NETLIFY_AGENT_RUNNER_HAS_REPO!=="0",E=!O.env.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED,x=O.env.NETLIFY_AGENT_RUNNER_SHA,T=Nr(),m=Ze(),N={id:e,sessionId:t,resultBranch:r,prompt:n,runner:o,model:s,validateAgent:a,errorLogsPath:i,sessionHistoryContext:c,siteContext:p,hasRepo:h,useGateway:E,sha:x,accountType:T,validateAgentWithBuild:l,modelVersionOverrides:m};return xt.log({fullConfig:N}),N},Nr=()=>{let e=O.env.NETLIFY_TEAM_TYPE;return e?e.includes("personal")?M:e.includes("pro")?"pro":e.startsWith("enterprise")?G:e.startsWith("free")?j:U:U};var wt=_("bin_cmd"),te=Cr(De.argv.slice(2),{string:["auth","cwd","cli-path","error-logs-path","filter","trace-exporter-url"]});try{let e=Rt();await Tt({config:e,apiToken:te.auth,cwd:te.cwd,cliPath:te["cli-path"],errorLogsPath:te["error-logs-path"],filter:te.filter,traceExporterUrl:te["trace-exporter-url"]}),wt.info("Finished agent"),De.exit(0)}catch(e){wt.error("Error running agent pipeline:",e),De.exit(1)}
|
|
132
132
|
//# sourceMappingURL=bin.js.map
|
package/dist/index.js
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
|
-
import{createRequire as
|
|
2
|
-
`),r=[],n=-1,o=0;for(;o<t.length;){let l=t[o].slice(0,500).toLowerCase();if(
|
|
1
|
+
import{createRequire as ur}from"module";import{createTracerProvider as gt}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as be}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as ht}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as yt}from"@netlify/otel";import{OTLPTraceExporter as Et}from"@opentelemetry/exporter-trace-otlp-grpc";function _(e){let t=!process.env.VITEST;return{log:(...r)=>{t&&console.log(`[AR]-[${e}]`,...r)},error:(...r)=>{t&&console.error(`[AR]-[${e}]`,...r)},warn:(...r)=>{t&&console.warn(`[AR]-[${e}]`,...r)},info:(...r)=>{t&&console.info(`[AR]-[${e}]`,...r)},debug:(...r)=>{t&&console.debug(`[AR]-[${e}]`,...r)}}}var Ee=_("tracing"),$e=(e,t,r)=>gt({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new be(new _e),new be(new Et({url:r}))],instrumentations:[new ht({skipHeaders:!0})]});function ie(e,t,r){return Ee.log(`\u23F3 TRACE: ${t} starting...`),yt(e,t,r)}var _e=class{export(t,r){for(let n of t)this.logSpan(n);r({code:1})}async shutdown(){}forceFlush(){return Promise.resolve()}logSpan(t){let r=(t.endTime[0]-t.startTime[0])*1e3+(t.endTime[1]-t.startTime[1])/1e6,n=t.attributes,o=[];for(let[l,i]of Object.entries(n))l.includes("duration")&&typeof i=="number"?o.push(`${l}=${i.toFixed(2)}ms`):o.push(`${l}=${i}`);let s=t.status?.code===2?"\u274C":"\u2705",a=o.length>0?` [${o.join(", ")}]`:"";Ee.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${a}`),t.status?.code===2&&t.status.message&&Ee.log(` \u274C Error: ${t.status.message}`)}};var _t=["error","failed","exception","fatal","panic","abort","crash"];function De(e){let t=e.split(`
|
|
2
|
+
`),r=[],n=-1,o=0;for(;o<t.length;){let l=t[o].slice(0,500).toLowerCase();if(_t.some(f=>l.includes(f))){let f=Math.max(0,o-10,n+1),c=Math.min(t.length-1,o+20),d=[];for(let h=f;h<=c;h++)d.push(t[h]);r.push(d.join(`
|
|
3
3
|
`)),n=c,o=c+1}else o++}if(r.length===0)return e;let s=r.map((a,l)=>`<extracted_error_chunk order="${l+1}">
|
|
4
4
|
${a}
|
|
5
5
|
</extracted_error_chunk>`).join(`
|
|
6
6
|
|
|
7
|
-
`);return s.length>e.length*.8?e:s}import fe from"process";import{getTracer as
|
|
8
|
-
`).filter(o=>!
|
|
9
|
-
`).forEach(a=>{let l=a.match(/\?\? (.+?)\.log$/)?.[1];l&&n.push(`:!${l}.log`)}),n};import
|
|
7
|
+
`);return s.length>e.length*.8?e:s}import fe from"process";import{getTracer as Xt}from"@netlify/otel";import ae from"process";var xe=ae.env.NETLIFY_API_URL,Te=ae.env.NETLIFY_API_TOKEN,Q=_("api"),le=async(e,t={})=>{if(!xe||!Te)throw new Error("No API URL or token");let r=new URL(e,xe),n={...t,headers:{...t.headers,Authorization:`Bearer ${Te}`}};ae.env.AGENT_RUNNERS_DEBUG==="true"&&(n.headers["x-nf-debug-logging"]="true"),t.json&&(n.headers||={},n.headers["Content-Type"]="application/json",n.body=JSON.stringify(t.json));let o=await fetch(r,n),s=o.ok&&o.status<=299;if(ae.env.AGENT_RUNNERS_DEBUG==="true")Q.log(`Response headers for ${r}:`),o.headers.forEach((l,i)=>{Q.log(` ${i}: ${l}`)});else{let l=o.headers.get("x-request-id")||o.headers.get("x-nf-request-id");Q.log(`Request ID for ${r}: ${l||"N/A"}`)}if(s||Q.error(`Got status ${o.status} for request ${r}`),t.raw){if(!s)throw o;return o}let a=await(o.headers.get("content-type")?.includes("application/json")?o.json():o.text());if(!s)throw a;return a},Le=e=>{Q.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(xe=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Te=e.constants.NETLIFY_API_TOKEN)},ue=(e,t)=>le(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),Y=(e,t,r)=>le(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var Fe=(e,t)=>le(`/api/v1/agent_runners/${e}/sessions/${t}`),Ue=(e,t,r)=>le(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}});var Me=_("ai_gateway"),je=async({netlify:e,config:t})=>{let r,n,o,s,a=e.constants?.SITE_ID;if(!a)throw new Error("No site id");let l=async()=>{clearTimeout(o),Me.log("Requesting AI gateway information");let i=await Ue(a,t.id,t.sessionId);if({token:r,url:s}=i,n=i.expires_at?i.expires_at*1e3:void 0,Me.log("Got AI gateway information",{token:!!r,expiresAt:n,url:s}),n){let f=n-Date.now()-6e4;f>0&&(o=setTimeout(()=>{l()},f))}};return await l(),{get url(){return s},get token(){return r}}};import te from"process";import{execa as It,execaCommand as kr}from"execa";import{Transform as xt}from"stream";var Tt=["NODE_ENV","PATH","HOME","USER","USERNAME","SHELL","PWD","OLDPWD","TMPDIR","TMP","TEMP","LANG","TERM","EDITOR","PAGER","OS","PROCESSOR_ARCHITECTURE","PROCESSOR_IDENTIFIER","SYSTEMROOT","WINDIR","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","APPDATA","LOCALAPPDATA","NODE_OPTIONS","NODE_PATH","NODE_DEBUG","NODE_NO_WARNINGS","npm_config_registry","npm_config_cache","npm_execpath","npm_node_execpath","CI","GITHUB_ACTIONS","GITHUB_WORKSPACE","GITHUB_REPOSITORY","GITHUB_REF","BUILDKITE","BUILDKITE_BRANCH","BUILDKITE_COMMIT","BUILDKITE_BUILD_NUMBER","JENKINS_URL","TRAVIS","CIRCLECI","DISPLAY","COLORTERM","TERM_PROGRAM","TERM_PROGRAM_VERSION","COLUMNS","LINES","HISTSIZE","HISTFILE"];function wt(){return Object.entries(process.env).filter(([e,t])=>!(!t||Tt.includes(e)||t.length<5)).map(([,e])=>e).filter(Boolean)}function we(e){if(typeof e!="string")return e;let t=wt();if(t.length===0)return e;let r=e;return t.forEach(n=>{let o=new RegExp(Rt(n),"g");r=r.replace(o,"******")}),r}function Rt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ee=class extends xt{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,n){let o=t.toString(),s=we(o);n(null,s)}};function Ge(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(n,o,s){let a=typeof n=="string"?we(n):n;return typeof o=="function"?t(a,o):t(a,o,s)},process.stderr.write=function(n,o,s){let a=typeof n=="string"?we(n):n;return typeof o=="function"?r(a,o):r(a,o,s)}}var Dr=_("shell"),Ct={preferLocal:!0},Be=(e,t,r)=>{let[n,o]=Nt(t,r),s={...Ct,...o},a=It(e,n,s);return St(a,s),a};var Nt=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},St=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(te.env.NETLIFY_MASK_LOGS!=="false"){e.stdout?.pipe(new ee).pipe(te.stdout),e.stderr?.pipe(new ee).pipe(te.stderr);return}e.stdout?.pipe(te.stdout),e.stderr?.pipe(te.stderr)};var Ye="netlify-agent-runner-context.md",Re="task-history",Ie="netlify-context",b=".netlify",re="results.md",Ce="assets",H="other",q="personal";var K="enterprise",V="free";var At=_("utils"),Pt=e=>new Promise(t=>{setTimeout(t,e)}),He=(e,t=3e3)=>{let r=!1,n=null,o=[],s=null,a=(...l)=>{if(r)return n=l,new Promise(c=>{o.push(c)});r=!0;let i,f=new Promise(c=>{i=c});return s=(async()=>{await Promise.resolve();let c=await e(...l);for(i(c);;){if(await Pt(t),!n)return r=!1,s=null,c;let d=n,h=o;n=null,o=[],c=await e(...d),h.forEach(y=>{y(c)})}})(),f};return a.flush=async()=>{if((r||n)&&s)return await s,a.flush()},a},ce=(e,t,r=!1)=>{let n=null,o=null,s=null,a=function(...l){o=l,s=this;let i=r&&!n;clearTimeout(n),n=setTimeout(()=>{n=null,r||(e.apply(s,o),o=null,s=null)},t),i&&(e.apply(s,o),o=null,s=null)};return a.cancel=()=>{clearTimeout(n),n=null,o=null,s=null},a.flush=()=>{if(n){clearTimeout(n);let l=o,i=s;n=null,o=null,s=null,e.apply(i,l)}},a},qe=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(n){t&&(r?.error?r.error("Could not parse JSON",n):At.error("Could not parse JSON",n))}},Ke=(e,t)=>{let o=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let l=`--${t}${o}`;if(l.length>55)return"";let i=60-l.length;if(i<=0)return"";if(i>=s.length+6){let f=Math.min(i-s.length,e.length);return`${s}${e.slice(0,f)}`}return e.slice(0,i)};import{Buffer as Ve}from"buffer";var We=async({config:e,netlify:t})=>{let r=await Ot(t),{hasChanges:n}=r,{status:o}=r;if(!n)return{hasChanges:!1};let s=await kt(t,o);await t.utils.run("git",["add",".",...s]);let a={stdio:["ignore","pipe","pipe"]},i=(await t.utils.run("git",["diff","--staged"],a)).stdout;if(n=!!i,!n)return{hasChanges:!1};let c=(await t.utils.run("git",["diff","--staged","--binary"],a)).stdout,d,h;if(e.sha){await t.utils.run("git",["commit","-m","Agent runner"]),d=(await t.utils.run("git",["diff",e.sha,"HEAD"],a)).stdout;let g=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;d!==g&&(h=Ve.from(g).toString("base64"))}let y={hasChanges:!0,diff:i,resultDiff:d};return i!==c&&(y.diffBinary=Ve.from(c).toString("base64")),h&&(y.resultDiffBinary=h),y},vt=["?? mise.toml","?? deno.lock",/\?\? .+?\.log/],Ot=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
|
|
8
|
+
`).filter(o=>!vt.some(s=>s instanceof RegExp?s.test(o):o===s))).length!==0,status:t.stdout}};var Je=async e=>{let{stdout:t}=await e.utils.run("git",["rev-parse","HEAD"]);return t.trim()},Xe=async e=>{let{stdout:t}=await e.utils.run("git",["rev-list","--max-parents=0","HEAD"]);return t.trim()},kt=async(e,t="")=>{let r=[".netlify","mise.toml","deno.lock","node_modules"],n=[],o=r.map(async a=>{try{return await e.utils.run("git",["check-ignore","-v",a]),null}catch{return`:!${a}`}});return(await Promise.all(o)).forEach(a=>{a&&n.push(a)}),t.split(`
|
|
9
|
+
`).forEach(a=>{let l=a.match(/\?\? (.+?)\.log$/)?.[1];l&&n.push(`:!${l}.log`)}),n};import $t from"fs/promises";import Dt from"os";import de from"path";import M from"process";import Ne from"path";import bt from"fs/promises";var Se=_("agent-output-utils");async function W({initialResult:e,agentName:t,hasError:r}){let n="",o=Ne.join(process.cwd(),b,re);try{let s=await bt.readFile(o,"utf-8");s&&(n=s,Se.log(`Pulled result from ${Ne.relative(process.cwd(),o)}`))}catch{Se.log(`No results file found at ${Ne.relative(process.cwd(),o)}`)}return n||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function J({error:e,agentName:t}){let r=e&&typeof e=="object"?JSON.stringify(e):e,n=r?.replace(/\s+/g," ").trim()||"",o="";return n?.includes("ai gateway is not available for your account")?o="AI Gateway is currently not available on your account. Please confirm your account meets the criteria for using Agent Runners and AI Gateway and that your account has remaining AI Gateway inference credits available. Reach out to Netlify support if this is unexpected.":n?.includes("error when talking to gemini api")?o="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":(n?.includes("connection closed prematurely while waiting for the model")||n?.includes("499")&&t.toLowerCase().includes("gemini"))&&(o="The agent's models were currently overloaded. Please try again or use a different available agent."),o&&Se.log(`Providing updated error messsage: ${o}, replacing original error: ${r}`),o||r||void 0}function X(e){if(!e)return!1;let r=(e&&typeof e=="object"?JSON.stringify(e):e)?.replace(/\s+/g," ").trim()||"";return!!(r?.includes("error when talking to gemini api")||r?.includes("connection closed prematurely while waiting for the model"))}var F=_("runner_claude"),ze="Claude Code",Lt=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(F.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(F.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(F.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0}));async function Ae({config:e,netlify:t,persistSteps:r,aiGateway:n}){let o=e,{accountType:s,prompt:a,modelVersionOverrides:l}=o,{model:i}=o;if(n){let{token:w,url:m}=n;if(!w||!m)throw new Error("No token or url provided from AI Gateway");let p=Ft[s];if(!p)throw new Error(`Claude is not supported for the account type ${s}`);if(i&&!p?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(l?.claude){let u=l?.claude?.[s];u&&(i=u)}M.env.ANTHROPIC_API_KEY=w,M.env.ANTHROPIC_BASE_URL=m}else if(!M.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let f=[],c=[],d={},h=0,y=0,R,x,g=de.join(M.cwd(),"node_modules"),A=[de.join(M.env.NODE_PATH||g,".bin/claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...i?["--model",i]:[],"-p",a],C=`${M.env.NVM_BIN}/node`;F.log(`Running ${C} ${A.join(" ")}`);let P=t.utils.run(C,A,{all:!0,env:M.env});P.stdin?.end();let I=ce(()=>{r?.({steps:f,duration:y})},250),T=(w,m)=>{let p={...w,id:h};h+=1,c.push(p),f.push(p),m||I.flush(),I(),m&&I.flush()},N="";return P.all?.on("data",w=>{if(N+=w.toString(),!w.includes(`
|
|
10
10
|
`))return;let m=N.split(`
|
|
11
11
|
`).filter(Boolean).map(p=>{try{return JSON.parse(p)}catch{F.log("Could not parse line",p)}return null}).filter(Boolean);N="",m.forEach(p=>{Array.isArray(p?.message?.content)?p.message.content.forEach(u=>{switch(u.type){case"text":{u.text&&T({message:u.text});break}case"image":{typeof u.source=="object"&&u.source&&u.source.type==="base64"&&u.source.media_type?T({message:``}):F.log(`Unsupported image type ${u.source?.type}`,u.source);break}case"tool_use":{if(u.name==="Task"){let E=u.input?.description&&`\`${u.input.description}\``;T({title:[u.name,E].filter(Boolean).join(" ")})}else u.id&&(d[u.id]=u);I.flush();break}case"tool_result":{let E=u.tool_use_id?d[u.tool_use_id]:void 0,D;if(E){let L=E.input?.file_path&&de.relative(M.cwd(),E.input.file_path),S=L&&`\`${L}\``;D=[E.name,S].filter(Boolean).join(" ")}let U=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(E?.name||""),k;if(typeof u.content=="string")k=u.content;else if(Array.isArray(u.content)){let L=[];u.content.forEach(S=>{S?.type==="text"&&typeof S.text=="string"?L.push(S.text):S?.type==="image"&&typeof S.source=="object"&&S.source?S.source.type==="base64"&&S.source.media_type?L.push(``):F.log(`Unsupported image type ${S.source.type}`,S.source):F.log(`Unsupported block type ${S?.type}`)}),k=L.join(`
|
|
12
12
|
|
|
13
13
|
`)}U&&k&&(k=`\`\`\`
|
|
14
14
|
${k.trim()}
|
|
15
|
-
\`\`\``),T({title:D,message:k},!0);break}case"thinking":{u.thinking&&T({title:"Thinking",message:u.thinking},!0);break}default:F.log(`Message content type is not supported ${u.type}`,u)}}):p?.type==="result"&&(y=p.duration_ms||0,p.is_error?x=p.result:R=p.result,[c,f].forEach(u=>{u[u.length-1]?.message===R&&u.pop()}))})}),await P.catch(w=>{({error:x,result:R}=
|
|
15
|
+
\`\`\``),T({title:D,message:k},!0);break}case"thinking":{u.thinking&&T({title:"Thinking",message:u.thinking},!0);break}default:F.log(`Message content type is not supported ${u.type}`,u)}}):p?.type==="result"&&(y=p.duration_ms||0,p.is_error?x=p.result:R=p.result,[c,f].forEach(u=>{u[u.length-1]?.message===R&&u.pop()}))})}),await P.catch(w=>{({error:x,result:R}=Lt({catchError:w,runCmd:P,error:x,result:R,runnerName:"Claude"}))}),I.flush(),{steps:c,duration:y,result:await W({initialResult:R,agentName:ze,hasError:!!x}),error:J({error:x,agentName:ze}),isRetryableError:X(x)}}var Ze=async()=>{let e=de.join(Dt.homedir(),".claude");await $t.rm(e,{recursive:!0,force:!0})},Ft={[K]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:64e3},"claude-3-haiku-20240307":{maxTokens:4096},"claude-opus-4-20250514":{maxTokens:32e3},"claude-sonnet-4-20250514":{maxTokens:64e3}}},pro:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[q]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[V]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}},[H]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}}};import Ut from"fs/promises";import Mt from"os";import Pe from"path";import B from"process";var z=_("runner_codex"),Qe="Codex CLI",jt=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(z.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(z.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(z.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0}));async function ve({config:e,netlify:t,persistSteps:r,sendSteps:n,aiGateway:o}){let{accountType:s,prompt:a,modelVersionOverrides:l}=e,{model:i}=e;if(o){let{token:T,url:N}=o;if(!T||!N)throw new Error("No token or url provided from AI Gateway");let w=Gt[s];if(!w)throw new Error(`Codex is not supported for the account type ${s}`);if(i&&!w?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(l?.codex){let m=l?.codex?.[s];m&&(i=m)}B.env.OPENAI_API_KEY=T,B.env.OPENAI_BASE_URL=N}else if(!B.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let f=[],c=[],d={},h=0,y=0,R,x,g=Pe.join(B.cwd(),"node_modules"),A=[Pe.join(B.env.NODE_PATH||g,".bin/codex"),"--approval-mode","full-auto",o?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...i?["--model",i]:[],"-q",a].filter(Boolean),C=`${B.env.NVM_BIN}/node`;z.log(`Running ${C} ${A.join(" ")}`);let P=t.utils.run(C,A,{all:!0,env:{...B.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),I="";return P.all.on("data",T=>{if(I+=T.toString(),!T.includes(`
|
|
16
16
|
`))return;let N=I.toString().split(`
|
|
17
|
-
`).filter(Boolean).map(p=>{try{return JSON.parse(p)}catch{z.log("Could not parse line",p)}return null}).filter(Boolean);I="";let w=[],m=!1;N.forEach(p=>{if(p?.duration_ms&&(y=p.duration_ms,m=!0),p?.type==="local_shell_call")d[p.call_id]=p;else if(p?.type==="local_shell_call_output"){let u=
|
|
17
|
+
`).filter(Boolean).map(p=>{try{return JSON.parse(p)}catch{z.log("Could not parse line",p)}return null}).filter(Boolean);I="";let w=[],m=!1;N.forEach(p=>{if(p?.duration_ms&&(y=p.duration_ms,m=!0),p?.type==="local_shell_call")d[p.call_id]=p;else if(p?.type==="local_shell_call_output"){let u=Yt(d[p.call_id],p);u.id=h,h+=1,u&&(c.push(u),f.push(u),w.push(u),m=!0)}else p?.type==="message"&&p.role==="assistant"?R=p.content.map(u=>u.text).join(`
|
|
18
18
|
`):p?.type==="message"&&p.role==="system"&&(x=p.content.map(u=>u.text).join(`
|
|
19
|
-
`))}),m&&(r?.({steps:f,duration:y}),n?.({steps:w,duration:y}))}),await P.catch(T=>{({error:x,result:R}=
|
|
19
|
+
`))}),m&&(r?.({steps:f,duration:y}),n?.({steps:w,duration:y}))}),await P.catch(T=>{({error:x,result:R}=jt({catchError:T,runCmd:P,error:x,result:R,runnerName:"Codex"}))}),{steps:c,duration:y,result:await W({initialResult:R,agentName:Qe,hasError:!!x}),error:J({error:x,agentName:Qe}),isRetryableError:X(x)}}var et=async()=>{let e=Pe.join(Mt.homedir(),".codex");await Ut.rm(e,{recursive:!0,force:!0})},Gt={[K]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},o1:{maxTokens:1e5},"o1-mini":{maxTokens:65536},"o3-mini":{maxTokens:1e5},"gpt-image-1":{},"dall-e-2":{},"dall-e-3":{}}},[q]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768}}},pro:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768}}},[V]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},"o3-mini":{maxTokens:16e3}}},[H]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},"o3-mini":{maxTokens:16e3}}}},Bt=new Set(["bash","-lc"]),Yt=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!Bt.has(s)),n=r?`Running \`${r.join(" ")}\``:void 0,o;try{o=JSON.parse(t.output).output?.trim(),o&&(o=`\`\`\`
|
|
20
20
|
${o.trim()}
|
|
21
|
-
\`\`\``)}catch(s){z.error("Could not decode outputMsg",s,t.output)}return{title:n,message:o}};import
|
|
21
|
+
\`\`\``)}catch(s){z.error("Could not decode outputMsg",s,t.output)}return{title:n,message:o}};import Ht from"fs/promises";import qt from"os";import pe from"path";import j from"process";var oe=_("runner_gemini"),tt="Gemini CLI",Kt=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(oe.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(oe.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(oe.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0})),Vt={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 Oe({config:e,netlify:t,persistSteps:r,sendSteps:n,aiGateway:o}){let{accountType:s,prompt:a,modelVersionOverrides:l}=e,{model:i}=e;if(o){let{token:m,url:p}=o;if(!m||!p)throw new Error("No token or url provided from AI Gateway");let u=Wt[s];if(!u)throw new Error(`Gemini is not supported for the account type ${s}`);if(i&&!u?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(l?.gemini){let E=l?.gemini?.[s];E&&(i=E)}j.env.GEMINI_API_KEY=m,j.env.GOOGLE_GEMINI_BASE_URL=p}else if(!j.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let f=[],c=[],d=[],h={},y=0,R=0,x,g,A=pe.join(j.cwd(),"node_modules"),C=[pe.join(j.env.NODE_PATH||A,".bin/gemini"),...i?["--model",i]:[],"--yolo","-p",a],P=`${j.env.NVM_BIN}/node`;oe.log(`Running ${P} ${C.join(" ")}`);let I=t.utils.run(P,C,{all:!0,env:j.env});I.stdin?.end();let T=ce(()=>{r?.({steps:f,duration:R}),n?.({steps:c,duration:R}),c=[]},250),N=(m,p)=>{m.id=y,y+=1,d.push(m),f.push(m),c.push(m),p||T.flush(),T(),p&&T.flush()},w="";return I.all.on("data",m=>{if(w+=m.toString(),!m.includes(`
|
|
22
22
|
`))return;let p=w.toString().split(`
|
|
23
|
-
`).filter(Boolean).map(u=>{try{if(u.startsWith("[API Error")){let E=u.match(/\[api error: (.+?)]$/i)?.[1];return{type:"error",value:qe(E,!1)?.error?.message||E||"Gemini encountered error"}}return JSON.parse(u)}catch{}return null}).filter(Boolean);w="",p.forEach(u=>{switch(u.type){case"thought":{let E=u.value;N({title:E?.subject??"Thinking...",message:E?.description},!0);break}case"content":{u.value&&N({message:u.value});break}case"tool_call_request":{let E=u.value,D=
|
|
23
|
+
`).filter(Boolean).map(u=>{try{if(u.startsWith("[API Error")){let E=u.match(/\[api error: (.+?)]$/i)?.[1];return{type:"error",value:qe(E,!1)?.error?.message||E||"Gemini encountered error"}}return JSON.parse(u)}catch{}return null}).filter(Boolean);w="",p.forEach(u=>{switch(u.type){case"thought":{let E=u.value;N({title:E?.subject??"Thinking...",message:E?.description},!0);break}case"content":{u.value&&N({message:u.value});break}case"tool_call_request":{let E=u.value,D=Vt[E.name]??E.name,U=E.args?.path||E.args?.absolute_path,k=U&&pe.relative(j.cwd(),U),L=E.args?.command,mt={title:[D,k&&`\`${k}\``,L&&`\`${L}\``].filter(Boolean).join(" ")};h[E.callId]=mt,T.flush();break}case"tool_result":{let E=u.value,D=h[E.callId];if(D){let U=[E.resultDisplay,E.responseParts?.functionResponse?.response?.output].find(k=>typeof k=="string"&&k);U&&(D.message=`\`\`\`
|
|
24
24
|
${U.trim()}
|
|
25
|
-
\`\`\``),N(D,!0)}break}case"result":{R=u.duration_ms,x=u.value,[d,f,c].forEach(E=>{E[E.length-1]?.message===x&&E.pop()});break}case"error":{g=u.value;break}case"finished":break;default:{oe.warn("Unhandled message type:",u.type);break}}})}),await I.catch(m=>{({error:g,result:x}=
|
|
25
|
+
\`\`\``),N(D,!0)}break}case"result":{R=u.duration_ms,x=u.value,[d,f,c].forEach(E=>{E[E.length-1]?.message===x&&E.pop()});break}case"error":{g=u.value;break}case"finished":break;default:{oe.warn("Unhandled message type:",u.type);break}}})}),await I.catch(m=>{({error:g,result:x}=Kt({catchError:m,runCmd:I,error:g,result:x,runnerName:"Gemini"}))}),T.flush(),{steps:d,duration:R,result:await W({initialResult:x,agentName:tt,hasError:!!g}),error:J({error:g,agentName:tt}),isRetryableError:X(g)}}var rt=async()=>{let e=pe.join(qt.homedir(),".gemini");await Ht.rm(e,{recursive:!0,force:!0})},Wt={[K]:{models:{"gemini-1.5-flash":{maxTokens:8192},"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-1.5-pro":{maxTokens:8192},"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:65536},"gemini-2.5-flash-lite":{maxTokens:65536},"gemini-2.5-pro":{maxTokens:65536},"imagen-4.0-generate-001":{},"veo-3.0-generate-preview":{}}},pro:{models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[q]:{models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[V]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}},[H]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}}};var Jt={codex:{runner:ve,clean:et},claude:{runner:Ae,clean:Ze},gemini:{runner:Oe,clean:rt}},nt=Jt;var ot=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:n})=>{let o=Xt();return ie(o,"init-stage",async s=>{let a=performance.now();s?.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,"init.runnerVersion":n||"unknown"});let l=nt[e.runner];if(!l)throw s?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let i=zt({apiToken:r});Le(i);let f=e.useGateway?await je({netlify:i,config:e}):void 0;s?.setAttributes({"init.aiGateway.created":!!f}),e.validateAgent&&e.errorLogsPath&&s?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let c=He(({steps:y=[],duration:R})=>{let x=[...y];return y.length=0,Y(e.id,e.sessionId,{steps:x,duration:R})},t),d;e.hasRepo?e.sha?(d=e.sha,s?.setAttributes({"init.sha.source":"provided"})):(d=await Je(i),await ue(e.id,{sha:d}),s?.setAttributes({"init.sha.source":"current_commit"})):(d=await Xe(i),s?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let h=performance.now()-a;return s?.setAttributes({"init.sha":d||"unknown","init.duration.ms":h,"init.status":"success"}),{aiGateway:f,context:i,persistSteps:c,runner:l,sha:d}})},zt=({apiToken:e})=>({constants:{NETLIFY_API_HOST:fe.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||fe.env.NETLIFY_API_TOKEN,SITE_ID:fe.env.SITE_ID,FUNCTIONS_DIST:fe.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:Be}});import Zt from"crypto";import G from"fs/promises";import O from"path";import $ from"process";var v=_("context"),Qt=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:$.env.NETLIFY_TEAM_ID,userId:$.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:$.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},er=10,tr=async e=>{let{name:t,ext:r}=O.parse(e),n=e,o=O.join($.cwd(),b,n),s=0;for(;await rr(o);){if(s>=er)throw new Error("Failed to generate context file");n=`${t}-${Zt.randomUUID().slice(0,5)}${r}`,o=O.join($.cwd(),b,n),s+=1}return n},rr=async e=>{try{return await G.access(e),!0}catch{return!1}},nr=async()=>{try{v.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 v.warn("Invalid response structure: missing or invalid consumers array"),null;let r=t.consumers.find(n=>n&&typeof n=="object"&&n.key==="catchall-consumer");return r?!r.contextScopes||typeof r.contextScopes!="object"?(v.warn("Catchall consumer missing or invalid contextScopes"),null):r:(v.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?v.warn("Netlify features context request timed out"):v.warn("Failed to fetch Netlify features context:",e.message),null}},or=async(e,t)=>{try{let r=await fetch(e,{signal:AbortSignal.timeout(1e4)});if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let n=await r.text();return await G.writeFile(t,n,"utf-8"),!0}catch(r){return r.name==="AbortError"?v.warn(`Download timeout for ${e}`):v.warn(`Failed to download context file ${e}:`,r.message),!1}},me=null,sr=async()=>{if(me)return me;let e=await nr();if(!e)return[];let t=O.join($.cwd(),b,Ie);await G.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([o,s])=>{if(!s||typeof s!="object"||!s.endpoint||!s.scope)return v.warn(`Invalid scope data for ${o}, skipping...`),null;let a=`${o}.md`,l=O.join(t,a),i=O.join(b,Ie,a);return v.log(`Downloading ${s.scope} context...`),await or(s.endpoint,l)?(v.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:o}):null});return me=(await Promise.all(r)).filter(o=>o!==null),me},st=async({cliPath:e,netlify:t,config:r,buildErrorContext:n})=>{let o=Qt(t),s=await tr(Ye),a=O.join($.cwd(),b);await G.mkdir(a,{recursive:!0});let l=O.join(b,s),i=O.join($.cwd(),l),f=O.join($.cwd(),b,re);try{await G.unlink(f),v.log(`Deleted old results file: ${f}`)}catch{}let c=n?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
|
|
26
26
|
Your task is to analyze and fix the build errors.
|
|
27
27
|
Don't apply techniques of reverting changes. Apply fixes related to errors.
|
|
28
28
|
Don't try to run build by yourself. Just fix the errors.
|
|
@@ -54,7 +54,7 @@ ${C.response}
|
|
|
54
54
|
`)}
|
|
55
55
|
|
|
56
56
|
</session_history_context>
|
|
57
|
-
`}let y=await
|
|
57
|
+
`}let y=await sr(),R="";y.length>0&&(R=`
|
|
58
58
|
<netlify_features_context>
|
|
59
59
|
If the user request is explicitly related to a specific Netlify feature (e.g., Netlify Forms, Netlify Functions, etc.), you MUST review the relevant documentation below in addition to reviewing the project files.
|
|
60
60
|
DO NOT force the use of any Netlify feature if the user request does not explicitly require it or if the project has alternative implementations in place already.
|
|
@@ -120,12 +120,12 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
120
120
|
</request>
|
|
121
121
|
|
|
122
122
|
Use the following file for the complete context of the ask, the environment, and what's available. ${i} You MUST READ ALL OF IT. Make sure to read it first. Never cite or paraphrase private context.
|
|
123
|
-
`),x};var
|
|
123
|
+
`),x};var ir=_("prompt"),it=async({cliPath:e,config:t,netlify:r,buildErrorContext:n})=>{let o=await st({cliPath:e,config:t,netlify:r,buildErrorContext:n});return process.env.AGENT_RUNNER_DEBUG&&ir.log("Contextful Prompt:",o),{prompt:o}};var at=_("inference_stage"),lt=2,ge=async e=>{let{cliPath:t,config:r,context:n,buildErrors:o,runner:s,persistSteps:a,aiGateway:l,attempt:i}=e;Ge();let{prompt:f}=await it({cliPath:t,config:r,buildErrorContext:ar(o),netlify:n}),c={...r,prompt:f},d=await s({aiGateway:l,config:c,netlify:n,persistSteps:a});if(await a.flush(),d.error){if(at.error("Runner failed",{stepsCount:d.steps.length,duration:d.duration,error:d.error,isRetryableError:d.isRetryableError}),d.error&&d.isRetryableError&&(!i||i<lt))return at.log(`Retrying inference stage, attempt ${i} of ${lt}...`),await new Promise(y=>setTimeout(y,5e3)),{runnerResult:(await ge({...e,attempt:(i||1)+1})).runnerResult};throw new Error(d.error)}return{runnerResult:d}},ar=e=>!e||e.length===0?"":`
|
|
124
124
|
Deploy failed failed. Here are the errors to review on the latest build:
|
|
125
125
|
|
|
126
126
|
Below are all of the logs with potential issues that we extracted. Some of them may be false positives, discern them carefully and ensure fixes are relevant.
|
|
127
127
|
|
|
128
128
|
${e.pop()}
|
|
129
|
-
`;import
|
|
130
|
-
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(l){throw se.error("Failed to create preview deploy via CLI:",l),l}};var he=_("deploy_stage"),ke=async({cliPath:e,config:t,context:r,result:n,filter:o})=>{let s=await We({config:t,netlify:r});if(!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:l,diffBinary:i,resultDiffBinary:f}=s,c=!0;he.log("Preview deploy condition check:",{resultUndefined:n===void 0,resultType:typeof n,hasChanges:c,wouldCreatePreview:n!==void 0&&c});let d=null;if(n!==void 0&&c)try{let h;try{let y=await Fe(t.id,t.sessionId);y?.title&&(h=y.title)}catch(y){he.warn("Failed to fetch session title, using fallback message:",y.message)}d=await ut({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:h,skipBuild:!1,deploySubdomain:Ke(t.id,
|
|
129
|
+
`;import lr from"process";var se=_("deploy"),ut=async({netlify:e,hasRepo:t,skipBuild:r,message:n="Agent Preview",deploySubdomain:o,cliPath:s,filter:a})=>{try{let l=["deploy","--message",`"${n}"`,"--json","--draft","--verbose"];t||(se.log("Deploy: Uploading source zip"),l.push("--upload-source-zip")),o&&l.push("--alias",o),a&&l.push("--filter",a),r?(se.log("Deploy: Skipping build"),l.push("--no-build")):l.push("--context","deploy-preview");let i=s||"netlify";se.log(`Running: ${i} ${l.join(" ")}`);let f=await e.utils.run(i,l,{stdio:["ignore","pipe","pipe"]}),c=JSON.parse(f.stdout.trim());se.log(`
|
|
130
|
+
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(l){throw se.error("Failed to create preview deploy via CLI:",l),l}};var he=_("deploy_stage"),ke=async({cliPath:e,config:t,context:r,result:n,filter:o})=>{let s=await We({config:t,netlify:r});if(!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:l,diffBinary:i,resultDiffBinary:f}=s,c=!0;he.log("Preview deploy condition check:",{resultUndefined:n===void 0,resultType:typeof n,hasChanges:c,wouldCreatePreview:n!==void 0&&c});let d=null;if(n!==void 0&&c)try{let h;try{let y=await Fe(t.id,t.sessionId);y?.title&&(h=y.title)}catch(y){he.warn("Failed to fetch session title, using fallback message:",y.message)}d=await ut({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:h,skipBuild:!1,deploySubdomain:Ke(t.id,lr.env.SITE_NAME),filter:o})}catch(h){return he.warn("Failed to create preview deploy (continuing with agent run):",h),{diff:a,resultDiff:l,hasChanges:c,previewInfo:null,diffBinary:i,resultDiffBinary:f,deployError:h instanceof Error?h.message:String(h)}}return he.log("Git status",{hasDiff:!!a,hasChanges:c}),{diff:a,resultDiff:l,hasChanges:c,previewInfo:d,diffBinary:i,resultDiffBinary:f}};async function ct(e,t){let{maxRetries:r,baseDelay:n,onRetry:o}=t,s;for(let a=1;a<=r;a++)try{return await e()}catch(l){if(s=l,a===r)throw s;o&&o(a,s),await new Promise(i=>setTimeout(i,n*a))}throw s}var Z=_("cleanup_stage"),dt=async({config:e,diff:t,result:r,duration:n,resultDiff:o,diffBinary:s,resultDiffBinary:a,previewInfo:l})=>{let i={result_diff:t,result:r||"Done",duration:n,result_diff_binary:s};return l&&l.deployId&&(i.deploy_id=l.deployId),l&&l.sourceZipFilename&&(i.result_zip_file_name=l.sourceZipFilename),o||a?(Z.log("Updating total agent result diff"),await ue(e.id,{result_diff:o,result_diff_binary:a})):Z.log("No total result diff, not updating"),Z.log("Updated agent runner with result"),await ct(()=>Y(e.id,e.sessionId,i),{maxRetries:3,baseDelay:1e3,onRetry:(f,c)=>{Z.error(`Error updating agent runner session (attempt ${f}):`,c),Z.log("Retrying...")}}),Z.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as cr}from"@netlify/otel";var dr=ur(import.meta.url),pt=dr("../package.json"),ft=_("pipeline_index"),ye=3,To=async({config:e,apiToken:t,cliPath:r="netlify",cwd:n,errorLogsPath:o,filter:s,traceExporterUrl:a})=>{let l;try{await $e(pt.version,e.id,a);let i=cr(),f,{aiGateway:c,context:d,persistSteps:h,runner:y,sha:R}=await ot({config:e,apiToken:t,cliPath:r,cwd:n,errorLogsPath:o,filter:s,runnerVersion:pt.version});l=y.clean,e.sha=R;let{runnerResult:x}=await ge({cliPath:r,config:e,context:d,runner:y.runner,persistSteps:h,aiGateway:c}),g=await ke({cliPath:r,config:e,context:d,result:x.result,filter:s}),A=x,C=[];if(g.hasChanges&&g.deployError){C.push(De(g.deployError));let m=1;for(;m<=ye&&!g.previewInfo;)ft.log(`Deploy attempt had errors. Retrying. ${m}/${ye}`),await ie(i,"stage-deploy",async p=>{p?.setAttributes({"stage.attempt":m});let{runnerResult:u}=await ge({cliPath:r,config:e,context:d,runner:y.runner,persistSteps:h,aiGateway:c,buildErrors:C});A={...u,steps:[...A.steps||[],...u.steps||[]],duration:(A.duration||0)+(u.duration||0)},g=await ke({cliPath:r,config:e,context:d,result:u.result,filter:s}),g.deployError&&C.push(g.deployError),m++});m>ye&&!g.previewInfo&&(f=new Error(`Deploy validation failed after ${ye} attempts`))}let{diff:P,resultDiff:I,previewInfo:T,diffBinary:N,resultDiffBinary:w}=g;if(await dt({config:e,diff:P,result:A.result,duration:A.duration,resultDiff:I,diffBinary:N,resultDiffBinary:w,previewInfo:T}),f)throw f;await y.clean?.()}catch(i){ft.error("Got error while running pipeline",i),await l?.();let f=i instanceof Error&&i.message;throw await Y(e.id,e.sessionId,{result:f||"Encountered error when running agent",state:"error"}),i}};export{To as runPipeline};
|
|
131
131
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@netlify/agent-runner-cli",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "1.
|
|
4
|
+
"version": "1.31.0-alpha",
|
|
5
5
|
"description": "CLI tool for running Netlify agents",
|
|
6
6
|
"main": "./dist/index.js",
|
|
7
7
|
"types": "./dist/index.d.ts",
|
|
@@ -71,7 +71,7 @@
|
|
|
71
71
|
"vitest": "^1.5.0"
|
|
72
72
|
},
|
|
73
73
|
"dependencies": {
|
|
74
|
-
"@anthropic-ai/claude-code": "
|
|
74
|
+
"@anthropic-ai/claude-code": "2.0.0",
|
|
75
75
|
"@google/gemini-cli": "0.1.17",
|
|
76
76
|
"@netlify/otel": "^4.0.0",
|
|
77
77
|
"@opentelemetry/exporter-trace-otlp-grpc": "^0.57.0",
|