@netlify/agent-runner-cli 1.44.0 → 1.46.0

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