@netlify/agent-runner-cli 1.45.0 → 1.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin-local.js CHANGED
@@ -1,88 +1,88 @@
1
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}">
2
+ import C from"process";import Mt from"path";import Gt from"fs";import Zr from"minimist";import{createRequire as Jr}from"module";import{createTracerProvider as jt}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as We}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as Yt}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as Bt}from"@netlify/otel";import{propagation as Je,context as Xe,W3CTraceContextPropagator as Ht}from"@netlify/otel/opentelemetry";import{OTLPTraceExporter as qt}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 Ne=_("tracing"),ze=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 We(new Se),new We(new qt({url:r.exporterUrl}))],instrumentations:[new Yt({skipHeaders:!0})]}),r.traceparent?(Je.setGlobalPropagator(new Ht),Je.extract(Xe.active(),{traceparent:r.traceparent,isRemote:!0})):Xe.active());function b(e,t,r){return Ne.log(`\u23F3 TRACE: ${t} starting...`),Bt(e,t,r)}var Se=class{export(t,r){for(let o of t)this.logSpan(o);r({code:1})}async shutdown(){}forceFlush(){return Promise.resolve()}logSpan(t){let r=(t.endTime[0]-t.startTime[0])*1e3+(t.endTime[1]-t.startTime[1])/1e6,o=t.attributes,n=[];for(let[l,s]of Object.entries(o))l.includes("duration")&&typeof s=="number"?n.push(`${l}=${s.toFixed(2)}ms`):n.push(`${l}=${s}`);let i=t.status?.code===2?"\u274C":"\u2705",a=n.length>0?` [${n.join(", ")}]`:"";Ne.log(`${i} 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 Ze(e){let t=e.split(`
3
+ `),r=[],o=-1,n=0;for(;n<t.length;){let l=t[n].slice(0,500).toLowerCase();if(Kt.some(m=>l.includes(m))){let m=Math.max(0,n-10,o+1),u=Math.min(t.length-1,n+20),c=[];for(let f=m;f<=u;f++)c.push(t[f]);r.push(c.join(`
4
+ `)),o=u,n=u+1}else n++}if(r.length===0)return e;let i=r.map((a,l)=>`<extracted_error_chunk order="${l+1}">
5
5
  ${a}
6
6
  </extracted_error_chunk>`).join(`
7
7
 
8
- `);return i.length>e.length*.8?e:i}import 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(`
8
+ `);return i.length>e.length*.8?e:i}import Te from"process";import{getTracer as Or}from"@netlify/otel";import le from"process";var pe=le.env.NETLIFY_API_URL,fe=le.env.NETLIFY_API_TOKEN,H=_("api"),be=()=>le.env.NETLIFY_LOCAL_MODE==="true",ge=async(e,t={})=>{if(!pe||!fe)throw new Error("No API URL or token");let r=new URL(e,pe),o={...t,headers:{...t.headers,Authorization:`Bearer ${fe}`}};le.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let n=await fetch(r,o),i=n.ok&&n.status<=299;if(le.env.AGENT_RUNNERS_DEBUG==="true")H.log(`Response headers for ${r}:`),n.headers.forEach((l,s)=>{H.log(` ${s}: ${l}`)});else{let l=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");H.log(`Request ID for ${r}: ${l||"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},Qe=e=>{H.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(pe=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(fe=e.constants.NETLIFY_API_TOKEN)},et=()=>({apiUrl:pe,token:fe}),me=async(e,t)=>be()?(H.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):ge(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),G=async(e,t,r)=>be()?(H.log("Mock API: updateRunnerSession called",{runnerId:e,sessionId:t,data:r}),{id:e,sessionId:t,...r}):ge(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var tt=async(e,t)=>be()?(H.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):ge(`/api/v1/agent_runners/${e}/sessions/${t}`),rt=(e,t,r)=>ge(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}});var Z=_("ai_gateway"),Ce=null;var nt=async()=>{if(Ce)return Ce;Z.log("Fetching available AI gateway providers");let e=await fetch(`${et().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 Ce=t,Z.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},Vt=async(e,t)=>{let o=(await nt()).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},ot=async({netlify:e,config:t})=>{let r,o,n,i,a=e.constants?.SITE_ID;if(!a)throw new Error("No site id");let l=async()=>{clearTimeout(n),Z.log("Requesting AI gateway information");let s=await rt(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 m=o-Date.now()-6e4;m>0&&(n=setTimeout(()=>{l()},m))}};return await Promise.all([l(),nt()]),{get url(){return i},get token(){return r},isModelAvailableForProvider:Vt}};import Y from"process";import he from"path";import Pe from"fs";import{fileURLToPath as Qt}from"url";import{execa as er,execaCommand as An}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 j(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 Q=class extends Wt{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),i=j(n);o(null,i)}};function it(){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"?j(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"?j(o):o;return typeof n=="function"?r(a,n):r(a,n,i)}}var ue=null,st=e=>(ue&&ue.destroy(),ue=new K({totalAllowedTime:e}),ue),at=()=>ue;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((l,s)=>{i=setTimeout(()=>{s(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return a?await Promise.race([r(),a]):await r()}finally{n(),i&&clearTimeout(i)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var tr=Qt(import.meta.url),rr=he.dirname(tr),ye=_("shell"),Oe=new Set,nr={preferLocal:!0},Ee=(e,t,r)=>{let[o,n]=or(t,r),i={...nr,...n},a=er(e,o,i);return ir(a,i),ar(a),a};var or=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},ir=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(Y.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new Q).pipe(Y.stdout),e.stdout?.pipe(new Q).pipe(Y.stdout),e.stderr?.pipe(new Q).pipe(Y.stderr);return}e.stdout?.pipe(Y.stdout),e.stderr?.pipe(Y.stderr)},lt=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(Y.kill(-e.pid,t),ye.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return ye.error("Error killing process:",r),!1}},sr=e=>lt(e,"SIGKILL"),ar=e=>{Oe.add(e);let t=at();if(t){let r=t.onTimesUp(()=>{ye.log(`Global timer expired, killing process ${e.pid}`),lt(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ye.log(`Force killing process ${e.pid} after timeout`),sr(e))},5e3)});e.on("exit",()=>{Oe.delete(e),r()}),e.on("error",()=>{Oe.delete(e),r()})}};function _e(e,t){return!!V(e,t)}function V(e,t){if(Y.env.NODE_PATH){let n=he.join(Y.env.NODE_PATH,".bin",t);if(Pe.existsSync(n))return n}let r=he.join(e,"node_modules",".bin",t);if(Pe.existsSync(r))return r;let o=he.join(rr,"..","node_modules",".bin",t);if(Pe.existsSync(o))return o}var ut="netlify-agent-runner-context.md",$e="task-history",De="netlify-context",F=".netlify",ee="results.md",Le="assets";var lr=_("utils"),ur=e=>new Promise(t=>{setTimeout(t,e)}),ct=(e,t=3e3)=>{let r=!1,o=null,n=[],i=null,a=(...l)=>{if(r)return o=l,new Promise(u=>{n.push(u)});r=!0;let s,m=new Promise(u=>{s=u});return i=(async()=>{await Promise.resolve();let u=await e(...l);for(s(u);;){if(await ur(t),!o)return r=!1,i=null,u;let c=o,f=n;o=null,n=[],u=await e(...c),f.forEach(E=>{E(u)})}})(),m};return a.flush=async()=>{if((r||o)&&i)return await i,a.flush()},a},we=(e,t,r=!1)=>{let o=null,n=null,i=null,a=function(...l){n=l,i=this;let s=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(i,n),n=null,i=null)},t),s&&(e.apply(i,n),n=null,i=null)};return a.cancel=()=>{clearTimeout(o),o=null,n=null,i=null},a.flush=()=>{if(o){clearTimeout(o);let l=n,s=i;o=null,n=null,i=null,e.apply(s,l)}},a},dt=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):lr.error("Could not parse JSON",o))}},pt=(e,t)=>{let n=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let l=`--${t}${n}`;if(l.length>55)return"";let s=60-l.length;if(s<=0)return"";if(s>=i.length+6){let m=Math.min(s-i.length,e.length);return`${i}${e.slice(0,m)}`}return e.slice(0,s)};import{Buffer as ft}from"buffer";import cr from"path";var gt=async({config:e,netlify:t})=>{let r=await pr(t),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};let i=await fr(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 u=(await t.utils.run("git",["diff","--staged","--binary"],a)).stdout,c,f;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await t.utils.run("git",["commit","-m","Agent runner"]),c=(await t.utils.run("git",["diff",e.sha,"HEAD"],a)).stdout;let g=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;c!==g&&(f=ft.from(g).toString("base64"))}let E={hasChanges:!0,diff:s,resultDiff:c,ignored:i};return s!==u&&(E.diffBinary=ft.from(u).toString("base64")),f&&(E.resultDiffBinary=f),E},dr=["?? mise.toml","?? deno.lock",/\?\? .+?\.log/],pr=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
9
+ `).filter(n=>!dr.some(i=>i instanceof RegExp?i.test(n):n===i))).length!==0,status:t.stdout}};var mt=async e=>{let{stdout:t}=await e.utils.run("git",["rev-parse","HEAD"]);return t.trim()},ht=async e=>{let{stdout:t}=await e.utils.run("git",["rev-list","--max-parents=0","HEAD"]);return t.trim()},fr=async e=>{let t=[".netlify","mise.toml","deno.lock","node_modules"],r=[];return e.split(`
10
+ `).forEach(o=>{t.forEach(i=>{[`?? ${i}`,`?? ${i}${cr.sep}`].some(l=>o.startsWith(l))&&r.push(`:!${i}`)});let n=o.match(/\?\? (.+?)\.log$/)?.[1];n&&r.push(`:!${n}.log`)}),r};import mr from"fs/promises";import hr from"os";import Et from"path";import W from"process";import yr from"readline";import Fe from"path";import gr from"fs/promises";var ke=_("agent-output-utils");async function te({initialResult:e,agentName:t,hasError:r}){let o="",n=Fe.join(process.cwd(),F,ee);try{let i=await gr.readFile(n,"utf-8");i&&(o=i,ke.log(`Pulled result from ${Fe.relative(process.cwd(),n)}`))}catch{ke.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 re({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&&ke.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function ne(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=_("runner_claude"),yt="Claude Code",Ie="claude-sonnet-4-5-20250929",Er=({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 Ue({config:e,netlify:t,persistSteps:r,aiGateway:o,continueSession:n,priorAgentSessionId:i}){let a=e,{accountType:l,prompt:s,modelVersionOverrides:m}=a,{model:u}=a,c="";if(o){let{token:p,url:T}=o;if(!p||!T)throw new Error("No token or url provided from AI Gateway");if(m?.claude){let d=m?.claude?.[l];if(d){if(!await o.isModelAvailableForProvider("anthropic",d))throw new Error(`Model override '${d}' is not available for anthropic provider`);u=d}}else if(u){if(!await o.isModelAvailableForProvider("anthropic",u))throw new Error(`Model '${u}' is not available for anthropic provider`)}else await o.isModelAvailableForProvider("anthropic",Ie)?(u=Ie,k.log(`Using default model: ${Ie}`)):k.log(`Default model ${Ie} is not available, proceeding without model specification`);W.env.ANTHROPIC_API_KEY=p,W.env.ANTHROPIC_BASE_URL=T}else if(!W.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let f=[],E=[],x={},I=0,g=0,A,R,S=[V(W.cwd(),"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...u?["--model",u]:[],...n?["--continue"]:[],...n&&i?["--resume",i]:[],"-p",s],v=`${W.env.NVM_BIN}/node`;k.log(`Running ${v} ${S.join(" ")}`);let y=t.utils.run(v,S,{all:!0,env:W.env});y.stdin?.end();let N=we(()=>{r?.({steps:f,duration:g})},250),w=(p,T)=>{let d={...p,id:I};I+=1,E.push(d),f.push(d),T||N.flush(),N(),T&&N.flush()},h=yr.createInterface({input:y.all});return h.on("error",p=>{k.error("Readline interface error",{error:p.message,stack:p.stack})}),h.on("line",p=>{let T=null;try{T=JSON.parse(p)}catch{k.log("Could not parse line",p)}T?.session_id&&T.session_id!==c&&(c=T.session_id),Array.isArray(T?.message?.content)?T.message.content.forEach(d=>{switch(d.type){case"text":{d.text&&w({message:d.text});break}case"image":{typeof d.source=="object"&&d.source&&d.source.type==="base64"&&d.source.media_type?w({message:`![](data:${d.source.media_type};base64,${d.source.data})`}):k.log(`Unsupported image type ${d.source?.type}`,d.source);break}case"tool_use":{if(d.name==="Task"){let P=d.input?.description&&`\`${d.input.description}\``;w({title:[d.name,P].filter(Boolean).join(" ")})}else d.id&&(x[d.id]=d);N.flush();break}case"tool_result":{let P=d.tool_use_id?x[d.tool_use_id]:void 0,ae;if(P){let z=P.input?.file_path&&Et.relative(W.cwd(),P.input.file_path),O=z&&`\`${z}\``;ae=[P.name,O].filter(Boolean).join(" ")}let Ve=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(P?.name||""),B;if(typeof d.content=="string")B=d.content;else if(Array.isArray(d.content)){let z=[];d.content.forEach(O=>{O?.type==="text"&&typeof O.text=="string"?z.push(O.text):O?.type==="image"&&typeof O.source=="object"&&O.source?O.source.type==="base64"&&O.source.media_type?z.push(`![](data:${O.source.media_type};base64,${O.source.data})`):k.log(`Unsupported image type ${O.source.type}`,O.source):k.log(`Unsupported block type ${O?.type}`)}),B=z.join(`
11
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=`\`\`\`
12
+ `)}Ve&&B&&(B=`\`\`\`
13
+ ${B.trim()}
14
+ \`\`\``),w({title:ae,message:B},!0);break}case"thinking":{d.thinking&&w({title:"Thinking",message:d.thinking},!0);break}default:k.log(`Message content type is not supported ${d.type}`,d)}}):T?.type==="result"&&(g=T.duration_ms||0,T.is_error?R=T.result:A=T.result,[E,f].forEach(d=>{d[d.length-1]?.message===A&&d.pop()}))}),await y.catch(p=>{({error:R,result:A}=Er({catchError:p,runCmd:y,error:R,result:A,runnerName:"Claude"}))}),h.close(),N.flush(),{steps:E,duration:g,result:await te({initialResult:A,agentName:yt,hasError:!!R}),error:re({error:R,agentName:yt}),isRetryableError:ne(R),agentSessionId:c}}var _t=async()=>{let e=Et.join(hr.homedir(),".claude");await mr.rm(e,{recursive:!0,force:!0})};import _r from"fs/promises";import wr from"os";import Ir from"path";import oe from"process";import Tr from"readline";var J=_("runner_codex"),wt="Codex CLI",xr=({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 Me({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:i,prompt:a,modelVersionOverrides:l}=e,{model:s}=e;if(n){let{token:v,url:y}=n;if(!v||!y)throw new Error("No token or url provided from AI Gateway");if(l?.codex){let N=l?.codex?.[i];if(N){if(!await n.isModelAvailableForProvider("openai",N))throw new Error(`Model override '${N}' is not available for openai provider`);s=N}}else if(s&&!await n.isModelAvailableForProvider("openai",s))throw new Error(`Model '${s}' is not available for openai provider`);oe.env.OPENAI_API_KEY=v,oe.env.OPENAI_BASE_URL=y}else if(!oe.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let m=[],u=[],c={},f=0,E=0,x,I,g=[V(oe.cwd(),"codex"),"--approval-mode","full-auto",n?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...s?["--model",s]:[],"-q",a].filter(Boolean),A=`${oe.env.NVM_BIN}/node`;J.log(`Running ${A} ${g.join(" ")}`);let R=t.utils.run(A,g,{all:!0,env:{...oe.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),S=Tr.createInterface({input:R.all});return S.on("error",v=>{J.error("Readline interface error",{error:v.message,stack:v.stack})}),S.on("line",v=>{let y=null;try{y=JSON.parse(v)}catch{J.log("Could not parse line",v);return}let N=[],w=!1;if(y?.duration_ms&&(E=y.duration_ms,w=!0),y?.type==="local_shell_call")c[y.call_id]=y;else if(y?.type==="local_shell_call_output"){let h=Rr(c[y.call_id],y);h&&(h.id=f,f+=1,u.push(h),m.push(h),N.push(h),w=!0)}else y?.type==="message"&&y.role==="assistant"?x=y.content.map(h=>h.text).join(`
15
+ `):y?.type==="message"&&y.role==="system"&&(I=y.content.map(h=>h.text).join(`
16
+ `));w&&(r?.({steps:m,duration:E}),o?.({steps:N,duration:E}))}),await R.catch(v=>{let y=xr({catchError:v,runCmd:R,error:I,result:x,runnerName:"Codex"});I=y.error,x=y.result}),S.close(),{steps:u,duration:E,result:await te({initialResult:x,agentName:wt,hasError:!!I}),error:re({error:I,agentName:wt}),isRetryableError:ne(I)}}var It=async()=>{let e=Ir.join(wr.homedir(),".codex");await _r.rm(e,{recursive:!0,force:!0})},vr=new Set(["bash","-lc"]),Rr=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(i=>!vr.has(i)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
17
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.
18
+ \`\`\``)}catch(i){J.error("Could not decode outputMsg",i,t.output)}return{title:o,message:n}};import Ar from"fs/promises";import Nr from"os";import xt from"path";import X from"process";import Sr from"readline";var ie=_("runner_gemini"),Tt="Gemini CLI",br=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(ie.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?(ie.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}):(ie.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),Cr={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 Ge({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:i,prompt:a,modelVersionOverrides:l}=e,{model:s}=e;if(n){let{token:w,url:h}=n;if(!w||!h)throw new Error("No token or url provided from AI Gateway");if(l?.gemini){let p=l?.gemini?.[i];if(p){if(!await n.isModelAvailableForProvider("gemini",p))throw new Error(`Model override '${p}' is not available for gemini provider`);s=p}}else if(s&&!await n.isModelAvailableForProvider("gemini",s))throw new Error(`Model '${s}' is not available for gemini provider`);X.env.GEMINI_API_KEY=w,X.env.GOOGLE_GEMINI_BASE_URL=h}else if(!X.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let m=[],u=[],c=[],f={},E=0,x=0,I,g,A=[V(X.cwd(),"gemini"),...s?["--model",s]:[],"--yolo","-p",a],R=`${X.env.NVM_BIN}/node`;ie.log(`Running ${R} ${A.join(" ")}`);let S=t.utils.run(R,A,{all:!0,env:X.env});S.stdin?.end();let v=we(()=>{r?.({steps:m,duration:x}),o?.({steps:u,duration:x}),u=[]},250),y=(w,h)=>{w.id=E,E+=1,c.push(w),m.push(w),u.push(w),h||v.flush(),v(),h&&v.flush()},N=Sr.createInterface({input:S.all});return N.on("error",w=>{ie.error("Readline interface error",{error:w.message,stack:w.stack})}),N.on("line",w=>{let h=null;try{if(w.startsWith("[API Error")){let p=w.match(/\[api error: (.+?)]$/i)?.[1];h={type:"error",value:dt(p,!1)?.error?.message||p||"Gemini encountered error"}}else h=JSON.parse(w)}catch{return}if(h)switch(h.type){case"thought":{let p=h.value;y({title:p?.subject??"Thinking...",message:p?.description},!0);break}case"content":{h.value&&y({message:h.value});break}case"tool_call_request":{let p=h.value,T=Cr[p.name]??p.name,d=p.args?.path||p.args?.absolute_path,P=d&&xt.relative(X.cwd(),d),ae=p.args?.command,B={title:[T,P&&`\`${P}\``,ae&&`\`${ae}\``].filter(Boolean).join(" ")};f[p.callId]=B,v.flush();break}case"tool_result":{let p=h.value,T=f[p.callId];if(T){let d=[p.resultDisplay,p.responseParts?.functionResponse?.response?.output].find(P=>typeof P=="string"&&P);d&&(T.message=`\`\`\`
19
+ ${d.trim()}
20
+ \`\`\``),y(T,!0)}break}case"result":{x=h.duration_ms,I=h.value,[c,m,u].forEach(p=>{p[p.length-1]?.message===I&&p.pop()});break}case"error":{g=h.value;break}case"finished":break;default:{ie.warn("Unhandled message type:",h.type);break}}}),await S.catch(w=>{({error:g,result:I}=br({catchError:w,runCmd:S,error:g,result:I,runnerName:"Gemini"}))}),N.close(),v.flush(),{steps:c,duration:x,result:await te({initialResult:I,agentName:Tt,hasError:!!g}),error:re({error:g,agentName:Tt}),isRetryableError:ne(g)}}var vt=async()=>{let e=xt.join(Nr.homedir(),".gemini");await Ar.rm(e,{recursive:!0,force:!0})};var Pr={codex:{runner:Me,clean:It},claude:{runner:Ue,clean:_t},gemini:{runner:Ge,clean:vt}},Rt=Pr;var At=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>await b(Or(),"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=Rt[e.runner];if(!a)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let l=$r({apiToken:r});Qe(l);let s=e.useGateway?await ot({netlify:l,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!s}),e.validateAgent&&e.errorLogsPath&&n?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let m=ct(({steps:f=[],duration:E})=>{let x=f.map(I=>({...I,title:I.title?j(I.title):void 0,message:I.message?j(I.message):void 0}));return f.length=0,G(e.id,e.sessionId,{steps:x,duration:E})},t),u;e.hasRepo?e.sha?(u=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(u=await mt(l),await me(e.id,{sha:u}),n?.setAttributes({"init.sha.source":"current_commit"})):(u=await ht(l),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let c=performance.now()-i;return n?.setAttributes({"init.sha":u||"unknown","init.duration.ms":c,"init.status":"success"}),{aiGateway:s,context:l,persistSteps:m,runner:a,sha:u}}),$r=({apiToken:e})=>({constants:{NETLIFY_API_HOST:Te.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||Te.env.NETLIFY_API_TOKEN,SITE_ID:Te.env.SITE_ID,FUNCTIONS_DIST:Te.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:Ee}});import{getTracer as je}from"@netlify/otel";import Dr from"crypto";import q from"fs/promises";import L from"path";import U from"process";var D=_("context"),Lr=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}},Fr=10,kr=async e=>{let{name:t,ext:r}=L.parse(e),o=e,n=L.join(U.cwd(),F,o),i=0;for(;await Ur(n);){if(i>=Fr)throw new Error("Failed to generate context file");o=`${t}-${Dr.randomUUID().slice(0,5)}${r}`,n=L.join(U.cwd(),F,o),i+=1}return o},Ur=async e=>{try{return await q.access(e),!0}catch{return!1}},Mr=async()=>{try{D.log("Fetching Netlify features context...");let e=await fetch("https://docs.netlify.com/ai-context/context-consumers",{signal:AbortSignal.timeout(1e4)});if(!e.ok)throw new Error(`Failed to fetch context consumers: ${e.status} ${e.statusText}`);let t=await e.json();if(!t||typeof t!="object"||!Array.isArray(t.consumers))return D.warn("Invalid response structure: missing or invalid consumers array"),null;let r=t.consumers.find(o=>o&&typeof o=="object"&&o.key==="catchall-consumer");return r?!r.contextScopes||typeof r.contextScopes!="object"?(D.warn("Catchall consumer missing or invalid contextScopes"),null):r:(D.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?D.warn("Netlify features context request timed out"):D.warn("Failed to fetch Netlify features context:",e.message),null}},Gr=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"?D.warn(`Download timeout for ${e}`):D.warn(`Failed to download context file ${e}:`,r.message),!1}},xe=null,jr=async()=>{if(xe)return xe;let e=await Mr();if(!e)return[];let t=L.join(U.cwd(),F,De);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 D.warn(`Invalid scope data for ${n}, skipping...`),null;let a=`${n}.md`,l=L.join(t,a),s=L.join(F,De,a);return D.log(`Downloading ${i.scope} context...`),await Gr(i.endpoint,l)?(D.log(`Downloaded: ${s}`),{scope:i.scope,path:s,key:n}):null});return xe=(await Promise.all(r)).filter(n=>n!==null),xe},Nt=async({cliPath:e,netlify:t,config:r,buildErrorContext:o})=>{let n=Lr(t),i=await kr(ut),a=L.join(U.cwd(),F);await q.mkdir(a,{recursive:!0});let l=L.join(F,i),s=L.join(U.cwd(),l),m=L.join(U.cwd(),F,ee);try{await q.unlink(m),D.log(`Deleted old results file: ${m}`)}catch{}let u=o?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
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>`:"",c="";r.siteContext&&r.siteContext.length!==0&&(c=`
28
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(`
29
+ ${r.siteContext.filter(g=>g.site_context).map(g=>typeof g.site_context=="string"?g.site_context:typeof g.site_context=="object"?JSON.stringify(g.site_context):"").join(`
30
30
 
31
31
  `)}
32
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}
33
+ `);let f="";if(r.sessionHistoryContext?.length){let g=L.join(U.cwd(),F,$e);await q.mkdir(g,{recursive:!0});let A=await Promise.all(r.sessionHistoryContext.map(async(R,S)=>{let v=S+1,y=`attempt-${v}.md`,N=L.join(g,y),w=L.join(F,$e,y),h=`# Task History - Attempt ${v}
34
34
 
35
35
  ## Request - what the user asked for
36
- ${v.request}
36
+ ${R.request}
37
37
 
38
38
  ---
39
39
 
40
40
  ## Response - what the agent replied with after its work
41
41
 
42
- ${v.response}
43
- `;return await q.writeFile(T,l,"utf-8"),P.log(`Created history file: ${m}`),m}));p+=`
42
+ ${R.response}
43
+ `;return await q.writeFile(N,h,"utf-8"),D.log(`Created history file: ${w}`),w}));f+=`
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
- ${R.slice(-5).map(v=>`- ${v}`).join(`
48
+ ${A.slice(-5).map(R=>`- ${R}`).join(`
49
49
  `)}
50
50
 
51
51
  </session_history_context>
52
- `}let _=await Mr(),I="";_.length>0&&(I=`
52
+ `}let E=await jr(),x="";E.length>0&&(x=`
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(w=>`- **${w.scope}**: ${w.path}`).join(`
57
+ ${E.map(g=>`- **${g.scope}**: ${g.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 h=`
62
+ `);let I=`
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>
66
66
  <user_request>
67
67
  ${r.prompt}
68
68
  </user_request>
69
- ${c}
69
+ ${u}
70
70
  </request>
71
71
 
72
72
  <requirements>
73
73
  <responses>
74
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.
75
+ - When work is complete, write a changes summary in ${a}/${ee} 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}/${ee} file.
77
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
78
  - NEVER look into the \`.git\` folder
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}/${$e} folder
83
- - move assets from ${a}/${$e} 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}/${Le} folder
83
+ - move assets from ${a}/${Le} folder to the project assets folder if they are referenced in a code or applied changes
84
84
  </attachements>
85
- ${d}
85
+ ${c}
86
86
  </requirements>
87
87
 
88
88
  <extra_context>
@@ -99,36 +99,36 @@ 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
- ${I}
102
+ ${x}
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
- ${p}
110
- `;return await q.writeFile(s,h,"utf-8"),P.log(`Generated agent context document at: ${s}`),h.length>5e5&&(h=`
109
+ ${f}
110
+ `;return await q.writeFile(s,I,"utf-8"),D.log(`Generated agent context document at: ${s}`),I.length>5e5&&(I=`
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>
114
114
  <user_request>
115
115
  ${r.prompt}
116
116
  </user_request>
117
- ${c}
117
+ ${u}
118
118
  </request>
119
119
 
120
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?"":`
121
+ `),I};var Yr=_("prompt"),St=async({cliPath:e,config:t,netlify:r,buildErrorContext:o})=>{let n=await Nt({cliPath:e,config:t,netlify:r,buildErrorContext:o});return process.env.AGENT_RUNNER_DEBUG&&Yr.log("Contextful Prompt:",n),{prompt:n}};var ve=_("inference_stage"),bt=5,Re=async e=>{let{cliPath:t,config:r,context:o,buildErrors:n,runner:i,persistSteps:a,aiGateway:l,attempt:s,contextPrefix:m,priorAgentSessionId:u}=e;ve.log(`Running inference stage, attempt ${s} of ${bt}`);let c=await b(je(),"inference-stage",async f=>{f?.setAttributes({"inference.attempt":s||1}),it();let{prompt:E}=await b(je(),"compose-prompt",async()=>await St({cliPath:t,config:r,buildErrorContext:Br(n),netlify:o})),x=`
122
+ ${m||""}
123
+ ${E}
124
+ `.trim(),I={...r,prompt:x},g=await b(je(),`run-${r.runner}`,async()=>await i({aiGateway:l,config:I,netlify:o,persistSteps:a,continueSession:!!(s&&s>1),priorAgentSessionId:u}));return g.result&&(g.result=j(g.result)),g.error&&(g.error=j(g.error)),await a.flush(),g});if(c.error){if(ve.error("Runner failed",{stepsCount:c.steps.length,duration:c.duration,error:c.error,isRetryableError:c.isRetryableError,attempt:s||1,agentSessionId:c.agentSessionId}),c.isRetryableError&&(!s||s<bt))return ve.log("Retrying inference stage"),await new Promise(E=>setTimeout(E,5e3)),{runnerResult:(await Re({...e,attempt:(s||1)+1,priorAgentSessionId:c.agentSessionId,contextPrefix:c.agentSessionId?"":"<important> The agent has already started on this work but ran into networking errors trying to complete it. Please continue from where it left off (you can use git commands to see what's currently changed thus far) and do not start over. Here is the full prompt for context: </important>"})).runnerResult};throw ve.log("Do not retry inference stage"),new Error(c.error)}return{runnerResult:c}},Br=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 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(`
130
+ `;import Kr from"process";import{getTracer as Ye}from"@netlify/otel";import{getTracer as Hr}from"@netlify/otel";var ce=_("deploy"),Ct=async e=>await b(Hr(),"create-preview-deploy",async t=>qr(e,t)),qr=async({netlify:e,hasRepo:t,skipBuild:r,message:o="Agent Preview",deploySubdomain:n,cliPath:i,filter:a},l)=>{try{let s=["deploy","--message",`"${o}"`,"--json","--draft","--verbose"];t||(ce.log("Deploy: Uploading source zip"),s.push("--upload-source-zip")),n&&s.push("--alias",n),a&&s.push("--filter",a),r?(ce.log("Deploy: Skipping build"),s.push("--no-build")):s.push("--context","deploy-preview");let m=i||"netlify";ce.log(`Running: ${m} ${s.join(" ")}`),l?.setAttributes({cmd:m,args:s});let u=await e.utils.run(m,s,{stdio:["ignore","pipe","pipe"]}),c=JSON.parse(u.stdout.trim());l?.setAttributes({success:!0,deployId:c.deploy_id,deployUrl:c.deploy_url,siteId:c.site_id}),ce.log(`
131
+ Preview deploy created successfully:`,{deployId:c.deploy_id,deployUrl:c.deploy_url,siteId:c.site_id});let f={deployId:c.deploy_id,previewUrl:c.deploy_url,logsUrl:c.logs,siteId:c.site_id};return t||(f.sourceZipFilename=c.source_zip_filename),f}catch(s){throw ce.error("Failed to create preview deploy via CLI:",s),l?.setAttributes({success:!1,error:s.message}),s}};var de=_("deploy_stage"),Be=async e=>await b(Ye(),"run-deploy-stage",async()=>Vr(e)),Vr=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let i=await b(Ye(),"get-runner-diffs",async()=>await gt({config:t,netlify:r}));if(de.info("Resolved git",{hasChanges:i.hasChanges,ignored:i.ignored??[]}),!i.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:l,diffBinary:s,resultDiffBinary:m}=i,u=!0;de.log("Preview deploy condition check:",{resultUndefined:o===void 0,resultType:typeof o,hasChanges:u,wouldCreatePreview:o!==void 0&&u});let c=null;if(o!==void 0&&u)try{let f;try{let E=await b(Ye(),"get-runner-session",async()=>await tt(t.id,t.sessionId));E?.title&&(f=E.title)}catch(E){de.warn("Failed to fetch session title, using fallback message:",E.message)}await G(t.id,t.sessionId,{steps:[{title:"Deploying the run preview"}]}),c=await Ct({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:f,skipBuild:!1,deploySubdomain:pt(t.id,Kr.env.SITE_NAME),filter:n})}catch(f){return de.warn("Failed to create preview deploy (continuing with agent run):",f),{diff:a,resultDiff:l,hasChanges:u,previewInfo:null,diffBinary:s,resultDiffBinary:m,deployError:f instanceof Error?f.message:String(f)}}return de.log("Git status",{hasDiff:!!a,hasChanges:u}),{diff:a,resultDiff:l,hasChanges:u,previewInfo:c,diffBinary:s,resultDiffBinary:m}};import{getTracer as He}from"@netlify/otel";async function Pt(e,t){let{maxRetries:r,baseDelay:o,onRetry:n}=t,i;for(let a=1;a<=r;a++)try{return await e()}catch(l){if(i=l,a===r)throw i;n&&n(a,i),await new Promise(s=>setTimeout(s,o*a))}throw i}var se=_("cleanup_stage"),Ot=async e=>await b(He(),"cleanup-stage",async()=>Wr(e)),Wr=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:i,resultDiffBinary:a,previewInfo:l})=>{let s={result_diff:t,result:r||"Done",duration:o,result_diff_binary:i};return l&&l.deployId&&(s.deploy_id=l.deployId),l&&l.sourceZipFilename&&(s.result_zip_file_name=l.sourceZipFilename),n||a?(s.cumulative_diff=n,s.cumulative_diff_binary=a,se.log("Updating total agent result diff"),await b(He(),"update-runner",async()=>{await me(e.id,{result_diff:n,result_diff_binary:a})})):se.log("No total result diff, not updating"),se.log("Updated agent runner with result"),await Pt(async()=>await b(He(),"update-runner-session",()=>G(e.id,e.sessionId,s)),{maxRetries:3,baseDelay:1e3,onRetry:(m,u)=>{se.error(`Error updating agent runner session (attempt ${m}):`,u),se.log("Retrying...")}}),se.log("Finished updating agent runner with result"),{sessionUpdate:s}};import{getTracer as $t,shutdownTracers as Xr,withActiveSpan as Dt}from"@netlify/otel";var zr=Jr(import.meta.url),Lt=zr("../package.json"),Ft=_("pipeline_index"),Ae=3,kt=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:i,tracing:a={}})=>{let l,{withStageTimer:s}=st(K.timeUnits.hours(4)),m=await ze(Lt.version,e.id,a);try{await Dt($t(),"run-pipeline",{},m,async()=>{let u,{aiGateway:c,context:f,persistSteps:E,runner:x,sha:I}=await s("init",()=>At({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:i,runnerVersion:Lt.version}),K.timeUnits.minutes(10));l=x.clean,e.sha=I;let{runnerResult:g}=await s("inference",()=>Re({cliPath:r,config:e,context:f,runner:x.runner,persistSteps:E,aiGateway:c}));await G(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let A=await s("deploy",()=>Be({cliPath:r,config:e,context:f,result:g.result,filter:i})),R=g,S=[];if(A.hasChanges&&A.deployError){S.push(Ze(A.deployError));let p=1;for(;p<=Ae&&!A.previewInfo;)Ft.log(`Deploy attempt had errors. Retrying. ${p}/${Ae}`),await Dt($t(),"deploy-stage",async T=>{T?.setAttributes({"stage.attempt":p});let{runnerResult:d}=await s(`inference-retry-${p}`,()=>Re({cliPath:r,config:e,context:f,runner:x.runner,persistSteps:E,aiGateway:c,buildErrors:S,priorAgentSessionId:g.agentSessionId}));R={...d,steps:[...R.steps||[],...d.steps||[]],duration:(R.duration||0)+(d.duration||0)},A=await s(`deploy-retry-${p}`,()=>Be({cliPath:r,config:e,context:f,result:d.result,filter:i})),A.deployError&&S.push(A.deployError),p++});p>Ae&&!A.previewInfo&&(u=new Error(`Deploy validation failed after ${Ae} attempts`))}let{diff:v,resultDiff:y,previewInfo:N,diffBinary:w,resultDiffBinary:h}=A;if(await s("cleanup",()=>Ot({config:e,diff:v,result:R.result,duration:R.duration,resultDiff:y,diffBinary:w,resultDiffBinary:h,previewInfo:N}),K.timeUnits.minutes(10)),u)throw u;await x.clean?.()})}catch(u){Ft.error("Got error while running pipeline",u),await l?.();let c=u instanceof Error&&u.message;throw await G(e.id,e.sessionId,{result:c||"Encountered error when running agent",state:"error"}),u}finally{await Xr()}};import Ut from"crypto";var $=_("bin_local"),M=Zr(C.argv.slice(2),{string:["cwd","cli-path","filter","prompt","runner","model","netlify-api-token"],boolean:["verbose","help"],alias:{h:"help",v:"verbose"}}),Ke=()=>{console.log(`
132
132
  agent-runner-cli-local - Run Netlify agent runner locally without API connections
133
133
 
134
134
  USAGE:
@@ -160,6 +160,6 @@ NOTE:
160
160
  This local mode mocks all Netlify API calls. The agent will run through
161
161
  the full pipeline including inference and deployment, but API calls will
162
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}}
163
+ `)};M.help&&(Ke(),C.exit(0));M.prompt||($.error("Error: --prompt is required"),Ke(),C.exit(1));M["netlify-api-token"]||($.error("Error: --netlify-api-token is required - generate a PAT from your Netlify user settings"),Ke(),C.exit(1));try{let e=M.cwd||C.cwd(),t=Mt.join(e,".netlify","netlify-agent-runner-context*");Gt.rmSync(t,{recursive:!0,force:!0});let r;try{r=await Qr(e)}catch(l){$.error(l.message),$.error(`
164
+ To link this directory to a Netlify site, run:`),$.error(" netlify link"),C.exit(1)}let o=`local-${Ut.randomBytes(8).toString("hex")}`,n=`session-${Ut.randomBytes(8).toString("hex")}`,i=M.runner||"claude";$.log("Starting agent runner in local mode",{runnerId:o,sessionId:n,siteId:r,cwd:e,runner:i});let a={id:o,sessionId:n,prompt:M.prompt,runner:i,model:M.model,accountType:"local",validateAgent:!1,validateAgentWithBuild:!1,sessionHistoryContext:[],siteContext:[],hasRepo:!0,useGateway:!0,sha:void 0,modelVersionOverrides:{}};C.env.NETLIFY_LOCAL_MODE="true",C.env.NETLIFY_API_HOST="api.netlify.com",C.env.NETLIFY_API_TOKEN=M["netlify-api-token"],C.env.SITE_ID=r,C.env.NETLIFY_TEAM_ID="local-team-id",C.env.NETLIFY_AGENT_RUNNER_USER_ID="local-user-id",C.env.SITE_NAME="local-site",i==="claude"?_e(e,"claude")||($.log("Claude CLI not found, installing..."),await qe(e,"@anthropic-ai/claude-code")):i==="gemini"?_e(e,"gemini")||($.log("Gemini CLI not found, installing..."),await qe(e,"@google/gemini-cli@0.1.17")):i==="codex"?_e(e,"codex")||($.log("Codex CLI not found, installing..."),await qe(e,"my-codex-no-sandbox")):($.error(`Unknown runner: ${i}`),C.exit(1)),await kt({config:a,cwd:e,cliPath:M["cli-path"],filter:M.filter,tracing:{exporterUrl:void 0,traceparent:void 0}}),$.info("Finished agent (local mode)"),C.exit(0)}catch(e){$.error("Error running agent pipeline (local mode):",e),C.exit(1)}function qe(e,t){return new Promise((r,o)=>{Ee("npm",["install",t,"--no-save"],{cwd:e}).then(({stdout:n})=>{$.log(`${t} installed: ${n}`),r()}).catch(n=>{$.error(`Error installing ${t}: ${n.stderr||n.message}`),o(n)})})}async function Qr(e){let t=Mt.join(e,".netlify","state.json");try{let r=await Gt.readFileSync(t,"utf-8"),o=JSON.parse(r);if(!o.siteId)throw new Error(`No siteId found in ${t}. Please link this directory to a Netlify site using 'netlify link'.`);return $.log(`Found site ID from state file: ${o.siteId}`),o.siteId}catch(r){throw r.code==="ENOENT"?new Error(`No .netlify/state.json found in ${e}. Please link this directory to a Netlify site using 'netlify link'.`):r}}
165
165
  //# sourceMappingURL=bin-local.js.map