@netlify/agent-runner-cli 1.52.0 → 1.54.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 CHANGED
@@ -1,37 +1,45 @@
1
1
  #!/usr/bin/env node
2
- import O from"process";import er from"path";import tr from"fs";import En from"minimist";import{createRequire as mn}from"module";import{createTracerProvider as rr}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as nt}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as nr}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as or}from"@netlify/otel";import{propagation as ot,context as it,W3CTraceContextPropagator as ir}from"@netlify/otel/opentelemetry";import{OTLPTraceExporter as sr}from"@opentelemetry/exporter-trace-otlp-grpc";function E(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 $e=E("tracing"),st=async(e,t,r)=>(await rr({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new nt(new De),new nt(new sr({url:r.exporterUrl}))],instrumentations:[new nr({skipHeaders:!0})]}),r.traceparent?(ot.setGlobalPropagator(new ir),ot.extract(it.active(),{traceparent:r.traceparent,isRemote:!0})):it.active());function b(e,t,r){return $e.log(`\u23F3 TRACE: ${t} starting...`),or(e,t,r)}var De=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,s]of Object.entries(o))l.includes("duration")&&typeof s=="number"?n.push(`${l}=${s.toFixed(2)}ms`):n.push(`${l}=${s}`);let i=t.status?.code===2?"\u274C":"\u2705",a=n.length>0?` [${n.join(", ")}]`:"";$e.log(`${i} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${a}`),t.status?.code===2&&t.status.message&&$e.log(` \u274C Error: ${t.status.message}`)}};var ar=["error","failed","exception","fatal","panic","abort","crash"];function at(e){let t=e.split(`
3
- `),r=[],o=-1,n=0;for(;n<t.length;){let l=t[n].slice(0,500).toLowerCase();if(ar.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 f=m;f<=u;f++)c.push(t[f]);r.push(c.join(`
4
- `)),o=u,n=u+1}else n++}if(r.length===0)return e;let i=r.map((a,l)=>`<extracted_error_chunk order="${l+1}">
5
- ${a}
2
+ import C from"process";import nr from"path";import or from"fs";import En from"minimist";import{createRequire as hn}from"module";import{createTracerProvider as ir}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as it}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as sr}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as ar}from"@netlify/otel";import{propagation as st,context as at,W3CTraceContextPropagator as lr}from"@netlify/otel/opentelemetry";import{OTLPTraceExporter as cr}from"@opentelemetry/exporter-trace-otlp-grpc";function _(e){let t=!process.env.VITEST;return{log:(...r)=>{t&&console.log(`[AR]-[${e}]`,...r)},error:(...r)=>{t&&console.error(`[AR]-[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 Le=_("tracing"),lt=async(e,t,r)=>(await ir({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new it(new Ue),new it(new cr({url:r.exporterUrl}))],instrumentations:[new sr({skipHeaders:!0})]}),r.traceparent?(st.setGlobalPropagator(new lr),st.extract(at.active(),{traceparent:r.traceparent,isRemote:!0})):at.active());function S(e,t,r){return Le.log(`\u23F3 TRACE: ${t} starting...`),ar(e,t,r)}var Ue=class{export(t,r){for(let n of t)this.logSpan(n);r({code:1})}async shutdown(){}forceFlush(){return Promise.resolve()}logSpan(t){let r=(t.endTime[0]-t.startTime[0])*1e3+(t.endTime[1]-t.startTime[1])/1e6,n=t.attributes,o=[];for(let[c,s]of Object.entries(n))c.includes("duration")&&typeof s=="number"?o.push(`${c}=${s.toFixed(2)}ms`):o.push(`${c}=${s}`);let i=t.status?.code===2?"\u274C":"\u2705",l=o.length>0?` [${o.join(", ")}]`:"";Le.log(`${i} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${l}`),t.status?.code===2&&t.status.message&&Le.log(` \u274C Error: ${t.status.message}`)}};var ur=["error","failed","exception","fatal","panic","abort","crash"];function ct(e){let t=e.split(`
3
+ `),r=[],n=-1,o=0;for(;o<t.length;){let c=t[o].slice(0,500).toLowerCase();if(ur.some(m=>c.includes(m))){let m=Math.max(0,o-10,n+1),p=Math.min(t.length-1,o+20),u=[];for(let g=m;g<=p;g++)u.push(t[g]);r.push(u.join(`
4
+ `)),n=p,o=p+1}else o++}if(r.length===0)return e;let i=r.map((l,c)=>`<extracted_error_chunk order="${c+1}">
5
+ ${l}
6
6
  </extracted_error_chunk>`).join(`
7
7
 
8
- `);return i.length>e.length*.8?e:i}import Ne from"process";import{getTracer as Xr}from"@netlify/otel";import ue from"process";var ye=ue.env.NETLIFY_API_URL,Ee=ue.env.NETLIFY_API_TOKEN,Y=E("api"),_e=()=>ue.env.NETLIFY_LOCAL_MODE==="true",de=async(e,t={})=>{if(!ye||!Ee)throw new Error("No API URL or token");let r=new URL(e,ye),o={...t,headers:{...t.headers,Authorization:`Bearer ${Ee}`}};ue.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),i=n.ok&&n.status<=299;if(ue.env.AGENT_RUNNERS_DEBUG==="true")Y.log(`Response headers for ${r}:`),n.headers.forEach((l,s)=>{Y.log(` ${s}: ${l}`)});else{let l=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");Y.log(`Request ID for ${r}: ${l||"N/A"}`)}if(i||Y.error(`Got status ${n.status} for request ${r}`),t.raw){if(!i)throw n;return n}let a=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!i)throw a;return a},lt=e=>{Y.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(ye=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Ee=e.constants.NETLIFY_API_TOKEN)},ct=()=>({apiUrl:ye,token:Ee}),pe=async(e,t)=>_e()?(Y.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):de(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),q=async(e,t,r)=>_e()?(Y.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):de(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var ut=async(e,t)=>_e()?(Y.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):de(`/api/v1/agent_runners/${e}/sessions/${t}`),dt=(e,t,r)=>de(`/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()?(Y.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"}}):de(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Le=async(e,t)=>{Y.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 ne=E("ai_gateway"),Ue=null;var ft=async()=>{if(Ue)return Ue;ne.log("Fetching available AI gateway providers");let e=await fetch(`${ct().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 Ue=t,ne.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},lr=async(e,t)=>{let o=(await ft()).providers[e];if(!o)return ne.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return ne.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},gt=async({netlify:e,config:t})=>{let r,o,n,i,a=e.constants?.SITE_ID;if(!a)throw new Error("No site id");let l=async()=>{clearTimeout(n),ne.log("Requesting AI gateway information");let s=await dt(a,t.id,t.sessionId);if({token:r,url:i}=s,o=s.expires_at?s.expires_at*1e3:void 0,ne.log("Got AI gateway information",{token:!!r,expiresAt:o,url:i}),o){let m=o-Date.now()-6e4;m>0&&(n=setTimeout(()=>{l()},m))}};return await Promise.all([l(),ft()]),{get url(){return i},get token(){return r},isModelAvailableForProvider:lr}};import B from"process";import W from"path";import we from"fs";import{fileURLToPath as mr}from"url";import{createRequire as hr}from"module";import{execa as yr,execaCommand as Wn}from"execa";import{Transform as cr}from"stream";var ur=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 pr(){return Object.entries(process.env).filter(([e,t])=>!(!t||ur.has(e)||dr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function K(e){if(typeof e!="string")return e;let t=pr();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 oe=class extends cr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),i=K(n);o(null,i)}};function mt(){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,i){let a=typeof o=="string"?K(o):o;return typeof n=="function"?t(a,n):t(a,n,i)},process.stderr.write=function(o,n,i){let a=typeof o=="string"?K(o):o;return typeof n=="function"?r(a,n):r(a,n,i)}}var fe=null,ht=e=>(fe&&fe.destroy(),fe=new z({totalAllowedTime:e}),fe),yt=()=>fe;var z=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.`)}),i=null,a=null;o!==void 0&&(a=new Promise((l,s)=>{i=setTimeout(()=>{s(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return a?await Promise.race([r(),a]):await r()}finally{n(),i&&clearTimeout(i)}};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.52.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=mr(import.meta.url),_r=W.dirname(Er),wr=hr(import.meta.url),Ie=E("shell"),Me=new Set,Ir={preferLocal:!0},P=(e,t,r)=>{let[o,n]=Tr(t,r),i={...Ir,...n},a=yr(e,o,i);return xr(a,i),Rr(a),a};var Tr=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(B.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new oe).pipe(B.stdout),e.stdout?.pipe(new oe).pipe(B.stdout),e.stderr?.pipe(new oe).pipe(B.stderr);return}e.stdout?.pipe(B.stdout),e.stderr?.pipe(B.stderr)},_t=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(B.kill(-e.pid,t),Ie.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return Ie.error("Error killing process:",r),!1}},vr=e=>_t(e,"SIGKILL"),Rr=e=>{Me.add(e);let t=yt();if(t){let r=t.onTimesUp(()=>{Ie.log(`Global timer expired, killing process ${e.pid}`),_t(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(Ie.log(`Force killing process ${e.pid} after timeout`),vr(e))},5e3)});e.on("exit",()=>{Me.delete(e),r()}),e.on("error",()=>{Me.delete(e),r()})}};function Te(e,t){return!!Z(e,t)}function Z(e,t){if(!B.env.NETLIFY_LOCAL_MODE)try{let n=wr.resolve(Et.name),i=W.dirname(n);for(;i!==W.dirname(i);){let a=W.dirname(i);if(W.basename(a)==="node_modules"){let l=W.join(a,".bin",t);if(we.existsSync(l))return l;break}i=a}}catch(n){console.error("Could not resolve package.json",n)}if(B.env.NODE_PATH){let n=W.join(B.env.NODE_PATH,".bin",t);if(we.existsSync(n))return n}let r=W.join(e,"node_modules",".bin",t);if(we.existsSync(r))return r;let o=W.join(_r,"..","node_modules",".bin",t);if(we.existsSync(o))return o}var wt="netlify-agent-runner-context.md",je="task-history",Ge="netlify-context",U=".netlify",ie="results.md",Ye="assets";var Sr=E("utils"),Ar=e=>new Promise(t=>{setTimeout(t,e)}),It=(e,t=3e3)=>{let r=!1,o=null,n=[],i=null,a=(...l)=>{if(r)return o=l,new Promise(u=>{n.push(u)});r=!0;let s,m=new Promise(u=>{s=u});return i=(async()=>{await Promise.resolve();let u=await e(...l);for(s(u);;){if(await Ar(t),!o)return r=!1,i=null,u;let c=o,f=n;o=null,n=[],u=await e(...c),f.forEach(h=>{h(u)})}})(),m};return a.flush=async()=>{if((r||o)&&i)return await i,a.flush()},a},xe=(e,t,r=!1)=>{let o=null,n=null,i=null,a=function(...l){n=l,i=this;let s=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(i,n),n=null,i=null)},t),s&&(e.apply(i,n),n=null,i=null)};return a.cancel=()=>{clearTimeout(o),o=null,n=null,i=null},a.flush=()=>{if(o){clearTimeout(o);let l=n,s=i;o=null,n=null,i=null,e.apply(s,l)}},a},Tt=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):Sr.error("Could not parse JSON",o))}},xt=(e,t)=>{let n=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let l=`--${t}${n}`;if(l.length>55)return"";let s=60-l.length;if(s<=0)return"";if(s>=i.length+6){let m=Math.min(s-i.length,e.length);return`${i}${e.slice(0,m)}`}return e.slice(0,s)};import{Buffer as vt}from"buffer";import Nr from"path";var Rt=E("repo"),St=async({config:e})=>{Rt.info("Getting runner diffs");let t=await Cr(),{hasChanges:r}=t,{status:o}=t;if(!r)return{hasChanges:!1};let n=Pr(o);await Or(n),Rt.info("Changes after processing"),await He();let i=await qe(o);await Be(i);let a={stdio:["ignore","pipe","pipe"]},s=(await P("git",["diff","--staged"],a)).stdout;if(r=!!s,!r)return{hasChanges:!1,ignored:i};let u=(await P("git",["diff","--staged","--binary"],a)).stdout,c,f;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await P("git",["commit","-m","Agent runner"]),c=(await P("git",["diff",e.sha,"HEAD"],a)).stdout;let g=(await P("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;c!==g&&(f=vt.from(g).toString("base64"))}let h={hasChanges:!0,diff:s,resultDiff:c,ignored:i};return s!==u&&(h.diffBinary=vt.from(u).toString("base64")),f&&(h.resultDiffBinary=f),h},Be=async(e=[])=>{await P("git",["add",".",...e])},He=async()=>(await P("git",["status","-s"])).stdout,At=/.. (.+)?\.log$/,br=[At],Cr=async()=>{let e=await He();return{hasChanges:(e.trim().length===0?[]:e.split(`
9
- `).filter(o=>br.some(i=>i instanceof RegExp?i.test(o):o===i)?!1:o[1]?.trim()!=="")).length!==0,status:e}},Nt=async()=>{let{stdout:e}=await P("git",["rev-parse","HEAD"]);return e.trim()},bt=async()=>{let{stdout:e}=await P("git",["rev-list","--max-parents=0","HEAD"]);return e.trim()},qe=async e=>{e||=await He();let t=[".netlify","node_modules"],r=[];return e.split(`
10
- `).forEach(o=>{t.forEach(i=>{[`?? ${i}`,`?? ${i}${Nr.sep}`].some(l=>o.startsWith(l))&&r.push(`:!${i}`)});let n=o.match(At)?.[1];n&&r.push(`:!${n}.log`)}),r},Ct=async()=>{await P("git",["reset","--hard","HEAD"])},Pr=e=>{let t=e.split(`
11
- `).reduce((r,o)=>{if(!o)return r;let[n,i,,...a]=o,l=a.join(""),s=n.trim(),m=i.trim();return r[l]?r[l].change=m:r[l]={filePath:l,stage:s,change:m},r},{});return Object.values(t)},Or=async e=>{let t=[];for(let r of e)r.stage&&!r.change&&t.push(P("git",["restore","--staged","--worktree",r.filePath]));await Promise.allSettled(t)};import kr from"fs/promises";import $r from"os";import Ft from"path";import Q from"process";import Dr from"readline";import Ke from"path";import Fr from"fs/promises";var We=E("agent-output-utils");async function se({initialResult:e,agentName:t,hasError:r}){let o="",n=Ke.join(process.cwd(),U,ie);try{let i=await Fr.readFile(n,"utf-8");i&&(o=i,We.log(`Pulled result from ${Ke.relative(process.cwd(),n)}`))}catch{We.log(`No results file found at ${Ke.relative(process.cwd(),n)}`)}return o||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function ae({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&&We.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function le(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 M=E("runner_claude"),Pt="Claude Code",ve="claude-sonnet-4-5-20250929",Ot=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,Lr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(M.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?(M.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}):(M.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:i}){let a=e,{accountType:l,prompt:s,modelVersionOverrides:m}=a,{model:u}=a,c="";if(o){let{token:y,url:p}=o;if(!y||!p)throw new Error("No token or url provided from AI Gateway");if(m?.claude){let d=m?.claude?.[l];if(d){if(!await o.isModelAvailableForProvider("anthropic",d))throw new Error(`Model override '${d}' is not available for anthropic provider`);u=d}}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",ve)?(u=ve,M.log(`Using default model: ${ve}`)):M.log(`Default model ${ve} is not available, proceeding without model specification`);Q.env.ANTHROPIC_API_KEY=y,Q.env.ANTHROPIC_BASE_URL=p}else if(!Q.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let f=[],h=[],w={},I=0,g=0,v,x,N=[Z(Q.cwd(),"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...u?["--model",u]:[],...n?["--continue"]:[],...n&&i?["--resume",i]:[],"-p",s],T=`${Q.env.NVM_BIN}/node`;M.log(`Running ${T} ${N.join(" ")}`);let _=t.utils.run(T,N,{all:!0,env:Q.env});_.stdin?.end();let R=xe(()=>{r?.({steps:f,duration:g})},250),S=(y,p)=>{let d={...y,id:I};I+=1,h.push(d),f.push(d),p||R.flush(),R(),p&&R.flush()},A=Dr.createInterface({input:_.all});return A.on("error",y=>{M.error("Readline interface error",{error:y.message,stack:y.stack})}),A.on("line",y=>{let p=null;try{p=JSON.parse(y)}catch{M.log("Could not parse line",y)}p?.session_id&&p.session_id!==c&&(c=p.session_id),Array.isArray(p?.message?.content)?p.message.content.forEach(d=>{switch(d.type){case"text":{d.text&&S({message:d.text});break}case"image":{typeof d.source=="object"&&d.source&&d.source.type==="base64"&&d.source.media_type?S({message:`![](data:${d.source.media_type};base64,${d.source.data})`}):M.log(`Unsupported image type ${d.source?.type}`,d.source);break}case"tool_use":{if(d.name==="Task"){let $=d.input?.description&&`\`${d.input.description}\``;S({title:[Ot(d.name),$].filter(Boolean).join(" ")})}else d.id&&(w[d.id]=d);R.flush();break}case"tool_result":{let $=d.tool_use_id?w[d.tool_use_id]:void 0,re;if($){let V=$.input?.file_path&&Ft.relative(Q.cwd(),$.input.file_path),F=V&&`\`${V}\``;re=[Ot($.name||""),F].filter(Boolean).join(" ")}let he=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes($?.name||""),X;if(typeof d.content=="string")X=d.content;else if(Array.isArray(d.content)){let V=[];d.content.forEach(F=>{F?.type==="text"&&typeof F.text=="string"?V.push(F.text):F?.type==="image"&&typeof F.source=="object"&&F.source?F.source.type==="base64"&&F.source.media_type?V.push(`![](data:${F.source.media_type};base64,${F.source.data})`):M.log(`Unsupported image type ${F.source.type}`,F.source):M.log(`Unsupported block type ${F?.type}`)}),X=V.join(`
12
-
13
- `)}he&&X&&(X=`\`\`\`
14
- ${X.trim()}
15
- \`\`\``),S({title:re,message:X},!0);break}case"thinking":{d.thinking&&S({title:"Thinking",message:d.thinking},!0);break}default:M.log(`Message content type is not supported ${d.type}`,d)}}):p?.type==="result"&&(g=p.duration_ms||0,p.is_error?x=p.result:v=p.result,[h,f].forEach(d=>{d[d.length-1]?.message===v&&d.pop()}))}),await _.catch(y=>{({error:x,result:v}=Lr({catchError:y,runCmd:_,error:x,result:v,runnerName:"Claude"}))}),A.close(),R.flush(),{steps:h,duration:g,result:await se({initialResult:v,agentName:Pt,hasError:!!x}),error:ae({error:x,agentName:Pt}),isRetryableError:le(x),agentSessionId:c}}var kt=async()=>{let e=Ft.join($r.homedir(),".claude");await kr.rm(e,{recursive:!0,force:!0})};import Ur from"fs/promises";import Mr from"os";import jr from"path";import ce from"process";import Gr from"readline";var ee=E("runner_codex"),$t="Codex CLI",Yr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(ee.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?(ee.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}):(ee.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:i,prompt:a,modelVersionOverrides:l}=e,{model:s}=e;if(n){let{token:T,url:_}=n;if(!T||!_)throw new Error("No token or url provided from AI Gateway");if(l?.codex){let R=l?.codex?.[i];if(R){if(!await n.isModelAvailableForProvider("openai",R))throw new Error(`Model override '${R}' is not available for openai provider`);s=R}}else if(s&&!await n.isModelAvailableForProvider("openai",s))throw new Error(`Model '${s}' is not available for openai provider`);ce.env.OPENAI_API_KEY=T,ce.env.OPENAI_BASE_URL=_}else if(!ce.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let m=[],u=[],c={},f=0,h=0,w,I,g=[Z(ce.cwd(),"codex"),"--approval-mode","full-auto",n?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...s?["--model",s]:[],"-q",a].filter(Boolean),v=`${ce.env.NVM_BIN}/node`;ee.log(`Running ${v} ${g.join(" ")}`);let x=t.utils.run(v,g,{all:!0,env:{...ce.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),N=Gr.createInterface({input:x.all});return N.on("error",T=>{ee.error("Readline interface error",{error:T.message,stack:T.stack})}),N.on("line",T=>{let _=null;try{_=JSON.parse(T)}catch{ee.log("Could not parse line",T);return}let R=[],S=!1;if(_?.duration_ms&&(h=_.duration_ms,S=!0),_?.type==="local_shell_call")c[_.call_id]=_;else if(_?.type==="local_shell_call_output"){let A=Hr(c[_.call_id],_);A&&(A.id=f,f+=1,u.push(A),m.push(A),R.push(A),S=!0)}else _?.type==="message"&&_.role==="assistant"?w=_.content.map(A=>A.text).join(`
16
- `):_?.type==="message"&&_.role==="system"&&(I=_.content.map(A=>A.text).join(`
17
- `));S&&(r?.({steps:m,duration:h}),o?.({steps:R,duration:h}))}),await x.catch(T=>{let _=Yr({catchError:T,runCmd:x,error:I,result:w,runnerName:"Codex"});I=_.error,w=_.result}),N.close(),{steps:u,duration:h,result:await se({initialResult:w,agentName:$t,hasError:!!I}),error:ae({error:I,agentName:$t}),isRetryableError:le(I)}}var Dt=async()=>{let e=jr.join(Mr.homedir(),".codex");await Ur.rm(e,{recursive:!0,force:!0})},Br=new Set(["bash","-lc"]),Hr=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(i=>!Br.has(i)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
18
- ${n.trim()}
19
- \`\`\``)}catch(i){ee.error("Could not decode outputMsg",i,t.output)}return{title:o,message:n}};import Se from"fs/promises";import Ut from"os";import Ae from"path";import te from"process";import qr from"readline";var j=E("runner_gemini"),Lt="Gemini CLI",Re="gemini-2.5-pro",Kr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(j.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?(j.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}):(j.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),Wr={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"},Vr=async()=>{let e=Ae.join(Ut.homedir(),".gemini"),t=Ae.join(e,"settings.json");try{await Se.mkdir(e,{recursive:!0});let r={};try{let o=await Se.readFile(t,"utf-8");r=JSON.parse(o)}catch{j.log("Creating new Gemini CLI settings file")}r.general||(r.general={}),r.general.previewFeatures||(r.general.previewFeatures=!0),r.model||(r.model={}),r.model.compressionThreshold!==.3&&(r.model.compressionThreshold=.3),await Se.writeFile(t,JSON.stringify(r,null,2),"utf-8"),j.log("Configured Gemini CLI settings (preview features and compression threshold)")}catch(r){j.error("Failed to ensure Gemini CLI settings",{error:r.message})}};async function Xe({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:i,prompt:a,modelVersionOverrides:l}=e,{model:s}=e;if(await Vr(),n){let{token:y,url:p}=n;if(!y||!p)throw new Error("No token or url provided from AI Gateway");if(l?.gemini){let d=l?.gemini?.[i];if(d){if(!await n.isModelAvailableForProvider("gemini",d))throw new Error(`Model override '${d}' is not available for gemini provider`);s=d}}if(!s)await n.isModelAvailableForProvider("gemini",Re)?(s=Re,j.log(`Using default model: ${Re}`)):j.log(`Default model ${Re} is not available, proceeding without model specification`);else if(s&&!l?.gemini?.[i]&&!await n.isModelAvailableForProvider("gemini",s))throw new Error(`Model '${s}' is not available for gemini provider`);te.env.GEMINI_API_KEY=y,te.env.GOOGLE_GEMINI_BASE_URL=p}else if(!te.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let m=[],u=[],c=[],f={},h=0,w=0,I,g,v=[Z(te.cwd(),"gemini"),...s?["--model",s]:[],"--yolo","--output-format","stream-json","-p",a],x=`${te.env.NVM_BIN}/node`;j.log(`Running ${x} ${v.join(" ")}`);let N=t.utils.run(x,v,{all:!0,env:te.env});N.stdin?.end();let T=xe(()=>{r?.({steps:m,duration:w}),o?.({steps:u,duration:w}),u=[]},250),_=(y,p)=>{y.id=h,h+=1,c.push(y),m.push(y),u.push(y),p||T.flush(),T(),p&&T.flush()},R=qr.createInterface({input:N.all});R.on("error",y=>{j.error("Readline interface error",{error:y.message,stack:y.stack})});let S="",A=()=>{S&&_({message:S.trim()}),S=""};return R.on("line",y=>{let p=null;try{if(y.startsWith("[API Error")){let d=y.match(/\[api error: (.+?)]$/i)?.[1];p={type:"error",value:Tt(d,!1)?.error?.message||d||"Gemini encountered error"}}else p=JSON.parse(y)}catch{return}if(p)switch(["message","result"].includes(p.type)||A(),p.type){case"message":{p.role!=="user"&&p.content&&(S+=p.content);break}case"tool_use":{let d=Wr[p.tool_name]??p.tool_name,$=p.parameters?.file_path,re=$&&Ae.relative(te.cwd(),$),he=p.parameters?.command,V={title:[d,re&&`\`${re}\``,he&&`\`${he}\``].filter(Boolean).join(" ")};f[p.tool_id]=V,T.flush();break}case"tool_result":{let d=f[p.tool_id];d&&(p.output&&(d.message=`\`\`\`
20
- ${p.output.trim()}
21
- \`\`\``),_(d,!0));break}case"result":{w=p.stats?.duration_ms,p.status==="error"?g=p.error?.message:I=S.trim();break}case"error":{g=p.error;break}case"finished":break;default:{j.warn("Unhandled message type:",p.type);break}}}),await N.catch(y=>{({error:g,result:I}=Kr({catchError:y,runCmd:N,error:g,result:I,runnerName:"Gemini"}))}),R.close(),T.flush(),{steps:c,duration:w,result:await se({initialResult:I,agentName:Lt,hasError:!!g}),error:ae({error:g,agentName:Lt}),isRetryableError:le(g)}}var Mt=async()=>{let e=Ae.join(Ut.homedir(),".gemini");await Se.rm(e,{recursive:!0,force:!0})};var Jr={codex:{runner:Je,clean:Dt},claude:{runner:Ve,clean:kt},gemini:{runner:Xe,clean:Mt}},jt=Jr;var zr=E("init_stage"),Gt=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>await b(Xr(),"init-stage",async n=>{let i=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=Zr({apiToken:r});lt(l);let s=e.useGateway?await gt({netlify:l,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!s}),e.validateAgent&&e.errorLogsPath&&n?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let m=It(({steps:h=[],duration:w})=>{let I=h.map(g=>({...g,title:g.title?K(g.title):void 0,message:g.message?K(g.message):void 0}));return h.length=0,q(e.id,e.sessionId,{steps:I,duration:w})},t);zr.info("Adding build files to stage");let u=await qe();await Be(u);let c;e.hasRepo?e.sha?(c=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(c=await Nt(),await pe(e.id,{sha:c}),n?.setAttributes({"init.sha.source":"current_commit"})):(c=await bt(),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let f=performance.now()-i;return n?.setAttributes({"init.sha":c||"unknown","init.duration.ms":f,"init.status":"success"}),{aiGateway:s,context:l,persistSteps:m,runner:a,sha:c}}),Zr=({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:P}});import{getTracer as ze}from"@netlify/otel";import Qr from"crypto";import J from"fs/promises";import L from"path";import G from"process";var D=E("context"),en=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}},tn=10,rn=async e=>{let{name:t,ext:r}=L.parse(e),o=e,n=L.join(G.cwd(),U,o),i=0;for(;await nn(n);){if(i>=tn)throw new Error("Failed to generate context file");o=`${t}-${Qr.randomUUID().slice(0,5)}${r}`,n=L.join(G.cwd(),U,o),i+=1}return o},nn=async e=>{try{return await J.access(e),!0}catch{return!1}},on=async()=>{try{D.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 D.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"?(D.warn("Catchall consumer missing or invalid contextScopes"),null):r:(D.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?D.warn("Netlify features context request timed out"):D.warn("Failed to fetch Netlify features context:",e.message),null}},sn=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 J.writeFile(t,o,"utf-8"),!0}catch(r){return r.name==="AbortError"?D.warn(`Download timeout for ${e}`):D.warn(`Failed to download context file ${e}:`,r.message),!1}},be=null,an=async()=>{if(be)return be;let e=await on();if(!e)return[];let t=L.join(G.cwd(),U,Ge);await J.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([n,i])=>{if(!i||typeof i!="object"||!i.endpoint||!i.scope)return D.warn(`Invalid scope data for ${n}, skipping...`),null;let a=`${n}.md`,l=L.join(t,a),s=L.join(U,Ge,a);return D.log(`Downloading ${i.scope} context...`),await sn(i.endpoint,l)?(D.log(`Downloaded: ${s}`),{scope:i.scope,path:s,key:n}):null});return be=(await Promise.all(r)).filter(n=>n!==null),be},Yt=async({cliPath:e,netlify:t,config:r,buildErrorContext:o})=>{let n=en(t),i=await rn(wt),a=L.join(G.cwd(),U);await J.mkdir(a,{recursive:!0});let l=L.join(U,i),s=L.join(G.cwd(),l),m=L.join(G.cwd(),U,ie);try{await J.unlink(m),D.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.
8
+ `);return i.length>e.length*.8?e:i}import Ce from"process";import{getTracer as zr}from"@netlify/otel";import de from"process";var Ee=de.env.NETLIFY_API_URL,we=de.env.NETLIFY_API_TOKEN,Y=_("api"),Ie=()=>de.env.NETLIFY_LOCAL_MODE==="true",pe=async(e,t={})=>{if(!Ee||!we)throw new Error("No API URL or token");let r=new URL(e,Ee),n={...t,headers:{...t.headers,Authorization:`Bearer ${we}`}};de.env.AGENT_RUNNERS_DEBUG==="true"&&(n.headers["x-nf-debug-logging"]="true"),t.json&&(n.headers||={},n.headers["Content-Type"]="application/json",n.body=JSON.stringify(t.json));let o=await fetch(r,n),i=o.ok&&o.status<=299;if(de.env.AGENT_RUNNERS_DEBUG==="true")Y.log(`Response headers for ${r}:`),o.headers.forEach((c,s)=>{Y.log(` ${s}: ${c}`)});else{let c=o.headers.get("x-request-id")||o.headers.get("x-nf-request-id");Y.log(`Request ID for ${r}: ${c||"N/A"}`)}if(i||Y.error(`Got status ${o.status} for request ${r}`),t.raw){if(!i)throw o;return o}let l=await(o.headers.get("content-type")?.includes("application/json")?o.json():o.text());if(!i)throw l;return l},ut=e=>{Y.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Ee=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(we=e.constants.NETLIFY_API_TOKEN)},dt=()=>({apiUrl:Ee,token:we}),fe=async(e,t)=>Ie()?(Y.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):pe(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),q=async(e,t,r)=>Ie()?(Y.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):pe(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var pt=async(e,t)=>Ie()?(Y.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):pe(`/api/v1/agent_runners/${e}/sessions/${t}`),ft=(e,t,r)=>pe(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}}),gt=async(e,t)=>Ie()?(Y.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"}}):pe(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Me=async(e,t)=>{Y.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 oe=_("ai_gateway"),je=null;var mt=async()=>{if(je)return je;oe.log("Fetching available AI gateway providers");let e=await fetch(`${dt().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 je=t,oe.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},dr=async(e,t)=>{let n=(await mt()).providers[e];if(!n)return oe.log(`Provider '${e}' not found`),!1;let o=n.models.includes(t);return oe.log(`Model validation for ${e}/${t}`,{isAvailable:o}),o},ht=async({netlify:e,config:t})=>{let r,n,o,i,l=e.constants?.SITE_ID;if(!l)throw new Error("No site id");let c=async()=>{clearTimeout(o),oe.log("Requesting AI gateway information");let s=await ft(l,t.id,t.sessionId);if({token:r,url:i}=s,n=s.expires_at?s.expires_at*1e3:void 0,oe.log("Got AI gateway information",{token:!!r,expiresAt:n,url:i}),n){let m=n-Date.now()-6e4;m>0&&(o=setTimeout(()=>{c()},m))}};return await Promise.all([c(),mt()]),{get url(){return i},get token(){return r},isModelAvailableForProvider:dr}};import B from"process";import V from"path";import xe from"fs";import{fileURLToPath as _r}from"url";import{createRequire as Er}from"module";import{execa as wr,execaCommand as Vn}from"execa";import{Transform as pr}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 W(e){if(typeof e!="string")return e;let t=mr();if(t.length===0)return e;let r=e;return t.forEach(n=>{let o=new RegExp(hr(n),"g");r=r.replace(o,"******")}),r}function hr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ie=class extends pr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,n){let o=t.toString(),i=W(o);n(null,i)}};function yt(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(n,o,i){let l=typeof n=="string"?W(n):n;return typeof o=="function"?t(l,o):t(l,o,i)},process.stderr.write=function(n,o,i){let l=typeof n=="string"?W(n):n;return typeof o=="function"?r(l,o):r(l,o,i)}}var ge=null,_t=e=>(ge&&ge.destroy(),ge=new Q({totalAllowedTime:e}),ge),Et=()=>ge;var Q=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,n)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let o=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),i=null,l=null;n!==void 0&&(l=new Promise((c,s)=>{i=setTimeout(()=>{s(new Error(`${t} stage exceeded its maximum duration of ${n}ms`))},n)}));try{return l?await Promise.race([r(),l]):await r()}finally{o(),i&&clearTimeout(i)}};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 wt={name:"@netlify/agent-runner-cli",type:"module",version:"1.54.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","@openai/codex":"0.55.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.57.0",execa:"^8.0.0","get-port":"^5.1.1",minimist:"^1.2.8"}};var Ir=_r(import.meta.url),xr=V.dirname(Ir),Tr=Er(import.meta.url),Te=_("shell"),Ge=new Set,vr={preferLocal:!0},N=(e,t,r)=>{let[n,o]=Rr(t,r),i={...vr,...o},l=wr(e,n,i);return Sr(l,i),br(l),l};var Rr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Sr=(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 ie).pipe(B.stdout),e.stdout?.pipe(new ie).pipe(B.stdout),e.stderr?.pipe(new ie).pipe(B.stderr);return}e.stdout?.pipe(B.stdout),e.stderr?.pipe(B.stderr)},It=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(B.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=>It(e,"SIGKILL"),br=e=>{Ge.add(e);let t=Et();if(t){let r=t.onTimesUp(()=>{Te.log(`Global timer expired, killing process ${e.pid}`),It(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(Te.log(`Force killing process ${e.pid} after timeout`),Ar(e))},5e3)});e.on("exit",()=>{Ge.delete(e),r()}),e.on("error",()=>{Ge.delete(e),r()})}};function ve(e,t){return!!ee(e,t)}function ee(e,t){if(!B.env.NETLIFY_LOCAL_MODE)try{let o=Tr.resolve(wt.name),i=V.dirname(o);for(;i!==V.dirname(i);){let l=V.dirname(i);if(V.basename(l)==="node_modules"){let c=V.join(l,".bin",t);if(xe.existsSync(c))return c;break}i=l}}catch(o){console.error("Could not resolve package.json",o)}if(B.env.NODE_PATH){let o=V.join(B.env.NODE_PATH,".bin",t);if(xe.existsSync(o))return o}let r=V.join(e,"node_modules",".bin",t);if(xe.existsSync(r))return r;let n=V.join(xr,"..","node_modules",".bin",t);if(xe.existsSync(n))return n}var xt="netlify-agent-runner-context.md",Ye="task-history",Be="netlify-context",U=".netlify",se="results.md",He="assets";var Nr=_("utils"),Cr=e=>new Promise(t=>{setTimeout(t,e)}),Tt=(e,t=3e3)=>{let r=!1,n=null,o=[],i=null,l=(...c)=>{if(r)return n=c,new Promise(p=>{o.push(p)});r=!0;let s,m=new Promise(p=>{s=p});return i=(async()=>{await Promise.resolve();let p=await e(...c);for(s(p);;){if(await Cr(t),!n)return r=!1,i=null,p;let u=n,g=o;n=null,o=[],p=await e(...u),g.forEach(y=>{y(p)})}})(),m};return l.flush=async()=>{if((r||n)&&i)return await i,l.flush()},l},ae=(e,t,r=!1)=>{let n=null,o=null,i=null,l=function(...c){o=c,i=this;let s=r&&!n;clearTimeout(n),n=setTimeout(()=>{n=null,r||(e.apply(i,o),o=null,i=null)},t),s&&(e.apply(i,o),o=null,i=null)};return l.cancel=()=>{clearTimeout(n),n=null,o=null,i=null},l.flush=()=>{if(n){clearTimeout(n);let c=o,s=i;n=null,o=null,i=null,e.apply(s,c)}},l},vt=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(n){t&&(r?.error?r.error("Could not parse JSON",n):Nr.error("Could not parse JSON",n))}},Rt=(e,t)=>{let o=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let c=`--${t}${o}`;if(c.length>55)return"";let s=60-c.length;if(s<=0)return"";if(s>=i.length+6){let m=Math.min(s-i.length,e.length);return`${i}${e.slice(0,m)}`}return e.slice(0,s)};import{Buffer as St}from"buffer";import Pr from"path";var At=_("repo"),bt=async({config:e})=>{At.info("Getting runner diffs");let t=await Fr(),{hasChanges:r}=t,{status:n}=t;if(!r)return{hasChanges:!1};let o=$r(n);await kr(o),At.info("Changes after processing"),await qe();let i=await We(n);await Ke(i);let l={stdio:["ignore","pipe","pipe"]},s=(await N("git",["diff","--staged"],l)).stdout;if(r=!!s,!r)return{hasChanges:!1,ignored:i};let p=(await N("git",["diff","--staged","--binary"],l)).stdout,u,g;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await N("git",["commit","-m","Agent runner"]),u=(await N("git",["diff",e.sha,"HEAD"],l)).stdout;let f=(await N("git",["diff",e.sha,"HEAD","--binary"],l)).stdout;u!==f&&(g=St.from(f).toString("base64"))}let y={hasChanges:!0,diff:s,resultDiff:u,ignored:i};return s!==p&&(y.diffBinary=St.from(p).toString("base64")),g&&(y.resultDiffBinary=g),y},Ke=async(e=[])=>{await N("git",["add",".",...e])},qe=async()=>(await N("git",["status","-s"])).stdout,Nt=/.. (.+)?\.log$/,Or=[Nt],Fr=async()=>{let e=await qe();return{hasChanges:(e.trim().length===0?[]:e.split(`
9
+ `).filter(n=>Or.some(i=>i instanceof RegExp?i.test(n):n===i)?!1:n[1]?.trim()!=="")).length!==0,status:e}},Ct=async()=>{let{stdout:e}=await N("git",["rev-parse","HEAD"]);return e.trim()},Pt=async()=>{let{stdout:e}=await N("git",["rev-list","--max-parents=0","HEAD"]);return e.trim()},We=async e=>{e||=await qe();let t=[".netlify","node_modules"],r=[];return e.split(`
10
+ `).forEach(n=>{t.forEach(i=>{[`?? ${i}`,`?? ${i}${Pr.sep}`].some(c=>n.startsWith(c))&&r.push(`:!${i}`)});let o=n.match(Nt)?.[1];o&&r.push(`:!${o}.log`)}),r},Ot=async()=>{await N("git",["reset","--hard","HEAD"])},$r=e=>{let t=e.split(`
11
+ `).reduce((r,n)=>{if(!n)return r;let[o,i,,...l]=n,c=l.join(""),s=o.trim(),m=i.trim();return r[c]?r[c].change=m:r[c]={filePath:c,stage:s,change:m},r},{});return Object.values(t)},kr=async e=>{let t=[];for(let r of e)r.stage&&!r.change&&t.push(N("git",["restore","--staged","--worktree",r.filePath]));await Promise.allSettled(t)};import Lr from"fs/promises";import Ur from"os";import kt from"path";import te from"process";import Mr from"readline";import Ve from"path";import Dr from"fs/promises";var Je=_("agent-output-utils");async function le({initialResult:e,agentName:t,hasError:r}){let n="",o=Ve.join(process.cwd(),U,se);try{let i=await Dr.readFile(o,"utf-8");i&&(n=i,Je.log(`Pulled result from ${Ve.relative(process.cwd(),o)}`))}catch{Je.log(`No results file found at ${Ve.relative(process.cwd(),o)}`)}return n||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function ce({error:e,agentName:t}){let r=e&&typeof e=="object"?JSON.stringify(e):e,n=r?.replace(/\s+/g," ").trim().toLowerCase()||"",o="";return n?.includes("ai gateway is not available for your account")||n?.includes("ai gateway is not enabled for your account")?o="AI Gateway is currently not available on your account. Please confirm your account meets the criteria for using Agent Runners and AI Gateway and that your account has remaining AI Gateway inference credits available. Reach out to Netlify support if this is unexpected.":n?.includes("error when talking to gemini api")?o="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":(n?.includes("connection closed prematurely")||n?.includes("499")&&t.toLowerCase().includes("gemini"))&&(o=`The ${t} models were currently overloaded. Please try again or use a different available agent.`),n?.includes("request timed out")&&(o=`The ${t} API request's have timed out. Please try again or use a different available agent.`),n?.includes("network error")&&(o=`The ${t} agent is having network issues. Please try again or use a different available agent.`),o&&Je.log(`Providing updated error messsage: ${o}, replacing original error: ${r}`),o||r||void 0}function ue(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 M=_("runner_claude"),Ft="Claude Code",Re="claude-sonnet-4-5-20250929",$t=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,jr=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(M.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(M.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(M.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0}));async function Xe({config:e,netlify:t,persistSteps:r,aiGateway:n,continueSession:o,priorAgentSessionId:i}){let l=e,{accountType:c,prompt:s,modelVersionOverrides:m}=l,{model:p}=l,u="";if(n){let{token:h,url:d}=n;if(!h||!d)throw new Error("No token or url provided from AI Gateway");if(m?.claude){let a=m?.claude?.[c];if(a){if(!await n.isModelAvailableForProvider("anthropic",a))throw new Error(`Model override '${a}' is not available for anthropic provider`);p=a}}else if(p){if(!await n.isModelAvailableForProvider("anthropic",p))throw new Error(`Model '${p}' is not available for anthropic provider`)}else await n.isModelAvailableForProvider("anthropic",Re)?(p=Re,M.log(`Using default model: ${Re}`)):M.log(`Default model ${Re} is not available, proceeding without model specification`);te.env.ANTHROPIC_API_KEY=h,te.env.ANTHROPIC_BASE_URL=d}else if(!te.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let g=[],y=[],w={},I=0,f=0,T,x,b=[ee(te.cwd(),"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...p?["--model",p]:[],...o?["--continue"]:[],...o&&i?["--resume",i]:[],"-p",s],P=`${te.env.NVM_BIN}/node`;M.log(`Running ${P} ${b.join(" ")}`);let O=t.utils.run(P,b,{all:!0,env:te.env});O.stdin?.end();let R=ae(()=>{r?.({steps:g,duration:f})},250),v=(h,d)=>{let a={...h,id:I};I+=1,y.push(a),g.push(a),d||R.flush(),R(),d&&R.flush()},D=Mr.createInterface({input:O.all});return D.on("error",h=>{M.error("Readline interface error",{error:h.message,stack:h.stack})}),D.on("line",h=>{let d=null;try{d=JSON.parse(h)}catch{M.log("Could not parse line",h)}d?.session_id&&d.session_id!==u&&(u=d.session_id),Array.isArray(d?.message?.content)?d.message.content.forEach(a=>{switch(a.type){case"text":{a.text&&v({message:a.text});break}case"image":{typeof a.source=="object"&&a.source&&a.source.type==="base64"&&a.source.media_type?v({message:`![](data:${a.source.media_type};base64,${a.source.data})`}):M.log(`Unsupported image type ${a.source?.type}`,a.source);break}case"tool_use":{if(a.name==="Task"){let E=a.input?.description&&`\`${a.input.description}\``;v({title:[$t(a.name),E].filter(Boolean).join(" ")})}else a.id&&(w[a.id]=a);R.flush();break}case"tool_result":{let E=a.tool_use_id?w[a.tool_use_id]:void 0,z;if(E){let J=E.input?.file_path&&kt.relative(te.cwd(),E.input.file_path),F=J&&`\`${J}\``;z=[$t(E.name||""),F].filter(Boolean).join(" ")}let _e=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(E?.name||""),Z;if(typeof a.content=="string")Z=a.content;else if(Array.isArray(a.content)){let J=[];a.content.forEach(F=>{F?.type==="text"&&typeof F.text=="string"?J.push(F.text):F?.type==="image"&&typeof F.source=="object"&&F.source?F.source.type==="base64"&&F.source.media_type?J.push(`![](data:${F.source.media_type};base64,${F.source.data})`):M.log(`Unsupported image type ${F.source.type}`,F.source):M.log(`Unsupported block type ${F?.type}`)}),Z=J.join(`
12
+
13
+ `)}_e&&Z&&(Z=`\`\`\`
14
+ ${Z.trim()}
15
+ \`\`\``),v({title:z,message:Z},!0);break}case"thinking":{a.thinking&&v({title:"Thinking",message:a.thinking},!0);break}default:M.log(`Message content type is not supported ${a.type}`,a)}}):d?.type==="result"&&(f=d.duration_ms||0,d.is_error?x=d.result:T=d.result,[y,g].forEach(a=>{a[a.length-1]?.message===T&&a.pop()}))}),await O.catch(h=>{({error:x,result:T}=jr({catchError:h,runCmd:O,error:x,result:T,runnerName:"Claude"}))}),D.close(),R.flush(),{steps:y,duration:f,result:await le({initialResult:T,agentName:Ft,hasError:!!x}),error:ce({error:x,agentName:Ft}),isRetryableError:ue(x),agentSessionId:u}}var Dt=async()=>{let e=kt.join(Ur.homedir(),".claude");await Lr.rm(e,{recursive:!0,force:!0})};import me from"fs/promises";import Ut from"os";import Se from"path";import re from"process";import Gr from"readline";var H=_("runner_codex"),Lt="Codex CLI",Yr=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(H.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(H.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(H.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0}));async function ze({config:e,netlify:t,persistSteps:r,sendSteps:n,aiGateway:o}){let{accountType:i,prompt:l,modelVersionOverrides:c}=e,{model:s}=e;if(o){let{token:d,url:a}=o;if(!d||!a)throw new Error("No token or url provided from AI Gateway");if(c?.codex){let E=c?.codex?.[i];if(E){if(!await o.isModelAvailableForProvider("openai",E))throw new Error(`Model override '${E}' is not available for openai provider`);s=E}}else if(s&&!await o.isModelAvailableForProvider("openai",s))throw new Error(`Model '${s}' is not available for openai provider`);re.env.OPENAI_API_KEY=d,re.env.OPENAI_BASE_URL=a}else if(!re.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let m=[],p=[],u=[],g={},y=0,w=0,I,f,T=`${re.env.NVM_BIN}/node`,x=Se.join(Ut.homedir(),".codex"),b=Se.join(x,"config.toml"),P=Se.join(x,"auth.json");try{await me.mkdir(x,{recursive:!0});let d={OPENAI_API_KEY:re.env.OPENAI_API_KEY};await me.writeFile(P,JSON.stringify(d,null,2),"utf-8"),H.log("Created Codex auth.json file");let a="";try{a=await me.readFile(b,"utf-8")}catch{}a.includes("web_search")||(a.includes("[tools]")?a=a.replace(/\[tools\]/,`[tools]
16
+ web_search = true`):a+=`
17
+ [tools]
18
+ web_search = true
19
+ `,await me.writeFile(b,a,"utf-8"),H.log("Updated Codex config with web_search enabled"))}catch(d){throw H.warn("Failed to setup Codex config and credentials",{error:d.message}),new Error(`Codex setup failed: ${d.message}`)}let O=[ee(re.cwd(),"codex"),"exec","--yolo","--json","--config","web_search=true",...s?["--model",s]:[],l].filter(Boolean);H.log(`Running ${T} ${O.join(" ")}`);let R=t.utils.run(T,O,{all:!0,env:{...re.env}}),v=ae(()=>{r?.({steps:m,duration:w}),n?.({steps:p,duration:w}),p=[]},250),D=(d,a)=>{d.id=y,y+=1,u.push(d),m.push(d),p.push(d),a||v.flush(),v(),a&&v.flush()},h=Gr.createInterface({input:R.all});return h.on("error",d=>{H.error("Readline interface error",{error:d.message,stack:d.stack})}),h.on("line",d=>{let a=null;try{a=JSON.parse(d)}catch{H.log("Could not parse line",d);return}if(a?.duration_ms&&(w=a.duration_ms),a?.type==="item.started"&&a?.item?.type==="command_execution")g[a.item.id]=a.item;else if(a?.type==="item.completed"&&a?.item?.type==="command_execution"){let E=Hr(a.item);E&&D(E,!0)}else if(a?.type==="item.completed"&&a?.item?.type==="reasoning"){let E={title:"Reasoning",message:a.item.text};D(E,!0)}else if(a?.type==="local_shell_call")g[a.call_id]=a;else if(a?.type==="local_shell_call_output"){let E=Kr(g[a.call_id],a);E&&D(E,!0)}else a?.type==="message"&&a.role==="assistant"?I=a.content.map(E=>E.text).join(`
20
+ `):a?.type==="message"&&a.role==="system"&&(f=a.content.map(E=>E.text).join(`
21
+ `))}),await R.catch(d=>{let a=Yr({catchError:d,runCmd:R,error:f,result:I,runnerName:"Codex"});f=a.error,I=a.result}),h.close(),v.flush(),{steps:u,duration:w,result:await le({initialResult:I,agentName:Lt,hasError:!!f}),error:ce({error:f,agentName:Lt}),isRetryableError:ue(f)}}var Mt=async()=>{let e=Se.join(Ut.homedir(),".codex");await me.rm(e,{recursive:!0,force:!0})},Br=new Set(["bash","-lc"]),Hr=e=>{if(!e||e.type!=="command_execution")return null;let t=e.command;t.startsWith("bash -lc ")&&(t=t.replace(/^bash -lc ['"]/,"").replace(/['"]$/,""));let r=`Running \`${t}\``,n=e.aggregated_output?.trim();return n&&(n=`\`\`\`
22
+ ${n}
23
+ \`\`\``),e.status==="failed"&&e.exit_code!==0&&(n=n?`${n}
24
+
25
+ *Exit code: ${e.exit_code}*`:`*Command failed with exit code: ${e.exit_code}*`),{title:r,message:n}},Kr=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(i=>!Br.has(i)),n=r?`Running \`${r.join(" ")}\``:void 0,o;try{o=JSON.parse(t.output).output?.trim(),o&&(o=`\`\`\`
26
+ ${o.trim()}
27
+ \`\`\``)}catch(i){H.error("Could not decode outputMsg",i,t.output)}return{title:n,message:o}};import be from"fs/promises";import Gt from"os";import Ne from"path";import ne from"process";import qr from"readline";var j=_("runner_gemini"),jt="Gemini CLI",Ae="gemini-2.5-pro",Wr=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(j.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(j.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(j.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0})),Vr={list_directory:"List",read_file:"Read",write_file:"Write",glob:"Find",search_file_content:"Find",replace:"Edit",run_shell_command:"Run",web_fetch:"Web Fetch",web_search:"Web Search",read_many_files:"Read Many",save_memory:"Memorize"},Jr=async()=>{let e=Ne.join(Gt.homedir(),".gemini"),t=Ne.join(e,"settings.json");try{await be.mkdir(e,{recursive:!0});let r={};try{let n=await be.readFile(t,"utf-8");r=JSON.parse(n)}catch{j.log("Creating new Gemini CLI settings file")}r.general||(r.general={}),r.general.previewFeatures||(r.general.previewFeatures=!1),r.model||(r.model={}),r.model.compressionThreshold!==.3&&(r.model.compressionThreshold=.3),await be.writeFile(t,JSON.stringify(r,null,2),"utf-8"),j.log("Configured Gemini CLI settings (preview features and compression threshold)")}catch(r){j.error("Failed to ensure Gemini CLI settings",{error:r.message})}};async function Ze({config:e,netlify:t,persistSteps:r,sendSteps:n,aiGateway:o}){let{accountType:i,prompt:l,modelVersionOverrides:c}=e,{model:s}=e;if(await Jr(),o){let{token:h,url:d}=o;if(!h||!d)throw new Error("No token or url provided from AI Gateway");if(c?.gemini){let a=c?.gemini?.[i];if(a){if(!await o.isModelAvailableForProvider("gemini",a))throw new Error(`Model override '${a}' is not available for gemini provider`);s=a}}if(!s)await o.isModelAvailableForProvider("gemini",Ae)?(s=Ae,j.log(`Using default model: ${Ae}`)):j.log(`Default model ${Ae} is not available, proceeding without model specification`);else if(s&&!c?.gemini?.[i]&&!await o.isModelAvailableForProvider("gemini",s))throw new Error(`Model '${s}' is not available for gemini provider`);ne.env.GEMINI_API_KEY=h,ne.env.GOOGLE_GEMINI_BASE_URL=d}else if(!ne.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let m=[],p=[],u=[],g={},y=0,w=0,I,f,T=[ee(ne.cwd(),"gemini"),...s?["--model",s]:[],"--yolo","--output-format","stream-json","-p",l],x=`${ne.env.NVM_BIN}/node`;j.log(`Running ${x} ${T.join(" ")}`);let b=t.utils.run(x,T,{all:!0,env:ne.env});b.stdin?.end();let P=ae(()=>{r?.({steps:m,duration:w}),n?.({steps:p,duration:w}),p=[]},250),O=(h,d)=>{h.id=y,y+=1,u.push(h),m.push(h),p.push(h),d||P.flush(),P(),d&&P.flush()},R=qr.createInterface({input:b.all});R.on("error",h=>{j.error("Readline interface error",{error:h.message,stack:h.stack})});let v="",D=()=>{v&&O({message:v.trim()}),v=""};return R.on("line",h=>{let d=null;try{if(h.startsWith("[API Error")){let a=h.match(/\[api error: (.+?)]$/i)?.[1];d={type:"error",value:vt(a,!1)?.error?.message||a||"Gemini encountered error"}}else d=JSON.parse(h)}catch{return}if(d)switch(["message","result"].includes(d.type)||D(),d.type){case"message":{d.role!=="user"&&d.content&&(v+=d.content);break}case"tool_use":{let a=Vr[d.tool_name]??d.tool_name,E=d.parameters?.file_path,z=E&&Ne.relative(ne.cwd(),E),_e=d.parameters?.command,J={title:[a,z&&`\`${z}\``,_e&&`\`${_e}\``].filter(Boolean).join(" ")};g[d.tool_id]=J,P.flush();break}case"tool_result":{let a=g[d.tool_id];a&&(d.output&&(a.message=`\`\`\`
28
+ ${d.output.trim()}
29
+ \`\`\``),O(a,!0));break}case"result":{w=d.stats?.duration_ms,d.status==="error"?f=d.error?.message:I=v.trim();break}case"error":{f=d.error;break}case"finished":break;default:{j.warn("Unhandled message type:",d.type);break}}}),await b.catch(h=>{({error:f,result:I}=Wr({catchError:h,runCmd:b,error:f,result:I,runnerName:"Gemini"}))}),R.close(),P.flush(),{steps:u,duration:w,result:await le({initialResult:I,agentName:jt,hasError:!!f}),error:ce({error:f,agentName:jt}),isRetryableError:ue(f)}}var Yt=async()=>{let e=Ne.join(Gt.homedir(),".gemini");await be.rm(e,{recursive:!0,force:!0})};var Xr={codex:{runner:ze,clean:Mt},claude:{runner:Xe,clean:Dt},gemini:{runner:Ze,clean:Yt}},Bt=Xr;var Zr=_("init_stage"),Ht=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:n})=>await S(zr(),"init-stage",async o=>{let i=performance.now();o?.setAttributes({"init.runner":e.runner,"init.id":e.id,"init.sessionId":e.sessionId,"init.hasRepo":e.hasRepo,"init.useGateway":e.useGateway,"init.validateAgent":e.validateAgent,"init.runnerVersion":n||"unknown"});let l=Bt[e.runner];if(!l)throw o?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let c=Qr({apiToken:r});ut(c);let s=e.useGateway?await ht({netlify:c,config:e}):void 0;o?.setAttributes({"init.aiGateway.created":!!s}),e.validateAgent&&e.errorLogsPath&&o?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let m=Tt(({steps:y=[],duration:w})=>{let I=y.map(f=>({...f,title:f.title?W(f.title):void 0,message:f.message?W(f.message):void 0}));return y.length=0,q(e.id,e.sessionId,{steps:I,duration:w})},t);Zr.info("Adding build files to stage");let p=await We();await Ke(p);let u;e.hasRepo?e.sha?(u=e.sha,o?.setAttributes({"init.sha.source":"provided"})):(u=await Ct(),await fe(e.id,{sha:u}),o?.setAttributes({"init.sha.source":"current_commit"})):(u=await Pt(),o?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let g=performance.now()-i;return o?.setAttributes({"init.sha":u||"unknown","init.duration.ms":g,"init.status":"success"}),{aiGateway:s,context:c,persistSteps:m,runner:l,sha:u}}),Qr=({apiToken:e})=>({constants:{NETLIFY_API_HOST:Ce.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||Ce.env.NETLIFY_API_TOKEN,SITE_ID:Ce.env.SITE_ID,FUNCTIONS_DIST:Ce.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:N}});import{getTracer as Qe}from"@netlify/otel";import en from"crypto";import X from"fs/promises";import L from"path";import G from"process";var k=_("context"),tn=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}},rn=10,nn=async e=>{let{name:t,ext:r}=L.parse(e),n=e,o=L.join(G.cwd(),U,n),i=0;for(;await on(o);){if(i>=rn)throw new Error("Failed to generate context file");n=`${t}-${en.randomUUID().slice(0,5)}${r}`,o=L.join(G.cwd(),U,n),i+=1}return n},on=async e=>{try{return await X.access(e),!0}catch{return!1}},sn=async()=>{try{k.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 k.warn("Invalid response structure: missing or invalid consumers array"),null;let r=t.consumers.find(n=>n&&typeof n=="object"&&n.key==="catchall-consumer");return r?!r.contextScopes||typeof r.contextScopes!="object"?(k.warn("Catchall consumer missing or invalid contextScopes"),null):r:(k.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?k.warn("Netlify features context request timed out"):k.warn("Failed to fetch Netlify features context:",e.message),null}},an=async(e,t)=>{try{let r=await fetch(e,{signal:AbortSignal.timeout(1e4)});if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let n=await r.text();return await X.writeFile(t,n,"utf-8"),!0}catch(r){return r.name==="AbortError"?k.warn(`Download timeout for ${e}`):k.warn(`Failed to download context file ${e}:`,r.message),!1}},Pe=null,ln=async()=>{if(Pe)return Pe;let e=await sn();if(!e)return[];let t=L.join(G.cwd(),U,Be);await X.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([o,i])=>{if(!i||typeof i!="object"||!i.endpoint||!i.scope)return k.warn(`Invalid scope data for ${o}, skipping...`),null;let l=`${o}.md`,c=L.join(t,l),s=L.join(U,Be,l);return k.log(`Downloading ${i.scope} context...`),await an(i.endpoint,c)?(k.log(`Downloaded: ${s}`),{scope:i.scope,path:s,key:o}):null});return Pe=(await Promise.all(r)).filter(o=>o!==null),Pe},Kt=async({cliPath:e,netlify:t,config:r,buildErrorContext:n})=>{let o=tn(t),i=await nn(xt),l=L.join(G.cwd(),U);await X.mkdir(l,{recursive:!0});let c=L.join(U,i),s=L.join(G.cwd(),c),m=L.join(G.cwd(),U,se);try{await X.unlink(m),k.log(`Deleted old results file: ${m}`)}catch{}let p=n?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
22
30
  Your task is to analyze and fix the build errors.
23
31
  Don't apply techniques of reverting changes. Apply fixes related to errors.
24
32
  Don't try to run build by yourself. Just fix the errors.
25
33
 
26
34
  <build_error_context>
27
- ${o}
28
- </build_error_context>`:"",c="";r.siteContext&&r.siteContext.length!==0&&(c=`
35
+ ${n}
36
+ </build_error_context>`:"",u="";r.siteContext&&r.siteContext.length!==0&&(u=`
29
37
  <project_rules>
30
- ${r.siteContext.filter(g=>g.site_context).map(g=>typeof g.site_context=="string"?g.site_context:typeof g.site_context=="object"?JSON.stringify(g.site_context):"").join(`
38
+ ${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
39
 
32
40
  `)}
33
41
  </project_rules>
34
- `);let f="";if(r.sessionHistoryContext?.length){let g=L.join(G.cwd(),U,je);await J.mkdir(g,{recursive:!0});let v=await Promise.all(r.sessionHistoryContext.map(async(x,N)=>{let T=N+1,_=`attempt-${T}.md`,R=L.join(g,_),S=L.join(U,je,_),A=`# Task History - Attempt ${T}
42
+ `);let g="";if(r.sessionHistoryContext?.length){let f=L.join(G.cwd(),U,Ye);await X.mkdir(f,{recursive:!0});let T=await Promise.all(r.sessionHistoryContext.map(async(x,b)=>{let P=b+1,O=`attempt-${P}.md`,R=L.join(f,O),v=L.join(U,Ye,O),D=`# Task History - Attempt ${P}
35
43
 
36
44
  ## Request - what the user asked for
37
45
  ${x.request}
@@ -41,21 +49,21 @@ ${x.request}
41
49
  ## Response - what the agent replied with after its work
42
50
 
43
51
  ${x.response}
44
- `;return await J.writeFile(R,A,"utf-8"),D.log(`Created history file: ${S}`),S}));f+=`
52
+ `;return await X.writeFile(R,D,"utf-8"),k.log(`Created history file: ${v}`),v}));g+=`
45
53
  <session_history_context>
46
54
  History of prior work on this task.
47
55
  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
56
 
49
- ${v.slice(-5).map(x=>`- ${x}`).join(`
57
+ ${T.slice(-5).map(x=>`- ${x}`).join(`
50
58
  `)}
51
59
 
52
60
  </session_history_context>
53
- `}let h=await an(),w="";h.length>0&&(w=`
61
+ `}let y=await ln(),w="";y.length>0&&(w=`
54
62
  <netlify_features_context>
55
63
  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
64
  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
65
 
58
- ${h.map(g=>`- **${g.scope}**: ${g.path}`).join(`
66
+ ${y.map(f=>`- **${f.scope}**: ${f.path}`).join(`
59
67
  `)}
60
68
 
61
69
  Refer to these files when working with specific Netlify features.
@@ -67,32 +75,32 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
67
75
  <user_request>
68
76
  ${r.prompt}
69
77
  </user_request>
70
- ${u}
78
+ ${p}
71
79
  </request>
72
80
 
73
81
  <requirements>
74
82
  <responses>
75
83
  - Do not speak in first person. You may speak as "the agent".
76
- - When work is complete, write a changes summary in ${a}/${ie} 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}/${ie} file.
84
+ - When work is complete, write a changes summary in ${l}/${se} 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.
85
+ - 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 ${l}/${se} file.
78
86
  - 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
87
  - NEVER look into the \`.git\` folder
80
88
  - NEVER print potentially sensitive values (like secrets) in the planning output or results
81
89
  </responses>
82
90
  <attachements>
83
- - for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${a}/${Ye} folder
84
- - move assets from ${a}/${Ye} folder to the project assets folder if they are referenced in a code or applied changes
91
+ - for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${l}/${He} folder
92
+ - move assets from ${l}/${He} folder to the project assets folder if they are referenced in a code or applied changes
85
93
  </attachements>
86
- ${c}
94
+ ${u}
87
95
  </requirements>
88
96
 
89
97
  <extra_context>
90
98
  <metadata>
91
- - Site/Project ID: ${n.siteId}
92
- - Account/Team ID: ${n.accountId}
93
- - User ID: ${n.userId}
94
- - Site/Project Slug: ${n.siteSlug}
95
- - Netlify Functions directory: ${n.functionsDir}
99
+ - Site/Project ID: ${o.siteId}
100
+ - Account/Team ID: ${o.accountId}
101
+ - User ID: ${o.userId}
102
+ - Site/Project Slug: ${o.siteSlug}
103
+ - Netlify Functions directory: ${o.functionsDir}
96
104
  </metadata>
97
105
  <environment>
98
106
  - Node Version: ${G.version||"unknown"}
@@ -107,31 +115,31 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
107
115
  </docs>
108
116
  </extra_context>
109
117
 
110
- ${f}
111
- `;return await J.writeFile(s,I,"utf-8"),D.log(`Generated agent context document at: ${s}`),I.length>5e5&&(I=`
118
+ ${g}
119
+ `;return await X.writeFile(s,I,"utf-8"),k.log(`Generated agent context document at: ${s}`),I.length>5e5&&(I=`
112
120
  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
121
 
114
122
  <request>
115
123
  <user_request>
116
124
  ${r.prompt}
117
125
  </user_request>
118
- ${u}
126
+ ${p}
119
127
  </request>
120
128
 
121
129
  Use the following file for the complete context of the ask, the environment, and what's available. ${s} You MUST READ ALL OF IT. Make sure to read it first. Never cite or paraphrase private context.
122
- `),I};var ln=E("prompt"),Bt=async({cliPath:e,config:t,netlify:r,buildErrorContext:o})=>{let n=await Yt({cliPath:e,config:t,netlify:r,buildErrorContext:o});return process.env.AGENT_RUNNER_DEBUG&&ln.log("Contextful Prompt:",n),{prompt:n}};var Ce=E("inference_stage"),Ht=5,Pe=async e=>{let{cliPath:t,config:r,context:o,buildErrors:n,runner:i,persistSteps:a,aiGateway:l,attempt:s,contextPrefix:m,priorAgentSessionId:u}=e;Ce.log(`Running inference stage, attempt ${s} of ${Ht}`);let c=await b(ze(),"inference-stage",async f=>{f?.setAttributes({"inference.attempt":s||1}),mt();let{prompt:h}=await b(ze(),"compose-prompt",async()=>await Bt({cliPath:t,config:r,buildErrorContext:cn(n),netlify:o})),w=`
130
+ `),I};var cn=_("prompt"),qt=async({cliPath:e,config:t,netlify:r,buildErrorContext:n})=>{let o=await Kt({cliPath:e,config:t,netlify:r,buildErrorContext:n});return process.env.AGENT_RUNNER_DEBUG&&cn.log("Contextful Prompt:",o),{prompt:o}};var Oe=_("inference_stage"),Wt=5,Fe=async e=>{let{cliPath:t,config:r,context:n,buildErrors:o,runner:i,persistSteps:l,aiGateway:c,attempt:s,contextPrefix:m,priorAgentSessionId:p}=e;Oe.log(`Running inference stage, attempt ${s} of ${Wt}`);let u=await S(Qe(),"inference-stage",async g=>{g?.setAttributes({"inference.attempt":s||1}),yt();let{prompt:y}=await S(Qe(),"compose-prompt",async()=>await qt({cliPath:t,config:r,buildErrorContext:un(o),netlify:n})),w=`
123
131
  ${m||""}
124
- ${h}
125
- `.trim(),I={...r,prompt:w},g=await b(ze(),`run-${r.runner}`,async()=>await i({aiGateway:l,config:I,netlify:o,persistSteps:a,continueSession:!!(s&&s>1),priorAgentSessionId:u}));return g.result&&(g.result=K(g.result)),g.error&&(g.error=K(g.error)),await a.flush(),g});if(c.error){if(Ce.error("Runner failed",{stepsCount:c.steps.length,duration:c.duration,error:c.error,isRetryableError:c.isRetryableError,attempt:s||1,agentSessionId:c.agentSessionId}),c.isRetryableError&&(!s||s<Ht))return Ce.log("Retrying inference stage"),await new Promise(h=>setTimeout(h,5e3)),{runnerResult:(await Pe({...e,attempt:(s||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 Ce.log("Do not retry inference stage"),new Error(c.error)}return{runnerResult:c}},cn=e=>!e||e.length===0?"":`
132
+ ${y}
133
+ `.trim(),I={...r,prompt:w},f=await S(Qe(),`run-${r.runner}`,async()=>await i({aiGateway:c,config:I,netlify:n,persistSteps:l,continueSession:!!(s&&s>1),priorAgentSessionId:p}));return f.result&&(f.result=W(f.result)),f.error&&(f.error=W(f.error)),await l.flush(),f});if(u.error){if(Oe.error("Runner failed",{stepsCount:u.steps.length,duration:u.duration,error:u.error,isRetryableError:u.isRetryableError,attempt:s||1,agentSessionId:u.agentSessionId}),u.isRetryableError&&(!s||s<Wt))return Oe.log("Retrying inference stage"),await new Promise(y=>setTimeout(y,5e3)),{runnerResult:(await Fe({...e,attempt:(s||1)+1,priorAgentSessionId:u.agentSessionId,contextPrefix:u.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 Oe.log("Do not retry inference stage"),new Error(u.error)}return{runnerResult:u}},un=e=>!e||e.length===0?"":`
126
134
  Deploy failed failed. Here are the errors to review on the latest build:
127
135
 
128
136
  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
137
 
130
138
  ${e.pop()}
131
- `;import pn from"process";import{getTracer as Ze}from"@netlify/otel";import{getTracer as un}from"@netlify/otel";var ge=E("deploy"),qt=async e=>await b(un(),"create-preview-deploy",async t=>dn(e,t)),dn=async({netlify:e,hasRepo:t,skipBuild:r,message:o="Agent Preview",deploySubdomain:n,cliPath:i,filter:a},l)=>{try{let s=["deploy","--message",`"${o}"`,"--json","--draft","--verbose"];t||(ge.log("Deploy: Uploading source zip"),s.push("--upload-source-zip")),n&&s.push("--alias",n),a&&s.push("--filter",a),r?(ge.log("Deploy: Skipping build"),s.push("--no-build")):s.push("--context","deploy-preview");let m=i||"netlify";ge.log(`Running: ${m} ${s.join(" ")}`),l?.setAttributes({cmd:m,args:s});let u=await e.utils.run(m,s,{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}),ge.log(`
132
- Preview deploy created successfully:`,{deployId:c.deploy_id,deployUrl:c.deploy_url,siteId:c.site_id});let f={deployId:c.deploy_id,previewUrl:c.deploy_url,logsUrl:c.logs,siteId:c.site_id};return t||(f.sourceZipFilename=c.source_zip_filename),f}catch(s){throw ge.error("Failed to create preview deploy via CLI:",s),l?.setAttributes({success:!1,error:s.message}),s}};var me=E("deploy_stage"),Qe=async e=>await b(Ze(),"run-deploy-stage",async()=>fn(e)),fn=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let i=await b(Ze(),"get-runner-diffs",async()=>await St({config:t,netlify:r}));if(me.info("Resolved git",{hasChanges:i.hasChanges,ignored:i.ignored??[]}),!i.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:l,diffBinary:s,resultDiffBinary:m}=i,u=!0;me.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 f;try{let h=await b(Ze(),"get-runner-session",async()=>await ut(t.id,t.sessionId));h?.title&&(f=h.title)}catch(h){me.warn("Failed to fetch session title, using fallback message:",h.message)}await q(t.id,t.sessionId,{steps:[{title:"Deploying the run preview"}]}),c=await qt({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:f,skipBuild:!1,deploySubdomain:xt(t.id,pn.env.SITE_NAME),filter:n})}catch(f){return me.warn("Failed to create preview deploy (continuing with agent run):",f),{diff:a,resultDiff:l,hasChanges:u,previewInfo:null,diffBinary:s,resultDiffBinary:m,deployError:f instanceof Error?f.message:String(f)}}return me.log("Git status",{hasDiff:!!a,hasChanges:u}),{diff:a,resultDiff:l,hasChanges:u,previewInfo:c,diffBinary:s,resultDiffBinary:m}};import{getTracer as Fe}from"@netlify/otel";async function Kt(e,t){let{maxRetries:r,baseDelay:o,onRetry:n}=t,i;for(let a=1;a<=r;a++)try{return await e()}catch(l){if(i=l,a===r)throw i;n&&n(a,i),await new Promise(s=>setTimeout(s,o*a))}throw i}var Oe=class{scanDiffForForms(t){let r=[],o=null,n=[],i=t.split(`
133
- `);for(let a of i)if(a.startsWith("diff --git")){if(o&&n.length>0){let s=this.containsNetlifyForm(n,o);s&&r.push(s)}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:i,name:a}of n){let l=o.match(i);if(l){let s=l.index||0,m=Math.max(0,s-20),u=Math.min(o.length,s+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=E("cleanup_stage"),Wt=async e=>await b(Fe(),"cleanup-stage",async()=>gn(e)),et=1024*1024*10,gn=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:i,resultDiffBinary:a,previewInfo:l})=>{let s={result:r||"Done",duration:o};l&&l.deployId&&(s.deploy_id=l.deployId),l&&l.sourceZipFilename&&(s.result_zip_file_name=l.sourceZipFilename);let m=t||i||n||a;if(m){let u=new Oe,c=t||i||"",f=u.scanDiffForForms(c);f.detected?(C.log("Detected Netlify form(s) in diff:"),f.matches.forEach(({file:h,snippet:w})=>{C.log(` - ${h}: ${w}`)}),s.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||i)&&c.push(Le(u.result.upload_url,i||t).then(()=>{s.result_diff_s3_key=u.result.s3_key,C.log("Successfully uploaded result_diff to S3")})),(n||a)&&c.push(Le(u.cumulative.upload_url,a||n).then(()=>{s.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(Fe(),"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||i||""),f=Buffer.byteLength(a||n||"");if(c>et||f>et){let h=`Diffs exceed maximum inline size of ${et} bytes.`;throw C.error(h),new Error(h)}s.result_diff=t,s.result_diff_binary=i,(n||a)&&(s.cumulative_diff=n,s.cumulative_diff_binary=a,C.log("Updating agent runner with inline diffs (fallback)"),await b(Fe(),"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(Fe(),"update-runner-session",()=>q(e.id,e.sessionId,s)),{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:s}};import{getTracer as Vt,shutdownTracers as hn,withActiveSpan as Jt}from"@netlify/otel";var yn=mn(import.meta.url),Xt=yn("../package.json"),zt=E("pipeline_index"),ke=3,Zt=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:i,tracing:a={}})=>{let l,{withStageTimer:s}=ht(z.timeUnits.hours(4)),m=await st(Xt.version,e.id,a);try{await Jt(Vt(),"run-pipeline",{},m,async()=>{let u,{aiGateway:c,context:f,persistSteps:h,runner:w,sha:I}=await s("init",()=>Gt({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:i,runnerVersion:Xt.version}),z.timeUnits.minutes(10));l=w.clean,e.sha=I;let{runnerResult:g}=await s("inference",()=>Pe({cliPath:r,config:e,context:f,runner:w.runner,persistSteps:h,aiGateway:c}));await q(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let v=await s("deploy",()=>Qe({cliPath:r,config:e,context:f,result:g.result,filter:i})),x=g,N=[];if(v.hasChanges&&v.deployError){N.push(at(v.deployError));let y=1;for(;y<=ke&&!v.previewInfo;)zt.log(`Deploy attempt had errors. Retrying. ${y}/${ke}`),await Jt(Vt(),"deploy-stage",async p=>{p?.setAttributes({"stage.attempt":y});let{runnerResult:d}=await s(`inference-retry-${y}`,()=>Pe({cliPath:r,config:e,context:f,runner:w.runner,persistSteps:h,aiGateway:c,buildErrors:N,priorAgentSessionId:g.agentSessionId}));x={...d,steps:[...x.steps||[],...d.steps||[]],duration:(x.duration||0)+(d.duration||0)},v=await s(`deploy-retry-${y}`,()=>Qe({cliPath:r,config:e,context:f,result:d.result,filter:i})),v.deployError&&N.push(v.deployError),y++});y>ke&&!v.previewInfo&&(u=new Error(`Deploy validation failed after ${ke} attempts`))}let{diff:T,resultDiff:_,previewInfo:R,diffBinary:S,resultDiffBinary:A}=v;if(await s("cleanup",()=>Wt({config:e,diff:T,result:x.result,duration:x.duration,resultDiff:_,diffBinary:S,resultDiffBinary:A,previewInfo:R}),z.timeUnits.minutes(10)),u)throw u;process.env.NETLIFY_LOCAL_MODE||(await l?.(),await Ct())})}catch(u){zt.error("Got error while running pipeline",u),await l?.();let c=u instanceof Error&&u.message;throw await q(e.id,e.sessionId,{result:c||"Encountered error when running agent",state:"error"}),u}finally{await hn()}};import Qt from"crypto";var k=E("bin_local"),H=En(O.argv.slice(2),{string:["cwd","cli-path","filter","prompt","runner","model","netlify-api-token"],boolean:["verbose","help"],alias:{h:"help",v:"verbose"}}),rt=()=>{console.log(`
139
+ `;import fn from"process";import{getTracer as et}from"@netlify/otel";import{getTracer as dn}from"@netlify/otel";var he=_("deploy"),Vt=async e=>await S(dn(),"create-preview-deploy",async t=>pn(e,t)),pn=async({netlify:e,hasRepo:t,skipBuild:r,message:n="Agent Preview",deploySubdomain:o,cliPath:i,filter:l},c)=>{try{let s=["deploy","--message",`"${n}"`,"--json","--draft","--verbose"];t||(he.log("Deploy: Uploading source zip"),s.push("--upload-source-zip")),o&&s.push("--alias",o),l&&s.push("--filter",l),r?(he.log("Deploy: Skipping build"),s.push("--no-build")):s.push("--context","deploy-preview");let m=i||"netlify";he.log(`Running: ${m} ${s.join(" ")}`),c?.setAttributes({cmd:m,args:s});let p=await e.utils.run(m,s,{stdio:["ignore","pipe","pipe"]}),u=JSON.parse(p.stdout.trim());c?.setAttributes({success:!0,deployId:u.deploy_id,deployUrl:u.deploy_url,siteId:u.site_id}),he.log(`
140
+ Preview deploy created successfully:`,{deployId:u.deploy_id,deployUrl:u.deploy_url,siteId:u.site_id});let g={deployId:u.deploy_id,previewUrl:u.deploy_url,logsUrl:u.logs,siteId:u.site_id};return t||(g.sourceZipFilename=u.source_zip_filename),g}catch(s){throw he.error("Failed to create preview deploy via CLI:",s),c?.setAttributes({success:!1,error:s.message}),s}};var ye=_("deploy_stage"),tt=async e=>await S(et(),"run-deploy-stage",async()=>gn(e)),gn=async({cliPath:e,config:t,context:r,result:n,filter:o})=>{let i=await S(et(),"get-runner-diffs",async()=>await bt({config:t,netlify:r}));if(ye.info("Resolved git",{hasChanges:i.hasChanges,ignored:i.ignored??[]}),!i.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:l,resultDiff:c,diffBinary:s,resultDiffBinary:m}=i,p=!0;ye.log("Preview deploy condition check:",{resultUndefined:n===void 0,resultType:typeof n,hasChanges:p,wouldCreatePreview:n!==void 0&&p});let u=null;if(n!==void 0&&p)try{let g;try{let y=await S(et(),"get-runner-session",async()=>await pt(t.id,t.sessionId));y?.title&&(g=y.title)}catch(y){ye.warn("Failed to fetch session title, using fallback message:",y.message)}await q(t.id,t.sessionId,{steps:[{title:"Deploying the run preview"}]}),u=await Vt({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:g,skipBuild:!1,deploySubdomain:Rt(t.id,fn.env.SITE_NAME),filter:o})}catch(g){return ye.warn("Failed to create preview deploy (continuing with agent run):",g),{diff:l,resultDiff:c,hasChanges:p,previewInfo:null,diffBinary:s,resultDiffBinary:m,deployError:g instanceof Error?g.message:String(g)}}return ye.log("Git status",{hasDiff:!!l,hasChanges:p}),{diff:l,resultDiff:c,hasChanges:p,previewInfo:u,diffBinary:s,resultDiffBinary:m}};import{getTracer as ke}from"@netlify/otel";async function Jt(e,t){let{maxRetries:r,baseDelay:n,onRetry:o}=t,i;for(let l=1;l<=r;l++)try{return await e()}catch(c){if(i=c,l===r)throw i;o&&o(l,i),await new Promise(s=>setTimeout(s,n*l))}throw i}var $e=class{scanDiffForForms(t){let r=[],n=null,o=[],i=t.split(`
141
+ `);for(let l of i)if(l.startsWith("diff --git")){if(n&&o.length>0){let s=this.containsNetlifyForm(o,n);s&&r.push(s)}let c=l.split(" ");n=c[c.length-1].replace(/^b\//,""),o=[]}else l.startsWith("+")&&!l.startsWith("+++")&&o.push(l.slice(1));if(n&&o.length>0){let l=this.containsNetlifyForm(o,n);l&&r.push(l)}return{detected:r.length>0,matches:r}}containsNetlifyForm(t,r){let n=t.join(`
142
+ `),o=[{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:i,name:l}of o){let c=n.match(i);if(c){let s=c.index||0,m=Math.max(0,s-20),p=Math.min(n.length,s+c[0].length+20),u=n.slice(m,p).trim();return u=u.replace(/\s+/g," "),u.length>100&&(u=u.slice(0,97)+"..."),{file:r,snippet:`[${l}] ${u}`}}}return null}};var A=_("cleanup_stage"),Xt=async e=>await S(ke(),"cleanup-stage",async()=>mn(e)),rt=1024*1024*10,mn=async({config:e,diff:t,result:r,duration:n,resultDiff:o,diffBinary:i,resultDiffBinary:l,previewInfo:c})=>{let s={result:r||"Done",duration:n};c&&c.deployId&&(s.deploy_id=c.deployId),c&&c.sourceZipFilename&&(s.result_zip_file_name=c.sourceZipFilename);let m=t||i||o||l;if(m){let p=new $e,u=t||i||"",g=p.scanDiffForForms(u);g.detected?(A.log("Detected Netlify form(s) in diff:"),g.matches.forEach(({file:y,snippet:w})=>{A.log(` - ${y}: ${w}`)}),s.has_netlify_form=!0):A.log("Did not detect Netlify form(s) in diff"),A.log("Did not detect Netlify form(s) in diff")}if(m)try{A.log("Getting pre-signed URLs for diff upload");let p=await gt(e.id,e.sessionId),u=[];(t||i)&&u.push(Me(p.result.upload_url,i||t).then(()=>{s.result_diff_s3_key=p.result.s3_key,A.log("Successfully uploaded result_diff to S3")})),(o||l)&&u.push(Me(p.cumulative.upload_url,l||o).then(()=>{s.cumulative_diff_s3_key=p.cumulative.s3_key,A.log("Successfully uploaded cumulative_diff to S3")})),A.log(`Uploading ${u.length} diff(s) to S3 in parallel`),await Promise.all(u),(o||l)&&(A.log("Updating agent runner with cumulative diff S3 key"),await S(ke(),"update-runner",async()=>{await fe(e.id,{result_diff_s3_key:p.cumulative.s3_key})}))}catch(p){A.error("S3 upload failed, falling back to inline diffs:",p);let u=Buffer.byteLength(t||i||""),g=Buffer.byteLength(l||o||"");if(u>rt||g>rt){let y=`Diffs exceed maximum inline size of ${rt} bytes.`;throw A.error(y),new Error(y)}s.result_diff=t,s.result_diff_binary=i,(o||l)&&(s.cumulative_diff=o,s.cumulative_diff_binary=l,A.log("Updating agent runner with inline diffs (fallback)"),await S(ke(),"update-runner",async()=>{await fe(e.id,{result_diff:o,result_diff_binary:l})}))}else A.log("No diffs to upload");return A.log("Updated agent runner with result"),await Jt(async()=>await S(ke(),"update-runner-session",()=>q(e.id,e.sessionId,s)),{maxRetries:3,baseDelay:1e3,onRetry:(p,u)=>{A.error(`Error updating agent runner session (attempt ${p}):`,u),A.log("Retrying...")}}),A.log("Finished updating agent runner with result"),{sessionUpdate:s}};import{getTracer as zt,shutdownTracers as yn,withActiveSpan as Zt}from"@netlify/otel";var _n=hn(import.meta.url),Qt=_n("../package.json"),er=_("pipeline_index"),De=3,tr=async({config:e,apiToken:t,cliPath:r="netlify",cwd:n,errorLogsPath:o,filter:i,tracing:l={}})=>{let c,{withStageTimer:s}=_t(Q.timeUnits.hours(4)),m=await lt(Qt.version,e.id,l);try{await Zt(zt(),"run-pipeline",{},m,async()=>{let p,{aiGateway:u,context:g,persistSteps:y,runner:w,sha:I}=await s("init",()=>Ht({config:e,apiToken:t,cliPath:r,cwd:n,errorLogsPath:o,filter:i,runnerVersion:Qt.version}),Q.timeUnits.minutes(10));c=w.clean,e.sha=I;let{runnerResult:f}=await s("inference",()=>Fe({cliPath:r,config:e,context:g,runner:w.runner,persistSteps:y,aiGateway:u}));await q(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let T=await s("deploy",()=>tt({cliPath:r,config:e,context:g,result:f.result,filter:i})),x=f,b=[];if(T.hasChanges&&T.deployError){b.push(ct(T.deployError));let h=1;for(;h<=De&&!T.previewInfo;)er.log(`Deploy attempt had errors. Retrying. ${h}/${De}`),await Zt(zt(),"deploy-stage",async d=>{d?.setAttributes({"stage.attempt":h});let{runnerResult:a}=await s(`inference-retry-${h}`,()=>Fe({cliPath:r,config:e,context:g,runner:w.runner,persistSteps:y,aiGateway:u,buildErrors:b,priorAgentSessionId:f.agentSessionId}));x={...a,steps:[...x.steps||[],...a.steps||[]],duration:(x.duration||0)+(a.duration||0)},T=await s(`deploy-retry-${h}`,()=>tt({cliPath:r,config:e,context:g,result:a.result,filter:i})),T.deployError&&b.push(T.deployError),h++});h>De&&!T.previewInfo&&(p=new Error(`Deploy validation failed after ${De} attempts`))}let{diff:P,resultDiff:O,previewInfo:R,diffBinary:v,resultDiffBinary:D}=T;if(await s("cleanup",()=>Xt({config:e,diff:P,result:x.result,duration:x.duration,resultDiff:O,diffBinary:v,resultDiffBinary:D,previewInfo:R}),Q.timeUnits.minutes(10)),p)throw p;process.env.NETLIFY_LOCAL_MODE||(await c?.(),await Ot())})}catch(p){er.error("Got error while running pipeline",p),await c?.();let u=p instanceof Error&&p.message;throw await q(e.id,e.sessionId,{result:u||"Encountered error when running agent",state:"error"}),p}finally{await yn()}};import rr from"crypto";var $=_("bin_local"),K=En(C.argv.slice(2),{string:["cwd","cli-path","filter","prompt","runner","model","netlify-api-token"],boolean:["verbose","help"],alias:{h:"help",v:"verbose"}}),ot=()=>{console.log(`
135
143
  agent-runner-cli-local - Run Netlify agent runner locally without API connections
136
144
 
137
145
  USAGE:
@@ -163,6 +171,6 @@ NOTE:
163
171
  This local mode mocks all Netlify API calls. The agent will run through
164
172
  the full pipeline including inference and deployment, but API calls will
165
173
  be logged instead of executed.
166
- `)};H.help&&(rt(),O.exit(0));H.prompt||(k.error("Error: --prompt is required"),rt(),O.exit(1));H["netlify-api-token"]||(k.error("Error: --netlify-api-token is required - generate a PAT from your Netlify user settings"),rt(),O.exit(1));try{let e=H.cwd||O.cwd(),t=er.join(e,".netlify","netlify-agent-runner-context*");tr.rmSync(t,{recursive:!0,force:!0});let r;try{r=await _n(e)}catch(l){k.error(l.message),k.error(`
167
- To link this directory to a Netlify site, run:`),k.error(" netlify link"),O.exit(1)}let o=`local-${Qt.randomBytes(8).toString("hex")}`,n=`session-${Qt.randomBytes(8).toString("hex")}`,i=H.runner||"claude";k.log("Starting agent runner in local mode",{runnerId:o,sessionId:n,siteId:r,cwd:e,runner:i});let a={id:o,sessionId:n,prompt:H.prompt,runner:i,model:H.model,accountType:"local",validateAgent:!1,validateAgentWithBuild:!1,sessionHistoryContext:[],siteContext:[],hasRepo:!0,useGateway:!0,sha:void 0,modelVersionOverrides:{}};O.env.NETLIFY_LOCAL_MODE="true",O.env.NETLIFY_API_HOST="api.netlify.com",O.env.NETLIFY_API_TOKEN=H["netlify-api-token"],O.env.SITE_ID=r,O.env.NETLIFY_TEAM_ID="local-team-id",O.env.NETLIFY_AGENT_RUNNER_USER_ID="local-user-id",O.env.SITE_NAME="local-site",i==="claude"?Te(e,"claude")||(k.log("Claude CLI not found, installing..."),await tt(e,"@anthropic-ai/claude-code")):i==="gemini"?Te(e,"gemini")||(k.log("Gemini CLI not found, installing..."),await tt(e,"@google/gemini-cli")):i==="codex"?Te(e,"codex")||(k.log("Codex CLI not found, installing..."),await tt(e,"my-codex-no-sandbox")):(k.error(`Unknown runner: ${i}`),O.exit(1)),await Zt({config:a,cwd:e,cliPath:H["cli-path"],filter:H.filter,tracing:{exporterUrl:void 0,traceparent:void 0}}),k.info("Finished agent (local mode)"),O.exit(0)}catch(e){k.error("Error running agent pipeline (local mode):",e),O.exit(1)}function tt(e,t){return new Promise((r,o)=>{P("npm",["install",t,"--no-save"],{cwd:e}).then(({stdout:n})=>{k.log(`${t} installed: ${n}`),r()}).catch(n=>{k.error(`Error installing ${t}: ${n.stderr||n.message}`),o(n)})})}async function _n(e){let t=er.join(e,".netlify","state.json");try{let r=await tr.readFileSync(t,"utf-8"),o=JSON.parse(r);if(!o.siteId)throw new Error(`No siteId found in ${t}. Please link this directory to a Netlify site using 'netlify link'.`);return k.log(`Found site ID from state file: ${o.siteId}`),o.siteId}catch(r){throw r.code==="ENOENT"?new Error(`No .netlify/state.json found in ${e}. Please link this directory to a Netlify site using 'netlify link'.`):r}}
174
+ `)};K.help&&(ot(),C.exit(0));K.prompt||($.error("Error: --prompt is required"),ot(),C.exit(1));K["netlify-api-token"]||($.error("Error: --netlify-api-token is required - generate a PAT from your Netlify user settings"),ot(),C.exit(1));try{let e=K.cwd||C.cwd(),t=nr.join(e,".netlify","netlify-agent-runner-context*");or.rmSync(t,{recursive:!0,force:!0});let r;try{r=await wn(e)}catch(c){$.error(c.message),$.error(`
175
+ To link this directory to a Netlify site, run:`),$.error(" netlify link"),C.exit(1)}let n=`local-${rr.randomBytes(8).toString("hex")}`,o=`session-${rr.randomBytes(8).toString("hex")}`,i=K.runner||"claude";$.log("Starting agent runner in local mode",{runnerId:n,sessionId:o,siteId:r,cwd:e,runner:i});let l={id:n,sessionId:o,prompt:K.prompt,runner:i,model:K.model,accountType:"local",validateAgent:!1,validateAgentWithBuild:!1,sessionHistoryContext:[],siteContext:[],hasRepo:!0,useGateway:!0,sha:void 0,modelVersionOverrides:{}};C.env.NETLIFY_LOCAL_MODE="true",C.env.NETLIFY_API_HOST="api.netlify.com",C.env.NETLIFY_API_TOKEN=K["netlify-api-token"],C.env.SITE_ID=r,C.env.NETLIFY_TEAM_ID="local-team-id",C.env.NETLIFY_AGENT_RUNNER_USER_ID="local-user-id",C.env.SITE_NAME="local-site",i==="claude"?ve(e,"claude")||($.log("Claude CLI not found, installing..."),await nt(e,"@anthropic-ai/claude-code")):i==="gemini"?ve(e,"gemini")||($.log("Gemini CLI not found, installing..."),await nt(e,"@google/gemini-cli")):i==="codex"?ve(e,"codex")||($.log("Codex CLI not found, installing..."),await nt(e,"@openai/codex")):($.error(`Unknown runner: ${i}`),C.exit(1)),await tr({config:l,cwd:e,cliPath:K["cli-path"],filter:K.filter,tracing:{exporterUrl:void 0,traceparent:void 0}}),$.info("Finished agent (local mode)"),C.exit(0)}catch(e){$.error("Error running agent pipeline (local mode):",e),C.exit(1)}function nt(e,t){return new Promise((r,n)=>{N("npm",["install",t,"--no-save"],{cwd:e}).then(({stdout:o})=>{$.log(`${t} installed: ${o}`),r()}).catch(o=>{$.error(`Error installing ${t}: ${o.stderr||o.message}`),n(o)})})}async function wn(e){let t=nr.join(e,".netlify","state.json");try{let r=await or.readFileSync(t,"utf-8"),n=JSON.parse(r);if(!n.siteId)throw new Error(`No siteId found in ${t}. Please link this directory to a Netlify site using 'netlify link'.`);return $.log(`Found site ID from state file: ${n.siteId}`),n.siteId}catch(r){throw r.code==="ENOENT"?new Error(`No .netlify/state.json found in ${e}. Please link this directory to a Netlify site using 'netlify link'.`):r}}
168
176
  //# sourceMappingURL=bin-local.js.map