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