@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/bin.js CHANGED
@@ -1,64 +1,61 @@
1
1
  #!/usr/bin/env node
2
- import ze from"process";import pn from"minimist";import{createRequire as nn}from"module";import{createTracerProvider as Zt}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as Qe}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as Qt}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as er}from"@netlify/otel";import{propagation as et,context as tt,W3CTraceContextPropagator as tr}from"@netlify/otel/opentelemetry";import{OTLPTraceExporter as rr}from"@opentelemetry/exporter-trace-otlp-grpc";function y(e){let t=!process.env.VITEST;return{log:(...r)=>{t&&console.log(`[AR]-[${e}]`,...r)},error:(...r)=>{t&&console.error(`[AR]-[ERROR]-[${e}]`,...r)},warn:(...r)=>{t&&console.warn(`[AR]-[WARN]-[${e}]`,...r)},info:(...r)=>{t&&console.info(`[AR]-[${e}]`,...r)},debug:(...r)=>{t&&console.debug(`[AR]-[DEBUG]-[${e}]`,...r)}}}var be=y("tracing"),rt=async(e,t,r)=>(await Zt({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new Qe(new Ce),new Qe(new rr({url:r.exporterUrl}))],instrumentations:[new Qt({skipHeaders:!0})]}),r.traceparent?(et.setGlobalPropagator(new tr),et.extract(tt.active(),{traceparent:r.traceparent,isRemote:!0})):tt.active());function A(e,t,r){return be.log(`\u23F3 TRACE: ${t} starting...`),er(e,t,r)}var Ce=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(", ")}]`:"";be.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${a}`),t.status?.code===2&&t.status.message&&be.log(` \u274C Error: ${t.status.message}`)}};var nr=["error","failed","exception","fatal","panic","abort","crash"];function nt(e){let t=e.split(`
3
- `),r=[],o=-1,n=0;for(;n<t.length;){let u=t[n].slice(0,500).toLowerCase();if(nr.some(E=>u.includes(E))){let E=Math.max(0,n-10,o+1),l=Math.min(t.length-1,n+20),c=[];for(let g=E;g<=l;g++)c.push(t[g]);r.push(c.join(`
4
- `)),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}">
2
+ import et from"process";import wn from"minimist";import{createRequire as fn}from"module";import{createTracerProvider as rr}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as rt}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as nr}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as or}from"@netlify/otel";import{propagation as nt,context as ot,W3CTraceContextPropagator as sr}from"@netlify/otel/opentelemetry";import{OTLPTraceExporter as ir}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 Ce=E("tracing"),st=async(e,t,r)=>(await rr({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new rt(new be),new rt(new ir({url:r.exporterUrl}))],instrumentations:[new nr({skipHeaders:!0})]}),r.traceparent?(nt.setGlobalPropagator(new sr),nt.extract(ot.active(),{traceparent:r.traceparent,isRemote:!0})):ot.active());function C(e,t,r){return Ce.log(`\u23F3 TRACE: ${t} starting...`),or(e,t,r)}var be=class{export(t,r){for(let o of t)this.logSpan(o);r({code:1})}async shutdown(){}forceFlush(){return Promise.resolve()}logSpan(t){let r=(t.endTime[0]-t.startTime[0])*1e3+(t.endTime[1]-t.startTime[1])/1e6,o=t.attributes,n=[];for(let[l,i]of Object.entries(o))l.includes("duration")&&typeof i=="number"?n.push(`${l}=${i.toFixed(2)}ms`):n.push(`${l}=${i}`);let s=t.status?.code===2?"\u274C":"\u2705",a=n.length>0?` [${n.join(", ")}]`:"";Ce.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${a}`),t.status?.code===2&&t.status.message&&Ce.log(` \u274C Error: ${t.status.message}`)}};var ar=["error","failed","exception","fatal","panic","abort","crash"];function it(e){let t=e.split(`
3
+ `),r=[],o=-1,n=0;for(;n<t.length;){let l=t[n].slice(0,500).toLowerCase();if(ar.some(f=>l.includes(f))){let f=Math.max(0,n-10,o+1),c=Math.min(t.length-1,n+20),u=[];for(let d=f;d<=c;d++)u.push(t[d]);r.push(u.join(`
4
+ `)),o=c,n=c+1}else n++}if(r.length===0)return e;let s=r.map((a,l)=>`<extracted_error_chunk order="${l+1}">
5
5
  ${a}
6
6
  </extracted_error_chunk>`).join(`
7
7
 
8
- `);return s.length>e.length*.8?e:s}import Re from"process";import{getTracer as Mr}from"@netlify/otel";import ae from"process";var ge=ae.env.NETLIFY_API_URL,me=ae.env.NETLIFY_API_TOKEN,G=y("api"),he=()=>ae.env.NETLIFY_LOCAL_MODE==="true",le=async(e,t={})=>{if(!ge||!me)throw new Error("No API URL or token");let r=new URL(e,ge),o={...t,headers:{...t.headers,Authorization:`Bearer ${me}`}};ae.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let n=await fetch(r,o),s=n.ok&&n.status<=299;if(ae.env.AGENT_RUNNERS_DEBUG==="true")G.log(`Response headers for ${r}:`),n.headers.forEach((u,i)=>{G.log(` ${i}: ${u}`)});else{let u=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");G.log(`Request ID for ${r}: ${u||"N/A"}`)}if(s||G.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},ot=e=>{G.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(ge=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(me=e.constants.NETLIFY_API_TOKEN)},st=()=>({apiUrl:ge,token:me}),ue=async(e,t)=>he()?(G.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):le(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),j=async(e,t,r)=>he()?(G.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):le(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var it=async(e,t)=>he()?(G.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):le(`/api/v1/agent_runners/${e}/sessions/${t}`),at=(e,t,r)=>le(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}}),lt=async(e,t)=>he()?(G.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"}}):le(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Pe=async(e,t)=>{G.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 Z=y("ai_gateway"),Oe=null;var ut=async()=>{if(Oe)return Oe;Z.log("Fetching available AI gateway providers");let e=await fetch(`${st().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 Oe=t,Z.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},or=async(e,t)=>{let o=(await ut()).providers[e];if(!o)return Z.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return Z.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},ct=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),Z.log("Requesting AI gateway information");let i=await at(a,t.id,t.sessionId);if({token:r,url:s}=i,o=i.expires_at?i.expires_at*1e3:void 0,Z.log("Got AI gateway information",{token:!!r,expiresAt:o,url:s}),o){let E=o-Date.now()-6e4;E>0&&(n=setTimeout(()=>{u()},E))}};return await Promise.all([u(),ut()]),{get url(){return s},get token(){return r},isModelAvailableForProvider:or}};import B from"process";import Ee from"path";import Le from"fs";import{fileURLToPath as cr}from"url";import{execa as dr,execaCommand as Un}from"execa";import{Transform as sr}from"stream";var ir=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"]),ar=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function lr(){return Object.entries(process.env).filter(([e,t])=>!(!t||ir.has(e)||ar.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function Y(e){if(typeof e!="string")return e;let t=lr();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(ur(o),"g");r=r.replace(n,"******")}),r}function ur(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Q=class extends sr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),s=Y(n);o(null,s)}};function dt(){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"?Y(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"?Y(o):o;return typeof n=="function"?r(a,n):r(a,n,s)}}var ce=null,pt=e=>(ce&&ce.destroy(),ce=new q({totalAllowedTime:e}),ce),ft=()=>ce;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 pr=cr(import.meta.url),fr=Ee.dirname(pr),_e=y("shell"),Fe=new Set,gr={preferLocal:!0},gt=(e,t,r)=>{let[o,n]=mr(t,r),s={...gr,...n},a=dr(e,o,s);return hr(a,s),_r(a),a};var mr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},hr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(B.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new Q).pipe(B.stdout),e.stdout?.pipe(new Q).pipe(B.stdout),e.stderr?.pipe(new Q).pipe(B.stderr);return}e.stdout?.pipe(B.stdout),e.stderr?.pipe(B.stderr)},mt=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(B.kill(-e.pid,t),_e.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return _e.error("Error killing process:",r),!1}},Er=e=>mt(e,"SIGKILL"),_r=e=>{Fe.add(e);let t=ft();if(t){let r=t.onTimesUp(()=>{_e.log(`Global timer expired, killing process ${e.pid}`),mt(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(_e.log(`Force killing process ${e.pid} after timeout`),Er(e))},5e3)});e.on("exit",()=>{Fe.delete(e),r()}),e.on("error",()=>{Fe.delete(e),r()})}};function ee(e,t){if(B.env.NODE_PATH){let n=Ee.join(B.env.NODE_PATH,".bin",t);if(Le.existsSync(n))return n}let r=Ee.join(e,"node_modules",".bin",t);if(Le.existsSync(r))return r;let o=Ee.join(fr,"..","node_modules",".bin",t);if(Le.existsSync(o))return o}var ht="netlify-agent-runner-context.md",De="task-history",$e="netlify-context",$=".netlify",te="results.md",ke="assets",Ue="other",Ge="personal";var Me="enterprise",je="free",Et=[Ge,"pro",Me,je];var _t=y("utils"),yr=e=>new Promise(t=>{setTimeout(t,e)}),yt=(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,E=new Promise(l=>{i=l});return s=(async()=>{await Promise.resolve();let l=await e(...u);for(i(l);;){if(await yr(t),!o)return r=!1,s=null,l;let c=o,g=n;o=null,n=[],l=await e(...c),g.forEach(_=>{_(l)})}})(),E};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},Te=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):_t.error("Could not parse JSON",o))}},Tt=(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 E=Math.min(i-s.length,e.length);return`${s}${e.slice(0,E)}`}return e.slice(0,i)},Tr=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!Et.some(t=>t in e),wt=()=>{let e={},t={codex:process.env.NETLIFY_FF_AGENT_RUNNER_CODEX_VERSION,claude:process.env.NETLIFY_FF_AGENT_RUNNER_CLAUDE_VERSION,gemini:process.env.NETLIFY_FF_AGENT_RUNNER_GEMINI_VERSION};return Object.entries(t).forEach(([r,o])=>{if(o){let n=`NETLIFY_FF_AGENT_RUNNER_${r.toUpperCase()}_VERSION`;try{let s=JSON.parse(o);Tr(s)&&(e[r]=s)}catch(s){let u=s instanceof SyntaxError?"Invalid JSON":s.message;_t.error(`Could not parse ${r} model version override from ${n}: ${u}`)}}}),e};import{Buffer as It}from"buffer";import wr from"path";var Rt=async({config:e,netlify:t})=>{let r=await Rr(t),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};let s=await xr(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=It.from(h).toString("base64"))}let _={hasChanges:!0,diff:i,resultDiff:c,ignored:s};return i!==l&&(_.diffBinary=It.from(l).toString("base64")),g&&(_.resultDiffBinary=g),_},Ir=["?? mise.toml","?? deno.lock","?? .npmrc",/\?\? .+?\.log/],Rr=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
9
- `).filter(n=>!Ir.some(s=>s instanceof RegExp?s.test(n):n===s))).length!==0,status:t.stdout}};var xt=async e=>{let{stdout:t}=await e.utils.run("git",["rev-parse","HEAD"]);return t.trim()},Nt=async e=>{let{stdout:t}=await e.utils.run("git",["rev-list","--max-parents=0","HEAD"]);return t.trim()},xr=async e=>{let t=[".netlify","mise.toml","deno.lock",".npmrc","node_modules"],r=[];return e.split(`
10
- `).forEach(o=>{t.forEach(s=>{[`?? ${s}`,`?? ${s}${wr.sep}`].some(u=>o.startsWith(u))&&r.push(`:!${s}`)});let n=o.match(/\?\? (.+?)\.log$/)?.[1];n&&r.push(`:!${n}.log`)}),r};import vr from"fs/promises";import Ar from"os";import St from"path";import W from"process";import Sr from"readline";import Ye from"path";import Nr from"fs/promises";var Be=y("agent-output-utils");async function re({initialResult:e,agentName:t,hasError:r}){let o="",n=Ye.join(process.cwd(),$,te);try{let s=await Nr.readFile(n,"utf-8");s&&(o=s,Be.log(`Pulled result from ${Ye.relative(process.cwd(),n)}`))}catch{Be.log(`No results file found at ${Ye.relative(process.cwd(),n)}`)}return o||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function ne({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&&Be.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function oe(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=y("runner_claude"),vt="Claude Code",we="claude-sonnet-4-5-20250929",At=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,br=({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 He({config:e,netlify:t,persistSteps:r,aiGateway:o,continueSession:n,priorAgentSessionId:s}){let a=e,{accountType:u,prompt:i,modelVersionOverrides:E}=a,{model:l}=a,c="";if(o){let{token:f,url:T}=o;if(!f||!T)throw new Error("No token or url provided from AI Gateway");if(E?.claude){let d=E?.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",we)?(l=we,k.log(`Using default model: ${we}`)):k.log(`Default model ${we} is not available, proceeding without model specification`);W.env.ANTHROPIC_API_KEY=f,W.env.ANTHROPIC_BASE_URL=T}else if(!W.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let g=[],_=[],I={},w=0,h=0,R,x,b=[ee(W.cwd(),"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...l?["--model",l]:[],...n?["--continue"]:[],...n&&s?["--resume",s]:[],"-p",i],S=`${W.env.NVM_BIN}/node`;k.log(`Running ${S} ${b.join(" ")}`);let N=t.utils.run(S,b,{all:!0,env:W.env});N.stdin?.end();let v=ye(()=>{r?.({steps:g,duration:h})},250),m=(f,T)=>{let d={...f,id:w};w+=1,_.push(d),g.push(d),T||v.flush(),v(),T&&v.flush()},p=Sr.createInterface({input:N.all});return p.on("error",f=>{k.error("Readline interface error",{error:f.message,stack:f.stack})}),p.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!==c&&(c=T.session_id),Array.isArray(T?.message?.content)?T.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})`}):k.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:[At(d.name),C].filter(Boolean).join(" ")})}else d.id&&(I[d.id]=d);v.flush();break}case"tool_result":{let C=d.tool_use_id?I[d.tool_use_id]:void 0,ie;if(C){let z=C.input?.file_path&&St.relative(W.cwd(),C.input.file_path),P=z&&`\`${z}\``;ie=[At(C.name||""),P].filter(Boolean).join(" ")}let Ze=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(C?.name||""),H;if(typeof d.content=="string")H=d.content;else if(Array.isArray(d.content)){let z=[];d.content.forEach(P=>{P?.type==="text"&&typeof P.text=="string"?z.push(P.text):P?.type==="image"&&typeof P.source=="object"&&P.source?P.source.type==="base64"&&P.source.media_type?z.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}`)}),H=z.join(`
8
+ `);return s.length>e.length*.8?e:s}import Ie from"process";import{getTracer as Vr}from"@netlify/otel";import le from"process";var ge=le.env.NETLIFY_API_URL,me=le.env.NETLIFY_API_TOKEN,G=E("api"),he=()=>le.env.NETLIFY_LOCAL_MODE==="true",ue=async(e,t={})=>{if(!ge||!me)throw new Error("No API URL or token");let r=new URL(e,ge),o={...t,headers:{...t.headers,Authorization:`Bearer ${me}`}};le.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let n=await fetch(r,o),s=n.ok&&n.status<=299;if(le.env.AGENT_RUNNERS_DEBUG==="true")G.log(`Response headers for ${r}:`),n.headers.forEach((l,i)=>{G.log(` ${i}: ${l}`)});else{let l=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");G.log(`Request ID for ${r}: ${l||"N/A"}`)}if(s||G.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},at=e=>{G.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(ge=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(me=e.constants.NETLIFY_API_TOKEN)},lt=()=>({apiUrl:ge,token:me}),ce=async(e,t)=>he()?(G.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):ue(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),j=async(e,t,r)=>he()?(G.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):ue(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var ut=async(e,t)=>he()?(G.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):ue(`/api/v1/agent_runners/${e}/sessions/${t}`),ct=(e,t,r)=>ue(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}}),pt=async(e,t)=>he()?(G.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"}}):ue(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Pe=async(e,t)=>{G.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 Z=E("ai_gateway"),Oe=null;var dt=async()=>{if(Oe)return Oe;Z.log("Fetching available AI gateway providers");let e=await fetch(`${lt().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 Oe=t,Z.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},lr=async(e,t)=>{let o=(await dt()).providers[e];if(!o)return Z.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return Z.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},ft=async({netlify:e,config:t})=>{let r,o,n,s,a=e.constants?.SITE_ID;if(!a)throw new Error("No site id");let l=async()=>{clearTimeout(n),Z.log("Requesting AI gateway information");let i=await ct(a,t.id,t.sessionId);if({token:r,url:s}=i,o=i.expires_at?i.expires_at*1e3:void 0,Z.log("Got AI gateway information",{token:!!r,expiresAt:o,url:s}),o){let f=o-Date.now()-6e4;f>0&&(n=setTimeout(()=>{l()},f))}};return await Promise.all([l(),dt()]),{get url(){return s},get token(){return r},isModelAvailableForProvider:lr}};import B from"process";import Ee from"path";import Fe from"fs";import{fileURLToPath as gr}from"url";import{execa as mr,execaCommand as Kn}from"execa";import{Transform as ur}from"stream";var cr=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"]),pr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function dr(){return Object.entries(process.env).filter(([e,t])=>!(!t||cr.has(e)||pr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function Y(e){if(typeof e!="string")return e;let t=dr();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(fr(o),"g");r=r.replace(n,"******")}),r}function fr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Q=class extends ur{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),s=Y(n);o(null,s)}};function gt(){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"?Y(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"?Y(o):o;return typeof n=="function"?r(a,n):r(a,n,s)}}var pe=null,mt=e=>(pe&&pe.destroy(),pe=new q({totalAllowedTime:e}),pe),ht=()=>pe;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((l,i)=>{s=setTimeout(()=>{i(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return a?await Promise.race([r(),a]):await r()}finally{n(),s&&clearTimeout(s)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var hr=gr(import.meta.url),Er=Ee.dirname(hr),ye=E("shell"),Le=new Set,yr={preferLocal:!0},F=(e,t,r)=>{let[o,n]=_r(t,r),s={...yr,...n},a=mr(e,o,s);return Tr(a,s),Ir(a),a};var _r=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Tr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(B.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new Q).pipe(B.stdout),e.stdout?.pipe(new Q).pipe(B.stdout),e.stderr?.pipe(new Q).pipe(B.stderr);return}e.stdout?.pipe(B.stdout),e.stderr?.pipe(B.stderr)},Et=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(B.kill(-e.pid,t),ye.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return ye.error("Error killing process:",r),!1}},wr=e=>Et(e,"SIGKILL"),Ir=e=>{Le.add(e);let t=ht();if(t){let r=t.onTimesUp(()=>{ye.log(`Global timer expired, killing process ${e.pid}`),Et(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ye.log(`Force killing process ${e.pid} after timeout`),wr(e))},5e3)});e.on("exit",()=>{Le.delete(e),r()}),e.on("error",()=>{Le.delete(e),r()})}};function ee(e,t){if(B.env.NODE_PATH){let n=Ee.join(B.env.NODE_PATH,".bin",t);if(Fe.existsSync(n))return n}let r=Ee.join(e,"node_modules",".bin",t);if(Fe.existsSync(r))return r;let o=Ee.join(Er,"..","node_modules",".bin",t);if(Fe.existsSync(o))return o}var yt="netlify-agent-runner-context.md",De="task-history",$e="netlify-context",k=".netlify",te="results.md",ke="assets",Ue="other",Me="personal";var Ge="enterprise",je="free",_t=[Me,"pro",Ge,je];var Tt=E("utils"),Rr=e=>new Promise(t=>{setTimeout(t,e)}),wt=(e,t=3e3)=>{let r=!1,o=null,n=[],s=null,a=(...l)=>{if(r)return o=l,new Promise(c=>{n.push(c)});r=!0;let i,f=new Promise(c=>{i=c});return s=(async()=>{await Promise.resolve();let c=await e(...l);for(i(c);;){if(await Rr(t),!o)return r=!1,s=null,c;let u=o,d=n;o=null,n=[],c=await e(...u),d.forEach(h=>{h(c)})}})(),f};return a.flush=async()=>{if((r||o)&&s)return await s,a.flush()},a},_e=(e,t,r=!1)=>{let o=null,n=null,s=null,a=function(...l){n=l,s=this;let i=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(s,n),n=null,s=null)},t),i&&(e.apply(s,n),n=null,s=null)};return a.cancel=()=>{clearTimeout(o),o=null,n=null,s=null},a.flush=()=>{if(o){clearTimeout(o);let l=n,i=s;o=null,n=null,s=null,e.apply(i,l)}},a},Te=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):Tt.error("Could not parse JSON",o))}},It=(e,t)=>{let n=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let l=`--${t}${n}`;if(l.length>55)return"";let i=60-l.length;if(i<=0)return"";if(i>=s.length+6){let f=Math.min(i-s.length,e.length);return`${s}${e.slice(0,f)}`}return e.slice(0,i)},Nr=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!_t.some(t=>t in e),Rt=()=>{let e={},t={codex:process.env.NETLIFY_FF_AGENT_RUNNER_CODEX_VERSION,claude:process.env.NETLIFY_FF_AGENT_RUNNER_CLAUDE_VERSION,gemini:process.env.NETLIFY_FF_AGENT_RUNNER_GEMINI_VERSION};return Object.entries(t).forEach(([r,o])=>{if(o){let n=`NETLIFY_FF_AGENT_RUNNER_${r.toUpperCase()}_VERSION`;try{let s=JSON.parse(o);Nr(s)&&(e[r]=s)}catch(s){let l=s instanceof SyntaxError?"Invalid JSON":s.message;Tt.error(`Could not parse ${r} model version override from ${n}: ${l}`)}}}),e};import{Buffer as Nt}from"buffer";import xr from"path";var xt=E("repo"),vt=async({config:e})=>{xt.info("Getting runner diffs");let t=await Ar(),{hasChanges:r}=t,{status:o}=t;if(!r)return{hasChanges:!1};let n=Sr(o);await Cr(n),xt.info("Changes after processing"),await Be();let s=await He(o);await Ye(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,u,d;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await F("git",["commit","-m","Agent runner"]),u=(await F("git",["diff",e.sha,"HEAD"],a)).stdout;let g=(await F("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;u!==g&&(d=Nt.from(g).toString("base64"))}let h={hasChanges:!0,diff:i,resultDiff:u,ignored:s};return i!==c&&(h.diffBinary=Nt.from(c).toString("base64")),d&&(h.resultDiffBinary=d),h},Ye=async(e=[])=>{await F("git",["add",".",...e])},Be=async()=>(await F("git",["status","-s"])).stdout,At=/.. (.+)?\.log$/,vr=[At],Ar=async()=>{let e=await Be();return{hasChanges:(e.trim().length===0?[]:e.split(`
9
+ `).filter(o=>vr.some(s=>s instanceof RegExp?s.test(o):o===s)?!1:o[1]?.trim()!=="")).length!==0,status:e}},St=async()=>{let{stdout:e}=await F("git",["rev-parse","HEAD"]);return e.trim()},Ct=async()=>{let{stdout:e}=await F("git",["rev-list","--max-parents=0","HEAD"]);return e.trim()},He=async e=>{e||=await Be();let t=[".netlify","node_modules"],r=[];return e.split(`
10
+ `).forEach(o=>{t.forEach(s=>{[`?? ${s}`,`?? ${s}${xr.sep}`].some(l=>o.startsWith(l))&&r.push(`:!${s}`)});let n=o.match(At)?.[1];n&&r.push(`:!${n}.log`)}),r},bt=async()=>{await F("git",["reset","--hard","HEAD"])},Sr=e=>{let t=e.split(`
11
+ `).reduce((r,o)=>{if(!o)return r;let[n,s,,...a]=o,l=a.join(""),i=n.trim(),f=s.trim();return r[l]?r[l].change=f:r[l]={filePath:l,stage:i,change:f},r},{});return Object.values(t)},Cr=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 Pr from"fs/promises";import Or from"os";import Ft from"path";import K from"process";import Fr from"readline";import We from"path";import br from"fs/promises";var qe=E("agent-output-utils");async function re({initialResult:e,agentName:t,hasError:r}){let o="",n=We.join(process.cwd(),k,te);try{let s=await br.readFile(n,"utf-8");s&&(o=s,qe.log(`Pulled result from ${We.relative(process.cwd(),n)}`))}catch{qe.log(`No results file found at ${We.relative(process.cwd(),n)}`)}return o||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function ne({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&&qe.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function oe(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 U=E("runner_claude"),Pt="Claude Code",we="claude-sonnet-4-5-20250929",Ot=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,Lr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(U.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?(U.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}):(U.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:l,prompt:i,modelVersionOverrides:f}=a,{model:c}=a,u="";if(o){let{token:m,url:I}=o;if(!m||!I)throw new Error("No token or url provided from AI Gateway");if(f?.claude){let p=f?.claude?.[l];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",we)?(c=we,U.log(`Using default model: ${we}`)):U.log(`Default model ${we} is not available, proceeding without model specification`);K.env.ANTHROPIC_API_KEY=m,K.env.ANTHROPIC_BASE_URL=I}else if(!K.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let d=[],h=[],R={},w=0,g=0,N,v,S=[ee(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],x=`${K.env.NVM_BIN}/node`;U.log(`Running ${x} ${S.join(" ")}`);let _=t.utils.run(x,S,{all:!0,env:K.env});_.stdin?.end();let A=_e(()=>{r?.({steps:d,duration:g})},250),T=(m,I)=>{let p={...m,id:w};w+=1,h.push(p),d.push(p),I||A.flush(),A(),I&&A.flush()},y=Fr.createInterface({input:_.all});return y.on("error",m=>{U.error("Readline interface error",{error:m.message,stack:m.stack})}),y.on("line",m=>{let I=null;try{I=JSON.parse(m)}catch{U.log("Could not parse line",m)}I?.session_id&&I.session_id!==u&&(u=I.session_id),Array.isArray(I?.message?.content)?I.message.content.forEach(p=>{switch(p.type){case"text":{p.text&&T({message:p.text});break}case"image":{typeof p.source=="object"&&p.source&&p.source.type==="base64"&&p.source.media_type?T({message:`![](data:${p.source.media_type};base64,${p.source.data})`}):U.log(`Unsupported image type ${p.source?.type}`,p.source);break}case"tool_use":{if(p.name==="Task"){let b=p.input?.description&&`\`${p.input.description}\``;T({title:[Ot(p.name),b].filter(Boolean).join(" ")})}else p.id&&(R[p.id]=p);A.flush();break}case"tool_result":{let b=p.tool_use_id?R[p.tool_use_id]:void 0,ae;if(b){let z=b.input?.file_path&&Ft.relative(K.cwd(),b.input.file_path),P=z&&`\`${z}\``;ae=[Ot(b.name||""),P].filter(Boolean).join(" ")}let tt=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(b?.name||""),H;if(typeof p.content=="string")H=p.content;else if(Array.isArray(p.content)){let z=[];p.content.forEach(P=>{P?.type==="text"&&typeof P.text=="string"?z.push(P.text):P?.type==="image"&&typeof P.source=="object"&&P.source?P.source.type==="base64"&&P.source.media_type?z.push(`![](data:${P.source.media_type};base64,${P.source.data})`):U.log(`Unsupported image type ${P.source.type}`,P.source):U.log(`Unsupported block type ${P?.type}`)}),H=z.join(`
11
12
 
12
- `)}Ze&&H&&(H=`\`\`\`
13
+ `)}tt&&H&&(H=`\`\`\`
13
14
  ${H.trim()}
14
- \`\`\``),m({title:ie,message:H},!0);break}case"thinking":{d.thinking&&m({title:"Thinking",message:d.thinking},!0);break}default:k.log(`Message content type is not supported ${d.type}`,d)}}):T?.type==="result"&&(h=T.duration_ms||0,T.is_error?x=T.result:R=T.result,[_,g].forEach(d=>{d[d.length-1]?.message===R&&d.pop()}))}),await N.catch(f=>{({error:x,result:R}=br({catchError:f,runCmd:N,error:x,result:R,runnerName:"Claude"}))}),p.close(),v.flush(),{steps:_,duration:h,result:await re({initialResult:R,agentName:vt,hasError:!!x}),error:ne({error:x,agentName:vt}),isRetryableError:oe(x),agentSessionId:c}}var bt=async()=>{let e=St.join(Ar.homedir(),".claude");await vr.rm(e,{recursive:!0,force:!0})};import de from"fs/promises";import Pt from"os";import Ie from"path";import V from"process";import Cr from"readline";var M=y("runner_codex"),Ct="Codex CLI",Pr=({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 Ke({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`);V.env.OPENAI_API_KEY=m,V.env.OPENAI_BASE_URL=p}else if(!V.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let E=[],l=[],c={},g=0,_=0,I,w,h=`${V.env.NVM_BIN}/node`,R=Ie.join(Pt.homedir(),".codex"),x=Ie.join(R,"config.toml"),b=Ie.join(R,"auth.json");try{await de.mkdir(R,{recursive:!0});let m={OPENAI_API_KEY:V.env.OPENAI_API_KEY};await de.writeFile(b,JSON.stringify(m,null,2),"utf-8"),M.log("Created Codex auth.json file");let p="";try{p=await de.readFile(x,"utf-8")}catch{}p.includes("web_search")||(p.includes("[tools]")?p=p.replace(/\[tools\]/,`[tools]
15
- web_search = true`):p+=`
16
- [tools]
17
- web_search = true
18
- `,await de.writeFile(x,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 S=[ee(V.cwd(),"codex"),"exec","--yolo","--json","--config","web_search=true",...i?["--model",i]:[],a].filter(Boolean);M.log(`Running ${h} ${S.join(" ")}`);let N=t.utils.run(h,S,{all:!0,env:{...V.env}}),v=Cr.createInterface({input:N.all});return v.on("error",m=>{M.error("Readline interface error",{error:m.message,stack:m.stack})}),v.on("line",m=>{let p=null;try{p=JSON.parse(m)}catch{M.log("Could not parse line",m);return}let f=[],T=!1;if(p?.duration_ms&&(_=p.duration_ms,T=!0),p?.type==="local_shell_call")c[p.call_id]=p;else if(p?.type==="local_shell_call_output"){let d=Lr(c[p.call_id],p);d&&(d.id=g,g+=1,l.push(d),E.push(d),f.push(d),T=!0)}else p?.type==="message"&&p.role==="assistant"?I=p.content.map(d=>d.text).join(`
19
- `):p?.type==="message"&&p.role==="system"&&(w=p.content.map(d=>d.text).join(`
20
- `));T&&(r?.({steps:E,duration:_}),o?.({steps:f,duration:_}))}),await N.catch(m=>{let p=Pr({catchError:m,runCmd:N,error:w,result:I,runnerName:"Codex"});w=p.error,I=p.result}),v.close(),{steps:l,duration:_,result:await re({initialResult:I,agentName:Ct,hasError:!!w}),error:ne({error:w,agentName:Ct}),isRetryableError:oe(w)}}var Ot=async()=>{let e=Ie.join(Pt.homedir(),".codex");await de.rm(e,{recursive:!0,force:!0})},Or=new Set(["bash","-lc"]),Lr=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!Or.has(s)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
15
+ \`\`\``),T({title:ae,message:H},!0);break}case"thinking":{p.thinking&&T({title:"Thinking",message:p.thinking},!0);break}default:U.log(`Message content type is not supported ${p.type}`,p)}}):I?.type==="result"&&(g=I.duration_ms||0,I.is_error?v=I.result:N=I.result,[h,d].forEach(p=>{p[p.length-1]?.message===N&&p.pop()}))}),await _.catch(m=>{({error:v,result:N}=Lr({catchError:m,runCmd:_,error:v,result:N,runnerName:"Claude"}))}),y.close(),A.flush(),{steps:h,duration:g,result:await re({initialResult:N,agentName:Pt,hasError:!!v}),error:ne({error:v,agentName:Pt}),isRetryableError:oe(v),agentSessionId:u}}var Lt=async()=>{let e=Ft.join(Or.homedir(),".claude");await Pr.rm(e,{recursive:!0,force:!0})};import Dr from"fs/promises";import $r from"os";import kr from"path";import se from"process";import Ur from"readline";var V=E("runner_codex"),Dt="Codex CLI",Mr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(V.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(V.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(V.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function Ve({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:a,modelVersionOverrides:l}=e,{model:i}=e;if(n){let{token:x,url:_}=n;if(!x||!_)throw new Error("No token or url provided from AI Gateway");if(l?.codex){let A=l?.codex?.[s];if(A){if(!await n.isModelAvailableForProvider("openai",A))throw new Error(`Model override '${A}' is not available for openai provider`);i=A}}else if(i&&!await n.isModelAvailableForProvider("openai",i))throw new Error(`Model '${i}' is not available for openai provider`);se.env.OPENAI_API_KEY=x,se.env.OPENAI_BASE_URL=_}else if(!se.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let f=[],c=[],u={},d=0,h=0,R,w,g=[ee(se.cwd(),"codex"),"--approval-mode","full-auto",n?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...i?["--model",i]:[],"-q",a].filter(Boolean),N=`${se.env.NVM_BIN}/node`;V.log(`Running ${N} ${g.join(" ")}`);let v=t.utils.run(N,g,{all:!0,env:{...se.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),S=Ur.createInterface({input:v.all});return S.on("error",x=>{V.error("Readline interface error",{error:x.message,stack:x.stack})}),S.on("line",x=>{let _=null;try{_=JSON.parse(x)}catch{V.log("Could not parse line",x);return}let A=[],T=!1;if(_?.duration_ms&&(h=_.duration_ms,T=!0),_?.type==="local_shell_call")u[_.call_id]=_;else if(_?.type==="local_shell_call_output"){let y=jr(u[_.call_id],_);y&&(y.id=d,d+=1,c.push(y),f.push(y),A.push(y),T=!0)}else _?.type==="message"&&_.role==="assistant"?R=_.content.map(y=>y.text).join(`
16
+ `):_?.type==="message"&&_.role==="system"&&(w=_.content.map(y=>y.text).join(`
17
+ `));T&&(r?.({steps:f,duration:h}),o?.({steps:A,duration:h}))}),await v.catch(x=>{let _=Mr({catchError:x,runCmd:v,error:w,result:R,runnerName:"Codex"});w=_.error,R=_.result}),S.close(),{steps:c,duration:h,result:await re({initialResult:R,agentName:Dt,hasError:!!w}),error:ne({error:w,agentName:Dt}),isRetryableError:oe(w)}}var $t=async()=>{let e=kr.join($r.homedir(),".codex");await Dr.rm(e,{recursive:!0,force:!0})},Gr=new Set(["bash","-lc"]),jr=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!Gr.has(s)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
21
18
  ${n.trim()}
22
- \`\`\``)}catch(s){M.error("Could not decode outputMsg",s,t.output)}return{title:o,message:n}};import Fr from"fs/promises";import Dr from"os";import Ft from"path";import J from"process";import $r from"readline";var se=y("runner_gemini"),Lt="Gemini CLI",kr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(se.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?(se.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}):(se.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),Ur={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 qe({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`);J.env.GEMINI_API_KEY=m,J.env.GOOGLE_GEMINI_BASE_URL=p}else if(!J.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let E=[],l=[],c=[],g={},_=0,I=0,w,h,R=[ee(J.cwd(),"gemini"),...i?["--model",i]:[],"--yolo","-p",a],x=`${J.env.NVM_BIN}/node`;se.log(`Running ${x} ${R.join(" ")}`);let b=t.utils.run(x,R,{all:!0,env:J.env});b.stdin?.end();let S=ye(()=>{r?.({steps:E,duration:I}),o?.({steps:l,duration:I}),l=[]},250),N=(m,p)=>{m.id=_,_+=1,c.push(m),E.push(m),l.push(m),p||S.flush(),S(),p&&S.flush()},v=$r.createInterface({input:b.all});return v.on("error",m=>{se.error("Readline interface error",{error:m.message,stack:m.stack})}),v.on("line",m=>{let p=null;try{if(m.startsWith("[API Error")){let f=m.match(/\[api error: (.+?)]$/i)?.[1];p={type:"error",value:Te(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;N({title:f?.subject??"Thinking...",message:f?.description},!0);break}case"content":{p.value&&N({message:p.value});break}case"tool_call_request":{let f=p.value,T=Ur[f.name]??f.name,d=f.args?.path||f.args?.absolute_path,C=d&&Ft.relative(J.cwd(),d),ie=f.args?.command,H={title:[T,C&&`\`${C}\``,ie&&`\`${ie}\``].filter(Boolean).join(" ")};g[f.callId]=H,S.flush();break}case"tool_result":{let f=p.value,T=g[f.callId];if(T){let d=[f.resultDisplay,f.responseParts?.functionResponse?.response?.output].find(C=>typeof C=="string"&&C);d&&(T.message=`\`\`\`
23
- ${d.trim()}
24
- \`\`\``),N(T,!0)}break}case"result":{I=p.duration_ms,w=p.value,[c,E,l].forEach(f=>{f[f.length-1]?.message===w&&f.pop()});break}case"error":{h=p.value;break}case"finished":break;default:{se.warn("Unhandled message type:",p.type);break}}}),await b.catch(m=>{({error:h,result:w}=kr({catchError:m,runCmd:b,error:h,result:w,runnerName:"Gemini"}))}),v.close(),S.flush(),{steps:c,duration:I,result:await re({initialResult:w,agentName:Lt,hasError:!!h}),error:ne({error:h,agentName:Lt}),isRetryableError:oe(h)}}var Dt=async()=>{let e=Ft.join(Dr.homedir(),".gemini");await Fr.rm(e,{recursive:!0,force:!0})};var Gr={codex:{runner:Ke,clean:Ot},claude:{runner:He,clean:bt},gemini:{runner:qe,clean:Dt}},$t=Gr;var kt=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>await A(Mr(),"init-stage",async n=>{let s=performance.now();n?.setAttributes({"init.runner":e.runner,"init.id":e.id,"init.sessionId":e.sessionId,"init.hasRepo":e.hasRepo,"init.useGateway":e.useGateway,"init.validateAgent":e.validateAgent,"init.runnerVersion":o||"unknown"});let a=$t[e.runner];if(!a)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let u=jr({apiToken:r});ot(u);let i=e.useGateway?await ct({netlify:u,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!i}),e.validateAgent&&e.errorLogsPath&&n?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let E=yt(({steps:g=[],duration:_})=>{let I=g.map(w=>({...w,title:w.title?Y(w.title):void 0,message:w.message?Y(w.message):void 0}));return g.length=0,j(e.id,e.sessionId,{steps:I,duration:_})},t),l;e.hasRepo?e.sha?(l=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(l=await xt(u),await ue(e.id,{sha:l}),n?.setAttributes({"init.sha.source":"current_commit"})):(l=await Nt(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:E,runner:a,sha:l}}),jr=({apiToken:e})=>({constants:{NETLIFY_API_HOST:Re.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||Re.env.NETLIFY_API_TOKEN,SITE_ID:Re.env.SITE_ID,FUNCTIONS_DIST:Re.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:gt}});import{getTracer as We}from"@netlify/otel";import Yr from"crypto";import K from"fs/promises";import F from"path";import U from"process";var O=y("context"),Br=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}},Hr=10,Kr=async e=>{let{name:t,ext:r}=F.parse(e),o=e,n=F.join(U.cwd(),$,o),s=0;for(;await qr(n);){if(s>=Hr)throw new Error("Failed to generate context file");o=`${t}-${Yr.randomUUID().slice(0,5)}${r}`,n=F.join(U.cwd(),$,o),s+=1}return o},qr=async e=>{try{return await K.access(e),!0}catch{return!1}},Wr=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}},Vr=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 K.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}},xe=null,Jr=async()=>{if(xe)return xe;let e=await Wr();if(!e)return[];let t=F.join(U.cwd(),$,$e);await K.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=F.join(t,a),i=F.join($,$e,a);return O.log(`Downloading ${s.scope} context...`),await Vr(s.endpoint,u)?(O.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:n}):null});return xe=(await Promise.all(r)).filter(n=>n!==null),xe},Ut=async({cliPath:e,netlify:t,config:r,buildErrorContext:o})=>{let n=Br(t),s=await Kr(ht),a=F.join(U.cwd(),$);await K.mkdir(a,{recursive:!0});let u=F.join($,s),i=F.join(U.cwd(),u),E=F.join(U.cwd(),$,te);try{await K.unlink(E),O.log(`Deleted old results file: ${E}`)}catch{}let l=o?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
19
+ \`\`\``)}catch(s){V.error("Could not decode outputMsg",s,t.output)}return{title:o,message:n}};import Yr from"fs/promises";import Br from"os";import Ut from"path";import J from"process";import Hr from"readline";var ie=E("runner_gemini"),kt="Gemini CLI",Wr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(ie.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(ie.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(ie.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),qr={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 Je({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:a,modelVersionOverrides:l}=e,{model:i}=e;if(n){let{token:T,url:y}=n;if(!T||!y)throw new Error("No token or url provided from AI Gateway");if(l?.gemini){let m=l?.gemini?.[s];if(m){if(!await n.isModelAvailableForProvider("gemini",m))throw new Error(`Model override '${m}' is not available for gemini provider`);i=m}}else if(i&&!await n.isModelAvailableForProvider("gemini",i))throw new Error(`Model '${i}' is not available for gemini provider`);J.env.GEMINI_API_KEY=T,J.env.GOOGLE_GEMINI_BASE_URL=y}else if(!J.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let f=[],c=[],u=[],d={},h=0,R=0,w,g,N=[ee(J.cwd(),"gemini"),...i?["--model",i]:[],"--yolo","-p",a],v=`${J.env.NVM_BIN}/node`;ie.log(`Running ${v} ${N.join(" ")}`);let S=t.utils.run(v,N,{all:!0,env:J.env});S.stdin?.end();let x=_e(()=>{r?.({steps:f,duration:R}),o?.({steps:c,duration:R}),c=[]},250),_=(T,y)=>{T.id=h,h+=1,u.push(T),f.push(T),c.push(T),y||x.flush(),x(),y&&x.flush()},A=Hr.createInterface({input:S.all});return A.on("error",T=>{ie.error("Readline interface error",{error:T.message,stack:T.stack})}),A.on("line",T=>{let y=null;try{if(T.startsWith("[API Error")){let m=T.match(/\[api error: (.+?)]$/i)?.[1];y={type:"error",value:Te(m,!1)?.error?.message||m||"Gemini encountered error"}}else y=JSON.parse(T)}catch{return}if(y)switch(y.type){case"thought":{let m=y.value;_({title:m?.subject??"Thinking...",message:m?.description},!0);break}case"content":{y.value&&_({message:y.value});break}case"tool_call_request":{let m=y.value,I=qr[m.name]??m.name,p=m.args?.path||m.args?.absolute_path,b=p&&Ut.relative(J.cwd(),p),ae=m.args?.command,H={title:[I,b&&`\`${b}\``,ae&&`\`${ae}\``].filter(Boolean).join(" ")};d[m.callId]=H,x.flush();break}case"tool_result":{let m=y.value,I=d[m.callId];if(I){let p=[m.resultDisplay,m.responseParts?.functionResponse?.response?.output].find(b=>typeof b=="string"&&b);p&&(I.message=`\`\`\`
20
+ ${p.trim()}
21
+ \`\`\``),_(I,!0)}break}case"result":{R=y.duration_ms,w=y.value,[u,f,c].forEach(m=>{m[m.length-1]?.message===w&&m.pop()});break}case"error":{g=y.value;break}case"finished":break;default:{ie.warn("Unhandled message type:",y.type);break}}}),await S.catch(T=>{({error:g,result:w}=Wr({catchError:T,runCmd:S,error:g,result:w,runnerName:"Gemini"}))}),A.close(),x.flush(),{steps:u,duration:R,result:await re({initialResult:w,agentName:kt,hasError:!!g}),error:ne({error:g,agentName:kt}),isRetryableError:oe(g)}}var Mt=async()=>{let e=Ut.join(Br.homedir(),".gemini");await Yr.rm(e,{recursive:!0,force:!0})};var Kr={codex:{runner:Ve,clean:$t},claude:{runner:Ke,clean:Lt},gemini:{runner:Je,clean:Mt}},Gt=Kr;var Jr=E("init_stage"),jt=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>await C(Vr(),"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=Gt[e.runner];if(!a)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let l=Xr({apiToken:r});at(l);let i=e.useGateway?await ft({netlify:l,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!i}),e.validateAgent&&e.errorLogsPath&&n?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let f=wt(({steps:h=[],duration:R})=>{let w=h.map(g=>({...g,title:g.title?Y(g.title):void 0,message:g.message?Y(g.message):void 0}));return h.length=0,j(e.id,e.sessionId,{steps:w,duration:R})},t);Jr.info("Adding build files to stage");let c=await He();await Ye(c);let u;e.hasRepo?e.sha?(u=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(u=await St(),await ce(e.id,{sha:u}),n?.setAttributes({"init.sha.source":"current_commit"})):(u=await Ct(),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let d=performance.now()-s;return n?.setAttributes({"init.sha":u||"unknown","init.duration.ms":d,"init.status":"success"}),{aiGateway:i,context:l,persistSteps:f,runner:a,sha:u}}),Xr=({apiToken:e})=>({constants:{NETLIFY_API_HOST:Ie.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||Ie.env.NETLIFY_API_TOKEN,SITE_ID:Ie.env.SITE_ID,FUNCTIONS_DIST:Ie.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:F}});import{getTracer as Xe}from"@netlify/otel";import zr from"crypto";import W from"fs/promises";import $ from"path";import M from"process";var L=E("context"),Zr=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:M.env.NETLIFY_TEAM_ID,userId:M.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:M.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},Qr=10,en=async e=>{let{name:t,ext:r}=$.parse(e),o=e,n=$.join(M.cwd(),k,o),s=0;for(;await tn(n);){if(s>=Qr)throw new Error("Failed to generate context file");o=`${t}-${zr.randomUUID().slice(0,5)}${r}`,n=$.join(M.cwd(),k,o),s+=1}return o},tn=async e=>{try{return await W.access(e),!0}catch{return!1}},rn=async()=>{try{L.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 L.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"?(L.warn("Catchall consumer missing or invalid contextScopes"),null):r:(L.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?L.warn("Netlify features context request timed out"):L.warn("Failed to fetch Netlify features context:",e.message),null}},nn=async(e,t)=>{try{let r=await fetch(e,{signal:AbortSignal.timeout(1e4)});if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let o=await r.text();return await W.writeFile(t,o,"utf-8"),!0}catch(r){return r.name==="AbortError"?L.warn(`Download timeout for ${e}`):L.warn(`Failed to download context file ${e}:`,r.message),!1}},Re=null,on=async()=>{if(Re)return Re;let e=await rn();if(!e)return[];let t=$.join(M.cwd(),k,$e);await W.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([n,s])=>{if(!s||typeof s!="object"||!s.endpoint||!s.scope)return L.warn(`Invalid scope data for ${n}, skipping...`),null;let a=`${n}.md`,l=$.join(t,a),i=$.join(k,$e,a);return L.log(`Downloading ${s.scope} context...`),await nn(s.endpoint,l)?(L.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:n}):null});return Re=(await Promise.all(r)).filter(n=>n!==null),Re},Yt=async({cliPath:e,netlify:t,config:r,buildErrorContext:o})=>{let n=Zr(t),s=await en(yt),a=$.join(M.cwd(),k);await W.mkdir(a,{recursive:!0});let l=$.join(k,s),i=$.join(M.cwd(),l),f=$.join(M.cwd(),k,te);try{await W.unlink(f),L.log(`Deleted old results file: ${f}`)}catch{}let c=o?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
25
22
  Your task is to analyze and fix the build errors.
26
23
  Don't apply techniques of reverting changes. Apply fixes related to errors.
27
24
  Don't try to run build by yourself. Just fix the errors.
28
25
 
29
26
  <build_error_context>
30
27
  ${o}
31
- </build_error_context>`:"",c="";r.siteContext&&r.siteContext.length!==0&&(c=`
28
+ </build_error_context>`:"",u="";r.siteContext&&r.siteContext.length!==0&&(u=`
32
29
  <project_rules>
33
- ${r.siteContext.filter(h=>h.site_context).map(h=>typeof h.site_context=="string"?h.site_context:typeof h.site_context=="object"?JSON.stringify(h.site_context):"").join(`
30
+ ${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(`
34
31
 
35
32
  `)}
36
33
  </project_rules>
37
- `);let g="";if(r.sessionHistoryContext?.length){let h=F.join(U.cwd(),$,De);await K.mkdir(h,{recursive:!0});let R=await Promise.all(r.sessionHistoryContext.map(async(x,b)=>{let S=b+1,N=`attempt-${S}.md`,v=F.join(h,N),m=F.join($,De,N),p=`# Task History - Attempt ${S}
34
+ `);let d="";if(r.sessionHistoryContext?.length){let g=$.join(M.cwd(),k,De);await W.mkdir(g,{recursive:!0});let N=await Promise.all(r.sessionHistoryContext.map(async(v,S)=>{let x=S+1,_=`attempt-${x}.md`,A=$.join(g,_),T=$.join(k,De,_),y=`# Task History - Attempt ${x}
38
35
 
39
36
  ## Request - what the user asked for
40
- ${x.request}
37
+ ${v.request}
41
38
 
42
39
  ---
43
40
 
44
41
  ## Response - what the agent replied with after its work
45
42
 
46
- ${x.response}
47
- `;return await K.writeFile(v,p,"utf-8"),O.log(`Created history file: ${m}`),m}));g+=`
43
+ ${v.response}
44
+ `;return await W.writeFile(A,y,"utf-8"),L.log(`Created history file: ${T}`),T}));d+=`
48
45
  <session_history_context>
49
46
  History of prior work on this task.
50
47
  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.
51
48
 
52
- ${R.slice(-5).map(x=>`- ${x}`).join(`
49
+ ${N.slice(-5).map(v=>`- ${v}`).join(`
53
50
  `)}
54
51
 
55
52
  </session_history_context>
56
- `}let _=await Jr(),I="";_.length>0&&(I=`
53
+ `}let h=await on(),R="";h.length>0&&(R=`
57
54
  <netlify_features_context>
58
55
  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.
59
56
  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.
60
57
 
61
- ${_.map(h=>`- **${h.scope}**: ${h.path}`).join(`
58
+ ${h.map(g=>`- **${g.scope}**: ${g.path}`).join(`
62
59
  `)}
63
60
 
64
61
  Refer to these files when working with specific Netlify features.
@@ -70,7 +67,7 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
70
67
  <user_request>
71
68
  ${r.prompt}
72
69
  </user_request>
73
- ${l}
70
+ ${c}
74
71
  </request>
75
72
 
76
73
  <requirements>
@@ -86,7 +83,7 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
86
83
  - for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${a}/${ke} folder
87
84
  - move assets from ${a}/${ke} folder to the project assets folder if they are referenced in a code or applied changes
88
85
  </attachements>
89
- ${c}
86
+ ${u}
90
87
  </requirements>
91
88
 
92
89
  <extra_context>
@@ -98,39 +95,41 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
98
95
  - Netlify Functions directory: ${n.functionsDir}
99
96
  </metadata>
100
97
  <environment>
101
- - Node Version: ${U.version||"unknown"}
98
+ - Node Version: ${M.version||"unknown"}
102
99
  - Environment variables are set globally (e.g. \`echo $VARIABLE_NAME\` can be used to check if a var is set).
103
100
  - 'netlify-cli' npm package is already available as a global package. Don't try to install it again
104
101
  - 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.
105
102
  </environment>
106
- ${I}
103
+ ${R}
107
104
  <docs>
108
105
  - Netlify Docs: https://docs.netlify.com
109
106
  - LLM Resources Index: https://docs.netlify.com/llms.txt
110
107
  </docs>
111
108
  </extra_context>
112
109
 
113
- ${g}
114
- `;return await K.writeFile(i,w,"utf-8"),O.log(`Generated agent context document at: ${i}`),w.length>5e5&&(w=`
110
+ ${d}
111
+ `;return await W.writeFile(i,w,"utf-8"),L.log(`Generated agent context document at: ${i}`),w.length>5e5&&(w=`
115
112
  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.
116
113
 
117
114
  <request>
118
115
  <user_request>
119
116
  ${r.prompt}
120
117
  </user_request>
121
- ${l}
118
+ ${c}
122
119
  </request>
123
120
 
124
121
  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.
125
- `),w};var Xr=y("prompt"),Gt=async({cliPath:e,config:t,netlify:r,buildErrorContext:o})=>{let n=await Ut({cliPath:e,config:t,netlify:r,buildErrorContext:o});return process.env.AGENT_RUNNER_DEBUG&&Xr.log("Contextful Prompt:",n),{prompt:n}};var Ne=y("inference_stage"),Mt=5,ve=async e=>{let{cliPath:t,config:r,context:o,buildErrors:n,runner:s,persistSteps:a,aiGateway:u,attempt:i,contextPrefix:E,priorAgentSessionId:l}=e;Ne.log(`Running inference stage, attempt ${i} of ${Mt}`);let c=await A(We(),"inference-stage",async g=>{g?.setAttributes({"inference.attempt":i||1}),dt();let{prompt:_}=await A(We(),"compose-prompt",async()=>await Gt({cliPath:t,config:r,buildErrorContext:zr(n),netlify:o})),I=`
126
- ${E||""}
127
- ${_}
128
- `.trim(),w={...r,prompt:I},h=await A(We(),`run-${r.runner}`,async()=>await s({aiGateway:u,config:w,netlify:o,persistSteps:a,continueSession:!!(i&&i>1),priorAgentSessionId:l}));return h.result&&(h.result=Y(h.result)),h.error&&(h.error=Y(h.error)),await a.flush(),h});if(c.error){if(Ne.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<Mt))return Ne.log("Retrying inference stage"),await new Promise(_=>setTimeout(_,5e3)),{runnerResult:(await ve({...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 Ne.log("Do not retry inference stage"),new Error(c.error)}return{runnerResult:c}},zr=e=>!e||e.length===0?"":`
122
+ `),w};var sn=E("prompt"),Bt=async({cliPath:e,config:t,netlify:r,buildErrorContext:o})=>{let n=await Yt({cliPath:e,config:t,netlify:r,buildErrorContext:o});return process.env.AGENT_RUNNER_DEBUG&&sn.log("Contextful Prompt:",n),{prompt:n}};var Ne=E("inference_stage"),Ht=5,xe=async e=>{let{cliPath:t,config:r,context:o,buildErrors:n,runner:s,persistSteps:a,aiGateway:l,attempt:i,contextPrefix:f,priorAgentSessionId:c}=e;Ne.log(`Running inference stage, attempt ${i} of ${Ht}`);let u=await C(Xe(),"inference-stage",async d=>{d?.setAttributes({"inference.attempt":i||1}),gt();let{prompt:h}=await C(Xe(),"compose-prompt",async()=>await Bt({cliPath:t,config:r,buildErrorContext:an(n),netlify:o})),R=`
123
+ ${f||""}
124
+ ${h}
125
+ `.trim(),w={...r,prompt:R},g=await C(Xe(),`run-${r.runner}`,async()=>await s({aiGateway:l,config:w,netlify:o,persistSteps:a,continueSession:!!(i&&i>1),priorAgentSessionId:c}));return g.result&&(g.result=Y(g.result)),g.error&&(g.error=Y(g.error)),await a.flush(),g});if(u.error){if(Ne.error("Runner failed",{stepsCount:u.steps.length,duration:u.duration,error:u.error,isRetryableError:u.isRetryableError,attempt:i||1,agentSessionId:u.agentSessionId}),u.isRetryableError&&(!i||i<Ht))return Ne.log("Retrying inference stage"),await new Promise(h=>setTimeout(h,5e3)),{runnerResult:(await xe({...e,attempt:(i||1)+1,priorAgentSessionId:u.agentSessionId,contextPrefix:u.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 Ne.log("Do not retry inference stage"),new Error(u.error)}return{runnerResult:u}},an=e=>!e||e.length===0?"":`
129
126
  Deploy failed failed. Here are the errors to review on the latest build:
130
127
 
131
128
  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.
132
129
 
133
130
  ${e.pop()}
134
- `;import en from"process";import{getTracer as Ve}from"@netlify/otel";import{getTracer as Zr}from"@netlify/otel";var pe=y("deploy"),jt=async e=>await A(Zr(),"create-preview-deploy",async t=>Qr(e,t)),Qr=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||(pe.log("Deploy: Uploading source zip"),i.push("--upload-source-zip")),n&&i.push("--alias",n),a&&i.push("--filter",a),r?(pe.log("Deploy: Skipping build"),i.push("--no-build")):i.push("--context","deploy-preview");let E=s||"netlify";pe.log(`Running: ${E} ${i.join(" ")}`),u?.setAttributes({cmd:E,args:i});let l=await e.utils.run(E,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}),pe.log(`
135
- 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 pe.error("Failed to create preview deploy via CLI:",i),u?.setAttributes({success:!1,error:i.message}),i}};var fe=y("deploy_stage"),Je=async e=>await A(Ve(),"run-deploy-stage",async()=>tn(e)),tn=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let s=await A(Ve(),"get-runner-diffs",async()=>await Rt({config:t,netlify:r}));if(fe.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:E}=s,l=!0;fe.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 _=await A(Ve(),"get-runner-session",async()=>await it(t.id,t.sessionId));_?.title&&(g=_.title)}catch(_){fe.warn("Failed to fetch session title, using fallback message:",_.message)}await j(t.id,t.sessionId,{steps:[{title:"Deploying the run preview"}]}),c=await jt({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:g,skipBuild:!1,deploySubdomain:Tt(t.id,en.env.SITE_NAME),filter:n})}catch(g){return fe.warn("Failed to create preview deploy (continuing with agent run):",g),{diff:a,resultDiff:u,hasChanges:l,previewInfo:null,diffBinary:i,resultDiffBinary:E,deployError:g instanceof Error?g.message:String(g)}}return fe.log("Git status",{hasDiff:!!a,hasChanges:l}),{diff:a,resultDiff:u,hasChanges:l,previewInfo:c,diffBinary:i,resultDiffBinary:E}};import{getTracer as Ae}from"@netlify/otel";async function Yt(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=y("cleanup_stage"),Bt=async e=>await A(Ae(),"cleanup-stage",async()=>rn(e)),Xe=1024*1024*10,rn=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 lt(e.id,e.sessionId),c=[];(t||s)&&c.push(Pe(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(Pe(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(Ae(),"update-runner",async()=>{await ue(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>Xe||g>Xe){let _=`Diffs exceed maximum inline size of ${Xe} bytes.`;throw D.error(_),new Error(_)}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(Ae(),"update-runner",async()=>{await ue(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 Yt(async()=>await A(Ae(),"update-runner-session",()=>j(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 Ht,shutdownTracers as on,withActiveSpan as Kt}from"@netlify/otel";var sn=nn(import.meta.url),qt=sn("../package.json"),Wt=y("pipeline_index"),Se=3,Vt=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:s,tracing:a={}})=>{let u,{withStageTimer:i}=pt(q.timeUnits.hours(4)),E=await rt(qt.version,e.id,a);try{await Kt(Ht(),"run-pipeline",{},E,async()=>{let l,{aiGateway:c,context:g,persistSteps:_,runner:I,sha:w}=await i("init",()=>kt({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:s,runnerVersion:qt.version}),q.timeUnits.minutes(10));u=I.clean,e.sha=w;let{runnerResult:h}=await i("inference",()=>ve({cliPath:r,config:e,context:g,runner:I.runner,persistSteps:_,aiGateway:c}));await j(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let R=await i("deploy",()=>Je({cliPath:r,config:e,context:g,result:h.result,filter:s})),x=h,b=[];if(R.hasChanges&&R.deployError){b.push(nt(R.deployError));let f=1;for(;f<=Se&&!R.previewInfo;)Wt.log(`Deploy attempt had errors. Retrying. ${f}/${Se}`),await Kt(Ht(),"deploy-stage",async T=>{T?.setAttributes({"stage.attempt":f});let{runnerResult:d}=await i(`inference-retry-${f}`,()=>ve({cliPath:r,config:e,context:g,runner:I.runner,persistSteps:_,aiGateway:c,buildErrors:b,priorAgentSessionId:h.agentSessionId}));x={...d,steps:[...x.steps||[],...d.steps||[]],duration:(x.duration||0)+(d.duration||0)},R=await i(`deploy-retry-${f}`,()=>Je({cliPath:r,config:e,context:g,result:d.result,filter:s})),R.deployError&&b.push(R.deployError),f++});f>Se&&!R.previewInfo&&(l=new Error(`Deploy validation failed after ${Se} attempts`))}let{diff:S,resultDiff:N,previewInfo:v,diffBinary:m,resultDiffBinary:p}=R;if(await i("cleanup",()=>Bt({config:e,diff:S,result:x.result,duration:x.duration,resultDiff:N,diffBinary:m,resultDiffBinary:p,previewInfo:v}),q.timeUnits.minutes(10)),l)throw l;process.env.NETLIFY_LOCAL_MODE||await I.clean?.()})}catch(l){Wt.error("Got error while running pipeline",l),await u?.();let c=l instanceof Error&&l.message;throw await j(e.id,e.sessionId,{result:c||"Encountered error when running agent",state:"error"}),l}finally{await on()}};import L from"process";var ln="claude",un=e=>(e??[]).filter(t=>t.request&&t.response),cn=e=>(e??[]).filter(t=>t.site_context),Jt=y("config"),Xt=()=>{let e=L.env.NETLIFY_AGENT_RUNNER_ID,t=L.env.NETLIFY_AGENT_RUNNER_SESSION_ID;if(!e||!t)throw new Error("ID of agent runner is not provided");let r=L.env.NETLIFY_AGENT_RUNNER_RESULT_BRANCH,o=L.env.NETLIFY_AGENT_RUNNER_PROMPT;if(!o)throw new Error("Prompt is not provided");let n=L.env.NETLIFY_AGENT_RUNNER_AGENT||ln,s=L.env.NETLIFY_AGENT_RUNNER_MODEL,a=L.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED==="1",u=L.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED==="1",i=L.env.ERROR_LOGS_PATH,E=Te(L.env.NETLIFY_AGENT_RUNNER_CONTEXT,!0,Jt),l=un(E),c=cn(E),g=L.env.NETLIFY_AGENT_RUNNER_HAS_REPO!=="0",_=!L.env.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED,I=L.env.NETLIFY_AGENT_RUNNER_SHA,w=dn(),h=wt(),R={id:e,sessionId:t,resultBranch:r,prompt:o,runner:n,model:s,validateAgent:a,errorLogsPath:i,sessionHistoryContext:l,siteContext:c,hasRepo:g,useGateway:_,sha:I,accountType:w,validateAgentWithBuild:u,modelVersionOverrides:h};return Jt.log({fullConfig:R}),R},dn=()=>{let e=L.env.NETLIFY_TEAM_TYPE;return e?e.includes("personal")?Ge:e.includes("pro")?"pro":e.startsWith("enterprise")?Me:e.startsWith("free")?je:Ue:Ue};var zt=y("bin_cmd"),X=pn(ze.argv.slice(2),{string:["auth","cwd","cli-path","error-logs-path","filter","trace-exporter-url","traceparent"]});try{let e=Xt();await Vt({config:e,apiToken:X.auth,cwd:X.cwd,cliPath:X["cli-path"],errorLogsPath:X["error-logs-path"],filter:X.filter,tracing:{exporterUrl:X["trace-exporter-url"],traceparent:X.traceparent}}),zt.info("Finished agent"),ze.exit(0)}catch(e){zt.error("Error running agent pipeline:",e),ze.exit(1)}
131
+ `;import cn from"process";import{getTracer as ze}from"@netlify/otel";import{getTracer as ln}from"@netlify/otel";var de=E("deploy"),Wt=async e=>await C(ln(),"create-preview-deploy",async t=>un(e,t)),un=async({netlify:e,hasRepo:t,skipBuild:r,message:o="Agent Preview",deploySubdomain:n,cliPath:s,filter:a},l)=>{try{let i=["deploy","--message",`"${o}"`,"--json","--draft","--verbose"];t||(de.log("Deploy: Uploading source zip"),i.push("--upload-source-zip")),n&&i.push("--alias",n),a&&i.push("--filter",a),r?(de.log("Deploy: Skipping build"),i.push("--no-build")):i.push("--context","deploy-preview");let f=s||"netlify";de.log(`Running: ${f} ${i.join(" ")}`),l?.setAttributes({cmd:f,args:i});let c=await e.utils.run(f,i,{stdio:["ignore","pipe","pipe"]}),u=JSON.parse(c.stdout.trim());l?.setAttributes({success:!0,deployId:u.deploy_id,deployUrl:u.deploy_url,siteId:u.site_id}),de.log(`
132
+ Preview deploy created successfully:`,{deployId:u.deploy_id,deployUrl:u.deploy_url,siteId:u.site_id});let d={deployId:u.deploy_id,previewUrl:u.deploy_url,logsUrl:u.logs,siteId:u.site_id};return t||(d.sourceZipFilename=u.source_zip_filename),d}catch(i){throw de.error("Failed to create preview deploy via CLI:",i),l?.setAttributes({success:!1,error:i.message}),i}};var fe=E("deploy_stage"),Ze=async e=>await C(ze(),"run-deploy-stage",async()=>pn(e)),pn=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let s=await C(ze(),"get-runner-diffs",async()=>await vt({config:t,netlify:r}));if(fe.info("Resolved git",{hasChanges:s.hasChanges,ignored:s.ignored??[]}),!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:l,diffBinary:i,resultDiffBinary:f}=s,c=!0;fe.log("Preview deploy condition check:",{resultUndefined:o===void 0,resultType:typeof o,hasChanges:c,wouldCreatePreview:o!==void 0&&c});let u=null;if(o!==void 0&&c)try{let d;try{let h=await C(ze(),"get-runner-session",async()=>await ut(t.id,t.sessionId));h?.title&&(d=h.title)}catch(h){fe.warn("Failed to fetch session title, using fallback message:",h.message)}await j(t.id,t.sessionId,{steps:[{title:"Deploying the run preview"}]}),u=await Wt({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:d,skipBuild:!1,deploySubdomain:It(t.id,cn.env.SITE_NAME),filter:n})}catch(d){return fe.warn("Failed to create preview deploy (continuing with agent run):",d),{diff:a,resultDiff:l,hasChanges:c,previewInfo:null,diffBinary:i,resultDiffBinary:f,deployError:d instanceof Error?d.message:String(d)}}return fe.log("Git status",{hasDiff:!!a,hasChanges:c}),{diff:a,resultDiff:l,hasChanges:c,previewInfo:u,diffBinary:i,resultDiffBinary:f}};import{getTracer as Ae}from"@netlify/otel";async function qt(e,t){let{maxRetries:r,baseDelay:o,onRetry:n}=t,s;for(let a=1;a<=r;a++)try{return await e()}catch(l){if(s=l,a===r)throw s;n&&n(a,s),await new Promise(i=>setTimeout(i,o*a))}throw s}var ve=class{scanDiffForForms(t){let r=[],o=null,n=[],s=t.split(`
133
+ `);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 l=a.split(" ");o=l[l.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(`
134
+ `),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 l=o.match(s);if(l){let i=l.index||0,f=Math.max(0,i-20),c=Math.min(o.length,i+l[0].length+20),u=o.slice(f,c).trim();return u=u.replace(/\s+/g," "),u.length>100&&(u=u.slice(0,97)+"..."),{file:r,snippet:`[${a}] ${u}`}}}return null}};var O=E("cleanup_stage"),Kt=async e=>await C(Ae(),"cleanup-stage",async()=>dn(e)),Qe=1024*1024*10,dn=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:s,resultDiffBinary:a,previewInfo:l})=>{let i={result:r||"Done",duration:o};l&&l.deployId&&(i.deploy_id=l.deployId),l&&l.sourceZipFilename&&(i.result_zip_file_name=l.sourceZipFilename);let f=t||s||n||a;if(f){let c=new ve,u=t||s||"",d=c.scanDiffForForms(u);d.detected&&(O.log("Detected Netlify form(s) in diff:"),d.matches.forEach(({file:h,snippet:R})=>{O.log(` - ${h}: ${R}`)}),i.has_netlify_form=!0)}if(f)try{O.log("Getting pre-signed URLs for diff upload");let c=await pt(e.id,e.sessionId),u=[];(t||s)&&u.push(Pe(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)&&u.push(Pe(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 ${u.length} diff(s) to S3 in parallel`),await Promise.all(u),(n||a)&&(O.log("Updating agent runner with cumulative diff S3 key"),await C(Ae(),"update-runner",async()=>{await ce(e.id,{result_diff_s3_key:c.cumulative.s3_key})}))}catch(c){O.error("S3 upload failed, falling back to inline diffs:",c);let u=Buffer.byteLength(t||s||""),d=Buffer.byteLength(a||n||"");if(u>Qe||d>Qe){let h=`Diffs exceed maximum inline size of ${Qe} 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 C(Ae(),"update-runner",async()=>{await ce(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 qt(async()=>await C(Ae(),"update-runner-session",()=>j(e.id,e.sessionId,i)),{maxRetries:3,baseDelay:1e3,onRetry:(c,u)=>{O.error(`Error updating agent runner session (attempt ${c}):`,u),O.log("Retrying...")}}),O.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as Vt,shutdownTracers as gn,withActiveSpan as Jt}from"@netlify/otel";var mn=fn(import.meta.url),Xt=mn("../package.json"),zt=E("pipeline_index"),Se=3,Zt=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:s,tracing:a={}})=>{let l,{withStageTimer:i}=mt(q.timeUnits.hours(4)),f=await st(Xt.version,e.id,a);try{await Jt(Vt(),"run-pipeline",{},f,async()=>{let c,{aiGateway:u,context:d,persistSteps:h,runner:R,sha:w}=await i("init",()=>jt({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:s,runnerVersion:Xt.version}),q.timeUnits.minutes(10));l=R.clean,e.sha=w;let{runnerResult:g}=await i("inference",()=>xe({cliPath:r,config:e,context:d,runner:R.runner,persistSteps:h,aiGateway:u}));await j(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let N=await i("deploy",()=>Ze({cliPath:r,config:e,context:d,result:g.result,filter:s})),v=g,S=[];if(N.hasChanges&&N.deployError){S.push(it(N.deployError));let m=1;for(;m<=Se&&!N.previewInfo;)zt.log(`Deploy attempt had errors. Retrying. ${m}/${Se}`),await Jt(Vt(),"deploy-stage",async I=>{I?.setAttributes({"stage.attempt":m});let{runnerResult:p}=await i(`inference-retry-${m}`,()=>xe({cliPath:r,config:e,context:d,runner:R.runner,persistSteps:h,aiGateway:u,buildErrors:S,priorAgentSessionId:g.agentSessionId}));v={...p,steps:[...v.steps||[],...p.steps||[]],duration:(v.duration||0)+(p.duration||0)},N=await i(`deploy-retry-${m}`,()=>Ze({cliPath:r,config:e,context:d,result:p.result,filter:s})),N.deployError&&S.push(N.deployError),m++});m>Se&&!N.previewInfo&&(c=new Error(`Deploy validation failed after ${Se} attempts`))}let{diff:x,resultDiff:_,previewInfo:A,diffBinary:T,resultDiffBinary:y}=N;if(await i("cleanup",()=>Kt({config:e,diff:x,result:v.result,duration:v.duration,resultDiff:_,diffBinary:T,resultDiffBinary:y,previewInfo:A}),q.timeUnits.minutes(10)),c)throw c;process.env.NETLIFY_LOCAL_MODE||(await l?.(),await bt())})}catch(c){zt.error("Got error while running pipeline",c),await l?.();let u=c instanceof Error&&c.message;throw await j(e.id,e.sessionId,{result:u||"Encountered error when running agent",state:"error"}),c}finally{await gn()}};import D from"process";var En="claude",yn=e=>(e??[]).filter(t=>t.request&&t.response),_n=e=>(e??[]).filter(t=>t.site_context),Qt=E("config"),er=()=>{let e=D.env.NETLIFY_AGENT_RUNNER_ID,t=D.env.NETLIFY_AGENT_RUNNER_SESSION_ID;if(!e||!t)throw new Error("ID of agent runner is not provided");let r=D.env.NETLIFY_AGENT_RUNNER_RESULT_BRANCH,o=D.env.NETLIFY_AGENT_RUNNER_PROMPT;if(!o)throw new Error("Prompt is not provided");let n=D.env.NETLIFY_AGENT_RUNNER_AGENT||En,s=D.env.NETLIFY_AGENT_RUNNER_MODEL,a=D.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED==="1",l=D.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED==="1",i=D.env.ERROR_LOGS_PATH,f=Te(D.env.NETLIFY_AGENT_RUNNER_CONTEXT,!0,Qt),c=yn(f),u=_n(f),d=D.env.NETLIFY_AGENT_RUNNER_HAS_REPO!=="0",h=!D.env.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED,R=D.env.NETLIFY_AGENT_RUNNER_SHA,w=Tn(),g=Rt(),N={id:e,sessionId:t,resultBranch:r,prompt:o,runner:n,model:s,validateAgent:a,errorLogsPath:i,sessionHistoryContext:c,siteContext:u,hasRepo:d,useGateway:h,sha:R,accountType:w,validateAgentWithBuild:l,modelVersionOverrides:g};return Qt.log({fullConfig:N}),N},Tn=()=>{let e=D.env.NETLIFY_TEAM_TYPE;return e?e.includes("personal")?Me:e.includes("pro")?"pro":e.startsWith("enterprise")?Ge:e.startsWith("free")?je:Ue:Ue};var tr=E("bin_cmd"),X=wn(et.argv.slice(2),{string:["auth","cwd","cli-path","error-logs-path","filter","trace-exporter-url","traceparent"]});try{let e=er();await Zt({config:e,apiToken:X.auth,cwd:X.cwd,cliPath:X["cli-path"],errorLogsPath:X["error-logs-path"],filter:X.filter,tracing:{exporterUrl:X["trace-exporter-url"],traceparent:X.traceparent}}),tr.info("Finished agent"),et.exit(0)}catch(e){tr.error("Error running agent pipeline:",e),et.exit(1)}
136
135
  //# sourceMappingURL=bin.js.map