@netlify/agent-runner-cli 1.49.0-alpha → 1.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin-local.js CHANGED
@@ -1,27 +1,24 @@
1
1
  #!/usr/bin/env node
2
- import b from"process";import qt from"path";import Wt from"fs";import rn from"minimist";import{createRequire as Qr}from"module";import{createTracerProvider as Vt}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as Ze}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as Jt}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as Xt}from"@netlify/otel";import{propagation as Qe,context as et,W3CTraceContextPropagator as zt}from"@netlify/otel/opentelemetry";import{OTLPTraceExporter as Zt}from"@opentelemetry/exporter-trace-otlp-grpc";function w(e){let t=!process.env.VITEST;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 Pe=w("tracing"),tt=async(e,t,r)=>(await Vt({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new Ze(new Oe),new Ze(new Zt({url:r.exporterUrl}))],instrumentations:[new Jt({skipHeaders:!0})]}),r.traceparent?(Qe.setGlobalPropagator(new zt),Qe.extract(et.active(),{traceparent:r.traceparent,isRemote:!0})):et.active());function A(e,t,r){return Pe.log(`\u23F3 TRACE: ${t} starting...`),Xt(e,t,r)}var Oe=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[u,s]of Object.entries(o))u.includes("duration")&&typeof s=="number"?n.push(`${u}=${s.toFixed(2)}ms`):n.push(`${u}=${s}`);let i=t.status?.code===2?"\u274C":"\u2705",a=n.length>0?` [${n.join(", ")}]`:"";Pe.log(`${i} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${a}`),t.status?.code===2&&t.status.message&&Pe.log(` \u274C Error: ${t.status.message}`)}};var Qt=["error","failed","exception","fatal","panic","abort","crash"];function rt(e){let t=e.split(`
3
- `),r=[],o=-1,n=0;for(;n<t.length;){let u=t[n].slice(0,500).toLowerCase();if(Qt.some(y=>u.includes(y))){let y=Math.max(0,n-10,o+1),l=Math.min(t.length-1,n+20),c=[];for(let g=y;g<=l;g++)c.push(t[g]);r.push(c.join(`
4
- `)),o=l,n=l+1}else n++}if(r.length===0)return e;let i=r.map((a,u)=>`<extracted_error_chunk order="${u+1}">
2
+ import O from"process";import zt from"path";import Zt from"fs";import hn from"minimist";import{createRequire as fn}from"module";import{createTracerProvider as Qt}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as et}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as er}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as tr}from"@netlify/otel";import{propagation as tt,context as rt,W3CTraceContextPropagator as rr}from"@netlify/otel/opentelemetry";import{OTLPTraceExporter as nr}from"@opentelemetry/exporter-trace-otlp-grpc";function E(e){let t=!process.env.VITEST;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 Oe=E("tracing"),nt=async(e,t,r)=>(await Qt({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new et(new ke),new et(new nr({url:r.exporterUrl}))],instrumentations:[new er({skipHeaders:!0})]}),r.traceparent?(tt.setGlobalPropagator(new rr),tt.extract(rt.active(),{traceparent:r.traceparent,isRemote:!0})):rt.active());function b(e,t,r){return Oe.log(`\u23F3 TRACE: ${t} starting...`),tr(e,t,r)}var ke=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[l,s]of Object.entries(o))l.includes("duration")&&typeof s=="number"?n.push(`${l}=${s.toFixed(2)}ms`):n.push(`${l}=${s}`);let i=t.status?.code===2?"\u274C":"\u2705",a=n.length>0?` [${n.join(", ")}]`:"";Oe.log(`${i} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${a}`),t.status?.code===2&&t.status.message&&Oe.log(` \u274C Error: ${t.status.message}`)}};var or=["error","failed","exception","fatal","panic","abort","crash"];function ot(e){let t=e.split(`
3
+ `),r=[],o=-1,n=0;for(;n<t.length;){let l=t[n].slice(0,500).toLowerCase();if(or.some(m=>l.includes(m))){let m=Math.max(0,n-10,o+1),u=Math.min(t.length-1,n+20),c=[];for(let f=m;f<=u;f++)c.push(t[f]);r.push(c.join(`
4
+ `)),o=u,n=u+1}else n++}if(r.length===0)return e;let i=r.map((a,l)=>`<extracted_error_chunk order="${l+1}">
5
5
  ${a}
6
6
  </extracted_error_chunk>`).join(`
7
7
 
8
- `);return i.length>e.length*.8?e:i}import Re from"process";import{getTracer as Lr}from"@netlify/otel";import le from"process";var me=le.env.NETLIFY_API_URL,he=le.env.NETLIFY_API_TOKEN,G=w("api"),ye=()=>le.env.NETLIFY_LOCAL_MODE==="true",ue=async(e,t={})=>{if(!me||!he)throw new Error("No API URL or token");let r=new URL(e,me),o={...t,headers:{...t.headers,Authorization:`Bearer ${he}`}};le.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let n=await fetch(r,o),i=n.ok&&n.status<=299;if(le.env.AGENT_RUNNERS_DEBUG==="true")G.log(`Response headers for ${r}:`),n.headers.forEach((u,s)=>{G.log(` ${s}: ${u}`)});else{let u=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");G.log(`Request ID for ${r}: ${u||"N/A"}`)}if(i||G.error(`Got status ${n.status} for request ${r}`),t.raw){if(!i)throw n;return n}let a=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!i)throw a;return a},nt=e=>{G.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(me=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(he=e.constants.NETLIFY_API_TOKEN)},ot=()=>({apiUrl:me,token:he}),ce=async(e,t)=>ye()?(G.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):ue(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),B=async(e,t,r)=>ye()?(G.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):ue(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var it=async(e,t)=>ye()?(G.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):ue(`/api/v1/agent_runners/${e}/sessions/${t}`),st=(e,t,r)=>ue(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}}),at=async(e,t)=>ye()?(G.log("Mock API: getDiffUploadUrls called",{runnerId:e,sessionId:t}),{result:{upload_url:"https://s3.mock.com/mock-upload-url-result",s3_key:"mock-s3-key-result"},cumulative:{upload_url:"https://s3.mock.com/mock-upload-url-cumulative",s3_key:"mock-s3-key-cumulative"}}):ue(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),$e=async(e,t)=>{G.log(`Uploading diff to S3: ${e.substring(0,50)}...`);let r=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"text/plain"}});if(!r.ok)throw new Error(`S3 upload failed with status ${r.status}`);return r};var ee=w("ai_gateway"),ke=null;var lt=async()=>{if(ke)return ke;ee.log("Fetching available AI gateway providers");let e=await fetch(`${ot().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,ee.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},er=async(e,t)=>{let o=(await lt()).providers[e];if(!o)return ee.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return ee.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},ut=async({netlify:e,config:t})=>{let r,o,n,i,a=e.constants?.SITE_ID;if(!a)throw new Error("No site id");let u=async()=>{clearTimeout(n),ee.log("Requesting AI gateway information");let s=await st(a,t.id,t.sessionId);if({token:r,url:i}=s,o=s.expires_at?s.expires_at*1e3:void 0,ee.log("Got AI gateway information",{token:!!r,expiresAt:o,url:i}),o){let y=o-Date.now()-6e4;y>0&&(n=setTimeout(()=>{u()},y))}};return await Promise.all([u(),lt()]),{get url(){return i},get token(){return r},isModelAvailableForProvider:er}};import K from"process";import Ee from"path";import De from"fs";import{fileURLToPath as sr}from"url";import{execa as ar,execaCommand as Cn}from"execa";import{Transform as tr}from"stream";var rr=new Set(["NODE_ENV","PATH","HOME","USER","USERNAME","SHELL","PWD","OLDPWD","TMPDIR","TMP","TEMP","LANG","TERM","EDITOR","PAGER","OS","PROCESSOR_ARCHITECTURE","PROCESSOR_IDENTIFIER","SYSTEMROOT","WINDIR","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","APPDATA","LOCALAPPDATA","NODE_OPTIONS","NODE_PATH","NODE_DEBUG","NODE_NO_WARNINGS","npm_config_registry","npm_config_cache","npm_execpath","npm_node_execpath","CI","GITHUB_ACTIONS","GITHUB_WORKSPACE","GITHUB_REPOSITORY","GITHUB_REF","BUILDKITE","BUILDKITE_BRANCH","BUILDKITE_COMMIT","BUILDKITE_BUILD_NUMBER","JENKINS_URL","TRAVIS","CIRCLECI","DISPLAY","COLORTERM","TERM_PROGRAM","TERM_PROGRAM_VERSION","COLUMNS","LINES","HISTSIZE","HISTFILE","NETLIFY_AGENT_RUNNER_ID","NETLIFY_AGENT_RUNNER_SESSION_ID","NETLIFY_AGENT_RUNNER_PROMPT","NETLIFY_AGENT_RUNNER_AGENT","NETLIFY_AGENT_RUNNER_MODEL","NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED","NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED","ERROR_LOGS_PATH","NETLIFY_AGENT_RUNNER_CONTEXT","NETLIFY_AGENT_RUNNER_HAS_REPO","NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED","NETLIFY_AGENT_RUNNER_SHA","NETLIFY_TEAM_TYPE","AGENT_RUNNERS_DEBUG","NETLIFY_TEAM_ID","NETLIFY_AGENT_RUNNER_USER_ID","SITE_NAME"]),nr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function or(){return Object.entries(process.env).filter(([e,t])=>!(!t||rr.has(e)||nr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function H(e){if(typeof e!="string")return e;let t=or();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(ir(o),"g");r=r.replace(n,"******")}),r}function ir(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var te=class extends tr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),i=H(n);o(null,i)}};function ct(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(o,n,i){let a=typeof o=="string"?H(o):o;return typeof n=="function"?t(a,n):t(a,n,i)},process.stderr.write=function(o,n,i){let a=typeof o=="string"?H(o):o;return typeof n=="function"?r(a,n):r(a,n,i)}}var de=null,dt=e=>(de&&de.destroy(),de=new V({totalAllowedTime:e}),de),pt=()=>de;var V=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,o)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let n=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),i=null,a=null;o!==void 0&&(a=new Promise((u,s)=>{i=setTimeout(()=>{s(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return a?await Promise.race([r(),a]):await r()}finally{n(),i&&clearTimeout(i)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var lr=sr(import.meta.url),ur=Ee.dirname(lr),_e=w("shell"),Le=new Set,cr={preferLocal:!0},we=(e,t,r)=>{let[o,n]=dr(t,r),i={...cr,...n},a=ar(e,o,i);return pr(a,i),gr(a),a};var dr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},pr=(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 te).pipe(K.stdout),e.stdout?.pipe(new te).pipe(K.stdout),e.stderr?.pipe(new te).pipe(K.stderr);return}e.stdout?.pipe(K.stdout),e.stderr?.pipe(K.stderr)},ft=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(K.kill(-e.pid,t),_e.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return _e.error("Error killing process:",r),!1}},fr=e=>ft(e,"SIGKILL"),gr=e=>{Le.add(e);let t=pt();if(t){let r=t.onTimesUp(()=>{_e.log(`Global timer expired, killing process ${e.pid}`),ft(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(_e.log(`Force killing process ${e.pid} after timeout`),fr(e))},5e3)});e.on("exit",()=>{Le.delete(e),r()}),e.on("error",()=>{Le.delete(e),r()})}};function Ie(e,t){return!!J(e,t)}function J(e,t){if(K.env.NODE_PATH){let n=Ee.join(K.env.NODE_PATH,".bin",t);if(De.existsSync(n))return n}let r=Ee.join(e,"node_modules",".bin",t);if(De.existsSync(r))return r;let o=Ee.join(ur,"..","node_modules",".bin",t);if(De.existsSync(o))return o}var gt="netlify-agent-runner-context.md",Fe="task-history",Ue="netlify-context",F=".netlify",re="results.md",Me="assets";var mr=w("utils"),hr=e=>new Promise(t=>{setTimeout(t,e)}),mt=(e,t=3e3)=>{let r=!1,o=null,n=[],i=null,a=(...u)=>{if(r)return o=u,new Promise(l=>{n.push(l)});r=!0;let s,y=new Promise(l=>{s=l});return i=(async()=>{await Promise.resolve();let l=await e(...u);for(s(l);;){if(await hr(t),!o)return r=!1,i=null,l;let c=o,g=n;o=null,n=[],l=await e(...c),g.forEach(E=>{E(l)})}})(),y};return a.flush=async()=>{if((r||o)&&i)return await i,a.flush()},a},Te=(e,t,r=!1)=>{let o=null,n=null,i=null,a=function(...u){n=u,i=this;let s=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(i,n),n=null,i=null)},t),s&&(e.apply(i,n),n=null,i=null)};return a.cancel=()=>{clearTimeout(o),o=null,n=null,i=null},a.flush=()=>{if(o){clearTimeout(o);let u=n,s=i;o=null,n=null,i=null,e.apply(s,u)}},a},ht=(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))}},yt=(e,t)=>{let n=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let u=`--${t}${n}`;if(u.length>55)return"";let s=60-u.length;if(s<=0)return"";if(s>=i.length+6){let y=Math.min(s-i.length,e.length);return`${i}${e.slice(0,y)}`}return e.slice(0,s)};import{Buffer as Et}from"buffer";import yr from"path";var _t=async({config:e,netlify:t})=>{let r=await _r(t),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};let i=await wr(n);await t.utils.run("git",["add",".",...i]);let a={stdio:["ignore","pipe","pipe"]},s=(await t.utils.run("git",["diff","--staged"],a)).stdout;if(o=!!s,!o)return{hasChanges:!1,ignored:i};let l=(await t.utils.run("git",["diff","--staged","--binary"],a)).stdout,c,g;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await t.utils.run("git",["commit","-m","Agent runner"]),c=(await t.utils.run("git",["diff",e.sha,"HEAD"],a)).stdout;let h=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;c!==h&&(g=Et.from(h).toString("base64"))}let E={hasChanges:!0,diff:s,resultDiff:c,ignored:i};return s!==l&&(E.diffBinary=Et.from(l).toString("base64")),g&&(E.resultDiffBinary=g),E},Er=["?? mise.toml","?? deno.lock","?? .npmrc",/\?\? .+?\.log/],_r=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
9
- `).filter(n=>!Er.some(i=>i instanceof RegExp?i.test(n):n===i))).length!==0,status:t.stdout}};var wt=async e=>{let{stdout:t}=await e.utils.run("git",["rev-parse","HEAD"]);return t.trim()},It=async e=>{let{stdout:t}=await e.utils.run("git",["rev-list","--max-parents=0","HEAD"]);return t.trim()},wr=async e=>{let t=[".netlify","mise.toml","deno.lock",".npmrc","node_modules"],r=[];return e.split(`
10
- `).forEach(o=>{t.forEach(i=>{[`?? ${i}`,`?? ${i}${yr.sep}`].some(u=>o.startsWith(u))&&r.push(`:!${i}`)});let n=o.match(/\?\? (.+?)\.log$/)?.[1];n&&r.push(`:!${n}.log`)}),r};import Tr from"fs/promises";import xr from"os";import vt from"path";import X from"process";import vr from"readline";import Ge from"path";import Ir from"fs/promises";var je=w("agent-output-utils");async function ne({initialResult:e,agentName:t,hasError:r}){let o="",n=Ge.join(process.cwd(),F,re);try{let i=await Ir.readFile(n,"utf-8");i&&(o=i,je.log(`Pulled result from ${Ge.relative(process.cwd(),n)}`))}catch{je.log(`No results file found at ${Ge.relative(process.cwd(),n)}`)}return o||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function oe({error:e,agentName:t}){let r=e&&typeof e=="object"?JSON.stringify(e):e,o=r?.replace(/\s+/g," ").trim().toLowerCase()||"",n="";return o?.includes("ai gateway is not available for your account")||o?.includes("ai gateway is not enabled for your account")?n="AI Gateway is currently not available on your account. Please confirm your account meets the criteria for using Agent Runners and AI Gateway and that your account has remaining AI Gateway inference credits available. Reach out to Netlify support if this is unexpected.":o?.includes("error when talking to gemini api")?n="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":(o?.includes("connection closed prematurely")||o?.includes("499")&&t.toLowerCase().includes("gemini"))&&(n=`The ${t} models were currently overloaded. Please try again or use a different available agent.`),o?.includes("request timed out")&&(n=`The ${t} API request's have timed out. Please try again or use a different available agent.`),o?.includes("network error")&&(n=`The ${t} agent is having network issues. Please try again or use a different available agent.`),n&&je.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function ie(e){if(!e)return!1;let r=(e&&typeof e=="object"?JSON.stringify(e):e)?.replace(/\s+/g," ").trim().toLowerCase()||"";return!!(r?.includes("error when talking to gemini api")||r?.includes("499")||r?.includes("connection closed prematurely")||r?.includes("request timed out")||r?.includes("network error"))}var U=w("runner_claude"),Tt="Claude Code",xe="claude-sonnet-4-5-20250929",xt=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,Rr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(U.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(U.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(U.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function Ye({config:e,netlify:t,persistSteps:r,aiGateway:o,continueSession:n,priorAgentSessionId:i}){let a=e,{accountType:u,prompt:s,modelVersionOverrides:y}=a,{model:l}=a,c="";if(o){let{token:f,url:_}=o;if(!f||!_)throw new Error("No token or url provided from AI Gateway");if(y?.claude){let d=y?.claude?.[u];if(d){if(!await o.isModelAvailableForProvider("anthropic",d))throw new Error(`Model override '${d}' is not available for anthropic provider`);l=d}}else if(l){if(!await o.isModelAvailableForProvider("anthropic",l))throw new Error(`Model '${l}' is not available for anthropic provider`)}else await o.isModelAvailableForProvider("anthropic",xe)?(l=xe,U.log(`Using default model: ${xe}`)):U.log(`Default model ${xe} is not available, proceeding without model specification`);X.env.ANTHROPIC_API_KEY=f,X.env.ANTHROPIC_BASE_URL=_}else if(!X.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let g=[],E=[],T={},I=0,h=0,x,v,C=[J(X.cwd(),"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...l?["--model",l]:[],...n?["--continue"]:[],...n&&i?["--resume",i]:[],"-p",s],N=`${X.env.NVM_BIN}/node`;U.log(`Running ${N} ${C.join(" ")}`);let R=t.utils.run(N,C,{all:!0,env:X.env});R.stdin?.end();let S=Te(()=>{r?.({steps:g,duration:h})},250),m=(f,_)=>{let d={...f,id:I};I+=1,E.push(d),g.push(d),_||S.flush(),S(),_&&S.flush()},p=vr.createInterface({input:R.all});return p.on("error",f=>{U.error("Readline interface error",{error:f.message,stack:f.stack})}),p.on("line",f=>{let _=null;try{_=JSON.parse(f)}catch{U.log("Could not parse line",f)}_?.session_id&&_.session_id!==c&&(c=_.session_id),Array.isArray(_?.message?.content)?_.message.content.forEach(d=>{switch(d.type){case"text":{d.text&&m({message:d.text});break}case"image":{typeof d.source=="object"&&d.source&&d.source.type==="base64"&&d.source.media_type?m({message:`![](data:${d.source.media_type};base64,${d.source.data})`}):U.log(`Unsupported image type ${d.source?.type}`,d.source);break}case"tool_use":{if(d.name==="Task"){let P=d.input?.description&&`\`${d.input.description}\``;m({title:[xt(d.name),P].filter(Boolean).join(" ")})}else d.id&&(T[d.id]=d);S.flush();break}case"tool_result":{let P=d.tool_use_id?T[d.tool_use_id]:void 0,ae;if(P){let Q=P.input?.file_path&&vt.relative(X.cwd(),P.input.file_path),O=Q&&`\`${Q}\``;ae=[xt(P.name||""),O].filter(Boolean).join(" ")}let ze=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(P?.name||""),q;if(typeof d.content=="string")q=d.content;else if(Array.isArray(d.content)){let Q=[];d.content.forEach(O=>{O?.type==="text"&&typeof O.text=="string"?Q.push(O.text):O?.type==="image"&&typeof O.source=="object"&&O.source?O.source.type==="base64"&&O.source.media_type?Q.push(`![](data:${O.source.media_type};base64,${O.source.data})`):U.log(`Unsupported image type ${O.source.type}`,O.source):U.log(`Unsupported block type ${O?.type}`)}),q=Q.join(`
11
-
12
- `)}ze&&q&&(q=`\`\`\`
13
- ${q.trim()}
14
- \`\`\``),m({title:ae,message:q},!0);break}case"thinking":{d.thinking&&m({title:"Thinking",message:d.thinking},!0);break}default:U.log(`Message content type is not supported ${d.type}`,d)}}):_?.type==="result"&&(h=_.duration_ms||0,_.is_error?v=_.result:x=_.result,[E,g].forEach(d=>{d[d.length-1]?.message===x&&d.pop()}))}),await R.catch(f=>{({error:v,result:x}=Rr({catchError:f,runCmd:R,error:v,result:x,runnerName:"Claude"}))}),p.close(),S.flush(),{steps:E,duration:h,result:await ne({initialResult:x,agentName:Tt,hasError:!!v}),error:oe({error:v,agentName:Tt}),isRetryableError:ie(v),agentSessionId:c}}var Rt=async()=>{let e=vt.join(xr.homedir(),".claude");await Tr.rm(e,{recursive:!0,force:!0})};import pe from"fs/promises";import At from"os";import ve from"path";import z from"process";import Sr from"readline";var j=w("runner_codex"),St="Codex CLI",Ar=({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 Be({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:i,prompt:a,modelVersionOverrides:u}=e,{model:s}=e;if(n){let{token:m,url:p}=n;if(!m||!p)throw new Error("No token or url provided from AI Gateway");if(u?.codex){let f=u?.codex?.[i];if(f){if(!await n.isModelAvailableForProvider("openai",f))throw new Error(`Model override '${f}' is not available for openai provider`);s=f}}else if(s&&!await n.isModelAvailableForProvider("openai",s))throw new Error(`Model '${s}' is not available for openai provider`);z.env.OPENAI_API_KEY=m,z.env.OPENAI_BASE_URL=p}else if(!z.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let y=[],l=[],c={},g=0,E=0,T,I,h=`${z.env.NVM_BIN}/node`,x=ve.join(At.homedir(),".codex"),v=ve.join(x,"config.toml"),C=ve.join(x,"auth.json");try{await pe.mkdir(x,{recursive:!0});let m={OPENAI_API_KEY:z.env.OPENAI_API_KEY};await pe.writeFile(C,JSON.stringify(m,null,2),"utf-8"),j.log("Created Codex auth.json file");let p="";try{p=await pe.readFile(v,"utf-8")}catch{}p.includes("web_search")||(p.includes("[tools]")?p=p.replace(/\[tools\]/,`[tools]
15
- web_search = true`):p+=`
16
- [tools]
17
- web_search = true
18
- `,await pe.writeFile(v,p,"utf-8"),j.log("Updated Codex config with web_search enabled"))}catch(m){throw j.warn("Failed to setup Codex config and credentials",{error:m.message}),new Error(`Codex setup failed: ${m.message}`)}let N=[J(z.cwd(),"codex"),"exec","--yolo","--json","--config","web_search=true",...s?["--model",s]:[],a].filter(Boolean);j.log(`Running ${h} ${N.join(" ")}`);let R=t.utils.run(h,N,{all:!0,env:{...z.env}}),S=Sr.createInterface({input:R.all});return S.on("error",m=>{j.error("Readline interface error",{error:m.message,stack:m.stack})}),S.on("line",m=>{let p=null;try{p=JSON.parse(m)}catch{j.log("Could not parse line",m);return}let f=[],_=!1;if(p?.duration_ms&&(E=p.duration_ms,_=!0),p?.type==="local_shell_call")c[p.call_id]=p;else if(p?.type==="local_shell_call_output"){let d=br(c[p.call_id],p);d&&(d.id=g,g+=1,l.push(d),y.push(d),f.push(d),_=!0)}else p?.type==="message"&&p.role==="assistant"?T=p.content.map(d=>d.text).join(`
19
- `):p?.type==="message"&&p.role==="system"&&(I=p.content.map(d=>d.text).join(`
20
- `));_&&(r?.({steps:y,duration:E}),o?.({steps:f,duration:E}))}),await R.catch(m=>{let p=Ar({catchError:m,runCmd:R,error:I,result:T,runnerName:"Codex"});I=p.error,T=p.result}),S.close(),{steps:l,duration:E,result:await ne({initialResult:T,agentName:St,hasError:!!I}),error:oe({error:I,agentName:St}),isRetryableError:ie(I)}}var Nt=async()=>{let e=ve.join(At.homedir(),".codex");await pe.rm(e,{recursive:!0,force:!0})},Nr=new Set(["bash","-lc"]),br=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(i=>!Nr.has(i)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
8
+ `);return i.length>e.length*.8?e:i}import Re from"process";import{getTracer as Vr}from"@netlify/otel";import ue from"process";var ye=ue.env.NETLIFY_API_URL,Ee=ue.env.NETLIFY_API_TOKEN,G=E("api"),_e=()=>ue.env.NETLIFY_LOCAL_MODE==="true",pe=async(e,t={})=>{if(!ye||!Ee)throw new Error("No API URL or token");let r=new URL(e,ye),o={...t,headers:{...t.headers,Authorization:`Bearer ${Ee}`}};ue.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let n=await fetch(r,o),i=n.ok&&n.status<=299;if(ue.env.AGENT_RUNNERS_DEBUG==="true")G.log(`Response headers for ${r}:`),n.headers.forEach((l,s)=>{G.log(` ${s}: ${l}`)});else{let l=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");G.log(`Request ID for ${r}: ${l||"N/A"}`)}if(i||G.error(`Got status ${n.status} for request ${r}`),t.raw){if(!i)throw n;return n}let a=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!i)throw a;return a},it=e=>{G.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(ye=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Ee=e.constants.NETLIFY_API_TOKEN)},st=()=>({apiUrl:ye,token:Ee}),de=async(e,t)=>_e()?(G.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):pe(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),H=async(e,t,r)=>_e()?(G.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):pe(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var at=async(e,t)=>_e()?(G.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):pe(`/api/v1/agent_runners/${e}/sessions/${t}`),lt=(e,t,r)=>pe(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}}),ct=async(e,t)=>_e()?(G.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"}}):pe(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Fe=async(e,t)=>{G.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 re=E("ai_gateway"),$e=null;var ut=async()=>{if($e)return $e;re.log("Fetching available AI gateway providers");let e=await fetch(`${st().apiUrl}/api/v1/ai-gateway/providers`);if(!e.ok)throw new Error(`Failed to fetch AI gateway providers: ${e.statusText}`);let t=await e.json();return $e=t,re.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},ir=async(e,t)=>{let o=(await ut()).providers[e];if(!o)return re.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return re.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},pt=async({netlify:e,config:t})=>{let r,o,n,i,a=e.constants?.SITE_ID;if(!a)throw new Error("No site id");let l=async()=>{clearTimeout(n),re.log("Requesting AI gateway information");let s=await lt(a,t.id,t.sessionId);if({token:r,url:i}=s,o=s.expires_at?s.expires_at*1e3:void 0,re.log("Got AI gateway information",{token:!!r,expiresAt:o,url:i}),o){let m=o-Date.now()-6e4;m>0&&(n=setTimeout(()=>{l()},m))}};return await Promise.all([l(),ut()]),{get url(){return i},get token(){return r},isModelAvailableForProvider:ir}};import Y from"process";import K from"path";import we from"fs";import{fileURLToPath as dr}from"url";import{createRequire as fr}from"module";import{execa as gr,execaCommand as qn}from"execa";import{Transform as sr}from"stream";var ar=new Set(["NODE_ENV","PATH","HOME","USER","USERNAME","SHELL","PWD","OLDPWD","TMPDIR","TMP","TEMP","LANG","TERM","EDITOR","PAGER","OS","PROCESSOR_ARCHITECTURE","PROCESSOR_IDENTIFIER","SYSTEMROOT","WINDIR","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","APPDATA","LOCALAPPDATA","NODE_OPTIONS","NODE_PATH","NODE_DEBUG","NODE_NO_WARNINGS","npm_config_registry","npm_config_cache","npm_execpath","npm_node_execpath","CI","GITHUB_ACTIONS","GITHUB_WORKSPACE","GITHUB_REPOSITORY","GITHUB_REF","BUILDKITE","BUILDKITE_BRANCH","BUILDKITE_COMMIT","BUILDKITE_BUILD_NUMBER","JENKINS_URL","TRAVIS","CIRCLECI","DISPLAY","COLORTERM","TERM_PROGRAM","TERM_PROGRAM_VERSION","COLUMNS","LINES","HISTSIZE","HISTFILE","NETLIFY_AGENT_RUNNER_ID","NETLIFY_AGENT_RUNNER_SESSION_ID","NETLIFY_AGENT_RUNNER_PROMPT","NETLIFY_AGENT_RUNNER_AGENT","NETLIFY_AGENT_RUNNER_MODEL","NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED","NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED","ERROR_LOGS_PATH","NETLIFY_AGENT_RUNNER_CONTEXT","NETLIFY_AGENT_RUNNER_HAS_REPO","NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED","NETLIFY_AGENT_RUNNER_SHA","NETLIFY_TEAM_TYPE","AGENT_RUNNERS_DEBUG","NETLIFY_TEAM_ID","NETLIFY_AGENT_RUNNER_USER_ID","SITE_NAME"]),lr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function cr(){return Object.entries(process.env).filter(([e,t])=>!(!t||ar.has(e)||lr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function q(e){if(typeof e!="string")return e;let t=cr();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(ur(o),"g");r=r.replace(n,"******")}),r}function ur(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ne=class extends sr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),i=q(n);o(null,i)}};function dt(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(o,n,i){let a=typeof o=="string"?q(o):o;return typeof n=="function"?t(a,n):t(a,n,i)},process.stderr.write=function(o,n,i){let a=typeof o=="string"?q(o):o;return typeof n=="function"?r(a,n):r(a,n,i)}}var fe=null,ft=e=>(fe&&fe.destroy(),fe=new X({totalAllowedTime:e}),fe),gt=()=>fe;var X=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,o)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let n=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),i=null,a=null;o!==void 0&&(a=new Promise((l,s)=>{i=setTimeout(()=>{s(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return a?await Promise.race([r(),a]):await r()}finally{n(),i&&clearTimeout(i)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var mt={name:"@netlify/agent-runner-cli",type:"module",version:"1.49.0",description:"CLI tool for running Netlify agents",main:"./dist/index.js",types:"./dist/index.d.ts",exports:"./dist/index.js",bin:{"agent-runner-cli":"./dist/bin.js","agent-runner-cli-local":"./dist/bin-local.js"},files:["dist/**/*.js","dist/**/*.d.ts","patches","scripts"],scripts:{build:"tsup",dev:"tsup --watch",prepare:"husky install node_modules/@netlify/eslint-config-node/.husky/",prepublishOnly:"npm ci && npm test",prepack:"npm run build",test:"run-s build format test:dev",format:"run-s build format:check-fix:*","format:ci":"run-s build format:check:*","format:check-fix:lint":"run-e format:check:lint format:fix:lint","format:check:lint":"cross-env-shell eslint $npm_package_config_eslint","format:fix:lint":"cross-env-shell eslint --fix $npm_package_config_eslint","format:check-fix:prettier":"run-e format:check:prettier format:fix:prettier","format:check:prettier":"cross-env-shell prettier --check $npm_package_config_prettier","format:fix:prettier":"cross-env-shell prettier --write $npm_package_config_prettier","test:dev":"run-s build test:dev:*","test:ci":"run-s build test:ci:*","test:dev:vitest":"vitest","test:ci:vitest":"c8 -r lcovonly -r text -r json vitest",postinstall:"node scripts/postinstall.js"},config:{eslint:'--cache --format=codeframe --max-warnings=0 "{src,scripts,test,.github}/**/*.{js,ts,md,html}"',prettier:'--ignore-path .gitignore --loglevel=warn "{src,scripts,test,.github}/**/*.{js,ts,md,yml,json,html}" "*.{js,ts,yml,json,html}" ".*.{js,ts,yml,json,html}" "!**/package-lock.json" "!package-lock.json"'},keywords:[],license:"MIT",repository:"netlify/agent-runner-cli",bugs:{url:"https://github.com/netlify/agent-runner-cli/issues"},author:"Netlify Inc.",directories:{test:"test"},devDependencies:{"@commitlint/cli":"^19.0.0","@commitlint/config-conventional":"^19.0.0","@eslint/compat":"^1.3.2","@eslint/js":"^9.35.0","@netlify/eslint-config-node":"^7.0.1","@types/node":"^24.5.0","@typescript-eslint/eslint-plugin":"^7.1.0","@typescript-eslint/parser":"^7.1.0","@vitest/eslint-plugin":"^1.3.10",c8:"^9.0.0","eslint-config-prettier":"^10.1.8","eslint-plugin-n":"^17.0.0",husky:"^8.0.0","patch-package":"^8.0.0",tsup:"^8.5.0",typescript:"^5.0.0","typescript-eslint":"^8.44.0",vitest:"^1.5.0"},dependencies:{"@anthropic-ai/claude-code":"2.0.42","@google/gemini-cli":"0.16.0","@netlify/otel":"^5.0.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.57.0",execa:"^8.0.0","get-port":"^5.1.1",minimist:"^1.2.8","my-codex-no-sandbox":"^0.1.2505290819"}};var mr=dr(import.meta.url),hr=K.dirname(mr),yr=fr(import.meta.url),Ie=E("shell"),De=new Set,Er={preferLocal:!0},P=(e,t,r)=>{let[o,n]=_r(t,r),i={...Er,...n},a=gr(e,o,i);return wr(a,i),Tr(a),a};var _r=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},wr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(Y.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new ne).pipe(Y.stdout),e.stdout?.pipe(new ne).pipe(Y.stdout),e.stderr?.pipe(new ne).pipe(Y.stderr);return}e.stdout?.pipe(Y.stdout),e.stderr?.pipe(Y.stderr)},ht=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(Y.kill(-e.pid,t),Ie.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return Ie.error("Error killing process:",r),!1}},Ir=e=>ht(e,"SIGKILL"),Tr=e=>{De.add(e);let t=gt();if(t){let r=t.onTimesUp(()=>{Ie.log(`Global timer expired, killing process ${e.pid}`),ht(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(Ie.log(`Force killing process ${e.pid} after timeout`),Ir(e))},5e3)});e.on("exit",()=>{De.delete(e),r()}),e.on("error",()=>{De.delete(e),r()})}};function Te(e,t){return!!z(e,t)}function z(e,t){if(!Y.env.NETLIFY_LOCAL_MODE)try{let n=yr.resolve(mt.name),i=K.dirname(n);for(;i!==K.dirname(i);){let a=K.dirname(i);if(K.basename(a)==="node_modules"){let l=K.join(a,".bin",t);if(we.existsSync(l))return l;break}i=a}}catch(n){console.error("Could not resolve package.json",n)}if(Y.env.NODE_PATH){let n=K.join(Y.env.NODE_PATH,".bin",t);if(we.existsSync(n))return n}let r=K.join(e,"node_modules",".bin",t);if(we.existsSync(r))return r;let o=K.join(hr,"..","node_modules",".bin",t);if(we.existsSync(o))return o}var yt="netlify-agent-runner-context.md",Le="task-history",Ue="netlify-context",U=".netlify",oe="results.md",Me="assets";var xr=E("utils"),vr=e=>new Promise(t=>{setTimeout(t,e)}),Et=(e,t=3e3)=>{let r=!1,o=null,n=[],i=null,a=(...l)=>{if(r)return o=l,new Promise(u=>{n.push(u)});r=!0;let s,m=new Promise(u=>{s=u});return i=(async()=>{await Promise.resolve();let u=await e(...l);for(s(u);;){if(await vr(t),!o)return r=!1,i=null,u;let c=o,f=n;o=null,n=[],u=await e(...c),f.forEach(h=>{h(u)})}})(),m};return a.flush=async()=>{if((r||o)&&i)return await i,a.flush()},a},xe=(e,t,r=!1)=>{let o=null,n=null,i=null,a=function(...l){n=l,i=this;let s=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(i,n),n=null,i=null)},t),s&&(e.apply(i,n),n=null,i=null)};return a.cancel=()=>{clearTimeout(o),o=null,n=null,i=null},a.flush=()=>{if(o){clearTimeout(o);let l=n,s=i;o=null,n=null,i=null,e.apply(s,l)}},a},_t=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):xr.error("Could not parse JSON",o))}},wt=(e,t)=>{let n=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let l=`--${t}${n}`;if(l.length>55)return"";let s=60-l.length;if(s<=0)return"";if(s>=i.length+6){let m=Math.min(s-i.length,e.length);return`${i}${e.slice(0,m)}`}return e.slice(0,s)};import{Buffer as It}from"buffer";import Rr from"path";var Tt=E("repo"),xt=async({config:e})=>{Tt.info("Getting runner diffs");let t=await Ar(),{hasChanges:r}=t,{status:o}=t;if(!r)return{hasChanges:!1};let n=Nr(o);await br(n),Tt.info("Changes after processing"),await Ge();let i=await Ye(o);await je(i);let a={stdio:["ignore","pipe","pipe"]},s=(await P("git",["diff","--staged"],a)).stdout;if(r=!!s,!r)return{hasChanges:!1,ignored:i};let u=(await P("git",["diff","--staged","--binary"],a)).stdout,c,f;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await P("git",["commit","-m","Agent runner"]),c=(await P("git",["diff",e.sha,"HEAD"],a)).stdout;let g=(await P("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;c!==g&&(f=It.from(g).toString("base64"))}let h={hasChanges:!0,diff:s,resultDiff:c,ignored:i};return s!==u&&(h.diffBinary=It.from(u).toString("base64")),f&&(h.resultDiffBinary=f),h},je=async(e=[])=>{await P("git",["add",".",...e])},Ge=async()=>(await P("git",["status","-s"])).stdout,vt=/.. (.+)?\.log$/,Sr=[vt],Ar=async()=>{let e=await Ge();return{hasChanges:(e.trim().length===0?[]:e.split(`
9
+ `).filter(o=>Sr.some(i=>i instanceof RegExp?i.test(o):o===i)?!1:o[1]?.trim()!=="")).length!==0,status:e}},Rt=async()=>{let{stdout:e}=await P("git",["rev-parse","HEAD"]);return e.trim()},St=async()=>{let{stdout:e}=await P("git",["rev-list","--max-parents=0","HEAD"]);return e.trim()},Ye=async e=>{e||=await Ge();let t=[".netlify","node_modules"],r=[];return e.split(`
10
+ `).forEach(o=>{t.forEach(i=>{[`?? ${i}`,`?? ${i}${Rr.sep}`].some(l=>o.startsWith(l))&&r.push(`:!${i}`)});let n=o.match(vt)?.[1];n&&r.push(`:!${n}.log`)}),r},At=async()=>{await P("git",["reset","--hard","HEAD"])},Nr=e=>{let t=e.split(`
11
+ `).reduce((r,o)=>{if(!o)return r;let[n,i,,...a]=o,l=a.join(""),s=n.trim(),m=i.trim();return r[l]?r[l].change=m:r[l]={filePath:l,stage:s,change:m},r},{});return Object.values(t)},br=async e=>{let t=[];for(let r of e)r.stage&&!r.change&&t.push(P("git",["restore","--staged","--worktree",r.filePath]));await Promise.allSettled(t)};import Pr from"fs/promises";import Or from"os";import Ct from"path";import Z from"process";import kr from"readline";import Be from"path";import Cr from"fs/promises";var He=E("agent-output-utils");async function ie({initialResult:e,agentName:t,hasError:r}){let o="",n=Be.join(process.cwd(),U,oe);try{let i=await Cr.readFile(n,"utf-8");i&&(o=i,He.log(`Pulled result from ${Be.relative(process.cwd(),n)}`))}catch{He.log(`No results file found at ${Be.relative(process.cwd(),n)}`)}return o||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function se({error:e,agentName:t}){let r=e&&typeof e=="object"?JSON.stringify(e):e,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&&He.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function ae(e){if(!e)return!1;let r=(e&&typeof e=="object"?JSON.stringify(e):e)?.replace(/\s+/g," ").trim().toLowerCase()||"";return!!(r?.includes("error when talking to gemini api")||r?.includes("499")||r?.includes("connection closed prematurely")||r?.includes("request timed out")||r?.includes("network error"))}var M=E("runner_claude"),Nt="Claude Code",ve="claude-sonnet-4-5-20250929",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,Fr=({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 qe({config:e,netlify:t,persistSteps:r,aiGateway:o,continueSession:n,priorAgentSessionId:i}){let a=e,{accountType:l,prompt:s,modelVersionOverrides:m}=a,{model:u}=a,c="";if(o){let{token:y,url:d}=o;if(!y||!d)throw new Error("No token or url provided from AI Gateway");if(m?.claude){let p=m?.claude?.[l];if(p){if(!await o.isModelAvailableForProvider("anthropic",p))throw new Error(`Model override '${p}' is not available for anthropic provider`);u=p}}else if(u){if(!await o.isModelAvailableForProvider("anthropic",u))throw new Error(`Model '${u}' is not available for anthropic provider`)}else await o.isModelAvailableForProvider("anthropic",ve)?(u=ve,M.log(`Using default model: ${ve}`)):M.log(`Default model ${ve} is not available, proceeding without model specification`);Z.env.ANTHROPIC_API_KEY=y,Z.env.ANTHROPIC_BASE_URL=d}else if(!Z.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let f=[],h=[],w={},I=0,g=0,v,x,N=[z(Z.cwd(),"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...u?["--model",u]:[],...n?["--continue"]:[],...n&&i?["--resume",i]:[],"-p",s],T=`${Z.env.NVM_BIN}/node`;M.log(`Running ${T} ${N.join(" ")}`);let _=t.utils.run(T,N,{all:!0,env:Z.env});_.stdin?.end();let R=xe(()=>{r?.({steps:f,duration:g})},250),S=(y,d)=>{let p={...y,id:I};I+=1,h.push(p),f.push(p),d||R.flush(),R(),d&&R.flush()},A=kr.createInterface({input:_.all});return A.on("error",y=>{M.error("Readline interface error",{error:y.message,stack:y.stack})}),A.on("line",y=>{let d=null;try{d=JSON.parse(y)}catch{M.log("Could not parse line",y)}d?.session_id&&d.session_id!==c&&(c=d.session_id),Array.isArray(d?.message?.content)?d.message.content.forEach(p=>{switch(p.type){case"text":{p.text&&S({message:p.text});break}case"image":{typeof p.source=="object"&&p.source&&p.source.type==="base64"&&p.source.media_type?S({message:`![](data:${p.source.media_type};base64,${p.source.data})`}):M.log(`Unsupported image type ${p.source?.type}`,p.source);break}case"tool_use":{if(p.name==="Task"){let $=p.input?.description&&`\`${p.input.description}\``;S({title:[bt(p.name),$].filter(Boolean).join(" ")})}else p.id&&(w[p.id]=p);R.flush();break}case"tool_result":{let $=p.tool_use_id?w[p.tool_use_id]:void 0,te;if($){let W=$.input?.file_path&&Ct.relative(Z.cwd(),$.input.file_path),k=W&&`\`${W}\``;te=[bt($.name||""),k].filter(Boolean).join(" ")}let he=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes($?.name||""),J;if(typeof p.content=="string")J=p.content;else if(Array.isArray(p.content)){let W=[];p.content.forEach(k=>{k?.type==="text"&&typeof k.text=="string"?W.push(k.text):k?.type==="image"&&typeof k.source=="object"&&k.source?k.source.type==="base64"&&k.source.media_type?W.push(`![](data:${k.source.media_type};base64,${k.source.data})`):M.log(`Unsupported image type ${k.source.type}`,k.source):M.log(`Unsupported block type ${k?.type}`)}),J=W.join(`
12
+
13
+ `)}he&&J&&(J=`\`\`\`
14
+ ${J.trim()}
15
+ \`\`\``),S({title:te,message:J},!0);break}case"thinking":{p.thinking&&S({title:"Thinking",message:p.thinking},!0);break}default:M.log(`Message content type is not supported ${p.type}`,p)}}):d?.type==="result"&&(g=d.duration_ms||0,d.is_error?x=d.result:v=d.result,[h,f].forEach(p=>{p[p.length-1]?.message===v&&p.pop()}))}),await _.catch(y=>{({error:x,result:v}=Fr({catchError:y,runCmd:_,error:x,result:v,runnerName:"Claude"}))}),A.close(),R.flush(),{steps:h,duration:g,result:await ie({initialResult:v,agentName:Nt,hasError:!!x}),error:se({error:x,agentName:Nt}),isRetryableError:ae(x),agentSessionId:c}}var Pt=async()=>{let e=Ct.join(Or.homedir(),".claude");await Pr.rm(e,{recursive:!0,force:!0})};import $r from"fs/promises";import Dr from"os";import Lr from"path";import le from"process";import Ur from"readline";var Q=E("runner_codex"),Ot="Codex CLI",Mr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(Q.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?(Q.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}):(Q.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function Ke({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:i,prompt:a,modelVersionOverrides:l}=e,{model:s}=e;if(n){let{token:T,url:_}=n;if(!T||!_)throw new Error("No token or url provided from AI Gateway");if(l?.codex){let R=l?.codex?.[i];if(R){if(!await n.isModelAvailableForProvider("openai",R))throw new Error(`Model override '${R}' is not available for openai provider`);s=R}}else if(s&&!await n.isModelAvailableForProvider("openai",s))throw new Error(`Model '${s}' is not available for openai provider`);le.env.OPENAI_API_KEY=T,le.env.OPENAI_BASE_URL=_}else if(!le.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let m=[],u=[],c={},f=0,h=0,w,I,g=[z(le.cwd(),"codex"),"--approval-mode","full-auto",n?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...s?["--model",s]:[],"-q",a].filter(Boolean),v=`${le.env.NVM_BIN}/node`;Q.log(`Running ${v} ${g.join(" ")}`);let x=t.utils.run(v,g,{all:!0,env:{...le.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),N=Ur.createInterface({input:x.all});return N.on("error",T=>{Q.error("Readline interface error",{error:T.message,stack:T.stack})}),N.on("line",T=>{let _=null;try{_=JSON.parse(T)}catch{Q.log("Could not parse line",T);return}let R=[],S=!1;if(_?.duration_ms&&(h=_.duration_ms,S=!0),_?.type==="local_shell_call")c[_.call_id]=_;else if(_?.type==="local_shell_call_output"){let A=Gr(c[_.call_id],_);A&&(A.id=f,f+=1,u.push(A),m.push(A),R.push(A),S=!0)}else _?.type==="message"&&_.role==="assistant"?w=_.content.map(A=>A.text).join(`
16
+ `):_?.type==="message"&&_.role==="system"&&(I=_.content.map(A=>A.text).join(`
17
+ `));S&&(r?.({steps:m,duration:h}),o?.({steps:R,duration:h}))}),await x.catch(T=>{let _=Mr({catchError:T,runCmd:x,error:I,result:w,runnerName:"Codex"});I=_.error,w=_.result}),N.close(),{steps:u,duration:h,result:await ie({initialResult:w,agentName:Ot,hasError:!!I}),error:se({error:I,agentName:Ot}),isRetryableError:ae(I)}}var kt=async()=>{let e=Lr.join(Dr.homedir(),".codex");await $r.rm(e,{recursive:!0,force:!0})},jr=new Set(["bash","-lc"]),Gr=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(i=>!jr.has(i)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
21
18
  ${n.trim()}
22
- \`\`\``)}catch(i){j.error("Could not decode outputMsg",i,t.output)}return{title:o,message:n}};import Cr from"fs/promises";import Pr from"os";import Ct from"path";import Z from"process";import Or from"readline";var se=w("runner_gemini"),bt="Gemini CLI",$r=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(se.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?(se.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}):(se.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),kr={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"};async function He({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:i,prompt:a,modelVersionOverrides:u}=e,{model:s}=e;if(n){let{token:m,url:p}=n;if(!m||!p)throw new Error("No token or url provided from AI Gateway");if(u?.gemini){let f=u?.gemini?.[i];if(f){if(!await n.isModelAvailableForProvider("gemini",f))throw new Error(`Model override '${f}' is not available for gemini provider`);s=f}}else if(s&&!await n.isModelAvailableForProvider("gemini",s))throw new Error(`Model '${s}' is not available for gemini provider`);Z.env.GEMINI_API_KEY=m,Z.env.GOOGLE_GEMINI_BASE_URL=p}else if(!Z.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let y=[],l=[],c=[],g={},E=0,T=0,I,h,x=[J(Z.cwd(),"gemini"),...s?["--model",s]:[],"--yolo","-p",a],v=`${Z.env.NVM_BIN}/node`;se.log(`Running ${v} ${x.join(" ")}`);let C=t.utils.run(v,x,{all:!0,env:Z.env});C.stdin?.end();let N=Te(()=>{r?.({steps:y,duration:T}),o?.({steps:l,duration:T}),l=[]},250),R=(m,p)=>{m.id=E,E+=1,c.push(m),y.push(m),l.push(m),p||N.flush(),N(),p&&N.flush()},S=Or.createInterface({input:C.all});return S.on("error",m=>{se.error("Readline interface error",{error:m.message,stack:m.stack})}),S.on("line",m=>{let p=null;try{if(m.startsWith("[API Error")){let f=m.match(/\[api error: (.+?)]$/i)?.[1];p={type:"error",value:ht(f,!1)?.error?.message||f||"Gemini encountered error"}}else p=JSON.parse(m)}catch{return}if(p)switch(p.type){case"thought":{let f=p.value;R({title:f?.subject??"Thinking...",message:f?.description},!0);break}case"content":{p.value&&R({message:p.value});break}case"tool_call_request":{let f=p.value,_=kr[f.name]??f.name,d=f.args?.path||f.args?.absolute_path,P=d&&Ct.relative(Z.cwd(),d),ae=f.args?.command,q={title:[_,P&&`\`${P}\``,ae&&`\`${ae}\``].filter(Boolean).join(" ")};g[f.callId]=q,N.flush();break}case"tool_result":{let f=p.value,_=g[f.callId];if(_){let d=[f.resultDisplay,f.responseParts?.functionResponse?.response?.output].find(P=>typeof P=="string"&&P);d&&(_.message=`\`\`\`
23
- ${d.trim()}
24
- \`\`\``),R(_,!0)}break}case"result":{T=p.duration_ms,I=p.value,[c,y,l].forEach(f=>{f[f.length-1]?.message===I&&f.pop()});break}case"error":{h=p.value;break}case"finished":break;default:{se.warn("Unhandled message type:",p.type);break}}}),await C.catch(m=>{({error:h,result:I}=$r({catchError:m,runCmd:C,error:h,result:I,runnerName:"Gemini"}))}),S.close(),N.flush(),{steps:c,duration:T,result:await ne({initialResult:I,agentName:bt,hasError:!!h}),error:oe({error:h,agentName:bt}),isRetryableError:ie(h)}}var Pt=async()=>{let e=Ct.join(Pr.homedir(),".gemini");await Cr.rm(e,{recursive:!0,force:!0})};var Dr={codex:{runner:Be,clean:Nt},claude:{runner:Ye,clean:Rt},gemini:{runner:He,clean:Pt}},Ot=Dr;var $t=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>await A(Lr(),"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.validateAgent":e.validateAgent,"init.runnerVersion":o||"unknown"});let a=Ot[e.runner];if(!a)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let u=Fr({apiToken:r});nt(u);let s=e.useGateway?await ut({netlify:u,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!s}),e.validateAgent&&e.errorLogsPath&&n?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let y=mt(({steps:g=[],duration:E})=>{let T=g.map(I=>({...I,title:I.title?H(I.title):void 0,message:I.message?H(I.message):void 0}));return g.length=0,B(e.id,e.sessionId,{steps:T,duration:E})},t),l;e.hasRepo?e.sha?(l=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(l=await wt(u),await ce(e.id,{sha:l}),n?.setAttributes({"init.sha.source":"current_commit"})):(l=await It(u),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let c=performance.now()-i;return n?.setAttributes({"init.sha":l||"unknown","init.duration.ms":c,"init.status":"success"}),{aiGateway:s,context:u,persistSteps:y,runner:a,sha:l}}),Fr=({apiToken:e})=>({constants:{NETLIFY_API_HOST:Re.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||Re.env.NETLIFY_API_TOKEN,SITE_ID:Re.env.SITE_ID,FUNCTIONS_DIST:Re.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:we}});import{getTracer as Ke}from"@netlify/otel";import Ur from"crypto";import W from"fs/promises";import D from"path";import M from"process";var k=w("context"),Mr=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:M.env.NETLIFY_TEAM_ID,userId:M.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:M.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},Gr=10,jr=async e=>{let{name:t,ext:r}=D.parse(e),o=e,n=D.join(M.cwd(),F,o),i=0;for(;await Yr(n);){if(i>=Gr)throw new Error("Failed to generate context file");o=`${t}-${Ur.randomUUID().slice(0,5)}${r}`,n=D.join(M.cwd(),F,o),i+=1}return o},Yr=async e=>{try{return await W.access(e),!0}catch{return!1}},Br=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}},Hr=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 W.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}},Se=null,Kr=async()=>{if(Se)return Se;let e=await Br();if(!e)return[];let t=D.join(M.cwd(),F,Ue);await W.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 a=`${n}.md`,u=D.join(t,a),s=D.join(F,Ue,a);return k.log(`Downloading ${i.scope} context...`),await Hr(i.endpoint,u)?(k.log(`Downloaded: ${s}`),{scope:i.scope,path:s,key:n}):null});return Se=(await Promise.all(r)).filter(n=>n!==null),Se},kt=async({cliPath:e,netlify:t,config:r,buildErrorContext:o})=>{let n=Mr(t),i=await jr(gt),a=D.join(M.cwd(),F);await W.mkdir(a,{recursive:!0});let u=D.join(F,i),s=D.join(M.cwd(),u),y=D.join(M.cwd(),F,re);try{await W.unlink(y),k.log(`Deleted old results file: ${y}`)}catch{}let l=o?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
19
+ \`\`\``)}catch(i){Q.error("Could not decode outputMsg",i,t.output)}return{title:o,message:n}};import Yr from"fs/promises";import Br from"os";import $t from"path";import ee from"process";import Hr from"readline";var ce=E("runner_gemini"),Ft="Gemini CLI",qr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(ce.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?(ce.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}):(ce.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),Kr={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"};async function We({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:i,prompt:a,modelVersionOverrides:l}=e,{model:s}=e;if(n){let{token:y,url:d}=n;if(!y||!d)throw new Error("No token or url provided from AI Gateway");if(l?.gemini){let p=l?.gemini?.[i];if(p){if(!await n.isModelAvailableForProvider("gemini",p))throw new Error(`Model override '${p}' is not available for gemini provider`);s=p}}else if(s&&!await n.isModelAvailableForProvider("gemini",s))throw new Error(`Model '${s}' is not available for gemini provider`);ee.env.GEMINI_API_KEY=y,ee.env.GOOGLE_GEMINI_BASE_URL=d}else if(!ee.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let m=[],u=[],c=[],f={},h=0,w=0,I,g,v=[z(ee.cwd(),"gemini"),...s?["--model",s]:[],"--yolo","--output-format","stream-json","-p",a],x=`${ee.env.NVM_BIN}/node`;ce.log(`Running ${x} ${v.join(" ")}`);let N=t.utils.run(x,v,{all:!0,env:ee.env});N.stdin?.end();let T=xe(()=>{r?.({steps:m,duration:w}),o?.({steps:u,duration:w}),u=[]},250),_=(y,d)=>{y.id=h,h+=1,c.push(y),m.push(y),u.push(y),d||T.flush(),T(),d&&T.flush()},R=Hr.createInterface({input:N.all});R.on("error",y=>{ce.error("Readline interface error",{error:y.message,stack:y.stack})});let S="",A=()=>{S&&_({message:S.trim()}),S=""};return R.on("line",y=>{let d=null;try{if(y.startsWith("[API Error")){let p=y.match(/\[api error: (.+?)]$/i)?.[1];d={type:"error",value:_t(p,!1)?.error?.message||p||"Gemini encountered error"}}else d=JSON.parse(y)}catch{return}if(d)switch(["message","result"].includes(d.type)||A(),d.type){case"message":{d.role!=="user"&&d.content&&(S+=d.content);break}case"tool_use":{let p=Kr[d.tool_name]??d.tool_name,$=d.parameters?.file_path,te=$&&$t.relative(ee.cwd(),$),he=d.parameters?.command,W={title:[p,te&&`\`${te}\``,he&&`\`${he}\``].filter(Boolean).join(" ")};f[d.tool_id]=W,T.flush();break}case"tool_result":{let p=f[d.tool_id];p&&(d.output&&(p.message=`\`\`\`
20
+ ${d.output.trim()}
21
+ \`\`\``),_(p,!0));break}case"result":{w=d.stats?.duration_ms,d.status==="error"?g=d.error?.message:I=S.trim();break}case"error":{g=d.error;break}case"finished":break;default:{ce.warn("Unhandled message type:",d.type);break}}}),await N.catch(y=>{({error:g,result:I}=qr({catchError:y,runCmd:N,error:g,result:I,runnerName:"Gemini"}))}),R.close(),T.flush(),{steps:c,duration:w,result:await ie({initialResult:I,agentName:Ft,hasError:!!g}),error:se({error:g,agentName:Ft}),isRetryableError:ae(g)}}var Dt=async()=>{let e=$t.join(Br.homedir(),".gemini");await Yr.rm(e,{recursive:!0,force:!0})};var Wr={codex:{runner:Ke,clean:kt},claude:{runner:qe,clean:Pt},gemini:{runner:We,clean:Dt}},Lt=Wr;var Jr=E("init_stage"),Ut=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>await b(Vr(),"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.validateAgent":e.validateAgent,"init.runnerVersion":o||"unknown"});let a=Lt[e.runner];if(!a)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let l=Xr({apiToken:r});it(l);let s=e.useGateway?await pt({netlify:l,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!s}),e.validateAgent&&e.errorLogsPath&&n?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let m=Et(({steps:h=[],duration:w})=>{let I=h.map(g=>({...g,title:g.title?q(g.title):void 0,message:g.message?q(g.message):void 0}));return h.length=0,H(e.id,e.sessionId,{steps:I,duration:w})},t);Jr.info("Adding build files to stage");let u=await Ye();await je(u);let c;e.hasRepo?e.sha?(c=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(c=await Rt(),await de(e.id,{sha:c}),n?.setAttributes({"init.sha.source":"current_commit"})):(c=await St(),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let f=performance.now()-i;return n?.setAttributes({"init.sha":c||"unknown","init.duration.ms":f,"init.status":"success"}),{aiGateway:s,context:l,persistSteps:m,runner:a,sha:c}}),Xr=({apiToken:e})=>({constants:{NETLIFY_API_HOST:Re.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||Re.env.NETLIFY_API_TOKEN,SITE_ID:Re.env.SITE_ID,FUNCTIONS_DIST:Re.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:P}});import{getTracer as Ve}from"@netlify/otel";import zr from"crypto";import V from"fs/promises";import L from"path";import j from"process";var D=E("context"),Zr=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:j.env.NETLIFY_TEAM_ID,userId:j.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:j.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},Qr=10,en=async e=>{let{name:t,ext:r}=L.parse(e),o=e,n=L.join(j.cwd(),U,o),i=0;for(;await tn(n);){if(i>=Qr)throw new Error("Failed to generate context file");o=`${t}-${zr.randomUUID().slice(0,5)}${r}`,n=L.join(j.cwd(),U,o),i+=1}return o},tn=async e=>{try{return await V.access(e),!0}catch{return!1}},rn=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}},nn=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 V.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}},Se=null,on=async()=>{if(Se)return Se;let e=await rn();if(!e)return[];let t=L.join(j.cwd(),U,Ue);await V.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 a=`${n}.md`,l=L.join(t,a),s=L.join(U,Ue,a);return D.log(`Downloading ${i.scope} context...`),await nn(i.endpoint,l)?(D.log(`Downloaded: ${s}`),{scope:i.scope,path:s,key:n}):null});return Se=(await Promise.all(r)).filter(n=>n!==null),Se},Mt=async({cliPath:e,netlify:t,config:r,buildErrorContext:o})=>{let n=Zr(t),i=await en(yt),a=L.join(j.cwd(),U);await V.mkdir(a,{recursive:!0});let l=L.join(U,i),s=L.join(j.cwd(),l),m=L.join(j.cwd(),U,oe);try{await V.unlink(m),D.log(`Deleted old results file: ${m}`)}catch{}let u=o?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
25
22
  Your task is to analyze and fix the build errors.
26
23
  Don't apply techniques of reverting changes. Apply fixes related to errors.
27
24
  Don't try to run build by yourself. Just fix the errors.
@@ -30,35 +27,35 @@ Don't try to run build by yourself. Just fix the errors.
30
27
  ${o}
31
28
  </build_error_context>`:"",c="";r.siteContext&&r.siteContext.length!==0&&(c=`
32
29
  <project_rules>
33
- ${r.siteContext.filter(h=>h.site_context).map(h=>typeof h.site_context=="string"?h.site_context:typeof h.site_context=="object"?JSON.stringify(h.site_context):"").join(`
30
+ ${r.siteContext.filter(g=>g.site_context).map(g=>typeof g.site_context=="string"?g.site_context:typeof g.site_context=="object"?JSON.stringify(g.site_context):"").join(`
34
31
 
35
32
  `)}
36
33
  </project_rules>
37
- `);let g="";if(r.sessionHistoryContext?.length){let h=D.join(M.cwd(),F,Fe);await W.mkdir(h,{recursive:!0});let x=await Promise.all(r.sessionHistoryContext.map(async(v,C)=>{let N=C+1,R=`attempt-${N}.md`,S=D.join(h,R),m=D.join(F,Fe,R),p=`# Task History - Attempt ${N}
34
+ `);let f="";if(r.sessionHistoryContext?.length){let g=L.join(j.cwd(),U,Le);await V.mkdir(g,{recursive:!0});let v=await Promise.all(r.sessionHistoryContext.map(async(x,N)=>{let T=N+1,_=`attempt-${T}.md`,R=L.join(g,_),S=L.join(U,Le,_),A=`# Task History - Attempt ${T}
38
35
 
39
36
  ## Request - what the user asked for
40
- ${v.request}
37
+ ${x.request}
41
38
 
42
39
  ---
43
40
 
44
41
  ## Response - what the agent replied with after its work
45
42
 
46
- ${v.response}
47
- `;return await W.writeFile(S,p,"utf-8"),k.log(`Created history file: ${m}`),m}));g+=`
43
+ ${x.response}
44
+ `;return await V.writeFile(R,A,"utf-8"),D.log(`Created history file: ${S}`),S}));f+=`
48
45
  <session_history_context>
49
46
  History of prior work on this task.
50
47
  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.
51
48
 
52
- ${x.slice(-5).map(v=>`- ${v}`).join(`
49
+ ${v.slice(-5).map(x=>`- ${x}`).join(`
53
50
  `)}
54
51
 
55
52
  </session_history_context>
56
- `}let E=await Kr(),T="";E.length>0&&(T=`
53
+ `}let h=await on(),w="";h.length>0&&(w=`
57
54
  <netlify_features_context>
58
55
  If the user request is explicitly related to a specific Netlify feature (e.g., Netlify Forms, Netlify Functions, etc.), you MUST review the relevant documentation below in addition to reviewing the project files.
59
56
  DO NOT force the use of any Netlify feature if the user request does not explicitly require it or if the project has alternative implementations in place already.
60
57
 
61
- ${E.map(h=>`- **${h.scope}**: ${h.path}`).join(`
58
+ ${h.map(g=>`- **${g.scope}**: ${g.path}`).join(`
62
59
  `)}
63
60
 
64
61
  Refer to these files when working with specific Netlify features.
@@ -70,14 +67,14 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
70
67
  <user_request>
71
68
  ${r.prompt}
72
69
  </user_request>
73
- ${l}
70
+ ${u}
74
71
  </request>
75
72
 
76
73
  <requirements>
77
74
  <responses>
78
75
  - Do not speak in first person. You may speak as "the agent".
79
- - When work is complete, write a changes summary in ${a}/${re} 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.
80
- - 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 ${a}/${re} file.
76
+ - When work is complete, write a changes summary in ${a}/${oe} 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.
77
+ - 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 ${a}/${oe} file.
81
78
  - 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.
82
79
  - NEVER look into the \`.git\` folder
83
80
  - NEVER print potentially sensitive values (like secrets) in the planning output or results
@@ -98,41 +95,43 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
98
95
  - Netlify Functions directory: ${n.functionsDir}
99
96
  </metadata>
100
97
  <environment>
101
- - Node Version: ${M.version||"unknown"}
98
+ - Node Version: ${j.version||"unknown"}
102
99
  - Environment variables are set globally (e.g. \`echo $VARIABLE_NAME\` can be used to check if a var is set).
103
100
  - 'netlify-cli' npm package is already available as a global package. Don't try to install it again
104
101
  - If you need to start a local development server in order to fulfill the request, try using the Netlify CLI over by running the shell command '${e} dev'. This will start a local HTTP server on port 8888, including live-reloading of any changes and, most critically, it offers local emulation for all Netlify features.
105
102
  </environment>
106
- ${T}
103
+ ${w}
107
104
  <docs>
108
105
  - Netlify Docs: https://docs.netlify.com
109
106
  - LLM Resources Index: https://docs.netlify.com/llms.txt
110
107
  </docs>
111
108
  </extra_context>
112
109
 
113
- ${g}
114
- `;return await W.writeFile(s,I,"utf-8"),k.log(`Generated agent context document at: ${s}`),I.length>5e5&&(I=`
110
+ ${f}
111
+ `;return await V.writeFile(s,I,"utf-8"),D.log(`Generated agent context document at: ${s}`),I.length>5e5&&(I=`
115
112
  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.
116
113
 
117
114
  <request>
118
115
  <user_request>
119
116
  ${r.prompt}
120
117
  </user_request>
121
- ${l}
118
+ ${u}
122
119
  </request>
123
120
 
124
121
  Use the following file for the complete context of the ask, the environment, and what's available. ${s} You MUST READ ALL OF IT. Make sure to read it first. Never cite or paraphrase private context.
125
- `),I};var qr=w("prompt"),Dt=async({cliPath:e,config:t,netlify:r,buildErrorContext:o})=>{let n=await kt({cliPath:e,config:t,netlify:r,buildErrorContext:o});return process.env.AGENT_RUNNER_DEBUG&&qr.log("Contextful Prompt:",n),{prompt:n}};var Ae=w("inference_stage"),Lt=5,Ne=async e=>{let{cliPath:t,config:r,context:o,buildErrors:n,runner:i,persistSteps:a,aiGateway:u,attempt:s,contextPrefix:y,priorAgentSessionId:l}=e;Ae.log(`Running inference stage, attempt ${s} of ${Lt}`);let c=await A(Ke(),"inference-stage",async g=>{g?.setAttributes({"inference.attempt":s||1}),ct();let{prompt:E}=await A(Ke(),"compose-prompt",async()=>await Dt({cliPath:t,config:r,buildErrorContext:Wr(n),netlify:o})),T=`
126
- ${y||""}
127
- ${E}
128
- `.trim(),I={...r,prompt:T},h=await A(Ke(),`run-${r.runner}`,async()=>await i({aiGateway:u,config:I,netlify:o,persistSteps:a,continueSession:!!(s&&s>1),priorAgentSessionId:l}));return h.result&&(h.result=H(h.result)),h.error&&(h.error=H(h.error)),await a.flush(),h});if(c.error){if(Ae.error("Runner failed",{stepsCount:c.steps.length,duration:c.duration,error:c.error,isRetryableError:c.isRetryableError,attempt:s||1,agentSessionId:c.agentSessionId}),c.isRetryableError&&(!s||s<Lt))return Ae.log("Retrying inference stage"),await new Promise(E=>setTimeout(E,5e3)),{runnerResult:(await Ne({...e,attempt:(s||1)+1,priorAgentSessionId:c.agentSessionId,contextPrefix:c.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 Ae.log("Do not retry inference stage"),new Error(c.error)}return{runnerResult:c}},Wr=e=>!e||e.length===0?"":`
122
+ `),I};var sn=E("prompt"),jt=async({cliPath:e,config:t,netlify:r,buildErrorContext:o})=>{let n=await Mt({cliPath:e,config:t,netlify:r,buildErrorContext:o});return process.env.AGENT_RUNNER_DEBUG&&sn.log("Contextful Prompt:",n),{prompt:n}};var Ae=E("inference_stage"),Gt=5,Ne=async e=>{let{cliPath:t,config:r,context:o,buildErrors:n,runner:i,persistSteps:a,aiGateway:l,attempt:s,contextPrefix:m,priorAgentSessionId:u}=e;Ae.log(`Running inference stage, attempt ${s} of ${Gt}`);let c=await b(Ve(),"inference-stage",async f=>{f?.setAttributes({"inference.attempt":s||1}),dt();let{prompt:h}=await b(Ve(),"compose-prompt",async()=>await jt({cliPath:t,config:r,buildErrorContext:an(n),netlify:o})),w=`
123
+ ${m||""}
124
+ ${h}
125
+ `.trim(),I={...r,prompt:w},g=await b(Ve(),`run-${r.runner}`,async()=>await i({aiGateway:l,config:I,netlify:o,persistSteps:a,continueSession:!!(s&&s>1),priorAgentSessionId:u}));return g.result&&(g.result=q(g.result)),g.error&&(g.error=q(g.error)),await a.flush(),g});if(c.error){if(Ae.error("Runner failed",{stepsCount:c.steps.length,duration:c.duration,error:c.error,isRetryableError:c.isRetryableError,attempt:s||1,agentSessionId:c.agentSessionId}),c.isRetryableError&&(!s||s<Gt))return Ae.log("Retrying inference stage"),await new Promise(h=>setTimeout(h,5e3)),{runnerResult:(await Ne({...e,attempt:(s||1)+1,priorAgentSessionId:c.agentSessionId,contextPrefix:c.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 Ae.log("Do not retry inference stage"),new Error(c.error)}return{runnerResult:c}},an=e=>!e||e.length===0?"":`
129
126
  Deploy failed failed. Here are the errors to review on the latest build:
130
127
 
131
128
  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.
132
129
 
133
130
  ${e.pop()}
134
- `;import Xr from"process";import{getTracer as qe}from"@netlify/otel";import{getTracer as Vr}from"@netlify/otel";var fe=w("deploy"),Ft=async e=>await A(Vr(),"create-preview-deploy",async t=>Jr(e,t)),Jr=async({netlify:e,hasRepo:t,skipBuild:r,message:o="Agent Preview",deploySubdomain:n,cliPath:i,filter:a},u)=>{try{let s=["deploy","--message",`"${o}"`,"--json","--draft","--verbose"];t||(fe.log("Deploy: Uploading source zip"),s.push("--upload-source-zip")),n&&s.push("--alias",n),a&&s.push("--filter",a),r?(fe.log("Deploy: Skipping build"),s.push("--no-build")):s.push("--context","deploy-preview");let y=i||"netlify";fe.log(`Running: ${y} ${s.join(" ")}`),u?.setAttributes({cmd:y,args:s});let l=await e.utils.run(y,s,{stdio:["ignore","pipe","pipe"]}),c=JSON.parse(l.stdout.trim());u?.setAttributes({success:!0,deployId:c.deploy_id,deployUrl:c.deploy_url,siteId:c.site_id}),fe.log(`
135
- Preview deploy created successfully:`,{deployId:c.deploy_id,deployUrl:c.deploy_url,siteId:c.site_id});let g={deployId:c.deploy_id,previewUrl:c.deploy_url,logsUrl:c.logs,siteId:c.site_id};return t||(g.sourceZipFilename=c.source_zip_filename),g}catch(s){throw fe.error("Failed to create preview deploy via CLI:",s),u?.setAttributes({success:!1,error:s.message}),s}};var ge=w("deploy_stage"),We=async e=>await A(qe(),"run-deploy-stage",async()=>zr(e)),zr=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let i=await A(qe(),"get-runner-diffs",async()=>await _t({config:t,netlify:r}));if(ge.info("Resolved git",{hasChanges:i.hasChanges,ignored:i.ignored??[]}),!i.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:u,diffBinary:s,resultDiffBinary:y}=i,l=!0;ge.log("Preview deploy condition check:",{resultUndefined:o===void 0,resultType:typeof o,hasChanges:l,wouldCreatePreview:o!==void 0&&l});let c=null;if(o!==void 0&&l)try{let g;try{let E=await A(qe(),"get-runner-session",async()=>await it(t.id,t.sessionId));E?.title&&(g=E.title)}catch(E){ge.warn("Failed to fetch session title, using fallback message:",E.message)}await B(t.id,t.sessionId,{steps:[{title:"Deploying the run preview"}]}),c=await Ft({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:g,skipBuild:!1,deploySubdomain:yt(t.id,Xr.env.SITE_NAME),filter:n})}catch(g){return ge.warn("Failed to create preview deploy (continuing with agent run):",g),{diff:a,resultDiff:u,hasChanges:l,previewInfo:null,diffBinary:s,resultDiffBinary:y,deployError:g instanceof Error?g.message:String(g)}}return ge.log("Git status",{hasDiff:!!a,hasChanges:l}),{diff:a,resultDiff:u,hasChanges:l,previewInfo:c,diffBinary:s,resultDiffBinary:y}};import{getTracer as be}from"@netlify/otel";async function Ut(e,t){let{maxRetries:r,baseDelay:o,onRetry:n}=t,i;for(let a=1;a<=r;a++)try{return await e()}catch(u){if(i=u,a===r)throw i;n&&n(a,i),await new Promise(s=>setTimeout(s,o*a))}throw i}var L=w("cleanup_stage"),Mt=async e=>await A(be(),"cleanup-stage",async()=>Zr(e)),Ve=1024*1024*10,Zr=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:i,resultDiffBinary:a,previewInfo:u})=>{let s={result:r||"Done",duration:o};if(u&&u.deployId&&(s.deploy_id=u.deployId),u&&u.sourceZipFilename&&(s.result_zip_file_name=u.sourceZipFilename),t||i||n||a)try{L.log("Getting pre-signed URLs for diff upload");let l=await at(e.id,e.sessionId),c=[];(t||i)&&c.push($e(l.result.upload_url,i||t).then(()=>{s.result_diff_s3_key=l.result.s3_key,L.log("Successfully uploaded result_diff to S3")})),(n||a)&&c.push($e(l.cumulative.upload_url,a||n).then(()=>{s.cumulative_diff_s3_key=l.cumulative.s3_key,L.log("Successfully uploaded cumulative_diff to S3")})),L.log(`Uploading ${c.length} diff(s) to S3 in parallel`),await Promise.all(c),(n||a)&&(L.log("Updating agent runner with cumulative diff S3 key"),await A(be(),"update-runner",async()=>{await ce(e.id,{result_diff_s3_key:l.cumulative.s3_key})}))}catch(l){L.error("S3 upload failed, falling back to inline diffs:",l);let c=Buffer.byteLength(t||i||""),g=Buffer.byteLength(a||n||"");if(c>Ve||g>Ve){let E=`Diffs exceed maximum inline size of ${Ve} bytes.`;throw L.error(E),new Error(E)}s.result_diff=t,s.result_diff_binary=i,(n||a)&&(s.cumulative_diff=n,s.cumulative_diff_binary=a,L.log("Updating agent runner with inline diffs (fallback)"),await A(be(),"update-runner",async()=>{await ce(e.id,{result_diff:n,result_diff_binary:a})}))}else L.log("No diffs to upload");return L.log("Updated agent runner with result"),await Ut(async()=>await A(be(),"update-runner-session",()=>B(e.id,e.sessionId,s)),{maxRetries:3,baseDelay:1e3,onRetry:(l,c)=>{L.error(`Error updating agent runner session (attempt ${l}):`,c),L.log("Retrying...")}}),L.log("Finished updating agent runner with result"),{sessionUpdate:s}};import{getTracer as Gt,shutdownTracers as en,withActiveSpan as jt}from"@netlify/otel";var tn=Qr(import.meta.url),Yt=tn("../package.json"),Bt=w("pipeline_index"),Ce=3,Ht=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:i,tracing:a={}})=>{let u,{withStageTimer:s}=dt(V.timeUnits.hours(4)),y=await tt(Yt.version,e.id,a);try{await jt(Gt(),"run-pipeline",{},y,async()=>{let l,{aiGateway:c,context:g,persistSteps:E,runner:T,sha:I}=await s("init",()=>$t({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:i,runnerVersion:Yt.version}),V.timeUnits.minutes(10));u=T.clean,e.sha=I;let{runnerResult:h}=await s("inference",()=>Ne({cliPath:r,config:e,context:g,runner:T.runner,persistSteps:E,aiGateway:c}));await B(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let x=await s("deploy",()=>We({cliPath:r,config:e,context:g,result:h.result,filter:i})),v=h,C=[];if(x.hasChanges&&x.deployError){C.push(rt(x.deployError));let f=1;for(;f<=Ce&&!x.previewInfo;)Bt.log(`Deploy attempt had errors. Retrying. ${f}/${Ce}`),await jt(Gt(),"deploy-stage",async _=>{_?.setAttributes({"stage.attempt":f});let{runnerResult:d}=await s(`inference-retry-${f}`,()=>Ne({cliPath:r,config:e,context:g,runner:T.runner,persistSteps:E,aiGateway:c,buildErrors:C,priorAgentSessionId:h.agentSessionId}));v={...d,steps:[...v.steps||[],...d.steps||[]],duration:(v.duration||0)+(d.duration||0)},x=await s(`deploy-retry-${f}`,()=>We({cliPath:r,config:e,context:g,result:d.result,filter:i})),x.deployError&&C.push(x.deployError),f++});f>Ce&&!x.previewInfo&&(l=new Error(`Deploy validation failed after ${Ce} attempts`))}let{diff:N,resultDiff:R,previewInfo:S,diffBinary:m,resultDiffBinary:p}=x;if(await s("cleanup",()=>Mt({config:e,diff:N,result:v.result,duration:v.duration,resultDiff:R,diffBinary:m,resultDiffBinary:p,previewInfo:S}),V.timeUnits.minutes(10)),l)throw l;process.env.NETLIFY_LOCAL_MODE||await T.clean?.()})}catch(l){Bt.error("Got error while running pipeline",l),await u?.();let c=l instanceof Error&&l.message;throw await B(e.id,e.sessionId,{result:c||"Encountered error when running agent",state:"error"}),l}finally{await en()}};import Kt from"crypto";var $=w("bin_local"),Y=rn(b.argv.slice(2),{string:["cwd","cli-path","filter","prompt","runner","model","netlify-api-token"],boolean:["verbose","help"],alias:{h:"help",v:"verbose"}}),Xe=()=>{console.log(`
131
+ `;import un from"process";import{getTracer as Je}from"@netlify/otel";import{getTracer as ln}from"@netlify/otel";var ge=E("deploy"),Yt=async e=>await b(ln(),"create-preview-deploy",async t=>cn(e,t)),cn=async({netlify:e,hasRepo:t,skipBuild:r,message:o="Agent Preview",deploySubdomain:n,cliPath:i,filter:a},l)=>{try{let s=["deploy","--message",`"${o}"`,"--json","--draft","--verbose"];t||(ge.log("Deploy: Uploading source zip"),s.push("--upload-source-zip")),n&&s.push("--alias",n),a&&s.push("--filter",a),r?(ge.log("Deploy: Skipping build"),s.push("--no-build")):s.push("--context","deploy-preview");let m=i||"netlify";ge.log(`Running: ${m} ${s.join(" ")}`),l?.setAttributes({cmd:m,args:s});let u=await e.utils.run(m,s,{stdio:["ignore","pipe","pipe"]}),c=JSON.parse(u.stdout.trim());l?.setAttributes({success:!0,deployId:c.deploy_id,deployUrl:c.deploy_url,siteId:c.site_id}),ge.log(`
132
+ Preview deploy created successfully:`,{deployId:c.deploy_id,deployUrl:c.deploy_url,siteId:c.site_id});let f={deployId:c.deploy_id,previewUrl:c.deploy_url,logsUrl:c.logs,siteId:c.site_id};return t||(f.sourceZipFilename=c.source_zip_filename),f}catch(s){throw ge.error("Failed to create preview deploy via CLI:",s),l?.setAttributes({success:!1,error:s.message}),s}};var me=E("deploy_stage"),Xe=async e=>await b(Je(),"run-deploy-stage",async()=>pn(e)),pn=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let i=await b(Je(),"get-runner-diffs",async()=>await xt({config:t,netlify:r}));if(me.info("Resolved git",{hasChanges:i.hasChanges,ignored:i.ignored??[]}),!i.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:l,diffBinary:s,resultDiffBinary:m}=i,u=!0;me.log("Preview deploy condition check:",{resultUndefined:o===void 0,resultType:typeof o,hasChanges:u,wouldCreatePreview:o!==void 0&&u});let c=null;if(o!==void 0&&u)try{let f;try{let h=await b(Je(),"get-runner-session",async()=>await at(t.id,t.sessionId));h?.title&&(f=h.title)}catch(h){me.warn("Failed to fetch session title, using fallback message:",h.message)}await H(t.id,t.sessionId,{steps:[{title:"Deploying the run preview"}]}),c=await Yt({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:f,skipBuild:!1,deploySubdomain:wt(t.id,un.env.SITE_NAME),filter:n})}catch(f){return me.warn("Failed to create preview deploy (continuing with agent run):",f),{diff:a,resultDiff:l,hasChanges:u,previewInfo:null,diffBinary:s,resultDiffBinary:m,deployError:f instanceof Error?f.message:String(f)}}return me.log("Git status",{hasDiff:!!a,hasChanges:u}),{diff:a,resultDiff:l,hasChanges:u,previewInfo:c,diffBinary:s,resultDiffBinary:m}};import{getTracer as Ce}from"@netlify/otel";async function Bt(e,t){let{maxRetries:r,baseDelay:o,onRetry:n}=t,i;for(let a=1;a<=r;a++)try{return await e()}catch(l){if(i=l,a===r)throw i;n&&n(a,i),await new Promise(s=>setTimeout(s,o*a))}throw i}var be=class{scanDiffForForms(t){let r=[],o=null,n=[],i=t.split(`
133
+ `);for(let a of i)if(a.startsWith("diff --git")){if(o&&n.length>0){let s=this.containsNetlifyForm(n,o);s&&r.push(s)}let l=a.split(" ");o=l[l.length-1].replace(/^b\//,""),n=[]}else a.startsWith("+")&&!a.startsWith("+++")&&n.push(a.slice(1));if(o&&n.length>0){let a=this.containsNetlifyForm(n,o);a&&r.push(a)}return{detected:r.length>0,matches:r}}containsNetlifyForm(t,r){let o=t.join(`
134
+ `),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:a}of n){let l=o.match(i);if(l){let s=l.index||0,m=Math.max(0,s-20),u=Math.min(o.length,s+l[0].length+20),c=o.slice(m,u).trim();return c=c.replace(/\s+/g," "),c.length>100&&(c=c.slice(0,97)+"..."),{file:r,snippet:`[${a}] ${c}`}}}return null}};var C=E("cleanup_stage"),Ht=async e=>await b(Ce(),"cleanup-stage",async()=>dn(e)),ze=1024*1024*10,dn=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:i,resultDiffBinary:a,previewInfo:l})=>{let s={result:r||"Done",duration:o};l&&l.deployId&&(s.deploy_id=l.deployId),l&&l.sourceZipFilename&&(s.result_zip_file_name=l.sourceZipFilename);let m=t||i||n||a;if(m){let u=new be,c=t||i||"",f=u.scanDiffForForms(c);f.detected?(C.log("Detected Netlify form(s) in diff:"),f.matches.forEach(({file:h,snippet:w})=>{C.log(` - ${h}: ${w}`)}),s.has_netlify_form=!0):C.log("Did not detect Netlify form(s) in diff"),C.log("Did not detect Netlify form(s) in diff")}if(m)try{C.log("Getting pre-signed URLs for diff upload");let u=await ct(e.id,e.sessionId),c=[];(t||i)&&c.push(Fe(u.result.upload_url,i||t).then(()=>{s.result_diff_s3_key=u.result.s3_key,C.log("Successfully uploaded result_diff to S3")})),(n||a)&&c.push(Fe(u.cumulative.upload_url,a||n).then(()=>{s.cumulative_diff_s3_key=u.cumulative.s3_key,C.log("Successfully uploaded cumulative_diff to S3")})),C.log(`Uploading ${c.length} diff(s) to S3 in parallel`),await Promise.all(c),(n||a)&&(C.log("Updating agent runner with cumulative diff S3 key"),await b(Ce(),"update-runner",async()=>{await de(e.id,{result_diff_s3_key:u.cumulative.s3_key})}))}catch(u){C.error("S3 upload failed, falling back to inline diffs:",u);let c=Buffer.byteLength(t||i||""),f=Buffer.byteLength(a||n||"");if(c>ze||f>ze){let h=`Diffs exceed maximum inline size of ${ze} bytes.`;throw C.error(h),new Error(h)}s.result_diff=t,s.result_diff_binary=i,(n||a)&&(s.cumulative_diff=n,s.cumulative_diff_binary=a,C.log("Updating agent runner with inline diffs (fallback)"),await b(Ce(),"update-runner",async()=>{await de(e.id,{result_diff:n,result_diff_binary:a})}))}else C.log("No diffs to upload");return C.log("Updated agent runner with result"),await Bt(async()=>await b(Ce(),"update-runner-session",()=>H(e.id,e.sessionId,s)),{maxRetries:3,baseDelay:1e3,onRetry:(u,c)=>{C.error(`Error updating agent runner session (attempt ${u}):`,c),C.log("Retrying...")}}),C.log("Finished updating agent runner with result"),{sessionUpdate:s}};import{getTracer as qt,shutdownTracers as gn,withActiveSpan as Kt}from"@netlify/otel";var mn=fn(import.meta.url),Wt=mn("../package.json"),Vt=E("pipeline_index"),Pe=3,Jt=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:i,tracing:a={}})=>{let l,{withStageTimer:s}=ft(X.timeUnits.hours(4)),m=await nt(Wt.version,e.id,a);try{await Kt(qt(),"run-pipeline",{},m,async()=>{let u,{aiGateway:c,context:f,persistSteps:h,runner:w,sha:I}=await s("init",()=>Ut({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:i,runnerVersion:Wt.version}),X.timeUnits.minutes(10));l=w.clean,e.sha=I;let{runnerResult:g}=await s("inference",()=>Ne({cliPath:r,config:e,context:f,runner:w.runner,persistSteps:h,aiGateway:c}));await H(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let v=await s("deploy",()=>Xe({cliPath:r,config:e,context:f,result:g.result,filter:i})),x=g,N=[];if(v.hasChanges&&v.deployError){N.push(ot(v.deployError));let y=1;for(;y<=Pe&&!v.previewInfo;)Vt.log(`Deploy attempt had errors. Retrying. ${y}/${Pe}`),await Kt(qt(),"deploy-stage",async d=>{d?.setAttributes({"stage.attempt":y});let{runnerResult:p}=await s(`inference-retry-${y}`,()=>Ne({cliPath:r,config:e,context:f,runner:w.runner,persistSteps:h,aiGateway:c,buildErrors:N,priorAgentSessionId:g.agentSessionId}));x={...p,steps:[...x.steps||[],...p.steps||[]],duration:(x.duration||0)+(p.duration||0)},v=await s(`deploy-retry-${y}`,()=>Xe({cliPath:r,config:e,context:f,result:p.result,filter:i})),v.deployError&&N.push(v.deployError),y++});y>Pe&&!v.previewInfo&&(u=new Error(`Deploy validation failed after ${Pe} attempts`))}let{diff:T,resultDiff:_,previewInfo:R,diffBinary:S,resultDiffBinary:A}=v;if(await s("cleanup",()=>Ht({config:e,diff:T,result:x.result,duration:x.duration,resultDiff:_,diffBinary:S,resultDiffBinary:A,previewInfo:R}),X.timeUnits.minutes(10)),u)throw u;process.env.NETLIFY_LOCAL_MODE||(await l?.(),await At())})}catch(u){Vt.error("Got error while running pipeline",u),await l?.();let c=u instanceof Error&&u.message;throw await H(e.id,e.sessionId,{result:c||"Encountered error when running agent",state:"error"}),u}finally{await gn()}};import Xt from"crypto";var F=E("bin_local"),B=hn(O.argv.slice(2),{string:["cwd","cli-path","filter","prompt","runner","model","netlify-api-token"],boolean:["verbose","help"],alias:{h:"help",v:"verbose"}}),Qe=()=>{console.log(`
136
135
  agent-runner-cli-local - Run Netlify agent runner locally without API connections
137
136
 
138
137
  USAGE:
@@ -164,6 +163,6 @@ NOTE:
164
163
  This local mode mocks all Netlify API calls. The agent will run through
165
164
  the full pipeline including inference and deployment, but API calls will
166
165
  be logged instead of executed.
167
- `)};Y.help&&(Xe(),b.exit(0));Y.prompt||($.error("Error: --prompt is required"),Xe(),b.exit(1));Y["netlify-api-token"]||($.error("Error: --netlify-api-token is required - generate a PAT from your Netlify user settings"),Xe(),b.exit(1));try{let e=Y.cwd||b.cwd(),t=qt.join(e,".netlify","netlify-agent-runner-context*");Wt.rmSync(t,{recursive:!0,force:!0});let r;try{r=await nn(e)}catch(u){$.error(u.message),$.error(`
168
- To link this directory to a Netlify site, run:`),$.error(" netlify link"),b.exit(1)}let o=`local-${Kt.randomBytes(8).toString("hex")}`,n=`session-${Kt.randomBytes(8).toString("hex")}`,i=Y.runner||"claude";$.log("Starting agent runner in local mode",{runnerId:o,sessionId:n,siteId:r,cwd:e,runner:i});let a={id:o,sessionId:n,prompt:Y.prompt,runner:i,model:Y.model,accountType:"local",validateAgent:!1,validateAgentWithBuild:!1,sessionHistoryContext:[],siteContext:[],hasRepo:!0,useGateway:!0,sha:void 0,modelVersionOverrides:{}};b.env.NETLIFY_LOCAL_MODE="true",b.env.NETLIFY_API_HOST="api.netlify.com",b.env.NETLIFY_API_TOKEN=Y["netlify-api-token"],b.env.SITE_ID=r,b.env.NETLIFY_TEAM_ID="local-team-id",b.env.NETLIFY_AGENT_RUNNER_USER_ID="local-user-id",b.env.SITE_NAME="local-site",i==="claude"?Ie(e,"claude")||($.log("Claude CLI not found, installing..."),await Je(e,"@anthropic-ai/claude-code")):i==="gemini"?Ie(e,"gemini")||($.log("Gemini CLI not found, installing..."),await Je(e,"@google/gemini-cli@0.1.17")):i==="codex"?Ie(e,"codex")||($.log("Codex CLI not found, installing..."),await Je(e,"@openai/codex")):($.error(`Unknown runner: ${i}`),b.exit(1)),await Ht({config:a,cwd:e,cliPath:Y["cli-path"],filter:Y.filter,tracing:{exporterUrl:void 0,traceparent:void 0}}),$.info("Finished agent (local mode)"),b.exit(0)}catch(e){$.error("Error running agent pipeline (local mode):",e),b.exit(1)}function Je(e,t){return new Promise((r,o)=>{we("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 nn(e){let t=qt.join(e,".netlify","state.json");try{let r=await Wt.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}}
166
+ `)};B.help&&(Qe(),O.exit(0));B.prompt||(F.error("Error: --prompt is required"),Qe(),O.exit(1));B["netlify-api-token"]||(F.error("Error: --netlify-api-token is required - generate a PAT from your Netlify user settings"),Qe(),O.exit(1));try{let e=B.cwd||O.cwd(),t=zt.join(e,".netlify","netlify-agent-runner-context*");Zt.rmSync(t,{recursive:!0,force:!0});let r;try{r=await yn(e)}catch(l){F.error(l.message),F.error(`
167
+ To link this directory to a Netlify site, run:`),F.error(" netlify link"),O.exit(1)}let o=`local-${Xt.randomBytes(8).toString("hex")}`,n=`session-${Xt.randomBytes(8).toString("hex")}`,i=B.runner||"claude";F.log("Starting agent runner in local mode",{runnerId:o,sessionId:n,siteId:r,cwd:e,runner:i});let a={id:o,sessionId:n,prompt:B.prompt,runner:i,model:B.model,accountType:"local",validateAgent:!1,validateAgentWithBuild:!1,sessionHistoryContext:[],siteContext:[],hasRepo:!0,useGateway:!0,sha:void 0,modelVersionOverrides:{}};O.env.NETLIFY_LOCAL_MODE="true",O.env.NETLIFY_API_HOST="api.netlify.com",O.env.NETLIFY_API_TOKEN=B["netlify-api-token"],O.env.SITE_ID=r,O.env.NETLIFY_TEAM_ID="local-team-id",O.env.NETLIFY_AGENT_RUNNER_USER_ID="local-user-id",O.env.SITE_NAME="local-site",i==="claude"?Te(e,"claude")||(F.log("Claude CLI not found, installing..."),await Ze(e,"@anthropic-ai/claude-code")):i==="gemini"?Te(e,"gemini")||(F.log("Gemini CLI not found, installing..."),await Ze(e,"@google/gemini-cli")):i==="codex"?Te(e,"codex")||(F.log("Codex CLI not found, installing..."),await Ze(e,"my-codex-no-sandbox")):(F.error(`Unknown runner: ${i}`),O.exit(1)),await Jt({config:a,cwd:e,cliPath:B["cli-path"],filter:B.filter,tracing:{exporterUrl:void 0,traceparent:void 0}}),F.info("Finished agent (local mode)"),O.exit(0)}catch(e){F.error("Error running agent pipeline (local mode):",e),O.exit(1)}function Ze(e,t){return new Promise((r,o)=>{P("npm",["install",t,"--no-save"],{cwd:e}).then(({stdout:n})=>{F.log(`${t} installed: ${n}`),r()}).catch(n=>{F.error(`Error installing ${t}: ${n.stderr||n.message}`),o(n)})})}async function yn(e){let t=zt.join(e,".netlify","state.json");try{let r=await Zt.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 F.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}}
169
168
  //# sourceMappingURL=bin-local.js.map