@netlify/agent-runner-cli 1.49.0-alpha → 1.49.1-alpha

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