@netlify/agent-runner-cli 1.43.0 → 1.44.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.
Files changed (3) hide show
  1. package/dist/bin.js +24 -24
  2. package/dist/index.js +24 -24
  3. package/package.json +2 -2
package/dist/bin.js CHANGED
@@ -1,36 +1,36 @@
1
1
  #!/usr/bin/env node
2
- import qe from"process";import Qr from"minimist";import{createRequire as qr}from"module";import{createTracerProvider as jt}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as Ke}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as Yt}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as Bt}from"@netlify/otel";import{propagation as Ve,context as We,W3CTraceContextPropagator as Ht}from"@netlify/otel/opentelemetry";import{OTLPTraceExporter as qt}from"@opentelemetry/exporter-trace-otlp-grpc";function y(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 Ne=y("tracing"),Je=async(e,t,r)=>(await jt({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new Ke(new xe),new Ke(new qt({url:r.exporterUrl}))],instrumentations:[new Yt({skipHeaders:!0})]}),r.traceparent?(Ve.setGlobalPropagator(new Ht),Ve.extract(We.active(),{traceparent:r.traceparent,isRemote:!0})):We.active());function b(e,t,r){return Ne.log(`\u23F3 TRACE: ${t} starting...`),Bt(e,t,r)}var xe=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,i]of Object.entries(o))u.includes("duration")&&typeof i=="number"?n.push(`${u}=${i.toFixed(2)}ms`):n.push(`${u}=${i}`);let s=t.status?.code===2?"\u274C":"\u2705",a=n.length>0?` [${n.join(", ")}]`:"";Ne.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${a}`),t.status?.code===2&&t.status.message&&Ne.log(` \u274C Error: ${t.status.message}`)}};var Kt=["error","failed","exception","fatal","panic","abort","crash"];function Xe(e){let t=e.split(`
3
- `),r=[],o=-1,n=0;for(;n<t.length;){let u=t[n].slice(0,500).toLowerCase();if(Kt.some(p=>u.includes(p))){let p=Math.max(0,n-10,o+1),c=Math.min(t.length-1,n+20),d=[];for(let f=p;f<=c;f++)d.push(t[f]);r.push(d.join(`
2
+ import qe from"process";import Qr from"minimist";import{createRequire as qr}from"module";import{createTracerProvider as jt}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as Ke}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as Yt}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as Bt}from"@netlify/otel";import{propagation as Ve,context as We,W3CTraceContextPropagator as Ht}from"@netlify/otel/opentelemetry";import{OTLPTraceExporter as qt}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 Ne=E("tracing"),Je=async(e,t,r)=>(await jt({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new Ke(new xe),new Ke(new qt({url:r.exporterUrl}))],instrumentations:[new Yt({skipHeaders:!0})]}),r.traceparent?(Ve.setGlobalPropagator(new Ht),Ve.extract(We.active(),{traceparent:r.traceparent,isRemote:!0})):We.active());function b(e,t,r){return Ne.log(`\u23F3 TRACE: ${t} starting...`),Bt(e,t,r)}var xe=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,i]of Object.entries(o))u.includes("duration")&&typeof i=="number"?n.push(`${u}=${i.toFixed(2)}ms`):n.push(`${u}=${i}`);let s=t.status?.code===2?"\u274C":"\u2705",a=n.length>0?` [${n.join(", ")}]`:"";Ne.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${a}`),t.status?.code===2&&t.status.message&&Ne.log(` \u274C Error: ${t.status.message}`)}};var Kt=["error","failed","exception","fatal","panic","abort","crash"];function Xe(e){let t=e.split(`
3
+ `),r=[],o=-1,n=0;for(;n<t.length;){let u=t[n].slice(0,500).toLowerCase();if(Kt.some(f=>u.includes(f))){let f=Math.max(0,n-10,o+1),c=Math.min(t.length-1,n+20),p=[];for(let d=f;d<=c;d++)p.push(t[d]);r.push(p.join(`
4
4
  `)),o=c,n=c+1}else n++}if(r.length===0)return e;let s=r.map((a,u)=>`<extracted_error_chunk order="${u+1}">
5
5
  ${a}
6
6
  </extracted_error_chunk>`).join(`
7
7
 
8
- `);return s.length>e.length*.8?e:s}import _e from"process";import{getTracer as Sr}from"@netlify/otel";import le from"process";var ue=le.env.NETLIFY_API_URL,ce=le.env.NETLIFY_API_TOKEN,oe=y("api"),pe=async(e,t={})=>{if(!ue||!ce)throw new Error("No API URL or token");let r=new URL(e,ue),o={...t,headers:{...t.headers,Authorization:`Bearer ${ce}`}};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),s=n.ok&&n.status<=299;if(le.env.AGENT_RUNNERS_DEBUG==="true")oe.log(`Response headers for ${r}:`),n.headers.forEach((u,i)=>{oe.log(` ${i}: ${u}`)});else{let u=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");oe.log(`Request ID for ${r}: ${u||"N/A"}`)}if(s||oe.error(`Got status ${n.status} for request ${r}`),t.raw){if(!s)throw n;return n}let a=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!s)throw a;return a},ze=e=>{oe.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(ue=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(ce=e.constants.NETLIFY_API_TOKEN)},Ze=()=>({apiUrl:ue,token:ce}),de=(e,t)=>pe(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),G=(e,t,r)=>pe(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var Qe=(e,t)=>pe(`/api/v1/agent_runners/${e}/sessions/${t}`),et=(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}});var X=y("ai_gateway"),ve=null;var tt=async()=>{if(ve)return ve;X.log("Fetching available AI gateway providers");let e=await fetch(`${Ze().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 ve=t,X.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},Vt=async(e,t)=>{let o=(await tt()).providers[e];if(!o)return X.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return X.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},rt=async({netlify:e,config:t})=>{let r,o,n,s,a=e.constants?.SITE_ID;if(!a)throw new Error("No site id");let u=async()=>{clearTimeout(n),X.log("Requesting AI gateway information");let i=await et(a,t.id,t.sessionId);if({token:r,url:s}=i,o=i.expires_at?i.expires_at*1e3:void 0,X.log("Got AI gateway information",{token:!!r,expiresAt:o,url:s}),o){let p=o-Date.now()-6e4;p>0&&(n=setTimeout(()=>{u()},p))}};return await Promise.all([u(),tt()]),{get url(){return s},get token(){return r},isModelAvailableForProvider:Vt}};import K from"process";import{execa as Qt,execaCommand as Rn}from"execa";import{Transform as Wt}from"stream";var Jt=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"]),Xt=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function zt(){return Object.entries(process.env).filter(([e,t])=>!(!t||Jt.has(e)||Xt.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function M(e){if(typeof e!="string")return e;let t=zt();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(Zt(o),"g");r=r.replace(n,"******")}),r}function Zt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var z=class extends Wt{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),s=M(n);o(null,s)}};function nt(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(o,n,s){let a=typeof o=="string"?M(o):o;return typeof n=="function"?t(a,n):t(a,n,s)},process.stderr.write=function(o,n,s){let a=typeof o=="string"?M(o):o;return typeof n=="function"?r(a,n):r(a,n,s)}}var se=null,ot=e=>(se&&se.destroy(),se=new q({totalAllowedTime:e}),se),st=()=>se;var q=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.`)}),s=null,a=null;o!==void 0&&(a=new Promise((u,i)=>{s=setTimeout(()=>{i(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return a?await Promise.race([r(),a]):await r()}finally{n(),s&&clearTimeout(s)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var fe=y("shell"),Ae=new Set,er={preferLocal:!0},it=(e,t,r)=>{let[o,n]=tr(t,r),s={...er,...n},a=Qt(e,o,s);return rr(a,s),or(a),a};var tr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},rr=(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 z).pipe(K.stdout),e.stdout?.pipe(new z).pipe(K.stdout),e.stderr?.pipe(new z).pipe(K.stderr);return}e.stdout?.pipe(K.stdout),e.stderr?.pipe(K.stderr)},at=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(K.kill(-e.pid,t),fe.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return fe.error("Error killing process:",r),!1}},nr=e=>at(e,"SIGKILL"),or=e=>{Ae.add(e);let t=st();if(t){let r=t.onTimesUp(()=>{fe.log(`Global timer expired, killing process ${e.pid}`),at(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(fe.log(`Force killing process ${e.pid} after timeout`),nr(e))},5e3)});e.on("exit",()=>{Ae.delete(e),r()}),e.on("error",()=>{Ae.delete(e),r()})}};var lt="netlify-agent-runner-context.md",Se="task-history",Ce="netlify-context",F=".netlify",Z="results.md",be="assets",Pe="other",Oe="personal";var De="enterprise",Le="free",ut=[Oe,"pro",De,Le];var ct=y("utils"),sr=e=>new Promise(t=>{setTimeout(t,e)}),pt=(e,t=3e3)=>{let r=!1,o=null,n=[],s=null,a=(...u)=>{if(r)return o=u,new Promise(c=>{n.push(c)});r=!0;let i,p=new Promise(c=>{i=c});return s=(async()=>{await Promise.resolve();let c=await e(...u);for(i(c);;){if(await sr(t),!o)return r=!1,s=null,c;let d=o,f=n;o=null,n=[],c=await e(...d),f.forEach(_=>{_(c)})}})(),p};return a.flush=async()=>{if((r||o)&&s)return await s,a.flush()},a},ge=(e,t,r=!1)=>{let o=null,n=null,s=null,a=function(...u){n=u,s=this;let i=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(s,n),n=null,s=null)},t),i&&(e.apply(s,n),n=null,s=null)};return a.cancel=()=>{clearTimeout(o),o=null,n=null,s=null},a.flush=()=>{if(o){clearTimeout(o);let u=n,i=s;o=null,n=null,s=null,e.apply(i,u)}},a},me=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):ct.error("Could not parse JSON",o))}},dt=(e,t)=>{let n=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let u=`--${t}${n}`;if(u.length>55)return"";let i=60-u.length;if(i<=0)return"";if(i>=s.length+6){let p=Math.min(i-s.length,e.length);return`${s}${e.slice(0,p)}`}return e.slice(0,i)},ir=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!ut.some(t=>t in e),ft=()=>{let e={},t={codex:process.env.NETLIFY_FF_AGENT_RUNNER_CODEX_VERSION,claude:process.env.NETLIFY_FF_AGENT_RUNNER_CLAUDE_VERSION,gemini:process.env.NETLIFY_FF_AGENT_RUNNER_GEMINI_VERSION};return Object.entries(t).forEach(([r,o])=>{if(o){let n=`NETLIFY_FF_AGENT_RUNNER_${r.toUpperCase()}_VERSION`;try{let s=JSON.parse(o);ir(s)&&(e[r]=s)}catch(s){let u=s instanceof SyntaxError?"Invalid JSON":s.message;ct.error(`Could not parse ${r} model version override from ${n}: ${u}`)}}}),e};import{Buffer as gt}from"buffer";import ar from"path";var mt=async({config:e,netlify:t})=>{let r=await ur(t),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};let s=await cr(n);await t.utils.run("git",["add",".",...s]);let a={stdio:["ignore","pipe","pipe"]},i=(await t.utils.run("git",["diff","--staged"],a)).stdout;if(o=!!i,!o)return{hasChanges:!1,ignored:s};let c=(await t.utils.run("git",["diff","--staged","--binary"],a)).stdout,d,f;if(e.sha){await t.utils.run("git",["commit","-m","Agent runner"]),d=(await t.utils.run("git",["diff",e.sha,"HEAD"],a)).stdout;let T=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;d!==T&&(f=gt.from(T).toString("base64"))}let _={hasChanges:!0,diff:i,resultDiff:d,ignored:s};return i!==c&&(_.diffBinary=gt.from(c).toString("base64")),f&&(_.resultDiffBinary=f),_},lr=["?? mise.toml","?? deno.lock",/\?\? .+?\.log/],ur=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
8
+ `);return s.length>e.length*.8?e:s}import _e from"process";import{getTracer as Sr}from"@netlify/otel";import le from"process";var ue=le.env.NETLIFY_API_URL,ce=le.env.NETLIFY_API_TOKEN,oe=E("api"),pe=async(e,t={})=>{if(!ue||!ce)throw new Error("No API URL or token");let r=new URL(e,ue),o={...t,headers:{...t.headers,Authorization:`Bearer ${ce}`}};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),s=n.ok&&n.status<=299;if(le.env.AGENT_RUNNERS_DEBUG==="true")oe.log(`Response headers for ${r}:`),n.headers.forEach((u,i)=>{oe.log(` ${i}: ${u}`)});else{let u=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");oe.log(`Request ID for ${r}: ${u||"N/A"}`)}if(s||oe.error(`Got status ${n.status} for request ${r}`),t.raw){if(!s)throw n;return n}let a=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!s)throw a;return a},ze=e=>{oe.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(ue=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(ce=e.constants.NETLIFY_API_TOKEN)},Ze=()=>({apiUrl:ue,token:ce}),de=(e,t)=>pe(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),G=(e,t,r)=>pe(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var Qe=(e,t)=>pe(`/api/v1/agent_runners/${e}/sessions/${t}`),et=(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}});var X=E("ai_gateway"),ve=null;var tt=async()=>{if(ve)return ve;X.log("Fetching available AI gateway providers");let e=await fetch(`${Ze().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 ve=t,X.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},Vt=async(e,t)=>{let o=(await tt()).providers[e];if(!o)return X.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return X.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},rt=async({netlify:e,config:t})=>{let r,o,n,s,a=e.constants?.SITE_ID;if(!a)throw new Error("No site id");let u=async()=>{clearTimeout(n),X.log("Requesting AI gateway information");let i=await et(a,t.id,t.sessionId);if({token:r,url:s}=i,o=i.expires_at?i.expires_at*1e3:void 0,X.log("Got AI gateway information",{token:!!r,expiresAt:o,url:s}),o){let f=o-Date.now()-6e4;f>0&&(n=setTimeout(()=>{u()},f))}};return await Promise.all([u(),tt()]),{get url(){return s},get token(){return r},isModelAvailableForProvider:Vt}};import K from"process";import{execa as Qt,execaCommand as Rn}from"execa";import{Transform as Wt}from"stream";var Jt=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"]),Xt=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function zt(){return Object.entries(process.env).filter(([e,t])=>!(!t||Jt.has(e)||Xt.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function M(e){if(typeof e!="string")return e;let t=zt();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(Zt(o),"g");r=r.replace(n,"******")}),r}function Zt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var z=class extends Wt{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),s=M(n);o(null,s)}};function nt(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(o,n,s){let a=typeof o=="string"?M(o):o;return typeof n=="function"?t(a,n):t(a,n,s)},process.stderr.write=function(o,n,s){let a=typeof o=="string"?M(o):o;return typeof n=="function"?r(a,n):r(a,n,s)}}var se=null,ot=e=>(se&&se.destroy(),se=new q({totalAllowedTime:e}),se),st=()=>se;var q=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.`)}),s=null,a=null;o!==void 0&&(a=new Promise((u,i)=>{s=setTimeout(()=>{i(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return a?await Promise.race([r(),a]):await r()}finally{n(),s&&clearTimeout(s)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var fe=E("shell"),Ae=new Set,er={preferLocal:!0},it=(e,t,r)=>{let[o,n]=tr(t,r),s={...er,...n},a=Qt(e,o,s);return rr(a,s),or(a),a};var tr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},rr=(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 z).pipe(K.stdout),e.stdout?.pipe(new z).pipe(K.stdout),e.stderr?.pipe(new z).pipe(K.stderr);return}e.stdout?.pipe(K.stdout),e.stderr?.pipe(K.stderr)},at=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(K.kill(-e.pid,t),fe.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return fe.error("Error killing process:",r),!1}},nr=e=>at(e,"SIGKILL"),or=e=>{Ae.add(e);let t=st();if(t){let r=t.onTimesUp(()=>{fe.log(`Global timer expired, killing process ${e.pid}`),at(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(fe.log(`Force killing process ${e.pid} after timeout`),nr(e))},5e3)});e.on("exit",()=>{Ae.delete(e),r()}),e.on("error",()=>{Ae.delete(e),r()})}};var lt="netlify-agent-runner-context.md",Se="task-history",Ce="netlify-context",F=".netlify",Z="results.md",be="assets",Pe="other",Oe="personal";var De="enterprise",Le="free",ut=[Oe,"pro",De,Le];var ct=E("utils"),sr=e=>new Promise(t=>{setTimeout(t,e)}),pt=(e,t=3e3)=>{let r=!1,o=null,n=[],s=null,a=(...u)=>{if(r)return o=u,new Promise(c=>{n.push(c)});r=!0;let i,f=new Promise(c=>{i=c});return s=(async()=>{await Promise.resolve();let c=await e(...u);for(i(c);;){if(await sr(t),!o)return r=!1,s=null,c;let p=o,d=n;o=null,n=[],c=await e(...p),d.forEach(y=>{y(c)})}})(),f};return a.flush=async()=>{if((r||o)&&s)return await s,a.flush()},a},ge=(e,t,r=!1)=>{let o=null,n=null,s=null,a=function(...u){n=u,s=this;let i=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(s,n),n=null,s=null)},t),i&&(e.apply(s,n),n=null,s=null)};return a.cancel=()=>{clearTimeout(o),o=null,n=null,s=null},a.flush=()=>{if(o){clearTimeout(o);let u=n,i=s;o=null,n=null,s=null,e.apply(i,u)}},a},me=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):ct.error("Could not parse JSON",o))}},dt=(e,t)=>{let n=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let u=`--${t}${n}`;if(u.length>55)return"";let i=60-u.length;if(i<=0)return"";if(i>=s.length+6){let f=Math.min(i-s.length,e.length);return`${s}${e.slice(0,f)}`}return e.slice(0,i)},ir=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!ut.some(t=>t in e),ft=()=>{let e={},t={codex:process.env.NETLIFY_FF_AGENT_RUNNER_CODEX_VERSION,claude:process.env.NETLIFY_FF_AGENT_RUNNER_CLAUDE_VERSION,gemini:process.env.NETLIFY_FF_AGENT_RUNNER_GEMINI_VERSION};return Object.entries(t).forEach(([r,o])=>{if(o){let n=`NETLIFY_FF_AGENT_RUNNER_${r.toUpperCase()}_VERSION`;try{let s=JSON.parse(o);ir(s)&&(e[r]=s)}catch(s){let u=s instanceof SyntaxError?"Invalid JSON":s.message;ct.error(`Could not parse ${r} model version override from ${n}: ${u}`)}}}),e};import{Buffer as gt}from"buffer";import ar from"path";var mt=async({config:e,netlify:t})=>{let r=await ur(t),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};let s=await cr(n);await t.utils.run("git",["add",".",...s]);let a={stdio:["ignore","pipe","pipe"]},i=(await t.utils.run("git",["diff","--staged"],a)).stdout;if(o=!!i,!o)return{hasChanges:!1,ignored:s};let c=(await t.utils.run("git",["diff","--staged","--binary"],a)).stdout,p,d;if(e.sha){await t.utils.run("git",["commit","-m","Agent runner"]),p=(await t.utils.run("git",["diff",e.sha,"HEAD"],a)).stdout;let T=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;p!==T&&(d=gt.from(T).toString("base64"))}let y={hasChanges:!0,diff:i,resultDiff:p,ignored:s};return i!==c&&(y.diffBinary=gt.from(c).toString("base64")),d&&(y.resultDiffBinary=d),y},lr=["?? mise.toml","?? deno.lock",/\?\? .+?\.log/],ur=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
9
9
  `).filter(n=>!lr.some(s=>s instanceof RegExp?s.test(n):n===s))).length!==0,status:t.stdout}};var ht=async e=>{let{stdout:t}=await e.utils.run("git",["rev-parse","HEAD"]);return t.trim()},Et=async e=>{let{stdout:t}=await e.utils.run("git",["rev-list","--max-parents=0","HEAD"]);return t.trim()},cr=async e=>{let t=[".netlify","mise.toml","deno.lock","node_modules"],r=[];return e.split(`
10
- `).forEach(o=>{t.forEach(s=>{[`?? ${s}`,`?? ${s}${ar.sep}`].some(u=>o.startsWith(u))&&r.push(`:!${s}`)});let n=o.match(/\?\? (.+?)\.log$/)?.[1];n&&r.push(`:!${n}.log`)}),r};import dr from"fs/promises";import fr from"os";import Ee from"path";import Y from"process";import gr from"readline";import Fe from"path";import pr from"fs/promises";var $e=y("agent-output-utils");async function Q({initialResult:e,agentName:t,hasError:r}){let o="",n=Fe.join(process.cwd(),F,Z);try{let s=await pr.readFile(n,"utf-8");s&&(o=s,$e.log(`Pulled result from ${Fe.relative(process.cwd(),n)}`))}catch{$e.log(`No results file found at ${Fe.relative(process.cwd(),n)}`)}return o||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function ee({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&&$e.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function te(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 $=y("runner_claude"),yt="Claude Code",he="claude-sonnet-4-5-20250929",mr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>($.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?($.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}):($.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function Ue({config:e,netlify:t,persistSteps:r,aiGateway:o}){let n=e,{accountType:s,prompt:a,modelVersionOverrides:u}=n,{model:i}=n;if(o){let{token:I,url:m}=o;if(!I||!m)throw new Error("No token or url provided from AI Gateway");if(u?.claude){let l=u?.claude?.[s];if(l){if(!await o.isModelAvailableForProvider("anthropic",l))throw new Error(`Model override '${l}' is not available for anthropic provider`);i=l}}else if(i){if(!await o.isModelAvailableForProvider("anthropic",i))throw new Error(`Model '${i}' is not available for anthropic provider`)}else await o.isModelAvailableForProvider("anthropic",he)?(i=he,$.log(`Using default model: ${he}`)):$.log(`Default model ${he} is not available, proceeding without model specification`);Y.env.ANTHROPIC_API_KEY=I,Y.env.ANTHROPIC_BASE_URL=m}else if(!Y.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let p=[],c=[],d={},f=0,_=0,g,E,T=Ee.join(Y.cwd(),"node_modules"),N=[Ee.join(Y.env.NODE_PATH||T,".bin/claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...i?["--model",i]:[],"-p",a],x=`${Y.env.NVM_BIN}/node`;$.log(`Running ${x} ${N.join(" ")}`);let A=t.utils.run(x,N,{all:!0,env:Y.env});A.stdin?.end();let v=ge(()=>{r?.({steps:p,duration:_})},250),R=(I,m)=>{let l={...I,id:f};f+=1,c.push(l),p.push(l),m||v.flush(),v(),m&&v.flush()},w=gr.createInterface({input:A.all});return w.on("error",I=>{$.error("Readline interface error",{error:I.message,stack:I.stack})}),w.on("line",I=>{let m=null;try{m=JSON.parse(I)}catch{$.log("Could not parse line",I)}Array.isArray(m?.message?.content)?m.message.content.forEach(l=>{switch(l.type){case"text":{l.text&&R({message:l.text});break}case"image":{typeof l.source=="object"&&l.source&&l.source.type==="base64"&&l.source.media_type?R({message:`![](data:${l.source.media_type};base64,${l.source.data})`}):$.log(`Unsupported image type ${l.source?.type}`,l.source);break}case"tool_use":{if(l.name==="Task"){let h=l.input?.description&&`\`${l.input.description}\``;R({title:[l.name,h].filter(Boolean).join(" ")})}else l.id&&(d[l.id]=l);v.flush();break}case"tool_result":{let h=l.tool_use_id?d[l.tool_use_id]:void 0,S;if(h){let k=h.input?.file_path&&Ee.relative(Y.cwd(),h.input.file_path),C=k&&`\`${k}\``;S=[h.name,C].filter(Boolean).join(" ")}let j=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(h?.name||""),L;if(typeof l.content=="string")L=l.content;else if(Array.isArray(l.content)){let k=[];l.content.forEach(C=>{C?.type==="text"&&typeof C.text=="string"?k.push(C.text):C?.type==="image"&&typeof C.source=="object"&&C.source?C.source.type==="base64"&&C.source.media_type?k.push(`![](data:${C.source.media_type};base64,${C.source.data})`):$.log(`Unsupported image type ${C.source.type}`,C.source):$.log(`Unsupported block type ${C?.type}`)}),L=k.join(`
10
+ `).forEach(o=>{t.forEach(s=>{[`?? ${s}`,`?? ${s}${ar.sep}`].some(u=>o.startsWith(u))&&r.push(`:!${s}`)});let n=o.match(/\?\? (.+?)\.log$/)?.[1];n&&r.push(`:!${n}.log`)}),r};import dr from"fs/promises";import fr from"os";import Ee from"path";import Y from"process";import gr from"readline";import Fe from"path";import pr from"fs/promises";var $e=E("agent-output-utils");async function Q({initialResult:e,agentName:t,hasError:r}){let o="",n=Fe.join(process.cwd(),F,Z);try{let s=await pr.readFile(n,"utf-8");s&&(o=s,$e.log(`Pulled result from ${Fe.relative(process.cwd(),n)}`))}catch{$e.log(`No results file found at ${Fe.relative(process.cwd(),n)}`)}return o||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function ee({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&&$e.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function te(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 $=E("runner_claude"),yt="Claude Code",he="claude-sonnet-4-5-20250929",mr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>($.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?($.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}):($.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function Ue({config:e,netlify:t,persistSteps:r,aiGateway:o}){let n=e,{accountType:s,prompt:a,modelVersionOverrides:u}=n,{model:i}=n;if(o){let{token:w,url:m}=o;if(!w||!m)throw new Error("No token or url provided from AI Gateway");if(u?.claude){let l=u?.claude?.[s];if(l){if(!await o.isModelAvailableForProvider("anthropic",l))throw new Error(`Model override '${l}' is not available for anthropic provider`);i=l}}else if(i){if(!await o.isModelAvailableForProvider("anthropic",i))throw new Error(`Model '${i}' is not available for anthropic provider`)}else await o.isModelAvailableForProvider("anthropic",he)?(i=he,$.log(`Using default model: ${he}`)):$.log(`Default model ${he} is not available, proceeding without model specification`);Y.env.ANTHROPIC_API_KEY=w,Y.env.ANTHROPIC_BASE_URL=m}else if(!Y.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let f=[],c=[],p={},d=0,y=0,I,g,T=Ee.join(Y.cwd(),"node_modules"),N=[Ee.join(Y.env.NODE_PATH||T,".bin/claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...i?["--model",i]:[],"-p",a],x=`${Y.env.NVM_BIN}/node`;$.log(`Running ${x} ${N.join(" ")}`);let A=t.utils.run(x,N,{all:!0,env:Y.env});A.stdin?.end();let v=ge(()=>{r?.({steps:f,duration:y})},250),R=(w,m)=>{let l={...w,id:d};d+=1,c.push(l),f.push(l),m||v.flush(),v(),m&&v.flush()},_=gr.createInterface({input:A.all});return _.on("error",w=>{$.error("Readline interface error",{error:w.message,stack:w.stack})}),_.on("line",w=>{let m=null;try{m=JSON.parse(w)}catch{$.log("Could not parse line",w)}Array.isArray(m?.message?.content)?m.message.content.forEach(l=>{switch(l.type){case"text":{l.text&&R({message:l.text});break}case"image":{typeof l.source=="object"&&l.source&&l.source.type==="base64"&&l.source.media_type?R({message:`![](data:${l.source.media_type};base64,${l.source.data})`}):$.log(`Unsupported image type ${l.source?.type}`,l.source);break}case"tool_use":{if(l.name==="Task"){let h=l.input?.description&&`\`${l.input.description}\``;R({title:[l.name,h].filter(Boolean).join(" ")})}else l.id&&(p[l.id]=l);v.flush();break}case"tool_result":{let h=l.tool_use_id?p[l.tool_use_id]:void 0,S;if(h){let k=h.input?.file_path&&Ee.relative(Y.cwd(),h.input.file_path),C=k&&`\`${k}\``;S=[h.name,C].filter(Boolean).join(" ")}let j=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(h?.name||""),L;if(typeof l.content=="string")L=l.content;else if(Array.isArray(l.content)){let k=[];l.content.forEach(C=>{C?.type==="text"&&typeof C.text=="string"?k.push(C.text):C?.type==="image"&&typeof C.source=="object"&&C.source?C.source.type==="base64"&&C.source.media_type?k.push(`![](data:${C.source.media_type};base64,${C.source.data})`):$.log(`Unsupported image type ${C.source.type}`,C.source):$.log(`Unsupported block type ${C?.type}`)}),L=k.join(`
11
11
 
12
12
  `)}j&&L&&(L=`\`\`\`
13
13
  ${L.trim()}
14
- \`\`\``),R({title:S,message:L},!0);break}case"thinking":{l.thinking&&R({title:"Thinking",message:l.thinking},!0);break}default:$.log(`Message content type is not supported ${l.type}`,l)}}):m?.type==="result"&&(_=m.duration_ms||0,m.is_error?E=m.result:g=m.result,[c,p].forEach(l=>{l[l.length-1]?.message===g&&l.pop()}))}),await A.catch(I=>{({error:E,result:g}=mr({catchError:I,runCmd:A,error:E,result:g,runnerName:"Claude"}))}),w.close(),v.flush(),{steps:c,duration:_,result:await Q({initialResult:g,agentName:yt,hasError:!!E}),error:ee({error:E,agentName:yt}),isRetryableError:te(E)}}var _t=async()=>{let e=Ee.join(fr.homedir(),".claude");await dr.rm(e,{recursive:!0,force:!0})};import hr from"fs/promises";import Er from"os";import ke from"path";import V from"process";import yr from"readline";var W=y("runner_codex"),Tt="Codex CLI",_r=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(W.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?(W.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}):(W.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function Ge({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:a,modelVersionOverrides:u}=e,{model:i}=e;if(n){let{token:R,url:w}=n;if(!R||!w)throw new Error("No token or url provided from AI Gateway");if(u?.codex){let I=u?.codex?.[s];if(I){if(!await n.isModelAvailableForProvider("openai",I))throw new Error(`Model override '${I}' is not available for openai provider`);i=I}}else if(i&&!await n.isModelAvailableForProvider("openai",i))throw new Error(`Model '${i}' is not available for openai provider`);V.env.OPENAI_API_KEY=R,V.env.OPENAI_BASE_URL=w}else if(!V.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let p=[],c=[],d={},f=0,_=0,g,E,T=ke.join(V.cwd(),"node_modules"),N=[ke.join(V.env.NODE_PATH||T,".bin/codex"),"--approval-mode","full-auto",n?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...i?["--model",i]:[],"-q",a].filter(Boolean),x=`${V.env.NVM_BIN}/node`;W.log(`Running ${x} ${N.join(" ")}`);let A=t.utils.run(x,N,{all:!0,env:{...V.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),v=yr.createInterface({input:A.all});return v.on("error",R=>{W.error("Readline interface error",{error:R.message,stack:R.stack})}),v.on("line",R=>{let w=null;try{w=JSON.parse(R)}catch{W.log("Could not parse line",R);return}let I=[],m=!1;if(w?.duration_ms&&(_=w.duration_ms,m=!0),w?.type==="local_shell_call")d[w.call_id]=w;else if(w?.type==="local_shell_call_output"){let l=wr(d[w.call_id],w);l&&(l.id=f,f+=1,c.push(l),p.push(l),I.push(l),m=!0)}else w?.type==="message"&&w.role==="assistant"?g=w.content.map(l=>l.text).join(`
15
- `):w?.type==="message"&&w.role==="system"&&(E=w.content.map(l=>l.text).join(`
16
- `));m&&(r?.({steps:p,duration:_}),o?.({steps:I,duration:_}))}),await A.catch(R=>{let w=_r({catchError:R,runCmd:A,error:E,result:g,runnerName:"Codex"});E=w.error,g=w.result}),v.close(),{steps:c,duration:_,result:await Q({initialResult:g,agentName:Tt,hasError:!!E}),error:ee({error:E,agentName:Tt}),isRetryableError:te(E)}}var wt=async()=>{let e=ke.join(Er.homedir(),".codex");await hr.rm(e,{recursive:!0,force:!0})},Tr=new Set(["bash","-lc"]),wr=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!Tr.has(s)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
14
+ \`\`\``),R({title:S,message:L},!0);break}case"thinking":{l.thinking&&R({title:"Thinking",message:l.thinking},!0);break}default:$.log(`Message content type is not supported ${l.type}`,l)}}):m?.type==="result"&&(y=m.duration_ms||0,m.is_error?g=m.result:I=m.result,[c,f].forEach(l=>{l[l.length-1]?.message===I&&l.pop()}))}),await A.catch(w=>{({error:g,result:I}=mr({catchError:w,runCmd:A,error:g,result:I,runnerName:"Claude"}))}),_.close(),v.flush(),{steps:c,duration:y,result:await Q({initialResult:I,agentName:yt,hasError:!!g}),error:ee({error:g,agentName:yt}),isRetryableError:te(g)}}var _t=async()=>{let e=Ee.join(fr.homedir(),".claude");await dr.rm(e,{recursive:!0,force:!0})};import hr from"fs/promises";import Er from"os";import ke from"path";import V from"process";import yr from"readline";var W=E("runner_codex"),Tt="Codex CLI",_r=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(W.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?(W.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}):(W.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function Ge({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:a,modelVersionOverrides:u}=e,{model:i}=e;if(n){let{token:R,url:_}=n;if(!R||!_)throw new Error("No token or url provided from AI Gateway");if(u?.codex){let w=u?.codex?.[s];if(w){if(!await n.isModelAvailableForProvider("openai",w))throw new Error(`Model override '${w}' is not available for openai provider`);i=w}}else if(i&&!await n.isModelAvailableForProvider("openai",i))throw new Error(`Model '${i}' is not available for openai provider`);V.env.OPENAI_API_KEY=R,V.env.OPENAI_BASE_URL=_}else if(!V.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let f=[],c=[],p={},d=0,y=0,I,g,T=ke.join(V.cwd(),"node_modules"),N=[ke.join(V.env.NODE_PATH||T,".bin/codex"),"--approval-mode","full-auto",n?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...i?["--model",i]:[],"-q",a].filter(Boolean),x=`${V.env.NVM_BIN}/node`;W.log(`Running ${x} ${N.join(" ")}`);let A=t.utils.run(x,N,{all:!0,env:{...V.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),v=yr.createInterface({input:A.all});return v.on("error",R=>{W.error("Readline interface error",{error:R.message,stack:R.stack})}),v.on("line",R=>{let _=null;try{_=JSON.parse(R)}catch{W.log("Could not parse line",R);return}let w=[],m=!1;if(_?.duration_ms&&(y=_.duration_ms,m=!0),_?.type==="local_shell_call")p[_.call_id]=_;else if(_?.type==="local_shell_call_output"){let l=wr(p[_.call_id],_);l&&(l.id=d,d+=1,c.push(l),f.push(l),w.push(l),m=!0)}else _?.type==="message"&&_.role==="assistant"?I=_.content.map(l=>l.text).join(`
15
+ `):_?.type==="message"&&_.role==="system"&&(g=_.content.map(l=>l.text).join(`
16
+ `));m&&(r?.({steps:f,duration:y}),o?.({steps:w,duration:y}))}),await A.catch(R=>{let _=_r({catchError:R,runCmd:A,error:g,result:I,runnerName:"Codex"});g=_.error,I=_.result}),v.close(),{steps:c,duration:y,result:await Q({initialResult:I,agentName:Tt,hasError:!!g}),error:ee({error:g,agentName:Tt}),isRetryableError:te(g)}}var wt=async()=>{let e=ke.join(Er.homedir(),".codex");await hr.rm(e,{recursive:!0,force:!0})},Tr=new Set(["bash","-lc"]),wr=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!Tr.has(s)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
17
17
  ${n.trim()}
18
- \`\`\``)}catch(s){W.error("Could not decode outputMsg",s,t.output)}return{title:o,message:n}};import Ir from"fs/promises";import Rr from"os";import ye from"path";import B from"process";import Nr from"readline";var re=y("runner_gemini"),It="Gemini CLI",xr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(re.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?(re.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}):(re.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),vr={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 Me({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:a,modelVersionOverrides:u}=e,{model:i}=e;if(n){let{token:m,url:l}=n;if(!m||!l)throw new Error("No token or url provided from AI Gateway");if(u?.gemini){let h=u?.gemini?.[s];if(h){if(!await n.isModelAvailableForProvider("gemini",h))throw new Error(`Model override '${h}' is not available for gemini provider`);i=h}}else if(i&&!await n.isModelAvailableForProvider("gemini",i))throw new Error(`Model '${i}' is not available for gemini provider`);B.env.GEMINI_API_KEY=m,B.env.GOOGLE_GEMINI_BASE_URL=l}else if(!B.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let p=[],c=[],d=[],f={},_=0,g=0,E,T,N=ye.join(B.cwd(),"node_modules"),x=[ye.join(B.env.NODE_PATH||N,".bin/gemini"),...i?["--model",i]:[],"--yolo","-p",a],A=`${B.env.NVM_BIN}/node`;re.log(`Running ${A} ${x.join(" ")}`);let v=t.utils.run(A,x,{all:!0,env:B.env});v.stdin?.end();let R=ge(()=>{r?.({steps:p,duration:g}),o?.({steps:c,duration:g}),c=[]},250),w=(m,l)=>{m.id=_,_+=1,d.push(m),p.push(m),c.push(m),l||R.flush(),R(),l&&R.flush()},I=Nr.createInterface({input:v.all});return I.on("error",m=>{re.error("Readline interface error",{error:m.message,stack:m.stack})}),I.on("line",m=>{let l=null;try{if(m.startsWith("[API Error")){let h=m.match(/\[api error: (.+?)]$/i)?.[1];l={type:"error",value:me(h,!1)?.error?.message||h||"Gemini encountered error"}}else l=JSON.parse(m)}catch{return}if(l)switch(l.type){case"thought":{let h=l.value;w({title:h?.subject??"Thinking...",message:h?.description},!0);break}case"content":{l.value&&w({message:l.value});break}case"tool_call_request":{let h=l.value,S=vr[h.name]??h.name,j=h.args?.path||h.args?.absolute_path,L=j&&ye.relative(B.cwd(),j),k=h.args?.command,Mt={title:[S,L&&`\`${L}\``,k&&`\`${k}\``].filter(Boolean).join(" ")};f[h.callId]=Mt,R.flush();break}case"tool_result":{let h=l.value,S=f[h.callId];if(S){let j=[h.resultDisplay,h.responseParts?.functionResponse?.response?.output].find(L=>typeof L=="string"&&L);j&&(S.message=`\`\`\`
18
+ \`\`\``)}catch(s){W.error("Could not decode outputMsg",s,t.output)}return{title:o,message:n}};import Ir from"fs/promises";import Rr from"os";import ye from"path";import B from"process";import Nr from"readline";var re=E("runner_gemini"),It="Gemini CLI",xr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(re.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?(re.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}):(re.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),vr={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 Me({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:a,modelVersionOverrides:u}=e,{model:i}=e;if(n){let{token:m,url:l}=n;if(!m||!l)throw new Error("No token or url provided from AI Gateway");if(u?.gemini){let h=u?.gemini?.[s];if(h){if(!await n.isModelAvailableForProvider("gemini",h))throw new Error(`Model override '${h}' is not available for gemini provider`);i=h}}else if(i&&!await n.isModelAvailableForProvider("gemini",i))throw new Error(`Model '${i}' is not available for gemini provider`);B.env.GEMINI_API_KEY=m,B.env.GOOGLE_GEMINI_BASE_URL=l}else if(!B.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let f=[],c=[],p=[],d={},y=0,I=0,g,T,N=ye.join(B.cwd(),"node_modules"),x=[ye.join(B.env.NODE_PATH||N,".bin/gemini"),...i?["--model",i]:[],"--yolo","-p",a],A=`${B.env.NVM_BIN}/node`;re.log(`Running ${A} ${x.join(" ")}`);let v=t.utils.run(A,x,{all:!0,env:B.env});v.stdin?.end();let R=ge(()=>{r?.({steps:f,duration:I}),o?.({steps:c,duration:I}),c=[]},250),_=(m,l)=>{m.id=y,y+=1,p.push(m),f.push(m),c.push(m),l||R.flush(),R(),l&&R.flush()},w=Nr.createInterface({input:v.all});return w.on("error",m=>{re.error("Readline interface error",{error:m.message,stack:m.stack})}),w.on("line",m=>{let l=null;try{if(m.startsWith("[API Error")){let h=m.match(/\[api error: (.+?)]$/i)?.[1];l={type:"error",value:me(h,!1)?.error?.message||h||"Gemini encountered error"}}else l=JSON.parse(m)}catch{return}if(l)switch(l.type){case"thought":{let h=l.value;_({title:h?.subject??"Thinking...",message:h?.description},!0);break}case"content":{l.value&&_({message:l.value});break}case"tool_call_request":{let h=l.value,S=vr[h.name]??h.name,j=h.args?.path||h.args?.absolute_path,L=j&&ye.relative(B.cwd(),j),k=h.args?.command,Mt={title:[S,L&&`\`${L}\``,k&&`\`${k}\``].filter(Boolean).join(" ")};d[h.callId]=Mt,R.flush();break}case"tool_result":{let h=l.value,S=d[h.callId];if(S){let j=[h.resultDisplay,h.responseParts?.functionResponse?.response?.output].find(L=>typeof L=="string"&&L);j&&(S.message=`\`\`\`
19
19
  ${j.trim()}
20
- \`\`\``),w(S,!0)}break}case"result":{g=l.duration_ms,E=l.value,[d,p,c].forEach(h=>{h[h.length-1]?.message===E&&h.pop()});break}case"error":{T=l.value;break}case"finished":break;default:{re.warn("Unhandled message type:",l.type);break}}}),await v.catch(m=>{({error:T,result:E}=xr({catchError:m,runCmd:v,error:T,result:E,runnerName:"Gemini"}))}),I.close(),R.flush(),{steps:d,duration:g,result:await Q({initialResult:E,agentName:It,hasError:!!T}),error:ee({error:T,agentName:It}),isRetryableError:te(T)}}var Rt=async()=>{let e=ye.join(Rr.homedir(),".gemini");await Ir.rm(e,{recursive:!0,force:!0})};var Ar={codex:{runner:Ge,clean:wt},claude:{runner:Ue,clean:_t},gemini:{runner:Me,clean:Rt}},Nt=Ar;var xt=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>await b(Sr(),"init-stage",async n=>{let s=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=Nt[e.runner];if(!a)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let u=Cr({apiToken:r});ze(u);let i=e.useGateway?await rt({netlify:u,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!i}),e.validateAgent&&e.errorLogsPath&&n?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let p=pt(({steps:f=[],duration:_})=>{let g=f.map(E=>({...E,title:E.title?M(E.title):void 0,message:E.message?M(E.message):void 0}));return f.length=0,G(e.id,e.sessionId,{steps:g,duration:_})},t),c;e.hasRepo?e.sha?(c=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(c=await ht(u),await de(e.id,{sha:c}),n?.setAttributes({"init.sha.source":"current_commit"})):(c=await Et(u),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let d=performance.now()-s;return n?.setAttributes({"init.sha":c||"unknown","init.duration.ms":d,"init.status":"success"}),{aiGateway:i,context:u,persistSteps:p,runner:a,sha:c}}),Cr=({apiToken:e})=>({constants:{NETLIFY_API_HOST:_e.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||_e.env.NETLIFY_API_TOKEN,SITE_ID:_e.env.SITE_ID,FUNCTIONS_DIST:_e.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:it}});import{getTracer as je}from"@netlify/otel";import br from"crypto";import H from"fs/promises";import D from"path";import U from"process";var P=y("context"),Pr=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:U.env.NETLIFY_TEAM_ID,userId:U.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:U.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},Or=10,Dr=async e=>{let{name:t,ext:r}=D.parse(e),o=e,n=D.join(U.cwd(),F,o),s=0;for(;await Lr(n);){if(s>=Or)throw new Error("Failed to generate context file");o=`${t}-${br.randomUUID().slice(0,5)}${r}`,n=D.join(U.cwd(),F,o),s+=1}return o},Lr=async e=>{try{return await H.access(e),!0}catch{return!1}},Fr=async()=>{try{P.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 P.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"?(P.warn("Catchall consumer missing or invalid contextScopes"),null):r:(P.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?P.warn("Netlify features context request timed out"):P.warn("Failed to fetch Netlify features context:",e.message),null}},$r=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 H.writeFile(t,o,"utf-8"),!0}catch(r){return r.name==="AbortError"?P.warn(`Download timeout for ${e}`):P.warn(`Failed to download context file ${e}:`,r.message),!1}},Te=null,Ur=async()=>{if(Te)return Te;let e=await Fr();if(!e)return[];let t=D.join(U.cwd(),F,Ce);await H.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([n,s])=>{if(!s||typeof s!="object"||!s.endpoint||!s.scope)return P.warn(`Invalid scope data for ${n}, skipping...`),null;let a=`${n}.md`,u=D.join(t,a),i=D.join(F,Ce,a);return P.log(`Downloading ${s.scope} context...`),await $r(s.endpoint,u)?(P.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:n}):null});return Te=(await Promise.all(r)).filter(n=>n!==null),Te},vt=async({cliPath:e,netlify:t,config:r,buildErrorContext:o})=>{let n=Pr(t),s=await Dr(lt),a=D.join(U.cwd(),F);await H.mkdir(a,{recursive:!0});let u=D.join(F,s),i=D.join(U.cwd(),u),p=D.join(U.cwd(),F,Z);try{await H.unlink(p),P.log(`Deleted old results file: ${p}`)}catch{}let c=o?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
20
+ \`\`\``),_(S,!0)}break}case"result":{I=l.duration_ms,g=l.value,[p,f,c].forEach(h=>{h[h.length-1]?.message===g&&h.pop()});break}case"error":{T=l.value;break}case"finished":break;default:{re.warn("Unhandled message type:",l.type);break}}}),await v.catch(m=>{({error:T,result:g}=xr({catchError:m,runCmd:v,error:T,result:g,runnerName:"Gemini"}))}),w.close(),R.flush(),{steps:p,duration:I,result:await Q({initialResult:g,agentName:It,hasError:!!T}),error:ee({error:T,agentName:It}),isRetryableError:te(T)}}var Rt=async()=>{let e=ye.join(Rr.homedir(),".gemini");await Ir.rm(e,{recursive:!0,force:!0})};var Ar={codex:{runner:Ge,clean:wt},claude:{runner:Ue,clean:_t},gemini:{runner:Me,clean:Rt}},Nt=Ar;var xt=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>await b(Sr(),"init-stage",async n=>{let s=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=Nt[e.runner];if(!a)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let u=Cr({apiToken:r});ze(u);let i=e.useGateway?await rt({netlify:u,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!i}),e.validateAgent&&e.errorLogsPath&&n?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let f=pt(({steps:d=[],duration:y})=>{let I=d.map(g=>({...g,title:g.title?M(g.title):void 0,message:g.message?M(g.message):void 0}));return d.length=0,G(e.id,e.sessionId,{steps:I,duration:y})},t),c;e.hasRepo?e.sha?(c=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(c=await ht(u),await de(e.id,{sha:c}),n?.setAttributes({"init.sha.source":"current_commit"})):(c=await Et(u),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let p=performance.now()-s;return n?.setAttributes({"init.sha":c||"unknown","init.duration.ms":p,"init.status":"success"}),{aiGateway:i,context:u,persistSteps:f,runner:a,sha:c}}),Cr=({apiToken:e})=>({constants:{NETLIFY_API_HOST:_e.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||_e.env.NETLIFY_API_TOKEN,SITE_ID:_e.env.SITE_ID,FUNCTIONS_DIST:_e.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:it}});import{getTracer as je}from"@netlify/otel";import br from"crypto";import H from"fs/promises";import D from"path";import U from"process";var P=E("context"),Pr=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:U.env.NETLIFY_TEAM_ID,userId:U.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:U.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},Or=10,Dr=async e=>{let{name:t,ext:r}=D.parse(e),o=e,n=D.join(U.cwd(),F,o),s=0;for(;await Lr(n);){if(s>=Or)throw new Error("Failed to generate context file");o=`${t}-${br.randomUUID().slice(0,5)}${r}`,n=D.join(U.cwd(),F,o),s+=1}return o},Lr=async e=>{try{return await H.access(e),!0}catch{return!1}},Fr=async()=>{try{P.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 P.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"?(P.warn("Catchall consumer missing or invalid contextScopes"),null):r:(P.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?P.warn("Netlify features context request timed out"):P.warn("Failed to fetch Netlify features context:",e.message),null}},$r=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 H.writeFile(t,o,"utf-8"),!0}catch(r){return r.name==="AbortError"?P.warn(`Download timeout for ${e}`):P.warn(`Failed to download context file ${e}:`,r.message),!1}},Te=null,Ur=async()=>{if(Te)return Te;let e=await Fr();if(!e)return[];let t=D.join(U.cwd(),F,Ce);await H.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([n,s])=>{if(!s||typeof s!="object"||!s.endpoint||!s.scope)return P.warn(`Invalid scope data for ${n}, skipping...`),null;let a=`${n}.md`,u=D.join(t,a),i=D.join(F,Ce,a);return P.log(`Downloading ${s.scope} context...`),await $r(s.endpoint,u)?(P.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:n}):null});return Te=(await Promise.all(r)).filter(n=>n!==null),Te},vt=async({cliPath:e,netlify:t,config:r,buildErrorContext:o})=>{let n=Pr(t),s=await Dr(lt),a=D.join(U.cwd(),F);await H.mkdir(a,{recursive:!0});let u=D.join(F,s),i=D.join(U.cwd(),u),f=D.join(U.cwd(),F,Z);try{await H.unlink(f),P.log(`Deleted old results file: ${f}`)}catch{}let c=o?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
21
21
  Your task is to analyze and fix the build errors.
22
22
  Don't apply techniques of reverting changes. Apply fixes related to errors.
23
23
  Don't try to run build by yourself. Just fix the errors.
24
24
 
25
25
  <build_error_context>
26
26
  ${o}
27
- </build_error_context>`:"",d="";r.siteContext&&r.siteContext.length!==0&&(d=`
27
+ </build_error_context>`:"",p="";r.siteContext&&r.siteContext.length!==0&&(p=`
28
28
  <project_rules>
29
29
  ${r.siteContext.filter(T=>T.site_context).map(T=>typeof T.site_context=="string"?T.site_context:typeof T.site_context=="object"?JSON.stringify(T.site_context):"").join(`
30
30
 
31
31
  `)}
32
32
  </project_rules>
33
- `);let f="";if(r.sessionHistoryContext?.length){let T=D.join(U.cwd(),F,Se);await H.mkdir(T,{recursive:!0});let N=await Promise.all(r.sessionHistoryContext.map(async(x,A)=>{let v=A+1,R=`attempt-${v}.md`,w=D.join(T,R),I=D.join(F,Se,R),m=`# Task History - Attempt ${v}
33
+ `);let d="";if(r.sessionHistoryContext?.length){let T=D.join(U.cwd(),F,Se);await H.mkdir(T,{recursive:!0});let N=await Promise.all(r.sessionHistoryContext.map(async(x,A)=>{let v=A+1,R=`attempt-${v}.md`,_=D.join(T,R),w=D.join(F,Se,R),m=`# Task History - Attempt ${v}
34
34
 
35
35
  ## Request - what the user asked for
36
36
  ${x.request}
@@ -40,7 +40,7 @@ ${x.request}
40
40
  ## Response - what the agent replied with after its work
41
41
 
42
42
  ${x.response}
43
- `;return await H.writeFile(w,m,"utf-8"),P.log(`Created history file: ${I}`),I}));f+=`
43
+ `;return await H.writeFile(_,m,"utf-8"),P.log(`Created history file: ${w}`),w}));d+=`
44
44
  <session_history_context>
45
45
  History of prior work on this task.
46
46
  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.
@@ -49,17 +49,17 @@ ${x.response}
49
49
  `)}
50
50
 
51
51
  </session_history_context>
52
- `}let _=await Ur(),g="";_.length>0&&(g=`
52
+ `}let y=await Ur(),I="";y.length>0&&(I=`
53
53
  <netlify_features_context>
54
54
  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.
55
55
  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.
56
56
 
57
- ${_.map(T=>`- **${T.scope}**: ${T.path}`).join(`
57
+ ${y.map(T=>`- **${T.scope}**: ${T.path}`).join(`
58
58
  `)}
59
59
 
60
60
  Refer to these files when working with specific Netlify features.
61
61
  </netlify_features_context>
62
- `);let E=`
62
+ `);let g=`
63
63
  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.
64
64
 
65
65
  <request>
@@ -82,7 +82,7 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
82
82
  - for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${a}/${be} folder
83
83
  - move assets from ${a}/${be} folder to the project assets folder if they are referenced in a code or applied changes
84
84
  </attachements>
85
- ${d}
85
+ ${p}
86
86
  </requirements>
87
87
 
88
88
  <extra_context>
@@ -99,15 +99,15 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
99
99
  - 'netlify-cli' npm package is already available as a global package. Don't try to install it again
100
100
  - 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.
101
101
  </environment>
102
- ${g}
102
+ ${I}
103
103
  <docs>
104
104
  - Netlify Docs: https://docs.netlify.com
105
105
  - LLM Resources Index: https://docs.netlify.com/llms.txt
106
106
  </docs>
107
107
  </extra_context>
108
108
 
109
- ${f}
110
- `;return await H.writeFile(i,E,"utf-8"),P.log(`Generated agent context document at: ${i}`),E.length>5e5&&(E=`
109
+ ${d}
110
+ `;return await H.writeFile(i,g,"utf-8"),P.log(`Generated agent context document at: ${i}`),g.length>5e5&&(g=`
111
111
  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.
112
112
 
113
113
  <request>
@@ -118,15 +118,15 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
118
118
  </request>
119
119
 
120
120
  Use the following file for the complete context of the ask, the environment, and what's available. ${i} You MUST READ ALL OF IT. Make sure to read it first. Never cite or paraphrase private context.
121
- `),E};var kr=y("prompt"),At=async({cliPath:e,config:t,netlify:r,buildErrorContext:o})=>{let n=await vt({cliPath:e,config:t,netlify:r,buildErrorContext:o});return process.env.AGENT_RUNNER_DEBUG&&kr.log("Contextful Prompt:",n),{prompt:n}};var we=y("inference_stage"),St=5,Ie=async e=>await b(je(),"inference-stage",async t=>{let{cliPath:r,config:o,context:n,buildErrors:s,runner:a,persistSteps:u,aiGateway:i,attempt:p,contextPrefix:c}=e;t?.setAttributes({"inference.attempt":p}),we.log(`Running inference stage, attempt ${p} of ${St}`),nt();let{prompt:d}=await b(je(),"compose-prompt",async()=>await At({cliPath:r,config:o,buildErrorContext:Gr(s),netlify:n})),f=`
122
- ${c||""}
121
+ `),g};var kr=E("prompt"),At=async({cliPath:e,config:t,netlify:r,buildErrorContext:o})=>{let n=await vt({cliPath:e,config:t,netlify:r,buildErrorContext:o});return process.env.AGENT_RUNNER_DEBUG&&kr.log("Contextful Prompt:",n),{prompt:n}};var we=E("inference_stage"),St=5,Ie=async e=>{let{cliPath:t,config:r,context:o,buildErrors:n,runner:s,persistSteps:a,aiGateway:u,attempt:i,contextPrefix:f}=e;we.log(`Running inference stage, attempt ${i} of ${St}`);let c=await b(je(),"inference-stage",async p=>{p?.setAttributes({"inference.attempt":i||1}),nt();let{prompt:d}=await b(je(),"compose-prompt",async()=>await At({cliPath:t,config:r,buildErrorContext:Gr(n),netlify:o})),y=`
122
+ ${f||""}
123
123
  ${d}
124
- `.trim(),_={...o,prompt:f},g=await b(je(),`run-${o.runner}`,async()=>await a({aiGateway:i,config:_,netlify:n,persistSteps:u}));if(g.result&&(g.result=M(g.result)),g.error&&(g.error=M(g.error)),await u.flush(),g.error){if(we.error("Runner failed",{stepsCount:g.steps.length,duration:g.duration,error:g.error,isRetryableError:g.isRetryableError,attempt:p||1}),g.isRetryableError&&(!p||p<St))return we.log("Retrying inference stage"),await new Promise(T=>setTimeout(T,5e3)),{runnerResult:(await Ie({...e,attempt:(p||1)+1,contextPrefix:"<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 we.log("Do not retry inference stage"),new Error(g.error)}return{runnerResult:g}}),Gr=e=>!e||e.length===0?"":`
124
+ `.trim(),I={...r,prompt:y},g=await b(je(),`run-${r.runner}`,async()=>await s({aiGateway:u,config:I,netlify:o,persistSteps:a}));return g.result&&(g.result=M(g.result)),g.error&&(g.error=M(g.error)),await a.flush(),g});if(c.error){if(we.error("Runner failed",{stepsCount:c.steps.length,duration:c.duration,error:c.error,isRetryableError:c.isRetryableError,attempt:i||1}),c.isRetryableError&&(!i||i<St))return we.log("Retrying inference stage"),await new Promise(d=>setTimeout(d,5e3)),{runnerResult:(await Ie({...e,attempt:(i||1)+1,contextPrefix:"<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 we.log("Do not retry inference stage"),new Error(c.error)}return{runnerResult:c}},Gr=e=>!e||e.length===0?"":`
125
125
  Deploy failed failed. Here are the errors to review on the latest build:
126
126
 
127
127
  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.
128
128
 
129
129
  ${e.pop()}
130
- `;import Yr from"process";import{getTracer as Ye}from"@netlify/otel";import{getTracer as Mr}from"@netlify/otel";var ie=y("deploy"),Ct=async e=>await b(Mr(),"create-preview-deploy",async t=>jr(e,t)),jr=async({netlify:e,hasRepo:t,skipBuild:r,message:o="Agent Preview",deploySubdomain:n,cliPath:s,filter:a},u)=>{try{let i=["deploy","--message",`"${o}"`,"--json","--draft","--verbose"];t||(ie.log("Deploy: Uploading source zip"),i.push("--upload-source-zip")),n&&i.push("--alias",n),a&&i.push("--filter",a),r?(ie.log("Deploy: Skipping build"),i.push("--no-build")):i.push("--context","deploy-preview");let p=s||"netlify";ie.log(`Running: ${p} ${i.join(" ")}`),u?.setAttributes({cmd:p,args:i});let c=await e.utils.run(p,i,{stdio:["ignore","pipe","pipe"]}),d=JSON.parse(c.stdout.trim());u?.setAttributes({success:!0,deployId:d.deploy_id,deployUrl:d.deploy_url,siteId:d.site_id}),ie.log(`
131
- Preview deploy created successfully:`,{deployId:d.deploy_id,deployUrl:d.deploy_url,siteId:d.site_id});let f={deployId:d.deploy_id,previewUrl:d.deploy_url,logsUrl:d.logs,siteId:d.site_id};return t||(f.sourceZipFilename=d.source_zip_filename),f}catch(i){throw ie.error("Failed to create preview deploy via CLI:",i),u?.setAttributes({success:!1,error:i.message}),i}};var ae=y("deploy_stage"),Be=async e=>await b(Ye(),"run-deploy-stage",async()=>Br(e)),Br=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let s=await b(Ye(),"get-runner-diffs",async()=>await mt({config:t,netlify:r}));if(ae.info("Resolved git",{hasChanges:s.hasChanges,ignored:s.ignored??[]}),!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:u,diffBinary:i,resultDiffBinary:p}=s,c=!0;ae.log("Preview deploy condition check:",{resultUndefined:o===void 0,resultType:typeof o,hasChanges:c,wouldCreatePreview:o!==void 0&&c});let d=null;if(o!==void 0&&c)try{let f;try{let _=await b(Ye(),"get-runner-session",async()=>await Qe(t.id,t.sessionId));_?.title&&(f=_.title)}catch(_){ae.warn("Failed to fetch session title, using fallback message:",_.message)}await G(t.id,t.sessionId,{steps:[{title:"Deploying the run preview"}]}),d=await Ct({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:f,skipBuild:!1,deploySubdomain:dt(t.id,Yr.env.SITE_NAME),filter:n})}catch(f){return ae.warn("Failed to create preview deploy (continuing with agent run):",f),{diff:a,resultDiff:u,hasChanges:c,previewInfo:null,diffBinary:i,resultDiffBinary:p,deployError:f instanceof Error?f.message:String(f)}}return ae.log("Git status",{hasDiff:!!a,hasChanges:c}),{diff:a,resultDiff:u,hasChanges:c,previewInfo:d,diffBinary:i,resultDiffBinary:p}};import{getTracer as He}from"@netlify/otel";async function bt(e,t){let{maxRetries:r,baseDelay:o,onRetry:n}=t,s;for(let a=1;a<=r;a++)try{return await e()}catch(u){if(s=u,a===r)throw s;n&&n(a,s),await new Promise(i=>setTimeout(i,o*a))}throw s}var ne=y("cleanup_stage"),Pt=async e=>await b(He(),"cleanup-stage",async()=>Hr(e)),Hr=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:s,resultDiffBinary:a,previewInfo:u})=>{let i={result_diff:t,result:r||"Done",duration:o,result_diff_binary:s};return u&&u.deployId&&(i.deploy_id=u.deployId),u&&u.sourceZipFilename&&(i.result_zip_file_name=u.sourceZipFilename),n||a?(i.cumulative_diff=n,i.cumulative_diff_binary=a,ne.log("Updating total agent result diff"),await b(He(),"update-runner",async()=>{await de(e.id,{result_diff:n,result_diff_binary:a})})):ne.log("No total result diff, not updating"),ne.log("Updated agent runner with result"),await bt(async()=>await b(He(),"update-runner-session",()=>G(e.id,e.sessionId,i)),{maxRetries:3,baseDelay:1e3,onRetry:(p,c)=>{ne.error(`Error updating agent runner session (attempt ${p}):`,c),ne.log("Retrying...")}}),ne.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as Ot,shutdownTracers as Kr,withActiveSpan as Dt}from"@netlify/otel";var Vr=qr(import.meta.url),Lt=Vr("../package.json"),Ft=y("pipeline_index"),Re=3,$t=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:s,tracing:a={}})=>{let u,{withStageTimer:i}=ot(q.timeUnits.hours(4)),p=await Je(Lt.version,e.id,a);try{await Dt(Ot(),"run-pipeline",{},p,async()=>{let c,{aiGateway:d,context:f,persistSteps:_,runner:g,sha:E}=await i("init",()=>xt({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:s,runnerVersion:Lt.version}),q.timeUnits.minutes(10));u=g.clean,e.sha=E;let{runnerResult:T}=await i("inference",()=>Ie({cliPath:r,config:e,context:f,runner:g.runner,persistSteps:_,aiGateway:d}));await G(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let N=await i("deploy",()=>Be({cliPath:r,config:e,context:f,result:T.result,filter:s})),x=T,A=[];if(N.hasChanges&&N.deployError){A.push(Xe(N.deployError));let l=1;for(;l<=Re&&!N.previewInfo;)Ft.log(`Deploy attempt had errors. Retrying. ${l}/${Re}`),await Dt(Ot(),"deploy-stage",async h=>{h?.setAttributes({"stage.attempt":l});let{runnerResult:S}=await i(`inference-retry-${l}`,()=>Ie({cliPath:r,config:e,context:f,runner:g.runner,persistSteps:_,aiGateway:d,buildErrors:A}));x={...S,steps:[...x.steps||[],...S.steps||[]],duration:(x.duration||0)+(S.duration||0)},N=await i(`deploy-retry-${l}`,()=>Be({cliPath:r,config:e,context:f,result:S.result,filter:s})),N.deployError&&A.push(N.deployError),l++});l>Re&&!N.previewInfo&&(c=new Error(`Deploy validation failed after ${Re} attempts`))}let{diff:v,resultDiff:R,previewInfo:w,diffBinary:I,resultDiffBinary:m}=N;if(await i("cleanup",()=>Pt({config:e,diff:v,result:x.result,duration:x.duration,resultDiff:R,diffBinary:I,resultDiffBinary:m,previewInfo:w}),q.timeUnits.minutes(10)),c)throw c;await g.clean?.()})}catch(c){Ft.error("Got error while running pipeline",c),await u?.();let d=c instanceof Error&&c.message;throw await G(e.id,e.sessionId,{result:d||"Encountered error when running agent",state:"error"}),c}finally{await Kr()}};import O from"process";var Jr="claude",Xr=e=>(e??[]).filter(t=>t.request&&t.response),zr=e=>(e??[]).filter(t=>t.site_context),Ut=y("config"),kt=()=>{let e=O.env.NETLIFY_AGENT_RUNNER_ID,t=O.env.NETLIFY_AGENT_RUNNER_SESSION_ID;if(!e||!t)throw new Error("ID of agent runner is not provided");let r=O.env.NETLIFY_AGENT_RUNNER_RESULT_BRANCH,o=O.env.NETLIFY_AGENT_RUNNER_PROMPT;if(!o)throw new Error("Prompt is not provided");let n=O.env.NETLIFY_AGENT_RUNNER_AGENT||Jr,s=O.env.NETLIFY_AGENT_RUNNER_MODEL,a=O.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED==="1",u=O.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED==="1",i=O.env.ERROR_LOGS_PATH,p=me(O.env.NETLIFY_AGENT_RUNNER_CONTEXT,!0,Ut),c=Xr(p),d=zr(p),f=O.env.NETLIFY_AGENT_RUNNER_HAS_REPO!=="0",_=!O.env.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED,g=O.env.NETLIFY_AGENT_RUNNER_SHA,E=Zr(),T=ft(),N={id:e,sessionId:t,resultBranch:r,prompt:o,runner:n,model:s,validateAgent:a,errorLogsPath:i,sessionHistoryContext:c,siteContext:d,hasRepo:f,useGateway:_,sha:g,accountType:E,validateAgentWithBuild:u,modelVersionOverrides:T};return Ut.log({fullConfig:N}),N},Zr=()=>{let e=O.env.NETLIFY_TEAM_TYPE;return e?e.includes("personal")?Oe:e.includes("pro")?"pro":e.startsWith("enterprise")?De:e.startsWith("free")?Le:Pe:Pe};var Gt=y("bin_cmd"),J=Qr(qe.argv.slice(2),{string:["auth","cwd","cli-path","error-logs-path","filter","trace-exporter-url","traceparent"]});try{let e=kt();await $t({config:e,apiToken:J.auth,cwd:J.cwd,cliPath:J["cli-path"],errorLogsPath:J["error-logs-path"],filter:J.filter,tracing:{exporterUrl:J["trace-exporter-url"],traceparent:J.traceparent}}),Gt.info("Finished agent"),qe.exit(0)}catch(e){Gt.error("Error running agent pipeline:",e),qe.exit(1)}
130
+ `;import Yr from"process";import{getTracer as Ye}from"@netlify/otel";import{getTracer as Mr}from"@netlify/otel";var ie=E("deploy"),Ct=async e=>await b(Mr(),"create-preview-deploy",async t=>jr(e,t)),jr=async({netlify:e,hasRepo:t,skipBuild:r,message:o="Agent Preview",deploySubdomain:n,cliPath:s,filter:a},u)=>{try{let i=["deploy","--message",`"${o}"`,"--json","--draft","--verbose"];t||(ie.log("Deploy: Uploading source zip"),i.push("--upload-source-zip")),n&&i.push("--alias",n),a&&i.push("--filter",a),r?(ie.log("Deploy: Skipping build"),i.push("--no-build")):i.push("--context","deploy-preview");let f=s||"netlify";ie.log(`Running: ${f} ${i.join(" ")}`),u?.setAttributes({cmd:f,args:i});let c=await e.utils.run(f,i,{stdio:["ignore","pipe","pipe"]}),p=JSON.parse(c.stdout.trim());u?.setAttributes({success:!0,deployId:p.deploy_id,deployUrl:p.deploy_url,siteId:p.site_id}),ie.log(`
131
+ Preview deploy created successfully:`,{deployId:p.deploy_id,deployUrl:p.deploy_url,siteId:p.site_id});let d={deployId:p.deploy_id,previewUrl:p.deploy_url,logsUrl:p.logs,siteId:p.site_id};return t||(d.sourceZipFilename=p.source_zip_filename),d}catch(i){throw ie.error("Failed to create preview deploy via CLI:",i),u?.setAttributes({success:!1,error:i.message}),i}};var ae=E("deploy_stage"),Be=async e=>await b(Ye(),"run-deploy-stage",async()=>Br(e)),Br=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let s=await b(Ye(),"get-runner-diffs",async()=>await mt({config:t,netlify:r}));if(ae.info("Resolved git",{hasChanges:s.hasChanges,ignored:s.ignored??[]}),!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:u,diffBinary:i,resultDiffBinary:f}=s,c=!0;ae.log("Preview deploy condition check:",{resultUndefined:o===void 0,resultType:typeof o,hasChanges:c,wouldCreatePreview:o!==void 0&&c});let p=null;if(o!==void 0&&c)try{let d;try{let y=await b(Ye(),"get-runner-session",async()=>await Qe(t.id,t.sessionId));y?.title&&(d=y.title)}catch(y){ae.warn("Failed to fetch session title, using fallback message:",y.message)}await G(t.id,t.sessionId,{steps:[{title:"Deploying the run preview"}]}),p=await Ct({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:d,skipBuild:!1,deploySubdomain:dt(t.id,Yr.env.SITE_NAME),filter:n})}catch(d){return ae.warn("Failed to create preview deploy (continuing with agent run):",d),{diff:a,resultDiff:u,hasChanges:c,previewInfo:null,diffBinary:i,resultDiffBinary:f,deployError:d instanceof Error?d.message:String(d)}}return ae.log("Git status",{hasDiff:!!a,hasChanges:c}),{diff:a,resultDiff:u,hasChanges:c,previewInfo:p,diffBinary:i,resultDiffBinary:f}};import{getTracer as He}from"@netlify/otel";async function bt(e,t){let{maxRetries:r,baseDelay:o,onRetry:n}=t,s;for(let a=1;a<=r;a++)try{return await e()}catch(u){if(s=u,a===r)throw s;n&&n(a,s),await new Promise(i=>setTimeout(i,o*a))}throw s}var ne=E("cleanup_stage"),Pt=async e=>await b(He(),"cleanup-stage",async()=>Hr(e)),Hr=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:s,resultDiffBinary:a,previewInfo:u})=>{let i={result_diff:t,result:r||"Done",duration:o,result_diff_binary:s};return u&&u.deployId&&(i.deploy_id=u.deployId),u&&u.sourceZipFilename&&(i.result_zip_file_name=u.sourceZipFilename),n||a?(i.cumulative_diff=n,i.cumulative_diff_binary=a,ne.log("Updating total agent result diff"),await b(He(),"update-runner",async()=>{await de(e.id,{result_diff:n,result_diff_binary:a})})):ne.log("No total result diff, not updating"),ne.log("Updated agent runner with result"),await bt(async()=>await b(He(),"update-runner-session",()=>G(e.id,e.sessionId,i)),{maxRetries:3,baseDelay:1e3,onRetry:(f,c)=>{ne.error(`Error updating agent runner session (attempt ${f}):`,c),ne.log("Retrying...")}}),ne.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as Ot,shutdownTracers as Kr,withActiveSpan as Dt}from"@netlify/otel";var Vr=qr(import.meta.url),Lt=Vr("../package.json"),Ft=E("pipeline_index"),Re=3,$t=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:s,tracing:a={}})=>{let u,{withStageTimer:i}=ot(q.timeUnits.hours(4)),f=await Je(Lt.version,e.id,a);try{await Dt(Ot(),"run-pipeline",{},f,async()=>{let c,{aiGateway:p,context:d,persistSteps:y,runner:I,sha:g}=await i("init",()=>xt({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:s,runnerVersion:Lt.version}),q.timeUnits.minutes(10));u=I.clean,e.sha=g;let{runnerResult:T}=await i("inference",()=>Ie({cliPath:r,config:e,context:d,runner:I.runner,persistSteps:y,aiGateway:p}));await G(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let N=await i("deploy",()=>Be({cliPath:r,config:e,context:d,result:T.result,filter:s})),x=T,A=[];if(N.hasChanges&&N.deployError){A.push(Xe(N.deployError));let l=1;for(;l<=Re&&!N.previewInfo;)Ft.log(`Deploy attempt had errors. Retrying. ${l}/${Re}`),await Dt(Ot(),"deploy-stage",async h=>{h?.setAttributes({"stage.attempt":l});let{runnerResult:S}=await i(`inference-retry-${l}`,()=>Ie({cliPath:r,config:e,context:d,runner:I.runner,persistSteps:y,aiGateway:p,buildErrors:A}));x={...S,steps:[...x.steps||[],...S.steps||[]],duration:(x.duration||0)+(S.duration||0)},N=await i(`deploy-retry-${l}`,()=>Be({cliPath:r,config:e,context:d,result:S.result,filter:s})),N.deployError&&A.push(N.deployError),l++});l>Re&&!N.previewInfo&&(c=new Error(`Deploy validation failed after ${Re} attempts`))}let{diff:v,resultDiff:R,previewInfo:_,diffBinary:w,resultDiffBinary:m}=N;if(await i("cleanup",()=>Pt({config:e,diff:v,result:x.result,duration:x.duration,resultDiff:R,diffBinary:w,resultDiffBinary:m,previewInfo:_}),q.timeUnits.minutes(10)),c)throw c;await I.clean?.()})}catch(c){Ft.error("Got error while running pipeline",c),await u?.();let p=c instanceof Error&&c.message;throw await G(e.id,e.sessionId,{result:p||"Encountered error when running agent",state:"error"}),c}finally{await Kr()}};import O from"process";var Jr="claude",Xr=e=>(e??[]).filter(t=>t.request&&t.response),zr=e=>(e??[]).filter(t=>t.site_context),Ut=E("config"),kt=()=>{let e=O.env.NETLIFY_AGENT_RUNNER_ID,t=O.env.NETLIFY_AGENT_RUNNER_SESSION_ID;if(!e||!t)throw new Error("ID of agent runner is not provided");let r=O.env.NETLIFY_AGENT_RUNNER_RESULT_BRANCH,o=O.env.NETLIFY_AGENT_RUNNER_PROMPT;if(!o)throw new Error("Prompt is not provided");let n=O.env.NETLIFY_AGENT_RUNNER_AGENT||Jr,s=O.env.NETLIFY_AGENT_RUNNER_MODEL,a=O.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED==="1",u=O.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED==="1",i=O.env.ERROR_LOGS_PATH,f=me(O.env.NETLIFY_AGENT_RUNNER_CONTEXT,!0,Ut),c=Xr(f),p=zr(f),d=O.env.NETLIFY_AGENT_RUNNER_HAS_REPO!=="0",y=!O.env.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED,I=O.env.NETLIFY_AGENT_RUNNER_SHA,g=Zr(),T=ft(),N={id:e,sessionId:t,resultBranch:r,prompt:o,runner:n,model:s,validateAgent:a,errorLogsPath:i,sessionHistoryContext:c,siteContext:p,hasRepo:d,useGateway:y,sha:I,accountType:g,validateAgentWithBuild:u,modelVersionOverrides:T};return Ut.log({fullConfig:N}),N},Zr=()=>{let e=O.env.NETLIFY_TEAM_TYPE;return e?e.includes("personal")?Oe:e.includes("pro")?"pro":e.startsWith("enterprise")?De:e.startsWith("free")?Le:Pe:Pe};var Gt=E("bin_cmd"),J=Qr(qe.argv.slice(2),{string:["auth","cwd","cli-path","error-logs-path","filter","trace-exporter-url","traceparent"]});try{let e=kt();await $t({config:e,apiToken:J.auth,cwd:J.cwd,cliPath:J["cli-path"],errorLogsPath:J["error-logs-path"],filter:J.filter,tracing:{exporterUrl:J["trace-exporter-url"],traceparent:J.traceparent}}),Gt.info("Finished agent"),qe.exit(0)}catch(e){Gt.error("Error running agent pipeline:",e),qe.exit(1)}
132
132
  //# sourceMappingURL=bin.js.map
package/dist/index.js CHANGED
@@ -1,35 +1,35 @@
1
- import{createRequire as Pr}from"module";import{createTracerProvider as Nt}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as Ue}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as bt}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as St}from"@netlify/otel";import{propagation as Me,context as Ge,W3CTraceContextPropagator as Ct}from"@netlify/otel/opentelemetry";import{OTLPTraceExporter as Pt}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 Te=w("tracing"),je=async(e,t,r)=>(await Nt({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new Ue(new Ie),new Ue(new Pt({url:r.exporterUrl}))],instrumentations:[new bt({skipHeaders:!0})]}),r.traceparent?(Me.setGlobalPropagator(new Ct),Me.extract(Ge.active(),{traceparent:r.traceparent,isRemote:!0})):Ge.active());function C(e,t,r){return Te.log(`\u23F3 TRACE: ${t} starting...`),St(e,t,r)}var Ie=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,i]of Object.entries(o))u.includes("duration")&&typeof i=="number"?n.push(`${u}=${i.toFixed(2)}ms`):n.push(`${u}=${i}`);let s=t.status?.code===2?"\u274C":"\u2705",l=n.length>0?` [${n.join(", ")}]`:"";Te.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${l}`),t.status?.code===2&&t.status.message&&Te.log(` \u274C Error: ${t.status.message}`)}};var Ot=["error","failed","exception","fatal","panic","abort","crash"];function Be(e){let t=e.split(`
2
- `),r=[],o=-1,n=0;for(;n<t.length;){let u=t[n].slice(0,500).toLowerCase();if(Ot.some(p=>u.includes(p))){let p=Math.max(0,n-10,o+1),c=Math.min(t.length-1,n+20),d=[];for(let f=p;f<=c;f++)d.push(t[f]);r.push(d.join(`
1
+ import{createRequire as Pr}from"module";import{createTracerProvider as Nt}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as Ue}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as bt}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as St}from"@netlify/otel";import{propagation as Me,context as Ge,W3CTraceContextPropagator as Ct}from"@netlify/otel/opentelemetry";import{OTLPTraceExporter as Pt}from"@opentelemetry/exporter-trace-otlp-grpc";function _(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 Te=_("tracing"),je=async(e,t,r)=>(await Nt({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new Ue(new Ie),new Ue(new Pt({url:r.exporterUrl}))],instrumentations:[new bt({skipHeaders:!0})]}),r.traceparent?(Me.setGlobalPropagator(new Ct),Me.extract(Ge.active(),{traceparent:r.traceparent,isRemote:!0})):Ge.active());function C(e,t,r){return Te.log(`\u23F3 TRACE: ${t} starting...`),St(e,t,r)}var Ie=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,i]of Object.entries(o))u.includes("duration")&&typeof i=="number"?n.push(`${u}=${i.toFixed(2)}ms`):n.push(`${u}=${i}`);let s=t.status?.code===2?"\u274C":"\u2705",l=n.length>0?` [${n.join(", ")}]`:"";Te.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${l}`),t.status?.code===2&&t.status.message&&Te.log(` \u274C Error: ${t.status.message}`)}};var Ot=["error","failed","exception","fatal","panic","abort","crash"];function Be(e){let t=e.split(`
2
+ `),r=[],o=-1,n=0;for(;n<t.length;){let u=t[n].slice(0,500).toLowerCase();if(Ot.some(m=>u.includes(m))){let m=Math.max(0,n-10,o+1),c=Math.min(t.length-1,n+20),p=[];for(let d=m;d<=c;d++)p.push(t[d]);r.push(p.join(`
3
3
  `)),o=c,n=c+1}else n++}if(r.length===0)return e;let s=r.map((l,u)=>`<extracted_error_chunk order="${u+1}">
4
4
  ${l}
5
5
  </extracted_error_chunk>`).join(`
6
6
 
7
- `);return s.length>e.length*.8?e:s}import he from"process";import{getTracer as mr}from"@netlify/otel";import ie from"process";var ae=ie.env.NETLIFY_API_URL,le=ie.env.NETLIFY_API_TOKEN,re=w("api"),ue=async(e,t={})=>{if(!ae||!le)throw new Error("No API URL or token");let r=new URL(e,ae),o={...t,headers:{...t.headers,Authorization:`Bearer ${le}`}};ie.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),s=n.ok&&n.status<=299;if(ie.env.AGENT_RUNNERS_DEBUG==="true")re.log(`Response headers for ${r}:`),n.headers.forEach((u,i)=>{re.log(` ${i}: ${u}`)});else{let u=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");re.log(`Request ID for ${r}: ${u||"N/A"}`)}if(s||re.error(`Got status ${n.status} for request ${r}`),t.raw){if(!s)throw n;return n}let l=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!s)throw l;return l},Ye=e=>{re.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(ae=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(le=e.constants.NETLIFY_API_TOKEN)},He=()=>({apiUrl:ae,token:le}),ce=(e,t)=>ue(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),U=(e,t,r)=>ue(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var qe=(e,t)=>ue(`/api/v1/agent_runners/${e}/sessions/${t}`),Ke=(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}});var W=w("ai_gateway"),xe=null;var Ve=async()=>{if(xe)return xe;W.log("Fetching available AI gateway providers");let e=await fetch(`${He().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 xe=t,W.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},$t=async(e,t)=>{let o=(await Ve()).providers[e];if(!o)return W.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return W.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},We=async({netlify:e,config:t})=>{let r,o,n,s,l=e.constants?.SITE_ID;if(!l)throw new Error("No site id");let u=async()=>{clearTimeout(n),W.log("Requesting AI gateway information");let i=await Ke(l,t.id,t.sessionId);if({token:r,url:s}=i,o=i.expires_at?i.expires_at*1e3:void 0,W.log("Got AI gateway information",{token:!!r,expiresAt:o,url:s}),o){let p=o-Date.now()-6e4;p>0&&(n=setTimeout(()=>{u()},p))}};return await Promise.all([u(),Ve()]),{get url(){return s},get token(){return r},isModelAvailableForProvider:$t}};import q from"process";import{execa as Mt,execaCommand as rn}from"execa";import{Transform as Dt}from"stream";var Ft=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"]),Lt=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function kt(){return Object.entries(process.env).filter(([e,t])=>!(!t||Ft.has(e)||Lt.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function M(e){if(typeof e!="string")return e;let t=kt();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(Ut(o),"g");r=r.replace(n,"******")}),r}function Ut(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var J=class extends Dt{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),s=M(n);o(null,s)}};function Je(){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,s){let l=typeof o=="string"?M(o):o;return typeof n=="function"?t(l,n):t(l,n,s)},process.stderr.write=function(o,n,s){let l=typeof o=="string"?M(o):o;return typeof n=="function"?r(l,n):r(l,n,s)}}var ne=null,Xe=e=>(ne&&ne.destroy(),ne=new H({totalAllowedTime:e}),ne),ze=()=>ne;var H=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.`)}),s=null,l=null;o!==void 0&&(l=new Promise((u,i)=>{s=setTimeout(()=>{i(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return l?await Promise.race([r(),l]):await r()}finally{n(),s&&clearTimeout(s)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var pe=w("shell"),Re=new Set,Gt={preferLocal:!0},Ze=(e,t,r)=>{let[o,n]=jt(t,r),s={...Gt,...n},l=Mt(e,o,s);return Bt(l,s),Ht(l),l};var jt=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Bt=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(q.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new J).pipe(q.stdout),e.stdout?.pipe(new J).pipe(q.stdout),e.stderr?.pipe(new J).pipe(q.stderr);return}e.stdout?.pipe(q.stdout),e.stderr?.pipe(q.stderr)},Qe=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(q.kill(-e.pid,t),pe.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return pe.error("Error killing process:",r),!1}},Yt=e=>Qe(e,"SIGKILL"),Ht=e=>{Re.add(e);let t=ze();if(t){let r=t.onTimesUp(()=>{pe.log(`Global timer expired, killing process ${e.pid}`),Qe(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(pe.log(`Force killing process ${e.pid} after timeout`),Yt(e))},5e3)});e.on("exit",()=>{Re.delete(e),r()}),e.on("error",()=>{Re.delete(e),r()})}};var et="netlify-agent-runner-context.md",ve="task-history",Ae="netlify-context",D=".netlify",X="results.md",Ne="assets";var qt=w("utils"),Kt=e=>new Promise(t=>{setTimeout(t,e)}),tt=(e,t=3e3)=>{let r=!1,o=null,n=[],s=null,l=(...u)=>{if(r)return o=u,new Promise(c=>{n.push(c)});r=!0;let i,p=new Promise(c=>{i=c});return s=(async()=>{await Promise.resolve();let c=await e(...u);for(i(c);;){if(await Kt(t),!o)return r=!1,s=null,c;let d=o,f=n;o=null,n=[],c=await e(...d),f.forEach(_=>{_(c)})}})(),p};return l.flush=async()=>{if((r||o)&&s)return await s,l.flush()},l},de=(e,t,r=!1)=>{let o=null,n=null,s=null,l=function(...u){n=u,s=this;let i=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(s,n),n=null,s=null)},t),i&&(e.apply(s,n),n=null,s=null)};return l.cancel=()=>{clearTimeout(o),o=null,n=null,s=null},l.flush=()=>{if(o){clearTimeout(o);let u=n,i=s;o=null,n=null,s=null,e.apply(i,u)}},l},rt=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):qt.error("Could not parse JSON",o))}},nt=(e,t)=>{let n=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let u=`--${t}${n}`;if(u.length>55)return"";let i=60-u.length;if(i<=0)return"";if(i>=s.length+6){let p=Math.min(i-s.length,e.length);return`${s}${e.slice(0,p)}`}return e.slice(0,i)};import{Buffer as ot}from"buffer";import Vt from"path";var st=async({config:e,netlify:t})=>{let r=await Jt(t),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};let s=await Xt(n);await t.utils.run("git",["add",".",...s]);let l={stdio:["ignore","pipe","pipe"]},i=(await t.utils.run("git",["diff","--staged"],l)).stdout;if(o=!!i,!o)return{hasChanges:!1,ignored:s};let c=(await t.utils.run("git",["diff","--staged","--binary"],l)).stdout,d,f;if(e.sha){await t.utils.run("git",["commit","-m","Agent runner"]),d=(await t.utils.run("git",["diff",e.sha,"HEAD"],l)).stdout;let T=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"],l)).stdout;d!==T&&(f=ot.from(T).toString("base64"))}let _={hasChanges:!0,diff:i,resultDiff:d,ignored:s};return i!==c&&(_.diffBinary=ot.from(c).toString("base64")),f&&(_.resultDiffBinary=f),_},Wt=["?? mise.toml","?? deno.lock",/\?\? .+?\.log/],Jt=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
7
+ `);return s.length>e.length*.8?e:s}import he from"process";import{getTracer as mr}from"@netlify/otel";import ie from"process";var ae=ie.env.NETLIFY_API_URL,le=ie.env.NETLIFY_API_TOKEN,re=_("api"),ue=async(e,t={})=>{if(!ae||!le)throw new Error("No API URL or token");let r=new URL(e,ae),o={...t,headers:{...t.headers,Authorization:`Bearer ${le}`}};ie.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),s=n.ok&&n.status<=299;if(ie.env.AGENT_RUNNERS_DEBUG==="true")re.log(`Response headers for ${r}:`),n.headers.forEach((u,i)=>{re.log(` ${i}: ${u}`)});else{let u=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");re.log(`Request ID for ${r}: ${u||"N/A"}`)}if(s||re.error(`Got status ${n.status} for request ${r}`),t.raw){if(!s)throw n;return n}let l=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!s)throw l;return l},Ye=e=>{re.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(ae=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(le=e.constants.NETLIFY_API_TOKEN)},He=()=>({apiUrl:ae,token:le}),ce=(e,t)=>ue(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),U=(e,t,r)=>ue(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var qe=(e,t)=>ue(`/api/v1/agent_runners/${e}/sessions/${t}`),Ke=(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}});var W=_("ai_gateway"),xe=null;var Ve=async()=>{if(xe)return xe;W.log("Fetching available AI gateway providers");let e=await fetch(`${He().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 xe=t,W.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},$t=async(e,t)=>{let o=(await Ve()).providers[e];if(!o)return W.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return W.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},We=async({netlify:e,config:t})=>{let r,o,n,s,l=e.constants?.SITE_ID;if(!l)throw new Error("No site id");let u=async()=>{clearTimeout(n),W.log("Requesting AI gateway information");let i=await Ke(l,t.id,t.sessionId);if({token:r,url:s}=i,o=i.expires_at?i.expires_at*1e3:void 0,W.log("Got AI gateway information",{token:!!r,expiresAt:o,url:s}),o){let m=o-Date.now()-6e4;m>0&&(n=setTimeout(()=>{u()},m))}};return await Promise.all([u(),Ve()]),{get url(){return s},get token(){return r},isModelAvailableForProvider:$t}};import q from"process";import{execa as Mt,execaCommand as rn}from"execa";import{Transform as Dt}from"stream";var Ft=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"]),Lt=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function kt(){return Object.entries(process.env).filter(([e,t])=>!(!t||Ft.has(e)||Lt.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function M(e){if(typeof e!="string")return e;let t=kt();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(Ut(o),"g");r=r.replace(n,"******")}),r}function Ut(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var J=class extends Dt{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),s=M(n);o(null,s)}};function Je(){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,s){let l=typeof o=="string"?M(o):o;return typeof n=="function"?t(l,n):t(l,n,s)},process.stderr.write=function(o,n,s){let l=typeof o=="string"?M(o):o;return typeof n=="function"?r(l,n):r(l,n,s)}}var ne=null,Xe=e=>(ne&&ne.destroy(),ne=new H({totalAllowedTime:e}),ne),ze=()=>ne;var H=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.`)}),s=null,l=null;o!==void 0&&(l=new Promise((u,i)=>{s=setTimeout(()=>{i(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return l?await Promise.race([r(),l]):await r()}finally{n(),s&&clearTimeout(s)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var pe=_("shell"),Re=new Set,Gt={preferLocal:!0},Ze=(e,t,r)=>{let[o,n]=jt(t,r),s={...Gt,...n},l=Mt(e,o,s);return Bt(l,s),Ht(l),l};var jt=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Bt=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(q.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new J).pipe(q.stdout),e.stdout?.pipe(new J).pipe(q.stdout),e.stderr?.pipe(new J).pipe(q.stderr);return}e.stdout?.pipe(q.stdout),e.stderr?.pipe(q.stderr)},Qe=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(q.kill(-e.pid,t),pe.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return pe.error("Error killing process:",r),!1}},Yt=e=>Qe(e,"SIGKILL"),Ht=e=>{Re.add(e);let t=ze();if(t){let r=t.onTimesUp(()=>{pe.log(`Global timer expired, killing process ${e.pid}`),Qe(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(pe.log(`Force killing process ${e.pid} after timeout`),Yt(e))},5e3)});e.on("exit",()=>{Re.delete(e),r()}),e.on("error",()=>{Re.delete(e),r()})}};var et="netlify-agent-runner-context.md",ve="task-history",Ae="netlify-context",D=".netlify",X="results.md",Ne="assets";var qt=_("utils"),Kt=e=>new Promise(t=>{setTimeout(t,e)}),tt=(e,t=3e3)=>{let r=!1,o=null,n=[],s=null,l=(...u)=>{if(r)return o=u,new Promise(c=>{n.push(c)});r=!0;let i,m=new Promise(c=>{i=c});return s=(async()=>{await Promise.resolve();let c=await e(...u);for(i(c);;){if(await Kt(t),!o)return r=!1,s=null,c;let p=o,d=n;o=null,n=[],c=await e(...p),d.forEach(E=>{E(c)})}})(),m};return l.flush=async()=>{if((r||o)&&s)return await s,l.flush()},l},de=(e,t,r=!1)=>{let o=null,n=null,s=null,l=function(...u){n=u,s=this;let i=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(s,n),n=null,s=null)},t),i&&(e.apply(s,n),n=null,s=null)};return l.cancel=()=>{clearTimeout(o),o=null,n=null,s=null},l.flush=()=>{if(o){clearTimeout(o);let u=n,i=s;o=null,n=null,s=null,e.apply(i,u)}},l},rt=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):qt.error("Could not parse JSON",o))}},nt=(e,t)=>{let n=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let u=`--${t}${n}`;if(u.length>55)return"";let i=60-u.length;if(i<=0)return"";if(i>=s.length+6){let m=Math.min(i-s.length,e.length);return`${s}${e.slice(0,m)}`}return e.slice(0,i)};import{Buffer as ot}from"buffer";import Vt from"path";var st=async({config:e,netlify:t})=>{let r=await Jt(t),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};let s=await Xt(n);await t.utils.run("git",["add",".",...s]);let l={stdio:["ignore","pipe","pipe"]},i=(await t.utils.run("git",["diff","--staged"],l)).stdout;if(o=!!i,!o)return{hasChanges:!1,ignored:s};let c=(await t.utils.run("git",["diff","--staged","--binary"],l)).stdout,p,d;if(e.sha){await t.utils.run("git",["commit","-m","Agent runner"]),p=(await t.utils.run("git",["diff",e.sha,"HEAD"],l)).stdout;let T=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"],l)).stdout;p!==T&&(d=ot.from(T).toString("base64"))}let E={hasChanges:!0,diff:i,resultDiff:p,ignored:s};return i!==c&&(E.diffBinary=ot.from(c).toString("base64")),d&&(E.resultDiffBinary=d),E},Wt=["?? mise.toml","?? deno.lock",/\?\? .+?\.log/],Jt=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
8
8
  `).filter(n=>!Wt.some(s=>s instanceof RegExp?s.test(n):n===s))).length!==0,status:t.stdout}};var it=async e=>{let{stdout:t}=await e.utils.run("git",["rev-parse","HEAD"]);return t.trim()},at=async e=>{let{stdout:t}=await e.utils.run("git",["rev-list","--max-parents=0","HEAD"]);return t.trim()},Xt=async e=>{let t=[".netlify","mise.toml","deno.lock","node_modules"],r=[];return e.split(`
9
- `).forEach(o=>{t.forEach(s=>{[`?? ${s}`,`?? ${s}${Vt.sep}`].some(u=>o.startsWith(u))&&r.push(`:!${s}`)});let n=o.match(/\?\? (.+?)\.log$/)?.[1];n&&r.push(`:!${n}.log`)}),r};import Zt from"fs/promises";import Qt from"os";import me from"path";import j from"process";import er from"readline";import be from"path";import zt from"fs/promises";var Se=w("agent-output-utils");async function z({initialResult:e,agentName:t,hasError:r}){let o="",n=be.join(process.cwd(),D,X);try{let s=await zt.readFile(n,"utf-8");s&&(o=s,Se.log(`Pulled result from ${be.relative(process.cwd(),n)}`))}catch{Se.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 Z({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&&Se.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function Q(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 F=w("runner_claude"),lt="Claude Code",fe="claude-sonnet-4-5-20250929",tr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(F.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?(F.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}):(F.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function Ce({config:e,netlify:t,persistSteps:r,aiGateway:o}){let n=e,{accountType:s,prompt:l,modelVersionOverrides:u}=n,{model:i}=n;if(o){let{token:I,url:m}=o;if(!I||!m)throw new Error("No token or url provided from AI Gateway");if(u?.claude){let a=u?.claude?.[s];if(a){if(!await o.isModelAvailableForProvider("anthropic",a))throw new Error(`Model override '${a}' is not available for anthropic provider`);i=a}}else if(i){if(!await o.isModelAvailableForProvider("anthropic",i))throw new Error(`Model '${i}' is not available for anthropic provider`)}else await o.isModelAvailableForProvider("anthropic",fe)?(i=fe,F.log(`Using default model: ${fe}`)):F.log(`Default model ${fe} is not available, proceeding without model specification`);j.env.ANTHROPIC_API_KEY=I,j.env.ANTHROPIC_BASE_URL=m}else if(!j.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let p=[],c=[],d={},f=0,_=0,g,y,T=me.join(j.cwd(),"node_modules"),R=[me.join(j.env.NODE_PATH||T,".bin/claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...i?["--model",i]:[],"-p",l],v=`${j.env.NVM_BIN}/node`;F.log(`Running ${v} ${R.join(" ")}`);let N=t.utils.run(v,R,{all:!0,env:j.env});N.stdin?.end();let A=de(()=>{r?.({steps:p,duration:_})},250),x=(I,m)=>{let a={...I,id:f};f+=1,c.push(a),p.push(a),m||A.flush(),A(),m&&A.flush()},E=er.createInterface({input:N.all});return E.on("error",I=>{F.error("Readline interface error",{error:I.message,stack:I.stack})}),E.on("line",I=>{let m=null;try{m=JSON.parse(I)}catch{F.log("Could not parse line",I)}Array.isArray(m?.message?.content)?m.message.content.forEach(a=>{switch(a.type){case"text":{a.text&&x({message:a.text});break}case"image":{typeof a.source=="object"&&a.source&&a.source.type==="base64"&&a.source.media_type?x({message:`![](data:${a.source.media_type};base64,${a.source.data})`}):F.log(`Unsupported image type ${a.source?.type}`,a.source);break}case"tool_use":{if(a.name==="Task"){let h=a.input?.description&&`\`${a.input.description}\``;x({title:[a.name,h].filter(Boolean).join(" ")})}else a.id&&(d[a.id]=a);A.flush();break}case"tool_result":{let h=a.tool_use_id?d[a.tool_use_id]:void 0,b;if(h){let k=h.input?.file_path&&me.relative(j.cwd(),h.input.file_path),S=k&&`\`${k}\``;b=[h.name,S].filter(Boolean).join(" ")}let G=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(h?.name||""),$;if(typeof a.content=="string")$=a.content;else if(Array.isArray(a.content)){let k=[];a.content.forEach(S=>{S?.type==="text"&&typeof S.text=="string"?k.push(S.text):S?.type==="image"&&typeof S.source=="object"&&S.source?S.source.type==="base64"&&S.source.media_type?k.push(`![](data:${S.source.media_type};base64,${S.source.data})`):F.log(`Unsupported image type ${S.source.type}`,S.source):F.log(`Unsupported block type ${S?.type}`)}),$=k.join(`
9
+ `).forEach(o=>{t.forEach(s=>{[`?? ${s}`,`?? ${s}${Vt.sep}`].some(u=>o.startsWith(u))&&r.push(`:!${s}`)});let n=o.match(/\?\? (.+?)\.log$/)?.[1];n&&r.push(`:!${n}.log`)}),r};import Zt from"fs/promises";import Qt from"os";import me from"path";import j from"process";import er from"readline";import be from"path";import zt from"fs/promises";var Se=_("agent-output-utils");async function z({initialResult:e,agentName:t,hasError:r}){let o="",n=be.join(process.cwd(),D,X);try{let s=await zt.readFile(n,"utf-8");s&&(o=s,Se.log(`Pulled result from ${be.relative(process.cwd(),n)}`))}catch{Se.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 Z({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&&Se.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function Q(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 F=_("runner_claude"),lt="Claude Code",fe="claude-sonnet-4-5-20250929",tr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(F.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?(F.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}):(F.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function Ce({config:e,netlify:t,persistSteps:r,aiGateway:o}){let n=e,{accountType:s,prompt:l,modelVersionOverrides:u}=n,{model:i}=n;if(o){let{token:w,url:f}=o;if(!w||!f)throw new Error("No token or url provided from AI Gateway");if(u?.claude){let a=u?.claude?.[s];if(a){if(!await o.isModelAvailableForProvider("anthropic",a))throw new Error(`Model override '${a}' is not available for anthropic provider`);i=a}}else if(i){if(!await o.isModelAvailableForProvider("anthropic",i))throw new Error(`Model '${i}' is not available for anthropic provider`)}else await o.isModelAvailableForProvider("anthropic",fe)?(i=fe,F.log(`Using default model: ${fe}`)):F.log(`Default model ${fe} is not available, proceeding without model specification`);j.env.ANTHROPIC_API_KEY=w,j.env.ANTHROPIC_BASE_URL=f}else if(!j.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let m=[],c=[],p={},d=0,E=0,I,g,T=me.join(j.cwd(),"node_modules"),R=[me.join(j.env.NODE_PATH||T,".bin/claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...i?["--model",i]:[],"-p",l],v=`${j.env.NVM_BIN}/node`;F.log(`Running ${v} ${R.join(" ")}`);let N=t.utils.run(v,R,{all:!0,env:j.env});N.stdin?.end();let A=de(()=>{r?.({steps:m,duration:E})},250),x=(w,f)=>{let a={...w,id:d};d+=1,c.push(a),m.push(a),f||A.flush(),A(),f&&A.flush()},y=er.createInterface({input:N.all});return y.on("error",w=>{F.error("Readline interface error",{error:w.message,stack:w.stack})}),y.on("line",w=>{let f=null;try{f=JSON.parse(w)}catch{F.log("Could not parse line",w)}Array.isArray(f?.message?.content)?f.message.content.forEach(a=>{switch(a.type){case"text":{a.text&&x({message:a.text});break}case"image":{typeof a.source=="object"&&a.source&&a.source.type==="base64"&&a.source.media_type?x({message:`![](data:${a.source.media_type};base64,${a.source.data})`}):F.log(`Unsupported image type ${a.source?.type}`,a.source);break}case"tool_use":{if(a.name==="Task"){let h=a.input?.description&&`\`${a.input.description}\``;x({title:[a.name,h].filter(Boolean).join(" ")})}else a.id&&(p[a.id]=a);A.flush();break}case"tool_result":{let h=a.tool_use_id?p[a.tool_use_id]:void 0,b;if(h){let k=h.input?.file_path&&me.relative(j.cwd(),h.input.file_path),S=k&&`\`${k}\``;b=[h.name,S].filter(Boolean).join(" ")}let G=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(h?.name||""),$;if(typeof a.content=="string")$=a.content;else if(Array.isArray(a.content)){let k=[];a.content.forEach(S=>{S?.type==="text"&&typeof S.text=="string"?k.push(S.text):S?.type==="image"&&typeof S.source=="object"&&S.source?S.source.type==="base64"&&S.source.media_type?k.push(`![](data:${S.source.media_type};base64,${S.source.data})`):F.log(`Unsupported image type ${S.source.type}`,S.source):F.log(`Unsupported block type ${S?.type}`)}),$=k.join(`
10
10
 
11
11
  `)}G&&$&&($=`\`\`\`
12
12
  ${$.trim()}
13
- \`\`\``),x({title:b,message:$},!0);break}case"thinking":{a.thinking&&x({title:"Thinking",message:a.thinking},!0);break}default:F.log(`Message content type is not supported ${a.type}`,a)}}):m?.type==="result"&&(_=m.duration_ms||0,m.is_error?y=m.result:g=m.result,[c,p].forEach(a=>{a[a.length-1]?.message===g&&a.pop()}))}),await N.catch(I=>{({error:y,result:g}=tr({catchError:I,runCmd:N,error:y,result:g,runnerName:"Claude"}))}),E.close(),A.flush(),{steps:c,duration:_,result:await z({initialResult:g,agentName:lt,hasError:!!y}),error:Z({error:y,agentName:lt}),isRetryableError:Q(y)}}var ut=async()=>{let e=me.join(Qt.homedir(),".claude");await Zt.rm(e,{recursive:!0,force:!0})};import rr from"fs/promises";import nr from"os";import Pe from"path";import K from"process";import or from"readline";var V=w("runner_codex"),ct="Codex CLI",sr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(V.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?(V.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}):(V.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function Oe({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:l,modelVersionOverrides:u}=e,{model:i}=e;if(n){let{token:x,url:E}=n;if(!x||!E)throw new Error("No token or url provided from AI Gateway");if(u?.codex){let I=u?.codex?.[s];if(I){if(!await n.isModelAvailableForProvider("openai",I))throw new Error(`Model override '${I}' is not available for openai provider`);i=I}}else if(i&&!await n.isModelAvailableForProvider("openai",i))throw new Error(`Model '${i}' is not available for openai provider`);K.env.OPENAI_API_KEY=x,K.env.OPENAI_BASE_URL=E}else if(!K.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let p=[],c=[],d={},f=0,_=0,g,y,T=Pe.join(K.cwd(),"node_modules"),R=[Pe.join(K.env.NODE_PATH||T,".bin/codex"),"--approval-mode","full-auto",n?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...i?["--model",i]:[],"-q",l].filter(Boolean),v=`${K.env.NVM_BIN}/node`;V.log(`Running ${v} ${R.join(" ")}`);let N=t.utils.run(v,R,{all:!0,env:{...K.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),A=or.createInterface({input:N.all});return A.on("error",x=>{V.error("Readline interface error",{error:x.message,stack:x.stack})}),A.on("line",x=>{let E=null;try{E=JSON.parse(x)}catch{V.log("Could not parse line",x);return}let I=[],m=!1;if(E?.duration_ms&&(_=E.duration_ms,m=!0),E?.type==="local_shell_call")d[E.call_id]=E;else if(E?.type==="local_shell_call_output"){let a=ar(d[E.call_id],E);a&&(a.id=f,f+=1,c.push(a),p.push(a),I.push(a),m=!0)}else E?.type==="message"&&E.role==="assistant"?g=E.content.map(a=>a.text).join(`
14
- `):E?.type==="message"&&E.role==="system"&&(y=E.content.map(a=>a.text).join(`
15
- `));m&&(r?.({steps:p,duration:_}),o?.({steps:I,duration:_}))}),await N.catch(x=>{let E=sr({catchError:x,runCmd:N,error:y,result:g,runnerName:"Codex"});y=E.error,g=E.result}),A.close(),{steps:c,duration:_,result:await z({initialResult:g,agentName:ct,hasError:!!y}),error:Z({error:y,agentName:ct}),isRetryableError:Q(y)}}var pt=async()=>{let e=Pe.join(nr.homedir(),".codex");await rr.rm(e,{recursive:!0,force:!0})},ir=new Set(["bash","-lc"]),ar=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!ir.has(s)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
13
+ \`\`\``),x({title:b,message:$},!0);break}case"thinking":{a.thinking&&x({title:"Thinking",message:a.thinking},!0);break}default:F.log(`Message content type is not supported ${a.type}`,a)}}):f?.type==="result"&&(E=f.duration_ms||0,f.is_error?g=f.result:I=f.result,[c,m].forEach(a=>{a[a.length-1]?.message===I&&a.pop()}))}),await N.catch(w=>{({error:g,result:I}=tr({catchError:w,runCmd:N,error:g,result:I,runnerName:"Claude"}))}),y.close(),A.flush(),{steps:c,duration:E,result:await z({initialResult:I,agentName:lt,hasError:!!g}),error:Z({error:g,agentName:lt}),isRetryableError:Q(g)}}var ut=async()=>{let e=me.join(Qt.homedir(),".claude");await Zt.rm(e,{recursive:!0,force:!0})};import rr from"fs/promises";import nr from"os";import Pe from"path";import K from"process";import or from"readline";var V=_("runner_codex"),ct="Codex CLI",sr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(V.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?(V.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}):(V.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function Oe({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:l,modelVersionOverrides:u}=e,{model:i}=e;if(n){let{token:x,url:y}=n;if(!x||!y)throw new Error("No token or url provided from AI Gateway");if(u?.codex){let w=u?.codex?.[s];if(w){if(!await n.isModelAvailableForProvider("openai",w))throw new Error(`Model override '${w}' is not available for openai provider`);i=w}}else if(i&&!await n.isModelAvailableForProvider("openai",i))throw new Error(`Model '${i}' is not available for openai provider`);K.env.OPENAI_API_KEY=x,K.env.OPENAI_BASE_URL=y}else if(!K.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let m=[],c=[],p={},d=0,E=0,I,g,T=Pe.join(K.cwd(),"node_modules"),R=[Pe.join(K.env.NODE_PATH||T,".bin/codex"),"--approval-mode","full-auto",n?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...i?["--model",i]:[],"-q",l].filter(Boolean),v=`${K.env.NVM_BIN}/node`;V.log(`Running ${v} ${R.join(" ")}`);let N=t.utils.run(v,R,{all:!0,env:{...K.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),A=or.createInterface({input:N.all});return A.on("error",x=>{V.error("Readline interface error",{error:x.message,stack:x.stack})}),A.on("line",x=>{let y=null;try{y=JSON.parse(x)}catch{V.log("Could not parse line",x);return}let w=[],f=!1;if(y?.duration_ms&&(E=y.duration_ms,f=!0),y?.type==="local_shell_call")p[y.call_id]=y;else if(y?.type==="local_shell_call_output"){let a=ar(p[y.call_id],y);a&&(a.id=d,d+=1,c.push(a),m.push(a),w.push(a),f=!0)}else y?.type==="message"&&y.role==="assistant"?I=y.content.map(a=>a.text).join(`
14
+ `):y?.type==="message"&&y.role==="system"&&(g=y.content.map(a=>a.text).join(`
15
+ `));f&&(r?.({steps:m,duration:E}),o?.({steps:w,duration:E}))}),await N.catch(x=>{let y=sr({catchError:x,runCmd:N,error:g,result:I,runnerName:"Codex"});g=y.error,I=y.result}),A.close(),{steps:c,duration:E,result:await z({initialResult:I,agentName:ct,hasError:!!g}),error:Z({error:g,agentName:ct}),isRetryableError:Q(g)}}var pt=async()=>{let e=Pe.join(nr.homedir(),".codex");await rr.rm(e,{recursive:!0,force:!0})},ir=new Set(["bash","-lc"]),ar=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!ir.has(s)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
16
16
  ${n.trim()}
17
- \`\`\``)}catch(s){V.error("Could not decode outputMsg",s,t.output)}return{title:o,message:n}};import lr from"fs/promises";import ur from"os";import ge from"path";import B from"process";import cr from"readline";var ee=w("runner_gemini"),dt="Gemini CLI",pr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(ee.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?(ee.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}):(ee.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),dr={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 $e({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:l,modelVersionOverrides:u}=e,{model:i}=e;if(n){let{token:m,url:a}=n;if(!m||!a)throw new Error("No token or url provided from AI Gateway");if(u?.gemini){let h=u?.gemini?.[s];if(h){if(!await n.isModelAvailableForProvider("gemini",h))throw new Error(`Model override '${h}' is not available for gemini provider`);i=h}}else if(i&&!await n.isModelAvailableForProvider("gemini",i))throw new Error(`Model '${i}' is not available for gemini provider`);B.env.GEMINI_API_KEY=m,B.env.GOOGLE_GEMINI_BASE_URL=a}else if(!B.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let p=[],c=[],d=[],f={},_=0,g=0,y,T,R=ge.join(B.cwd(),"node_modules"),v=[ge.join(B.env.NODE_PATH||R,".bin/gemini"),...i?["--model",i]:[],"--yolo","-p",l],N=`${B.env.NVM_BIN}/node`;ee.log(`Running ${N} ${v.join(" ")}`);let A=t.utils.run(N,v,{all:!0,env:B.env});A.stdin?.end();let x=de(()=>{r?.({steps:p,duration:g}),o?.({steps:c,duration:g}),c=[]},250),E=(m,a)=>{m.id=_,_+=1,d.push(m),p.push(m),c.push(m),a||x.flush(),x(),a&&x.flush()},I=cr.createInterface({input:A.all});return I.on("error",m=>{ee.error("Readline interface error",{error:m.message,stack:m.stack})}),I.on("line",m=>{let a=null;try{if(m.startsWith("[API Error")){let h=m.match(/\[api error: (.+?)]$/i)?.[1];a={type:"error",value:rt(h,!1)?.error?.message||h||"Gemini encountered error"}}else a=JSON.parse(m)}catch{return}if(a)switch(a.type){case"thought":{let h=a.value;E({title:h?.subject??"Thinking...",message:h?.description},!0);break}case"content":{a.value&&E({message:a.value});break}case"tool_call_request":{let h=a.value,b=dr[h.name]??h.name,G=h.args?.path||h.args?.absolute_path,$=G&&ge.relative(B.cwd(),G),k=h.args?.command,At={title:[b,$&&`\`${$}\``,k&&`\`${k}\``].filter(Boolean).join(" ")};f[h.callId]=At,x.flush();break}case"tool_result":{let h=a.value,b=f[h.callId];if(b){let G=[h.resultDisplay,h.responseParts?.functionResponse?.response?.output].find($=>typeof $=="string"&&$);G&&(b.message=`\`\`\`
17
+ \`\`\``)}catch(s){V.error("Could not decode outputMsg",s,t.output)}return{title:o,message:n}};import lr from"fs/promises";import ur from"os";import ge from"path";import B from"process";import cr from"readline";var ee=_("runner_gemini"),dt="Gemini CLI",pr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(ee.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?(ee.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}):(ee.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),dr={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 $e({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:l,modelVersionOverrides:u}=e,{model:i}=e;if(n){let{token:f,url:a}=n;if(!f||!a)throw new Error("No token or url provided from AI Gateway");if(u?.gemini){let h=u?.gemini?.[s];if(h){if(!await n.isModelAvailableForProvider("gemini",h))throw new Error(`Model override '${h}' is not available for gemini provider`);i=h}}else if(i&&!await n.isModelAvailableForProvider("gemini",i))throw new Error(`Model '${i}' is not available for gemini provider`);B.env.GEMINI_API_KEY=f,B.env.GOOGLE_GEMINI_BASE_URL=a}else if(!B.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let m=[],c=[],p=[],d={},E=0,I=0,g,T,R=ge.join(B.cwd(),"node_modules"),v=[ge.join(B.env.NODE_PATH||R,".bin/gemini"),...i?["--model",i]:[],"--yolo","-p",l],N=`${B.env.NVM_BIN}/node`;ee.log(`Running ${N} ${v.join(" ")}`);let A=t.utils.run(N,v,{all:!0,env:B.env});A.stdin?.end();let x=de(()=>{r?.({steps:m,duration:I}),o?.({steps:c,duration:I}),c=[]},250),y=(f,a)=>{f.id=E,E+=1,p.push(f),m.push(f),c.push(f),a||x.flush(),x(),a&&x.flush()},w=cr.createInterface({input:A.all});return w.on("error",f=>{ee.error("Readline interface error",{error:f.message,stack:f.stack})}),w.on("line",f=>{let a=null;try{if(f.startsWith("[API Error")){let h=f.match(/\[api error: (.+?)]$/i)?.[1];a={type:"error",value:rt(h,!1)?.error?.message||h||"Gemini encountered error"}}else a=JSON.parse(f)}catch{return}if(a)switch(a.type){case"thought":{let h=a.value;y({title:h?.subject??"Thinking...",message:h?.description},!0);break}case"content":{a.value&&y({message:a.value});break}case"tool_call_request":{let h=a.value,b=dr[h.name]??h.name,G=h.args?.path||h.args?.absolute_path,$=G&&ge.relative(B.cwd(),G),k=h.args?.command,At={title:[b,$&&`\`${$}\``,k&&`\`${k}\``].filter(Boolean).join(" ")};d[h.callId]=At,x.flush();break}case"tool_result":{let h=a.value,b=d[h.callId];if(b){let G=[h.resultDisplay,h.responseParts?.functionResponse?.response?.output].find($=>typeof $=="string"&&$);G&&(b.message=`\`\`\`
18
18
  ${G.trim()}
19
- \`\`\``),E(b,!0)}break}case"result":{g=a.duration_ms,y=a.value,[d,p,c].forEach(h=>{h[h.length-1]?.message===y&&h.pop()});break}case"error":{T=a.value;break}case"finished":break;default:{ee.warn("Unhandled message type:",a.type);break}}}),await A.catch(m=>{({error:T,result:y}=pr({catchError:m,runCmd:A,error:T,result:y,runnerName:"Gemini"}))}),I.close(),x.flush(),{steps:d,duration:g,result:await z({initialResult:y,agentName:dt,hasError:!!T}),error:Z({error:T,agentName:dt}),isRetryableError:Q(T)}}var ft=async()=>{let e=ge.join(ur.homedir(),".gemini");await lr.rm(e,{recursive:!0,force:!0})};var fr={codex:{runner:Oe,clean:pt},claude:{runner:Ce,clean:ut},gemini:{runner:$e,clean:ft}},mt=fr;var gt=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>await C(mr(),"init-stage",async n=>{let s=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 l=mt[e.runner];if(!l)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let u=gr({apiToken:r});Ye(u);let i=e.useGateway?await We({netlify:u,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!i}),e.validateAgent&&e.errorLogsPath&&n?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let p=tt(({steps:f=[],duration:_})=>{let g=f.map(y=>({...y,title:y.title?M(y.title):void 0,message:y.message?M(y.message):void 0}));return f.length=0,U(e.id,e.sessionId,{steps:g,duration:_})},t),c;e.hasRepo?e.sha?(c=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(c=await it(u),await ce(e.id,{sha:c}),n?.setAttributes({"init.sha.source":"current_commit"})):(c=await at(u),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let d=performance.now()-s;return n?.setAttributes({"init.sha":c||"unknown","init.duration.ms":d,"init.status":"success"}),{aiGateway:i,context:u,persistSteps:p,runner:l,sha:c}}),gr=({apiToken:e})=>({constants:{NETLIFY_API_HOST:he.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||he.env.NETLIFY_API_TOKEN,SITE_ID:he.env.SITE_ID,FUNCTIONS_DIST:he.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:Ze}});import{getTracer as De}from"@netlify/otel";import hr from"crypto";import Y from"fs/promises";import O from"path";import L from"process";var P=w("context"),yr=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:L.env.NETLIFY_TEAM_ID,userId:L.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:L.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},Er=10,_r=async e=>{let{name:t,ext:r}=O.parse(e),o=e,n=O.join(L.cwd(),D,o),s=0;for(;await wr(n);){if(s>=Er)throw new Error("Failed to generate context file");o=`${t}-${hr.randomUUID().slice(0,5)}${r}`,n=O.join(L.cwd(),D,o),s+=1}return o},wr=async e=>{try{return await Y.access(e),!0}catch{return!1}},Tr=async()=>{try{P.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 P.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"?(P.warn("Catchall consumer missing or invalid contextScopes"),null):r:(P.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?P.warn("Netlify features context request timed out"):P.warn("Failed to fetch Netlify features context:",e.message),null}},Ir=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 Y.writeFile(t,o,"utf-8"),!0}catch(r){return r.name==="AbortError"?P.warn(`Download timeout for ${e}`):P.warn(`Failed to download context file ${e}:`,r.message),!1}},ye=null,xr=async()=>{if(ye)return ye;let e=await Tr();if(!e)return[];let t=O.join(L.cwd(),D,Ae);await Y.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([n,s])=>{if(!s||typeof s!="object"||!s.endpoint||!s.scope)return P.warn(`Invalid scope data for ${n}, skipping...`),null;let l=`${n}.md`,u=O.join(t,l),i=O.join(D,Ae,l);return P.log(`Downloading ${s.scope} context...`),await Ir(s.endpoint,u)?(P.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:n}):null});return ye=(await Promise.all(r)).filter(n=>n!==null),ye},ht=async({cliPath:e,netlify:t,config:r,buildErrorContext:o})=>{let n=yr(t),s=await _r(et),l=O.join(L.cwd(),D);await Y.mkdir(l,{recursive:!0});let u=O.join(D,s),i=O.join(L.cwd(),u),p=O.join(L.cwd(),D,X);try{await Y.unlink(p),P.log(`Deleted old results file: ${p}`)}catch{}let c=o?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
19
+ \`\`\``),y(b,!0)}break}case"result":{I=a.duration_ms,g=a.value,[p,m,c].forEach(h=>{h[h.length-1]?.message===g&&h.pop()});break}case"error":{T=a.value;break}case"finished":break;default:{ee.warn("Unhandled message type:",a.type);break}}}),await A.catch(f=>{({error:T,result:g}=pr({catchError:f,runCmd:A,error:T,result:g,runnerName:"Gemini"}))}),w.close(),x.flush(),{steps:p,duration:I,result:await z({initialResult:g,agentName:dt,hasError:!!T}),error:Z({error:T,agentName:dt}),isRetryableError:Q(T)}}var ft=async()=>{let e=ge.join(ur.homedir(),".gemini");await lr.rm(e,{recursive:!0,force:!0})};var fr={codex:{runner:Oe,clean:pt},claude:{runner:Ce,clean:ut},gemini:{runner:$e,clean:ft}},mt=fr;var gt=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>await C(mr(),"init-stage",async n=>{let s=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 l=mt[e.runner];if(!l)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let u=gr({apiToken:r});Ye(u);let i=e.useGateway?await We({netlify:u,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!i}),e.validateAgent&&e.errorLogsPath&&n?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let m=tt(({steps:d=[],duration:E})=>{let I=d.map(g=>({...g,title:g.title?M(g.title):void 0,message:g.message?M(g.message):void 0}));return d.length=0,U(e.id,e.sessionId,{steps:I,duration:E})},t),c;e.hasRepo?e.sha?(c=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(c=await it(u),await ce(e.id,{sha:c}),n?.setAttributes({"init.sha.source":"current_commit"})):(c=await at(u),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let p=performance.now()-s;return n?.setAttributes({"init.sha":c||"unknown","init.duration.ms":p,"init.status":"success"}),{aiGateway:i,context:u,persistSteps:m,runner:l,sha:c}}),gr=({apiToken:e})=>({constants:{NETLIFY_API_HOST:he.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||he.env.NETLIFY_API_TOKEN,SITE_ID:he.env.SITE_ID,FUNCTIONS_DIST:he.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:Ze}});import{getTracer as De}from"@netlify/otel";import hr from"crypto";import Y from"fs/promises";import O from"path";import L from"process";var P=_("context"),yr=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:L.env.NETLIFY_TEAM_ID,userId:L.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:L.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},Er=10,_r=async e=>{let{name:t,ext:r}=O.parse(e),o=e,n=O.join(L.cwd(),D,o),s=0;for(;await wr(n);){if(s>=Er)throw new Error("Failed to generate context file");o=`${t}-${hr.randomUUID().slice(0,5)}${r}`,n=O.join(L.cwd(),D,o),s+=1}return o},wr=async e=>{try{return await Y.access(e),!0}catch{return!1}},Tr=async()=>{try{P.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 P.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"?(P.warn("Catchall consumer missing or invalid contextScopes"),null):r:(P.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?P.warn("Netlify features context request timed out"):P.warn("Failed to fetch Netlify features context:",e.message),null}},Ir=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 Y.writeFile(t,o,"utf-8"),!0}catch(r){return r.name==="AbortError"?P.warn(`Download timeout for ${e}`):P.warn(`Failed to download context file ${e}:`,r.message),!1}},ye=null,xr=async()=>{if(ye)return ye;let e=await Tr();if(!e)return[];let t=O.join(L.cwd(),D,Ae);await Y.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([n,s])=>{if(!s||typeof s!="object"||!s.endpoint||!s.scope)return P.warn(`Invalid scope data for ${n}, skipping...`),null;let l=`${n}.md`,u=O.join(t,l),i=O.join(D,Ae,l);return P.log(`Downloading ${s.scope} context...`),await Ir(s.endpoint,u)?(P.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:n}):null});return ye=(await Promise.all(r)).filter(n=>n!==null),ye},ht=async({cliPath:e,netlify:t,config:r,buildErrorContext:o})=>{let n=yr(t),s=await _r(et),l=O.join(L.cwd(),D);await Y.mkdir(l,{recursive:!0});let u=O.join(D,s),i=O.join(L.cwd(),u),m=O.join(L.cwd(),D,X);try{await Y.unlink(m),P.log(`Deleted old results file: ${m}`)}catch{}let c=o?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
20
20
  Your task is to analyze and fix the build errors.
21
21
  Don't apply techniques of reverting changes. Apply fixes related to errors.
22
22
  Don't try to run build by yourself. Just fix the errors.
23
23
 
24
24
  <build_error_context>
25
25
  ${o}
26
- </build_error_context>`:"",d="";r.siteContext&&r.siteContext.length!==0&&(d=`
26
+ </build_error_context>`:"",p="";r.siteContext&&r.siteContext.length!==0&&(p=`
27
27
  <project_rules>
28
28
  ${r.siteContext.filter(T=>T.site_context).map(T=>typeof T.site_context=="string"?T.site_context:typeof T.site_context=="object"?JSON.stringify(T.site_context):"").join(`
29
29
 
30
30
  `)}
31
31
  </project_rules>
32
- `);let f="";if(r.sessionHistoryContext?.length){let T=O.join(L.cwd(),D,ve);await Y.mkdir(T,{recursive:!0});let R=await Promise.all(r.sessionHistoryContext.map(async(v,N)=>{let A=N+1,x=`attempt-${A}.md`,E=O.join(T,x),I=O.join(D,ve,x),m=`# Task History - Attempt ${A}
32
+ `);let d="";if(r.sessionHistoryContext?.length){let T=O.join(L.cwd(),D,ve);await Y.mkdir(T,{recursive:!0});let R=await Promise.all(r.sessionHistoryContext.map(async(v,N)=>{let A=N+1,x=`attempt-${A}.md`,y=O.join(T,x),w=O.join(D,ve,x),f=`# Task History - Attempt ${A}
33
33
 
34
34
  ## Request - what the user asked for
35
35
  ${v.request}
@@ -39,7 +39,7 @@ ${v.request}
39
39
  ## Response - what the agent replied with after its work
40
40
 
41
41
  ${v.response}
42
- `;return await Y.writeFile(E,m,"utf-8"),P.log(`Created history file: ${I}`),I}));f+=`
42
+ `;return await Y.writeFile(y,f,"utf-8"),P.log(`Created history file: ${w}`),w}));d+=`
43
43
  <session_history_context>
44
44
  History of prior work on this task.
45
45
  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.
@@ -48,17 +48,17 @@ ${v.response}
48
48
  `)}
49
49
 
50
50
  </session_history_context>
51
- `}let _=await xr(),g="";_.length>0&&(g=`
51
+ `}let E=await xr(),I="";E.length>0&&(I=`
52
52
  <netlify_features_context>
53
53
  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.
54
54
  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.
55
55
 
56
- ${_.map(T=>`- **${T.scope}**: ${T.path}`).join(`
56
+ ${E.map(T=>`- **${T.scope}**: ${T.path}`).join(`
57
57
  `)}
58
58
 
59
59
  Refer to these files when working with specific Netlify features.
60
60
  </netlify_features_context>
61
- `);let y=`
61
+ `);let g=`
62
62
  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.
63
63
 
64
64
  <request>
@@ -81,7 +81,7 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
81
81
  - for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${l}/${Ne} folder
82
82
  - move assets from ${l}/${Ne} folder to the project assets folder if they are referenced in a code or applied changes
83
83
  </attachements>
84
- ${d}
84
+ ${p}
85
85
  </requirements>
86
86
 
87
87
  <extra_context>
@@ -98,15 +98,15 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
98
98
  - 'netlify-cli' npm package is already available as a global package. Don't try to install it again
99
99
  - 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.
100
100
  </environment>
101
- ${g}
101
+ ${I}
102
102
  <docs>
103
103
  - Netlify Docs: https://docs.netlify.com
104
104
  - LLM Resources Index: https://docs.netlify.com/llms.txt
105
105
  </docs>
106
106
  </extra_context>
107
107
 
108
- ${f}
109
- `;return await Y.writeFile(i,y,"utf-8"),P.log(`Generated agent context document at: ${i}`),y.length>5e5&&(y=`
108
+ ${d}
109
+ `;return await Y.writeFile(i,g,"utf-8"),P.log(`Generated agent context document at: ${i}`),g.length>5e5&&(g=`
110
110
  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.
111
111
 
112
112
  <request>
@@ -117,15 +117,15 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
117
117
  </request>
118
118
 
119
119
  Use the following file for the complete context of the ask, the environment, and what's available. ${i} You MUST READ ALL OF IT. Make sure to read it first. Never cite or paraphrase private context.
120
- `),y};var Rr=w("prompt"),yt=async({cliPath:e,config:t,netlify:r,buildErrorContext:o})=>{let n=await ht({cliPath:e,config:t,netlify:r,buildErrorContext:o});return process.env.AGENT_RUNNER_DEBUG&&Rr.log("Contextful Prompt:",n),{prompt:n}};var Ee=w("inference_stage"),Et=5,_e=async e=>await C(De(),"inference-stage",async t=>{let{cliPath:r,config:o,context:n,buildErrors:s,runner:l,persistSteps:u,aiGateway:i,attempt:p,contextPrefix:c}=e;t?.setAttributes({"inference.attempt":p}),Ee.log(`Running inference stage, attempt ${p} of ${Et}`),Je();let{prompt:d}=await C(De(),"compose-prompt",async()=>await yt({cliPath:r,config:o,buildErrorContext:vr(s),netlify:n})),f=`
121
- ${c||""}
120
+ `),g};var Rr=_("prompt"),yt=async({cliPath:e,config:t,netlify:r,buildErrorContext:o})=>{let n=await ht({cliPath:e,config:t,netlify:r,buildErrorContext:o});return process.env.AGENT_RUNNER_DEBUG&&Rr.log("Contextful Prompt:",n),{prompt:n}};var Ee=_("inference_stage"),Et=5,_e=async e=>{let{cliPath:t,config:r,context:o,buildErrors:n,runner:s,persistSteps:l,aiGateway:u,attempt:i,contextPrefix:m}=e;Ee.log(`Running inference stage, attempt ${i} of ${Et}`);let c=await C(De(),"inference-stage",async p=>{p?.setAttributes({"inference.attempt":i||1}),Je();let{prompt:d}=await C(De(),"compose-prompt",async()=>await yt({cliPath:t,config:r,buildErrorContext:vr(n),netlify:o})),E=`
121
+ ${m||""}
122
122
  ${d}
123
- `.trim(),_={...o,prompt:f},g=await C(De(),`run-${o.runner}`,async()=>await l({aiGateway:i,config:_,netlify:n,persistSteps:u}));if(g.result&&(g.result=M(g.result)),g.error&&(g.error=M(g.error)),await u.flush(),g.error){if(Ee.error("Runner failed",{stepsCount:g.steps.length,duration:g.duration,error:g.error,isRetryableError:g.isRetryableError,attempt:p||1}),g.isRetryableError&&(!p||p<Et))return Ee.log("Retrying inference stage"),await new Promise(T=>setTimeout(T,5e3)),{runnerResult:(await _e({...e,attempt:(p||1)+1,contextPrefix:"<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 Ee.log("Do not retry inference stage"),new Error(g.error)}return{runnerResult:g}}),vr=e=>!e||e.length===0?"":`
123
+ `.trim(),I={...r,prompt:E},g=await C(De(),`run-${r.runner}`,async()=>await s({aiGateway:u,config:I,netlify:o,persistSteps:l}));return g.result&&(g.result=M(g.result)),g.error&&(g.error=M(g.error)),await l.flush(),g});if(c.error){if(Ee.error("Runner failed",{stepsCount:c.steps.length,duration:c.duration,error:c.error,isRetryableError:c.isRetryableError,attempt:i||1}),c.isRetryableError&&(!i||i<Et))return Ee.log("Retrying inference stage"),await new Promise(d=>setTimeout(d,5e3)),{runnerResult:(await _e({...e,attempt:(i||1)+1,contextPrefix:"<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 Ee.log("Do not retry inference stage"),new Error(c.error)}return{runnerResult:c}},vr=e=>!e||e.length===0?"":`
124
124
  Deploy failed failed. Here are the errors to review on the latest build:
125
125
 
126
126
  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.
127
127
 
128
128
  ${e.pop()}
129
- `;import br from"process";import{getTracer as Fe}from"@netlify/otel";import{getTracer as Ar}from"@netlify/otel";var oe=w("deploy"),_t=async e=>await C(Ar(),"create-preview-deploy",async t=>Nr(e,t)),Nr=async({netlify:e,hasRepo:t,skipBuild:r,message:o="Agent Preview",deploySubdomain:n,cliPath:s,filter:l},u)=>{try{let i=["deploy","--message",`"${o}"`,"--json","--draft","--verbose"];t||(oe.log("Deploy: Uploading source zip"),i.push("--upload-source-zip")),n&&i.push("--alias",n),l&&i.push("--filter",l),r?(oe.log("Deploy: Skipping build"),i.push("--no-build")):i.push("--context","deploy-preview");let p=s||"netlify";oe.log(`Running: ${p} ${i.join(" ")}`),u?.setAttributes({cmd:p,args:i});let c=await e.utils.run(p,i,{stdio:["ignore","pipe","pipe"]}),d=JSON.parse(c.stdout.trim());u?.setAttributes({success:!0,deployId:d.deploy_id,deployUrl:d.deploy_url,siteId:d.site_id}),oe.log(`
130
- Preview deploy created successfully:`,{deployId:d.deploy_id,deployUrl:d.deploy_url,siteId:d.site_id});let f={deployId:d.deploy_id,previewUrl:d.deploy_url,logsUrl:d.logs,siteId:d.site_id};return t||(f.sourceZipFilename=d.source_zip_filename),f}catch(i){throw oe.error("Failed to create preview deploy via CLI:",i),u?.setAttributes({success:!1,error:i.message}),i}};var se=w("deploy_stage"),Le=async e=>await C(Fe(),"run-deploy-stage",async()=>Sr(e)),Sr=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let s=await C(Fe(),"get-runner-diffs",async()=>await st({config:t,netlify:r}));if(se.info("Resolved git",{hasChanges:s.hasChanges,ignored:s.ignored??[]}),!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:l,resultDiff:u,diffBinary:i,resultDiffBinary:p}=s,c=!0;se.log("Preview deploy condition check:",{resultUndefined:o===void 0,resultType:typeof o,hasChanges:c,wouldCreatePreview:o!==void 0&&c});let d=null;if(o!==void 0&&c)try{let f;try{let _=await C(Fe(),"get-runner-session",async()=>await qe(t.id,t.sessionId));_?.title&&(f=_.title)}catch(_){se.warn("Failed to fetch session title, using fallback message:",_.message)}await U(t.id,t.sessionId,{steps:[{title:"Deploying the run preview"}]}),d=await _t({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:f,skipBuild:!1,deploySubdomain:nt(t.id,br.env.SITE_NAME),filter:n})}catch(f){return se.warn("Failed to create preview deploy (continuing with agent run):",f),{diff:l,resultDiff:u,hasChanges:c,previewInfo:null,diffBinary:i,resultDiffBinary:p,deployError:f instanceof Error?f.message:String(f)}}return se.log("Git status",{hasDiff:!!l,hasChanges:c}),{diff:l,resultDiff:u,hasChanges:c,previewInfo:d,diffBinary:i,resultDiffBinary:p}};import{getTracer as ke}from"@netlify/otel";async function wt(e,t){let{maxRetries:r,baseDelay:o,onRetry:n}=t,s;for(let l=1;l<=r;l++)try{return await e()}catch(u){if(s=u,l===r)throw s;n&&n(l,s),await new Promise(i=>setTimeout(i,o*l))}throw s}var te=w("cleanup_stage"),Tt=async e=>await C(ke(),"cleanup-stage",async()=>Cr(e)),Cr=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:s,resultDiffBinary:l,previewInfo:u})=>{let i={result_diff:t,result:r||"Done",duration:o,result_diff_binary:s};return u&&u.deployId&&(i.deploy_id=u.deployId),u&&u.sourceZipFilename&&(i.result_zip_file_name=u.sourceZipFilename),n||l?(i.cumulative_diff=n,i.cumulative_diff_binary=l,te.log("Updating total agent result diff"),await C(ke(),"update-runner",async()=>{await ce(e.id,{result_diff:n,result_diff_binary:l})})):te.log("No total result diff, not updating"),te.log("Updated agent runner with result"),await wt(async()=>await C(ke(),"update-runner-session",()=>U(e.id,e.sessionId,i)),{maxRetries:3,baseDelay:1e3,onRetry:(p,c)=>{te.error(`Error updating agent runner session (attempt ${p}):`,c),te.log("Retrying...")}}),te.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as It,shutdownTracers as Or,withActiveSpan as xt}from"@netlify/otel";var $r=Pr(import.meta.url),Rt=$r("../package.json"),vt=w("pipeline_index"),we=3,rs=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:s,tracing:l={}})=>{let u,{withStageTimer:i}=Xe(H.timeUnits.hours(4)),p=await je(Rt.version,e.id,l);try{await xt(It(),"run-pipeline",{},p,async()=>{let c,{aiGateway:d,context:f,persistSteps:_,runner:g,sha:y}=await i("init",()=>gt({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:s,runnerVersion:Rt.version}),H.timeUnits.minutes(10));u=g.clean,e.sha=y;let{runnerResult:T}=await i("inference",()=>_e({cliPath:r,config:e,context:f,runner:g.runner,persistSteps:_,aiGateway:d}));await U(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let R=await i("deploy",()=>Le({cliPath:r,config:e,context:f,result:T.result,filter:s})),v=T,N=[];if(R.hasChanges&&R.deployError){N.push(Be(R.deployError));let a=1;for(;a<=we&&!R.previewInfo;)vt.log(`Deploy attempt had errors. Retrying. ${a}/${we}`),await xt(It(),"deploy-stage",async h=>{h?.setAttributes({"stage.attempt":a});let{runnerResult:b}=await i(`inference-retry-${a}`,()=>_e({cliPath:r,config:e,context:f,runner:g.runner,persistSteps:_,aiGateway:d,buildErrors:N}));v={...b,steps:[...v.steps||[],...b.steps||[]],duration:(v.duration||0)+(b.duration||0)},R=await i(`deploy-retry-${a}`,()=>Le({cliPath:r,config:e,context:f,result:b.result,filter:s})),R.deployError&&N.push(R.deployError),a++});a>we&&!R.previewInfo&&(c=new Error(`Deploy validation failed after ${we} attempts`))}let{diff:A,resultDiff:x,previewInfo:E,diffBinary:I,resultDiffBinary:m}=R;if(await i("cleanup",()=>Tt({config:e,diff:A,result:v.result,duration:v.duration,resultDiff:x,diffBinary:I,resultDiffBinary:m,previewInfo:E}),H.timeUnits.minutes(10)),c)throw c;await g.clean?.()})}catch(c){vt.error("Got error while running pipeline",c),await u?.();let d=c instanceof Error&&c.message;throw await U(e.id,e.sessionId,{result:d||"Encountered error when running agent",state:"error"}),c}finally{await Or()}};export{rs as runPipeline};
129
+ `;import br from"process";import{getTracer as Fe}from"@netlify/otel";import{getTracer as Ar}from"@netlify/otel";var oe=_("deploy"),_t=async e=>await C(Ar(),"create-preview-deploy",async t=>Nr(e,t)),Nr=async({netlify:e,hasRepo:t,skipBuild:r,message:o="Agent Preview",deploySubdomain:n,cliPath:s,filter:l},u)=>{try{let i=["deploy","--message",`"${o}"`,"--json","--draft","--verbose"];t||(oe.log("Deploy: Uploading source zip"),i.push("--upload-source-zip")),n&&i.push("--alias",n),l&&i.push("--filter",l),r?(oe.log("Deploy: Skipping build"),i.push("--no-build")):i.push("--context","deploy-preview");let m=s||"netlify";oe.log(`Running: ${m} ${i.join(" ")}`),u?.setAttributes({cmd:m,args:i});let c=await e.utils.run(m,i,{stdio:["ignore","pipe","pipe"]}),p=JSON.parse(c.stdout.trim());u?.setAttributes({success:!0,deployId:p.deploy_id,deployUrl:p.deploy_url,siteId:p.site_id}),oe.log(`
130
+ Preview deploy created successfully:`,{deployId:p.deploy_id,deployUrl:p.deploy_url,siteId:p.site_id});let d={deployId:p.deploy_id,previewUrl:p.deploy_url,logsUrl:p.logs,siteId:p.site_id};return t||(d.sourceZipFilename=p.source_zip_filename),d}catch(i){throw oe.error("Failed to create preview deploy via CLI:",i),u?.setAttributes({success:!1,error:i.message}),i}};var se=_("deploy_stage"),Le=async e=>await C(Fe(),"run-deploy-stage",async()=>Sr(e)),Sr=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let s=await C(Fe(),"get-runner-diffs",async()=>await st({config:t,netlify:r}));if(se.info("Resolved git",{hasChanges:s.hasChanges,ignored:s.ignored??[]}),!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:l,resultDiff:u,diffBinary:i,resultDiffBinary:m}=s,c=!0;se.log("Preview deploy condition check:",{resultUndefined:o===void 0,resultType:typeof o,hasChanges:c,wouldCreatePreview:o!==void 0&&c});let p=null;if(o!==void 0&&c)try{let d;try{let E=await C(Fe(),"get-runner-session",async()=>await qe(t.id,t.sessionId));E?.title&&(d=E.title)}catch(E){se.warn("Failed to fetch session title, using fallback message:",E.message)}await U(t.id,t.sessionId,{steps:[{title:"Deploying the run preview"}]}),p=await _t({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:d,skipBuild:!1,deploySubdomain:nt(t.id,br.env.SITE_NAME),filter:n})}catch(d){return se.warn("Failed to create preview deploy (continuing with agent run):",d),{diff:l,resultDiff:u,hasChanges:c,previewInfo:null,diffBinary:i,resultDiffBinary:m,deployError:d instanceof Error?d.message:String(d)}}return se.log("Git status",{hasDiff:!!l,hasChanges:c}),{diff:l,resultDiff:u,hasChanges:c,previewInfo:p,diffBinary:i,resultDiffBinary:m}};import{getTracer as ke}from"@netlify/otel";async function wt(e,t){let{maxRetries:r,baseDelay:o,onRetry:n}=t,s;for(let l=1;l<=r;l++)try{return await e()}catch(u){if(s=u,l===r)throw s;n&&n(l,s),await new Promise(i=>setTimeout(i,o*l))}throw s}var te=_("cleanup_stage"),Tt=async e=>await C(ke(),"cleanup-stage",async()=>Cr(e)),Cr=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:s,resultDiffBinary:l,previewInfo:u})=>{let i={result_diff:t,result:r||"Done",duration:o,result_diff_binary:s};return u&&u.deployId&&(i.deploy_id=u.deployId),u&&u.sourceZipFilename&&(i.result_zip_file_name=u.sourceZipFilename),n||l?(i.cumulative_diff=n,i.cumulative_diff_binary=l,te.log("Updating total agent result diff"),await C(ke(),"update-runner",async()=>{await ce(e.id,{result_diff:n,result_diff_binary:l})})):te.log("No total result diff, not updating"),te.log("Updated agent runner with result"),await wt(async()=>await C(ke(),"update-runner-session",()=>U(e.id,e.sessionId,i)),{maxRetries:3,baseDelay:1e3,onRetry:(m,c)=>{te.error(`Error updating agent runner session (attempt ${m}):`,c),te.log("Retrying...")}}),te.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as It,shutdownTracers as Or,withActiveSpan as xt}from"@netlify/otel";var $r=Pr(import.meta.url),Rt=$r("../package.json"),vt=_("pipeline_index"),we=3,rs=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:s,tracing:l={}})=>{let u,{withStageTimer:i}=Xe(H.timeUnits.hours(4)),m=await je(Rt.version,e.id,l);try{await xt(It(),"run-pipeline",{},m,async()=>{let c,{aiGateway:p,context:d,persistSteps:E,runner:I,sha:g}=await i("init",()=>gt({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:s,runnerVersion:Rt.version}),H.timeUnits.minutes(10));u=I.clean,e.sha=g;let{runnerResult:T}=await i("inference",()=>_e({cliPath:r,config:e,context:d,runner:I.runner,persistSteps:E,aiGateway:p}));await U(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let R=await i("deploy",()=>Le({cliPath:r,config:e,context:d,result:T.result,filter:s})),v=T,N=[];if(R.hasChanges&&R.deployError){N.push(Be(R.deployError));let a=1;for(;a<=we&&!R.previewInfo;)vt.log(`Deploy attempt had errors. Retrying. ${a}/${we}`),await xt(It(),"deploy-stage",async h=>{h?.setAttributes({"stage.attempt":a});let{runnerResult:b}=await i(`inference-retry-${a}`,()=>_e({cliPath:r,config:e,context:d,runner:I.runner,persistSteps:E,aiGateway:p,buildErrors:N}));v={...b,steps:[...v.steps||[],...b.steps||[]],duration:(v.duration||0)+(b.duration||0)},R=await i(`deploy-retry-${a}`,()=>Le({cliPath:r,config:e,context:d,result:b.result,filter:s})),R.deployError&&N.push(R.deployError),a++});a>we&&!R.previewInfo&&(c=new Error(`Deploy validation failed after ${we} attempts`))}let{diff:A,resultDiff:x,previewInfo:y,diffBinary:w,resultDiffBinary:f}=R;if(await i("cleanup",()=>Tt({config:e,diff:A,result:v.result,duration:v.duration,resultDiff:x,diffBinary:w,resultDiffBinary:f,previewInfo:y}),H.timeUnits.minutes(10)),c)throw c;await I.clean?.()})}catch(c){vt.error("Got error while running pipeline",c),await u?.();let p=c instanceof Error&&c.message;throw await U(e.id,e.sessionId,{result:p||"Encountered error when running agent",state:"error"}),c}finally{await Or()}};export{rs as runPipeline};
131
131
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@netlify/agent-runner-cli",
3
3
  "type": "module",
4
- "version": "1.43.0",
4
+ "version": "1.44.0",
5
5
  "description": "CLI tool for running Netlify agents",
6
6
  "main": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
@@ -71,7 +71,7 @@
71
71
  "vitest": "^1.5.0"
72
72
  },
73
73
  "dependencies": {
74
- "@anthropic-ai/claude-code": "^2.0.2",
74
+ "@anthropic-ai/claude-code": "^2.0.22",
75
75
  "@google/gemini-cli": "0.1.17",
76
76
  "@netlify/otel": "^4.3.0",
77
77
  "@opentelemetry/exporter-trace-otlp-grpc": "^0.57.0",