@netlify/agent-runner-cli 1.51.0 → 1.52.0-alpha

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