@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.js CHANGED
@@ -1,88 +1,88 @@
1
1
  #!/usr/bin/env node
2
- import qe from"process";import sn from"minimist";import{createRequire as zr}from"module";import{createTracerProvider as Bt}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as Ke}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as Ht}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as qt}from"@netlify/otel";import{propagation as Ve,context as We,W3CTraceContextPropagator as Kt}from"@netlify/otel/opentelemetry";import{OTLPTraceExporter as Vt}from"@opentelemetry/exporter-trace-otlp-grpc";function E(e){let t=!process.env.VITEST;return{log:(...r)=>{t&&console.log(`[AR]-[${e}]`,...r)},error:(...r)=>{t&&console.error(`[AR]-[ERROR]-[${e}]`,...r)},warn:(...r)=>{t&&console.warn(`[AR]-[WARN]-[${e}]`,...r)},info:(...r)=>{t&&console.info(`[AR]-[${e}]`,...r)},debug:(...r)=>{t&&console.debug(`[AR]-[DEBUG]-[${e}]`,...r)}}}var Ie=E("tracing"),Je=async(e,t,r)=>(await Bt({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new Ke(new xe),new Ke(new Vt({url:r.exporterUrl}))],instrumentations:[new Ht({skipHeaders:!0})]}),r.traceparent?(Ve.setGlobalPropagator(new Kt),Ve.extract(We.active(),{traceparent:r.traceparent,isRemote:!0})):We.active());function S(e,t,r){return Ie.log(`\u23F3 TRACE: ${t} starting...`),qt(e,t,r)}var xe=class{export(t,r){for(let o of t)this.logSpan(o);r({code:1})}async shutdown(){}forceFlush(){return Promise.resolve()}logSpan(t){let r=(t.endTime[0]-t.startTime[0])*1e3+(t.endTime[1]-t.startTime[1])/1e6,o=t.attributes,n=[];for(let[u,i]of Object.entries(o))u.includes("duration")&&typeof i=="number"?n.push(`${u}=${i.toFixed(2)}ms`):n.push(`${u}=${i}`);let s=t.status?.code===2?"\u274C":"\u2705",a=n.length>0?` [${n.join(", ")}]`:"";Ie.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${a}`),t.status?.code===2&&t.status.message&&Ie.log(` \u274C Error: ${t.status.message}`)}};var Wt=["error","failed","exception","fatal","panic","abort","crash"];function Xe(e){let t=e.split(`
3
- `),r=[],o=-1,n=0;for(;n<t.length;){let u=t[n].slice(0,500).toLowerCase();if(Wt.some(f=>u.includes(f))){let f=Math.max(0,n-10,o+1),c=Math.min(t.length-1,n+20),p=[];for(let d=f;d<=c;d++)p.push(t[d]);r.push(p.join(`
4
- `)),o=c,n=c+1}else n++}if(r.length===0)return e;let s=r.map((a,u)=>`<extracted_error_chunk order="${u+1}">
2
+ import Ve from"process";import ln from"minimist";import{createRequire as Qr}from"module";import{createTracerProvider as qt}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as Je}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as Kt}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as Vt}from"@netlify/otel";import{propagation as Xe,context as ze,W3CTraceContextPropagator as Wt}from"@netlify/otel/opentelemetry";import{OTLPTraceExporter as Jt}from"@opentelemetry/exporter-trace-otlp-grpc";function y(e){let t=!process.env.VITEST;return{log:(...r)=>{t&&console.log(`[AR]-[${e}]`,...r)},error:(...r)=>{t&&console.error(`[AR]-[ERROR]-[${e}]`,...r)},warn:(...r)=>{t&&console.warn(`[AR]-[WARN]-[${e}]`,...r)},info:(...r)=>{t&&console.info(`[AR]-[${e}]`,...r)},debug:(...r)=>{t&&console.debug(`[AR]-[DEBUG]-[${e}]`,...r)}}}var Ne=y("tracing"),Ze=async(e,t,r)=>(await qt({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new Je(new ve),new Je(new Jt({url:r.exporterUrl}))],instrumentations:[new Kt({skipHeaders:!0})]}),r.traceparent?(Xe.setGlobalPropagator(new Wt),Xe.extract(ze.active(),{traceparent:r.traceparent,isRemote:!0})):ze.active());function C(e,t,r){return Ne.log(`\u23F3 TRACE: ${t} starting...`),Vt(e,t,r)}var ve=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,i]of Object.entries(o))l.includes("duration")&&typeof i=="number"?n.push(`${l}=${i.toFixed(2)}ms`):n.push(`${l}=${i}`);let s=t.status?.code===2?"\u274C":"\u2705",a=n.length>0?` [${n.join(", ")}]`:"";Ne.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${a}`),t.status?.code===2&&t.status.message&&Ne.log(` \u274C Error: ${t.status.message}`)}};var Xt=["error","failed","exception","fatal","panic","abort","crash"];function Qe(e){let t=e.split(`
3
+ `),r=[],o=-1,n=0;for(;n<t.length;){let l=t[n].slice(0,500).toLowerCase();if(Xt.some(g=>l.includes(g))){let g=Math.max(0,n-10,o+1),u=Math.min(t.length-1,n+20),c=[];for(let f=g;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 s=r.map((a,l)=>`<extracted_error_chunk order="${l+1}">
5
5
  ${a}
6
6
  </extracted_error_chunk>`).join(`
7
7
 
8
- `);return s.length>e.length*.8?e:s}import ye from"process";import{getTracer as Dr}from"@netlify/otel";import se from"process";var ue=se.env.NETLIFY_API_URL,ce=se.env.NETLIFY_API_TOKEN,Y=E("api"),Ne=()=>se.env.NETLIFY_LOCAL_MODE==="true",pe=async(e,t={})=>{if(!ue||!ce)throw new Error("No API URL or token");let r=new URL(e,ue),o={...t,headers:{...t.headers,Authorization:`Bearer ${ce}`}};se.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let n=await fetch(r,o),s=n.ok&&n.status<=299;if(se.env.AGENT_RUNNERS_DEBUG==="true")Y.log(`Response headers for ${r}:`),n.headers.forEach((u,i)=>{Y.log(` ${i}: ${u}`)});else{let u=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");Y.log(`Request ID for ${r}: ${u||"N/A"}`)}if(s||Y.error(`Got status ${n.status} for request ${r}`),t.raw){if(!s)throw n;return n}let a=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!s)throw a;return a},ze=e=>{Y.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(ue=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(ce=e.constants.NETLIFY_API_TOKEN)},Ze=()=>({apiUrl:ue,token:ce}),de=async(e,t)=>Ne()?(Y.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):pe(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),G=async(e,t,r)=>Ne()?(Y.log("Mock API: updateRunnerSession called",{runnerId:e,sessionId:t,data:r}),{id:e,sessionId:t,...r}):pe(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var Qe=async(e,t)=>Ne()?(Y.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):pe(`/api/v1/agent_runners/${e}/sessions/${t}`),et=(e,t,r)=>pe(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}});var J=E("ai_gateway"),ve=null;var tt=async()=>{if(ve)return ve;J.log("Fetching available AI gateway providers");let e=await fetch(`${Ze().apiUrl}/api/v1/ai-gateway/providers`);if(!e.ok)throw new Error(`Failed to fetch AI gateway providers: ${e.statusText}`);let t=await e.json();return ve=t,J.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},Jt=async(e,t)=>{let o=(await tt()).providers[e];if(!o)return J.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return J.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},rt=async({netlify:e,config:t})=>{let r,o,n,s,a=e.constants?.SITE_ID;if(!a)throw new Error("No site id");let u=async()=>{clearTimeout(n),J.log("Requesting AI gateway information");let i=await et(a,t.id,t.sessionId);if({token:r,url:s}=i,o=i.expires_at?i.expires_at*1e3:void 0,J.log("Got AI gateway information",{token:!!r,expiresAt:o,url:s}),o){let f=o-Date.now()-6e4;f>0&&(n=setTimeout(()=>{u()},f))}};return await Promise.all([u(),tt()]),{get url(){return s},get token(){return r},isModelAvailableForProvider:Jt}};import j from"process";import fe from"path";import Ae from"fs";import{fileURLToPath as tr}from"url";import{execa as rr,execaCommand as On}from"execa";import{Transform as Xt}from"stream";var zt=new Set(["NODE_ENV","PATH","HOME","USER","USERNAME","SHELL","PWD","OLDPWD","TMPDIR","TMP","TEMP","LANG","TERM","EDITOR","PAGER","OS","PROCESSOR_ARCHITECTURE","PROCESSOR_IDENTIFIER","SYSTEMROOT","WINDIR","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","APPDATA","LOCALAPPDATA","NODE_OPTIONS","NODE_PATH","NODE_DEBUG","NODE_NO_WARNINGS","npm_config_registry","npm_config_cache","npm_execpath","npm_node_execpath","CI","GITHUB_ACTIONS","GITHUB_WORKSPACE","GITHUB_REPOSITORY","GITHUB_REF","BUILDKITE","BUILDKITE_BRANCH","BUILDKITE_COMMIT","BUILDKITE_BUILD_NUMBER","JENKINS_URL","TRAVIS","CIRCLECI","DISPLAY","COLORTERM","TERM_PROGRAM","TERM_PROGRAM_VERSION","COLUMNS","LINES","HISTSIZE","HISTFILE","NETLIFY_AGENT_RUNNER_ID","NETLIFY_AGENT_RUNNER_SESSION_ID","NETLIFY_AGENT_RUNNER_PROMPT","NETLIFY_AGENT_RUNNER_AGENT","NETLIFY_AGENT_RUNNER_MODEL","NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED","NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED","ERROR_LOGS_PATH","NETLIFY_AGENT_RUNNER_CONTEXT","NETLIFY_AGENT_RUNNER_HAS_REPO","NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED","NETLIFY_AGENT_RUNNER_SHA","NETLIFY_TEAM_TYPE","AGENT_RUNNERS_DEBUG","NETLIFY_TEAM_ID","NETLIFY_AGENT_RUNNER_USER_ID","SITE_NAME"]),Zt=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function Qt(){return Object.entries(process.env).filter(([e,t])=>!(!t||zt.has(e)||Zt.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function M(e){if(typeof e!="string")return e;let t=Qt();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(er(o),"g");r=r.replace(n,"******")}),r}function er(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var X=class extends Xt{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),s=M(n);o(null,s)}};function nt(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(o,n,s){let a=typeof o=="string"?M(o):o;return typeof n=="function"?t(a,n):t(a,n,s)},process.stderr.write=function(o,n,s){let a=typeof o=="string"?M(o):o;return typeof n=="function"?r(a,n):r(a,n,s)}}var ie=null,ot=e=>(ie&&ie.destroy(),ie=new H({totalAllowedTime:e}),ie),st=()=>ie;var H=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,o)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let n=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),s=null,a=null;o!==void 0&&(a=new Promise((u,i)=>{s=setTimeout(()=>{i(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return a?await Promise.race([r(),a]):await r()}finally{n(),s&&clearTimeout(s)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var nr=tr(import.meta.url),or=fe.dirname(nr),ge=E("shell"),Se=new Set,sr={preferLocal:!0},it=(e,t,r)=>{let[o,n]=ir(t,r),s={...sr,...n},a=rr(e,o,s);return ar(a,s),ur(a),a};var ir=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},ar=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(j.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new X).pipe(j.stdout),e.stdout?.pipe(new X).pipe(j.stdout),e.stderr?.pipe(new X).pipe(j.stderr);return}e.stdout?.pipe(j.stdout),e.stderr?.pipe(j.stderr)},at=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(j.kill(-e.pid,t),ge.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return ge.error("Error killing process:",r),!1}},lr=e=>at(e,"SIGKILL"),ur=e=>{Se.add(e);let t=st();if(t){let r=t.onTimesUp(()=>{ge.log(`Global timer expired, killing process ${e.pid}`),at(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ge.log(`Force killing process ${e.pid} after timeout`),lr(e))},5e3)});e.on("exit",()=>{Se.delete(e),r()}),e.on("error",()=>{Se.delete(e),r()})}};function z(e,t){if(j.env.NODE_PATH){let n=fe.join(j.env.NODE_PATH,".bin",t);if(Ae.existsSync(n))return n}let r=fe.join(e,"node_modules",".bin",t);if(Ae.existsSync(r))return r;let o=fe.join(or,"..","node_modules",".bin",t);if(Ae.existsSync(o))return o}var lt="netlify-agent-runner-context.md",Ce="task-history",be="netlify-context",F=".netlify",Z="results.md",Pe="assets",Oe="other",Le="personal";var De="enterprise",Fe="free",ut=[Le,"pro",De,Fe];var ct=E("utils"),cr=e=>new Promise(t=>{setTimeout(t,e)}),pt=(e,t=3e3)=>{let r=!1,o=null,n=[],s=null,a=(...u)=>{if(r)return o=u,new Promise(c=>{n.push(c)});r=!0;let i,f=new Promise(c=>{i=c});return s=(async()=>{await Promise.resolve();let c=await e(...u);for(i(c);;){if(await cr(t),!o)return r=!1,s=null,c;let p=o,d=n;o=null,n=[],c=await e(...p),d.forEach(y=>{y(c)})}})(),f};return a.flush=async()=>{if((r||o)&&s)return await s,a.flush()},a},me=(e,t,r=!1)=>{let o=null,n=null,s=null,a=function(...u){n=u,s=this;let i=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(s,n),n=null,s=null)},t),i&&(e.apply(s,n),n=null,s=null)};return a.cancel=()=>{clearTimeout(o),o=null,n=null,s=null},a.flush=()=>{if(o){clearTimeout(o);let u=n,i=s;o=null,n=null,s=null,e.apply(i,u)}},a},he=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):ct.error("Could not parse JSON",o))}},dt=(e,t)=>{let n=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let u=`--${t}${n}`;if(u.length>55)return"";let i=60-u.length;if(i<=0)return"";if(i>=s.length+6){let f=Math.min(i-s.length,e.length);return`${s}${e.slice(0,f)}`}return e.slice(0,i)},pr=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!ut.some(t=>t in e),ft=()=>{let e={},t={codex:process.env.NETLIFY_FF_AGENT_RUNNER_CODEX_VERSION,claude:process.env.NETLIFY_FF_AGENT_RUNNER_CLAUDE_VERSION,gemini:process.env.NETLIFY_FF_AGENT_RUNNER_GEMINI_VERSION};return Object.entries(t).forEach(([r,o])=>{if(o){let n=`NETLIFY_FF_AGENT_RUNNER_${r.toUpperCase()}_VERSION`;try{let s=JSON.parse(o);pr(s)&&(e[r]=s)}catch(s){let u=s instanceof SyntaxError?"Invalid JSON":s.message;ct.error(`Could not parse ${r} model version override from ${n}: ${u}`)}}}),e};import{Buffer as gt}from"buffer";import dr from"path";var mt=async({config:e,netlify:t})=>{let r=await gr(t),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};let s=await mr(n);await t.utils.run("git",["add",".",...s]);let a={stdio:["ignore","pipe","pipe"]},i=(await t.utils.run("git",["diff","--staged"],a)).stdout;if(o=!!i,!o)return{hasChanges:!1,ignored:s};let c=(await t.utils.run("git",["diff","--staged","--binary"],a)).stdout,p,d;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await t.utils.run("git",["commit","-m","Agent runner"]),p=(await t.utils.run("git",["diff",e.sha,"HEAD"],a)).stdout;let T=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;p!==T&&(d=gt.from(T).toString("base64"))}let y={hasChanges:!0,diff:i,resultDiff:p,ignored:s};return i!==c&&(y.diffBinary=gt.from(c).toString("base64")),d&&(y.resultDiffBinary=d),y},fr=["?? mise.toml","?? deno.lock",/\?\? .+?\.log/],gr=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
9
- `).filter(n=>!fr.some(s=>s instanceof RegExp?s.test(n):n===s))).length!==0,status:t.stdout}};var ht=async e=>{let{stdout:t}=await e.utils.run("git",["rev-parse","HEAD"]);return t.trim()},Et=async e=>{let{stdout:t}=await e.utils.run("git",["rev-list","--max-parents=0","HEAD"]);return t.trim()},mr=async e=>{let t=[".netlify","mise.toml","deno.lock","node_modules"],r=[];return e.split(`
10
- `).forEach(o=>{t.forEach(s=>{[`?? ${s}`,`?? ${s}${dr.sep}`].some(u=>o.startsWith(u))&&r.push(`:!${s}`)});let n=o.match(/\?\? (.+?)\.log$/)?.[1];n&&r.push(`:!${n}.log`)}),r};import Er from"fs/promises";import yr from"os";import _t from"path";import q from"process";import _r from"readline";import $e from"path";import hr from"fs/promises";var Ue=E("agent-output-utils");async function Q({initialResult:e,agentName:t,hasError:r}){let o="",n=$e.join(process.cwd(),F,Z);try{let s=await hr.readFile(n,"utf-8");s&&(o=s,Ue.log(`Pulled result from ${$e.relative(process.cwd(),n)}`))}catch{Ue.log(`No results file found at ${$e.relative(process.cwd(),n)}`)}return o||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function ee({error:e,agentName:t}){let r=e&&typeof e=="object"?JSON.stringify(e):e,o=r?.replace(/\s+/g," ").trim().toLowerCase()||"",n="";return o?.includes("ai gateway is not available for your account")||o?.includes("ai gateway is not enabled for your account")?n="AI Gateway is currently not available on your account. Please confirm your account meets the criteria for using Agent Runners and AI Gateway and that your account has remaining AI Gateway inference credits available. Reach out to Netlify support if this is unexpected.":o?.includes("error when talking to gemini api")?n="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":(o?.includes("connection closed prematurely")||o?.includes("499")&&t.toLowerCase().includes("gemini"))&&(n=`The ${t} models were currently overloaded. Please try again or use a different available agent.`),o?.includes("request timed out")&&(n=`The ${t} API request's have timed out. Please try again or use a different available agent.`),o?.includes("network error")&&(n=`The ${t} agent is having network issues. Please try again or use a different available agent.`),n&&Ue.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function te(e){if(!e)return!1;let r=(e&&typeof e=="object"?JSON.stringify(e):e)?.replace(/\s+/g," ").trim().toLowerCase()||"";return!!(r?.includes("error when talking to gemini api")||r?.includes("499")||r?.includes("connection closed prematurely")||r?.includes("request timed out")||r?.includes("network error"))}var $=E("runner_claude"),yt="Claude Code",Ee="claude-sonnet-4-5-20250929",Tr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>($.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?($.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):($.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function ke({config:e,netlify:t,persistSteps:r,aiGateway:o}){let n=e,{accountType:s,prompt:a,modelVersionOverrides:u}=n,{model:i}=n;if(o){let{token:R,url:h}=o;if(!R||!h)throw new Error("No token or url provided from AI Gateway");if(u?.claude){let l=u?.claude?.[s];if(l){if(!await o.isModelAvailableForProvider("anthropic",l))throw new Error(`Model override '${l}' is not available for anthropic provider`);i=l}}else if(i){if(!await o.isModelAvailableForProvider("anthropic",i))throw new Error(`Model '${i}' is not available for anthropic provider`)}else await o.isModelAvailableForProvider("anthropic",Ee)?(i=Ee,$.log(`Using default model: ${Ee}`)):$.log(`Default model ${Ee} is not available, proceeding without model specification`);q.env.ANTHROPIC_API_KEY=R,q.env.ANTHROPIC_BASE_URL=h}else if(!q.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let f=[],c=[],p={},d=0,y=0,w,m,T=[z(q.cwd(),"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...i?["--model",i]:[],"-p",a],x=`${q.env.NVM_BIN}/node`;$.log(`Running ${x} ${T.join(" ")}`);let N=t.utils.run(x,T,{all:!0,env:q.env});N.stdin?.end();let v=me(()=>{r?.({steps:f,duration:y})},250),I=(R,h)=>{let l={...R,id:d};d+=1,c.push(l),f.push(l),h||v.flush(),v(),h&&v.flush()},_=_r.createInterface({input:N.all});return _.on("error",R=>{$.error("Readline interface error",{error:R.message,stack:R.stack})}),_.on("line",R=>{let h=null;try{h=JSON.parse(R)}catch{$.log("Could not parse line",R)}Array.isArray(h?.message?.content)?h.message.content.forEach(l=>{switch(l.type){case"text":{l.text&&I({message:l.text});break}case"image":{typeof l.source=="object"&&l.source&&l.source.type==="base64"&&l.source.media_type?I({message:`![](data:${l.source.media_type};base64,${l.source.data})`}):$.log(`Unsupported image type ${l.source?.type}`,l.source);break}case"tool_use":{if(l.name==="Task"){let g=l.input?.description&&`\`${l.input.description}\``;I({title:[l.name,g].filter(Boolean).join(" ")})}else l.id&&(p[l.id]=l);v.flush();break}case"tool_result":{let g=l.tool_use_id?p[l.tool_use_id]:void 0,P;if(g){let k=g.input?.file_path&&_t.relative(q.cwd(),g.input.file_path),A=k&&`\`${k}\``;P=[g.name,A].filter(Boolean).join(" ")}let O=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(g?.name||""),D;if(typeof l.content=="string")D=l.content;else if(Array.isArray(l.content)){let k=[];l.content.forEach(A=>{A?.type==="text"&&typeof A.text=="string"?k.push(A.text):A?.type==="image"&&typeof A.source=="object"&&A.source?A.source.type==="base64"&&A.source.media_type?k.push(`![](data:${A.source.media_type};base64,${A.source.data})`):$.log(`Unsupported image type ${A.source.type}`,A.source):$.log(`Unsupported block type ${A?.type}`)}),D=k.join(`
8
+ `);return s.length>e.length*.8?e:s}import Te from"process";import{getTracer as $r}from"@netlify/otel";import ae from"process";var pe=ae.env.NETLIFY_API_URL,de=ae.env.NETLIFY_API_TOKEN,Y=y("api"),Ae=()=>ae.env.NETLIFY_LOCAL_MODE==="true",fe=async(e,t={})=>{if(!pe||!de)throw new Error("No API URL or token");let r=new URL(e,pe),o={...t,headers:{...t.headers,Authorization:`Bearer ${de}`}};ae.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let n=await fetch(r,o),s=n.ok&&n.status<=299;if(ae.env.AGENT_RUNNERS_DEBUG==="true")Y.log(`Response headers for ${r}:`),n.headers.forEach((l,i)=>{Y.log(` ${i}: ${l}`)});else{let l=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");Y.log(`Request ID for ${r}: ${l||"N/A"}`)}if(s||Y.error(`Got status ${n.status} for request ${r}`),t.raw){if(!s)throw n;return n}let a=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!s)throw a;return a},et=e=>{Y.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&&(de=e.constants.NETLIFY_API_TOKEN)},tt=()=>({apiUrl:pe,token:de}),ge=async(e,t)=>Ae()?(Y.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):fe(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),k=async(e,t,r)=>Ae()?(Y.log("Mock API: updateRunnerSession called",{runnerId:e,sessionId:t,data:r}),{id:e,sessionId:t,...r}):fe(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var rt=async(e,t)=>Ae()?(Y.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):fe(`/api/v1/agent_runners/${e}/sessions/${t}`),nt=(e,t,r)=>fe(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}});var X=y("ai_gateway"),Se=null;var ot=async()=>{if(Se)return Se;X.log("Fetching available AI gateway providers");let e=await fetch(`${tt().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,X.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},zt=async(e,t)=>{let o=(await ot()).providers[e];if(!o)return X.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return X.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},st=async({netlify:e,config:t})=>{let r,o,n,s,a=e.constants?.SITE_ID;if(!a)throw new Error("No site id");let l=async()=>{clearTimeout(n),X.log("Requesting AI gateway information");let i=await nt(a,t.id,t.sessionId);if({token:r,url:s}=i,o=i.expires_at?i.expires_at*1e3:void 0,X.log("Got AI gateway information",{token:!!r,expiresAt:o,url:s}),o){let g=o-Date.now()-6e4;g>0&&(n=setTimeout(()=>{l()},g))}};return await Promise.all([l(),ot()]),{get url(){return s},get token(){return r},isModelAvailableForProvider:zt}};import M from"process";import me from"path";import Ce from"fs";import{fileURLToPath as nr}from"url";import{execa as or,execaCommand as Dn}from"execa";import{Transform as Zt}from"stream";var Qt=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"]),er=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function tr(){return Object.entries(process.env).filter(([e,t])=>!(!t||Qt.has(e)||er.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function G(e){if(typeof e!="string")return e;let t=tr();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(rr(o),"g");r=r.replace(n,"******")}),r}function rr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var z=class extends Zt{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),s=G(n);o(null,s)}};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,s){let a=typeof o=="string"?G(o):o;return typeof n=="function"?t(a,n):t(a,n,s)},process.stderr.write=function(o,n,s){let a=typeof o=="string"?G(o):o;return typeof n=="function"?r(a,n):r(a,n,s)}}var le=null,at=e=>(le&&le.destroy(),le=new H({totalAllowedTime:e}),le),lt=()=>le;var H=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,o)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let n=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),s=null,a=null;o!==void 0&&(a=new Promise((l,i)=>{s=setTimeout(()=>{i(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return a?await Promise.race([r(),a]):await r()}finally{n(),s&&clearTimeout(s)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var sr=nr(import.meta.url),ir=me.dirname(sr),he=y("shell"),be=new Set,ar={preferLocal:!0},ut=(e,t,r)=>{let[o,n]=lr(t,r),s={...ar,...n},a=or(e,o,s);return ur(a,s),pr(a),a};var lr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},ur=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(M.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new z).pipe(M.stdout),e.stdout?.pipe(new z).pipe(M.stdout),e.stderr?.pipe(new z).pipe(M.stderr);return}e.stdout?.pipe(M.stdout),e.stderr?.pipe(M.stderr)},ct=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(M.kill(-e.pid,t),he.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return he.error("Error killing process:",r),!1}},cr=e=>ct(e,"SIGKILL"),pr=e=>{be.add(e);let t=lt();if(t){let r=t.onTimesUp(()=>{he.log(`Global timer expired, killing process ${e.pid}`),ct(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(he.log(`Force killing process ${e.pid} after timeout`),cr(e))},5e3)});e.on("exit",()=>{be.delete(e),r()}),e.on("error",()=>{be.delete(e),r()})}};function Z(e,t){if(M.env.NODE_PATH){let n=me.join(M.env.NODE_PATH,".bin",t);if(Ce.existsSync(n))return n}let r=me.join(e,"node_modules",".bin",t);if(Ce.existsSync(r))return r;let o=me.join(ir,"..","node_modules",".bin",t);if(Ce.existsSync(o))return o}var pt="netlify-agent-runner-context.md",Pe="task-history",Oe="netlify-context",F=".netlify",Q="results.md",Le="assets",De="other",Fe="personal";var $e="enterprise",Ue="free",dt=[Fe,"pro",$e,Ue];var ft=y("utils"),dr=e=>new Promise(t=>{setTimeout(t,e)}),gt=(e,t=3e3)=>{let r=!1,o=null,n=[],s=null,a=(...l)=>{if(r)return o=l,new Promise(u=>{n.push(u)});r=!0;let i,g=new Promise(u=>{i=u});return s=(async()=>{await Promise.resolve();let u=await e(...l);for(i(u);;){if(await dr(t),!o)return r=!1,s=null,u;let c=o,f=n;o=null,n=[],u=await e(...c),f.forEach(E=>{E(u)})}})(),g};return a.flush=async()=>{if((r||o)&&s)return await s,a.flush()},a},Ee=(e,t,r=!1)=>{let o=null,n=null,s=null,a=function(...l){n=l,s=this;let i=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(s,n),n=null,s=null)},t),i&&(e.apply(s,n),n=null,s=null)};return a.cancel=()=>{clearTimeout(o),o=null,n=null,s=null},a.flush=()=>{if(o){clearTimeout(o);let l=n,i=s;o=null,n=null,s=null,e.apply(i,l)}},a},ye=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):ft.error("Could not parse JSON",o))}},mt=(e,t)=>{let n=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let l=`--${t}${n}`;if(l.length>55)return"";let i=60-l.length;if(i<=0)return"";if(i>=s.length+6){let g=Math.min(i-s.length,e.length);return`${s}${e.slice(0,g)}`}return e.slice(0,i)},fr=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!dt.some(t=>t in e),ht=()=>{let e={},t={codex:process.env.NETLIFY_FF_AGENT_RUNNER_CODEX_VERSION,claude:process.env.NETLIFY_FF_AGENT_RUNNER_CLAUDE_VERSION,gemini:process.env.NETLIFY_FF_AGENT_RUNNER_GEMINI_VERSION};return Object.entries(t).forEach(([r,o])=>{if(o){let n=`NETLIFY_FF_AGENT_RUNNER_${r.toUpperCase()}_VERSION`;try{let s=JSON.parse(o);fr(s)&&(e[r]=s)}catch(s){let l=s instanceof SyntaxError?"Invalid JSON":s.message;ft.error(`Could not parse ${r} model version override from ${n}: ${l}`)}}}),e};import{Buffer as Et}from"buffer";import gr from"path";var yt=async({config:e,netlify:t})=>{let r=await hr(t),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};let s=await Er(n);await t.utils.run("git",["add",".",...s]);let a={stdio:["ignore","pipe","pipe"]},i=(await t.utils.run("git",["diff","--staged"],a)).stdout;if(o=!!i,!o)return{hasChanges:!1,ignored:s};let 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 m=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;c!==m&&(f=Et.from(m).toString("base64"))}let E={hasChanges:!0,diff:i,resultDiff:c,ignored:s};return i!==u&&(E.diffBinary=Et.from(u).toString("base64")),f&&(E.resultDiffBinary=f),E},mr=["?? mise.toml","?? deno.lock",/\?\? .+?\.log/],hr=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
9
+ `).filter(n=>!mr.some(s=>s instanceof RegExp?s.test(n):n===s))).length!==0,status:t.stdout}};var _t=async e=>{let{stdout:t}=await e.utils.run("git",["rev-parse","HEAD"]);return t.trim()},Tt=async e=>{let{stdout:t}=await e.utils.run("git",["rev-list","--max-parents=0","HEAD"]);return t.trim()},Er=async e=>{let t=[".netlify","mise.toml","deno.lock","node_modules"],r=[];return e.split(`
10
+ `).forEach(o=>{t.forEach(s=>{[`?? ${s}`,`?? ${s}${gr.sep}`].some(l=>o.startsWith(l))&&r.push(`:!${s}`)});let n=o.match(/\?\? (.+?)\.log$/)?.[1];n&&r.push(`:!${n}.log`)}),r};import _r from"fs/promises";import Tr from"os";import It from"path";import q from"process";import wr from"readline";import ke from"path";import yr from"fs/promises";var Ge=y("agent-output-utils");async function ee({initialResult:e,agentName:t,hasError:r}){let o="",n=ke.join(process.cwd(),F,Q);try{let s=await yr.readFile(n,"utf-8");s&&(o=s,Ge.log(`Pulled result from ${ke.relative(process.cwd(),n)}`))}catch{Ge.log(`No results file found at ${ke.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&&Ge.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 $=y("runner_claude"),wt="Claude Code",_e="claude-sonnet-4-5-20250929",Ir=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>($.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?($.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):($.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function Me({config:e,netlify:t,persistSteps:r,aiGateway:o,continueSession:n,priorAgentSessionId:s}){let a=e,{accountType:l,prompt:i,modelVersionOverrides:g}=a,{model:u}=a,c="";if(o){let{token:d,url:I}=o;if(!d||!I)throw new Error("No token or url provided from AI Gateway");if(g?.claude){let p=g?.claude?.[l];if(p){if(!await o.isModelAvailableForProvider("anthropic",p))throw new Error(`Model override '${p}' is not available for anthropic provider`);u=p}}else if(u){if(!await o.isModelAvailableForProvider("anthropic",u))throw new Error(`Model '${u}' is not available for anthropic provider`)}else await o.isModelAvailableForProvider("anthropic",_e)?(u=_e,$.log(`Using default model: ${_e}`)):$.log(`Default model ${_e} is not available, proceeding without model specification`);q.env.ANTHROPIC_API_KEY=d,q.env.ANTHROPIC_BASE_URL=I}else if(!q.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let f=[],E=[],R={},T=0,m=0,x,v,S=[Z(q.cwd(),"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...u?["--model",u]:[],...n?["--continue"]:[],...n&&s?["--resume",s]:[],"-p",i],N=`${q.env.NVM_BIN}/node`;$.log(`Running ${N} ${S.join(" ")}`);let _=t.utils.run(N,S,{all:!0,env:q.env});_.stdin?.end();let A=Ee(()=>{r?.({steps:f,duration:m})},250),w=(d,I)=>{let p={...d,id:T};T+=1,E.push(p),f.push(p),I||A.flush(),A(),I&&A.flush()},h=wr.createInterface({input:_.all});return h.on("error",d=>{$.error("Readline interface error",{error:d.message,stack:d.stack})}),h.on("line",d=>{let I=null;try{I=JSON.parse(d)}catch{$.log("Could not parse line",d)}I?.session_id&&I.session_id!==c&&(c=I.session_id),Array.isArray(I?.message?.content)?I.message.content.forEach(p=>{switch(p.type){case"text":{p.text&&w({message:p.text});break}case"image":{typeof p.source=="object"&&p.source&&p.source.type==="base64"&&p.source.media_type?w({message:`![](data:${p.source.media_type};base64,${p.source.data})`}):$.log(`Unsupported image type ${p.source?.type}`,p.source);break}case"tool_use":{if(p.name==="Task"){let b=p.input?.description&&`\`${p.input.description}\``;w({title:[p.name,b].filter(Boolean).join(" ")})}else p.id&&(R[p.id]=p);A.flush();break}case"tool_result":{let b=p.tool_use_id?R[p.tool_use_id]:void 0,ie;if(b){let J=b.input?.file_path&&It.relative(q.cwd(),b.input.file_path),P=J&&`\`${J}\``;ie=[b.name,P].filter(Boolean).join(" ")}let We=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(b?.name||""),j;if(typeof p.content=="string")j=p.content;else if(Array.isArray(p.content)){let J=[];p.content.forEach(P=>{P?.type==="text"&&typeof P.text=="string"?J.push(P.text):P?.type==="image"&&typeof P.source=="object"&&P.source?P.source.type==="base64"&&P.source.media_type?J.push(`![](data:${P.source.media_type};base64,${P.source.data})`):$.log(`Unsupported image type ${P.source.type}`,P.source):$.log(`Unsupported block type ${P?.type}`)}),j=J.join(`
11
11
 
12
- `)}O&&D&&(D=`\`\`\`
13
- ${D.trim()}
14
- \`\`\``),I({title:P,message:D},!0);break}case"thinking":{l.thinking&&I({title:"Thinking",message:l.thinking},!0);break}default:$.log(`Message content type is not supported ${l.type}`,l)}}):h?.type==="result"&&(y=h.duration_ms||0,h.is_error?m=h.result:w=h.result,[c,f].forEach(l=>{l[l.length-1]?.message===w&&l.pop()}))}),await N.catch(R=>{({error:m,result:w}=Tr({catchError:R,runCmd:N,error:m,result:w,runnerName:"Claude"}))}),_.close(),v.flush(),{steps:c,duration:y,result:await Q({initialResult:w,agentName:yt,hasError:!!m}),error:ee({error:m,agentName:yt}),isRetryableError:te(m)}}var Tt=async()=>{let e=_t.join(yr.homedir(),".claude");await Er.rm(e,{recursive:!0,force:!0})};import wr from"fs/promises";import Rr from"os";import Ir from"path";import re from"process";import xr from"readline";var K=E("runner_codex"),wt="Codex CLI",Nr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(K.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(K.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(K.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function Ge({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:a,modelVersionOverrides:u}=e,{model:i}=e;if(n){let{token:I,url:_}=n;if(!I||!_)throw new Error("No token or url provided from AI Gateway");if(u?.codex){let R=u?.codex?.[s];if(R){if(!await n.isModelAvailableForProvider("openai",R))throw new Error(`Model override '${R}' is not available for openai provider`);i=R}}else if(i&&!await n.isModelAvailableForProvider("openai",i))throw new Error(`Model '${i}' is not available for openai provider`);re.env.OPENAI_API_KEY=I,re.env.OPENAI_BASE_URL=_}else if(!re.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let f=[],c=[],p={},d=0,y=0,w,m,T=[z(re.cwd(),"codex"),"--approval-mode","full-auto",n?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...i?["--model",i]:[],"-q",a].filter(Boolean),x=`${re.env.NVM_BIN}/node`;K.log(`Running ${x} ${T.join(" ")}`);let N=t.utils.run(x,T,{all:!0,env:{...re.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),v=xr.createInterface({input:N.all});return v.on("error",I=>{K.error("Readline interface error",{error:I.message,stack:I.stack})}),v.on("line",I=>{let _=null;try{_=JSON.parse(I)}catch{K.log("Could not parse line",I);return}let R=[],h=!1;if(_?.duration_ms&&(y=_.duration_ms,h=!0),_?.type==="local_shell_call")p[_.call_id]=_;else if(_?.type==="local_shell_call_output"){let l=Ar(p[_.call_id],_);l&&(l.id=d,d+=1,c.push(l),f.push(l),R.push(l),h=!0)}else _?.type==="message"&&_.role==="assistant"?w=_.content.map(l=>l.text).join(`
15
- `):_?.type==="message"&&_.role==="system"&&(m=_.content.map(l=>l.text).join(`
16
- `));h&&(r?.({steps:f,duration:y}),o?.({steps:R,duration:y}))}),await N.catch(I=>{let _=Nr({catchError:I,runCmd:N,error:m,result:w,runnerName:"Codex"});m=_.error,w=_.result}),v.close(),{steps:c,duration:y,result:await Q({initialResult:w,agentName:wt,hasError:!!m}),error:ee({error:m,agentName:wt}),isRetryableError:te(m)}}var Rt=async()=>{let e=Ir.join(Rr.homedir(),".codex");await wr.rm(e,{recursive:!0,force:!0})},vr=new Set(["bash","-lc"]),Ar=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!vr.has(s)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
12
+ `)}We&&j&&(j=`\`\`\`
13
+ ${j.trim()}
14
+ \`\`\``),w({title:ie,message:j},!0);break}case"thinking":{p.thinking&&w({title:"Thinking",message:p.thinking},!0);break}default:$.log(`Message content type is not supported ${p.type}`,p)}}):I?.type==="result"&&(m=I.duration_ms||0,I.is_error?v=I.result:x=I.result,[E,f].forEach(p=>{p[p.length-1]?.message===x&&p.pop()}))}),await _.catch(d=>{({error:v,result:x}=Ir({catchError:d,runCmd:_,error:v,result:x,runnerName:"Claude"}))}),h.close(),A.flush(),{steps:E,duration:m,result:await ee({initialResult:x,agentName:wt,hasError:!!v}),error:te({error:v,agentName:wt}),isRetryableError:re(v),agentSessionId:c}}var Rt=async()=>{let e=It.join(Tr.homedir(),".claude");await _r.rm(e,{recursive:!0,force:!0})};import Rr from"fs/promises";import xr from"os";import Nr from"path";import ne from"process";import vr from"readline";var K=y("runner_codex"),xt="Codex CLI",Ar=({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 je({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:a,modelVersionOverrides:l}=e,{model:i}=e;if(n){let{token:N,url:_}=n;if(!N||!_)throw new Error("No token or url provided from AI Gateway");if(l?.codex){let A=l?.codex?.[s];if(A){if(!await n.isModelAvailableForProvider("openai",A))throw new Error(`Model override '${A}' is not available for openai provider`);i=A}}else if(i&&!await n.isModelAvailableForProvider("openai",i))throw new Error(`Model '${i}' is not available for openai provider`);ne.env.OPENAI_API_KEY=N,ne.env.OPENAI_BASE_URL=_}else if(!ne.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let g=[],u=[],c={},f=0,E=0,R,T,m=[Z(ne.cwd(),"codex"),"--approval-mode","full-auto",n?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...i?["--model",i]:[],"-q",a].filter(Boolean),x=`${ne.env.NVM_BIN}/node`;K.log(`Running ${x} ${m.join(" ")}`);let v=t.utils.run(x,m,{all:!0,env:{...ne.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),S=vr.createInterface({input:v.all});return S.on("error",N=>{K.error("Readline interface error",{error:N.message,stack:N.stack})}),S.on("line",N=>{let _=null;try{_=JSON.parse(N)}catch{K.log("Could not parse line",N);return}let A=[],w=!1;if(_?.duration_ms&&(E=_.duration_ms,w=!0),_?.type==="local_shell_call")c[_.call_id]=_;else if(_?.type==="local_shell_call_output"){let h=Cr(c[_.call_id],_);h&&(h.id=f,f+=1,u.push(h),g.push(h),A.push(h),w=!0)}else _?.type==="message"&&_.role==="assistant"?R=_.content.map(h=>h.text).join(`
15
+ `):_?.type==="message"&&_.role==="system"&&(T=_.content.map(h=>h.text).join(`
16
+ `));w&&(r?.({steps:g,duration:E}),o?.({steps:A,duration:E}))}),await v.catch(N=>{let _=Ar({catchError:N,runCmd:v,error:T,result:R,runnerName:"Codex"});T=_.error,R=_.result}),S.close(),{steps:u,duration:E,result:await ee({initialResult:R,agentName:xt,hasError:!!T}),error:te({error:T,agentName:xt}),isRetryableError:re(T)}}var Nt=async()=>{let e=Nr.join(xr.homedir(),".codex");await Rr.rm(e,{recursive:!0,force:!0})},Sr=new Set(["bash","-lc"]),Cr=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!Sr.has(s)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
17
17
  ${n.trim()}
18
- \`\`\``)}catch(s){K.error("Could not decode outputMsg",s,t.output)}return{title:o,message:n}};import Sr from"fs/promises";import Cr from"os";import xt from"path";import V from"process";import br from"readline";var ne=E("runner_gemini"),It="Gemini CLI",Pr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(ne.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(ne.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(ne.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),Or={list_directory:"List",read_file:"Read",write_file:"Write",glob:"Find",search_file_content:"Find",replace:"Edit",run_shell_command:"Run",web_fetch:"Web Fetch",web_search:"Web Search",read_many_files:"Read Many",save_memory:"Memorize"};async function Me({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:a,modelVersionOverrides:u}=e,{model:i}=e;if(n){let{token:h,url:l}=n;if(!h||!l)throw new Error("No token or url provided from AI Gateway");if(u?.gemini){let g=u?.gemini?.[s];if(g){if(!await n.isModelAvailableForProvider("gemini",g))throw new Error(`Model override '${g}' is not available for gemini provider`);i=g}}else if(i&&!await n.isModelAvailableForProvider("gemini",i))throw new Error(`Model '${i}' is not available for gemini provider`);V.env.GEMINI_API_KEY=h,V.env.GOOGLE_GEMINI_BASE_URL=l}else if(!V.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let f=[],c=[],p=[],d={},y=0,w=0,m,T,x=[z(V.cwd(),"gemini"),...i?["--model",i]:[],"--yolo","-p",a],N=`${V.env.NVM_BIN}/node`;ne.log(`Running ${N} ${x.join(" ")}`);let v=t.utils.run(N,x,{all:!0,env:V.env});v.stdin?.end();let I=me(()=>{r?.({steps:f,duration:w}),o?.({steps:c,duration:w}),c=[]},250),_=(h,l)=>{h.id=y,y+=1,p.push(h),f.push(h),c.push(h),l||I.flush(),I(),l&&I.flush()},R=br.createInterface({input:v.all});return R.on("error",h=>{ne.error("Readline interface error",{error:h.message,stack:h.stack})}),R.on("line",h=>{let l=null;try{if(h.startsWith("[API Error")){let g=h.match(/\[api error: (.+?)]$/i)?.[1];l={type:"error",value:he(g,!1)?.error?.message||g||"Gemini encountered error"}}else l=JSON.parse(h)}catch{return}if(l)switch(l.type){case"thought":{let g=l.value;_({title:g?.subject??"Thinking...",message:g?.description},!0);break}case"content":{l.value&&_({message:l.value});break}case"tool_call_request":{let g=l.value,P=Or[g.name]??g.name,O=g.args?.path||g.args?.absolute_path,D=O&&xt.relative(V.cwd(),O),k=g.args?.command,Yt={title:[P,D&&`\`${D}\``,k&&`\`${k}\``].filter(Boolean).join(" ")};d[g.callId]=Yt,I.flush();break}case"tool_result":{let g=l.value,P=d[g.callId];if(P){let O=[g.resultDisplay,g.responseParts?.functionResponse?.response?.output].find(D=>typeof D=="string"&&D);O&&(P.message=`\`\`\`
19
- ${O.trim()}
20
- \`\`\``),_(P,!0)}break}case"result":{w=l.duration_ms,m=l.value,[p,f,c].forEach(g=>{g[g.length-1]?.message===m&&g.pop()});break}case"error":{T=l.value;break}case"finished":break;default:{ne.warn("Unhandled message type:",l.type);break}}}),await v.catch(h=>{({error:T,result:m}=Pr({catchError:h,runCmd:v,error:T,result:m,runnerName:"Gemini"}))}),R.close(),I.flush(),{steps:p,duration:w,result:await Q({initialResult:m,agentName:It,hasError:!!T}),error:ee({error:T,agentName:It}),isRetryableError:te(T)}}var Nt=async()=>{let e=xt.join(Cr.homedir(),".gemini");await Sr.rm(e,{recursive:!0,force:!0})};var Lr={codex:{runner:Ge,clean:Rt},claude:{runner:ke,clean:Tt},gemini:{runner:Me,clean:Nt}},vt=Lr;var At=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>await S(Dr(),"init-stage",async n=>{let s=performance.now();n?.setAttributes({"init.runner":e.runner,"init.id":e.id,"init.sessionId":e.sessionId,"init.hasRepo":e.hasRepo,"init.useGateway":e.useGateway,"init.validateAgent":e.validateAgent,"init.runnerVersion":o||"unknown"});let a=vt[e.runner];if(!a)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let u=Fr({apiToken:r});ze(u);let i=e.useGateway?await rt({netlify:u,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!i}),e.validateAgent&&e.errorLogsPath&&n?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let f=pt(({steps:d=[],duration:y})=>{let w=d.map(m=>({...m,title:m.title?M(m.title):void 0,message:m.message?M(m.message):void 0}));return d.length=0,G(e.id,e.sessionId,{steps:w,duration:y})},t),c;e.hasRepo?e.sha?(c=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(c=await ht(u),await de(e.id,{sha:c}),n?.setAttributes({"init.sha.source":"current_commit"})):(c=await Et(u),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let p=performance.now()-s;return n?.setAttributes({"init.sha":c||"unknown","init.duration.ms":p,"init.status":"success"}),{aiGateway:i,context:u,persistSteps:f,runner:a,sha:c}}),Fr=({apiToken:e})=>({constants:{NETLIFY_API_HOST:ye.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||ye.env.NETLIFY_API_TOKEN,SITE_ID:ye.env.SITE_ID,FUNCTIONS_DIST:ye.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:it}});import{getTracer as je}from"@netlify/otel";import $r from"crypto";import B from"fs/promises";import L from"path";import U from"process";var C=E("context"),Ur=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:U.env.NETLIFY_TEAM_ID,userId:U.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:U.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},kr=10,Gr=async e=>{let{name:t,ext:r}=L.parse(e),o=e,n=L.join(U.cwd(),F,o),s=0;for(;await Mr(n);){if(s>=kr)throw new Error("Failed to generate context file");o=`${t}-${$r.randomUUID().slice(0,5)}${r}`,n=L.join(U.cwd(),F,o),s+=1}return o},Mr=async e=>{try{return await B.access(e),!0}catch{return!1}},jr=async()=>{try{C.log("Fetching Netlify features context...");let e=await fetch("https://docs.netlify.com/ai-context/context-consumers",{signal:AbortSignal.timeout(1e4)});if(!e.ok)throw new Error(`Failed to fetch context consumers: ${e.status} ${e.statusText}`);let t=await e.json();if(!t||typeof t!="object"||!Array.isArray(t.consumers))return C.warn("Invalid response structure: missing or invalid consumers array"),null;let r=t.consumers.find(o=>o&&typeof o=="object"&&o.key==="catchall-consumer");return r?!r.contextScopes||typeof r.contextScopes!="object"?(C.warn("Catchall consumer missing or invalid contextScopes"),null):r:(C.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?C.warn("Netlify features context request timed out"):C.warn("Failed to fetch Netlify features context:",e.message),null}},Yr=async(e,t)=>{try{let r=await fetch(e,{signal:AbortSignal.timeout(1e4)});if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let o=await r.text();return await B.writeFile(t,o,"utf-8"),!0}catch(r){return r.name==="AbortError"?C.warn(`Download timeout for ${e}`):C.warn(`Failed to download context file ${e}:`,r.message),!1}},_e=null,Br=async()=>{if(_e)return _e;let e=await jr();if(!e)return[];let t=L.join(U.cwd(),F,be);await B.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([n,s])=>{if(!s||typeof s!="object"||!s.endpoint||!s.scope)return C.warn(`Invalid scope data for ${n}, skipping...`),null;let a=`${n}.md`,u=L.join(t,a),i=L.join(F,be,a);return C.log(`Downloading ${s.scope} context...`),await Yr(s.endpoint,u)?(C.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:n}):null});return _e=(await Promise.all(r)).filter(n=>n!==null),_e},St=async({cliPath:e,netlify:t,config:r,buildErrorContext:o})=>{let n=Ur(t),s=await Gr(lt),a=L.join(U.cwd(),F);await B.mkdir(a,{recursive:!0});let u=L.join(F,s),i=L.join(U.cwd(),u),f=L.join(U.cwd(),F,Z);try{await B.unlink(f),C.log(`Deleted old results file: ${f}`)}catch{}let c=o?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
18
+ \`\`\``)}catch(s){K.error("Could not decode outputMsg",s,t.output)}return{title:o,message:n}};import br from"fs/promises";import Pr from"os";import At from"path";import V from"process";import Or from"readline";var oe=y("runner_gemini"),vt="Gemini CLI",Lr=({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})),Dr={list_directory:"List",read_file:"Read",write_file:"Write",glob:"Find",search_file_content:"Find",replace:"Edit",run_shell_command:"Run",web_fetch:"Web Fetch",web_search:"Web Search",read_many_files:"Read Many",save_memory:"Memorize"};async function Ye({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:a,modelVersionOverrides:l}=e,{model:i}=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 d=l?.gemini?.[s];if(d){if(!await n.isModelAvailableForProvider("gemini",d))throw new Error(`Model override '${d}' is not available for gemini provider`);i=d}}else if(i&&!await n.isModelAvailableForProvider("gemini",i))throw new Error(`Model '${i}' is not available for gemini provider`);V.env.GEMINI_API_KEY=w,V.env.GOOGLE_GEMINI_BASE_URL=h}else if(!V.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let g=[],u=[],c=[],f={},E=0,R=0,T,m,x=[Z(V.cwd(),"gemini"),...i?["--model",i]:[],"--yolo","-p",a],v=`${V.env.NVM_BIN}/node`;oe.log(`Running ${v} ${x.join(" ")}`);let S=t.utils.run(v,x,{all:!0,env:V.env});S.stdin?.end();let N=Ee(()=>{r?.({steps:g,duration:R}),o?.({steps:u,duration:R}),u=[]},250),_=(w,h)=>{w.id=E,E+=1,c.push(w),g.push(w),u.push(w),h||N.flush(),N(),h&&N.flush()},A=Or.createInterface({input:S.all});return A.on("error",w=>{oe.error("Readline interface error",{error:w.message,stack:w.stack})}),A.on("line",w=>{let h=null;try{if(w.startsWith("[API Error")){let d=w.match(/\[api error: (.+?)]$/i)?.[1];h={type:"error",value:ye(d,!1)?.error?.message||d||"Gemini encountered error"}}else h=JSON.parse(w)}catch{return}if(h)switch(h.type){case"thought":{let d=h.value;_({title:d?.subject??"Thinking...",message:d?.description},!0);break}case"content":{h.value&&_({message:h.value});break}case"tool_call_request":{let d=h.value,I=Dr[d.name]??d.name,p=d.args?.path||d.args?.absolute_path,b=p&&At.relative(V.cwd(),p),ie=d.args?.command,j={title:[I,b&&`\`${b}\``,ie&&`\`${ie}\``].filter(Boolean).join(" ")};f[d.callId]=j,N.flush();break}case"tool_result":{let d=h.value,I=f[d.callId];if(I){let p=[d.resultDisplay,d.responseParts?.functionResponse?.response?.output].find(b=>typeof b=="string"&&b);p&&(I.message=`\`\`\`
19
+ ${p.trim()}
20
+ \`\`\``),_(I,!0)}break}case"result":{R=h.duration_ms,T=h.value,[c,g,u].forEach(d=>{d[d.length-1]?.message===T&&d.pop()});break}case"error":{m=h.value;break}case"finished":break;default:{oe.warn("Unhandled message type:",h.type);break}}}),await S.catch(w=>{({error:m,result:T}=Lr({catchError:w,runCmd:S,error:m,result:T,runnerName:"Gemini"}))}),A.close(),N.flush(),{steps:c,duration:R,result:await ee({initialResult:T,agentName:vt,hasError:!!m}),error:te({error:m,agentName:vt}),isRetryableError:re(m)}}var St=async()=>{let e=At.join(Pr.homedir(),".gemini");await br.rm(e,{recursive:!0,force:!0})};var Fr={codex:{runner:je,clean:Nt},claude:{runner:Me,clean:Rt},gemini:{runner:Ye,clean:St}},Ct=Fr;var bt=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>await C($r(),"init-stage",async n=>{let s=performance.now();n?.setAttributes({"init.runner":e.runner,"init.id":e.id,"init.sessionId":e.sessionId,"init.hasRepo":e.hasRepo,"init.useGateway":e.useGateway,"init.validateAgent":e.validateAgent,"init.runnerVersion":o||"unknown"});let a=Ct[e.runner];if(!a)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let l=Ur({apiToken:r});et(l);let i=e.useGateway?await st({netlify:l,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!i}),e.validateAgent&&e.errorLogsPath&&n?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let g=gt(({steps:f=[],duration:E})=>{let R=f.map(T=>({...T,title:T.title?G(T.title):void 0,message:T.message?G(T.message):void 0}));return f.length=0,k(e.id,e.sessionId,{steps:R,duration:E})},t),u;e.hasRepo?e.sha?(u=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(u=await _t(l),await ge(e.id,{sha:u}),n?.setAttributes({"init.sha.source":"current_commit"})):(u=await Tt(l),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let c=performance.now()-s;return n?.setAttributes({"init.sha":u||"unknown","init.duration.ms":c,"init.status":"success"}),{aiGateway:i,context:l,persistSteps:g,runner:a,sha:u}}),Ur=({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:ut}});import{getTracer as Be}from"@netlify/otel";import kr from"crypto";import B from"fs/promises";import D from"path";import U from"process";var O=y("context"),Gr=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}},Mr=10,jr=async e=>{let{name:t,ext:r}=D.parse(e),o=e,n=D.join(U.cwd(),F,o),s=0;for(;await Yr(n);){if(s>=Mr)throw new Error("Failed to generate context file");o=`${t}-${kr.randomUUID().slice(0,5)}${r}`,n=D.join(U.cwd(),F,o),s+=1}return o},Yr=async e=>{try{return await B.access(e),!0}catch{return!1}},Br=async()=>{try{O.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 O.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"?(O.warn("Catchall consumer missing or invalid contextScopes"),null):r:(O.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?O.warn("Netlify features context request timed out"):O.warn("Failed to fetch Netlify features context:",e.message),null}},Hr=async(e,t)=>{try{let r=await fetch(e,{signal:AbortSignal.timeout(1e4)});if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let o=await r.text();return await B.writeFile(t,o,"utf-8"),!0}catch(r){return r.name==="AbortError"?O.warn(`Download timeout for ${e}`):O.warn(`Failed to download context file ${e}:`,r.message),!1}},we=null,qr=async()=>{if(we)return we;let e=await Br();if(!e)return[];let t=D.join(U.cwd(),F,Oe);await B.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([n,s])=>{if(!s||typeof s!="object"||!s.endpoint||!s.scope)return O.warn(`Invalid scope data for ${n}, skipping...`),null;let a=`${n}.md`,l=D.join(t,a),i=D.join(F,Oe,a);return O.log(`Downloading ${s.scope} context...`),await Hr(s.endpoint,l)?(O.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:n}):null});return we=(await Promise.all(r)).filter(n=>n!==null),we},Pt=async({cliPath:e,netlify:t,config:r,buildErrorContext:o})=>{let n=Gr(t),s=await jr(pt),a=D.join(U.cwd(),F);await B.mkdir(a,{recursive:!0});let l=D.join(F,s),i=D.join(U.cwd(),l),g=D.join(U.cwd(),F,Q);try{await B.unlink(g),O.log(`Deleted old results file: ${g}`)}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>`:"",p="";r.siteContext&&r.siteContext.length!==0&&(p=`
27
+ </build_error_context>`:"",c="";r.siteContext&&r.siteContext.length!==0&&(c=`
28
28
  <project_rules>
29
- ${r.siteContext.filter(T=>T.site_context).map(T=>typeof T.site_context=="string"?T.site_context:typeof T.site_context=="object"?JSON.stringify(T.site_context):"").join(`
29
+ ${r.siteContext.filter(m=>m.site_context).map(m=>typeof m.site_context=="string"?m.site_context:typeof m.site_context=="object"?JSON.stringify(m.site_context):"").join(`
30
30
 
31
31
  `)}
32
32
  </project_rules>
33
- `);let d="";if(r.sessionHistoryContext?.length){let T=L.join(U.cwd(),F,Ce);await B.mkdir(T,{recursive:!0});let x=await Promise.all(r.sessionHistoryContext.map(async(N,v)=>{let I=v+1,_=`attempt-${I}.md`,R=L.join(T,_),h=L.join(F,Ce,_),l=`# Task History - Attempt ${I}
33
+ `);let f="";if(r.sessionHistoryContext?.length){let m=D.join(U.cwd(),F,Pe);await B.mkdir(m,{recursive:!0});let x=await Promise.all(r.sessionHistoryContext.map(async(v,S)=>{let N=S+1,_=`attempt-${N}.md`,A=D.join(m,_),w=D.join(F,Pe,_),h=`# Task History - Attempt ${N}
34
34
 
35
35
  ## Request - what the user asked for
36
- ${N.request}
36
+ ${v.request}
37
37
 
38
38
  ---
39
39
 
40
40
  ## Response - what the agent replied with after its work
41
41
 
42
- ${N.response}
43
- `;return await B.writeFile(R,l,"utf-8"),C.log(`Created history file: ${h}`),h}));d+=`
42
+ ${v.response}
43
+ `;return await B.writeFile(A,h,"utf-8"),O.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
- ${x.slice(-5).map(N=>`- ${N}`).join(`
48
+ ${x.slice(-5).map(v=>`- ${v}`).join(`
49
49
  `)}
50
50
 
51
51
  </session_history_context>
52
- `}let y=await Br(),w="";y.length>0&&(w=`
52
+ `}let E=await qr(),R="";E.length>0&&(R=`
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
- ${y.map(T=>`- **${T.scope}**: ${T.path}`).join(`
57
+ ${E.map(m=>`- **${m.scope}**: ${m.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 m=`
62
+ `);let T=`
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}/${Z} 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}/${Z} file.
75
+ - When work is complete, write a changes summary in ${a}/${Q} as a standalone PR description. Explain what was accomplished and why (avoid too many implementation details), assuming the reader has no prior context. Use past tense and write in prose without calling it a "PR", "Changelog", etc. This is the core of a PR message or summary page that already has a heading.
76
+ - If the user's request is informational in nature (asking for output, status, information, or analysis rather than asking you to make changes), write the requested information directly to the ${a}/${Q} file.
77
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}/${Pe} folder
83
- - move assets from ${a}/${Pe} 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
- ${p}
85
+ ${c}
86
86
  </requirements>
87
87
 
88
88
  <extra_context>
@@ -99,34 +99,34 @@ 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
- ${w}
102
+ ${R}
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
- ${d}
110
- `;return await B.writeFile(i,m,"utf-8"),C.log(`Generated agent context document at: ${i}`),m.length>5e5&&(m=`
109
+ ${f}
110
+ `;return await B.writeFile(i,T,"utf-8"),O.log(`Generated agent context document at: ${i}`),T.length>5e5&&(T=`
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. ${i} You MUST READ ALL OF IT. Make sure to read it first. Never cite or paraphrase private context.
121
- `),m};var Hr=E("prompt"),Ct=async({cliPath:e,config:t,netlify:r,buildErrorContext:o})=>{let n=await St({cliPath:e,config:t,netlify:r,buildErrorContext:o});return process.env.AGENT_RUNNER_DEBUG&&Hr.log("Contextful Prompt:",n),{prompt:n}};var Te=E("inference_stage"),bt=5,we=async e=>{let{cliPath:t,config:r,context:o,buildErrors:n,runner:s,persistSteps:a,aiGateway:u,attempt:i,contextPrefix:f}=e;Te.log(`Running inference stage, attempt ${i} of ${bt}`);let c=await S(je(),"inference-stage",async p=>{p?.setAttributes({"inference.attempt":i||1}),nt();let{prompt:d}=await S(je(),"compose-prompt",async()=>await Ct({cliPath:t,config:r,buildErrorContext:qr(n),netlify:o})),y=`
122
- ${f||""}
123
- ${d}
124
- `.trim(),w={...r,prompt:y},m=await S(je(),`run-${r.runner}`,async()=>await s({aiGateway:u,config:w,netlify:o,persistSteps:a}));return m.result&&(m.result=M(m.result)),m.error&&(m.error=M(m.error)),await a.flush(),m});if(c.error){if(Te.error("Runner failed",{stepsCount:c.steps.length,duration:c.duration,error:c.error,isRetryableError:c.isRetryableError,attempt:i||1}),c.isRetryableError&&(!i||i<bt))return Te.log("Retrying inference stage"),await new Promise(d=>setTimeout(d,5e3)),{runnerResult:(await we({...e,attempt:(i||1)+1,contextPrefix:"<important> The agent has already started on this work but ran into networking errors trying to complete it. Please continue from where it left off (you can use git commands to see what's currently changed thus far) and do not start over. Here is the full prompt for context: </important>"})).runnerResult};throw Te.log("Do not retry inference stage"),new Error(c.error)}return{runnerResult:c}},qr=e=>!e||e.length===0?"":`
121
+ `),T};var Kr=y("prompt"),Ot=async({cliPath:e,config:t,netlify:r,buildErrorContext:o})=>{let n=await Pt({cliPath:e,config:t,netlify:r,buildErrorContext:o});return process.env.AGENT_RUNNER_DEBUG&&Kr.log("Contextful Prompt:",n),{prompt:n}};var Ie=y("inference_stage"),Lt=5,Re=async e=>{let{cliPath:t,config:r,context:o,buildErrors:n,runner:s,persistSteps:a,aiGateway:l,attempt:i,contextPrefix:g,priorAgentSessionId:u}=e;Ie.log(`Running inference stage, attempt ${i} of ${Lt}`);let c=await C(Be(),"inference-stage",async f=>{f?.setAttributes({"inference.attempt":i||1}),it();let{prompt:E}=await C(Be(),"compose-prompt",async()=>await Ot({cliPath:t,config:r,buildErrorContext:Vr(n),netlify:o})),R=`
122
+ ${g||""}
123
+ ${E}
124
+ `.trim(),T={...r,prompt:R},m=await C(Be(),`run-${r.runner}`,async()=>await s({aiGateway:l,config:T,netlify:o,persistSteps:a,continueSession:!!(i&&i>1),priorAgentSessionId:u}));return m.result&&(m.result=G(m.result)),m.error&&(m.error=G(m.error)),await a.flush(),m});if(c.error){if(Ie.error("Runner failed",{stepsCount:c.steps.length,duration:c.duration,error:c.error,isRetryableError:c.isRetryableError,attempt:i||1,agentSessionId:c.agentSessionId}),c.isRetryableError&&(!i||i<Lt))return Ie.log("Retrying inference stage"),await new Promise(E=>setTimeout(E,5e3)),{runnerResult:(await Re({...e,attempt:(i||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 Ie.log("Do not retry inference stage"),new Error(c.error)}return{runnerResult:c}},Vr=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 Wr from"process";import{getTracer as Ye}from"@netlify/otel";import{getTracer as Kr}from"@netlify/otel";var ae=E("deploy"),Pt=async e=>await S(Kr(),"create-preview-deploy",async t=>Vr(e,t)),Vr=async({netlify:e,hasRepo:t,skipBuild:r,message:o="Agent Preview",deploySubdomain:n,cliPath:s,filter:a},u)=>{try{let i=["deploy","--message",`"${o}"`,"--json","--draft","--verbose"];t||(ae.log("Deploy: Uploading source zip"),i.push("--upload-source-zip")),n&&i.push("--alias",n),a&&i.push("--filter",a),r?(ae.log("Deploy: Skipping build"),i.push("--no-build")):i.push("--context","deploy-preview");let f=s||"netlify";ae.log(`Running: ${f} ${i.join(" ")}`),u?.setAttributes({cmd:f,args:i});let c=await e.utils.run(f,i,{stdio:["ignore","pipe","pipe"]}),p=JSON.parse(c.stdout.trim());u?.setAttributes({success:!0,deployId:p.deploy_id,deployUrl:p.deploy_url,siteId:p.site_id}),ae.log(`
131
- Preview deploy created successfully:`,{deployId:p.deploy_id,deployUrl:p.deploy_url,siteId:p.site_id});let d={deployId:p.deploy_id,previewUrl:p.deploy_url,logsUrl:p.logs,siteId:p.site_id};return t||(d.sourceZipFilename=p.source_zip_filename),d}catch(i){throw ae.error("Failed to create preview deploy via CLI:",i),u?.setAttributes({success:!1,error:i.message}),i}};var le=E("deploy_stage"),Be=async e=>await S(Ye(),"run-deploy-stage",async()=>Jr(e)),Jr=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let s=await S(Ye(),"get-runner-diffs",async()=>await mt({config:t,netlify:r}));if(le.info("Resolved git",{hasChanges:s.hasChanges,ignored:s.ignored??[]}),!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:u,diffBinary:i,resultDiffBinary:f}=s,c=!0;le.log("Preview deploy condition check:",{resultUndefined:o===void 0,resultType:typeof o,hasChanges:c,wouldCreatePreview:o!==void 0&&c});let p=null;if(o!==void 0&&c)try{let d;try{let y=await S(Ye(),"get-runner-session",async()=>await Qe(t.id,t.sessionId));y?.title&&(d=y.title)}catch(y){le.warn("Failed to fetch session title, using fallback message:",y.message)}await G(t.id,t.sessionId,{steps:[{title:"Deploying the run preview"}]}),p=await Pt({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:d,skipBuild:!1,deploySubdomain:dt(t.id,Wr.env.SITE_NAME),filter:n})}catch(d){return le.warn("Failed to create preview deploy (continuing with agent run):",d),{diff:a,resultDiff:u,hasChanges:c,previewInfo:null,diffBinary:i,resultDiffBinary:f,deployError:d instanceof Error?d.message:String(d)}}return le.log("Git status",{hasDiff:!!a,hasChanges:c}),{diff:a,resultDiff:u,hasChanges:c,previewInfo:p,diffBinary:i,resultDiffBinary:f}};import{getTracer as He}from"@netlify/otel";async function Ot(e,t){let{maxRetries:r,baseDelay:o,onRetry:n}=t,s;for(let a=1;a<=r;a++)try{return await e()}catch(u){if(s=u,a===r)throw s;n&&n(a,s),await new Promise(i=>setTimeout(i,o*a))}throw s}var oe=E("cleanup_stage"),Lt=async e=>await S(He(),"cleanup-stage",async()=>Xr(e)),Xr=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:s,resultDiffBinary:a,previewInfo:u})=>{let i={result_diff:t,result:r||"Done",duration:o,result_diff_binary:s};return u&&u.deployId&&(i.deploy_id=u.deployId),u&&u.sourceZipFilename&&(i.result_zip_file_name=u.sourceZipFilename),n||a?(i.cumulative_diff=n,i.cumulative_diff_binary=a,oe.log("Updating total agent result diff"),await S(He(),"update-runner",async()=>{await de(e.id,{result_diff:n,result_diff_binary:a})})):oe.log("No total result diff, not updating"),oe.log("Updated agent runner with result"),await Ot(async()=>await S(He(),"update-runner-session",()=>G(e.id,e.sessionId,i)),{maxRetries:3,baseDelay:1e3,onRetry:(f,c)=>{oe.error(`Error updating agent runner session (attempt ${f}):`,c),oe.log("Retrying...")}}),oe.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as Dt,shutdownTracers as Zr,withActiveSpan as Ft}from"@netlify/otel";var Qr=zr(import.meta.url),$t=Qr("../package.json"),Ut=E("pipeline_index"),Re=3,kt=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:s,tracing:a={}})=>{let u,{withStageTimer:i}=ot(H.timeUnits.hours(4)),f=await Je($t.version,e.id,a);try{await Ft(Dt(),"run-pipeline",{},f,async()=>{let c,{aiGateway:p,context:d,persistSteps:y,runner:w,sha:m}=await i("init",()=>At({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:s,runnerVersion:$t.version}),H.timeUnits.minutes(10));u=w.clean,e.sha=m;let{runnerResult:T}=await i("inference",()=>we({cliPath:r,config:e,context:d,runner:w.runner,persistSteps:y,aiGateway:p}));await G(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let x=await i("deploy",()=>Be({cliPath:r,config:e,context:d,result:T.result,filter:s})),N=T,v=[];if(x.hasChanges&&x.deployError){v.push(Xe(x.deployError));let g=1;for(;g<=Re&&!x.previewInfo;)Ut.log(`Deploy attempt had errors. Retrying. ${g}/${Re}`),await Ft(Dt(),"deploy-stage",async P=>{P?.setAttributes({"stage.attempt":g});let{runnerResult:O}=await i(`inference-retry-${g}`,()=>we({cliPath:r,config:e,context:d,runner:w.runner,persistSteps:y,aiGateway:p,buildErrors:v}));N={...O,steps:[...N.steps||[],...O.steps||[]],duration:(N.duration||0)+(O.duration||0)},x=await i(`deploy-retry-${g}`,()=>Be({cliPath:r,config:e,context:d,result:O.result,filter:s})),x.deployError&&v.push(x.deployError),g++});g>Re&&!x.previewInfo&&(c=new Error(`Deploy validation failed after ${Re} attempts`))}let{diff:I,resultDiff:_,previewInfo:R,diffBinary:h,resultDiffBinary:l}=x;if(await i("cleanup",()=>Lt({config:e,diff:I,result:N.result,duration:N.duration,resultDiff:_,diffBinary:h,resultDiffBinary:l,previewInfo:R}),H.timeUnits.minutes(10)),c)throw c;await w.clean?.()})}catch(c){Ut.error("Got error while running pipeline",c),await u?.();let p=c instanceof Error&&c.message;throw await G(e.id,e.sessionId,{result:p||"Encountered error when running agent",state:"error"}),c}finally{await Zr()}};import b from"process";var tn="claude",rn=e=>(e??[]).filter(t=>t.request&&t.response),nn=e=>(e??[]).filter(t=>t.site_context),Gt=E("config"),Mt=()=>{let e=b.env.NETLIFY_AGENT_RUNNER_ID,t=b.env.NETLIFY_AGENT_RUNNER_SESSION_ID;if(!e||!t)throw new Error("ID of agent runner is not provided");let r=b.env.NETLIFY_AGENT_RUNNER_RESULT_BRANCH,o=b.env.NETLIFY_AGENT_RUNNER_PROMPT;if(!o)throw new Error("Prompt is not provided");let n=b.env.NETLIFY_AGENT_RUNNER_AGENT||tn,s=b.env.NETLIFY_AGENT_RUNNER_MODEL,a=b.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED==="1",u=b.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED==="1",i=b.env.ERROR_LOGS_PATH,f=he(b.env.NETLIFY_AGENT_RUNNER_CONTEXT,!0,Gt),c=rn(f),p=nn(f),d=b.env.NETLIFY_AGENT_RUNNER_HAS_REPO!=="0",y=!b.env.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED,w=b.env.NETLIFY_AGENT_RUNNER_SHA,m=on(),T=ft(),x={id:e,sessionId:t,resultBranch:r,prompt:o,runner:n,model:s,validateAgent:a,errorLogsPath:i,sessionHistoryContext:c,siteContext:p,hasRepo:d,useGateway:y,sha:w,accountType:m,validateAgentWithBuild:u,modelVersionOverrides:T};return Gt.log({fullConfig:x}),x},on=()=>{let e=b.env.NETLIFY_TEAM_TYPE;return e?e.includes("personal")?Le:e.includes("pro")?"pro":e.startsWith("enterprise")?De:e.startsWith("free")?Fe:Oe:Oe};var jt=E("bin_cmd"),W=sn(qe.argv.slice(2),{string:["auth","cwd","cli-path","error-logs-path","filter","trace-exporter-url","traceparent"]});try{let e=Mt();await kt({config:e,apiToken:W.auth,cwd:W.cwd,cliPath:W["cli-path"],errorLogsPath:W["error-logs-path"],filter:W.filter,tracing:{exporterUrl:W["trace-exporter-url"],traceparent:W.traceparent}}),jt.info("Finished agent"),qe.exit(0)}catch(e){jt.error("Error running agent pipeline:",e),qe.exit(1)}
130
+ `;import Xr from"process";import{getTracer as He}from"@netlify/otel";import{getTracer as Wr}from"@netlify/otel";var ue=y("deploy"),Dt=async e=>await C(Wr(),"create-preview-deploy",async t=>Jr(e,t)),Jr=async({netlify:e,hasRepo:t,skipBuild:r,message:o="Agent Preview",deploySubdomain:n,cliPath:s,filter:a},l)=>{try{let i=["deploy","--message",`"${o}"`,"--json","--draft","--verbose"];t||(ue.log("Deploy: Uploading source zip"),i.push("--upload-source-zip")),n&&i.push("--alias",n),a&&i.push("--filter",a),r?(ue.log("Deploy: Skipping build"),i.push("--no-build")):i.push("--context","deploy-preview");let g=s||"netlify";ue.log(`Running: ${g} ${i.join(" ")}`),l?.setAttributes({cmd:g,args:i});let u=await e.utils.run(g,i,{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}),ue.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(i){throw ue.error("Failed to create preview deploy via CLI:",i),l?.setAttributes({success:!1,error:i.message}),i}};var ce=y("deploy_stage"),qe=async e=>await C(He(),"run-deploy-stage",async()=>zr(e)),zr=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let s=await C(He(),"get-runner-diffs",async()=>await yt({config:t,netlify:r}));if(ce.info("Resolved git",{hasChanges:s.hasChanges,ignored:s.ignored??[]}),!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:l,diffBinary:i,resultDiffBinary:g}=s,u=!0;ce.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 C(He(),"get-runner-session",async()=>await rt(t.id,t.sessionId));E?.title&&(f=E.title)}catch(E){ce.warn("Failed to fetch session title, using fallback message:",E.message)}await k(t.id,t.sessionId,{steps:[{title:"Deploying the run preview"}]}),c=await Dt({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:f,skipBuild:!1,deploySubdomain:mt(t.id,Xr.env.SITE_NAME),filter:n})}catch(f){return ce.warn("Failed to create preview deploy (continuing with agent run):",f),{diff:a,resultDiff:l,hasChanges:u,previewInfo:null,diffBinary:i,resultDiffBinary:g,deployError:f instanceof Error?f.message:String(f)}}return ce.log("Git status",{hasDiff:!!a,hasChanges:u}),{diff:a,resultDiff:l,hasChanges:u,previewInfo:c,diffBinary:i,resultDiffBinary:g}};import{getTracer as Ke}from"@netlify/otel";async function Ft(e,t){let{maxRetries:r,baseDelay:o,onRetry:n}=t,s;for(let a=1;a<=r;a++)try{return await e()}catch(l){if(s=l,a===r)throw s;n&&n(a,s),await new Promise(i=>setTimeout(i,o*a))}throw s}var se=y("cleanup_stage"),$t=async e=>await C(Ke(),"cleanup-stage",async()=>Zr(e)),Zr=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:s,resultDiffBinary:a,previewInfo:l})=>{let i={result_diff:t,result:r||"Done",duration:o,result_diff_binary:s};return l&&l.deployId&&(i.deploy_id=l.deployId),l&&l.sourceZipFilename&&(i.result_zip_file_name=l.sourceZipFilename),n||a?(i.cumulative_diff=n,i.cumulative_diff_binary=a,se.log("Updating total agent result diff"),await C(Ke(),"update-runner",async()=>{await ge(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 Ft(async()=>await C(Ke(),"update-runner-session",()=>k(e.id,e.sessionId,i)),{maxRetries:3,baseDelay:1e3,onRetry:(g,u)=>{se.error(`Error updating agent runner session (attempt ${g}):`,u),se.log("Retrying...")}}),se.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as Ut,shutdownTracers as en,withActiveSpan as kt}from"@netlify/otel";var tn=Qr(import.meta.url),Gt=tn("../package.json"),Mt=y("pipeline_index"),xe=3,jt=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:s,tracing:a={}})=>{let l,{withStageTimer:i}=at(H.timeUnits.hours(4)),g=await Ze(Gt.version,e.id,a);try{await kt(Ut(),"run-pipeline",{},g,async()=>{let u,{aiGateway:c,context:f,persistSteps:E,runner:R,sha:T}=await i("init",()=>bt({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:s,runnerVersion:Gt.version}),H.timeUnits.minutes(10));l=R.clean,e.sha=T;let{runnerResult:m}=await i("inference",()=>Re({cliPath:r,config:e,context:f,runner:R.runner,persistSteps:E,aiGateway:c}));await k(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let x=await i("deploy",()=>qe({cliPath:r,config:e,context:f,result:m.result,filter:s})),v=m,S=[];if(x.hasChanges&&x.deployError){S.push(Qe(x.deployError));let d=1;for(;d<=xe&&!x.previewInfo;)Mt.log(`Deploy attempt had errors. Retrying. ${d}/${xe}`),await kt(Ut(),"deploy-stage",async I=>{I?.setAttributes({"stage.attempt":d});let{runnerResult:p}=await i(`inference-retry-${d}`,()=>Re({cliPath:r,config:e,context:f,runner:R.runner,persistSteps:E,aiGateway:c,buildErrors:S,priorAgentSessionId:m.agentSessionId}));v={...p,steps:[...v.steps||[],...p.steps||[]],duration:(v.duration||0)+(p.duration||0)},x=await i(`deploy-retry-${d}`,()=>qe({cliPath:r,config:e,context:f,result:p.result,filter:s})),x.deployError&&S.push(x.deployError),d++});d>xe&&!x.previewInfo&&(u=new Error(`Deploy validation failed after ${xe} attempts`))}let{diff:N,resultDiff:_,previewInfo:A,diffBinary:w,resultDiffBinary:h}=x;if(await i("cleanup",()=>$t({config:e,diff:N,result:v.result,duration:v.duration,resultDiff:_,diffBinary:w,resultDiffBinary:h,previewInfo:A}),H.timeUnits.minutes(10)),u)throw u;await R.clean?.()})}catch(u){Mt.error("Got error while running pipeline",u),await l?.();let c=u instanceof Error&&u.message;throw await k(e.id,e.sessionId,{result:c||"Encountered error when running agent",state:"error"}),u}finally{await en()}};import L from"process";var nn="claude",on=e=>(e??[]).filter(t=>t.request&&t.response),sn=e=>(e??[]).filter(t=>t.site_context),Yt=y("config"),Bt=()=>{let e=L.env.NETLIFY_AGENT_RUNNER_ID,t=L.env.NETLIFY_AGENT_RUNNER_SESSION_ID;if(!e||!t)throw new Error("ID of agent runner is not provided");let r=L.env.NETLIFY_AGENT_RUNNER_RESULT_BRANCH,o=L.env.NETLIFY_AGENT_RUNNER_PROMPT;if(!o)throw new Error("Prompt is not provided");let n=L.env.NETLIFY_AGENT_RUNNER_AGENT||nn,s=L.env.NETLIFY_AGENT_RUNNER_MODEL,a=L.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED==="1",l=L.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED==="1",i=L.env.ERROR_LOGS_PATH,g=ye(L.env.NETLIFY_AGENT_RUNNER_CONTEXT,!0,Yt),u=on(g),c=sn(g),f=L.env.NETLIFY_AGENT_RUNNER_HAS_REPO!=="0",E=!L.env.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED,R=L.env.NETLIFY_AGENT_RUNNER_SHA,T=an(),m=ht(),x={id:e,sessionId:t,resultBranch:r,prompt:o,runner:n,model:s,validateAgent:a,errorLogsPath:i,sessionHistoryContext:u,siteContext:c,hasRepo:f,useGateway:E,sha:R,accountType:T,validateAgentWithBuild:l,modelVersionOverrides:m};return Yt.log({fullConfig:x}),x},an=()=>{let e=L.env.NETLIFY_TEAM_TYPE;return e?e.includes("personal")?Fe:e.includes("pro")?"pro":e.startsWith("enterprise")?$e:e.startsWith("free")?Ue:De:De};var Ht=y("bin_cmd"),W=ln(Ve.argv.slice(2),{string:["auth","cwd","cli-path","error-logs-path","filter","trace-exporter-url","traceparent"]});try{let e=Bt();await jt({config:e,apiToken:W.auth,cwd:W.cwd,cliPath:W["cli-path"],errorLogsPath:W["error-logs-path"],filter:W.filter,tracing:{exporterUrl:W["trace-exporter-url"],traceparent:W.traceparent}}),Ht.info("Finished agent"),Ve.exit(0)}catch(e){Ht.error("Error running agent pipeline:",e),Ve.exit(1)}
132
132
  //# sourceMappingURL=bin.js.map