@netlify/agent-runner-cli 1.49.7-alpha → 1.50.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-local.js +32 -32
- package/dist/bin.js +35 -35
- package/dist/index.js +36 -36
- package/package.json +1 -1
package/dist/bin.js
CHANGED
|
@@ -1,56 +1,56 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`),r=[],o=-1,n=0;for(;n<t.length;){let l=t[n].slice(0,500).toLowerCase();if(
|
|
4
|
-
`)),o=
|
|
2
|
+
import nt from"process";import Nn from"minimist";import{createRequire as _n}from"module";import{createTracerProvider as sr}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as ot}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as ir}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as ar}from"@netlify/otel";import{propagation as st,context as it,W3CTraceContextPropagator as lr}from"@netlify/otel/opentelemetry";import{OTLPTraceExporter as cr}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 Fe=y("tracing"),at=async(e,t,r)=>(await sr({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new ot(new Le),new ot(new cr({url:r.exporterUrl}))],instrumentations:[new ir({skipHeaders:!0})]}),r.traceparent?(st.setGlobalPropagator(new lr),st.extract(it.active(),{traceparent:r.traceparent,isRemote:!0})):it.active());function b(e,t,r){return Fe.log(`\u23F3 TRACE: ${t} starting...`),ar(e,t,r)}var Le=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[l,i]of Object.entries(o))l.includes("duration")&&typeof i=="number"?n.push(`${l}=${i.toFixed(2)}ms`):n.push(`${l}=${i}`);let s=t.status?.code===2?"\u274C":"\u2705",a=n.length>0?` [${n.join(", ")}]`:"";Fe.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${a}`),t.status?.code===2&&t.status.message&&Fe.log(` \u274C Error: ${t.status.message}`)}};var ur=["error","failed","exception","fatal","panic","abort","crash"];function lt(e){let t=e.split(`
|
|
3
|
+
`),r=[],o=-1,n=0;for(;n<t.length;){let l=t[n].slice(0,500).toLowerCase();if(ur.some(m=>l.includes(m))){let m=Math.max(0,n-10,o+1),u=Math.min(t.length-1,n+20),c=[];for(let d=m;d<=u;d++)c.push(t[d]);r.push(c.join(`
|
|
4
|
+
`)),o=u,n=u+1}else n++}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 Re from"process";import{getTracer as Vr}from"@netlify/otel";import le from"process";var me=le.env.NETLIFY_API_URL,he=le.env.NETLIFY_API_TOKEN,G=E("api"),Ee=()=>le.env.NETLIFY_LOCAL_MODE==="true",ue=async(e,t={})=>{if(!me||!he)throw new Error("No API URL or token");let r=new URL(e,me),o={...t,headers:{...t.headers,Authorization:`Bearer ${he}`}};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")G.log(`Response headers for ${r}:`),n.headers.forEach((l,i)=>{G.log(` ${i}: ${l}`)});else{let l=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");G.log(`Request ID for ${r}: ${l||"N/A"}`)}if(s||G.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},at=e=>{G.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(me=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(he=e.constants.NETLIFY_API_TOKEN)},lt=()=>({apiUrl:me,token:he}),ce=async(e,t)=>Ee()?(G.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):ue(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),j=async(e,t,r)=>Ee()?(G.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):ue(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var ut=async(e,t)=>Ee()?(G.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):ue(`/api/v1/agent_runners/${e}/sessions/${t}`),ct=(e,t,r)=>ue(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}}),pt=async(e,t)=>Ee()?(G.log("Mock API: getDiffUploadUrls called",{runnerId:e,sessionId:t}),{result:{upload_url:"https://s3.mock.com/mock-upload-url-result",s3_key:"mock-s3-key-result"},cumulative:{upload_url:"https://s3.mock.com/mock-upload-url-cumulative",s3_key:"mock-s3-key-cumulative"}}):ue(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Oe=async(e,t)=>{G.log(`Uploading diff to S3: ${e.substring(0,50)}...`);let r=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"text/plain"}});if(!r.ok)throw new Error(`S3 upload failed with status ${r.status}`);return r};var Q=E("ai_gateway"),Fe=null;var dt=async()=>{if(Fe)return Fe;Q.log("Fetching available AI gateway providers");let e=await fetch(`${lt().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 Fe=t,Q.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},lr=async(e,t)=>{let o=(await dt()).providers[e];if(!o)return Q.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return Q.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},ft=async({netlify:e,config:t})=>{let r,o,n,s,a=e.constants?.SITE_ID;if(!a)throw new Error("No site id");let l=async()=>{clearTimeout(n),Q.log("Requesting AI gateway information");let i=await ct(a,t.id,t.sessionId);if({token:r,url:s}=i,o=i.expires_at?i.expires_at*1e3:void 0,Q.log("Got AI gateway information",{token:!!r,expiresAt:o,url:s}),o){let m=o-Date.now()-6e4;m>0&&(n=setTimeout(()=>{l()},m))}};return await Promise.all([l(),dt()]),{get url(){return s},get token(){return r},isModelAvailableForProvider:lr}};import B from"process";import ye from"path";import Le from"fs";import{fileURLToPath as gr}from"url";import{execa as mr,execaCommand as qn}from"execa";import{Transform as ur}from"stream";var cr=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"]),pr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function dr(){return Object.entries(process.env).filter(([e,t])=>!(!t||cr.has(e)||pr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function Y(e){if(typeof e!="string")return e;let t=dr();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(fr(o),"g");r=r.replace(n,"******")}),r}function fr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ee=class extends ur{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),s=Y(n);o(null,s)}};function gt(){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"?Y(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"?Y(o):o;return typeof n=="function"?r(a,n):r(a,n,s)}}var pe=null,mt=e=>(pe&&pe.destroy(),pe=new q({totalAllowedTime:e}),pe),ht=()=>pe;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((l,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 hr=gr(import.meta.url),Er=ye.dirname(hr),_e=E("shell"),De=new Set,yr={preferLocal:!0},F=(e,t,r)=>{let[o,n]=_r(t,r),s={...yr,...n},a=mr(e,o,s);return Tr(a,s),Ir(a),a};var _r=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Tr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(B.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new ee).pipe(B.stdout),e.stdout?.pipe(new ee).pipe(B.stdout),e.stderr?.pipe(new ee).pipe(B.stderr);return}e.stdout?.pipe(B.stdout),e.stderr?.pipe(B.stderr)},Et=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(B.kill(-e.pid,t),_e.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return _e.error("Error killing process:",r),!1}},wr=e=>Et(e,"SIGKILL"),Ir=e=>{De.add(e);let t=ht();if(t){let r=t.onTimesUp(()=>{_e.log(`Global timer expired, killing process ${e.pid}`),Et(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(_e.log(`Force killing process ${e.pid} after timeout`),wr(e))},5e3)});e.on("exit",()=>{De.delete(e),r()}),e.on("error",()=>{De.delete(e),r()})}};function te(e,t){if(B.env.NODE_PATH){let n=ye.join(B.env.NODE_PATH,".bin",t);if(Le.existsSync(n))return n}let r=ye.join(e,"node_modules",".bin",t);if(Le.existsSync(r))return r;let o=ye.join(Er,"..","node_modules",".bin",t);if(Le.existsSync(o))return o}var yt="netlify-agent-runner-context.md",$e="task-history",Ue="netlify-context",U=".netlify",re="results.md",ke="assets",Me="other",Ge="personal";var je="enterprise",Ye="free",_t=[Ge,"pro",je,Ye];var Tt=E("utils"),Rr=e=>new Promise(t=>{setTimeout(t,e)}),wt=(e,t=3e3)=>{let r=!1,o=null,n=[],s=null,a=(...l)=>{if(r)return o=l,new Promise(c=>{n.push(c)});r=!0;let i,m=new Promise(c=>{i=c});return s=(async()=>{await Promise.resolve();let c=await e(...l);for(i(c);;){if(await Rr(t),!o)return r=!1,s=null,c;let u=o,d=n;o=null,n=[],c=await e(...u),d.forEach(h=>{h(c)})}})(),m};return a.flush=async()=>{if((r||o)&&s)return await s,a.flush()},a},Te=(e,t,r=!1)=>{let o=null,n=null,s=null,a=function(...l){n=l,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 l=n,i=s;o=null,n=null,s=null,e.apply(i,l)}},a},we=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):Tt.error("Could not parse JSON",o))}},It=(e,t)=>{let n=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let l=`--${t}${n}`;if(l.length>55)return"";let i=60-l.length;if(i<=0)return"";if(i>=s.length+6){let m=Math.min(i-s.length,e.length);return`${s}${e.slice(0,m)}`}return e.slice(0,i)},Nr=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!_t.some(t=>t in e),Rt=()=>{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);Nr(s)&&(e[r]=s)}catch(s){let l=s instanceof SyntaxError?"Invalid JSON":s.message;Tt.error(`Could not parse ${r} model version override from ${n}: ${l}`)}}}),e};import{Buffer as Nt}from"buffer";import xr from"path";var xt=E("repo"),vt=async({config:e})=>{xt.info("Getting runner diffs");let t=await Ar(),{hasChanges:r}=t,{status:o}=t;if(!r)return{hasChanges:!1};let n=Sr(o);await Cr(n),xt.info("Changes after processing"),await He();let s=await We(o);await Be(s);let a={stdio:["ignore","pipe","pipe"]},i=(await F("git",["diff","--staged"],a)).stdout;if(r=!!i,!r)return{hasChanges:!1,ignored:s};let c=(await F("git",["diff","--staged","--binary"],a)).stdout,u,d;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await F("git",["commit","-m","Agent runner"]),u=(await F("git",["diff",e.sha,"HEAD"],a)).stdout;let f=(await F("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;u!==f&&(d=Nt.from(f).toString("base64"))}let h={hasChanges:!0,diff:i,resultDiff:u,ignored:s};return i!==c&&(h.diffBinary=Nt.from(c).toString("base64")),d&&(h.resultDiffBinary=d),h},Be=async(e=[])=>{await F("git",["add",".",...e])},He=async()=>(await F("git",["status","-s"])).stdout,At=/.. (.+)?\.log$/,vr=[At],Ar=async()=>{let e=await He();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
9
|
-
`).filter(o=>
|
|
10
|
-
`).forEach(o=>{t.forEach(s=>{[`?? ${s}`,`?? ${s}${
|
|
11
|
-
`).reduce((r,o)=>{if(!o)return r;let[n,s,,...a]=o,l=a.join(""),i=n.trim(),m=s.trim();return r[l]?r[l].change=m:r[l]={filePath:l,stage:i,change:m},r},{});return Object.values(t)},
|
|
8
|
+
`);return s.length>e.length*.8?e:s}import Ne from"process";import{getTracer as Qr}from"@netlify/otel";import ce from"process";var he=ce.env.NETLIFY_API_URL,ye=ce.env.NETLIFY_API_TOKEN,M=y("api"),_e=()=>ce.env.NETLIFY_LOCAL_MODE==="true",ue=async(e,t={})=>{if(!he||!ye)throw new Error("No API URL or token");let r=new URL(e,he),o={...t,headers:{...t.headers,Authorization:`Bearer ${ye}`}};ce.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(ce.env.AGENT_RUNNERS_DEBUG==="true")M.log(`Response headers for ${r}:`),n.headers.forEach((l,i)=>{M.log(` ${i}: ${l}`)});else{let l=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");M.log(`Request ID for ${r}: ${l||"N/A"}`)}if(s||M.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},ct=e=>{M.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(he=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(ye=e.constants.NETLIFY_API_TOKEN)},ut=()=>({apiUrl:he,token:ye}),pe=async(e,t)=>_e()?(M.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):ue(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),Y=async(e,t,r)=>_e()?(M.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):ue(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var pt=async(e,t)=>_e()?(M.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):ue(`/api/v1/agent_runners/${e}/sessions/${t}`),dt=(e,t,r)=>ue(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}}),ft=async(e,t)=>_e()?(M.log("Mock API: getDiffUploadUrls called",{runnerId:e,sessionId:t}),{result:{upload_url:"https://s3.mock.com/mock-upload-url-result",s3_key:"mock-s3-key-result"},cumulative:{upload_url:"https://s3.mock.com/mock-upload-url-cumulative",s3_key:"mock-s3-key-cumulative"}}):ue(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),De=async(e,t)=>{M.log(`Uploading diff to S3: ${e.substring(0,50)}...`);let r=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"text/plain"}});if(!r.ok)throw new Error(`S3 upload failed with status ${r.status}`);return r};var te=y("ai_gateway"),$e=null;var gt=async()=>{if($e)return $e;te.log("Fetching available AI gateway providers");let e=await fetch(`${ut().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 $e=t,te.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},pr=async(e,t)=>{let o=(await gt()).providers[e];if(!o)return te.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return te.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},mt=async({netlify:e,config:t})=>{let r,o,n,s,a=e.constants?.SITE_ID;if(!a)throw new Error("No site id");let l=async()=>{clearTimeout(n),te.log("Requesting AI gateway information");let i=await dt(a,t.id,t.sessionId);if({token:r,url:s}=i,o=i.expires_at?i.expires_at*1e3:void 0,te.log("Got AI gateway information",{token:!!r,expiresAt:o,url:s}),o){let m=o-Date.now()-6e4;m>0&&(n=setTimeout(()=>{l()},m))}};return await Promise.all([l(),gt()]),{get url(){return s},get token(){return r},isModelAvailableForProvider:pr}};import j from"process";import H from"path";import Ee from"fs";import{fileURLToPath as _r}from"url";import{createRequire as Er}from"module";import{execa as Tr,execaCommand as eo}from"execa";import{Transform as dr}from"stream";var fr=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"]),gr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function mr(){return Object.entries(process.env).filter(([e,t])=>!(!t||fr.has(e)||gr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function B(e){if(typeof e!="string")return e;let t=mr();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(hr(o),"g");r=r.replace(n,"******")}),r}function hr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var re=class extends dr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),s=B(n);o(null,s)}};function ht(){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"?B(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"?B(o):o;return typeof n=="function"?r(a,n):r(a,n,s)}}var de=null,yt=e=>(de&&de.destroy(),de=new J({totalAllowedTime:e}),de),_t=()=>de;var J=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((l,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 Et={name:"@netlify/agent-runner-cli",type:"module",version:"1.50.0",description:"CLI tool for running Netlify agents",main:"./dist/index.js",types:"./dist/index.d.ts",exports:"./dist/index.js",bin:{"agent-runner-cli":"./dist/bin.js","agent-runner-cli-local":"./dist/bin-local.js"},files:["dist/**/*.js","dist/**/*.d.ts","patches","scripts"],scripts:{build:"tsup",dev:"tsup --watch",prepare:"husky install node_modules/@netlify/eslint-config-node/.husky/",prepublishOnly:"npm ci && npm test",prepack:"npm run build",test:"run-s build format test:dev",format:"run-s build format:check-fix:*","format:ci":"run-s build format:check:*","format:check-fix:lint":"run-e format:check:lint format:fix:lint","format:check:lint":"cross-env-shell eslint $npm_package_config_eslint","format:fix:lint":"cross-env-shell eslint --fix $npm_package_config_eslint","format:check-fix:prettier":"run-e format:check:prettier format:fix:prettier","format:check:prettier":"cross-env-shell prettier --check $npm_package_config_prettier","format:fix:prettier":"cross-env-shell prettier --write $npm_package_config_prettier","test:dev":"run-s build test:dev:*","test:ci":"run-s build test:ci:*","test:dev:vitest":"vitest","test:ci:vitest":"c8 -r lcovonly -r text -r json vitest",postinstall:"node scripts/postinstall.js"},config:{eslint:'--cache --format=codeframe --max-warnings=0 "{src,scripts,test,.github}/**/*.{js,ts,md,html}"',prettier:'--ignore-path .gitignore --loglevel=warn "{src,scripts,test,.github}/**/*.{js,ts,md,yml,json,html}" "*.{js,ts,yml,json,html}" ".*.{js,ts,yml,json,html}" "!**/package-lock.json" "!package-lock.json"'},keywords:[],license:"MIT",repository:"netlify/agent-runner-cli",bugs:{url:"https://github.com/netlify/agent-runner-cli/issues"},author:"Netlify Inc.",directories:{test:"test"},devDependencies:{"@commitlint/cli":"^19.0.0","@commitlint/config-conventional":"^19.0.0","@eslint/compat":"^1.3.2","@eslint/js":"^9.35.0","@netlify/eslint-config-node":"^7.0.1","@types/node":"^24.5.0","@typescript-eslint/eslint-plugin":"^7.1.0","@typescript-eslint/parser":"^7.1.0","@vitest/eslint-plugin":"^1.3.10",c8:"^9.0.0","eslint-config-prettier":"^10.1.8","eslint-plugin-n":"^17.0.0",husky:"^8.0.0","patch-package":"^8.0.0",tsup:"^8.5.0",typescript:"^5.0.0","typescript-eslint":"^8.44.0",vitest:"^1.5.0"},dependencies:{"@anthropic-ai/claude-code":"2.0.42","@google/gemini-cli":"0.16.0","@netlify/otel":"^5.0.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.57.0",execa:"^8.0.0","get-port":"^5.1.1",minimist:"^1.2.8","my-codex-no-sandbox":"^0.1.2505290819"}};var wr=_r(import.meta.url),Ir=H.dirname(wr),Rr=Er(import.meta.url),Te=y("shell"),ke=new Set,xr={preferLocal:!0},F=(e,t,r)=>{let[o,n]=vr(t,r),s={...xr,...n},a=Tr(e,o,s);return Nr(a,s),Sr(a),a};var vr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Nr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(j.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new re).pipe(j.stdout),e.stdout?.pipe(new re).pipe(j.stdout),e.stderr?.pipe(new re).pipe(j.stderr);return}e.stdout?.pipe(j.stdout),e.stderr?.pipe(j.stderr)},Tt=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(j.kill(-e.pid,t),Te.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return Te.error("Error killing process:",r),!1}},Ar=e=>Tt(e,"SIGKILL"),Sr=e=>{ke.add(e);let t=_t();if(t){let r=t.onTimesUp(()=>{Te.log(`Global timer expired, killing process ${e.pid}`),Tt(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(Te.log(`Force killing process ${e.pid} after timeout`),Ar(e))},5e3)});e.on("exit",()=>{ke.delete(e),r()}),e.on("error",()=>{ke.delete(e),r()})}};function ne(e,t){if(!j.env.NETLIFY_LOCAL_MODE)try{let n=Rr.resolve(Et.name),s=H.dirname(n);for(;s!==H.dirname(s);){let a=H.dirname(s);if(H.basename(a)==="node_modules"){let l=H.join(a,".bin",t);if(Ee.existsSync(l))return l;break}s=a}}catch(n){console.error("Could not resolve package.json",n)}if(j.env.NODE_PATH){let n=H.join(j.env.NODE_PATH,".bin",t);if(Ee.existsSync(n))return n}let r=H.join(e,"node_modules",".bin",t);if(Ee.existsSync(r))return r;let o=H.join(Ir,"..","node_modules",".bin",t);if(Ee.existsSync(o))return o}var wt="netlify-agent-runner-context.md",Ue="task-history",Ge="netlify-context",k=".netlify",oe="results.md",Me="assets",je="other",Ye="personal";var Be="enterprise",He="free",It=[Ye,"pro",Be,He];var Rt=y("utils"),br=e=>new Promise(t=>{setTimeout(t,e)}),xt=(e,t=3e3)=>{let r=!1,o=null,n=[],s=null,a=(...l)=>{if(r)return o=l,new Promise(u=>{n.push(u)});r=!0;let i,m=new Promise(u=>{i=u});return s=(async()=>{await Promise.resolve();let u=await e(...l);for(i(u);;){if(await br(t),!o)return r=!1,s=null,u;let c=o,d=n;o=null,n=[],u=await e(...c),d.forEach(h=>{h(u)})}})(),m};return a.flush=async()=>{if((r||o)&&s)return await s,a.flush()},a},we=(e,t,r=!1)=>{let o=null,n=null,s=null,a=function(...l){n=l,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 l=n,i=s;o=null,n=null,s=null,e.apply(i,l)}},a},Ie=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):Rt.error("Could not parse JSON",o))}},vt=(e,t)=>{let n=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let l=`--${t}${n}`;if(l.length>55)return"";let i=60-l.length;if(i<=0)return"";if(i>=s.length+6){let m=Math.min(i-s.length,e.length);return`${s}${e.slice(0,m)}`}return e.slice(0,i)},Cr=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!It.some(t=>t in e),Nt=()=>{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);Cr(s)&&(e[r]=s)}catch(s){let l=s instanceof SyntaxError?"Invalid JSON":s.message;Rt.error(`Could not parse ${r} model version override from ${n}: ${l}`)}}}),e};import{Buffer as At}from"buffer";import Pr from"path";var St=y("repo"),bt=async({config:e})=>{St.info("Getting runner diffs");let t=await Fr(),{hasChanges:r}=t,{status:o}=t;if(!r)return{hasChanges:!1};let n=Lr(o);await Dr(n),St.info("Changes after processing"),await qe();let s=await Ke(o);await We(s);let a={stdio:["ignore","pipe","pipe"]},i=(await F("git",["diff","--staged"],a)).stdout;if(r=!!i,!r)return{hasChanges:!1,ignored:s};let u=(await F("git",["diff","--staged","--binary"],a)).stdout,c,d;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await F("git",["commit","-m","Agent runner"]),c=(await F("git",["diff",e.sha,"HEAD"],a)).stdout;let f=(await F("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;c!==f&&(d=At.from(f).toString("base64"))}let h={hasChanges:!0,diff:i,resultDiff:c,ignored:s};return i!==u&&(h.diffBinary=At.from(u).toString("base64")),d&&(h.resultDiffBinary=d),h},We=async(e=[])=>{await F("git",["add",".",...e])},qe=async()=>(await F("git",["status","-s"])).stdout,Ct=/.. (.+)?\.log$/,Or=[Ct],Fr=async()=>{let e=await qe();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
9
|
+
`).filter(o=>Or.some(s=>s instanceof RegExp?s.test(o):o===s)?!1:o[1]?.trim()!=="")).length!==0,status:e}},Pt=async()=>{let{stdout:e}=await F("git",["rev-parse","HEAD"]);return e.trim()},Ot=async()=>{let{stdout:e}=await F("git",["rev-list","--max-parents=0","HEAD"]);return e.trim()},Ke=async e=>{e||=await qe();let t=[".netlify","node_modules"],r=[];return e.split(`
|
|
10
|
+
`).forEach(o=>{t.forEach(s=>{[`?? ${s}`,`?? ${s}${Pr.sep}`].some(l=>o.startsWith(l))&&r.push(`:!${s}`)});let n=o.match(Ct)?.[1];n&&r.push(`:!${n}.log`)}),r},Ft=async()=>{await F("git",["reset","--hard","HEAD"])},Lr=e=>{let t=e.split(`
|
|
11
|
+
`).reduce((r,o)=>{if(!o)return r;let[n,s,,...a]=o,l=a.join(""),i=n.trim(),m=s.trim();return r[l]?r[l].change=m:r[l]={filePath:l,stage:i,change:m},r},{});return Object.values(t)},Dr=async e=>{let t=[];for(let r of e)r.stage&&!r.change&&t.push(F("git",["restore","--staged","--worktree",r.filePath]));await Promise.allSettled(t)};import kr from"fs/promises";import Ur from"os";import $t from"path";import X from"process";import Gr from"readline";import Ve from"path";import $r from"fs/promises";var Je=y("agent-output-utils");async function se({initialResult:e,agentName:t,hasError:r}){let o="",n=Ve.join(process.cwd(),k,oe);try{let s=await $r.readFile(n,"utf-8");s&&(o=s,Je.log(`Pulled result from ${Ve.relative(process.cwd(),n)}`))}catch{Je.log(`No results file found at ${Ve.relative(process.cwd(),n)}`)}return o||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function ie({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&&Je.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function ae(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 U=y("runner_claude"),Lt="Claude Code",Re="claude-sonnet-4-5-20250929",Dt=e=>({Task:"Task",Bash:"Run command",Glob:"Find files",Grep:"Search files",LS:"List directory",ExitPlanMode:"Exit planning",Read:"Read file",Edit:"Edit file",MultiEdit:"Edit multiple files",Write:"Coding",NotebookEdit:"Edit notebook",WebFetch:"Fetch webpage",TodoWrite:"Update task list",WebSearch:"Search web",BashOutput:"Get command output",KillBash:"Stop command"})[e]||e,Mr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(U.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?(U.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}):(U.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function Xe({config:e,netlify:t,persistSteps:r,aiGateway:o,continueSession:n,priorAgentSessionId:s}){let a=e,{accountType:l,prompt:i,modelVersionOverrides:m}=a,{model:u}=a,c="";if(o){let{token:_,url:g}=o;if(!_||!g)throw new Error("No token or url provided from AI Gateway");if(m?.claude){let p=m?.claude?.[l];if(p){if(!await o.isModelAvailableForProvider("anthropic",p))throw new Error(`Model override '${p}' is not available for anthropic provider`);u=p}}else if(u){if(!await o.isModelAvailableForProvider("anthropic",u))throw new Error(`Model '${u}' is not available for anthropic provider`)}else await o.isModelAvailableForProvider("anthropic",Re)?(u=Re,U.log(`Using default model: ${Re}`)):U.log(`Default model ${Re} is not available, proceeding without model specification`);X.env.ANTHROPIC_API_KEY=_,X.env.ANTHROPIC_BASE_URL=g}else if(!X.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let d=[],h=[],T={},w=0,f=0,I,x,S=[ne(X.cwd(),"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...u?["--model",u]:[],...n?["--continue"]:[],...n&&s?["--resume",s]:[],"-p",i],R=`${X.env.NVM_BIN}/node`;U.log(`Running ${R} ${S.join(" ")}`);let E=t.utils.run(R,S,{all:!0,env:X.env});E.stdin?.end();let v=we(()=>{r?.({steps:d,duration:f})},250),N=(_,g)=>{let p={..._,id:w};w+=1,h.push(p),d.push(p),g||v.flush(),v(),g&&v.flush()},A=Gr.createInterface({input:E.all});return A.on("error",_=>{U.error("Readline interface error",{error:_.message,stack:_.stack})}),A.on("line",_=>{let g=null;try{g=JSON.parse(_)}catch{U.log("Could not parse line",_)}g?.session_id&&g.session_id!==c&&(c=g.session_id),Array.isArray(g?.message?.content)?g.message.content.forEach(p=>{switch(p.type){case"text":{p.text&&N({message:p.text});break}case"image":{typeof p.source=="object"&&p.source&&p.source.type==="base64"&&p.source.media_type?N({message:``}):U.log(`Unsupported image type ${p.source?.type}`,p.source);break}case"tool_use":{if(p.name==="Task"){let O=p.input?.description&&`\`${p.input.description}\``;N({title:[Dt(p.name),O].filter(Boolean).join(" ")})}else p.id&&(T[p.id]=p);v.flush();break}case"tool_result":{let O=p.tool_use_id?T[p.tool_use_id]:void 0,ee;if(O){let q=O.input?.file_path&&$t.relative(X.cwd(),O.input.file_path),P=q&&`\`${q}\``;ee=[Dt(O.name||""),P].filter(Boolean).join(" ")}let me=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(O?.name||""),V;if(typeof p.content=="string")V=p.content;else if(Array.isArray(p.content)){let q=[];p.content.forEach(P=>{P?.type==="text"&&typeof P.text=="string"?q.push(P.text):P?.type==="image"&&typeof P.source=="object"&&P.source?P.source.type==="base64"&&P.source.media_type?q.push(``):U.log(`Unsupported image type ${P.source.type}`,P.source):U.log(`Unsupported block type ${P?.type}`)}),V=q.join(`
|
|
12
12
|
|
|
13
|
-
`)}
|
|
14
|
-
${
|
|
15
|
-
\`\`\``),
|
|
16
|
-
`):
|
|
17
|
-
`));
|
|
13
|
+
`)}me&&V&&(V=`\`\`\`
|
|
14
|
+
${V.trim()}
|
|
15
|
+
\`\`\``),N({title:ee,message:V},!0);break}case"thinking":{p.thinking&&N({title:"Thinking",message:p.thinking},!0);break}default:U.log(`Message content type is not supported ${p.type}`,p)}}):g?.type==="result"&&(f=g.duration_ms||0,g.is_error?x=g.result:I=g.result,[h,d].forEach(p=>{p[p.length-1]?.message===I&&p.pop()}))}),await E.catch(_=>{({error:x,result:I}=Mr({catchError:_,runCmd:E,error:x,result:I,runnerName:"Claude"}))}),A.close(),v.flush(),{steps:h,duration:f,result:await se({initialResult:I,agentName:Lt,hasError:!!x}),error:ie({error:x,agentName:Lt}),isRetryableError:ae(x),agentSessionId:c}}var kt=async()=>{let e=$t.join(Ur.homedir(),".claude");await kr.rm(e,{recursive:!0,force:!0})};import jr from"fs/promises";import Yr from"os";import Br from"path";import le from"process";import Hr from"readline";var z=y("runner_codex"),Ut="Codex CLI",Wr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(z.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?(z.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}):(z.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function ze({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:a,modelVersionOverrides:l}=e,{model:i}=e;if(n){let{token:R,url:E}=n;if(!R||!E)throw new Error("No token or url provided from AI Gateway");if(l?.codex){let v=l?.codex?.[s];if(v){if(!await n.isModelAvailableForProvider("openai",v))throw new Error(`Model override '${v}' is not available for openai provider`);i=v}}else if(i&&!await n.isModelAvailableForProvider("openai",i))throw new Error(`Model '${i}' is not available for openai provider`);le.env.OPENAI_API_KEY=R,le.env.OPENAI_BASE_URL=E}else if(!le.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let m=[],u=[],c={},d=0,h=0,T,w,f=[ne(le.cwd(),"codex"),"--approval-mode","full-auto",n?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...i?["--model",i]:[],"-q",a].filter(Boolean),I=`${le.env.NVM_BIN}/node`;z.log(`Running ${I} ${f.join(" ")}`);let x=t.utils.run(I,f,{all:!0,env:{...le.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),S=Hr.createInterface({input:x.all});return S.on("error",R=>{z.error("Readline interface error",{error:R.message,stack:R.stack})}),S.on("line",R=>{let E=null;try{E=JSON.parse(R)}catch{z.log("Could not parse line",R);return}let v=[],N=!1;if(E?.duration_ms&&(h=E.duration_ms,N=!0),E?.type==="local_shell_call")c[E.call_id]=E;else if(E?.type==="local_shell_call_output"){let A=Kr(c[E.call_id],E);A&&(A.id=d,d+=1,u.push(A),m.push(A),v.push(A),N=!0)}else E?.type==="message"&&E.role==="assistant"?T=E.content.map(A=>A.text).join(`
|
|
16
|
+
`):E?.type==="message"&&E.role==="system"&&(w=E.content.map(A=>A.text).join(`
|
|
17
|
+
`));N&&(r?.({steps:m,duration:h}),o?.({steps:v,duration:h}))}),await x.catch(R=>{let E=Wr({catchError:R,runCmd:x,error:w,result:T,runnerName:"Codex"});w=E.error,T=E.result}),S.close(),{steps:u,duration:h,result:await se({initialResult:T,agentName:Ut,hasError:!!w}),error:ie({error:w,agentName:Ut}),isRetryableError:ae(w)}}var Gt=async()=>{let e=Br.join(Yr.homedir(),".codex");await jr.rm(e,{recursive:!0,force:!0})},qr=new Set(["bash","-lc"]),Kr=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!qr.has(s)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
|
|
18
18
|
${n.trim()}
|
|
19
|
-
\`\`\``)}catch(s){
|
|
19
|
+
\`\`\``)}catch(s){z.error("Could not decode outputMsg",s,t.output)}return{title:o,message:n}};import xe from"fs/promises";import jt from"os";import ve from"path";import Z from"process";import Vr from"readline";var W=y("runner_gemini"),Mt="Gemini CLI",Jr=({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})),Xr={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"},zr=async()=>{let e=ve.join(jt.homedir(),".gemini"),t=ve.join(e,"settings.json");try{await xe.mkdir(e,{recursive:!0});let r={};try{let o=await xe.readFile(t,"utf-8");r=JSON.parse(o)}catch{W.log("Creating new Gemini CLI settings file")}r.general||(r.general={}),r.general.previewFeatures||(r.general.previewFeatures=!0),await xe.writeFile(t,JSON.stringify(r,null,2),"utf-8"),W.log("Enabled preview features in Gemini CLI settings")}catch(r){W.error("Failed to ensure Gemini CLI settings",{error:r.message})}};async function Ze({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:a,modelVersionOverrides:l}=e,{model:i}=e;if(await zr(),n){let{token:_,url:g}=n;if(!_||!g)throw new Error("No token or url provided from AI Gateway");if(l?.gemini){let p=l?.gemini?.[s];if(p){if(!await n.isModelAvailableForProvider("gemini",p))throw new Error(`Model override '${p}' is not available for gemini provider`);i=p}}else if(i&&!await n.isModelAvailableForProvider("gemini",i))throw new Error(`Model '${i}' is not available for gemini provider`);Z.env.GEMINI_API_KEY=_,Z.env.GOOGLE_GEMINI_BASE_URL=g}else if(!Z.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let m=[],u=[],c=[],d={},h=0,T=0,w,f,I=[ne(Z.cwd(),"gemini"),...i?["--model",i]:[],"--yolo","--output-format","stream-json","-p",a],x=`${Z.env.NVM_BIN}/node`;W.log(`Running ${x} ${I.join(" ")}`);let S=t.utils.run(x,I,{all:!0,env:Z.env});S.stdin?.end();let R=we(()=>{r?.({steps:m,duration:T}),o?.({steps:u,duration:T}),u=[]},250),E=(_,g)=>{_.id=h,h+=1,c.push(_),m.push(_),u.push(_),g||R.flush(),R(),g&&R.flush()},v=Vr.createInterface({input:S.all});v.on("error",_=>{W.error("Readline interface error",{error:_.message,stack:_.stack})});let N="",A=()=>{N&&E({message:N.trim()}),N=""};return v.on("line",_=>{let g=null;try{if(_.startsWith("[API Error")){let p=_.match(/\[api error: (.+?)]$/i)?.[1];g={type:"error",value:Ie(p,!1)?.error?.message||p||"Gemini encountered error"}}else g=JSON.parse(_)}catch{return}if(g)switch(["message","result"].includes(g.type)||A(),g.type){case"message":{g.role!=="user"&&g.content&&(N+=g.content);break}case"tool_use":{let p=Xr[g.tool_name]??g.tool_name,O=g.parameters?.file_path,ee=O&&ve.relative(Z.cwd(),O),me=g.parameters?.command,q={title:[p,ee&&`\`${ee}\``,me&&`\`${me}\``].filter(Boolean).join(" ")};d[g.tool_id]=q,R.flush();break}case"tool_result":{let p=d[g.tool_id];p&&(g.output&&(p.message=`\`\`\`
|
|
20
20
|
${g.output.trim()}
|
|
21
|
-
\`\`\``),
|
|
21
|
+
\`\`\``),E(p,!0));break}case"result":{T=g.stats?.duration_ms,g.status==="error"?f=g.error?.message:w=N.trim();break}case"error":{f=g.error;break}case"finished":break;default:{W.warn("Unhandled message type:",g.type);break}}}),await S.catch(_=>{({error:f,result:w}=Jr({catchError:_,runCmd:S,error:f,result:w,runnerName:"Gemini"}))}),v.close(),R.flush(),{steps:c,duration:T,result:await se({initialResult:w,agentName:Mt,hasError:!!f}),error:ie({error:f,agentName:Mt}),isRetryableError:ae(f)}}var Yt=async()=>{let e=ve.join(jt.homedir(),".gemini");await xe.rm(e,{recursive:!0,force:!0})};var Zr={codex:{runner:ze,clean:Gt},claude:{runner:Xe,clean:kt},gemini:{runner:Ze,clean:Yt}},Bt=Zr;var en=y("init_stage"),Ht=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>await b(Qr(),"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=Bt[e.runner];if(!a)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let l=tn({apiToken:r});ct(l);let i=e.useGateway?await mt({netlify:l,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!i}),e.validateAgent&&e.errorLogsPath&&n?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let m=xt(({steps:h=[],duration:T})=>{let w=h.map(f=>({...f,title:f.title?B(f.title):void 0,message:f.message?B(f.message):void 0}));return h.length=0,Y(e.id,e.sessionId,{steps:w,duration:T})},t);en.info("Adding build files to stage");let u=await Ke();await We(u);let c;e.hasRepo?e.sha?(c=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(c=await Pt(),await pe(e.id,{sha:c}),n?.setAttributes({"init.sha.source":"current_commit"})):(c=await Ot(),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:l,persistSteps:m,runner:a,sha:c}}),tn=({apiToken:e})=>({constants:{NETLIFY_API_HOST:Ne.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||Ne.env.NETLIFY_API_TOKEN,SITE_ID:Ne.env.SITE_ID,FUNCTIONS_DIST:Ne.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:F}});import{getTracer as Qe}from"@netlify/otel";import rn from"crypto";import K from"fs/promises";import $ from"path";import G from"process";var L=y("context"),nn=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:G.env.NETLIFY_TEAM_ID,userId:G.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:G.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},on=10,sn=async e=>{let{name:t,ext:r}=$.parse(e),o=e,n=$.join(G.cwd(),k,o),s=0;for(;await an(n);){if(s>=on)throw new Error("Failed to generate context file");o=`${t}-${rn.randomUUID().slice(0,5)}${r}`,n=$.join(G.cwd(),k,o),s+=1}return o},an=async e=>{try{return await K.access(e),!0}catch{return!1}},ln=async()=>{try{L.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 L.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"?(L.warn("Catchall consumer missing or invalid contextScopes"),null):r:(L.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?L.warn("Netlify features context request timed out"):L.warn("Failed to fetch Netlify features context:",e.message),null}},cn=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 K.writeFile(t,o,"utf-8"),!0}catch(r){return r.name==="AbortError"?L.warn(`Download timeout for ${e}`):L.warn(`Failed to download context file ${e}:`,r.message),!1}},Ae=null,un=async()=>{if(Ae)return Ae;let e=await ln();if(!e)return[];let t=$.join(G.cwd(),k,Ge);await K.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([n,s])=>{if(!s||typeof s!="object"||!s.endpoint||!s.scope)return L.warn(`Invalid scope data for ${n}, skipping...`),null;let a=`${n}.md`,l=$.join(t,a),i=$.join(k,Ge,a);return L.log(`Downloading ${s.scope} context...`),await cn(s.endpoint,l)?(L.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:n}):null});return Ae=(await Promise.all(r)).filter(n=>n!==null),Ae},Wt=async({cliPath:e,netlify:t,config:r,buildErrorContext:o})=>{let n=nn(t),s=await sn(wt),a=$.join(G.cwd(),k);await K.mkdir(a,{recursive:!0});let l=$.join(k,s),i=$.join(G.cwd(),l),m=$.join(G.cwd(),k,oe);try{await K.unlink(m),L.log(`Deleted old results file: ${m}`)}catch{}let u=o?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
|
|
22
22
|
Your task is to analyze and fix the build errors.
|
|
23
23
|
Don't apply techniques of reverting changes. Apply fixes related to errors.
|
|
24
24
|
Don't try to run build by yourself. Just fix the errors.
|
|
25
25
|
|
|
26
26
|
<build_error_context>
|
|
27
27
|
${o}
|
|
28
|
-
</build_error_context>`:"",
|
|
28
|
+
</build_error_context>`:"",c="";r.siteContext&&r.siteContext.length!==0&&(c=`
|
|
29
29
|
<project_rules>
|
|
30
30
|
${r.siteContext.filter(f=>f.site_context).map(f=>typeof f.site_context=="string"?f.site_context:typeof f.site_context=="object"?JSON.stringify(f.site_context):"").join(`
|
|
31
31
|
|
|
32
32
|
`)}
|
|
33
33
|
</project_rules>
|
|
34
|
-
`);let d="";if(r.sessionHistoryContext?.length){let f=$.join(
|
|
34
|
+
`);let d="";if(r.sessionHistoryContext?.length){let f=$.join(G.cwd(),k,Ue);await K.mkdir(f,{recursive:!0});let I=await Promise.all(r.sessionHistoryContext.map(async(x,S)=>{let R=S+1,E=`attempt-${R}.md`,v=$.join(f,E),N=$.join(k,Ue,E),A=`# Task History - Attempt ${R}
|
|
35
35
|
|
|
36
36
|
## Request - what the user asked for
|
|
37
|
-
${
|
|
37
|
+
${x.request}
|
|
38
38
|
|
|
39
39
|
---
|
|
40
40
|
|
|
41
41
|
## Response - what the agent replied with after its work
|
|
42
42
|
|
|
43
|
-
${
|
|
44
|
-
`;return await
|
|
43
|
+
${x.response}
|
|
44
|
+
`;return await K.writeFile(v,A,"utf-8"),L.log(`Created history file: ${N}`),N}));d+=`
|
|
45
45
|
<session_history_context>
|
|
46
46
|
History of prior work on this task.
|
|
47
47
|
You MUST review ALL of the files below as context to understand the context of previous attempts. Use this information to continue the discussion appropriately.
|
|
48
48
|
|
|
49
|
-
${I.slice(-5).map(
|
|
49
|
+
${I.slice(-5).map(x=>`- ${x}`).join(`
|
|
50
50
|
`)}
|
|
51
51
|
|
|
52
52
|
</session_history_context>
|
|
53
|
-
`}let h=await
|
|
53
|
+
`}let h=await un(),T="";h.length>0&&(T=`
|
|
54
54
|
<netlify_features_context>
|
|
55
55
|
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.
|
|
56
56
|
DO NOT force the use of any Netlify feature if the user request does not explicitly require it or if the project has alternative implementations in place already.
|
|
@@ -67,23 +67,23 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
67
67
|
<user_request>
|
|
68
68
|
${r.prompt}
|
|
69
69
|
</user_request>
|
|
70
|
-
${
|
|
70
|
+
${u}
|
|
71
71
|
</request>
|
|
72
72
|
|
|
73
73
|
<requirements>
|
|
74
74
|
<responses>
|
|
75
75
|
- Do not speak in first person. You may speak as "the agent".
|
|
76
|
-
- When work is complete, write a changes summary in ${a}/${
|
|
77
|
-
- 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}/${
|
|
76
|
+
- When work is complete, write a changes summary in ${a}/${oe} 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.
|
|
77
|
+
- 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}/${oe} file.
|
|
78
78
|
- 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.
|
|
79
79
|
- NEVER look into the \`.git\` folder
|
|
80
80
|
- NEVER print potentially sensitive values (like secrets) in the planning output or results
|
|
81
81
|
</responses>
|
|
82
82
|
<attachements>
|
|
83
|
-
- for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${a}/${
|
|
84
|
-
- move assets from ${a}/${
|
|
83
|
+
- for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${a}/${Me} folder
|
|
84
|
+
- move assets from ${a}/${Me} folder to the project assets folder if they are referenced in a code or applied changes
|
|
85
85
|
</attachements>
|
|
86
|
-
${
|
|
86
|
+
${c}
|
|
87
87
|
</requirements>
|
|
88
88
|
|
|
89
89
|
<extra_context>
|
|
@@ -95,7 +95,7 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
95
95
|
- Netlify Functions directory: ${n.functionsDir}
|
|
96
96
|
</metadata>
|
|
97
97
|
<environment>
|
|
98
|
-
- Node Version: ${
|
|
98
|
+
- Node Version: ${G.version||"unknown"}
|
|
99
99
|
- Environment variables are set globally (e.g. \`echo $VARIABLE_NAME\` can be used to check if a var is set).
|
|
100
100
|
- 'netlify-cli' npm package is already available as a global package. Don't try to install it again
|
|
101
101
|
- If you need to start a local development server in order to fulfill the request, try using the Netlify CLI over by running the shell command '${e} dev'. This will start a local HTTP server on port 8888, including live-reloading of any changes and, most critically, it offers local emulation for all Netlify features.
|
|
@@ -108,28 +108,28 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
108
108
|
</extra_context>
|
|
109
109
|
|
|
110
110
|
${d}
|
|
111
|
-
`;return await
|
|
111
|
+
`;return await K.writeFile(i,w,"utf-8"),L.log(`Generated agent context document at: ${i}`),w.length>5e5&&(w=`
|
|
112
112
|
You're an AI agent designed to assist with tasks related to a Netlify project. Please review, understand, and use the context provided to complete the user's request as needed.
|
|
113
113
|
|
|
114
114
|
<request>
|
|
115
115
|
<user_request>
|
|
116
116
|
${r.prompt}
|
|
117
117
|
</user_request>
|
|
118
|
-
${
|
|
118
|
+
${u}
|
|
119
119
|
</request>
|
|
120
120
|
|
|
121
121
|
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.
|
|
122
|
-
`),w};var
|
|
122
|
+
`),w};var pn=y("prompt"),qt=async({cliPath:e,config:t,netlify:r,buildErrorContext:o})=>{let n=await Wt({cliPath:e,config:t,netlify:r,buildErrorContext:o});return process.env.AGENT_RUNNER_DEBUG&&pn.log("Contextful Prompt:",n),{prompt:n}};var Se=y("inference_stage"),Kt=5,be=async e=>{let{cliPath:t,config:r,context:o,buildErrors:n,runner:s,persistSteps:a,aiGateway:l,attempt:i,contextPrefix:m,priorAgentSessionId:u}=e;Se.log(`Running inference stage, attempt ${i} of ${Kt}`);let c=await b(Qe(),"inference-stage",async d=>{d?.setAttributes({"inference.attempt":i||1}),ht();let{prompt:h}=await b(Qe(),"compose-prompt",async()=>await qt({cliPath:t,config:r,buildErrorContext:dn(n),netlify:o})),T=`
|
|
123
123
|
${m||""}
|
|
124
124
|
${h}
|
|
125
|
-
`.trim(),w={...r,prompt:T},f=await
|
|
125
|
+
`.trim(),w={...r,prompt:T},f=await b(Qe(),`run-${r.runner}`,async()=>await s({aiGateway:l,config:w,netlify:o,persistSteps:a,continueSession:!!(i&&i>1),priorAgentSessionId:u}));return f.result&&(f.result=B(f.result)),f.error&&(f.error=B(f.error)),await a.flush(),f});if(c.error){if(Se.error("Runner failed",{stepsCount:c.steps.length,duration:c.duration,error:c.error,isRetryableError:c.isRetryableError,attempt:i||1,agentSessionId:c.agentSessionId}),c.isRetryableError&&(!i||i<Kt))return Se.log("Retrying inference stage"),await new Promise(h=>setTimeout(h,5e3)),{runnerResult:(await be({...e,attempt:(i||1)+1,priorAgentSessionId:c.agentSessionId,contextPrefix:c.agentSessionId?"":"<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 Se.log("Do not retry inference stage"),new Error(c.error)}return{runnerResult:c}},dn=e=>!e||e.length===0?"":`
|
|
126
126
|
Deploy failed failed. Here are the errors to review on the latest build:
|
|
127
127
|
|
|
128
128
|
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.
|
|
129
129
|
|
|
130
130
|
${e.pop()}
|
|
131
|
-
`;import
|
|
132
|
-
Preview deploy created successfully:`,{deployId:
|
|
131
|
+
`;import mn from"process";import{getTracer as et}from"@netlify/otel";import{getTracer as fn}from"@netlify/otel";var fe=y("deploy"),Vt=async e=>await b(fn(),"create-preview-deploy",async t=>gn(e,t)),gn=async({netlify:e,hasRepo:t,skipBuild:r,message:o="Agent Preview",deploySubdomain:n,cliPath:s,filter:a},l)=>{try{let i=["deploy","--message",`"${o}"`,"--json","--draft","--verbose"];t||(fe.log("Deploy: Uploading source zip"),i.push("--upload-source-zip")),n&&i.push("--alias",n),a&&i.push("--filter",a),r?(fe.log("Deploy: Skipping build"),i.push("--no-build")):i.push("--context","deploy-preview");let m=s||"netlify";fe.log(`Running: ${m} ${i.join(" ")}`),l?.setAttributes({cmd:m,args:i});let u=await e.utils.run(m,i,{stdio:["ignore","pipe","pipe"]}),c=JSON.parse(u.stdout.trim());l?.setAttributes({success:!0,deployId:c.deploy_id,deployUrl:c.deploy_url,siteId:c.site_id}),fe.log(`
|
|
132
|
+
Preview deploy created successfully:`,{deployId:c.deploy_id,deployUrl:c.deploy_url,siteId:c.site_id});let d={deployId:c.deploy_id,previewUrl:c.deploy_url,logsUrl:c.logs,siteId:c.site_id};return t||(d.sourceZipFilename=c.source_zip_filename),d}catch(i){throw fe.error("Failed to create preview deploy via CLI:",i),l?.setAttributes({success:!1,error:i.message}),i}};var ge=y("deploy_stage"),tt=async e=>await b(et(),"run-deploy-stage",async()=>hn(e)),hn=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let s=await b(et(),"get-runner-diffs",async()=>await bt({config:t,netlify:r}));if(ge.info("Resolved git",{hasChanges:s.hasChanges,ignored:s.ignored??[]}),!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:l,diffBinary:i,resultDiffBinary:m}=s,u=!0;ge.log("Preview deploy condition check:",{resultUndefined:o===void 0,resultType:typeof o,hasChanges:u,wouldCreatePreview:o!==void 0&&u});let c=null;if(o!==void 0&&u)try{let d;try{let h=await b(et(),"get-runner-session",async()=>await pt(t.id,t.sessionId));h?.title&&(d=h.title)}catch(h){ge.warn("Failed to fetch session title, using fallback message:",h.message)}await Y(t.id,t.sessionId,{steps:[{title:"Deploying the run preview"}]}),c=await Vt({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:d,skipBuild:!1,deploySubdomain:vt(t.id,mn.env.SITE_NAME),filter:n})}catch(d){return ge.warn("Failed to create preview deploy (continuing with agent run):",d),{diff:a,resultDiff:l,hasChanges:u,previewInfo:null,diffBinary:i,resultDiffBinary:m,deployError:d instanceof Error?d.message:String(d)}}return ge.log("Git status",{hasDiff:!!a,hasChanges:u}),{diff:a,resultDiff:l,hasChanges:u,previewInfo:c,diffBinary:i,resultDiffBinary:m}};import{getTracer as Pe}from"@netlify/otel";async function Jt(e,t){let{maxRetries:r,baseDelay:o,onRetry:n}=t,s;for(let a=1;a<=r;a++)try{return await e()}catch(l){if(s=l,a===r)throw s;n&&n(a,s),await new Promise(i=>setTimeout(i,o*a))}throw s}var Ce=class{scanDiffForForms(t){let r=[],o=null,n=[],s=t.split(`
|
|
133
133
|
`);for(let a of s)if(a.startsWith("diff --git")){if(o&&n.length>0){let i=this.containsNetlifyForm(n,o);i&&r.push(i)}let l=a.split(" ");o=l[l.length-1].replace(/^b\//,""),n=[]}else a.startsWith("+")&&!a.startsWith("+++")&&n.push(a.slice(1));if(o&&n.length>0){let a=this.containsNetlifyForm(n,o);a&&r.push(a)}return{detected:r.length>0,matches:r}}containsNetlifyForm(t,r){let o=t.join(`
|
|
134
|
-
`),n=[{pattern:/<[\w-]*form[\s\S]*?(data-)?netlify/i,name:"standard form element"},{pattern:/<[A-Z][\w]*[\s\S]*?component\s*=\s*["']form["'][\s\S]*?(data-)?netlify/i,name:"component with form prop"}];for(let{pattern:s,name:a}of n){let l=o.match(s);if(l){let i=l.index||0,m=Math.max(0,i-20),
|
|
134
|
+
`),n=[{pattern:/<[\w-]*form[\s\S]*?(data-)?netlify/i,name:"standard form element"},{pattern:/<[A-Z][\w]*[\s\S]*?component\s*=\s*["']form["'][\s\S]*?(data-)?netlify/i,name:"component with form prop"}];for(let{pattern:s,name:a}of n){let l=o.match(s);if(l){let i=l.index||0,m=Math.max(0,i-20),u=Math.min(o.length,i+l[0].length+20),c=o.slice(m,u).trim();return c=c.replace(/\s+/g," "),c.length>100&&(c=c.slice(0,97)+"..."),{file:r,snippet:`[${a}] ${c}`}}}return null}};var C=y("cleanup_stage"),Xt=async e=>await b(Pe(),"cleanup-stage",async()=>yn(e)),rt=1024*1024*10,yn=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:s,resultDiffBinary:a,previewInfo:l})=>{let i={result:r||"Done",duration:o};l&&l.deployId&&(i.deploy_id=l.deployId),l&&l.sourceZipFilename&&(i.result_zip_file_name=l.sourceZipFilename);let m=t||s||n||a;if(m){let u=new Ce,c=t||s||"",d=u.scanDiffForForms(c);d.detected?(C.log("Detected Netlify form(s) in diff:"),d.matches.forEach(({file:h,snippet:T})=>{C.log(` - ${h}: ${T}`)}),i.has_netlify_form=!0):C.log("Did not detect Netlify form(s) in diff"),C.log("Did not detect Netlify form(s) in diff")}if(m)try{C.log("Getting pre-signed URLs for diff upload");let u=await ft(e.id,e.sessionId),c=[];(t||s)&&c.push(De(u.result.upload_url,s||t).then(()=>{i.result_diff_s3_key=u.result.s3_key,C.log("Successfully uploaded result_diff to S3")})),(n||a)&&c.push(De(u.cumulative.upload_url,a||n).then(()=>{i.cumulative_diff_s3_key=u.cumulative.s3_key,C.log("Successfully uploaded cumulative_diff to S3")})),C.log(`Uploading ${c.length} diff(s) to S3 in parallel`),await Promise.all(c),(n||a)&&(C.log("Updating agent runner with cumulative diff S3 key"),await b(Pe(),"update-runner",async()=>{await pe(e.id,{result_diff_s3_key:u.cumulative.s3_key})}))}catch(u){C.error("S3 upload failed, falling back to inline diffs:",u);let c=Buffer.byteLength(t||s||""),d=Buffer.byteLength(a||n||"");if(c>rt||d>rt){let h=`Diffs exceed maximum inline size of ${rt} bytes.`;throw C.error(h),new Error(h)}i.result_diff=t,i.result_diff_binary=s,(n||a)&&(i.cumulative_diff=n,i.cumulative_diff_binary=a,C.log("Updating agent runner with inline diffs (fallback)"),await b(Pe(),"update-runner",async()=>{await pe(e.id,{result_diff:n,result_diff_binary:a})}))}else C.log("No diffs to upload");return C.log("Updated agent runner with result"),await Jt(async()=>await b(Pe(),"update-runner-session",()=>Y(e.id,e.sessionId,i)),{maxRetries:3,baseDelay:1e3,onRetry:(u,c)=>{C.error(`Error updating agent runner session (attempt ${u}):`,c),C.log("Retrying...")}}),C.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as zt,shutdownTracers as En,withActiveSpan as Zt}from"@netlify/otel";var Tn=_n(import.meta.url),Qt=Tn("../package.json"),er=y("pipeline_index"),Oe=3,tr=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:s,tracing:a={}})=>{let l,{withStageTimer:i}=yt(J.timeUnits.hours(4)),m=await at(Qt.version,e.id,a);try{await Zt(zt(),"run-pipeline",{},m,async()=>{let u,{aiGateway:c,context:d,persistSteps:h,runner:T,sha:w}=await i("init",()=>Ht({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:s,runnerVersion:Qt.version}),J.timeUnits.minutes(10));l=T.clean,e.sha=w;let{runnerResult:f}=await i("inference",()=>be({cliPath:r,config:e,context:d,runner:T.runner,persistSteps:h,aiGateway:c}));await Y(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let I=await i("deploy",()=>tt({cliPath:r,config:e,context:d,result:f.result,filter:s})),x=f,S=[];if(I.hasChanges&&I.deployError){S.push(lt(I.deployError));let _=1;for(;_<=Oe&&!I.previewInfo;)er.log(`Deploy attempt had errors. Retrying. ${_}/${Oe}`),await Zt(zt(),"deploy-stage",async g=>{g?.setAttributes({"stage.attempt":_});let{runnerResult:p}=await i(`inference-retry-${_}`,()=>be({cliPath:r,config:e,context:d,runner:T.runner,persistSteps:h,aiGateway:c,buildErrors:S,priorAgentSessionId:f.agentSessionId}));x={...p,steps:[...x.steps||[],...p.steps||[]],duration:(x.duration||0)+(p.duration||0)},I=await i(`deploy-retry-${_}`,()=>tt({cliPath:r,config:e,context:d,result:p.result,filter:s})),I.deployError&&S.push(I.deployError),_++});_>Oe&&!I.previewInfo&&(u=new Error(`Deploy validation failed after ${Oe} attempts`))}let{diff:R,resultDiff:E,previewInfo:v,diffBinary:N,resultDiffBinary:A}=I;if(await i("cleanup",()=>Xt({config:e,diff:R,result:x.result,duration:x.duration,resultDiff:E,diffBinary:N,resultDiffBinary:A,previewInfo:v}),J.timeUnits.minutes(10)),u)throw u;process.env.NETLIFY_LOCAL_MODE||(await l?.(),await Ft())})}catch(u){er.error("Got error while running pipeline",u),await l?.();let c=u instanceof Error&&u.message;throw await Y(e.id,e.sessionId,{result:c||"Encountered error when running agent",state:"error"}),u}finally{await En()}};import D from"process";var In="claude",Rn=e=>(e??[]).filter(t=>t.request&&t.response),xn=e=>(e??[]).filter(t=>t.site_context),rr=y("config"),nr=()=>{let e=D.env.NETLIFY_AGENT_RUNNER_ID,t=D.env.NETLIFY_AGENT_RUNNER_SESSION_ID;if(!e||!t)throw new Error("ID of agent runner is not provided");let r=D.env.NETLIFY_AGENT_RUNNER_RESULT_BRANCH,o=D.env.NETLIFY_AGENT_RUNNER_PROMPT;if(!o)throw new Error("Prompt is not provided");let n=D.env.NETLIFY_AGENT_RUNNER_AGENT||In,s=D.env.NETLIFY_AGENT_RUNNER_MODEL,a=D.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED==="1",l=D.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED==="1",i=D.env.ERROR_LOGS_PATH,m=Ie(D.env.NETLIFY_AGENT_RUNNER_CONTEXT,!0,rr),u=Rn(m),c=xn(m),d=D.env.NETLIFY_AGENT_RUNNER_HAS_REPO!=="0",h=!D.env.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED,T=D.env.NETLIFY_AGENT_RUNNER_SHA,w=vn(),f=Nt(),I={id:e,sessionId:t,resultBranch:r,prompt:o,runner:n,model:s,validateAgent:a,errorLogsPath:i,sessionHistoryContext:u,siteContext:c,hasRepo:d,useGateway:h,sha:T,accountType:w,validateAgentWithBuild:l,modelVersionOverrides:f};return rr.log({fullConfig:I}),I},vn=()=>{let e=D.env.NETLIFY_TEAM_TYPE;return e?e.includes("personal")?Ye:e.includes("pro")?"pro":e.startsWith("enterprise")?Be:e.startsWith("free")?He:je:je};var or=y("bin_cmd"),Q=Nn(nt.argv.slice(2),{string:["auth","cwd","cli-path","error-logs-path","filter","trace-exporter-url","traceparent"]});try{let e=nr();await tr({config:e,apiToken:Q.auth,cwd:Q.cwd,cliPath:Q["cli-path"],errorLogsPath:Q["error-logs-path"],filter:Q.filter,tracing:{exporterUrl:Q["trace-exporter-url"],traceparent:Q.traceparent}}),or.info("Finished agent"),nt.exit(0)}catch(e){or.error("Error running agent pipeline:",e),nt.exit(1)}
|
|
135
135
|
//# sourceMappingURL=bin.js.map
|