@netlify/agent-runner-cli 1.95.0 → 1.96.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin-local.js CHANGED
@@ -5,7 +5,7 @@ import j from"process";import nn from"path";import on from"fs";import Bo from"mi
5
5
  ${s}
6
6
  </extracted_error_chunk>`).join(`
7
7
 
8
- `);return i.length>e.length*.8?e:i}import{execSync as ao}from"child_process";import $r from"fs/promises";import lo from"path";import Ee from"process";import{getTracer as co}from"@netlify/otel";import Le from"process";var ne=class extends Error{constructor(r,o,n,i=!1){super(r);this.statusCode=o;this.userMessage=n;this.isCreditLimitExceeded=i;this.name="GracefulShutdownError"}},Ve=e=>e instanceof ne;var Ke=Le.env.NETLIFY_API_URL,Je=Le.env.NETLIFY_API_TOKEN,V=v("api"),Te=()=>Le.env.NETLIFY_LOCAL_MODE==="true",ue=async(e,t={})=>{if(!Ke||!Je)throw new Error("No API URL or token");let r=new URL(e,Ke),o={...t,headers:{...t.headers,Authorization:`Bearer ${Je}`}};Le.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let n=await fetch(r,o),i=n.ok&&n.status<=299;if(Le.env.AGENT_RUNNERS_DEBUG==="true")V.log(`Response headers for ${r}:`),n.headers.forEach((a,c)=>{V.log(` ${c}: ${a}`)});else{let a=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");V.log(`Request ID for ${r}: ${a||"N/A"}`)}if(i||V.error(`Got status ${n.status} for request ${r}`),t.raw){if(!i)throw new Error(`API request failed: ${n.status} ${n.statusText}`);return n}let s=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!i){let a=typeof s=="string"?s:JSON.stringify(s);throw n.status===404?new ne(`API request failed: 404 - ${a}`,404,"The site associated with this agent run no longer exists."):n.status===503&&t.gracefulOn503&&a.toLowerCase().includes("usage exceeded")?new ne(`API request failed: 503 - ${a}`,503,"Credit limit reached. Please add more credits to continue using Agent Runners.",!0):new Error(`API request failed: ${n.status} - ${a}`)}return s},Kt=e=>{V.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Ke=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Je=e.constants.NETLIFY_API_TOKEN)},Jt=()=>({apiUrl:Ke,token:Je}),De=async(e,t)=>Te()?(V.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):ue(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),K=async(e,t,r)=>Te()?(V.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):ue(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var zt=async e=>Te()?(V.log("Mock API: getSite called",{siteId:e}),{id:e,published_deploy:{id:"id"}}):ue(`/api/v1/sites/${e}`),Xt=async(e,t)=>Te()?(V.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):ue(`/api/v1/agent_runners/${e}/sessions/${t}`),Zt=(e,t,r)=>ue(`/api/v1/accounts/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn503:!0}),Qt=(e,t,r)=>ue(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn503:!0}),er=async(e,t)=>Te()?(V.log("Mock API: getDiffUploadUrls called",{runnerId:e,sessionId:t}),{result:{upload_url:"https://s3.mock.com/mock-upload-url-result",s3_key:"mock-s3-key-result"},cumulative:{upload_url:"https://s3.mock.com/mock-upload-url-cumulative",s3_key:"mock-s3-key-cumulative"}}):ue(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),tr=async(e,t)=>Te()?(V.log("Mock API: updateSessionUsage called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,usage:0}):ue(`/api/v1/agent_runners/${e}/sessions/${t}/update_usage`,{method:"POST"}),pt=async(e,t,{maxRetries:r=3,baseDelayMs:o=500}={})=>{V.log(`Uploading diff to S3: ${e.substring(0,50)}...`);for(let n=1;n<=r;n++)try{let i=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"text/plain"}});if(!i.ok)throw new Error(`S3 upload failed with status ${i.status}`);return i}catch(i){if(n===r)throw i;let s=o*2**(n-1);V.warn(`S3 upload attempt ${n}/${r} failed: ${i.message}. Retrying in ${s}ms...`),await new Promise(a=>setTimeout(a,s))}};var ve=v("ai_gateway"),mt=null;var ze=async()=>{if(mt)return mt;ve.log("Fetching available AI gateway providers");let e=await fetch(`${Jt().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 mt=t,ve.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},mn=async(e,t)=>{let o=(await ze()).providers[e];if(!o)return ve.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return ve.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},rr=async({config:e})=>{let t,r,o,n,i=!e.site?.published_deploy;if(!(i?e.accountId:e.siteId))throw new Error(`No entity id for ${i?"account":"site"}`);let a=async()=>{clearTimeout(o),ve.log("Requesting AI gateway information");let l=await(i?Zt(e.accountId,e.id,e.sessionId):Qt(e.siteId,e.id,e.sessionId));if({token:t,url:n}=l,r=l.expires_at?l.expires_at*1e3:void 0,ve.log("Got AI gateway information",{token:!!t,expiresAt:r,url:n}),r){let u=r-Date.now()-6e4;u>0&&(o=setTimeout(()=>{a()},u))}};return await Promise.all([a(),ze()]),{get url(){return n},get token(){return t},isModelAvailableForProvider:mn}};import oe from"process";import ae from"path";import Xe from"fs";import{fileURLToPath as En}from"url";import{createRequire as xn}from"module";import{execa as Tn,execaCommand as Ti}from"execa";import{Transform as gn}from"stream";function fn(){let e=process.env.NETLIFY_SENSITIVE_ENV_KEYS;return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function hn(e){let t=e.toLowerCase();return t==="true"||t==="false"?!0:e.trim().length<4}function yn(){let t=fn().map(r=>process.env[r]).filter(r=>!(!r||hn(r)));return[...new Set(t)].sort((r,o)=>o.length-r.length)}function se(e){if(typeof e!="string")return e;let t=yn();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(wn(o),"g");r=r.replace(n,"******")}),r}function wn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Ie=class extends gn{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),i=se(n);o(null,i)}};function nr(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(o,n,i){let s=typeof o=="string"?se(o):o;return typeof n=="function"?t(s,n):t(s,n,i)},process.stderr.write=function(o,n,i){let s=typeof o=="string"?se(o):o;return typeof n=="function"?r(s,n):r(s,n,i)}}var Me=null,or=e=>(Me&&Me.destroy(),Me=new de({totalAllowedTime:e}),Me),ir=()=>Me;var de=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,o)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let n=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),i=null,s=null;o!==void 0&&(s=new Promise((a,c)=>{i=setTimeout(()=>{c(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return s?await Promise.race([r(),s]):await r()}finally{n(),i&&clearTimeout(i)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var sr="netlify-agent-runner-context.md",gt="task-history",z=".netlify",he="results.md",ft="assets",ar="features";var lr="free";var ye=1800*1e3,f={Environment:"environment",UserMessage:"user-message",AgentMessage:"agent-message",Task:"task",RunCommand:"run-command",Explore:"explore",Plan:"plan",FileRead:"file-read",FileWrite:"file-write",Notebook:"notebook",Web:"web",Todo:"todo",Reasoning:"reasoning",Skill:"skill",Memorize:"memorize",Deployment:"deployment",SiteGeneration:"site-generation"};var cr={name:"@netlify/agent-runner-cli",type:"module",version:"1.95.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","test:integration:create-stage":"vitest run test/integration/create.test.ts","test:integration:skill-invocation":"vitest run test/integration/skill-invocation.test.ts","test:integration:feature-enablement":"vitest run test/integration/feature-enablement.test.ts","check:types":"tsc --noEmit",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" "!src/skills/**/*.md"'},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.87","@anthropic-ai/sdk":"0.78.0","@google/gemini-cli":"0.31.0","@netlify/otel":"^5.1.5","@netlify/ts-cli":"^1.0.4","@openai/codex":"0.115.0","@opentelemetry/exporter-trace-otlp-grpc":"0.57.2",execa:"^9.6.1",minimist:"^1.2.8",openai:"6.26.0"}};var vn=En(import.meta.url),In=ae.dirname(vn),Sn=xn(import.meta.url),Se=v("shell"),ht=new Set,bn={preferLocal:!0},P=(e,t,r)=>{let[o,n]=Rn(t,r),i={...bn,...n},s=Tn(e,o,i);An(s,i),Cn(s);let a=r?.idleTimeout;return a&&a>0&&kn(s,a),s};var Rn=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},An=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(oe.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new Ie).pipe(oe.stdout),e.stdout?.pipe(new Ie).pipe(oe.stdout),e.stderr?.pipe(new Ie).pipe(oe.stderr);return}e.stdout?.pipe(oe.stdout),e.stderr?.pipe(oe.stderr)},yt=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(oe.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}},ur=e=>yt(e,"SIGKILL"),kn=(e,t)=>{let r=null,o=()=>{Se.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),yt(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(Se.log(`Force killing idle process ${e.pid}`),ur(e))},5e3)},n=()=>{r&&clearTimeout(r),r=setTimeout(o,t)};n(),e.stdout?.on("data",n),e.stderr?.on("data",n);let i=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",i),e.on("error",i)},Cn=e=>{ht.add(e);let t=ir();if(t){let r=t.onTimesUp(()=>{Se.log(`Global timer expired, killing process ${e.pid}`),yt(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(Se.log(`Force killing process ${e.pid} after timeout`),ur(e))},5e3)});e.on("exit",()=>{ht.delete(e),r()}),e.on("error",()=>{ht.delete(e),r()})}};function Ze(e,t){return!!le(e,t)}function le(e,t){if(!oe.env.NETLIFY_LOCAL_MODE)try{let n=Sn.resolve(cr.name),i=ae.dirname(n);for(;i!==ae.dirname(i);){let s=ae.dirname(i);if(ae.basename(s)==="node_modules"){let a=ae.join(s,".bin",t);if(Xe.existsSync(a))return a;break}i=s}}catch(n){console.error("Could not resolve package.json",n)}if(oe.env.NODE_PATH){let n=ae.join(oe.env.NODE_PATH,".bin",t);if(Xe.existsSync(n))return n}let r=ae.join(e,"node_modules",".bin",t);if(Xe.existsSync(r))return r;let o=ae.join(In,"..","node_modules",".bin",t);if(Xe.existsSync(o))return o}import Pn from"process";var Nn="NETLIFY_FF_",Ue=()=>{let e={};for(let[t,r]of Object.entries(Pn.env))t.startsWith(Nn)&&r!==void 0&&(e[t]=r);return{byokEnabled:e.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED==="true"||e.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED==="1",skillVariations:Object.entries(e).filter(([t,r])=>t.startsWith("NETLIFY_FF_AGENT_RUNNER_SKILL_")&&(r==="true"||r==="1")).map(([t])=>t.replace("NETLIFY_FF_AGENT_RUNNER_SKILL_","").toLowerCase()),modelVersionOverrides:{codex:e.NETLIFY_FF_AGENT_RUNNER_CODEX_VERSION,claude:e.NETLIFY_FF_AGENT_RUNNER_CLAUDE_VERSION,gemini:e.NETLIFY_FF_AGENT_RUNNER_GEMINI_VERSION},raw:e}};var $n=v("utils"),On=e=>new Promise(t=>{setTimeout(t,e)}),Qe=(e,t=3e3)=>{let r=!1,o=null,n=[],i=null,s=(...a)=>{if(r)return o=a,new Promise(u=>{n.push(u)});r=!0;let c,l=new Promise(u=>{c=u});return i=(async()=>{await Promise.resolve();let u=await e(...a);for(c(u);;){if(await On(t),!o)return r=!1,i=null,u;let p=o,d=n;o=null,n=[],u=await e(...p),d.forEach(g=>{g(u)})}})(),l};return s.flush=async()=>{if((r||o)&&i)return await i,s.flush()},s},be=(e,t,r=!1)=>{let o=null,n=null,i=null,s=function(...a){n=a,i=this;let c=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(i,n),n=null,i=null)},t),c&&(e.apply(i,n),n=null,i=null)};return s.cancel=()=>{clearTimeout(o),o=null,n=null,i=null},s.flush=()=>{if(o){clearTimeout(o);let a=n,c=i;o=null,n=null,i=null,e.apply(c,a)}},s},dr=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):$n.error("Could not parse JSON",o))}},wt=e=>e.charAt(0).toUpperCase()+e.slice(1),pe=e=>e.split("-").map(t=>t.length===2?t.toUpperCase():wt(t)).join(" ");function we(e,t){t&&e.log(`Skill invoked: ${t}`)}var pr=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),mr=(e,t)=>{let n=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let a=`--${t}${n}`;if(a.length>55)return"";let c=60-a.length;if(c<=0)return"";if(c>=i.length+6){let l=Math.min(c-i.length,e.length);return`${i}${e.slice(0,l)}`}return e.slice(0,c)};var Fn=1e4,_t=(e,t=Fn)=>{if(!e||typeof e!="string"||e.length<=t)return e;let o=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+o};import{Buffer as gr}from"buffer";import Ln from"path";var fr=v("repo"),yr=async({config:e,isRetry:t,cwd:r=process.cwd()})=>{fr.info("Getting runner diffs");let o=await Mn(r),{hasChanges:n}=o,{status:i}=o;if(!n)return{hasChanges:!1};if(!t){let x=Gn(i);await jn(x,r)}fr.info("Changes after processing"),await xt(r);let s=await Tt(i,r);if(await Et(s,r),n=await Un(r),!n)return{hasChanges:!1,ignored:s};process.env.NETLIFY_INTERNAL_GIT="1";try{await P("git",["commit","-m","Agent runner"],{cwd:r})}finally{process.env.NETLIFY_INTERNAL_GIT="0"}let a={stdio:["ignore","pipe","pipe"],cwd:r},c=await P("git",["diff",e.runSha,"HEAD"],a),l=String(c.stdout??"");if(n=!!l,!n)return await hr(r),{hasChanges:!1,ignored:s};let u=await P("git",["diff",e.runSha,"HEAD","--binary"],a),p=String(u.stdout??""),d,g;if(e.sha){let x=await P("git",["diff",e.sha,"HEAD"],a);d=String(x.stdout??"");let w=await P("git",["diff",e.sha,"HEAD","--binary"],a),_=String(w.stdout??"");d!==_&&(g=gr.from(_).toString("base64"))}await hr(r);let I={hasChanges:!0,diff:l,resultDiff:d,ignored:s};return l!==p&&(I.diffBinary=gr.from(p).toString("base64")),g&&(I.resultDiffBinary=g),I},hr=async(e=process.cwd())=>{process.env.NETLIFY_LOCAL_MODE&&await P("git",["reset","--soft","HEAD~1"],{cwd:e})},Et=async(e=[],t=process.cwd())=>{process.env.NETLIFY_INTERNAL_GIT="1";try{await P("git",["add",".",...e],{cwd:t})}finally{process.env.NETLIFY_INTERNAL_GIT="0"}},xt=async(e=process.cwd())=>{let t=await P("git",["status","-s"],{cwd:e});return String(t.stdout??"")},wr=/.. (.+)?\.log$/,Dn=[wr],Mn=async(e=process.cwd())=>{let t=await xt(e);return{hasChanges:(t.trim().length===0?[]:t.split(`
8
+ `);return i.length>e.length*.8?e:i}import{execSync as ao}from"child_process";import $r from"fs/promises";import lo from"path";import Ee from"process";import{getTracer as co}from"@netlify/otel";import Le from"process";var ne=class extends Error{constructor(r,o,n,i=!1){super(r);this.statusCode=o;this.userMessage=n;this.isCreditLimitExceeded=i;this.name="GracefulShutdownError"}},Ve=e=>e instanceof ne;var Ke=Le.env.NETLIFY_API_URL,Je=Le.env.NETLIFY_API_TOKEN,V=v("api"),Te=()=>Le.env.NETLIFY_LOCAL_MODE==="true",ue=async(e,t={})=>{if(!Ke||!Je)throw new Error("No API URL or token");let r=new URL(e,Ke),o={...t,headers:{...t.headers,Authorization:`Bearer ${Je}`}};Le.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let n=await fetch(r,o),i=n.ok&&n.status<=299;if(Le.env.AGENT_RUNNERS_DEBUG==="true")V.log(`Response headers for ${r}:`),n.headers.forEach((a,c)=>{V.log(` ${c}: ${a}`)});else{let a=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");V.log(`Request ID for ${r}: ${a||"N/A"}`)}if(i||V.error(`Got status ${n.status} for request ${r}`),t.raw){if(!i)throw new Error(`API request failed: ${n.status} ${n.statusText}`);return n}let s=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!i){let a=typeof s=="string"?s:JSON.stringify(s);throw n.status===404?new ne(`API request failed: 404 - ${a}`,404,"The site associated with this agent run no longer exists."):n.status===503&&t.gracefulOn503&&a.toLowerCase().includes("usage exceeded")?new ne(`API request failed: 503 - ${a}`,503,"Credit limit reached. Please add more credits to continue using Agent Runners.",!0):new Error(`API request failed: ${n.status} - ${a}`)}return s},Kt=e=>{V.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Ke=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Je=e.constants.NETLIFY_API_TOKEN)},Jt=()=>({apiUrl:Ke,token:Je}),De=async(e,t)=>Te()?(V.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):ue(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),K=async(e,t,r)=>Te()?(V.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):ue(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var zt=async e=>Te()?(V.log("Mock API: getSite called",{siteId:e}),{id:e,published_deploy:{id:"id"}}):ue(`/api/v1/sites/${e}`),Xt=async(e,t)=>Te()?(V.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):ue(`/api/v1/agent_runners/${e}/sessions/${t}`),Zt=(e,t,r)=>ue(`/api/v1/accounts/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn503:!0}),Qt=(e,t,r)=>ue(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn503:!0}),er=async(e,t)=>Te()?(V.log("Mock API: getDiffUploadUrls called",{runnerId:e,sessionId:t}),{result:{upload_url:"https://s3.mock.com/mock-upload-url-result",s3_key:"mock-s3-key-result"},cumulative:{upload_url:"https://s3.mock.com/mock-upload-url-cumulative",s3_key:"mock-s3-key-cumulative"}}):ue(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),tr=async(e,t)=>Te()?(V.log("Mock API: updateSessionUsage called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,usage:0}):ue(`/api/v1/agent_runners/${e}/sessions/${t}/update_usage`,{method:"POST"}),pt=async(e,t,{maxRetries:r=3,baseDelayMs:o=500}={})=>{V.log(`Uploading diff to S3: ${e.substring(0,50)}...`);for(let n=1;n<=r;n++)try{let i=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"text/plain"}});if(!i.ok)throw new Error(`S3 upload failed with status ${i.status}`);return i}catch(i){if(n===r)throw i;let s=o*2**(n-1);V.warn(`S3 upload attempt ${n}/${r} failed: ${i.message}. Retrying in ${s}ms...`),await new Promise(a=>setTimeout(a,s))}};var ve=v("ai_gateway"),mt=null;var ze=async()=>{if(mt)return mt;ve.log("Fetching available AI gateway providers");let e=await fetch(`${Jt().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 mt=t,ve.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},mn=async(e,t)=>{let o=(await ze()).providers[e];if(!o)return ve.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return ve.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},rr=async({config:e})=>{let t,r,o,n,i=!e.site?.published_deploy;if(!(i?e.accountId:e.siteId))throw new Error(`No entity id for ${i?"account":"site"}`);let a=async()=>{clearTimeout(o),ve.log("Requesting AI gateway information");let l=await(i?Zt(e.accountId,e.id,e.sessionId):Qt(e.siteId,e.id,e.sessionId));if({token:t,url:n}=l,r=l.expires_at?l.expires_at*1e3:void 0,ve.log("Got AI gateway information",{token:!!t,expiresAt:r,url:n}),r){let u=r-Date.now()-6e4;u>0&&(o=setTimeout(()=>{a()},u))}};return await Promise.all([a(),ze()]),{get url(){return n},get token(){return t},isModelAvailableForProvider:mn}};import oe from"process";import ae from"path";import Xe from"fs";import{fileURLToPath as En}from"url";import{createRequire as xn}from"module";import{execa as Tn,execaCommand as Ti}from"execa";import{Transform as gn}from"stream";function fn(){let e=process.env.NETLIFY_SENSITIVE_ENV_KEYS;return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function hn(e){let t=e.toLowerCase();return t==="true"||t==="false"?!0:e.trim().length<4}function yn(){let t=fn().map(r=>process.env[r]).filter(r=>!(!r||hn(r)));return[...new Set(t)].sort((r,o)=>o.length-r.length)}function se(e){if(typeof e!="string")return e;let t=yn();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(wn(o),"g");r=r.replace(n,"******")}),r}function wn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Ie=class extends gn{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),i=se(n);o(null,i)}};function nr(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(o,n,i){let s=typeof o=="string"?se(o):o;return typeof n=="function"?t(s,n):t(s,n,i)},process.stderr.write=function(o,n,i){let s=typeof o=="string"?se(o):o;return typeof n=="function"?r(s,n):r(s,n,i)}}var Me=null,or=e=>(Me&&Me.destroy(),Me=new de({totalAllowedTime:e}),Me),ir=()=>Me;var de=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,o)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let n=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),i=null,s=null;o!==void 0&&(s=new Promise((a,c)=>{i=setTimeout(()=>{c(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return s?await Promise.race([r(),s]):await r()}finally{n(),i&&clearTimeout(i)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var sr="netlify-agent-runner-context.md",gt="task-history",z=".netlify",he="results.md",ft="assets",ar="features";var lr="free";var ye=1800*1e3,f={Environment:"environment",UserMessage:"user-message",AgentMessage:"agent-message",Task:"task",RunCommand:"run-command",Explore:"explore",Plan:"plan",FileRead:"file-read",FileWrite:"file-write",Notebook:"notebook",Web:"web",Todo:"todo",Reasoning:"reasoning",Skill:"skill",Memorize:"memorize",Deployment:"deployment",SiteGeneration:"site-generation"};var cr={name:"@netlify/agent-runner-cli",type:"module",version:"1.96.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","test:integration:create-stage":"vitest run test/integration/create.test.ts","test:integration:skill-invocation":"vitest run test/integration/skill-invocation.test.ts","test:integration:feature-enablement":"vitest run test/integration/feature-enablement.test.ts","check:types":"tsc --noEmit",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" "!src/skills/**/*.md"'},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.87","@anthropic-ai/sdk":"0.78.0","@google/gemini-cli":"0.31.0","@netlify/otel":"^5.1.5","@netlify/ts-cli":"^1.0.4","@openai/codex":"0.115.0","@opentelemetry/exporter-trace-otlp-grpc":"0.57.2",execa:"^9.6.1",minimist:"^1.2.8",openai:"6.26.0"}};var vn=En(import.meta.url),In=ae.dirname(vn),Sn=xn(import.meta.url),Se=v("shell"),ht=new Set,bn={preferLocal:!0},P=(e,t,r)=>{let[o,n]=Rn(t,r),i={...bn,...n},s=Tn(e,o,i);An(s,i),Cn(s);let a=r?.idleTimeout;return a&&a>0&&kn(s,a),s};var Rn=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},An=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(oe.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new Ie).pipe(oe.stdout),e.stdout?.pipe(new Ie).pipe(oe.stdout),e.stderr?.pipe(new Ie).pipe(oe.stderr);return}e.stdout?.pipe(oe.stdout),e.stderr?.pipe(oe.stderr)},yt=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(oe.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}},ur=e=>yt(e,"SIGKILL"),kn=(e,t)=>{let r=null,o=()=>{Se.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),yt(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(Se.log(`Force killing idle process ${e.pid}`),ur(e))},5e3)},n=()=>{r&&clearTimeout(r),r=setTimeout(o,t)};n(),e.stdout?.on("data",n),e.stderr?.on("data",n);let i=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",i),e.on("error",i)},Cn=e=>{ht.add(e);let t=ir();if(t){let r=t.onTimesUp(()=>{Se.log(`Global timer expired, killing process ${e.pid}`),yt(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(Se.log(`Force killing process ${e.pid} after timeout`),ur(e))},5e3)});e.on("exit",()=>{ht.delete(e),r()}),e.on("error",()=>{ht.delete(e),r()})}};function Ze(e,t){return!!le(e,t)}function le(e,t){if(!oe.env.NETLIFY_LOCAL_MODE)try{let n=Sn.resolve(cr.name),i=ae.dirname(n);for(;i!==ae.dirname(i);){let s=ae.dirname(i);if(ae.basename(s)==="node_modules"){let a=ae.join(s,".bin",t);if(Xe.existsSync(a))return a;break}i=s}}catch(n){console.error("Could not resolve package.json",n)}if(oe.env.NODE_PATH){let n=ae.join(oe.env.NODE_PATH,".bin",t);if(Xe.existsSync(n))return n}let r=ae.join(e,"node_modules",".bin",t);if(Xe.existsSync(r))return r;let o=ae.join(In,"..","node_modules",".bin",t);if(Xe.existsSync(o))return o}import Pn from"process";var Nn="NETLIFY_FF_",Ue=()=>{let e={};for(let[t,r]of Object.entries(Pn.env))t.startsWith(Nn)&&r!==void 0&&(e[t]=r);return{byokEnabled:e.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED==="true"||e.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED==="1",skillVariations:Object.entries(e).filter(([t,r])=>t.startsWith("NETLIFY_FF_AGENT_RUNNER_SKILL_")&&(r==="true"||r==="1")).map(([t])=>t.replace("NETLIFY_FF_AGENT_RUNNER_SKILL_","").toLowerCase()),modelVersionOverrides:{codex:e.NETLIFY_FF_AGENT_RUNNER_CODEX_VERSION,claude:e.NETLIFY_FF_AGENT_RUNNER_CLAUDE_VERSION,gemini:e.NETLIFY_FF_AGENT_RUNNER_GEMINI_VERSION},raw:e}};var $n=v("utils"),On=e=>new Promise(t=>{setTimeout(t,e)}),Qe=(e,t=3e3)=>{let r=!1,o=null,n=[],i=null,s=(...a)=>{if(r)return o=a,new Promise(u=>{n.push(u)});r=!0;let c,l=new Promise(u=>{c=u});return i=(async()=>{await Promise.resolve();let u=await e(...a);for(c(u);;){if(await On(t),!o)return r=!1,i=null,u;let p=o,d=n;o=null,n=[],u=await e(...p),d.forEach(g=>{g(u)})}})(),l};return s.flush=async()=>{if((r||o)&&i)return await i,s.flush()},s},be=(e,t,r=!1)=>{let o=null,n=null,i=null,s=function(...a){n=a,i=this;let c=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(i,n),n=null,i=null)},t),c&&(e.apply(i,n),n=null,i=null)};return s.cancel=()=>{clearTimeout(o),o=null,n=null,i=null},s.flush=()=>{if(o){clearTimeout(o);let a=n,c=i;o=null,n=null,i=null,e.apply(c,a)}},s},dr=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):$n.error("Could not parse JSON",o))}},wt=e=>e.charAt(0).toUpperCase()+e.slice(1),pe=e=>e.split("-").map(t=>t.length===2?t.toUpperCase():wt(t)).join(" ");function we(e,t){t&&e.log(`Skill invoked: ${t}`)}var pr=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),mr=(e,t)=>{let n=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let a=`--${t}${n}`;if(a.length>55)return"";let c=60-a.length;if(c<=0)return"";if(c>=i.length+6){let l=Math.min(c-i.length,e.length);return`${i}${e.slice(0,l)}`}return e.slice(0,c)};var Fn=1e4,_t=(e,t=Fn)=>{if(!e||typeof e!="string"||e.length<=t)return e;let o=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+o};import{Buffer as gr}from"buffer";import Ln from"path";var fr=v("repo"),yr=async({config:e,isRetry:t,cwd:r=process.cwd()})=>{fr.info("Getting runner diffs");let o=await Mn(r),{hasChanges:n}=o,{status:i}=o;if(!n)return{hasChanges:!1};if(!t){let x=Gn(i);await jn(x,r)}fr.info("Changes after processing"),await xt(r);let s=await Tt(i,r);if(await Et(s,r),n=await Un(r),!n)return{hasChanges:!1,ignored:s};process.env.NETLIFY_INTERNAL_GIT="1";try{await P("git",["commit","-m","Agent runner"],{cwd:r})}finally{process.env.NETLIFY_INTERNAL_GIT="0"}let a={stdio:["ignore","pipe","pipe"],cwd:r},c=await P("git",["diff",e.runSha,"HEAD"],a),l=String(c.stdout??"");if(n=!!l,!n)return await hr(r),{hasChanges:!1,ignored:s};let u=await P("git",["diff",e.runSha,"HEAD","--binary"],a),p=String(u.stdout??""),d,g;if(e.sha){let x=await P("git",["diff",e.sha,"HEAD"],a);d=String(x.stdout??"");let w=await P("git",["diff",e.sha,"HEAD","--binary"],a),_=String(w.stdout??"");d!==_&&(g=gr.from(_).toString("base64"))}await hr(r);let I={hasChanges:!0,diff:l,resultDiff:d,ignored:s};return l!==p&&(I.diffBinary=gr.from(p).toString("base64")),g&&(I.resultDiffBinary=g),I},hr=async(e=process.cwd())=>{process.env.NETLIFY_LOCAL_MODE&&await P("git",["reset","--soft","HEAD~1"],{cwd:e})},Et=async(e=[],t=process.cwd())=>{process.env.NETLIFY_INTERNAL_GIT="1";try{await P("git",["add",".",...e],{cwd:t})}finally{process.env.NETLIFY_INTERNAL_GIT="0"}},xt=async(e=process.cwd())=>{let t=await P("git",["status","-s"],{cwd:e});return String(t.stdout??"")},wr=/.. (.+)?\.log$/,Dn=[wr],Mn=async(e=process.cwd())=>{let t=await xt(e);return{hasChanges:(t.trim().length===0?[]:t.split(`
9
9
  `).filter(n=>Dn.some(s=>s instanceof RegExp?s.test(n):n===s)?!1:n[1]?.trim()!=="")).length!==0,status:t}},Un=async(e=process.cwd())=>{try{return await P("git",["diff","--staged","--quiet"],{cwd:e}),!1}catch{return!0}},Ge=async(e=process.cwd())=>{let{stdout:t}=await P("git",["rev-parse","HEAD"],{cwd:e});return String(t??"").trim()},_r=async(e=process.cwd())=>{let{stdout:t}=await P("git",["rev-list","--max-parents=0","HEAD"],{cwd:e});return String(t??"").trim()},Tt=async(e,t=process.cwd())=>{e||=await xt(t);let r=[".netlify","node_modules","dist",".next","out",".nuxt",".output",".cache",".turbo",".parcel-cache","coverage",".nyc_output","storybook-static","public/build","CLAUDE.local.md"],o=[];return e.split(`
10
10
  `).forEach(n=>{r.forEach(s=>{let a=n===`?? ${s}`,c=n.startsWith(`?? ${s}/`)||n.startsWith(`?? ${s}${Ln.sep}`);(a||c)&&o.push(`:!${s}`)});let i=n.match(wr)?.[1];i&&o.push(`:!${i}.log`)}),o},vt=async(e=process.cwd())=>{await P("git",["reset","--hard","HEAD"],{cwd:e})},Gn=e=>{let t=e.split(`
11
11
  `).reduce((r,o)=>{if(!o)return r;let[n,i,,...s]=o,a=s.join(""),c=n.trim(),l=i.trim();return r[a]?r[a].change=l:r[a]={filePath:a,stage:c,change:l},r},{});return Object.values(t)},jn=async(e,t=process.cwd())=>{let r=e.filter(o=>o.stage&&!o.change).map(o=>o.filePath);r.length!==0&&await P("git",["restore","--staged","--worktree","--pathspec-from-file=-"],{cwd:t,input:r.join(`
package/dist/bin.js CHANGED
@@ -5,7 +5,7 @@ import Ht from"process";import ri from"minimist";import{createRequire as Ho}from
5
5
  ${s}
6
6
  </extracted_error_chunk>`).join(`
7
7
 
8
- `);return i.length>e.length*.8?e:i}import{execSync as mo}from"child_process";import Ur from"fs/promises";import go from"path";import Ee from"process";import{getTracer as fo}from"@netlify/otel";import Le from"process";var te=class extends Error{constructor(r,o,n,i=!1){super(r);this.statusCode=o;this.userMessage=n;this.isCreditLimitExceeded=i;this.name="GracefulShutdownError"}},We=e=>e instanceof te;var Ve=Le.env.NETLIFY_API_URL,Ke=Le.env.NETLIFY_API_TOKEN,H=v("api"),Te=()=>Le.env.NETLIFY_LOCAL_MODE==="true",ae=async(e,t={})=>{if(!Ve||!Ke)throw new Error("No API URL or token");let r=new URL(e,Ve),o={...t,headers:{...t.headers,Authorization:`Bearer ${Ke}`}};Le.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let n=await fetch(r,o),i=n.ok&&n.status<=299;if(Le.env.AGENT_RUNNERS_DEBUG==="true")H.log(`Response headers for ${r}:`),n.headers.forEach((a,d)=>{H.log(` ${d}: ${a}`)});else{let a=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");H.log(`Request ID for ${r}: ${a||"N/A"}`)}if(i||H.error(`Got status ${n.status} for request ${r}`),t.raw){if(!i)throw new Error(`API request failed: ${n.status} ${n.statusText}`);return n}let s=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!i){let a=typeof s=="string"?s:JSON.stringify(s);throw n.status===404?new te(`API request failed: 404 - ${a}`,404,"The site associated with this agent run no longer exists."):n.status===503&&t.gracefulOn503&&a.toLowerCase().includes("usage exceeded")?new te(`API request failed: 503 - ${a}`,503,"Credit limit reached. Please add more credits to continue using Agent Runners.",!0):new Error(`API request failed: ${n.status} - ${a}`)}return s},Xt=e=>{H.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&&(Ke=e.constants.NETLIFY_API_TOKEN)},Zt=()=>({apiUrl:Ve,token:Ke}),De=async(e,t)=>Te()?(H.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):ae(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),W=async(e,t,r)=>Te()?(H.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):ae(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var Qt=async e=>Te()?(H.log("Mock API: getSite called",{siteId:e}),{id:e,published_deploy:{id:"id"}}):ae(`/api/v1/sites/${e}`),er=async(e,t)=>Te()?(H.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):ae(`/api/v1/agent_runners/${e}/sessions/${t}`),tr=(e,t,r)=>ae(`/api/v1/accounts/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn503:!0}),rr=(e,t,r)=>ae(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn503:!0}),nr=async(e,t)=>Te()?(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"}}):ae(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),or=async(e,t)=>Te()?(H.log("Mock API: updateSessionUsage called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,usage:0}):ae(`/api/v1/agent_runners/${e}/sessions/${t}/update_usage`,{method:"POST"}),dt=async(e,t,{maxRetries:r=3,baseDelayMs:o=500}={})=>{H.log(`Uploading diff to S3: ${e.substring(0,50)}...`);for(let n=1;n<=r;n++)try{let i=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"text/plain"}});if(!i.ok)throw new Error(`S3 upload failed with status ${i.status}`);return i}catch(i){if(n===r)throw i;let s=o*2**(n-1);H.warn(`S3 upload attempt ${n}/${r} failed: ${i.message}. Retrying in ${s}ms...`),await new Promise(a=>setTimeout(a,s))}};var xe=v("ai_gateway"),pt=null;var Je=async()=>{if(pt)return pt;xe.log("Fetching available AI gateway providers");let e=await fetch(`${Zt().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 pt=t,xe.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},_n=async(e,t)=>{let o=(await Je()).providers[e];if(!o)return xe.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return xe.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},ir=async({config:e})=>{let t,r,o,n,i=!e.site?.published_deploy;if(!(i?e.accountId:e.siteId))throw new Error(`No entity id for ${i?"account":"site"}`);let a=async()=>{clearTimeout(o),xe.log("Requesting AI gateway information");let l=await(i?tr(e.accountId,e.id,e.sessionId):rr(e.siteId,e.id,e.sessionId));if({token:t,url:n}=l,r=l.expires_at?l.expires_at*1e3:void 0,xe.log("Got AI gateway information",{token:!!t,expiresAt:r,url:n}),r){let u=r-Date.now()-6e4;u>0&&(o=setTimeout(()=>{a()},u))}};return await Promise.all([a(),Je()]),{get url(){return n},get token(){return t},isModelAvailableForProvider:_n}};import re from"process";import ie from"path";import ze from"fs";import{fileURLToPath as Sn}from"url";import{createRequire as Rn}from"module";import{execa as bn,execaCommand as Fi}from"execa";import{Transform as En}from"stream";function wn(){let e=process.env.NETLIFY_SENSITIVE_ENV_KEYS;return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function Tn(e){let t=e.toLowerCase();return t==="true"||t==="false"?!0:e.trim().length<4}function xn(){let t=wn().map(r=>process.env[r]).filter(r=>!(!r||Tn(r)));return[...new Set(t)].sort((r,o)=>o.length-r.length)}function oe(e){if(typeof e!="string")return e;let t=xn();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(vn(o),"g");r=r.replace(n,"******")}),r}function vn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ve=class extends En{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),i=oe(n);o(null,i)}};function sr(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(o,n,i){let s=typeof o=="string"?oe(o):o;return typeof n=="function"?t(s,n):t(s,n,i)},process.stderr.write=function(o,n,i){let s=typeof o=="string"?oe(o):o;return typeof n=="function"?r(s,n):r(s,n,i)}}var Me=null,ar=e=>(Me&&Me.destroy(),Me=new le({totalAllowedTime:e}),Me),lr=()=>Me;var le=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,o)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let n=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),i=null,s=null;o!==void 0&&(s=new Promise((a,d)=>{i=setTimeout(()=>{d(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return s?await Promise.race([r(),s]):await r()}finally{n(),i&&clearTimeout(i)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var cr="netlify-agent-runner-context.md",mt="task-history",J=".netlify",fe="results.md",gt="assets",ur="features",ft="other",ht="personal";var yt="enterprise",Ue="free",dr=[ht,"pro",yt,Ue],pr=["normal","redeploy","create","ask","dtn-prod-iteration","rebase"],mr="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.",he=1800*1e3,f={Environment:"environment",UserMessage:"user-message",AgentMessage:"agent-message",Task:"task",RunCommand:"run-command",Explore:"explore",Plan:"plan",FileRead:"file-read",FileWrite:"file-write",Notebook:"notebook",Web:"web",Todo:"todo",Reasoning:"reasoning",Skill:"skill",Memorize:"memorize",Deployment:"deployment",SiteGeneration:"site-generation"};var gr={name:"@netlify/agent-runner-cli",type:"module",version:"1.95.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","test:integration:create-stage":"vitest run test/integration/create.test.ts","test:integration:skill-invocation":"vitest run test/integration/skill-invocation.test.ts","test:integration:feature-enablement":"vitest run test/integration/feature-enablement.test.ts","check:types":"tsc --noEmit",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" "!src/skills/**/*.md"'},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.87","@anthropic-ai/sdk":"0.78.0","@google/gemini-cli":"0.31.0","@netlify/otel":"^5.1.5","@netlify/ts-cli":"^1.0.4","@openai/codex":"0.115.0","@opentelemetry/exporter-trace-otlp-grpc":"0.57.2",execa:"^9.6.1",minimist:"^1.2.8",openai:"6.26.0"}};var An=Sn(import.meta.url),Cn=ie.dirname(An),kn=Rn(import.meta.url),Ie=v("shell"),_t=new Set,Nn={preferLocal:!0},$=(e,t,r)=>{let[o,n]=Pn(t,r),i={...Nn,...n},s=bn(e,o,i);On(s,i),$n(s);let a=r?.idleTimeout;return a&&a>0&&Fn(s,a),s};var Pn=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},On=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(re.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new ve).pipe(re.stdout),e.stdout?.pipe(new ve).pipe(re.stdout),e.stderr?.pipe(new ve).pipe(re.stderr);return}e.stdout?.pipe(re.stdout),e.stderr?.pipe(re.stderr)},Et=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(re.kill(-e.pid,t),Ie.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return Ie.error("Error killing process:",r),!1}},fr=e=>Et(e,"SIGKILL"),Fn=(e,t)=>{let r=null,o=()=>{Ie.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),Et(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(Ie.log(`Force killing idle process ${e.pid}`),fr(e))},5e3)},n=()=>{r&&clearTimeout(r),r=setTimeout(o,t)};n(),e.stdout?.on("data",n),e.stderr?.on("data",n);let i=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",i),e.on("error",i)},$n=e=>{_t.add(e);let t=lr();if(t){let r=t.onTimesUp(()=>{Ie.log(`Global timer expired, killing process ${e.pid}`),Et(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(Ie.log(`Force killing process ${e.pid} after timeout`),fr(e))},5e3)});e.on("exit",()=>{_t.delete(e),r()}),e.on("error",()=>{_t.delete(e),r()})}};function ce(e,t){if(!re.env.NETLIFY_LOCAL_MODE)try{let n=kn.resolve(gr.name),i=ie.dirname(n);for(;i!==ie.dirname(i);){let s=ie.dirname(i);if(ie.basename(s)==="node_modules"){let a=ie.join(s,".bin",t);if(ze.existsSync(a))return a;break}i=s}}catch(n){console.error("Could not resolve package.json",n)}if(re.env.NODE_PATH){let n=ie.join(re.env.NODE_PATH,".bin",t);if(ze.existsSync(n))return n}let r=ie.join(e,"node_modules",".bin",t);if(ze.existsSync(r))return r;let o=ie.join(Cn,"..","node_modules",".bin",t);if(ze.existsSync(o))return o}import Ln from"process";var Dn="NETLIFY_FF_",ue=()=>{let e={};for(let[t,r]of Object.entries(Ln.env))t.startsWith(Dn)&&r!==void 0&&(e[t]=r);return{byokEnabled:e.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED==="true"||e.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED==="1",skillVariations:Object.entries(e).filter(([t,r])=>t.startsWith("NETLIFY_FF_AGENT_RUNNER_SKILL_")&&(r==="true"||r==="1")).map(([t])=>t.replace("NETLIFY_FF_AGENT_RUNNER_SKILL_","").toLowerCase()),modelVersionOverrides:{codex:e.NETLIFY_FF_AGENT_RUNNER_CODEX_VERSION,claude:e.NETLIFY_FF_AGENT_RUNNER_CLAUDE_VERSION,gemini:e.NETLIFY_FF_AGENT_RUNNER_GEMINI_VERSION},raw:e}};var hr=v("utils"),Mn=e=>new Promise(t=>{setTimeout(t,e)}),Xe=(e,t=3e3)=>{let r=!1,o=null,n=[],i=null,s=(...a)=>{if(r)return o=a,new Promise(u=>{n.push(u)});r=!0;let d,l=new Promise(u=>{d=u});return i=(async()=>{await Promise.resolve();let u=await e(...a);for(d(u);;){if(await Mn(t),!o)return r=!1,i=null,u;let p=o,c=n;o=null,n=[],u=await e(...p),c.forEach(g=>{g(u)})}})(),l};return s.flush=async()=>{if((r||o)&&i)return await i,s.flush()},s},Se=(e,t,r=!1)=>{let o=null,n=null,i=null,s=function(...a){n=a,i=this;let d=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(i,n),n=null,i=null)},t),d&&(e.apply(i,n),n=null,i=null)};return s.cancel=()=>{clearTimeout(o),o=null,n=null,i=null},s.flush=()=>{if(o){clearTimeout(o);let a=n,d=i;o=null,n=null,i=null,e.apply(d,a)}},s},Ze=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):hr.error("Could not parse JSON",o))}},wt=e=>e.charAt(0).toUpperCase()+e.slice(1),de=e=>e.split("-").map(t=>t.length===2?t.toUpperCase():wt(t)).join(" ");function ye(e,t){t&&e.log(`Skill invoked: ${t}`)}var yr=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),_r=(e,t)=>{let n=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let a=`--${t}${n}`;if(a.length>55)return"";let d=60-a.length;if(d<=0)return"";if(d>=i.length+6){let l=Math.min(d-i.length,e.length);return`${i}${e.slice(0,l)}`}return e.slice(0,d)},Un=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!dr.some(t=>t in e),Er=()=>{let e={},t=ue().modelVersionOverrides;return Object.entries(t).forEach(([r,o])=>{if(o)try{let n=JSON.parse(o);Un(n)&&(e[r]=n)}catch(n){let s=n instanceof SyntaxError?"Invalid JSON":n.message;hr.error(`Could not parse ${r} model version override from feature flag: ${s}`)}}),e},Gn=1e4,Tt=(e,t=Gn)=>{if(!e||typeof e!="string"||e.length<=t)return e;let o=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+o};import{Buffer as wr}from"buffer";import jn from"path";var Tr=v("repo"),vr=async({config:e,isRetry:t,cwd:r=process.cwd()})=>{Tr.info("Getting runner diffs");let o=await Bn(r),{hasChanges:n}=o,{status:i}=o;if(!n)return{hasChanges:!1};if(!t){let x=Hn(i);await Wn(x,r)}Tr.info("Changes after processing"),await vt(r);let s=await St(i,r);if(await xt(s,r),n=await qn(r),!n)return{hasChanges:!1,ignored:s};process.env.NETLIFY_INTERNAL_GIT="1";try{await $("git",["commit","-m","Agent runner"],{cwd:r})}finally{process.env.NETLIFY_INTERNAL_GIT="0"}let a={stdio:["ignore","pipe","pipe"],cwd:r},d=await $("git",["diff",e.runSha,"HEAD"],a),l=String(d.stdout??"");if(n=!!l,!n)return await xr(r),{hasChanges:!1,ignored:s};let u=await $("git",["diff",e.runSha,"HEAD","--binary"],a),p=String(u.stdout??""),c,g;if(e.sha){let x=await $("git",["diff",e.sha,"HEAD"],a);c=String(x.stdout??"");let y=await $("git",["diff",e.sha,"HEAD","--binary"],a),E=String(y.stdout??"");c!==E&&(g=wr.from(E).toString("base64"))}await xr(r);let I={hasChanges:!0,diff:l,resultDiff:c,ignored:s};return l!==p&&(I.diffBinary=wr.from(p).toString("base64")),g&&(I.resultDiffBinary=g),I},xr=async(e=process.cwd())=>{process.env.NETLIFY_LOCAL_MODE&&await $("git",["reset","--soft","HEAD~1"],{cwd:e})},xt=async(e=[],t=process.cwd())=>{process.env.NETLIFY_INTERNAL_GIT="1";try{await $("git",["add",".",...e],{cwd:t})}finally{process.env.NETLIFY_INTERNAL_GIT="0"}},vt=async(e=process.cwd())=>{let t=await $("git",["status","-s"],{cwd:e});return String(t.stdout??"")},Ir=/.. (.+)?\.log$/,Yn=[Ir],Bn=async(e=process.cwd())=>{let t=await vt(e);return{hasChanges:(t.trim().length===0?[]:t.split(`
8
+ `);return i.length>e.length*.8?e:i}import{execSync as mo}from"child_process";import Ur from"fs/promises";import go from"path";import Ee from"process";import{getTracer as fo}from"@netlify/otel";import Le from"process";var te=class extends Error{constructor(r,o,n,i=!1){super(r);this.statusCode=o;this.userMessage=n;this.isCreditLimitExceeded=i;this.name="GracefulShutdownError"}},We=e=>e instanceof te;var Ve=Le.env.NETLIFY_API_URL,Ke=Le.env.NETLIFY_API_TOKEN,H=v("api"),Te=()=>Le.env.NETLIFY_LOCAL_MODE==="true",ae=async(e,t={})=>{if(!Ve||!Ke)throw new Error("No API URL or token");let r=new URL(e,Ve),o={...t,headers:{...t.headers,Authorization:`Bearer ${Ke}`}};Le.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let n=await fetch(r,o),i=n.ok&&n.status<=299;if(Le.env.AGENT_RUNNERS_DEBUG==="true")H.log(`Response headers for ${r}:`),n.headers.forEach((a,d)=>{H.log(` ${d}: ${a}`)});else{let a=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");H.log(`Request ID for ${r}: ${a||"N/A"}`)}if(i||H.error(`Got status ${n.status} for request ${r}`),t.raw){if(!i)throw new Error(`API request failed: ${n.status} ${n.statusText}`);return n}let s=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!i){let a=typeof s=="string"?s:JSON.stringify(s);throw n.status===404?new te(`API request failed: 404 - ${a}`,404,"The site associated with this agent run no longer exists."):n.status===503&&t.gracefulOn503&&a.toLowerCase().includes("usage exceeded")?new te(`API request failed: 503 - ${a}`,503,"Credit limit reached. Please add more credits to continue using Agent Runners.",!0):new Error(`API request failed: ${n.status} - ${a}`)}return s},Xt=e=>{H.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&&(Ke=e.constants.NETLIFY_API_TOKEN)},Zt=()=>({apiUrl:Ve,token:Ke}),De=async(e,t)=>Te()?(H.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):ae(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),W=async(e,t,r)=>Te()?(H.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):ae(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var Qt=async e=>Te()?(H.log("Mock API: getSite called",{siteId:e}),{id:e,published_deploy:{id:"id"}}):ae(`/api/v1/sites/${e}`),er=async(e,t)=>Te()?(H.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):ae(`/api/v1/agent_runners/${e}/sessions/${t}`),tr=(e,t,r)=>ae(`/api/v1/accounts/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn503:!0}),rr=(e,t,r)=>ae(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn503:!0}),nr=async(e,t)=>Te()?(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"}}):ae(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),or=async(e,t)=>Te()?(H.log("Mock API: updateSessionUsage called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,usage:0}):ae(`/api/v1/agent_runners/${e}/sessions/${t}/update_usage`,{method:"POST"}),dt=async(e,t,{maxRetries:r=3,baseDelayMs:o=500}={})=>{H.log(`Uploading diff to S3: ${e.substring(0,50)}...`);for(let n=1;n<=r;n++)try{let i=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"text/plain"}});if(!i.ok)throw new Error(`S3 upload failed with status ${i.status}`);return i}catch(i){if(n===r)throw i;let s=o*2**(n-1);H.warn(`S3 upload attempt ${n}/${r} failed: ${i.message}. Retrying in ${s}ms...`),await new Promise(a=>setTimeout(a,s))}};var xe=v("ai_gateway"),pt=null;var Je=async()=>{if(pt)return pt;xe.log("Fetching available AI gateway providers");let e=await fetch(`${Zt().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 pt=t,xe.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},_n=async(e,t)=>{let o=(await Je()).providers[e];if(!o)return xe.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return xe.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},ir=async({config:e})=>{let t,r,o,n,i=!e.site?.published_deploy;if(!(i?e.accountId:e.siteId))throw new Error(`No entity id for ${i?"account":"site"}`);let a=async()=>{clearTimeout(o),xe.log("Requesting AI gateway information");let l=await(i?tr(e.accountId,e.id,e.sessionId):rr(e.siteId,e.id,e.sessionId));if({token:t,url:n}=l,r=l.expires_at?l.expires_at*1e3:void 0,xe.log("Got AI gateway information",{token:!!t,expiresAt:r,url:n}),r){let u=r-Date.now()-6e4;u>0&&(o=setTimeout(()=>{a()},u))}};return await Promise.all([a(),Je()]),{get url(){return n},get token(){return t},isModelAvailableForProvider:_n}};import re from"process";import ie from"path";import ze from"fs";import{fileURLToPath as Sn}from"url";import{createRequire as Rn}from"module";import{execa as bn,execaCommand as Fi}from"execa";import{Transform as En}from"stream";function wn(){let e=process.env.NETLIFY_SENSITIVE_ENV_KEYS;return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function Tn(e){let t=e.toLowerCase();return t==="true"||t==="false"?!0:e.trim().length<4}function xn(){let t=wn().map(r=>process.env[r]).filter(r=>!(!r||Tn(r)));return[...new Set(t)].sort((r,o)=>o.length-r.length)}function oe(e){if(typeof e!="string")return e;let t=xn();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(vn(o),"g");r=r.replace(n,"******")}),r}function vn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ve=class extends En{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),i=oe(n);o(null,i)}};function sr(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(o,n,i){let s=typeof o=="string"?oe(o):o;return typeof n=="function"?t(s,n):t(s,n,i)},process.stderr.write=function(o,n,i){let s=typeof o=="string"?oe(o):o;return typeof n=="function"?r(s,n):r(s,n,i)}}var Me=null,ar=e=>(Me&&Me.destroy(),Me=new le({totalAllowedTime:e}),Me),lr=()=>Me;var le=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,o)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let n=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),i=null,s=null;o!==void 0&&(s=new Promise((a,d)=>{i=setTimeout(()=>{d(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return s?await Promise.race([r(),s]):await r()}finally{n(),i&&clearTimeout(i)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var cr="netlify-agent-runner-context.md",mt="task-history",J=".netlify",fe="results.md",gt="assets",ur="features",ft="other",ht="personal";var yt="enterprise",Ue="free",dr=[ht,"pro",yt,Ue],pr=["normal","redeploy","create","ask","dtn-prod-iteration","rebase"],mr="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.",he=1800*1e3,f={Environment:"environment",UserMessage:"user-message",AgentMessage:"agent-message",Task:"task",RunCommand:"run-command",Explore:"explore",Plan:"plan",FileRead:"file-read",FileWrite:"file-write",Notebook:"notebook",Web:"web",Todo:"todo",Reasoning:"reasoning",Skill:"skill",Memorize:"memorize",Deployment:"deployment",SiteGeneration:"site-generation"};var gr={name:"@netlify/agent-runner-cli",type:"module",version:"1.96.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","test:integration:create-stage":"vitest run test/integration/create.test.ts","test:integration:skill-invocation":"vitest run test/integration/skill-invocation.test.ts","test:integration:feature-enablement":"vitest run test/integration/feature-enablement.test.ts","check:types":"tsc --noEmit",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" "!src/skills/**/*.md"'},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.87","@anthropic-ai/sdk":"0.78.0","@google/gemini-cli":"0.31.0","@netlify/otel":"^5.1.5","@netlify/ts-cli":"^1.0.4","@openai/codex":"0.115.0","@opentelemetry/exporter-trace-otlp-grpc":"0.57.2",execa:"^9.6.1",minimist:"^1.2.8",openai:"6.26.0"}};var An=Sn(import.meta.url),Cn=ie.dirname(An),kn=Rn(import.meta.url),Ie=v("shell"),_t=new Set,Nn={preferLocal:!0},$=(e,t,r)=>{let[o,n]=Pn(t,r),i={...Nn,...n},s=bn(e,o,i);On(s,i),$n(s);let a=r?.idleTimeout;return a&&a>0&&Fn(s,a),s};var Pn=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},On=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(re.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new ve).pipe(re.stdout),e.stdout?.pipe(new ve).pipe(re.stdout),e.stderr?.pipe(new ve).pipe(re.stderr);return}e.stdout?.pipe(re.stdout),e.stderr?.pipe(re.stderr)},Et=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(re.kill(-e.pid,t),Ie.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return Ie.error("Error killing process:",r),!1}},fr=e=>Et(e,"SIGKILL"),Fn=(e,t)=>{let r=null,o=()=>{Ie.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),Et(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(Ie.log(`Force killing idle process ${e.pid}`),fr(e))},5e3)},n=()=>{r&&clearTimeout(r),r=setTimeout(o,t)};n(),e.stdout?.on("data",n),e.stderr?.on("data",n);let i=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",i),e.on("error",i)},$n=e=>{_t.add(e);let t=lr();if(t){let r=t.onTimesUp(()=>{Ie.log(`Global timer expired, killing process ${e.pid}`),Et(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(Ie.log(`Force killing process ${e.pid} after timeout`),fr(e))},5e3)});e.on("exit",()=>{_t.delete(e),r()}),e.on("error",()=>{_t.delete(e),r()})}};function ce(e,t){if(!re.env.NETLIFY_LOCAL_MODE)try{let n=kn.resolve(gr.name),i=ie.dirname(n);for(;i!==ie.dirname(i);){let s=ie.dirname(i);if(ie.basename(s)==="node_modules"){let a=ie.join(s,".bin",t);if(ze.existsSync(a))return a;break}i=s}}catch(n){console.error("Could not resolve package.json",n)}if(re.env.NODE_PATH){let n=ie.join(re.env.NODE_PATH,".bin",t);if(ze.existsSync(n))return n}let r=ie.join(e,"node_modules",".bin",t);if(ze.existsSync(r))return r;let o=ie.join(Cn,"..","node_modules",".bin",t);if(ze.existsSync(o))return o}import Ln from"process";var Dn="NETLIFY_FF_",ue=()=>{let e={};for(let[t,r]of Object.entries(Ln.env))t.startsWith(Dn)&&r!==void 0&&(e[t]=r);return{byokEnabled:e.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED==="true"||e.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED==="1",skillVariations:Object.entries(e).filter(([t,r])=>t.startsWith("NETLIFY_FF_AGENT_RUNNER_SKILL_")&&(r==="true"||r==="1")).map(([t])=>t.replace("NETLIFY_FF_AGENT_RUNNER_SKILL_","").toLowerCase()),modelVersionOverrides:{codex:e.NETLIFY_FF_AGENT_RUNNER_CODEX_VERSION,claude:e.NETLIFY_FF_AGENT_RUNNER_CLAUDE_VERSION,gemini:e.NETLIFY_FF_AGENT_RUNNER_GEMINI_VERSION},raw:e}};var hr=v("utils"),Mn=e=>new Promise(t=>{setTimeout(t,e)}),Xe=(e,t=3e3)=>{let r=!1,o=null,n=[],i=null,s=(...a)=>{if(r)return o=a,new Promise(u=>{n.push(u)});r=!0;let d,l=new Promise(u=>{d=u});return i=(async()=>{await Promise.resolve();let u=await e(...a);for(d(u);;){if(await Mn(t),!o)return r=!1,i=null,u;let p=o,c=n;o=null,n=[],u=await e(...p),c.forEach(g=>{g(u)})}})(),l};return s.flush=async()=>{if((r||o)&&i)return await i,s.flush()},s},Se=(e,t,r=!1)=>{let o=null,n=null,i=null,s=function(...a){n=a,i=this;let d=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(i,n),n=null,i=null)},t),d&&(e.apply(i,n),n=null,i=null)};return s.cancel=()=>{clearTimeout(o),o=null,n=null,i=null},s.flush=()=>{if(o){clearTimeout(o);let a=n,d=i;o=null,n=null,i=null,e.apply(d,a)}},s},Ze=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):hr.error("Could not parse JSON",o))}},wt=e=>e.charAt(0).toUpperCase()+e.slice(1),de=e=>e.split("-").map(t=>t.length===2?t.toUpperCase():wt(t)).join(" ");function ye(e,t){t&&e.log(`Skill invoked: ${t}`)}var yr=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),_r=(e,t)=>{let n=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let a=`--${t}${n}`;if(a.length>55)return"";let d=60-a.length;if(d<=0)return"";if(d>=i.length+6){let l=Math.min(d-i.length,e.length);return`${i}${e.slice(0,l)}`}return e.slice(0,d)},Un=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!dr.some(t=>t in e),Er=()=>{let e={},t=ue().modelVersionOverrides;return Object.entries(t).forEach(([r,o])=>{if(o)try{let n=JSON.parse(o);Un(n)&&(e[r]=n)}catch(n){let s=n instanceof SyntaxError?"Invalid JSON":n.message;hr.error(`Could not parse ${r} model version override from feature flag: ${s}`)}}),e},Gn=1e4,Tt=(e,t=Gn)=>{if(!e||typeof e!="string"||e.length<=t)return e;let o=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+o};import{Buffer as wr}from"buffer";import jn from"path";var Tr=v("repo"),vr=async({config:e,isRetry:t,cwd:r=process.cwd()})=>{Tr.info("Getting runner diffs");let o=await Bn(r),{hasChanges:n}=o,{status:i}=o;if(!n)return{hasChanges:!1};if(!t){let x=Hn(i);await Wn(x,r)}Tr.info("Changes after processing"),await vt(r);let s=await St(i,r);if(await xt(s,r),n=await qn(r),!n)return{hasChanges:!1,ignored:s};process.env.NETLIFY_INTERNAL_GIT="1";try{await $("git",["commit","-m","Agent runner"],{cwd:r})}finally{process.env.NETLIFY_INTERNAL_GIT="0"}let a={stdio:["ignore","pipe","pipe"],cwd:r},d=await $("git",["diff",e.runSha,"HEAD"],a),l=String(d.stdout??"");if(n=!!l,!n)return await xr(r),{hasChanges:!1,ignored:s};let u=await $("git",["diff",e.runSha,"HEAD","--binary"],a),p=String(u.stdout??""),c,g;if(e.sha){let x=await $("git",["diff",e.sha,"HEAD"],a);c=String(x.stdout??"");let y=await $("git",["diff",e.sha,"HEAD","--binary"],a),E=String(y.stdout??"");c!==E&&(g=wr.from(E).toString("base64"))}await xr(r);let I={hasChanges:!0,diff:l,resultDiff:c,ignored:s};return l!==p&&(I.diffBinary=wr.from(p).toString("base64")),g&&(I.resultDiffBinary=g),I},xr=async(e=process.cwd())=>{process.env.NETLIFY_LOCAL_MODE&&await $("git",["reset","--soft","HEAD~1"],{cwd:e})},xt=async(e=[],t=process.cwd())=>{process.env.NETLIFY_INTERNAL_GIT="1";try{await $("git",["add",".",...e],{cwd:t})}finally{process.env.NETLIFY_INTERNAL_GIT="0"}},vt=async(e=process.cwd())=>{let t=await $("git",["status","-s"],{cwd:e});return String(t.stdout??"")},Ir=/.. (.+)?\.log$/,Yn=[Ir],Bn=async(e=process.cwd())=>{let t=await vt(e);return{hasChanges:(t.trim().length===0?[]:t.split(`
9
9
  `).filter(n=>Yn.some(s=>s instanceof RegExp?s.test(n):n===s)?!1:n[1]?.trim()!=="")).length!==0,status:t}},qn=async(e=process.cwd())=>{try{return await $("git",["diff","--staged","--quiet"],{cwd:e}),!1}catch{return!0}},It=async(e=process.cwd())=>{let{stdout:t}=await $("git",["rev-parse","HEAD"],{cwd:e});return String(t??"").trim()},Sr=async(e=process.cwd())=>{let{stdout:t}=await $("git",["rev-list","--max-parents=0","HEAD"],{cwd:e});return String(t??"").trim()},St=async(e,t=process.cwd())=>{e||=await vt(t);let r=[".netlify","node_modules","dist",".next","out",".nuxt",".output",".cache",".turbo",".parcel-cache","coverage",".nyc_output","storybook-static","public/build","CLAUDE.local.md"],o=[];return e.split(`
10
10
  `).forEach(n=>{r.forEach(s=>{let a=n===`?? ${s}`,d=n.startsWith(`?? ${s}/`)||n.startsWith(`?? ${s}${jn.sep}`);(a||d)&&o.push(`:!${s}`)});let i=n.match(Ir)?.[1];i&&o.push(`:!${i}.log`)}),o},Rt=async(e=process.cwd())=>{await $("git",["reset","--hard","HEAD"],{cwd:e})},Hn=e=>{let t=e.split(`
11
11
  `).reduce((r,o)=>{if(!o)return r;let[n,i,,...s]=o,a=s.join(""),d=n.trim(),l=i.trim();return r[a]?r[a].change=l:r[a]={filePath:a,stage:d,change:l},r},{});return Object.values(t)},Wn=async(e,t=process.cwd())=>{let r=e.filter(o=>o.stage&&!o.change).map(o=>o.filePath);r.length!==0&&await $("git",["restore","--staged","--worktree","--pathspec-from-file=-"],{cwd:t,input:r.join(`
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import{createRequire as Co}from"module";import{createTracerProvider as zr}from"@
4
4
  ${s}
5
5
  </extracted_error_chunk>`).join(`
6
6
 
7
- `);return i.length>e.length*.8?e:i}import{execSync as Xn}from"child_process";import Rr from"fs/promises";import Zn from"path";import ye from"process";import{getTracer as Qn}from"@netlify/otel";import $e from"process";var ee=class extends Error{constructor(r,o,n,i=!1){super(r);this.statusCode=o;this.userMessage=n;this.isCreditLimitExceeded=i;this.name="GracefulShutdownError"}},Be=e=>e instanceof ee;var qe=$e.env.NETLIFY_API_URL,He=$e.env.NETLIFY_API_TOKEN,H=v("api"),_e=()=>$e.env.NETLIFY_LOCAL_MODE==="true",se=async(e,t={})=>{if(!qe||!He)throw new Error("No API URL or token");let r=new URL(e,qe),o={...t,headers:{...t.headers,Authorization:`Bearer ${He}`}};$e.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let n=await fetch(r,o),i=n.ok&&n.status<=299;if($e.env.AGENT_RUNNERS_DEBUG==="true")H.log(`Response headers for ${r}:`),n.headers.forEach((a,d)=>{H.log(` ${d}: ${a}`)});else{let a=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");H.log(`Request ID for ${r}: ${a||"N/A"}`)}if(i||H.error(`Got status ${n.status} for request ${r}`),t.raw){if(!i)throw new Error(`API request failed: ${n.status} ${n.statusText}`);return n}let s=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!i){let a=typeof s=="string"?s:JSON.stringify(s);throw n.status===404?new ee(`API request failed: 404 - ${a}`,404,"The site associated with this agent run no longer exists."):n.status===503&&t.gracefulOn503&&a.toLowerCase().includes("usage exceeded")?new ee(`API request failed: 503 - ${a}`,503,"Credit limit reached. Please add more credits to continue using Agent Runners.",!0):new Error(`API request failed: ${n.status} - ${a}`)}return s},Yt=e=>{H.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(qe=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(He=e.constants.NETLIFY_API_TOKEN)},Bt=()=>({apiUrl:qe,token:He}),Oe=async(e,t)=>_e()?(H.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):se(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),W=async(e,t,r)=>_e()?(H.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):se(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var qt=async e=>_e()?(H.log("Mock API: getSite called",{siteId:e}),{id:e,published_deploy:{id:"id"}}):se(`/api/v1/sites/${e}`),Ht=async(e,t)=>_e()?(H.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):se(`/api/v1/agent_runners/${e}/sessions/${t}`),Wt=(e,t,r)=>se(`/api/v1/accounts/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn503:!0}),Vt=(e,t,r)=>se(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn503:!0}),Kt=async(e,t)=>_e()?(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"}}):se(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Jt=async(e,t)=>_e()?(H.log("Mock API: updateSessionUsage called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,usage:0}):se(`/api/v1/agent_runners/${e}/sessions/${t}/update_usage`,{method:"POST"}),at=async(e,t,{maxRetries:r=3,baseDelayMs:o=500}={})=>{H.log(`Uploading diff to S3: ${e.substring(0,50)}...`);for(let n=1;n<=r;n++)try{let i=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"text/plain"}});if(!i.ok)throw new Error(`S3 upload failed with status ${i.status}`);return i}catch(i){if(n===r)throw i;let s=o*2**(n-1);H.warn(`S3 upload attempt ${n}/${r} failed: ${i.message}. Retrying in ${s}ms...`),await new Promise(a=>setTimeout(a,s))}};var Ee=v("ai_gateway"),lt=null;var We=async()=>{if(lt)return lt;Ee.log("Fetching available AI gateway providers");let e=await fetch(`${Bt().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 lt=t,Ee.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},rn=async(e,t)=>{let o=(await We()).providers[e];if(!o)return Ee.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return Ee.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},zt=async({config:e})=>{let t,r,o,n,i=!e.site?.published_deploy;if(!(i?e.accountId:e.siteId))throw new Error(`No entity id for ${i?"account":"site"}`);let a=async()=>{clearTimeout(o),Ee.log("Requesting AI gateway information");let l=await(i?Wt(e.accountId,e.id,e.sessionId):Vt(e.siteId,e.id,e.sessionId));if({token:t,url:n}=l,r=l.expires_at?l.expires_at*1e3:void 0,Ee.log("Got AI gateway information",{token:!!t,expiresAt:r,url:n}),r){let u=r-Date.now()-6e4;u>0&&(o=setTimeout(()=>{a()},u))}};return await Promise.all([a(),We()]),{get url(){return n},get token(){return t},isModelAvailableForProvider:rn}};import te from"process";import oe from"path";import Ve from"fs";import{fileURLToPath as un}from"url";import{createRequire as dn}from"module";import{execa as pn,execaCommand as ui}from"execa";import{Transform as nn}from"stream";function on(){let e=process.env.NETLIFY_SENSITIVE_ENV_KEYS;return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function sn(e){let t=e.toLowerCase();return t==="true"||t==="false"?!0:e.trim().length<4}function an(){let t=on().map(r=>process.env[r]).filter(r=>!(!r||sn(r)));return[...new Set(t)].sort((r,o)=>o.length-r.length)}function ne(e){if(typeof e!="string")return e;let t=an();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(ln(o),"g");r=r.replace(n,"******")}),r}function ln(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var xe=class extends nn{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),i=ne(n);o(null,i)}};function Xt(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(o,n,i){let s=typeof o=="string"?ne(o):o;return typeof n=="function"?t(s,n):t(s,n,i)},process.stderr.write=function(o,n,i){let s=typeof o=="string"?ne(o):o;return typeof n=="function"?r(s,n):r(s,n,i)}}var Fe=null,Zt=e=>(Fe&&Fe.destroy(),Fe=new ae({totalAllowedTime:e}),Fe),Qt=()=>Fe;var ae=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,o)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let n=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),i=null,s=null;o!==void 0&&(s=new Promise((a,d)=>{i=setTimeout(()=>{d(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return s?await Promise.race([r(),s]):await r()}finally{n(),i&&clearTimeout(i)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var er="netlify-agent-runner-context.md",ct="task-history",K=".netlify",me="results.md",ut="assets",tr="features";var rr="free";var ge=1800*1e3,f={Environment:"environment",UserMessage:"user-message",AgentMessage:"agent-message",Task:"task",RunCommand:"run-command",Explore:"explore",Plan:"plan",FileRead:"file-read",FileWrite:"file-write",Notebook:"notebook",Web:"web",Todo:"todo",Reasoning:"reasoning",Skill:"skill",Memorize:"memorize",Deployment:"deployment",SiteGeneration:"site-generation"};var nr={name:"@netlify/agent-runner-cli",type:"module",version:"1.95.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","test:integration:create-stage":"vitest run test/integration/create.test.ts","test:integration:skill-invocation":"vitest run test/integration/skill-invocation.test.ts","test:integration:feature-enablement":"vitest run test/integration/feature-enablement.test.ts","check:types":"tsc --noEmit",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" "!src/skills/**/*.md"'},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.87","@anthropic-ai/sdk":"0.78.0","@google/gemini-cli":"0.31.0","@netlify/otel":"^5.1.5","@netlify/ts-cli":"^1.0.4","@openai/codex":"0.115.0","@opentelemetry/exporter-trace-otlp-grpc":"0.57.2",execa:"^9.6.1",minimist:"^1.2.8",openai:"6.26.0"}};var mn=un(import.meta.url),gn=oe.dirname(mn),fn=dn(import.meta.url),Te=v("shell"),dt=new Set,hn={preferLocal:!0},F=(e,t,r)=>{let[o,n]=yn(t,r),i={...hn,...n},s=pn(e,o,i);wn(s,i),En(s);let a=r?.idleTimeout;return a&&a>0&&_n(s,a),s};var yn=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},wn=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(te.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new xe).pipe(te.stdout),e.stdout?.pipe(new xe).pipe(te.stdout),e.stderr?.pipe(new xe).pipe(te.stderr);return}e.stdout?.pipe(te.stdout),e.stderr?.pipe(te.stderr)},pt=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(te.kill(-e.pid,t),Te.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return Te.error("Error killing process:",r),!1}},or=e=>pt(e,"SIGKILL"),_n=(e,t)=>{let r=null,o=()=>{Te.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),pt(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(Te.log(`Force killing idle process ${e.pid}`),or(e))},5e3)},n=()=>{r&&clearTimeout(r),r=setTimeout(o,t)};n(),e.stdout?.on("data",n),e.stderr?.on("data",n);let i=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",i),e.on("error",i)},En=e=>{dt.add(e);let t=Qt();if(t){let r=t.onTimesUp(()=>{Te.log(`Global timer expired, killing process ${e.pid}`),pt(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(Te.log(`Force killing process ${e.pid} after timeout`),or(e))},5e3)});e.on("exit",()=>{dt.delete(e),r()}),e.on("error",()=>{dt.delete(e),r()})}};function le(e,t){if(!te.env.NETLIFY_LOCAL_MODE)try{let n=fn.resolve(nr.name),i=oe.dirname(n);for(;i!==oe.dirname(i);){let s=oe.dirname(i);if(oe.basename(s)==="node_modules"){let a=oe.join(s,".bin",t);if(Ve.existsSync(a))return a;break}i=s}}catch(n){console.error("Could not resolve package.json",n)}if(te.env.NODE_PATH){let n=oe.join(te.env.NODE_PATH,".bin",t);if(Ve.existsSync(n))return n}let r=oe.join(e,"node_modules",".bin",t);if(Ve.existsSync(r))return r;let o=oe.join(gn,"..","node_modules",".bin",t);if(Ve.existsSync(o))return o}import xn from"process";var Tn="NETLIFY_FF_",Le=()=>{let e={};for(let[t,r]of Object.entries(xn.env))t.startsWith(Tn)&&r!==void 0&&(e[t]=r);return{byokEnabled:e.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED==="true"||e.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED==="1",skillVariations:Object.entries(e).filter(([t,r])=>t.startsWith("NETLIFY_FF_AGENT_RUNNER_SKILL_")&&(r==="true"||r==="1")).map(([t])=>t.replace("NETLIFY_FF_AGENT_RUNNER_SKILL_","").toLowerCase()),modelVersionOverrides:{codex:e.NETLIFY_FF_AGENT_RUNNER_CODEX_VERSION,claude:e.NETLIFY_FF_AGENT_RUNNER_CLAUDE_VERSION,gemini:e.NETLIFY_FF_AGENT_RUNNER_GEMINI_VERSION},raw:e}};var vn=v("utils"),Sn=e=>new Promise(t=>{setTimeout(t,e)}),Ke=(e,t=3e3)=>{let r=!1,o=null,n=[],i=null,s=(...a)=>{if(r)return o=a,new Promise(u=>{n.push(u)});r=!0;let d,l=new Promise(u=>{d=u});return i=(async()=>{await Promise.resolve();let u=await e(...a);for(d(u);;){if(await Sn(t),!o)return r=!1,i=null,u;let p=o,c=n;o=null,n=[],u=await e(...p),c.forEach(g=>{g(u)})}})(),l};return s.flush=async()=>{if((r||o)&&i)return await i,s.flush()},s},ve=(e,t,r=!1)=>{let o=null,n=null,i=null,s=function(...a){n=a,i=this;let d=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(i,n),n=null,i=null)},t),d&&(e.apply(i,n),n=null,i=null)};return s.cancel=()=>{clearTimeout(o),o=null,n=null,i=null},s.flush=()=>{if(o){clearTimeout(o);let a=n,d=i;o=null,n=null,i=null,e.apply(d,a)}},s},ir=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):vn.error("Could not parse JSON",o))}},mt=e=>e.charAt(0).toUpperCase()+e.slice(1),ce=e=>e.split("-").map(t=>t.length===2?t.toUpperCase():mt(t)).join(" ");function fe(e,t){t&&e.log(`Skill invoked: ${t}`)}var sr=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),ar=(e,t)=>{let n=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let a=`--${t}${n}`;if(a.length>55)return"";let d=60-a.length;if(d<=0)return"";if(d>=i.length+6){let l=Math.min(d-i.length,e.length);return`${i}${e.slice(0,l)}`}return e.slice(0,d)};var In=1e4,gt=(e,t=In)=>{if(!e||typeof e!="string"||e.length<=t)return e;let o=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+o};import{Buffer as lr}from"buffer";import bn from"path";var cr=v("repo"),dr=async({config:e,isRetry:t,cwd:r=process.cwd()})=>{cr.info("Getting runner diffs");let o=await An(r),{hasChanges:n}=o,{status:i}=o;if(!n)return{hasChanges:!1};if(!t){let x=Cn(i);await Pn(x,r)}cr.info("Changes after processing"),await ht(r);let s=await wt(i,r);if(await ft(s,r),n=await kn(r),!n)return{hasChanges:!1,ignored:s};process.env.NETLIFY_INTERNAL_GIT="1";try{await F("git",["commit","-m","Agent runner"],{cwd:r})}finally{process.env.NETLIFY_INTERNAL_GIT="0"}let a={stdio:["ignore","pipe","pipe"],cwd:r},d=await F("git",["diff",e.runSha,"HEAD"],a),l=String(d.stdout??"");if(n=!!l,!n)return await ur(r),{hasChanges:!1,ignored:s};let u=await F("git",["diff",e.runSha,"HEAD","--binary"],a),p=String(u.stdout??""),c,g;if(e.sha){let x=await F("git",["diff",e.sha,"HEAD"],a);c=String(x.stdout??"");let w=await F("git",["diff",e.sha,"HEAD","--binary"],a),_=String(w.stdout??"");c!==_&&(g=lr.from(_).toString("base64"))}await ur(r);let S={hasChanges:!0,diff:l,resultDiff:c,ignored:s};return l!==p&&(S.diffBinary=lr.from(p).toString("base64")),g&&(S.resultDiffBinary=g),S},ur=async(e=process.cwd())=>{process.env.NETLIFY_LOCAL_MODE&&await F("git",["reset","--soft","HEAD~1"],{cwd:e})},ft=async(e=[],t=process.cwd())=>{process.env.NETLIFY_INTERNAL_GIT="1";try{await F("git",["add",".",...e],{cwd:t})}finally{process.env.NETLIFY_INTERNAL_GIT="0"}},ht=async(e=process.cwd())=>{let t=await F("git",["status","-s"],{cwd:e});return String(t.stdout??"")},pr=/.. (.+)?\.log$/,Rn=[pr],An=async(e=process.cwd())=>{let t=await ht(e);return{hasChanges:(t.trim().length===0?[]:t.split(`
7
+ `);return i.length>e.length*.8?e:i}import{execSync as Xn}from"child_process";import Rr from"fs/promises";import Zn from"path";import ye from"process";import{getTracer as Qn}from"@netlify/otel";import $e from"process";var ee=class extends Error{constructor(r,o,n,i=!1){super(r);this.statusCode=o;this.userMessage=n;this.isCreditLimitExceeded=i;this.name="GracefulShutdownError"}},Be=e=>e instanceof ee;var qe=$e.env.NETLIFY_API_URL,He=$e.env.NETLIFY_API_TOKEN,H=v("api"),_e=()=>$e.env.NETLIFY_LOCAL_MODE==="true",se=async(e,t={})=>{if(!qe||!He)throw new Error("No API URL or token");let r=new URL(e,qe),o={...t,headers:{...t.headers,Authorization:`Bearer ${He}`}};$e.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let n=await fetch(r,o),i=n.ok&&n.status<=299;if($e.env.AGENT_RUNNERS_DEBUG==="true")H.log(`Response headers for ${r}:`),n.headers.forEach((a,d)=>{H.log(` ${d}: ${a}`)});else{let a=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");H.log(`Request ID for ${r}: ${a||"N/A"}`)}if(i||H.error(`Got status ${n.status} for request ${r}`),t.raw){if(!i)throw new Error(`API request failed: ${n.status} ${n.statusText}`);return n}let s=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!i){let a=typeof s=="string"?s:JSON.stringify(s);throw n.status===404?new ee(`API request failed: 404 - ${a}`,404,"The site associated with this agent run no longer exists."):n.status===503&&t.gracefulOn503&&a.toLowerCase().includes("usage exceeded")?new ee(`API request failed: 503 - ${a}`,503,"Credit limit reached. Please add more credits to continue using Agent Runners.",!0):new Error(`API request failed: ${n.status} - ${a}`)}return s},Yt=e=>{H.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(qe=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(He=e.constants.NETLIFY_API_TOKEN)},Bt=()=>({apiUrl:qe,token:He}),Oe=async(e,t)=>_e()?(H.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):se(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),W=async(e,t,r)=>_e()?(H.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):se(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var qt=async e=>_e()?(H.log("Mock API: getSite called",{siteId:e}),{id:e,published_deploy:{id:"id"}}):se(`/api/v1/sites/${e}`),Ht=async(e,t)=>_e()?(H.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):se(`/api/v1/agent_runners/${e}/sessions/${t}`),Wt=(e,t,r)=>se(`/api/v1/accounts/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn503:!0}),Vt=(e,t,r)=>se(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn503:!0}),Kt=async(e,t)=>_e()?(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"}}):se(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Jt=async(e,t)=>_e()?(H.log("Mock API: updateSessionUsage called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,usage:0}):se(`/api/v1/agent_runners/${e}/sessions/${t}/update_usage`,{method:"POST"}),at=async(e,t,{maxRetries:r=3,baseDelayMs:o=500}={})=>{H.log(`Uploading diff to S3: ${e.substring(0,50)}...`);for(let n=1;n<=r;n++)try{let i=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"text/plain"}});if(!i.ok)throw new Error(`S3 upload failed with status ${i.status}`);return i}catch(i){if(n===r)throw i;let s=o*2**(n-1);H.warn(`S3 upload attempt ${n}/${r} failed: ${i.message}. Retrying in ${s}ms...`),await new Promise(a=>setTimeout(a,s))}};var Ee=v("ai_gateway"),lt=null;var We=async()=>{if(lt)return lt;Ee.log("Fetching available AI gateway providers");let e=await fetch(`${Bt().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 lt=t,Ee.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},rn=async(e,t)=>{let o=(await We()).providers[e];if(!o)return Ee.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return Ee.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},zt=async({config:e})=>{let t,r,o,n,i=!e.site?.published_deploy;if(!(i?e.accountId:e.siteId))throw new Error(`No entity id for ${i?"account":"site"}`);let a=async()=>{clearTimeout(o),Ee.log("Requesting AI gateway information");let l=await(i?Wt(e.accountId,e.id,e.sessionId):Vt(e.siteId,e.id,e.sessionId));if({token:t,url:n}=l,r=l.expires_at?l.expires_at*1e3:void 0,Ee.log("Got AI gateway information",{token:!!t,expiresAt:r,url:n}),r){let u=r-Date.now()-6e4;u>0&&(o=setTimeout(()=>{a()},u))}};return await Promise.all([a(),We()]),{get url(){return n},get token(){return t},isModelAvailableForProvider:rn}};import te from"process";import oe from"path";import Ve from"fs";import{fileURLToPath as un}from"url";import{createRequire as dn}from"module";import{execa as pn,execaCommand as ui}from"execa";import{Transform as nn}from"stream";function on(){let e=process.env.NETLIFY_SENSITIVE_ENV_KEYS;return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function sn(e){let t=e.toLowerCase();return t==="true"||t==="false"?!0:e.trim().length<4}function an(){let t=on().map(r=>process.env[r]).filter(r=>!(!r||sn(r)));return[...new Set(t)].sort((r,o)=>o.length-r.length)}function ne(e){if(typeof e!="string")return e;let t=an();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(ln(o),"g");r=r.replace(n,"******")}),r}function ln(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var xe=class extends nn{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),i=ne(n);o(null,i)}};function Xt(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(o,n,i){let s=typeof o=="string"?ne(o):o;return typeof n=="function"?t(s,n):t(s,n,i)},process.stderr.write=function(o,n,i){let s=typeof o=="string"?ne(o):o;return typeof n=="function"?r(s,n):r(s,n,i)}}var Fe=null,Zt=e=>(Fe&&Fe.destroy(),Fe=new ae({totalAllowedTime:e}),Fe),Qt=()=>Fe;var ae=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,o)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let n=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),i=null,s=null;o!==void 0&&(s=new Promise((a,d)=>{i=setTimeout(()=>{d(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return s?await Promise.race([r(),s]):await r()}finally{n(),i&&clearTimeout(i)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var er="netlify-agent-runner-context.md",ct="task-history",K=".netlify",me="results.md",ut="assets",tr="features";var rr="free";var ge=1800*1e3,f={Environment:"environment",UserMessage:"user-message",AgentMessage:"agent-message",Task:"task",RunCommand:"run-command",Explore:"explore",Plan:"plan",FileRead:"file-read",FileWrite:"file-write",Notebook:"notebook",Web:"web",Todo:"todo",Reasoning:"reasoning",Skill:"skill",Memorize:"memorize",Deployment:"deployment",SiteGeneration:"site-generation"};var nr={name:"@netlify/agent-runner-cli",type:"module",version:"1.96.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","test:integration:create-stage":"vitest run test/integration/create.test.ts","test:integration:skill-invocation":"vitest run test/integration/skill-invocation.test.ts","test:integration:feature-enablement":"vitest run test/integration/feature-enablement.test.ts","check:types":"tsc --noEmit",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" "!src/skills/**/*.md"'},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.87","@anthropic-ai/sdk":"0.78.0","@google/gemini-cli":"0.31.0","@netlify/otel":"^5.1.5","@netlify/ts-cli":"^1.0.4","@openai/codex":"0.115.0","@opentelemetry/exporter-trace-otlp-grpc":"0.57.2",execa:"^9.6.1",minimist:"^1.2.8",openai:"6.26.0"}};var mn=un(import.meta.url),gn=oe.dirname(mn),fn=dn(import.meta.url),Te=v("shell"),dt=new Set,hn={preferLocal:!0},F=(e,t,r)=>{let[o,n]=yn(t,r),i={...hn,...n},s=pn(e,o,i);wn(s,i),En(s);let a=r?.idleTimeout;return a&&a>0&&_n(s,a),s};var yn=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},wn=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(te.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new xe).pipe(te.stdout),e.stdout?.pipe(new xe).pipe(te.stdout),e.stderr?.pipe(new xe).pipe(te.stderr);return}e.stdout?.pipe(te.stdout),e.stderr?.pipe(te.stderr)},pt=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(te.kill(-e.pid,t),Te.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return Te.error("Error killing process:",r),!1}},or=e=>pt(e,"SIGKILL"),_n=(e,t)=>{let r=null,o=()=>{Te.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),pt(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(Te.log(`Force killing idle process ${e.pid}`),or(e))},5e3)},n=()=>{r&&clearTimeout(r),r=setTimeout(o,t)};n(),e.stdout?.on("data",n),e.stderr?.on("data",n);let i=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",i),e.on("error",i)},En=e=>{dt.add(e);let t=Qt();if(t){let r=t.onTimesUp(()=>{Te.log(`Global timer expired, killing process ${e.pid}`),pt(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(Te.log(`Force killing process ${e.pid} after timeout`),or(e))},5e3)});e.on("exit",()=>{dt.delete(e),r()}),e.on("error",()=>{dt.delete(e),r()})}};function le(e,t){if(!te.env.NETLIFY_LOCAL_MODE)try{let n=fn.resolve(nr.name),i=oe.dirname(n);for(;i!==oe.dirname(i);){let s=oe.dirname(i);if(oe.basename(s)==="node_modules"){let a=oe.join(s,".bin",t);if(Ve.existsSync(a))return a;break}i=s}}catch(n){console.error("Could not resolve package.json",n)}if(te.env.NODE_PATH){let n=oe.join(te.env.NODE_PATH,".bin",t);if(Ve.existsSync(n))return n}let r=oe.join(e,"node_modules",".bin",t);if(Ve.existsSync(r))return r;let o=oe.join(gn,"..","node_modules",".bin",t);if(Ve.existsSync(o))return o}import xn from"process";var Tn="NETLIFY_FF_",Le=()=>{let e={};for(let[t,r]of Object.entries(xn.env))t.startsWith(Tn)&&r!==void 0&&(e[t]=r);return{byokEnabled:e.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED==="true"||e.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED==="1",skillVariations:Object.entries(e).filter(([t,r])=>t.startsWith("NETLIFY_FF_AGENT_RUNNER_SKILL_")&&(r==="true"||r==="1")).map(([t])=>t.replace("NETLIFY_FF_AGENT_RUNNER_SKILL_","").toLowerCase()),modelVersionOverrides:{codex:e.NETLIFY_FF_AGENT_RUNNER_CODEX_VERSION,claude:e.NETLIFY_FF_AGENT_RUNNER_CLAUDE_VERSION,gemini:e.NETLIFY_FF_AGENT_RUNNER_GEMINI_VERSION},raw:e}};var vn=v("utils"),Sn=e=>new Promise(t=>{setTimeout(t,e)}),Ke=(e,t=3e3)=>{let r=!1,o=null,n=[],i=null,s=(...a)=>{if(r)return o=a,new Promise(u=>{n.push(u)});r=!0;let d,l=new Promise(u=>{d=u});return i=(async()=>{await Promise.resolve();let u=await e(...a);for(d(u);;){if(await Sn(t),!o)return r=!1,i=null,u;let p=o,c=n;o=null,n=[],u=await e(...p),c.forEach(g=>{g(u)})}})(),l};return s.flush=async()=>{if((r||o)&&i)return await i,s.flush()},s},ve=(e,t,r=!1)=>{let o=null,n=null,i=null,s=function(...a){n=a,i=this;let d=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(i,n),n=null,i=null)},t),d&&(e.apply(i,n),n=null,i=null)};return s.cancel=()=>{clearTimeout(o),o=null,n=null,i=null},s.flush=()=>{if(o){clearTimeout(o);let a=n,d=i;o=null,n=null,i=null,e.apply(d,a)}},s},ir=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):vn.error("Could not parse JSON",o))}},mt=e=>e.charAt(0).toUpperCase()+e.slice(1),ce=e=>e.split("-").map(t=>t.length===2?t.toUpperCase():mt(t)).join(" ");function fe(e,t){t&&e.log(`Skill invoked: ${t}`)}var sr=e=>Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0)),ar=(e,t)=>{let n=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let a=`--${t}${n}`;if(a.length>55)return"";let d=60-a.length;if(d<=0)return"";if(d>=i.length+6){let l=Math.min(d-i.length,e.length);return`${i}${e.slice(0,l)}`}return e.slice(0,d)};var In=1e4,gt=(e,t=In)=>{if(!e||typeof e!="string"||e.length<=t)return e;let o=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+o};import{Buffer as lr}from"buffer";import bn from"path";var cr=v("repo"),dr=async({config:e,isRetry:t,cwd:r=process.cwd()})=>{cr.info("Getting runner diffs");let o=await An(r),{hasChanges:n}=o,{status:i}=o;if(!n)return{hasChanges:!1};if(!t){let x=Cn(i);await Pn(x,r)}cr.info("Changes after processing"),await ht(r);let s=await wt(i,r);if(await ft(s,r),n=await kn(r),!n)return{hasChanges:!1,ignored:s};process.env.NETLIFY_INTERNAL_GIT="1";try{await F("git",["commit","-m","Agent runner"],{cwd:r})}finally{process.env.NETLIFY_INTERNAL_GIT="0"}let a={stdio:["ignore","pipe","pipe"],cwd:r},d=await F("git",["diff",e.runSha,"HEAD"],a),l=String(d.stdout??"");if(n=!!l,!n)return await ur(r),{hasChanges:!1,ignored:s};let u=await F("git",["diff",e.runSha,"HEAD","--binary"],a),p=String(u.stdout??""),c,g;if(e.sha){let x=await F("git",["diff",e.sha,"HEAD"],a);c=String(x.stdout??"");let w=await F("git",["diff",e.sha,"HEAD","--binary"],a),_=String(w.stdout??"");c!==_&&(g=lr.from(_).toString("base64"))}await ur(r);let S={hasChanges:!0,diff:l,resultDiff:c,ignored:s};return l!==p&&(S.diffBinary=lr.from(p).toString("base64")),g&&(S.resultDiffBinary=g),S},ur=async(e=process.cwd())=>{process.env.NETLIFY_LOCAL_MODE&&await F("git",["reset","--soft","HEAD~1"],{cwd:e})},ft=async(e=[],t=process.cwd())=>{process.env.NETLIFY_INTERNAL_GIT="1";try{await F("git",["add",".",...e],{cwd:t})}finally{process.env.NETLIFY_INTERNAL_GIT="0"}},ht=async(e=process.cwd())=>{let t=await F("git",["status","-s"],{cwd:e});return String(t.stdout??"")},pr=/.. (.+)?\.log$/,Rn=[pr],An=async(e=process.cwd())=>{let t=await ht(e);return{hasChanges:(t.trim().length===0?[]:t.split(`
8
8
  `).filter(n=>Rn.some(s=>s instanceof RegExp?s.test(n):n===s)?!1:n[1]?.trim()!=="")).length!==0,status:t}},kn=async(e=process.cwd())=>{try{return await F("git",["diff","--staged","--quiet"],{cwd:e}),!1}catch{return!0}},yt=async(e=process.cwd())=>{let{stdout:t}=await F("git",["rev-parse","HEAD"],{cwd:e});return String(t??"").trim()},mr=async(e=process.cwd())=>{let{stdout:t}=await F("git",["rev-list","--max-parents=0","HEAD"],{cwd:e});return String(t??"").trim()},wt=async(e,t=process.cwd())=>{e||=await ht(t);let r=[".netlify","node_modules","dist",".next","out",".nuxt",".output",".cache",".turbo",".parcel-cache","coverage",".nyc_output","storybook-static","public/build","CLAUDE.local.md"],o=[];return e.split(`
9
9
  `).forEach(n=>{r.forEach(s=>{let a=n===`?? ${s}`,d=n.startsWith(`?? ${s}/`)||n.startsWith(`?? ${s}${bn.sep}`);(a||d)&&o.push(`:!${s}`)});let i=n.match(pr)?.[1];i&&o.push(`:!${i}.log`)}),o},_t=async(e=process.cwd())=>{await F("git",["reset","--hard","HEAD"],{cwd:e})},Cn=e=>{let t=e.split(`
10
10
  `).reduce((r,o)=>{if(!o)return r;let[n,i,,...s]=o,a=s.join(""),d=n.trim(),l=i.trim();return r[a]?r[a].change=l:r[a]={filePath:a,stage:d,change:l},r},{});return Object.values(t)},Pn=async(e,t=process.cwd())=>{let r=e.filter(o=>o.stage&&!o.change).map(o=>o.filePath);r.length!==0&&await F("git",["restore","--staged","--worktree","--pathspec-from-file=-"],{cwd:t,input:r.join(`
@@ -24,6 +24,9 @@ There are two recommended approaches:
24
24
  `drizzle-orm` soon), and `drizzle-kit`.
25
25
  - **Native `@netlify/db` driver**: Use the `sql` tagged template literal for direct SQL queries. Install `@netlify/db`.
26
26
 
27
+ IMPORTANT: Any code that assumes a different database schema requires a corresponding migration file in
28
+ `netlify/db/migrations/`. Without a migration, the database schema will not change and the application will break.
29
+
27
30
  See the **netlify-db** skill for complete setup instructions and usage examples.
28
31
 
29
32
  ## Key-value data: Netlify Blobs
@@ -23,6 +23,18 @@ This affects:
23
23
 
24
24
  The `drizzle-kit` package is NOT affected — use the regular `drizzle-kit` package.
25
25
 
26
+ ## CRITICAL: Database schema changes always require migrations
27
+
28
+ Any code change that assumes a different database schema (adding tables, adding columns, renaming fields, changing types,
29
+ adding indexes, etc.) will only work if a corresponding migration exists in `netlify/db/migrations/`. Without a
30
+ migration, the database schema will not change and the application will break at runtime.
31
+
32
+ This applies regardless of whether you are using Drizzle ORM or the native `@netlify/db` driver:
33
+ - **With Drizzle ORM**: Update the schema definition, then run `npx drizzle-kit generate`
34
+ - **With native driver**: Write a new SQL migration file in `netlify/db/migrations/`
35
+
36
+ Never consider a schema change complete without a corresponding migration file.
37
+
26
38
  ## Setup with Drizzle ORM (recommended)
27
39
 
28
40
  This is the recommended approach. It gives you type-safe schema definitions, a query builder, and automatic migration
@@ -148,6 +160,17 @@ export const config: Config = {
148
160
  };
149
161
  ```
150
162
 
163
+ ### Modifying an existing schema
164
+
165
+ When adding columns, tables, or changing the schema in an existing project:
166
+
167
+ 1. Update the Drizzle schema definition with your changes
168
+ 2. Run `npx drizzle-kit generate` — this is REQUIRED, not optional
169
+ 3. Verify new migration files appear in `netlify/db/migrations/`
170
+ 4. Update any application code that uses the changed tables
171
+
172
+ Do NOT skip step 2. The database will not reflect your schema changes without a generated migration.
173
+
151
174
  ### Drizzle ORM query reference
152
175
 
153
176
  ```typescript
@@ -322,8 +345,10 @@ Drizzle Kit generates migrations in the subdirectory format. Both formats can co
322
345
  2. **Using `drizzle-orm` instead of `netlify-drizzle-orm-tests`**: The Netlify DB adapter is not yet in the main
323
346
  `drizzle-orm` package. Use `netlify-drizzle-orm-tests` for all Drizzle imports.
324
347
 
325
- 3. **Forgetting to run `drizzle-kit generate`**: After changing `db/schema.ts`, you must run `npx drizzle-kit generate`
326
- to create migration files. Schema changes alone do nothing the migration files are what Netlify applies.
348
+ 3. **NEVER skip migration generation after schema changes**: Any code that assumes a different database schema requires
349
+ a corresponding migration in `netlify/db/migrations/`. With Drizzle ORM, run `npx drizzle-kit generate` after
350
+ updating the schema definition. With the native driver, write a SQL migration file. Schema changes alone do
351
+ nothing — the migration files are what Netlify applies. The application WILL break without them.
327
352
 
328
353
  4. **Editing generated migrations**: Never manually edit migrations created by Drizzle Kit. If you need to change
329
354
  something, update the schema and generate a new migration.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@netlify/agent-runner-cli",
3
3
  "type": "module",
4
- "version": "1.95.0",
4
+ "version": "1.96.0",
5
5
  "description": "CLI tool for running Netlify agents",
6
6
  "main": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",