@netlify/agent-runner-cli 1.57.0 → 1.57.1

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
@@ -5,7 +5,7 @@ import C from"process";import nr from"path";import or from"fs";import En from"mi
5
5
  ${l}
6
6
  </extracted_error_chunk>`).join(`
7
7
 
8
- `);return i.length>e.length*.8?e:i}import Ce from"process";import{getTracer as zr}from"@netlify/otel";import de from"process";var we=de.env.NETLIFY_API_URL,Ie=de.env.NETLIFY_API_TOKEN,Y=_("api"),xe=()=>de.env.NETLIFY_LOCAL_MODE==="true",pe=async(e,t={})=>{if(!we||!Ie)throw new Error("No API URL or token");let r=new URL(e,we),n={...t,headers:{...t.headers,Authorization:`Bearer ${Ie}`}};de.env.AGENT_RUNNERS_DEBUG==="true"&&(n.headers["x-nf-debug-logging"]="true"),t.json&&(n.headers||={},n.headers["Content-Type"]="application/json",n.body=JSON.stringify(t.json));let o=await fetch(r,n),i=o.ok&&o.status<=299;if(de.env.AGENT_RUNNERS_DEBUG==="true")Y.log(`Response headers for ${r}:`),o.headers.forEach((c,s)=>{Y.log(` ${s}: ${c}`)});else{let c=o.headers.get("x-request-id")||o.headers.get("x-nf-request-id");Y.log(`Request ID for ${r}: ${c||"N/A"}`)}if(i||Y.error(`Got status ${o.status} for request ${r}`),t.raw){if(!i)throw o;return o}let l=await(o.headers.get("content-type")?.includes("application/json")?o.json():o.text());if(!i)throw l;return l},ut=e=>{Y.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(we=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Ie=e.constants.NETLIFY_API_TOKEN)},dt=()=>({apiUrl:we,token:Ie}),fe=async(e,t)=>xe()?(Y.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):pe(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),q=async(e,t,r)=>xe()?(Y.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):pe(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var pt=async(e,t)=>xe()?(Y.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):pe(`/api/v1/agent_runners/${e}/sessions/${t}`),ft=(e,t,r)=>pe(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}}),gt=async(e,t)=>xe()?(Y.log("Mock API: getDiffUploadUrls called",{runnerId:e,sessionId:t}),{result:{upload_url:"https://s3.mock.com/mock-upload-url-result",s3_key:"mock-s3-key-result"},cumulative:{upload_url:"https://s3.mock.com/mock-upload-url-cumulative",s3_key:"mock-s3-key-cumulative"}}):pe(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Me=async(e,t)=>{Y.log(`Uploading diff to S3: ${e.substring(0,50)}...`);let r=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"text/plain"}});if(!r.ok)throw new Error(`S3 upload failed with status ${r.status}`);return r};var oe=_("ai_gateway"),je=null;var mt=async()=>{if(je)return je;oe.log("Fetching available AI gateway providers");let e=await fetch(`${dt().apiUrl}/api/v1/ai-gateway/providers`);if(!e.ok)throw new Error(`Failed to fetch AI gateway providers: ${e.statusText}`);let t=await e.json();return je=t,oe.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},dr=async(e,t)=>{let n=(await mt()).providers[e];if(!n)return oe.log(`Provider '${e}' not found`),!1;let o=n.models.includes(t);return oe.log(`Model validation for ${e}/${t}`,{isAvailable:o}),o},ht=async({netlify:e,config:t})=>{let r,n,o,i,l=e.constants?.SITE_ID;if(!l)throw new Error("No site id");let c=async()=>{clearTimeout(o),oe.log("Requesting AI gateway information");let s=await ft(l,t.id,t.sessionId);if({token:r,url:i}=s,n=s.expires_at?s.expires_at*1e3:void 0,oe.log("Got AI gateway information",{token:!!r,expiresAt:n,url:i}),n){let m=n-Date.now()-6e4;m>0&&(o=setTimeout(()=>{c()},m))}};return await Promise.all([c(),mt()]),{get url(){return i},get token(){return r},isModelAvailableForProvider:dr}};import B from"process";import V from"path";import Te from"fs";import{fileURLToPath as _r}from"url";import{createRequire as Er}from"module";import{execa as wr,execaCommand as Vn}from"execa";import{Transform as pr}from"stream";var fr=new Set(["NODE_ENV","PATH","HOME","USER","USERNAME","SHELL","PWD","OLDPWD","TMPDIR","TMP","TEMP","LANG","TERM","EDITOR","PAGER","OS","PROCESSOR_ARCHITECTURE","PROCESSOR_IDENTIFIER","SYSTEMROOT","WINDIR","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","APPDATA","LOCALAPPDATA","NODE_OPTIONS","NODE_PATH","NODE_DEBUG","NODE_NO_WARNINGS","npm_config_registry","npm_config_cache","npm_execpath","npm_node_execpath","CI","GITHUB_ACTIONS","GITHUB_WORKSPACE","GITHUB_REPOSITORY","GITHUB_REF","BUILDKITE","BUILDKITE_BRANCH","BUILDKITE_COMMIT","BUILDKITE_BUILD_NUMBER","JENKINS_URL","TRAVIS","CIRCLECI","DISPLAY","COLORTERM","TERM_PROGRAM","TERM_PROGRAM_VERSION","COLUMNS","LINES","HISTSIZE","HISTFILE","NETLIFY_AGENT_RUNNER_ID","NETLIFY_AGENT_RUNNER_SESSION_ID","NETLIFY_AGENT_RUNNER_PROMPT","NETLIFY_AGENT_RUNNER_AGENT","NETLIFY_AGENT_RUNNER_MODEL","NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED","NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED","ERROR_LOGS_PATH","NETLIFY_AGENT_RUNNER_CONTEXT","NETLIFY_AGENT_RUNNER_HAS_REPO","NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED","NETLIFY_AGENT_RUNNER_SHA","NETLIFY_TEAM_TYPE","AGENT_RUNNERS_DEBUG","NETLIFY_TEAM_ID","NETLIFY_AGENT_RUNNER_USER_ID","SITE_NAME"]),gr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function mr(){return Object.entries(process.env).filter(([e,t])=>!(!t||fr.has(e)||gr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function W(e){if(typeof e!="string")return e;let t=mr();if(t.length===0)return e;let r=e;return t.forEach(n=>{let o=new RegExp(hr(n),"g");r=r.replace(o,"******")}),r}function hr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ie=class extends pr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,n){let o=t.toString(),i=W(o);n(null,i)}};function yt(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(n,o,i){let l=typeof n=="string"?W(n):n;return typeof o=="function"?t(l,o):t(l,o,i)},process.stderr.write=function(n,o,i){let l=typeof n=="string"?W(n):n;return typeof o=="function"?r(l,o):r(l,o,i)}}var ge=null,_t=e=>(ge&&ge.destroy(),ge=new Q({totalAllowedTime:e}),ge),Et=()=>ge;var Q=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,n)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let o=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),i=null,l=null;n!==void 0&&(l=new Promise((c,s)=>{i=setTimeout(()=>{s(new Error(`${t} stage exceeded its maximum duration of ${n}ms`))},n)}));try{return l?await Promise.race([r(),l]):await r()}finally{o(),i&&clearTimeout(i)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var wt={name:"@netlify/agent-runner-cli",type:"module",version:"1.57.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.51","@google/gemini-cli":"0.16.0","@netlify/otel":"^5.0.0","@openai/codex":"0.55.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.57.0",execa:"^8.0.0","get-port":"^5.1.1",minimist:"^1.2.8"}};var Ir=_r(import.meta.url),xr=V.dirname(Ir),Tr=Er(import.meta.url),ve=_("shell"),Ge=new Set,vr={preferLocal:!0},N=(e,t,r)=>{let[n,o]=Rr(t,r),i={...vr,...o},l=wr(e,n,i);return Sr(l,i),br(l),l};var Rr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Sr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(B.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new ie).pipe(B.stdout),e.stdout?.pipe(new ie).pipe(B.stdout),e.stderr?.pipe(new ie).pipe(B.stderr);return}e.stdout?.pipe(B.stdout),e.stderr?.pipe(B.stderr)},It=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(B.kill(-e.pid,t),ve.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return ve.error("Error killing process:",r),!1}},Ar=e=>It(e,"SIGKILL"),br=e=>{Ge.add(e);let t=Et();if(t){let r=t.onTimesUp(()=>{ve.log(`Global timer expired, killing process ${e.pid}`),It(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ve.log(`Force killing process ${e.pid} after timeout`),Ar(e))},5e3)});e.on("exit",()=>{Ge.delete(e),r()}),e.on("error",()=>{Ge.delete(e),r()})}};function Re(e,t){return!!ee(e,t)}function ee(e,t){if(!B.env.NETLIFY_LOCAL_MODE)try{let o=Tr.resolve(wt.name),i=V.dirname(o);for(;i!==V.dirname(i);){let l=V.dirname(i);if(V.basename(l)==="node_modules"){let c=V.join(l,".bin",t);if(Te.existsSync(c))return c;break}i=l}}catch(o){console.error("Could not resolve package.json",o)}if(B.env.NODE_PATH){let o=V.join(B.env.NODE_PATH,".bin",t);if(Te.existsSync(o))return o}let r=V.join(e,"node_modules",".bin",t);if(Te.existsSync(r))return r;let n=V.join(xr,"..","node_modules",".bin",t);if(Te.existsSync(n))return n}var xt="netlify-agent-runner-context.md",Ye="task-history",Be="netlify-context",U=".netlify",se="results.md",He="assets";var Nr=_("utils"),Cr=e=>new Promise(t=>{setTimeout(t,e)}),Tt=(e,t=3e3)=>{let r=!1,n=null,o=[],i=null,l=(...c)=>{if(r)return n=c,new Promise(p=>{o.push(p)});r=!0;let s,m=new Promise(p=>{s=p});return i=(async()=>{await Promise.resolve();let p=await e(...c);for(s(p);;){if(await Cr(t),!n)return r=!1,i=null,p;let u=n,g=o;n=null,o=[],p=await e(...u),g.forEach(y=>{y(p)})}})(),m};return l.flush=async()=>{if((r||n)&&i)return await i,l.flush()},l},ae=(e,t,r=!1)=>{let n=null,o=null,i=null,l=function(...c){o=c,i=this;let s=r&&!n;clearTimeout(n),n=setTimeout(()=>{n=null,r||(e.apply(i,o),o=null,i=null)},t),s&&(e.apply(i,o),o=null,i=null)};return l.cancel=()=>{clearTimeout(n),n=null,o=null,i=null},l.flush=()=>{if(n){clearTimeout(n);let c=o,s=i;n=null,o=null,i=null,e.apply(s,c)}},l},vt=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(n){t&&(r?.error?r.error("Could not parse JSON",n):Nr.error("Could not parse JSON",n))}},Rt=(e,t)=>{let o=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let c=`--${t}${o}`;if(c.length>55)return"";let s=60-c.length;if(s<=0)return"";if(s>=i.length+6){let m=Math.min(s-i.length,e.length);return`${i}${e.slice(0,m)}`}return e.slice(0,s)};import{Buffer as St}from"buffer";import Pr from"path";var At=_("repo"),bt=async({config:e})=>{At.info("Getting runner diffs");let t=await Fr(),{hasChanges:r}=t,{status:n}=t;if(!r)return{hasChanges:!1};let o=$r(n);await kr(o),At.info("Changes after processing"),await qe();let i=await We(n);await Ke(i);let l={stdio:["ignore","pipe","pipe"]},s=(await N("git",["diff","--staged"],l)).stdout;if(r=!!s,!r)return{hasChanges:!1,ignored:i};let p=(await N("git",["diff","--staged","--binary"],l)).stdout,u,g;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await N("git",["commit","-m","Agent runner"]),u=(await N("git",["diff",e.sha,"HEAD"],l)).stdout;let f=(await N("git",["diff",e.sha,"HEAD","--binary"],l)).stdout;u!==f&&(g=St.from(f).toString("base64"))}let y={hasChanges:!0,diff:s,resultDiff:u,ignored:i};return s!==p&&(y.diffBinary=St.from(p).toString("base64")),g&&(y.resultDiffBinary=g),y},Ke=async(e=[])=>{await N("git",["add",".",...e])},qe=async()=>(await N("git",["status","-s"])).stdout,Nt=/.. (.+)?\.log$/,Or=[Nt],Fr=async()=>{let e=await qe();return{hasChanges:(e.trim().length===0?[]:e.split(`
8
+ `);return i.length>e.length*.8?e:i}import Ce from"process";import{getTracer as zr}from"@netlify/otel";import de from"process";var we=de.env.NETLIFY_API_URL,Ie=de.env.NETLIFY_API_TOKEN,Y=_("api"),xe=()=>de.env.NETLIFY_LOCAL_MODE==="true",pe=async(e,t={})=>{if(!we||!Ie)throw new Error("No API URL or token");let r=new URL(e,we),n={...t,headers:{...t.headers,Authorization:`Bearer ${Ie}`}};de.env.AGENT_RUNNERS_DEBUG==="true"&&(n.headers["x-nf-debug-logging"]="true"),t.json&&(n.headers||={},n.headers["Content-Type"]="application/json",n.body=JSON.stringify(t.json));let o=await fetch(r,n),i=o.ok&&o.status<=299;if(de.env.AGENT_RUNNERS_DEBUG==="true")Y.log(`Response headers for ${r}:`),o.headers.forEach((c,s)=>{Y.log(` ${s}: ${c}`)});else{let c=o.headers.get("x-request-id")||o.headers.get("x-nf-request-id");Y.log(`Request ID for ${r}: ${c||"N/A"}`)}if(i||Y.error(`Got status ${o.status} for request ${r}`),t.raw){if(!i)throw o;return o}let l=await(o.headers.get("content-type")?.includes("application/json")?o.json():o.text());if(!i)throw l;return l},ut=e=>{Y.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(we=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Ie=e.constants.NETLIFY_API_TOKEN)},dt=()=>({apiUrl:we,token:Ie}),fe=async(e,t)=>xe()?(Y.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):pe(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),q=async(e,t,r)=>xe()?(Y.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):pe(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var pt=async(e,t)=>xe()?(Y.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):pe(`/api/v1/agent_runners/${e}/sessions/${t}`),ft=(e,t,r)=>pe(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}}),gt=async(e,t)=>xe()?(Y.log("Mock API: getDiffUploadUrls called",{runnerId:e,sessionId:t}),{result:{upload_url:"https://s3.mock.com/mock-upload-url-result",s3_key:"mock-s3-key-result"},cumulative:{upload_url:"https://s3.mock.com/mock-upload-url-cumulative",s3_key:"mock-s3-key-cumulative"}}):pe(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Me=async(e,t)=>{Y.log(`Uploading diff to S3: ${e.substring(0,50)}...`);let r=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"text/plain"}});if(!r.ok)throw new Error(`S3 upload failed with status ${r.status}`);return r};var oe=_("ai_gateway"),je=null;var mt=async()=>{if(je)return je;oe.log("Fetching available AI gateway providers");let e=await fetch(`${dt().apiUrl}/api/v1/ai-gateway/providers`);if(!e.ok)throw new Error(`Failed to fetch AI gateway providers: ${e.statusText}`);let t=await e.json();return je=t,oe.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},dr=async(e,t)=>{let n=(await mt()).providers[e];if(!n)return oe.log(`Provider '${e}' not found`),!1;let o=n.models.includes(t);return oe.log(`Model validation for ${e}/${t}`,{isAvailable:o}),o},ht=async({netlify:e,config:t})=>{let r,n,o,i,l=e.constants?.SITE_ID;if(!l)throw new Error("No site id");let c=async()=>{clearTimeout(o),oe.log("Requesting AI gateway information");let s=await ft(l,t.id,t.sessionId);if({token:r,url:i}=s,n=s.expires_at?s.expires_at*1e3:void 0,oe.log("Got AI gateway information",{token:!!r,expiresAt:n,url:i}),n){let m=n-Date.now()-6e4;m>0&&(o=setTimeout(()=>{c()},m))}};return await Promise.all([c(),mt()]),{get url(){return i},get token(){return r},isModelAvailableForProvider:dr}};import B from"process";import V from"path";import Te from"fs";import{fileURLToPath as _r}from"url";import{createRequire as Er}from"module";import{execa as wr,execaCommand as Vn}from"execa";import{Transform as pr}from"stream";var fr=new Set(["NODE_ENV","PATH","HOME","USER","USERNAME","SHELL","PWD","OLDPWD","TMPDIR","TMP","TEMP","LANG","TERM","EDITOR","PAGER","OS","PROCESSOR_ARCHITECTURE","PROCESSOR_IDENTIFIER","SYSTEMROOT","WINDIR","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","APPDATA","LOCALAPPDATA","NODE_OPTIONS","NODE_PATH","NODE_DEBUG","NODE_NO_WARNINGS","npm_config_registry","npm_config_cache","npm_execpath","npm_node_execpath","CI","GITHUB_ACTIONS","GITHUB_WORKSPACE","GITHUB_REPOSITORY","GITHUB_REF","BUILDKITE","BUILDKITE_BRANCH","BUILDKITE_COMMIT","BUILDKITE_BUILD_NUMBER","JENKINS_URL","TRAVIS","CIRCLECI","DISPLAY","COLORTERM","TERM_PROGRAM","TERM_PROGRAM_VERSION","COLUMNS","LINES","HISTSIZE","HISTFILE","NETLIFY_AGENT_RUNNER_ID","NETLIFY_AGENT_RUNNER_SESSION_ID","NETLIFY_AGENT_RUNNER_PROMPT","NETLIFY_AGENT_RUNNER_AGENT","NETLIFY_AGENT_RUNNER_MODEL","NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED","NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED","ERROR_LOGS_PATH","NETLIFY_AGENT_RUNNER_CONTEXT","NETLIFY_AGENT_RUNNER_HAS_REPO","NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED","NETLIFY_AGENT_RUNNER_SHA","NETLIFY_TEAM_TYPE","AGENT_RUNNERS_DEBUG","NETLIFY_TEAM_ID","NETLIFY_AGENT_RUNNER_USER_ID","SITE_NAME"]),gr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function mr(){return Object.entries(process.env).filter(([e,t])=>!(!t||fr.has(e)||gr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function W(e){if(typeof e!="string")return e;let t=mr();if(t.length===0)return e;let r=e;return t.forEach(n=>{let o=new RegExp(hr(n),"g");r=r.replace(o,"******")}),r}function hr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ie=class extends pr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,n){let o=t.toString(),i=W(o);n(null,i)}};function yt(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(n,o,i){let l=typeof n=="string"?W(n):n;return typeof o=="function"?t(l,o):t(l,o,i)},process.stderr.write=function(n,o,i){let l=typeof n=="string"?W(n):n;return typeof o=="function"?r(l,o):r(l,o,i)}}var ge=null,_t=e=>(ge&&ge.destroy(),ge=new Q({totalAllowedTime:e}),ge),Et=()=>ge;var Q=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,n)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let o=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),i=null,l=null;n!==void 0&&(l=new Promise((c,s)=>{i=setTimeout(()=>{s(new Error(`${t} stage exceeded its maximum duration of ${n}ms`))},n)}));try{return l?await Promise.race([r(),l]):await r()}finally{o(),i&&clearTimeout(i)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var wt={name:"@netlify/agent-runner-cli",type:"module",version:"1.57.1",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.58","@google/gemini-cli":"0.19.1","@netlify/otel":"^5.0.1","@openai/codex":"0.65.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.57.0",execa:"^8.0.0","get-port":"^5.1.1",minimist:"^1.2.8"}};var Ir=_r(import.meta.url),xr=V.dirname(Ir),Tr=Er(import.meta.url),ve=_("shell"),Ge=new Set,vr={preferLocal:!0},N=(e,t,r)=>{let[n,o]=Rr(t,r),i={...vr,...o},l=wr(e,n,i);return Sr(l,i),br(l),l};var Rr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Sr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(B.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new ie).pipe(B.stdout),e.stdout?.pipe(new ie).pipe(B.stdout),e.stderr?.pipe(new ie).pipe(B.stderr);return}e.stdout?.pipe(B.stdout),e.stderr?.pipe(B.stderr)},It=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(B.kill(-e.pid,t),ve.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return ve.error("Error killing process:",r),!1}},Ar=e=>It(e,"SIGKILL"),br=e=>{Ge.add(e);let t=Et();if(t){let r=t.onTimesUp(()=>{ve.log(`Global timer expired, killing process ${e.pid}`),It(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ve.log(`Force killing process ${e.pid} after timeout`),Ar(e))},5e3)});e.on("exit",()=>{Ge.delete(e),r()}),e.on("error",()=>{Ge.delete(e),r()})}};function Re(e,t){return!!ee(e,t)}function ee(e,t){if(!B.env.NETLIFY_LOCAL_MODE)try{let o=Tr.resolve(wt.name),i=V.dirname(o);for(;i!==V.dirname(i);){let l=V.dirname(i);if(V.basename(l)==="node_modules"){let c=V.join(l,".bin",t);if(Te.existsSync(c))return c;break}i=l}}catch(o){console.error("Could not resolve package.json",o)}if(B.env.NODE_PATH){let o=V.join(B.env.NODE_PATH,".bin",t);if(Te.existsSync(o))return o}let r=V.join(e,"node_modules",".bin",t);if(Te.existsSync(r))return r;let n=V.join(xr,"..","node_modules",".bin",t);if(Te.existsSync(n))return n}var xt="netlify-agent-runner-context.md",Ye="task-history",Be="netlify-context",U=".netlify",se="results.md",He="assets";var Nr=_("utils"),Cr=e=>new Promise(t=>{setTimeout(t,e)}),Tt=(e,t=3e3)=>{let r=!1,n=null,o=[],i=null,l=(...c)=>{if(r)return n=c,new Promise(p=>{o.push(p)});r=!0;let s,m=new Promise(p=>{s=p});return i=(async()=>{await Promise.resolve();let p=await e(...c);for(s(p);;){if(await Cr(t),!n)return r=!1,i=null,p;let u=n,g=o;n=null,o=[],p=await e(...u),g.forEach(y=>{y(p)})}})(),m};return l.flush=async()=>{if((r||n)&&i)return await i,l.flush()},l},ae=(e,t,r=!1)=>{let n=null,o=null,i=null,l=function(...c){o=c,i=this;let s=r&&!n;clearTimeout(n),n=setTimeout(()=>{n=null,r||(e.apply(i,o),o=null,i=null)},t),s&&(e.apply(i,o),o=null,i=null)};return l.cancel=()=>{clearTimeout(n),n=null,o=null,i=null},l.flush=()=>{if(n){clearTimeout(n);let c=o,s=i;n=null,o=null,i=null,e.apply(s,c)}},l},vt=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(n){t&&(r?.error?r.error("Could not parse JSON",n):Nr.error("Could not parse JSON",n))}},Rt=(e,t)=>{let o=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let c=`--${t}${o}`;if(c.length>55)return"";let s=60-c.length;if(s<=0)return"";if(s>=i.length+6){let m=Math.min(s-i.length,e.length);return`${i}${e.slice(0,m)}`}return e.slice(0,s)};import{Buffer as St}from"buffer";import Pr from"path";var At=_("repo"),bt=async({config:e})=>{At.info("Getting runner diffs");let t=await Fr(),{hasChanges:r}=t,{status:n}=t;if(!r)return{hasChanges:!1};let o=$r(n);await kr(o),At.info("Changes after processing"),await qe();let i=await We(n);await Ke(i);let l={stdio:["ignore","pipe","pipe"]},s=(await N("git",["diff","--staged"],l)).stdout;if(r=!!s,!r)return{hasChanges:!1,ignored:i};let p=(await N("git",["diff","--staged","--binary"],l)).stdout,u,g;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await N("git",["commit","-m","Agent runner"]),u=(await N("git",["diff",e.sha,"HEAD"],l)).stdout;let f=(await N("git",["diff",e.sha,"HEAD","--binary"],l)).stdout;u!==f&&(g=St.from(f).toString("base64"))}let y={hasChanges:!0,diff:s,resultDiff:u,ignored:i};return s!==p&&(y.diffBinary=St.from(p).toString("base64")),g&&(y.resultDiffBinary=g),y},Ke=async(e=[])=>{await N("git",["add",".",...e])},qe=async()=>(await N("git",["status","-s"])).stdout,Nt=/.. (.+)?\.log$/,Or=[Nt],Fr=async()=>{let e=await qe();return{hasChanges:(e.trim().length===0?[]:e.split(`
9
9
  `).filter(n=>Or.some(i=>i instanceof RegExp?i.test(n):n===i)?!1:n[1]?.trim()!=="")).length!==0,status:e}},Ct=async()=>{let{stdout:e}=await N("git",["rev-parse","HEAD"]);return e.trim()},Pt=async()=>{let{stdout:e}=await N("git",["rev-list","--max-parents=0","HEAD"]);return e.trim()},We=async e=>{e||=await qe();let t=[".netlify","node_modules"],r=[];return e.split(`
10
10
  `).forEach(n=>{t.forEach(i=>{[`?? ${i}`,`?? ${i}${Pr.sep}`].some(c=>n.startsWith(c))&&r.push(`:!${i}`)});let o=n.match(Nt)?.[1];o&&r.push(`:!${o}.log`)}),r},Ot=async()=>{await N("git",["reset","--hard","HEAD"])},$r=e=>{let t=e.split(`
11
11
  `).reduce((r,n)=>{if(!n)return r;let[o,i,,...l]=n,c=l.join(""),s=o.trim(),m=i.trim();return r[c]?r[c].change=m:r[c]={filePath:c,stage:s,change:m},r},{});return Object.values(t)},kr=async e=>{let t=[];for(let r of e)r.stage&&!r.change&&t.push(N("git",["restore","--staged","--worktree",r.filePath]));await Promise.allSettled(t)};import Lr from"fs/promises";import Ur from"os";import kt from"path";import te from"process";import Mr from"readline";import Ve from"path";import Dr from"fs/promises";var Je=_("agent-output-utils");async function le({initialResult:e,agentName:t,hasError:r}){let n="",o=Ve.join(process.cwd(),U,se);try{let i=await Dr.readFile(o,"utf-8");i&&(n=i,Je.log(`Pulled result from ${Ve.relative(process.cwd(),o)}`))}catch{Je.log(`No results file found at ${Ve.relative(process.cwd(),o)}`)}return n||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function ce({error:e,agentName:t}){let r=e&&typeof e=="object"?JSON.stringify(e):e,n=r?.replace(/\s+/g," ").trim().toLowerCase()||"",o="";return n?.includes("ai gateway is not available for your account")||n?.includes("ai gateway is not enabled for your account")?o="AI Gateway is currently not available on your account. Please confirm your account meets the criteria for using Agent Runners and AI Gateway and that your account has remaining AI Gateway inference credits available. Reach out to Netlify support if this is unexpected.":n?.includes("error when talking to gemini api")?o="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":(n?.includes("connection closed prematurely")||n?.includes("499")&&t.toLowerCase().includes("gemini"))&&(o=`The ${t} models were currently overloaded. Please try again or use a different available agent.`),n?.includes("request timed out")&&(o=`The ${t} API request's have timed out. Please try again or use a different available agent.`),n?.includes("network error")&&(o=`The ${t} agent is having network issues. Please try again or use a different available agent.`),o&&Je.log(`Providing updated error messsage: ${o}, replacing original error: ${r}`),o||r||void 0}function ue(e){if(!e)return!1;let r=(e&&typeof e=="object"?JSON.stringify(e):e)?.replace(/\s+/g," ").trim().toLowerCase()||"";return!!(r?.includes("error when talking to gemini api")||r?.includes("499")||r?.includes("connection closed prematurely")||r?.includes("request timed out")||r?.includes("network error"))}var M=_("runner_claude"),Ft="Claude Code",Se="claude-opus-4-5-20251101",$t=e=>({Task:"Task",Bash:"Run command",Glob:"Find files",Grep:"Search files",LS:"List directory",ExitPlanMode:"Exit planning",Read:"Read file",Edit:"Edit file",MultiEdit:"Edit multiple files",Write:"Coding",NotebookEdit:"Edit notebook",WebFetch:"Fetch webpage",TodoWrite:"Update task list",WebSearch:"Search web",BashOutput:"Get command output",KillBash:"Stop command"})[e]||e,jr=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(M.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(M.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(M.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0}));async function Xe({config:e,netlify:t,persistSteps:r,aiGateway:n,continueSession:o,priorAgentSessionId:i}){let l=e,{accountType:c,prompt:s,modelVersionOverrides:m}=l,{model:p}=l,u="";if(n){let{token:h,url:d}=n;if(!h||!d)throw new Error("No token or url provided from AI Gateway");if(m?.claude){let a=m?.claude?.[c];if(a){if(!await n.isModelAvailableForProvider("anthropic",a))throw new Error(`Model override '${a}' is not available for anthropic provider`);p=a}}else if(p){if(!await n.isModelAvailableForProvider("anthropic",p))throw new Error(`Model '${p}' is not available for anthropic provider`)}else await n.isModelAvailableForProvider("anthropic",Se)?(p=Se,M.log(`Using default model: ${Se}`)):M.log(`Default model ${Se} is not available, proceeding without model specification`);te.env.ANTHROPIC_API_KEY=h,te.env.ANTHROPIC_BASE_URL=d}else if(!te.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let g=[],y=[],w={},I=0,f=0,T,x,b=[ee(te.cwd(),"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...p?["--model",p]:[],...o?["--continue"]:[],...o&&i?["--resume",i]:[],"-p",s],P=`${te.env.NVM_BIN}/node`;M.log(`Running ${P} ${b.join(" ")}`);let O=t.utils.run(P,b,{all:!0,env:te.env});O.stdin?.end();let R=ae(()=>{r?.({steps:g,duration:f})},250),v=(h,d)=>{let a={...h,id:I};I+=1,y.push(a),g.push(a),d||R.flush(),R(),d&&R.flush()},D=Mr.createInterface({input:O.all});return D.on("error",h=>{M.error("Readline interface error",{error:h.message,stack:h.stack})}),D.on("line",h=>{let d=null;try{d=JSON.parse(h)}catch{M.log("Could not parse line",h)}d?.session_id&&d.session_id!==u&&(u=d.session_id),Array.isArray(d?.message?.content)?d.message.content.forEach(a=>{switch(a.type){case"text":{a.text&&v({message:a.text});break}case"image":{typeof a.source=="object"&&a.source&&a.source.type==="base64"&&a.source.media_type?v({message:`![](data:${a.source.media_type};base64,${a.source.data})`}):M.log(`Unsupported image type ${a.source?.type}`,a.source);break}case"tool_use":{if(a.name==="Task"){let E=a.input?.description&&`\`${a.input.description}\``;v({title:[$t(a.name),E].filter(Boolean).join(" ")})}else a.id&&(w[a.id]=a);R.flush();break}case"tool_result":{let E=a.tool_use_id?w[a.tool_use_id]:void 0,z;if(E){let J=E.input?.file_path&&kt.relative(te.cwd(),E.input.file_path),F=J&&`\`${J}\``;z=[$t(E.name||""),F].filter(Boolean).join(" ")}let Ee=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(E?.name||""),Z;if(typeof a.content=="string")Z=a.content;else if(Array.isArray(a.content)){let J=[];a.content.forEach(F=>{F?.type==="text"&&typeof F.text=="string"?J.push(F.text):F?.type==="image"&&typeof F.source=="object"&&F.source?F.source.type==="base64"&&F.source.media_type?J.push(`![](data:${F.source.media_type};base64,${F.source.data})`):M.log(`Unsupported image type ${F.source.type}`,F.source):M.log(`Unsupported block type ${F?.type}`)}),Z=J.join(`
package/dist/bin.js CHANGED
@@ -5,7 +5,7 @@ import it from"process";import Sn from"minimist";import{createRequire as wn}from
5
5
  ${l}
6
6
  </extracted_error_chunk>`).join(`
7
7
 
8
- `);return s.length>e.length*.8?e:s}import be from"process";import{getTracer as tn}from"@netlify/otel";import ue from"process";var Ee=ue.env.NETLIFY_API_URL,we=ue.env.NETLIFY_API_TOKEN,j=_("api"),Te=()=>ue.env.NETLIFY_LOCAL_MODE==="true",pe=async(e,t={})=>{if(!Ee||!we)throw new Error("No API URL or token");let r=new URL(e,Ee),n={...t,headers:{...t.headers,Authorization:`Bearer ${we}`}};ue.env.AGENT_RUNNERS_DEBUG==="true"&&(n.headers["x-nf-debug-logging"]="true"),t.json&&(n.headers||={},n.headers["Content-Type"]="application/json",n.body=JSON.stringify(t.json));let o=await fetch(r,n),s=o.ok&&o.status<=299;if(ue.env.AGENT_RUNNERS_DEBUG==="true")j.log(`Response headers for ${r}:`),o.headers.forEach((c,i)=>{j.log(` ${i}: ${c}`)});else{let c=o.headers.get("x-request-id")||o.headers.get("x-nf-request-id");j.log(`Request ID for ${r}: ${c||"N/A"}`)}if(s||j.error(`Got status ${o.status} for request ${r}`),t.raw){if(!s)throw o;return o}let l=await(o.headers.get("content-type")?.includes("application/json")?o.json():o.text());if(!s)throw l;return l},dt=e=>{j.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Ee=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(we=e.constants.NETLIFY_API_TOKEN)},ft=()=>({apiUrl:Ee,token:we}),de=async(e,t)=>Te()?(j.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):pe(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),H=async(e,t,r)=>Te()?(j.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):pe(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var gt=async(e,t)=>Te()?(j.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):pe(`/api/v1/agent_runners/${e}/sessions/${t}`),mt=(e,t,r)=>pe(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}}),ht=async(e,t)=>Te()?(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"}}):pe(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Ue=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 re=_("ai_gateway"),Me=null;var yt=async()=>{if(Me)return Me;re.log("Fetching available AI gateway providers");let e=await fetch(`${ft().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 Me=t,re.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},mr=async(e,t)=>{let n=(await yt()).providers[e];if(!n)return re.log(`Provider '${e}' not found`),!1;let o=n.models.includes(t);return re.log(`Model validation for ${e}/${t}`,{isAvailable:o}),o},_t=async({netlify:e,config:t})=>{let r,n,o,s,l=e.constants?.SITE_ID;if(!l)throw new Error("No site id");let c=async()=>{clearTimeout(o),re.log("Requesting AI gateway information");let i=await mt(l,t.id,t.sessionId);if({token:r,url:s}=i,n=i.expires_at?i.expires_at*1e3:void 0,re.log("Got AI gateway information",{token:!!r,expiresAt:n,url:s}),n){let m=n-Date.now()-6e4;m>0&&(o=setTimeout(()=>{c()},m))}};return await Promise.all([c(),yt()]),{get url(){return s},get token(){return r},isModelAvailableForProvider:mr}};import Y from"process";import K from"path";import Ie from"fs";import{fileURLToPath as Ir}from"url";import{createRequire as xr}from"module";import{execa as Rr,execaCommand as ro}from"execa";import{Transform as hr}from"stream";var yr=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"]),_r=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function Er(){return Object.entries(process.env).filter(([e,t])=>!(!t||yr.has(e)||_r.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function W(e){if(typeof e!="string")return e;let t=Er();if(t.length===0)return e;let r=e;return t.forEach(n=>{let o=new RegExp(wr(n),"g");r=r.replace(o,"******")}),r}function wr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ne=class extends hr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,n){let o=t.toString(),s=W(o);n(null,s)}};function Et(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(n,o,s){let l=typeof n=="string"?W(n):n;return typeof o=="function"?t(l,o):t(l,o,s)},process.stderr.write=function(n,o,s){let l=typeof n=="string"?W(n):n;return typeof o=="function"?r(l,o):r(l,o,s)}}var fe=null,wt=e=>(fe&&fe.destroy(),fe=new z({totalAllowedTime:e}),fe),Tt=()=>fe;var z=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,n)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let o=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),s=null,l=null;n!==void 0&&(l=new Promise((c,i)=>{s=setTimeout(()=>{i(new Error(`${t} stage exceeded its maximum duration of ${n}ms`))},n)}));try{return l?await Promise.race([r(),l]):await r()}finally{o(),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 It={name:"@netlify/agent-runner-cli",type:"module",version:"1.57.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.51","@google/gemini-cli":"0.16.0","@netlify/otel":"^5.0.0","@openai/codex":"0.55.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.57.0",execa:"^8.0.0","get-port":"^5.1.1",minimist:"^1.2.8"}};var vr=Ir(import.meta.url),Nr=K.dirname(vr),Ar=xr(import.meta.url),xe=_("shell"),Ge=new Set,Sr={preferLocal:!0},O=(e,t,r)=>{let[n,o]=br(t,r),s={...Sr,...o},l=Rr(e,n,s);return Cr(l,s),Or(l),l};var br=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Cr=(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 ne).pipe(Y.stdout),e.stdout?.pipe(new ne).pipe(Y.stdout),e.stderr?.pipe(new ne).pipe(Y.stderr);return}e.stdout?.pipe(Y.stdout),e.stderr?.pipe(Y.stderr)},xt=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(Y.kill(-e.pid,t),xe.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return xe.error("Error killing process:",r),!1}},Pr=e=>xt(e,"SIGKILL"),Or=e=>{Ge.add(e);let t=Tt();if(t){let r=t.onTimesUp(()=>{xe.log(`Global timer expired, killing process ${e.pid}`),xt(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(xe.log(`Force killing process ${e.pid} after timeout`),Pr(e))},5e3)});e.on("exit",()=>{Ge.delete(e),r()}),e.on("error",()=>{Ge.delete(e),r()})}};function oe(e,t){if(!Y.env.NETLIFY_LOCAL_MODE)try{let o=Ar.resolve(It.name),s=K.dirname(o);for(;s!==K.dirname(s);){let l=K.dirname(s);if(K.basename(l)==="node_modules"){let c=K.join(l,".bin",t);if(Ie.existsSync(c))return c;break}s=l}}catch(o){console.error("Could not resolve package.json",o)}if(Y.env.NODE_PATH){let o=K.join(Y.env.NODE_PATH,".bin",t);if(Ie.existsSync(o))return o}let r=K.join(e,"node_modules",".bin",t);if(Ie.existsSync(r))return r;let n=K.join(Nr,"..","node_modules",".bin",t);if(Ie.existsSync(n))return n}var Rt="netlify-agent-runner-context.md",je="task-history",Ye="netlify-context",k=".netlify",se="results.md",Be="assets",He="other",We="personal";var Ke="enterprise",qe="free",vt=[We,"pro",Ke,qe];var Nt=_("utils"),Fr=e=>new Promise(t=>{setTimeout(t,e)}),At=(e,t=3e3)=>{let r=!1,n=null,o=[],s=null,l=(...c)=>{if(r)return n=c,new Promise(p=>{o.push(p)});r=!0;let i,m=new Promise(p=>{i=p});return s=(async()=>{await Promise.resolve();let p=await e(...c);for(i(p);;){if(await Fr(t),!n)return r=!1,s=null,p;let u=n,g=o;n=null,o=[],p=await e(...u),g.forEach(y=>{y(p)})}})(),m};return l.flush=async()=>{if((r||n)&&s)return await s,l.flush()},l},ie=(e,t,r=!1)=>{let n=null,o=null,s=null,l=function(...c){o=c,s=this;let i=r&&!n;clearTimeout(n),n=setTimeout(()=>{n=null,r||(e.apply(s,o),o=null,s=null)},t),i&&(e.apply(s,o),o=null,s=null)};return l.cancel=()=>{clearTimeout(n),n=null,o=null,s=null},l.flush=()=>{if(n){clearTimeout(n);let c=o,i=s;n=null,o=null,s=null,e.apply(i,c)}},l},Re=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(n){t&&(r?.error?r.error("Could not parse JSON",n):Nt.error("Could not parse JSON",n))}},St=(e,t)=>{let o=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let c=`--${t}${o}`;if(c.length>55)return"";let i=60-c.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)},Lr=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!vt.some(t=>t in e),bt=()=>{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,n])=>{if(n){let o=`NETLIFY_FF_AGENT_RUNNER_${r.toUpperCase()}_VERSION`;try{let s=JSON.parse(n);Lr(s)&&(e[r]=s)}catch(s){let c=s instanceof SyntaxError?"Invalid JSON":s.message;Nt.error(`Could not parse ${r} model version override from ${o}: ${c}`)}}}),e};import{Buffer as Ct}from"buffer";import Dr from"path";var Pt=_("repo"),Ot=async({config:e})=>{Pt.info("Getting runner diffs");let t=await kr(),{hasChanges:r}=t,{status:n}=t;if(!r)return{hasChanges:!1};let o=Ur(n);await Mr(o),Pt.info("Changes after processing"),await Je();let s=await Xe(n);await Ve(s);let l={stdio:["ignore","pipe","pipe"]},i=(await O("git",["diff","--staged"],l)).stdout;if(r=!!i,!r)return{hasChanges:!1,ignored:s};let p=(await O("git",["diff","--staged","--binary"],l)).stdout,u,g;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await O("git",["commit","-m","Agent runner"]),u=(await O("git",["diff",e.sha,"HEAD"],l)).stdout;let f=(await O("git",["diff",e.sha,"HEAD","--binary"],l)).stdout;u!==f&&(g=Ct.from(f).toString("base64"))}let y={hasChanges:!0,diff:i,resultDiff:u,ignored:s};return i!==p&&(y.diffBinary=Ct.from(p).toString("base64")),g&&(y.resultDiffBinary=g),y},Ve=async(e=[])=>{await O("git",["add",".",...e])},Je=async()=>(await O("git",["status","-s"])).stdout,Ft=/.. (.+)?\.log$/,$r=[Ft],kr=async()=>{let e=await Je();return{hasChanges:(e.trim().length===0?[]:e.split(`
8
+ `);return s.length>e.length*.8?e:s}import be from"process";import{getTracer as tn}from"@netlify/otel";import ue from"process";var Ee=ue.env.NETLIFY_API_URL,we=ue.env.NETLIFY_API_TOKEN,j=_("api"),Te=()=>ue.env.NETLIFY_LOCAL_MODE==="true",pe=async(e,t={})=>{if(!Ee||!we)throw new Error("No API URL or token");let r=new URL(e,Ee),n={...t,headers:{...t.headers,Authorization:`Bearer ${we}`}};ue.env.AGENT_RUNNERS_DEBUG==="true"&&(n.headers["x-nf-debug-logging"]="true"),t.json&&(n.headers||={},n.headers["Content-Type"]="application/json",n.body=JSON.stringify(t.json));let o=await fetch(r,n),s=o.ok&&o.status<=299;if(ue.env.AGENT_RUNNERS_DEBUG==="true")j.log(`Response headers for ${r}:`),o.headers.forEach((c,i)=>{j.log(` ${i}: ${c}`)});else{let c=o.headers.get("x-request-id")||o.headers.get("x-nf-request-id");j.log(`Request ID for ${r}: ${c||"N/A"}`)}if(s||j.error(`Got status ${o.status} for request ${r}`),t.raw){if(!s)throw o;return o}let l=await(o.headers.get("content-type")?.includes("application/json")?o.json():o.text());if(!s)throw l;return l},dt=e=>{j.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Ee=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(we=e.constants.NETLIFY_API_TOKEN)},ft=()=>({apiUrl:Ee,token:we}),de=async(e,t)=>Te()?(j.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):pe(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),H=async(e,t,r)=>Te()?(j.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):pe(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var gt=async(e,t)=>Te()?(j.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):pe(`/api/v1/agent_runners/${e}/sessions/${t}`),mt=(e,t,r)=>pe(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}}),ht=async(e,t)=>Te()?(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"}}):pe(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Ue=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 re=_("ai_gateway"),Me=null;var yt=async()=>{if(Me)return Me;re.log("Fetching available AI gateway providers");let e=await fetch(`${ft().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 Me=t,re.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},mr=async(e,t)=>{let n=(await yt()).providers[e];if(!n)return re.log(`Provider '${e}' not found`),!1;let o=n.models.includes(t);return re.log(`Model validation for ${e}/${t}`,{isAvailable:o}),o},_t=async({netlify:e,config:t})=>{let r,n,o,s,l=e.constants?.SITE_ID;if(!l)throw new Error("No site id");let c=async()=>{clearTimeout(o),re.log("Requesting AI gateway information");let i=await mt(l,t.id,t.sessionId);if({token:r,url:s}=i,n=i.expires_at?i.expires_at*1e3:void 0,re.log("Got AI gateway information",{token:!!r,expiresAt:n,url:s}),n){let m=n-Date.now()-6e4;m>0&&(o=setTimeout(()=>{c()},m))}};return await Promise.all([c(),yt()]),{get url(){return s},get token(){return r},isModelAvailableForProvider:mr}};import Y from"process";import K from"path";import Ie from"fs";import{fileURLToPath as Ir}from"url";import{createRequire as xr}from"module";import{execa as Rr,execaCommand as ro}from"execa";import{Transform as hr}from"stream";var yr=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"]),_r=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function Er(){return Object.entries(process.env).filter(([e,t])=>!(!t||yr.has(e)||_r.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function W(e){if(typeof e!="string")return e;let t=Er();if(t.length===0)return e;let r=e;return t.forEach(n=>{let o=new RegExp(wr(n),"g");r=r.replace(o,"******")}),r}function wr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ne=class extends hr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,n){let o=t.toString(),s=W(o);n(null,s)}};function Et(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(n,o,s){let l=typeof n=="string"?W(n):n;return typeof o=="function"?t(l,o):t(l,o,s)},process.stderr.write=function(n,o,s){let l=typeof n=="string"?W(n):n;return typeof o=="function"?r(l,o):r(l,o,s)}}var fe=null,wt=e=>(fe&&fe.destroy(),fe=new z({totalAllowedTime:e}),fe),Tt=()=>fe;var z=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,n)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let o=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),s=null,l=null;n!==void 0&&(l=new Promise((c,i)=>{s=setTimeout(()=>{i(new Error(`${t} stage exceeded its maximum duration of ${n}ms`))},n)}));try{return l?await Promise.race([r(),l]):await r()}finally{o(),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 It={name:"@netlify/agent-runner-cli",type:"module",version:"1.57.1",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.58","@google/gemini-cli":"0.19.1","@netlify/otel":"^5.0.1","@openai/codex":"0.65.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.57.0",execa:"^8.0.0","get-port":"^5.1.1",minimist:"^1.2.8"}};var vr=Ir(import.meta.url),Nr=K.dirname(vr),Ar=xr(import.meta.url),xe=_("shell"),Ge=new Set,Sr={preferLocal:!0},O=(e,t,r)=>{let[n,o]=br(t,r),s={...Sr,...o},l=Rr(e,n,s);return Cr(l,s),Or(l),l};var br=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Cr=(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 ne).pipe(Y.stdout),e.stdout?.pipe(new ne).pipe(Y.stdout),e.stderr?.pipe(new ne).pipe(Y.stderr);return}e.stdout?.pipe(Y.stdout),e.stderr?.pipe(Y.stderr)},xt=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(Y.kill(-e.pid,t),xe.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return xe.error("Error killing process:",r),!1}},Pr=e=>xt(e,"SIGKILL"),Or=e=>{Ge.add(e);let t=Tt();if(t){let r=t.onTimesUp(()=>{xe.log(`Global timer expired, killing process ${e.pid}`),xt(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(xe.log(`Force killing process ${e.pid} after timeout`),Pr(e))},5e3)});e.on("exit",()=>{Ge.delete(e),r()}),e.on("error",()=>{Ge.delete(e),r()})}};function oe(e,t){if(!Y.env.NETLIFY_LOCAL_MODE)try{let o=Ar.resolve(It.name),s=K.dirname(o);for(;s!==K.dirname(s);){let l=K.dirname(s);if(K.basename(l)==="node_modules"){let c=K.join(l,".bin",t);if(Ie.existsSync(c))return c;break}s=l}}catch(o){console.error("Could not resolve package.json",o)}if(Y.env.NODE_PATH){let o=K.join(Y.env.NODE_PATH,".bin",t);if(Ie.existsSync(o))return o}let r=K.join(e,"node_modules",".bin",t);if(Ie.existsSync(r))return r;let n=K.join(Nr,"..","node_modules",".bin",t);if(Ie.existsSync(n))return n}var Rt="netlify-agent-runner-context.md",je="task-history",Ye="netlify-context",k=".netlify",se="results.md",Be="assets",He="other",We="personal";var Ke="enterprise",qe="free",vt=[We,"pro",Ke,qe];var Nt=_("utils"),Fr=e=>new Promise(t=>{setTimeout(t,e)}),At=(e,t=3e3)=>{let r=!1,n=null,o=[],s=null,l=(...c)=>{if(r)return n=c,new Promise(p=>{o.push(p)});r=!0;let i,m=new Promise(p=>{i=p});return s=(async()=>{await Promise.resolve();let p=await e(...c);for(i(p);;){if(await Fr(t),!n)return r=!1,s=null,p;let u=n,g=o;n=null,o=[],p=await e(...u),g.forEach(y=>{y(p)})}})(),m};return l.flush=async()=>{if((r||n)&&s)return await s,l.flush()},l},ie=(e,t,r=!1)=>{let n=null,o=null,s=null,l=function(...c){o=c,s=this;let i=r&&!n;clearTimeout(n),n=setTimeout(()=>{n=null,r||(e.apply(s,o),o=null,s=null)},t),i&&(e.apply(s,o),o=null,s=null)};return l.cancel=()=>{clearTimeout(n),n=null,o=null,s=null},l.flush=()=>{if(n){clearTimeout(n);let c=o,i=s;n=null,o=null,s=null,e.apply(i,c)}},l},Re=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(n){t&&(r?.error?r.error("Could not parse JSON",n):Nt.error("Could not parse JSON",n))}},St=(e,t)=>{let o=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let c=`--${t}${o}`;if(c.length>55)return"";let i=60-c.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)},Lr=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!vt.some(t=>t in e),bt=()=>{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,n])=>{if(n){let o=`NETLIFY_FF_AGENT_RUNNER_${r.toUpperCase()}_VERSION`;try{let s=JSON.parse(n);Lr(s)&&(e[r]=s)}catch(s){let c=s instanceof SyntaxError?"Invalid JSON":s.message;Nt.error(`Could not parse ${r} model version override from ${o}: ${c}`)}}}),e};import{Buffer as Ct}from"buffer";import Dr from"path";var Pt=_("repo"),Ot=async({config:e})=>{Pt.info("Getting runner diffs");let t=await kr(),{hasChanges:r}=t,{status:n}=t;if(!r)return{hasChanges:!1};let o=Ur(n);await Mr(o),Pt.info("Changes after processing"),await Je();let s=await Xe(n);await Ve(s);let l={stdio:["ignore","pipe","pipe"]},i=(await O("git",["diff","--staged"],l)).stdout;if(r=!!i,!r)return{hasChanges:!1,ignored:s};let p=(await O("git",["diff","--staged","--binary"],l)).stdout,u,g;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await O("git",["commit","-m","Agent runner"]),u=(await O("git",["diff",e.sha,"HEAD"],l)).stdout;let f=(await O("git",["diff",e.sha,"HEAD","--binary"],l)).stdout;u!==f&&(g=Ct.from(f).toString("base64"))}let y={hasChanges:!0,diff:i,resultDiff:u,ignored:s};return i!==p&&(y.diffBinary=Ct.from(p).toString("base64")),g&&(y.resultDiffBinary=g),y},Ve=async(e=[])=>{await O("git",["add",".",...e])},Je=async()=>(await O("git",["status","-s"])).stdout,Ft=/.. (.+)?\.log$/,$r=[Ft],kr=async()=>{let e=await Je();return{hasChanges:(e.trim().length===0?[]:e.split(`
9
9
  `).filter(n=>$r.some(s=>s instanceof RegExp?s.test(n):n===s)?!1:n[1]?.trim()!=="")).length!==0,status:e}},Lt=async()=>{let{stdout:e}=await O("git",["rev-parse","HEAD"]);return e.trim()},Dt=async()=>{let{stdout:e}=await O("git",["rev-list","--max-parents=0","HEAD"]);return e.trim()},Xe=async e=>{e||=await Je();let t=[".netlify","node_modules"],r=[];return e.split(`
10
10
  `).forEach(n=>{t.forEach(s=>{[`?? ${s}`,`?? ${s}${Dr.sep}`].some(c=>n.startsWith(c))&&r.push(`:!${s}`)});let o=n.match(Ft)?.[1];o&&r.push(`:!${o}.log`)}),r},$t=async()=>{await O("git",["reset","--hard","HEAD"])},Ur=e=>{let t=e.split(`
11
11
  `).reduce((r,n)=>{if(!n)return r;let[o,s,,...l]=n,c=l.join(""),i=o.trim(),m=s.trim();return r[c]?r[c].change=m:r[c]={filePath:c,stage:i,change:m},r},{});return Object.values(t)},Mr=async e=>{let t=[];for(let r of e)r.stage&&!r.change&&t.push(O("git",["restore","--staged","--worktree",r.filePath]));await Promise.allSettled(t)};import jr from"fs/promises";import Yr from"os";import Mt from"path";import Z from"process";import Br from"readline";import ze from"path";import Gr from"fs/promises";var Ze=_("agent-output-utils");async function ae({initialResult:e,agentName:t,hasError:r}){let n="",o=ze.join(process.cwd(),k,se);try{let s=await Gr.readFile(o,"utf-8");s&&(n=s,Ze.log(`Pulled result from ${ze.relative(process.cwd(),o)}`))}catch{Ze.log(`No results file found at ${ze.relative(process.cwd(),o)}`)}return n||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function le({error:e,agentName:t}){let r=e&&typeof e=="object"?JSON.stringify(e):e,n=r?.replace(/\s+/g," ").trim().toLowerCase()||"",o="";return n?.includes("ai gateway is not available for your account")||n?.includes("ai gateway is not enabled for your account")?o="AI Gateway is currently not available on your account. Please confirm your account meets the criteria for using Agent Runners and AI Gateway and that your account has remaining AI Gateway inference credits available. Reach out to Netlify support if this is unexpected.":n?.includes("error when talking to gemini api")?o="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":(n?.includes("connection closed prematurely")||n?.includes("499")&&t.toLowerCase().includes("gemini"))&&(o=`The ${t} models were currently overloaded. Please try again or use a different available agent.`),n?.includes("request timed out")&&(o=`The ${t} API request's have timed out. Please try again or use a different available agent.`),n?.includes("network error")&&(o=`The ${t} agent is having network issues. Please try again or use a different available agent.`),o&&Ze.log(`Providing updated error messsage: ${o}, replacing original error: ${r}`),o||r||void 0}function ce(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=_("runner_claude"),kt="Claude Code",ve="claude-opus-4-5-20251101",Ut=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,Hr=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(U.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(U.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(U.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0}));async function Qe({config:e,netlify:t,persistSteps:r,aiGateway:n,continueSession:o,priorAgentSessionId:s}){let l=e,{accountType:c,prompt:i,modelVersionOverrides:m}=l,{model:p}=l,u="";if(n){let{token:h,url:d}=n;if(!h||!d)throw new Error("No token or url provided from AI Gateway");if(m?.claude){let a=m?.claude?.[c];if(a){if(!await n.isModelAvailableForProvider("anthropic",a))throw new Error(`Model override '${a}' is not available for anthropic provider`);p=a}}else if(p){if(!await n.isModelAvailableForProvider("anthropic",p))throw new Error(`Model '${p}' is not available for anthropic provider`)}else await n.isModelAvailableForProvider("anthropic",ve)?(p=ve,U.log(`Using default model: ${ve}`)):U.log(`Default model ${ve} is not available, proceeding without model specification`);Z.env.ANTHROPIC_API_KEY=h,Z.env.ANTHROPIC_BASE_URL=d}else if(!Z.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let g=[],y=[],w={},T=0,f=0,I,x,S=[oe(Z.cwd(),"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...p?["--model",p]:[],...o?["--continue"]:[],...o&&s?["--resume",s]:[],"-p",i],b=`${Z.env.NVM_BIN}/node`;U.log(`Running ${b} ${S.join(" ")}`);let C=t.utils.run(b,S,{all:!0,env:Z.env});C.stdin?.end();let v=ie(()=>{r?.({steps:g,duration:f})},250),R=(h,d)=>{let a={...h,id:T};T+=1,y.push(a),g.push(a),d||v.flush(),v(),d&&v.flush()},D=Br.createInterface({input:C.all});return D.on("error",h=>{U.error("Readline interface error",{error:h.message,stack:h.stack})}),D.on("line",h=>{let d=null;try{d=JSON.parse(h)}catch{U.log("Could not parse line",h)}d?.session_id&&d.session_id!==u&&(u=d.session_id),Array.isArray(d?.message?.content)?d.message.content.forEach(a=>{switch(a.type){case"text":{a.text&&R({message:a.text});break}case"image":{typeof a.source=="object"&&a.source&&a.source.type==="base64"&&a.source.media_type?R({message:`![](data:${a.source.media_type};base64,${a.source.data})`}):U.log(`Unsupported image type ${a.source?.type}`,a.source);break}case"tool_use":{if(a.name==="Task"){let E=a.input?.description&&`\`${a.input.description}\``;R({title:[Ut(a.name),E].filter(Boolean).join(" ")})}else a.id&&(w[a.id]=a);v.flush();break}case"tool_result":{let E=a.tool_use_id?w[a.tool_use_id]:void 0,J;if(E){let q=E.input?.file_path&&Mt.relative(Z.cwd(),E.input.file_path),P=q&&`\`${q}\``;J=[Ut(E.name||""),P].filter(Boolean).join(" ")}let _e=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(E?.name||""),X;if(typeof a.content=="string")X=a.content;else if(Array.isArray(a.content)){let q=[];a.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}`)}),X=q.join(`
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import{createRequire as sn}from"module";import{createTracerProvider as Jt}from"@
4
4
  ${l}
5
5
  </extracted_error_chunk>`).join(`
6
6
 
7
- `);return s.length>e.length*.8?e:s}import Se from"process";import{getTracer as Gr}from"@netlify/otel";import le from"process";var ye=le.env.NETLIFY_API_URL,_e=le.env.NETLIFY_API_TOKEN,j=_("api"),Ee=()=>le.env.NETLIFY_LOCAL_MODE==="true",ce=async(e,t={})=>{if(!ye||!_e)throw new Error("No API URL or token");let r=new URL(e,ye),n={...t,headers:{...t.headers,Authorization:`Bearer ${_e}`}};le.env.AGENT_RUNNERS_DEBUG==="true"&&(n.headers["x-nf-debug-logging"]="true"),t.json&&(n.headers||={},n.headers["Content-Type"]="application/json",n.body=JSON.stringify(t.json));let o=await fetch(r,n),s=o.ok&&o.status<=299;if(le.env.AGENT_RUNNERS_DEBUG==="true")j.log(`Response headers for ${r}:`),o.headers.forEach((c,i)=>{j.log(` ${i}: ${c}`)});else{let c=o.headers.get("x-request-id")||o.headers.get("x-nf-request-id");j.log(`Request ID for ${r}: ${c||"N/A"}`)}if(s||j.error(`Got status ${o.status} for request ${r}`),t.raw){if(!s)throw o;return o}let l=await(o.headers.get("content-type")?.includes("application/json")?o.json():o.text());if(!s)throw l;return l},ot=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&&(_e=e.constants.NETLIFY_API_TOKEN)},st=()=>({apiUrl:ye,token:_e}),ue=async(e,t)=>Ee()?(j.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):ce(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),B=async(e,t,r)=>Ee()?(j.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):ce(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var it=async(e,t)=>Ee()?(j.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):ce(`/api/v1/agent_runners/${e}/sessions/${t}`),at=(e,t,r)=>ce(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}}),lt=async(e,t)=>Ee()?(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"}}):ce(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),ke=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 ee=_("ai_gateway"),De=null;var ct=async()=>{if(De)return De;ee.log("Fetching available AI gateway providers");let e=await fetch(`${st().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,ee.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},tr=async(e,t)=>{let n=(await ct()).providers[e];if(!n)return ee.log(`Provider '${e}' not found`),!1;let o=n.models.includes(t);return ee.log(`Model validation for ${e}/${t}`,{isAvailable:o}),o},ut=async({netlify:e,config:t})=>{let r,n,o,s,l=e.constants?.SITE_ID;if(!l)throw new Error("No site id");let c=async()=>{clearTimeout(o),ee.log("Requesting AI gateway information");let i=await at(l,t.id,t.sessionId);if({token:r,url:s}=i,n=i.expires_at?i.expires_at*1e3:void 0,ee.log("Got AI gateway information",{token:!!r,expiresAt:n,url:s}),n){let m=n-Date.now()-6e4;m>0&&(o=setTimeout(()=>{c()},m))}};return await Promise.all([c(),ct()]),{get url(){return s},get token(){return r},isModelAvailableForProvider:tr}};import G from"process";import K from"path";import we from"fs";import{fileURLToPath as lr}from"url";import{createRequire as cr}from"module";import{execa as ur,execaCommand as Dn}from"execa";import{Transform as rr}from"stream";var nr=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"]),or=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function sr(){return Object.entries(process.env).filter(([e,t])=>!(!t||nr.has(e)||or.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function H(e){if(typeof e!="string")return e;let t=sr();if(t.length===0)return e;let r=e;return t.forEach(n=>{let o=new RegExp(ir(n),"g");r=r.replace(o,"******")}),r}function ir(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var te=class extends rr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,n){let o=t.toString(),s=H(o);n(null,s)}};function dt(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(n,o,s){let l=typeof n=="string"?H(n):n;return typeof o=="function"?t(l,o):t(l,o,s)},process.stderr.write=function(n,o,s){let l=typeof n=="string"?H(n):n;return typeof o=="function"?r(l,o):r(l,o,s)}}var de=null,pt=e=>(de&&de.destroy(),de=new X({totalAllowedTime:e}),de),ft=()=>de;var X=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,n)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let o=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),s=null,l=null;n!==void 0&&(l=new Promise((c,i)=>{s=setTimeout(()=>{i(new Error(`${t} stage exceeded its maximum duration of ${n}ms`))},n)}));try{return l?await Promise.race([r(),l]):await r()}finally{o(),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 gt={name:"@netlify/agent-runner-cli",type:"module",version:"1.57.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.51","@google/gemini-cli":"0.16.0","@netlify/otel":"^5.0.0","@openai/codex":"0.55.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.57.0",execa:"^8.0.0","get-port":"^5.1.1",minimist:"^1.2.8"}};var dr=lr(import.meta.url),pr=K.dirname(dr),fr=cr(import.meta.url),xe=_("shell"),Le=new Set,gr={preferLocal:!0},F=(e,t,r)=>{let[n,o]=mr(t,r),s={...gr,...o},l=ur(e,n,s);return hr(l,s),_r(l),l};var mr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},hr=(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 te).pipe(G.stdout),e.stdout?.pipe(new te).pipe(G.stdout),e.stderr?.pipe(new te).pipe(G.stderr);return}e.stdout?.pipe(G.stdout),e.stderr?.pipe(G.stderr)},mt=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(G.kill(-e.pid,t),xe.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return xe.error("Error killing process:",r),!1}},yr=e=>mt(e,"SIGKILL"),_r=e=>{Le.add(e);let t=ft();if(t){let r=t.onTimesUp(()=>{xe.log(`Global timer expired, killing process ${e.pid}`),mt(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(xe.log(`Force killing process ${e.pid} after timeout`),yr(e))},5e3)});e.on("exit",()=>{Le.delete(e),r()}),e.on("error",()=>{Le.delete(e),r()})}};function re(e,t){if(!G.env.NETLIFY_LOCAL_MODE)try{let o=fr.resolve(gt.name),s=K.dirname(o);for(;s!==K.dirname(s);){let l=K.dirname(s);if(K.basename(l)==="node_modules"){let c=K.join(l,".bin",t);if(we.existsSync(c))return c;break}s=l}}catch(o){console.error("Could not resolve package.json",o)}if(G.env.NODE_PATH){let o=K.join(G.env.NODE_PATH,".bin",t);if(we.existsSync(o))return o}let r=K.join(e,"node_modules",".bin",t);if(we.existsSync(r))return r;let n=K.join(pr,"..","node_modules",".bin",t);if(we.existsSync(n))return n}var ht="netlify-agent-runner-context.md",Ue="task-history",Me="netlify-context",D=".netlify",ne="results.md",je="assets";var Er=_("utils"),wr=e=>new Promise(t=>{setTimeout(t,e)}),yt=(e,t=3e3)=>{let r=!1,n=null,o=[],s=null,l=(...c)=>{if(r)return n=c,new Promise(p=>{o.push(p)});r=!0;let i,m=new Promise(p=>{i=p});return s=(async()=>{await Promise.resolve();let p=await e(...c);for(i(p);;){if(await wr(t),!n)return r=!1,s=null,p;let u=n,g=o;n=null,o=[],p=await e(...u),g.forEach(y=>{y(p)})}})(),m};return l.flush=async()=>{if((r||n)&&s)return await s,l.flush()},l},oe=(e,t,r=!1)=>{let n=null,o=null,s=null,l=function(...c){o=c,s=this;let i=r&&!n;clearTimeout(n),n=setTimeout(()=>{n=null,r||(e.apply(s,o),o=null,s=null)},t),i&&(e.apply(s,o),o=null,s=null)};return l.cancel=()=>{clearTimeout(n),n=null,o=null,s=null},l.flush=()=>{if(n){clearTimeout(n);let c=o,i=s;n=null,o=null,s=null,e.apply(i,c)}},l},_t=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(n){t&&(r?.error?r.error("Could not parse JSON",n):Er.error("Could not parse JSON",n))}},Et=(e,t)=>{let o=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let c=`--${t}${o}`;if(c.length>55)return"";let i=60-c.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 wt}from"buffer";import xr from"path";var xt=_("repo"),Tt=async({config:e})=>{xt.info("Getting runner diffs");let t=await Ir(),{hasChanges:r}=t,{status:n}=t;if(!r)return{hasChanges:!1};let o=vr(n);await Rr(o),xt.info("Changes after processing"),await Ye();let s=await Be(n);await Ge(s);let l={stdio:["ignore","pipe","pipe"]},i=(await F("git",["diff","--staged"],l)).stdout;if(r=!!i,!r)return{hasChanges:!1,ignored:s};let p=(await F("git",["diff","--staged","--binary"],l)).stdout,u,g;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await F("git",["commit","-m","Agent runner"]),u=(await F("git",["diff",e.sha,"HEAD"],l)).stdout;let f=(await F("git",["diff",e.sha,"HEAD","--binary"],l)).stdout;u!==f&&(g=wt.from(f).toString("base64"))}let y={hasChanges:!0,diff:i,resultDiff:u,ignored:s};return i!==p&&(y.diffBinary=wt.from(p).toString("base64")),g&&(y.resultDiffBinary=g),y},Ge=async(e=[])=>{await F("git",["add",".",...e])},Ye=async()=>(await F("git",["status","-s"])).stdout,It=/.. (.+)?\.log$/,Tr=[It],Ir=async()=>{let e=await Ye();return{hasChanges:(e.trim().length===0?[]:e.split(`
7
+ `);return s.length>e.length*.8?e:s}import Se from"process";import{getTracer as Gr}from"@netlify/otel";import le from"process";var ye=le.env.NETLIFY_API_URL,_e=le.env.NETLIFY_API_TOKEN,j=_("api"),Ee=()=>le.env.NETLIFY_LOCAL_MODE==="true",ce=async(e,t={})=>{if(!ye||!_e)throw new Error("No API URL or token");let r=new URL(e,ye),n={...t,headers:{...t.headers,Authorization:`Bearer ${_e}`}};le.env.AGENT_RUNNERS_DEBUG==="true"&&(n.headers["x-nf-debug-logging"]="true"),t.json&&(n.headers||={},n.headers["Content-Type"]="application/json",n.body=JSON.stringify(t.json));let o=await fetch(r,n),s=o.ok&&o.status<=299;if(le.env.AGENT_RUNNERS_DEBUG==="true")j.log(`Response headers for ${r}:`),o.headers.forEach((c,i)=>{j.log(` ${i}: ${c}`)});else{let c=o.headers.get("x-request-id")||o.headers.get("x-nf-request-id");j.log(`Request ID for ${r}: ${c||"N/A"}`)}if(s||j.error(`Got status ${o.status} for request ${r}`),t.raw){if(!s)throw o;return o}let l=await(o.headers.get("content-type")?.includes("application/json")?o.json():o.text());if(!s)throw l;return l},ot=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&&(_e=e.constants.NETLIFY_API_TOKEN)},st=()=>({apiUrl:ye,token:_e}),ue=async(e,t)=>Ee()?(j.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):ce(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),B=async(e,t,r)=>Ee()?(j.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):ce(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var it=async(e,t)=>Ee()?(j.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):ce(`/api/v1/agent_runners/${e}/sessions/${t}`),at=(e,t,r)=>ce(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}}),lt=async(e,t)=>Ee()?(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"}}):ce(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),ke=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 ee=_("ai_gateway"),De=null;var ct=async()=>{if(De)return De;ee.log("Fetching available AI gateway providers");let e=await fetch(`${st().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,ee.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},tr=async(e,t)=>{let n=(await ct()).providers[e];if(!n)return ee.log(`Provider '${e}' not found`),!1;let o=n.models.includes(t);return ee.log(`Model validation for ${e}/${t}`,{isAvailable:o}),o},ut=async({netlify:e,config:t})=>{let r,n,o,s,l=e.constants?.SITE_ID;if(!l)throw new Error("No site id");let c=async()=>{clearTimeout(o),ee.log("Requesting AI gateway information");let i=await at(l,t.id,t.sessionId);if({token:r,url:s}=i,n=i.expires_at?i.expires_at*1e3:void 0,ee.log("Got AI gateway information",{token:!!r,expiresAt:n,url:s}),n){let m=n-Date.now()-6e4;m>0&&(o=setTimeout(()=>{c()},m))}};return await Promise.all([c(),ct()]),{get url(){return s},get token(){return r},isModelAvailableForProvider:tr}};import G from"process";import K from"path";import we from"fs";import{fileURLToPath as lr}from"url";import{createRequire as cr}from"module";import{execa as ur,execaCommand as Dn}from"execa";import{Transform as rr}from"stream";var nr=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"]),or=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function sr(){return Object.entries(process.env).filter(([e,t])=>!(!t||nr.has(e)||or.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function H(e){if(typeof e!="string")return e;let t=sr();if(t.length===0)return e;let r=e;return t.forEach(n=>{let o=new RegExp(ir(n),"g");r=r.replace(o,"******")}),r}function ir(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var te=class extends rr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,n){let o=t.toString(),s=H(o);n(null,s)}};function dt(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(n,o,s){let l=typeof n=="string"?H(n):n;return typeof o=="function"?t(l,o):t(l,o,s)},process.stderr.write=function(n,o,s){let l=typeof n=="string"?H(n):n;return typeof o=="function"?r(l,o):r(l,o,s)}}var de=null,pt=e=>(de&&de.destroy(),de=new X({totalAllowedTime:e}),de),ft=()=>de;var X=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,n)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let o=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),s=null,l=null;n!==void 0&&(l=new Promise((c,i)=>{s=setTimeout(()=>{i(new Error(`${t} stage exceeded its maximum duration of ${n}ms`))},n)}));try{return l?await Promise.race([r(),l]):await r()}finally{o(),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 gt={name:"@netlify/agent-runner-cli",type:"module",version:"1.57.1",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.58","@google/gemini-cli":"0.19.1","@netlify/otel":"^5.0.1","@openai/codex":"0.65.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.57.0",execa:"^8.0.0","get-port":"^5.1.1",minimist:"^1.2.8"}};var dr=lr(import.meta.url),pr=K.dirname(dr),fr=cr(import.meta.url),xe=_("shell"),Le=new Set,gr={preferLocal:!0},F=(e,t,r)=>{let[n,o]=mr(t,r),s={...gr,...o},l=ur(e,n,s);return hr(l,s),_r(l),l};var mr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},hr=(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 te).pipe(G.stdout),e.stdout?.pipe(new te).pipe(G.stdout),e.stderr?.pipe(new te).pipe(G.stderr);return}e.stdout?.pipe(G.stdout),e.stderr?.pipe(G.stderr)},mt=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(G.kill(-e.pid,t),xe.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return xe.error("Error killing process:",r),!1}},yr=e=>mt(e,"SIGKILL"),_r=e=>{Le.add(e);let t=ft();if(t){let r=t.onTimesUp(()=>{xe.log(`Global timer expired, killing process ${e.pid}`),mt(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(xe.log(`Force killing process ${e.pid} after timeout`),yr(e))},5e3)});e.on("exit",()=>{Le.delete(e),r()}),e.on("error",()=>{Le.delete(e),r()})}};function re(e,t){if(!G.env.NETLIFY_LOCAL_MODE)try{let o=fr.resolve(gt.name),s=K.dirname(o);for(;s!==K.dirname(s);){let l=K.dirname(s);if(K.basename(l)==="node_modules"){let c=K.join(l,".bin",t);if(we.existsSync(c))return c;break}s=l}}catch(o){console.error("Could not resolve package.json",o)}if(G.env.NODE_PATH){let o=K.join(G.env.NODE_PATH,".bin",t);if(we.existsSync(o))return o}let r=K.join(e,"node_modules",".bin",t);if(we.existsSync(r))return r;let n=K.join(pr,"..","node_modules",".bin",t);if(we.existsSync(n))return n}var ht="netlify-agent-runner-context.md",Ue="task-history",Me="netlify-context",D=".netlify",ne="results.md",je="assets";var Er=_("utils"),wr=e=>new Promise(t=>{setTimeout(t,e)}),yt=(e,t=3e3)=>{let r=!1,n=null,o=[],s=null,l=(...c)=>{if(r)return n=c,new Promise(p=>{o.push(p)});r=!0;let i,m=new Promise(p=>{i=p});return s=(async()=>{await Promise.resolve();let p=await e(...c);for(i(p);;){if(await wr(t),!n)return r=!1,s=null,p;let u=n,g=o;n=null,o=[],p=await e(...u),g.forEach(y=>{y(p)})}})(),m};return l.flush=async()=>{if((r||n)&&s)return await s,l.flush()},l},oe=(e,t,r=!1)=>{let n=null,o=null,s=null,l=function(...c){o=c,s=this;let i=r&&!n;clearTimeout(n),n=setTimeout(()=>{n=null,r||(e.apply(s,o),o=null,s=null)},t),i&&(e.apply(s,o),o=null,s=null)};return l.cancel=()=>{clearTimeout(n),n=null,o=null,s=null},l.flush=()=>{if(n){clearTimeout(n);let c=o,i=s;n=null,o=null,s=null,e.apply(i,c)}},l},_t=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(n){t&&(r?.error?r.error("Could not parse JSON",n):Er.error("Could not parse JSON",n))}},Et=(e,t)=>{let o=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let c=`--${t}${o}`;if(c.length>55)return"";let i=60-c.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 wt}from"buffer";import xr from"path";var xt=_("repo"),Tt=async({config:e})=>{xt.info("Getting runner diffs");let t=await Ir(),{hasChanges:r}=t,{status:n}=t;if(!r)return{hasChanges:!1};let o=vr(n);await Rr(o),xt.info("Changes after processing"),await Ye();let s=await Be(n);await Ge(s);let l={stdio:["ignore","pipe","pipe"]},i=(await F("git",["diff","--staged"],l)).stdout;if(r=!!i,!r)return{hasChanges:!1,ignored:s};let p=(await F("git",["diff","--staged","--binary"],l)).stdout,u,g;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await F("git",["commit","-m","Agent runner"]),u=(await F("git",["diff",e.sha,"HEAD"],l)).stdout;let f=(await F("git",["diff",e.sha,"HEAD","--binary"],l)).stdout;u!==f&&(g=wt.from(f).toString("base64"))}let y={hasChanges:!0,diff:i,resultDiff:u,ignored:s};return i!==p&&(y.diffBinary=wt.from(p).toString("base64")),g&&(y.resultDiffBinary=g),y},Ge=async(e=[])=>{await F("git",["add",".",...e])},Ye=async()=>(await F("git",["status","-s"])).stdout,It=/.. (.+)?\.log$/,Tr=[It],Ir=async()=>{let e=await Ye();return{hasChanges:(e.trim().length===0?[]:e.split(`
8
8
  `).filter(n=>Tr.some(s=>s instanceof RegExp?s.test(n):n===s)?!1:n[1]?.trim()!=="")).length!==0,status:e}},vt=async()=>{let{stdout:e}=await F("git",["rev-parse","HEAD"]);return e.trim()},Rt=async()=>{let{stdout:e}=await F("git",["rev-list","--max-parents=0","HEAD"]);return e.trim()},Be=async e=>{e||=await Ye();let t=[".netlify","node_modules"],r=[];return e.split(`
9
9
  `).forEach(n=>{t.forEach(s=>{[`?? ${s}`,`?? ${s}${xr.sep}`].some(c=>n.startsWith(c))&&r.push(`:!${s}`)});let o=n.match(It)?.[1];o&&r.push(`:!${o}.log`)}),r},St=async()=>{await F("git",["reset","--hard","HEAD"])},vr=e=>{let t=e.split(`
10
10
  `).reduce((r,n)=>{if(!n)return r;let[o,s,,...l]=n,c=l.join(""),i=o.trim(),m=s.trim();return r[c]?r[c].change=m:r[c]={filePath:c,stage:i,change:m},r},{});return Object.values(t)},Rr=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 br from"fs/promises";import Ar from"os";import Nt from"path";import z from"process";import Nr from"readline";import He from"path";import Sr from"fs/promises";var Ke=_("agent-output-utils");async function se({initialResult:e,agentName:t,hasError:r}){let n="",o=He.join(process.cwd(),D,ne);try{let s=await Sr.readFile(o,"utf-8");s&&(n=s,Ke.log(`Pulled result from ${He.relative(process.cwd(),o)}`))}catch{Ke.log(`No results file found at ${He.relative(process.cwd(),o)}`)}return n||(!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,n=r?.replace(/\s+/g," ").trim().toLowerCase()||"",o="";return n?.includes("ai gateway is not available for your account")||n?.includes("ai gateway is not enabled for your account")?o="AI Gateway is currently not available on your account. Please confirm your account meets the criteria for using Agent Runners and AI Gateway and that your account has remaining AI Gateway inference credits available. Reach out to Netlify support if this is unexpected.":n?.includes("error when talking to gemini api")?o="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":(n?.includes("connection closed prematurely")||n?.includes("499")&&t.toLowerCase().includes("gemini"))&&(o=`The ${t} models were currently overloaded. Please try again or use a different available agent.`),n?.includes("request timed out")&&(o=`The ${t} API request's have timed out. Please try again or use a different available agent.`),n?.includes("network error")&&(o=`The ${t} agent is having network issues. Please try again or use a different available agent.`),o&&Ke.log(`Providing updated error messsage: ${o}, replacing original error: ${r}`),o||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 L=_("runner_claude"),bt="Claude Code",Te="claude-opus-4-5-20251101",At=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,Cr=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(L.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(L.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(L.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0}));async function We({config:e,netlify:t,persistSteps:r,aiGateway:n,continueSession:o,priorAgentSessionId:s}){let l=e,{accountType:c,prompt:i,modelVersionOverrides:m}=l,{model:p}=l,u="";if(n){let{token:h,url:d}=n;if(!h||!d)throw new Error("No token or url provided from AI Gateway");if(m?.claude){let a=m?.claude?.[c];if(a){if(!await n.isModelAvailableForProvider("anthropic",a))throw new Error(`Model override '${a}' is not available for anthropic provider`);p=a}}else if(p){if(!await n.isModelAvailableForProvider("anthropic",p))throw new Error(`Model '${p}' is not available for anthropic provider`)}else await n.isModelAvailableForProvider("anthropic",Te)?(p=Te,L.log(`Using default model: ${Te}`)):L.log(`Default model ${Te} is not available, proceeding without model specification`);z.env.ANTHROPIC_API_KEY=h,z.env.ANTHROPIC_BASE_URL=d}else if(!z.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let g=[],y=[],w={},x=0,f=0,I,T,A=[re(z.cwd(),"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...p?["--model",p]:[],...o?["--continue"]:[],...o&&s?["--resume",s]:[],"-p",i],N=`${z.env.NVM_BIN}/node`;L.log(`Running ${N} ${A.join(" ")}`);let C=t.utils.run(N,A,{all:!0,env:z.env});C.stdin?.end();let R=oe(()=>{r?.({steps:g,duration:f})},250),v=(h,d)=>{let a={...h,id:x};x+=1,y.push(a),g.push(a),d||R.flush(),R(),d&&R.flush()},$=Nr.createInterface({input:C.all});return $.on("error",h=>{L.error("Readline interface error",{error:h.message,stack:h.stack})}),$.on("line",h=>{let d=null;try{d=JSON.parse(h)}catch{L.log("Could not parse line",h)}d?.session_id&&d.session_id!==u&&(u=d.session_id),Array.isArray(d?.message?.content)?d.message.content.forEach(a=>{switch(a.type){case"text":{a.text&&v({message:a.text});break}case"image":{typeof a.source=="object"&&a.source&&a.source.type==="base64"&&a.source.media_type?v({message:`![](data:${a.source.media_type};base64,${a.source.data})`}):L.log(`Unsupported image type ${a.source?.type}`,a.source);break}case"tool_use":{if(a.name==="Task"){let E=a.input?.description&&`\`${a.input.description}\``;v({title:[At(a.name),E].filter(Boolean).join(" ")})}else a.id&&(w[a.id]=a);R.flush();break}case"tool_result":{let E=a.tool_use_id?w[a.tool_use_id]:void 0,V;if(E){let W=E.input?.file_path&&Nt.relative(z.cwd(),E.input.file_path),P=W&&`\`${W}\``;V=[At(E.name||""),P].filter(Boolean).join(" ")}let he=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(E?.name||""),J;if(typeof a.content=="string")J=a.content;else if(Array.isArray(a.content)){let W=[];a.content.forEach(P=>{P?.type==="text"&&typeof P.text=="string"?W.push(P.text):P?.type==="image"&&typeof P.source=="object"&&P.source?P.source.type==="base64"&&P.source.media_type?W.push(`![](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}`)}),J=W.join(`
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@netlify/agent-runner-cli",
3
3
  "type": "module",
4
- "version": "1.57.0",
4
+ "version": "1.57.1",
5
5
  "description": "CLI tool for running Netlify agents",
6
6
  "main": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
@@ -72,10 +72,10 @@
72
72
  "vitest": "^1.5.0"
73
73
  },
74
74
  "dependencies": {
75
- "@anthropic-ai/claude-code": "2.0.51",
76
- "@google/gemini-cli": "0.16.0",
77
- "@netlify/otel": "^5.0.0",
78
- "@openai/codex": "0.55.0",
75
+ "@anthropic-ai/claude-code": "2.0.58",
76
+ "@google/gemini-cli": "0.19.1",
77
+ "@netlify/otel": "^5.0.1",
78
+ "@openai/codex": "0.65.0",
79
79
  "@opentelemetry/exporter-trace-otlp-grpc": "^0.57.0",
80
80
  "execa": "^8.0.0",
81
81
  "get-port": "^5.1.1",