@netlify/agent-runner-cli 1.58.7-alpha → 1.59.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin-local.js +1 -1
- package/dist/bin.js +1 -1
- package/dist/index.js +1 -1
- package/package.json +2 -2
package/dist/bin-local.js
CHANGED
|
@@ -5,7 +5,7 @@ import C from"process";import cr from"path";import ur from"fs";import Sn from"mi
|
|
|
5
5
|
${s}
|
|
6
6
|
</extracted_error_chunk>`).join(`
|
|
7
7
|
|
|
8
|
-
`);return i.length>e.length*.8?e:i}import Fe from"process";import{getTracer as sn}from"@netlify/otel";import ye from"process";var Re=ye.env.NETLIFY_API_URL,Se=ye.env.NETLIFY_API_TOKEN,H=_("api"),be=()=>ye.env.NETLIFY_LOCAL_MODE==="true",_e=async(e,t={})=>{if(!Re||!Se)throw new Error("No API URL or token");let r=new URL(e,Re),o={...t,headers:{...t.headers,Authorization:`Bearer ${Se}`}};ye.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(ye.env.AGENT_RUNNERS_DEBUG==="true")H.log(`Response headers for ${r}:`),n.headers.forEach((c,l)=>{H.log(` ${l}: ${c}`)});else{let c=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");H.log(`Request ID for ${r}: ${c||"N/A"}`)}if(i||H.error(`Got status ${n.status} for request ${r}`),t.raw){if(!i)throw new Error(`API request failed: ${n.status} ${n.statusText}`);return n}let s=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!i){let c=typeof s=="string"?s:JSON.stringify(s);throw new Error(`API request failed: ${n.status} - ${c}`)}return s},ht=e=>{H.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Re=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Se=e.constants.NETLIFY_API_TOKEN)},yt=()=>({apiUrl:Re,token:Se}),Ee=async(e,t)=>be()?(H.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):_e(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),W=async(e,t,r)=>be()?(H.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):_e(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var _t=async(e,t)=>be()?(H.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):_e(`/api/v1/agent_runners/${e}/sessions/${t}`),Et=(e,t,r)=>_e(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}}),wt=async(e,t)=>be()?(H.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"}}):_e(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Ye=async(e,t)=>{H.log(`Uploading diff to S3: ${e.substring(0,50)}...`);let r=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"text/plain"}});if(!r.ok)throw new Error(`S3 upload failed with status ${r.status}`);return r};var oe=_("ai_gateway"),Be=null;var Tt=async()=>{if(Be)return Be;oe.log("Fetching available AI gateway providers");let e=await fetch(`${yt().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 Be=t,oe.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},_r=async(e,t)=>{let o=(await Tt()).providers[e];if(!o)return oe.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return oe.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},It=async({netlify:e,config:t})=>{let r,o,n,i,s=e.constants?.SITE_ID;if(!s)throw new Error("No site id");let c=async()=>{clearTimeout(n),oe.log("Requesting AI gateway information");let l=await Et(s,t.id,t.sessionId);if({token:r,url:i}=l,o=l.expires_at?l.expires_at*1e3:void 0,oe.log("Got AI gateway information",{token:!!r,expiresAt:o,url:i}),o){let p=o-Date.now()-6e4;p>0&&(n=setTimeout(()=>{c()},p))}};return await Promise.all([c(),Tt()]),{get url(){return i},get token(){return r},isModelAvailableForProvider:_r}};import q from"process";import V from"path";import Ae from"fs";import{fileURLToPath as Rr}from"url";import{createRequire as Sr}from"module";import{execa as br,execaCommand as no}from"execa";import{Transform as Er}from"stream";var wr=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_WITH_BUILD_ENABLED","NETLIFY_AGENT_RUNNER_CONTEXT","NETLIFY_AGENT_RUNNER_HAS_REPO","NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED","NETLIFY_AGENT_RUNNER_SHA","NETLIFY_TEAM_TYPE","AGENT_RUNNERS_DEBUG","NETLIFY_TEAM_ID","NETLIFY_AGENT_RUNNER_USER_ID","SITE_NAME"]),Tr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function Ir(){return Object.entries(process.env).filter(([e,t])=>!(!t||wr.has(e)||Tr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function J(e){if(typeof e!="string")return e;let t=Ir();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(xr(o),"g");r=r.replace(n,"******")}),r}function xr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ie=class extends Er{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),i=J(n);o(null,i)}};function xt(){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 s=typeof o=="string"?J(o):o;return typeof n=="function"?t(s,n):t(s,n,i)},process.stderr.write=function(o,n,i){let s=typeof o=="string"?J(o):o;return typeof n=="function"?r(s,n):r(s,n,i)}}var we=null,vt=e=>(we&&we.destroy(),we=new ee({totalAllowedTime:e}),we),Rt=()=>we;var ee=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,s=null;o!==void 0&&(s=new Promise((c,l)=>{i=setTimeout(()=>{l(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return s?await Promise.race([r(),s]):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 St="netlify-agent-runner-context.md",He="task-history",qe="netlify-context",U=".netlify",se="results.md",Ke="assets";var te=600*1e3;var bt={name:"@netlify/agent-runner-cli",type:"module",version:"1.58.7-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":"LOG=0 vitest --exclude '**/integration/**'","test:ci:vitest":"LOG=0 c8 -r lcovonly -r text -r json vitest --exclude '**/integration/**'","test:integration":"vitest run test/integration/","test:integration:codex":"vitest run test/integration/codex.test.ts","test:integration:claude":"vitest run test/integration/claude.test.ts","test:integration:gemini":"vitest run test/integration/gemini.test.ts",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":"^20.0.0","@commitlint/config-conventional":"^20.0.0","@eslint/compat":"^2.0.0","@eslint/js":"^9.35.0","@netlify/eslint-config-node":"^7.0.1","@types/node":"^24.5.0","@typescript-eslint/eslint-plugin":"^8.0.0","@typescript-eslint/parser":"^8.0.0","@vitest/eslint-plugin":"^1.6.6",c8:"^10.0.0","eslint-config-prettier":"^10.1.8","eslint-plugin-n":"^17.0.0",husky:"^9.0.0","patch-package":"^8.0.0",tsup:"^8.5.0",typescript:"^5.0.0","typescript-eslint":"^8.44.0",vitest:"^4.0.16"},dependencies:{"@anthropic-ai/claude-code":"2.0.76","@google/gemini-cli":"0.23.0","@netlify/otel":"^5.1.1","@openai/codex":"0.77.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.208.0",execa:"^9.6.1",minimist:"^1.2.8"}};var Ar=Rr(import.meta.url),Nr=V.dirname(Ar),Cr=Sr(import.meta.url),ae=_("shell"),We=new Set,Pr={preferLocal:!0},N=(e,t,r)=>{let[o,n]=Or(t,r),i={...Pr,...n},s=br(e,o,i);Fr(s,i),kr(s);let c=r?.idleTimeout;return c&&c>0&&$r(s,c),s};var Or=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Fr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(q.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new ie).pipe(q.stdout),e.stdout?.pipe(new ie).pipe(q.stdout),e.stderr?.pipe(new ie).pipe(q.stderr);return}e.stdout?.pipe(q.stdout),e.stderr?.pipe(q.stderr)},Je=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(q.kill(-e.pid,t),ae.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return ae.error("Error killing process:",r),!1}},At=e=>Je(e,"SIGKILL"),$r=(e,t)=>{let r=null,o=()=>{ae.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),Je(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ae.log(`Force killing idle process ${e.pid}`),At(e))},5e3)},n=()=>{r&&clearTimeout(r),r=setTimeout(o,t)};n(),e.stdout?.on("data",n),e.stderr?.on("data",n);let i=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",i),e.on("error",i)},kr=e=>{We.add(e);let t=Rt();if(t){let r=t.onTimesUp(()=>{ae.log(`Global timer expired, killing process ${e.pid}`),Je(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ae.log(`Force killing process ${e.pid} after timeout`),At(e))},5e3)});e.on("exit",()=>{We.delete(e),r()}),e.on("error",()=>{We.delete(e),r()})}};function Ne(e,t){return!!re(e,t)}function re(e,t){if(!q.env.NETLIFY_LOCAL_MODE)try{let n=Cr.resolve(bt.name),i=V.dirname(n);for(;i!==V.dirname(i);){let s=V.dirname(i);if(V.basename(s)==="node_modules"){let c=V.join(s,".bin",t);if(Ae.existsSync(c))return c;break}i=s}}catch(n){console.error("Could not resolve package.json",n)}if(q.env.NODE_PATH){let n=V.join(q.env.NODE_PATH,".bin",t);if(Ae.existsSync(n))return n}let r=V.join(e,"node_modules",".bin",t);if(Ae.existsSync(r))return r;let o=V.join(Nr,"..","node_modules",".bin",t);if(Ae.existsSync(o))return o}var Dr=_("utils"),Lr=e=>new Promise(t=>{setTimeout(t,e)}),Nt=(e,t=3e3)=>{let r=!1,o=null,n=[],i=null,s=(...c)=>{if(r)return o=c,new Promise(f=>{n.push(f)});r=!0;let l,p=new Promise(f=>{l=f});return i=(async()=>{await Promise.resolve();let f=await e(...c);for(l(f);;){if(await Lr(t),!o)return r=!1,i=null,f;let u=o,m=n;o=null,n=[],f=await e(...u),m.forEach(y=>{y(f)})}})(),p};return s.flush=async()=>{if((r||o)&&i)return await i,s.flush()},s},le=(e,t,r=!1)=>{let o=null,n=null,i=null,s=function(...c){n=c,i=this;let l=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(i,n),n=null,i=null)},t),l&&(e.apply(i,n),n=null,i=null)};return s.cancel=()=>{clearTimeout(o),o=null,n=null,i=null},s.flush=()=>{if(o){clearTimeout(o);let c=n,l=i;o=null,n=null,i=null,e.apply(l,c)}},s},Ct=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):Dr.error("Could not parse JSON",o))}},Pt=(e,t)=>{let n=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let c=`--${t}${n}`;if(c.length>55)return"";let l=60-c.length;if(l<=0)return"";if(l>=i.length+6){let p=Math.min(l-i.length,e.length);return`${i}${e.slice(0,p)}`}return e.slice(0,l)};var Ur=50*1024,Ve=(e,t=Ur)=>{if(!e||typeof e!="string"||e.length<=t)return e;let o=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+o};import{Buffer as Ot}from"buffer";import Mr from"path";var Ft=_("repo"),$t=async({config:e,isRetry:t})=>{Ft.info("Getting runner diffs");let r=await Gr(),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};if(!t){let I=Yr(n);await Br(I)}Ft.info("Changes after processing"),await ze();let i=await Ze(n);await Xe(i);let s={stdio:["ignore","pipe","pipe"]},c=await N("git",["diff","--staged"],s),l=String(c.stdout??"");if(o=!!l,!o)return{hasChanges:!1,ignored:i};let p=await N("git",["diff","--staged","--binary"],s),f=String(p.stdout??""),u,m;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await N("git",["commit","-m","Agent runner"]);let I=await N("git",["diff",e.sha,"HEAD"],s);u=String(I.stdout??"");let w=await N("git",["diff",e.sha,"HEAD","--binary"],s),g=String(w.stdout??"");u!==g&&(m=Ot.from(g).toString("base64"))}let y={hasChanges:!0,diff:l,resultDiff:u,ignored:i};return l!==f&&(y.diffBinary=Ot.from(f).toString("base64")),m&&(y.resultDiffBinary=m),y},Xe=async(e=[])=>{await N("git",["add",".",...e])},ze=async()=>{let e=await N("git",["status","-s"]);return String(e.stdout??"")},kt=/.. (.+)?\.log$/,jr=[kt],Gr=async()=>{let e=await ze();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
8
|
+
`);return i.length>e.length*.8?e:i}import Fe from"process";import{getTracer as sn}from"@netlify/otel";import ye from"process";var Re=ye.env.NETLIFY_API_URL,Se=ye.env.NETLIFY_API_TOKEN,H=_("api"),be=()=>ye.env.NETLIFY_LOCAL_MODE==="true",_e=async(e,t={})=>{if(!Re||!Se)throw new Error("No API URL or token");let r=new URL(e,Re),o={...t,headers:{...t.headers,Authorization:`Bearer ${Se}`}};ye.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(ye.env.AGENT_RUNNERS_DEBUG==="true")H.log(`Response headers for ${r}:`),n.headers.forEach((c,l)=>{H.log(` ${l}: ${c}`)});else{let c=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");H.log(`Request ID for ${r}: ${c||"N/A"}`)}if(i||H.error(`Got status ${n.status} for request ${r}`),t.raw){if(!i)throw new Error(`API request failed: ${n.status} ${n.statusText}`);return n}let s=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!i){let c=typeof s=="string"?s:JSON.stringify(s);throw new Error(`API request failed: ${n.status} - ${c}`)}return s},ht=e=>{H.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Re=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Se=e.constants.NETLIFY_API_TOKEN)},yt=()=>({apiUrl:Re,token:Se}),Ee=async(e,t)=>be()?(H.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):_e(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),W=async(e,t,r)=>be()?(H.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):_e(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var _t=async(e,t)=>be()?(H.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):_e(`/api/v1/agent_runners/${e}/sessions/${t}`),Et=(e,t,r)=>_e(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}}),wt=async(e,t)=>be()?(H.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"}}):_e(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Ye=async(e,t)=>{H.log(`Uploading diff to S3: ${e.substring(0,50)}...`);let r=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"text/plain"}});if(!r.ok)throw new Error(`S3 upload failed with status ${r.status}`);return r};var oe=_("ai_gateway"),Be=null;var Tt=async()=>{if(Be)return Be;oe.log("Fetching available AI gateway providers");let e=await fetch(`${yt().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 Be=t,oe.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},_r=async(e,t)=>{let o=(await Tt()).providers[e];if(!o)return oe.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return oe.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},It=async({netlify:e,config:t})=>{let r,o,n,i,s=e.constants?.SITE_ID;if(!s)throw new Error("No site id");let c=async()=>{clearTimeout(n),oe.log("Requesting AI gateway information");let l=await Et(s,t.id,t.sessionId);if({token:r,url:i}=l,o=l.expires_at?l.expires_at*1e3:void 0,oe.log("Got AI gateway information",{token:!!r,expiresAt:o,url:i}),o){let p=o-Date.now()-6e4;p>0&&(n=setTimeout(()=>{c()},p))}};return await Promise.all([c(),Tt()]),{get url(){return i},get token(){return r},isModelAvailableForProvider:_r}};import q from"process";import V from"path";import Ae from"fs";import{fileURLToPath as Rr}from"url";import{createRequire as Sr}from"module";import{execa as br,execaCommand as no}from"execa";import{Transform as Er}from"stream";var wr=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_WITH_BUILD_ENABLED","NETLIFY_AGENT_RUNNER_CONTEXT","NETLIFY_AGENT_RUNNER_HAS_REPO","NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED","NETLIFY_AGENT_RUNNER_SHA","NETLIFY_TEAM_TYPE","AGENT_RUNNERS_DEBUG","NETLIFY_TEAM_ID","NETLIFY_AGENT_RUNNER_USER_ID","SITE_NAME"]),Tr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function Ir(){return Object.entries(process.env).filter(([e,t])=>!(!t||wr.has(e)||Tr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function J(e){if(typeof e!="string")return e;let t=Ir();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(xr(o),"g");r=r.replace(n,"******")}),r}function xr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ie=class extends Er{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),i=J(n);o(null,i)}};function xt(){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 s=typeof o=="string"?J(o):o;return typeof n=="function"?t(s,n):t(s,n,i)},process.stderr.write=function(o,n,i){let s=typeof o=="string"?J(o):o;return typeof n=="function"?r(s,n):r(s,n,i)}}var we=null,vt=e=>(we&&we.destroy(),we=new ee({totalAllowedTime:e}),we),Rt=()=>we;var ee=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,s=null;o!==void 0&&(s=new Promise((c,l)=>{i=setTimeout(()=>{l(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return s?await Promise.race([r(),s]):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 St="netlify-agent-runner-context.md",He="task-history",qe="netlify-context",U=".netlify",se="results.md",Ke="assets";var te=1800*1e3;var bt={name:"@netlify/agent-runner-cli",type:"module",version:"1.59.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":"LOG=0 vitest --exclude '**/integration/**'","test:ci:vitest":"LOG=0 c8 -r lcovonly -r text -r json vitest --exclude '**/integration/**'","test:integration":"vitest run test/integration/","test:integration:codex":"vitest run test/integration/codex.test.ts","test:integration:claude":"vitest run test/integration/claude.test.ts","test:integration:gemini":"vitest run test/integration/gemini.test.ts",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":"^20.0.0","@commitlint/config-conventional":"^20.0.0","@eslint/compat":"^2.0.0","@eslint/js":"^9.35.0","@netlify/eslint-config-node":"^7.0.1","@types/node":"^24.5.0","@typescript-eslint/eslint-plugin":"^8.0.0","@typescript-eslint/parser":"^8.0.0","@vitest/eslint-plugin":"^1.6.6",c8:"^10.0.0","eslint-config-prettier":"^10.1.8","eslint-plugin-n":"^17.0.0",husky:"^9.0.0","patch-package":"^8.0.0",tsup:"^8.5.0",typescript:"^5.0.0","typescript-eslint":"^8.44.0",vitest:"^4.0.16"},dependencies:{"@anthropic-ai/claude-code":"2.0.76","@google/gemini-cli":"0.23.0","@netlify/otel":"^5.1.1","@openai/codex":"0.79.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.208.0",execa:"^9.6.1",minimist:"^1.2.8"}};var Ar=Rr(import.meta.url),Nr=V.dirname(Ar),Cr=Sr(import.meta.url),ae=_("shell"),We=new Set,Pr={preferLocal:!0},N=(e,t,r)=>{let[o,n]=Or(t,r),i={...Pr,...n},s=br(e,o,i);Fr(s,i),kr(s);let c=r?.idleTimeout;return c&&c>0&&$r(s,c),s};var Or=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Fr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(q.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new ie).pipe(q.stdout),e.stdout?.pipe(new ie).pipe(q.stdout),e.stderr?.pipe(new ie).pipe(q.stderr);return}e.stdout?.pipe(q.stdout),e.stderr?.pipe(q.stderr)},Je=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(q.kill(-e.pid,t),ae.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return ae.error("Error killing process:",r),!1}},At=e=>Je(e,"SIGKILL"),$r=(e,t)=>{let r=null,o=()=>{ae.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),Je(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ae.log(`Force killing idle process ${e.pid}`),At(e))},5e3)},n=()=>{r&&clearTimeout(r),r=setTimeout(o,t)};n(),e.stdout?.on("data",n),e.stderr?.on("data",n);let i=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",i),e.on("error",i)},kr=e=>{We.add(e);let t=Rt();if(t){let r=t.onTimesUp(()=>{ae.log(`Global timer expired, killing process ${e.pid}`),Je(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ae.log(`Force killing process ${e.pid} after timeout`),At(e))},5e3)});e.on("exit",()=>{We.delete(e),r()}),e.on("error",()=>{We.delete(e),r()})}};function Ne(e,t){return!!re(e,t)}function re(e,t){if(!q.env.NETLIFY_LOCAL_MODE)try{let n=Cr.resolve(bt.name),i=V.dirname(n);for(;i!==V.dirname(i);){let s=V.dirname(i);if(V.basename(s)==="node_modules"){let c=V.join(s,".bin",t);if(Ae.existsSync(c))return c;break}i=s}}catch(n){console.error("Could not resolve package.json",n)}if(q.env.NODE_PATH){let n=V.join(q.env.NODE_PATH,".bin",t);if(Ae.existsSync(n))return n}let r=V.join(e,"node_modules",".bin",t);if(Ae.existsSync(r))return r;let o=V.join(Nr,"..","node_modules",".bin",t);if(Ae.existsSync(o))return o}var Dr=_("utils"),Lr=e=>new Promise(t=>{setTimeout(t,e)}),Nt=(e,t=3e3)=>{let r=!1,o=null,n=[],i=null,s=(...c)=>{if(r)return o=c,new Promise(f=>{n.push(f)});r=!0;let l,p=new Promise(f=>{l=f});return i=(async()=>{await Promise.resolve();let f=await e(...c);for(l(f);;){if(await Lr(t),!o)return r=!1,i=null,f;let u=o,m=n;o=null,n=[],f=await e(...u),m.forEach(y=>{y(f)})}})(),p};return s.flush=async()=>{if((r||o)&&i)return await i,s.flush()},s},le=(e,t,r=!1)=>{let o=null,n=null,i=null,s=function(...c){n=c,i=this;let l=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(i,n),n=null,i=null)},t),l&&(e.apply(i,n),n=null,i=null)};return s.cancel=()=>{clearTimeout(o),o=null,n=null,i=null},s.flush=()=>{if(o){clearTimeout(o);let c=n,l=i;o=null,n=null,i=null,e.apply(l,c)}},s},Ct=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):Dr.error("Could not parse JSON",o))}},Pt=(e,t)=>{let n=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let c=`--${t}${n}`;if(c.length>55)return"";let l=60-c.length;if(l<=0)return"";if(l>=i.length+6){let p=Math.min(l-i.length,e.length);return`${i}${e.slice(0,p)}`}return e.slice(0,l)};var Ur=50*1024,Ve=(e,t=Ur)=>{if(!e||typeof e!="string"||e.length<=t)return e;let o=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+o};import{Buffer as Ot}from"buffer";import Mr from"path";var Ft=_("repo"),$t=async({config:e,isRetry:t})=>{Ft.info("Getting runner diffs");let r=await Gr(),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};if(!t){let I=Yr(n);await Br(I)}Ft.info("Changes after processing"),await ze();let i=await Ze(n);await Xe(i);let s={stdio:["ignore","pipe","pipe"]},c=await N("git",["diff","--staged"],s),l=String(c.stdout??"");if(o=!!l,!o)return{hasChanges:!1,ignored:i};let p=await N("git",["diff","--staged","--binary"],s),f=String(p.stdout??""),u,m;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await N("git",["commit","-m","Agent runner"]);let I=await N("git",["diff",e.sha,"HEAD"],s);u=String(I.stdout??"");let w=await N("git",["diff",e.sha,"HEAD","--binary"],s),g=String(w.stdout??"");u!==g&&(m=Ot.from(g).toString("base64"))}let y={hasChanges:!0,diff:l,resultDiff:u,ignored:i};return l!==f&&(y.diffBinary=Ot.from(f).toString("base64")),m&&(y.resultDiffBinary=m),y},Xe=async(e=[])=>{await N("git",["add",".",...e])},ze=async()=>{let e=await N("git",["status","-s"]);return String(e.stdout??"")},kt=/.. (.+)?\.log$/,jr=[kt],Gr=async()=>{let e=await ze();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
9
9
|
`).filter(o=>jr.some(i=>i instanceof RegExp?i.test(o):o===i)?!1:o[1]?.trim()!=="")).length!==0,status:e}},Dt=async()=>{let{stdout:e}=await N("git",["rev-parse","HEAD"]);return String(e??"").trim()},Lt=async()=>{let{stdout:e}=await N("git",["rev-list","--max-parents=0","HEAD"]);return String(e??"").trim()},Ze=async e=>{e||=await ze();let t=[".netlify","node_modules","dist"],r=[];return e.split(`
|
|
10
10
|
`).forEach(o=>{t.forEach(i=>{[`?? ${i}`,`?? ${i}${Mr.sep}`].some(c=>o.startsWith(c))&&r.push(`:!${i}`)});let n=o.match(kt)?.[1];n&&r.push(`:!${n}.log`)}),r},Ut=async()=>{await N("git",["reset","--hard","HEAD"])},Yr=e=>{let t=e.split(`
|
|
11
11
|
`).reduce((r,o)=>{if(!o)return r;let[n,i,,...s]=o,c=s.join(""),l=n.trim(),p=i.trim();return r[c]?r[c].change=p:r[c]={filePath:c,stage:l,change:p},r},{});return Object.values(t)},Br=async e=>{let t=[];for(let r of e)r.stage&&!r.change&&t.push(N("git",["restore","--staged","--worktree",r.filePath]));await Promise.allSettled(t)};import qr from"fs/promises";import Kr from"os";import Gt from"path";import pe from"process";import Wr from"readline";import Qe from"path";import Hr from"fs/promises";var et=_("agent-output-utils");async function ce({initialResult:e,agentName:t,hasError:r}){let o="",n=Qe.join(process.cwd(),U,se);try{let i=await Hr.readFile(n,"utf-8");i&&(o=i,et.log(`Pulled result from ${Qe.relative(process.cwd(),n)}`))}catch{et.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 ue({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&&et.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function de(e){if(!e)return!1;let r=(e&&typeof e=="object"?JSON.stringify(e):e)?.replace(/\s+/g," ").trim().toLowerCase()||"";return!!(r?.includes("error when talking to gemini api")||r?.includes("499")||r?.includes("connection closed prematurely")||r?.includes("request timed out")||r?.includes("network error"))}var M=_("runner_claude"),Mt="Claude Code",fe="claude-opus-4-5-20251101",jt=e=>({Task:"Task",Bash:"Run command",Glob:"Find files",Grep:"Search files",LS:"List directory",ExitPlanMode:"Exit planning",Read:"Read file",Edit:"Edit file",MultiEdit:"Edit multiple files",Write:"Coding",NotebookEdit:"Edit notebook",WebFetch:"Fetch webpage",TodoWrite:"Update task list",WebSearch:"Search web",BashOutput:"Get command output",KillBash:"Stop command"})[e]||e,Jr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(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 tt({config:e,netlify:t,persistSteps:r,aiGateway:o,continueSession:n,priorAgentSessionId:i,cwd:s=pe.cwd()}){let c=e,{accountType:l,prompt:p,modelVersionOverrides:f}=c,{model:u}=c,m="";if(o){let{token:h,url:d}=o;if(!h||!d)throw new Error("No token or url provided from AI Gateway");if(f?.claude){let a=f?.claude?.[l];if(a){if(!await o.isModelAvailableForProvider("anthropic",a))throw new Error(`Model override '${a}' is not available for anthropic provider`);u=a}}else if(u){if(!await o.isModelAvailableForProvider("anthropic",u))throw new Error(`Model '${u}' is not available for anthropic provider`)}else!!fe&&await o.isModelAvailableForProvider("anthropic",fe)?(u=fe,M.log(`Using default model: ${fe}`)):fe&&M.log(`Default model ${fe} is not available, proceeding without model specification`);pe.env.ANTHROPIC_API_KEY=h,pe.env.ANTHROPIC_BASE_URL=d}else if(!pe.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let y=[],I=[],w={},g=0,T=0,R,S,P=[re(s,"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...u?["--model",u]:[],...n?["--continue"]:[],...n&&i?["--resume",i]:[],"-p",p],O=`${pe.env.NVM_BIN}/node`;M.log(`Running ${O} ${P.join(" ")}`);let k=t.utils.run(O,P,{all:!0,env:pe.env,cwd:s,idleTimeout:te});k.stdin?.end();let x=le(()=>{r?.({steps:y,duration:T})},250),v=(h,d)=>{let a={...h,id:g};g+=1,I.push(a),y.push(a),d||x.flush(),x(),d&&x.flush()},G=Wr.createInterface({input:k.all});return G.on("error",h=>{M.error("Readline interface error",{error:h.message,stack:h.stack})}),G.on("line",h=>{let d=null;try{d=JSON.parse(h)}catch{M.log("Could not parse line",h)}d?.session_id&&d.session_id!==m&&(m=d.session_id),Array.isArray(d?.message?.content)?d.message.content.forEach(a=>{switch(a.type){case"text":{a.text&&v({message:a.text});break}case"image":{typeof a.source=="object"&&a.source&&a.source.type==="base64"&&a.source.media_type?v({message:``}):M.log(`Unsupported image type ${a.source?.type}`,a.source);break}case"tool_use":{if(a.name==="Task"){let E=a.input?.description&&`\`${a.input.description}\``;v({title:[jt(a.name),E].filter(Boolean).join(" ")})}else a.id&&(w[a.id]=a);x.flush();break}case"tool_result":{let E=a.tool_use_id?w[a.tool_use_id]:void 0,Z;if(E){let X=E.input?.file_path&&Gt.relative(s,E.input.file_path),F=X&&`\`${X}\``;Z=[jt(E.name||""),F].filter(Boolean).join(" ")}let ve=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(E?.name||""),Q;if(typeof a.content=="string")Q=a.content;else if(Array.isArray(a.content)){let X=[];a.content.forEach(F=>{F?.type==="text"&&typeof F.text=="string"?X.push(F.text):F?.type==="image"&&typeof F.source=="object"&&F.source?F.source.type==="base64"&&F.source.media_type?X.push(``):M.log(`Unsupported image type ${F.source.type}`,F.source):M.log(`Unsupported block type ${F?.type}`)}),Q=X.join(`
|
package/dist/bin.js
CHANGED
|
@@ -5,7 +5,7 @@ import dt from"process";import Dn from"minimist";import{createRequire as An}from
|
|
|
5
5
|
${s}
|
|
6
6
|
</extracted_error_chunk>`).join(`
|
|
7
7
|
|
|
8
|
-
`);return i.length>e.length*.8?e:i}import Oe from"process";import{getTracer as un}from"@netlify/otel";import he from"process";var Re=he.env.NETLIFY_API_URL,ve=he.env.NETLIFY_API_TOKEN,B=_("api"),Ne=()=>he.env.NETLIFY_LOCAL_MODE==="true",ye=async(e,t={})=>{if(!Re||!ve)throw new Error("No API URL or token");let r=new URL(e,Re),o={...t,headers:{...t.headers,Authorization:`Bearer ${ve}`}};he.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(he.env.AGENT_RUNNERS_DEBUG==="true")B.log(`Response headers for ${r}:`),n.headers.forEach((c,l)=>{B.log(` ${l}: ${c}`)});else{let c=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");B.log(`Request ID for ${r}: ${c||"N/A"}`)}if(i||B.error(`Got status ${n.status} for request ${r}`),t.raw){if(!i)throw new Error(`API request failed: ${n.status} ${n.statusText}`);return n}let s=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!i){let c=typeof s=="string"?s:JSON.stringify(s);throw new Error(`API request failed: ${n.status} - ${c}`)}return s},_t=e=>{B.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Re=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(ve=e.constants.NETLIFY_API_TOKEN)},Et=()=>({apiUrl:Re,token:ve}),_e=async(e,t)=>Ne()?(B.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):ye(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),q=async(e,t,r)=>Ne()?(B.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):ye(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var Tt=async(e,t)=>Ne()?(B.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):ye(`/api/v1/agent_runners/${e}/sessions/${t}`),wt=(e,t,r)=>ye(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}}),It=async(e,t)=>Ne()?(B.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"}}):ye(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),je=async(e,t)=>{B.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=_("ai_gateway"),Ye=null;var xt=async()=>{if(Ye)return Ye;te.log("Fetching available AI gateway providers");let e=await fetch(`${Et().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 Ye=t,te.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},Ir=async(e,t)=>{let o=(await xt()).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},Rt=async({netlify:e,config:t})=>{let r,o,n,i,s=e.constants?.SITE_ID;if(!s)throw new Error("No site id");let c=async()=>{clearTimeout(n),te.log("Requesting AI gateway information");let l=await wt(s,t.id,t.sessionId);if({token:r,url:i}=l,o=l.expires_at?l.expires_at*1e3:void 0,te.log("Got AI gateway information",{token:!!r,expiresAt:o,url:i}),o){let d=o-Date.now()-6e4;d>0&&(n=setTimeout(()=>{c()},d))}};return await Promise.all([c(),xt()]),{get url(){return i},get token(){return r},isModelAvailableForProvider:Ir}};import H from"process";import K from"path";import Ae from"fs";import{fileURLToPath as br}from"url";import{createRequire as Cr}from"module";import{execa as Pr,execaCommand as po}from"execa";import{Transform as xr}from"stream";var Rr=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_WITH_BUILD_ENABLED","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"]),vr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function Nr(){return Object.entries(process.env).filter(([e,t])=>!(!t||Rr.has(e)||vr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function W(e){if(typeof e!="string")return e;let t=Nr();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(Ar(o),"g");r=r.replace(n,"******")}),r}function Ar(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var re=class extends xr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),i=W(n);o(null,i)}};function vt(){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 s=typeof o=="string"?W(o):o;return typeof n=="function"?t(s,n):t(s,n,i)},process.stderr.write=function(o,n,i){let s=typeof o=="string"?W(o):o;return typeof n=="function"?r(s,n):r(s,n,i)}}var Ee=null,Nt=e=>(Ee&&Ee.destroy(),Ee=new Z({totalAllowedTime:e}),Ee),At=()=>Ee;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,s=null;o!==void 0&&(s=new Promise((c,l)=>{i=setTimeout(()=>{l(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return s?await Promise.race([r(),s]):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 St="netlify-agent-runner-context.md",Be="task-history",He="netlify-context",$=".netlify",ne="results.md",qe="assets",We="other",Ke="personal";var Ve="enterprise",Je="free",bt=[Ke,"pro",Ve,Je],Q=600*1e3;var Ct={name:"@netlify/agent-runner-cli",type:"module",version:"1.58.7-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":"LOG=0 vitest --exclude '**/integration/**'","test:ci:vitest":"LOG=0 c8 -r lcovonly -r text -r json vitest --exclude '**/integration/**'","test:integration":"vitest run test/integration/","test:integration:codex":"vitest run test/integration/codex.test.ts","test:integration:claude":"vitest run test/integration/claude.test.ts","test:integration:gemini":"vitest run test/integration/gemini.test.ts",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":"^20.0.0","@commitlint/config-conventional":"^20.0.0","@eslint/compat":"^2.0.0","@eslint/js":"^9.35.0","@netlify/eslint-config-node":"^7.0.1","@types/node":"^24.5.0","@typescript-eslint/eslint-plugin":"^8.0.0","@typescript-eslint/parser":"^8.0.0","@vitest/eslint-plugin":"^1.6.6",c8:"^10.0.0","eslint-config-prettier":"^10.1.8","eslint-plugin-n":"^17.0.0",husky:"^9.0.0","patch-package":"^8.0.0",tsup:"^8.5.0",typescript:"^5.0.0","typescript-eslint":"^8.44.0",vitest:"^4.0.16"},dependencies:{"@anthropic-ai/claude-code":"2.0.76","@google/gemini-cli":"0.23.0","@netlify/otel":"^5.1.1","@openai/codex":"0.77.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.208.0",execa:"^9.6.1",minimist:"^1.2.8"}};var Or=br(import.meta.url),Fr=K.dirname(Or),Lr=Cr(import.meta.url),oe=_("shell"),Xe=new Set,Dr={preferLocal:!0},F=(e,t,r)=>{let[o,n]=$r(t,r),i={...Dr,...n},s=Pr(e,o,i);kr(s,i),Mr(s);let c=r?.idleTimeout;return c&&c>0&&Ur(s,c),s};var $r=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},kr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(H.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new re).pipe(H.stdout),e.stdout?.pipe(new re).pipe(H.stdout),e.stderr?.pipe(new re).pipe(H.stderr);return}e.stdout?.pipe(H.stdout),e.stderr?.pipe(H.stderr)},ze=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(H.kill(-e.pid,t),oe.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return oe.error("Error killing process:",r),!1}},Pt=e=>ze(e,"SIGKILL"),Ur=(e,t)=>{let r=null,o=()=>{oe.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),ze(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(oe.log(`Force killing idle process ${e.pid}`),Pt(e))},5e3)},n=()=>{r&&clearTimeout(r),r=setTimeout(o,t)};n(),e.stdout?.on("data",n),e.stderr?.on("data",n);let i=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",i),e.on("error",i)},Mr=e=>{Xe.add(e);let t=At();if(t){let r=t.onTimesUp(()=>{oe.log(`Global timer expired, killing process ${e.pid}`),ze(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(oe.log(`Force killing process ${e.pid} after timeout`),Pt(e))},5e3)});e.on("exit",()=>{Xe.delete(e),r()}),e.on("error",()=>{Xe.delete(e),r()})}};function ie(e,t){if(!H.env.NETLIFY_LOCAL_MODE)try{let n=Lr.resolve(Ct.name),i=K.dirname(n);for(;i!==K.dirname(i);){let s=K.dirname(i);if(K.basename(s)==="node_modules"){let c=K.join(s,".bin",t);if(Ae.existsSync(c))return c;break}i=s}}catch(n){console.error("Could not resolve package.json",n)}if(H.env.NODE_PATH){let n=K.join(H.env.NODE_PATH,".bin",t);if(Ae.existsSync(n))return n}let r=K.join(e,"node_modules",".bin",t);if(Ae.existsSync(r))return r;let o=K.join(Fr,"..","node_modules",".bin",t);if(Ae.existsSync(o))return o}var Ot=_("utils"),Gr=e=>new Promise(t=>{setTimeout(t,e)}),Ft=(e,t=3e3)=>{let r=!1,o=null,n=[],i=null,s=(...c)=>{if(r)return o=c,new Promise(f=>{n.push(f)});r=!0;let l,d=new Promise(f=>{l=f});return i=(async()=>{await Promise.resolve();let f=await e(...c);for(l(f);;){if(await Gr(t),!o)return r=!1,i=null,f;let u=o,m=n;o=null,n=[],f=await e(...u),m.forEach(h=>{h(f)})}})(),d};return s.flush=async()=>{if((r||o)&&i)return await i,s.flush()},s},se=(e,t,r=!1)=>{let o=null,n=null,i=null,s=function(...c){n=c,i=this;let l=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(i,n),n=null,i=null)},t),l&&(e.apply(i,n),n=null,i=null)};return s.cancel=()=>{clearTimeout(o),o=null,n=null,i=null},s.flush=()=>{if(o){clearTimeout(o);let c=n,l=i;o=null,n=null,i=null,e.apply(l,c)}},s},Se=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):Ot.error("Could not parse JSON",o))}},Lt=(e,t)=>{let n=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let c=`--${t}${n}`;if(c.length>55)return"";let l=60-c.length;if(l<=0)return"";if(l>=i.length+6){let d=Math.min(l-i.length,e.length);return`${i}${e.slice(0,d)}`}return e.slice(0,l)},jr=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!bt.some(t=>t in e),Dt=()=>{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 i=JSON.parse(o);jr(i)&&(e[r]=i)}catch(i){let c=i instanceof SyntaxError?"Invalid JSON":i.message;Ot.error(`Could not parse ${r} model version override from ${n}: ${c}`)}}}),e},Yr=50*1024,Ze=(e,t=Yr)=>{if(!e||typeof e!="string"||e.length<=t)return e;let o=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+o};import{Buffer as $t}from"buffer";import Br from"path";var kt=_("repo"),Ut=async({config:e,isRetry:t})=>{kt.info("Getting runner diffs");let r=await qr(),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};if(!t){let T=Wr(n);await Kr(T)}kt.info("Changes after processing"),await et();let i=await tt(n);await Qe(i);let s={stdio:["ignore","pipe","pipe"]},c=await F("git",["diff","--staged"],s),l=String(c.stdout??"");if(o=!!l,!o)return{hasChanges:!1,ignored:i};let d=await F("git",["diff","--staged","--binary"],s),f=String(d.stdout??""),u,m;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await F("git",["commit","-m","Agent runner"]);let T=await F("git",["diff",e.sha,"HEAD"],s);u=String(T.stdout??"");let E=await F("git",["diff",e.sha,"HEAD","--binary"],s),g=String(E.stdout??"");u!==g&&(m=$t.from(g).toString("base64"))}let h={hasChanges:!0,diff:l,resultDiff:u,ignored:i};return l!==f&&(h.diffBinary=$t.from(f).toString("base64")),m&&(h.resultDiffBinary=m),h},Qe=async(e=[])=>{await F("git",["add",".",...e])},et=async()=>{let e=await F("git",["status","-s"]);return String(e.stdout??"")},Mt=/.. (.+)?\.log$/,Hr=[Mt],qr=async()=>{let e=await et();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
8
|
+
`);return i.length>e.length*.8?e:i}import Oe from"process";import{getTracer as un}from"@netlify/otel";import he from"process";var Re=he.env.NETLIFY_API_URL,ve=he.env.NETLIFY_API_TOKEN,B=_("api"),Ne=()=>he.env.NETLIFY_LOCAL_MODE==="true",ye=async(e,t={})=>{if(!Re||!ve)throw new Error("No API URL or token");let r=new URL(e,Re),o={...t,headers:{...t.headers,Authorization:`Bearer ${ve}`}};he.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(he.env.AGENT_RUNNERS_DEBUG==="true")B.log(`Response headers for ${r}:`),n.headers.forEach((c,l)=>{B.log(` ${l}: ${c}`)});else{let c=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");B.log(`Request ID for ${r}: ${c||"N/A"}`)}if(i||B.error(`Got status ${n.status} for request ${r}`),t.raw){if(!i)throw new Error(`API request failed: ${n.status} ${n.statusText}`);return n}let s=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!i){let c=typeof s=="string"?s:JSON.stringify(s);throw new Error(`API request failed: ${n.status} - ${c}`)}return s},_t=e=>{B.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Re=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(ve=e.constants.NETLIFY_API_TOKEN)},Et=()=>({apiUrl:Re,token:ve}),_e=async(e,t)=>Ne()?(B.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):ye(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),q=async(e,t,r)=>Ne()?(B.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):ye(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var Tt=async(e,t)=>Ne()?(B.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):ye(`/api/v1/agent_runners/${e}/sessions/${t}`),wt=(e,t,r)=>ye(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}}),It=async(e,t)=>Ne()?(B.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"}}):ye(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),je=async(e,t)=>{B.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=_("ai_gateway"),Ye=null;var xt=async()=>{if(Ye)return Ye;te.log("Fetching available AI gateway providers");let e=await fetch(`${Et().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 Ye=t,te.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},Ir=async(e,t)=>{let o=(await xt()).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},Rt=async({netlify:e,config:t})=>{let r,o,n,i,s=e.constants?.SITE_ID;if(!s)throw new Error("No site id");let c=async()=>{clearTimeout(n),te.log("Requesting AI gateway information");let l=await wt(s,t.id,t.sessionId);if({token:r,url:i}=l,o=l.expires_at?l.expires_at*1e3:void 0,te.log("Got AI gateway information",{token:!!r,expiresAt:o,url:i}),o){let d=o-Date.now()-6e4;d>0&&(n=setTimeout(()=>{c()},d))}};return await Promise.all([c(),xt()]),{get url(){return i},get token(){return r},isModelAvailableForProvider:Ir}};import H from"process";import K from"path";import Ae from"fs";import{fileURLToPath as br}from"url";import{createRequire as Cr}from"module";import{execa as Pr,execaCommand as po}from"execa";import{Transform as xr}from"stream";var Rr=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_WITH_BUILD_ENABLED","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"]),vr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function Nr(){return Object.entries(process.env).filter(([e,t])=>!(!t||Rr.has(e)||vr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function W(e){if(typeof e!="string")return e;let t=Nr();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(Ar(o),"g");r=r.replace(n,"******")}),r}function Ar(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var re=class extends xr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),i=W(n);o(null,i)}};function vt(){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 s=typeof o=="string"?W(o):o;return typeof n=="function"?t(s,n):t(s,n,i)},process.stderr.write=function(o,n,i){let s=typeof o=="string"?W(o):o;return typeof n=="function"?r(s,n):r(s,n,i)}}var Ee=null,Nt=e=>(Ee&&Ee.destroy(),Ee=new Z({totalAllowedTime:e}),Ee),At=()=>Ee;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,s=null;o!==void 0&&(s=new Promise((c,l)=>{i=setTimeout(()=>{l(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return s?await Promise.race([r(),s]):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 St="netlify-agent-runner-context.md",Be="task-history",He="netlify-context",$=".netlify",ne="results.md",qe="assets",We="other",Ke="personal";var Ve="enterprise",Je="free",bt=[Ke,"pro",Ve,Je],Q=1800*1e3;var Ct={name:"@netlify/agent-runner-cli",type:"module",version:"1.59.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":"LOG=0 vitest --exclude '**/integration/**'","test:ci:vitest":"LOG=0 c8 -r lcovonly -r text -r json vitest --exclude '**/integration/**'","test:integration":"vitest run test/integration/","test:integration:codex":"vitest run test/integration/codex.test.ts","test:integration:claude":"vitest run test/integration/claude.test.ts","test:integration:gemini":"vitest run test/integration/gemini.test.ts",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":"^20.0.0","@commitlint/config-conventional":"^20.0.0","@eslint/compat":"^2.0.0","@eslint/js":"^9.35.0","@netlify/eslint-config-node":"^7.0.1","@types/node":"^24.5.0","@typescript-eslint/eslint-plugin":"^8.0.0","@typescript-eslint/parser":"^8.0.0","@vitest/eslint-plugin":"^1.6.6",c8:"^10.0.0","eslint-config-prettier":"^10.1.8","eslint-plugin-n":"^17.0.0",husky:"^9.0.0","patch-package":"^8.0.0",tsup:"^8.5.0",typescript:"^5.0.0","typescript-eslint":"^8.44.0",vitest:"^4.0.16"},dependencies:{"@anthropic-ai/claude-code":"2.0.76","@google/gemini-cli":"0.23.0","@netlify/otel":"^5.1.1","@openai/codex":"0.79.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.208.0",execa:"^9.6.1",minimist:"^1.2.8"}};var Or=br(import.meta.url),Fr=K.dirname(Or),Lr=Cr(import.meta.url),oe=_("shell"),Xe=new Set,Dr={preferLocal:!0},F=(e,t,r)=>{let[o,n]=$r(t,r),i={...Dr,...n},s=Pr(e,o,i);kr(s,i),Mr(s);let c=r?.idleTimeout;return c&&c>0&&Ur(s,c),s};var $r=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},kr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(H.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new re).pipe(H.stdout),e.stdout?.pipe(new re).pipe(H.stdout),e.stderr?.pipe(new re).pipe(H.stderr);return}e.stdout?.pipe(H.stdout),e.stderr?.pipe(H.stderr)},ze=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(H.kill(-e.pid,t),oe.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return oe.error("Error killing process:",r),!1}},Pt=e=>ze(e,"SIGKILL"),Ur=(e,t)=>{let r=null,o=()=>{oe.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),ze(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(oe.log(`Force killing idle process ${e.pid}`),Pt(e))},5e3)},n=()=>{r&&clearTimeout(r),r=setTimeout(o,t)};n(),e.stdout?.on("data",n),e.stderr?.on("data",n);let i=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",i),e.on("error",i)},Mr=e=>{Xe.add(e);let t=At();if(t){let r=t.onTimesUp(()=>{oe.log(`Global timer expired, killing process ${e.pid}`),ze(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(oe.log(`Force killing process ${e.pid} after timeout`),Pt(e))},5e3)});e.on("exit",()=>{Xe.delete(e),r()}),e.on("error",()=>{Xe.delete(e),r()})}};function ie(e,t){if(!H.env.NETLIFY_LOCAL_MODE)try{let n=Lr.resolve(Ct.name),i=K.dirname(n);for(;i!==K.dirname(i);){let s=K.dirname(i);if(K.basename(s)==="node_modules"){let c=K.join(s,".bin",t);if(Ae.existsSync(c))return c;break}i=s}}catch(n){console.error("Could not resolve package.json",n)}if(H.env.NODE_PATH){let n=K.join(H.env.NODE_PATH,".bin",t);if(Ae.existsSync(n))return n}let r=K.join(e,"node_modules",".bin",t);if(Ae.existsSync(r))return r;let o=K.join(Fr,"..","node_modules",".bin",t);if(Ae.existsSync(o))return o}var Ot=_("utils"),Gr=e=>new Promise(t=>{setTimeout(t,e)}),Ft=(e,t=3e3)=>{let r=!1,o=null,n=[],i=null,s=(...c)=>{if(r)return o=c,new Promise(f=>{n.push(f)});r=!0;let l,d=new Promise(f=>{l=f});return i=(async()=>{await Promise.resolve();let f=await e(...c);for(l(f);;){if(await Gr(t),!o)return r=!1,i=null,f;let u=o,m=n;o=null,n=[],f=await e(...u),m.forEach(h=>{h(f)})}})(),d};return s.flush=async()=>{if((r||o)&&i)return await i,s.flush()},s},se=(e,t,r=!1)=>{let o=null,n=null,i=null,s=function(...c){n=c,i=this;let l=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(i,n),n=null,i=null)},t),l&&(e.apply(i,n),n=null,i=null)};return s.cancel=()=>{clearTimeout(o),o=null,n=null,i=null},s.flush=()=>{if(o){clearTimeout(o);let c=n,l=i;o=null,n=null,i=null,e.apply(l,c)}},s},Se=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):Ot.error("Could not parse JSON",o))}},Lt=(e,t)=>{let n=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let c=`--${t}${n}`;if(c.length>55)return"";let l=60-c.length;if(l<=0)return"";if(l>=i.length+6){let d=Math.min(l-i.length,e.length);return`${i}${e.slice(0,d)}`}return e.slice(0,l)},jr=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!bt.some(t=>t in e),Dt=()=>{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 i=JSON.parse(o);jr(i)&&(e[r]=i)}catch(i){let c=i instanceof SyntaxError?"Invalid JSON":i.message;Ot.error(`Could not parse ${r} model version override from ${n}: ${c}`)}}}),e},Yr=50*1024,Ze=(e,t=Yr)=>{if(!e||typeof e!="string"||e.length<=t)return e;let o=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+o};import{Buffer as $t}from"buffer";import Br from"path";var kt=_("repo"),Ut=async({config:e,isRetry:t})=>{kt.info("Getting runner diffs");let r=await qr(),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};if(!t){let T=Wr(n);await Kr(T)}kt.info("Changes after processing"),await et();let i=await tt(n);await Qe(i);let s={stdio:["ignore","pipe","pipe"]},c=await F("git",["diff","--staged"],s),l=String(c.stdout??"");if(o=!!l,!o)return{hasChanges:!1,ignored:i};let d=await F("git",["diff","--staged","--binary"],s),f=String(d.stdout??""),u,m;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await F("git",["commit","-m","Agent runner"]);let T=await F("git",["diff",e.sha,"HEAD"],s);u=String(T.stdout??"");let E=await F("git",["diff",e.sha,"HEAD","--binary"],s),g=String(E.stdout??"");u!==g&&(m=$t.from(g).toString("base64"))}let h={hasChanges:!0,diff:l,resultDiff:u,ignored:i};return l!==f&&(h.diffBinary=$t.from(f).toString("base64")),m&&(h.resultDiffBinary=m),h},Qe=async(e=[])=>{await F("git",["add",".",...e])},et=async()=>{let e=await F("git",["status","-s"]);return String(e.stdout??"")},Mt=/.. (.+)?\.log$/,Hr=[Mt],qr=async()=>{let e=await et();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
9
9
|
`).filter(o=>Hr.some(i=>i instanceof RegExp?i.test(o):o===i)?!1:o[1]?.trim()!=="")).length!==0,status:e}},Gt=async()=>{let{stdout:e}=await F("git",["rev-parse","HEAD"]);return String(e??"").trim()},jt=async()=>{let{stdout:e}=await F("git",["rev-list","--max-parents=0","HEAD"]);return String(e??"").trim()},tt=async e=>{e||=await et();let t=[".netlify","node_modules","dist"],r=[];return e.split(`
|
|
10
10
|
`).forEach(o=>{t.forEach(i=>{[`?? ${i}`,`?? ${i}${Br.sep}`].some(c=>o.startsWith(c))&&r.push(`:!${i}`)});let n=o.match(Mt)?.[1];n&&r.push(`:!${n}.log`)}),r},Yt=async()=>{await F("git",["reset","--hard","HEAD"])},Wr=e=>{let t=e.split(`
|
|
11
11
|
`).reduce((r,o)=>{if(!o)return r;let[n,i,,...s]=o,c=s.join(""),l=n.trim(),d=i.trim();return r[c]?r[c].change=d:r[c]={filePath:c,stage:l,change:d},r},{});return Object.values(t)},Kr=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 Jr from"fs/promises";import Xr from"os";import qt from"path";import ue from"process";import zr from"readline";import rt from"path";import Vr from"fs/promises";var nt=_("agent-output-utils");async function ae({initialResult:e,agentName:t,hasError:r}){let o="",n=rt.join(process.cwd(),$,ne);try{let i=await Vr.readFile(n,"utf-8");i&&(o=i,nt.log(`Pulled result from ${rt.relative(process.cwd(),n)}`))}catch{nt.log(`No results file found at ${rt.relative(process.cwd(),n)}`)}return o||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function le({error:e,agentName:t}){let r=e&&typeof e=="object"?JSON.stringify(e):e,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&&nt.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function ce(e){if(!e)return!1;let r=(e&&typeof e=="object"?JSON.stringify(e):e)?.replace(/\s+/g," ").trim().toLowerCase()||"";return!!(r?.includes("error when talking to gemini api")||r?.includes("499")||r?.includes("connection closed prematurely")||r?.includes("request timed out")||r?.includes("network error"))}var k=_("runner_claude"),Bt="Claude Code",pe="claude-opus-4-5-20251101",Ht=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,Zr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(k.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?(k.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}):(k.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function ot({config:e,netlify:t,persistSteps:r,aiGateway:o,continueSession:n,priorAgentSessionId:i,cwd:s=ue.cwd()}){let c=e,{accountType:l,prompt:d,modelVersionOverrides:f}=c,{model:u}=c,m="";if(o){let{token:y,url:p}=o;if(!y||!p)throw new Error("No token or url provided from AI Gateway");if(f?.claude){let a=f?.claude?.[l];if(a){if(!await o.isModelAvailableForProvider("anthropic",a))throw new Error(`Model override '${a}' is not available for anthropic provider`);u=a}}else if(u){if(!await o.isModelAvailableForProvider("anthropic",u))throw new Error(`Model '${u}' is not available for anthropic provider`)}else!!pe&&await o.isModelAvailableForProvider("anthropic",pe)?(u=pe,k.log(`Using default model: ${pe}`)):pe&&k.log(`Default model ${pe} is not available, proceeding without model specification`);ue.env.ANTHROPIC_API_KEY=y,ue.env.ANTHROPIC_BASE_URL=p}else if(!ue.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let h=[],T=[],E={},g=0,I=0,v,N,b=[ie(s,"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...u?["--model",u]:[],...n?["--continue"]:[],...n&&i?["--resume",i]:[],"-p",d],C=`${ue.env.NVM_BIN}/node`;k.log(`Running ${C} ${b.join(" ")}`);let O=t.utils.run(C,b,{all:!0,env:ue.env,cwd:s,idleTimeout:Q});O.stdin?.end();let x=se(()=>{r?.({steps:h,duration:I})},250),R=(y,p)=>{let a={...y,id:g};g+=1,T.push(a),h.push(a),p||x.flush(),x(),p&&x.flush()},G=zr.createInterface({input:O.all});return G.on("error",y=>{k.error("Readline interface error",{error:y.message,stack:y.stack})}),G.on("line",y=>{let p=null;try{p=JSON.parse(y)}catch{k.log("Could not parse line",y)}p?.session_id&&p.session_id!==m&&(m=p.session_id),Array.isArray(p?.message?.content)?p.message.content.forEach(a=>{switch(a.type){case"text":{a.text&&R({message:a.text});break}case"image":{typeof a.source=="object"&&a.source&&a.source.type==="base64"&&a.source.media_type?R({message:``}):k.log(`Unsupported image type ${a.source?.type}`,a.source);break}case"tool_use":{if(a.name==="Task"){let w=a.input?.description&&`\`${a.input.description}\``;R({title:[Ht(a.name),w].filter(Boolean).join(" ")})}else a.id&&(E[a.id]=a);x.flush();break}case"tool_result":{let w=a.tool_use_id?E[a.tool_use_id]:void 0,X;if(w){let V=w.input?.file_path&&qt.relative(s,w.input.file_path),P=V&&`\`${V}\``;X=[Ht(w.name||""),P].filter(Boolean).join(" ")}let xe=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(w?.name||""),z;if(typeof a.content=="string")z=a.content;else if(Array.isArray(a.content)){let V=[];a.content.forEach(P=>{P?.type==="text"&&typeof P.text=="string"?V.push(P.text):P?.type==="image"&&typeof P.source=="object"&&P.source?P.source.type==="base64"&&P.source.media_type?V.push(``):k.log(`Unsupported image type ${P.source.type}`,P.source):k.log(`Unsupported block type ${P?.type}`)}),z=V.join(`
|
package/dist/index.js
CHANGED
|
@@ -4,7 +4,7 @@ import{createRequire as fn}from"module";import{createTracerProvider as rr}from"@
|
|
|
4
4
|
${s}
|
|
5
5
|
</extracted_error_chunk>`).join(`
|
|
6
6
|
|
|
7
|
-
`);return i.length>e.length*.8?e:i}import Ne from"process";import{getTracer as Vr}from"@netlify/otel";import me from"process";var Ie=me.env.NETLIFY_API_URL,xe=me.env.NETLIFY_API_TOKEN,Y=_("api"),ve=()=>me.env.NETLIFY_LOCAL_MODE==="true",ge=async(e,t={})=>{if(!Ie||!xe)throw new Error("No API URL or token");let r=new URL(e,Ie),o={...t,headers:{...t.headers,Authorization:`Bearer ${xe}`}};me.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(me.env.AGENT_RUNNERS_DEBUG==="true")Y.log(`Response headers for ${r}:`),n.headers.forEach((u,l)=>{Y.log(` ${l}: ${u}`)});else{let u=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");Y.log(`Request ID for ${r}: ${u||"N/A"}`)}if(i||Y.error(`Got status ${n.status} for request ${r}`),t.raw){if(!i)throw new Error(`API request failed: ${n.status} ${n.statusText}`);return n}let s=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!i){let u=typeof s=="string"?s:JSON.stringify(s);throw new Error(`API request failed: ${n.status} - ${u}`)}return s},ct=e=>{Y.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Ie=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(xe=e.constants.NETLIFY_API_TOKEN)},dt=()=>({apiUrl:Ie,token:xe}),he=async(e,t)=>ve()?(Y.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):ge(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),H=async(e,t,r)=>ve()?(Y.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):ge(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var pt=async(e,t)=>ve()?(Y.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):ge(`/api/v1/agent_runners/${e}/sessions/${t}`),ft=(e,t,r)=>ge(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}}),mt=async(e,t)=>ve()?(Y.log("Mock API: getDiffUploadUrls called",{runnerId:e,sessionId:t}),{result:{upload_url:"https://s3.mock.com/mock-upload-url-result",s3_key:"mock-s3-key-result"},cumulative:{upload_url:"https://s3.mock.com/mock-upload-url-cumulative",s3_key:"mock-s3-key-cumulative"}}):ge(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Ue=async(e,t)=>{Y.log(`Uploading diff to S3: ${e.substring(0,50)}...`);let r=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"text/plain"}});if(!r.ok)throw new Error(`S3 upload failed with status ${r.status}`);return r};var ee=_("ai_gateway"),Me=null;var gt=async()=>{if(Me)return Me;ee.log("Fetching available AI gateway providers");let e=await fetch(`${dt().apiUrl}/api/v1/ai-gateway/providers`);if(!e.ok)throw new Error(`Failed to fetch AI gateway providers: ${e.statusText}`);let t=await e.json();return Me=t,ee.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},lr=async(e,t)=>{let o=(await gt()).providers[e];if(!o)return ee.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return ee.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},ht=async({netlify:e,config:t})=>{let r,o,n,i,s=e.constants?.SITE_ID;if(!s)throw new Error("No site id");let u=async()=>{clearTimeout(n),ee.log("Requesting AI gateway information");let l=await ft(s,t.id,t.sessionId);if({token:r,url:i}=l,o=l.expires_at?l.expires_at*1e3:void 0,ee.log("Got AI gateway information",{token:!!r,expiresAt:o,url:i}),o){let p=o-Date.now()-6e4;p>0&&(n=setTimeout(()=>{u()},p))}};return await Promise.all([u(),gt()]),{get url(){return i},get token(){return r},isModelAvailableForProvider:lr}};import B from"process";import K from"path";import Re from"fs";import{fileURLToPath as gr}from"url";import{createRequire as hr}from"module";import{execa as yr,execaCommand as qn}from"execa";import{Transform as ur}from"stream";var cr=new Set(["NODE_ENV","PATH","HOME","USER","USERNAME","SHELL","PWD","OLDPWD","TMPDIR","TMP","TEMP","LANG","TERM","EDITOR","PAGER","OS","PROCESSOR_ARCHITECTURE","PROCESSOR_IDENTIFIER","SYSTEMROOT","WINDIR","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","APPDATA","LOCALAPPDATA","NODE_OPTIONS","NODE_PATH","NODE_DEBUG","NODE_NO_WARNINGS","npm_config_registry","npm_config_cache","npm_execpath","npm_node_execpath","CI","GITHUB_ACTIONS","GITHUB_WORKSPACE","GITHUB_REPOSITORY","GITHUB_REF","BUILDKITE","BUILDKITE_BRANCH","BUILDKITE_COMMIT","BUILDKITE_BUILD_NUMBER","JENKINS_URL","TRAVIS","CIRCLECI","DISPLAY","COLORTERM","TERM_PROGRAM","TERM_PROGRAM_VERSION","COLUMNS","LINES","HISTSIZE","HISTFILE","NETLIFY_AGENT_RUNNER_ID","NETLIFY_AGENT_RUNNER_SESSION_ID","NETLIFY_AGENT_RUNNER_PROMPT","NETLIFY_AGENT_RUNNER_AGENT","NETLIFY_AGENT_RUNNER_MODEL","NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED","NETLIFY_AGENT_RUNNER_CONTEXT","NETLIFY_AGENT_RUNNER_HAS_REPO","NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED","NETLIFY_AGENT_RUNNER_SHA","NETLIFY_TEAM_TYPE","AGENT_RUNNERS_DEBUG","NETLIFY_TEAM_ID","NETLIFY_AGENT_RUNNER_USER_ID","SITE_NAME"]),dr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function pr(){return Object.entries(process.env).filter(([e,t])=>!(!t||cr.has(e)||dr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function q(e){if(typeof e!="string")return e;let t=pr();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(fr(o),"g");r=r.replace(n,"******")}),r}function fr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var te=class extends ur{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),i=q(n);o(null,i)}};function yt(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(o,n,i){let s=typeof o=="string"?q(o):o;return typeof n=="function"?t(s,n):t(s,n,i)},process.stderr.write=function(o,n,i){let s=typeof o=="string"?q(o):o;return typeof n=="function"?r(s,n):r(s,n,i)}}var ye=null,_t=e=>(ye&&ye.destroy(),ye=new z({totalAllowedTime:e}),ye),Et=()=>ye;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,s=null;o!==void 0&&(s=new Promise((u,l)=>{i=setTimeout(()=>{l(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return s?await Promise.race([r(),s]):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 wt="netlify-agent-runner-context.md",je="task-history",Ge="netlify-context",k=".netlify",re="results.md",Ye="assets";var Z=600*1e3;var Tt={name:"@netlify/agent-runner-cli",type:"module",version:"1.58.7-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":"LOG=0 vitest --exclude '**/integration/**'","test:ci:vitest":"LOG=0 c8 -r lcovonly -r text -r json vitest --exclude '**/integration/**'","test:integration":"vitest run test/integration/","test:integration:codex":"vitest run test/integration/codex.test.ts","test:integration:claude":"vitest run test/integration/claude.test.ts","test:integration:gemini":"vitest run test/integration/gemini.test.ts",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":"^20.0.0","@commitlint/config-conventional":"^20.0.0","@eslint/compat":"^2.0.0","@eslint/js":"^9.35.0","@netlify/eslint-config-node":"^7.0.1","@types/node":"^24.5.0","@typescript-eslint/eslint-plugin":"^8.0.0","@typescript-eslint/parser":"^8.0.0","@vitest/eslint-plugin":"^1.6.6",c8:"^10.0.0","eslint-config-prettier":"^10.1.8","eslint-plugin-n":"^17.0.0",husky:"^9.0.0","patch-package":"^8.0.0",tsup:"^8.5.0",typescript:"^5.0.0","typescript-eslint":"^8.44.0",vitest:"^4.0.16"},dependencies:{"@anthropic-ai/claude-code":"2.0.76","@google/gemini-cli":"0.23.0","@netlify/otel":"^5.1.1","@openai/codex":"0.77.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.208.0",execa:"^9.6.1",minimist:"^1.2.8"}};var _r=gr(import.meta.url),Er=K.dirname(_r),wr=hr(import.meta.url),ne=_("shell"),Be=new Set,Tr={preferLocal:!0},F=(e,t,r)=>{let[o,n]=Ir(t,r),i={...Tr,...n},s=yr(e,o,i);xr(s,i),Rr(s);let u=r?.idleTimeout;return u&&u>0&&vr(s,u),s};var Ir=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},xr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(B.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new te).pipe(B.stdout),e.stdout?.pipe(new te).pipe(B.stdout),e.stderr?.pipe(new te).pipe(B.stderr);return}e.stdout?.pipe(B.stdout),e.stderr?.pipe(B.stderr)},He=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(B.kill(-e.pid,t),ne.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return ne.error("Error killing process:",r),!1}},It=e=>He(e,"SIGKILL"),vr=(e,t)=>{let r=null,o=()=>{ne.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),He(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ne.log(`Force killing idle process ${e.pid}`),It(e))},5e3)},n=()=>{r&&clearTimeout(r),r=setTimeout(o,t)};n(),e.stdout?.on("data",n),e.stderr?.on("data",n);let i=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",i),e.on("error",i)},Rr=e=>{Be.add(e);let t=Et();if(t){let r=t.onTimesUp(()=>{ne.log(`Global timer expired, killing process ${e.pid}`),He(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ne.log(`Force killing process ${e.pid} after timeout`),It(e))},5e3)});e.on("exit",()=>{Be.delete(e),r()}),e.on("error",()=>{Be.delete(e),r()})}};function oe(e,t){if(!B.env.NETLIFY_LOCAL_MODE)try{let n=wr.resolve(Tt.name),i=K.dirname(n);for(;i!==K.dirname(i);){let s=K.dirname(i);if(K.basename(s)==="node_modules"){let u=K.join(s,".bin",t);if(Re.existsSync(u))return u;break}i=s}}catch(n){console.error("Could not resolve package.json",n)}if(B.env.NODE_PATH){let n=K.join(B.env.NODE_PATH,".bin",t);if(Re.existsSync(n))return n}let r=K.join(e,"node_modules",".bin",t);if(Re.existsSync(r))return r;let o=K.join(Er,"..","node_modules",".bin",t);if(Re.existsSync(o))return o}var Sr=_("utils"),br=e=>new Promise(t=>{setTimeout(t,e)}),xt=(e,t=3e3)=>{let r=!1,o=null,n=[],i=null,s=(...u)=>{if(r)return o=u,new Promise(f=>{n.push(f)});r=!0;let l,p=new Promise(f=>{l=f});return i=(async()=>{await Promise.resolve();let f=await e(...u);for(l(f);;){if(await br(t),!o)return r=!1,i=null,f;let c=o,m=n;o=null,n=[],f=await e(...c),m.forEach(y=>{y(f)})}})(),p};return s.flush=async()=>{if((r||o)&&i)return await i,s.flush()},s},ie=(e,t,r=!1)=>{let o=null,n=null,i=null,s=function(...u){n=u,i=this;let l=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(i,n),n=null,i=null)},t),l&&(e.apply(i,n),n=null,i=null)};return s.cancel=()=>{clearTimeout(o),o=null,n=null,i=null},s.flush=()=>{if(o){clearTimeout(o);let u=n,l=i;o=null,n=null,i=null,e.apply(l,u)}},s},vt=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):Sr.error("Could not parse JSON",o))}},Rt=(e,t)=>{let n=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let u=`--${t}${n}`;if(u.length>55)return"";let l=60-u.length;if(l<=0)return"";if(l>=i.length+6){let p=Math.min(l-i.length,e.length);return`${i}${e.slice(0,p)}`}return e.slice(0,l)};var Ar=50*1024,qe=(e,t=Ar)=>{if(!e||typeof e!="string"||e.length<=t)return e;let o=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+o};import{Buffer as St}from"buffer";import Nr from"path";var bt=_("repo"),At=async({config:e,isRetry:t})=>{bt.info("Getting runner diffs");let r=await Pr(),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};if(!t){let I=Or(n);await Fr(I)}bt.info("Changes after processing"),await We();let i=await Je(n);await Ke(i);let s={stdio:["ignore","pipe","pipe"]},u=await F("git",["diff","--staged"],s),l=String(u.stdout??"");if(o=!!l,!o)return{hasChanges:!1,ignored:i};let p=await F("git",["diff","--staged","--binary"],s),f=String(p.stdout??""),c,m;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await F("git",["commit","-m","Agent runner"]);let I=await F("git",["diff",e.sha,"HEAD"],s);c=String(I.stdout??"");let w=await F("git",["diff",e.sha,"HEAD","--binary"],s),g=String(w.stdout??"");c!==g&&(m=St.from(g).toString("base64"))}let y={hasChanges:!0,diff:l,resultDiff:c,ignored:i};return l!==f&&(y.diffBinary=St.from(f).toString("base64")),m&&(y.resultDiffBinary=m),y},Ke=async(e=[])=>{await F("git",["add",".",...e])},We=async()=>{let e=await F("git",["status","-s"]);return String(e.stdout??"")},Nt=/.. (.+)?\.log$/,Cr=[Nt],Pr=async()=>{let e=await We();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
7
|
+
`);return i.length>e.length*.8?e:i}import Ne from"process";import{getTracer as Vr}from"@netlify/otel";import me from"process";var Ie=me.env.NETLIFY_API_URL,xe=me.env.NETLIFY_API_TOKEN,Y=_("api"),ve=()=>me.env.NETLIFY_LOCAL_MODE==="true",ge=async(e,t={})=>{if(!Ie||!xe)throw new Error("No API URL or token");let r=new URL(e,Ie),o={...t,headers:{...t.headers,Authorization:`Bearer ${xe}`}};me.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(me.env.AGENT_RUNNERS_DEBUG==="true")Y.log(`Response headers for ${r}:`),n.headers.forEach((u,l)=>{Y.log(` ${l}: ${u}`)});else{let u=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");Y.log(`Request ID for ${r}: ${u||"N/A"}`)}if(i||Y.error(`Got status ${n.status} for request ${r}`),t.raw){if(!i)throw new Error(`API request failed: ${n.status} ${n.statusText}`);return n}let s=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!i){let u=typeof s=="string"?s:JSON.stringify(s);throw new Error(`API request failed: ${n.status} - ${u}`)}return s},ct=e=>{Y.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Ie=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(xe=e.constants.NETLIFY_API_TOKEN)},dt=()=>({apiUrl:Ie,token:xe}),he=async(e,t)=>ve()?(Y.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):ge(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),H=async(e,t,r)=>ve()?(Y.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):ge(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var pt=async(e,t)=>ve()?(Y.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):ge(`/api/v1/agent_runners/${e}/sessions/${t}`),ft=(e,t,r)=>ge(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}}),mt=async(e,t)=>ve()?(Y.log("Mock API: getDiffUploadUrls called",{runnerId:e,sessionId:t}),{result:{upload_url:"https://s3.mock.com/mock-upload-url-result",s3_key:"mock-s3-key-result"},cumulative:{upload_url:"https://s3.mock.com/mock-upload-url-cumulative",s3_key:"mock-s3-key-cumulative"}}):ge(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Ue=async(e,t)=>{Y.log(`Uploading diff to S3: ${e.substring(0,50)}...`);let r=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"text/plain"}});if(!r.ok)throw new Error(`S3 upload failed with status ${r.status}`);return r};var ee=_("ai_gateway"),Me=null;var gt=async()=>{if(Me)return Me;ee.log("Fetching available AI gateway providers");let e=await fetch(`${dt().apiUrl}/api/v1/ai-gateway/providers`);if(!e.ok)throw new Error(`Failed to fetch AI gateway providers: ${e.statusText}`);let t=await e.json();return Me=t,ee.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},lr=async(e,t)=>{let o=(await gt()).providers[e];if(!o)return ee.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return ee.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},ht=async({netlify:e,config:t})=>{let r,o,n,i,s=e.constants?.SITE_ID;if(!s)throw new Error("No site id");let u=async()=>{clearTimeout(n),ee.log("Requesting AI gateway information");let l=await ft(s,t.id,t.sessionId);if({token:r,url:i}=l,o=l.expires_at?l.expires_at*1e3:void 0,ee.log("Got AI gateway information",{token:!!r,expiresAt:o,url:i}),o){let p=o-Date.now()-6e4;p>0&&(n=setTimeout(()=>{u()},p))}};return await Promise.all([u(),gt()]),{get url(){return i},get token(){return r},isModelAvailableForProvider:lr}};import B from"process";import K from"path";import Re from"fs";import{fileURLToPath as gr}from"url";import{createRequire as hr}from"module";import{execa as yr,execaCommand as qn}from"execa";import{Transform as ur}from"stream";var cr=new Set(["NODE_ENV","PATH","HOME","USER","USERNAME","SHELL","PWD","OLDPWD","TMPDIR","TMP","TEMP","LANG","TERM","EDITOR","PAGER","OS","PROCESSOR_ARCHITECTURE","PROCESSOR_IDENTIFIER","SYSTEMROOT","WINDIR","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","APPDATA","LOCALAPPDATA","NODE_OPTIONS","NODE_PATH","NODE_DEBUG","NODE_NO_WARNINGS","npm_config_registry","npm_config_cache","npm_execpath","npm_node_execpath","CI","GITHUB_ACTIONS","GITHUB_WORKSPACE","GITHUB_REPOSITORY","GITHUB_REF","BUILDKITE","BUILDKITE_BRANCH","BUILDKITE_COMMIT","BUILDKITE_BUILD_NUMBER","JENKINS_URL","TRAVIS","CIRCLECI","DISPLAY","COLORTERM","TERM_PROGRAM","TERM_PROGRAM_VERSION","COLUMNS","LINES","HISTSIZE","HISTFILE","NETLIFY_AGENT_RUNNER_ID","NETLIFY_AGENT_RUNNER_SESSION_ID","NETLIFY_AGENT_RUNNER_PROMPT","NETLIFY_AGENT_RUNNER_AGENT","NETLIFY_AGENT_RUNNER_MODEL","NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED","NETLIFY_AGENT_RUNNER_CONTEXT","NETLIFY_AGENT_RUNNER_HAS_REPO","NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED","NETLIFY_AGENT_RUNNER_SHA","NETLIFY_TEAM_TYPE","AGENT_RUNNERS_DEBUG","NETLIFY_TEAM_ID","NETLIFY_AGENT_RUNNER_USER_ID","SITE_NAME"]),dr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function pr(){return Object.entries(process.env).filter(([e,t])=>!(!t||cr.has(e)||dr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function q(e){if(typeof e!="string")return e;let t=pr();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(fr(o),"g");r=r.replace(n,"******")}),r}function fr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var te=class extends ur{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),i=q(n);o(null,i)}};function yt(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(o,n,i){let s=typeof o=="string"?q(o):o;return typeof n=="function"?t(s,n):t(s,n,i)},process.stderr.write=function(o,n,i){let s=typeof o=="string"?q(o):o;return typeof n=="function"?r(s,n):r(s,n,i)}}var ye=null,_t=e=>(ye&&ye.destroy(),ye=new z({totalAllowedTime:e}),ye),Et=()=>ye;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,s=null;o!==void 0&&(s=new Promise((u,l)=>{i=setTimeout(()=>{l(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return s?await Promise.race([r(),s]):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 wt="netlify-agent-runner-context.md",je="task-history",Ge="netlify-context",k=".netlify",re="results.md",Ye="assets";var Z=1800*1e3;var Tt={name:"@netlify/agent-runner-cli",type:"module",version:"1.59.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":"LOG=0 vitest --exclude '**/integration/**'","test:ci:vitest":"LOG=0 c8 -r lcovonly -r text -r json vitest --exclude '**/integration/**'","test:integration":"vitest run test/integration/","test:integration:codex":"vitest run test/integration/codex.test.ts","test:integration:claude":"vitest run test/integration/claude.test.ts","test:integration:gemini":"vitest run test/integration/gemini.test.ts",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":"^20.0.0","@commitlint/config-conventional":"^20.0.0","@eslint/compat":"^2.0.0","@eslint/js":"^9.35.0","@netlify/eslint-config-node":"^7.0.1","@types/node":"^24.5.0","@typescript-eslint/eslint-plugin":"^8.0.0","@typescript-eslint/parser":"^8.0.0","@vitest/eslint-plugin":"^1.6.6",c8:"^10.0.0","eslint-config-prettier":"^10.1.8","eslint-plugin-n":"^17.0.0",husky:"^9.0.0","patch-package":"^8.0.0",tsup:"^8.5.0",typescript:"^5.0.0","typescript-eslint":"^8.44.0",vitest:"^4.0.16"},dependencies:{"@anthropic-ai/claude-code":"2.0.76","@google/gemini-cli":"0.23.0","@netlify/otel":"^5.1.1","@openai/codex":"0.79.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.208.0",execa:"^9.6.1",minimist:"^1.2.8"}};var _r=gr(import.meta.url),Er=K.dirname(_r),wr=hr(import.meta.url),ne=_("shell"),Be=new Set,Tr={preferLocal:!0},F=(e,t,r)=>{let[o,n]=Ir(t,r),i={...Tr,...n},s=yr(e,o,i);xr(s,i),Rr(s);let u=r?.idleTimeout;return u&&u>0&&vr(s,u),s};var Ir=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},xr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(B.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new te).pipe(B.stdout),e.stdout?.pipe(new te).pipe(B.stdout),e.stderr?.pipe(new te).pipe(B.stderr);return}e.stdout?.pipe(B.stdout),e.stderr?.pipe(B.stderr)},He=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(B.kill(-e.pid,t),ne.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return ne.error("Error killing process:",r),!1}},It=e=>He(e,"SIGKILL"),vr=(e,t)=>{let r=null,o=()=>{ne.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),He(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ne.log(`Force killing idle process ${e.pid}`),It(e))},5e3)},n=()=>{r&&clearTimeout(r),r=setTimeout(o,t)};n(),e.stdout?.on("data",n),e.stderr?.on("data",n);let i=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",i),e.on("error",i)},Rr=e=>{Be.add(e);let t=Et();if(t){let r=t.onTimesUp(()=>{ne.log(`Global timer expired, killing process ${e.pid}`),He(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ne.log(`Force killing process ${e.pid} after timeout`),It(e))},5e3)});e.on("exit",()=>{Be.delete(e),r()}),e.on("error",()=>{Be.delete(e),r()})}};function oe(e,t){if(!B.env.NETLIFY_LOCAL_MODE)try{let n=wr.resolve(Tt.name),i=K.dirname(n);for(;i!==K.dirname(i);){let s=K.dirname(i);if(K.basename(s)==="node_modules"){let u=K.join(s,".bin",t);if(Re.existsSync(u))return u;break}i=s}}catch(n){console.error("Could not resolve package.json",n)}if(B.env.NODE_PATH){let n=K.join(B.env.NODE_PATH,".bin",t);if(Re.existsSync(n))return n}let r=K.join(e,"node_modules",".bin",t);if(Re.existsSync(r))return r;let o=K.join(Er,"..","node_modules",".bin",t);if(Re.existsSync(o))return o}var Sr=_("utils"),br=e=>new Promise(t=>{setTimeout(t,e)}),xt=(e,t=3e3)=>{let r=!1,o=null,n=[],i=null,s=(...u)=>{if(r)return o=u,new Promise(f=>{n.push(f)});r=!0;let l,p=new Promise(f=>{l=f});return i=(async()=>{await Promise.resolve();let f=await e(...u);for(l(f);;){if(await br(t),!o)return r=!1,i=null,f;let c=o,m=n;o=null,n=[],f=await e(...c),m.forEach(y=>{y(f)})}})(),p};return s.flush=async()=>{if((r||o)&&i)return await i,s.flush()},s},ie=(e,t,r=!1)=>{let o=null,n=null,i=null,s=function(...u){n=u,i=this;let l=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(i,n),n=null,i=null)},t),l&&(e.apply(i,n),n=null,i=null)};return s.cancel=()=>{clearTimeout(o),o=null,n=null,i=null},s.flush=()=>{if(o){clearTimeout(o);let u=n,l=i;o=null,n=null,i=null,e.apply(l,u)}},s},vt=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):Sr.error("Could not parse JSON",o))}},Rt=(e,t)=>{let n=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let u=`--${t}${n}`;if(u.length>55)return"";let l=60-u.length;if(l<=0)return"";if(l>=i.length+6){let p=Math.min(l-i.length,e.length);return`${i}${e.slice(0,p)}`}return e.slice(0,l)};var Ar=50*1024,qe=(e,t=Ar)=>{if(!e||typeof e!="string"||e.length<=t)return e;let o=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+o};import{Buffer as St}from"buffer";import Nr from"path";var bt=_("repo"),At=async({config:e,isRetry:t})=>{bt.info("Getting runner diffs");let r=await Pr(),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};if(!t){let I=Or(n);await Fr(I)}bt.info("Changes after processing"),await We();let i=await Je(n);await Ke(i);let s={stdio:["ignore","pipe","pipe"]},u=await F("git",["diff","--staged"],s),l=String(u.stdout??"");if(o=!!l,!o)return{hasChanges:!1,ignored:i};let p=await F("git",["diff","--staged","--binary"],s),f=String(p.stdout??""),c,m;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await F("git",["commit","-m","Agent runner"]);let I=await F("git",["diff",e.sha,"HEAD"],s);c=String(I.stdout??"");let w=await F("git",["diff",e.sha,"HEAD","--binary"],s),g=String(w.stdout??"");c!==g&&(m=St.from(g).toString("base64"))}let y={hasChanges:!0,diff:l,resultDiff:c,ignored:i};return l!==f&&(y.diffBinary=St.from(f).toString("base64")),m&&(y.resultDiffBinary=m),y},Ke=async(e=[])=>{await F("git",["add",".",...e])},We=async()=>{let e=await F("git",["status","-s"]);return String(e.stdout??"")},Nt=/.. (.+)?\.log$/,Cr=[Nt],Pr=async()=>{let e=await We();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
8
8
|
`).filter(o=>Cr.some(i=>i instanceof RegExp?i.test(o):o===i)?!1:o[1]?.trim()!=="")).length!==0,status:e}},Ct=async()=>{let{stdout:e}=await F("git",["rev-parse","HEAD"]);return String(e??"").trim()},Pt=async()=>{let{stdout:e}=await F("git",["rev-list","--max-parents=0","HEAD"]);return String(e??"").trim()},Je=async e=>{e||=await We();let t=[".netlify","node_modules","dist"],r=[];return e.split(`
|
|
9
9
|
`).forEach(o=>{t.forEach(i=>{[`?? ${i}`,`?? ${i}${Nr.sep}`].some(u=>o.startsWith(u))&&r.push(`:!${i}`)});let n=o.match(Nt)?.[1];n&&r.push(`:!${n}.log`)}),r},Ot=async()=>{await F("git",["reset","--hard","HEAD"])},Or=e=>{let t=e.split(`
|
|
10
10
|
`).reduce((r,o)=>{if(!o)return r;let[n,i,,...s]=o,u=s.join(""),l=n.trim(),p=i.trim();return r[u]?r[u].change=p:r[u]={filePath:u,stage:l,change:p},r},{});return Object.values(t)},Fr=async e=>{let t=[];for(let r of e)r.stage&&!r.change&&t.push(F("git",["restore","--staged","--worktree",r.filePath]));await Promise.allSettled(t)};import Dr from"fs/promises";import kr from"os";import Dt from"path";import ue from"process";import Lr from"readline";import Ve from"path";import $r from"fs/promises";var Xe=_("agent-output-utils");async function se({initialResult:e,agentName:t,hasError:r}){let o="",n=Ve.join(process.cwd(),k,re);try{let i=await $r.readFile(n,"utf-8");i&&(o=i,Xe.log(`Pulled result from ${Ve.relative(process.cwd(),n)}`))}catch{Xe.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 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&&Xe.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 L=_("runner_claude"),Ft="Claude Code",ce="claude-opus-4-5-20251101",$t=e=>({Task:"Task",Bash:"Run command",Glob:"Find files",Grep:"Search files",LS:"List directory",ExitPlanMode:"Exit planning",Read:"Read file",Edit:"Edit file",MultiEdit:"Edit multiple files",Write:"Coding",NotebookEdit:"Edit notebook",WebFetch:"Fetch webpage",TodoWrite:"Update task list",WebSearch:"Search web",BashOutput:"Get command output",KillBash:"Stop command"})[e]||e,Ur=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(L.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(L.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(L.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function ze({config:e,netlify:t,persistSteps:r,aiGateway:o,continueSession:n,priorAgentSessionId:i,cwd:s=ue.cwd()}){let u=e,{accountType:l,prompt:p,modelVersionOverrides:f}=u,{model:c}=u,m="";if(o){let{token:h,url:d}=o;if(!h||!d)throw new Error("No token or url provided from AI Gateway");if(f?.claude){let a=f?.claude?.[l];if(a){if(!await o.isModelAvailableForProvider("anthropic",a))throw new Error(`Model override '${a}' is not available for anthropic provider`);c=a}}else if(c){if(!await o.isModelAvailableForProvider("anthropic",c))throw new Error(`Model '${c}' is not available for anthropic provider`)}else!!ce&&await o.isModelAvailableForProvider("anthropic",ce)?(c=ce,L.log(`Using default model: ${ce}`)):ce&&L.log(`Default model ${ce} is not available, proceeding without model specification`);ue.env.ANTHROPIC_API_KEY=h,ue.env.ANTHROPIC_BASE_URL=d}else if(!ue.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let y=[],I=[],w={},g=0,T=0,R,S,N=[oe(s,"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...c?["--model",c]:[],...n?["--continue"]:[],...n&&i?["--resume",i]:[],"-p",p],C=`${ue.env.NVM_BIN}/node`;L.log(`Running ${C} ${N.join(" ")}`);let O=t.utils.run(C,N,{all:!0,env:ue.env,cwd:s,idleTimeout:Z});O.stdin?.end();let x=ie(()=>{r?.({steps:y,duration:T})},250),v=(h,d)=>{let a={...h,id:g};g+=1,I.push(a),y.push(a),d||x.flush(),x(),d&&x.flush()},M=Lr.createInterface({input:O.all});return M.on("error",h=>{L.error("Readline interface error",{error:h.message,stack:h.stack})}),M.on("line",h=>{let d=null;try{d=JSON.parse(h)}catch{L.log("Could not parse line",h)}d?.session_id&&d.session_id!==m&&(m=d.session_id),Array.isArray(d?.message?.content)?d.message.content.forEach(a=>{switch(a.type){case"text":{a.text&&v({message:a.text});break}case"image":{typeof a.source=="object"&&a.source&&a.source.type==="base64"&&a.source.media_type?v({message:``}):L.log(`Unsupported image type ${a.source?.type}`,a.source);break}case"tool_use":{if(a.name==="Task"){let E=a.input?.description&&`\`${a.input.description}\``;v({title:[$t(a.name),E].filter(Boolean).join(" ")})}else a.id&&(w[a.id]=a);x.flush();break}case"tool_result":{let E=a.tool_use_id?w[a.tool_use_id]:void 0,V;if(E){let W=E.input?.file_path&&Dt.relative(s,E.input.file_path),P=W&&`\`${W}\``;V=[$t(E.name||""),P].filter(Boolean).join(" ")}let Te=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(E?.name||""),X;if(typeof a.content=="string")X=a.content;else if(Array.isArray(a.content)){let W=[];a.content.forEach(P=>{P?.type==="text"&&typeof P.text=="string"?W.push(P.text):P?.type==="image"&&typeof P.source=="object"&&P.source?P.source.type==="base64"&&P.source.media_type?W.push(``):L.log(`Unsupported image type ${P.source.type}`,P.source):L.log(`Unsupported block type ${P?.type}`)}),X=W.join(`
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@netlify/agent-runner-cli",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "1.
|
|
4
|
+
"version": "1.59.0",
|
|
5
5
|
"description": "CLI tool for running Netlify agents",
|
|
6
6
|
"main": "./dist/index.js",
|
|
7
7
|
"types": "./dist/index.d.ts",
|
|
@@ -79,7 +79,7 @@
|
|
|
79
79
|
"@anthropic-ai/claude-code": "2.0.76",
|
|
80
80
|
"@google/gemini-cli": "0.23.0",
|
|
81
81
|
"@netlify/otel": "^5.1.1",
|
|
82
|
-
"@openai/codex": "0.
|
|
82
|
+
"@openai/codex": "0.79.0",
|
|
83
83
|
"@opentelemetry/exporter-trace-otlp-grpc": "^0.208.0",
|
|
84
84
|
"execa": "^9.6.1",
|
|
85
85
|
"minimist": "^1.2.8"
|