@netlify/agent-runner-cli 1.66.0-alpha.0 → 1.66.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin-local.js
CHANGED
|
@@ -5,7 +5,7 @@ import O from"process";import gr from"path";import hr from"fs";import Mn from"mi
|
|
|
5
5
|
${s}
|
|
6
6
|
</extracted_error_chunk>`).join(`
|
|
7
7
|
|
|
8
|
-
`);return o.length>e.length*.8?e:o}import{execSync as pn}from"child_process";import tr from"fs/promises";import fn from"path";import Q from"process";import{getTracer as mn}from"@netlify/otel";import we from"process";var se=class extends Error{constructor(r,n,i){super(r);this.statusCode=n;this.userMessage=i;this.name="GracefulShutdownError"}},Tt=e=>e instanceof se;var be=we.env.NETLIFY_API_URL,Ne=we.env.NETLIFY_API_TOKEN,H=_("api"),Pe=()=>we.env.NETLIFY_LOCAL_MODE==="true",Te=async(e,t={})=>{if(!be||!Ne)throw new Error("No API URL or token");let r=new URL(e,be),n={...t,headers:{...t.headers,Authorization:`Bearer ${Ne}`}};we.env.AGENT_RUNNERS_DEBUG==="true"&&(n.headers["x-nf-debug-logging"]="true"),t.json&&(n.headers||={},n.headers["Content-Type"]="application/json",n.body=JSON.stringify(t.json));let i=await fetch(r,n),o=i.ok&&i.status<=299;if(we.env.AGENT_RUNNERS_DEBUG==="true")H.log(`Response headers for ${r}:`),i.headers.forEach((a,c)=>{H.log(` ${c}: ${a}`)});else{let a=i.headers.get("x-request-id")||i.headers.get("x-nf-request-id");H.log(`Request ID for ${r}: ${a||"N/A"}`)}if(o||H.error(`Got status ${i.status} for request ${r}`),t.raw){if(!o)throw new Error(`API request failed: ${i.status} ${i.statusText}`);return i}let s=await(i.headers.get("content-type")?.includes("application/json")?i.json():i.text());if(!o){let a=typeof s=="string"?s:JSON.stringify(s);throw i.status===404?new se(`API request failed: 404 - ${a}`,404,"The site associated with this agent run no longer exists."):i.status===403&&t.gracefulOn403?new se(`API request failed: 403 - ${a}`,403,"Credit limit reached. Please add more credits to continue using Agent Runners."):new Error(`API request failed: ${i.status} - ${a}`)}return s},It=e=>{H.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(be=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Ne=e.constants.NETLIFY_API_TOKEN)},xt=()=>({apiUrl:be,token:Ne}),Ie=async(e,t)=>Pe()?(H.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):Te(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),Y=async(e,t,r)=>Pe()?(H.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):Te(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var vt=async(e,t)=>Pe()?(H.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):Te(`/api/v1/agent_runners/${e}/sessions/${t}`),Rt=(e,t,r)=>Te(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn403:!0}),St=async(e,t)=>Pe()?(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"}}):Te(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Ke=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 ae=_("ai_gateway"),We=null;var At=async()=>{if(We)return We;ae.log("Fetching available AI gateway providers");let e=await fetch(`${xt().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 We=t,ae.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},vr=async(e,t)=>{let n=(await At()).providers[e];if(!n)return ae.log(`Provider '${e}' not found`),!1;let i=n.models.includes(t);return ae.log(`Model validation for ${e}/${t}`,{isAvailable:i}),i},bt=async({netlify:e,config:t})=>{let r,n,i,o,s=e.constants?.SITE_ID;if(!s)throw new Error("No site id");let a=async()=>{clearTimeout(i),ae.log("Requesting AI gateway information");let c=await Rt(s,t.id,t.sessionId);if({token:r,url:o}=c,n=c.expires_at?c.expires_at*1e3:void 0,ae.log("Got AI gateway information",{token:!!r,expiresAt:n,url:o}),n){let p=n-Date.now()-6e4;p>0&&(i=setTimeout(()=>{a()},p))}};return await Promise.all([a(),At()]),{get url(){return o},get token(){return r},isModelAvailableForProvider:vr}};import K from"process";import X from"path";import Ce from"fs";import{fileURLToPath as Cr}from"url";import{createRequire as Or}from"module";import{execa as kr,execaCommand as Ei}from"execa";import{Transform as Rr}from"stream";var Sr=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_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"]),Ar=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function br(){return Object.entries(process.env).filter(([e,t])=>!(!t||Sr.has(e)||Ar.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function J(e){if(typeof e!="string")return e;let t=br();if(t.length===0)return e;let r=e;return t.forEach(n=>{let i=new RegExp(Nr(n),"g");r=r.replace(i,"******")}),r}function Nr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var le=class extends Rr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,n){let i=t.toString(),o=J(i);n(null,o)}};function Nt(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(n,i,o){let s=typeof n=="string"?J(n):n;return typeof i=="function"?t(s,i):t(s,i,o)},process.stderr.write=function(n,i,o){let s=typeof n=="string"?J(n):n;return typeof i=="function"?r(s,i):r(s,i,o)}}var xe=null,Pt=e=>(xe&&xe.destroy(),xe=new Z({totalAllowedTime:e}),xe),Ct=()=>xe;var Z=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,n)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let i=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),o=null,s=null;n!==void 0&&(s=new Promise((a,c)=>{o=setTimeout(()=>{c(new Error(`${t} stage exceeded its maximum duration of ${n}ms`))},n)}));try{return s?await Promise.race([r(),s]):await r()}finally{i(),o&&clearTimeout(o)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var Ot="netlify-agent-runner-context.md",Ve="task-history",q=".netlify",re="results.md",Je="assets";var ne=1800*1e3;var kt={name:"@netlify/agent-runner-cli",type:"module",version:"1.66.0-alpha.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","dist/skills/**","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.1.32","@google/gemini-cli":"0.25.2","@netlify/otel":"^5.1.1","@openai/codex":"0.93.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.208.0",execa:"^9.6.1",minimist:"^1.2.8"}};var $r=Cr(import.meta.url),Lr=X.dirname($r),Dr=Or(import.meta.url),ce=_("shell"),Xe=new Set,Fr={preferLocal:!0},C=(e,t,r)=>{let[n,i]=Ur(t,r),o={...Fr,...i},s=kr(e,n,o);Mr(s,o),jr(s);let a=r?.idleTimeout;return a&&a>0&&Gr(s,a),s};var Ur=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Mr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(K.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new le).pipe(K.stdout),e.stdout?.pipe(new le).pipe(K.stdout),e.stderr?.pipe(new le).pipe(K.stderr);return}e.stdout?.pipe(K.stdout),e.stderr?.pipe(K.stderr)},ze=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(K.kill(-e.pid,t),ce.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return ce.error("Error killing process:",r),!1}},$t=e=>ze(e,"SIGKILL"),Gr=(e,t)=>{let r=null,n=()=>{ce.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),ze(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ce.log(`Force killing idle process ${e.pid}`),$t(e))},5e3)},i=()=>{r&&clearTimeout(r),r=setTimeout(n,t)};i(),e.stdout?.on("data",i),e.stderr?.on("data",i);let o=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",o),e.on("error",o)},jr=e=>{Xe.add(e);let t=Ct();if(t){let r=t.onTimesUp(()=>{ce.log(`Global timer expired, killing process ${e.pid}`),ze(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ce.log(`Force killing process ${e.pid} after timeout`),$t(e))},5e3)});e.on("exit",()=>{Xe.delete(e),r()}),e.on("error",()=>{Xe.delete(e),r()})}};function Oe(e,t){return!!ie(e,t)}function ie(e,t){if(!K.env.NETLIFY_LOCAL_MODE)try{let i=Dr.resolve(kt.name),o=X.dirname(i);for(;o!==X.dirname(o);){let s=X.dirname(o);if(X.basename(s)==="node_modules"){let a=X.join(s,".bin",t);if(Ce.existsSync(a))return a;break}o=s}}catch(i){console.error("Could not resolve package.json",i)}if(K.env.NODE_PATH){let i=X.join(K.env.NODE_PATH,".bin",t);if(Ce.existsSync(i))return i}let r=X.join(e,"node_modules",".bin",t);if(Ce.existsSync(r))return r;let n=X.join(Lr,"..","node_modules",".bin",t);if(Ce.existsSync(n))return n}var Yr=_("utils"),Br=e=>new Promise(t=>{setTimeout(t,e)}),Lt=(e,t=3e3)=>{let r=!1,n=null,i=[],o=null,s=(...a)=>{if(r)return n=a,new Promise(d=>{i.push(d)});r=!0;let c,p=new Promise(d=>{c=d});return o=(async()=>{await Promise.resolve();let d=await e(...a);for(c(d);;){if(await Br(t),!n)return r=!1,o=null,d;let u=n,m=i;n=null,i=[],d=await e(...u),m.forEach(g=>{g(d)})}})(),p};return s.flush=async()=>{if((r||n)&&o)return await o,s.flush()},s},ue=(e,t,r=!1)=>{let n=null,i=null,o=null,s=function(...a){i=a,o=this;let c=r&&!n;clearTimeout(n),n=setTimeout(()=>{n=null,r||(e.apply(o,i),i=null,o=null)},t),c&&(e.apply(o,i),i=null,o=null)};return s.cancel=()=>{clearTimeout(n),n=null,i=null,o=null},s.flush=()=>{if(n){clearTimeout(n);let a=i,c=o;n=null,i=null,o=null,e.apply(c,a)}},s},Dt=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(n){t&&(r?.error?r.error("Could not parse JSON",n):Yr.error("Could not parse JSON",n))}},Ft=(e,t)=>{let i=".netlify.app",o="agent-";if(!t)return`${o}${e.slice(0,6)}`;let a=`--${t}${i}`;if(a.length>55)return"";let c=60-a.length;if(c<=0)return"";if(c>=o.length+6){let p=Math.min(c-o.length,e.length);return`${o}${e.slice(0,p)}`}return e.slice(0,c)};var Hr=50*1024,Ze=(e,t=Hr)=>{if(!e||typeof e!="string"||e.length<=t)return e;let n=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+n};import{Buffer as Ut}from"buffer";import qr from"path";var Mt=_("repo"),Gt=async({config:e,isRetry:t})=>{Mt.info("Getting runner diffs");let r=await Wr(),{hasChanges:n}=r,{status:i}=r;if(!n)return{hasChanges:!1};if(!t){let y=Vr(i);await Jr(y)}Mt.info("Changes after processing"),await et();let o=await tt(i);await Qe(o);let s={stdio:["ignore","pipe","pipe"]},a=await C("git",["diff","--staged"],s),c=String(a.stdout??"");if(n=!!c,!n)return{hasChanges:!1,ignored:o};let p=await C("git",["diff","--staged","--binary"],s),d=String(p.stdout??""),u,m;if(e.sha){if(!process.env.NETLIFY_LOCAL_MODE){process.env.NETLIFY_INTERNAL_GIT="1";try{await C("git",["commit","-m","Agent runner"])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}}let y=await C("git",["diff",e.sha,"HEAD"],s);u=String(y.stdout??"");let w=await C("git",["diff",e.sha,"HEAD","--binary"],s),E=String(w.stdout??"");u!==E&&(m=Ut.from(E).toString("base64"))}let g={hasChanges:!0,diff:c,resultDiff:u,ignored:o};return c!==d&&(g.diffBinary=Ut.from(d).toString("base64")),m&&(g.resultDiffBinary=m),g},Qe=async(e=[])=>{process.env.NETLIFY_INTERNAL_GIT="1";try{await C("git",["add",".",...e])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}},et=async()=>{let e=await C("git",["status","-s"]);return String(e.stdout??"")},jt=/.. (.+)?\.log$/,Kr=[jt],Wr=async()=>{let e=await et();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
8
|
+
`);return o.length>e.length*.8?e:o}import{execSync as pn}from"child_process";import tr from"fs/promises";import fn from"path";import Q from"process";import{getTracer as mn}from"@netlify/otel";import we from"process";var se=class extends Error{constructor(r,n,i){super(r);this.statusCode=n;this.userMessage=i;this.name="GracefulShutdownError"}},Tt=e=>e instanceof se;var be=we.env.NETLIFY_API_URL,Ne=we.env.NETLIFY_API_TOKEN,H=_("api"),Pe=()=>we.env.NETLIFY_LOCAL_MODE==="true",Te=async(e,t={})=>{if(!be||!Ne)throw new Error("No API URL or token");let r=new URL(e,be),n={...t,headers:{...t.headers,Authorization:`Bearer ${Ne}`}};we.env.AGENT_RUNNERS_DEBUG==="true"&&(n.headers["x-nf-debug-logging"]="true"),t.json&&(n.headers||={},n.headers["Content-Type"]="application/json",n.body=JSON.stringify(t.json));let i=await fetch(r,n),o=i.ok&&i.status<=299;if(we.env.AGENT_RUNNERS_DEBUG==="true")H.log(`Response headers for ${r}:`),i.headers.forEach((a,c)=>{H.log(` ${c}: ${a}`)});else{let a=i.headers.get("x-request-id")||i.headers.get("x-nf-request-id");H.log(`Request ID for ${r}: ${a||"N/A"}`)}if(o||H.error(`Got status ${i.status} for request ${r}`),t.raw){if(!o)throw new Error(`API request failed: ${i.status} ${i.statusText}`);return i}let s=await(i.headers.get("content-type")?.includes("application/json")?i.json():i.text());if(!o){let a=typeof s=="string"?s:JSON.stringify(s);throw i.status===404?new se(`API request failed: 404 - ${a}`,404,"The site associated with this agent run no longer exists."):i.status===403&&t.gracefulOn403?new se(`API request failed: 403 - ${a}`,403,"Credit limit reached. Please add more credits to continue using Agent Runners."):new Error(`API request failed: ${i.status} - ${a}`)}return s},It=e=>{H.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(be=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Ne=e.constants.NETLIFY_API_TOKEN)},xt=()=>({apiUrl:be,token:Ne}),Ie=async(e,t)=>Pe()?(H.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):Te(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),Y=async(e,t,r)=>Pe()?(H.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):Te(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var vt=async(e,t)=>Pe()?(H.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):Te(`/api/v1/agent_runners/${e}/sessions/${t}`),Rt=(e,t,r)=>Te(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn403:!0}),St=async(e,t)=>Pe()?(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"}}):Te(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Ke=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 ae=_("ai_gateway"),We=null;var At=async()=>{if(We)return We;ae.log("Fetching available AI gateway providers");let e=await fetch(`${xt().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 We=t,ae.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},vr=async(e,t)=>{let n=(await At()).providers[e];if(!n)return ae.log(`Provider '${e}' not found`),!1;let i=n.models.includes(t);return ae.log(`Model validation for ${e}/${t}`,{isAvailable:i}),i},bt=async({netlify:e,config:t})=>{let r,n,i,o,s=e.constants?.SITE_ID;if(!s)throw new Error("No site id");let a=async()=>{clearTimeout(i),ae.log("Requesting AI gateway information");let c=await Rt(s,t.id,t.sessionId);if({token:r,url:o}=c,n=c.expires_at?c.expires_at*1e3:void 0,ae.log("Got AI gateway information",{token:!!r,expiresAt:n,url:o}),n){let p=n-Date.now()-6e4;p>0&&(i=setTimeout(()=>{a()},p))}};return await Promise.all([a(),At()]),{get url(){return o},get token(){return r},isModelAvailableForProvider:vr}};import K from"process";import X from"path";import Ce from"fs";import{fileURLToPath as Cr}from"url";import{createRequire as Or}from"module";import{execa as kr,execaCommand as Ei}from"execa";import{Transform as Rr}from"stream";var Sr=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_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"]),Ar=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function br(){return Object.entries(process.env).filter(([e,t])=>!(!t||Sr.has(e)||Ar.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function J(e){if(typeof e!="string")return e;let t=br();if(t.length===0)return e;let r=e;return t.forEach(n=>{let i=new RegExp(Nr(n),"g");r=r.replace(i,"******")}),r}function Nr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var le=class extends Rr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,n){let i=t.toString(),o=J(i);n(null,o)}};function Nt(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(n,i,o){let s=typeof n=="string"?J(n):n;return typeof i=="function"?t(s,i):t(s,i,o)},process.stderr.write=function(n,i,o){let s=typeof n=="string"?J(n):n;return typeof i=="function"?r(s,i):r(s,i,o)}}var xe=null,Pt=e=>(xe&&xe.destroy(),xe=new Z({totalAllowedTime:e}),xe),Ct=()=>xe;var Z=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,n)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let i=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),o=null,s=null;n!==void 0&&(s=new Promise((a,c)=>{o=setTimeout(()=>{c(new Error(`${t} stage exceeded its maximum duration of ${n}ms`))},n)}));try{return s?await Promise.race([r(),s]):await r()}finally{i(),o&&clearTimeout(o)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var Ot="netlify-agent-runner-context.md",Ve="task-history",q=".netlify",re="results.md",Je="assets";var ne=1800*1e3;var kt={name:"@netlify/agent-runner-cli",type:"module",version:"1.66.0-alpha.1",description:"CLI tool for running Netlify agents",main:"./dist/index.js",types:"./dist/index.d.ts",exports:"./dist/index.js",bin:{"agent-runner-cli":"./dist/bin.js","agent-runner-cli-local":"./dist/bin-local.js"},files:["dist/**/*.js","dist/**/*.d.ts","dist/skills/**","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.1.32","@google/gemini-cli":"0.25.2","@netlify/otel":"^5.1.1","@openai/codex":"0.93.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.208.0",execa:"^9.6.1",minimist:"^1.2.8"}};var $r=Cr(import.meta.url),Lr=X.dirname($r),Dr=Or(import.meta.url),ce=_("shell"),Xe=new Set,Fr={preferLocal:!0},C=(e,t,r)=>{let[n,i]=Ur(t,r),o={...Fr,...i},s=kr(e,n,o);Mr(s,o),jr(s);let a=r?.idleTimeout;return a&&a>0&&Gr(s,a),s};var Ur=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Mr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(K.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new le).pipe(K.stdout),e.stdout?.pipe(new le).pipe(K.stdout),e.stderr?.pipe(new le).pipe(K.stderr);return}e.stdout?.pipe(K.stdout),e.stderr?.pipe(K.stderr)},ze=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(K.kill(-e.pid,t),ce.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return ce.error("Error killing process:",r),!1}},$t=e=>ze(e,"SIGKILL"),Gr=(e,t)=>{let r=null,n=()=>{ce.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),ze(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ce.log(`Force killing idle process ${e.pid}`),$t(e))},5e3)},i=()=>{r&&clearTimeout(r),r=setTimeout(n,t)};i(),e.stdout?.on("data",i),e.stderr?.on("data",i);let o=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",o),e.on("error",o)},jr=e=>{Xe.add(e);let t=Ct();if(t){let r=t.onTimesUp(()=>{ce.log(`Global timer expired, killing process ${e.pid}`),ze(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ce.log(`Force killing process ${e.pid} after timeout`),$t(e))},5e3)});e.on("exit",()=>{Xe.delete(e),r()}),e.on("error",()=>{Xe.delete(e),r()})}};function Oe(e,t){return!!ie(e,t)}function ie(e,t){if(!K.env.NETLIFY_LOCAL_MODE)try{let i=Dr.resolve(kt.name),o=X.dirname(i);for(;o!==X.dirname(o);){let s=X.dirname(o);if(X.basename(s)==="node_modules"){let a=X.join(s,".bin",t);if(Ce.existsSync(a))return a;break}o=s}}catch(i){console.error("Could not resolve package.json",i)}if(K.env.NODE_PATH){let i=X.join(K.env.NODE_PATH,".bin",t);if(Ce.existsSync(i))return i}let r=X.join(e,"node_modules",".bin",t);if(Ce.existsSync(r))return r;let n=X.join(Lr,"..","node_modules",".bin",t);if(Ce.existsSync(n))return n}var Yr=_("utils"),Br=e=>new Promise(t=>{setTimeout(t,e)}),Lt=(e,t=3e3)=>{let r=!1,n=null,i=[],o=null,s=(...a)=>{if(r)return n=a,new Promise(d=>{i.push(d)});r=!0;let c,p=new Promise(d=>{c=d});return o=(async()=>{await Promise.resolve();let d=await e(...a);for(c(d);;){if(await Br(t),!n)return r=!1,o=null,d;let u=n,m=i;n=null,i=[],d=await e(...u),m.forEach(g=>{g(d)})}})(),p};return s.flush=async()=>{if((r||n)&&o)return await o,s.flush()},s},ue=(e,t,r=!1)=>{let n=null,i=null,o=null,s=function(...a){i=a,o=this;let c=r&&!n;clearTimeout(n),n=setTimeout(()=>{n=null,r||(e.apply(o,i),i=null,o=null)},t),c&&(e.apply(o,i),i=null,o=null)};return s.cancel=()=>{clearTimeout(n),n=null,i=null,o=null},s.flush=()=>{if(n){clearTimeout(n);let a=i,c=o;n=null,i=null,o=null,e.apply(c,a)}},s},Dt=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(n){t&&(r?.error?r.error("Could not parse JSON",n):Yr.error("Could not parse JSON",n))}},Ft=(e,t)=>{let i=".netlify.app",o="agent-";if(!t)return`${o}${e.slice(0,6)}`;let a=`--${t}${i}`;if(a.length>55)return"";let c=60-a.length;if(c<=0)return"";if(c>=o.length+6){let p=Math.min(c-o.length,e.length);return`${o}${e.slice(0,p)}`}return e.slice(0,c)};var Hr=50*1024,Ze=(e,t=Hr)=>{if(!e||typeof e!="string"||e.length<=t)return e;let n=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+n};import{Buffer as Ut}from"buffer";import qr from"path";var Mt=_("repo"),Gt=async({config:e,isRetry:t})=>{Mt.info("Getting runner diffs");let r=await Wr(),{hasChanges:n}=r,{status:i}=r;if(!n)return{hasChanges:!1};if(!t){let y=Vr(i);await Jr(y)}Mt.info("Changes after processing"),await et();let o=await tt(i);await Qe(o);let s={stdio:["ignore","pipe","pipe"]},a=await C("git",["diff","--staged"],s),c=String(a.stdout??"");if(n=!!c,!n)return{hasChanges:!1,ignored:o};let p=await C("git",["diff","--staged","--binary"],s),d=String(p.stdout??""),u,m;if(e.sha){if(!process.env.NETLIFY_LOCAL_MODE){process.env.NETLIFY_INTERNAL_GIT="1";try{await C("git",["commit","-m","Agent runner"])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}}let y=await C("git",["diff",e.sha,"HEAD"],s);u=String(y.stdout??"");let w=await C("git",["diff",e.sha,"HEAD","--binary"],s),E=String(w.stdout??"");u!==E&&(m=Ut.from(E).toString("base64"))}let g={hasChanges:!0,diff:c,resultDiff:u,ignored:o};return c!==d&&(g.diffBinary=Ut.from(d).toString("base64")),m&&(g.resultDiffBinary=m),g},Qe=async(e=[])=>{process.env.NETLIFY_INTERNAL_GIT="1";try{await C("git",["add",".",...e])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}},et=async()=>{let e=await C("git",["status","-s"]);return String(e.stdout??"")},jt=/.. (.+)?\.log$/,Kr=[jt],Wr=async()=>{let e=await et();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
9
9
|
`).filter(n=>Kr.some(o=>o instanceof RegExp?o.test(n):n===o)?!1:n[1]?.trim()!=="")).length!==0,status:e}},Yt=async()=>{let{stdout:e}=await C("git",["rev-parse","HEAD"]);return String(e??"").trim()},Bt=async()=>{let{stdout:e}=await C("git",["rev-list","--max-parents=0","HEAD"]);return String(e??"").trim()},tt=async e=>{e||=await et();let t=[".netlify","node_modules","dist",".next","out",".nuxt",".output",".cache",".turbo",".parcel-cache","coverage",".nyc_output","storybook-static","public/build"],r=[];return e.split(`
|
|
10
10
|
`).forEach(n=>{t.forEach(o=>{let s=n===`?? ${o}`,a=n.startsWith(`?? ${o}/`)||n.startsWith(`?? ${o}${qr.sep}`);(s||a)&&r.push(`:!${o}`)});let i=n.match(jt)?.[1];i&&r.push(`:!${i}.log`)}),r},rt=async()=>{await C("git",["reset","--hard","HEAD"])},Vr=e=>{let t=e.split(`
|
|
11
11
|
`).reduce((r,n)=>{if(!n)return r;let[i,o,,...s]=n,a=s.join(""),c=i.trim(),p=o.trim();return r[a]?r[a].change=p:r[a]={filePath:a,stage:c,change:p},r},{});return Object.values(t)},Jr=async e=>{let t=[];for(let r of e)r.stage&&!r.change&&t.push(C("git",["restore","--staged","--worktree",r.filePath]));await Promise.allSettled(t)};import zr from"fs/promises";import Zr from"os";import Kt from"path";import me from"process";import Qr from"readline";import nt from"path";import Xr from"fs/promises";var it=_("agent-output-utils");async function de({initialResult:e,agentName:t,hasError:r}){let n="",i=nt.join(process.cwd(),q,re);try{let o=await Xr.readFile(i,"utf-8");o&&(n=o,it.log(`Pulled result from ${nt.relative(process.cwd(),i)}`))}catch{it.log(`No results file found at ${nt.relative(process.cwd(),i)}`)}return n||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function pe({error:e,agentName:t}){let r=e&&typeof e=="object"?JSON.stringify(e):e,n=r?.replace(/\s+/g," ").trim().toLowerCase()||"",i="";return n?.includes("ai gateway is not available for your account")||n?.includes("ai gateway is not enabled for your account")?i="AI Gateway is currently not available on your account. Please confirm your account meets the criteria for using Agent Runners and AI Gateway and that your account has remaining AI Gateway inference credits available. Reach out to Netlify support if this is unexpected.":n?.includes("error when talking to gemini api")?i="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":(n?.includes("connection closed prematurely")||n?.includes("499")&&t.toLowerCase().includes("gemini"))&&(i=`The ${t} models were currently overloaded. Please try again or use a different available agent.`),n?.includes("request timed out")&&(i=`The ${t} API request's have timed out. Please try again or use a different available agent.`),n?.includes("network error")&&(i=`The ${t} agent is having network issues. Please try again or use a different available agent.`),n?.includes("503")&&(i=`The ${t} API is currently experiencing high load. Retrying automatically...`),i&&it.log(`Providing updated error messsage: ${i}, replacing original error: ${r}`),i||r||void 0}function fe(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")||r?.includes("503"))}var M=_("runner_claude"),Ht="Claude Code",ge="claude-opus-4-6",qt=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,en=({catchError:e,runCmd:t,error:r,result:n,runnerName:i})=>(M.log(`${i} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(M.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(M.log("Setting result to undefined because no valid result was captured"),{error:r||`${i} failed`,result:void 0}));async function ot({config:e,netlify:t,persistSteps:r,aiGateway:n,continueSession:i,priorAgentSessionId:o,cwd:s=me.cwd()}){let a=e,{accountType:c,prompt:p,modelVersionOverrides:d}=a,{model:u}=a,m="";if(n){let{token:h,url:f}=n;if(!h||!f)throw new Error("No token or url provided from AI Gateway");if(d?.claude){let l=d?.claude?.[c];if(l){if(!await n.isModelAvailableForProvider("anthropic",l))throw new Error(`Model override '${l}' is not available for anthropic provider`);u=l}}else if(u){if(!await n.isModelAvailableForProvider("anthropic",u))throw new Error(`Model '${u}' is not available for anthropic provider`)}else!!ge&&await n.isModelAvailableForProvider("anthropic",ge)?(u=ge,M.log(`Using default model: ${ge}`)):ge&&M.log(`Default model ${ge} is not available, proceeding without model specification`);me.env.ANTHROPIC_API_KEY=h,me.env.ANTHROPIC_BASE_URL=f}else if(!me.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let g=[],y=[],w={},E=0,I=0,b,S,D=[ie(s,"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose","--disallowed-tools","ExitPlanMode,AskUserQuestion",...u?["--model",u]:[],...i?["--continue"]:[],...i&&o?["--resume",o]:[],"-p",p],k=`${me.env.NVM_BIN}/node`;M.log(`Running ${k} ${D.join(" ")}`);let F=t.utils.run(k,D,{all:!0,env:me.env,cwd:s,idleTimeout:ne});F.stdin?.end();let x=ue(()=>{r?.({steps:g,duration:I})},250),v=(h,f)=>{let l={...h,id:E};E+=1,y.push(l),g.push(l),f||x.flush(),x(),f&&x.flush()},U=Qr.createInterface({input:F.all});return U.on("error",h=>{M.error("Readline interface error",{error:h.message,stack:h.stack})}),U.on("line",h=>{let f=null;try{f=JSON.parse(h)}catch{M.log("Could not parse line",h)}f?.session_id&&f.session_id!==m&&(m=f.session_id),Array.isArray(f?.message?.content)?f.message.content.forEach(l=>{switch(l.type){case"text":{l.text&&v({message:l.text});break}case"image":{typeof l.source=="object"&&l.source&&l.source.type==="base64"&&l.source.media_type?v({message:``}):M.log(`Unsupported image type ${l.source?.type}`,l.source);break}case"tool_use":{if(l.name==="Task"){let T=l.input?.description&&`\`${l.input.description}\``;v({title:[qt(l.name),T].filter(Boolean).join(" ")})}else l.id&&(w[l.id]=l);x.flush();break}case"tool_result":{let T=l.tool_use_id?w[l.tool_use_id]:void 0,ee;if(T){let z=T.input?.file_path&&Kt.relative(s,T.input.file_path),$=z&&`\`${z}\``;ee=[qt(T.name||""),$].filter(Boolean).join(" ")}let Ae=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(T?.name||""),te;if(typeof l.content=="string")te=l.content;else if(Array.isArray(l.content)){let z=[];l.content.forEach($=>{$?.type==="text"&&typeof $.text=="string"?z.push($.text):$?.type==="image"&&typeof $.source=="object"&&$.source?$.source.type==="base64"&&$.source.media_type?z.push(``):M.log(`Unsupported image type ${$.source.type}`,$.source):M.log(`Unsupported block type ${$?.type}`)}),te=z.join(`
|
package/dist/bin.js
CHANGED
|
@@ -5,7 +5,7 @@ import yt from"process";import Zn from"minimist";import{createRequire as Yn}from
|
|
|
5
5
|
${s}
|
|
6
6
|
</extracted_error_chunk>`).join(`
|
|
7
7
|
|
|
8
|
-
`);return i.length>e.length*.8?e:i}import{execSync as En}from"child_process";import ar from"fs/promises";import _n from"path";import z from"process";import{getTracer as Tn}from"@netlify/otel";import _e from"process";var ne=class extends Error{constructor(r,n,o){super(r);this.statusCode=n;this.userMessage=o;this.name="GracefulShutdownError"}},xt=e=>e instanceof ne;var Ae=_e.env.NETLIFY_API_URL,Ne=_e.env.NETLIFY_API_TOKEN,B=_("api"),be=()=>_e.env.NETLIFY_LOCAL_MODE==="true",Te=async(e,t={})=>{if(!Ae||!Ne)throw new Error("No API URL or token");let r=new URL(e,Ae),n={...t,headers:{...t.headers,Authorization:`Bearer ${Ne}`}};_e.env.AGENT_RUNNERS_DEBUG==="true"&&(n.headers["x-nf-debug-logging"]="true"),t.json&&(n.headers||={},n.headers["Content-Type"]="application/json",n.body=JSON.stringify(t.json));let o=await fetch(r,n),i=o.ok&&o.status<=299;if(_e.env.AGENT_RUNNERS_DEBUG==="true")B.log(`Response headers for ${r}:`),o.headers.forEach((a,c)=>{B.log(` ${c}: ${a}`)});else{let a=o.headers.get("x-request-id")||o.headers.get("x-nf-request-id");B.log(`Request ID for ${r}: ${a||"N/A"}`)}if(i||B.error(`Got status ${o.status} for request ${r}`),t.raw){if(!i)throw new Error(`API request failed: ${o.status} ${o.statusText}`);return o}let s=await(o.headers.get("content-type")?.includes("application/json")?o.json():o.text());if(!i){let a=typeof s=="string"?s:JSON.stringify(s);throw o.status===404?new ne(`API request failed: 404 - ${a}`,404,"The site associated with this agent run no longer exists."):o.status===403&&t.gracefulOn403?new ne(`API request failed: 403 - ${a}`,403,"Credit limit reached. Please add more credits to continue using Agent Runners."):new Error(`API request failed: ${o.status} - ${a}`)}return s},Rt=e=>{B.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Ae=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Ne=e.constants.NETLIFY_API_TOKEN)},vt=()=>({apiUrl:Ae,token:Ne}),we=async(e,t)=>be()?(B.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):Te(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),G=async(e,t,r)=>be()?(B.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):Te(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var St=async(e,t)=>be()?(B.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):Te(`/api/v1/agent_runners/${e}/sessions/${t}`),At=(e,t,r)=>Te(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn403:!0}),Nt=async(e,t)=>be()?(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"}}):Te(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),qe=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 oe=_("ai_gateway"),We=null;var bt=async()=>{if(We)return We;oe.log("Fetching available AI gateway providers");let e=await fetch(`${vt().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 We=t,oe.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},Cr=async(e,t)=>{let n=(await bt()).providers[e];if(!n)return oe.log(`Provider '${e}' not found`),!1;let o=n.models.includes(t);return oe.log(`Model validation for ${e}/${t}`,{isAvailable:o}),o},Ct=async({netlify:e,config:t})=>{let r,n,o,i,s=e.constants?.SITE_ID;if(!s)throw new Error("No site id");let a=async()=>{clearTimeout(o),oe.log("Requesting AI gateway information");let c=await At(s,t.id,t.sessionId);if({token:r,url:i}=c,n=c.expires_at?c.expires_at*1e3:void 0,oe.log("Got AI gateway information",{token:!!r,expiresAt:n,url:i}),n){let d=n-Date.now()-6e4;d>0&&(o=setTimeout(()=>{a()},d))}};return await Promise.all([a(),bt()]),{get url(){return i},get token(){return r},isModelAvailableForProvider:Cr}};import q from"process";import V from"path";import Ce from"fs";import{fileURLToPath as $r}from"url";import{createRequire as Ur}from"module";import{execa as Mr,execaCommand as Po}from"execa";import{Transform as Pr}from"stream";var Or=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_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"]),kr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function Fr(){return Object.entries(process.env).filter(([e,t])=>!(!t||Or.has(e)||kr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function K(e){if(typeof e!="string")return e;let t=Fr();if(t.length===0)return e;let r=e;return t.forEach(n=>{let o=new RegExp(Lr(n),"g");r=r.replace(o,"******")}),r}function Lr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ie=class extends Pr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,n){let o=t.toString(),i=K(o);n(null,i)}};function Pt(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(n,o,i){let s=typeof n=="string"?K(n):n;return typeof o=="function"?t(s,o):t(s,o,i)},process.stderr.write=function(n,o,i){let s=typeof n=="string"?K(n):n;return typeof o=="function"?r(s,o):r(s,o,i)}}var Ie=null,Ot=e=>(Ie&&Ie.destroy(),Ie=new X({totalAllowedTime:e}),Ie),kt=()=>Ie;var X=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,n)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let o=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),i=null,s=null;n!==void 0&&(s=new Promise((a,c)=>{i=setTimeout(()=>{c(new Error(`${t} stage exceeded its maximum duration of ${n}ms`))},n)}));try{return s?await Promise.race([r(),s]):await r()}finally{o(),i&&clearTimeout(i)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var Ft="netlify-agent-runner-context.md",Ke="task-history",H=".netlify",ee="results.md",Ve="assets",Je="other",Xe="personal";var ze="enterprise",Ze="free",Lt=[Xe,"pro",ze,Ze],Dt=["normal","redeploy","create","ask","dtn-prod-iteration","rebase"],$t="The production deploy has changed since you started working. Please reapply the changes to the current codebase, resolving any conflicts that arise. Use the attached diff file if present, otherwise review the previous session context to reproduce the changes.",te=1800*1e3;var Ut={name:"@netlify/agent-runner-cli",type:"module",version:"1.66.0-alpha.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","dist/skills/**","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.1.32","@google/gemini-cli":"0.25.2","@netlify/otel":"^5.1.1","@openai/codex":"0.93.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.208.0",execa:"^9.6.1",minimist:"^1.2.8"}};var Gr=$r(import.meta.url),jr=V.dirname(Gr),Yr=Ur(import.meta.url),se=_("shell"),Qe=new Set,Br={preferLocal:!0},L=(e,t,r)=>{let[n,o]=Hr(t,r),i={...Br,...o},s=Mr(e,n,i);qr(s,i),Kr(s);let a=r?.idleTimeout;return a&&a>0&&Wr(s,a),s};var Hr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},qr=(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)},et=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(q.kill(-e.pid,t),se.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return se.error("Error killing process:",r),!1}},Mt=e=>et(e,"SIGKILL"),Wr=(e,t)=>{let r=null,n=()=>{se.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),et(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(se.log(`Force killing idle process ${e.pid}`),Mt(e))},5e3)},o=()=>{r&&clearTimeout(r),r=setTimeout(n,t)};o(),e.stdout?.on("data",o),e.stderr?.on("data",o);let i=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",i),e.on("error",i)},Kr=e=>{Qe.add(e);let t=kt();if(t){let r=t.onTimesUp(()=>{se.log(`Global timer expired, killing process ${e.pid}`),et(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(se.log(`Force killing process ${e.pid} after timeout`),Mt(e))},5e3)});e.on("exit",()=>{Qe.delete(e),r()}),e.on("error",()=>{Qe.delete(e),r()})}};function ae(e,t){if(!q.env.NETLIFY_LOCAL_MODE)try{let o=Yr.resolve(Ut.name),i=V.dirname(o);for(;i!==V.dirname(i);){let s=V.dirname(i);if(V.basename(s)==="node_modules"){let a=V.join(s,".bin",t);if(Ce.existsSync(a))return a;break}i=s}}catch(o){console.error("Could not resolve package.json",o)}if(q.env.NODE_PATH){let o=V.join(q.env.NODE_PATH,".bin",t);if(Ce.existsSync(o))return o}let r=V.join(e,"node_modules",".bin",t);if(Ce.existsSync(r))return r;let n=V.join(jr,"..","node_modules",".bin",t);if(Ce.existsSync(n))return n}var Gt=_("utils"),Vr=e=>new Promise(t=>{setTimeout(t,e)}),jt=(e,t=3e3)=>{let r=!1,n=null,o=[],i=null,s=(...a)=>{if(r)return n=a,new Promise(p=>{o.push(p)});r=!0;let c,d=new Promise(p=>{c=p});return i=(async()=>{await Promise.resolve();let p=await e(...a);for(c(p);;){if(await Vr(t),!n)return r=!1,i=null,p;let u=n,m=o;n=null,o=[],p=await e(...u),m.forEach(g=>{g(p)})}})(),d};return s.flush=async()=>{if((r||n)&&i)return await i,s.flush()},s},le=(e,t,r=!1)=>{let n=null,o=null,i=null,s=function(...a){o=a,i=this;let c=r&&!n;clearTimeout(n),n=setTimeout(()=>{n=null,r||(e.apply(i,o),o=null,i=null)},t),c&&(e.apply(i,o),o=null,i=null)};return s.cancel=()=>{clearTimeout(n),n=null,o=null,i=null},s.flush=()=>{if(n){clearTimeout(n);let a=o,c=i;n=null,o=null,i=null,e.apply(c,a)}},s},Pe=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(n){t&&(r?.error?r.error("Could not parse JSON",n):Gt.error("Could not parse JSON",n))}},Yt=(e,t)=>{let o=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let a=`--${t}${o}`;if(a.length>55)return"";let c=60-a.length;if(c<=0)return"";if(c>=i.length+6){let d=Math.min(c-i.length,e.length);return`${i}${e.slice(0,d)}`}return e.slice(0,c)},Jr=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!Lt.some(t=>t in e),Bt=()=>{let e={},t={codex:process.env.NETLIFY_FF_AGENT_RUNNER_CODEX_VERSION,claude:process.env.NETLIFY_FF_AGENT_RUNNER_CLAUDE_VERSION,gemini:process.env.NETLIFY_FF_AGENT_RUNNER_GEMINI_VERSION};return Object.entries(t).forEach(([r,n])=>{if(n){let o=`NETLIFY_FF_AGENT_RUNNER_${r.toUpperCase()}_VERSION`;try{let i=JSON.parse(n);Jr(i)&&(e[r]=i)}catch(i){let a=i instanceof SyntaxError?"Invalid JSON":i.message;Gt.error(`Could not parse ${r} model version override from ${o}: ${a}`)}}}),e},Xr=50*1024,tt=(e,t=Xr)=>{if(!e||typeof e!="string"||e.length<=t)return e;let n=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+n};import{Buffer as Ht}from"buffer";import zr from"path";var qt=_("repo"),Wt=async({config:e,isRetry:t})=>{qt.info("Getting runner diffs");let r=await Qr(),{hasChanges:n}=r,{status:o}=r;if(!n)return{hasChanges:!1};if(!t){let E=en(o);await tn(E)}qt.info("Changes after processing"),await nt();let i=await ot(o);await rt(i);let s={stdio:["ignore","pipe","pipe"]},a=await L("git",["diff","--staged"],s),c=String(a.stdout??"");if(n=!!c,!n)return{hasChanges:!1,ignored:i};let d=await L("git",["diff","--staged","--binary"],s),p=String(d.stdout??""),u,m;if(e.sha){if(!process.env.NETLIFY_LOCAL_MODE){process.env.NETLIFY_INTERNAL_GIT="1";try{await L("git",["commit","-m","Agent runner"])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}}let E=await L("git",["diff",e.sha,"HEAD"],s);u=String(E.stdout??"");let T=await L("git",["diff",e.sha,"HEAD","--binary"],s),h=String(T.stdout??"");u!==h&&(m=Ht.from(h).toString("base64"))}let g={hasChanges:!0,diff:c,resultDiff:u,ignored:i};return c!==p&&(g.diffBinary=Ht.from(p).toString("base64")),m&&(g.resultDiffBinary=m),g},rt=async(e=[])=>{process.env.NETLIFY_INTERNAL_GIT="1";try{await L("git",["add",".",...e])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}},nt=async()=>{let e=await L("git",["status","-s"]);return String(e.stdout??"")},Kt=/.. (.+)?\.log$/,Zr=[Kt],Qr=async()=>{let e=await nt();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
8
|
+
`);return i.length>e.length*.8?e:i}import{execSync as En}from"child_process";import ar from"fs/promises";import _n from"path";import z from"process";import{getTracer as Tn}from"@netlify/otel";import _e from"process";var ne=class extends Error{constructor(r,n,o){super(r);this.statusCode=n;this.userMessage=o;this.name="GracefulShutdownError"}},xt=e=>e instanceof ne;var Ae=_e.env.NETLIFY_API_URL,Ne=_e.env.NETLIFY_API_TOKEN,B=_("api"),be=()=>_e.env.NETLIFY_LOCAL_MODE==="true",Te=async(e,t={})=>{if(!Ae||!Ne)throw new Error("No API URL or token");let r=new URL(e,Ae),n={...t,headers:{...t.headers,Authorization:`Bearer ${Ne}`}};_e.env.AGENT_RUNNERS_DEBUG==="true"&&(n.headers["x-nf-debug-logging"]="true"),t.json&&(n.headers||={},n.headers["Content-Type"]="application/json",n.body=JSON.stringify(t.json));let o=await fetch(r,n),i=o.ok&&o.status<=299;if(_e.env.AGENT_RUNNERS_DEBUG==="true")B.log(`Response headers for ${r}:`),o.headers.forEach((a,c)=>{B.log(` ${c}: ${a}`)});else{let a=o.headers.get("x-request-id")||o.headers.get("x-nf-request-id");B.log(`Request ID for ${r}: ${a||"N/A"}`)}if(i||B.error(`Got status ${o.status} for request ${r}`),t.raw){if(!i)throw new Error(`API request failed: ${o.status} ${o.statusText}`);return o}let s=await(o.headers.get("content-type")?.includes("application/json")?o.json():o.text());if(!i){let a=typeof s=="string"?s:JSON.stringify(s);throw o.status===404?new ne(`API request failed: 404 - ${a}`,404,"The site associated with this agent run no longer exists."):o.status===403&&t.gracefulOn403?new ne(`API request failed: 403 - ${a}`,403,"Credit limit reached. Please add more credits to continue using Agent Runners."):new Error(`API request failed: ${o.status} - ${a}`)}return s},Rt=e=>{B.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Ae=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Ne=e.constants.NETLIFY_API_TOKEN)},vt=()=>({apiUrl:Ae,token:Ne}),we=async(e,t)=>be()?(B.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):Te(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),G=async(e,t,r)=>be()?(B.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):Te(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var St=async(e,t)=>be()?(B.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):Te(`/api/v1/agent_runners/${e}/sessions/${t}`),At=(e,t,r)=>Te(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn403:!0}),Nt=async(e,t)=>be()?(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"}}):Te(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),qe=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 oe=_("ai_gateway"),We=null;var bt=async()=>{if(We)return We;oe.log("Fetching available AI gateway providers");let e=await fetch(`${vt().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 We=t,oe.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},Cr=async(e,t)=>{let n=(await bt()).providers[e];if(!n)return oe.log(`Provider '${e}' not found`),!1;let o=n.models.includes(t);return oe.log(`Model validation for ${e}/${t}`,{isAvailable:o}),o},Ct=async({netlify:e,config:t})=>{let r,n,o,i,s=e.constants?.SITE_ID;if(!s)throw new Error("No site id");let a=async()=>{clearTimeout(o),oe.log("Requesting AI gateway information");let c=await At(s,t.id,t.sessionId);if({token:r,url:i}=c,n=c.expires_at?c.expires_at*1e3:void 0,oe.log("Got AI gateway information",{token:!!r,expiresAt:n,url:i}),n){let d=n-Date.now()-6e4;d>0&&(o=setTimeout(()=>{a()},d))}};return await Promise.all([a(),bt()]),{get url(){return i},get token(){return r},isModelAvailableForProvider:Cr}};import q from"process";import V from"path";import Ce from"fs";import{fileURLToPath as $r}from"url";import{createRequire as Ur}from"module";import{execa as Mr,execaCommand as Po}from"execa";import{Transform as Pr}from"stream";var Or=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_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"]),kr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function Fr(){return Object.entries(process.env).filter(([e,t])=>!(!t||Or.has(e)||kr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function K(e){if(typeof e!="string")return e;let t=Fr();if(t.length===0)return e;let r=e;return t.forEach(n=>{let o=new RegExp(Lr(n),"g");r=r.replace(o,"******")}),r}function Lr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ie=class extends Pr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,n){let o=t.toString(),i=K(o);n(null,i)}};function Pt(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(n,o,i){let s=typeof n=="string"?K(n):n;return typeof o=="function"?t(s,o):t(s,o,i)},process.stderr.write=function(n,o,i){let s=typeof n=="string"?K(n):n;return typeof o=="function"?r(s,o):r(s,o,i)}}var Ie=null,Ot=e=>(Ie&&Ie.destroy(),Ie=new X({totalAllowedTime:e}),Ie),kt=()=>Ie;var X=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,n)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let o=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),i=null,s=null;n!==void 0&&(s=new Promise((a,c)=>{i=setTimeout(()=>{c(new Error(`${t} stage exceeded its maximum duration of ${n}ms`))},n)}));try{return s?await Promise.race([r(),s]):await r()}finally{o(),i&&clearTimeout(i)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var Ft="netlify-agent-runner-context.md",Ke="task-history",H=".netlify",ee="results.md",Ve="assets",Je="other",Xe="personal";var ze="enterprise",Ze="free",Lt=[Xe,"pro",ze,Ze],Dt=["normal","redeploy","create","ask","dtn-prod-iteration","rebase"],$t="The production deploy has changed since you started working. Please reapply the changes to the current codebase, resolving any conflicts that arise. Use the attached diff file if present, otherwise review the previous session context to reproduce the changes.",te=1800*1e3;var Ut={name:"@netlify/agent-runner-cli",type:"module",version:"1.66.0-alpha.1",description:"CLI tool for running Netlify agents",main:"./dist/index.js",types:"./dist/index.d.ts",exports:"./dist/index.js",bin:{"agent-runner-cli":"./dist/bin.js","agent-runner-cli-local":"./dist/bin-local.js"},files:["dist/**/*.js","dist/**/*.d.ts","dist/skills/**","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.1.32","@google/gemini-cli":"0.25.2","@netlify/otel":"^5.1.1","@openai/codex":"0.93.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.208.0",execa:"^9.6.1",minimist:"^1.2.8"}};var Gr=$r(import.meta.url),jr=V.dirname(Gr),Yr=Ur(import.meta.url),se=_("shell"),Qe=new Set,Br={preferLocal:!0},L=(e,t,r)=>{let[n,o]=Hr(t,r),i={...Br,...o},s=Mr(e,n,i);qr(s,i),Kr(s);let a=r?.idleTimeout;return a&&a>0&&Wr(s,a),s};var Hr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},qr=(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)},et=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(q.kill(-e.pid,t),se.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return se.error("Error killing process:",r),!1}},Mt=e=>et(e,"SIGKILL"),Wr=(e,t)=>{let r=null,n=()=>{se.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),et(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(se.log(`Force killing idle process ${e.pid}`),Mt(e))},5e3)},o=()=>{r&&clearTimeout(r),r=setTimeout(n,t)};o(),e.stdout?.on("data",o),e.stderr?.on("data",o);let i=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",i),e.on("error",i)},Kr=e=>{Qe.add(e);let t=kt();if(t){let r=t.onTimesUp(()=>{se.log(`Global timer expired, killing process ${e.pid}`),et(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(se.log(`Force killing process ${e.pid} after timeout`),Mt(e))},5e3)});e.on("exit",()=>{Qe.delete(e),r()}),e.on("error",()=>{Qe.delete(e),r()})}};function ae(e,t){if(!q.env.NETLIFY_LOCAL_MODE)try{let o=Yr.resolve(Ut.name),i=V.dirname(o);for(;i!==V.dirname(i);){let s=V.dirname(i);if(V.basename(s)==="node_modules"){let a=V.join(s,".bin",t);if(Ce.existsSync(a))return a;break}i=s}}catch(o){console.error("Could not resolve package.json",o)}if(q.env.NODE_PATH){let o=V.join(q.env.NODE_PATH,".bin",t);if(Ce.existsSync(o))return o}let r=V.join(e,"node_modules",".bin",t);if(Ce.existsSync(r))return r;let n=V.join(jr,"..","node_modules",".bin",t);if(Ce.existsSync(n))return n}var Gt=_("utils"),Vr=e=>new Promise(t=>{setTimeout(t,e)}),jt=(e,t=3e3)=>{let r=!1,n=null,o=[],i=null,s=(...a)=>{if(r)return n=a,new Promise(p=>{o.push(p)});r=!0;let c,d=new Promise(p=>{c=p});return i=(async()=>{await Promise.resolve();let p=await e(...a);for(c(p);;){if(await Vr(t),!n)return r=!1,i=null,p;let u=n,m=o;n=null,o=[],p=await e(...u),m.forEach(g=>{g(p)})}})(),d};return s.flush=async()=>{if((r||n)&&i)return await i,s.flush()},s},le=(e,t,r=!1)=>{let n=null,o=null,i=null,s=function(...a){o=a,i=this;let c=r&&!n;clearTimeout(n),n=setTimeout(()=>{n=null,r||(e.apply(i,o),o=null,i=null)},t),c&&(e.apply(i,o),o=null,i=null)};return s.cancel=()=>{clearTimeout(n),n=null,o=null,i=null},s.flush=()=>{if(n){clearTimeout(n);let a=o,c=i;n=null,o=null,i=null,e.apply(c,a)}},s},Pe=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(n){t&&(r?.error?r.error("Could not parse JSON",n):Gt.error("Could not parse JSON",n))}},Yt=(e,t)=>{let o=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let a=`--${t}${o}`;if(a.length>55)return"";let c=60-a.length;if(c<=0)return"";if(c>=i.length+6){let d=Math.min(c-i.length,e.length);return`${i}${e.slice(0,d)}`}return e.slice(0,c)},Jr=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!Lt.some(t=>t in e),Bt=()=>{let e={},t={codex:process.env.NETLIFY_FF_AGENT_RUNNER_CODEX_VERSION,claude:process.env.NETLIFY_FF_AGENT_RUNNER_CLAUDE_VERSION,gemini:process.env.NETLIFY_FF_AGENT_RUNNER_GEMINI_VERSION};return Object.entries(t).forEach(([r,n])=>{if(n){let o=`NETLIFY_FF_AGENT_RUNNER_${r.toUpperCase()}_VERSION`;try{let i=JSON.parse(n);Jr(i)&&(e[r]=i)}catch(i){let a=i instanceof SyntaxError?"Invalid JSON":i.message;Gt.error(`Could not parse ${r} model version override from ${o}: ${a}`)}}}),e},Xr=50*1024,tt=(e,t=Xr)=>{if(!e||typeof e!="string"||e.length<=t)return e;let n=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+n};import{Buffer as Ht}from"buffer";import zr from"path";var qt=_("repo"),Wt=async({config:e,isRetry:t})=>{qt.info("Getting runner diffs");let r=await Qr(),{hasChanges:n}=r,{status:o}=r;if(!n)return{hasChanges:!1};if(!t){let E=en(o);await tn(E)}qt.info("Changes after processing"),await nt();let i=await ot(o);await rt(i);let s={stdio:["ignore","pipe","pipe"]},a=await L("git",["diff","--staged"],s),c=String(a.stdout??"");if(n=!!c,!n)return{hasChanges:!1,ignored:i};let d=await L("git",["diff","--staged","--binary"],s),p=String(d.stdout??""),u,m;if(e.sha){if(!process.env.NETLIFY_LOCAL_MODE){process.env.NETLIFY_INTERNAL_GIT="1";try{await L("git",["commit","-m","Agent runner"])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}}let E=await L("git",["diff",e.sha,"HEAD"],s);u=String(E.stdout??"");let T=await L("git",["diff",e.sha,"HEAD","--binary"],s),h=String(T.stdout??"");u!==h&&(m=Ht.from(h).toString("base64"))}let g={hasChanges:!0,diff:c,resultDiff:u,ignored:i};return c!==p&&(g.diffBinary=Ht.from(p).toString("base64")),m&&(g.resultDiffBinary=m),g},rt=async(e=[])=>{process.env.NETLIFY_INTERNAL_GIT="1";try{await L("git",["add",".",...e])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}},nt=async()=>{let e=await L("git",["status","-s"]);return String(e.stdout??"")},Kt=/.. (.+)?\.log$/,Zr=[Kt],Qr=async()=>{let e=await nt();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
9
9
|
`).filter(n=>Zr.some(i=>i instanceof RegExp?i.test(n):n===i)?!1:n[1]?.trim()!=="")).length!==0,status:e}},Vt=async()=>{let{stdout:e}=await L("git",["rev-parse","HEAD"]);return String(e??"").trim()},Jt=async()=>{let{stdout:e}=await L("git",["rev-list","--max-parents=0","HEAD"]);return String(e??"").trim()},ot=async e=>{e||=await nt();let t=[".netlify","node_modules","dist",".next","out",".nuxt",".output",".cache",".turbo",".parcel-cache","coverage",".nyc_output","storybook-static","public/build"],r=[];return e.split(`
|
|
10
10
|
`).forEach(n=>{t.forEach(i=>{let s=n===`?? ${i}`,a=n.startsWith(`?? ${i}/`)||n.startsWith(`?? ${i}${zr.sep}`);(s||a)&&r.push(`:!${i}`)});let o=n.match(Kt)?.[1];o&&r.push(`:!${o}.log`)}),r},it=async()=>{await L("git",["reset","--hard","HEAD"])},en=e=>{let t=e.split(`
|
|
11
11
|
`).reduce((r,n)=>{if(!n)return r;let[o,i,,...s]=n,a=s.join(""),c=o.trim(),d=i.trim();return r[a]?r[a].change=d:r[a]={filePath:a,stage:c,change:d},r},{});return Object.values(t)},tn=async e=>{let t=[];for(let r of e)r.stage&&!r.change&&t.push(L("git",["restore","--staged","--worktree",r.filePath]));await Promise.allSettled(t)};import nn from"fs/promises";import on from"os";import Zt from"path";import de from"process";import sn from"readline";import st from"path";import rn from"fs/promises";var at=_("agent-output-utils");async function ce({initialResult:e,agentName:t,hasError:r}){let n="",o=st.join(process.cwd(),H,ee);try{let i=await rn.readFile(o,"utf-8");i&&(n=i,at.log(`Pulled result from ${st.relative(process.cwd(),o)}`))}catch{at.log(`No results file found at ${st.relative(process.cwd(),o)}`)}return n||(!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,n=r?.replace(/\s+/g," ").trim().toLowerCase()||"",o="";return n?.includes("ai gateway is not available for your account")||n?.includes("ai gateway is not enabled for your account")?o="AI Gateway is currently not available on your account. Please confirm your account meets the criteria for using Agent Runners and AI Gateway and that your account has remaining AI Gateway inference credits available. Reach out to Netlify support if this is unexpected.":n?.includes("error when talking to gemini api")?o="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":(n?.includes("connection closed prematurely")||n?.includes("499")&&t.toLowerCase().includes("gemini"))&&(o=`The ${t} models were currently overloaded. Please try again or use a different available agent.`),n?.includes("request timed out")&&(o=`The ${t} API request's have timed out. Please try again or use a different available agent.`),n?.includes("network error")&&(o=`The ${t} agent is having network issues. Please try again or use a different available agent.`),n?.includes("503")&&(o=`The ${t} API is currently experiencing high load. Retrying automatically...`),o&&at.log(`Providing updated error messsage: ${o}, replacing original error: ${r}`),o||r||void 0}function pe(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")||r?.includes("503"))}var $=_("runner_claude"),Xt="Claude Code",fe="claude-opus-4-6",zt=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,an=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>($.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?($.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):($.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0}));async function lt({config:e,netlify:t,persistSteps:r,aiGateway:n,continueSession:o,priorAgentSessionId:i,cwd:s=de.cwd()}){let a=e,{accountType:c,prompt:d,modelVersionOverrides:p}=a,{model:u}=a,m="";if(n){let{token:y,url:f}=n;if(!y||!f)throw new Error("No token or url provided from AI Gateway");if(p?.claude){let l=p?.claude?.[c];if(l){if(!await n.isModelAvailableForProvider("anthropic",l))throw new Error(`Model override '${l}' is not available for anthropic provider`);u=l}}else if(u){if(!await n.isModelAvailableForProvider("anthropic",u))throw new Error(`Model '${u}' is not available for anthropic provider`)}else!!fe&&await n.isModelAvailableForProvider("anthropic",fe)?(u=fe,$.log(`Using default model: ${fe}`)):fe&&$.log(`Default model ${fe} is not available, proceeding without model specification`);de.env.ANTHROPIC_API_KEY=y,de.env.ANTHROPIC_BASE_URL=f}else if(!de.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let g=[],E=[],T={},h=0,I=0,N,S,k=[ae(s,"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose","--disallowed-tools","ExitPlanMode,AskUserQuestion",...u?["--model",u]:[],...o?["--continue"]:[],...o&&i?["--resume",i]:[],"-p",d],P=`${de.env.NVM_BIN}/node`;$.log(`Running ${P} ${k.join(" ")}`);let F=t.utils.run(P,k,{all:!0,env:de.env,cwd:s,idleTimeout:te});F.stdin?.end();let x=le(()=>{r?.({steps:g,duration:I})},250),R=(y,f)=>{let l={...y,id:h};h+=1,E.push(l),g.push(l),f||x.flush(),x(),f&&x.flush()},D=sn.createInterface({input:F.all});return D.on("error",y=>{$.error("Readline interface error",{error:y.message,stack:y.stack})}),D.on("line",y=>{let f=null;try{f=JSON.parse(y)}catch{$.log("Could not parse line",y)}f?.session_id&&f.session_id!==m&&(m=f.session_id),Array.isArray(f?.message?.content)?f.message.content.forEach(l=>{switch(l.type){case"text":{l.text&&R({message:l.text});break}case"image":{typeof l.source=="object"&&l.source&&l.source.type==="base64"&&l.source.media_type?R({message:``}):$.log(`Unsupported image type ${l.source?.type}`,l.source);break}case"tool_use":{if(l.name==="Task"){let w=l.input?.description&&`\`${l.input.description}\``;R({title:[zt(l.name),w].filter(Boolean).join(" ")})}else l.id&&(T[l.id]=l);x.flush();break}case"tool_result":{let w=l.tool_use_id?T[l.tool_use_id]:void 0,Z;if(w){let J=w.input?.file_path&&Zt.relative(s,w.input.file_path),O=J&&`\`${J}\``;Z=[zt(w.name||""),O].filter(Boolean).join(" ")}let Se=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(w?.name||""),Q;if(typeof l.content=="string")Q=l.content;else if(Array.isArray(l.content)){let J=[];l.content.forEach(O=>{O?.type==="text"&&typeof O.text=="string"?J.push(O.text):O?.type==="image"&&typeof O.source=="object"&&O.source?O.source.type==="base64"&&O.source.media_type?J.push(``):$.log(`Unsupported image type ${O.source.type}`,O.source):$.log(`Unsupported block type ${O?.type}`)}),Q=J.join(`
|
package/dist/index.js
CHANGED
|
@@ -4,7 +4,7 @@ import{createRequire as Sn}from"module";import{createTracerProvider as lr}from"@
|
|
|
4
4
|
${o}
|
|
5
5
|
</extracted_error_chunk>`).join(`
|
|
6
6
|
|
|
7
|
-
`);return s.length>e.length*.8?e:s}import{execSync as tn}from"child_process";import Jt from"fs/promises";import rn from"path";import X from"process";import{getTracer as nn}from"@netlify/otel";import ye from"process";var re=class extends Error{constructor(r,n,i){super(r);this.statusCode=n;this.userMessage=i;this.name="GracefulShutdownError"}},gt=e=>e instanceof re;var ve=ye.env.NETLIFY_API_URL,Se=ye.env.NETLIFY_API_TOKEN,Y=E("api"),Ae=()=>ye.env.NETLIFY_LOCAL_MODE==="true",_e=async(e,t={})=>{if(!ve||!Se)throw new Error("No API URL or token");let r=new URL(e,ve),n={...t,headers:{...t.headers,Authorization:`Bearer ${Se}`}};ye.env.AGENT_RUNNERS_DEBUG==="true"&&(n.headers["x-nf-debug-logging"]="true"),t.json&&(n.headers||={},n.headers["Content-Type"]="application/json",n.body=JSON.stringify(t.json));let i=await fetch(r,n),s=i.ok&&i.status<=299;if(ye.env.AGENT_RUNNERS_DEBUG==="true")Y.log(`Response headers for ${r}:`),i.headers.forEach((a,c)=>{Y.log(` ${c}: ${a}`)});else{let a=i.headers.get("x-request-id")||i.headers.get("x-nf-request-id");Y.log(`Request ID for ${r}: ${a||"N/A"}`)}if(s||Y.error(`Got status ${i.status} for request ${r}`),t.raw){if(!s)throw new Error(`API request failed: ${i.status} ${i.statusText}`);return i}let o=await(i.headers.get("content-type")?.includes("application/json")?i.json():i.text());if(!s){let a=typeof o=="string"?o:JSON.stringify(o);throw i.status===404?new re(`API request failed: 404 - ${a}`,404,"The site associated with this agent run no longer exists."):i.status===403&&t.gracefulOn403?new re(`API request failed: 403 - ${a}`,403,"Credit limit reached. Please add more credits to continue using Agent Runners."):new Error(`API request failed: ${i.status} - ${a}`)}return o},ht=e=>{Y.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(ve=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Se=e.constants.NETLIFY_API_TOKEN)},yt=()=>({apiUrl:ve,token:Se}),Ee=async(e,t)=>Ae()?(Y.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):_e(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),G=async(e,t,r)=>Ae()?(Y.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)=>Ae()?(Y.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},gracefulOn403:!0}),wt=async(e,t)=>Ae()?(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"}}):_e(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Ye=async(e,t)=>{Y.log(`Uploading diff to S3: ${e.substring(0,50)}...`);let r=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"text/plain"}});if(!r.ok)throw new Error(`S3 upload failed with status ${r.status}`);return r};var ne=E("ai_gateway"),Be=null;var Tt=async()=>{if(Be)return Be;ne.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,ne.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},mr=async(e,t)=>{let n=(await Tt()).providers[e];if(!n)return ne.log(`Provider '${e}' not found`),!1;let i=n.models.includes(t);return ne.log(`Model validation for ${e}/${t}`,{isAvailable:i}),i},It=async({netlify:e,config:t})=>{let r,n,i,s,o=e.constants?.SITE_ID;if(!o)throw new Error("No site id");let a=async()=>{clearTimeout(i),ne.log("Requesting AI gateway information");let c=await Et(o,t.id,t.sessionId);if({token:r,url:s}=c,n=c.expires_at?c.expires_at*1e3:void 0,ne.log("Got AI gateway information",{token:!!r,expiresAt:n,url:s}),n){let d=n-Date.now()-6e4;d>0&&(i=setTimeout(()=>{a()},d))}};return await Promise.all([a(),Tt()]),{get url(){return s},get token(){return r},isModelAvailableForProvider:mr}};import H from"process";import W from"path";import be from"fs";import{fileURLToPath as Tr}from"url";import{createRequire as Ir}from"module";import{execa as xr,execaCommand as si}from"execa";import{Transform as gr}from"stream";var hr=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_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"]),yr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function _r(){return Object.entries(process.env).filter(([e,t])=>!(!t||hr.has(e)||yr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function K(e){if(typeof e!="string")return e;let t=_r();if(t.length===0)return e;let r=e;return t.forEach(n=>{let i=new RegExp(Er(n),"g");r=r.replace(i,"******")}),r}function Er(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ie=class extends gr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,n){let i=t.toString(),s=K(i);n(null,s)}};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(n,i,s){let o=typeof n=="string"?K(n):n;return typeof i=="function"?t(o,i):t(o,i,s)},process.stderr.write=function(n,i,s){let o=typeof n=="string"?K(n):n;return typeof i=="function"?r(o,i):r(o,i,s)}}var we=null,Rt=e=>(we&&we.destroy(),we=new J({totalAllowedTime:e}),we),vt=()=>we;var J=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,n)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let i=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),s=null,o=null;n!==void 0&&(o=new Promise((a,c)=>{s=setTimeout(()=>{c(new Error(`${t} stage exceeded its maximum duration of ${n}ms`))},n)}));try{return o?await Promise.race([r(),o]):await r()}finally{i(),s&&clearTimeout(s)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var St="netlify-agent-runner-context.md",He="task-history",B=".netlify",Q="results.md",qe="assets";var ee=1800*1e3;var At={name:"@netlify/agent-runner-cli",type:"module",version:"1.66.0-alpha.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","dist/skills/**","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.1.32","@google/gemini-cli":"0.25.2","@netlify/otel":"^5.1.1","@openai/codex":"0.93.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.208.0",execa:"^9.6.1",minimist:"^1.2.8"}};var Rr=Tr(import.meta.url),vr=W.dirname(Rr),Sr=Ir(import.meta.url),oe=E("shell"),Ke=new Set,Ar={preferLocal:!0},D=(e,t,r)=>{let[n,i]=br(t,r),s={...Ar,...i},o=xr(e,n,s);Nr(o,s),Pr(o);let a=r?.idleTimeout;return a&&a>0&&Cr(o,a),o};var br=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Nr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(H.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new ie).pipe(H.stdout),e.stdout?.pipe(new ie).pipe(H.stdout),e.stderr?.pipe(new ie).pipe(H.stderr);return}e.stdout?.pipe(H.stdout),e.stderr?.pipe(H.stderr)},We=(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}},bt=e=>We(e,"SIGKILL"),Cr=(e,t)=>{let r=null,n=()=>{oe.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),We(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(oe.log(`Force killing idle process ${e.pid}`),bt(e))},5e3)},i=()=>{r&&clearTimeout(r),r=setTimeout(n,t)};i(),e.stdout?.on("data",i),e.stderr?.on("data",i);let s=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",s),e.on("error",s)},Pr=e=>{Ke.add(e);let t=vt();if(t){let r=t.onTimesUp(()=>{oe.log(`Global timer expired, killing process ${e.pid}`),We(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(oe.log(`Force killing process ${e.pid} after timeout`),bt(e))},5e3)});e.on("exit",()=>{Ke.delete(e),r()}),e.on("error",()=>{Ke.delete(e),r()})}};function se(e,t){if(!H.env.NETLIFY_LOCAL_MODE)try{let i=Sr.resolve(At.name),s=W.dirname(i);for(;s!==W.dirname(s);){let o=W.dirname(s);if(W.basename(o)==="node_modules"){let a=W.join(o,".bin",t);if(be.existsSync(a))return a;break}s=o}}catch(i){console.error("Could not resolve package.json",i)}if(H.env.NODE_PATH){let i=W.join(H.env.NODE_PATH,".bin",t);if(be.existsSync(i))return i}let r=W.join(e,"node_modules",".bin",t);if(be.existsSync(r))return r;let n=W.join(vr,"..","node_modules",".bin",t);if(be.existsSync(n))return n}var Or=E("utils"),kr=e=>new Promise(t=>{setTimeout(t,e)}),Nt=(e,t=3e3)=>{let r=!1,n=null,i=[],s=null,o=(...a)=>{if(r)return n=a,new Promise(p=>{i.push(p)});r=!0;let c,d=new Promise(p=>{c=p});return s=(async()=>{await Promise.resolve();let p=await e(...a);for(c(p);;){if(await kr(t),!n)return r=!1,s=null,p;let u=n,m=i;n=null,i=[],p=await e(...u),m.forEach(g=>{g(p)})}})(),d};return o.flush=async()=>{if((r||n)&&s)return await s,o.flush()},o},ae=(e,t,r=!1)=>{let n=null,i=null,s=null,o=function(...a){i=a,s=this;let c=r&&!n;clearTimeout(n),n=setTimeout(()=>{n=null,r||(e.apply(s,i),i=null,s=null)},t),c&&(e.apply(s,i),i=null,s=null)};return o.cancel=()=>{clearTimeout(n),n=null,i=null,s=null},o.flush=()=>{if(n){clearTimeout(n);let a=i,c=s;n=null,i=null,s=null,e.apply(c,a)}},o},Ct=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(n){t&&(r?.error?r.error("Could not parse JSON",n):Or.error("Could not parse JSON",n))}},Pt=(e,t)=>{let i=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let a=`--${t}${i}`;if(a.length>55)return"";let c=60-a.length;if(c<=0)return"";if(c>=s.length+6){let d=Math.min(c-s.length,e.length);return`${s}${e.slice(0,d)}`}return e.slice(0,c)};var $r=50*1024,Ve=(e,t=$r)=>{if(!e||typeof e!="string"||e.length<=t)return e;let n=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+n};import{Buffer as Ot}from"buffer";import Dr from"path";var kt=E("repo"),$t=async({config:e,isRetry:t})=>{kt.info("Getting runner diffs");let r=await Lr(),{hasChanges:n}=r,{status:i}=r;if(!n)return{hasChanges:!1};if(!t){let y=Ur(i);await Mr(y)}kt.info("Changes after processing"),await Xe();let s=await ze(i);await Je(s);let o={stdio:["ignore","pipe","pipe"]},a=await D("git",["diff","--staged"],o),c=String(a.stdout??"");if(n=!!c,!n)return{hasChanges:!1,ignored:s};let d=await D("git",["diff","--staged","--binary"],o),p=String(d.stdout??""),u,m;if(e.sha){if(!process.env.NETLIFY_LOCAL_MODE){process.env.NETLIFY_INTERNAL_GIT="1";try{await D("git",["commit","-m","Agent runner"])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}}let y=await D("git",["diff",e.sha,"HEAD"],o);u=String(y.stdout??"");let w=await D("git",["diff",e.sha,"HEAD","--binary"],o),_=String(w.stdout??"");u!==_&&(m=Ot.from(_).toString("base64"))}let g={hasChanges:!0,diff:c,resultDiff:u,ignored:s};return c!==p&&(g.diffBinary=Ot.from(p).toString("base64")),m&&(g.resultDiffBinary=m),g},Je=async(e=[])=>{process.env.NETLIFY_INTERNAL_GIT="1";try{await D("git",["add",".",...e])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}},Xe=async()=>{let e=await D("git",["status","-s"]);return String(e.stdout??"")},Dt=/.. (.+)?\.log$/,Fr=[Dt],Lr=async()=>{let e=await Xe();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
7
|
+
`);return s.length>e.length*.8?e:s}import{execSync as tn}from"child_process";import Jt from"fs/promises";import rn from"path";import X from"process";import{getTracer as nn}from"@netlify/otel";import ye from"process";var re=class extends Error{constructor(r,n,i){super(r);this.statusCode=n;this.userMessage=i;this.name="GracefulShutdownError"}},gt=e=>e instanceof re;var ve=ye.env.NETLIFY_API_URL,Se=ye.env.NETLIFY_API_TOKEN,Y=E("api"),Ae=()=>ye.env.NETLIFY_LOCAL_MODE==="true",_e=async(e,t={})=>{if(!ve||!Se)throw new Error("No API URL or token");let r=new URL(e,ve),n={...t,headers:{...t.headers,Authorization:`Bearer ${Se}`}};ye.env.AGENT_RUNNERS_DEBUG==="true"&&(n.headers["x-nf-debug-logging"]="true"),t.json&&(n.headers||={},n.headers["Content-Type"]="application/json",n.body=JSON.stringify(t.json));let i=await fetch(r,n),s=i.ok&&i.status<=299;if(ye.env.AGENT_RUNNERS_DEBUG==="true")Y.log(`Response headers for ${r}:`),i.headers.forEach((a,c)=>{Y.log(` ${c}: ${a}`)});else{let a=i.headers.get("x-request-id")||i.headers.get("x-nf-request-id");Y.log(`Request ID for ${r}: ${a||"N/A"}`)}if(s||Y.error(`Got status ${i.status} for request ${r}`),t.raw){if(!s)throw new Error(`API request failed: ${i.status} ${i.statusText}`);return i}let o=await(i.headers.get("content-type")?.includes("application/json")?i.json():i.text());if(!s){let a=typeof o=="string"?o:JSON.stringify(o);throw i.status===404?new re(`API request failed: 404 - ${a}`,404,"The site associated with this agent run no longer exists."):i.status===403&&t.gracefulOn403?new re(`API request failed: 403 - ${a}`,403,"Credit limit reached. Please add more credits to continue using Agent Runners."):new Error(`API request failed: ${i.status} - ${a}`)}return o},ht=e=>{Y.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(ve=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Se=e.constants.NETLIFY_API_TOKEN)},yt=()=>({apiUrl:ve,token:Se}),Ee=async(e,t)=>Ae()?(Y.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):_e(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),G=async(e,t,r)=>Ae()?(Y.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)=>Ae()?(Y.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},gracefulOn403:!0}),wt=async(e,t)=>Ae()?(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"}}):_e(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Ye=async(e,t)=>{Y.log(`Uploading diff to S3: ${e.substring(0,50)}...`);let r=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"text/plain"}});if(!r.ok)throw new Error(`S3 upload failed with status ${r.status}`);return r};var ne=E("ai_gateway"),Be=null;var Tt=async()=>{if(Be)return Be;ne.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,ne.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},mr=async(e,t)=>{let n=(await Tt()).providers[e];if(!n)return ne.log(`Provider '${e}' not found`),!1;let i=n.models.includes(t);return ne.log(`Model validation for ${e}/${t}`,{isAvailable:i}),i},It=async({netlify:e,config:t})=>{let r,n,i,s,o=e.constants?.SITE_ID;if(!o)throw new Error("No site id");let a=async()=>{clearTimeout(i),ne.log("Requesting AI gateway information");let c=await Et(o,t.id,t.sessionId);if({token:r,url:s}=c,n=c.expires_at?c.expires_at*1e3:void 0,ne.log("Got AI gateway information",{token:!!r,expiresAt:n,url:s}),n){let d=n-Date.now()-6e4;d>0&&(i=setTimeout(()=>{a()},d))}};return await Promise.all([a(),Tt()]),{get url(){return s},get token(){return r},isModelAvailableForProvider:mr}};import H from"process";import W from"path";import be from"fs";import{fileURLToPath as Tr}from"url";import{createRequire as Ir}from"module";import{execa as xr,execaCommand as si}from"execa";import{Transform as gr}from"stream";var hr=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_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"]),yr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function _r(){return Object.entries(process.env).filter(([e,t])=>!(!t||hr.has(e)||yr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function K(e){if(typeof e!="string")return e;let t=_r();if(t.length===0)return e;let r=e;return t.forEach(n=>{let i=new RegExp(Er(n),"g");r=r.replace(i,"******")}),r}function Er(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ie=class extends gr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,n){let i=t.toString(),s=K(i);n(null,s)}};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(n,i,s){let o=typeof n=="string"?K(n):n;return typeof i=="function"?t(o,i):t(o,i,s)},process.stderr.write=function(n,i,s){let o=typeof n=="string"?K(n):n;return typeof i=="function"?r(o,i):r(o,i,s)}}var we=null,Rt=e=>(we&&we.destroy(),we=new J({totalAllowedTime:e}),we),vt=()=>we;var J=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,n)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let i=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),s=null,o=null;n!==void 0&&(o=new Promise((a,c)=>{s=setTimeout(()=>{c(new Error(`${t} stage exceeded its maximum duration of ${n}ms`))},n)}));try{return o?await Promise.race([r(),o]):await r()}finally{i(),s&&clearTimeout(s)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var St="netlify-agent-runner-context.md",He="task-history",B=".netlify",Q="results.md",qe="assets";var ee=1800*1e3;var At={name:"@netlify/agent-runner-cli",type:"module",version:"1.66.0-alpha.1",description:"CLI tool for running Netlify agents",main:"./dist/index.js",types:"./dist/index.d.ts",exports:"./dist/index.js",bin:{"agent-runner-cli":"./dist/bin.js","agent-runner-cli-local":"./dist/bin-local.js"},files:["dist/**/*.js","dist/**/*.d.ts","dist/skills/**","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.1.32","@google/gemini-cli":"0.25.2","@netlify/otel":"^5.1.1","@openai/codex":"0.93.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.208.0",execa:"^9.6.1",minimist:"^1.2.8"}};var Rr=Tr(import.meta.url),vr=W.dirname(Rr),Sr=Ir(import.meta.url),oe=E("shell"),Ke=new Set,Ar={preferLocal:!0},D=(e,t,r)=>{let[n,i]=br(t,r),s={...Ar,...i},o=xr(e,n,s);Nr(o,s),Pr(o);let a=r?.idleTimeout;return a&&a>0&&Cr(o,a),o};var br=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Nr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(H.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new ie).pipe(H.stdout),e.stdout?.pipe(new ie).pipe(H.stdout),e.stderr?.pipe(new ie).pipe(H.stderr);return}e.stdout?.pipe(H.stdout),e.stderr?.pipe(H.stderr)},We=(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}},bt=e=>We(e,"SIGKILL"),Cr=(e,t)=>{let r=null,n=()=>{oe.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),We(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(oe.log(`Force killing idle process ${e.pid}`),bt(e))},5e3)},i=()=>{r&&clearTimeout(r),r=setTimeout(n,t)};i(),e.stdout?.on("data",i),e.stderr?.on("data",i);let s=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",s),e.on("error",s)},Pr=e=>{Ke.add(e);let t=vt();if(t){let r=t.onTimesUp(()=>{oe.log(`Global timer expired, killing process ${e.pid}`),We(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(oe.log(`Force killing process ${e.pid} after timeout`),bt(e))},5e3)});e.on("exit",()=>{Ke.delete(e),r()}),e.on("error",()=>{Ke.delete(e),r()})}};function se(e,t){if(!H.env.NETLIFY_LOCAL_MODE)try{let i=Sr.resolve(At.name),s=W.dirname(i);for(;s!==W.dirname(s);){let o=W.dirname(s);if(W.basename(o)==="node_modules"){let a=W.join(o,".bin",t);if(be.existsSync(a))return a;break}s=o}}catch(i){console.error("Could not resolve package.json",i)}if(H.env.NODE_PATH){let i=W.join(H.env.NODE_PATH,".bin",t);if(be.existsSync(i))return i}let r=W.join(e,"node_modules",".bin",t);if(be.existsSync(r))return r;let n=W.join(vr,"..","node_modules",".bin",t);if(be.existsSync(n))return n}var Or=E("utils"),kr=e=>new Promise(t=>{setTimeout(t,e)}),Nt=(e,t=3e3)=>{let r=!1,n=null,i=[],s=null,o=(...a)=>{if(r)return n=a,new Promise(p=>{i.push(p)});r=!0;let c,d=new Promise(p=>{c=p});return s=(async()=>{await Promise.resolve();let p=await e(...a);for(c(p);;){if(await kr(t),!n)return r=!1,s=null,p;let u=n,m=i;n=null,i=[],p=await e(...u),m.forEach(g=>{g(p)})}})(),d};return o.flush=async()=>{if((r||n)&&s)return await s,o.flush()},o},ae=(e,t,r=!1)=>{let n=null,i=null,s=null,o=function(...a){i=a,s=this;let c=r&&!n;clearTimeout(n),n=setTimeout(()=>{n=null,r||(e.apply(s,i),i=null,s=null)},t),c&&(e.apply(s,i),i=null,s=null)};return o.cancel=()=>{clearTimeout(n),n=null,i=null,s=null},o.flush=()=>{if(n){clearTimeout(n);let a=i,c=s;n=null,i=null,s=null,e.apply(c,a)}},o},Ct=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(n){t&&(r?.error?r.error("Could not parse JSON",n):Or.error("Could not parse JSON",n))}},Pt=(e,t)=>{let i=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let a=`--${t}${i}`;if(a.length>55)return"";let c=60-a.length;if(c<=0)return"";if(c>=s.length+6){let d=Math.min(c-s.length,e.length);return`${s}${e.slice(0,d)}`}return e.slice(0,c)};var $r=50*1024,Ve=(e,t=$r)=>{if(!e||typeof e!="string"||e.length<=t)return e;let n=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+n};import{Buffer as Ot}from"buffer";import Dr from"path";var kt=E("repo"),$t=async({config:e,isRetry:t})=>{kt.info("Getting runner diffs");let r=await Lr(),{hasChanges:n}=r,{status:i}=r;if(!n)return{hasChanges:!1};if(!t){let y=Ur(i);await Mr(y)}kt.info("Changes after processing"),await Xe();let s=await ze(i);await Je(s);let o={stdio:["ignore","pipe","pipe"]},a=await D("git",["diff","--staged"],o),c=String(a.stdout??"");if(n=!!c,!n)return{hasChanges:!1,ignored:s};let d=await D("git",["diff","--staged","--binary"],o),p=String(d.stdout??""),u,m;if(e.sha){if(!process.env.NETLIFY_LOCAL_MODE){process.env.NETLIFY_INTERNAL_GIT="1";try{await D("git",["commit","-m","Agent runner"])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}}let y=await D("git",["diff",e.sha,"HEAD"],o);u=String(y.stdout??"");let w=await D("git",["diff",e.sha,"HEAD","--binary"],o),_=String(w.stdout??"");u!==_&&(m=Ot.from(_).toString("base64"))}let g={hasChanges:!0,diff:c,resultDiff:u,ignored:s};return c!==p&&(g.diffBinary=Ot.from(p).toString("base64")),m&&(g.resultDiffBinary=m),g},Je=async(e=[])=>{process.env.NETLIFY_INTERNAL_GIT="1";try{await D("git",["add",".",...e])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}},Xe=async()=>{let e=await D("git",["status","-s"]);return String(e.stdout??"")},Dt=/.. (.+)?\.log$/,Fr=[Dt],Lr=async()=>{let e=await Xe();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
8
8
|
`).filter(n=>Fr.some(s=>s instanceof RegExp?s.test(n):n===s)?!1:n[1]?.trim()!=="")).length!==0,status:e}},Ft=async()=>{let{stdout:e}=await D("git",["rev-parse","HEAD"]);return String(e??"").trim()},Lt=async()=>{let{stdout:e}=await D("git",["rev-list","--max-parents=0","HEAD"]);return String(e??"").trim()},ze=async e=>{e||=await Xe();let t=[".netlify","node_modules","dist",".next","out",".nuxt",".output",".cache",".turbo",".parcel-cache","coverage",".nyc_output","storybook-static","public/build"],r=[];return e.split(`
|
|
9
9
|
`).forEach(n=>{t.forEach(s=>{let o=n===`?? ${s}`,a=n.startsWith(`?? ${s}/`)||n.startsWith(`?? ${s}${Dr.sep}`);(o||a)&&r.push(`:!${s}`)});let i=n.match(Dt)?.[1];i&&r.push(`:!${i}.log`)}),r},Ze=async()=>{await D("git",["reset","--hard","HEAD"])},Ur=e=>{let t=e.split(`
|
|
10
10
|
`).reduce((r,n)=>{if(!n)return r;let[i,s,,...o]=n,a=o.join(""),c=i.trim(),d=s.trim();return r[a]?r[a].change=d:r[a]={filePath:a,stage:c,change:d},r},{});return Object.values(t)},Mr=async e=>{let t=[];for(let r of e)r.stage&&!r.change&&t.push(D("git",["restore","--staged","--worktree",r.filePath]));await Promise.allSettled(t)};import jr from"fs/promises";import Yr from"os";import Gt from"path";import pe from"process";import Br from"readline";import Qe from"path";import Gr from"fs/promises";var et=E("agent-output-utils");async function le({initialResult:e,agentName:t,hasError:r}){let n="",i=Qe.join(process.cwd(),B,Q);try{let s=await Gr.readFile(i,"utf-8");s&&(n=s,et.log(`Pulled result from ${Qe.relative(process.cwd(),i)}`))}catch{et.log(`No results file found at ${Qe.relative(process.cwd(),i)}`)}return n||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function ce({error:e,agentName:t}){let r=e&&typeof e=="object"?JSON.stringify(e):e,n=r?.replace(/\s+/g," ").trim().toLowerCase()||"",i="";return n?.includes("ai gateway is not available for your account")||n?.includes("ai gateway is not enabled for your account")?i="AI Gateway is currently not available on your account. Please confirm your account meets the criteria for using Agent Runners and AI Gateway and that your account has remaining AI Gateway inference credits available. Reach out to Netlify support if this is unexpected.":n?.includes("error when talking to gemini api")?i="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":(n?.includes("connection closed prematurely")||n?.includes("499")&&t.toLowerCase().includes("gemini"))&&(i=`The ${t} models were currently overloaded. Please try again or use a different available agent.`),n?.includes("request timed out")&&(i=`The ${t} API request's have timed out. Please try again or use a different available agent.`),n?.includes("network error")&&(i=`The ${t} agent is having network issues. Please try again or use a different available agent.`),n?.includes("503")&&(i=`The ${t} API is currently experiencing high load. Retrying automatically...`),i&&et.log(`Providing updated error messsage: ${i}, replacing original error: ${r}`),i||r||void 0}function ue(e){if(!e)return!1;let r=(e&&typeof e=="object"?JSON.stringify(e):e)?.replace(/\s+/g," ").trim().toLowerCase()||"";return!!(r?.includes("error when talking to gemini api")||r?.includes("499")||r?.includes("connection closed prematurely")||r?.includes("request timed out")||r?.includes("network error")||r?.includes("503"))}var L=E("runner_claude"),Ut="Claude Code",de="claude-opus-4-6",Mt=e=>({Task:"Task",Bash:"Run command",Glob:"Find files",Grep:"Search files",LS:"List directory",ExitPlanMode:"Exit planning",Read:"Read file",Edit:"Edit file",MultiEdit:"Edit multiple files",Write:"Coding",NotebookEdit:"Edit notebook",WebFetch:"Fetch webpage",TodoWrite:"Update task list",WebSearch:"Search web",BashOutput:"Get command output",KillBash:"Stop command"})[e]||e,Hr=({catchError:e,runCmd:t,error:r,result:n,runnerName:i})=>(L.log(`${i} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(L.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(L.log("Setting result to undefined because no valid result was captured"),{error:r||`${i} failed`,result:void 0}));async function tt({config:e,netlify:t,persistSteps:r,aiGateway:n,continueSession:i,priorAgentSessionId:s,cwd:o=pe.cwd()}){let a=e,{accountType:c,prompt:d,modelVersionOverrides:p}=a,{model:u}=a,m="";if(n){let{token:h,url:f}=n;if(!h||!f)throw new Error("No token or url provided from AI Gateway");if(p?.claude){let l=p?.claude?.[c];if(l){if(!await n.isModelAvailableForProvider("anthropic",l))throw new Error(`Model override '${l}' is not available for anthropic provider`);u=l}}else if(u){if(!await n.isModelAvailableForProvider("anthropic",u))throw new Error(`Model '${u}' is not available for anthropic provider`)}else!!de&&await n.isModelAvailableForProvider("anthropic",de)?(u=de,L.log(`Using default model: ${de}`)):de&&L.log(`Default model ${de} is not available, proceeding without model specification`);pe.env.ANTHROPIC_API_KEY=h,pe.env.ANTHROPIC_BASE_URL=f}else if(!pe.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let g=[],y=[],w={},_=0,I=0,b,S,k=[se(o,"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose","--disallowed-tools","ExitPlanMode,AskUserQuestion",...u?["--model",u]:[],...i?["--continue"]:[],...i&&s?["--resume",s]:[],"-p",d],P=`${pe.env.NVM_BIN}/node`;L.log(`Running ${P} ${k.join(" ")}`);let $=t.utils.run(P,k,{all:!0,env:pe.env,cwd:o,idleTimeout:ee});$.stdin?.end();let x=ae(()=>{r?.({steps:g,duration:I})},250),R=(h,f)=>{let l={...h,id:_};_+=1,y.push(l),g.push(l),f||x.flush(),x(),f&&x.flush()},F=Br.createInterface({input:$.all});return F.on("error",h=>{L.error("Readline interface error",{error:h.message,stack:h.stack})}),F.on("line",h=>{let f=null;try{f=JSON.parse(h)}catch{L.log("Could not parse line",h)}f?.session_id&&f.session_id!==m&&(m=f.session_id),Array.isArray(f?.message?.content)?f.message.content.forEach(l=>{switch(l.type){case"text":{l.text&&R({message:l.text});break}case"image":{typeof l.source=="object"&&l.source&&l.source.type==="base64"&&l.source.media_type?R({message:``}):L.log(`Unsupported image type ${l.source?.type}`,l.source);break}case"tool_use":{if(l.name==="Task"){let T=l.input?.description&&`\`${l.input.description}\``;R({title:[Mt(l.name),T].filter(Boolean).join(" ")})}else l.id&&(w[l.id]=l);x.flush();break}case"tool_result":{let T=l.tool_use_id?w[l.tool_use_id]:void 0,z;if(T){let V=T.input?.file_path&&Gt.relative(o,T.input.file_path),O=V&&`\`${V}\``;z=[Mt(T.name||""),O].filter(Boolean).join(" ")}let Re=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(T?.name||""),Z;if(typeof l.content=="string")Z=l.content;else if(Array.isArray(l.content)){let V=[];l.content.forEach(O=>{O?.type==="text"&&typeof O.text=="string"?V.push(O.text):O?.type==="image"&&typeof O.source=="object"&&O.source?O.source.type==="base64"&&O.source.media_type?V.push(``):L.log(`Unsupported image type ${O.source.type}`,O.source):L.log(`Unsupported block type ${O?.type}`)}),Z=V.join(`
|
package/package.json
CHANGED
|
File without changes
|