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