@netlify/agent-runner-cli 1.61.0-alpha → 1.61.2-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin-local.js CHANGED
@@ -1,36 +1,62 @@
1
1
  #!/usr/bin/env node
2
- import C from"process";import fr from"path";import mr from"fs";import Pn from"minimist";import{createRequire as An}from"module";import{createTracerProvider as hr}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as ft}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as yr}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as _r}from"@netlify/otel";import{propagation as mt,context as gt,W3CTraceContextPropagator as Er}from"@netlify/otel/opentelemetry";import{OTLPTraceExporter as wr}from"@opentelemetry/exporter-trace-otlp-grpc";import gr from"process";function _(e){let t=gr.env.LOG!=="0";return{log:(...r)=>{t&&console.log(`[AR]-[${e}]`,...r)},error:(...r)=>{t&&console.error(`[AR]-[ERROR]-[${e}]`,...r)},warn:(...r)=>{t&&console.warn(`[AR]-[WARN]-[${e}]`,...r)},info:(...r)=>{t&&console.info(`[AR]-[${e}]`,...r)},debug:(...r)=>{t&&console.debug(`[AR]-[DEBUG]-[${e}]`,...r)}}}var Be=_("tracing"),ht=async(e,t,r)=>(await hr({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new ft(new He),new ft(new wr({url:r.exporterUrl}))],instrumentations:[new yr({skipHeaders:!0})]}),r.traceparent?(mt.setGlobalPropagator(new Er),mt.extract(gt.active(),{traceparent:r.traceparent,isRemote:!0})):gt.active());function b(e,t,r){return Be.log(`\u23F3 TRACE: ${t} starting...`),_r(e,t,r)}var He=class{export(t,r){for(let o of t)this.logSpan(o);r({code:1})}async shutdown(){}forceFlush(){return Promise.resolve()}logSpan(t){let r=(t.endTime[0]-t.startTime[0])*1e3+(t.endTime[1]-t.startTime[1])/1e6,o=t.attributes,n=[];for(let[c,l]of Object.entries(o))c.includes("duration")&&typeof l=="number"?n.push(`${c}=${l.toFixed(2)}ms`):n.push(`${c}=${l}`);let i=t.status?.code===2?"\u274C":"\u2705",s=n.length>0?` [${n.join(", ")}]`:"";Be.log(`${i} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${s}`),t.status?.code===2&&t.status.message&&Be.log(` \u274C Error: ${t.status.message}`)}};var Tr=["error","failed","exception","fatal","panic","abort","crash"];function yt(e){let t=e.split(`
3
- `),r=[],o=-1,n=0;for(;n<t.length;){let c=t[n].slice(0,500).toLowerCase();if(Tr.some(p=>c.includes(p))){let p=Math.max(0,n-10,o+1),f=Math.min(t.length-1,n+20),u=[];for(let m=p;m<=f;m++)u.push(t[m]);r.push(u.join(`
2
+ import C from"process";import pr from"path";import fr from"fs";import Pn from"minimist";import{createRequire as An}from"module";import{createTracerProvider as gr}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as ft}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as hr}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as yr}from"@netlify/otel";import{propagation as mt,context as gt,W3CTraceContextPropagator as _r}from"@netlify/otel/opentelemetry";import{OTLPTraceExporter as Er}from"@opentelemetry/exporter-trace-otlp-grpc";import mr from"process";function _(e){let t=mr.env.LOG!=="0";return{log:(...r)=>{t&&console.log(`[AR]-[${e}]`,...r)},error:(...r)=>{t&&console.error(`[AR]-[ERROR]-[${e}]`,...r)},warn:(...r)=>{t&&console.warn(`[AR]-[WARN]-[${e}]`,...r)},info:(...r)=>{t&&console.info(`[AR]-[${e}]`,...r)},debug:(...r)=>{t&&console.debug(`[AR]-[DEBUG]-[${e}]`,...r)}}}var Be=_("tracing"),ht=async(e,t,r)=>(await gr({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new ft(new He),new ft(new Er({url:r.exporterUrl}))],instrumentations:[new hr({skipHeaders:!0})]}),r.traceparent?(mt.setGlobalPropagator(new _r),mt.extract(gt.active(),{traceparent:r.traceparent,isRemote:!0})):gt.active());function b(e,t,r){return Be.log(`\u23F3 TRACE: ${t} starting...`),yr(e,t,r)}var He=class{export(t,r){for(let o of t)this.logSpan(o);r({code:1})}async shutdown(){}forceFlush(){return Promise.resolve()}logSpan(t){let r=(t.endTime[0]-t.startTime[0])*1e3+(t.endTime[1]-t.startTime[1])/1e6,o=t.attributes,n=[];for(let[c,l]of Object.entries(o))c.includes("duration")&&typeof l=="number"?n.push(`${c}=${l.toFixed(2)}ms`):n.push(`${c}=${l}`);let i=t.status?.code===2?"\u274C":"\u2705",s=n.length>0?` [${n.join(", ")}]`:"";Be.log(`${i} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${s}`),t.status?.code===2&&t.status.message&&Be.log(` \u274C Error: ${t.status.message}`)}};var wr=["error","failed","exception","fatal","panic","abort","crash"];function yt(e){let t=e.split(`
3
+ `),r=[],o=-1,n=0;for(;n<t.length;){let c=t[n].slice(0,500).toLowerCase();if(wr.some(p=>c.includes(p))){let p=Math.max(0,n-10,o+1),f=Math.min(t.length-1,n+20),u=[];for(let m=p;m<=f;m++)u.push(t[m]);r.push(u.join(`
4
4
  `)),o=f,n=f+1}else n++}if(r.length===0)return e;let i=r.map((s,c)=>`<extracted_error_chunk order="${c+1}">
5
5
  ${s}
6
6
  </extracted_error_chunk>`).join(`
7
7
 
8
- `);return i.length>e.length*.8?e:i}import Qt from"fs/promises";import er from"path";import xe from"process";import{getTracer as un}from"@netlify/otel";import _e from"process";var oe=class extends Error{constructor(r,o,n){super(r);this.statusCode=o;this.userMessage=n;this.name="GracefulShutdownError"}},_t=e=>e instanceof oe;var Ae=_e.env.NETLIFY_API_URL,Ne=_e.env.NETLIFY_API_TOKEN,H=_("api"),Ce=()=>_e.env.NETLIFY_LOCAL_MODE==="true",Ee=async(e,t={})=>{if(!Ae||!Ne)throw new Error("No API URL or token");let r=new URL(e,Ae),o={...t,headers:{...t.headers,Authorization:`Bearer ${Ne}`}};_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((c,l)=>{H.log(` ${l}: ${c}`)});else{let c=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");H.log(`Request ID for ${r}: ${c||"N/A"}`)}if(i||H.error(`Got status ${n.status} for request ${r}`),t.raw){if(!i)throw new Error(`API request failed: ${n.status} ${n.statusText}`);return n}let s=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!i){let c=typeof s=="string"?s:JSON.stringify(s);throw n.status===404?new oe(`API request failed: 404 - ${c}`,404,"The site associated with this agent run no longer exists."):n.status===403&&t.gracefulOn403?new oe(`API request failed: 403 - ${c}`,403,"Credit limit reached. Please add more credits to continue using Agent Runners."):new Error(`API request failed: ${n.status} - ${c}`)}return s},Et=e=>{H.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Ae=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Ne=e.constants.NETLIFY_API_TOKEN)},wt=()=>({apiUrl:Ae,token:Ne}),we=async(e,t)=>Ce()?(H.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):Ee(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),q=async(e,t,r)=>Ce()?(H.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):Ee(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var Tt=async(e,t)=>Ce()?(H.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):Ee(`/api/v1/agent_runners/${e}/sessions/${t}`),It=(e,t,r)=>Ee(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn403:!0}),xt=async(e,t)=>Ce()?(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"}}):Ee(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),qe=async(e,t)=>{H.log(`Uploading diff to S3: ${e.substring(0,50)}...`);let r=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"text/plain"}});if(!r.ok)throw new Error(`S3 upload failed with status ${r.status}`);return r};var ie=_("ai_gateway"),Ke=null;var vt=async()=>{if(Ke)return Ke;ie.log("Fetching available AI gateway providers");let e=await fetch(`${wt().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 Ke=t,ie.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},Ir=async(e,t)=>{let o=(await vt()).providers[e];if(!o)return ie.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return ie.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},Rt=async({netlify:e,config:t})=>{let r,o,n,i,s=e.constants?.SITE_ID;if(!s)throw new Error("No site id");let c=async()=>{clearTimeout(n),ie.log("Requesting AI gateway information");let l=await It(s,t.id,t.sessionId);if({token:r,url:i}=l,o=l.expires_at?l.expires_at*1e3:void 0,ie.log("Got AI gateway information",{token:!!r,expiresAt:o,url:i}),o){let p=o-Date.now()-6e4;p>0&&(n=setTimeout(()=>{c()},p))}};return await Promise.all([c(),vt()]),{get url(){return i},get token(){return r},isModelAvailableForProvider:Ir}};import K from"process";import V from"path";import Pe from"fs";import{fileURLToPath as Nr}from"url";import{createRequire as Cr}from"module";import{execa as Pr,execaCommand as uo}from"execa";import{Transform as xr}from"stream";var vr=new Set(["NODE_ENV","PATH","HOME","USER","USERNAME","SHELL","PWD","OLDPWD","TMPDIR","TMP","TEMP","LANG","TERM","EDITOR","PAGER","OS","PROCESSOR_ARCHITECTURE","PROCESSOR_IDENTIFIER","SYSTEMROOT","WINDIR","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","APPDATA","LOCALAPPDATA","NODE_OPTIONS","NODE_PATH","NODE_DEBUG","NODE_NO_WARNINGS","npm_config_registry","npm_config_cache","npm_execpath","npm_node_execpath","CI","GITHUB_ACTIONS","GITHUB_WORKSPACE","GITHUB_REPOSITORY","GITHUB_REF","BUILDKITE","BUILDKITE_BRANCH","BUILDKITE_COMMIT","BUILDKITE_BUILD_NUMBER","JENKINS_URL","TRAVIS","CIRCLECI","DISPLAY","COLORTERM","TERM_PROGRAM","TERM_PROGRAM_VERSION","COLUMNS","LINES","HISTSIZE","HISTFILE","NETLIFY_AGENT_RUNNER_ID","NETLIFY_AGENT_RUNNER_SESSION_ID","NETLIFY_AGENT_RUNNER_PROMPT","NETLIFY_AGENT_RUNNER_AGENT","NETLIFY_AGENT_RUNNER_MODEL","NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED","NETLIFY_AGENT_RUNNER_CONTEXT","NETLIFY_AGENT_RUNNER_HAS_REPO","NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED","NETLIFY_AGENT_RUNNER_SHA","NETLIFY_TEAM_TYPE","AGENT_RUNNERS_DEBUG","NETLIFY_TEAM_ID","NETLIFY_AGENT_RUNNER_USER_ID","SITE_NAME"]),Rr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function Sr(){return Object.entries(process.env).filter(([e,t])=>!(!t||vr.has(e)||Rr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function J(e){if(typeof e!="string")return e;let t=Sr();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(br(o),"g");r=r.replace(n,"******")}),r}function br(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var se=class extends xr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),i=J(n);o(null,i)}};function St(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(o,n,i){let s=typeof o=="string"?J(o):o;return typeof n=="function"?t(s,n):t(s,n,i)},process.stderr.write=function(o,n,i){let s=typeof o=="string"?J(o):o;return typeof n=="function"?r(s,n):r(s,n,i)}}var Te=null,bt=e=>(Te&&Te.destroy(),Te=new ee({totalAllowedTime:e}),Te),At=()=>Te;var ee=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,o)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let n=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),i=null,s=null;o!==void 0&&(s=new Promise((c,l)=>{i=setTimeout(()=>{l(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return s?await Promise.race([r(),s]):await r()}finally{n(),i&&clearTimeout(i)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var Nt="netlify-agent-runner-context.md",We="task-history",Je="netlify-context",U=".netlify",ae="results.md",Ve="assets";var te=1800*1e3;var Ct={name:"@netlify/agent-runner-cli",type:"module",version:"1.61.0-alpha",description:"CLI tool for running Netlify agents",main:"./dist/index.js",types:"./dist/index.d.ts",exports:"./dist/index.js",bin:{"agent-runner-cli":"./dist/bin.js","agent-runner-cli-local":"./dist/bin-local.js"},files:["dist/**/*.js","dist/**/*.d.ts","patches","scripts"],scripts:{build:"tsup",dev:"tsup --watch",prepare:"husky install node_modules/@netlify/eslint-config-node/.husky/",prepublishOnly:"npm ci && npm test",prepack:"npm run build",test:"run-s build format test:dev",format:"run-s build format:check-fix:*","format:ci":"run-s build format:check:*","format:check-fix:lint":"run-e format:check:lint format:fix:lint","format:check:lint":"cross-env-shell eslint $npm_package_config_eslint","format:fix:lint":"cross-env-shell eslint --fix $npm_package_config_eslint","format:check-fix:prettier":"run-e format:check:prettier format:fix:prettier","format:check:prettier":"cross-env-shell prettier --check $npm_package_config_prettier","format:fix:prettier":"cross-env-shell prettier --write $npm_package_config_prettier","test:dev":"run-s build test:dev:*","test:ci":"run-s build test:ci:*","test:dev:vitest":"LOG=0 vitest --exclude '**/integration/**'","test:ci:vitest":"LOG=0 c8 -r lcovonly -r text -r json vitest --exclude '**/integration/**'","test:integration":"vitest run test/integration/","test:integration:codex":"vitest run test/integration/codex.test.ts","test:integration:claude":"vitest run test/integration/claude.test.ts","test:integration:gemini":"vitest run test/integration/gemini.test.ts",postinstall:"node scripts/postinstall.js"},config:{eslint:'--cache --format=codeframe --max-warnings=0 "{src,scripts,test,.github}/**/*.{js,ts,md,html}"',prettier:'--ignore-path .gitignore --loglevel=warn "{src,scripts,test,.github}/**/*.{js,ts,md,yml,json,html}" "*.{js,ts,yml,json,html}" ".*.{js,ts,yml,json,html}" "!**/package-lock.json" "!package-lock.json"'},keywords:[],license:"MIT",repository:"netlify/agent-runner-cli",bugs:{url:"https://github.com/netlify/agent-runner-cli/issues"},author:"Netlify Inc.",directories:{test:"test"},devDependencies:{"@commitlint/cli":"^20.0.0","@commitlint/config-conventional":"^20.0.0","@eslint/compat":"^2.0.0","@eslint/js":"^9.35.0","@netlify/eslint-config-node":"^7.0.1","@types/node":"^24.5.0","@typescript-eslint/eslint-plugin":"^8.0.0","@typescript-eslint/parser":"^8.0.0","@vitest/eslint-plugin":"^1.6.6",c8:"^10.0.0","eslint-config-prettier":"^10.1.8","eslint-plugin-n":"^17.0.0",husky:"^9.0.0","patch-package":"^8.0.0",tsup:"^8.5.0",typescript:"^5.0.0","typescript-eslint":"^8.44.0",vitest:"^4.0.16"},dependencies:{"@anthropic-ai/claude-code":"2.0.76","@google/gemini-cli":"0.23.0","@netlify/otel":"^5.1.1","@openai/codex":"0.81.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.208.0",execa:"^9.6.1",minimist:"^1.2.8"}};var Or=Nr(import.meta.url),Fr=V.dirname(Or),$r=Cr(import.meta.url),le=_("shell"),Xe=new Set,kr={preferLocal:!0},N=(e,t,r)=>{let[o,n]=Dr(t,r),i={...kr,...n},s=Pr(e,o,i);Lr(s,i),Mr(s);let c=r?.idleTimeout;return c&&c>0&&Ur(s,c),s};var Dr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Lr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(K.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new se).pipe(K.stdout),e.stdout?.pipe(new se).pipe(K.stdout),e.stderr?.pipe(new se).pipe(K.stderr);return}e.stdout?.pipe(K.stdout),e.stderr?.pipe(K.stderr)},ze=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(K.kill(-e.pid,t),le.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return le.error("Error killing process:",r),!1}},Pt=e=>ze(e,"SIGKILL"),Ur=(e,t)=>{let r=null,o=()=>{le.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),ze(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(le.log(`Force killing idle process ${e.pid}`),Pt(e))},5e3)},n=()=>{r&&clearTimeout(r),r=setTimeout(o,t)};n(),e.stdout?.on("data",n),e.stderr?.on("data",n);let i=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",i),e.on("error",i)},Mr=e=>{Xe.add(e);let t=At();if(t){let r=t.onTimesUp(()=>{le.log(`Global timer expired, killing process ${e.pid}`),ze(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(le.log(`Force killing process ${e.pid} after timeout`),Pt(e))},5e3)});e.on("exit",()=>{Xe.delete(e),r()}),e.on("error",()=>{Xe.delete(e),r()})}};function Oe(e,t){return!!re(e,t)}function re(e,t){if(!K.env.NETLIFY_LOCAL_MODE)try{let n=$r.resolve(Ct.name),i=V.dirname(n);for(;i!==V.dirname(i);){let s=V.dirname(i);if(V.basename(s)==="node_modules"){let c=V.join(s,".bin",t);if(Pe.existsSync(c))return c;break}i=s}}catch(n){console.error("Could not resolve package.json",n)}if(K.env.NODE_PATH){let n=V.join(K.env.NODE_PATH,".bin",t);if(Pe.existsSync(n))return n}let r=V.join(e,"node_modules",".bin",t);if(Pe.existsSync(r))return r;let o=V.join(Fr,"..","node_modules",".bin",t);if(Pe.existsSync(o))return o}var jr=_("utils"),Gr=e=>new Promise(t=>{setTimeout(t,e)}),Ot=(e,t=3e3)=>{let r=!1,o=null,n=[],i=null,s=(...c)=>{if(r)return o=c,new Promise(f=>{n.push(f)});r=!0;let l,p=new Promise(f=>{l=f});return i=(async()=>{await Promise.resolve();let f=await e(...c);for(l(f);;){if(await Gr(t),!o)return r=!1,i=null,f;let u=o,m=n;o=null,n=[],f=await e(...u),m.forEach(y=>{y(f)})}})(),p};return s.flush=async()=>{if((r||o)&&i)return await i,s.flush()},s},ce=(e,t,r=!1)=>{let o=null,n=null,i=null,s=function(...c){n=c,i=this;let l=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(i,n),n=null,i=null)},t),l&&(e.apply(i,n),n=null,i=null)};return s.cancel=()=>{clearTimeout(o),o=null,n=null,i=null},s.flush=()=>{if(o){clearTimeout(o);let c=n,l=i;o=null,n=null,i=null,e.apply(l,c)}},s},Ft=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):jr.error("Could not parse JSON",o))}},$t=(e,t)=>{let n=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let c=`--${t}${n}`;if(c.length>55)return"";let l=60-c.length;if(l<=0)return"";if(l>=i.length+6){let p=Math.min(l-i.length,e.length);return`${i}${e.slice(0,p)}`}return e.slice(0,l)};var Yr=50*1024,Ze=(e,t=Yr)=>{if(!e||typeof e!="string"||e.length<=t)return e;let o=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+o};import{Buffer as kt}from"buffer";import Br from"path";var Dt=_("repo"),Lt=async({config:e,isRetry:t})=>{Dt.info("Getting runner diffs");let r=await qr(),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};if(!t){let I=Kr(n);await Wr(I)}Dt.info("Changes after processing"),await et();let i=await tt(n);await Qe(i);let s={stdio:["ignore","pipe","pipe"]},c=await N("git",["diff","--staged"],s),l=String(c.stdout??"");if(o=!!l,!o)return{hasChanges:!1,ignored:i};let p=await N("git",["diff","--staged","--binary"],s),f=String(p.stdout??""),u,m;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await N("git",["commit","-m","Agent runner"]);let I=await N("git",["diff",e.sha,"HEAD"],s);u=String(I.stdout??"");let w=await N("git",["diff",e.sha,"HEAD","--binary"],s),g=String(w.stdout??"");u!==g&&(m=kt.from(g).toString("base64"))}let y={hasChanges:!0,diff:l,resultDiff:u,ignored:i};return l!==f&&(y.diffBinary=kt.from(f).toString("base64")),m&&(y.resultDiffBinary=m),y},Qe=async(e=[])=>{await N("git",["add",".",...e])},et=async()=>{let e=await N("git",["status","-s"]);return String(e.stdout??"")},Ut=/.. (.+)?\.log$/,Hr=[Ut],qr=async()=>{let e=await et();return{hasChanges:(e.trim().length===0?[]:e.split(`
9
- `).filter(o=>Hr.some(i=>i instanceof RegExp?i.test(o):o===i)?!1:o[1]?.trim()!=="")).length!==0,status:e}},Mt=async()=>{let{stdout:e}=await N("git",["rev-parse","HEAD"]);return String(e??"").trim()},jt=async()=>{let{stdout:e}=await N("git",["rev-list","--max-parents=0","HEAD"]);return String(e??"").trim()},tt=async e=>{e||=await et();let t=[".netlify","node_modules","dist"],r=[];return e.split(`
10
- `).forEach(o=>{t.forEach(i=>{[`?? ${i}`,`?? ${i}${Br.sep}`].some(c=>o.startsWith(c))&&r.push(`:!${i}`)});let n=o.match(Ut)?.[1];n&&r.push(`:!${n}.log`)}),r},Gt=async()=>{await N("git",["reset","--hard","HEAD"])},Kr=e=>{let t=e.split(`
11
- `).reduce((r,o)=>{if(!o)return r;let[n,i,,...s]=o,c=s.join(""),l=n.trim(),p=i.trim();return r[c]?r[c].change=p:r[c]={filePath:c,stage:l,change:p},r},{});return Object.values(t)},Wr=async e=>{let t=[];for(let r of e)r.stage&&!r.change&&t.push(N("git",["restore","--staged","--worktree",r.filePath]));await Promise.allSettled(t)};import Vr from"fs/promises";import Xr from"os";import Ht from"path";import fe from"process";import zr from"readline";import rt from"path";import Jr from"fs/promises";var nt=_("agent-output-utils");async function ue({initialResult:e,agentName:t,hasError:r}){let o="",n=rt.join(process.cwd(),U,ae);try{let i=await Jr.readFile(n,"utf-8");i&&(o=i,nt.log(`Pulled result from ${rt.relative(process.cwd(),n)}`))}catch{nt.log(`No results file found at ${rt.relative(process.cwd(),n)}`)}return o||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function de({error:e,agentName:t}){let r=e&&typeof e=="object"?JSON.stringify(e):e,o=r?.replace(/\s+/g," ").trim().toLowerCase()||"",n="";return o?.includes("ai gateway is not available for your account")||o?.includes("ai gateway is not enabled for your account")?n="AI Gateway is currently not available on your account. Please confirm your account meets the criteria for using Agent Runners and AI Gateway and that your account has remaining AI Gateway inference credits available. Reach out to Netlify support if this is unexpected.":o?.includes("error when talking to gemini api")?n="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":(o?.includes("connection closed prematurely")||o?.includes("499")&&t.toLowerCase().includes("gemini"))&&(n=`The ${t} models were currently overloaded. Please try again or use a different available agent.`),o?.includes("request timed out")&&(n=`The ${t} API request's have timed out. Please try again or use a different available agent.`),o?.includes("network error")&&(n=`The ${t} agent is having network issues. Please try again or use a different available agent.`),n&&nt.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function pe(e){if(!e)return!1;let r=(e&&typeof e=="object"?JSON.stringify(e):e)?.replace(/\s+/g," ").trim().toLowerCase()||"";return!!(r?.includes("error when talking to gemini api")||r?.includes("499")||r?.includes("connection closed prematurely")||r?.includes("request timed out")||r?.includes("network error"))}var M=_("runner_claude"),Yt="Claude Code",me="claude-opus-4-5-20251101",Bt=e=>({Task:"Task",Bash:"Run command",Glob:"Find files",Grep:"Search files",LS:"List directory",ExitPlanMode:"Exit planning",Read:"Read file",Edit:"Edit file",MultiEdit:"Edit multiple files",Write:"Coding",NotebookEdit:"Edit notebook",WebFetch:"Fetch webpage",TodoWrite:"Update task list",WebSearch:"Search web",BashOutput:"Get command output",KillBash:"Stop command"})[e]||e,Zr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(M.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(M.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(M.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function ot({config:e,netlify:t,persistSteps:r,aiGateway:o,continueSession:n,priorAgentSessionId:i,cwd:s=fe.cwd()}){let c=e,{accountType:l,prompt:p,modelVersionOverrides:f}=c,{model:u}=c,m="";if(o){let{token:h,url:d}=o;if(!h||!d)throw new Error("No token or url provided from AI Gateway");if(f?.claude){let a=f?.claude?.[l];if(a){if(!await o.isModelAvailableForProvider("anthropic",a))throw new Error(`Model override '${a}' is not available for anthropic provider`);u=a}}else if(u){if(!await o.isModelAvailableForProvider("anthropic",u))throw new Error(`Model '${u}' is not available for anthropic provider`)}else!!me&&await o.isModelAvailableForProvider("anthropic",me)?(u=me,M.log(`Using default model: ${me}`)):me&&M.log(`Default model ${me} is not available, proceeding without model specification`);fe.env.ANTHROPIC_API_KEY=h,fe.env.ANTHROPIC_BASE_URL=d}else if(!fe.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let y=[],I=[],w={},g=0,T=0,R,S,P=[re(s,"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...u?["--model",u]:[],...n?["--continue"]:[],...n&&i?["--resume",i]:[],"-p",p],O=`${fe.env.NVM_BIN}/node`;M.log(`Running ${O} ${P.join(" ")}`);let k=t.utils.run(O,P,{all:!0,env:fe.env,cwd:s,idleTimeout:te});k.stdin?.end();let x=ce(()=>{r?.({steps:y,duration:T})},250),v=(h,d)=>{let a={...h,id:g};g+=1,I.push(a),y.push(a),d||x.flush(),x(),d&&x.flush()},G=zr.createInterface({input:k.all});return G.on("error",h=>{M.error("Readline interface error",{error:h.message,stack:h.stack})}),G.on("line",h=>{let d=null;try{d=JSON.parse(h)}catch{M.log("Could not parse line",h)}d?.session_id&&d.session_id!==m&&(m=d.session_id),Array.isArray(d?.message?.content)?d.message.content.forEach(a=>{switch(a.type){case"text":{a.text&&v({message:a.text});break}case"image":{typeof a.source=="object"&&a.source&&a.source.type==="base64"&&a.source.media_type?v({message:`![](data:${a.source.media_type};base64,${a.source.data})`}):M.log(`Unsupported image type ${a.source?.type}`,a.source);break}case"tool_use":{if(a.name==="Task"){let E=a.input?.description&&`\`${a.input.description}\``;v({title:[Bt(a.name),E].filter(Boolean).join(" ")})}else a.id&&(w[a.id]=a);x.flush();break}case"tool_result":{let E=a.tool_use_id?w[a.tool_use_id]:void 0,Z;if(E){let X=E.input?.file_path&&Ht.relative(s,E.input.file_path),F=X&&`\`${X}\``;Z=[Bt(E.name||""),F].filter(Boolean).join(" ")}let be=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(E?.name||""),Q;if(typeof a.content=="string")Q=a.content;else if(Array.isArray(a.content)){let X=[];a.content.forEach(F=>{F?.type==="text"&&typeof F.text=="string"?X.push(F.text):F?.type==="image"&&typeof F.source=="object"&&F.source?F.source.type==="base64"&&F.source.media_type?X.push(`![](data:${F.source.media_type};base64,${F.source.data})`):M.log(`Unsupported image type ${F.source.type}`,F.source):M.log(`Unsupported block type ${F?.type}`)}),Q=X.join(`
8
+ `);return i.length>e.length*.8?e:i}import Qt from"fs/promises";import cn from"path";import oe from"process";import{getTracer as un}from"@netlify/otel";import Ee from"process";var ie=class extends Error{constructor(r,o,n){super(r);this.statusCode=o;this.userMessage=n;this.name="GracefulShutdownError"}},_t=e=>e instanceof ie;var Ae=Ee.env.NETLIFY_API_URL,Ne=Ee.env.NETLIFY_API_TOKEN,H=_("api"),Ce=()=>Ee.env.NETLIFY_LOCAL_MODE==="true",we=async(e,t={})=>{if(!Ae||!Ne)throw new Error("No API URL or token");let r=new URL(e,Ae),o={...t,headers:{...t.headers,Authorization:`Bearer ${Ne}`}};Ee.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(Ee.env.AGENT_RUNNERS_DEBUG==="true")H.log(`Response headers for ${r}:`),n.headers.forEach((c,l)=>{H.log(` ${l}: ${c}`)});else{let c=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");H.log(`Request ID for ${r}: ${c||"N/A"}`)}if(i||H.error(`Got status ${n.status} for request ${r}`),t.raw){if(!i)throw new Error(`API request failed: ${n.status} ${n.statusText}`);return n}let s=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!i){let c=typeof s=="string"?s:JSON.stringify(s);throw n.status===404?new ie(`API request failed: 404 - ${c}`,404,"The site associated with this agent run no longer exists."):n.status===403&&t.gracefulOn403?new ie(`API request failed: 403 - ${c}`,403,"Credit limit reached. Please add more credits to continue using Agent Runners."):new Error(`API request failed: ${n.status} - ${c}`)}return s},Et=e=>{H.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Ae=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Ne=e.constants.NETLIFY_API_TOKEN)},wt=()=>({apiUrl:Ae,token:Ne}),Te=async(e,t)=>Ce()?(H.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):we(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),q=async(e,t,r)=>Ce()?(H.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):we(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var Tt=async(e,t)=>Ce()?(H.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):we(`/api/v1/agent_runners/${e}/sessions/${t}`),It=(e,t,r)=>we(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn403:!0}),xt=async(e,t)=>Ce()?(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"}}):we(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),qe=async(e,t)=>{H.log(`Uploading diff to S3: ${e.substring(0,50)}...`);let r=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"text/plain"}});if(!r.ok)throw new Error(`S3 upload failed with status ${r.status}`);return r};var se=_("ai_gateway"),Ke=null;var vt=async()=>{if(Ke)return Ke;se.log("Fetching available AI gateway providers");let e=await fetch(`${wt().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 Ke=t,se.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},Tr=async(e,t)=>{let o=(await vt()).providers[e];if(!o)return se.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return se.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},Rt=async({netlify:e,config:t})=>{let r,o,n,i,s=e.constants?.SITE_ID;if(!s)throw new Error("No site id");let c=async()=>{clearTimeout(n),se.log("Requesting AI gateway information");let l=await It(s,t.id,t.sessionId);if({token:r,url:i}=l,o=l.expires_at?l.expires_at*1e3:void 0,se.log("Got AI gateway information",{token:!!r,expiresAt:o,url:i}),o){let p=o-Date.now()-6e4;p>0&&(n=setTimeout(()=>{c()},p))}};return await Promise.all([c(),vt()]),{get url(){return i},get token(){return r},isModelAvailableForProvider:Tr}};import K from"process";import V from"path";import Pe from"fs";import{fileURLToPath as Ar}from"url";import{createRequire as Nr}from"module";import{execa as Cr,execaCommand as uo}from"execa";import{Transform as Ir}from"stream";var xr=new Set(["NODE_ENV","PATH","HOME","USER","USERNAME","SHELL","PWD","OLDPWD","TMPDIR","TMP","TEMP","LANG","TERM","EDITOR","PAGER","OS","PROCESSOR_ARCHITECTURE","PROCESSOR_IDENTIFIER","SYSTEMROOT","WINDIR","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","APPDATA","LOCALAPPDATA","NODE_OPTIONS","NODE_PATH","NODE_DEBUG","NODE_NO_WARNINGS","npm_config_registry","npm_config_cache","npm_execpath","npm_node_execpath","CI","GITHUB_ACTIONS","GITHUB_WORKSPACE","GITHUB_REPOSITORY","GITHUB_REF","BUILDKITE","BUILDKITE_BRANCH","BUILDKITE_COMMIT","BUILDKITE_BUILD_NUMBER","JENKINS_URL","TRAVIS","CIRCLECI","DISPLAY","COLORTERM","TERM_PROGRAM","TERM_PROGRAM_VERSION","COLUMNS","LINES","HISTSIZE","HISTFILE","NETLIFY_AGENT_RUNNER_ID","NETLIFY_AGENT_RUNNER_SESSION_ID","NETLIFY_AGENT_RUNNER_PROMPT","NETLIFY_AGENT_RUNNER_AGENT","NETLIFY_AGENT_RUNNER_MODEL","NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED","NETLIFY_AGENT_RUNNER_CONTEXT","NETLIFY_AGENT_RUNNER_HAS_REPO","NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED","NETLIFY_AGENT_RUNNER_SHA","NETLIFY_TEAM_TYPE","AGENT_RUNNERS_DEBUG","NETLIFY_TEAM_ID","NETLIFY_AGENT_RUNNER_USER_ID","SITE_NAME"]),vr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function Rr(){return Object.entries(process.env).filter(([e,t])=>!(!t||xr.has(e)||vr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function J(e){if(typeof e!="string")return e;let t=Rr();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(Sr(o),"g");r=r.replace(n,"******")}),r}function Sr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ae=class extends Ir{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),i=J(n);o(null,i)}};function St(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(o,n,i){let s=typeof o=="string"?J(o):o;return typeof n=="function"?t(s,n):t(s,n,i)},process.stderr.write=function(o,n,i){let s=typeof o=="string"?J(o):o;return typeof n=="function"?r(s,n):r(s,n,i)}}var Ie=null,bt=e=>(Ie&&Ie.destroy(),Ie=new ee({totalAllowedTime:e}),Ie),At=()=>Ie;var ee=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,o)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let n=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),i=null,s=null;o!==void 0&&(s=new Promise((c,l)=>{i=setTimeout(()=>{l(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return s?await Promise.race([r(),s]):await r()}finally{n(),i&&clearTimeout(i)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var Nt="netlify-agent-runner-context.md",We="task-history",Je="netlify-context",U=".netlify",le="results.md",Ve="assets";var te=1800*1e3;var Ct={name:"@netlify/agent-runner-cli",type:"module",version:"1.61.2-alpha",description:"CLI tool for running Netlify agents",main:"./dist/index.js",types:"./dist/index.d.ts",exports:"./dist/index.js",bin:{"agent-runner-cli":"./dist/bin.js","agent-runner-cli-local":"./dist/bin-local.js"},files:["dist/**/*.js","dist/**/*.d.ts","patches","scripts"],scripts:{build:"tsup",dev:"tsup --watch",prepare:"husky install node_modules/@netlify/eslint-config-node/.husky/",prepublishOnly:"npm ci && npm test",prepack:"npm run build",test:"run-s build format test:dev",format:"run-s build format:check-fix:*","format:ci":"run-s build format:check:*","format:check-fix:lint":"run-e format:check:lint format:fix:lint","format:check:lint":"cross-env-shell eslint $npm_package_config_eslint","format:fix:lint":"cross-env-shell eslint --fix $npm_package_config_eslint","format:check-fix:prettier":"run-e format:check:prettier format:fix:prettier","format:check:prettier":"cross-env-shell prettier --check $npm_package_config_prettier","format:fix:prettier":"cross-env-shell prettier --write $npm_package_config_prettier","test:dev":"run-s build test:dev:*","test:ci":"run-s build test:ci:*","test:dev:vitest":"LOG=0 vitest --exclude '**/integration/**'","test:ci:vitest":"LOG=0 c8 -r lcovonly -r text -r json vitest --exclude '**/integration/**'","test:integration":"vitest run test/integration/","test:integration:codex":"vitest run test/integration/codex.test.ts","test:integration:claude":"vitest run test/integration/claude.test.ts","test:integration:gemini":"vitest run test/integration/gemini.test.ts",postinstall:"node scripts/postinstall.js"},config:{eslint:'--cache --format=codeframe --max-warnings=0 "{src,scripts,test,.github}/**/*.{js,ts,md,html}"',prettier:'--ignore-path .gitignore --loglevel=warn "{src,scripts,test,.github}/**/*.{js,ts,md,yml,json,html}" "*.{js,ts,yml,json,html}" ".*.{js,ts,yml,json,html}" "!**/package-lock.json" "!package-lock.json"'},keywords:[],license:"MIT",repository:"netlify/agent-runner-cli",bugs:{url:"https://github.com/netlify/agent-runner-cli/issues"},author:"Netlify Inc.",directories:{test:"test"},devDependencies:{"@commitlint/cli":"^20.0.0","@commitlint/config-conventional":"^20.0.0","@eslint/compat":"^2.0.0","@eslint/js":"^9.35.0","@netlify/eslint-config-node":"^7.0.1","@types/node":"^24.5.0","@typescript-eslint/eslint-plugin":"^8.0.0","@typescript-eslint/parser":"^8.0.0","@vitest/eslint-plugin":"^1.6.6",c8:"^10.0.0","eslint-config-prettier":"^10.1.8","eslint-plugin-n":"^17.0.0",husky:"^9.0.0","patch-package":"^8.0.0",tsup:"^8.5.0",typescript:"^5.0.0","typescript-eslint":"^8.44.0",vitest:"^4.0.16"},dependencies:{"@anthropic-ai/claude-code":"2.0.76","@google/gemini-cli":"0.23.0","@netlify/otel":"^5.1.1","@openai/codex":"0.81.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.208.0",execa:"^9.6.1",minimist:"^1.2.8"}};var Pr=Ar(import.meta.url),Fr=V.dirname(Pr),$r=Nr(import.meta.url),ce=_("shell"),Xe=new Set,Or={preferLocal:!0},N=(e,t,r)=>{let[o,n]=Lr(t,r),i={...Or,...n},s=Cr(e,o,i);kr(s,i),Ur(s);let c=r?.idleTimeout;return c&&c>0&&Dr(s,c),s};var Lr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},kr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(K.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new ae).pipe(K.stdout),e.stdout?.pipe(new ae).pipe(K.stdout),e.stderr?.pipe(new ae).pipe(K.stderr);return}e.stdout?.pipe(K.stdout),e.stderr?.pipe(K.stderr)},ze=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(K.kill(-e.pid,t),ce.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return ce.error("Error killing process:",r),!1}},Pt=e=>ze(e,"SIGKILL"),Dr=(e,t)=>{let r=null,o=()=>{ce.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),ze(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ce.log(`Force killing idle process ${e.pid}`),Pt(e))},5e3)},n=()=>{r&&clearTimeout(r),r=setTimeout(o,t)};n(),e.stdout?.on("data",n),e.stderr?.on("data",n);let i=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",i),e.on("error",i)},Ur=e=>{Xe.add(e);let t=At();if(t){let r=t.onTimesUp(()=>{ce.log(`Global timer expired, killing process ${e.pid}`),ze(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ce.log(`Force killing process ${e.pid} after timeout`),Pt(e))},5e3)});e.on("exit",()=>{Xe.delete(e),r()}),e.on("error",()=>{Xe.delete(e),r()})}};function Fe(e,t){return!!re(e,t)}function re(e,t){if(!K.env.NETLIFY_LOCAL_MODE)try{let n=$r.resolve(Ct.name),i=V.dirname(n);for(;i!==V.dirname(i);){let s=V.dirname(i);if(V.basename(s)==="node_modules"){let c=V.join(s,".bin",t);if(Pe.existsSync(c))return c;break}i=s}}catch(n){console.error("Could not resolve package.json",n)}if(K.env.NODE_PATH){let n=V.join(K.env.NODE_PATH,".bin",t);if(Pe.existsSync(n))return n}let r=V.join(e,"node_modules",".bin",t);if(Pe.existsSync(r))return r;let o=V.join(Fr,"..","node_modules",".bin",t);if(Pe.existsSync(o))return o}var Mr=_("utils"),Gr=e=>new Promise(t=>{setTimeout(t,e)}),Ft=(e,t=3e3)=>{let r=!1,o=null,n=[],i=null,s=(...c)=>{if(r)return o=c,new Promise(f=>{n.push(f)});r=!0;let l,p=new Promise(f=>{l=f});return i=(async()=>{await Promise.resolve();let f=await e(...c);for(l(f);;){if(await Gr(t),!o)return r=!1,i=null,f;let u=o,m=n;o=null,n=[],f=await e(...u),m.forEach(y=>{y(f)})}})(),p};return s.flush=async()=>{if((r||o)&&i)return await i,s.flush()},s},ue=(e,t,r=!1)=>{let o=null,n=null,i=null,s=function(...c){n=c,i=this;let l=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(i,n),n=null,i=null)},t),l&&(e.apply(i,n),n=null,i=null)};return s.cancel=()=>{clearTimeout(o),o=null,n=null,i=null},s.flush=()=>{if(o){clearTimeout(o);let c=n,l=i;o=null,n=null,i=null,e.apply(l,c)}},s},$t=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):Mr.error("Could not parse JSON",o))}},Ot=(e,t)=>{let n=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let c=`--${t}${n}`;if(c.length>55)return"";let l=60-c.length;if(l<=0)return"";if(l>=i.length+6){let p=Math.min(l-i.length,e.length);return`${i}${e.slice(0,p)}`}return e.slice(0,l)};var jr=50*1024,Ze=(e,t=jr)=>{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 Lt}from"buffer";import Yr from"path";var kt=_("repo"),Dt=async({config:e,isRetry:t})=>{kt.info("Getting runner diffs");let r=await Hr(),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};if(!t){let I=qr(n);await Kr(I)}kt.info("Changes after processing"),await et();let i=await tt(n);await Qe(i);let s={stdio:["ignore","pipe","pipe"]},c=await N("git",["diff","--staged"],s),l=String(c.stdout??"");if(o=!!l,!o)return{hasChanges:!1,ignored:i};let p=await N("git",["diff","--staged","--binary"],s),f=String(p.stdout??""),u,m;if(e.sha){if(!process.env.NETLIFY_LOCAL_MODE){process.env.NETLIFY_INTERNAL_GIT="1";try{await N("git",["commit","-m","Agent runner"])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}}let I=await N("git",["diff",e.sha,"HEAD"],s);u=String(I.stdout??"");let w=await N("git",["diff",e.sha,"HEAD","--binary"],s),g=String(w.stdout??"");u!==g&&(m=Lt.from(g).toString("base64"))}let y={hasChanges:!0,diff:l,resultDiff:u,ignored:i};return l!==f&&(y.diffBinary=Lt.from(f).toString("base64")),m&&(y.resultDiffBinary=m),y},Qe=async(e=[])=>{process.env.NETLIFY_INTERNAL_GIT="1";try{await N("git",["add",".",...e])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}},et=async()=>{let e=await N("git",["status","-s"]);return String(e.stdout??"")},Ut=/.. (.+)?\.log$/,Br=[Ut],Hr=async()=>{let e=await et();return{hasChanges:(e.trim().length===0?[]:e.split(`
9
+ `).filter(o=>Br.some(i=>i instanceof RegExp?i.test(o):o===i)?!1:o[1]?.trim()!=="")).length!==0,status:e}},Mt=async()=>{let{stdout:e}=await N("git",["rev-parse","HEAD"]);return String(e??"").trim()},Gt=async()=>{let{stdout:e}=await N("git",["rev-list","--max-parents=0","HEAD"]);return String(e??"").trim()},tt=async e=>{e||=await et();let t=[".netlify","node_modules","dist"],r=[];return e.split(`
10
+ `).forEach(o=>{t.forEach(i=>{[`?? ${i}`,`?? ${i}${Yr.sep}`].some(c=>o.startsWith(c))&&r.push(`:!${i}`)});let n=o.match(Ut)?.[1];n&&r.push(`:!${n}.log`)}),r},jt=async()=>{await N("git",["reset","--hard","HEAD"])},qr=e=>{let t=e.split(`
11
+ `).reduce((r,o)=>{if(!o)return r;let[n,i,,...s]=o,c=s.join(""),l=n.trim(),p=i.trim();return r[c]?r[c].change=p:r[c]={filePath:c,stage:l,change:p},r},{});return Object.values(t)},Kr=async e=>{let t=[];for(let r of e)r.stage&&!r.change&&t.push(N("git",["restore","--staged","--worktree",r.filePath]));await Promise.allSettled(t)};import Jr from"fs/promises";import Vr from"os";import Ht from"path";import me from"process";import Xr from"readline";import rt from"path";import Wr from"fs/promises";var nt=_("agent-output-utils");async function de({initialResult:e,agentName:t,hasError:r}){let o="",n=rt.join(process.cwd(),U,le);try{let i=await Wr.readFile(n,"utf-8");i&&(o=i,nt.log(`Pulled result from ${rt.relative(process.cwd(),n)}`))}catch{nt.log(`No results file found at ${rt.relative(process.cwd(),n)}`)}return o||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function pe({error:e,agentName:t}){let r=e&&typeof e=="object"?JSON.stringify(e):e,o=r?.replace(/\s+/g," ").trim().toLowerCase()||"",n="";return o?.includes("ai gateway is not available for your account")||o?.includes("ai gateway is not enabled for your account")?n="AI Gateway is currently not available on your account. Please confirm your account meets the criteria for using Agent Runners and AI Gateway and that your account has remaining AI Gateway inference credits available. Reach out to Netlify support if this is unexpected.":o?.includes("error when talking to gemini api")?n="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":(o?.includes("connection closed prematurely")||o?.includes("499")&&t.toLowerCase().includes("gemini"))&&(n=`The ${t} models were currently overloaded. Please try again or use a different available agent.`),o?.includes("request timed out")&&(n=`The ${t} API request's have timed out. Please try again or use a different available agent.`),o?.includes("network error")&&(n=`The ${t} agent is having network issues. Please try again or use a different available agent.`),n&&nt.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function fe(e){if(!e)return!1;let r=(e&&typeof e=="object"?JSON.stringify(e):e)?.replace(/\s+/g," ").trim().toLowerCase()||"";return!!(r?.includes("error when talking to gemini api")||r?.includes("499")||r?.includes("connection closed prematurely")||r?.includes("request timed out")||r?.includes("network error"))}var M=_("runner_claude"),Yt="Claude Code",ge="claude-opus-4-5-20251101",Bt=e=>({Task:"Task",Bash:"Run command",Glob:"Find files",Grep:"Search files",LS:"List directory",ExitPlanMode:"Exit planning",Read:"Read file",Edit:"Edit file",MultiEdit:"Edit multiple files",Write:"Coding",NotebookEdit:"Edit notebook",WebFetch:"Fetch webpage",TodoWrite:"Update task list",WebSearch:"Search web",BashOutput:"Get command output",KillBash:"Stop command"})[e]||e,zr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(M.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(M.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(M.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function ot({config:e,netlify:t,persistSteps:r,aiGateway:o,continueSession:n,priorAgentSessionId:i,cwd:s=me.cwd()}){let c=e,{accountType:l,prompt:p,modelVersionOverrides:f}=c,{model:u}=c,m="";if(o){let{token:h,url:d}=o;if(!h||!d)throw new Error("No token or url provided from AI Gateway");if(f?.claude){let a=f?.claude?.[l];if(a){if(!await o.isModelAvailableForProvider("anthropic",a))throw new Error(`Model override '${a}' is not available for anthropic provider`);u=a}}else if(u){if(!await o.isModelAvailableForProvider("anthropic",u))throw new Error(`Model '${u}' is not available for anthropic provider`)}else!!ge&&await o.isModelAvailableForProvider("anthropic",ge)?(u=ge,M.log(`Using default model: ${ge}`)):ge&&M.log(`Default model ${ge} is not available, proceeding without model specification`);me.env.ANTHROPIC_API_KEY=h,me.env.ANTHROPIC_BASE_URL=d}else if(!me.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let y=[],I=[],w={},g=0,T=0,R,S,P=[re(s,"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...u?["--model",u]:[],...n?["--continue"]:[],...n&&i?["--resume",i]:[],"-p",p],F=`${me.env.NVM_BIN}/node`;M.log(`Running ${F} ${P.join(" ")}`);let L=t.utils.run(F,P,{all:!0,env:me.env,cwd:s,idleTimeout:te});L.stdin?.end();let x=ue(()=>{r?.({steps:y,duration:T})},250),v=(h,d)=>{let a={...h,id:g};g+=1,I.push(a),y.push(a),d||x.flush(),x(),d&&x.flush()},j=Xr.createInterface({input:L.all});return j.on("error",h=>{M.error("Readline interface error",{error:h.message,stack:h.stack})}),j.on("line",h=>{let d=null;try{d=JSON.parse(h)}catch{M.log("Could not parse line",h)}d?.session_id&&d.session_id!==m&&(m=d.session_id),Array.isArray(d?.message?.content)?d.message.content.forEach(a=>{switch(a.type){case"text":{a.text&&v({message:a.text});break}case"image":{typeof a.source=="object"&&a.source&&a.source.type==="base64"&&a.source.media_type?v({message:`![](data:${a.source.media_type};base64,${a.source.data})`}):M.log(`Unsupported image type ${a.source?.type}`,a.source);break}case"tool_use":{if(a.name==="Task"){let E=a.input?.description&&`\`${a.input.description}\``;v({title:[Bt(a.name),E].filter(Boolean).join(" ")})}else a.id&&(w[a.id]=a);x.flush();break}case"tool_result":{let E=a.tool_use_id?w[a.tool_use_id]:void 0,Z;if(E){let X=E.input?.file_path&&Ht.relative(s,E.input.file_path),$=X&&`\`${X}\``;Z=[Bt(E.name||""),$].filter(Boolean).join(" ")}let be=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(E?.name||""),Q;if(typeof a.content=="string")Q=a.content;else if(Array.isArray(a.content)){let X=[];a.content.forEach($=>{$?.type==="text"&&typeof $.text=="string"?X.push($.text):$?.type==="image"&&typeof $.source=="object"&&$.source?$.source.type==="base64"&&$.source.media_type?X.push(`![](data:${$.source.media_type};base64,${$.source.data})`):M.log(`Unsupported image type ${$.source.type}`,$.source):M.log(`Unsupported block type ${$?.type}`)}),Q=X.join(`
12
12
 
13
13
  `)}be&&Q&&(Q=`\`\`\`
14
14
  ${Q.trim()}
15
- \`\`\``),v({title:Z,message:Q},!0);break}case"thinking":{a.thinking&&v({title:"Thinking",message:a.thinking},!0);break}default:M.log(`Message content type is not supported ${a.type}`,a)}}):d?.type==="result"&&(T=d.duration_ms||0,d.is_error?S=d.result:R=d.result,[I,y].forEach(a=>{a[a.length-1]?.message===R&&a.pop()}))}),await k.catch(h=>{({error:S,result:R}=Zr({catchError:h,runCmd:k,error:S,result:R,runnerName:"Claude"}))}),G.close(),x.flush(),{steps:I,duration:T,result:await ue({initialResult:R,agentName:Yt,hasError:!!S}),error:de({error:S,agentName:Yt}),isRetryableError:pe(S),agentSessionId:m}}var qt=async()=>{let e=Ht.join(Xr.homedir(),".claude");await Vr.rm(e,{recursive:!0,force:!0})};import Ie from"fs/promises";import Wt from"os";import Fe from"path";import ne from"process";import Qr from"readline";var j=_("runner_codex"),Kt="Codex CLI",ge="",en=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(j.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(j.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(j.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function it({config:e,netlify:t,persistSteps:r=void 0,sendSteps:o=void 0,aiGateway:n,cwd:i=ne.cwd()}){let{accountType:s,prompt:c,modelVersionOverrides:l}=e,{model:p}=e;if(n){let{token:d,url:a}=n;if(!d||!a)throw new Error("No token or url provided from AI Gateway");if(l?.codex){let E=l?.codex?.[s];if(E){if(!await n.isModelAvailableForProvider("openai",E))throw new Error(`Model override '${E}' is not available for openai provider`);p=E}}else if(p){if(!await n.isModelAvailableForProvider("openai",p))throw new Error(`Model '${p}' is not available for openai provider`)}else!!ge&&await n.isModelAvailableForProvider("openai",ge)?(p=ge,j.log(`Using default model: ${ge}`)):ge&&j.log(`Default model ${ge} is not available, proceeding without model specification`);ne.env.OPENAI_API_KEY=d,ne.env.OPENAI_BASE_URL=a}else if(!ne.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let f=[],u=[],m=[],y={},I=0,w=0,g,T,R=`${ne.env.NVM_BIN}/node`,S=Fe.join(Wt.homedir(),".codex"),P=Fe.join(S,"config.toml"),O=Fe.join(S,"auth.json");try{await Ie.mkdir(S,{recursive:!0});let d={OPENAI_API_KEY:ne.env.OPENAI_API_KEY};await Ie.writeFile(O,JSON.stringify(d,null,2),"utf-8"),j.log("Created Codex auth.json file");let a="";try{a=await Ie.readFile(P,"utf-8")}catch{}a.includes("web_search_request")||(a.includes("[features]")?a=a.replace(/\[features\]/,`[features]
15
+ \`\`\``),v({title:Z,message:Q},!0);break}case"thinking":{a.thinking&&v({title:"Thinking",message:a.thinking},!0);break}default:M.log(`Message content type is not supported ${a.type}`,a)}}):d?.type==="result"&&(T=d.duration_ms||0,d.is_error?S=d.result:R=d.result,[I,y].forEach(a=>{a[a.length-1]?.message===R&&a.pop()}))}),await L.catch(h=>{({error:S,result:R}=zr({catchError:h,runCmd:L,error:S,result:R,runnerName:"Claude"}))}),j.close(),x.flush(),{steps:I,duration:T,result:await de({initialResult:R,agentName:Yt,hasError:!!S}),error:pe({error:S,agentName:Yt}),isRetryableError:fe(S),agentSessionId:m}}var qt=async()=>{let e=Ht.join(Vr.homedir(),".claude");await Jr.rm(e,{recursive:!0,force:!0})};import xe from"fs/promises";import Wt from"os";import $e from"path";import ne from"process";import Zr from"readline";var G=_("runner_codex"),Kt="Codex CLI",he="",Qr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(G.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(G.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(G.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function it({config:e,netlify:t,persistSteps:r=void 0,sendSteps:o=void 0,aiGateway:n,cwd:i=ne.cwd()}){let{accountType:s,prompt:c,modelVersionOverrides:l}=e,{model:p}=e;if(n){let{token:d,url:a}=n;if(!d||!a)throw new Error("No token or url provided from AI Gateway");if(l?.codex){let E=l?.codex?.[s];if(E){if(!await n.isModelAvailableForProvider("openai",E))throw new Error(`Model override '${E}' is not available for openai provider`);p=E}}else if(p){if(!await n.isModelAvailableForProvider("openai",p))throw new Error(`Model '${p}' is not available for openai provider`)}else!!he&&await n.isModelAvailableForProvider("openai",he)?(p=he,G.log(`Using default model: ${he}`)):he&&G.log(`Default model ${he} is not available, proceeding without model specification`);ne.env.OPENAI_API_KEY=d,ne.env.OPENAI_BASE_URL=a}else if(!ne.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let f=[],u=[],m=[],y={},I=0,w=0,g,T,R=`${ne.env.NVM_BIN}/node`,S=$e.join(Wt.homedir(),".codex"),P=$e.join(S,"config.toml"),F=$e.join(S,"auth.json");try{await xe.mkdir(S,{recursive:!0});let d={OPENAI_API_KEY:ne.env.OPENAI_API_KEY};await xe.writeFile(F,JSON.stringify(d,null,2),"utf-8"),G.log("Created Codex auth.json file");let a="";try{a=await xe.readFile(P,"utf-8")}catch{}a.includes("web_search_request")||(a.includes("[features]")?a=a.replace(/\[features\]/,`[features]
16
16
  web_search_request = true`):a+=`
17
17
  [features]
18
18
  web_search_request = true
19
- `,await Ie.writeFile(P,a,"utf-8"),j.log("Updated Codex config with web_search_request enabled"))}catch(d){throw j.warn("Failed to setup Codex config and credentials",{error:d.message}),new Error(`Codex setup failed: ${d.message}`)}let k=[re(i,"codex"),"exec","--yolo","--json","--enable","web_search_request",...p?["--model",p]:[],c].filter(Boolean);j.log(`Running ${R} ${k.join(" ")}`);let x=t.utils.run(R,k,{all:!0,cwd:i,env:{...ne.env},idleTimeout:te}),v=ce(()=>{r?.({steps:f,duration:w}),o?.({steps:u,duration:w}),u=[]},250),G=(d,a)=>{d.id=I,I+=1,m.push(d),f.push(d),u.push(d),a||v.flush(),v(),a&&v.flush()},h=Qr.createInterface({input:x.all});return h.on("error",d=>{j.error("Readline interface error",{error:d.message,stack:d.stack})}),h.on("line",d=>{let a=null;try{a=JSON.parse(d)}catch{j.log("Could not parse line",d);return}if(a?.duration_ms&&(w=a.duration_ms),a?.type==="item.started"&&a?.item?.type==="command_execution")y[a.item.id]=a.item;else if(a?.type==="item.completed"&&a?.item?.type==="command_execution"){let E=rn(a.item);E&&G(E,!0)}else if(a?.type==="item.completed"&&a?.item?.type==="reasoning"){let E={title:"Reasoning",message:a.item.text};G(E,!0)}else if(a?.type==="local_shell_call")y[a.call_id]=a;else if(a?.type==="local_shell_call_output"){let E=nn(y[a.call_id],a);E&&G(E,!0)}else a?.type==="message"&&a.role==="assistant"?g=a.content.map(E=>E.text).join(`
19
+ `,await xe.writeFile(P,a,"utf-8"),G.log("Updated Codex config with web_search_request enabled"))}catch(d){throw G.warn("Failed to setup Codex config and credentials",{error:d.message}),new Error(`Codex setup failed: ${d.message}`)}let L=[re(i,"codex"),"exec","--yolo","--json","--enable","web_search_request",...p?["--model",p]:[],c].filter(Boolean);G.log(`Running ${R} ${L.join(" ")}`);let x=t.utils.run(R,L,{all:!0,cwd:i,env:{...ne.env},idleTimeout:te}),v=ue(()=>{r?.({steps:f,duration:w}),o?.({steps:u,duration:w}),u=[]},250),j=(d,a)=>{d.id=I,I+=1,m.push(d),f.push(d),u.push(d),a||v.flush(),v(),a&&v.flush()},h=Zr.createInterface({input:x.all});return h.on("error",d=>{G.error("Readline interface error",{error:d.message,stack:d.stack})}),h.on("line",d=>{let a=null;try{a=JSON.parse(d)}catch{G.log("Could not parse line",d);return}if(a?.duration_ms&&(w=a.duration_ms),a?.type==="item.started"&&a?.item?.type==="command_execution")y[a.item.id]=a.item;else if(a?.type==="item.completed"&&a?.item?.type==="command_execution"){let E=tn(a.item);E&&j(E,!0)}else if(a?.type==="item.completed"&&a?.item?.type==="reasoning"){let E={title:"Reasoning",message:a.item.text};j(E,!0)}else if(a?.type==="local_shell_call")y[a.call_id]=a;else if(a?.type==="local_shell_call_output"){let E=rn(y[a.call_id],a);E&&j(E,!0)}else a?.type==="message"&&a.role==="assistant"?g=a.content.map(E=>E.text).join(`
20
20
  `):a?.type==="message"&&a.role==="system"&&(T=a.content.map(E=>E.text).join(`
21
- `))}),await x.catch(d=>{let a=en({catchError:d,runCmd:x,error:T,result:g,runnerName:"Codex"});T=a.error,g=a.result}),h.close(),v.flush(),{steps:m,duration:w,result:await ue({initialResult:g,agentName:Kt,hasError:!!T}),error:de({error:T,agentName:Kt}),isRetryableError:pe(T)}}var Jt=async()=>{let e=Fe.join(Wt.homedir(),".codex");await Ie.rm(e,{recursive:!0,force:!0})},tn=new Set(["bash","-lc"]),rn=e=>{if(!e||e.type!=="command_execution")return null;let t=e.command;t.startsWith("bash -lc ")&&(t=t.replace(/^bash -lc ['"]/,"").replace(/['"]$/,""));let r=`Running \`${t}\``,o=e.aggregated_output?.trim();return o&&(o=`\`\`\`
21
+ `))}),await x.catch(d=>{let a=Qr({catchError:d,runCmd:x,error:T,result:g,runnerName:"Codex"});T=a.error,g=a.result}),h.close(),v.flush(),{steps:m,duration:w,result:await de({initialResult:g,agentName:Kt,hasError:!!T}),error:pe({error:T,agentName:Kt}),isRetryableError:fe(T)}}var Jt=async()=>{let e=$e.join(Wt.homedir(),".codex");await xe.rm(e,{recursive:!0,force:!0})},en=new Set(["bash","-lc"]),tn=e=>{if(!e||e.type!=="command_execution")return null;let t=e.command;t.startsWith("bash -lc ")&&(t=t.replace(/^bash -lc ['"]/,"").replace(/['"]$/,""));let r=`Running \`${t}\``,o=e.aggregated_output?.trim();return o&&(o=`\`\`\`
22
22
  ${o}
23
23
  \`\`\``),e.status==="failed"&&e.exit_code!==0&&(o=o?`${o}
24
24
 
25
- *Exit code: ${e.exit_code}*`:`*Command failed with exit code: ${e.exit_code}*`),{title:r,message:o}},nn=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(i=>!tn.has(i)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
25
+ *Exit code: ${e.exit_code}*`:`*Command failed with exit code: ${e.exit_code}*`),{title:r,message:o}},rn=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(i=>!en.has(i)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
26
26
  ${n.trim()}
27
- \`\`\``)}catch(i){j.error("Could not decode outputMsg",i,t.output)}return{title:o,message:n}};import $e from"fs/promises";import Xt from"os";import ke from"path";import he from"process";import on from"readline";var Y=_("runner_gemini"),Vt="Gemini CLI",ye="",sn=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(Y.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(Y.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(Y.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),an={list_directory:"List",read_file:"Read",write_file:"Write",glob:"Find",search_file_content:"Find",replace:"Edit",run_shell_command:"Run",web_fetch:"Web Fetch",web_search:"Web Search",read_many_files:"Read Many",save_memory:"Memorize"},ln=async()=>{let e=ke.join(Xt.homedir(),".gemini"),t=ke.join(e,"settings.json");try{await $e.mkdir(e,{recursive:!0});let r={};try{let o=await $e.readFile(t,"utf-8");r=JSON.parse(o)}catch{Y.log("Creating new Gemini CLI settings file")}r.general||(r.general={}),r.general.previewFeatures||(r.general.previewFeatures=!0),r.model||(r.model={}),r.model.compressionThreshold!==.3&&(r.model.compressionThreshold=.3),await $e.writeFile(t,JSON.stringify(r,null,2),"utf-8"),Y.log("Configured Gemini CLI settings (preview features and compression threshold)")}catch(r){Y.error("Failed to ensure Gemini CLI settings",{error:r.message})}};async function st({config:e,netlify:t,persistSteps:r=void 0,sendSteps:o=void 0,aiGateway:n,cwd:i=he.cwd()}){let{accountType:s,prompt:c,modelVersionOverrides:l}=e,{model:p}=e;if(await ln(),n){let{token:h,url:d}=n;if(!h||!d)throw new Error("No token or url provided from AI Gateway");if(l?.gemini){let a=l?.gemini?.[s];if(a){if(!await n.isModelAvailableForProvider("gemini",a))throw new Error(`Model override '${a}' is not available for gemini provider`);p=a}}if(!p)!!ye&&await n.isModelAvailableForProvider("gemini",ye)?(p=ye,Y.log(`Using default model: ${ye}`)):ye&&Y.log(`Default model ${ye} is not available, proceeding without model specification`);else if(p&&!l?.gemini?.[s]&&!await n.isModelAvailableForProvider("gemini",p))throw new Error(`Model '${p}' is not available for gemini provider`);he.env.GEMINI_API_KEY=h,he.env.GOOGLE_GEMINI_BASE_URL=d}else if(!he.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let f=[],u=[],m=[],y={},I=0,w=0,g,T,R=[re(i,"gemini"),...p?["--model",p]:[],"--yolo","--output-format","stream-json","-p",c],S=`${he.env.NVM_BIN}/node`;Y.log(`Running ${S} ${R.join(" ")}`);let P=t.utils.run(S,R,{all:!0,env:he.env,cwd:i,idleTimeout:te});P.stdin?.end();let O=ce(()=>{r?.({steps:f,duration:w}),o?.({steps:u,duration:w}),u=[]},250),k=(h,d)=>{h.id=I,I+=1,m.push(h),f.push(h),u.push(h),d||O.flush(),O(),d&&O.flush()},x=on.createInterface({input:P.all});x.on("error",h=>{Y.error("Readline interface error",{error:h.message,stack:h.stack})});let v="",G=()=>{v&&k({message:v.trim()}),v=""};return x.on("line",h=>{let d=null;try{if(h.startsWith("[API Error")){let a=h.match(/\[api error: (.+?)]$/i)?.[1];d={type:"error",value:Ft(a,!1)?.error?.message||a||"Gemini encountered error"}}else d=JSON.parse(h)}catch{return}if(d)switch(["message","result"].includes(d.type)||G(),d.type){case"message":{d.role!=="user"&&d.content&&(v+=d.content);break}case"tool_use":{let a=an[d.tool_name]??d.tool_name,E=d.parameters?.file_path,Z=E&&ke.relative(i,E),be=d.parameters?.command,X={title:[a,Z&&`\`${Z}\``,be&&`\`${be}\``].filter(Boolean).join(" ")};y[d.tool_id]=X,O.flush();break}case"tool_result":{let a=y[d.tool_id];a&&(d.output&&(a.message=`\`\`\`
27
+ \`\`\``)}catch(i){G.error("Could not decode outputMsg",i,t.output)}return{title:o,message:n}};import Oe from"fs/promises";import Xt from"os";import Le from"path";import ye from"process";import nn from"readline";var Y=_("runner_gemini"),Vt="Gemini CLI",_e="",on=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(Y.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(Y.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(Y.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),sn={list_directory:"List",read_file:"Read",write_file:"Write",glob:"Find",search_file_content:"Find",replace:"Edit",run_shell_command:"Run",web_fetch:"Web Fetch",web_search:"Web Search",read_many_files:"Read Many",save_memory:"Memorize"},an=async()=>{let e=Le.join(Xt.homedir(),".gemini"),t=Le.join(e,"settings.json");try{await Oe.mkdir(e,{recursive:!0});let r={};try{let o=await Oe.readFile(t,"utf-8");r=JSON.parse(o)}catch{Y.log("Creating new Gemini CLI settings file")}r.general||(r.general={}),r.general.previewFeatures||(r.general.previewFeatures=!0),r.model||(r.model={}),r.model.compressionThreshold!==.3&&(r.model.compressionThreshold=.3),await Oe.writeFile(t,JSON.stringify(r,null,2),"utf-8"),Y.log("Configured Gemini CLI settings (preview features and compression threshold)")}catch(r){Y.error("Failed to ensure Gemini CLI settings",{error:r.message})}};async function st({config:e,netlify:t,persistSteps:r=void 0,sendSteps:o=void 0,aiGateway:n,cwd:i=ye.cwd()}){let{accountType:s,prompt:c,modelVersionOverrides:l}=e,{model:p}=e;if(await an(),n){let{token:h,url:d}=n;if(!h||!d)throw new Error("No token or url provided from AI Gateway");if(l?.gemini){let a=l?.gemini?.[s];if(a){if(!await n.isModelAvailableForProvider("gemini",a))throw new Error(`Model override '${a}' is not available for gemini provider`);p=a}}if(!p)!!_e&&await n.isModelAvailableForProvider("gemini",_e)?(p=_e,Y.log(`Using default model: ${_e}`)):_e&&Y.log(`Default model ${_e} is not available, proceeding without model specification`);else if(p&&!l?.gemini?.[s]&&!await n.isModelAvailableForProvider("gemini",p))throw new Error(`Model '${p}' is not available for gemini provider`);ye.env.GEMINI_API_KEY=h,ye.env.GOOGLE_GEMINI_BASE_URL=d}else if(!ye.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let f=[],u=[],m=[],y={},I=0,w=0,g,T,R=[re(i,"gemini"),...p?["--model",p]:[],"--yolo","--output-format","stream-json","-p",c],S=`${ye.env.NVM_BIN}/node`;Y.log(`Running ${S} ${R.join(" ")}`);let P=t.utils.run(S,R,{all:!0,env:ye.env,cwd:i,idleTimeout:te});P.stdin?.end();let F=ue(()=>{r?.({steps:f,duration:w}),o?.({steps:u,duration:w}),u=[]},250),L=(h,d)=>{h.id=I,I+=1,m.push(h),f.push(h),u.push(h),d||F.flush(),F(),d&&F.flush()},x=nn.createInterface({input:P.all});x.on("error",h=>{Y.error("Readline interface error",{error:h.message,stack:h.stack})});let v="",j=()=>{v&&L({message:v.trim()}),v=""};return x.on("line",h=>{let d=null;try{if(h.startsWith("[API Error")){let a=h.match(/\[api error: (.+?)]$/i)?.[1];d={type:"error",value:$t(a,!1)?.error?.message||a||"Gemini encountered error"}}else d=JSON.parse(h)}catch{return}if(d)switch(["message","result"].includes(d.type)||j(),d.type){case"message":{d.role!=="user"&&d.content&&(v+=d.content);break}case"tool_use":{let a=sn[d.tool_name]??d.tool_name,E=d.parameters?.file_path,Z=E&&Le.relative(i,E),be=d.parameters?.command,X={title:[a,Z&&`\`${Z}\``,be&&`\`${be}\``].filter(Boolean).join(" ")};y[d.tool_id]=X,F.flush();break}case"tool_result":{let a=y[d.tool_id];a&&(d.output&&(a.message=`\`\`\`
28
28
  ${d.output.trim()}
29
- \`\`\``),k(a,!0));break}case"result":{w=d.stats?.duration_ms,d.status==="error"?T=d.error?.message:g=v.trim();break}case"error":{T=d.error;break}case"finished":break;default:{Y.warn("Unhandled message type:",d.type);break}}}),await P.catch(h=>{({error:T,result:g}=sn({catchError:h,runCmd:P,error:T,result:g,runnerName:"Gemini"}))}),x.close(),O.flush(),{steps:m,duration:w,result:await ue({initialResult:g,agentName:Vt,hasError:!!T}),error:de({error:T,agentName:Vt}),isRetryableError:pe(T)}}var zt=async()=>{let e=ke.join(Xt.homedir(),".gemini");await $e.rm(e,{recursive:!0,force:!0})};var cn={codex:{runner:it,clean:Jt},claude:{runner:ot,clean:qt},gemini:{runner:st,clean:zt}},Zt=cn;var De=_("init_stage"),tr=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>await b(un(),"init-stage",async n=>{let i=performance.now();n?.setAttributes({"init.runner":e.runner,"init.id":e.id,"init.sessionId":e.sessionId,"init.hasRepo":e.hasRepo,"init.useGateway":e.useGateway,"init.runnerVersion":o||"unknown"});let s=Zt[e.runner];if(!s)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let c=pn({apiToken:r});Et(c);let l=e.useGateway?await Rt({netlify:c,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!l});let p=5*1024,f=Ot(async({steps:I=[],duration:w})=>{let g=I.map(T=>{let R=T.title?Ze(J(T.title),p):void 0,S=T.message?Ze(J(T.message)):void 0;return{...T,title:R,message:S}});I.length=0;try{return await q(e.id,e.sessionId,{steps:g,duration:w})}catch(T){De.error("persistSteps failed",{error:T?.message||T})}},t);De.info("Adding build files to stage");let u=await tt();await Qe(u),await dn();let m;e.hasRepo?e.sha?(m=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(m=await Mt(),await we(e.id,{sha:m}),n?.setAttributes({"init.sha.source":"current_commit"})):(m=await jt(),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let y=performance.now()-i;return n?.setAttributes({"init.sha":m||"unknown","init.duration.ms":y,"init.status":"success"}),{aiGateway:l,context:c,persistSteps:f,runner:s,sha:m}}),dn=async()=>{let e=er.join(xe.cwd(),".git","hooks","pre-commit"),t=`#!/bin/bash
30
- echo "Error: Commits are disabled. The deployment system handles commits automatically."
31
- echo "Leave your changes uncommitted."
32
- exit 1
33
- `;try{await Qt.mkdir(er.dirname(e),{recursive:!0}),await Qt.writeFile(e,t,{mode:493}),De.info("Installed pre-commit hook to prevent agent commits")}catch(r){De.warn("Failed to install pre-commit hook",{error:r?.message||r})}},pn=({apiToken:e})=>({constants:{NETLIFY_API_HOST:xe.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||xe.env.NETLIFY_API_TOKEN,SITE_ID:xe.env.SITE_ID,FUNCTIONS_DIST:xe.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:N}});import{getTracer as at}from"@netlify/otel";import fn from"crypto";import z from"fs/promises";import L from"path";import B from"process";var D=_("context"),mn=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:B.env.NETLIFY_TEAM_ID,userId:B.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:B.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},gn=10,hn=async e=>{let{name:t,ext:r}=L.parse(e),o=e,n=L.join(B.cwd(),U,o),i=0;for(;await yn(n);){if(i>=gn)throw new Error("Failed to generate context file");o=`${t}-${fn.randomUUID().slice(0,5)}${r}`,n=L.join(B.cwd(),U,o),i+=1}return o},yn=async e=>{try{return await z.access(e),!0}catch{return!1}},_n=async()=>{try{D.log("Fetching Netlify features context...");let e=await fetch("https://docs.netlify.com/ai-context/context-consumers",{signal:AbortSignal.timeout(1e4)});if(!e.ok)throw new Error(`Failed to fetch context consumers: ${e.status} ${e.statusText}`);let t=await e.json();if(!t||typeof t!="object"||!Array.isArray(t.consumers))return D.warn("Invalid response structure: missing or invalid consumers array"),null;let r=t.consumers.find(o=>o&&typeof o=="object"&&o.key==="catchall-consumer");return r?!r.contextScopes||typeof r.contextScopes!="object"?(D.warn("Catchall consumer missing or invalid contextScopes"),null):r:(D.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?D.warn("Netlify features context request timed out"):D.warn("Failed to fetch Netlify features context:",e.message),null}},En=async(e,t)=>{try{let r=await fetch(e,{signal:AbortSignal.timeout(1e4)});if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let o=await r.text();return await z.writeFile(t,o,"utf-8"),!0}catch(r){return r.name==="AbortError"?D.warn(`Download timeout for ${e}`):D.warn(`Failed to download context file ${e}:`,r.message),!1}},Le=null,wn=async()=>{if(Le)return Le;let e=await _n();if(!e)return[];let t=L.join(B.cwd(),U,Je);await z.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([n,i])=>{if(!i||typeof i!="object"||!i.endpoint||!i.scope)return D.warn(`Invalid scope data for ${n}, skipping...`),null;let s=`${n}.md`,c=L.join(t,s),l=L.join(U,Je,s);return D.log(`Downloading ${i.scope} context...`),await En(i.endpoint,c)?(D.log(`Downloaded: ${l}`),{scope:i.scope,path:l,key:n}):null});return Le=(await Promise.all(r)).filter(n=>n!==null),Le},rr=async({cliPath:e,netlify:t,config:r,buildErrorContext:o})=>{let n=mn(t),i=await hn(Nt),s=L.join(B.cwd(),U);await z.mkdir(s,{recursive:!0});let c=L.join(U,i),l=L.join(B.cwd(),c),p=L.join(B.cwd(),U,ae);try{await z.unlink(p),D.log(`Deleted old results file: ${p}`)}catch{}let f=o?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
29
+ \`\`\``),L(a,!0));break}case"result":{w=d.stats?.duration_ms,d.status==="error"?T=d.error?.message:g=v.trim();break}case"error":{T=d.error;break}case"finished":break;default:{Y.warn("Unhandled message type:",d.type);break}}}),await P.catch(h=>{({error:T,result:g}=on({catchError:h,runCmd:P,error:T,result:g,runnerName:"Gemini"}))}),x.close(),F.flush(),{steps:m,duration:w,result:await de({initialResult:g,agentName:Vt,hasError:!!T}),error:pe({error:T,agentName:Vt}),isRetryableError:fe(T)}}var zt=async()=>{let e=Le.join(Xt.homedir(),".gemini");await Oe.rm(e,{recursive:!0,force:!0})};var ln={codex:{runner:it,clean:Jt},claude:{runner:ot,clean:qt},gemini:{runner:st,clean:zt}},Zt=ln;var ke=_("init_stage"),er=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>await b(un(),"init-stage",async n=>{let i=performance.now();n?.setAttributes({"init.runner":e.runner,"init.id":e.id,"init.sessionId":e.sessionId,"init.hasRepo":e.hasRepo,"init.useGateway":e.useGateway,"init.runnerVersion":o||"unknown"});let s=Zt[e.runner];if(!s)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let c=pn({apiToken:r});Et(c);let l=e.useGateway?await Rt({netlify:c,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!l});let p=5*1024,f=Ft(async({steps:I=[],duration:w})=>{let g=I.map(T=>{let R=T.title?Ze(J(T.title),p):void 0,S=T.message?Ze(J(T.message)):void 0;return{...T,title:R,message:S}});I.length=0;try{return await q(e.id,e.sessionId,{steps:g,duration:w})}catch(T){ke.error("persistSteps failed",{error:T?.message||T})}},t);ke.info("Adding build files to stage");let u=await tt();await Qe(u),await dn();let m;e.hasRepo?e.sha?(m=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(m=await Mt(),await Te(e.id,{sha:m}),n?.setAttributes({"init.sha.source":"current_commit"})):(m=await Gt(),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let y=performance.now()-i;return n?.setAttributes({"init.sha":m||"unknown","init.duration.ms":y,"init.status":"success"}),{aiGateway:l,context:c,persistSteps:f,runner:s,sha:m}}),dn=async()=>{let e="/tmp/netlify-git-wrapper",t=cn.join(e,"git"),r=`#!/bin/bash
30
+ # Git wrapper that blocks add and commit commands
31
+ # The deployment system handles staging and commits automatically
32
+
33
+ # Allow internal system calls to bypass the wrapper
34
+ if [ "$NETLIFY_INTERNAL_GIT" = "1" ]; then
35
+ exec /usr/bin/git "$@"
36
+ fi
37
+
38
+ case "$1" in
39
+ add)
40
+ echo ""
41
+ echo "Note: 'git add' is disabled in this environment."
42
+ echo "The deployment system automatically detects your file changes."
43
+ echo "Just edit files directly - no need to stage them manually."
44
+ echo ""
45
+ exit 1
46
+ ;;
47
+ commit)
48
+ echo ""
49
+ echo "Note: 'git commit' is disabled in this environment."
50
+ echo "The deployment system handles commits automatically."
51
+ echo "Just edit files and leave them uncommitted."
52
+ echo ""
53
+ exit 1
54
+ ;;
55
+ *)
56
+ exec /usr/bin/git "$@"
57
+ ;;
58
+ esac
59
+ `;try{await Qt.mkdir(e,{recursive:!0}),await Qt.writeFile(t,r,{mode:493}),oe.env.PATH=`${e}:${oe.env.PATH}`,oe.env.NETLIFY_INTERNAL_GIT="0",ke.info("Installed git wrapper to block add/commit commands")}catch(o){ke.warn("Failed to install git wrapper",{error:o?.message||o})}},pn=({apiToken:e})=>({constants:{NETLIFY_API_HOST:oe.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||oe.env.NETLIFY_API_TOKEN,SITE_ID:oe.env.SITE_ID,FUNCTIONS_DIST:oe.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:N}});import{getTracer as at}from"@netlify/otel";import fn from"crypto";import z from"fs/promises";import D from"path";import B from"process";var k=_("context"),mn=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:B.env.NETLIFY_TEAM_ID,userId:B.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:B.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},gn=10,hn=async e=>{let{name:t,ext:r}=D.parse(e),o=e,n=D.join(B.cwd(),U,o),i=0;for(;await yn(n);){if(i>=gn)throw new Error("Failed to generate context file");o=`${t}-${fn.randomUUID().slice(0,5)}${r}`,n=D.join(B.cwd(),U,o),i+=1}return o},yn=async e=>{try{return await z.access(e),!0}catch{return!1}},_n=async()=>{try{k.log("Fetching Netlify features context...");let e=await fetch("https://docs.netlify.com/ai-context/context-consumers",{signal:AbortSignal.timeout(1e4)});if(!e.ok)throw new Error(`Failed to fetch context consumers: ${e.status} ${e.statusText}`);let t=await e.json();if(!t||typeof t!="object"||!Array.isArray(t.consumers))return k.warn("Invalid response structure: missing or invalid consumers array"),null;let r=t.consumers.find(o=>o&&typeof o=="object"&&o.key==="catchall-consumer");return r?!r.contextScopes||typeof r.contextScopes!="object"?(k.warn("Catchall consumer missing or invalid contextScopes"),null):r:(k.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?k.warn("Netlify features context request timed out"):k.warn("Failed to fetch Netlify features context:",e.message),null}},En=async(e,t)=>{try{let r=await fetch(e,{signal:AbortSignal.timeout(1e4)});if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let o=await r.text();return await z.writeFile(t,o,"utf-8"),!0}catch(r){return r.name==="AbortError"?k.warn(`Download timeout for ${e}`):k.warn(`Failed to download context file ${e}:`,r.message),!1}},De=null,wn=async()=>{if(De)return De;let e=await _n();if(!e)return[];let t=D.join(B.cwd(),U,Je);await z.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([n,i])=>{if(!i||typeof i!="object"||!i.endpoint||!i.scope)return k.warn(`Invalid scope data for ${n}, skipping...`),null;let s=`${n}.md`,c=D.join(t,s),l=D.join(U,Je,s);return k.log(`Downloading ${i.scope} context...`),await En(i.endpoint,c)?(k.log(`Downloaded: ${l}`),{scope:i.scope,path:l,key:n}):null});return De=(await Promise.all(r)).filter(n=>n!==null),De},tr=async({cliPath:e,netlify:t,config:r,buildErrorContext:o})=>{let n=mn(t),i=await hn(Nt),s=D.join(B.cwd(),U);await z.mkdir(s,{recursive:!0});let c=D.join(U,i),l=D.join(B.cwd(),c),p=D.join(B.cwd(),U,le);try{await z.unlink(p),k.log(`Deleted old results file: ${p}`)}catch{}let f=o?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
34
60
  Your task is to analyze and fix the build errors.
35
61
  Don't apply techniques of reverting changes. Apply fixes related to errors.
36
62
  Don't try to run build by yourself. Just fix the errors.
@@ -43,7 +69,7 @@ ${r.siteContext.filter(g=>g.site_context).map(g=>typeof g.site_context=="string"
43
69
 
44
70
  `)}
45
71
  </project_rules>
46
- `);let m="";if(r.sessionHistoryContext?.length){let g=L.join(B.cwd(),U,We);await z.mkdir(g,{recursive:!0});let T=await Promise.all(r.sessionHistoryContext.map(async(R,S)=>{let P=S+1,O=`attempt-${P}.md`,k=L.join(g,O),x=L.join(U,We,O),v=`# Task History - Attempt ${P}
72
+ `);let m="";if(r.sessionHistoryContext?.length){let g=D.join(B.cwd(),U,We);await z.mkdir(g,{recursive:!0});let T=await Promise.all(r.sessionHistoryContext.map(async(R,S)=>{let P=S+1,F=`attempt-${P}.md`,L=D.join(g,F),x=D.join(U,We,F),v=`# Task History - Attempt ${P}
47
73
 
48
74
  ## Request - what the user asked for
49
75
  ${R.request}
@@ -53,7 +79,7 @@ ${R.request}
53
79
  ## Response - what the agent replied with after its work
54
80
 
55
81
  ${R.response}
56
- `;return await z.writeFile(k,v,"utf-8"),D.log(`Created history file: ${x}`),x}));m+=`
82
+ `;return await z.writeFile(L,v,"utf-8"),k.log(`Created history file: ${x}`),x}));m+=`
57
83
  <session_history_context>
58
84
  History of prior work on this task.
59
85
  You MUST review ALL of the files below as context to understand the context of previous attempts. Use this information to continue the discussion appropriately.
@@ -85,8 +111,8 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
85
111
  <requirements>
86
112
  <responses>
87
113
  - Do not speak in first person. You may speak as "the agent".
88
- - When work is complete, write a changes summary in ${s}/${ae} as a standalone PR description. Explain what was accomplished and why (avoid too many implementation details), assuming the reader has no prior context. Use past tense and write in prose without calling it a "PR", "Changelog", etc. This is the core of a PR message or summary page that already has a heading.
89
- - If the user's request is informational in nature (asking for output, status, information, or analysis rather than asking you to make changes), write the requested information directly to the ${s}/${ae} file.
114
+ - When work is complete, write a changes summary in ${s}/${le} as a standalone PR description. Explain what was accomplished and why (avoid too many implementation details), assuming the reader has no prior context. Use past tense and write in prose without calling it a "PR", "Changelog", etc. This is the core of a PR message or summary page that already has a heading.
115
+ - If the user's request is informational in nature (asking for output, status, information, or analysis rather than asking you to make changes), write the requested information directly to the ${s}/${le} file.
90
116
  - Do not attempt to create git commits, PRs, etc. directly. You can use git to review information if required but the system that runs this agent will handle creating PRs or commits of the changes it performs.
91
117
  - NEVER look into the \`.git\` folder
92
118
  - NEVER print potentially sensitive values (like secrets) in the planning output or results
@@ -120,7 +146,7 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
120
146
  </extra_context>
121
147
 
122
148
  ${m}
123
- `;return await z.writeFile(l,w,"utf-8"),D.log(`Generated agent context document at: ${l}`),w.length>5e5&&(w=`
149
+ `;return await z.writeFile(l,w,"utf-8"),k.log(`Generated agent context document at: ${l}`),w.length>5e5&&(w=`
124
150
  You're an AI agent designed to assist with tasks related to a Netlify project. Please review, understand, and use the context provided to complete the user's request as needed.
125
151
 
126
152
  <request>
@@ -131,19 +157,19 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
131
157
  </request>
132
158
 
133
159
  Use the following file for the complete context of the ask, the environment, and what's available. ${l} You MUST READ ALL OF IT. Make sure to read it first. Never cite or paraphrase private context.
134
- `),w};var Tn=_("prompt"),nr=async({cliPath:e,config:t,netlify:r,buildErrorContext:o})=>{let n=await rr({cliPath:e,config:t,netlify:r,buildErrorContext:o});return process.env.AGENT_RUNNER_DEBUG&&Tn.log("Contextful Prompt:",n),{prompt:n}};var Ue=_("inference_stage"),or=5,Me=async e=>{let{cliPath:t,config:r,context:o,buildErrors:n,runner:i,persistSteps:s,aiGateway:c,attempt:l,contextPrefix:p,priorAgentSessionId:f}=e;Ue.log(`Running inference stage, attempt ${l} of ${or}`);let u=await b(at(),"inference-stage",async m=>{m?.setAttributes({"inference.attempt":l||1}),St();let{prompt:y}=await b(at(),"compose-prompt",async()=>await nr({cliPath:t,config:r,buildErrorContext:In(n),netlify:o})),I=`
160
+ `),w};var Tn=_("prompt"),rr=async({cliPath:e,config:t,netlify:r,buildErrorContext:o})=>{let n=await tr({cliPath:e,config:t,netlify:r,buildErrorContext:o});return process.env.AGENT_RUNNER_DEBUG&&Tn.log("Contextful Prompt:",n),{prompt:n}};var Ue=_("inference_stage"),nr=5,Me=async e=>{let{cliPath:t,config:r,context:o,buildErrors:n,runner:i,persistSteps:s,aiGateway:c,attempt:l,contextPrefix:p,priorAgentSessionId:f}=e;Ue.log(`Running inference stage, attempt ${l} of ${nr}`);let u=await b(at(),"inference-stage",async m=>{m?.setAttributes({"inference.attempt":l||1}),St();let{prompt:y}=await b(at(),"compose-prompt",async()=>await rr({cliPath:t,config:r,buildErrorContext:In(n),netlify:o})),I=`
135
161
  ${p||""}
136
162
  ${y}
137
- `.trim(),w={...r,prompt:I},g=await b(at(),`run-${r.runner}`,async()=>await i({aiGateway:c,config:w,netlify:o,persistSteps:s,continueSession:!!(l&&l>1),priorAgentSessionId:f}));return g.result&&(g.result=J(g.result)),g.error&&(g.error=J(g.error)),await s.flush(),g});if(u.error){if(Ue.error("Runner failed",{stepsCount:u.steps.length,duration:u.duration,error:u.error,isRetryableError:u.isRetryableError,attempt:l||1,agentSessionId:u.agentSessionId}),u.isRetryableError&&(!l||l<or))return Ue.log("Retrying inference stage"),await new Promise(y=>setTimeout(y,5e3)),{runnerResult:(await Me({...e,attempt:(l||1)+1,priorAgentSessionId:u.agentSessionId,contextPrefix:u.agentSessionId?"":"<important> The agent has already started on this work but ran into networking errors trying to complete it. Please continue from where it left off (you can use git commands to see what's currently changed thus far) and do not start over. Here is the full prompt for context: </important>"})).runnerResult};throw Ue.log("Do not retry inference stage"),new Error(u.error)}return{runnerResult:u}},In=e=>!e||e.length===0?"":`
163
+ `.trim(),w={...r,prompt:I},g=await b(at(),`run-${r.runner}`,async()=>await i({aiGateway:c,config:w,netlify:o,persistSteps:s,continueSession:!!(l&&l>1),priorAgentSessionId:f}));return g.result&&(g.result=J(g.result)),g.error&&(g.error=J(g.error)),await s.flush(),g});if(u.error){if(Ue.error("Runner failed",{stepsCount:u.steps.length,duration:u.duration,error:u.error,isRetryableError:u.isRetryableError,attempt:l||1,agentSessionId:u.agentSessionId}),u.isRetryableError&&(!l||l<nr))return Ue.log("Retrying inference stage"),await new Promise(y=>setTimeout(y,5e3)),{runnerResult:(await Me({...e,attempt:(l||1)+1,priorAgentSessionId:u.agentSessionId,contextPrefix:u.agentSessionId?"":"<important> The agent has already started on this work but ran into networking errors trying to complete it. Please continue from where it left off (you can use git commands to see what's currently changed thus far) and do not start over. Here is the full prompt for context: </important>"})).runnerResult};throw Ue.log("Do not retry inference stage"),new Error(u.error)}return{runnerResult:u}},In=e=>!e||e.length===0?"":`
138
164
  Deploy failed failed. Here are the errors to review on the latest build:
139
165
 
140
166
  Below are all of the logs with potential issues that we extracted. Some of them may be false positives, discern them carefully and ensure fixes are relevant.
141
167
 
142
168
  ${e.pop()}
143
- `;import Rn from"process";import{getTracer as lt}from"@netlify/otel";import{getTracer as xn}from"@netlify/otel";var ve=_("deploy"),ir=async e=>await b(xn(),"create-preview-deploy",async t=>vn(e,t)),vn=async({netlify:e,hasRepo:t,skipBuild:r,message:o="Agent Preview",deploySubdomain:n,cliPath:i,filter:s},c)=>{try{let l=["deploy","--message",`"${o}"`,"--json","--draft","--verbose"];t||(ve.log("Deploy: Uploading source zip"),l.push("--upload-source-zip")),n&&l.push("--alias",n),s&&l.push("--filter",s),r?(ve.log("Deploy: Skipping build"),l.push("--no-build")):l.push("--context","deploy-preview");let p=i||"netlify";ve.log(`Running: ${p} ${l.join(" ")}`),c?.setAttributes({cmd:p,args:l});let f=await e.utils.run(p,l,{stdio:["ignore","pipe","pipe"]}),u=JSON.parse(String(f.stdout??"").trim());c?.setAttributes({success:!0,deployId:u.deploy_id,deployUrl:u.deploy_url,siteId:u.site_id}),ve.log(`
144
- Preview deploy created successfully:`,{deployId:u.deploy_id,deployUrl:u.deploy_url,siteId:u.site_id});let m={deployId:u.deploy_id,previewUrl:u.deploy_url,logsUrl:u.logs,siteId:u.site_id};return t||(m.sourceZipFilename=u.source_zip_filename),m}catch(l){throw ve.error("Failed to create preview deploy via CLI:",l),c?.setAttributes({success:!1,error:l.message}),l}};var Re=_("deploy_stage"),ct=async e=>await b(lt(),"run-deploy-stage",async()=>Sn(e)),Sn=async({cliPath:e,config:t,context:r,result:o,filter:n,isRetry:i})=>{let s=await b(lt(),"get-runner-diffs",async()=>await Lt({config:t,isRetry:i}));if(Re.info("Resolved git",{hasChanges:s.hasChanges,ignored:s.ignored??[]}),!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:c,resultDiff:l,diffBinary:p,resultDiffBinary:f}=s,u=!0;Re.log("Preview deploy condition check:",{resultUndefined:o===void 0,resultType:typeof o,hasChanges:u,wouldCreatePreview:o!==void 0&&u});let m=null;if(o!==void 0&&u)try{let y;try{let I=await b(lt(),"get-runner-session",async()=>await Tt(t.id,t.sessionId));I?.title&&(y=I.title)}catch(I){Re.warn("Failed to fetch session title, using fallback message:",I.message)}await q(t.id,t.sessionId,{steps:[{title:"Deploying the run preview"}]}),m=await ir({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:y,skipBuild:!1,deploySubdomain:$t(t.id,Rn.env.SITE_NAME),filter:n})}catch(y){return Re.warn("Failed to create preview deploy (continuing with agent run):",y),{diff:c,resultDiff:l,hasChanges:u,previewInfo:null,diffBinary:p,resultDiffBinary:f,deployError:y instanceof Error?y.message:String(y)}}return Re.log("Git status",{hasDiff:!!c,hasChanges:u}),{diff:c,resultDiff:l,hasChanges:u,previewInfo:m,diffBinary:p,resultDiffBinary:f}};import{getTracer as Ge}from"@netlify/otel";async function sr(e,t){let{maxRetries:r,baseDelay:o,onRetry:n}=t,i;for(let s=1;s<=r;s++)try{return await e()}catch(c){if(i=c,s===r)throw i;n&&n(s,i),await new Promise(l=>setTimeout(l,o*s))}throw i}var je=class{scanDiffForForms(t){let r=[],o=null,n=[],i=t.split(`
169
+ `;import Rn from"process";import{getTracer as lt}from"@netlify/otel";import{getTracer as xn}from"@netlify/otel";var ve=_("deploy"),or=async e=>await b(xn(),"create-preview-deploy",async t=>vn(e,t)),vn=async({netlify:e,hasRepo:t,skipBuild:r,message:o="Agent Preview",deploySubdomain:n,cliPath:i,filter:s},c)=>{try{let l=["deploy","--message",`"${o}"`,"--json","--draft","--verbose"];t||(ve.log("Deploy: Uploading source zip"),l.push("--upload-source-zip")),n&&l.push("--alias",n),s&&l.push("--filter",s),r?(ve.log("Deploy: Skipping build"),l.push("--no-build")):l.push("--context","deploy-preview");let p=i||"netlify";ve.log(`Running: ${p} ${l.join(" ")}`),c?.setAttributes({cmd:p,args:l});let f=await e.utils.run(p,l,{stdio:["ignore","pipe","pipe"]}),u=JSON.parse(String(f.stdout??"").trim());c?.setAttributes({success:!0,deployId:u.deploy_id,deployUrl:u.deploy_url,siteId:u.site_id}),ve.log(`
170
+ Preview deploy created successfully:`,{deployId:u.deploy_id,deployUrl:u.deploy_url,siteId:u.site_id});let m={deployId:u.deploy_id,previewUrl:u.deploy_url,logsUrl:u.logs,siteId:u.site_id};return t||(m.sourceZipFilename=u.source_zip_filename),m}catch(l){throw ve.error("Failed to create preview deploy via CLI:",l),c?.setAttributes({success:!1,error:l.message}),l}};var Re=_("deploy_stage"),ct=async e=>await b(lt(),"run-deploy-stage",async()=>Sn(e)),Sn=async({cliPath:e,config:t,context:r,result:o,filter:n,isRetry:i})=>{let s=await b(lt(),"get-runner-diffs",async()=>await Dt({config:t,isRetry:i}));if(Re.info("Resolved git",{hasChanges:s.hasChanges,ignored:s.ignored??[]}),!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:c,resultDiff:l,diffBinary:p,resultDiffBinary:f}=s,u=!0;Re.log("Preview deploy condition check:",{resultUndefined:o===void 0,resultType:typeof o,hasChanges:u,wouldCreatePreview:o!==void 0&&u});let m=null;if(o!==void 0&&u)try{let y;try{let I=await b(lt(),"get-runner-session",async()=>await Tt(t.id,t.sessionId));I?.title&&(y=I.title)}catch(I){Re.warn("Failed to fetch session title, using fallback message:",I.message)}await q(t.id,t.sessionId,{steps:[{title:"Deploying the run preview"}]}),m=await or({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:y,skipBuild:!1,deploySubdomain:Ot(t.id,Rn.env.SITE_NAME),filter:n})}catch(y){return Re.warn("Failed to create preview deploy (continuing with agent run):",y),{diff:c,resultDiff:l,hasChanges:u,previewInfo:null,diffBinary:p,resultDiffBinary:f,deployError:y instanceof Error?y.message:String(y)}}return Re.log("Git status",{hasDiff:!!c,hasChanges:u}),{diff:c,resultDiff:l,hasChanges:u,previewInfo:m,diffBinary:p,resultDiffBinary:f}};import{getTracer as je}from"@netlify/otel";async function ir(e,t){let{maxRetries:r,baseDelay:o,onRetry:n}=t,i;for(let s=1;s<=r;s++)try{return await e()}catch(c){if(i=c,s===r)throw i;n&&n(s,i),await new Promise(l=>setTimeout(l,o*s))}throw i}var Ge=class{scanDiffForForms(t){let r=[],o=null,n=[],i=t.split(`
145
171
  `);for(let s of i)if(s.startsWith("diff --git")){if(o&&n.length>0){let l=this.containsNetlifyForm(n,o);l&&r.push(l)}let c=s.split(" ");o=c[c.length-1].replace(/^b\//,""),n=[]}else s.startsWith("+")&&!s.startsWith("+++")&&n.push(s.slice(1));if(o&&n.length>0){let s=this.containsNetlifyForm(n,o);s&&r.push(s)}return{detected:r.length>0,matches:r}}containsNetlifyForm(t,r){let o=t.join(`
146
- `),n=[{pattern:/<[\w-]*form[\s\S]*?(data-)?netlify/i,name:"standard form element"},{pattern:/<[A-Z][\w]*[\s\S]*?component\s*=\s*["']form["'][\s\S]*?(data-)?netlify/i,name:"component with form prop"}];for(let{pattern:i,name:s}of n){let c=o.match(i);if(c){let l=c.index||0,p=Math.max(0,l-20),f=Math.min(o.length,l+c[0].length+20),u=o.slice(p,f).trim();return u=u.replace(/\s+/g," "),u.length>100&&(u=u.slice(0,97)+"..."),{file:r,snippet:`[${s}] ${u}`}}}return null}};var A=_("cleanup_stage"),ar=async e=>await b(Ge(),"cleanup-stage",async()=>bn(e)),ut=1024*1024*10,bn=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:i,resultDiffBinary:s,previewInfo:c})=>{let l={result:r||"Done",duration:o};c&&c.deployId&&(l.deploy_id=c.deployId),c&&c.sourceZipFilename&&(l.result_zip_file_name=c.sourceZipFilename);let p=t||i||n||s;if(p&&(l.diff_produced=!0),p){let f=new je,u=t||i||"",m=f.scanDiffForForms(u);m.detected?(A.log("Detected Netlify form(s) in diff:"),m.matches.forEach(({file:y,snippet:I})=>{A.log(` - ${y}: ${I}`)}),l.has_netlify_form=!0):A.log("Did not detect Netlify form(s) in diff"),A.log("Did not detect Netlify form(s) in diff")}if(p)try{A.log("Getting pre-signed URLs for diff upload");let f=await xt(e.id,e.sessionId),u=[];(t||i)&&u.push(qe(f.result.upload_url,i||t).then(()=>{l.result_diff_s3_key=f.result.s3_key,A.log("Successfully uploaded result_diff to S3")})),(n||s)&&u.push(qe(f.cumulative.upload_url,s||n).then(()=>{l.cumulative_diff_s3_key=f.cumulative.s3_key,A.log("Successfully uploaded cumulative_diff to S3")})),A.log(`Uploading ${u.length} diff(s) to S3 in parallel`),await Promise.all(u),(n||s)&&(A.log("Updating agent runner with cumulative diff S3 key"),await b(Ge(),"update-runner",async()=>{await we(e.id,{result_diff_s3_key:f.cumulative.s3_key})}))}catch(f){A.error("S3 upload failed, falling back to inline diffs:",f);let u=Buffer.byteLength(t||i||""),m=Buffer.byteLength(s||n||"");if(u>ut||m>ut){let y=`Diffs exceed maximum inline size of ${ut} bytes.`;throw A.error(y),new Error(y)}l.result_diff=t,l.result_diff_binary=i,(n||s)&&(l.cumulative_diff=n,l.cumulative_diff_binary=s,A.log("Updating agent runner with inline diffs (fallback)"),await b(Ge(),"update-runner",async()=>{await we(e.id,{result_diff:n,result_diff_binary:s})}))}else A.log("No diffs to upload");return A.log("Updated agent runner with result"),await sr(async()=>await b(Ge(),"update-runner-session",()=>q(e.id,e.sessionId,l)),{maxRetries:3,baseDelay:1e3,onRetry:(f,u)=>{A.error(`Error updating agent runner session (attempt ${f}):`,u),A.log("Retrying...")}}),A.log("Finished updating agent runner with result"),{sessionUpdate:l}};import{getTracer as lr,shutdownTracers as Nn,withActiveSpan as cr}from"@netlify/otel";var Cn=An(import.meta.url),ur=Cn("../package.json"),Se=_("pipeline_index"),Ye=3,dr=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,filter:n,tracing:i={}})=>{let s,{withStageTimer:c}=bt(ee.timeUnits.hours(4)),l=await ht(ur.version,e.id,i);try{await cr(lr(),"run-pipeline",{},l,async()=>{let{aiGateway:p,context:f,persistSteps:u,runner:m,sha:y}=await c("init",()=>tr({config:e,apiToken:t,cliPath:r,cwd:o,filter:n,runnerVersion:ur.version}),ee.timeUnits.minutes(10));s=m.clean,e.sha=y;let{runnerResult:I}=await c("inference",()=>Me({cliPath:r,config:e,context:f,runner:m.runner,persistSteps:u,aiGateway:p}));await q(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let w=await c("deploy",()=>ct({cliPath:r,config:e,context:f,result:I.result,filter:n,isRetry:!1})),g=I,T=[];if(w.hasChanges&&w.deployError){T.push(yt(w.deployError));let x=1,v=!1;for(;x<=Ye&&!w.previewInfo&&!v;)Se.log(`Deploy attempt had errors. Retrying. ${x}/${Ye}`),await cr(lr(),"deploy-stage",async G=>{G?.setAttributes({"stage.attempt":x});let h;try{h=(await c(`inference-retry-${x}`,()=>Me({cliPath:r,config:e,context:f,runner:m.runner,persistSteps:u,aiGateway:p,buildErrors:T,priorAgentSessionId:I.agentSessionId}))).runnerResult}catch(d){Se.warn(`Inference retry ${x} failed, stopping deploy retries:`,d),v=!0;return}g={...h,steps:[...g.steps||[],...h.steps||[]],duration:(g.duration||0)+(h.duration||0)},w=await c(`deploy-retry-${x}`,()=>ct({cliPath:r,config:e,context:f,result:h.result,filter:n,isRetry:!0})),w.deployError&&T.push(w.deployError),x++});x>Ye&&!w.previewInfo&&console.warn(`Deploy validation failed after ${Ye} attempts`)}let{diff:R,resultDiff:S,previewInfo:P,diffBinary:O,resultDiffBinary:k}=w;await c("cleanup",()=>ar({config:e,diff:R,result:g.result,duration:g.duration,resultDiff:S,diffBinary:O,resultDiffBinary:k,previewInfo:P}),ee.timeUnits.minutes(10)),process.env.NETLIFY_LOCAL_MODE||(await s?.(),await Gt())})}catch(p){if(_t(p)){Se.info("Agent run terminated gracefully",{statusCode:p.statusCode,reason:p.message}),await s?.();try{await q(e.id,e.sessionId,{result:p.userMessage,state:"error"})}catch{Se.info("Could not update session (site may have been deleted)")}return}Se.error("Got error while running pipeline",p),await s?.();let f=p instanceof Error&&p.message;throw await q(e.id,e.sessionId,{result:f||"Encountered error when running agent",state:"error"}),p}finally{await Nn()}};import pr from"crypto";var $=_("bin_local"),W=Pn(C.argv.slice(2),{string:["cwd","cli-path","filter","prompt","runner","model","netlify-api-token"],boolean:["verbose","help"],alias:{h:"help",v:"verbose"}}),pt=()=>{console.log(`
172
+ `),n=[{pattern:/<[\w-]*form[\s\S]*?(data-)?netlify/i,name:"standard form element"},{pattern:/<[A-Z][\w]*[\s\S]*?component\s*=\s*["']form["'][\s\S]*?(data-)?netlify/i,name:"component with form prop"}];for(let{pattern:i,name:s}of n){let c=o.match(i);if(c){let l=c.index||0,p=Math.max(0,l-20),f=Math.min(o.length,l+c[0].length+20),u=o.slice(p,f).trim();return u=u.replace(/\s+/g," "),u.length>100&&(u=u.slice(0,97)+"..."),{file:r,snippet:`[${s}] ${u}`}}}return null}};var A=_("cleanup_stage"),sr=async e=>await b(je(),"cleanup-stage",async()=>bn(e)),ut=1024*1024*10,bn=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:i,resultDiffBinary:s,previewInfo:c})=>{let l={result:r||"Done",duration:o};c&&c.deployId&&(l.deploy_id=c.deployId),c&&c.sourceZipFilename&&(l.result_zip_file_name=c.sourceZipFilename);let p=t||i||n||s;if(p&&(l.diff_produced=!0),p){let f=new Ge,u=t||i||"",m=f.scanDiffForForms(u);m.detected?(A.log("Detected Netlify form(s) in diff:"),m.matches.forEach(({file:y,snippet:I})=>{A.log(` - ${y}: ${I}`)}),l.has_netlify_form=!0):A.log("Did not detect Netlify form(s) in diff"),A.log("Did not detect Netlify form(s) in diff")}if(p)try{A.log("Getting pre-signed URLs for diff upload");let f=await xt(e.id,e.sessionId),u=[];(t||i)&&u.push(qe(f.result.upload_url,i||t).then(()=>{l.result_diff_s3_key=f.result.s3_key,A.log("Successfully uploaded result_diff to S3")})),(n||s)&&u.push(qe(f.cumulative.upload_url,s||n).then(()=>{l.cumulative_diff_s3_key=f.cumulative.s3_key,A.log("Successfully uploaded cumulative_diff to S3")})),A.log(`Uploading ${u.length} diff(s) to S3 in parallel`),await Promise.all(u),(n||s)&&(A.log("Updating agent runner with cumulative diff S3 key"),await b(je(),"update-runner",async()=>{await Te(e.id,{result_diff_s3_key:f.cumulative.s3_key})}))}catch(f){A.error("S3 upload failed, falling back to inline diffs:",f);let u=Buffer.byteLength(t||i||""),m=Buffer.byteLength(s||n||"");if(u>ut||m>ut){let y=`Diffs exceed maximum inline size of ${ut} bytes.`;throw A.error(y),new Error(y)}l.result_diff=t,l.result_diff_binary=i,(n||s)&&(l.cumulative_diff=n,l.cumulative_diff_binary=s,A.log("Updating agent runner with inline diffs (fallback)"),await b(je(),"update-runner",async()=>{await Te(e.id,{result_diff:n,result_diff_binary:s})}))}else A.log("No diffs to upload");return A.log("Updated agent runner with result"),await ir(async()=>await b(je(),"update-runner-session",()=>q(e.id,e.sessionId,l)),{maxRetries:3,baseDelay:1e3,onRetry:(f,u)=>{A.error(`Error updating agent runner session (attempt ${f}):`,u),A.log("Retrying...")}}),A.log("Finished updating agent runner with result"),{sessionUpdate:l}};import{getTracer as ar,shutdownTracers as Nn,withActiveSpan as lr}from"@netlify/otel";var Cn=An(import.meta.url),cr=Cn("../package.json"),Se=_("pipeline_index"),Ye=3,ur=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,filter:n,tracing:i={}})=>{let s,{withStageTimer:c}=bt(ee.timeUnits.hours(4)),l=await ht(cr.version,e.id,i);try{await lr(ar(),"run-pipeline",{},l,async()=>{let{aiGateway:p,context:f,persistSteps:u,runner:m,sha:y}=await c("init",()=>er({config:e,apiToken:t,cliPath:r,cwd:o,filter:n,runnerVersion:cr.version}),ee.timeUnits.minutes(10));s=m.clean,e.sha=y;let{runnerResult:I}=await c("inference",()=>Me({cliPath:r,config:e,context:f,runner:m.runner,persistSteps:u,aiGateway:p}));await q(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let w=await c("deploy",()=>ct({cliPath:r,config:e,context:f,result:I.result,filter:n,isRetry:!1})),g=I,T=[];if(w.hasChanges&&w.deployError){T.push(yt(w.deployError));let x=1,v=!1;for(;x<=Ye&&!w.previewInfo&&!v;)Se.log(`Deploy attempt had errors. Retrying. ${x}/${Ye}`),await lr(ar(),"deploy-stage",async j=>{j?.setAttributes({"stage.attempt":x});let h;try{h=(await c(`inference-retry-${x}`,()=>Me({cliPath:r,config:e,context:f,runner:m.runner,persistSteps:u,aiGateway:p,buildErrors:T,priorAgentSessionId:I.agentSessionId}))).runnerResult}catch(d){Se.warn(`Inference retry ${x} failed, stopping deploy retries:`,d),v=!0;return}g={...h,steps:[...g.steps||[],...h.steps||[]],duration:(g.duration||0)+(h.duration||0)},w=await c(`deploy-retry-${x}`,()=>ct({cliPath:r,config:e,context:f,result:h.result,filter:n,isRetry:!0})),w.deployError&&T.push(w.deployError),x++});x>Ye&&!w.previewInfo&&console.warn(`Deploy validation failed after ${Ye} attempts`)}let{diff:R,resultDiff:S,previewInfo:P,diffBinary:F,resultDiffBinary:L}=w;await c("cleanup",()=>sr({config:e,diff:R,result:g.result,duration:g.duration,resultDiff:S,diffBinary:F,resultDiffBinary:L,previewInfo:P}),ee.timeUnits.minutes(10)),process.env.NETLIFY_LOCAL_MODE||(await s?.(),await jt())})}catch(p){if(_t(p)){Se.info("Agent run terminated gracefully",{statusCode:p.statusCode,reason:p.message}),await s?.();try{await q(e.id,e.sessionId,{result:p.userMessage,state:"error"})}catch{Se.info("Could not update session (site may have been deleted)")}return}Se.error("Got error while running pipeline",p),await s?.();let f=p instanceof Error&&p.message;throw await q(e.id,e.sessionId,{result:f||"Encountered error when running agent",state:"error"}),p}finally{await Nn()}};import dr from"crypto";var O=_("bin_local"),W=Pn(C.argv.slice(2),{string:["cwd","cli-path","filter","prompt","runner","model","netlify-api-token"],boolean:["verbose","help"],alias:{h:"help",v:"verbose"}}),pt=()=>{console.log(`
147
173
  agent-runner-cli-local - Run Netlify agent runner locally without API connections
148
174
 
149
175
  USAGE:
@@ -175,6 +201,6 @@ NOTE:
175
201
  This local mode mocks all Netlify API calls. The agent will run through
176
202
  the full pipeline including inference and deployment, but API calls will
177
203
  be logged instead of executed.
178
- `)};W.help&&(pt(),C.exit(0));W.prompt||($.error("Error: --prompt is required"),pt(),C.exit(1));W["netlify-api-token"]||($.error("Error: --netlify-api-token is required - generate a PAT from your Netlify user settings"),pt(),C.exit(1));try{let e=W.cwd||C.cwd(),t=fr.join(e,".netlify","netlify-agent-runner-context*");mr.rmSync(t,{recursive:!0,force:!0});let r;try{r=await On(e)}catch(c){$.error(c.message),$.error(`
179
- To link this directory to a Netlify site, run:`),$.error(" netlify link"),C.exit(1)}let o=`local-${pr.randomBytes(8).toString("hex")}`,n=`session-${pr.randomBytes(8).toString("hex")}`,i=W.runner||"claude";$.log("Starting agent runner in local mode",{runnerId:o,sessionId:n,siteId:r,cwd:e,runner:i});let s={id:o,sessionId:n,prompt:W.prompt,runner:i,model:W.model,accountType:"local",validateAgentWithBuild:!1,sessionHistoryContext:[],siteContext:[],hasRepo:!0,useGateway:!0,sha:void 0,modelVersionOverrides:{}};C.env.NETLIFY_LOCAL_MODE="true",C.env.NETLIFY_API_HOST="api.netlify.com",C.env.NETLIFY_API_TOKEN=W["netlify-api-token"],C.env.SITE_ID=r,C.env.NETLIFY_TEAM_ID="local-team-id",C.env.NETLIFY_AGENT_RUNNER_USER_ID="local-user-id",C.env.SITE_NAME="local-site",i==="claude"?Oe(e,"claude")||($.log("Claude CLI not found, installing..."),await dt(e,"@anthropic-ai/claude-code")):i==="gemini"?Oe(e,"gemini")||($.log("Gemini CLI not found, installing..."),await dt(e,"@google/gemini-cli")):i==="codex"?Oe(e,"codex")||($.log("Codex CLI not found, installing..."),await dt(e,"@openai/codex")):($.error(`Unknown runner: ${i}`),C.exit(1)),await dr({config:s,cwd:e,cliPath:W["cli-path"],filter:W.filter,tracing:{exporterUrl:void 0,traceparent:void 0}}),$.info("Finished agent (local mode)"),C.exit(0)}catch(e){$.error("Error running agent pipeline (local mode):",e),C.exit(1)}function dt(e,t){return new Promise((r,o)=>{N("npm",["install",t,"--no-save"],{cwd:e}).then(({stdout:n})=>{$.log(`${t} installed: ${n}`),r()}).catch(n=>{$.error(`Error installing ${t}: ${n.stderr||n.message}`),o(n)})})}async function On(e){let t=fr.join(e,".netlify","state.json");try{let r=await mr.readFileSync(t,"utf-8"),o=JSON.parse(r);if(!o.siteId)throw new Error(`No siteId found in ${t}. Please link this directory to a Netlify site using 'netlify link'.`);return $.log(`Found site ID from state file: ${o.siteId}`),o.siteId}catch(r){throw r.code==="ENOENT"?new Error(`No .netlify/state.json found in ${e}. Please link this directory to a Netlify site using 'netlify link'.`):r}}
204
+ `)};W.help&&(pt(),C.exit(0));W.prompt||(O.error("Error: --prompt is required"),pt(),C.exit(1));W["netlify-api-token"]||(O.error("Error: --netlify-api-token is required - generate a PAT from your Netlify user settings"),pt(),C.exit(1));try{let e=W.cwd||C.cwd(),t=pr.join(e,".netlify","netlify-agent-runner-context*");fr.rmSync(t,{recursive:!0,force:!0});let r;try{r=await Fn(e)}catch(c){O.error(c.message),O.error(`
205
+ To link this directory to a Netlify site, run:`),O.error(" netlify link"),C.exit(1)}let o=`local-${dr.randomBytes(8).toString("hex")}`,n=`session-${dr.randomBytes(8).toString("hex")}`,i=W.runner||"claude";O.log("Starting agent runner in local mode",{runnerId:o,sessionId:n,siteId:r,cwd:e,runner:i});let s={id:o,sessionId:n,prompt:W.prompt,runner:i,model:W.model,accountType:"local",validateAgentWithBuild:!1,sessionHistoryContext:[],siteContext:[],hasRepo:!0,useGateway:!0,sha:void 0,modelVersionOverrides:{}};C.env.NETLIFY_LOCAL_MODE="true",C.env.NETLIFY_API_HOST="api.netlify.com",C.env.NETLIFY_API_TOKEN=W["netlify-api-token"],C.env.SITE_ID=r,C.env.NETLIFY_TEAM_ID="local-team-id",C.env.NETLIFY_AGENT_RUNNER_USER_ID="local-user-id",C.env.SITE_NAME="local-site",i==="claude"?Fe(e,"claude")||(O.log("Claude CLI not found, installing..."),await dt(e,"@anthropic-ai/claude-code")):i==="gemini"?Fe(e,"gemini")||(O.log("Gemini CLI not found, installing..."),await dt(e,"@google/gemini-cli")):i==="codex"?Fe(e,"codex")||(O.log("Codex CLI not found, installing..."),await dt(e,"@openai/codex")):(O.error(`Unknown runner: ${i}`),C.exit(1)),await ur({config:s,cwd:e,cliPath:W["cli-path"],filter:W.filter,tracing:{exporterUrl:void 0,traceparent:void 0}}),O.info("Finished agent (local mode)"),C.exit(0)}catch(e){O.error("Error running agent pipeline (local mode):",e),C.exit(1)}function dt(e,t){return new Promise((r,o)=>{N("npm",["install",t,"--no-save"],{cwd:e}).then(({stdout:n})=>{O.log(`${t} installed: ${n}`),r()}).catch(n=>{O.error(`Error installing ${t}: ${n.stderr||n.message}`),o(n)})})}async function Fn(e){let t=pr.join(e,".netlify","state.json");try{let r=await fr.readFileSync(t,"utf-8"),o=JSON.parse(r);if(!o.siteId)throw new Error(`No siteId found in ${t}. Please link this directory to a Netlify site using 'netlify link'.`);return O.log(`Found site ID from state file: ${o.siteId}`),o.siteId}catch(r){throw r.code==="ENOENT"?new Error(`No .netlify/state.json found in ${e}. Please link this directory to a Netlify site using 'netlify link'.`):r}}
180
206
  //# sourceMappingURL=bin-local.js.map