@netlify/agent-runner-cli 1.45.0 → 1.46.0

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