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