@netlify/agent-runner-cli 1.39.0 → 1.39.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/bin.js +46 -46
  2. package/dist/index.js +35 -35
  3. package/package.json +1 -1
package/dist/bin.js CHANGED
@@ -1,65 +1,65 @@
1
1
  #!/usr/bin/env node
2
- import Fe from"process";import Or from"minimist";import{createRequire as Ir}from"module";import{createTracerProvider as It}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as $e}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as wt}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as At}from"@netlify/otel";import{OTLPTraceExporter as Ct}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 Re=_("tracing"),Ue=(e,t,r)=>It({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new $e(new Ne),new $e(new Ct({url:r}))],instrumentations:[new wt({skipHeaders:!0})]});function V(e,t,r){return Re.log(`\u23F3 TRACE: ${t} starting...`),At(e,t,r)}var Ne=class{export(t,r){for(let n of t)this.logSpan(n);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,n=t.attributes,o=[];for(let[a,i]of Object.entries(n))a.includes("duration")&&typeof i=="number"?o.push(`${a}=${i.toFixed(2)}ms`):o.push(`${a}=${i}`);let s=t.status?.code===2?"\u274C":"\u2705",l=o.length>0?` [${o.join(", ")}]`:"";Re.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${l}`),t.status?.code===2&&t.status.message&&Re.log(` \u274C Error: ${t.status.message}`)}};var St=["error","failed","exception","fatal","panic","abort","crash"];function Ge(e){let t=e.split(`
3
- `),r=[],n=-1,o=0;for(;o<t.length;){let a=t[o].slice(0,500).toLowerCase();if(St.some(p=>a.includes(p))){let p=Math.max(0,o-10,n+1),c=Math.min(t.length-1,o+20),m=[];for(let h=p;h<=c;h++)m.push(t[h]);r.push(m.join(`
4
- `)),n=c,o=c+1}else o++}if(r.length===0)return e;let s=r.map((l,a)=>`<extracted_error_chunk order="${a+1}">
5
- ${l}
2
+ import Ge from"process";import $r from"minimist";import{createRequire as Or}from"module";import{createTracerProvider as St}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as Ye}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as Pt}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as vt}from"@netlify/otel";import{OTLPTraceExporter as Ot}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 Re=_("tracing"),Me=(e,t,r)=>St({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new Ye(new Ne),new Ye(new Ot({url:r}))],instrumentations:[new Pt({skipHeaders:!0})]});function w(e,t,r){return Re.log(`\u23F3 TRACE: ${t} starting...`),vt(e,t,r)}var Ne=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(", ")}]`:"";Re.log(`${s} 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 kt=["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(kt.some(p=>u.includes(p))){let p=Math.max(0,n-10,o+1),c=Math.min(t.length-1,n+20),d=[];for(let m=p;m<=c;m++)d.push(t[m]);r.push(d.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}">
5
+ ${a}
6
6
  </extracted_error_chunk>`).join(`
7
7
 
8
- `);return s.length>e.length*.8?e:s}import Ee from"process";import{getTracer as cr}from"@netlify/otel";import ce from"process";var Ie=ce.env.NETLIFY_API_URL,we=ce.env.NETLIFY_API_TOKEN,ae=_("api"),pe=async(e,t={})=>{if(!Ie||!we)throw new Error("No API URL or token");let r=new URL(e,Ie),n={...t,headers:{...t.headers,Authorization:`Bearer ${we}`}};ce.env.AGENT_RUNNERS_DEBUG==="true"&&(n.headers["x-nf-debug-logging"]="true"),t.json&&(n.headers||={},n.headers["Content-Type"]="application/json",n.body=JSON.stringify(t.json));let o=await fetch(r,n),s=o.ok&&o.status<=299;if(ce.env.AGENT_RUNNERS_DEBUG==="true")ae.log(`Response headers for ${r}:`),o.headers.forEach((a,i)=>{ae.log(` ${i}: ${a}`)});else{let a=o.headers.get("x-request-id")||o.headers.get("x-nf-request-id");ae.log(`Request ID for ${r}: ${a||"N/A"}`)}if(s||ae.error(`Got status ${o.status} for request ${r}`),t.raw){if(!s)throw o;return o}let l=await(o.headers.get("content-type")?.includes("application/json")?o.json():o.text());if(!s)throw l;return l},Ye=e=>{ae.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Ie=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(we=e.constants.NETLIFY_API_TOKEN)},de=(e,t)=>pe(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),K=(e,t,r)=>pe(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var Me=(e,t)=>pe(`/api/v1/agent_runners/${e}/sessions/${t}`),je=(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 Be=_("ai_gateway"),He=async({netlify:e,config:t})=>{let r,n,o,s,l=e.constants?.SITE_ID;if(!l)throw new Error("No site id");let a=async()=>{clearTimeout(o),Be.log("Requesting AI gateway information");let i=await je(l,t.id,t.sessionId);if({token:r,url:s}=i,n=i.expires_at?i.expires_at*1e3:void 0,Be.log("Got AI gateway information",{token:!!r,expiresAt:n,url:s}),n){let p=n-Date.now()-6e4;p>0&&(o=setTimeout(()=>{a()},p))}};return await a(),{get url(){return s},get token(){return r}}};import Q from"process";import{execa as bt,execaCommand as Zr}from"execa";import{Transform as Pt}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"]),Ot=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function kt(){return Object.entries(process.env).filter(([e,t])=>!(!t||vt.has(e)||Ot.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function z(e){if(typeof e!="string")return e;let t=kt();if(t.length===0)return e;let r=e;return t.forEach(n=>{let o=new RegExp(Lt(n),"g");r=r.replace(o,"******")}),r}function Lt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Z=class extends Pt{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,n){let o=t.toString(),s=z(o);n(null,s)}};function qe(){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(n,o,s){let l=typeof n=="string"?z(n):n;return typeof o=="function"?t(l,o):t(l,o,s)},process.stderr.write=function(n,o,s){let l=typeof n=="string"?z(n):n;return typeof o=="function"?r(l,o):r(l,o,s)}}var tn=_("shell"),Dt={preferLocal:!0},Ve=(e,t,r)=>{let[n,o]=Ft(t,r),s={...Dt,...o},l=bt(e,n,s);return $t(l,s),l};var Ft=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},$t=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(Q.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new Z).pipe(Q.stdout),e.stdout?.pipe(new Z).pipe(Q.stdout),e.stderr?.pipe(new Z).pipe(Q.stderr);return}e.stdout?.pipe(Q.stdout),e.stderr?.pipe(Q.stderr)};var Ke="netlify-agent-runner-context.md",Ae="task-history",Ce="netlify-context",b=".netlify",ee="results.md",Se="assets",U="other",G="personal";var Y="enterprise",M="free",We=[G,"pro",Y,M];var Xe=_("utils"),Ut=e=>new Promise(t=>{setTimeout(t,e)}),Je=(e,t=3e3)=>{let r=!1,n=null,o=[],s=null,l=(...a)=>{if(r)return n=a,new Promise(c=>{o.push(c)});r=!0;let i,p=new Promise(c=>{i=c});return s=(async()=>{await Promise.resolve();let c=await e(...a);for(i(c);;){if(await Ut(t),!n)return r=!1,s=null,c;let m=n,h=o;n=null,o=[],c=await e(...m),h.forEach(E=>{E(c)})}})(),p};return l.flush=async()=>{if((r||n)&&s)return await s,l.flush()},l},fe=(e,t,r=!1)=>{let n=null,o=null,s=null,l=function(...a){o=a,s=this;let i=r&&!n;clearTimeout(n),n=setTimeout(()=>{n=null,r||(e.apply(s,o),o=null,s=null)},t),i&&(e.apply(s,o),o=null,s=null)};return l.cancel=()=>{clearTimeout(n),n=null,o=null,s=null},l.flush=()=>{if(n){clearTimeout(n);let a=o,i=s;n=null,o=null,s=null,e.apply(i,a)}},l},me=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(n){t&&(r?.error?r.error("Could not parse JSON",n):Xe.error("Could not parse JSON",n))}},ze=(e,t)=>{let o=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let a=`--${t}${o}`;if(a.length>55)return"";let i=60-a.length;if(i<=0)return"";if(i>=s.length+6){let p=Math.min(i-s.length,e.length);return`${s}${e.slice(0,p)}`}return e.slice(0,i)},Gt=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!We.some(t=>t in e),Ze=()=>{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,n])=>{if(n){let o=`NETLIFY_FF_AGENT_RUNNER_${r.toUpperCase()}_VERSION`;try{let s=JSON.parse(n);Gt(s)&&(e[r]=s)}catch(s){let a=s instanceof SyntaxError?"Invalid JSON":s.message;Xe.error(`Could not parse ${r} model version override from ${o}: ${a}`)}}}),e};import{Buffer as Qe}from"buffer";import Yt from"path";var et=async({config:e,netlify:t})=>{let r=await jt(t),{hasChanges:n}=r,{status:o}=r;if(!n)return{hasChanges:!1};let s=await Bt(o);await t.utils.run("git",["add",".",...s]);let l={stdio:["ignore","pipe","pipe"]},i=(await t.utils.run("git",["diff","--staged"],l)).stdout;if(n=!!i,!n)return{hasChanges:!1,ignored:s};let c=(await t.utils.run("git",["diff","--staged","--binary"],l)).stdout,m,h;if(e.sha){await t.utils.run("git",["commit","-m","Agent runner"]),m=(await t.utils.run("git",["diff",e.sha,"HEAD"],l)).stdout;let f=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"],l)).stdout;m!==f&&(h=Qe.from(f).toString("base64"))}let E={hasChanges:!0,diff:i,resultDiff:m,ignored:s};return i!==c&&(E.diffBinary=Qe.from(c).toString("base64")),h&&(E.resultDiffBinary=h),E},Mt=["?? mise.toml","?? deno.lock",/\?\? .+?\.log/],jt=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
9
- `).filter(o=>!Mt.some(s=>s instanceof RegExp?s.test(o):o===s))).length!==0,status:t.stdout}};var tt=async e=>{let{stdout:t}=await e.utils.run("git",["rev-parse","HEAD"]);return t.trim()},rt=async e=>{let{stdout:t}=await e.utils.run("git",["rev-list","--max-parents=0","HEAD"]);return t.trim()},Bt=async e=>{let t=[".netlify","mise.toml","deno.lock","node_modules"],r=[];return e.split(`
10
- `).forEach(n=>{t.forEach(s=>{[`?? ${s}`,`?? ${s}${Yt.sep}`].some(a=>n.startsWith(a))&&r.push(`:!${s}`)});let o=n.match(/\?\? (.+?)\.log$/)?.[1];o&&r.push(`:!${o}.log`)}),r};import qt from"fs/promises";import Vt from"os";import ge from"path";import B from"process";import Kt from"readline";import Pe from"path";import Ht from"fs/promises";var ve=_("agent-output-utils");async function te({initialResult:e,agentName:t,hasError:r}){let n="",o=Pe.join(process.cwd(),b,ee);try{let s=await Ht.readFile(o,"utf-8");s&&(n=s,ve.log(`Pulled result from ${Pe.relative(process.cwd(),o)}`))}catch{ve.log(`No results file found at ${Pe.relative(process.cwd(),o)}`)}return n||(!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,n=r?.replace(/\s+/g," ").trim().toLowerCase()||"",o="";return n?.includes("ai gateway is not available for your account")||n?.includes("ai gateway is not enabled for your account")?o="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.":n?.includes("error when talking to gemini api")?o="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":(n?.includes("connection closed prematurely")||n?.includes("499")&&t.toLowerCase().includes("gemini"))&&(o=`The ${t} models were currently overloaded. Please try again or use a different available agent.`),n?.includes("request timed out")&&(o=`The ${t} API request's have timed out. Please try again or use a different available agent.`),n?.includes("network error")&&(o=`The ${t} agent is having network issues. Please try again or use a different available agent.`),o&&ve.log(`Providing updated error messsage: ${o}, replacing original error: ${r}`),o||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 F=_("runner_claude"),nt="Claude Code",Wt=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(F.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(F.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(F.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0}));async function Oe({config:e,netlify:t,persistSteps:r,aiGateway:n}){let o=e,{accountType:s,prompt:l,modelVersionOverrides:a}=o,{model:i}=o;if(n){let{token:N,url:d}=n;if(!N||!d)throw new Error("No token or url provided from AI Gateway");let u=Xt[s];if(!u)throw new Error(`Claude is not supported for the account type ${s}`);if(i&&!u?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(a?.claude){let g=a?.claude?.[s];g&&(i=g)}B.env.ANTHROPIC_API_KEY=N,B.env.ANTHROPIC_BASE_URL=d}else if(!B.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let p=[],c=[],m={},h=0,E=0,y,T,f=ge.join(B.cwd(),"node_modules"),w=[ge.join(B.env.NODE_PATH||f,".bin/claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...i?["--model",i]:[],"-p",l],A=`${B.env.NVM_BIN}/node`;F.log(`Running ${A} ${w.join(" ")}`);let S=t.utils.run(A,w,{all:!0,env:B.env});S.stdin?.end();let I=fe(()=>{r?.({steps:p,duration:E})},250),R=(N,d)=>{let u={...N,id:h};h+=1,c.push(u),p.push(u),d||I.flush(),I(),d&&I.flush()},x=Kt.createInterface({input:S.all});return x.on("error",N=>{F.error("Readline interface error",{error:N.message,stack:N.stack})}),x.on("line",N=>{let d=null;try{d=JSON.parse(N)}catch{F.log("Could not parse line",N)}Array.isArray(d?.message?.content)?d.message.content.forEach(u=>{switch(u.type){case"text":{u.text&&R({message:u.text});break}case"image":{typeof u.source=="object"&&u.source&&u.source.type==="base64"&&u.source.media_type?R({message:`![](data:${u.source.media_type};base64,${u.source.data})`}):F.log(`Unsupported image type ${u.source?.type}`,u.source);break}case"tool_use":{if(u.name==="Task"){let g=u.input?.description&&`\`${u.input.description}\``;R({title:[u.name,g].filter(Boolean).join(" ")})}else u.id&&(m[u.id]=u);I.flush();break}case"tool_result":{let g=u.tool_use_id?m[u.tool_use_id]:void 0,P;if(g){let $=g.input?.file_path&&ge.relative(B.cwd(),g.input.file_path),C=$&&`\`${$}\``;P=[g.name,C].filter(Boolean).join(" ")}let j=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(g?.name||""),L;if(typeof u.content=="string")L=u.content;else if(Array.isArray(u.content)){let $=[];u.content.forEach(C=>{C?.type==="text"&&typeof C.text=="string"?$.push(C.text):C?.type==="image"&&typeof C.source=="object"&&C.source?C.source.type==="base64"&&C.source.media_type?$.push(`![](data:${C.source.media_type};base64,${C.source.data})`):F.log(`Unsupported image type ${C.source.type}`,C.source):F.log(`Unsupported block type ${C?.type}`)}),L=$.join(`
11
-
12
- `)}j&&L&&(L=`\`\`\`
13
- ${L.trim()}
14
- \`\`\``),R({title:P,message:L},!0);break}case"thinking":{u.thinking&&R({title:"Thinking",message:u.thinking},!0);break}default:F.log(`Message content type is not supported ${u.type}`,u)}}):d?.type==="result"&&(E=d.duration_ms||0,d.is_error?T=d.result:y=d.result,[c,p].forEach(u=>{u[u.length-1]?.message===y&&u.pop()}))}),await S.catch(N=>{({error:T,result:y}=Wt({catchError:N,runCmd:S,error:T,result:y,runnerName:"Claude"}))}),x.close(),I.flush(),{steps:c,duration:E,result:await te({initialResult:y,agentName:nt,hasError:!!T}),error:re({error:T,agentName:nt}),isRetryableError:ne(T)}}var ot=async()=>{let e=ge.join(Vt.homedir(),".claude");await qt.rm(e,{recursive:!0,force:!0})},Xt={[Y]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:64e3},"claude-3-haiku-20240307":{maxTokens:4096},"claude-opus-4-20250514":{maxTokens:32e3},"claude-sonnet-4-20250514":{maxTokens:64e3}}},pro:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[G]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[M]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}},[U]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}}};import Jt from"fs/promises";import zt from"os";import ke from"path";import X from"process";import Zt from"readline";var J=_("runner_codex"),st="Codex CLI",Qt=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(J.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(J.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(J.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0}));async function Le({config:e,netlify:t,persistSteps:r,sendSteps:n,aiGateway:o}){let{accountType:s,prompt:l,modelVersionOverrides:a}=e,{model:i}=e;if(o){let{token:R,url:x}=o;if(!R||!x)throw new Error("No token or url provided from AI Gateway");let N=er[s];if(!N)throw new Error(`Codex is not supported for the account type ${s}`);if(i&&!N?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(a?.codex){let d=a?.codex?.[s];d&&(i=d)}X.env.OPENAI_API_KEY=R,X.env.OPENAI_BASE_URL=x}else if(!X.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let p=[],c=[],m={},h=0,E=0,y,T,f=ke.join(X.cwd(),"node_modules"),w=[ke.join(X.env.NODE_PATH||f,".bin/codex"),"--approval-mode","full-auto",o?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...i?["--model",i]:[],"-q",l].filter(Boolean),A=`${X.env.NVM_BIN}/node`;J.log(`Running ${A} ${w.join(" ")}`);let S=t.utils.run(A,w,{all:!0,env:{...X.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),I=Zt.createInterface({input:S.all});return I.on("error",R=>{J.error("Readline interface error",{error:R.message,stack:R.stack})}),I.on("line",R=>{let x=null;try{x=JSON.parse(R)}catch{J.log("Could not parse line",R);return}let N=[],d=!1;if(x?.duration_ms&&(E=x.duration_ms,d=!0),x?.type==="local_shell_call")m[x.call_id]=x;else if(x?.type==="local_shell_call_output"){let u=rr(m[x.call_id],x);u&&(u.id=h,h+=1,c.push(u),p.push(u),N.push(u),d=!0)}else x?.type==="message"&&x.role==="assistant"?y=x.content.map(u=>u.text).join(`
15
- `):x?.type==="message"&&x.role==="system"&&(T=x.content.map(u=>u.text).join(`
16
- `));d&&(r?.({steps:p,duration:E}),n?.({steps:N,duration:E}))}),await S.catch(R=>{let x=Qt({catchError:R,runCmd:S,error:T,result:y,runnerName:"Codex"});T=x.error,y=x.result}),I.close(),{steps:c,duration:E,result:await te({initialResult:y,agentName:st,hasError:!!T}),error:re({error:T,agentName:st}),isRetryableError:ne(T)}}var it=async()=>{let e=ke.join(zt.homedir(),".codex");await Jt.rm(e,{recursive:!0,force:!0})},er={[Y]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},o1:{maxTokens:1e5},"o1-mini":{maxTokens:65536},"o3-mini":{maxTokens:1e5},"gpt-image-1":{},"dall-e-2":{},"dall-e-3":{}}},[G]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768}}},pro:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768}}},[M]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},"o3-mini":{maxTokens:16e3}}},[U]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},"o3-mini":{maxTokens:16e3}}}},tr=new Set(["bash","-lc"]),rr=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!tr.has(s)),n=r?`Running \`${r.join(" ")}\``:void 0,o;try{o=JSON.parse(t.output).output?.trim(),o&&(o=`\`\`\`
17
- ${o.trim()}
18
- \`\`\``)}catch(s){J.error("Could not decode outputMsg",s,t.output)}return{title:n,message:o}};import nr from"fs/promises";import or from"os";import he from"path";import H from"process";import sr from"readline";var oe=_("runner_gemini"),at="Gemini CLI",ir=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(oe.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(oe.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(oe.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0})),ar={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 be({config:e,netlify:t,persistSteps:r,sendSteps:n,aiGateway:o}){let{accountType:s,prompt:l,modelVersionOverrides:a}=e,{model:i}=e;if(o){let{token:d,url:u}=o;if(!d||!u)throw new Error("No token or url provided from AI Gateway");let g=lr[s];if(!g)throw new Error(`Gemini is not supported for the account type ${s}`);if(i&&!g?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(a?.gemini){let P=a?.gemini?.[s];P&&(i=P)}H.env.GEMINI_API_KEY=d,H.env.GOOGLE_GEMINI_BASE_URL=u}else if(!H.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let p=[],c=[],m=[],h={},E=0,y=0,T,f,w=he.join(H.cwd(),"node_modules"),A=[he.join(H.env.NODE_PATH||w,".bin/gemini"),...i?["--model",i]:[],"--yolo","-p",l],S=`${H.env.NVM_BIN}/node`;oe.log(`Running ${S} ${A.join(" ")}`);let I=t.utils.run(S,A,{all:!0,env:H.env});I.stdin?.end();let R=fe(()=>{r?.({steps:p,duration:y}),n?.({steps:c,duration:y}),c=[]},250),x=(d,u)=>{d.id=E,E+=1,m.push(d),p.push(d),c.push(d),u||R.flush(),R(),u&&R.flush()},N=sr.createInterface({input:I.all});return N.on("error",d=>{oe.error("Readline interface error",{error:d.message,stack:d.stack})}),N.on("line",d=>{let u=null;try{if(d.startsWith("[API Error")){let g=d.match(/\[api error: (.+?)]$/i)?.[1];u={type:"error",value:me(g,!1)?.error?.message||g||"Gemini encountered error"}}else u=JSON.parse(d)}catch{return}if(u)switch(u.type){case"thought":{let g=u.value;x({title:g?.subject??"Thinking...",message:g?.description},!0);break}case"content":{u.value&&x({message:u.value});break}case"tool_call_request":{let g=u.value,P=ar[g.name]??g.name,j=g.args?.path||g.args?.absolute_path,L=j&&he.relative(H.cwd(),j),$=g.args?.command,Nt={title:[P,L&&`\`${L}\``,$&&`\`${$}\``].filter(Boolean).join(" ")};h[g.callId]=Nt,R.flush();break}case"tool_result":{let g=u.value,P=h[g.callId];if(P){let j=[g.resultDisplay,g.responseParts?.functionResponse?.response?.output].find(L=>typeof L=="string"&&L);j&&(P.message=`\`\`\`
19
- ${j.trim()}
20
- \`\`\``),x(P,!0)}break}case"result":{y=u.duration_ms,T=u.value,[m,p,c].forEach(g=>{g[g.length-1]?.message===T&&g.pop()});break}case"error":{f=u.value;break}case"finished":break;default:{oe.warn("Unhandled message type:",u.type);break}}}),await I.catch(d=>{({error:f,result:T}=ir({catchError:d,runCmd:I,error:f,result:T,runnerName:"Gemini"}))}),N.close(),R.flush(),{steps:m,duration:y,result:await te({initialResult:T,agentName:at,hasError:!!f}),error:re({error:f,agentName:at}),isRetryableError:ne(f)}}var lt=async()=>{let e=he.join(or.homedir(),".gemini");await nr.rm(e,{recursive:!0,force:!0})},lr={[Y]:{models:{"gemini-1.5-flash":{maxTokens:8192},"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-1.5-pro":{maxTokens:8192},"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:65536},"gemini-2.5-flash-lite":{maxTokens:65536},"gemini-2.5-pro":{maxTokens:65536},"imagen-4.0-generate-001":{},"veo-3.0-generate-preview":{}}},pro:{models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[G]:{models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[M]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}},[U]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}}};var ur={codex:{runner:Le,clean:it},claude:{runner:Oe,clean:ot},gemini:{runner:be,clean:lt}},ut=ur;var ct=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:n})=>{let o=cr();return V(o,"init-stage",async s=>{let l=performance.now();s?.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":n||"unknown"});let a=ut[e.runner];if(!a)throw s?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let i=pr({apiToken:r});Ye(i);let p=e.useGateway?await He({netlify:i,config:e}):void 0;s?.setAttributes({"init.aiGateway.created":!!p}),e.validateAgent&&e.errorLogsPath&&s?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let c=Je(({steps:E=[],duration:y})=>{let T=E.map(f=>({...f,title:f.title?z(f.title):void 0,message:f.message?z(f.message):void 0}));return E.length=0,K(e.id,e.sessionId,{steps:T,duration:y})},t),m;e.hasRepo?e.sha?(m=e.sha,s?.setAttributes({"init.sha.source":"provided"})):(m=await tt(i),await de(e.id,{sha:m}),s?.setAttributes({"init.sha.source":"current_commit"})):(m=await rt(i),s?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let h=performance.now()-l;return s?.setAttributes({"init.sha":m||"unknown","init.duration.ms":h,"init.status":"success"}),{aiGateway:p,context:i,persistSteps:c,runner:a,sha:m}})},pr=({apiToken:e})=>({constants:{NETLIFY_API_HOST:Ee.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||Ee.env.NETLIFY_API_TOKEN,SITE_ID:Ee.env.SITE_ID,FUNCTIONS_DIST:Ee.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:Ve}});import{getTracer as xr}from"@netlify/otel";import dr from"crypto";import q from"fs/promises";import k from"path";import D from"process";var v=_("context"),fr=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:D.env.NETLIFY_TEAM_ID,userId:D.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:D.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},mr=10,gr=async e=>{let{name:t,ext:r}=k.parse(e),n=e,o=k.join(D.cwd(),b,n),s=0;for(;await hr(o);){if(s>=mr)throw new Error("Failed to generate context file");n=`${t}-${dr.randomUUID().slice(0,5)}${r}`,o=k.join(D.cwd(),b,n),s+=1}return n},hr=async e=>{try{return await q.access(e),!0}catch{return!1}},Er=async()=>{try{v.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 v.warn("Invalid response structure: missing or invalid consumers array"),null;let r=t.consumers.find(n=>n&&typeof n=="object"&&n.key==="catchall-consumer");return r?!r.contextScopes||typeof r.contextScopes!="object"?(v.warn("Catchall consumer missing or invalid contextScopes"),null):r:(v.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?v.warn("Netlify features context request timed out"):v.warn("Failed to fetch Netlify features context:",e.message),null}},_r=async(e,t)=>{try{let r=await fetch(e,{signal:AbortSignal.timeout(1e4)});if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let n=await r.text();return await q.writeFile(t,n,"utf-8"),!0}catch(r){return r.name==="AbortError"?v.warn(`Download timeout for ${e}`):v.warn(`Failed to download context file ${e}:`,r.message),!1}},_e=null,yr=async()=>{if(_e)return _e;let e=await Er();if(!e)return[];let t=k.join(D.cwd(),b,Ce);await q.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([o,s])=>{if(!s||typeof s!="object"||!s.endpoint||!s.scope)return v.warn(`Invalid scope data for ${o}, skipping...`),null;let l=`${o}.md`,a=k.join(t,l),i=k.join(b,Ce,l);return v.log(`Downloading ${s.scope} context...`),await _r(s.endpoint,a)?(v.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:o}):null});return _e=(await Promise.all(r)).filter(o=>o!==null),_e},pt=async({cliPath:e,netlify:t,config:r,buildErrorContext:n})=>{let o=fr(t),s=await gr(Ke),l=k.join(D.cwd(),b);await q.mkdir(l,{recursive:!0});let a=k.join(b,s),i=k.join(D.cwd(),a),p=k.join(D.cwd(),b,ee);try{await q.unlink(p),v.log(`Deleted old results file: ${p}`)}catch{}let c=n?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
8
+ `);return s.length>e.length*.8?e:s}import Ee from"process";import{getTracer as mr}from"@netlify/otel";import ce from"process";var Ie=ce.env.NETLIFY_API_URL,we=ce.env.NETLIFY_API_TOKEN,ae=_("api"),pe=async(e,t={})=>{if(!Ie||!we)throw new Error("No API URL or token");let r=new URL(e,Ie),o={...t,headers:{...t.headers,Authorization:`Bearer ${we}`}};ce.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(ce.env.AGENT_RUNNERS_DEBUG==="true")ae.log(`Response headers for ${r}:`),n.headers.forEach((u,i)=>{ae.log(` ${i}: ${u}`)});else{let u=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");ae.log(`Request ID for ${r}: ${u||"N/A"}`)}if(s||ae.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},Be=e=>{ae.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Ie=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(we=e.constants.NETLIFY_API_TOKEN)},de=(e,t)=>pe(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),V=(e,t,r)=>pe(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var He=(e,t)=>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 We=_("ai_gateway"),Ve=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),We.log("Requesting AI gateway information");let i=await qe(a,t.id,t.sessionId);if({token:r,url:s}=i,o=i.expires_at?i.expires_at*1e3:void 0,We.log("Got AI gateway information",{token:!!r,expiresAt:o,url:s}),o){let p=o-Date.now()-6e4;p>0&&(n=setTimeout(()=>{u()},p))}};return await u(),{get url(){return s},get token(){return r}}};import Q from"process";import{execa as Ut,execaCommand as on}from"execa";import{Transform as Lt}from"stream";var bt=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"]),Dt=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function Ft(){return Object.entries(process.env).filter(([e,t])=>!(!t||bt.has(e)||Dt.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function z(e){if(typeof e!="string")return e;let t=Ft();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp($t(o),"g");r=r.replace(n,"******")}),r}function $t(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Z=class extends Lt{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),s=z(n);o(null,s)}};function Ke(){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"?z(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"?z(o):o;return typeof n=="function"?r(a,n):r(a,n,s)}}var ln=_("shell"),Gt={preferLocal:!0},Xe=(e,t,r)=>{let[o,n]=Yt(t,r),s={...Gt,...n},a=Ut(e,o,s);return Mt(a,s),a};var Yt=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Mt=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(Q.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new Z).pipe(Q.stdout),e.stdout?.pipe(new Z).pipe(Q.stdout),e.stderr?.pipe(new Z).pipe(Q.stderr);return}e.stdout?.pipe(Q.stdout),e.stderr?.pipe(Q.stderr)};var Je="netlify-agent-runner-context.md",Ae="task-history",Ce="netlify-context",D=".netlify",ee="results.md",Se="assets",G="other",Y="personal";var M="enterprise",j="free",ze=[Y,"pro",M,j];var Ze=_("utils"),jt=e=>new Promise(t=>{setTimeout(t,e)}),Qe=(e,t=3e3)=>{let r=!1,o=null,n=[],s=null,a=(...u)=>{if(r)return o=u,new Promise(c=>{n.push(c)});r=!0;let i,p=new Promise(c=>{i=c});return s=(async()=>{await Promise.resolve();let c=await e(...u);for(i(c);;){if(await jt(t),!o)return r=!1,s=null,c;let d=o,m=n;o=null,n=[],c=await e(...d),m.forEach(T=>{T(c)})}})(),p};return a.flush=async()=>{if((r||o)&&s)return await s,a.flush()},a},fe=(e,t,r=!1)=>{let o=null,n=null,s=null,a=function(...u){n=u,s=this;let i=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(s,n),n=null,s=null)},t),i&&(e.apply(s,n),n=null,s=null)};return a.cancel=()=>{clearTimeout(o),o=null,n=null,s=null},a.flush=()=>{if(o){clearTimeout(o);let u=n,i=s;o=null,n=null,s=null,e.apply(i,u)}},a},me=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):Ze.error("Could not parse JSON",o))}},et=(e,t)=>{let n=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let u=`--${t}${n}`;if(u.length>55)return"";let i=60-u.length;if(i<=0)return"";if(i>=s.length+6){let p=Math.min(i-s.length,e.length);return`${s}${e.slice(0,p)}`}return e.slice(0,i)},Bt=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!ze.some(t=>t in e),tt=()=>{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);Bt(s)&&(e[r]=s)}catch(s){let u=s instanceof SyntaxError?"Invalid JSON":s.message;Ze.error(`Could not parse ${r} model version override from ${n}: ${u}`)}}}),e};import{Buffer as rt}from"buffer";import Ht from"path";var nt=async({config:e,netlify:t})=>{let r=await Wt(t),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};let s=await Vt(n);await t.utils.run("git",["add",".",...s]);let a={stdio:["ignore","pipe","pipe"]},i=(await t.utils.run("git",["diff","--staged"],a)).stdout;if(o=!!i,!o)return{hasChanges:!1,ignored:s};let c=(await t.utils.run("git",["diff","--staged","--binary"],a)).stdout,d,m;if(e.sha){await t.utils.run("git",["commit","-m","Agent runner"]),d=(await t.utils.run("git",["diff",e.sha,"HEAD"],a)).stdout;let h=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;d!==h&&(m=rt.from(h).toString("base64"))}let T={hasChanges:!0,diff:i,resultDiff:d,ignored:s};return i!==c&&(T.diffBinary=rt.from(c).toString("base64")),m&&(T.resultDiffBinary=m),T},qt=["?? mise.toml","?? deno.lock",/\?\? .+?\.log/],Wt=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
9
+ `).filter(n=>!qt.some(s=>s instanceof RegExp?s.test(n):n===s))).length!==0,status:t.stdout}};var ot=async e=>{let{stdout:t}=await e.utils.run("git",["rev-parse","HEAD"]);return t.trim()},st=async e=>{let{stdout:t}=await e.utils.run("git",["rev-list","--max-parents=0","HEAD"]);return t.trim()},Vt=async e=>{let t=[".netlify","mise.toml","deno.lock","node_modules"],r=[];return e.split(`
10
+ `).forEach(o=>{t.forEach(s=>{[`?? ${s}`,`?? ${s}${Ht.sep}`].some(u=>o.startsWith(u))&&r.push(`:!${s}`)});let n=o.match(/\?\? (.+?)\.log$/)?.[1];n&&r.push(`:!${n}.log`)}),r};import Xt from"fs/promises";import Jt from"os";import ge from"path";import H from"process";import zt from"readline";import Pe from"path";import Kt from"fs/promises";var ve=_("agent-output-utils");async function te({initialResult:e,agentName:t,hasError:r}){let o="",n=Pe.join(process.cwd(),D,ee);try{let s=await Kt.readFile(n,"utf-8");s&&(o=s,ve.log(`Pulled result from ${Pe.relative(process.cwd(),n)}`))}catch{ve.log(`No results file found at ${Pe.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&&ve.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 $=_("runner_claude"),it="Claude Code",Zt=({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 Oe({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:f}=o;if(!R||!f)throw new Error("No token or url provided from AI Gateway");let l=Qt[s];if(!l)throw new Error(`Claude is not supported for the account type ${s}`);if(i&&!l?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(u?.claude){let E=u?.claude?.[s];E&&(i=E)}H.env.ANTHROPIC_API_KEY=R,H.env.ANTHROPIC_BASE_URL=f}else if(!H.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let p=[],c=[],d={},m=0,T=0,y,g,h=ge.join(H.cwd(),"node_modules"),A=[ge.join(H.env.NODE_PATH||h,".bin/claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...i?["--model",i]:[],"-p",a],S=`${H.env.NVM_BIN}/node`;$.log(`Running ${S} ${A.join(" ")}`);let P=t.utils.run(S,A,{all:!0,env:H.env});P.stdin?.end();let I=fe(()=>{r?.({steps:p,duration:T})},250),N=(R,f)=>{let l={...R,id:m};m+=1,c.push(l),p.push(l),f||I.flush(),I(),f&&I.flush()},x=zt.createInterface({input:P.all});return x.on("error",R=>{$.error("Readline interface error",{error:R.message,stack:R.stack})}),x.on("line",R=>{let f=null;try{f=JSON.parse(R)}catch{$.log("Could not parse line",R)}Array.isArray(f?.message?.content)?f.message.content.forEach(l=>{switch(l.type){case"text":{l.text&&N({message:l.text});break}case"image":{typeof l.source=="object"&&l.source&&l.source.type==="base64"&&l.source.media_type?N({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 E=l.input?.description&&`\`${l.input.description}\``;N({title:[l.name,E].filter(Boolean).join(" ")})}else l.id&&(d[l.id]=l);I.flush();break}case"tool_result":{let E=l.tool_use_id?d[l.tool_use_id]:void 0,v;if(E){let U=E.input?.file_path&&ge.relative(H.cwd(),E.input.file_path),C=U&&`\`${U}\``;v=[E.name,C].filter(Boolean).join(" ")}let B=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(E?.name||""),b;if(typeof l.content=="string")b=l.content;else if(Array.isArray(l.content)){let U=[];l.content.forEach(C=>{C?.type==="text"&&typeof C.text=="string"?U.push(C.text):C?.type==="image"&&typeof C.source=="object"&&C.source?C.source.type==="base64"&&C.source.media_type?U.push(`![](data:${C.source.media_type};base64,${C.source.data})`):$.log(`Unsupported image type ${C.source.type}`,C.source):$.log(`Unsupported block type ${C?.type}`)}),b=U.join(`
11
+
12
+ `)}B&&b&&(b=`\`\`\`
13
+ ${b.trim()}
14
+ \`\`\``),N({title:v,message:b},!0);break}case"thinking":{l.thinking&&N({title:"Thinking",message:l.thinking},!0);break}default:$.log(`Message content type is not supported ${l.type}`,l)}}):f?.type==="result"&&(T=f.duration_ms||0,f.is_error?g=f.result:y=f.result,[c,p].forEach(l=>{l[l.length-1]?.message===y&&l.pop()}))}),await P.catch(R=>{({error:g,result:y}=Zt({catchError:R,runCmd:P,error:g,result:y,runnerName:"Claude"}))}),x.close(),I.flush(),{steps:c,duration:T,result:await te({initialResult:y,agentName:it,hasError:!!g}),error:re({error:g,agentName:it}),isRetryableError:ne(g)}}var at=async()=>{let e=ge.join(Jt.homedir(),".claude");await Xt.rm(e,{recursive:!0,force:!0})},Qt={[M]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:64e3},"claude-3-haiku-20240307":{maxTokens:4096},"claude-opus-4-20250514":{maxTokens:32e3},"claude-sonnet-4-20250514":{maxTokens:64e3}}},pro:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[Y]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[j]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}},[G]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}}};import er from"fs/promises";import tr from"os";import ke from"path";import X from"process";import rr from"readline";var J=_("runner_codex"),lt="Codex CLI",nr=({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 Le({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:N,url:x}=n;if(!N||!x)throw new Error("No token or url provided from AI Gateway");let R=or[s];if(!R)throw new Error(`Codex is not supported for the account type ${s}`);if(i&&!R?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(u?.codex){let f=u?.codex?.[s];f&&(i=f)}X.env.OPENAI_API_KEY=N,X.env.OPENAI_BASE_URL=x}else if(!X.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let p=[],c=[],d={},m=0,T=0,y,g,h=ke.join(X.cwd(),"node_modules"),A=[ke.join(X.env.NODE_PATH||h,".bin/codex"),"--approval-mode","full-auto",n?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...i?["--model",i]:[],"-q",a].filter(Boolean),S=`${X.env.NVM_BIN}/node`;J.log(`Running ${S} ${A.join(" ")}`);let P=t.utils.run(S,A,{all:!0,env:{...X.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),I=rr.createInterface({input:P.all});return I.on("error",N=>{J.error("Readline interface error",{error:N.message,stack:N.stack})}),I.on("line",N=>{let x=null;try{x=JSON.parse(N)}catch{J.log("Could not parse line",N);return}let R=[],f=!1;if(x?.duration_ms&&(T=x.duration_ms,f=!0),x?.type==="local_shell_call")d[x.call_id]=x;else if(x?.type==="local_shell_call_output"){let l=ir(d[x.call_id],x);l&&(l.id=m,m+=1,c.push(l),p.push(l),R.push(l),f=!0)}else x?.type==="message"&&x.role==="assistant"?y=x.content.map(l=>l.text).join(`
15
+ `):x?.type==="message"&&x.role==="system"&&(g=x.content.map(l=>l.text).join(`
16
+ `));f&&(r?.({steps:p,duration:T}),o?.({steps:R,duration:T}))}),await P.catch(N=>{let x=nr({catchError:N,runCmd:P,error:g,result:y,runnerName:"Codex"});g=x.error,y=x.result}),I.close(),{steps:c,duration:T,result:await te({initialResult:y,agentName:lt,hasError:!!g}),error:re({error:g,agentName:lt}),isRetryableError:ne(g)}}var ut=async()=>{let e=ke.join(tr.homedir(),".codex");await er.rm(e,{recursive:!0,force:!0})},or={[M]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},o1:{maxTokens:1e5},"o1-mini":{maxTokens:65536},"o3-mini":{maxTokens:1e5},"gpt-image-1":{},"dall-e-2":{},"dall-e-3":{}}},[Y]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768}}},pro:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768}}},[j]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},"o3-mini":{maxTokens:16e3}}},[G]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},"o3-mini":{maxTokens:16e3}}}},sr=new Set(["bash","-lc"]),ir=(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
+ ${n.trim()}
18
+ \`\`\``)}catch(s){J.error("Could not decode outputMsg",s,t.output)}return{title:o,message:n}};import ar from"fs/promises";import lr from"os";import he from"path";import q from"process";import ur from"readline";var oe=_("runner_gemini"),ct="Gemini CLI",cr=({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})),pr={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 be({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:f,url:l}=n;if(!f||!l)throw new Error("No token or url provided from AI Gateway");let E=dr[s];if(!E)throw new Error(`Gemini is not supported for the account type ${s}`);if(i&&!E?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(u?.gemini){let v=u?.gemini?.[s];v&&(i=v)}q.env.GEMINI_API_KEY=f,q.env.GOOGLE_GEMINI_BASE_URL=l}else if(!q.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let p=[],c=[],d=[],m={},T=0,y=0,g,h,A=he.join(q.cwd(),"node_modules"),S=[he.join(q.env.NODE_PATH||A,".bin/gemini"),...i?["--model",i]:[],"--yolo","-p",a],P=`${q.env.NVM_BIN}/node`;oe.log(`Running ${P} ${S.join(" ")}`);let I=t.utils.run(P,S,{all:!0,env:q.env});I.stdin?.end();let N=fe(()=>{r?.({steps:p,duration:y}),o?.({steps:c,duration:y}),c=[]},250),x=(f,l)=>{f.id=T,T+=1,d.push(f),p.push(f),c.push(f),l||N.flush(),N(),l&&N.flush()},R=ur.createInterface({input:I.all});return R.on("error",f=>{oe.error("Readline interface error",{error:f.message,stack:f.stack})}),R.on("line",f=>{let l=null;try{if(f.startsWith("[API Error")){let E=f.match(/\[api error: (.+?)]$/i)?.[1];l={type:"error",value:me(E,!1)?.error?.message||E||"Gemini encountered error"}}else l=JSON.parse(f)}catch{return}if(l)switch(l.type){case"thought":{let E=l.value;x({title:E?.subject??"Thinking...",message:E?.description},!0);break}case"content":{l.value&&x({message:l.value});break}case"tool_call_request":{let E=l.value,v=pr[E.name]??E.name,B=E.args?.path||E.args?.absolute_path,b=B&&he.relative(q.cwd(),B),U=E.args?.command,Ct={title:[v,b&&`\`${b}\``,U&&`\`${U}\``].filter(Boolean).join(" ")};m[E.callId]=Ct,N.flush();break}case"tool_result":{let E=l.value,v=m[E.callId];if(v){let B=[E.resultDisplay,E.responseParts?.functionResponse?.response?.output].find(b=>typeof b=="string"&&b);B&&(v.message=`\`\`\`
19
+ ${B.trim()}
20
+ \`\`\``),x(v,!0)}break}case"result":{y=l.duration_ms,g=l.value,[d,p,c].forEach(E=>{E[E.length-1]?.message===g&&E.pop()});break}case"error":{h=l.value;break}case"finished":break;default:{oe.warn("Unhandled message type:",l.type);break}}}),await I.catch(f=>{({error:h,result:g}=cr({catchError:f,runCmd:I,error:h,result:g,runnerName:"Gemini"}))}),R.close(),N.flush(),{steps:d,duration:y,result:await te({initialResult:g,agentName:ct,hasError:!!h}),error:re({error:h,agentName:ct}),isRetryableError:ne(h)}}var pt=async()=>{let e=he.join(lr.homedir(),".gemini");await ar.rm(e,{recursive:!0,force:!0})},dr={[M]:{models:{"gemini-1.5-flash":{maxTokens:8192},"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-1.5-pro":{maxTokens:8192},"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:65536},"gemini-2.5-flash-lite":{maxTokens:65536},"gemini-2.5-pro":{maxTokens:65536},"imagen-4.0-generate-001":{},"veo-3.0-generate-preview":{}}},pro:{models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[Y]:{models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[j]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}},[G]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}}};var fr={codex:{runner:Le,clean:ut},claude:{runner:Oe,clean:at},gemini:{runner:be,clean:pt}},dt=fr;var ft=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>w(mr(),"init-stage",async n=>{let s=performance.now();n?.setAttributes({"init.runner":e.runner,"init.id":e.id,"init.sessionId":e.sessionId,"init.hasRepo":e.hasRepo,"init.useGateway":e.useGateway,"init.validateAgent":e.validateAgent,"init.runnerVersion":o||"unknown"});let a=dt[e.runner];if(!a)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let u=gr({apiToken:r});Be(u);let i=e.useGateway?await Ve({netlify:u,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!i}),e.validateAgent&&e.errorLogsPath&&n?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let p=Qe(({steps:m=[],duration:T})=>{let y=m.map(g=>({...g,title:g.title?z(g.title):void 0,message:g.message?z(g.message):void 0}));return m.length=0,V(e.id,e.sessionId,{steps:y,duration:T})},t),c;e.hasRepo?e.sha?(c=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(c=await ot(u),await de(e.id,{sha:c}),n?.setAttributes({"init.sha.source":"current_commit"})):(c=await st(u),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let d=performance.now()-s;return n?.setAttributes({"init.sha":c||"unknown","init.duration.ms":d,"init.status":"success"}),{aiGateway:i,context:u,persistSteps:p,runner:a,sha:c}}),gr=({apiToken:e})=>({constants:{NETLIFY_API_HOST:Ee.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||Ee.env.NETLIFY_API_TOKEN,SITE_ID:Ee.env.SITE_ID,FUNCTIONS_DIST:Ee.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:Xe}});import{getTracer as De}from"@netlify/otel";import hr from"crypto";import W from"fs/promises";import L from"path";import F from"process";var O=_("context"),Er=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:F.env.NETLIFY_TEAM_ID,userId:F.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:F.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},_r=10,yr=async e=>{let{name:t,ext:r}=L.parse(e),o=e,n=L.join(F.cwd(),D,o),s=0;for(;await Tr(n);){if(s>=_r)throw new Error("Failed to generate context file");o=`${t}-${hr.randomUUID().slice(0,5)}${r}`,n=L.join(F.cwd(),D,o),s+=1}return o},Tr=async e=>{try{return await W.access(e),!0}catch{return!1}},xr=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}},Rr=async(e,t)=>{try{let r=await fetch(e,{signal:AbortSignal.timeout(1e4)});if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let o=await r.text();return await W.writeFile(t,o,"utf-8"),!0}catch(r){return r.name==="AbortError"?O.warn(`Download timeout for ${e}`):O.warn(`Failed to download context file ${e}:`,r.message),!1}},_e=null,Nr=async()=>{if(_e)return _e;let e=await xr();if(!e)return[];let t=L.join(F.cwd(),D,Ce);await W.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`,u=L.join(t,a),i=L.join(D,Ce,a);return O.log(`Downloading ${s.scope} context...`),await Rr(s.endpoint,u)?(O.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:n}):null});return _e=(await Promise.all(r)).filter(n=>n!==null),_e},mt=async({cliPath:e,netlify:t,config:r,buildErrorContext:o})=>{let n=Er(t),s=await yr(Je),a=L.join(F.cwd(),D);await W.mkdir(a,{recursive:!0});let u=L.join(D,s),i=L.join(F.cwd(),u),p=L.join(F.cwd(),D,ee);try{await W.unlink(p),O.log(`Deleted old results file: ${p}`)}catch{}let c=o?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
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
- ${n}
27
- </build_error_context>`:"",m="";r.siteContext&&r.siteContext.length!==0&&(m=`
26
+ ${o}
27
+ </build_error_context>`:"",d="";r.siteContext&&r.siteContext.length!==0&&(d=`
28
28
  <project_rules>
29
- ${r.siteContext.filter(f=>f.site_context).map(f=>typeof f.site_context=="string"?f.site_context:typeof f.site_context=="object"?JSON.stringify(f.site_context):"").join(`
29
+ ${r.siteContext.filter(h=>h.site_context).map(h=>typeof h.site_context=="string"?h.site_context:typeof h.site_context=="object"?JSON.stringify(h.site_context):"").join(`
30
30
 
31
31
  `)}
32
32
  </project_rules>
33
- `);let h="";if(r.sessionHistoryContext?.length){let f=k.join(D.cwd(),b,Ae);await q.mkdir(f,{recursive:!0});let w=await Promise.all(r.sessionHistoryContext.map(async(A,S)=>{let I=S+1,R=`attempt-${I}.md`,x=k.join(f,R),N=k.join(b,Ae,R),d=`# Task History - Attempt ${I}
33
+ `);let m="";if(r.sessionHistoryContext?.length){let h=L.join(F.cwd(),D,Ae);await W.mkdir(h,{recursive:!0});let A=await Promise.all(r.sessionHistoryContext.map(async(S,P)=>{let I=P+1,N=`attempt-${I}.md`,x=L.join(h,N),R=L.join(D,Ae,N),f=`# Task History - Attempt ${I}
34
34
 
35
35
  ## Request - what the user asked for
36
- ${A.request}
36
+ ${S.request}
37
37
 
38
38
  ---
39
39
 
40
40
  ## Response - what the agent replied with after its work
41
41
 
42
- ${A.response}
43
- `;return await q.writeFile(x,d,"utf-8"),v.log(`Created history file: ${N}`),N}));h+=`
42
+ ${S.response}
43
+ `;return await W.writeFile(x,f,"utf-8"),O.log(`Created history file: ${R}`),R}));m+=`
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
- ${w.slice(-5).map(A=>`- ${A}`).join(`
48
+ ${A.slice(-5).map(S=>`- ${S}`).join(`
49
49
  `)}
50
50
 
51
51
  </session_history_context>
52
- `}let E=await yr(),y="";E.length>0&&(y=`
52
+ `}let T=await Nr(),y="";T.length>0&&(y=`
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
- ${E.map(f=>`- **${f.scope}**: ${f.path}`).join(`
57
+ ${T.map(h=>`- **${h.scope}**: ${h.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 T=`
62
+ `);let g=`
63
63
  You're an AI agent designed to assist with tasks related to a Netlify project. Please review, understand, and use the context provided to complete the user's request as needed.
64
64
 
65
65
  <request>
@@ -72,27 +72,27 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
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 ${l}/${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 ${l}/${ee} 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
  </responses>
79
79
  <attachements>
80
- - for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${l}/${Se} folder
81
- - move assets from ${l}/${Se} folder to the project assets folder if they are referenced in a code or applied changes
80
+ - for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${a}/${Se} folder
81
+ - move assets from ${a}/${Se} folder to the project assets folder if they are referenced in a code or applied changes
82
82
  </attachements>
83
- ${m}
83
+ ${d}
84
84
  </requirements>
85
85
 
86
86
  <extra_context>
87
87
  <metadata>
88
- - Site/Project ID: ${o.siteId}
89
- - Account/Team ID: ${o.accountId}
90
- - User ID: ${o.userId}
91
- - Site/Project Slug: ${o.siteSlug}
92
- - Netlify Functions directory: ${o.functionsDir}
88
+ - Site/Project ID: ${n.siteId}
89
+ - Account/Team ID: ${n.accountId}
90
+ - User ID: ${n.userId}
91
+ - Site/Project Slug: ${n.siteSlug}
92
+ - Netlify Functions directory: ${n.functionsDir}
93
93
  </metadata>
94
94
  <environment>
95
- - Node Version: ${D.version||"unknown"}
95
+ - Node Version: ${F.version||"unknown"}
96
96
  - Environment variables are set globally (e.g. \`echo $VARIABLE_NAME\` can be used to check if a var is set).
97
97
  - 'netlify-cli' npm package is already available as a global package. Don't try to install it again
98
98
  - 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.
@@ -104,8 +104,8 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
104
104
  </docs>
105
105
  </extra_context>
106
106
 
107
- ${h}
108
- `;return await q.writeFile(i,T,"utf-8"),v.log(`Generated agent context document at: ${i}`),T.length>5e5&&(T=`
107
+ ${m}
108
+ `;return await W.writeFile(i,g,"utf-8"),O.log(`Generated agent context document at: ${i}`),g.length>5e5&&(g=`
109
109
  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.
110
110
 
111
111
  <request>
@@ -116,15 +116,15 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
116
116
  </request>
117
117
 
118
118
  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.
119
- `),T};var Tr=_("prompt"),dt=async({cliPath:e,config:t,netlify:r,buildErrorContext:n})=>{let o=await pt({cliPath:e,config:t,netlify:r,buildErrorContext:n});return process.env.AGENT_RUNNER_DEBUG&&Tr.log("Contextful Prompt:",o),{prompt:o}};var ye=_("inference_stage"),ft=5,Te=async e=>V(xr(),"inference-stage",async t=>{let{cliPath:r,config:n,context:o,buildErrors:s,runner:l,persistSteps:a,aiGateway:i,attempt:p,contextPrefix:c}=e;t?.setAttributes({"inference.attempt":p}),ye.log(`Running inference stage, attempt ${p} of ${ft}`),qe();let{prompt:m}=await dt({cliPath:r,config:n,buildErrorContext:Rr(s),netlify:o}),h=`
119
+ `),g};var Ir=_("prompt"),gt=async({cliPath:e,config:t,netlify:r,buildErrorContext:o})=>{let n=await mt({cliPath:e,config:t,netlify:r,buildErrorContext:o});return process.env.AGENT_RUNNER_DEBUG&&Ir.log("Contextful Prompt:",n),{prompt:n}};var ye=_("inference_stage"),ht=5,Te=async e=>w(De(),"inference-stage",async t=>{let{cliPath:r,config:o,context:n,buildErrors:s,runner:a,persistSteps:u,aiGateway:i,attempt:p,contextPrefix:c}=e;t?.setAttributes({"inference.attempt":p}),ye.log(`Running inference stage, attempt ${p} of ${ht}`),Ke();let{prompt:d}=await w(De(),"compose-prompt",async()=>await gt({cliPath:r,config:o,buildErrorContext:wr(s),netlify:n})),m=`
120
120
  ${c||""}
121
- ${m}
122
- `.trim(),E={...n,prompt:h},y=await l({aiGateway:i,config:E,netlify:o,persistSteps:a});if(await a.flush(),y.error){if(ye.error("Runner failed",{stepsCount:y.steps.length,duration:y.duration,error:y.error,isRetryableError:y.isRetryableError,attempt:p||1}),y.isRetryableError&&(!p||p<ft))return ye.log("Retrying inference stage"),await new Promise(f=>setTimeout(f,5e3)),{runnerResult:(await Te({...e,attempt:(p||1)+1,contextPrefix:"<important> The agent has already started on this work but ran into networking errors trying to complete it. Please continue from where it left off (you can use git commands to see what's currently changed thus far) and do not start over. Here is the full prompt for context: </important>"})).runnerResult};throw ye.log("Do not retry inference stage"),new Error(y.error)}return{runnerResult:y}}),Rr=e=>!e||e.length===0?"":`
121
+ ${d}
122
+ `.trim(),T={...o,prompt:m},y=await w(De(),`run-${o.runner}`,async()=>await a({aiGateway:i,config:T,netlify:n,persistSteps:u}));if(await u.flush(),y.error){if(ye.error("Runner failed",{stepsCount:y.steps.length,duration:y.duration,error:y.error,isRetryableError:y.isRetryableError,attempt:p||1}),y.isRetryableError&&(!p||p<ht))return ye.log("Retrying inference stage"),await new Promise(h=>setTimeout(h,5e3)),{runnerResult:(await Te({...e,attempt:(p||1)+1,contextPrefix:"<important> The agent has already started on this work but ran into networking errors trying to complete it. Please continue from where it left off (you can use git commands to see what's currently changed thus far) and do not start over. Here is the full prompt for context: </important>"})).runnerResult};throw ye.log("Do not retry inference stage"),new Error(y.error)}return{runnerResult:y}}),wr=e=>!e||e.length===0?"":`
123
123
  Deploy failed failed. Here are the errors to review on the latest build:
124
124
 
125
125
  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.
126
126
 
127
127
  ${e.pop()}
128
- `;import Nr from"process";var le=_("deploy"),mt=async({netlify:e,hasRepo:t,skipBuild:r,message:n="Agent Preview",deploySubdomain:o,cliPath:s,filter:l})=>{try{let a=["deploy","--message",`"${n}"`,"--json","--draft","--verbose"];t||(le.log("Deploy: Uploading source zip"),a.push("--upload-source-zip")),o&&a.push("--alias",o),l&&a.push("--filter",l),r?(le.log("Deploy: Skipping build"),a.push("--no-build")):a.push("--context","deploy-preview");let i=s||"netlify";le.log(`Running: ${i} ${a.join(" ")}`);let p=await e.utils.run(i,a,{stdio:["ignore","pipe","pipe"]}),c=JSON.parse(p.stdout.trim());le.log(`
129
- Preview deploy created successfully:`,{deployId:c.deploy_id,deployUrl:c.deploy_url,siteId:c.site_id});let m={deployId:c.deploy_id,previewUrl:c.deploy_url,logsUrl:c.logs,siteId:c.site_id};return t||(m.sourceZipFilename=c.source_zip_filename),m}catch(a){throw le.error("Failed to create preview deploy via CLI:",a),a}};var ue=_("deploy_stage"),De=async({cliPath:e,config:t,context:r,result:n,filter:o})=>{let s=await et({config:t,netlify:r});if(ue.info("Resolved git",{hasChanges:s.hasChanges,ignored:s.ignored??[]}),!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:l,resultDiff:a,diffBinary:i,resultDiffBinary:p}=s,c=!0;ue.log("Preview deploy condition check:",{resultUndefined:n===void 0,resultType:typeof n,hasChanges:c,wouldCreatePreview:n!==void 0&&c});let m=null;if(n!==void 0&&c)try{let h;try{let E=await Me(t.id,t.sessionId);E?.title&&(h=E.title)}catch(E){ue.warn("Failed to fetch session title, using fallback message:",E.message)}m=await mt({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:h,skipBuild:!1,deploySubdomain:ze(t.id,Nr.env.SITE_NAME),filter:o})}catch(h){return ue.warn("Failed to create preview deploy (continuing with agent run):",h),{diff:l,resultDiff:a,hasChanges:c,previewInfo:null,diffBinary:i,resultDiffBinary:p,deployError:h instanceof Error?h.message:String(h)}}return ue.log("Git status",{hasDiff:!!l,hasChanges:c}),{diff:l,resultDiff:a,hasChanges:c,previewInfo:m,diffBinary:i,resultDiffBinary:p}};async function gt(e,t){let{maxRetries:r,baseDelay:n,onRetry:o}=t,s;for(let l=1;l<=r;l++)try{return await e()}catch(a){if(s=a,l===r)throw s;o&&o(l,s),await new Promise(i=>setTimeout(i,n*l))}throw s}var se=_("cleanup_stage"),ht=async({config:e,diff:t,result:r,duration:n,resultDiff:o,diffBinary:s,resultDiffBinary:l,previewInfo:a})=>{let i={result_diff:t,result:r||"Done",duration:n,result_diff_binary:s};return a&&a.deployId&&(i.deploy_id=a.deployId),a&&a.sourceZipFilename&&(i.result_zip_file_name=a.sourceZipFilename),o||l?(se.log("Updating total agent result diff"),await de(e.id,{result_diff:o,result_diff_binary:l})):se.log("No total result diff, not updating"),se.log("Updated agent runner with result"),await gt(()=>K(e.id,e.sessionId,i),{maxRetries:3,baseDelay:1e3,onRetry:(p,c)=>{se.error(`Error updating agent runner session (attempt ${p}):`,c),se.log("Retrying...")}}),se.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as wr}from"@netlify/otel";var Ar=Ir(import.meta.url),Et=Ar("../package.json"),_t=_("pipeline_index"),xe=3,yt=async({config:e,apiToken:t,cliPath:r="netlify",cwd:n,errorLogsPath:o,filter:s,traceExporterUrl:l})=>{let a;try{await Ue(Et.version,e.id,l);let i=wr();await V(i,"run-pipeline",async()=>{let p,{aiGateway:c,context:m,persistSteps:h,runner:E,sha:y}=await ct({config:e,apiToken:t,cliPath:r,cwd:n,errorLogsPath:o,filter:s,runnerVersion:Et.version});a=E.clean,e.sha=y;let{runnerResult:T}=await Te({cliPath:r,config:e,context:m,runner:E.runner,persistSteps:h,aiGateway:c});await K(e.id,e.sessionId,{steps:[{title:"Deploying the run preview"}]});let f=await De({cliPath:r,config:e,context:m,result:T.result,filter:s}),w=T,A=[];if(f.hasChanges&&f.deployError){A.push(Ge(f.deployError));let d=1;for(;d<=xe&&!f.previewInfo;)_t.log(`Deploy attempt had errors. Retrying. ${d}/${xe}`),await V(i,"stage-deploy",async u=>{u?.setAttributes({"stage.attempt":d});let{runnerResult:g}=await Te({cliPath:r,config:e,context:m,runner:E.runner,persistSteps:h,aiGateway:c,buildErrors:A});w={...g,steps:[...w.steps||[],...g.steps||[]],duration:(w.duration||0)+(g.duration||0)},f=await De({cliPath:r,config:e,context:m,result:g.result,filter:s}),f.deployError&&A.push(f.deployError),d++});d>xe&&!f.previewInfo&&(p=new Error(`Deploy validation failed after ${xe} attempts`))}let{diff:S,resultDiff:I,previewInfo:R,diffBinary:x,resultDiffBinary:N}=f;if(await ht({config:e,diff:S,result:w.result,duration:w.duration,resultDiff:I,diffBinary:x,resultDiffBinary:N,previewInfo:R}),p)throw p;await E.clean?.()})}catch(i){_t.error("Got error while running pipeline",i),await a?.();let p=i instanceof Error&&i.message;throw await K(e.id,e.sessionId,{result:p||"Encountered error when running agent",state:"error"}),i}};import O from"process";var Cr="claude",Sr=e=>(e??[]).filter(t=>t.request&&t.response),Pr=e=>(e??[]).filter(t=>t.site_context),Tt=_("config"),xt=()=>{let e=O.env.NETLIFY_AGENT_RUNNER_ID,t=O.env.NETLIFY_AGENT_RUNNER_SESSION_ID;if(!e||!t)throw new Error("ID of agent runner is not provided");let r=O.env.NETLIFY_AGENT_RUNNER_RESULT_BRANCH,n=O.env.NETLIFY_AGENT_RUNNER_PROMPT;if(!n)throw new Error("Prompt is not provided");let o=O.env.NETLIFY_AGENT_RUNNER_AGENT||Cr,s=O.env.NETLIFY_AGENT_RUNNER_MODEL,l=O.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED==="1",a=O.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED==="1",i=O.env.ERROR_LOGS_PATH,p=me(O.env.NETLIFY_AGENT_RUNNER_CONTEXT,!0,Tt),c=Sr(p),m=Pr(p),h=O.env.NETLIFY_AGENT_RUNNER_HAS_REPO!=="0",E=!O.env.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED,y=O.env.NETLIFY_AGENT_RUNNER_SHA,T=vr(),f=Ze(),w={id:e,sessionId:t,resultBranch:r,prompt:n,runner:o,model:s,validateAgent:l,errorLogsPath:i,sessionHistoryContext:c,siteContext:m,hasRepo:h,useGateway:E,sha:y,accountType:T,validateAgentWithBuild:a,modelVersionOverrides:f};return Tt.log({fullConfig:w}),w},vr=()=>{let e=O.env.NETLIFY_TEAM_TYPE;return e?e.includes("personal")?G:e.includes("pro")?"pro":e.startsWith("enterprise")?Y:e.startsWith("free")?M:U:U};var Rt=_("bin_cmd"),ie=Or(Fe.argv.slice(2),{string:["auth","cwd","cli-path","error-logs-path","filter","trace-exporter-url"]});try{let e=xt();await yt({config:e,apiToken:ie.auth,cwd:ie.cwd,cliPath:ie["cli-path"],errorLogsPath:ie["error-logs-path"],filter:ie.filter,traceExporterUrl:ie["trace-exporter-url"]}),Rt.info("Finished agent"),Fe.exit(0)}catch(e){Rt.error("Error running agent pipeline:",e),Fe.exit(1)}
128
+ `;import Sr from"process";import{getTracer as Fe}from"@netlify/otel";import{getTracer as Ar}from"@netlify/otel";var le=_("deploy"),Et=async e=>await w(Ar(),"create-preview-deploy",async t=>Cr(e,t)),Cr=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||(le.log("Deploy: Uploading source zip"),i.push("--upload-source-zip")),n&&i.push("--alias",n),a&&i.push("--filter",a),r?(le.log("Deploy: Skipping build"),i.push("--no-build")):i.push("--context","deploy-preview");let p=s||"netlify";le.log(`Running: ${p} ${i.join(" ")}`),u?.setAttributes({cmd:p,args:i});let c=await e.utils.run(p,i,{stdio:["ignore","pipe","pipe"]}),d=JSON.parse(c.stdout.trim());u?.setAttributes({success:!0,deployId:d.deploy_id,deployUrl:d.deploy_url,siteId:d.site_id}),le.log(`
129
+ Preview deploy created successfully:`,{deployId:d.deploy_id,deployUrl:d.deploy_url,siteId:d.site_id});let m={deployId:d.deploy_id,previewUrl:d.deploy_url,logsUrl:d.logs,siteId:d.site_id};return t||(m.sourceZipFilename=d.source_zip_filename),m}catch(i){throw le.error("Failed to create preview deploy via CLI:",i),u?.setAttributes({success:!1,error:i.message}),i}};var ue=_("deploy_stage"),$e=async e=>await w(Fe(),"run-deploy-stage",async()=>Pr(e)),Pr=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let s=await w(Fe(),"get-runner-diffs",async()=>await nt({config:t,netlify:r}));if(ue.info("Resolved git",{hasChanges:s.hasChanges,ignored:s.ignored??[]}),!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:u,diffBinary:i,resultDiffBinary:p}=s,c=!0;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 m;try{let T=await w(Fe(),"get-runner-session",async()=>await He(t.id,t.sessionId));T?.title&&(m=T.title)}catch(T){ue.warn("Failed to fetch session title, using fallback message:",T.message)}d=await Et({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:m,skipBuild:!1,deploySubdomain:et(t.id,Sr.env.SITE_NAME),filter:n})}catch(m){return ue.warn("Failed to create preview deploy (continuing with agent run):",m),{diff:a,resultDiff:u,hasChanges:c,previewInfo:null,diffBinary:i,resultDiffBinary:p,deployError:m instanceof Error?m.message:String(m)}}return ue.log("Git status",{hasDiff:!!a,hasChanges:c}),{diff:a,resultDiff:u,hasChanges:c,previewInfo:d,diffBinary:i,resultDiffBinary:p}};import{getTracer as Ue}from"@netlify/otel";async function _t(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 se=_("cleanup_stage"),yt=async e=>await w(Ue(),"cleanup-stage",async()=>vr(e)),vr=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?(se.log("Updating total agent result diff"),await w(Ue(),"update-runner",async()=>{await de(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 _t(async()=>await w(Ue(),"update-runner-session",()=>V(e.id,e.sessionId,i)),{maxRetries:3,baseDelay:1e3,onRetry:(p,c)=>{se.error(`Error updating agent runner session (attempt ${p}):`,c),se.log("Retrying...")}}),se.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as Tt}from"@netlify/otel";var kr=Or(import.meta.url),xt=kr("../package.json"),Rt=_("pipeline_index"),xe=3,Nt=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:s,traceExporterUrl:a})=>{let u;await Me(xt.version,e.id,a),await w(Tt(),"run-pipeline",async()=>{try{let i,{aiGateway:p,context:c,persistSteps:d,runner:m,sha:T}=await ft({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:s,runnerVersion:xt.version});u=m.clean,e.sha=T;let{runnerResult:y}=await Te({cliPath:r,config:e,context:c,runner:m.runner,persistSteps:d,aiGateway:p});await V(e.id,e.sessionId,{steps:[{title:"Deploying the run preview"}]});let g=await $e({cliPath:r,config:e,context:c,result:y.result,filter:s}),h=y,A=[];if(g.hasChanges&&g.deployError){A.push(je(g.deployError));let R=1;for(;R<=xe&&!g.previewInfo;)Rt.log(`Deploy attempt had errors. Retrying. ${R}/${xe}`),await w(Tt(),"deploy-stage",async f=>{f?.setAttributes({"stage.attempt":R});let{runnerResult:l}=await Te({cliPath:r,config:e,context:c,runner:m.runner,persistSteps:d,aiGateway:p,buildErrors:A});h={...l,steps:[...h.steps||[],...l.steps||[]],duration:(h.duration||0)+(l.duration||0)},g=await $e({cliPath:r,config:e,context:c,result:l.result,filter:s}),g.deployError&&A.push(g.deployError),R++});R>xe&&!g.previewInfo&&(i=new Error(`Deploy validation failed after ${xe} attempts`))}let{diff:S,resultDiff:P,previewInfo:I,diffBinary:N,resultDiffBinary:x}=g;if(await yt({config:e,diff:S,result:h.result,duration:h.duration,resultDiff:P,diffBinary:N,resultDiffBinary:x,previewInfo:I}),i)throw i;await m.clean?.()}catch(i){Rt.error("Got error while running pipeline",i),await u?.();let p=i instanceof Error&&i.message;throw await V(e.id,e.sessionId,{result:p||"Encountered error when running agent",state:"error"}),i}})};import k from"process";var Lr="claude",br=e=>(e??[]).filter(t=>t.request&&t.response),Dr=e=>(e??[]).filter(t=>t.site_context),It=_("config"),wt=()=>{let e=k.env.NETLIFY_AGENT_RUNNER_ID,t=k.env.NETLIFY_AGENT_RUNNER_SESSION_ID;if(!e||!t)throw new Error("ID of agent runner is not provided");let r=k.env.NETLIFY_AGENT_RUNNER_RESULT_BRANCH,o=k.env.NETLIFY_AGENT_RUNNER_PROMPT;if(!o)throw new Error("Prompt is not provided");let n=k.env.NETLIFY_AGENT_RUNNER_AGENT||Lr,s=k.env.NETLIFY_AGENT_RUNNER_MODEL,a=k.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED==="1",u=k.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED==="1",i=k.env.ERROR_LOGS_PATH,p=me(k.env.NETLIFY_AGENT_RUNNER_CONTEXT,!0,It),c=br(p),d=Dr(p),m=k.env.NETLIFY_AGENT_RUNNER_HAS_REPO!=="0",T=!k.env.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED,y=k.env.NETLIFY_AGENT_RUNNER_SHA,g=Fr(),h=tt(),A={id:e,sessionId:t,resultBranch:r,prompt:o,runner:n,model:s,validateAgent:a,errorLogsPath:i,sessionHistoryContext:c,siteContext:d,hasRepo:m,useGateway:T,sha:y,accountType:g,validateAgentWithBuild:u,modelVersionOverrides:h};return It.log({fullConfig:A}),A},Fr=()=>{let e=k.env.NETLIFY_TEAM_TYPE;return e?e.includes("personal")?Y:e.includes("pro")?"pro":e.startsWith("enterprise")?M:e.startsWith("free")?j:G:G};var At=_("bin_cmd"),ie=$r(Ge.argv.slice(2),{string:["auth","cwd","cli-path","error-logs-path","filter","trace-exporter-url"]});try{let e=wt();await Nt({config:e,apiToken:ie.auth,cwd:ie.cwd,cliPath:ie["cli-path"],errorLogsPath:ie["error-logs-path"],filter:ie.filter,traceExporterUrl:ie["trace-exporter-url"]}),At.info("Finished agent"),Ge.exit(0)}catch(e){At.error("Error running agent pipeline:",e),Ge.exit(1)}
130
130
  //# sourceMappingURL=bin.js.map
package/dist/index.js CHANGED
@@ -1,64 +1,64 @@
1
- import{createRequire as mr}from"module";import{createTracerProvider as mt}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as be}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as gt}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as ht}from"@netlify/otel";import{OTLPTraceExporter as Et}from"@opentelemetry/exporter-trace-otlp-grpc";function T(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 ye=T("tracing"),$e=(e,t,r)=>mt({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new be(new Te),new be(new Et({url:r}))],instrumentations:[new gt({skipHeaders:!0})]});function j(e,t,r){return ye.log(`\u23F3 TRACE: ${t} starting...`),ht(e,t,r)}var Te=class{export(t,r){for(let o of t)this.logSpan(o);r({code:1})}async shutdown(){}forceFlush(){return Promise.resolve()}logSpan(t){let r=(t.endTime[0]-t.startTime[0])*1e3+(t.endTime[1]-t.startTime[1])/1e6,o=t.attributes,n=[];for(let[a,i]of Object.entries(o))a.includes("duration")&&typeof i=="number"?n.push(`${a}=${i.toFixed(2)}ms`):n.push(`${a}=${i}`);let s=t.status?.code===2?"\u274C":"\u2705",l=n.length>0?` [${n.join(", ")}]`:"";ye.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${l}`),t.status?.code===2&&t.status.message&&ye.log(` \u274C Error: ${t.status.message}`)}};var _t=["error","failed","exception","fatal","panic","abort","crash"];function De(e){let t=e.split(`
2
- `),r=[],o=-1,n=0;for(;n<t.length;){let a=t[n].slice(0,500).toLowerCase();if(_t.some(d=>a.includes(d))){let d=Math.max(0,n-10,o+1),c=Math.min(t.length-1,n+20),m=[];for(let h=d;h<=c;h++)m.push(t[h]);r.push(m.join(`
3
- `)),o=c,n=c+1}else n++}if(r.length===0)return e;let s=r.map((l,a)=>`<extracted_error_chunk order="${a+1}">
1
+ import{createRequire as xr}from"module";import{createTracerProvider as Et}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as Le}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as _t}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as Tt}from"@netlify/otel";import{OTLPTraceExporter as xt}from"@opentelemetry/exporter-trace-otlp-grpc";function x(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 _e=x("tracing"),Fe=(e,t,r)=>Et({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new Le(new Te),new Le(new xt({url:r}))],instrumentations:[new _t({skipHeaders:!0})]});function N(e,t,r){return _e.log(`\u23F3 TRACE: ${t} starting...`),Tt(e,t,r)}var Te=class{export(t,r){for(let o of t)this.logSpan(o);r({code:1})}async shutdown(){}forceFlush(){return Promise.resolve()}logSpan(t){let r=(t.endTime[0]-t.startTime[0])*1e3+(t.endTime[1]-t.startTime[1])/1e6,o=t.attributes,n=[];for(let[u,i]of Object.entries(o))u.includes("duration")&&typeof i=="number"?n.push(`${u}=${i.toFixed(2)}ms`):n.push(`${u}=${i}`);let s=t.status?.code===2?"\u274C":"\u2705",l=n.length>0?` [${n.join(", ")}]`:"";_e.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${l}`),t.status?.code===2&&t.status.message&&_e.log(` \u274C Error: ${t.status.message}`)}};var wt=["error","failed","exception","fatal","panic","abort","crash"];function Ue(e){let t=e.split(`
2
+ `),r=[],o=-1,n=0;for(;n<t.length;){let u=t[n].slice(0,500).toLowerCase();if(wt.some(p=>u.includes(p))){let p=Math.max(0,n-10,o+1),c=Math.min(t.length-1,n+20),f=[];for(let m=p;m<=c;m++)f.push(t[m]);r.push(f.join(`
3
+ `)),o=c,n=c+1}else n++}if(r.length===0)return e;let s=r.map((l,u)=>`<extracted_error_chunk order="${u+1}">
4
4
  ${l}
5
5
  </extracted_error_chunk>`).join(`
6
6
 
7
- `);return s.length>e.length*.8?e:s}import me from"process";import{getTracer as er}from"@netlify/otel";import le from"process";var xe=le.env.NETLIFY_API_URL,Re=le.env.NETLIFY_API_TOKEN,oe=T("api"),ue=async(e,t={})=>{if(!xe||!Re)throw new Error("No API URL or token");let r=new URL(e,xe),o={...t,headers:{...t.headers,Authorization:`Bearer ${Re}`}};le.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let n=await fetch(r,o),s=n.ok&&n.status<=299;if(le.env.AGENT_RUNNERS_DEBUG==="true")oe.log(`Response headers for ${r}:`),n.headers.forEach((a,i)=>{oe.log(` ${i}: ${a}`)});else{let a=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");oe.log(`Request ID for ${r}: ${a||"N/A"}`)}if(s||oe.error(`Got status ${n.status} for request ${r}`),t.raw){if(!s)throw n;return n}let l=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!s)throw l;return l},Le=e=>{oe.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(xe=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Re=e.constants.NETLIFY_API_TOKEN)},ce=(e,t)=>ue(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),Y=(e,t,r)=>ue(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var Fe=(e,t)=>ue(`/api/v1/agent_runners/${e}/sessions/${t}`),Ue=(e,t,r)=>ue(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}});var Me=T("ai_gateway"),Ge=async({netlify:e,config:t})=>{let r,o,n,s,l=e.constants?.SITE_ID;if(!l)throw new Error("No site id");let a=async()=>{clearTimeout(n),Me.log("Requesting AI gateway information");let i=await Ue(l,t.id,t.sessionId);if({token:r,url:s}=i,o=i.expires_at?i.expires_at*1e3:void 0,Me.log("Got AI gateway information",{token:!!r,expiresAt:o,url:s}),o){let d=o-Date.now()-6e4;d>0&&(n=setTimeout(()=>{a()},d))}};return await a(),{get url(){return s},get token(){return r}}};import V from"process";import{execa as It,execaCommand as Fr}from"execa";import{Transform as yt}from"stream";var Tt=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 Rt(){return Object.entries(process.env).filter(([e,t])=>!(!t||Tt.has(e)||xt.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function q(e){if(typeof e!="string")return e;let t=Rt();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(wt(o),"g");r=r.replace(n,"******")}),r}function wt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var K=class extends yt{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),s=q(n);o(null,s)}};function je(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(o,n,s){let l=typeof o=="string"?q(o):o;return typeof n=="function"?t(l,n):t(l,n,s)},process.stderr.write=function(o,n,s){let l=typeof o=="string"?q(o):o;return typeof n=="function"?r(l,n):r(l,n,s)}}var Gr=T("shell"),Nt={preferLocal:!0},Ye=(e,t,r)=>{let[o,n]=Ct(t,r),s={...Nt,...n},l=It(e,o,s);return At(l,s),l};var Ct=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},At=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(V.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new K).pipe(V.stdout),e.stdout?.pipe(new K).pipe(V.stdout),e.stderr?.pipe(new K).pipe(V.stderr);return}e.stdout?.pipe(V.stdout),e.stderr?.pipe(V.stderr)};var Be="netlify-agent-runner-context.md",we="task-history",Ie="netlify-context",b=".netlify",W="results.md",Ne="assets",X="other",J="personal";var z="enterprise",Z="free";var St=T("utils"),Pt=e=>new Promise(t=>{setTimeout(t,e)}),He=(e,t=3e3)=>{let r=!1,o=null,n=[],s=null,l=(...a)=>{if(r)return o=a,new Promise(c=>{n.push(c)});r=!0;let i,d=new Promise(c=>{i=c});return s=(async()=>{await Promise.resolve();let c=await e(...a);for(i(c);;){if(await Pt(t),!o)return r=!1,s=null,c;let m=o,h=n;o=null,n=[],c=await e(...m),h.forEach(E=>{E(c)})}})(),d};return l.flush=async()=>{if((r||o)&&s)return await s,l.flush()},l},de=(e,t,r=!1)=>{let o=null,n=null,s=null,l=function(...a){n=a,s=this;let i=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(s,n),n=null,s=null)},t),i&&(e.apply(s,n),n=null,s=null)};return l.cancel=()=>{clearTimeout(o),o=null,n=null,s=null},l.flush=()=>{if(o){clearTimeout(o);let a=n,i=s;o=null,n=null,s=null,e.apply(i,a)}},l},qe=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):St.error("Could not parse JSON",o))}},Ke=(e,t)=>{let n=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let a=`--${t}${n}`;if(a.length>55)return"";let i=60-a.length;if(i<=0)return"";if(i>=s.length+6){let d=Math.min(i-s.length,e.length);return`${s}${e.slice(0,d)}`}return e.slice(0,i)};import{Buffer as Ve}from"buffer";import vt from"path";var We=async({config:e,netlify:t})=>{let r=await kt(t),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};let s=await bt(n);await t.utils.run("git",["add",".",...s]);let l={stdio:["ignore","pipe","pipe"]},i=(await t.utils.run("git",["diff","--staged"],l)).stdout;if(o=!!i,!o)return{hasChanges:!1,ignored:s};let c=(await t.utils.run("git",["diff","--staged","--binary"],l)).stdout,m,h;if(e.sha){await t.utils.run("git",["commit","-m","Agent runner"]),m=(await t.utils.run("git",["diff",e.sha,"HEAD"],l)).stdout;let f=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"],l)).stdout;m!==f&&(h=Ve.from(f).toString("base64"))}let E={hasChanges:!0,diff:i,resultDiff:m,ignored:s};return i!==c&&(E.diffBinary=Ve.from(c).toString("base64")),h&&(E.resultDiffBinary=h),E},Ot=["?? mise.toml","?? deno.lock",/\?\? .+?\.log/],kt=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
8
- `).filter(n=>!Ot.some(s=>s instanceof RegExp?s.test(n):n===s))).length!==0,status:t.stdout}};var Xe=async e=>{let{stdout:t}=await e.utils.run("git",["rev-parse","HEAD"]);return t.trim()},Je=async e=>{let{stdout:t}=await e.utils.run("git",["rev-list","--max-parents=0","HEAD"]);return t.trim()},bt=async e=>{let t=[".netlify","mise.toml","deno.lock","node_modules"],r=[];return e.split(`
9
- `).forEach(o=>{t.forEach(s=>{[`?? ${s}`,`?? ${s}${vt.sep}`].some(a=>o.startsWith(a))&&r.push(`:!${s}`)});let n=o.match(/\?\? (.+?)\.log$/)?.[1];n&&r.push(`:!${n}.log`)}),r};import Dt from"fs/promises";import Lt from"os";import pe from"path";import U from"process";import Ft from"readline";import Ce from"path";import $t from"fs/promises";var Ae=T("agent-output-utils");async function Q({initialResult:e,agentName:t,hasError:r}){let o="",n=Ce.join(process.cwd(),b,W);try{let s=await $t.readFile(n,"utf-8");s&&(o=s,Ae.log(`Pulled result from ${Ce.relative(process.cwd(),n)}`))}catch{Ae.log(`No results file found at ${Ce.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&&Ae.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 D=T("runner_claude"),ze="Claude Code",Ut=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(D.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?(D.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}):(D.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function Se({config:e,netlify:t,persistSteps:r,aiGateway:o}){let n=e,{accountType:s,prompt:l,modelVersionOverrides:a}=n,{model:i}=n;if(o){let{token:w,url:p}=o;if(!w||!p)throw new Error("No token or url provided from AI Gateway");let u=Mt[s];if(!u)throw new Error(`Claude is not supported for the account type ${s}`);if(i&&!u?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(a?.claude){let g=a?.claude?.[s];g&&(i=g)}U.env.ANTHROPIC_API_KEY=w,U.env.ANTHROPIC_BASE_URL=p}else if(!U.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let d=[],c=[],m={},h=0,E=0,y,x,f=pe.join(U.cwd(),"node_modules"),A=[pe.join(U.env.NODE_PATH||f,".bin/claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...i?["--model",i]:[],"-p",l],N=`${U.env.NVM_BIN}/node`;D.log(`Running ${N} ${A.join(" ")}`);let S=t.utils.run(N,A,{all:!0,env:U.env});S.stdin?.end();let I=de(()=>{r?.({steps:d,duration:E})},250),R=(w,p)=>{let u={...w,id:h};h+=1,c.push(u),d.push(u),p||I.flush(),I(),p&&I.flush()},_=Ft.createInterface({input:S.all});return _.on("error",w=>{D.error("Readline interface error",{error:w.message,stack:w.stack})}),_.on("line",w=>{let p=null;try{p=JSON.parse(w)}catch{D.log("Could not parse line",w)}Array.isArray(p?.message?.content)?p.message.content.forEach(u=>{switch(u.type){case"text":{u.text&&R({message:u.text});break}case"image":{typeof u.source=="object"&&u.source&&u.source.type==="base64"&&u.source.media_type?R({message:`![](data:${u.source.media_type};base64,${u.source.data})`}):D.log(`Unsupported image type ${u.source?.type}`,u.source);break}case"tool_use":{if(u.name==="Task"){let g=u.input?.description&&`\`${u.input.description}\``;R({title:[u.name,g].filter(Boolean).join(" ")})}else u.id&&(m[u.id]=u);I.flush();break}case"tool_result":{let g=u.tool_use_id?m[u.tool_use_id]:void 0,P;if(g){let L=g.input?.file_path&&pe.relative(U.cwd(),g.input.file_path),C=L&&`\`${L}\``;P=[g.name,C].filter(Boolean).join(" ")}let F=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(g?.name||""),k;if(typeof u.content=="string")k=u.content;else if(Array.isArray(u.content)){let L=[];u.content.forEach(C=>{C?.type==="text"&&typeof C.text=="string"?L.push(C.text):C?.type==="image"&&typeof C.source=="object"&&C.source?C.source.type==="base64"&&C.source.media_type?L.push(`![](data:${C.source.media_type};base64,${C.source.data})`):D.log(`Unsupported image type ${C.source.type}`,C.source):D.log(`Unsupported block type ${C?.type}`)}),k=L.join(`
7
+ `);return s.length>e.length*.8?e:s}import me from"process";import{getTracer as or}from"@netlify/otel";import le from"process";var xe=le.env.NETLIFY_API_URL,we=le.env.NETLIFY_API_TOKEN,oe=x("api"),ue=async(e,t={})=>{if(!xe||!we)throw new Error("No API URL or token");let r=new URL(e,xe),o={...t,headers:{...t.headers,Authorization:`Bearer ${we}`}};le.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let n=await fetch(r,o),s=n.ok&&n.status<=299;if(le.env.AGENT_RUNNERS_DEBUG==="true")oe.log(`Response headers for ${r}:`),n.headers.forEach((u,i)=>{oe.log(` ${i}: ${u}`)});else{let u=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");oe.log(`Request ID for ${r}: ${u||"N/A"}`)}if(s||oe.error(`Got status ${n.status} for request ${r}`),t.raw){if(!s)throw n;return n}let l=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!s)throw l;return l},Me=e=>{oe.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(xe=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(we=e.constants.NETLIFY_API_TOKEN)},ce=(e,t)=>ue(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),Y=(e,t,r)=>ue(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var Ge=(e,t)=>ue(`/api/v1/agent_runners/${e}/sessions/${t}`),je=(e,t,r)=>ue(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}});var Ye=x("ai_gateway"),Be=async({netlify:e,config:t})=>{let r,o,n,s,l=e.constants?.SITE_ID;if(!l)throw new Error("No site id");let u=async()=>{clearTimeout(n),Ye.log("Requesting AI gateway information");let i=await je(l,t.id,t.sessionId);if({token:r,url:s}=i,o=i.expires_at?i.expires_at*1e3:void 0,Ye.log("Got AI gateway information",{token:!!r,expiresAt:o,url:s}),o){let p=o-Date.now()-6e4;p>0&&(n=setTimeout(()=>{u()},p))}};return await u(),{get url(){return s},get token(){return r}}};import K from"process";import{execa as St,execaCommand as Br}from"execa";import{Transform as Rt}from"stream";var It=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"]),Nt=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function Ct(){return Object.entries(process.env).filter(([e,t])=>!(!t||It.has(e)||Nt.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function q(e){if(typeof e!="string")return e;let t=Ct();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(At(o),"g");r=r.replace(n,"******")}),r}function At(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var W=class extends Rt{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),s=q(n);o(null,s)}};function He(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(o,n,s){let l=typeof o=="string"?q(o):o;return typeof n=="function"?t(l,n):t(l,n,s)},process.stderr.write=function(o,n,s){let l=typeof o=="string"?q(o):o;return typeof n=="function"?r(l,n):r(l,n,s)}}var Wr=x("shell"),Pt={preferLocal:!0},qe=(e,t,r)=>{let[o,n]=vt(t,r),s={...Pt,...n},l=St(e,o,s);return Ot(l,s),l};var vt=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Ot=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(K.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new W).pipe(K.stdout),e.stdout?.pipe(new W).pipe(K.stdout),e.stderr?.pipe(new W).pipe(K.stderr);return}e.stdout?.pipe(K.stdout),e.stderr?.pipe(K.stderr)};var We="netlify-agent-runner-context.md",Re="task-history",Ie="netlify-context",D=".netlify",V="results.md",Ne="assets",X="other",J="personal";var z="enterprise",Z="free";var kt=x("utils"),bt=e=>new Promise(t=>{setTimeout(t,e)}),Ke=(e,t=3e3)=>{let r=!1,o=null,n=[],s=null,l=(...u)=>{if(r)return o=u,new Promise(c=>{n.push(c)});r=!0;let i,p=new Promise(c=>{i=c});return s=(async()=>{await Promise.resolve();let c=await e(...u);for(i(c);;){if(await bt(t),!o)return r=!1,s=null,c;let f=o,m=n;o=null,n=[],c=await e(...f),m.forEach(w=>{w(c)})}})(),p};return l.flush=async()=>{if((r||o)&&s)return await s,l.flush()},l},pe=(e,t,r=!1)=>{let o=null,n=null,s=null,l=function(...u){n=u,s=this;let i=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(s,n),n=null,s=null)},t),i&&(e.apply(s,n),n=null,s=null)};return l.cancel=()=>{clearTimeout(o),o=null,n=null,s=null},l.flush=()=>{if(o){clearTimeout(o);let u=n,i=s;o=null,n=null,s=null,e.apply(i,u)}},l},Ve=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):kt.error("Could not parse JSON",o))}},Xe=(e,t)=>{let n=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let u=`--${t}${n}`;if(u.length>55)return"";let i=60-u.length;if(i<=0)return"";if(i>=s.length+6){let p=Math.min(i-s.length,e.length);return`${s}${e.slice(0,p)}`}return e.slice(0,i)};import{Buffer as Je}from"buffer";import Dt from"path";var ze=async({config:e,netlify:t})=>{let r=await Lt(t),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};let s=await Ft(n);await t.utils.run("git",["add",".",...s]);let l={stdio:["ignore","pipe","pipe"]},i=(await t.utils.run("git",["diff","--staged"],l)).stdout;if(o=!!i,!o)return{hasChanges:!1,ignored:s};let c=(await t.utils.run("git",["diff","--staged","--binary"],l)).stdout,f,m;if(e.sha){await t.utils.run("git",["commit","-m","Agent runner"]),f=(await t.utils.run("git",["diff",e.sha,"HEAD"],l)).stdout;let y=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"],l)).stdout;f!==y&&(m=Je.from(y).toString("base64"))}let w={hasChanges:!0,diff:i,resultDiff:f,ignored:s};return i!==c&&(w.diffBinary=Je.from(c).toString("base64")),m&&(w.resultDiffBinary=m),w},$t=["?? mise.toml","?? deno.lock",/\?\? .+?\.log/],Lt=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
8
+ `).filter(n=>!$t.some(s=>s instanceof RegExp?s.test(n):n===s))).length!==0,status:t.stdout}};var Ze=async e=>{let{stdout:t}=await e.utils.run("git",["rev-parse","HEAD"]);return t.trim()},Qe=async e=>{let{stdout:t}=await e.utils.run("git",["rev-list","--max-parents=0","HEAD"]);return t.trim()},Ft=async e=>{let t=[".netlify","mise.toml","deno.lock","node_modules"],r=[];return e.split(`
9
+ `).forEach(o=>{t.forEach(s=>{[`?? ${s}`,`?? ${s}${Dt.sep}`].some(u=>o.startsWith(u))&&r.push(`:!${s}`)});let n=o.match(/\?\? (.+?)\.log$/)?.[1];n&&r.push(`:!${n}.log`)}),r};import Mt from"fs/promises";import Gt from"os";import de from"path";import M from"process";import jt from"readline";import Ce from"path";import Ut from"fs/promises";var Ae=x("agent-output-utils");async function Q({initialResult:e,agentName:t,hasError:r}){let o="",n=Ce.join(process.cwd(),D,V);try{let s=await Ut.readFile(n,"utf-8");s&&(o=s,Ae.log(`Pulled result from ${Ce.relative(process.cwd(),n)}`))}catch{Ae.log(`No results file found at ${Ce.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&&Ae.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 L=x("runner_claude"),et="Claude Code",Yt=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(L.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(L.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(L.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function Se({config:e,netlify:t,persistSteps:r,aiGateway:o}){let n=e,{accountType:s,prompt:l,modelVersionOverrides:u}=n,{model:i}=n;if(o){let{token:T,url:d}=o;if(!T||!d)throw new Error("No token or url provided from AI Gateway");let a=Bt[s];if(!a)throw new Error(`Claude is not supported for the account type ${s}`);if(i&&!a?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(u?.claude){let h=u?.claude?.[s];h&&(i=h)}M.env.ANTHROPIC_API_KEY=T,M.env.ANTHROPIC_BASE_URL=d}else if(!M.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let p=[],c=[],f={},m=0,w=0,E,g,y=de.join(M.cwd(),"node_modules"),O=[de.join(M.env.NODE_PATH||y,".bin/claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...i?["--model",i]:[],"-p",l],A=`${M.env.NVM_BIN}/node`;L.log(`Running ${A} ${O.join(" ")}`);let S=t.utils.run(A,O,{all:!0,env:M.env});S.stdin?.end();let I=pe(()=>{r?.({steps:p,duration:w})},250),R=(T,d)=>{let a={...T,id:m};m+=1,c.push(a),p.push(a),d||I.flush(),I(),d&&I.flush()},_=jt.createInterface({input:S.all});return _.on("error",T=>{L.error("Readline interface error",{error:T.message,stack:T.stack})}),_.on("line",T=>{let d=null;try{d=JSON.parse(T)}catch{L.log("Could not parse line",T)}Array.isArray(d?.message?.content)?d.message.content.forEach(a=>{switch(a.type){case"text":{a.text&&R({message:a.text});break}case"image":{typeof a.source=="object"&&a.source&&a.source.type==="base64"&&a.source.media_type?R({message:`![](data:${a.source.media_type};base64,${a.source.data})`}):L.log(`Unsupported image type ${a.source?.type}`,a.source);break}case"tool_use":{if(a.name==="Task"){let h=a.input?.description&&`\`${a.input.description}\``;R({title:[a.name,h].filter(Boolean).join(" ")})}else a.id&&(f[a.id]=a);I.flush();break}case"tool_result":{let h=a.tool_use_id?f[a.tool_use_id]:void 0,P;if(h){let F=h.input?.file_path&&de.relative(M.cwd(),h.input.file_path),C=F&&`\`${F}\``;P=[h.name,C].filter(Boolean).join(" ")}let U=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(h?.name||""),b;if(typeof a.content=="string")b=a.content;else if(Array.isArray(a.content)){let F=[];a.content.forEach(C=>{C?.type==="text"&&typeof C.text=="string"?F.push(C.text):C?.type==="image"&&typeof C.source=="object"&&C.source?C.source.type==="base64"&&C.source.media_type?F.push(`![](data:${C.source.media_type};base64,${C.source.data})`):L.log(`Unsupported image type ${C.source.type}`,C.source):L.log(`Unsupported block type ${C?.type}`)}),b=F.join(`
10
10
 
11
- `)}F&&k&&(k=`\`\`\`
12
- ${k.trim()}
13
- \`\`\``),R({title:P,message:k},!0);break}case"thinking":{u.thinking&&R({title:"Thinking",message:u.thinking},!0);break}default:D.log(`Message content type is not supported ${u.type}`,u)}}):p?.type==="result"&&(E=p.duration_ms||0,p.is_error?x=p.result:y=p.result,[c,d].forEach(u=>{u[u.length-1]?.message===y&&u.pop()}))}),await S.catch(w=>{({error:x,result:y}=Ut({catchError:w,runCmd:S,error:x,result:y,runnerName:"Claude"}))}),_.close(),I.flush(),{steps:c,duration:E,result:await Q({initialResult:y,agentName:ze,hasError:!!x}),error:ee({error:x,agentName:ze}),isRetryableError:te(x)}}var Ze=async()=>{let e=pe.join(Lt.homedir(),".claude");await Dt.rm(e,{recursive:!0,force:!0})},Mt={[z]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:64e3},"claude-3-haiku-20240307":{maxTokens:4096},"claude-opus-4-20250514":{maxTokens:32e3},"claude-sonnet-4-20250514":{maxTokens:64e3}}},pro:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[J]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[Z]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}},[X]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}}};import Gt from"fs/promises";import jt from"os";import Pe from"path";import B from"process";import Yt from"readline";var H=T("runner_codex"),Qe="Codex CLI",Bt=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(H.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?(H.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}):(H.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function ve({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:l,modelVersionOverrides:a}=e,{model:i}=e;if(n){let{token:R,url:_}=n;if(!R||!_)throw new Error("No token or url provided from AI Gateway");let w=Ht[s];if(!w)throw new Error(`Codex is not supported for the account type ${s}`);if(i&&!w?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(a?.codex){let p=a?.codex?.[s];p&&(i=p)}B.env.OPENAI_API_KEY=R,B.env.OPENAI_BASE_URL=_}else if(!B.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let d=[],c=[],m={},h=0,E=0,y,x,f=Pe.join(B.cwd(),"node_modules"),A=[Pe.join(B.env.NODE_PATH||f,".bin/codex"),"--approval-mode","full-auto",n?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...i?["--model",i]:[],"-q",l].filter(Boolean),N=`${B.env.NVM_BIN}/node`;H.log(`Running ${N} ${A.join(" ")}`);let S=t.utils.run(N,A,{all:!0,env:{...B.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),I=Yt.createInterface({input:S.all});return I.on("error",R=>{H.error("Readline interface error",{error:R.message,stack:R.stack})}),I.on("line",R=>{let _=null;try{_=JSON.parse(R)}catch{H.log("Could not parse line",R);return}let w=[],p=!1;if(_?.duration_ms&&(E=_.duration_ms,p=!0),_?.type==="local_shell_call")m[_.call_id]=_;else if(_?.type==="local_shell_call_output"){let u=Kt(m[_.call_id],_);u&&(u.id=h,h+=1,c.push(u),d.push(u),w.push(u),p=!0)}else _?.type==="message"&&_.role==="assistant"?y=_.content.map(u=>u.text).join(`
14
- `):_?.type==="message"&&_.role==="system"&&(x=_.content.map(u=>u.text).join(`
15
- `));p&&(r?.({steps:d,duration:E}),o?.({steps:w,duration:E}))}),await S.catch(R=>{let _=Bt({catchError:R,runCmd:S,error:x,result:y,runnerName:"Codex"});x=_.error,y=_.result}),I.close(),{steps:c,duration:E,result:await Q({initialResult:y,agentName:Qe,hasError:!!x}),error:ee({error:x,agentName:Qe}),isRetryableError:te(x)}}var et=async()=>{let e=Pe.join(jt.homedir(),".codex");await Gt.rm(e,{recursive:!0,force:!0})},Ht={[z]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},o1:{maxTokens:1e5},"o1-mini":{maxTokens:65536},"o3-mini":{maxTokens:1e5},"gpt-image-1":{},"dall-e-2":{},"dall-e-3":{}}},[J]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768}}},pro:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768}}},[Z]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},"o3-mini":{maxTokens:16e3}}},[X]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},"o3-mini":{maxTokens:16e3}}}},qt=new Set(["bash","-lc"]),Kt=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!qt.has(s)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
11
+ `)}U&&b&&(b=`\`\`\`
12
+ ${b.trim()}
13
+ \`\`\``),R({title:P,message:b},!0);break}case"thinking":{a.thinking&&R({title:"Thinking",message:a.thinking},!0);break}default:L.log(`Message content type is not supported ${a.type}`,a)}}):d?.type==="result"&&(w=d.duration_ms||0,d.is_error?g=d.result:E=d.result,[c,p].forEach(a=>{a[a.length-1]?.message===E&&a.pop()}))}),await S.catch(T=>{({error:g,result:E}=Yt({catchError:T,runCmd:S,error:g,result:E,runnerName:"Claude"}))}),_.close(),I.flush(),{steps:c,duration:w,result:await Q({initialResult:E,agentName:et,hasError:!!g}),error:ee({error:g,agentName:et}),isRetryableError:te(g)}}var tt=async()=>{let e=de.join(Gt.homedir(),".claude");await Mt.rm(e,{recursive:!0,force:!0})},Bt={[z]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:64e3},"claude-3-haiku-20240307":{maxTokens:4096},"claude-opus-4-20250514":{maxTokens:32e3},"claude-sonnet-4-20250514":{maxTokens:64e3}}},pro:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[J]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[Z]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}},[X]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}}};import Ht from"fs/promises";import qt from"os";import Pe from"path";import B from"process";import Wt from"readline";var H=x("runner_codex"),rt="Codex CLI",Kt=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(H.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?(H.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}):(H.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function ve({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:l,modelVersionOverrides:u}=e,{model:i}=e;if(n){let{token:R,url:_}=n;if(!R||!_)throw new Error("No token or url provided from AI Gateway");let T=Vt[s];if(!T)throw new Error(`Codex is not supported for the account type ${s}`);if(i&&!T?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(u?.codex){let d=u?.codex?.[s];d&&(i=d)}B.env.OPENAI_API_KEY=R,B.env.OPENAI_BASE_URL=_}else if(!B.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let p=[],c=[],f={},m=0,w=0,E,g,y=Pe.join(B.cwd(),"node_modules"),O=[Pe.join(B.env.NODE_PATH||y,".bin/codex"),"--approval-mode","full-auto",n?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...i?["--model",i]:[],"-q",l].filter(Boolean),A=`${B.env.NVM_BIN}/node`;H.log(`Running ${A} ${O.join(" ")}`);let S=t.utils.run(A,O,{all:!0,env:{...B.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),I=Wt.createInterface({input:S.all});return I.on("error",R=>{H.error("Readline interface error",{error:R.message,stack:R.stack})}),I.on("line",R=>{let _=null;try{_=JSON.parse(R)}catch{H.log("Could not parse line",R);return}let T=[],d=!1;if(_?.duration_ms&&(w=_.duration_ms,d=!0),_?.type==="local_shell_call")f[_.call_id]=_;else if(_?.type==="local_shell_call_output"){let a=Jt(f[_.call_id],_);a&&(a.id=m,m+=1,c.push(a),p.push(a),T.push(a),d=!0)}else _?.type==="message"&&_.role==="assistant"?E=_.content.map(a=>a.text).join(`
14
+ `):_?.type==="message"&&_.role==="system"&&(g=_.content.map(a=>a.text).join(`
15
+ `));d&&(r?.({steps:p,duration:w}),o?.({steps:T,duration:w}))}),await S.catch(R=>{let _=Kt({catchError:R,runCmd:S,error:g,result:E,runnerName:"Codex"});g=_.error,E=_.result}),I.close(),{steps:c,duration:w,result:await Q({initialResult:E,agentName:rt,hasError:!!g}),error:ee({error:g,agentName:rt}),isRetryableError:te(g)}}var nt=async()=>{let e=Pe.join(qt.homedir(),".codex");await Ht.rm(e,{recursive:!0,force:!0})},Vt={[z]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},o1:{maxTokens:1e5},"o1-mini":{maxTokens:65536},"o3-mini":{maxTokens:1e5},"gpt-image-1":{},"dall-e-2":{},"dall-e-3":{}}},[J]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768}}},pro:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768}}},[Z]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},"o3-mini":{maxTokens:16e3}}},[X]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},"o3-mini":{maxTokens:16e3}}}},Xt=new Set(["bash","-lc"]),Jt=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!Xt.has(s)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
16
16
  ${n.trim()}
17
- \`\`\``)}catch(s){H.error("Could not decode outputMsg",s,t.output)}return{title:o,message:n}};import Vt from"fs/promises";import Wt from"os";import fe from"path";import M from"process";import Xt from"readline";var re=T("runner_gemini"),tt="Gemini CLI",Jt=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(re.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(re.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(re.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),zt={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 Oe({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:l,modelVersionOverrides:a}=e,{model:i}=e;if(n){let{token:p,url:u}=n;if(!p||!u)throw new Error("No token or url provided from AI Gateway");let g=Zt[s];if(!g)throw new Error(`Gemini is not supported for the account type ${s}`);if(i&&!g?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(a?.gemini){let P=a?.gemini?.[s];P&&(i=P)}M.env.GEMINI_API_KEY=p,M.env.GOOGLE_GEMINI_BASE_URL=u}else if(!M.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let d=[],c=[],m=[],h={},E=0,y=0,x,f,A=fe.join(M.cwd(),"node_modules"),N=[fe.join(M.env.NODE_PATH||A,".bin/gemini"),...i?["--model",i]:[],"--yolo","-p",l],S=`${M.env.NVM_BIN}/node`;re.log(`Running ${S} ${N.join(" ")}`);let I=t.utils.run(S,N,{all:!0,env:M.env});I.stdin?.end();let R=de(()=>{r?.({steps:d,duration:y}),o?.({steps:c,duration:y}),c=[]},250),_=(p,u)=>{p.id=E,E+=1,m.push(p),d.push(p),c.push(p),u||R.flush(),R(),u&&R.flush()},w=Xt.createInterface({input:I.all});return w.on("error",p=>{re.error("Readline interface error",{error:p.message,stack:p.stack})}),w.on("line",p=>{let u=null;try{if(p.startsWith("[API Error")){let g=p.match(/\[api error: (.+?)]$/i)?.[1];u={type:"error",value:qe(g,!1)?.error?.message||g||"Gemini encountered error"}}else u=JSON.parse(p)}catch{return}if(u)switch(u.type){case"thought":{let g=u.value;_({title:g?.subject??"Thinking...",message:g?.description},!0);break}case"content":{u.value&&_({message:u.value});break}case"tool_call_request":{let g=u.value,P=zt[g.name]??g.name,F=g.args?.path||g.args?.absolute_path,k=F&&fe.relative(M.cwd(),F),L=g.args?.command,ft={title:[P,k&&`\`${k}\``,L&&`\`${L}\``].filter(Boolean).join(" ")};h[g.callId]=ft,R.flush();break}case"tool_result":{let g=u.value,P=h[g.callId];if(P){let F=[g.resultDisplay,g.responseParts?.functionResponse?.response?.output].find(k=>typeof k=="string"&&k);F&&(P.message=`\`\`\`
18
- ${F.trim()}
19
- \`\`\``),_(P,!0)}break}case"result":{y=u.duration_ms,x=u.value,[m,d,c].forEach(g=>{g[g.length-1]?.message===x&&g.pop()});break}case"error":{f=u.value;break}case"finished":break;default:{re.warn("Unhandled message type:",u.type);break}}}),await I.catch(p=>{({error:f,result:x}=Jt({catchError:p,runCmd:I,error:f,result:x,runnerName:"Gemini"}))}),w.close(),R.flush(),{steps:m,duration:y,result:await Q({initialResult:x,agentName:tt,hasError:!!f}),error:ee({error:f,agentName:tt}),isRetryableError:te(f)}}var rt=async()=>{let e=fe.join(Wt.homedir(),".gemini");await Vt.rm(e,{recursive:!0,force:!0})},Zt={[z]:{models:{"gemini-1.5-flash":{maxTokens:8192},"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-1.5-pro":{maxTokens:8192},"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:65536},"gemini-2.5-flash-lite":{maxTokens:65536},"gemini-2.5-pro":{maxTokens:65536},"imagen-4.0-generate-001":{},"veo-3.0-generate-preview":{}}},pro:{models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[J]:{models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[Z]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}},[X]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}}};var Qt={codex:{runner:ve,clean:et},claude:{runner:Se,clean:Ze},gemini:{runner:Oe,clean:rt}},nt=Qt;var ot=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>{let n=er();return j(n,"init-stage",async s=>{let l=performance.now();s?.setAttributes({"init.runner":e.runner,"init.id":e.id,"init.sessionId":e.sessionId,"init.hasRepo":e.hasRepo,"init.useGateway":e.useGateway,"init.validateAgent":e.validateAgent,"init.runnerVersion":o||"unknown"});let a=nt[e.runner];if(!a)throw s?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let i=tr({apiToken:r});Le(i);let d=e.useGateway?await Ge({netlify:i,config:e}):void 0;s?.setAttributes({"init.aiGateway.created":!!d}),e.validateAgent&&e.errorLogsPath&&s?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let c=He(({steps:E=[],duration:y})=>{let x=E.map(f=>({...f,title:f.title?q(f.title):void 0,message:f.message?q(f.message):void 0}));return E.length=0,Y(e.id,e.sessionId,{steps:x,duration:y})},t),m;e.hasRepo?e.sha?(m=e.sha,s?.setAttributes({"init.sha.source":"provided"})):(m=await Xe(i),await ce(e.id,{sha:m}),s?.setAttributes({"init.sha.source":"current_commit"})):(m=await Je(i),s?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let h=performance.now()-l;return s?.setAttributes({"init.sha":m||"unknown","init.duration.ms":h,"init.status":"success"}),{aiGateway:d,context:i,persistSteps:c,runner:a,sha:m}})},tr=({apiToken:e})=>({constants:{NETLIFY_API_HOST:me.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||me.env.NETLIFY_API_TOKEN,SITE_ID:me.env.SITE_ID,FUNCTIONS_DIST:me.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:Ye}});import{getTracer as dr}from"@netlify/otel";import rr from"crypto";import G from"fs/promises";import O from"path";import $ from"process";var v=T("context"),nr=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:$.env.NETLIFY_TEAM_ID,userId:$.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:$.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},or=10,sr=async e=>{let{name:t,ext:r}=O.parse(e),o=e,n=O.join($.cwd(),b,o),s=0;for(;await ir(n);){if(s>=or)throw new Error("Failed to generate context file");o=`${t}-${rr.randomUUID().slice(0,5)}${r}`,n=O.join($.cwd(),b,o),s+=1}return o},ir=async e=>{try{return await G.access(e),!0}catch{return!1}},ar=async()=>{try{v.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 v.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"?(v.warn("Catchall consumer missing or invalid contextScopes"),null):r:(v.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?v.warn("Netlify features context request timed out"):v.warn("Failed to fetch Netlify features context:",e.message),null}},lr=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 G.writeFile(t,o,"utf-8"),!0}catch(r){return r.name==="AbortError"?v.warn(`Download timeout for ${e}`):v.warn(`Failed to download context file ${e}:`,r.message),!1}},ge=null,ur=async()=>{if(ge)return ge;let e=await ar();if(!e)return[];let t=O.join($.cwd(),b,Ie);await G.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([n,s])=>{if(!s||typeof s!="object"||!s.endpoint||!s.scope)return v.warn(`Invalid scope data for ${n}, skipping...`),null;let l=`${n}.md`,a=O.join(t,l),i=O.join(b,Ie,l);return v.log(`Downloading ${s.scope} context...`),await lr(s.endpoint,a)?(v.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:n}):null});return ge=(await Promise.all(r)).filter(n=>n!==null),ge},st=async({cliPath:e,netlify:t,config:r,buildErrorContext:o})=>{let n=nr(t),s=await sr(Be),l=O.join($.cwd(),b);await G.mkdir(l,{recursive:!0});let a=O.join(b,s),i=O.join($.cwd(),a),d=O.join($.cwd(),b,W);try{await G.unlink(d),v.log(`Deleted old results file: ${d}`)}catch{}let c=o?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
17
+ \`\`\``)}catch(s){H.error("Could not decode outputMsg",s,t.output)}return{title:o,message:n}};import zt from"fs/promises";import Zt from"os";import fe from"path";import G from"process";import Qt from"readline";var re=x("runner_gemini"),ot="Gemini CLI",er=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(re.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(re.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(re.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),tr={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 Oe({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:l,modelVersionOverrides:u}=e,{model:i}=e;if(n){let{token:d,url:a}=n;if(!d||!a)throw new Error("No token or url provided from AI Gateway");let h=rr[s];if(!h)throw new Error(`Gemini is not supported for the account type ${s}`);if(i&&!h?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(u?.gemini){let P=u?.gemini?.[s];P&&(i=P)}G.env.GEMINI_API_KEY=d,G.env.GOOGLE_GEMINI_BASE_URL=a}else if(!G.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let p=[],c=[],f=[],m={},w=0,E=0,g,y,O=fe.join(G.cwd(),"node_modules"),A=[fe.join(G.env.NODE_PATH||O,".bin/gemini"),...i?["--model",i]:[],"--yolo","-p",l],S=`${G.env.NVM_BIN}/node`;re.log(`Running ${S} ${A.join(" ")}`);let I=t.utils.run(S,A,{all:!0,env:G.env});I.stdin?.end();let R=pe(()=>{r?.({steps:p,duration:E}),o?.({steps:c,duration:E}),c=[]},250),_=(d,a)=>{d.id=w,w+=1,f.push(d),p.push(d),c.push(d),a||R.flush(),R(),a&&R.flush()},T=Qt.createInterface({input:I.all});return T.on("error",d=>{re.error("Readline interface error",{error:d.message,stack:d.stack})}),T.on("line",d=>{let a=null;try{if(d.startsWith("[API Error")){let h=d.match(/\[api error: (.+?)]$/i)?.[1];a={type:"error",value:Ve(h,!1)?.error?.message||h||"Gemini encountered error"}}else a=JSON.parse(d)}catch{return}if(a)switch(a.type){case"thought":{let h=a.value;_({title:h?.subject??"Thinking...",message:h?.description},!0);break}case"content":{a.value&&_({message:a.value});break}case"tool_call_request":{let h=a.value,P=tr[h.name]??h.name,U=h.args?.path||h.args?.absolute_path,b=U&&fe.relative(G.cwd(),U),F=h.args?.command,yt={title:[P,b&&`\`${b}\``,F&&`\`${F}\``].filter(Boolean).join(" ")};m[h.callId]=yt,R.flush();break}case"tool_result":{let h=a.value,P=m[h.callId];if(P){let U=[h.resultDisplay,h.responseParts?.functionResponse?.response?.output].find(b=>typeof b=="string"&&b);U&&(P.message=`\`\`\`
18
+ ${U.trim()}
19
+ \`\`\``),_(P,!0)}break}case"result":{E=a.duration_ms,g=a.value,[f,p,c].forEach(h=>{h[h.length-1]?.message===g&&h.pop()});break}case"error":{y=a.value;break}case"finished":break;default:{re.warn("Unhandled message type:",a.type);break}}}),await I.catch(d=>{({error:y,result:g}=er({catchError:d,runCmd:I,error:y,result:g,runnerName:"Gemini"}))}),T.close(),R.flush(),{steps:f,duration:E,result:await Q({initialResult:g,agentName:ot,hasError:!!y}),error:ee({error:y,agentName:ot}),isRetryableError:te(y)}}var st=async()=>{let e=fe.join(Zt.homedir(),".gemini");await zt.rm(e,{recursive:!0,force:!0})},rr={[z]:{models:{"gemini-1.5-flash":{maxTokens:8192},"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-1.5-pro":{maxTokens:8192},"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:65536},"gemini-2.5-flash-lite":{maxTokens:65536},"gemini-2.5-pro":{maxTokens:65536},"imagen-4.0-generate-001":{},"veo-3.0-generate-preview":{}}},pro:{models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[J]:{models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[Z]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}},[X]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}}};var nr={codex:{runner:ve,clean:nt},claude:{runner:Se,clean:tt},gemini:{runner:Oe,clean:st}},it=nr;var at=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>N(or(),"init-stage",async n=>{let s=performance.now();n?.setAttributes({"init.runner":e.runner,"init.id":e.id,"init.sessionId":e.sessionId,"init.hasRepo":e.hasRepo,"init.useGateway":e.useGateway,"init.validateAgent":e.validateAgent,"init.runnerVersion":o||"unknown"});let l=it[e.runner];if(!l)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let u=sr({apiToken:r});Me(u);let i=e.useGateway?await Be({netlify:u,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!i}),e.validateAgent&&e.errorLogsPath&&n?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let p=Ke(({steps:m=[],duration:w})=>{let E=m.map(g=>({...g,title:g.title?q(g.title):void 0,message:g.message?q(g.message):void 0}));return m.length=0,Y(e.id,e.sessionId,{steps:E,duration:w})},t),c;e.hasRepo?e.sha?(c=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(c=await Ze(u),await ce(e.id,{sha:c}),n?.setAttributes({"init.sha.source":"current_commit"})):(c=await Qe(u),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let f=performance.now()-s;return n?.setAttributes({"init.sha":c||"unknown","init.duration.ms":f,"init.status":"success"}),{aiGateway:i,context:u,persistSteps:p,runner:l,sha:c}}),sr=({apiToken:e})=>({constants:{NETLIFY_API_HOST:me.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||me.env.NETLIFY_API_TOKEN,SITE_ID:me.env.SITE_ID,FUNCTIONS_DIST:me.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:qe}});import{getTracer as ke}from"@netlify/otel";import ir from"crypto";import j from"fs/promises";import k from"path";import $ from"process";var v=x("context"),ar=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:$.env.NETLIFY_TEAM_ID,userId:$.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:$.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},lr=10,ur=async e=>{let{name:t,ext:r}=k.parse(e),o=e,n=k.join($.cwd(),D,o),s=0;for(;await cr(n);){if(s>=lr)throw new Error("Failed to generate context file");o=`${t}-${ir.randomUUID().slice(0,5)}${r}`,n=k.join($.cwd(),D,o),s+=1}return o},cr=async e=>{try{return await j.access(e),!0}catch{return!1}},pr=async()=>{try{v.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 v.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"?(v.warn("Catchall consumer missing or invalid contextScopes"),null):r:(v.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?v.warn("Netlify features context request timed out"):v.warn("Failed to fetch Netlify features context:",e.message),null}},dr=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 j.writeFile(t,o,"utf-8"),!0}catch(r){return r.name==="AbortError"?v.warn(`Download timeout for ${e}`):v.warn(`Failed to download context file ${e}:`,r.message),!1}},ge=null,fr=async()=>{if(ge)return ge;let e=await pr();if(!e)return[];let t=k.join($.cwd(),D,Ie);await j.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([n,s])=>{if(!s||typeof s!="object"||!s.endpoint||!s.scope)return v.warn(`Invalid scope data for ${n}, skipping...`),null;let l=`${n}.md`,u=k.join(t,l),i=k.join(D,Ie,l);return v.log(`Downloading ${s.scope} context...`),await dr(s.endpoint,u)?(v.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:n}):null});return ge=(await Promise.all(r)).filter(n=>n!==null),ge},lt=async({cliPath:e,netlify:t,config:r,buildErrorContext:o})=>{let n=ar(t),s=await ur(We),l=k.join($.cwd(),D);await j.mkdir(l,{recursive:!0});let u=k.join(D,s),i=k.join($.cwd(),u),p=k.join($.cwd(),D,V);try{await j.unlink(p),v.log(`Deleted old results file: ${p}`)}catch{}let c=o?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
20
20
  Your task is to analyze and fix the build errors.
21
21
  Don't apply techniques of reverting changes. Apply fixes related to errors.
22
22
  Don't try to run build by yourself. Just fix the errors.
23
23
 
24
24
  <build_error_context>
25
25
  ${o}
26
- </build_error_context>`:"",m="";r.siteContext&&r.siteContext.length!==0&&(m=`
26
+ </build_error_context>`:"",f="";r.siteContext&&r.siteContext.length!==0&&(f=`
27
27
  <project_rules>
28
- ${r.siteContext.filter(f=>f.site_context).map(f=>typeof f.site_context=="string"?f.site_context:typeof f.site_context=="object"?JSON.stringify(f.site_context):"").join(`
28
+ ${r.siteContext.filter(y=>y.site_context).map(y=>typeof y.site_context=="string"?y.site_context:typeof y.site_context=="object"?JSON.stringify(y.site_context):"").join(`
29
29
 
30
30
  `)}
31
31
  </project_rules>
32
- `);let h="";if(r.sessionHistoryContext?.length){let f=O.join($.cwd(),b,we);await G.mkdir(f,{recursive:!0});let A=await Promise.all(r.sessionHistoryContext.map(async(N,S)=>{let I=S+1,R=`attempt-${I}.md`,_=O.join(f,R),w=O.join(b,we,R),p=`# Task History - Attempt ${I}
32
+ `);let m="";if(r.sessionHistoryContext?.length){let y=k.join($.cwd(),D,Re);await j.mkdir(y,{recursive:!0});let O=await Promise.all(r.sessionHistoryContext.map(async(A,S)=>{let I=S+1,R=`attempt-${I}.md`,_=k.join(y,R),T=k.join(D,Re,R),d=`# Task History - Attempt ${I}
33
33
 
34
34
  ## Request - what the user asked for
35
- ${N.request}
35
+ ${A.request}
36
36
 
37
37
  ---
38
38
 
39
39
  ## Response - what the agent replied with after its work
40
40
 
41
- ${N.response}
42
- `;return await G.writeFile(_,p,"utf-8"),v.log(`Created history file: ${w}`),w}));h+=`
41
+ ${A.response}
42
+ `;return await j.writeFile(_,d,"utf-8"),v.log(`Created history file: ${T}`),T}));m+=`
43
43
  <session_history_context>
44
44
  History of prior work on this task.
45
45
  You MUST review ALL of the files below as context to understand the context of previous attempts. Use this information to continue the discussion appropriately.
46
46
 
47
- ${A.slice(-5).map(N=>`- ${N}`).join(`
47
+ ${O.slice(-5).map(A=>`- ${A}`).join(`
48
48
  `)}
49
49
 
50
50
  </session_history_context>
51
- `}let E=await ur(),y="";E.length>0&&(y=`
51
+ `}let w=await fr(),E="";w.length>0&&(E=`
52
52
  <netlify_features_context>
53
53
  If the user request is explicitly related to a specific Netlify feature (e.g., Netlify Forms, Netlify Functions, etc.), you MUST review the relevant documentation below in addition to reviewing the project files.
54
54
  DO NOT force the use of any Netlify feature if the user request does not explicitly require it or if the project has alternative implementations in place already.
55
55
 
56
- ${E.map(f=>`- **${f.scope}**: ${f.path}`).join(`
56
+ ${w.map(y=>`- **${y.scope}**: ${y.path}`).join(`
57
57
  `)}
58
58
 
59
59
  Refer to these files when working with specific Netlify features.
60
60
  </netlify_features_context>
61
- `);let x=`
61
+ `);let g=`
62
62
  You're an AI agent designed to assist with tasks related to a Netlify project. Please review, understand, and use the context provided to complete the user's request as needed.
63
63
 
64
64
  <request>
@@ -71,15 +71,15 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
71
71
  <requirements>
72
72
  <responses>
73
73
  - Do not speak in first person. You may speak as "the agent".
74
- - When work is complete, write a changes summary in ${l}/${W} as a standalone PR description. Explain what was accomplished and why (avoid too many implementation details), assuming the reader has no prior context. Use past tense and write in prose without calling it a "PR", "Changelog", etc. This is the core of a PR message or summary page that already has a heading.
75
- - If the user's request is informational in nature (asking for output, status, information, or analysis rather than asking you to make changes), write the requested information directly to the ${l}/${W} file.
74
+ - When work is complete, write a changes summary in ${l}/${V} as a standalone PR description. Explain what was accomplished and why (avoid too many implementation details), assuming the reader has no prior context. Use past tense and write in prose without calling it a "PR", "Changelog", etc. This is the core of a PR message or summary page that already has a heading.
75
+ - If the user's request is informational in nature (asking for output, status, information, or analysis rather than asking you to make changes), write the requested information directly to the ${l}/${V} file.
76
76
  - Do not attempt to create git commits, PRs, etc. directly. You can use git to review information if required but the system that runs this agent will handle creating PRs or commits of the changes it performs.
77
77
  </responses>
78
78
  <attachements>
79
79
  - for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${l}/${Ne} folder
80
80
  - move assets from ${l}/${Ne} folder to the project assets folder if they are referenced in a code or applied changes
81
81
  </attachements>
82
- ${m}
82
+ ${f}
83
83
  </requirements>
84
84
 
85
85
  <extra_context>
@@ -96,15 +96,15 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
96
96
  - 'netlify-cli' npm package is already available as a global package. Don't try to install it again
97
97
  - 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.
98
98
  </environment>
99
- ${y}
99
+ ${E}
100
100
  <docs>
101
101
  - Netlify Docs: https://docs.netlify.com
102
102
  - LLM Resources Index: https://docs.netlify.com/llms.txt
103
103
  </docs>
104
104
  </extra_context>
105
105
 
106
- ${h}
107
- `;return await G.writeFile(i,x,"utf-8"),v.log(`Generated agent context document at: ${i}`),x.length>5e5&&(x=`
106
+ ${m}
107
+ `;return await j.writeFile(i,g,"utf-8"),v.log(`Generated agent context document at: ${i}`),g.length>5e5&&(g=`
108
108
  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.
109
109
 
110
110
  <request>
@@ -115,15 +115,15 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
115
115
  </request>
116
116
 
117
117
  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.
118
- `),x};var cr=T("prompt"),it=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&&cr.log("Contextful Prompt:",n),{prompt:n}};var he=T("inference_stage"),at=5,Ee=async e=>j(dr(),"inference-stage",async t=>{let{cliPath:r,config:o,context:n,buildErrors:s,runner:l,persistSteps:a,aiGateway:i,attempt:d,contextPrefix:c}=e;t?.setAttributes({"inference.attempt":d}),he.log(`Running inference stage, attempt ${d} of ${at}`),je();let{prompt:m}=await it({cliPath:r,config:o,buildErrorContext:pr(s),netlify:n}),h=`
118
+ `),g};var mr=x("prompt"),ut=async({cliPath:e,config:t,netlify:r,buildErrorContext:o})=>{let n=await lt({cliPath:e,config:t,netlify:r,buildErrorContext:o});return process.env.AGENT_RUNNER_DEBUG&&mr.log("Contextful Prompt:",n),{prompt:n}};var he=x("inference_stage"),ct=5,ye=async e=>N(ke(),"inference-stage",async t=>{let{cliPath:r,config:o,context:n,buildErrors:s,runner:l,persistSteps:u,aiGateway:i,attempt:p,contextPrefix:c}=e;t?.setAttributes({"inference.attempt":p}),he.log(`Running inference stage, attempt ${p} of ${ct}`),He();let{prompt:f}=await N(ke(),"compose-prompt",async()=>await ut({cliPath:r,config:o,buildErrorContext:gr(s),netlify:n})),m=`
119
119
  ${c||""}
120
- ${m}
121
- `.trim(),E={...o,prompt:h},y=await l({aiGateway:i,config:E,netlify:n,persistSteps:a});if(await a.flush(),y.error){if(he.error("Runner failed",{stepsCount:y.steps.length,duration:y.duration,error:y.error,isRetryableError:y.isRetryableError,attempt:d||1}),y.isRetryableError&&(!d||d<at))return he.log("Retrying inference stage"),await new Promise(f=>setTimeout(f,5e3)),{runnerResult:(await Ee({...e,attempt:(d||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 he.log("Do not retry inference stage"),new Error(y.error)}return{runnerResult:y}}),pr=e=>!e||e.length===0?"":`
120
+ ${f}
121
+ `.trim(),w={...o,prompt:m},E=await N(ke(),`run-${o.runner}`,async()=>await l({aiGateway:i,config:w,netlify:n,persistSteps:u}));if(await u.flush(),E.error){if(he.error("Runner failed",{stepsCount:E.steps.length,duration:E.duration,error:E.error,isRetryableError:E.isRetryableError,attempt:p||1}),E.isRetryableError&&(!p||p<ct))return he.log("Retrying inference stage"),await new Promise(y=>setTimeout(y,5e3)),{runnerResult:(await ye({...e,attempt:(p||1)+1,contextPrefix:"<important> The agent has already started on this work but ran into networking errors trying to complete it. Please continue from where it left off (you can use git commands to see what's currently changed thus far) and do not start over. Here is the full prompt for context: </important>"})).runnerResult};throw he.log("Do not retry inference stage"),new Error(E.error)}return{runnerResult:E}}),gr=e=>!e||e.length===0?"":`
122
122
  Deploy failed failed. Here are the errors to review on the latest build:
123
123
 
124
124
  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.
125
125
 
126
126
  ${e.pop()}
127
- `;import fr from"process";var ie=T("deploy"),lt=async({netlify:e,hasRepo:t,skipBuild:r,message:o="Agent Preview",deploySubdomain:n,cliPath:s,filter:l})=>{try{let a=["deploy","--message",`"${o}"`,"--json","--draft","--verbose"];t||(ie.log("Deploy: Uploading source zip"),a.push("--upload-source-zip")),n&&a.push("--alias",n),l&&a.push("--filter",l),r?(ie.log("Deploy: Skipping build"),a.push("--no-build")):a.push("--context","deploy-preview");let i=s||"netlify";ie.log(`Running: ${i} ${a.join(" ")}`);let d=await e.utils.run(i,a,{stdio:["ignore","pipe","pipe"]}),c=JSON.parse(d.stdout.trim());ie.log(`
128
- Preview deploy created successfully:`,{deployId:c.deploy_id,deployUrl:c.deploy_url,siteId:c.site_id});let m={deployId:c.deploy_id,previewUrl:c.deploy_url,logsUrl:c.logs,siteId:c.site_id};return t||(m.sourceZipFilename=c.source_zip_filename),m}catch(a){throw ie.error("Failed to create preview deploy via CLI:",a),a}};var ae=T("deploy_stage"),ke=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let s=await We({config:t,netlify:r});if(ae.info("Resolved git",{hasChanges:s.hasChanges,ignored:s.ignored??[]}),!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:l,resultDiff:a,diffBinary:i,resultDiffBinary:d}=s,c=!0;ae.log("Preview deploy condition check:",{resultUndefined:o===void 0,resultType:typeof o,hasChanges:c,wouldCreatePreview:o!==void 0&&c});let m=null;if(o!==void 0&&c)try{let h;try{let E=await Fe(t.id,t.sessionId);E?.title&&(h=E.title)}catch(E){ae.warn("Failed to fetch session title, using fallback message:",E.message)}m=await lt({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:h,skipBuild:!1,deploySubdomain:Ke(t.id,fr.env.SITE_NAME),filter:n})}catch(h){return ae.warn("Failed to create preview deploy (continuing with agent run):",h),{diff:l,resultDiff:a,hasChanges:c,previewInfo:null,diffBinary:i,resultDiffBinary:d,deployError:h instanceof Error?h.message:String(h)}}return ae.log("Git status",{hasDiff:!!l,hasChanges:c}),{diff:l,resultDiff:a,hasChanges:c,previewInfo:m,diffBinary:i,resultDiffBinary:d}};async function ut(e,t){let{maxRetries:r,baseDelay:o,onRetry:n}=t,s;for(let l=1;l<=r;l++)try{return await e()}catch(a){if(s=a,l===r)throw s;n&&n(l,s),await new Promise(i=>setTimeout(i,o*l))}throw s}var ne=T("cleanup_stage"),ct=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:s,resultDiffBinary:l,previewInfo:a})=>{let i={result_diff:t,result:r||"Done",duration:o,result_diff_binary:s};return a&&a.deployId&&(i.deploy_id=a.deployId),a&&a.sourceZipFilename&&(i.result_zip_file_name=a.sourceZipFilename),n||l?(ne.log("Updating total agent result diff"),await ce(e.id,{result_diff:n,result_diff_binary:l})):ne.log("No total result diff, not updating"),ne.log("Updated agent runner with result"),await ut(()=>Y(e.id,e.sessionId,i),{maxRetries:3,baseDelay:1e3,onRetry:(d,c)=>{ne.error(`Error updating agent runner session (attempt ${d}):`,c),ne.log("Retrying...")}}),ne.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as gr}from"@netlify/otel";var hr=mr(import.meta.url),dt=hr("../package.json"),pt=T("pipeline_index"),_e=3,bo=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:s,traceExporterUrl:l})=>{let a;try{await $e(dt.version,e.id,l);let i=gr();await j(i,"run-pipeline",async()=>{let d,{aiGateway:c,context:m,persistSteps:h,runner:E,sha:y}=await ot({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:s,runnerVersion:dt.version});a=E.clean,e.sha=y;let{runnerResult:x}=await Ee({cliPath:r,config:e,context:m,runner:E.runner,persistSteps:h,aiGateway:c});await Y(e.id,e.sessionId,{steps:[{title:"Deploying the run preview"}]});let f=await ke({cliPath:r,config:e,context:m,result:x.result,filter:s}),A=x,N=[];if(f.hasChanges&&f.deployError){N.push(De(f.deployError));let p=1;for(;p<=_e&&!f.previewInfo;)pt.log(`Deploy attempt had errors. Retrying. ${p}/${_e}`),await j(i,"stage-deploy",async u=>{u?.setAttributes({"stage.attempt":p});let{runnerResult:g}=await Ee({cliPath:r,config:e,context:m,runner:E.runner,persistSteps:h,aiGateway:c,buildErrors:N});A={...g,steps:[...A.steps||[],...g.steps||[]],duration:(A.duration||0)+(g.duration||0)},f=await ke({cliPath:r,config:e,context:m,result:g.result,filter:s}),f.deployError&&N.push(f.deployError),p++});p>_e&&!f.previewInfo&&(d=new Error(`Deploy validation failed after ${_e} attempts`))}let{diff:S,resultDiff:I,previewInfo:R,diffBinary:_,resultDiffBinary:w}=f;if(await ct({config:e,diff:S,result:A.result,duration:A.duration,resultDiff:I,diffBinary:_,resultDiffBinary:w,previewInfo:R}),d)throw d;await E.clean?.()})}catch(i){pt.error("Got error while running pipeline",i),await a?.();let d=i instanceof Error&&i.message;throw await Y(e.id,e.sessionId,{result:d||"Encountered error when running agent",state:"error"}),i}};export{bo as runPipeline};
127
+ `;import Er from"process";import{getTracer as be}from"@netlify/otel";import{getTracer as hr}from"@netlify/otel";var ie=x("deploy"),pt=async e=>await N(hr(),"create-preview-deploy",async t=>yr(e,t)),yr=async({netlify:e,hasRepo:t,skipBuild:r,message:o="Agent Preview",deploySubdomain:n,cliPath:s,filter:l},u)=>{try{let i=["deploy","--message",`"${o}"`,"--json","--draft","--verbose"];t||(ie.log("Deploy: Uploading source zip"),i.push("--upload-source-zip")),n&&i.push("--alias",n),l&&i.push("--filter",l),r?(ie.log("Deploy: Skipping build"),i.push("--no-build")):i.push("--context","deploy-preview");let p=s||"netlify";ie.log(`Running: ${p} ${i.join(" ")}`),u?.setAttributes({cmd:p,args:i});let c=await e.utils.run(p,i,{stdio:["ignore","pipe","pipe"]}),f=JSON.parse(c.stdout.trim());u?.setAttributes({success:!0,deployId:f.deploy_id,deployUrl:f.deploy_url,siteId:f.site_id}),ie.log(`
128
+ Preview deploy created successfully:`,{deployId:f.deploy_id,deployUrl:f.deploy_url,siteId:f.site_id});let m={deployId:f.deploy_id,previewUrl:f.deploy_url,logsUrl:f.logs,siteId:f.site_id};return t||(m.sourceZipFilename=f.source_zip_filename),m}catch(i){throw ie.error("Failed to create preview deploy via CLI:",i),u?.setAttributes({success:!1,error:i.message}),i}};var ae=x("deploy_stage"),De=async e=>await N(be(),"run-deploy-stage",async()=>_r(e)),_r=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let s=await N(be(),"get-runner-diffs",async()=>await ze({config:t,netlify:r}));if(ae.info("Resolved git",{hasChanges:s.hasChanges,ignored:s.ignored??[]}),!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:l,resultDiff:u,diffBinary:i,resultDiffBinary:p}=s,c=!0;ae.log("Preview deploy condition check:",{resultUndefined:o===void 0,resultType:typeof o,hasChanges:c,wouldCreatePreview:o!==void 0&&c});let f=null;if(o!==void 0&&c)try{let m;try{let w=await N(be(),"get-runner-session",async()=>await Ge(t.id,t.sessionId));w?.title&&(m=w.title)}catch(w){ae.warn("Failed to fetch session title, using fallback message:",w.message)}f=await pt({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:m,skipBuild:!1,deploySubdomain:Xe(t.id,Er.env.SITE_NAME),filter:n})}catch(m){return ae.warn("Failed to create preview deploy (continuing with agent run):",m),{diff:l,resultDiff:u,hasChanges:c,previewInfo:null,diffBinary:i,resultDiffBinary:p,deployError:m instanceof Error?m.message:String(m)}}return ae.log("Git status",{hasDiff:!!l,hasChanges:c}),{diff:l,resultDiff:u,hasChanges:c,previewInfo:f,diffBinary:i,resultDiffBinary:p}};import{getTracer as $e}from"@netlify/otel";async function dt(e,t){let{maxRetries:r,baseDelay:o,onRetry:n}=t,s;for(let l=1;l<=r;l++)try{return await e()}catch(u){if(s=u,l===r)throw s;n&&n(l,s),await new Promise(i=>setTimeout(i,o*l))}throw s}var ne=x("cleanup_stage"),ft=async e=>await N($e(),"cleanup-stage",async()=>Tr(e)),Tr=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:s,resultDiffBinary:l,previewInfo:u})=>{let i={result_diff:t,result:r||"Done",duration:o,result_diff_binary:s};return u&&u.deployId&&(i.deploy_id=u.deployId),u&&u.sourceZipFilename&&(i.result_zip_file_name=u.sourceZipFilename),n||l?(ne.log("Updating total agent result diff"),await N($e(),"update-runner",async()=>{await ce(e.id,{result_diff:n,result_diff_binary:l})})):ne.log("No total result diff, not updating"),ne.log("Updated agent runner with result"),await dt(async()=>await N($e(),"update-runner-session",()=>Y(e.id,e.sessionId,i)),{maxRetries:3,baseDelay:1e3,onRetry:(p,c)=>{ne.error(`Error updating agent runner session (attempt ${p}):`,c),ne.log("Retrying...")}}),ne.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as mt}from"@netlify/otel";var wr=xr(import.meta.url),gt=wr("../package.json"),ht=x("pipeline_index"),Ee=3,qo=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:s,traceExporterUrl:l})=>{let u;await Fe(gt.version,e.id,l),await N(mt(),"run-pipeline",async()=>{try{let i,{aiGateway:p,context:c,persistSteps:f,runner:m,sha:w}=await at({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:s,runnerVersion:gt.version});u=m.clean,e.sha=w;let{runnerResult:E}=await ye({cliPath:r,config:e,context:c,runner:m.runner,persistSteps:f,aiGateway:p});await Y(e.id,e.sessionId,{steps:[{title:"Deploying the run preview"}]});let g=await De({cliPath:r,config:e,context:c,result:E.result,filter:s}),y=E,O=[];if(g.hasChanges&&g.deployError){O.push(Ue(g.deployError));let T=1;for(;T<=Ee&&!g.previewInfo;)ht.log(`Deploy attempt had errors. Retrying. ${T}/${Ee}`),await N(mt(),"deploy-stage",async d=>{d?.setAttributes({"stage.attempt":T});let{runnerResult:a}=await ye({cliPath:r,config:e,context:c,runner:m.runner,persistSteps:f,aiGateway:p,buildErrors:O});y={...a,steps:[...y.steps||[],...a.steps||[]],duration:(y.duration||0)+(a.duration||0)},g=await De({cliPath:r,config:e,context:c,result:a.result,filter:s}),g.deployError&&O.push(g.deployError),T++});T>Ee&&!g.previewInfo&&(i=new Error(`Deploy validation failed after ${Ee} attempts`))}let{diff:A,resultDiff:S,previewInfo:I,diffBinary:R,resultDiffBinary:_}=g;if(await ft({config:e,diff:A,result:y.result,duration:y.duration,resultDiff:S,diffBinary:R,resultDiffBinary:_,previewInfo:I}),i)throw i;await m.clean?.()}catch(i){ht.error("Got error while running pipeline",i),await u?.();let p=i instanceof Error&&i.message;throw await Y(e.id,e.sessionId,{result:p||"Encountered error when running agent",state:"error"}),i}})};export{qo as runPipeline};
129
129
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@netlify/agent-runner-cli",
3
3
  "type": "module",
4
- "version": "1.39.0",
4
+ "version": "1.39.1",
5
5
  "description": "CLI tool for running Netlify agents",
6
6
  "main": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",