@netlify/agent-runner-cli 1.47.1 → 1.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,75 +1,72 @@
1
- import{createRequire as Br}from"module";import{createTracerProvider as Ut}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as Ke}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as Mt}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as Gt}from"@netlify/otel";import{propagation as qe,context as We,W3CTraceContextPropagator as jt}from"@netlify/otel/opentelemetry";import{OTLPTraceExporter as Yt}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 Se=w("tracing"),Ve=async(e,t,r)=>(await Ut({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new Ke(new Ae),new Ke(new Yt({url:r.exporterUrl}))],instrumentations:[new Mt({skipHeaders:!0})]}),r.traceparent?(qe.setGlobalPropagator(new jt),qe.extract(We.active(),{traceparent:r.traceparent,isRemote:!0})):We.active());function A(e,t,r){return Se.log(`\u23F3 TRACE: ${t} starting...`),Gt(e,t,r)}var Ae=class{export(t,r){for(let o of t)this.logSpan(o);r({code:1})}async shutdown(){}forceFlush(){return Promise.resolve()}logSpan(t){let r=(t.endTime[0]-t.startTime[0])*1e3+(t.endTime[1]-t.startTime[1])/1e6,o=t.attributes,n=[];for(let[u,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(", ")}]`:"";Se.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${a}`),t.status?.code===2&&t.status.message&&Se.log(` \u274C Error: ${t.status.message}`)}};var Bt=["error","failed","exception","fatal","panic","abort","crash"];function Je(e){let t=e.split(`
2
- `),r=[],o=-1,n=0;for(;n<t.length;){let u=t[n].slice(0,500).toLowerCase();if(Bt.some(y=>u.includes(y))){let y=Math.max(0,n-10,o+1),l=Math.min(t.length-1,n+20),c=[];for(let g=y;g<=l;g++)c.push(t[g]);r.push(c.join(`
3
- `)),o=l,n=l+1}else n++}if(r.length===0)return e;let s=r.map((a,u)=>`<extracted_error_chunk order="${u+1}">
1
+ import{createRequire as Zr}from"module";import{createTracerProvider as Yt}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as Ve}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as Bt}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as Ht}from"@netlify/otel";import{propagation as Je,context as Xe,W3CTraceContextPropagator as qt}from"@netlify/otel/opentelemetry";import{OTLPTraceExporter as Kt}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 Se=E("tracing"),ze=async(e,t,r)=>(await Yt({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new Ve(new Ae),new Ve(new Kt({url:r.exporterUrl}))],instrumentations:[new Bt({skipHeaders:!0})]}),r.traceparent?(Je.setGlobalPropagator(new qt),Je.extract(Xe.active(),{traceparent:r.traceparent,isRemote:!0})):Xe.active());function b(e,t,r){return Se.log(`\u23F3 TRACE: ${t} starting...`),Ht(e,t,r)}var Ae=class{export(t,r){for(let o of t)this.logSpan(o);r({code:1})}async shutdown(){}forceFlush(){return Promise.resolve()}logSpan(t){let r=(t.endTime[0]-t.startTime[0])*1e3+(t.endTime[1]-t.startTime[1])/1e6,o=t.attributes,n=[];for(let[u,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(", ")}]`:"";Se.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${a}`),t.status?.code===2&&t.status.message&&Se.log(` \u274C Error: ${t.status.message}`)}};var Wt=["error","failed","exception","fatal","panic","abort","crash"];function Ze(e){let t=e.split(`
2
+ `),r=[],o=-1,n=0;for(;n<t.length;){let u=t[n].slice(0,500).toLowerCase();if(Wt.some(m=>u.includes(m))){let m=Math.max(0,n-10,o+1),c=Math.min(t.length-1,n+20),l=[];for(let d=m;d<=c;d++)l.push(t[d]);r.push(l.join(`
3
+ `)),o=c,n=c+1}else n++}if(r.length===0)return e;let s=r.map((a,u)=>`<extracted_error_chunk order="${u+1}">
4
4
  ${a}
5
5
  </extracted_error_chunk>`).join(`
6
6
 
7
- `);return s.length>e.length*.8?e:s}import we from"process";import{getTracer as Sr}from"@netlify/otel";import se from"process";var pe=se.env.NETLIFY_API_URL,fe=se.env.NETLIFY_API_TOKEN,U=w("api"),ge=()=>se.env.NETLIFY_LOCAL_MODE==="true",ie=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}`}};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")U.log(`Response headers for ${r}:`),n.headers.forEach((u,i)=>{U.log(` ${i}: ${u}`)});else{let u=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");U.log(`Request ID for ${r}: ${u||"N/A"}`)}if(s||U.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},Xe=e=>{U.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)},ze=()=>({apiUrl:pe,token:fe}),ae=async(e,t)=>ge()?(U.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):ie(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),G=async(e,t,r)=>ge()?(U.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):ie(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var Ze=async(e,t)=>ge()?(U.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):ie(`/api/v1/agent_runners/${e}/sessions/${t}`),Qe=(e,t,r)=>ie(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}}),et=async(e,t)=>ge()?(U.log("Mock API: getDiffUploadUrls called",{runnerId:e,sessionId:t}),{result:{upload_url:"https://s3.mock.com/mock-upload-url-result",s3_key:"mock-s3-key-result"},cumulative:{upload_url:"https://s3.mock.com/mock-upload-url-cumulative",s3_key:"mock-s3-key-cumulative"}}):ie(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Ne=async(e,t)=>{U.log(`Uploading diff to S3: ${e.substring(0,50)}...`);let r=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"text/plain"}});if(!r.ok)throw new Error(`S3 upload failed with status ${r.status}`);return r};var X=w("ai_gateway"),be=null;var tt=async()=>{if(be)return be;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 be=t,X.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},Ht=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 Qe(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 y=o-Date.now()-6e4;y>0&&(n=setTimeout(()=>{u()},y))}};return await Promise.all([u(),tt()]),{get url(){return s},get token(){return r},isModelAvailableForProvider:Ht}};import Y from"process";import me from"path";import Ce from"fs";import{fileURLToPath as Xt}from"url";import{execa as zt,execaCommand as En}from"execa";import{Transform as Kt}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"]),Wt=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function Vt(){return Object.entries(process.env).filter(([e,t])=>!(!t||qt.has(e)||Wt.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function j(e){if(typeof e!="string")return e;let t=Vt();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(Jt(o),"g");r=r.replace(n,"******")}),r}function Jt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var z=class extends Kt{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),s=j(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"?j(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"?j(o):o;return typeof n=="function"?r(a,n):r(a,n,s)}}var le=null,ot=e=>(le&&le.destroy(),le=new K({totalAllowedTime:e}),le),st=()=>le;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.`)}),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 Zt=Xt(import.meta.url),Qt=me.dirname(Zt),he=w("shell"),Pe=new Set,er={preferLocal:!0},it=(e,t,r)=>{let[o,n]=tr(t,r),s={...er,...n},a=zt(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(Y.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new z).pipe(Y.stdout),e.stdout?.pipe(new z).pipe(Y.stdout),e.stderr?.pipe(new z).pipe(Y.stderr);return}e.stdout?.pipe(Y.stdout),e.stderr?.pipe(Y.stderr)},at=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(Y.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}},nr=e=>at(e,"SIGKILL"),or=e=>{Pe.add(e);let t=st();if(t){let r=t.onTimesUp(()=>{he.log(`Global timer expired, killing process ${e.pid}`),at(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(he.log(`Force killing process ${e.pid} after timeout`),nr(e))},5e3)});e.on("exit",()=>{Pe.delete(e),r()}),e.on("error",()=>{Pe.delete(e),r()})}};function Z(e,t){if(Y.env.NODE_PATH){let n=me.join(Y.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(Qt,"..","node_modules",".bin",t);if(Ce.existsSync(o))return o}var lt="netlify-agent-runner-context.md",Oe="task-history",$e="netlify-context",F=".netlify",Q="results.md",De="assets";var sr=w("utils"),ir=e=>new Promise(t=>{setTimeout(t,e)}),ut=(e,t=3e3)=>{let r=!1,o=null,n=[],s=null,a=(...u)=>{if(r)return o=u,new Promise(l=>{n.push(l)});r=!0;let i,y=new Promise(l=>{i=l});return s=(async()=>{await Promise.resolve();let l=await e(...u);for(i(l);;){if(await ir(t),!o)return r=!1,s=null,l;let c=o,g=n;o=null,n=[],l=await e(...c),g.forEach(E=>{E(l)})}})(),y};return a.flush=async()=>{if((r||o)&&s)return await s,a.flush()},a},ye=(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},ct=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):sr.error("Could not parse JSON",o))}},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 y=Math.min(i-s.length,e.length);return`${s}${e.slice(0,y)}`}return e.slice(0,i)};import{Buffer as pt}from"buffer";import ar from"path";var ft=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 l=(await t.utils.run("git",["diff","--staged","--binary"],a)).stdout,c,g;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 h=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;c!==h&&(g=pt.from(h).toString("base64"))}let E={hasChanges:!0,diff:i,resultDiff:c,ignored:s};return i!==l&&(E.diffBinary=pt.from(l).toString("base64")),g&&(E.resultDiffBinary=g),E},lr=["?? mise.toml","?? deno.lock","?? .npmrc",/\?\? .+?\.log/],ur=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
8
- `).filter(n=>!lr.some(s=>s instanceof RegExp?s.test(n):n===s))).length!==0,status:t.stdout}};var gt=async e=>{let{stdout:t}=await e.utils.run("git",["rev-parse","HEAD"]);return t.trim()},mt=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",".npmrc","node_modules"],r=[];return e.split(`
9
- `).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 pr from"fs/promises";import fr from"os";import Et from"path";import q from"process";import gr from"readline";import Fe from"path";import dr from"fs/promises";var Le=w("agent-output-utils");async function ee({initialResult:e,agentName:t,hasError:r}){let o="",n=Fe.join(process.cwd(),F,Q);try{let s=await dr.readFile(n,"utf-8");s&&(o=s,Le.log(`Pulled result from ${Fe.relative(process.cwd(),n)}`))}catch{Le.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 te({error:e,agentName:t}){let r=e&&typeof e=="object"?JSON.stringify(e):e,o=r?.replace(/\s+/g," ").trim().toLowerCase()||"",n="";return o?.includes("ai gateway is not available for your account")||o?.includes("ai gateway is not enabled for your account")?n="AI Gateway is currently not available on your account. Please confirm your account meets the criteria for using Agent Runners and AI Gateway and that your account has remaining AI Gateway inference credits available. Reach out to Netlify support if this is unexpected.":o?.includes("error when talking to gemini api")?n="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":(o?.includes("connection closed prematurely")||o?.includes("499")&&t.toLowerCase().includes("gemini"))&&(n=`The ${t} models were currently overloaded. Please try again or use a different available agent.`),o?.includes("request timed out")&&(n=`The ${t} API request's have timed out. Please try again or use a different available agent.`),o?.includes("network error")&&(n=`The ${t} agent is having network issues. Please try again or use a different available agent.`),n&&Le.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function re(e){if(!e)return!1;let r=(e&&typeof e=="object"?JSON.stringify(e):e)?.replace(/\s+/g," ").trim().toLowerCase()||"";return!!(r?.includes("error when talking to gemini api")||r?.includes("499")||r?.includes("connection closed prematurely")||r?.includes("request timed out")||r?.includes("network error"))}var L=w("runner_claude"),ht="Claude Code",Ee="claude-sonnet-4-5-20250929",yt=e=>({Task:"Task",Bash:"Run command",Glob:"Find files",Grep:"Search files",LS:"List directory",ExitPlanMode:"Exit planning",Read:"Read file",Edit:"Edit file",MultiEdit:"Edit multiple files",Write:"Coding",NotebookEdit:"Edit notebook",WebFetch:"Fetch webpage",TodoWrite:"Update task list",WebSearch:"Search web",BashOutput:"Get command output",KillBash:"Stop command"})[e]||e,mr=({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 ke({config:e,netlify:t,persistSteps:r,aiGateway:o,continueSession:n,priorAgentSessionId:s}){let a=e,{accountType:u,prompt:i,modelVersionOverrides:y}=a,{model:l}=a,c="";if(o){let{token:f,url:_}=o;if(!f||!_)throw new Error("No token or url provided from AI Gateway");if(y?.claude){let d=y?.claude?.[u];if(d){if(!await o.isModelAvailableForProvider("anthropic",d))throw new Error(`Model override '${d}' is not available for anthropic provider`);l=d}}else if(l){if(!await o.isModelAvailableForProvider("anthropic",l))throw new Error(`Model '${l}' is not available for anthropic provider`)}else await o.isModelAvailableForProvider("anthropic",Ee)?(l=Ee,L.log(`Using default model: ${Ee}`)):L.log(`Default model ${Ee} is not available, proceeding without model specification`);q.env.ANTHROPIC_API_KEY=f,q.env.ANTHROPIC_BASE_URL=_}else if(!q.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let g=[],E=[],I={},T=0,h=0,x,R,b=[Z(q.cwd(),"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...l?["--model",l]:[],...n?["--continue"]:[],...n&&s?["--resume",s]:[],"-p",i],N=`${q.env.NVM_BIN}/node`;L.log(`Running ${N} ${b.join(" ")}`);let v=t.utils.run(N,b,{all:!0,env:q.env});v.stdin?.end();let S=ye(()=>{r?.({steps:g,duration:h})},250),m=(f,_)=>{let d={...f,id:T};T+=1,E.push(d),g.push(d),_||S.flush(),S(),_&&S.flush()},p=gr.createInterface({input:v.all});return p.on("error",f=>{L.error("Readline interface error",{error:f.message,stack:f.stack})}),p.on("line",f=>{let _=null;try{_=JSON.parse(f)}catch{L.log("Could not parse line",f)}_?.session_id&&_.session_id!==c&&(c=_.session_id),Array.isArray(_?.message?.content)?_.message.content.forEach(d=>{switch(d.type){case"text":{d.text&&m({message:d.text});break}case"image":{typeof d.source=="object"&&d.source&&d.source.type==="base64"&&d.source.media_type?m({message:`![](data:${d.source.media_type};base64,${d.source.data})`}):L.log(`Unsupported image type ${d.source?.type}`,d.source);break}case"tool_use":{if(d.name==="Task"){let C=d.input?.description&&`\`${d.input.description}\``;m({title:[yt(d.name),C].filter(Boolean).join(" ")})}else d.id&&(I[d.id]=d);S.flush();break}case"tool_result":{let C=d.tool_use_id?I[d.tool_use_id]:void 0,oe;if(C){let J=C.input?.file_path&&Et.relative(q.cwd(),C.input.file_path),P=J&&`\`${J}\``;oe=[yt(C.name||""),P].filter(Boolean).join(" ")}let He=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(C?.name||""),B;if(typeof d.content=="string")B=d.content;else if(Array.isArray(d.content)){let J=[];d.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})`):L.log(`Unsupported image type ${P.source.type}`,P.source):L.log(`Unsupported block type ${P?.type}`)}),B=J.join(`
7
+ `);return s.length>e.length*.8?e:s}import _e from"process";import{getTracer as $r}from"@netlify/otel";import ie from"process";var de=ie.env.NETLIFY_API_URL,fe=ie.env.NETLIFY_API_TOKEN,M=E("api"),ge=()=>ie.env.NETLIFY_LOCAL_MODE==="true",ae=async(e,t={})=>{if(!de||!fe)throw new Error("No API URL or token");let r=new URL(e,de),o={...t,headers:{...t.headers,Authorization:`Bearer ${fe}`}};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")M.log(`Response headers for ${r}:`),n.headers.forEach((u,i)=>{M.log(` ${i}: ${u}`)});else{let u=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");M.log(`Request ID for ${r}: ${u||"N/A"}`)}if(s||M.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},Qe=e=>{M.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(de=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(fe=e.constants.NETLIFY_API_TOKEN)},et=()=>({apiUrl:de,token:fe}),le=async(e,t)=>ge()?(M.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):ae(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),G=async(e,t,r)=>ge()?(M.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):ae(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var tt=async(e,t)=>ge()?(M.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):ae(`/api/v1/agent_runners/${e}/sessions/${t}`),rt=(e,t,r)=>ae(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}}),nt=async(e,t)=>ge()?(M.log("Mock API: getDiffUploadUrls called",{runnerId:e,sessionId:t}),{result:{upload_url:"https://s3.mock.com/mock-upload-url-result",s3_key:"mock-s3-key-result"},cumulative:{upload_url:"https://s3.mock.com/mock-upload-url-cumulative",s3_key:"mock-s3-key-cumulative"}}):ae(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Ne=async(e,t)=>{M.log(`Uploading diff to S3: ${e.substring(0,50)}...`);let r=await fetch(e,{method:"PUT",body:t,headers:{"Content-Type":"text/plain"}});if(!r.ok)throw new Error(`S3 upload failed with status ${r.status}`);return r};var X=E("ai_gateway"),be=null;var ot=async()=>{if(be)return be;X.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 be=t,X.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},Vt=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 u=async()=>{clearTimeout(n),X.log("Requesting AI gateway information");let i=await rt(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 m=o-Date.now()-6e4;m>0&&(n=setTimeout(()=>{u()},m))}};return await Promise.all([u(),ot()]),{get url(){return s},get token(){return r},isModelAvailableForProvider:Vt}};import Y from"process";import me from"path";import Ce from"fs";import{fileURLToPath as er}from"url";import{execa as tr,execaCommand as An}from"execa";import{Transform as Jt}from"stream";var Xt=new Set(["NODE_ENV","PATH","HOME","USER","USERNAME","SHELL","PWD","OLDPWD","TMPDIR","TMP","TEMP","LANG","TERM","EDITOR","PAGER","OS","PROCESSOR_ARCHITECTURE","PROCESSOR_IDENTIFIER","SYSTEMROOT","WINDIR","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","APPDATA","LOCALAPPDATA","NODE_OPTIONS","NODE_PATH","NODE_DEBUG","NODE_NO_WARNINGS","npm_config_registry","npm_config_cache","npm_execpath","npm_node_execpath","CI","GITHUB_ACTIONS","GITHUB_WORKSPACE","GITHUB_REPOSITORY","GITHUB_REF","BUILDKITE","BUILDKITE_BRANCH","BUILDKITE_COMMIT","BUILDKITE_BUILD_NUMBER","JENKINS_URL","TRAVIS","CIRCLECI","DISPLAY","COLORTERM","TERM_PROGRAM","TERM_PROGRAM_VERSION","COLUMNS","LINES","HISTSIZE","HISTFILE","NETLIFY_AGENT_RUNNER_ID","NETLIFY_AGENT_RUNNER_SESSION_ID","NETLIFY_AGENT_RUNNER_PROMPT","NETLIFY_AGENT_RUNNER_AGENT","NETLIFY_AGENT_RUNNER_MODEL","NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED","NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED","ERROR_LOGS_PATH","NETLIFY_AGENT_RUNNER_CONTEXT","NETLIFY_AGENT_RUNNER_HAS_REPO","NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED","NETLIFY_AGENT_RUNNER_SHA","NETLIFY_TEAM_TYPE","AGENT_RUNNERS_DEBUG","NETLIFY_TEAM_ID","NETLIFY_AGENT_RUNNER_USER_ID","SITE_NAME"]),zt=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function Zt(){return Object.entries(process.env).filter(([e,t])=>!(!t||Xt.has(e)||zt.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(Qt(o),"g");r=r.replace(n,"******")}),r}function Qt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var z=class extends Jt{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),s=j(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"?j(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"?j(o):o;return typeof n=="function"?r(a,n):r(a,n,s)}}var ue=null,at=e=>(ue&&ue.destroy(),ue=new q({totalAllowedTime:e}),ue),lt=()=>ue;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 rr=er(import.meta.url),nr=me.dirname(rr),he=E("shell"),Pe=new Set,or={preferLocal:!0},F=(e,t,r)=>{let[o,n]=sr(t,r),s={...or,...n},a=tr(e,o,s);return ir(a,s),lr(a),a};var sr=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 z).pipe(Y.stdout),e.stdout?.pipe(new z).pipe(Y.stdout),e.stderr?.pipe(new z).pipe(Y.stderr);return}e.stdout?.pipe(Y.stdout),e.stderr?.pipe(Y.stderr)},ut=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(Y.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}},ar=e=>ut(e,"SIGKILL"),lr=e=>{Pe.add(e);let t=lt();if(t){let r=t.onTimesUp(()=>{he.log(`Global timer expired, killing process ${e.pid}`),ut(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(he.log(`Force killing process ${e.pid} after timeout`),ar(e))},5e3)});e.on("exit",()=>{Pe.delete(e),r()}),e.on("error",()=>{Pe.delete(e),r()})}};function Z(e,t){if(Y.env.NODE_PATH){let n=me.join(Y.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(nr,"..","node_modules",".bin",t);if(Ce.existsSync(o))return o}var ct="netlify-agent-runner-context.md",Oe="task-history",Fe="netlify-context",L=".netlify",Q="results.md",$e="assets";var ur=E("utils"),cr=e=>new Promise(t=>{setTimeout(t,e)}),pt=(e,t=3e3)=>{let r=!1,o=null,n=[],s=null,a=(...u)=>{if(r)return o=u,new Promise(c=>{n.push(c)});r=!0;let i,m=new Promise(c=>{i=c});return s=(async()=>{await Promise.resolve();let c=await e(...u);for(i(c);;){if(await cr(t),!o)return r=!1,s=null,c;let l=o,d=n;o=null,n=[],c=await e(...l),d.forEach(h=>{h(c)})}})(),m};return a.flush=async()=>{if((r||o)&&s)return await s,a.flush()},a},ye=(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},dt=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):ur.error("Could not parse JSON",o))}},ft=(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 gt}from"buffer";import pr from"path";var mt=E("repo"),ht=async({config:e})=>{mt.info("Getting runner diffs");let t=await fr(),{hasChanges:r}=t,{status:o}=t;if(!r)return{hasChanges:!1};let n=gr(o);await mr(n),mt.info("Changes after processing"),await Le();let s=await ke(o);await De(s);let a={stdio:["ignore","pipe","pipe"]},i=(await F("git",["diff","--staged"],a)).stdout;if(r=!!i,!r)return{hasChanges:!1,ignored:s};let c=(await F("git",["diff","--staged","--binary"],a)).stdout,l,d;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await F("git",["commit","-m","Agent runner"]),l=(await F("git",["diff",e.sha,"HEAD"],a)).stdout;let g=(await F("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;l!==g&&(d=gt.from(g).toString("base64"))}let h={hasChanges:!0,diff:i,resultDiff:l,ignored:s};return i!==c&&(h.diffBinary=gt.from(c).toString("base64")),d&&(h.resultDiffBinary=d),h},De=async(e=[])=>{await F("git",["add",".",...e])},Le=async()=>(await F("git",["status","-s"])).stdout,yt=/.. (.+)?\.log$/,dr=[yt],fr=async()=>{let e=await Le();return{hasChanges:(e.trim().length===0?[]:e.split(`
8
+ `).filter(o=>dr.some(s=>s instanceof RegExp?s.test(o):o===s)?!1:o[1]?.trim()!=="")).length!==0,status:e}},Et=async()=>{let{stdout:e}=await F("git",["rev-parse","HEAD"]);return e.trim()},_t=async()=>{let{stdout:e}=await F("git",["rev-list","--max-parents=0","HEAD"]);return e.trim()},ke=async e=>{e||=await Le();let t=[".netlify","node_modules"],r=[];return e.split(`
9
+ `).forEach(o=>{t.forEach(s=>{[`?? ${s}`,`?? ${s}${pr.sep}`].some(u=>o.startsWith(u))&&r.push(`:!${s}`)});let n=o.match(yt)?.[1];n&&r.push(`:!${n}.log`)}),r},wt=async()=>{await F("git",["reset","--hard","HEAD"])},gr=e=>{let t=e.split(`
10
+ `).reduce((r,o)=>{if(!o)return r;let[n,s,,...a]=o,u=a.join(""),i=n.trim(),m=s.trim();return r[u]?r[u].change=m:r[u]={filePath:u,stage:i,change:m},r},{});return Object.values(t)},mr=async e=>{let t=[];for(let r of e)r.stage&&!r.change&&t.push(F("git",["restore","--staged","--worktree",r.filePath]));await Promise.allSettled(t)};import yr from"fs/promises";import Er from"os";import xt from"path";import K from"process";import _r from"readline";import Ue from"path";import hr from"fs/promises";var Me=E("agent-output-utils");async function ee({initialResult:e,agentName:t,hasError:r}){let o="",n=Ue.join(process.cwd(),L,Q);try{let s=await hr.readFile(n,"utf-8");s&&(o=s,Me.log(`Pulled result from ${Ue.relative(process.cwd(),n)}`))}catch{Me.log(`No results file found at ${Ue.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&&Me.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function re(e){if(!e)return!1;let r=(e&&typeof e=="object"?JSON.stringify(e):e)?.replace(/\s+/g," ").trim().toLowerCase()||"";return!!(r?.includes("error when talking to gemini api")||r?.includes("499")||r?.includes("connection closed prematurely")||r?.includes("request timed out")||r?.includes("network error"))}var k=E("runner_claude"),Tt="Claude Code",Ee="claude-sonnet-4-5-20250929",It=e=>({Task:"Task",Bash:"Run command",Glob:"Find files",Grep:"Search files",LS:"List directory",ExitPlanMode:"Exit planning",Read:"Read file",Edit:"Edit file",MultiEdit:"Edit multiple files",Write:"Coding",NotebookEdit:"Edit notebook",WebFetch:"Fetch webpage",TodoWrite:"Update task list",WebSearch:"Search web",BashOutput:"Get command output",KillBash:"Stop command"})[e]||e,wr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(k.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(k.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(k.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function Ge({config:e,netlify:t,persistSteps:r,aiGateway:o,continueSession:n,priorAgentSessionId:s}){let a=e,{accountType:u,prompt:i,modelVersionOverrides:m}=a,{model:c}=a,l="";if(o){let{token:f,url:T}=o;if(!f||!T)throw new Error("No token or url provided from AI Gateway");if(m?.claude){let p=m?.claude?.[u];if(p){if(!await o.isModelAvailableForProvider("anthropic",p))throw new Error(`Model override '${p}' is not available for anthropic provider`);c=p}}else if(c){if(!await o.isModelAvailableForProvider("anthropic",c))throw new Error(`Model '${c}' is not available for anthropic provider`)}else await o.isModelAvailableForProvider("anthropic",Ee)?(c=Ee,k.log(`Using default model: ${Ee}`)):k.log(`Default model ${Ee} is not available, proceeding without model specification`);K.env.ANTHROPIC_API_KEY=f,K.env.ANTHROPIC_BASE_URL=T}else if(!K.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let d=[],h=[],x={},I=0,g=0,S,v,N=[Z(K.cwd(),"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...c?["--model",c]:[],...n?["--continue"]:[],...n&&s?["--resume",s]:[],"-p",i],R=`${K.env.NVM_BIN}/node`;k.log(`Running ${R} ${N.join(" ")}`);let _=t.utils.run(R,N,{all:!0,env:K.env});_.stdin?.end();let A=ye(()=>{r?.({steps:d,duration:g})},250),w=(f,T)=>{let p={...f,id:I};I+=1,h.push(p),d.push(p),T||A.flush(),A(),T&&A.flush()},y=_r.createInterface({input:_.all});return y.on("error",f=>{k.error("Readline interface error",{error:f.message,stack:f.stack})}),y.on("line",f=>{let T=null;try{T=JSON.parse(f)}catch{k.log("Could not parse line",f)}T?.session_id&&T.session_id!==l&&(l=T.session_id),Array.isArray(T?.message?.content)?T.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})`}):k.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}\``;w({title:[It(p.name),C].filter(Boolean).join(" ")})}else p.id&&(x[p.id]=p);A.flush();break}case"tool_result":{let C=p.tool_use_id?x[p.tool_use_id]:void 0,se;if(C){let J=C.input?.file_path&&xt.relative(K.cwd(),C.input.file_path),P=J&&`\`${J}\``;se=[It(C.name||""),P].filter(Boolean).join(" ")}let We=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(C?.name||""),B;if(typeof p.content=="string")B=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})`):k.log(`Unsupported image type ${P.source.type}`,P.source):k.log(`Unsupported block type ${P?.type}`)}),B=J.join(`
10
11
 
11
- `)}He&&B&&(B=`\`\`\`
12
+ `)}We&&B&&(B=`\`\`\`
12
13
  ${B.trim()}
13
- \`\`\``),m({title:oe,message:B},!0);break}case"thinking":{d.thinking&&m({title:"Thinking",message:d.thinking},!0);break}default:L.log(`Message content type is not supported ${d.type}`,d)}}):_?.type==="result"&&(h=_.duration_ms||0,_.is_error?R=_.result:x=_.result,[E,g].forEach(d=>{d[d.length-1]?.message===x&&d.pop()}))}),await v.catch(f=>{({error:R,result:x}=mr({catchError:f,runCmd:v,error:R,result:x,runnerName:"Claude"}))}),p.close(),S.flush(),{steps:E,duration:h,result:await ee({initialResult:x,agentName:ht,hasError:!!R}),error:te({error:R,agentName:ht}),isRetryableError:re(R),agentSessionId:c}}var _t=async()=>{let e=Et.join(fr.homedir(),".claude");await pr.rm(e,{recursive:!0,force:!0})};import ue from"fs/promises";import Tt from"os";import _e from"path";import W from"process";import hr from"readline";var M=w("runner_codex"),wt="Codex CLI",yr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(M.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?(M.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}):(M.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,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:a,modelVersionOverrides:u}=e,{model:i}=e;if(n){let{token:m,url:p}=n;if(!m||!p)throw new Error("No token or url provided from AI Gateway");if(u?.codex){let f=u?.codex?.[s];if(f){if(!await n.isModelAvailableForProvider("openai",f))throw new Error(`Model override '${f}' is not available for openai provider`);i=f}}else if(i&&!await n.isModelAvailableForProvider("openai",i))throw new Error(`Model '${i}' is not available for openai provider`);W.env.OPENAI_API_KEY=m,W.env.OPENAI_BASE_URL=p}else if(!W.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let y=[],l=[],c={},g=0,E=0,I,T,h=`${W.env.NVM_BIN}/node`,x=_e.join(Tt.homedir(),".codex"),R=_e.join(x,"config.toml"),b=_e.join(x,"auth.json");try{await ue.mkdir(x,{recursive:!0});let m={OPENAI_API_KEY:W.env.OPENAI_API_KEY};await ue.writeFile(b,JSON.stringify(m,null,2),"utf-8"),M.log("Created Codex auth.json file");let p="";try{p=await ue.readFile(R,"utf-8")}catch{}p.includes("web_search")||(p.includes("[tools]")?p=p.replace(/\[tools\]/,`[tools]
14
- web_search = true`):p+=`
15
- [tools]
16
- web_search = true
17
- `,await ue.writeFile(R,p,"utf-8"),M.log("Updated Codex config with web_search enabled"))}catch(m){throw M.warn("Failed to setup Codex config and credentials",{error:m.message}),new Error(`Codex setup failed: ${m.message}`)}let N=[Z(W.cwd(),"codex"),"exec","--yolo","--json","--config","web_search=true",...i?["--model",i]:[],a].filter(Boolean);M.log(`Running ${h} ${N.join(" ")}`);let v=t.utils.run(h,N,{all:!0,env:{...W.env}}),S=hr.createInterface({input:v.all});return S.on("error",m=>{M.error("Readline interface error",{error:m.message,stack:m.stack})}),S.on("line",m=>{let p=null;try{p=JSON.parse(m)}catch{M.log("Could not parse line",m);return}let f=[],_=!1;if(p?.duration_ms&&(E=p.duration_ms,_=!0),p?.type==="local_shell_call")c[p.call_id]=p;else if(p?.type==="local_shell_call_output"){let d=_r(c[p.call_id],p);d&&(d.id=g,g+=1,l.push(d),y.push(d),f.push(d),_=!0)}else p?.type==="message"&&p.role==="assistant"?I=p.content.map(d=>d.text).join(`
18
- `):p?.type==="message"&&p.role==="system"&&(T=p.content.map(d=>d.text).join(`
19
- `));_&&(r?.({steps:y,duration:E}),o?.({steps:f,duration:E}))}),await v.catch(m=>{let p=yr({catchError:m,runCmd:v,error:T,result:I,runnerName:"Codex"});T=p.error,I=p.result}),S.close(),{steps:l,duration:E,result:await ee({initialResult:I,agentName:wt,hasError:!!T}),error:te({error:T,agentName:wt}),isRetryableError:re(T)}}var It=async()=>{let e=_e.join(Tt.homedir(),".codex");await ue.rm(e,{recursive:!0,force:!0})},Er=new Set(["bash","-lc"]),_r=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!Er.has(s)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
14
+ \`\`\``),w({title:se,message:B},!0);break}case"thinking":{p.thinking&&w({title:"Thinking",message:p.thinking},!0);break}default:k.log(`Message content type is not supported ${p.type}`,p)}}):T?.type==="result"&&(g=T.duration_ms||0,T.is_error?v=T.result:S=T.result,[h,d].forEach(p=>{p[p.length-1]?.message===S&&p.pop()}))}),await _.catch(f=>{({error:v,result:S}=wr({catchError:f,runCmd:_,error:v,result:S,runnerName:"Claude"}))}),y.close(),A.flush(),{steps:h,duration:g,result:await ee({initialResult:S,agentName:Tt,hasError:!!v}),error:te({error:v,agentName:Tt}),isRetryableError:re(v),agentSessionId:l}}var Rt=async()=>{let e=xt.join(Er.homedir(),".claude");await yr.rm(e,{recursive:!0,force:!0})};import Tr from"fs/promises";import Ir from"os";import xr from"path";import ne from"process";import Rr from"readline";var W=E("runner_codex"),vt="Codex CLI",vr=({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 je({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 A=u?.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=R,ne.env.OPENAI_BASE_URL=_}else if(!ne.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let m=[],c=[],l={},d=0,h=0,x,I,g=[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),S=`${ne.env.NVM_BIN}/node`;W.log(`Running ${S} ${g.join(" ")}`);let v=t.utils.run(S,g,{all:!0,env:{...ne.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),N=Rr.createInterface({input:v.all});return N.on("error",R=>{W.error("Readline interface error",{error:R.message,stack:R.stack})}),N.on("line",R=>{let _=null;try{_=JSON.parse(R)}catch{W.log("Could not parse line",R);return}let A=[],w=!1;if(_?.duration_ms&&(h=_.duration_ms,w=!0),_?.type==="local_shell_call")l[_.call_id]=_;else if(_?.type==="local_shell_call_output"){let y=Ar(l[_.call_id],_);y&&(y.id=d,d+=1,c.push(y),m.push(y),A.push(y),w=!0)}else _?.type==="message"&&_.role==="assistant"?x=_.content.map(y=>y.text).join(`
15
+ `):_?.type==="message"&&_.role==="system"&&(I=_.content.map(y=>y.text).join(`
16
+ `));w&&(r?.({steps:m,duration:h}),o?.({steps:A,duration:h}))}),await v.catch(R=>{let _=vr({catchError:R,runCmd:v,error:I,result:x,runnerName:"Codex"});I=_.error,x=_.result}),N.close(),{steps:c,duration:h,result:await ee({initialResult:x,agentName:vt,hasError:!!I}),error:te({error:I,agentName:vt}),isRetryableError:re(I)}}var St=async()=>{let e=xr.join(Ir.homedir(),".codex");await Tr.rm(e,{recursive:!0,force:!0})},Sr=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=>!Sr.has(s)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
20
17
  ${n.trim()}
21
- \`\`\``)}catch(s){M.error("Could not decode outputMsg",s,t.output)}return{title:o,message:n}};import wr from"fs/promises";import Tr from"os";import Rt from"path";import V from"process";import Ir from"readline";var ne=w("runner_gemini"),xt="Gemini CLI",xr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(ne.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(ne.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(ne.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),Rr={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:p}=n;if(!m||!p)throw new Error("No token or url provided from AI Gateway");if(u?.gemini){let f=u?.gemini?.[s];if(f){if(!await n.isModelAvailableForProvider("gemini",f))throw new Error(`Model override '${f}' is not available for gemini provider`);i=f}}else if(i&&!await n.isModelAvailableForProvider("gemini",i))throw new Error(`Model '${i}' is not available for gemini provider`);V.env.GEMINI_API_KEY=m,V.env.GOOGLE_GEMINI_BASE_URL=p}else if(!V.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let y=[],l=[],c=[],g={},E=0,I=0,T,h,x=[Z(V.cwd(),"gemini"),...i?["--model",i]:[],"--yolo","-p",a],R=`${V.env.NVM_BIN}/node`;ne.log(`Running ${R} ${x.join(" ")}`);let b=t.utils.run(R,x,{all:!0,env:V.env});b.stdin?.end();let N=ye(()=>{r?.({steps:y,duration:I}),o?.({steps:l,duration:I}),l=[]},250),v=(m,p)=>{m.id=E,E+=1,c.push(m),y.push(m),l.push(m),p||N.flush(),N(),p&&N.flush()},S=Ir.createInterface({input:b.all});return S.on("error",m=>{ne.error("Readline interface error",{error:m.message,stack:m.stack})}),S.on("line",m=>{let p=null;try{if(m.startsWith("[API Error")){let f=m.match(/\[api error: (.+?)]$/i)?.[1];p={type:"error",value:ct(f,!1)?.error?.message||f||"Gemini encountered error"}}else p=JSON.parse(m)}catch{return}if(p)switch(p.type){case"thought":{let f=p.value;v({title:f?.subject??"Thinking...",message:f?.description},!0);break}case"content":{p.value&&v({message:p.value});break}case"tool_call_request":{let f=p.value,_=Rr[f.name]??f.name,d=f.args?.path||f.args?.absolute_path,C=d&&Rt.relative(V.cwd(),d),oe=f.args?.command,B={title:[_,C&&`\`${C}\``,oe&&`\`${oe}\``].filter(Boolean).join(" ")};g[f.callId]=B,N.flush();break}case"tool_result":{let f=p.value,_=g[f.callId];if(_){let d=[f.resultDisplay,f.responseParts?.functionResponse?.response?.output].find(C=>typeof C=="string"&&C);d&&(_.message=`\`\`\`
22
- ${d.trim()}
23
- \`\`\``),v(_,!0)}break}case"result":{I=p.duration_ms,T=p.value,[c,y,l].forEach(f=>{f[f.length-1]?.message===T&&f.pop()});break}case"error":{h=p.value;break}case"finished":break;default:{ne.warn("Unhandled message type:",p.type);break}}}),await b.catch(m=>{({error:h,result:T}=xr({catchError:m,runCmd:b,error:h,result:T,runnerName:"Gemini"}))}),S.close(),N.flush(),{steps:c,duration:I,result:await ee({initialResult:T,agentName:xt,hasError:!!h}),error:te({error:h,agentName:xt}),isRetryableError:re(h)}}var vt=async()=>{let e=Rt.join(Tr.homedir(),".gemini");await wr.rm(e,{recursive:!0,force:!0})};var vr={codex:{runner:Ue,clean:It},claude:{runner:ke,clean:_t},gemini:{runner:Me,clean:vt}},St=vr;var At=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>await A(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=St[e.runner];if(!a)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let u=Ar({apiToken:r});Xe(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 y=ut(({steps:g=[],duration:E})=>{let I=g.map(T=>({...T,title:T.title?j(T.title):void 0,message:T.message?j(T.message):void 0}));return g.length=0,G(e.id,e.sessionId,{steps:I,duration:E})},t),l;e.hasRepo?e.sha?(l=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(l=await gt(u),await ae(e.id,{sha:l}),n?.setAttributes({"init.sha.source":"current_commit"})):(l=await mt(u),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let c=performance.now()-s;return n?.setAttributes({"init.sha":l||"unknown","init.duration.ms":c,"init.status":"success"}),{aiGateway:i,context:u,persistSteps:y,runner:a,sha:l}}),Ar=({apiToken:e})=>({constants:{NETLIFY_API_HOST:we.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||we.env.NETLIFY_API_TOKEN,SITE_ID:we.env.SITE_ID,FUNCTIONS_DIST:we.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:it}});import{getTracer as Ge}from"@netlify/otel";import Nr from"crypto";import H from"fs/promises";import $ from"path";import k from"process";var O=w("context"),br=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:k.env.NETLIFY_TEAM_ID,userId:k.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:k.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},Cr=10,Pr=async e=>{let{name:t,ext:r}=$.parse(e),o=e,n=$.join(k.cwd(),F,o),s=0;for(;await Or(n);){if(s>=Cr)throw new Error("Failed to generate context file");o=`${t}-${Nr.randomUUID().slice(0,5)}${r}`,n=$.join(k.cwd(),F,o),s+=1}return o},Or=async e=>{try{return await H.access(e),!0}catch{return!1}},$r=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}},Dr=async(e,t)=>{try{let r=await fetch(e,{signal:AbortSignal.timeout(1e4)});if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let o=await r.text();return await H.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}},Te=null,Fr=async()=>{if(Te)return Te;let e=await $r();if(!e)return[];let t=$.join(k.cwd(),F,$e);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 O.warn(`Invalid scope data for ${n}, skipping...`),null;let a=`${n}.md`,u=$.join(t,a),i=$.join(F,$e,a);return O.log(`Downloading ${s.scope} context...`),await Dr(s.endpoint,u)?(O.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:n}):null});return Te=(await Promise.all(r)).filter(n=>n!==null),Te},Nt=async({cliPath:e,netlify:t,config:r,buildErrorContext:o})=>{let n=br(t),s=await Pr(lt),a=$.join(k.cwd(),F);await H.mkdir(a,{recursive:!0});let u=$.join(F,s),i=$.join(k.cwd(),u),y=$.join(k.cwd(),F,Q);try{await H.unlink(y),O.log(`Deleted old results file: ${y}`)}catch{}let l=o?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
18
+ \`\`\``)}catch(s){W.error("Could not decode outputMsg",s,t.output)}return{title:o,message:n}};import Nr from"fs/promises";import br from"os";import Nt from"path";import V from"process";import Cr from"readline";var oe=E("runner_gemini"),At="Gemini CLI",Pr=({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})),Or={list_directory:"List",read_file:"Read",write_file:"Write",glob:"Find",search_file_content:"Find",replace:"Edit",run_shell_command:"Run",web_fetch:"Web Fetch",web_search:"Web Search",read_many_files:"Read Many",save_memory:"Memorize"};async function Ye({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:w,url:y}=n;if(!w||!y)throw new Error("No token or url provided from AI Gateway");if(u?.gemini){let f=u?.gemini?.[s];if(f){if(!await n.isModelAvailableForProvider("gemini",f))throw new Error(`Model override '${f}' is not available for gemini provider`);i=f}}else if(i&&!await n.isModelAvailableForProvider("gemini",i))throw new Error(`Model '${i}' is not available for gemini provider`);V.env.GEMINI_API_KEY=w,V.env.GOOGLE_GEMINI_BASE_URL=y}else if(!V.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let m=[],c=[],l=[],d={},h=0,x=0,I,g,S=[Z(V.cwd(),"gemini"),...i?["--model",i]:[],"--yolo","-p",a],v=`${V.env.NVM_BIN}/node`;oe.log(`Running ${v} ${S.join(" ")}`);let N=t.utils.run(v,S,{all:!0,env:V.env});N.stdin?.end();let R=ye(()=>{r?.({steps:m,duration:x}),o?.({steps:c,duration:x}),c=[]},250),_=(w,y)=>{w.id=h,h+=1,l.push(w),m.push(w),c.push(w),y||R.flush(),R(),y&&R.flush()},A=Cr.createInterface({input:N.all});return A.on("error",w=>{oe.error("Readline interface error",{error:w.message,stack:w.stack})}),A.on("line",w=>{let y=null;try{if(w.startsWith("[API Error")){let f=w.match(/\[api error: (.+?)]$/i)?.[1];y={type:"error",value:dt(f,!1)?.error?.message||f||"Gemini encountered error"}}else y=JSON.parse(w)}catch{return}if(y)switch(y.type){case"thought":{let f=y.value;_({title:f?.subject??"Thinking...",message:f?.description},!0);break}case"content":{y.value&&_({message:y.value});break}case"tool_call_request":{let f=y.value,T=Or[f.name]??f.name,p=f.args?.path||f.args?.absolute_path,C=p&&Nt.relative(V.cwd(),p),se=f.args?.command,B={title:[T,C&&`\`${C}\``,se&&`\`${se}\``].filter(Boolean).join(" ")};d[f.callId]=B,R.flush();break}case"tool_result":{let f=y.value,T=d[f.callId];if(T){let p=[f.resultDisplay,f.responseParts?.functionResponse?.response?.output].find(C=>typeof C=="string"&&C);p&&(T.message=`\`\`\`
19
+ ${p.trim()}
20
+ \`\`\``),_(T,!0)}break}case"result":{x=y.duration_ms,I=y.value,[l,m,c].forEach(f=>{f[f.length-1]?.message===I&&f.pop()});break}case"error":{g=y.value;break}case"finished":break;default:{oe.warn("Unhandled message type:",y.type);break}}}),await N.catch(w=>{({error:g,result:I}=Pr({catchError:w,runCmd:N,error:g,result:I,runnerName:"Gemini"}))}),A.close(),R.flush(),{steps:l,duration:x,result:await ee({initialResult:I,agentName:At,hasError:!!g}),error:te({error:g,agentName:At}),isRetryableError:re(g)}}var bt=async()=>{let e=Nt.join(br.homedir(),".gemini");await Nr.rm(e,{recursive:!0,force:!0})};var Fr={codex:{runner:je,clean:St},claude:{runner:Ge,clean:Rt},gemini:{runner:Ye,clean:bt}},Ct=Fr;var Dr=E("init_stage"),Pt=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>await b($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 u=Lr({apiToken:r});Qe(u);let i=e.useGateway?await st({netlify:u,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!i}),e.validateAgent&&e.errorLogsPath&&n?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let m=pt(({steps:h=[],duration:x})=>{let I=h.map(g=>({...g,title:g.title?j(g.title):void 0,message:g.message?j(g.message):void 0}));return h.length=0,G(e.id,e.sessionId,{steps:I,duration:x})},t);Dr.info("Adding build files to stage");let c=await ke();await De(c);let l;e.hasRepo?e.sha?(l=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(l=await Et(),await le(e.id,{sha:l}),n?.setAttributes({"init.sha.source":"current_commit"})):(l=await _t(),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let d=performance.now()-s;return n?.setAttributes({"init.sha":l||"unknown","init.duration.ms":d,"init.status":"success"}),{aiGateway:i,context:u,persistSteps:m,runner:a,sha:l}}),Lr=({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:F}});import{getTracer as Be}from"@netlify/otel";import kr from"crypto";import H from"fs/promises";import D from"path";import U from"process";var $=E("context"),Ur=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:U.env.NETLIFY_TEAM_ID,userId:U.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:U.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},Mr=10,Gr=async e=>{let{name:t,ext:r}=D.parse(e),o=e,n=D.join(U.cwd(),L,o),s=0;for(;await jr(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(),L,o),s+=1}return o},jr=async e=>{try{return await H.access(e),!0}catch{return!1}},Yr=async()=>{try{$.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 $.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"?($.warn("Catchall consumer missing or invalid contextScopes"),null):r:($.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?$.warn("Netlify features context request timed out"):$.warn("Failed to fetch Netlify features context:",e.message),null}},Br=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"?$.warn(`Download timeout for ${e}`):$.warn(`Failed to download context file ${e}:`,r.message),!1}},we=null,Hr=async()=>{if(we)return we;let e=await Yr();if(!e)return[];let t=D.join(U.cwd(),L,Fe);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 $.warn(`Invalid scope data for ${n}, skipping...`),null;let a=`${n}.md`,u=D.join(t,a),i=D.join(L,Fe,a);return $.log(`Downloading ${s.scope} context...`),await Br(s.endpoint,u)?($.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:n}):null});return we=(await Promise.all(r)).filter(n=>n!==null),we},Ot=async({cliPath:e,netlify:t,config:r,buildErrorContext:o})=>{let n=Ur(t),s=await Gr(ct),a=D.join(U.cwd(),L);await H.mkdir(a,{recursive:!0});let u=D.join(L,s),i=D.join(U.cwd(),u),m=D.join(U.cwd(),L,Q);try{await H.unlink(m),$.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.
24
21
  Your task is to analyze and fix the build errors.
25
22
  Don't apply techniques of reverting changes. Apply fixes related to errors.
26
23
  Don't try to run build by yourself. Just fix the errors.
27
24
 
28
25
  <build_error_context>
29
26
  ${o}
30
- </build_error_context>`:"",c="";r.siteContext&&r.siteContext.length!==0&&(c=`
27
+ </build_error_context>`:"",l="";r.siteContext&&r.siteContext.length!==0&&(l=`
31
28
  <project_rules>
32
- ${r.siteContext.filter(h=>h.site_context).map(h=>typeof h.site_context=="string"?h.site_context:typeof h.site_context=="object"?JSON.stringify(h.site_context):"").join(`
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(`
33
30
 
34
31
  `)}
35
32
  </project_rules>
36
- `);let g="";if(r.sessionHistoryContext?.length){let h=$.join(k.cwd(),F,Oe);await H.mkdir(h,{recursive:!0});let x=await Promise.all(r.sessionHistoryContext.map(async(R,b)=>{let N=b+1,v=`attempt-${N}.md`,S=$.join(h,v),m=$.join(F,Oe,v),p=`# Task History - Attempt ${N}
33
+ `);let d="";if(r.sessionHistoryContext?.length){let g=D.join(U.cwd(),L,Oe);await H.mkdir(g,{recursive:!0});let S=await Promise.all(r.sessionHistoryContext.map(async(v,N)=>{let R=N+1,_=`attempt-${R}.md`,A=D.join(g,_),w=D.join(L,Oe,_),y=`# Task History - Attempt ${R}
37
34
 
38
35
  ## Request - what the user asked for
39
- ${R.request}
36
+ ${v.request}
40
37
 
41
38
  ---
42
39
 
43
40
  ## Response - what the agent replied with after its work
44
41
 
45
- ${R.response}
46
- `;return await H.writeFile(S,p,"utf-8"),O.log(`Created history file: ${m}`),m}));g+=`
42
+ ${v.response}
43
+ `;return await H.writeFile(A,y,"utf-8"),$.log(`Created history file: ${w}`),w}));d+=`
47
44
  <session_history_context>
48
45
  History of prior work on this task.
49
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.
50
47
 
51
- ${x.slice(-5).map(R=>`- ${R}`).join(`
48
+ ${S.slice(-5).map(v=>`- ${v}`).join(`
52
49
  `)}
53
50
 
54
51
  </session_history_context>
55
- `}let E=await Fr(),I="";E.length>0&&(I=`
52
+ `}let h=await Hr(),x="";h.length>0&&(x=`
56
53
  <netlify_features_context>
57
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.
58
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.
59
56
 
60
- ${E.map(h=>`- **${h.scope}**: ${h.path}`).join(`
57
+ ${h.map(g=>`- **${g.scope}**: ${g.path}`).join(`
61
58
  `)}
62
59
 
63
60
  Refer to these files when working with specific Netlify features.
64
61
  </netlify_features_context>
65
- `);let T=`
62
+ `);let I=`
66
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.
67
64
 
68
65
  <request>
69
66
  <user_request>
70
67
  ${r.prompt}
71
68
  </user_request>
72
- ${l}
69
+ ${c}
73
70
  </request>
74
71
 
75
72
  <requirements>
@@ -82,10 +79,10 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
82
79
  - NEVER print potentially sensitive values (like secrets) in the planning output or results
83
80
  </responses>
84
81
  <attachements>
85
- - for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${a}/${De} folder
86
- - move assets from ${a}/${De} 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}/${$e} folder
83
+ - move assets from ${a}/${$e} folder to the project assets folder if they are referenced in a code or applied changes
87
84
  </attachements>
88
- ${c}
85
+ ${l}
89
86
  </requirements>
90
87
 
91
88
  <extra_context>
@@ -97,39 +94,41 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
97
94
  - Netlify Functions directory: ${n.functionsDir}
98
95
  </metadata>
99
96
  <environment>
100
- - Node Version: ${k.version||"unknown"}
97
+ - Node Version: ${U.version||"unknown"}
101
98
  - Environment variables are set globally (e.g. \`echo $VARIABLE_NAME\` can be used to check if a var is set).
102
99
  - 'netlify-cli' npm package is already available as a global package. Don't try to install it again
103
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.
104
101
  </environment>
105
- ${I}
102
+ ${x}
106
103
  <docs>
107
104
  - Netlify Docs: https://docs.netlify.com
108
105
  - LLM Resources Index: https://docs.netlify.com/llms.txt
109
106
  </docs>
110
107
  </extra_context>
111
108
 
112
- ${g}
113
- `;return await H.writeFile(i,T,"utf-8"),O.log(`Generated agent context document at: ${i}`),T.length>5e5&&(T=`
109
+ ${d}
110
+ `;return await H.writeFile(i,I,"utf-8"),$.log(`Generated agent context document at: ${i}`),I.length>5e5&&(I=`
114
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.
115
112
 
116
113
  <request>
117
114
  <user_request>
118
115
  ${r.prompt}
119
116
  </user_request>
120
- ${l}
117
+ ${c}
121
118
  </request>
122
119
 
123
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.
124
- `),T};var Lr=w("prompt"),bt=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&&Lr.log("Contextful Prompt:",n),{prompt:n}};var Ie=w("inference_stage"),Ct=5,xe=async e=>{let{cliPath:t,config:r,context:o,buildErrors:n,runner:s,persistSteps:a,aiGateway:u,attempt:i,contextPrefix:y,priorAgentSessionId:l}=e;Ie.log(`Running inference stage, attempt ${i} of ${Ct}`);let c=await A(Ge(),"inference-stage",async g=>{g?.setAttributes({"inference.attempt":i||1}),nt();let{prompt:E}=await A(Ge(),"compose-prompt",async()=>await bt({cliPath:t,config:r,buildErrorContext:kr(n),netlify:o})),I=`
125
- ${y||""}
126
- ${E}
127
- `.trim(),T={...r,prompt:I},h=await A(Ge(),`run-${r.runner}`,async()=>await s({aiGateway:u,config:T,netlify:o,persistSteps:a,continueSession:!!(i&&i>1),priorAgentSessionId:l}));return h.result&&(h.result=j(h.result)),h.error&&(h.error=j(h.error)),await a.flush(),h});if(c.error){if(Ie.error("Runner failed",{stepsCount:c.steps.length,duration:c.duration,error:c.error,isRetryableError:c.isRetryableError,attempt:i||1,agentSessionId:c.agentSessionId}),c.isRetryableError&&(!i||i<Ct))return Ie.log("Retrying inference stage"),await new Promise(E=>setTimeout(E,5e3)),{runnerResult:(await xe({...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}},kr=e=>!e||e.length===0?"":`
121
+ `),I};var qr=E("prompt"),Ft=async({cliPath:e,config:t,netlify:r,buildErrorContext:o})=>{let n=await Ot({cliPath:e,config:t,netlify:r,buildErrorContext:o});return process.env.AGENT_RUNNER_DEBUG&&qr.log("Contextful Prompt:",n),{prompt:n}};var Te=E("inference_stage"),$t=5,Ie=async e=>{let{cliPath:t,config:r,context:o,buildErrors:n,runner:s,persistSteps:a,aiGateway:u,attempt:i,contextPrefix:m,priorAgentSessionId:c}=e;Te.log(`Running inference stage, attempt ${i} of ${$t}`);let l=await b(Be(),"inference-stage",async d=>{d?.setAttributes({"inference.attempt":i||1}),it();let{prompt:h}=await b(Be(),"compose-prompt",async()=>await Ft({cliPath:t,config:r,buildErrorContext:Kr(n),netlify:o})),x=`
122
+ ${m||""}
123
+ ${h}
124
+ `.trim(),I={...r,prompt:x},g=await b(Be(),`run-${r.runner}`,async()=>await s({aiGateway:u,config:I,netlify:o,persistSteps:a,continueSession:!!(i&&i>1),priorAgentSessionId:c}));return g.result&&(g.result=j(g.result)),g.error&&(g.error=j(g.error)),await a.flush(),g});if(l.error){if(Te.error("Runner failed",{stepsCount:l.steps.length,duration:l.duration,error:l.error,isRetryableError:l.isRetryableError,attempt:i||1,agentSessionId:l.agentSessionId}),l.isRetryableError&&(!i||i<$t))return Te.log("Retrying inference stage"),await new Promise(h=>setTimeout(h,5e3)),{runnerResult:(await Ie({...e,attempt:(i||1)+1,priorAgentSessionId:l.agentSessionId,contextPrefix:l.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 Te.log("Do not retry inference stage"),new Error(l.error)}return{runnerResult:l}},Kr=e=>!e||e.length===0?"":`
128
125
  Deploy failed failed. Here are the errors to review on the latest build:
129
126
 
130
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.
131
128
 
132
129
  ${e.pop()}
133
- `;import Gr from"process";import{getTracer as je}from"@netlify/otel";import{getTracer as Ur}from"@netlify/otel";var ce=w("deploy"),Pt=async e=>await A(Ur(),"create-preview-deploy",async t=>Mr(e,t)),Mr=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||(ce.log("Deploy: Uploading source zip"),i.push("--upload-source-zip")),n&&i.push("--alias",n),a&&i.push("--filter",a),r?(ce.log("Deploy: Skipping build"),i.push("--no-build")):i.push("--context","deploy-preview");let y=s||"netlify";ce.log(`Running: ${y} ${i.join(" ")}`),u?.setAttributes({cmd:y,args:i});let l=await e.utils.run(y,i,{stdio:["ignore","pipe","pipe"]}),c=JSON.parse(l.stdout.trim());u?.setAttributes({success:!0,deployId:c.deploy_id,deployUrl:c.deploy_url,siteId:c.site_id}),ce.log(`
134
- Preview deploy created successfully:`,{deployId:c.deploy_id,deployUrl:c.deploy_url,siteId:c.site_id});let g={deployId:c.deploy_id,previewUrl:c.deploy_url,logsUrl:c.logs,siteId:c.site_id};return t||(g.sourceZipFilename=c.source_zip_filename),g}catch(i){throw ce.error("Failed to create preview deploy via CLI:",i),u?.setAttributes({success:!1,error:i.message}),i}};var de=w("deploy_stage"),Ye=async e=>await A(je(),"run-deploy-stage",async()=>jr(e)),jr=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let s=await A(je(),"get-runner-diffs",async()=>await ft({config:t,netlify:r}));if(de.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:y}=s,l=!0;de.log("Preview deploy condition check:",{resultUndefined:o===void 0,resultType:typeof o,hasChanges:l,wouldCreatePreview:o!==void 0&&l});let c=null;if(o!==void 0&&l)try{let g;try{let E=await A(je(),"get-runner-session",async()=>await Ze(t.id,t.sessionId));E?.title&&(g=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 Pt({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:g,skipBuild:!1,deploySubdomain:dt(t.id,Gr.env.SITE_NAME),filter:n})}catch(g){return de.warn("Failed to create preview deploy (continuing with agent run):",g),{diff:a,resultDiff:u,hasChanges:l,previewInfo:null,diffBinary:i,resultDiffBinary:y,deployError:g instanceof Error?g.message:String(g)}}return de.log("Git status",{hasDiff:!!a,hasChanges:l}),{diff:a,resultDiff:u,hasChanges:l,previewInfo:c,diffBinary:i,resultDiffBinary:y}};import{getTracer as Re}from"@netlify/otel";async function Ot(e,t){let{maxRetries:r,baseDelay:o,onRetry:n}=t,s;for(let a=1;a<=r;a++)try{return await e()}catch(u){if(s=u,a===r)throw s;n&&n(a,s),await new Promise(i=>setTimeout(i,o*a))}throw s}var D=w("cleanup_stage"),$t=async e=>await A(Re(),"cleanup-stage",async()=>Yr(e)),Be=1024*1024*10,Yr=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:s,resultDiffBinary:a,previewInfo:u})=>{let i={result:r||"Done",duration:o};if(u&&u.deployId&&(i.deploy_id=u.deployId),u&&u.sourceZipFilename&&(i.result_zip_file_name=u.sourceZipFilename),t||s||n||a)try{D.log("Getting pre-signed URLs for diff upload");let l=await et(e.id,e.sessionId),c=[];(t||s)&&c.push(Ne(l.result.upload_url,s||t).then(()=>{i.result_diff_s3_key=l.result.s3_key,D.log("Successfully uploaded result_diff to S3")})),(n||a)&&c.push(Ne(l.cumulative.upload_url,a||n).then(()=>{i.cumulative_diff_s3_key=l.cumulative.s3_key,D.log("Successfully uploaded cumulative_diff to S3")})),D.log(`Uploading ${c.length} diff(s) to S3 in parallel`),await Promise.all(c),(n||a)&&(D.log("Updating agent runner with cumulative diff S3 key"),await A(Re(),"update-runner",async()=>{await ae(e.id,{result_diff_s3_key:l.cumulative.s3_key})}))}catch(l){D.error("S3 upload failed, falling back to inline diffs:",l);let c=Buffer.byteLength(t||s||""),g=Buffer.byteLength(a||n||"");if(c>Be||g>Be){let E=`Diffs exceed maximum inline size of ${Be} bytes.`;throw D.error(E),new Error(E)}i.result_diff=t,i.result_diff_binary=s,(n||a)&&(i.cumulative_diff=n,i.cumulative_diff_binary=a,D.log("Updating agent runner with inline diffs (fallback)"),await A(Re(),"update-runner",async()=>{await ae(e.id,{result_diff:n,result_diff_binary:a})}))}else D.log("No diffs to upload");return D.log("Updated agent runner with result"),await Ot(async()=>await A(Re(),"update-runner-session",()=>G(e.id,e.sessionId,i)),{maxRetries:3,baseDelay:1e3,onRetry:(l,c)=>{D.error(`Error updating agent runner session (attempt ${l}):`,c),D.log("Retrying...")}}),D.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as Dt,shutdownTracers as Hr,withActiveSpan as Ft}from"@netlify/otel";var Kr=Br(import.meta.url),Lt=Kr("../package.json"),kt=w("pipeline_index"),ve=3,ws=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:s,tracing:a={}})=>{let u,{withStageTimer:i}=ot(K.timeUnits.hours(4)),y=await Ve(Lt.version,e.id,a);try{await Ft(Dt(),"run-pipeline",{},y,async()=>{let l,{aiGateway:c,context:g,persistSteps:E,runner:I,sha:T}=await i("init",()=>At({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:s,runnerVersion:Lt.version}),K.timeUnits.minutes(10));u=I.clean,e.sha=T;let{runnerResult:h}=await i("inference",()=>xe({cliPath:r,config:e,context:g,runner:I.runner,persistSteps:E,aiGateway:c}));await G(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let x=await i("deploy",()=>Ye({cliPath:r,config:e,context:g,result:h.result,filter:s})),R=h,b=[];if(x.hasChanges&&x.deployError){b.push(Je(x.deployError));let f=1;for(;f<=ve&&!x.previewInfo;)kt.log(`Deploy attempt had errors. Retrying. ${f}/${ve}`),await Ft(Dt(),"deploy-stage",async _=>{_?.setAttributes({"stage.attempt":f});let{runnerResult:d}=await i(`inference-retry-${f}`,()=>xe({cliPath:r,config:e,context:g,runner:I.runner,persistSteps:E,aiGateway:c,buildErrors:b,priorAgentSessionId:h.agentSessionId}));R={...d,steps:[...R.steps||[],...d.steps||[]],duration:(R.duration||0)+(d.duration||0)},x=await i(`deploy-retry-${f}`,()=>Ye({cliPath:r,config:e,context:g,result:d.result,filter:s})),x.deployError&&b.push(x.deployError),f++});f>ve&&!x.previewInfo&&(l=new Error(`Deploy validation failed after ${ve} attempts`))}let{diff:N,resultDiff:v,previewInfo:S,diffBinary:m,resultDiffBinary:p}=x;if(await i("cleanup",()=>$t({config:e,diff:N,result:R.result,duration:R.duration,resultDiff:v,diffBinary:m,resultDiffBinary:p,previewInfo:S}),K.timeUnits.minutes(10)),l)throw l;process.env.NETLIFY_LOCAL_MODE||await I.clean?.()})}catch(l){kt.error("Got error while running pipeline",l),await u?.();let c=l instanceof Error&&l.message;throw await G(e.id,e.sessionId,{result:c||"Encountered error when running agent",state:"error"}),l}finally{await Hr()}};export{ws as runPipeline};
130
+ `;import Jr from"process";import{getTracer as He}from"@netlify/otel";import{getTracer as Wr}from"@netlify/otel";var ce=E("deploy"),Dt=async e=>await b(Wr(),"create-preview-deploy",async t=>Vr(e,t)),Vr=async({netlify:e,hasRepo:t,skipBuild:r,message:o="Agent Preview",deploySubdomain:n,cliPath:s,filter:a},u)=>{try{let i=["deploy","--message",`"${o}"`,"--json","--draft","--verbose"];t||(ce.log("Deploy: Uploading source zip"),i.push("--upload-source-zip")),n&&i.push("--alias",n),a&&i.push("--filter",a),r?(ce.log("Deploy: Skipping build"),i.push("--no-build")):i.push("--context","deploy-preview");let m=s||"netlify";ce.log(`Running: ${m} ${i.join(" ")}`),u?.setAttributes({cmd:m,args:i});let c=await e.utils.run(m,i,{stdio:["ignore","pipe","pipe"]}),l=JSON.parse(c.stdout.trim());u?.setAttributes({success:!0,deployId:l.deploy_id,deployUrl:l.deploy_url,siteId:l.site_id}),ce.log(`
131
+ Preview deploy created successfully:`,{deployId:l.deploy_id,deployUrl:l.deploy_url,siteId:l.site_id});let d={deployId:l.deploy_id,previewUrl:l.deploy_url,logsUrl:l.logs,siteId:l.site_id};return t||(d.sourceZipFilename=l.source_zip_filename),d}catch(i){throw ce.error("Failed to create preview deploy via CLI:",i),u?.setAttributes({success:!1,error:i.message}),i}};var pe=E("deploy_stage"),qe=async e=>await b(He(),"run-deploy-stage",async()=>Xr(e)),Xr=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let s=await b(He(),"get-runner-diffs",async()=>await ht({config:t,netlify:r}));if(pe.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:m}=s,c=!0;pe.log("Preview deploy condition check:",{resultUndefined:o===void 0,resultType:typeof o,hasChanges:c,wouldCreatePreview:o!==void 0&&c});let l=null;if(o!==void 0&&c)try{let d;try{let h=await b(He(),"get-runner-session",async()=>await tt(t.id,t.sessionId));h?.title&&(d=h.title)}catch(h){pe.warn("Failed to fetch session title, using fallback message:",h.message)}await G(t.id,t.sessionId,{steps:[{title:"Deploying the run preview"}]}),l=await Dt({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:d,skipBuild:!1,deploySubdomain:ft(t.id,Jr.env.SITE_NAME),filter:n})}catch(d){return pe.warn("Failed to create preview deploy (continuing with agent run):",d),{diff:a,resultDiff:u,hasChanges:c,previewInfo:null,diffBinary:i,resultDiffBinary:m,deployError:d instanceof Error?d.message:String(d)}}return pe.log("Git status",{hasDiff:!!a,hasChanges:c}),{diff:a,resultDiff:u,hasChanges:c,previewInfo:l,diffBinary:i,resultDiffBinary:m}};import{getTracer as Re}from"@netlify/otel";async function Lt(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 xe=class{scanDiffForForms(t){let r=[],o=null,n=[],s=t.split(`
132
+ `);for(let a of s)if(a.startsWith("diff --git")){if(o&&n.length>0){let i=this.containsNetlifyForm(n,o);i&&r.push(i)}let u=a.split(" ");o=u[u.length-1].replace(/^b\//,""),n=[]}else a.startsWith("+")&&!a.startsWith("+++")&&n.push(a.slice(1));if(o&&n.length>0){let a=this.containsNetlifyForm(n,o);a&&r.push(a)}return{detected:r.length>0,matches:r}}containsNetlifyForm(t,r){let o=t.join(`
133
+ `),n=[{pattern:/<[\w-]*form[\s\S]*?(data-)?netlify/i,name:"standard form element"},{pattern:/<[A-Z][\w]*[\s\S]*?component\s*=\s*["']form["'][\s\S]*?(data-)?netlify/i,name:"component with form prop"}];for(let{pattern:s,name:a}of n){let u=o.match(s);if(u){let i=u.index||0,m=Math.max(0,i-20),c=Math.min(o.length,i+u[0].length+20),l=o.slice(m,c).trim();return l=l.replace(/\s+/g," "),l.length>100&&(l=l.slice(0,97)+"..."),{file:r,snippet:`[${a}] ${l}`}}}return null}};var O=E("cleanup_stage"),kt=async e=>await b(Re(),"cleanup-stage",async()=>zr(e)),Ke=1024*1024*10,zr=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:s,resultDiffBinary:a,previewInfo:u})=>{let i={result:r||"Done",duration:o};u&&u.deployId&&(i.deploy_id=u.deployId),u&&u.sourceZipFilename&&(i.result_zip_file_name=u.sourceZipFilename);let m=t||s||n||a;if(m){let c=new xe,l=t||s||"",d=c.scanDiffForForms(l);d.detected&&(O.log("Detected Netlify form(s) in diff:"),d.matches.forEach(({file:h,snippet:x})=>{O.log(` - ${h}: ${x}`)}),i.has_netlify_form=!0)}if(m)try{O.log("Getting pre-signed URLs for diff upload");let c=await nt(e.id,e.sessionId),l=[];(t||s)&&l.push(Ne(c.result.upload_url,s||t).then(()=>{i.result_diff_s3_key=c.result.s3_key,O.log("Successfully uploaded result_diff to S3")})),(n||a)&&l.push(Ne(c.cumulative.upload_url,a||n).then(()=>{i.cumulative_diff_s3_key=c.cumulative.s3_key,O.log("Successfully uploaded cumulative_diff to S3")})),O.log(`Uploading ${l.length} diff(s) to S3 in parallel`),await Promise.all(l),(n||a)&&(O.log("Updating agent runner with cumulative diff S3 key"),await b(Re(),"update-runner",async()=>{await le(e.id,{result_diff_s3_key:c.cumulative.s3_key})}))}catch(c){O.error("S3 upload failed, falling back to inline diffs:",c);let l=Buffer.byteLength(t||s||""),d=Buffer.byteLength(a||n||"");if(l>Ke||d>Ke){let h=`Diffs exceed maximum inline size of ${Ke} bytes.`;throw O.error(h),new Error(h)}i.result_diff=t,i.result_diff_binary=s,(n||a)&&(i.cumulative_diff=n,i.cumulative_diff_binary=a,O.log("Updating agent runner with inline diffs (fallback)"),await b(Re(),"update-runner",async()=>{await le(e.id,{result_diff:n,result_diff_binary:a})}))}else O.log("No diffs to upload");return O.log("Updated agent runner with result"),await Lt(async()=>await b(Re(),"update-runner-session",()=>G(e.id,e.sessionId,i)),{maxRetries:3,baseDelay:1e3,onRetry:(c,l)=>{O.error(`Error updating agent runner session (attempt ${c}):`,l),O.log("Retrying...")}}),O.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as Ut,shutdownTracers as Qr,withActiveSpan as Mt}from"@netlify/otel";var en=Zr(import.meta.url),Gt=en("../package.json"),jt=E("pipeline_index"),ve=3,Ds=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:s,tracing:a={}})=>{let u,{withStageTimer:i}=at(q.timeUnits.hours(4)),m=await ze(Gt.version,e.id,a);try{await Mt(Ut(),"run-pipeline",{},m,async()=>{let c,{aiGateway:l,context:d,persistSteps:h,runner:x,sha:I}=await i("init",()=>Pt({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:s,runnerVersion:Gt.version}),q.timeUnits.minutes(10));u=x.clean,e.sha=I;let{runnerResult:g}=await i("inference",()=>Ie({cliPath:r,config:e,context:d,runner:x.runner,persistSteps:h,aiGateway:l}));await G(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let S=await i("deploy",()=>qe({cliPath:r,config:e,context:d,result:g.result,filter:s})),v=g,N=[];if(S.hasChanges&&S.deployError){N.push(Ze(S.deployError));let f=1;for(;f<=ve&&!S.previewInfo;)jt.log(`Deploy attempt had errors. Retrying. ${f}/${ve}`),await Mt(Ut(),"deploy-stage",async T=>{T?.setAttributes({"stage.attempt":f});let{runnerResult:p}=await i(`inference-retry-${f}`,()=>Ie({cliPath:r,config:e,context:d,runner:x.runner,persistSteps:h,aiGateway:l,buildErrors:N,priorAgentSessionId:g.agentSessionId}));v={...p,steps:[...v.steps||[],...p.steps||[]],duration:(v.duration||0)+(p.duration||0)},S=await i(`deploy-retry-${f}`,()=>qe({cliPath:r,config:e,context:d,result:p.result,filter:s})),S.deployError&&N.push(S.deployError),f++});f>ve&&!S.previewInfo&&(c=new Error(`Deploy validation failed after ${ve} attempts`))}let{diff:R,resultDiff:_,previewInfo:A,diffBinary:w,resultDiffBinary:y}=S;if(await i("cleanup",()=>kt({config:e,diff:R,result:v.result,duration:v.duration,resultDiff:_,diffBinary:w,resultDiffBinary:y,previewInfo:A}),q.timeUnits.minutes(10)),c)throw c;process.env.NETLIFY_LOCAL_MODE||(await u?.(),await wt())})}catch(c){jt.error("Got error while running pipeline",c),await u?.();let l=c instanceof Error&&c.message;throw await G(e.id,e.sessionId,{result:l||"Encountered error when running agent",state:"error"}),c}finally{await Qr()}};export{Ds as runPipeline};
135
134
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@netlify/agent-runner-cli",
3
3
  "type": "module",
4
- "version": "1.47.1",
4
+ "version": "1.48.0",
5
5
  "description": "CLI tool for running Netlify agents",
6
6
  "main": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
@@ -72,13 +72,13 @@
72
72
  "vitest": "^1.5.0"
73
73
  },
74
74
  "dependencies": {
75
- "@anthropic-ai/claude-code": "2.0.22",
75
+ "@anthropic-ai/claude-code": "2.0.42",
76
76
  "@google/gemini-cli": "0.1.17",
77
77
  "@netlify/otel": "^4.3.2",
78
- "@openai/codex": "0.55.0",
79
78
  "@opentelemetry/exporter-trace-otlp-grpc": "^0.57.0",
80
79
  "execa": "^8.0.0",
81
80
  "get-port": "^5.1.1",
82
- "minimist": "^1.2.8"
81
+ "minimist": "^1.2.8",
82
+ "my-codex-no-sandbox": "^0.1.2505290819"
83
83
  }
84
84
  }