@netlify/agent-runner-cli 1.48.2 → 1.49.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 +43 -43
- package/dist/bin.js +39 -39
- package/dist/index.js +39 -39
- package/package.json +2 -2
- package/patches/@google+gemini-cli+0.1.17.patch +0 -87
package/dist/bin.js
CHANGED
|
@@ -1,61 +1,61 @@
|
|
|
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 tt from"process";import vn from"minimist";import{createRequire as yn}from"module";import{createTracerProvider as nr}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as rt}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as or}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as sr}from"@netlify/otel";import{propagation as nt,context as ot,W3CTraceContextPropagator as ir}from"@netlify/otel/opentelemetry";import{OTLPTraceExporter as ar}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 Pe=y("tracing"),st=async(e,t,r)=>(await nr({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new rt(new Oe),new rt(new ar({url:r.exporterUrl}))],instrumentations:[new or({skipHeaders:!0})]}),r.traceparent?(nt.setGlobalPropagator(new ir),nt.extract(ot.active(),{traceparent:r.traceparent,isRemote:!0})):ot.active());function b(e,t,r){return Pe.log(`\u23F3 TRACE: ${t} starting...`),sr(e,t,r)}var Oe=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(", ")}]`:"";Pe.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${a}`),t.status?.code===2&&t.status.message&&Pe.log(` \u274C Error: ${t.status.message}`)}};var lr=["error","failed","exception","fatal","panic","abort","crash"];function it(e){let t=e.split(`
|
|
3
|
+
`),r=[],o=-1,n=0;for(;n<t.length;){let l=t[n].slice(0,500).toLowerCase();if(lr.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 Ie from"process";import{getTracer as Vr}from"@netlify/otel";import le from"process";var ge=le.env.NETLIFY_API_URL,me=le.env.NETLIFY_API_TOKEN,G=E("api"),he=()=>le.env.NETLIFY_LOCAL_MODE==="true",ue=async(e,t={})=>{if(!ge||!me)throw new Error("No API URL or token");let r=new URL(e,ge),o={...t,headers:{...t.headers,Authorization:`Bearer ${me}`}};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&&(ge=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(me=e.constants.NETLIFY_API_TOKEN)},lt=()=>({apiUrl:ge,token:me}),ce=async(e,t)=>he()?(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)=>he()?(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)=>he()?(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)=>he()?(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"}),Pe=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 Z=E("ai_gateway"),Oe=null;var dt=async()=>{if(Oe)return Oe;Z.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 Oe=t,Z.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 Z.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return Z.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),Z.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,Z.log("Got AI gateway information",{token:!!r,expiresAt:o,url:s}),o){let f=o-Date.now()-6e4;f>0&&(n=setTimeout(()=>{l()},f))}};return await Promise.all([l(),dt()]),{get url(){return s},get token(){return r},isModelAvailableForProvider:lr}};import B from"process";import Ee from"path";import Fe from"fs";import{fileURLToPath as gr}from"url";import{execa as mr,execaCommand as Kn}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 Q=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=Ee.dirname(hr),ye=E("shell"),Le=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 Q).pipe(B.stdout),e.stdout?.pipe(new Q).pipe(B.stdout),e.stderr?.pipe(new Q).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),ye.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return ye.error("Error killing process:",r),!1}},wr=e=>Et(e,"SIGKILL"),Ir=e=>{Le.add(e);let t=ht();if(t){let r=t.onTimesUp(()=>{ye.log(`Global timer expired, killing process ${e.pid}`),Et(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ye.log(`Force killing process ${e.pid} after timeout`),wr(e))},5e3)});e.on("exit",()=>{Le.delete(e),r()}),e.on("error",()=>{Le.delete(e),r()})}};function ee(e,t){if(B.env.NODE_PATH){let n=Ee.join(B.env.NODE_PATH,".bin",t);if(Fe.existsSync(n))return n}let r=Ee.join(e,"node_modules",".bin",t);if(Fe.existsSync(r))return r;let o=Ee.join(Er,"..","node_modules",".bin",t);if(Fe.existsSync(o))return o}var yt="netlify-agent-runner-context.md",De="task-history",$e="netlify-context",k=".netlify",te="results.md",ke="assets",Ue="other",Me="personal";var Ge="enterprise",je="free",_t=[Me,"pro",Ge,je];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,f=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)})}})(),f};return a.flush=async()=>{if((r||o)&&s)return await s,a.flush()},a},_e=(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},Te=(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 f=Math.min(i-s.length,e.length);return`${s}${e.slice(0,f)}`}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 Be();let s=await He(o);await Ye(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 g=(await F("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;u!==g&&(d=Nt.from(g).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},Ye=async(e=[])=>{await F("git",["add",".",...e])},Be=async()=>(await F("git",["status","-s"])).stdout,At=/.. (.+)?\.log$/,vr=[At],Ar=async()=>{let e=await Be();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(),
|
|
8
|
+
`);return s.length>e.length*.8?e:s}import xe from"process";import{getTracer as Zr}from"@netlify/otel";import ce from"process";var he=ce.env.NETLIFY_API_URL,ye=ce.env.NETLIFY_API_TOKEN,G=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")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&&(he=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(ye=e.constants.NETLIFY_API_TOKEN)},lt=()=>({apiUrl:he,token:ye}),pe=async(e,t)=>_e()?(G.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()?(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 ct=async(e,t)=>_e()?(G.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):ue(`/api/v1/agent_runners/${e}/sessions/${t}`),ut=(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)=>_e()?(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"}),Fe=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 ee=y("ai_gateway"),Le=null;var dt=async()=>{if(Le)return Le;ee.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 Le=t,ee.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},cr=async(e,t)=>{let o=(await dt()).providers[e];if(!o)return ee.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return ee.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),ee.log("Requesting AI gateway information");let i=await ut(a,t.id,t.sessionId);if({token:r,url:s}=i,o=i.expires_at?i.expires_at*1e3:void 0,ee.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:cr}};import j from"process";import H from"path";import Ee from"fs";import{fileURLToPath as hr}from"url";import{createRequire as yr}from"module";import{execa as _r,execaCommand as Qn}from"execa";import{Transform as ur}from"stream";var pr=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"]),dr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function fr(){return Object.entries(process.env).filter(([e,t])=>!(!t||pr.has(e)||dr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function B(e){if(typeof e!="string")return e;let t=fr();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(gr(o),"g");r=r.replace(n,"******")}),r}function gr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var te=class extends ur{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),s=B(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"?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,mt=e=>(de&&de.destroy(),de=new V({totalAllowedTime:e}),de),ht=()=>de;var V=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 yt={name:"@netlify/agent-runner-cli",type:"module",version:"1.49.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 Er=hr(import.meta.url),Tr=H.dirname(Er),wr=yr(import.meta.url),Te=y("shell"),De=new Set,Ir={preferLocal:!0},F=(e,t,r)=>{let[o,n]=Rr(t,r),s={...Ir,...n},a=_r(e,o,s);return xr(a,s),Nr(a),a};var Rr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},xr=(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 te).pipe(j.stdout),e.stdout?.pipe(new te).pipe(j.stdout),e.stderr?.pipe(new te).pipe(j.stderr);return}e.stdout?.pipe(j.stdout),e.stderr?.pipe(j.stderr)},_t=(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}},vr=e=>_t(e,"SIGKILL"),Nr=e=>{De.add(e);let t=ht();if(t){let r=t.onTimesUp(()=>{Te.log(`Global timer expired, killing process ${e.pid}`),_t(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(Te.log(`Force killing process ${e.pid} after timeout`),vr(e))},5e3)});e.on("exit",()=>{De.delete(e),r()}),e.on("error",()=>{De.delete(e),r()})}};function re(e,t){if(!j.env.NETLIFY_LOCAL_MODE)try{let n=wr.resolve(yt.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(Tr,"..","node_modules",".bin",t);if(Ee.existsSync(o))return o}var Et="netlify-agent-runner-context.md",$e="task-history",ke="netlify-context",k=".netlify",ne="results.md",Ue="assets",Me="other",Ge="personal";var je="enterprise",Ye="free",Tt=[Ge,"pro",je,Ye];var wt=y("utils"),Ar=e=>new Promise(t=>{setTimeout(t,e)}),It=(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 Ar(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):wt.error("Could not parse JSON",o))}},Rt=(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)},Sr=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!Tt.some(t=>t in e),xt=()=>{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);Sr(s)&&(e[r]=s)}catch(s){let l=s instanceof SyntaxError?"Invalid JSON":s.message;wt.error(`Could not parse ${r} model version override from ${n}: ${l}`)}}}),e};import{Buffer as vt}from"buffer";import br from"path";var Nt=y("repo"),At=async({config:e})=>{Nt.info("Getting runner diffs");let t=await Pr(),{hasChanges:r}=t,{status:o}=t;if(!r)return{hasChanges:!1};let n=Or(o);await Fr(n),Nt.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 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=vt.from(f).toString("base64"))}let h={hasChanges:!0,diff:i,resultDiff:c,ignored:s};return i!==u&&(h.diffBinary=vt.from(u).toString("base64")),d&&(h.resultDiffBinary=d),h},Be=async(e=[])=>{await F("git",["add",".",...e])},He=async()=>(await F("git",["status","-s"])).stdout,St=/.. (.+)?\.log$/,Cr=[St],Pr=async()=>{let e=await He();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
9
|
+
`).filter(o=>Cr.some(s=>s instanceof RegExp?s.test(o):o===s)?!1:o[1]?.trim()!=="")).length!==0,status:e}},bt=async()=>{let{stdout:e}=await F("git",["rev-parse","HEAD"]);return e.trim()},Ct=async()=>{let{stdout:e}=await F("git",["rev-list","--max-parents=0","HEAD"]);return e.trim()},We=async e=>{e||=await He();let t=[".netlify","node_modules"],r=[];return e.split(`
|
|
10
|
+
`).forEach(o=>{t.forEach(s=>{[`?? ${s}`,`?? ${s}${br.sep}`].some(l=>o.startsWith(l))&&r.push(`:!${s}`)});let n=o.match(St)?.[1];n&&r.push(`:!${n}.log`)}),r},Pt=async()=>{await F("git",["reset","--hard","HEAD"])},Or=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)},Fr=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 Dr from"fs/promises";import $r from"os";import Lt from"path";import J from"process";import kr from"readline";import qe from"path";import Lr from"fs/promises";var Ke=y("agent-output-utils");async function oe({initialResult:e,agentName:t,hasError:r}){let o="",n=qe.join(process.cwd(),k,ne);try{let s=await Lr.readFile(n,"utf-8");s&&(o=s,Ke.log(`Pulled result from ${qe.relative(process.cwd(),n)}`))}catch{Ke.log(`No results file found at ${qe.relative(process.cwd(),n)}`)}return o||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function se({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&&Ke.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function ie(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"),Ot="Claude Code",Re="claude-sonnet-4-5-20250929",Ft=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,Ur=({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 Ve({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`);J.env.ANTHROPIC_API_KEY=_,J.env.ANTHROPIC_BASE_URL=g}else if(!J.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let d=[],h=[],T={},w=0,f=0,I,x,S=[re(J.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=`${J.env.NVM_BIN}/node`;U.log(`Running ${R} ${S.join(" ")}`);let E=t.utils.run(R,S,{all:!0,env:J.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=kr.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:[Ft(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,Q;if(O){let W=O.input?.file_path&&Lt.relative(J.cwd(),O.input.file_path),P=W&&`\`${W}\``;Q=[Ft(O.name||""),P].filter(Boolean).join(" ")}let me=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(O?.name||""),K;if(typeof p.content=="string")K=p.content;else if(Array.isArray(p.content)){let W=[];p.content.forEach(P=>{P?.type==="text"&&typeof P.text=="string"?W.push(P.text):P?.type==="image"&&typeof P.source=="object"&&P.source?P.source.type==="base64"&&P.source.media_type?W.push(``):U.log(`Unsupported image type ${P.source.type}`,P.source):U.log(`Unsupported block type ${P?.type}`)}),K=W.join(`
|
|
12
12
|
|
|
13
|
-
`)}
|
|
14
|
-
${
|
|
15
|
-
\`\`\``),
|
|
16
|
-
`):
|
|
17
|
-
`));
|
|
13
|
+
`)}me&&K&&(K=`\`\`\`
|
|
14
|
+
${K.trim()}
|
|
15
|
+
\`\`\``),N({title:Q,message:K},!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}=Ur({catchError:_,runCmd:E,error:x,result:I,runnerName:"Claude"}))}),A.close(),v.flush(),{steps:h,duration:f,result:await oe({initialResult:I,agentName:Ot,hasError:!!x}),error:se({error:x,agentName:Ot}),isRetryableError:ie(x),agentSessionId:c}}var Dt=async()=>{let e=Lt.join($r.homedir(),".claude");await Dr.rm(e,{recursive:!0,force:!0})};import Mr from"fs/promises";import Gr from"os";import jr from"path";import ae from"process";import Yr from"readline";var X=y("runner_codex"),$t="Codex CLI",Br=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(X.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?(X.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}):(X.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function Je({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`);ae.env.OPENAI_API_KEY=R,ae.env.OPENAI_BASE_URL=E}else if(!ae.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let m=[],u=[],c={},d=0,h=0,T,w,f=[re(ae.cwd(),"codex"),"--approval-mode","full-auto",n?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...i?["--model",i]:[],"-q",a].filter(Boolean),I=`${ae.env.NVM_BIN}/node`;X.log(`Running ${I} ${f.join(" ")}`);let x=t.utils.run(I,f,{all:!0,env:{...ae.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),S=Yr.createInterface({input:x.all});return S.on("error",R=>{X.error("Readline interface error",{error:R.message,stack:R.stack})}),S.on("line",R=>{let E=null;try{E=JSON.parse(R)}catch{X.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=Wr(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=Br({catchError:R,runCmd:x,error:w,result:T,runnerName:"Codex"});w=E.error,T=E.result}),S.close(),{steps:u,duration:h,result:await oe({initialResult:T,agentName:$t,hasError:!!w}),error:se({error:w,agentName:$t}),isRetryableError:ie(w)}}var kt=async()=>{let e=jr.join(Gr.homedir(),".codex");await Mr.rm(e,{recursive:!0,force:!0})},Hr=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=>!Hr.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){
|
|
20
|
-
${
|
|
21
|
-
\`\`\``),
|
|
19
|
+
\`\`\``)}catch(s){X.error("Could not decode outputMsg",s,t.output)}return{title:o,message:n}};import qr from"fs/promises";import Kr from"os";import Mt from"path";import z from"process";import Vr from"readline";var le=y("runner_gemini"),Ut="Gemini CLI",Jr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(le.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?(le.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}):(le.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"};async function Xe({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:_,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=[re(z.cwd(),"gemini"),...i?["--model",i]:[],"--yolo","--output-format","stream-json","-p",a],x=`${z.env.NVM_BIN}/node`;le.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",_=>{le.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,Q=O&&Mt.relative(z.cwd(),O),me=g.parameters?.command,W={title:[p,Q&&`\`${Q}\``,me&&`\`${me}\``].filter(Boolean).join(" ")};d[g.tool_id]=W,R.flush();break}case"tool_result":{let p=d[g.tool_id];p&&(g.output&&(p.message=`\`\`\`
|
|
20
|
+
${g.output.trim()}
|
|
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:{le.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 oe({initialResult:w,agentName:Ut,hasError:!!f}),error:se({error:f,agentName:Ut}),isRetryableError:ie(f)}}var Gt=async()=>{let e=Mt.join(Kr.homedir(),".gemini");await qr.rm(e,{recursive:!0,force:!0})};var zr={codex:{runner:Je,clean:kt},claude:{runner:Ve,clean:Dt},gemini:{runner:Xe,clean:Gt}},jt=zr;var Qr=y("init_stage"),Yt=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>await b(Zr(),"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=jt[e.runner];if(!a)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let l=en({apiToken:r});at(l);let i=e.useGateway?await ft({netlify:l,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!i}),e.validateAgent&&e.errorLogsPath&&n?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let m=It(({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);Qr.info("Adding build files to stage");let u=await We();await Be(u);let c;e.hasRepo?e.sha?(c=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(c=await bt(),await pe(e.id,{sha:c}),n?.setAttributes({"init.sha.source":"current_commit"})):(c=await Ct(),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}}),en=({apiToken:e})=>({constants:{NETLIFY_API_HOST:xe.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||xe.env.NETLIFY_API_TOKEN,SITE_ID:xe.env.SITE_ID,FUNCTIONS_DIST:xe.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:F}});import{getTracer as ze}from"@netlify/otel";import tn from"crypto";import q from"fs/promises";import $ from"path";import M from"process";var L=y("context"),rn=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:M.env.NETLIFY_TEAM_ID,userId:M.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:M.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},nn=10,on=async e=>{let{name:t,ext:r}=$.parse(e),o=e,n=$.join(M.cwd(),k,o),s=0;for(;await sn(n);){if(s>=nn)throw new Error("Failed to generate context file");o=`${t}-${tn.randomUUID().slice(0,5)}${r}`,n=$.join(M.cwd(),k,o),s+=1}return o},sn=async e=>{try{return await q.access(e),!0}catch{return!1}},an=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}},ln=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 q.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}},ve=null,cn=async()=>{if(ve)return ve;let e=await an();if(!e)return[];let t=$.join(M.cwd(),k,ke);await q.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,ke,a);return L.log(`Downloading ${s.scope} context...`),await ln(s.endpoint,l)?(L.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:n}):null});return ve=(await Promise.all(r)).filter(n=>n!==null),ve},Bt=async({cliPath:e,netlify:t,config:r,buildErrorContext:o})=>{let n=rn(t),s=await on(Et),a=$.join(M.cwd(),k);await q.mkdir(a,{recursive:!0});let l=$.join(k,s),i=$.join(M.cwd(),l),m=$.join(M.cwd(),k,ne);try{await q.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
|
-
${r.siteContext.filter(
|
|
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
|
|
34
|
+
`);let d="";if(r.sessionHistoryContext?.length){let f=$.join(M.cwd(),k,$e);await q.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,$e,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 q.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
|
-
${
|
|
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 cn(),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.
|
|
57
57
|
|
|
58
|
-
${h.map(
|
|
58
|
+
${h.map(f=>`- **${f.scope}**: ${f.path}`).join(`
|
|
59
59
|
`)}
|
|
60
60
|
|
|
61
61
|
Refer to these files when working with specific Netlify features.
|
|
@@ -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}/${ne} 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}/${ne} 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}/${Ue} folder
|
|
84
|
+
- move assets from ${a}/${Ue} 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>
|
|
@@ -100,7 +100,7 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
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.
|
|
102
102
|
</environment>
|
|
103
|
-
${
|
|
103
|
+
${T}
|
|
104
104
|
<docs>
|
|
105
105
|
- Netlify Docs: https://docs.netlify.com
|
|
106
106
|
- LLM Resources Index: https://docs.netlify.com/llms.txt
|
|
@@ -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 q.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
|
|
123
|
-
${
|
|
122
|
+
`),w};var un=y("prompt"),Ht=async({cliPath:e,config:t,netlify:r,buildErrorContext:o})=>{let n=await Bt({cliPath:e,config:t,netlify:r,buildErrorContext:o});return process.env.AGENT_RUNNER_DEBUG&&un.log("Contextful Prompt:",n),{prompt:n}};var Ne=y("inference_stage"),Wt=5,Ae=async e=>{let{cliPath:t,config:r,context:o,buildErrors:n,runner:s,persistSteps:a,aiGateway:l,attempt:i,contextPrefix:m,priorAgentSessionId:u}=e;Ne.log(`Running inference stage, attempt ${i} of ${Wt}`);let c=await b(ze(),"inference-stage",async d=>{d?.setAttributes({"inference.attempt":i||1}),gt();let{prompt:h}=await b(ze(),"compose-prompt",async()=>await Ht({cliPath:t,config:r,buildErrorContext:pn(n),netlify:o})),T=`
|
|
123
|
+
${m||""}
|
|
124
124
|
${h}
|
|
125
|
-
`.trim(),w={...r,prompt:
|
|
125
|
+
`.trim(),w={...r,prompt:T},f=await b(ze(),`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(Ne.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<Wt))return Ne.log("Retrying inference stage"),await new Promise(h=>setTimeout(h,5e3)),{runnerResult:(await Ae({...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 Ne.log("Do not retry inference stage"),new Error(c.error)}return{runnerResult:c}},pn=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 gn from"process";import{getTracer as Ze}from"@netlify/otel";import{getTracer as dn}from"@netlify/otel";var fe=y("deploy"),qt=async e=>await b(dn(),"create-preview-deploy",async t=>fn(e,t)),fn=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"),Qe=async e=>await b(Ze(),"run-deploy-stage",async()=>mn(e)),mn=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let s=await b(Ze(),"get-runner-diffs",async()=>await At({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(Ze(),"get-runner-session",async()=>await ct(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 qt({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:d,skipBuild:!1,deploySubdomain:Rt(t.id,gn.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 be}from"@netlify/otel";async function Kt(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 Se=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,
|
|
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"),Vt=async e=>await b(be(),"cleanup-stage",async()=>hn(e)),et=1024*1024*10,hn=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 Se,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 pt(e.id,e.sessionId),c=[];(t||s)&&c.push(Fe(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(Fe(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(be(),"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>et||d>et){let h=`Diffs exceed maximum inline size of ${et} 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(be(),"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 Kt(async()=>await b(be(),"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 Jt,shutdownTracers as _n,withActiveSpan as Xt}from"@netlify/otel";var En=yn(import.meta.url),zt=En("../package.json"),Zt=y("pipeline_index"),Ce=3,Qt=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:s,tracing:a={}})=>{let l,{withStageTimer:i}=mt(V.timeUnits.hours(4)),m=await st(zt.version,e.id,a);try{await Xt(Jt(),"run-pipeline",{},m,async()=>{let u,{aiGateway:c,context:d,persistSteps:h,runner:T,sha:w}=await i("init",()=>Yt({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:s,runnerVersion:zt.version}),V.timeUnits.minutes(10));l=T.clean,e.sha=w;let{runnerResult:f}=await i("inference",()=>Ae({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",()=>Qe({cliPath:r,config:e,context:d,result:f.result,filter:s})),x=f,S=[];if(I.hasChanges&&I.deployError){S.push(it(I.deployError));let _=1;for(;_<=Ce&&!I.previewInfo;)Zt.log(`Deploy attempt had errors. Retrying. ${_}/${Ce}`),await Xt(Jt(),"deploy-stage",async g=>{g?.setAttributes({"stage.attempt":_});let{runnerResult:p}=await i(`inference-retry-${_}`,()=>Ae({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-${_}`,()=>Qe({cliPath:r,config:e,context:d,result:p.result,filter:s})),I.deployError&&S.push(I.deployError),_++});_>Ce&&!I.previewInfo&&(u=new Error(`Deploy validation failed after ${Ce} attempts`))}let{diff:R,resultDiff:E,previewInfo:v,diffBinary:N,resultDiffBinary:A}=I;if(await i("cleanup",()=>Vt({config:e,diff:R,result:x.result,duration:x.duration,resultDiff:E,diffBinary:N,resultDiffBinary:A,previewInfo:v}),V.timeUnits.minutes(10)),u)throw u;process.env.NETLIFY_LOCAL_MODE||(await l?.(),await Pt())})}catch(u){Zt.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 _n()}};import D from"process";var wn="claude",In=e=>(e??[]).filter(t=>t.request&&t.response),Rn=e=>(e??[]).filter(t=>t.site_context),er=y("config"),tr=()=>{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||wn,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,er),u=In(m),c=Rn(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=xn(),f=xt(),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 er.log({fullConfig:I}),I},xn=()=>{let e=D.env.NETLIFY_TEAM_TYPE;return e?e.includes("personal")?Ge:e.includes("pro")?"pro":e.startsWith("enterprise")?je:e.startsWith("free")?Ye:Me:Me};var rr=y("bin_cmd"),Z=vn(tt.argv.slice(2),{string:["auth","cwd","cli-path","error-logs-path","filter","trace-exporter-url","traceparent"]});try{let e=tr();await Qt({config:e,apiToken:Z.auth,cwd:Z.cwd,cliPath:Z["cli-path"],errorLogsPath:Z["error-logs-path"],filter:Z.filter,tracing:{exporterUrl:Z["trace-exporter-url"],traceparent:Z.traceparent}}),rr.info("Finished agent"),tt.exit(0)}catch(e){rr.error("Error running agent pipeline:",e),tt.exit(1)}
|
|
135
135
|
//# sourceMappingURL=bin.js.map
|