@netlify/agent-runner-cli 1.42.0 → 1.43.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 +17 -17
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/bin.js
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import qe from"process";import Qr from"minimist";import{createRequire as qr}from"module";import{createTracerProvider as jt}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as Ke}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as Yt}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as Bt}from"@netlify/otel";import{propagation as Ve,context as We,W3CTraceContextPropagator as Ht}from"@netlify/otel/opentelemetry";import{OTLPTraceExporter as qt}from"@opentelemetry/exporter-trace-otlp-grpc";function y(e){let t=!process.env.VITEST;return{log:(...r)=>{t&&console.log(`[AR]-[${e}]`,...r)},error:(...r)=>{t&&console.error(`[AR]-[ERROR]-[${e}]`,...r)},warn:(...r)=>{t&&console.warn(`[AR]-[WARN]-[${e}]`,...r)},info:(...r)=>{t&&console.info(`[AR]-[${e}]`,...r)},debug:(...r)=>{t&&console.debug(`[AR]-[DEBUG]-[${e}]`,...r)}}}var Ne=y("tracing"),Je=async(e,t,r)=>(await jt({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new Ke(new xe),new Ke(new qt({url:r.exporterUrl}))],instrumentations:[new Yt({skipHeaders:!0})]}),r.traceparent?(Ve.setGlobalPropagator(new Ht),Ve.extract(We.active(),{traceparent:r.traceparent,isRemote:!0})):We.active());function b(e,t,r){return Ne.log(`\u23F3 TRACE: ${t} starting...`),Bt(e,t,r)}var xe=class{export(t,r){for(let o of t)this.logSpan(o);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,o=t.attributes,n=[];for(let[u,i]of Object.entries(o))u.includes("duration")&&typeof i=="number"?n.push(`${u}=${i.toFixed(2)}ms`):n.push(`${u}=${i}`);let s=t.status?.code===2?"\u274C":"\u2705",
|
|
2
|
+
import qe from"process";import Qr from"minimist";import{createRequire as qr}from"module";import{createTracerProvider as jt}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as Ke}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as Yt}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as Bt}from"@netlify/otel";import{propagation as Ve,context as We,W3CTraceContextPropagator as Ht}from"@netlify/otel/opentelemetry";import{OTLPTraceExporter as qt}from"@opentelemetry/exporter-trace-otlp-grpc";function y(e){let t=!process.env.VITEST;return{log:(...r)=>{t&&console.log(`[AR]-[${e}]`,...r)},error:(...r)=>{t&&console.error(`[AR]-[ERROR]-[${e}]`,...r)},warn:(...r)=>{t&&console.warn(`[AR]-[WARN]-[${e}]`,...r)},info:(...r)=>{t&&console.info(`[AR]-[${e}]`,...r)},debug:(...r)=>{t&&console.debug(`[AR]-[DEBUG]-[${e}]`,...r)}}}var Ne=y("tracing"),Je=async(e,t,r)=>(await jt({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new Ke(new xe),new Ke(new qt({url:r.exporterUrl}))],instrumentations:[new Yt({skipHeaders:!0})]}),r.traceparent?(Ve.setGlobalPropagator(new Ht),Ve.extract(We.active(),{traceparent:r.traceparent,isRemote:!0})):We.active());function b(e,t,r){return Ne.log(`\u23F3 TRACE: ${t} starting...`),Bt(e,t,r)}var xe=class{export(t,r){for(let o of t)this.logSpan(o);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,o=t.attributes,n=[];for(let[u,i]of Object.entries(o))u.includes("duration")&&typeof i=="number"?n.push(`${u}=${i.toFixed(2)}ms`):n.push(`${u}=${i}`);let s=t.status?.code===2?"\u274C":"\u2705",a=n.length>0?` [${n.join(", ")}]`:"";Ne.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${a}`),t.status?.code===2&&t.status.message&&Ne.log(` \u274C Error: ${t.status.message}`)}};var Kt=["error","failed","exception","fatal","panic","abort","crash"];function Xe(e){let t=e.split(`
|
|
3
3
|
`),r=[],o=-1,n=0;for(;n<t.length;){let u=t[n].slice(0,500).toLowerCase();if(Kt.some(p=>u.includes(p))){let p=Math.max(0,n-10,o+1),c=Math.min(t.length-1,n+20),d=[];for(let f=p;f<=c;f++)d.push(t[f]);r.push(d.join(`
|
|
4
|
-
`)),o=c,n=c+1}else n++}if(r.length===0)return e;let s=r.map((
|
|
5
|
-
${
|
|
4
|
+
`)),o=c,n=c+1}else n++}if(r.length===0)return e;let s=r.map((a,u)=>`<extracted_error_chunk order="${u+1}">
|
|
5
|
+
${a}
|
|
6
6
|
</extracted_error_chunk>`).join(`
|
|
7
7
|
|
|
8
|
-
`);return s.length>e.length*.8?e:s}import _e from"process";import{getTracer as Sr}from"@netlify/otel";import le from"process";var ue=le.env.NETLIFY_API_URL,ce=le.env.NETLIFY_API_TOKEN,oe=y("api"),pe=async(e,t={})=>{if(!ue||!ce)throw new Error("No API URL or token");let r=new URL(e,ue),o={...t,headers:{...t.headers,Authorization:`Bearer ${ce}`}};le.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let n=await fetch(r,o),s=n.ok&&n.status<=299;if(le.env.AGENT_RUNNERS_DEBUG==="true")oe.log(`Response headers for ${r}:`),n.headers.forEach((u,i)=>{oe.log(` ${i}: ${u}`)});else{let u=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");oe.log(`Request ID for ${r}: ${u||"N/A"}`)}if(s||oe.error(`Got status ${n.status} for request ${r}`),t.raw){if(!s)throw n;return n}let l=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!s)throw l;return l},ze=e=>{oe.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(ue=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(ce=e.constants.NETLIFY_API_TOKEN)},Ze=()=>({apiUrl:ue,token:ce}),de=(e,t)=>pe(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),G=(e,t,r)=>pe(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var Qe=(e,t)=>pe(`/api/v1/agent_runners/${e}/sessions/${t}`),et=(e,t,r)=>pe(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}});var X=y("ai_gateway"),ve=null;var tt=async()=>{if(ve)return ve;X.log("Fetching available AI gateway providers");let e=await fetch(`${Ze().apiUrl}/api/v1/ai-gateway/providers`);if(!e.ok)throw new Error(`Failed to fetch AI gateway providers: ${e.statusText}`);let t=await e.json();return ve=t,X.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},Vt=async(e,t)=>{let o=(await tt()).providers[e];if(!o)return X.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return X.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},rt=async({netlify:e,config:t})=>{let r,o,n,s,l=e.constants?.SITE_ID;if(!l)throw new Error("No site id");let u=async()=>{clearTimeout(n),X.log("Requesting AI gateway information");let i=await et(l,t.id,t.sessionId);if({token:r,url:s}=i,o=i.expires_at?i.expires_at*1e3:void 0,X.log("Got AI gateway information",{token:!!r,expiresAt:o,url:s}),o){let p=o-Date.now()-6e4;p>0&&(n=setTimeout(()=>{u()},p))}};return await Promise.all([u(),tt()]),{get url(){return s},get token(){return r},isModelAvailableForProvider:Vt}};import K from"process";import{execa as Qt,execaCommand as Rn}from"execa";import{Transform as Wt}from"stream";var Jt=new Set(["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","NETLIFY_AGENT_RUNNER_ID","NETLIFY_AGENT_RUNNER_SESSION_ID","NETLIFY_AGENT_RUNNER_PROMPT","NETLIFY_AGENT_RUNNER_AGENT","NETLIFY_AGENT_RUNNER_MODEL","NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED","NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED","ERROR_LOGS_PATH","NETLIFY_AGENT_RUNNER_CONTEXT","NETLIFY_AGENT_RUNNER_HAS_REPO","NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED","NETLIFY_AGENT_RUNNER_SHA","NETLIFY_TEAM_TYPE","AGENT_RUNNERS_DEBUG","NETLIFY_TEAM_ID","NETLIFY_AGENT_RUNNER_USER_ID","SITE_NAME"]),Xt=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function zt(){return Object.entries(process.env).filter(([e,t])=>!(!t||Jt.has(e)||Xt.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function M(e){if(typeof e!="string")return e;let t=zt();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(Zt(o),"g");r=r.replace(n,"******")}),r}function Zt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var z=class extends Wt{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),s=M(n);o(null,s)}};function nt(){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(o,n,s){let l=typeof o=="string"?M(o):o;return typeof n=="function"?t(l,n):t(l,n,s)},process.stderr.write=function(o,n,s){let l=typeof o=="string"?M(o):o;return typeof n=="function"?r(l,n):r(l,n,s)}}var se=null,ot=e=>(se&&se.destroy(),se=new q({totalAllowedTime:e}),se),st=()=>se;var q=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,o)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let n=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),s=null,l=null;o!==void 0&&(l=new Promise((u,i)=>{s=setTimeout(()=>{i(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return l?await Promise.race([r(),l]):await r()}finally{n(),s&&clearTimeout(s)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var fe=y("shell"),Ae=new Set,er={preferLocal:!0},it=(e,t,r)=>{let[o,n]=tr(t,r),s={...er,...n},l=Qt(e,o,s);return rr(l,s),or(l),l};var tr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},rr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(K.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new z).pipe(K.stdout),e.stdout?.pipe(new z).pipe(K.stdout),e.stderr?.pipe(new z).pipe(K.stderr);return}e.stdout?.pipe(K.stdout),e.stderr?.pipe(K.stderr)},at=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(K.kill(-e.pid,t),fe.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return fe.error("Error killing process:",r),!1}},nr=e=>at(e,"SIGKILL"),or=e=>{Ae.add(e);let t=st();if(t){let r=t.onTimesUp(()=>{fe.log(`Global timer expired, killing process ${e.pid}`),at(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(fe.log(`Force killing process ${e.pid} after timeout`),nr(e))},5e3)});e.on("exit",()=>{Ae.delete(e),r()}),e.on("error",()=>{Ae.delete(e),r()})}};var lt="netlify-agent-runner-context.md",Se="task-history",Ce="netlify-context",F=".netlify",Z="results.md",be="assets",Pe="other",Oe="personal";var De="enterprise",Le="free",ut=[Oe,"pro",De,Le];var ct=y("utils"),sr=e=>new Promise(t=>{setTimeout(t,e)}),pt=(e,t=3e3)=>{let r=!1,o=null,n=[],s=null,l=(...u)=>{if(r)return o=u,new Promise(c=>{n.push(c)});r=!0;let i,p=new Promise(c=>{i=c});return s=(async()=>{await Promise.resolve();let c=await e(...u);for(i(c);;){if(await sr(t),!o)return r=!1,s=null,c;let d=o,f=n;o=null,n=[],c=await e(...d),f.forEach(_=>{_(c)})}})(),p};return l.flush=async()=>{if((r||o)&&s)return await s,l.flush()},l},ge=(e,t,r=!1)=>{let o=null,n=null,s=null,l=function(...u){n=u,s=this;let i=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(s,n),n=null,s=null)},t),i&&(e.apply(s,n),n=null,s=null)};return l.cancel=()=>{clearTimeout(o),o=null,n=null,s=null},l.flush=()=>{if(o){clearTimeout(o);let u=n,i=s;o=null,n=null,s=null,e.apply(i,u)}},l},me=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):ct.error("Could not parse JSON",o))}},dt=(e,t)=>{let n=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let u=`--${t}${n}`;if(u.length>55)return"";let i=60-u.length;if(i<=0)return"";if(i>=s.length+6){let p=Math.min(i-s.length,e.length);return`${s}${e.slice(0,p)}`}return e.slice(0,i)},ir=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!ut.some(t=>t in e),ft=()=>{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,o])=>{if(o){let n=`NETLIFY_FF_AGENT_RUNNER_${r.toUpperCase()}_VERSION`;try{let s=JSON.parse(o);ir(s)&&(e[r]=s)}catch(s){let u=s instanceof SyntaxError?"Invalid JSON":s.message;ct.error(`Could not parse ${r} model version override from ${n}: ${u}`)}}}),e};import{Buffer as gt}from"buffer";import ar from"path";var mt=async({config:e,netlify:t})=>{let r=await ur(t),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};let s=await cr(n);await t.utils.run("git",["add",".",...s]);let l={stdio:["ignore","pipe","pipe"]},i=(await t.utils.run("git",["diff","--staged"],l)).stdout;if(o=!!i,!o)return{hasChanges:!1,ignored:s};let c=(await t.utils.run("git",["diff","--staged","--binary"],l)).stdout,d,f;if(e.sha){await t.utils.run("git",["commit","-m","Agent runner"]),d=(await t.utils.run("git",["diff",e.sha,"HEAD"],l)).stdout;let T=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"],l)).stdout;d!==T&&(f=gt.from(T).toString("base64"))}let _={hasChanges:!0,diff:i,resultDiff:d,ignored:s};return i!==c&&(_.diffBinary=gt.from(c).toString("base64")),f&&(_.resultDiffBinary=f),_},lr=["?? mise.toml","?? deno.lock",/\?\? .+?\.log/],ur=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
|
|
8
|
+
`);return s.length>e.length*.8?e:s}import _e from"process";import{getTracer as Sr}from"@netlify/otel";import le from"process";var ue=le.env.NETLIFY_API_URL,ce=le.env.NETLIFY_API_TOKEN,oe=y("api"),pe=async(e,t={})=>{if(!ue||!ce)throw new Error("No API URL or token");let r=new URL(e,ue),o={...t,headers:{...t.headers,Authorization:`Bearer ${ce}`}};le.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let n=await fetch(r,o),s=n.ok&&n.status<=299;if(le.env.AGENT_RUNNERS_DEBUG==="true")oe.log(`Response headers for ${r}:`),n.headers.forEach((u,i)=>{oe.log(` ${i}: ${u}`)});else{let u=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");oe.log(`Request ID for ${r}: ${u||"N/A"}`)}if(s||oe.error(`Got status ${n.status} for request ${r}`),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},ze=e=>{oe.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(ue=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(ce=e.constants.NETLIFY_API_TOKEN)},Ze=()=>({apiUrl:ue,token:ce}),de=(e,t)=>pe(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),G=(e,t,r)=>pe(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var Qe=(e,t)=>pe(`/api/v1/agent_runners/${e}/sessions/${t}`),et=(e,t,r)=>pe(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}});var X=y("ai_gateway"),ve=null;var tt=async()=>{if(ve)return ve;X.log("Fetching available AI gateway providers");let e=await fetch(`${Ze().apiUrl}/api/v1/ai-gateway/providers`);if(!e.ok)throw new Error(`Failed to fetch AI gateway providers: ${e.statusText}`);let t=await e.json();return ve=t,X.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},Vt=async(e,t)=>{let o=(await tt()).providers[e];if(!o)return X.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return X.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},rt=async({netlify:e,config:t})=>{let r,o,n,s,a=e.constants?.SITE_ID;if(!a)throw new Error("No site id");let u=async()=>{clearTimeout(n),X.log("Requesting AI gateway information");let i=await et(a,t.id,t.sessionId);if({token:r,url:s}=i,o=i.expires_at?i.expires_at*1e3:void 0,X.log("Got AI gateway information",{token:!!r,expiresAt:o,url:s}),o){let p=o-Date.now()-6e4;p>0&&(n=setTimeout(()=>{u()},p))}};return await Promise.all([u(),tt()]),{get url(){return s},get token(){return r},isModelAvailableForProvider:Vt}};import K from"process";import{execa as Qt,execaCommand as Rn}from"execa";import{Transform as Wt}from"stream";var Jt=new Set(["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","NETLIFY_AGENT_RUNNER_ID","NETLIFY_AGENT_RUNNER_SESSION_ID","NETLIFY_AGENT_RUNNER_PROMPT","NETLIFY_AGENT_RUNNER_AGENT","NETLIFY_AGENT_RUNNER_MODEL","NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED","NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED","ERROR_LOGS_PATH","NETLIFY_AGENT_RUNNER_CONTEXT","NETLIFY_AGENT_RUNNER_HAS_REPO","NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED","NETLIFY_AGENT_RUNNER_SHA","NETLIFY_TEAM_TYPE","AGENT_RUNNERS_DEBUG","NETLIFY_TEAM_ID","NETLIFY_AGENT_RUNNER_USER_ID","SITE_NAME"]),Xt=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function zt(){return Object.entries(process.env).filter(([e,t])=>!(!t||Jt.has(e)||Xt.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function M(e){if(typeof e!="string")return e;let t=zt();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(Zt(o),"g");r=r.replace(n,"******")}),r}function Zt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var z=class extends Wt{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),s=M(n);o(null,s)}};function nt(){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(o,n,s){let a=typeof o=="string"?M(o):o;return typeof n=="function"?t(a,n):t(a,n,s)},process.stderr.write=function(o,n,s){let a=typeof o=="string"?M(o):o;return typeof n=="function"?r(a,n):r(a,n,s)}}var se=null,ot=e=>(se&&se.destroy(),se=new q({totalAllowedTime:e}),se),st=()=>se;var q=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,o)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let n=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),s=null,a=null;o!==void 0&&(a=new Promise((u,i)=>{s=setTimeout(()=>{i(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return a?await Promise.race([r(),a]):await r()}finally{n(),s&&clearTimeout(s)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var fe=y("shell"),Ae=new Set,er={preferLocal:!0},it=(e,t,r)=>{let[o,n]=tr(t,r),s={...er,...n},a=Qt(e,o,s);return rr(a,s),or(a),a};var tr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},rr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(K.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new z).pipe(K.stdout),e.stdout?.pipe(new z).pipe(K.stdout),e.stderr?.pipe(new z).pipe(K.stderr);return}e.stdout?.pipe(K.stdout),e.stderr?.pipe(K.stderr)},at=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(K.kill(-e.pid,t),fe.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return fe.error("Error killing process:",r),!1}},nr=e=>at(e,"SIGKILL"),or=e=>{Ae.add(e);let t=st();if(t){let r=t.onTimesUp(()=>{fe.log(`Global timer expired, killing process ${e.pid}`),at(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(fe.log(`Force killing process ${e.pid} after timeout`),nr(e))},5e3)});e.on("exit",()=>{Ae.delete(e),r()}),e.on("error",()=>{Ae.delete(e),r()})}};var lt="netlify-agent-runner-context.md",Se="task-history",Ce="netlify-context",F=".netlify",Z="results.md",be="assets",Pe="other",Oe="personal";var De="enterprise",Le="free",ut=[Oe,"pro",De,Le];var ct=y("utils"),sr=e=>new Promise(t=>{setTimeout(t,e)}),pt=(e,t=3e3)=>{let r=!1,o=null,n=[],s=null,a=(...u)=>{if(r)return o=u,new Promise(c=>{n.push(c)});r=!0;let i,p=new Promise(c=>{i=c});return s=(async()=>{await Promise.resolve();let c=await e(...u);for(i(c);;){if(await sr(t),!o)return r=!1,s=null,c;let d=o,f=n;o=null,n=[],c=await e(...d),f.forEach(_=>{_(c)})}})(),p};return a.flush=async()=>{if((r||o)&&s)return await s,a.flush()},a},ge=(e,t,r=!1)=>{let o=null,n=null,s=null,a=function(...u){n=u,s=this;let i=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(s,n),n=null,s=null)},t),i&&(e.apply(s,n),n=null,s=null)};return a.cancel=()=>{clearTimeout(o),o=null,n=null,s=null},a.flush=()=>{if(o){clearTimeout(o);let u=n,i=s;o=null,n=null,s=null,e.apply(i,u)}},a},me=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):ct.error("Could not parse JSON",o))}},dt=(e,t)=>{let n=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let u=`--${t}${n}`;if(u.length>55)return"";let i=60-u.length;if(i<=0)return"";if(i>=s.length+6){let p=Math.min(i-s.length,e.length);return`${s}${e.slice(0,p)}`}return e.slice(0,i)},ir=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!ut.some(t=>t in e),ft=()=>{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,o])=>{if(o){let n=`NETLIFY_FF_AGENT_RUNNER_${r.toUpperCase()}_VERSION`;try{let s=JSON.parse(o);ir(s)&&(e[r]=s)}catch(s){let u=s instanceof SyntaxError?"Invalid JSON":s.message;ct.error(`Could not parse ${r} model version override from ${n}: ${u}`)}}}),e};import{Buffer as gt}from"buffer";import ar from"path";var mt=async({config:e,netlify:t})=>{let r=await ur(t),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};let s=await cr(n);await t.utils.run("git",["add",".",...s]);let a={stdio:["ignore","pipe","pipe"]},i=(await t.utils.run("git",["diff","--staged"],a)).stdout;if(o=!!i,!o)return{hasChanges:!1,ignored:s};let c=(await t.utils.run("git",["diff","--staged","--binary"],a)).stdout,d,f;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 T=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;d!==T&&(f=gt.from(T).toString("base64"))}let _={hasChanges:!0,diff:i,resultDiff:d,ignored:s};return i!==c&&(_.diffBinary=gt.from(c).toString("base64")),f&&(_.resultDiffBinary=f),_},lr=["?? mise.toml","?? deno.lock",/\?\? .+?\.log/],ur=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
|
|
9
9
|
`).filter(n=>!lr.some(s=>s instanceof RegExp?s.test(n):n===s))).length!==0,status:t.stdout}};var ht=async e=>{let{stdout:t}=await e.utils.run("git",["rev-parse","HEAD"]);return t.trim()},Et=async e=>{let{stdout:t}=await e.utils.run("git",["rev-list","--max-parents=0","HEAD"]);return t.trim()},cr=async e=>{let t=[".netlify","mise.toml","deno.lock","node_modules"],r=[];return e.split(`
|
|
10
|
-
`).forEach(o=>{t.forEach(s=>{[`?? ${s}`,`?? ${s}${ar.sep}`].some(u=>o.startsWith(u))&&r.push(`:!${s}`)});let n=o.match(/\?\? (.+?)\.log$/)?.[1];n&&r.push(`:!${n}.log`)}),r};import dr from"fs/promises";import fr from"os";import Ee from"path";import Y from"process";import gr from"readline";import Fe from"path";import pr from"fs/promises";var $e=y("agent-output-utils");async function Q({initialResult:e,agentName:t,hasError:r}){let o="",n=Fe.join(process.cwd(),F,Z);try{let s=await pr.readFile(n,"utf-8");s&&(o=s,$e.log(`Pulled result from ${Fe.relative(process.cwd(),n)}`))}catch{$e.log(`No results file found at ${Fe.relative(process.cwd(),n)}`)}return o||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function ee({error:e,agentName:t}){let r=e&&typeof e=="object"?JSON.stringify(e):e,o=r?.replace(/\s+/g," ").trim().toLowerCase()||"",n="";return o?.includes("ai gateway is not available for your account")||o?.includes("ai gateway is not enabled for your account")?n="AI Gateway is currently not available on your account. Please confirm your account meets the criteria for using Agent Runners and AI Gateway and that your account has remaining AI Gateway inference credits available. Reach out to Netlify support if this is unexpected.":o?.includes("error when talking to gemini api")?n="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":(o?.includes("connection closed prematurely")||o?.includes("499")&&t.toLowerCase().includes("gemini"))&&(n=`The ${t} models were currently overloaded. Please try again or use a different available agent.`),o?.includes("request timed out")&&(n=`The ${t} API request's have timed out. Please try again or use a different available agent.`),o?.includes("network error")&&(n=`The ${t} agent is having network issues. Please try again or use a different available agent.`),n&&$e.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function te(e){if(!e)return!1;let r=(e&&typeof e=="object"?JSON.stringify(e):e)?.replace(/\s+/g," ").trim().toLowerCase()||"";return!!(r?.includes("error when talking to gemini api")||r?.includes("499")||r?.includes("connection closed prematurely")||r?.includes("request timed out")||r?.includes("network error"))}var $=y("runner_claude"),yt="Claude Code",he="claude-sonnet-4-5-20250929",mr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>($.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?($.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):($.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function Ue({config:e,netlify:t,persistSteps:r,aiGateway:o}){let n=e,{accountType:s,prompt:
|
|
10
|
+
`).forEach(o=>{t.forEach(s=>{[`?? ${s}`,`?? ${s}${ar.sep}`].some(u=>o.startsWith(u))&&r.push(`:!${s}`)});let n=o.match(/\?\? (.+?)\.log$/)?.[1];n&&r.push(`:!${n}.log`)}),r};import dr from"fs/promises";import fr from"os";import Ee from"path";import Y from"process";import gr from"readline";import Fe from"path";import pr from"fs/promises";var $e=y("agent-output-utils");async function Q({initialResult:e,agentName:t,hasError:r}){let o="",n=Fe.join(process.cwd(),F,Z);try{let s=await pr.readFile(n,"utf-8");s&&(o=s,$e.log(`Pulled result from ${Fe.relative(process.cwd(),n)}`))}catch{$e.log(`No results file found at ${Fe.relative(process.cwd(),n)}`)}return o||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function ee({error:e,agentName:t}){let r=e&&typeof e=="object"?JSON.stringify(e):e,o=r?.replace(/\s+/g," ").trim().toLowerCase()||"",n="";return o?.includes("ai gateway is not available for your account")||o?.includes("ai gateway is not enabled for your account")?n="AI Gateway is currently not available on your account. Please confirm your account meets the criteria for using Agent Runners and AI Gateway and that your account has remaining AI Gateway inference credits available. Reach out to Netlify support if this is unexpected.":o?.includes("error when talking to gemini api")?n="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":(o?.includes("connection closed prematurely")||o?.includes("499")&&t.toLowerCase().includes("gemini"))&&(n=`The ${t} models were currently overloaded. Please try again or use a different available agent.`),o?.includes("request timed out")&&(n=`The ${t} API request's have timed out. Please try again or use a different available agent.`),o?.includes("network error")&&(n=`The ${t} agent is having network issues. Please try again or use a different available agent.`),n&&$e.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function te(e){if(!e)return!1;let r=(e&&typeof e=="object"?JSON.stringify(e):e)?.replace(/\s+/g," ").trim().toLowerCase()||"";return!!(r?.includes("error when talking to gemini api")||r?.includes("499")||r?.includes("connection closed prematurely")||r?.includes("request timed out")||r?.includes("network error"))}var $=y("runner_claude"),yt="Claude Code",he="claude-sonnet-4-5-20250929",mr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>($.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?($.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):($.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function Ue({config:e,netlify:t,persistSteps:r,aiGateway:o}){let n=e,{accountType:s,prompt:a,modelVersionOverrides:u}=n,{model:i}=n;if(o){let{token:I,url:m}=o;if(!I||!m)throw new Error("No token or url provided from AI Gateway");if(u?.claude){let l=u?.claude?.[s];if(l){if(!await o.isModelAvailableForProvider("anthropic",l))throw new Error(`Model override '${l}' is not available for anthropic provider`);i=l}}else if(i){if(!await o.isModelAvailableForProvider("anthropic",i))throw new Error(`Model '${i}' is not available for anthropic provider`)}else await o.isModelAvailableForProvider("anthropic",he)?(i=he,$.log(`Using default model: ${he}`)):$.log(`Default model ${he} is not available, proceeding without model specification`);Y.env.ANTHROPIC_API_KEY=I,Y.env.ANTHROPIC_BASE_URL=m}else if(!Y.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let p=[],c=[],d={},f=0,_=0,g,E,T=Ee.join(Y.cwd(),"node_modules"),N=[Ee.join(Y.env.NODE_PATH||T,".bin/claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...i?["--model",i]:[],"-p",a],x=`${Y.env.NVM_BIN}/node`;$.log(`Running ${x} ${N.join(" ")}`);let A=t.utils.run(x,N,{all:!0,env:Y.env});A.stdin?.end();let v=ge(()=>{r?.({steps:p,duration:_})},250),R=(I,m)=>{let l={...I,id:f};f+=1,c.push(l),p.push(l),m||v.flush(),v(),m&&v.flush()},w=gr.createInterface({input:A.all});return w.on("error",I=>{$.error("Readline interface error",{error:I.message,stack:I.stack})}),w.on("line",I=>{let m=null;try{m=JSON.parse(I)}catch{$.log("Could not parse line",I)}Array.isArray(m?.message?.content)?m.message.content.forEach(l=>{switch(l.type){case"text":{l.text&&R({message:l.text});break}case"image":{typeof l.source=="object"&&l.source&&l.source.type==="base64"&&l.source.media_type?R({message:``}):$.log(`Unsupported image type ${l.source?.type}`,l.source);break}case"tool_use":{if(l.name==="Task"){let h=l.input?.description&&`\`${l.input.description}\``;R({title:[l.name,h].filter(Boolean).join(" ")})}else l.id&&(d[l.id]=l);v.flush();break}case"tool_result":{let h=l.tool_use_id?d[l.tool_use_id]:void 0,S;if(h){let k=h.input?.file_path&&Ee.relative(Y.cwd(),h.input.file_path),C=k&&`\`${k}\``;S=[h.name,C].filter(Boolean).join(" ")}let j=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(h?.name||""),L;if(typeof l.content=="string")L=l.content;else if(Array.isArray(l.content)){let k=[];l.content.forEach(C=>{C?.type==="text"&&typeof C.text=="string"?k.push(C.text):C?.type==="image"&&typeof C.source=="object"&&C.source?C.source.type==="base64"&&C.source.media_type?k.push(``):$.log(`Unsupported image type ${C.source.type}`,C.source):$.log(`Unsupported block type ${C?.type}`)}),L=k.join(`
|
|
11
11
|
|
|
12
12
|
`)}j&&L&&(L=`\`\`\`
|
|
13
13
|
${L.trim()}
|
|
14
|
-
\`\`\``),R({title:S,message:L},!0);break}case"thinking":{
|
|
15
|
-
`):w?.type==="message"&&w.role==="system"&&(E=w.content.map(
|
|
14
|
+
\`\`\``),R({title:S,message:L},!0);break}case"thinking":{l.thinking&&R({title:"Thinking",message:l.thinking},!0);break}default:$.log(`Message content type is not supported ${l.type}`,l)}}):m?.type==="result"&&(_=m.duration_ms||0,m.is_error?E=m.result:g=m.result,[c,p].forEach(l=>{l[l.length-1]?.message===g&&l.pop()}))}),await A.catch(I=>{({error:E,result:g}=mr({catchError:I,runCmd:A,error:E,result:g,runnerName:"Claude"}))}),w.close(),v.flush(),{steps:c,duration:_,result:await Q({initialResult:g,agentName:yt,hasError:!!E}),error:ee({error:E,agentName:yt}),isRetryableError:te(E)}}var _t=async()=>{let e=Ee.join(fr.homedir(),".claude");await dr.rm(e,{recursive:!0,force:!0})};import hr from"fs/promises";import Er from"os";import ke from"path";import V from"process";import yr from"readline";var W=y("runner_codex"),Tt="Codex CLI",_r=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(W.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(W.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(W.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function Ge({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:a,modelVersionOverrides:u}=e,{model:i}=e;if(n){let{token:R,url:w}=n;if(!R||!w)throw new Error("No token or url provided from AI Gateway");if(u?.codex){let I=u?.codex?.[s];if(I){if(!await n.isModelAvailableForProvider("openai",I))throw new Error(`Model override '${I}' is not available for openai provider`);i=I}}else if(i&&!await n.isModelAvailableForProvider("openai",i))throw new Error(`Model '${i}' is not available for openai provider`);V.env.OPENAI_API_KEY=R,V.env.OPENAI_BASE_URL=w}else if(!V.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let p=[],c=[],d={},f=0,_=0,g,E,T=ke.join(V.cwd(),"node_modules"),N=[ke.join(V.env.NODE_PATH||T,".bin/codex"),"--approval-mode","full-auto",n?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...i?["--model",i]:[],"-q",a].filter(Boolean),x=`${V.env.NVM_BIN}/node`;W.log(`Running ${x} ${N.join(" ")}`);let A=t.utils.run(x,N,{all:!0,env:{...V.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),v=yr.createInterface({input:A.all});return v.on("error",R=>{W.error("Readline interface error",{error:R.message,stack:R.stack})}),v.on("line",R=>{let w=null;try{w=JSON.parse(R)}catch{W.log("Could not parse line",R);return}let I=[],m=!1;if(w?.duration_ms&&(_=w.duration_ms,m=!0),w?.type==="local_shell_call")d[w.call_id]=w;else if(w?.type==="local_shell_call_output"){let l=wr(d[w.call_id],w);l&&(l.id=f,f+=1,c.push(l),p.push(l),I.push(l),m=!0)}else w?.type==="message"&&w.role==="assistant"?g=w.content.map(l=>l.text).join(`
|
|
15
|
+
`):w?.type==="message"&&w.role==="system"&&(E=w.content.map(l=>l.text).join(`
|
|
16
16
|
`));m&&(r?.({steps:p,duration:_}),o?.({steps:I,duration:_}))}),await A.catch(R=>{let w=_r({catchError:R,runCmd:A,error:E,result:g,runnerName:"Codex"});E=w.error,g=w.result}),v.close(),{steps:c,duration:_,result:await Q({initialResult:g,agentName:Tt,hasError:!!E}),error:ee({error:E,agentName:Tt}),isRetryableError:te(E)}}var wt=async()=>{let e=ke.join(Er.homedir(),".codex");await hr.rm(e,{recursive:!0,force:!0})},Tr=new Set(["bash","-lc"]),wr=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!Tr.has(s)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
|
|
17
17
|
${n.trim()}
|
|
18
|
-
\`\`\``)}catch(s){W.error("Could not decode outputMsg",s,t.output)}return{title:o,message:n}};import Ir from"fs/promises";import Rr from"os";import ye from"path";import B from"process";import Nr from"readline";var re=y("runner_gemini"),It="Gemini CLI",xr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(re.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(re.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(re.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),vr={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 Me({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:
|
|
18
|
+
\`\`\``)}catch(s){W.error("Could not decode outputMsg",s,t.output)}return{title:o,message:n}};import Ir from"fs/promises";import Rr from"os";import ye from"path";import B from"process";import Nr from"readline";var re=y("runner_gemini"),It="Gemini CLI",xr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(re.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(re.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(re.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),vr={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 Me({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:a,modelVersionOverrides:u}=e,{model:i}=e;if(n){let{token:m,url:l}=n;if(!m||!l)throw new Error("No token or url provided from AI Gateway");if(u?.gemini){let h=u?.gemini?.[s];if(h){if(!await n.isModelAvailableForProvider("gemini",h))throw new Error(`Model override '${h}' is not available for gemini provider`);i=h}}else if(i&&!await n.isModelAvailableForProvider("gemini",i))throw new Error(`Model '${i}' is not available for gemini provider`);B.env.GEMINI_API_KEY=m,B.env.GOOGLE_GEMINI_BASE_URL=l}else if(!B.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let p=[],c=[],d=[],f={},_=0,g=0,E,T,N=ye.join(B.cwd(),"node_modules"),x=[ye.join(B.env.NODE_PATH||N,".bin/gemini"),...i?["--model",i]:[],"--yolo","-p",a],A=`${B.env.NVM_BIN}/node`;re.log(`Running ${A} ${x.join(" ")}`);let v=t.utils.run(A,x,{all:!0,env:B.env});v.stdin?.end();let R=ge(()=>{r?.({steps:p,duration:g}),o?.({steps:c,duration:g}),c=[]},250),w=(m,l)=>{m.id=_,_+=1,d.push(m),p.push(m),c.push(m),l||R.flush(),R(),l&&R.flush()},I=Nr.createInterface({input:v.all});return I.on("error",m=>{re.error("Readline interface error",{error:m.message,stack:m.stack})}),I.on("line",m=>{let l=null;try{if(m.startsWith("[API Error")){let h=m.match(/\[api error: (.+?)]$/i)?.[1];l={type:"error",value:me(h,!1)?.error?.message||h||"Gemini encountered error"}}else l=JSON.parse(m)}catch{return}if(l)switch(l.type){case"thought":{let h=l.value;w({title:h?.subject??"Thinking...",message:h?.description},!0);break}case"content":{l.value&&w({message:l.value});break}case"tool_call_request":{let h=l.value,S=vr[h.name]??h.name,j=h.args?.path||h.args?.absolute_path,L=j&&ye.relative(B.cwd(),j),k=h.args?.command,Mt={title:[S,L&&`\`${L}\``,k&&`\`${k}\``].filter(Boolean).join(" ")};f[h.callId]=Mt,R.flush();break}case"tool_result":{let h=l.value,S=f[h.callId];if(S){let j=[h.resultDisplay,h.responseParts?.functionResponse?.response?.output].find(L=>typeof L=="string"&&L);j&&(S.message=`\`\`\`
|
|
19
19
|
${j.trim()}
|
|
20
|
-
\`\`\``),w(S,!0)}break}case"result":{g=
|
|
20
|
+
\`\`\``),w(S,!0)}break}case"result":{g=l.duration_ms,E=l.value,[d,p,c].forEach(h=>{h[h.length-1]?.message===E&&h.pop()});break}case"error":{T=l.value;break}case"finished":break;default:{re.warn("Unhandled message type:",l.type);break}}}),await v.catch(m=>{({error:T,result:E}=xr({catchError:m,runCmd:v,error:T,result:E,runnerName:"Gemini"}))}),I.close(),R.flush(),{steps:d,duration:g,result:await Q({initialResult:E,agentName:It,hasError:!!T}),error:ee({error:T,agentName:It}),isRetryableError:te(T)}}var Rt=async()=>{let e=ye.join(Rr.homedir(),".gemini");await Ir.rm(e,{recursive:!0,force:!0})};var Ar={codex:{runner:Ge,clean:wt},claude:{runner:Ue,clean:_t},gemini:{runner:Me,clean:Rt}},Nt=Ar;var xt=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>await b(Sr(),"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,"init.runnerVersion":o||"unknown"});let a=Nt[e.runner];if(!a)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let u=Cr({apiToken:r});ze(u);let i=e.useGateway?await rt({netlify:u,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!i}),e.validateAgent&&e.errorLogsPath&&n?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let p=pt(({steps:f=[],duration:_})=>{let g=f.map(E=>({...E,title:E.title?M(E.title):void 0,message:E.message?M(E.message):void 0}));return f.length=0,G(e.id,e.sessionId,{steps:g,duration:_})},t),c;e.hasRepo?e.sha?(c=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(c=await ht(u),await de(e.id,{sha:c}),n?.setAttributes({"init.sha.source":"current_commit"})):(c=await Et(u),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:i,context:u,persistSteps:p,runner:a,sha:c}}),Cr=({apiToken:e})=>({constants:{NETLIFY_API_HOST:_e.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||_e.env.NETLIFY_API_TOKEN,SITE_ID:_e.env.SITE_ID,FUNCTIONS_DIST:_e.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:it}});import{getTracer as je}from"@netlify/otel";import br from"crypto";import H from"fs/promises";import D from"path";import U from"process";var P=y("context"),Pr=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:U.env.NETLIFY_TEAM_ID,userId:U.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:U.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},Or=10,Dr=async e=>{let{name:t,ext:r}=D.parse(e),o=e,n=D.join(U.cwd(),F,o),s=0;for(;await Lr(n);){if(s>=Or)throw new Error("Failed to generate context file");o=`${t}-${br.randomUUID().slice(0,5)}${r}`,n=D.join(U.cwd(),F,o),s+=1}return o},Lr=async e=>{try{return await H.access(e),!0}catch{return!1}},Fr=async()=>{try{P.log("Fetching Netlify features context...");let e=await fetch("https://docs.netlify.com/ai-context/context-consumers",{signal:AbortSignal.timeout(1e4)});if(!e.ok)throw new Error(`Failed to fetch context consumers: ${e.status} ${e.statusText}`);let t=await e.json();if(!t||typeof t!="object"||!Array.isArray(t.consumers))return P.warn("Invalid response structure: missing or invalid consumers array"),null;let r=t.consumers.find(o=>o&&typeof o=="object"&&o.key==="catchall-consumer");return r?!r.contextScopes||typeof r.contextScopes!="object"?(P.warn("Catchall consumer missing or invalid contextScopes"),null):r:(P.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?P.warn("Netlify features context request timed out"):P.warn("Failed to fetch Netlify features context:",e.message),null}},$r=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 o=await r.text();return await H.writeFile(t,o,"utf-8"),!0}catch(r){return r.name==="AbortError"?P.warn(`Download timeout for ${e}`):P.warn(`Failed to download context file ${e}:`,r.message),!1}},Te=null,Ur=async()=>{if(Te)return Te;let e=await Fr();if(!e)return[];let t=D.join(U.cwd(),F,Ce);await H.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([n,s])=>{if(!s||typeof s!="object"||!s.endpoint||!s.scope)return P.warn(`Invalid scope data for ${n}, skipping...`),null;let a=`${n}.md`,u=D.join(t,a),i=D.join(F,Ce,a);return P.log(`Downloading ${s.scope} context...`),await $r(s.endpoint,u)?(P.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:n}):null});return Te=(await Promise.all(r)).filter(n=>n!==null),Te},vt=async({cliPath:e,netlify:t,config:r,buildErrorContext:o})=>{let n=Pr(t),s=await Dr(lt),a=D.join(U.cwd(),F);await H.mkdir(a,{recursive:!0});let u=D.join(F,s),i=D.join(U.cwd(),u),p=D.join(U.cwd(),F,Z);try{await H.unlink(p),P.log(`Deleted old results file: ${p}`)}catch{}let c=o?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
|
|
21
21
|
Your task is to analyze and fix the build errors.
|
|
22
22
|
Don't apply techniques of reverting changes. Apply fixes related to errors.
|
|
23
23
|
Don't try to run build by yourself. Just fix the errors.
|
|
@@ -72,15 +72,15 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
72
72
|
<requirements>
|
|
73
73
|
<responses>
|
|
74
74
|
- Do not speak in first person. You may speak as "the agent".
|
|
75
|
-
- When work is complete, write a changes summary in ${
|
|
76
|
-
- If the user's request is informational in nature (asking for output, status, information, or analysis rather than asking you to make changes), write the requested information directly to the ${
|
|
75
|
+
- When work is complete, write a changes summary in ${a}/${Z} as a standalone PR description. Explain what was accomplished and why (avoid too many implementation details), assuming the reader has no prior context. Use past tense and write in prose without calling it a "PR", "Changelog", etc. This is the core of a PR message or summary page that already has a heading.
|
|
76
|
+
- If the user's request is informational in nature (asking for output, status, information, or analysis rather than asking you to make changes), write the requested information directly to the ${a}/${Z} file.
|
|
77
77
|
- Do not attempt to create git commits, PRs, etc. directly. You can use git to review information if required but the system that runs this agent will handle creating PRs or commits of the changes it performs.
|
|
78
78
|
- NEVER look into the \`.git\` folder
|
|
79
79
|
- NEVER print potentially sensitive values (like secrets) in the planning output or results
|
|
80
80
|
</responses>
|
|
81
81
|
<attachements>
|
|
82
|
-
- for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${
|
|
83
|
-
- move assets from ${
|
|
82
|
+
- for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${a}/${be} folder
|
|
83
|
+
- move assets from ${a}/${be} folder to the project assets folder if they are referenced in a code or applied changes
|
|
84
84
|
</attachements>
|
|
85
85
|
${d}
|
|
86
86
|
</requirements>
|
|
@@ -118,15 +118,15 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
118
118
|
</request>
|
|
119
119
|
|
|
120
120
|
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.
|
|
121
|
-
`),E};var kr=y("prompt"),At=async({cliPath:e,config:t,netlify:r,buildErrorContext:o})=>{let n=await vt({cliPath:e,config:t,netlify:r,buildErrorContext:o});return process.env.AGENT_RUNNER_DEBUG&&kr.log("Contextful Prompt:",n),{prompt:n}};var we=y("inference_stage"),St=5,Ie=async e=>await b(je(),"inference-stage",async t=>{let{cliPath:r,config:o,context:n,buildErrors:s,runner:
|
|
121
|
+
`),E};var kr=y("prompt"),At=async({cliPath:e,config:t,netlify:r,buildErrorContext:o})=>{let n=await vt({cliPath:e,config:t,netlify:r,buildErrorContext:o});return process.env.AGENT_RUNNER_DEBUG&&kr.log("Contextful Prompt:",n),{prompt:n}};var we=y("inference_stage"),St=5,Ie=async e=>await b(je(),"inference-stage",async t=>{let{cliPath:r,config:o,context:n,buildErrors:s,runner:a,persistSteps:u,aiGateway:i,attempt:p,contextPrefix:c}=e;t?.setAttributes({"inference.attempt":p}),we.log(`Running inference stage, attempt ${p} of ${St}`),nt();let{prompt:d}=await b(je(),"compose-prompt",async()=>await At({cliPath:r,config:o,buildErrorContext:Gr(s),netlify:n})),f=`
|
|
122
122
|
${c||""}
|
|
123
123
|
${d}
|
|
124
|
-
`.trim(),_={...o,prompt:f},g=await b(je(),`run-${o.runner}`,async()=>await
|
|
124
|
+
`.trim(),_={...o,prompt:f},g=await b(je(),`run-${o.runner}`,async()=>await a({aiGateway:i,config:_,netlify:n,persistSteps:u}));if(g.result&&(g.result=M(g.result)),g.error&&(g.error=M(g.error)),await u.flush(),g.error){if(we.error("Runner failed",{stepsCount:g.steps.length,duration:g.duration,error:g.error,isRetryableError:g.isRetryableError,attempt:p||1}),g.isRetryableError&&(!p||p<St))return we.log("Retrying inference stage"),await new Promise(T=>setTimeout(T,5e3)),{runnerResult:(await Ie({...e,attempt:(p||1)+1,contextPrefix:"<important> The agent has already started on this work but ran into networking errors trying to complete it. Please continue from where it left off (you can use git commands to see what's currently changed thus far) and do not start over. Here is the full prompt for context: </important>"})).runnerResult};throw we.log("Do not retry inference stage"),new Error(g.error)}return{runnerResult:g}}),Gr=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 Yr from"process";import{getTracer as Ye}from"@netlify/otel";import{getTracer as Mr}from"@netlify/otel";var ie=y("deploy"),Ct=async e=>await b(Mr(),"create-preview-deploy",async t=>jr(e,t)),jr=async({netlify:e,hasRepo:t,skipBuild:r,message:o="Agent Preview",deploySubdomain:n,cliPath:s,filter:
|
|
131
|
-
Preview deploy created successfully:`,{deployId:d.deploy_id,deployUrl:d.deploy_url,siteId:d.site_id});let f={deployId:d.deploy_id,previewUrl:d.deploy_url,logsUrl:d.logs,siteId:d.site_id};return t||(f.sourceZipFilename=d.source_zip_filename),f}catch(i){throw ie.error("Failed to create preview deploy via CLI:",i),u?.setAttributes({success:!1,error:i.message}),i}};var ae=y("deploy_stage"),Be=async e=>await b(Ye(),"run-deploy-stage",async()=>Br(e)),Br=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let s=await b(Ye(),"get-runner-diffs",async()=>await mt({config:t,netlify:r}));if(ae.info("Resolved git",{hasChanges:s.hasChanges,ignored:s.ignored??[]}),!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:
|
|
130
|
+
`;import Yr from"process";import{getTracer as Ye}from"@netlify/otel";import{getTracer as Mr}from"@netlify/otel";var ie=y("deploy"),Ct=async e=>await b(Mr(),"create-preview-deploy",async t=>jr(e,t)),jr=async({netlify:e,hasRepo:t,skipBuild:r,message:o="Agent Preview",deploySubdomain:n,cliPath:s,filter:a},u)=>{try{let i=["deploy","--message",`"${o}"`,"--json","--draft","--verbose"];t||(ie.log("Deploy: Uploading source zip"),i.push("--upload-source-zip")),n&&i.push("--alias",n),a&&i.push("--filter",a),r?(ie.log("Deploy: Skipping build"),i.push("--no-build")):i.push("--context","deploy-preview");let p=s||"netlify";ie.log(`Running: ${p} ${i.join(" ")}`),u?.setAttributes({cmd:p,args:i});let c=await e.utils.run(p,i,{stdio:["ignore","pipe","pipe"]}),d=JSON.parse(c.stdout.trim());u?.setAttributes({success:!0,deployId:d.deploy_id,deployUrl:d.deploy_url,siteId:d.site_id}),ie.log(`
|
|
131
|
+
Preview deploy created successfully:`,{deployId:d.deploy_id,deployUrl:d.deploy_url,siteId:d.site_id});let f={deployId:d.deploy_id,previewUrl:d.deploy_url,logsUrl:d.logs,siteId:d.site_id};return t||(f.sourceZipFilename=d.source_zip_filename),f}catch(i){throw ie.error("Failed to create preview deploy via CLI:",i),u?.setAttributes({success:!1,error:i.message}),i}};var ae=y("deploy_stage"),Be=async e=>await b(Ye(),"run-deploy-stage",async()=>Br(e)),Br=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let s=await b(Ye(),"get-runner-diffs",async()=>await mt({config:t,netlify:r}));if(ae.info("Resolved git",{hasChanges:s.hasChanges,ignored:s.ignored??[]}),!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:u,diffBinary:i,resultDiffBinary:p}=s,c=!0;ae.log("Preview deploy condition check:",{resultUndefined:o===void 0,resultType:typeof o,hasChanges:c,wouldCreatePreview:o!==void 0&&c});let d=null;if(o!==void 0&&c)try{let f;try{let _=await b(Ye(),"get-runner-session",async()=>await Qe(t.id,t.sessionId));_?.title&&(f=_.title)}catch(_){ae.warn("Failed to fetch session title, using fallback message:",_.message)}await G(t.id,t.sessionId,{steps:[{title:"Deploying the run preview"}]}),d=await Ct({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:f,skipBuild:!1,deploySubdomain:dt(t.id,Yr.env.SITE_NAME),filter:n})}catch(f){return ae.warn("Failed to create preview deploy (continuing with agent run):",f),{diff:a,resultDiff:u,hasChanges:c,previewInfo:null,diffBinary:i,resultDiffBinary:p,deployError:f instanceof Error?f.message:String(f)}}return ae.log("Git status",{hasDiff:!!a,hasChanges:c}),{diff:a,resultDiff:u,hasChanges:c,previewInfo:d,diffBinary:i,resultDiffBinary:p}};import{getTracer as He}from"@netlify/otel";async function bt(e,t){let{maxRetries:r,baseDelay:o,onRetry:n}=t,s;for(let a=1;a<=r;a++)try{return await e()}catch(u){if(s=u,a===r)throw s;n&&n(a,s),await new Promise(i=>setTimeout(i,o*a))}throw s}var ne=y("cleanup_stage"),Pt=async e=>await b(He(),"cleanup-stage",async()=>Hr(e)),Hr=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:s,resultDiffBinary:a,previewInfo:u})=>{let i={result_diff:t,result:r||"Done",duration:o,result_diff_binary:s};return u&&u.deployId&&(i.deploy_id=u.deployId),u&&u.sourceZipFilename&&(i.result_zip_file_name=u.sourceZipFilename),n||a?(i.cumulative_diff=n,i.cumulative_diff_binary=a,ne.log("Updating total agent result diff"),await b(He(),"update-runner",async()=>{await de(e.id,{result_diff:n,result_diff_binary:a})})):ne.log("No total result diff, not updating"),ne.log("Updated agent runner with result"),await bt(async()=>await b(He(),"update-runner-session",()=>G(e.id,e.sessionId,i)),{maxRetries:3,baseDelay:1e3,onRetry:(p,c)=>{ne.error(`Error updating agent runner session (attempt ${p}):`,c),ne.log("Retrying...")}}),ne.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as Ot,shutdownTracers as Kr,withActiveSpan as Dt}from"@netlify/otel";var Vr=qr(import.meta.url),Lt=Vr("../package.json"),Ft=y("pipeline_index"),Re=3,$t=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:s,tracing:a={}})=>{let u,{withStageTimer:i}=ot(q.timeUnits.hours(4)),p=await Je(Lt.version,e.id,a);try{await Dt(Ot(),"run-pipeline",{},p,async()=>{let c,{aiGateway:d,context:f,persistSteps:_,runner:g,sha:E}=await i("init",()=>xt({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:s,runnerVersion:Lt.version}),q.timeUnits.minutes(10));u=g.clean,e.sha=E;let{runnerResult:T}=await i("inference",()=>Ie({cliPath:r,config:e,context:f,runner:g.runner,persistSteps:_,aiGateway:d}));await G(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let N=await i("deploy",()=>Be({cliPath:r,config:e,context:f,result:T.result,filter:s})),x=T,A=[];if(N.hasChanges&&N.deployError){A.push(Xe(N.deployError));let l=1;for(;l<=Re&&!N.previewInfo;)Ft.log(`Deploy attempt had errors. Retrying. ${l}/${Re}`),await Dt(Ot(),"deploy-stage",async h=>{h?.setAttributes({"stage.attempt":l});let{runnerResult:S}=await i(`inference-retry-${l}`,()=>Ie({cliPath:r,config:e,context:f,runner:g.runner,persistSteps:_,aiGateway:d,buildErrors:A}));x={...S,steps:[...x.steps||[],...S.steps||[]],duration:(x.duration||0)+(S.duration||0)},N=await i(`deploy-retry-${l}`,()=>Be({cliPath:r,config:e,context:f,result:S.result,filter:s})),N.deployError&&A.push(N.deployError),l++});l>Re&&!N.previewInfo&&(c=new Error(`Deploy validation failed after ${Re} attempts`))}let{diff:v,resultDiff:R,previewInfo:w,diffBinary:I,resultDiffBinary:m}=N;if(await i("cleanup",()=>Pt({config:e,diff:v,result:x.result,duration:x.duration,resultDiff:R,diffBinary:I,resultDiffBinary:m,previewInfo:w}),q.timeUnits.minutes(10)),c)throw c;await g.clean?.()})}catch(c){Ft.error("Got error while running pipeline",c),await u?.();let d=c instanceof Error&&c.message;throw await G(e.id,e.sessionId,{result:d||"Encountered error when running agent",state:"error"}),c}finally{await Kr()}};import O from"process";var Jr="claude",Xr=e=>(e??[]).filter(t=>t.request&&t.response),zr=e=>(e??[]).filter(t=>t.site_context),Ut=y("config"),kt=()=>{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,o=O.env.NETLIFY_AGENT_RUNNER_PROMPT;if(!o)throw new Error("Prompt is not provided");let n=O.env.NETLIFY_AGENT_RUNNER_AGENT||Jr,s=O.env.NETLIFY_AGENT_RUNNER_MODEL,a=O.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED==="1",u=O.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED==="1",i=O.env.ERROR_LOGS_PATH,p=me(O.env.NETLIFY_AGENT_RUNNER_CONTEXT,!0,Ut),c=Xr(p),d=zr(p),f=O.env.NETLIFY_AGENT_RUNNER_HAS_REPO!=="0",_=!O.env.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED,g=O.env.NETLIFY_AGENT_RUNNER_SHA,E=Zr(),T=ft(),N={id:e,sessionId:t,resultBranch:r,prompt:o,runner:n,model:s,validateAgent:a,errorLogsPath:i,sessionHistoryContext:c,siteContext:d,hasRepo:f,useGateway:_,sha:g,accountType:E,validateAgentWithBuild:u,modelVersionOverrides:T};return Ut.log({fullConfig:N}),N},Zr=()=>{let e=O.env.NETLIFY_TEAM_TYPE;return e?e.includes("personal")?Oe:e.includes("pro")?"pro":e.startsWith("enterprise")?De:e.startsWith("free")?Le:Pe:Pe};var Gt=y("bin_cmd"),J=Qr(qe.argv.slice(2),{string:["auth","cwd","cli-path","error-logs-path","filter","trace-exporter-url","traceparent"]});try{let e=kt();await $t({config:e,apiToken:J.auth,cwd:J.cwd,cliPath:J["cli-path"],errorLogsPath:J["error-logs-path"],filter:J.filter,tracing:{exporterUrl:J["trace-exporter-url"],traceparent:J.traceparent}}),Gt.info("Finished agent"),qe.exit(0)}catch(e){Gt.error("Error running agent pipeline:",e),qe.exit(1)}
|
|
132
132
|
//# sourceMappingURL=bin.js.map
|
package/dist/index.js
CHANGED
|
@@ -127,5 +127,5 @@ Below are all of the logs with potential issues that we extracted. Some of them
|
|
|
127
127
|
|
|
128
128
|
${e.pop()}
|
|
129
129
|
`;import br from"process";import{getTracer as Fe}from"@netlify/otel";import{getTracer as Ar}from"@netlify/otel";var oe=w("deploy"),_t=async e=>await C(Ar(),"create-preview-deploy",async t=>Nr(e,t)),Nr=async({netlify:e,hasRepo:t,skipBuild:r,message:o="Agent Preview",deploySubdomain:n,cliPath:s,filter:l},u)=>{try{let i=["deploy","--message",`"${o}"`,"--json","--draft","--verbose"];t||(oe.log("Deploy: Uploading source zip"),i.push("--upload-source-zip")),n&&i.push("--alias",n),l&&i.push("--filter",l),r?(oe.log("Deploy: Skipping build"),i.push("--no-build")):i.push("--context","deploy-preview");let p=s||"netlify";oe.log(`Running: ${p} ${i.join(" ")}`),u?.setAttributes({cmd:p,args:i});let c=await e.utils.run(p,i,{stdio:["ignore","pipe","pipe"]}),d=JSON.parse(c.stdout.trim());u?.setAttributes({success:!0,deployId:d.deploy_id,deployUrl:d.deploy_url,siteId:d.site_id}),oe.log(`
|
|
130
|
-
Preview deploy created successfully:`,{deployId:d.deploy_id,deployUrl:d.deploy_url,siteId:d.site_id});let f={deployId:d.deploy_id,previewUrl:d.deploy_url,logsUrl:d.logs,siteId:d.site_id};return t||(f.sourceZipFilename=d.source_zip_filename),f}catch(i){throw oe.error("Failed to create preview deploy via CLI:",i),u?.setAttributes({success:!1,error:i.message}),i}};var se=w("deploy_stage"),Le=async e=>await C(Fe(),"run-deploy-stage",async()=>Sr(e)),Sr=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let s=await C(Fe(),"get-runner-diffs",async()=>await st({config:t,netlify:r}));if(se.info("Resolved git",{hasChanges:s.hasChanges,ignored:s.ignored??[]}),!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:l,resultDiff:u,diffBinary:i,resultDiffBinary:p}=s,c=!0;se.log("Preview deploy condition check:",{resultUndefined:o===void 0,resultType:typeof o,hasChanges:c,wouldCreatePreview:o!==void 0&&c});let d=null;if(o!==void 0&&c)try{let f;try{let _=await C(Fe(),"get-runner-session",async()=>await qe(t.id,t.sessionId));_?.title&&(f=_.title)}catch(_){se.warn("Failed to fetch session title, using fallback message:",_.message)}await U(t.id,t.sessionId,{steps:[{title:"Deploying the run preview"}]}),d=await _t({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:f,skipBuild:!1,deploySubdomain:nt(t.id,br.env.SITE_NAME),filter:n})}catch(f){return se.warn("Failed to create preview deploy (continuing with agent run):",f),{diff:l,resultDiff:u,hasChanges:c,previewInfo:null,diffBinary:i,resultDiffBinary:p,deployError:f instanceof Error?f.message:String(f)}}return se.log("Git status",{hasDiff:!!l,hasChanges:c}),{diff:l,resultDiff:u,hasChanges:c,previewInfo:d,diffBinary:i,resultDiffBinary:p}};import{getTracer as ke}from"@netlify/otel";async function wt(e,t){let{maxRetries:r,baseDelay:o,onRetry:n}=t,s;for(let l=1;l<=r;l++)try{return await e()}catch(u){if(s=u,l===r)throw s;n&&n(l,s),await new Promise(i=>setTimeout(i,o*l))}throw s}var te=w("cleanup_stage"),Tt=async e=>await C(ke(),"cleanup-stage",async()=>Cr(e)),Cr=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:s,resultDiffBinary:l,previewInfo:u})=>{let i={result_diff:t,result:r||"Done",duration:o,result_diff_binary:s};return u&&u.deployId&&(i.deploy_id=u.deployId),u&&u.sourceZipFilename&&(i.result_zip_file_name=u.sourceZipFilename),n||l?(te.log("Updating total agent result diff"),await C(ke(),"update-runner",async()=>{await ce(e.id,{result_diff:n,result_diff_binary:l})})):te.log("No total result diff, not updating"),te.log("Updated agent runner with result"),await wt(async()=>await C(ke(),"update-runner-session",()=>U(e.id,e.sessionId,i)),{maxRetries:3,baseDelay:1e3,onRetry:(p,c)=>{te.error(`Error updating agent runner session (attempt ${p}):`,c),te.log("Retrying...")}}),te.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as It,shutdownTracers as Or,withActiveSpan as xt}from"@netlify/otel";var $r=Pr(import.meta.url),Rt=$r("../package.json"),vt=w("pipeline_index"),we=3,rs=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:s,tracing:l={}})=>{let u,{withStageTimer:i}=Xe(H.timeUnits.hours(4)),p=await je(Rt.version,e.id,l);try{await xt(It(),"run-pipeline",{},p,async()=>{let c,{aiGateway:d,context:f,persistSteps:_,runner:g,sha:y}=await i("init",()=>gt({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:s,runnerVersion:Rt.version}),H.timeUnits.minutes(10));u=g.clean,e.sha=y;let{runnerResult:T}=await i("inference",()=>_e({cliPath:r,config:e,context:f,runner:g.runner,persistSteps:_,aiGateway:d}));await U(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let R=await i("deploy",()=>Le({cliPath:r,config:e,context:f,result:T.result,filter:s})),v=T,N=[];if(R.hasChanges&&R.deployError){N.push(Be(R.deployError));let a=1;for(;a<=we&&!R.previewInfo;)vt.log(`Deploy attempt had errors. Retrying. ${a}/${we}`),await xt(It(),"deploy-stage",async h=>{h?.setAttributes({"stage.attempt":a});let{runnerResult:b}=await i(`inference-retry-${a}`,()=>_e({cliPath:r,config:e,context:f,runner:g.runner,persistSteps:_,aiGateway:d,buildErrors:N}));v={...b,steps:[...v.steps||[],...b.steps||[]],duration:(v.duration||0)+(b.duration||0)},R=await i(`deploy-retry-${a}`,()=>Le({cliPath:r,config:e,context:f,result:b.result,filter:s})),R.deployError&&N.push(R.deployError),a++});a>we&&!R.previewInfo&&(c=new Error(`Deploy validation failed after ${we} attempts`))}let{diff:A,resultDiff:x,previewInfo:E,diffBinary:I,resultDiffBinary:m}=R;if(await i("cleanup",()=>Tt({config:e,diff:A,result:v.result,duration:v.duration,resultDiff:x,diffBinary:I,resultDiffBinary:m,previewInfo:E}),H.timeUnits.minutes(10)),c)throw c;await g.clean?.()})}catch(c){vt.error("Got error while running pipeline",c),await u?.();let d=c instanceof Error&&c.message;throw await U(e.id,e.sessionId,{result:d||"Encountered error when running agent",state:"error"}),c}finally{await Or()}};export{rs as runPipeline};
|
|
130
|
+
Preview deploy created successfully:`,{deployId:d.deploy_id,deployUrl:d.deploy_url,siteId:d.site_id});let f={deployId:d.deploy_id,previewUrl:d.deploy_url,logsUrl:d.logs,siteId:d.site_id};return t||(f.sourceZipFilename=d.source_zip_filename),f}catch(i){throw oe.error("Failed to create preview deploy via CLI:",i),u?.setAttributes({success:!1,error:i.message}),i}};var se=w("deploy_stage"),Le=async e=>await C(Fe(),"run-deploy-stage",async()=>Sr(e)),Sr=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let s=await C(Fe(),"get-runner-diffs",async()=>await st({config:t,netlify:r}));if(se.info("Resolved git",{hasChanges:s.hasChanges,ignored:s.ignored??[]}),!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:l,resultDiff:u,diffBinary:i,resultDiffBinary:p}=s,c=!0;se.log("Preview deploy condition check:",{resultUndefined:o===void 0,resultType:typeof o,hasChanges:c,wouldCreatePreview:o!==void 0&&c});let d=null;if(o!==void 0&&c)try{let f;try{let _=await C(Fe(),"get-runner-session",async()=>await qe(t.id,t.sessionId));_?.title&&(f=_.title)}catch(_){se.warn("Failed to fetch session title, using fallback message:",_.message)}await U(t.id,t.sessionId,{steps:[{title:"Deploying the run preview"}]}),d=await _t({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:f,skipBuild:!1,deploySubdomain:nt(t.id,br.env.SITE_NAME),filter:n})}catch(f){return se.warn("Failed to create preview deploy (continuing with agent run):",f),{diff:l,resultDiff:u,hasChanges:c,previewInfo:null,diffBinary:i,resultDiffBinary:p,deployError:f instanceof Error?f.message:String(f)}}return se.log("Git status",{hasDiff:!!l,hasChanges:c}),{diff:l,resultDiff:u,hasChanges:c,previewInfo:d,diffBinary:i,resultDiffBinary:p}};import{getTracer as ke}from"@netlify/otel";async function wt(e,t){let{maxRetries:r,baseDelay:o,onRetry:n}=t,s;for(let l=1;l<=r;l++)try{return await e()}catch(u){if(s=u,l===r)throw s;n&&n(l,s),await new Promise(i=>setTimeout(i,o*l))}throw s}var te=w("cleanup_stage"),Tt=async e=>await C(ke(),"cleanup-stage",async()=>Cr(e)),Cr=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:s,resultDiffBinary:l,previewInfo:u})=>{let i={result_diff:t,result:r||"Done",duration:o,result_diff_binary:s};return u&&u.deployId&&(i.deploy_id=u.deployId),u&&u.sourceZipFilename&&(i.result_zip_file_name=u.sourceZipFilename),n||l?(i.cumulative_diff=n,i.cumulative_diff_binary=l,te.log("Updating total agent result diff"),await C(ke(),"update-runner",async()=>{await ce(e.id,{result_diff:n,result_diff_binary:l})})):te.log("No total result diff, not updating"),te.log("Updated agent runner with result"),await wt(async()=>await C(ke(),"update-runner-session",()=>U(e.id,e.sessionId,i)),{maxRetries:3,baseDelay:1e3,onRetry:(p,c)=>{te.error(`Error updating agent runner session (attempt ${p}):`,c),te.log("Retrying...")}}),te.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as It,shutdownTracers as Or,withActiveSpan as xt}from"@netlify/otel";var $r=Pr(import.meta.url),Rt=$r("../package.json"),vt=w("pipeline_index"),we=3,rs=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:s,tracing:l={}})=>{let u,{withStageTimer:i}=Xe(H.timeUnits.hours(4)),p=await je(Rt.version,e.id,l);try{await xt(It(),"run-pipeline",{},p,async()=>{let c,{aiGateway:d,context:f,persistSteps:_,runner:g,sha:y}=await i("init",()=>gt({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:s,runnerVersion:Rt.version}),H.timeUnits.minutes(10));u=g.clean,e.sha=y;let{runnerResult:T}=await i("inference",()=>_e({cliPath:r,config:e,context:f,runner:g.runner,persistSteps:_,aiGateway:d}));await U(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let R=await i("deploy",()=>Le({cliPath:r,config:e,context:f,result:T.result,filter:s})),v=T,N=[];if(R.hasChanges&&R.deployError){N.push(Be(R.deployError));let a=1;for(;a<=we&&!R.previewInfo;)vt.log(`Deploy attempt had errors. Retrying. ${a}/${we}`),await xt(It(),"deploy-stage",async h=>{h?.setAttributes({"stage.attempt":a});let{runnerResult:b}=await i(`inference-retry-${a}`,()=>_e({cliPath:r,config:e,context:f,runner:g.runner,persistSteps:_,aiGateway:d,buildErrors:N}));v={...b,steps:[...v.steps||[],...b.steps||[]],duration:(v.duration||0)+(b.duration||0)},R=await i(`deploy-retry-${a}`,()=>Le({cliPath:r,config:e,context:f,result:b.result,filter:s})),R.deployError&&N.push(R.deployError),a++});a>we&&!R.previewInfo&&(c=new Error(`Deploy validation failed after ${we} attempts`))}let{diff:A,resultDiff:x,previewInfo:E,diffBinary:I,resultDiffBinary:m}=R;if(await i("cleanup",()=>Tt({config:e,diff:A,result:v.result,duration:v.duration,resultDiff:x,diffBinary:I,resultDiffBinary:m,previewInfo:E}),H.timeUnits.minutes(10)),c)throw c;await g.clean?.()})}catch(c){vt.error("Got error while running pipeline",c),await u?.();let d=c instanceof Error&&c.message;throw await U(e.id,e.sessionId,{result:d||"Encountered error when running agent",state:"error"}),c}finally{await Or()}};export{rs as runPipeline};
|
|
131
131
|
//# sourceMappingURL=index.js.map
|