@netlify/agent-runner-cli 1.65.1 → 1.66.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin-local.js +63 -64
- package/dist/bin.js +62 -63
- package/dist/index.js +68 -69
- package/dist/skills/skills/netlify-forms/SKILL.md +306 -0
- package/package.json +2 -1
package/dist/index.js
CHANGED
|
@@ -1,31 +1,31 @@
|
|
|
1
|
-
import{createRequire as
|
|
2
|
-
`),r=[],
|
|
3
|
-
`)),
|
|
4
|
-
${
|
|
1
|
+
import{createRequire as Sn}from"module";import{createTracerProvider as lr}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as ut}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as cr}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as ur}from"@netlify/otel";import{propagation as pt,context as dt,W3CTraceContextPropagator as pr}from"@netlify/otel/opentelemetry";import{OTLPTraceExporter as dr}from"@opentelemetry/exporter-trace-otlp-grpc";import ar from"process";function E(e){let t=ar.env.LOG!=="0";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 Ge=E("tracing"),ft=async(e,t,r)=>(await lr({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new ut(new je),new ut(new dr({url:r.exporterUrl}))],instrumentations:[new cr({skipHeaders:!0})]}),r.traceparent?(pt.setGlobalPropagator(new pr),pt.extract(dt.active(),{traceparent:r.traceparent,isRemote:!0})):dt.active());function C(e,t,r){return Ge.log(`\u23F3 TRACE: ${t} starting...`),ur(e,t,r)}var je=class{export(t,r){for(let n of t)this.logSpan(n);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,n=t.attributes,i=[];for(let[a,c]of Object.entries(n))a.includes("duration")&&typeof c=="number"?i.push(`${a}=${c.toFixed(2)}ms`):i.push(`${a}=${c}`);let s=t.status?.code===2?"\u274C":"\u2705",o=i.length>0?` [${i.join(", ")}]`:"";Ge.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${o}`),t.status?.code===2&&t.status.message&&Ge.log(` \u274C Error: ${t.status.message}`)}};var fr=["error","failed","exception","fatal","panic","abort","crash"];function mt(e){let t=e.split(`
|
|
2
|
+
`),r=[],n=-1,i=0;for(;i<t.length;){let a=t[i].slice(0,500).toLowerCase();if(fr.some(d=>a.includes(d))){let d=Math.max(0,i-10,n+1),p=Math.min(t.length-1,i+20),u=[];for(let m=d;m<=p;m++)u.push(t[m]);r.push(u.join(`
|
|
3
|
+
`)),n=p,i=p+1}else i++}if(r.length===0)return e;let s=r.map((o,a)=>`<extracted_error_chunk order="${a+1}">
|
|
4
|
+
${o}
|
|
5
5
|
</extracted_error_chunk>`).join(`
|
|
6
6
|
|
|
7
|
-
`);return o.length>e.length*.8?e:o}import{execSync as en}from"child_process";import Jt from"fs/promises";import tn from"path";import J from"process";import{getTracer as rn}from"@netlify/otel";import ye from"process";var re=class extends Error{constructor(r,i,n){super(r);this.statusCode=i;this.userMessage=n;this.name="GracefulShutdownError"}},gt=e=>e instanceof re;var Re=ye.env.NETLIFY_API_URL,Se=ye.env.NETLIFY_API_TOKEN,B=E("api"),be=()=>ye.env.NETLIFY_LOCAL_MODE==="true",_e=async(e,t={})=>{if(!Re||!Se)throw new Error("No API URL or token");let r=new URL(e,Re),i={...t,headers:{...t.headers,Authorization:`Bearer ${Se}`}};ye.env.AGENT_RUNNERS_DEBUG==="true"&&(i.headers["x-nf-debug-logging"]="true"),t.json&&(i.headers||={},i.headers["Content-Type"]="application/json",i.body=JSON.stringify(t.json));let n=await fetch(r,i),o=n.ok&&n.status<=299;if(ye.env.AGENT_RUNNERS_DEBUG==="true")B.log(`Response headers for ${r}:`),n.headers.forEach((l,u)=>{B.log(` ${u}: ${l}`)});else{let l=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");B.log(`Request ID for ${r}: ${l||"N/A"}`)}if(o||B.error(`Got status ${n.status} for request ${r}`),t.raw){if(!o)throw new Error(`API request failed: ${n.status} ${n.statusText}`);return n}let s=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!o){let l=typeof s=="string"?s:JSON.stringify(s);throw n.status===404?new re(`API request failed: 404 - ${l}`,404,"The site associated with this agent run no longer exists."):n.status===403&&t.gracefulOn403?new re(`API request failed: 403 - ${l}`,403,"Credit limit reached. Please add more credits to continue using Agent Runners."):new Error(`API request failed: ${n.status} - ${l}`)}return s},ht=e=>{B.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Re=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Se=e.constants.NETLIFY_API_TOKEN)},yt=()=>({apiUrl:Re,token:Se}),Ee=async(e,t)=>be()?(B.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):_e(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),G=async(e,t,r)=>be()?(B.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):_e(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var _t=async(e,t)=>be()?(B.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):_e(`/api/v1/agent_runners/${e}/sessions/${t}`),Et=(e,t,r)=>_e(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn403:!0}),wt=async(e,t)=>be()?(B.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"}}):_e(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Be=async(e,t)=>{B.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 ne=E("ai_gateway"),He=null;var Tt=async()=>{if(He)return He;ne.log("Fetching available AI gateway providers");let e=await fetch(`${yt().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 He=t,ne.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},fr=async(e,t)=>{let i=(await Tt()).providers[e];if(!i)return ne.log(`Provider '${e}' not found`),!1;let n=i.models.includes(t);return ne.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},xt=async({netlify:e,config:t})=>{let r,i,n,o,s=e.constants?.SITE_ID;if(!s)throw new Error("No site id");let l=async()=>{clearTimeout(n),ne.log("Requesting AI gateway information");let u=await Et(s,t.id,t.sessionId);if({token:r,url:o}=u,i=u.expires_at?u.expires_at*1e3:void 0,ne.log("Got AI gateway information",{token:!!r,expiresAt:i,url:o}),i){let c=i-Date.now()-6e4;c>0&&(n=setTimeout(()=>{l()},c))}};return await Promise.all([l(),Tt()]),{get url(){return o},get token(){return r},isModelAvailableForProvider:fr}};import H from"process";import W from"path";import Ae from"fs";import{fileURLToPath as wr}from"url";import{createRequire as Tr}from"module";import{execa as xr,execaCommand as ti}from"execa";import{Transform as mr}from"stream";var gr=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_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"]),hr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function yr(){return Object.entries(process.env).filter(([e,t])=>!(!t||gr.has(e)||hr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function q(e){if(typeof e!="string")return e;let t=yr();if(t.length===0)return e;let r=e;return t.forEach(i=>{let n=new RegExp(_r(i),"g");r=r.replace(n,"******")}),r}function _r(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ie=class extends mr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,i){let n=t.toString(),o=q(n);i(null,o)}};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(i,n,o){let s=typeof i=="string"?q(i):i;return typeof n=="function"?t(s,n):t(s,n,o)},process.stderr.write=function(i,n,o){let s=typeof i=="string"?q(i):i;return typeof n=="function"?r(s,n):r(s,n,o)}}var we=null,vt=e=>(we&&we.destroy(),we=new V({totalAllowedTime:e}),we),Rt=()=>we;var V=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,i)=>{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.`)}),o=null,s=null;i!==void 0&&(s=new Promise((l,u)=>{o=setTimeout(()=>{u(new Error(`${t} stage exceeded its maximum duration of ${i}ms`))},i)}));try{return s?await Promise.race([r(),s]):await r()}finally{n(),o&&clearTimeout(o)}};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 St="netlify-agent-runner-context.md",qe="task-history",We="netlify-context",k=".netlify",Q="results.md",Ke="assets";var ee=1800*1e3;var bt={name:"@netlify/agent-runner-cli",type:"module",version:"1.65.1",description:"CLI tool for running Netlify agents",main:"./dist/index.js",types:"./dist/index.d.ts",exports:"./dist/index.js",bin:{"agent-runner-cli":"./dist/bin.js","agent-runner-cli-local":"./dist/bin-local.js"},files:["dist/**/*.js","dist/**/*.d.ts","patches","scripts"],scripts:{build:"tsup",dev:"tsup --watch",prepare:"husky install node_modules/@netlify/eslint-config-node/.husky/",prepublishOnly:"npm ci && npm test",prepack:"npm run build",test:"run-s build format test:dev",format:"run-s build format:check-fix:*","format:ci":"run-s build format:check:*","format:check-fix:lint":"run-e format:check:lint format:fix:lint","format:check:lint":"cross-env-shell eslint $npm_package_config_eslint","format:fix:lint":"cross-env-shell eslint --fix $npm_package_config_eslint","format:check-fix:prettier":"run-e format:check:prettier format:fix:prettier","format:check:prettier":"cross-env-shell prettier --check $npm_package_config_prettier","format:fix:prettier":"cross-env-shell prettier --write $npm_package_config_prettier","test:dev":"run-s build test:dev:*","test:ci":"run-s build test:ci:*","test:dev:vitest":"LOG=0 vitest --exclude '**/integration/**'","test:ci:vitest":"LOG=0 c8 -r lcovonly -r text -r json vitest --exclude '**/integration/**'","test:integration":"vitest run test/integration/","test:integration:codex":"vitest run test/integration/codex.test.ts","test:integration:claude":"vitest run test/integration/claude.test.ts","test:integration:gemini":"vitest run test/integration/gemini.test.ts",postinstall:"node scripts/postinstall.js"},config:{eslint:'--cache --format=codeframe --max-warnings=0 "{src,scripts,test,.github}/**/*.{js,ts,md,html}"',prettier:'--ignore-path .gitignore --loglevel=warn "{src,scripts,test,.github}/**/*.{js,ts,md,yml,json,html}" "*.{js,ts,yml,json,html}" ".*.{js,ts,yml,json,html}" "!**/package-lock.json" "!package-lock.json"'},keywords:[],license:"MIT",repository:"netlify/agent-runner-cli",bugs:{url:"https://github.com/netlify/agent-runner-cli/issues"},author:"Netlify Inc.",directories:{test:"test"},devDependencies:{"@commitlint/cli":"^20.0.0","@commitlint/config-conventional":"^20.0.0","@eslint/compat":"^2.0.0","@eslint/js":"^9.35.0","@netlify/eslint-config-node":"^7.0.1","@types/node":"^24.5.0","@typescript-eslint/eslint-plugin":"^8.0.0","@typescript-eslint/parser":"^8.0.0","@vitest/eslint-plugin":"^1.6.6",c8:"^10.0.0","eslint-config-prettier":"^10.1.8","eslint-plugin-n":"^17.0.0",husky:"^9.0.0","patch-package":"^8.0.0",tsup:"^8.5.0",typescript:"^5.0.0","typescript-eslint":"^8.44.0",vitest:"^4.0.16"},dependencies:{"@anthropic-ai/claude-code":"2.1.32","@google/gemini-cli":"0.25.2","@netlify/otel":"^5.1.1","@openai/codex":"0.93.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.208.0",execa:"^9.6.1",minimist:"^1.2.8"}};var Ir=wr(import.meta.url),vr=W.dirname(Ir),Rr=Tr(import.meta.url),oe=E("shell"),Ve=new Set,Sr={preferLocal:!0},$=(e,t,r)=>{let[i,n]=br(t,r),o={...Sr,...n},s=xr(e,i,o);Ar(s,o),Cr(s);let l=r?.idleTimeout;return l&&l>0&&Nr(s,l),s};var br=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(H.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new ie).pipe(H.stdout),e.stdout?.pipe(new ie).pipe(H.stdout),e.stderr?.pipe(new ie).pipe(H.stderr);return}e.stdout?.pipe(H.stdout),e.stderr?.pipe(H.stderr)},Je=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(H.kill(-e.pid,t),oe.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return oe.error("Error killing process:",r),!1}},At=e=>Je(e,"SIGKILL"),Nr=(e,t)=>{let r=null,i=()=>{oe.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),Je(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(oe.log(`Force killing idle process ${e.pid}`),At(e))},5e3)},n=()=>{r&&clearTimeout(r),r=setTimeout(i,t)};n(),e.stdout?.on("data",n),e.stderr?.on("data",n);let o=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",o),e.on("error",o)},Cr=e=>{Ve.add(e);let t=Rt();if(t){let r=t.onTimesUp(()=>{oe.log(`Global timer expired, killing process ${e.pid}`),Je(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(oe.log(`Force killing process ${e.pid} after timeout`),At(e))},5e3)});e.on("exit",()=>{Ve.delete(e),r()}),e.on("error",()=>{Ve.delete(e),r()})}};function se(e,t){if(!H.env.NETLIFY_LOCAL_MODE)try{let n=Rr.resolve(bt.name),o=W.dirname(n);for(;o!==W.dirname(o);){let s=W.dirname(o);if(W.basename(s)==="node_modules"){let l=W.join(s,".bin",t);if(Ae.existsSync(l))return l;break}o=s}}catch(n){console.error("Could not resolve package.json",n)}if(H.env.NODE_PATH){let n=W.join(H.env.NODE_PATH,".bin",t);if(Ae.existsSync(n))return n}let r=W.join(e,"node_modules",".bin",t);if(Ae.existsSync(r))return r;let i=W.join(vr,"..","node_modules",".bin",t);if(Ae.existsSync(i))return i}var Pr=E("utils"),Or=e=>new Promise(t=>{setTimeout(t,e)}),Nt=(e,t=3e3)=>{let r=!1,i=null,n=[],o=null,s=(...l)=>{if(r)return i=l,new Promise(f=>{n.push(f)});r=!0;let u,c=new Promise(f=>{u=f});return o=(async()=>{await Promise.resolve();let f=await e(...l);for(u(f);;){if(await Or(t),!i)return r=!1,o=null,f;let d=i,m=n;i=null,n=[],f=await e(...d),m.forEach(y=>{y(f)})}})(),c};return s.flush=async()=>{if((r||i)&&o)return await o,s.flush()},s},ae=(e,t,r=!1)=>{let i=null,n=null,o=null,s=function(...l){n=l,o=this;let u=r&&!i;clearTimeout(i),i=setTimeout(()=>{i=null,r||(e.apply(o,n),n=null,o=null)},t),u&&(e.apply(o,n),n=null,o=null)};return s.cancel=()=>{clearTimeout(i),i=null,n=null,o=null},s.flush=()=>{if(i){clearTimeout(i);let l=n,u=o;i=null,n=null,o=null,e.apply(u,l)}},s},Ct=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(i){t&&(r?.error?r.error("Could not parse JSON",i):Pr.error("Could not parse JSON",i))}},Pt=(e,t)=>{let n=".netlify.app",o="agent-";if(!t)return`${o}${e.slice(0,6)}`;let l=`--${t}${n}`;if(l.length>55)return"";let u=60-l.length;if(u<=0)return"";if(u>=o.length+6){let c=Math.min(u-o.length,e.length);return`${o}${e.slice(0,c)}`}return e.slice(0,u)};var $r=50*1024,Xe=(e,t=$r)=>{if(!e||typeof e!="string"||e.length<=t)return e;let i=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+i};import{Buffer as Ot}from"buffer";import Fr from"path";var $t=E("repo"),Ft=async({config:e,isRetry:t})=>{$t.info("Getting runner diffs");let r=await Lr(),{hasChanges:i}=r,{status:n}=r;if(!i)return{hasChanges:!1};if(!t){let T=kr(n);await Ur(T)}$t.info("Changes after processing"),await Ze();let o=await Qe(n);await ze(o);let s={stdio:["ignore","pipe","pipe"]},l=await $("git",["diff","--staged"],s),u=String(l.stdout??"");if(i=!!u,!i)return{hasChanges:!1,ignored:o};let c=await $("git",["diff","--staged","--binary"],s),f=String(c.stdout??""),d,m;if(e.sha){if(!process.env.NETLIFY_LOCAL_MODE){process.env.NETLIFY_INTERNAL_GIT="1";try{await $("git",["commit","-m","Agent runner"])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}}let T=await $("git",["diff",e.sha,"HEAD"],s);d=String(T.stdout??"");let _=await $("git",["diff",e.sha,"HEAD","--binary"],s),g=String(_.stdout??"");d!==g&&(m=Ot.from(g).toString("base64"))}let y={hasChanges:!0,diff:u,resultDiff:d,ignored:o};return u!==f&&(y.diffBinary=Ot.from(f).toString("base64")),m&&(y.resultDiffBinary=m),y},ze=async(e=[])=>{process.env.NETLIFY_INTERNAL_GIT="1";try{await $("git",["add",".",...e])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}},Ze=async()=>{let e=await $("git",["status","-s"]);return String(e.stdout??"")},Dt=/.. (.+)?\.log$/,Dr=[Dt],Lr=async()=>{let e=await Ze();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
8
|
-
`).filter(
|
|
9
|
-
`).forEach(
|
|
10
|
-
`).reduce((r,
|
|
7
|
+
`);return s.length>e.length*.8?e:s}import{execSync as tn}from"child_process";import Jt from"fs/promises";import rn from"path";import X from"process";import{getTracer as nn}from"@netlify/otel";import ye from"process";var re=class extends Error{constructor(r,n,i){super(r);this.statusCode=n;this.userMessage=i;this.name="GracefulShutdownError"}},gt=e=>e instanceof re;var ve=ye.env.NETLIFY_API_URL,Se=ye.env.NETLIFY_API_TOKEN,Y=E("api"),Ae=()=>ye.env.NETLIFY_LOCAL_MODE==="true",_e=async(e,t={})=>{if(!ve||!Se)throw new Error("No API URL or token");let r=new URL(e,ve),n={...t,headers:{...t.headers,Authorization:`Bearer ${Se}`}};ye.env.AGENT_RUNNERS_DEBUG==="true"&&(n.headers["x-nf-debug-logging"]="true"),t.json&&(n.headers||={},n.headers["Content-Type"]="application/json",n.body=JSON.stringify(t.json));let i=await fetch(r,n),s=i.ok&&i.status<=299;if(ye.env.AGENT_RUNNERS_DEBUG==="true")Y.log(`Response headers for ${r}:`),i.headers.forEach((a,c)=>{Y.log(` ${c}: ${a}`)});else{let a=i.headers.get("x-request-id")||i.headers.get("x-nf-request-id");Y.log(`Request ID for ${r}: ${a||"N/A"}`)}if(s||Y.error(`Got status ${i.status} for request ${r}`),t.raw){if(!s)throw new Error(`API request failed: ${i.status} ${i.statusText}`);return i}let o=await(i.headers.get("content-type")?.includes("application/json")?i.json():i.text());if(!s){let a=typeof o=="string"?o:JSON.stringify(o);throw i.status===404?new re(`API request failed: 404 - ${a}`,404,"The site associated with this agent run no longer exists."):i.status===403&&t.gracefulOn403?new re(`API request failed: 403 - ${a}`,403,"Credit limit reached. Please add more credits to continue using Agent Runners."):new Error(`API request failed: ${i.status} - ${a}`)}return o},ht=e=>{Y.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(ve=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Se=e.constants.NETLIFY_API_TOKEN)},yt=()=>({apiUrl:ve,token:Se}),Ee=async(e,t)=>Ae()?(Y.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):_e(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),G=async(e,t,r)=>Ae()?(Y.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):_e(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var _t=async(e,t)=>Ae()?(Y.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):_e(`/api/v1/agent_runners/${e}/sessions/${t}`),Et=(e,t,r)=>_e(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn403:!0}),wt=async(e,t)=>Ae()?(Y.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"}}):_e(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Ye=async(e,t)=>{Y.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 ne=E("ai_gateway"),Be=null;var Tt=async()=>{if(Be)return Be;ne.log("Fetching available AI gateway providers");let e=await fetch(`${yt().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,ne.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},mr=async(e,t)=>{let n=(await Tt()).providers[e];if(!n)return ne.log(`Provider '${e}' not found`),!1;let i=n.models.includes(t);return ne.log(`Model validation for ${e}/${t}`,{isAvailable:i}),i},It=async({netlify:e,config:t})=>{let r,n,i,s,o=e.constants?.SITE_ID;if(!o)throw new Error("No site id");let a=async()=>{clearTimeout(i),ne.log("Requesting AI gateway information");let c=await Et(o,t.id,t.sessionId);if({token:r,url:s}=c,n=c.expires_at?c.expires_at*1e3:void 0,ne.log("Got AI gateway information",{token:!!r,expiresAt:n,url:s}),n){let d=n-Date.now()-6e4;d>0&&(i=setTimeout(()=>{a()},d))}};return await Promise.all([a(),Tt()]),{get url(){return s},get token(){return r},isModelAvailableForProvider:mr}};import H from"process";import W from"path";import be from"fs";import{fileURLToPath as Tr}from"url";import{createRequire as Ir}from"module";import{execa as xr,execaCommand as si}from"execa";import{Transform as gr}from"stream";var hr=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_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"]),yr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function _r(){return Object.entries(process.env).filter(([e,t])=>!(!t||hr.has(e)||yr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function K(e){if(typeof e!="string")return e;let t=_r();if(t.length===0)return e;let r=e;return t.forEach(n=>{let i=new RegExp(Er(n),"g");r=r.replace(i,"******")}),r}function Er(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ie=class extends gr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,n){let i=t.toString(),s=K(i);n(null,s)}};function xt(){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(n,i,s){let o=typeof n=="string"?K(n):n;return typeof i=="function"?t(o,i):t(o,i,s)},process.stderr.write=function(n,i,s){let o=typeof n=="string"?K(n):n;return typeof i=="function"?r(o,i):r(o,i,s)}}var we=null,Rt=e=>(we&&we.destroy(),we=new J({totalAllowedTime:e}),we),vt=()=>we;var J=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,n)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let i=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),s=null,o=null;n!==void 0&&(o=new Promise((a,c)=>{s=setTimeout(()=>{c(new Error(`${t} stage exceeded its maximum duration of ${n}ms`))},n)}));try{return o?await Promise.race([r(),o]):await r()}finally{i(),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 St="netlify-agent-runner-context.md",He="task-history",B=".netlify",Q="results.md",qe="assets";var ee=1800*1e3;var At={name:"@netlify/agent-runner-cli",type:"module",version:"1.66.0-alpha.0",description:"CLI tool for running Netlify agents",main:"./dist/index.js",types:"./dist/index.d.ts",exports:"./dist/index.js",bin:{"agent-runner-cli":"./dist/bin.js","agent-runner-cli-local":"./dist/bin-local.js"},files:["dist/**/*.js","dist/**/*.d.ts","dist/skills/**","patches","scripts"],scripts:{build:"tsup",dev:"tsup --watch",prepare:"husky install node_modules/@netlify/eslint-config-node/.husky/",prepublishOnly:"npm ci && npm test",prepack:"npm run build",test:"run-s build format test:dev",format:"run-s build format:check-fix:*","format:ci":"run-s build format:check:*","format:check-fix:lint":"run-e format:check:lint format:fix:lint","format:check:lint":"cross-env-shell eslint $npm_package_config_eslint","format:fix:lint":"cross-env-shell eslint --fix $npm_package_config_eslint","format:check-fix:prettier":"run-e format:check:prettier format:fix:prettier","format:check:prettier":"cross-env-shell prettier --check $npm_package_config_prettier","format:fix:prettier":"cross-env-shell prettier --write $npm_package_config_prettier","test:dev":"run-s build test:dev:*","test:ci":"run-s build test:ci:*","test:dev:vitest":"LOG=0 vitest --exclude '**/integration/**'","test:ci:vitest":"LOG=0 c8 -r lcovonly -r text -r json vitest --exclude '**/integration/**'","test:integration":"vitest run test/integration/","test:integration:codex":"vitest run test/integration/codex.test.ts","test:integration:claude":"vitest run test/integration/claude.test.ts","test:integration:gemini":"vitest run test/integration/gemini.test.ts",postinstall:"node scripts/postinstall.js"},config:{eslint:'--cache --format=codeframe --max-warnings=0 "{src,scripts,test,.github}/**/*.{js,ts,md,html}"',prettier:'--ignore-path .gitignore --loglevel=warn "{src,scripts,test,.github}/**/*.{js,ts,md,yml,json,html}" "*.{js,ts,yml,json,html}" ".*.{js,ts,yml,json,html}" "!**/package-lock.json" "!package-lock.json"'},keywords:[],license:"MIT",repository:"netlify/agent-runner-cli",bugs:{url:"https://github.com/netlify/agent-runner-cli/issues"},author:"Netlify Inc.",directories:{test:"test"},devDependencies:{"@commitlint/cli":"^20.0.0","@commitlint/config-conventional":"^20.0.0","@eslint/compat":"^2.0.0","@eslint/js":"^9.35.0","@netlify/eslint-config-node":"^7.0.1","@types/node":"^24.5.0","@typescript-eslint/eslint-plugin":"^8.0.0","@typescript-eslint/parser":"^8.0.0","@vitest/eslint-plugin":"^1.6.6",c8:"^10.0.0","eslint-config-prettier":"^10.1.8","eslint-plugin-n":"^17.0.0",husky:"^9.0.0","patch-package":"^8.0.0",tsup:"^8.5.0",typescript:"^5.0.0","typescript-eslint":"^8.44.0",vitest:"^4.0.16"},dependencies:{"@anthropic-ai/claude-code":"2.1.32","@google/gemini-cli":"0.25.2","@netlify/otel":"^5.1.1","@openai/codex":"0.93.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.208.0",execa:"^9.6.1",minimist:"^1.2.8"}};var Rr=Tr(import.meta.url),vr=W.dirname(Rr),Sr=Ir(import.meta.url),oe=E("shell"),Ke=new Set,Ar={preferLocal:!0},D=(e,t,r)=>{let[n,i]=br(t,r),s={...Ar,...i},o=xr(e,n,s);Nr(o,s),Pr(o);let a=r?.idleTimeout;return a&&a>0&&Cr(o,a),o};var br=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Nr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(H.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new ie).pipe(H.stdout),e.stdout?.pipe(new ie).pipe(H.stdout),e.stderr?.pipe(new ie).pipe(H.stderr);return}e.stdout?.pipe(H.stdout),e.stderr?.pipe(H.stderr)},We=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(H.kill(-e.pid,t),oe.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return oe.error("Error killing process:",r),!1}},bt=e=>We(e,"SIGKILL"),Cr=(e,t)=>{let r=null,n=()=>{oe.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),We(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(oe.log(`Force killing idle process ${e.pid}`),bt(e))},5e3)},i=()=>{r&&clearTimeout(r),r=setTimeout(n,t)};i(),e.stdout?.on("data",i),e.stderr?.on("data",i);let s=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",s),e.on("error",s)},Pr=e=>{Ke.add(e);let t=vt();if(t){let r=t.onTimesUp(()=>{oe.log(`Global timer expired, killing process ${e.pid}`),We(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(oe.log(`Force killing process ${e.pid} after timeout`),bt(e))},5e3)});e.on("exit",()=>{Ke.delete(e),r()}),e.on("error",()=>{Ke.delete(e),r()})}};function se(e,t){if(!H.env.NETLIFY_LOCAL_MODE)try{let i=Sr.resolve(At.name),s=W.dirname(i);for(;s!==W.dirname(s);){let o=W.dirname(s);if(W.basename(o)==="node_modules"){let a=W.join(o,".bin",t);if(be.existsSync(a))return a;break}s=o}}catch(i){console.error("Could not resolve package.json",i)}if(H.env.NODE_PATH){let i=W.join(H.env.NODE_PATH,".bin",t);if(be.existsSync(i))return i}let r=W.join(e,"node_modules",".bin",t);if(be.existsSync(r))return r;let n=W.join(vr,"..","node_modules",".bin",t);if(be.existsSync(n))return n}var Or=E("utils"),kr=e=>new Promise(t=>{setTimeout(t,e)}),Nt=(e,t=3e3)=>{let r=!1,n=null,i=[],s=null,o=(...a)=>{if(r)return n=a,new Promise(p=>{i.push(p)});r=!0;let c,d=new Promise(p=>{c=p});return s=(async()=>{await Promise.resolve();let p=await e(...a);for(c(p);;){if(await kr(t),!n)return r=!1,s=null,p;let u=n,m=i;n=null,i=[],p=await e(...u),m.forEach(g=>{g(p)})}})(),d};return o.flush=async()=>{if((r||n)&&s)return await s,o.flush()},o},ae=(e,t,r=!1)=>{let n=null,i=null,s=null,o=function(...a){i=a,s=this;let c=r&&!n;clearTimeout(n),n=setTimeout(()=>{n=null,r||(e.apply(s,i),i=null,s=null)},t),c&&(e.apply(s,i),i=null,s=null)};return o.cancel=()=>{clearTimeout(n),n=null,i=null,s=null},o.flush=()=>{if(n){clearTimeout(n);let a=i,c=s;n=null,i=null,s=null,e.apply(c,a)}},o},Ct=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(n){t&&(r?.error?r.error("Could not parse JSON",n):Or.error("Could not parse JSON",n))}},Pt=(e,t)=>{let i=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let a=`--${t}${i}`;if(a.length>55)return"";let c=60-a.length;if(c<=0)return"";if(c>=s.length+6){let d=Math.min(c-s.length,e.length);return`${s}${e.slice(0,d)}`}return e.slice(0,c)};var $r=50*1024,Ve=(e,t=$r)=>{if(!e||typeof e!="string"||e.length<=t)return e;let n=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+n};import{Buffer as Ot}from"buffer";import Dr from"path";var kt=E("repo"),$t=async({config:e,isRetry:t})=>{kt.info("Getting runner diffs");let r=await Lr(),{hasChanges:n}=r,{status:i}=r;if(!n)return{hasChanges:!1};if(!t){let y=Ur(i);await Mr(y)}kt.info("Changes after processing"),await Xe();let s=await ze(i);await Je(s);let o={stdio:["ignore","pipe","pipe"]},a=await D("git",["diff","--staged"],o),c=String(a.stdout??"");if(n=!!c,!n)return{hasChanges:!1,ignored:s};let d=await D("git",["diff","--staged","--binary"],o),p=String(d.stdout??""),u,m;if(e.sha){if(!process.env.NETLIFY_LOCAL_MODE){process.env.NETLIFY_INTERNAL_GIT="1";try{await D("git",["commit","-m","Agent runner"])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}}let y=await D("git",["diff",e.sha,"HEAD"],o);u=String(y.stdout??"");let w=await D("git",["diff",e.sha,"HEAD","--binary"],o),_=String(w.stdout??"");u!==_&&(m=Ot.from(_).toString("base64"))}let g={hasChanges:!0,diff:c,resultDiff:u,ignored:s};return c!==p&&(g.diffBinary=Ot.from(p).toString("base64")),m&&(g.resultDiffBinary=m),g},Je=async(e=[])=>{process.env.NETLIFY_INTERNAL_GIT="1";try{await D("git",["add",".",...e])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}},Xe=async()=>{let e=await D("git",["status","-s"]);return String(e.stdout??"")},Dt=/.. (.+)?\.log$/,Fr=[Dt],Lr=async()=>{let e=await Xe();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
8
|
+
`).filter(n=>Fr.some(s=>s instanceof RegExp?s.test(n):n===s)?!1:n[1]?.trim()!=="")).length!==0,status:e}},Ft=async()=>{let{stdout:e}=await D("git",["rev-parse","HEAD"]);return String(e??"").trim()},Lt=async()=>{let{stdout:e}=await D("git",["rev-list","--max-parents=0","HEAD"]);return String(e??"").trim()},ze=async e=>{e||=await Xe();let t=[".netlify","node_modules","dist",".next","out",".nuxt",".output",".cache",".turbo",".parcel-cache","coverage",".nyc_output","storybook-static","public/build"],r=[];return e.split(`
|
|
9
|
+
`).forEach(n=>{t.forEach(s=>{let o=n===`?? ${s}`,a=n.startsWith(`?? ${s}/`)||n.startsWith(`?? ${s}${Dr.sep}`);(o||a)&&r.push(`:!${s}`)});let i=n.match(Dt)?.[1];i&&r.push(`:!${i}.log`)}),r},Ze=async()=>{await D("git",["reset","--hard","HEAD"])},Ur=e=>{let t=e.split(`
|
|
10
|
+
`).reduce((r,n)=>{if(!n)return r;let[i,s,,...o]=n,a=o.join(""),c=i.trim(),d=s.trim();return r[a]?r[a].change=d:r[a]={filePath:a,stage:c,change:d},r},{});return Object.values(t)},Mr=async e=>{let t=[];for(let r of e)r.stage&&!r.change&&t.push(D("git",["restore","--staged","--worktree",r.filePath]));await Promise.allSettled(t)};import jr from"fs/promises";import Yr from"os";import Gt from"path";import pe from"process";import Br from"readline";import Qe from"path";import Gr from"fs/promises";var et=E("agent-output-utils");async function le({initialResult:e,agentName:t,hasError:r}){let n="",i=Qe.join(process.cwd(),B,Q);try{let s=await Gr.readFile(i,"utf-8");s&&(n=s,et.log(`Pulled result from ${Qe.relative(process.cwd(),i)}`))}catch{et.log(`No results file found at ${Qe.relative(process.cwd(),i)}`)}return n||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function ce({error:e,agentName:t}){let r=e&&typeof e=="object"?JSON.stringify(e):e,n=r?.replace(/\s+/g," ").trim().toLowerCase()||"",i="";return n?.includes("ai gateway is not available for your account")||n?.includes("ai gateway is not enabled for your account")?i="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.":n?.includes("error when talking to gemini api")?i="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":(n?.includes("connection closed prematurely")||n?.includes("499")&&t.toLowerCase().includes("gemini"))&&(i=`The ${t} models were currently overloaded. Please try again or use a different available agent.`),n?.includes("request timed out")&&(i=`The ${t} API request's have timed out. Please try again or use a different available agent.`),n?.includes("network error")&&(i=`The ${t} agent is having network issues. Please try again or use a different available agent.`),n?.includes("503")&&(i=`The ${t} API is currently experiencing high load. Retrying automatically...`),i&&et.log(`Providing updated error messsage: ${i}, replacing original error: ${r}`),i||r||void 0}function ue(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")||r?.includes("503"))}var L=E("runner_claude"),Ut="Claude Code",de="claude-opus-4-6",Mt=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,Hr=({catchError:e,runCmd:t,error:r,result:n,runnerName:i})=>(L.log(`${i} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(L.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(L.log("Setting result to undefined because no valid result was captured"),{error:r||`${i} failed`,result:void 0}));async function tt({config:e,netlify:t,persistSteps:r,aiGateway:n,continueSession:i,priorAgentSessionId:s,cwd:o=pe.cwd()}){let a=e,{accountType:c,prompt:d,modelVersionOverrides:p}=a,{model:u}=a,m="";if(n){let{token:h,url:f}=n;if(!h||!f)throw new Error("No token or url provided from AI Gateway");if(p?.claude){let l=p?.claude?.[c];if(l){if(!await n.isModelAvailableForProvider("anthropic",l))throw new Error(`Model override '${l}' is not available for anthropic provider`);u=l}}else if(u){if(!await n.isModelAvailableForProvider("anthropic",u))throw new Error(`Model '${u}' is not available for anthropic provider`)}else!!de&&await n.isModelAvailableForProvider("anthropic",de)?(u=de,L.log(`Using default model: ${de}`)):de&&L.log(`Default model ${de} is not available, proceeding without model specification`);pe.env.ANTHROPIC_API_KEY=h,pe.env.ANTHROPIC_BASE_URL=f}else if(!pe.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let g=[],y=[],w={},_=0,I=0,b,S,k=[se(o,"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose","--disallowed-tools","ExitPlanMode,AskUserQuestion",...u?["--model",u]:[],...i?["--continue"]:[],...i&&s?["--resume",s]:[],"-p",d],P=`${pe.env.NVM_BIN}/node`;L.log(`Running ${P} ${k.join(" ")}`);let $=t.utils.run(P,k,{all:!0,env:pe.env,cwd:o,idleTimeout:ee});$.stdin?.end();let x=ae(()=>{r?.({steps:g,duration:I})},250),R=(h,f)=>{let l={...h,id:_};_+=1,y.push(l),g.push(l),f||x.flush(),x(),f&&x.flush()},F=Br.createInterface({input:$.all});return F.on("error",h=>{L.error("Readline interface error",{error:h.message,stack:h.stack})}),F.on("line",h=>{let f=null;try{f=JSON.parse(h)}catch{L.log("Could not parse line",h)}f?.session_id&&f.session_id!==m&&(m=f.session_id),Array.isArray(f?.message?.content)?f.message.content.forEach(l=>{switch(l.type){case"text":{l.text&&R({message:l.text});break}case"image":{typeof l.source=="object"&&l.source&&l.source.type==="base64"&&l.source.media_type?R({message:``}):L.log(`Unsupported image type ${l.source?.type}`,l.source);break}case"tool_use":{if(l.name==="Task"){let T=l.input?.description&&`\`${l.input.description}\``;R({title:[Mt(l.name),T].filter(Boolean).join(" ")})}else l.id&&(w[l.id]=l);x.flush();break}case"tool_result":{let T=l.tool_use_id?w[l.tool_use_id]:void 0,z;if(T){let V=T.input?.file_path&&Gt.relative(o,T.input.file_path),O=V&&`\`${V}\``;z=[Mt(T.name||""),O].filter(Boolean).join(" ")}let Re=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(T?.name||""),Z;if(typeof l.content=="string")Z=l.content;else if(Array.isArray(l.content)){let V=[];l.content.forEach(O=>{O?.type==="text"&&typeof O.text=="string"?V.push(O.text):O?.type==="image"&&typeof O.source=="object"&&O.source?O.source.type==="base64"&&O.source.media_type?V.push(``):L.log(`Unsupported image type ${O.source.type}`,O.source):L.log(`Unsupported block type ${O?.type}`)}),Z=V.join(`
|
|
11
11
|
|
|
12
|
-
`)}
|
|
12
|
+
`)}Re&&Z&&(Z=`\`\`\`
|
|
13
13
|
${Z.trim()}
|
|
14
|
-
\`\`\``),
|
|
15
|
-
web_search_request = true`):
|
|
14
|
+
\`\`\``),R({title:z,message:Z},!0);break}case"thinking":{l.thinking&&R({title:"Thinking",message:l.thinking},!0);break}default:L.log(`Message content type is not supported ${l.type}`,l)}}):f?.type==="result"&&(I=f.duration_ms||0,f.is_error?S=f.result:b=f.result,[y,g].forEach(l=>{l[l.length-1]?.message===b&&l.pop()}))}),await $.catch(h=>{({error:S,result:b}=Hr({catchError:h,runCmd:$,error:S,result:b,runnerName:"Claude"}))}),F.close(),x.flush(),{steps:y,duration:I,result:await le({initialResult:b,agentName:Ut,hasError:!!S}),error:ce({error:S,agentName:Ut}),isRetryableError:ue(S),agentSessionId:m}}var jt=async()=>{let e=Gt.join(Yr.homedir(),".claude");await jr.rm(e,{recursive:!0,force:!0})};import Te from"fs/promises";import Bt from"os";import Ne from"path";import te from"process";import qr from"readline";var U=E("runner_codex"),Yt="Codex CLI",fe="",Kr=({catchError:e,runCmd:t,error:r,result:n,runnerName:i})=>(U.log(`${i} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(U.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(U.log("Setting result to undefined because no valid result was captured"),{error:r||`${i} failed`,result:void 0}));async function rt({config:e,netlify:t,persistSteps:r=void 0,sendSteps:n=void 0,aiGateway:i,cwd:s=te.cwd()}){let{accountType:o,prompt:a,modelVersionOverrides:c}=e,{model:d}=e;if(i){let{token:f,url:l}=i;if(!f||!l)throw new Error("No token or url provided from AI Gateway");if(c?.codex){let T=c?.codex?.[o];if(T){if(!await i.isModelAvailableForProvider("openai",T))throw new Error(`Model override '${T}' is not available for openai provider`);d=T}}else if(d){if(!await i.isModelAvailableForProvider("openai",d))throw new Error(`Model '${d}' is not available for openai provider`)}else!!fe&&await i.isModelAvailableForProvider("openai",fe)?(d=fe,U.log(`Using default model: ${fe}`)):fe&&U.log(`Default model ${fe} is not available, proceeding without model specification`);te.env.OPENAI_API_KEY=f,te.env.OPENAI_BASE_URL=l}else if(!te.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let p=[],u=[],m=[],g={},y=0,w=0,_,I,b=`${te.env.NVM_BIN}/node`,S=Ne.join(Bt.homedir(),".codex"),k=Ne.join(S,"config.toml"),P=Ne.join(S,"auth.json");try{await Te.mkdir(S,{recursive:!0});let f={OPENAI_API_KEY:te.env.OPENAI_API_KEY};await Te.writeFile(P,JSON.stringify(f,null,2),"utf-8"),U.log("Created Codex auth.json file");let l="";try{l=await Te.readFile(k,"utf-8")}catch{}l.includes("web_search_request")||(l.includes("[features]")?l=l.replace(/\[features\]/,`[features]
|
|
15
|
+
web_search_request = true`):l+=`
|
|
16
16
|
[features]
|
|
17
17
|
web_search_request = true
|
|
18
|
-
`,await Te.writeFile(
|
|
19
|
-
`):
|
|
20
|
-
`))}),await
|
|
21
|
-
${
|
|
22
|
-
\`\`\``),e.status==="failed"&&e.exit_code!==0&&(
|
|
23
|
-
|
|
24
|
-
*Exit code: ${e.exit_code}*`:`*Command failed with exit code: ${e.exit_code}*`),{title:r,message:
|
|
25
|
-
${
|
|
26
|
-
\`\`\``)}catch(
|
|
27
|
-
${
|
|
28
|
-
\`\`\``)
|
|
18
|
+
`,await Te.writeFile(k,l,"utf-8"),U.log("Updated Codex config with web_search_request enabled"))}catch(f){throw U.warn("Failed to setup Codex config and credentials",{error:f.message}),new Error(`Codex setup failed: ${f.message}`)}let $=[se(s,"codex"),"exec","--yolo","--json","--enable","web_search_request",...d?["--model",d]:[],a].filter(Boolean);U.log(`Running ${b} ${$.join(" ")}`);let x=t.utils.run(b,$,{all:!0,cwd:s,env:{...te.env},idleTimeout:ee}),R=ae(()=>{r?.({steps:p,duration:w}),n?.({steps:u,duration:w}),u=[]},250),F=(f,l)=>{f.id=y,y+=1,m.push(f),p.push(f),u.push(f),l||R.flush(),R(),l&&R.flush()},h=qr.createInterface({input:x.all});return h.on("error",f=>{U.error("Readline interface error",{error:f.message,stack:f.stack})}),h.on("line",f=>{let l=null;try{l=JSON.parse(f)}catch{U.log("Could not parse line",f);return}if(l?.duration_ms&&(w=l.duration_ms),l?.type==="item.started"&&l?.item?.type==="command_execution")g[l.item.id]=l.item;else if(l?.type==="item.completed"&&l?.item?.type==="command_execution"){let T=Vr(l.item);T&&F(T,!0)}else if(l?.type==="item.completed"&&l?.item?.type==="reasoning"){let T={title:"Reasoning",message:l.item.text};F(T,!0)}else if(l?.type==="local_shell_call")g[l.call_id]=l;else if(l?.type==="local_shell_call_output"){let T=Jr(g[l.call_id],l);T&&F(T,!0)}else l?.type==="message"&&l.role==="assistant"?_=l.content.map(T=>T.text).join(`
|
|
19
|
+
`):l?.type==="message"&&l.role==="system"&&(I=l.content.map(T=>T.text).join(`
|
|
20
|
+
`))}),await x.catch(f=>{let l=Kr({catchError:f,runCmd:x,error:I,result:_,runnerName:"Codex"});I=l.error,_=l.result}),h.close(),R.flush(),{steps:m,duration:w,result:await le({initialResult:_,agentName:Yt,hasError:!!I}),error:ce({error:I,agentName:Yt}),isRetryableError:ue(I)}}var Ht=async()=>{let e=Ne.join(Bt.homedir(),".codex");await Te.rm(e,{recursive:!0,force:!0})},Wr=new Set(["bash","-lc"]),Vr=e=>{if(!e||e.type!=="command_execution")return null;let t=e.command;t.startsWith("bash -lc ")&&(t=t.replace(/^bash -lc ['"]/,"").replace(/['"]$/,""));let r=`Running \`${t}\``,n=e.aggregated_output?.trim();return n&&(n=`\`\`\`
|
|
21
|
+
${n}
|
|
22
|
+
\`\`\``),e.status==="failed"&&e.exit_code!==0&&(n=n?`${n}
|
|
23
|
+
|
|
24
|
+
*Exit code: ${e.exit_code}*`:`*Command failed with exit code: ${e.exit_code}*`),{title:r,message:n}},Jr=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!Wr.has(s)),n=r?`Running \`${r.join(" ")}\``:void 0,i;try{i=JSON.parse(t.output).output?.trim(),i&&(i=`\`\`\`
|
|
25
|
+
${i.trim()}
|
|
26
|
+
\`\`\``)}catch(s){U.error("Could not decode outputMsg",s,t.output)}return{title:n,message:i}};import Ce from"fs/promises";import Kt from"os";import Pe from"path";import me from"process";import Xr from"readline";var j=E("runner_gemini"),qt="Gemini CLI",ge="",zr=({catchError:e,runCmd:t,error:r,result:n,runnerName:i})=>(j.log(`${i} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(j.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(j.log("Setting result to undefined because no valid result was captured"),{error:r||`${i} failed`,result:void 0})),Zr={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"},Qr=async()=>{let e=Pe.join(Kt.homedir(),".gemini"),t=Pe.join(e,"settings.json");try{await Ce.mkdir(e,{recursive:!0});let r={};try{let n=await Ce.readFile(t,"utf-8");r=JSON.parse(n)}catch{j.log("Creating new Gemini CLI settings file")}r.general||(r.general={}),r.general.previewFeatures||(r.general.previewFeatures=!0),r.model||(r.model={}),r.model.compressionThreshold!==.3&&(r.model.compressionThreshold=.3),await Ce.writeFile(t,JSON.stringify(r,null,2),"utf-8"),j.log("Configured Gemini CLI settings (preview features and compression threshold)")}catch(r){j.error("Failed to ensure Gemini CLI settings",{error:r.message})}};async function nt({config:e,netlify:t,persistSteps:r=void 0,sendSteps:n=void 0,aiGateway:i,cwd:s=me.cwd()}){let{accountType:o,prompt:a,modelVersionOverrides:c}=e,{model:d}=e;if(await Qr(),i){let{token:h,url:f}=i;if(!h||!f)throw new Error("No token or url provided from AI Gateway");if(c?.gemini){let l=c?.gemini?.[o];if(l){if(!await i.isModelAvailableForProvider("gemini",l))throw new Error(`Model override '${l}' is not available for gemini provider`);d=l}}if(!d)!!ge&&await i.isModelAvailableForProvider("gemini",ge)?(d=ge,j.log(`Using default model: ${ge}`)):ge&&j.log(`Default model ${ge} is not available, proceeding without model specification`);else if(d&&!c?.gemini?.[o]&&!await i.isModelAvailableForProvider("gemini",d))throw new Error(`Model '${d}' is not available for gemini provider`);me.env.GEMINI_API_KEY=h,me.env.GOOGLE_GEMINI_BASE_URL=f}else if(!me.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let p=[],u=[],m=[],g={},y=0,w=0,_,I,b=[se(s,"gemini"),...d?["--model",d]:[],"--yolo","--output-format","stream-json","-p",a],S=`${me.env.NVM_BIN}/node`;j.log(`Running ${S} ${b.join(" ")}`);let k=t.utils.run(S,b,{all:!0,env:me.env,cwd:s,idleTimeout:ee});k.stdin?.end();let P=ae(()=>{r?.({steps:p,duration:w}),n?.({steps:u,duration:w}),u=[]},250),$=(h,f)=>{h.id=y,y+=1,m.push(h),p.push(h),u.push(h),f||P.flush(),P(),f&&P.flush()},x=Xr.createInterface({input:k.all});x.on("error",h=>{j.error("Readline interface error",{error:h.message,stack:h.stack})});let R="",F=()=>{R&&$({message:R.trim()}),R=""};return x.on("line",h=>{let f=null;try{if(h.startsWith("[API Error")){let l=h.match(/\[api error: (.+?)]$/i)?.[1];f={type:"error",value:Ct(l,!1)?.error?.message||l||"Gemini encountered error"}}else f=JSON.parse(h)}catch{return}if(f)switch(["message","result"].includes(f.type)||F(),f.type){case"message":{f.role!=="user"&&f.content&&(R+=f.content);break}case"tool_use":{let l=Zr[f.tool_name]??f.tool_name,T=f.parameters?.file_path,z=T&&Pe.relative(s,T),Re=f.parameters?.command,V={title:[l,z&&`\`${z}\``,Re&&`\`${Re}\``].filter(Boolean).join(" ")};g[f.tool_id]=V,P.flush();break}case"tool_result":{let l=g[f.tool_id];l&&(f.output&&(l.message=`\`\`\`
|
|
27
|
+
${f.output.trim()}
|
|
28
|
+
\`\`\``),$(l,!0));break}case"result":{w=f.stats?.duration_ms,f.status==="error"?I=f.error?.message:_=R.trim();break}case"error":{I=f.error;break}case"finished":break;default:{j.warn("Unhandled message type:",f.type);break}}}),await k.catch(h=>{({error:I,result:_}=zr({catchError:h,runCmd:k,error:I,result:_,runnerName:"Gemini"}))}),x.close(),P.flush(),{steps:m,duration:w,result:await le({initialResult:_,agentName:qt,hasError:!!I}),error:ce({error:I,agentName:qt}),isRetryableError:ue(I)}}var Wt=async()=>{let e=Pe.join(Kt.homedir(),".gemini");await Ce.rm(e,{recursive:!0,force:!0})};var en={codex:{runner:rt,clean:Ht},claude:{runner:tt,clean:jt},gemini:{runner:nt,clean:Wt}},Vt=en;var Oe=E("init_stage"),Xt=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:n})=>await C(nn(),"init-stage",async i=>{let s=performance.now();i?.setAttributes({"init.runner":e.runner,"init.id":e.id,"init.sessionId":e.sessionId,"init.hasRepo":e.hasRepo,"init.useGateway":e.useGateway,"init.runnerVersion":n||"unknown"});let o=Vt[e.runner];if(!o)throw i?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let a=sn({apiToken:r});ht(a);let c=e.useGateway?await It({netlify:a,config:e}):void 0;i?.setAttributes({"init.aiGateway.created":!!c});let d=5*1024,p=Nt(async({steps:y=[],duration:w})=>{let _=y.map(I=>{let b=I.title?Ve(K(I.title),d):void 0,S=I.message?Ve(K(I.message)):void 0;return{...I,title:b,message:S}});y.length=0;try{return await G(e.id,e.sessionId,{steps:_,duration:w})}catch(I){Oe.error("persistSteps failed",{error:I?.message||I})}},t);Oe.info("Adding build files to stage");let u=await ze();await Je(u),X.env.NETLIFY_LOCAL_MODE||await on();let m;e.hasRepo?e.sha?(m=e.sha,i?.setAttributes({"init.sha.source":"provided"})):(m=await Ft(),await Ee(e.id,{sha:m}),i?.setAttributes({"init.sha.source":"current_commit"})):(m=await Lt(),i?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let g=performance.now()-s;return i?.setAttributes({"init.sha":m||"unknown","init.duration.ms":g,"init.status":"success"}),{aiGateway:c,context:a,persistSteps:p,runner:o,sha:m}}),on=async()=>{let e="/usr/bin/git";try{e=tn("which git").toString().trim()||e}catch{}let t="/tmp/netlify-git-wrapper",r=rn.join(t,"git"),n=`#!/bin/bash
|
|
29
29
|
# Git wrapper that blocks add and commit commands
|
|
30
30
|
# The deployment system handles staging and commits automatically
|
|
31
31
|
|
|
@@ -55,90 +55,89 @@ case "$1" in
|
|
|
55
55
|
exec ${e} "$@"
|
|
56
56
|
;;
|
|
57
57
|
esac
|
|
58
|
-
`;try{await Jt.mkdir(t,{recursive:!0}),await Jt.writeFile(r,
|
|
58
|
+
`;try{await Jt.mkdir(t,{recursive:!0}),await Jt.writeFile(r,n,{mode:493}),X.env.PATH=`${t}:${X.env.PATH}`,X.env.NETLIFY_INTERNAL_GIT="0",Oe.info("Installed git wrapper to block add/commit commands")}catch(i){Oe.warn("Failed to install git wrapper",{error:i?.message||i})}},sn=({apiToken:e})=>({constants:{NETLIFY_API_HOST:X.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||X.env.NETLIFY_API_TOKEN,SITE_ID:X.env.SITE_ID,FUNCTIONS_DIST:X.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:D}});import{getTracer as st}from"@netlify/otel";import an from"crypto";import M from"fs/promises";import it from"os";import v from"path";import q from"process";import{fileURLToPath as ln}from"url";var N=E("context"),cn=ln(import.meta.url),un=v.dirname(cn),pn={claude:v.join(it.homedir(),".claude","skills"),gemini:v.join(it.homedir(),".gemini","skills"),codex:v.join(it.homedir(),".codex","skills")},zt=v.join(un,"skills"),dn="https://docs.netlify.com/ai-context/context-consumers",ot=null;var fn=async(e,t=[])=>{try{N.log("Fetching Netlify platform context...");let r=await fetch(dn,{signal:AbortSignal.timeout(1e4)});if(!r.ok)throw new Error(`Failed to fetch context consumers: ${r.status} ${r.statusText}`);let n=await r.json();if(!n||typeof n!="object"||!Array.isArray(n.consumers))return N.warn("Invalid response structure: missing or invalid consumers array"),!1;let i=n.consumers.find(p=>p&&typeof p=="object"&&p.key==="catchall-consumer");if(!i?.contextScopes||typeof i.contextScopes!="object")return N.warn("Catchall consumer not found or missing contextScopes"),!1;let s=Object.entries(i.contextScopes).filter(([p])=>{let u=`netlify-${p}`;return!t.includes(u)});if(s.length===0)return N.log("All scopes have bundled overrides, skipping platform skill fetch"),!1;let a=(await Promise.all(s.map(async([p,u])=>{if(!u?.endpoint)return N.warn(`Invalid scope data for ${p}, skipping`),null;try{let m=await fetch(u.endpoint,{signal:AbortSignal.timeout(1e4)});if(!m.ok)return N.warn(`Failed to fetch scope ${p}: ${m.status}`),null;let g=await m.text();return{key:p,scope:u.scope||p,content:g}}catch(m){return N.warn(`Failed to fetch scope ${p}:`,m.message),null}}))).filter(p=>p!==null);if(a.length===0)return N.warn("No scopes were fetched successfully"),!1;let c=`---
|
|
59
|
+
name: netlify-platform
|
|
60
|
+
description: Netlify platform features context covering ${a.map(p=>p.scope).join(", ")}
|
|
61
|
+
---
|
|
62
|
+
|
|
63
|
+
${a.map(p=>p.content).join(`
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
67
|
+
`)}
|
|
68
|
+
`,d=v.join(e,"netlify-platform");return await M.mkdir(d,{recursive:!0}),await M.writeFile(v.join(d,"SKILL.md"),c,"utf-8"),N.log(`Installed netlify-platform skill with ${a.length} scopes: ${a.map(p=>p.key).join(", ")}`),!0}catch(r){return r.name==="AbortError"?N.warn("Netlify platform context request timed out"):N.warn("Failed to fetch Netlify platform skill:",r.message),!1}},mn=async(e,{targetDir:t}={})=>{let r=t||pn[e];if(!r)return N.warn(`Unknown runner: ${e}, skipping skills setup`),[];if(ot)return ot;let n=[];try{let s=await M.readdir(zt);for(let o of s){let a=v.join(zt,o),c=v.join(r,o);if(!(await M.stat(a)).isDirectory())continue;await M.mkdir(c,{recursive:!0});let p=v.join(a,"SKILL.md"),u=v.join(c,"SKILL.md");try{await M.copyFile(p,u),n.push(o)}catch(m){N.warn(`Failed to copy skill ${o}:`,m.message)}}}catch(s){N.warn("Failed to setup agent skills:",s.message)}return await fn(r,n)&&n.push("netlify-platform"),n.length>0&&N.log(`Installed ${n.length} skills for ${e}: ${n.join(", ")}`,{runner:e,skills:n,targetDir:r}),ot=n,n},gn=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:q.env.NETLIFY_TEAM_ID,userId:q.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:q.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},hn=10,yn=async e=>{let{name:t,ext:r}=v.parse(e),n=e,i=v.join(q.cwd(),B,n),s=0;for(;await _n(i);){if(s>=hn)throw new Error("Failed to generate context file");n=`${t}-${an.randomUUID().slice(0,5)}${r}`,i=v.join(q.cwd(),B,n),s+=1}return n},_n=async e=>{try{return await M.access(e),!0}catch{return!1}},Zt=async({cliPath:e,netlify:t,config:r,buildErrorContext:n})=>{let i=gn(t),s=await yn(St),o=v.join(q.cwd(),B);await M.mkdir(o,{recursive:!0});let a=v.join(B,s),c=v.join(q.cwd(),a),d=v.join(q.cwd(),B,Q);try{await M.unlink(d),N.log(`Deleted old results file: ${d}`)}catch{}let p=n?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
|
|
59
69
|
Your task is to analyze and fix the build errors.
|
|
60
70
|
Don't apply techniques of reverting changes. Apply fixes related to errors.
|
|
61
71
|
Don't try to run build by yourself. Just fix the errors.
|
|
62
72
|
|
|
63
73
|
<build_error_context>
|
|
64
|
-
${
|
|
65
|
-
</build_error_context>`:"",
|
|
74
|
+
${n}
|
|
75
|
+
</build_error_context>`:"",u="";r.siteContext&&r.siteContext.length!==0&&(u=`
|
|
66
76
|
<project_rules>
|
|
67
|
-
${r.siteContext.filter(
|
|
77
|
+
${r.siteContext.filter(y=>y.site_context).map(y=>typeof y.site_context=="string"?y.site_context:typeof y.site_context=="object"?JSON.stringify(y.site_context):"").join(`
|
|
68
78
|
|
|
69
79
|
`)}
|
|
70
80
|
</project_rules>
|
|
71
|
-
`);let m="";if(r.sessionHistoryContext?.length){let
|
|
81
|
+
`);let m="";if(r.sessionHistoryContext?.length){let y=v.join(q.cwd(),B,He);await M.mkdir(y,{recursive:!0});let w=await Promise.all(r.sessionHistoryContext.map(async(_,I)=>{let b=I+1,S=`attempt-${b}.md`,k=v.join(y,S),P=v.join(B,He,S),$=`# Task History - Attempt ${b}
|
|
72
82
|
|
|
73
83
|
## Request - what the user asked for
|
|
74
|
-
${
|
|
84
|
+
${_.request}
|
|
75
85
|
|
|
76
86
|
---
|
|
77
87
|
|
|
78
88
|
## Response - what the agent replied with after its work
|
|
79
89
|
|
|
80
|
-
${
|
|
81
|
-
`;return await
|
|
90
|
+
${_.response}
|
|
91
|
+
`;return await M.writeFile(k,$,"utf-8"),N.log(`Created history file: ${P}`),P}));m+=`
|
|
82
92
|
<session_history_context>
|
|
83
93
|
History of prior work on this task.
|
|
84
94
|
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.
|
|
85
95
|
|
|
86
|
-
${
|
|
96
|
+
${w.slice(-5).map(_=>`- ${_}`).join(`
|
|
87
97
|
`)}
|
|
88
98
|
|
|
89
99
|
</session_history_context>
|
|
90
|
-
`}
|
|
91
|
-
<netlify_features_context>
|
|
92
|
-
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.
|
|
93
|
-
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.
|
|
94
|
-
|
|
95
|
-
${y.map(g=>`- **${g.scope}**: ${g.path}`).join(`
|
|
96
|
-
`)}
|
|
97
|
-
|
|
98
|
-
Refer to these files when working with specific Netlify features.
|
|
99
|
-
</netlify_features_context>
|
|
100
|
-
`);let _=`
|
|
100
|
+
`}r.runner&&await mn(r.runner,{targetDir:r.skillsTargetDir});let g=`
|
|
101
101
|
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.
|
|
102
102
|
|
|
103
103
|
<request>
|
|
104
104
|
<user_request>
|
|
105
105
|
${r.prompt}
|
|
106
106
|
</user_request>
|
|
107
|
-
${
|
|
107
|
+
${p}
|
|
108
108
|
</request>
|
|
109
109
|
|
|
110
110
|
<requirements>
|
|
111
111
|
<responses>
|
|
112
112
|
- Do not speak in first person. You may speak as "the agent".
|
|
113
|
-
- When work is complete, write a changes summary in ${
|
|
114
|
-
- 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 ${
|
|
113
|
+
- When work is complete, write a changes summary in ${o}/${Q} 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.
|
|
114
|
+
- 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 ${o}/${Q} file.
|
|
115
115
|
- 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.
|
|
116
116
|
- NEVER look into the \`.git\` folder
|
|
117
117
|
- NEVER print potentially sensitive values (like secrets) in the planning output or results
|
|
118
|
-
- If the user asks for "a plan", "just planning", or similar (without asking for implementation) you may use plan mode to explore the codebase in read-only mode, design your implementation approach and write the complete plan to ${
|
|
118
|
+
- If the user asks for "a plan", "just planning", or similar (without asking for implementation) you may use plan mode to explore the codebase in read-only mode, design your implementation approach and write the complete plan to ${o}/${Q}. Stop there, do not wait for approval and do not implement unless explicitly asked.
|
|
119
119
|
</responses>
|
|
120
120
|
<attachements>
|
|
121
|
-
- for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${
|
|
122
|
-
- move assets from ${
|
|
121
|
+
- for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${o}/${qe} folder
|
|
122
|
+
- move assets from ${o}/${qe} folder to the project assets folder if they are referenced in a code or applied changes
|
|
123
123
|
</attachements>
|
|
124
|
-
${
|
|
124
|
+
${u}
|
|
125
125
|
</requirements>
|
|
126
126
|
|
|
127
127
|
<extra_context>
|
|
128
128
|
<metadata>
|
|
129
|
-
- Site/Project ID: ${
|
|
130
|
-
- Account/Team ID: ${
|
|
131
|
-
- User ID: ${
|
|
132
|
-
- Site/Project Slug: ${
|
|
133
|
-
- Netlify Functions directory: ${
|
|
129
|
+
- Site/Project ID: ${i.siteId}
|
|
130
|
+
- Account/Team ID: ${i.accountId}
|
|
131
|
+
- User ID: ${i.userId}
|
|
132
|
+
- Site/Project Slug: ${i.siteSlug}
|
|
133
|
+
- Netlify Functions directory: ${i.functionsDir}
|
|
134
134
|
</metadata>
|
|
135
135
|
<environment>
|
|
136
|
-
- Node Version: ${
|
|
136
|
+
- Node Version: ${q.version||"unknown"}
|
|
137
137
|
- Environment variables are set globally (e.g. \`echo $VARIABLE_NAME\` can be used to check if a var is set).
|
|
138
138
|
- 'netlify-cli' npm package is already available as a global package. Don't try to install it again
|
|
139
139
|
- 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.
|
|
140
140
|
</environment>
|
|
141
|
-
${T}
|
|
142
141
|
<docs>
|
|
143
142
|
- Netlify Docs: https://docs.netlify.com
|
|
144
143
|
- LLM Resources Index: https://docs.netlify.com/llms.txt
|
|
@@ -146,30 +145,30 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
146
145
|
</extra_context>
|
|
147
146
|
|
|
148
147
|
${m}
|
|
149
|
-
`;return await
|
|
148
|
+
`;return await M.writeFile(c,g,"utf-8"),N.log(`Generated agent context document at: ${c}`),g.length>5e5&&(g=`
|
|
150
149
|
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.
|
|
151
150
|
|
|
152
151
|
<request>
|
|
153
152
|
<user_request>
|
|
154
153
|
${r.prompt}
|
|
155
154
|
</user_request>
|
|
156
|
-
${
|
|
155
|
+
${p}
|
|
157
156
|
</request>
|
|
158
157
|
|
|
159
|
-
Use the following file for the complete context of the ask, the environment, and what's available. ${
|
|
160
|
-
`),
|
|
161
|
-
${
|
|
162
|
-
${
|
|
163
|
-
`.trim(),
|
|
158
|
+
Use the following file for the complete context of the ask, the environment, and what's available. ${c} You MUST READ ALL OF IT. Make sure to read it first. Never cite or paraphrase private context.
|
|
159
|
+
`),g};var En=E("prompt"),Qt=async({cliPath:e,config:t,netlify:r,buildErrorContext:n})=>{let i=await Zt({cliPath:e,config:t,netlify:r,buildErrorContext:n});return process.env.AGENT_RUNNER_DEBUG&&En.log("Contextful Prompt:",i),{prompt:i}};var ke=E("inference_stage"),er=5,$e=async e=>{let{cliPath:t,config:r,context:n,buildErrors:i,runner:s,persistSteps:o,aiGateway:a,attempt:c,contextPrefix:d,priorAgentSessionId:p}=e;ke.log(`Running inference stage, attempt ${c} of ${er}`);let u=await C(st(),"inference-stage",async m=>{m?.setAttributes({"inference.attempt":c||1}),xt();let{prompt:g}=await C(st(),"compose-prompt",async()=>await Qt({cliPath:t,config:r,buildErrorContext:wn(i),netlify:n})),y=`
|
|
160
|
+
${d||""}
|
|
161
|
+
${g}
|
|
162
|
+
`.trim(),w={...r,prompt:y},_=await C(st(),`run-${r.runner}`,async()=>await s({aiGateway:a,config:w,netlify:n,persistSteps:o,continueSession:!!(c&&c>1),priorAgentSessionId:p}));return _.result&&(_.result=K(_.result)),_.error&&(_.error=K(_.error)),await o.flush(),_});if(u.error){if(ke.error("Runner failed",{stepsCount:u.steps.length,duration:u.duration,error:u.error,isRetryableError:u.isRetryableError,attempt:c||1,agentSessionId:u.agentSessionId}),u.isRetryableError&&(!c||c<er))return ke.log("Retrying inference stage"),await new Promise(g=>setTimeout(g,5e3)),{runnerResult:(await $e({...e,attempt:(c||1)+1,priorAgentSessionId:u.agentSessionId,contextPrefix:u.agentSessionId?"":"<important> The agent has already started on this work but ran into networking errors trying to complete it. Please continue from where it left off (you can use git commands to see what's currently changed thus far) and do not start over. Here is the full prompt for context: </important>"})).runnerResult};throw ke.log("Do not retry inference stage"),new Error(u.error)}return{runnerResult:u}},wn=e=>!e||e.length===0?"":`
|
|
164
163
|
Deploy failed failed. Here are the errors to review on the latest build:
|
|
165
164
|
|
|
166
165
|
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.
|
|
167
166
|
|
|
168
167
|
${e.pop()}
|
|
169
|
-
`;import
|
|
170
|
-
Preview deploy created successfully:`,{deployId:m.deploy_id,deployUrl:m.deploy_url,siteId:m.site_id});let
|
|
171
|
-
`);for(let
|
|
172
|
-
`),
|
|
173
|
-
`);for(let
|
|
174
|
-
`),
|
|
168
|
+
`;import xn from"process";import{getTracer as at}from"@netlify/otel";import{getTracer as Tn}from"@netlify/otel";var Ie=E("deploy"),tr=async e=>await C(Tn(),"create-preview-deploy",async t=>In(e,t)),In=async({netlify:e,hasRepo:t,skipBuild:r,message:n="Agent Preview",deploySubdomain:i,cliPath:s,filter:o,prodDeploy:a},c)=>{try{let d=["deploy","--message",`"${n}"`,"--json","--verbose"];a?d.push("--prod"):d.push("--draft"),t||(Ie.log("Deploy: Uploading source zip"),d.push("--upload-source-zip")),i&&d.push("--alias",i),o&&d.push("--filter",o),r?(Ie.log("Deploy: Skipping build"),d.push("--no-build")):d.push("--context","deploy-preview");let p=s||"netlify";Ie.log(`Running: ${p} ${d.join(" ")}`),c?.setAttributes({cmd:p,args:d});let u=await e.utils.run(p,d,{stdio:["ignore","pipe","pipe"]}),m=JSON.parse(String(u.stdout??"").trim());c?.setAttributes({success:!0,deployId:m.deploy_id,deployUrl:m.deploy_url,siteId:m.site_id}),Ie.log(`
|
|
169
|
+
Preview deploy created successfully:`,{deployId:m.deploy_id,deployUrl:m.deploy_url,siteId:m.site_id});let g={deployId:m.deploy_id,previewUrl:m.deploy_url,logsUrl:m.logs,siteId:m.site_id};return t||(g.sourceZipFilename=m.source_zip_filename),g}catch(d){throw Ie.error("Failed to create preview deploy via CLI:",d),c?.setAttributes({success:!1,error:d.message}),d}};var rr=e=>["dtn-prod-iteration","create"].includes(e);var xe=E("deploy_stage"),De=async e=>await C(at(),"run-deploy-stage",async()=>Rn(e)),Rn=async({cliPath:e,config:t,context:r,result:n,filter:i,isRetry:s})=>{let o=await C(at(),"get-runner-diffs",async()=>await $t({config:t,isRetry:s}));if(xe.info("Resolved git",{hasChanges:o.hasChanges,ignored:o.ignored??[]}),!o.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:c,diffBinary:d,resultDiffBinary:p}=o,u=!0;xe.log("Preview deploy condition check:",{resultUndefined:n===void 0,resultType:typeof n,hasChanges:u,wouldCreatePreview:n!==void 0&&u});let m=null;if(n!==void 0&&u)try{let g;try{let y=await C(at(),"get-runner-session",async()=>await _t(t.id,t.sessionId));y?.title&&(g=y.title)}catch(y){xe.warn("Failed to fetch session title, using fallback message:",y.message)}await G(t.id,t.sessionId,{steps:[{title:"Deploying the run preview"}]}),m=await tr({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:g,skipBuild:!1,deploySubdomain:Pt(t.id,xn.env.SITE_NAME),filter:i,prodDeploy:rr(t.mode)})}catch(g){return xe.warn("Failed to create preview deploy (continuing with agent run):",g),{diff:a,resultDiff:c,hasChanges:u,previewInfo:null,diffBinary:d,resultDiffBinary:p,deployError:g instanceof Error?g.message:String(g)}}return xe.log("Git status",{hasDiff:!!a,hasChanges:u}),{diff:a,resultDiff:c,hasChanges:u,previewInfo:m,diffBinary:d,resultDiffBinary:p}};import{getTracer as Ue}from"@netlify/otel";async function nr(e,t){let{maxRetries:r,baseDelay:n,onRetry:i}=t,s;for(let o=1;o<=r;o++)try{return await e()}catch(a){if(s=a,o===r)throw s;i&&i(o,s),await new Promise(c=>setTimeout(c,n*o))}throw s}var Fe=class{scanDiffForForms(t){let r=[],n=null,i=[],s=t.split(`
|
|
170
|
+
`);for(let o of s)if(o.startsWith("diff --git")){if(n&&i.length>0){let c=this.containsNetlifyForm(i,n);c&&r.push(c)}let a=o.split(" ");n=a[a.length-1].replace(/^b\//,""),i=[]}else o.startsWith("+")&&!o.startsWith("+++")&&i.push(o.slice(1));if(n&&i.length>0){let o=this.containsNetlifyForm(i,n);o&&r.push(o)}return{detected:r.length>0,matches:r}}containsNetlifyForm(t,r){let n=t.join(`
|
|
171
|
+
`),i=[{pattern:/<[\w-]*form[\s\S]*?(data-)?netlify/i,name:"standard form element"},{pattern:/<[A-Z][\w]*[\s\S]*?component\s*=\s*["']form["'][\s\S]*?(data-)?netlify/i,name:"component with form prop"}];for(let{pattern:s,name:o}of i){let a=n.match(s);if(a){let c=a.index||0,d=Math.max(0,c-20),p=Math.min(n.length,c+a[0].length+20),u=n.slice(d,p).trim();return u=u.replace(/\s+/g," "),u.length>100&&(u=u.slice(0,97)+"..."),{file:r,snippet:`[${o}] ${u}`}}}return null}};var Le=class{scanDiffForIdentity(t){let r=[],n=null,i=[],s=t.split(`
|
|
172
|
+
`);for(let o of s)if(o.startsWith("diff --git")){if(n&&i.length>0){let c=this.containsNetlifyIdentity(i,n);c&&r.push(c)}let a=o.split(" ");n=a[a.length-1].replace(/^b\//,""),i=[]}else o.startsWith("+")&&!o.startsWith("+++")&&i.push(o.slice(1));if(n&&i.length>0){let o=this.containsNetlifyIdentity(i,n);o&&r.push(o)}return{detected:r.length>0,matches:r}}containsNetlifyIdentity(t,r){let n=t.join(`
|
|
173
|
+
`),i=[{pattern:/data-netlify-identity-(button|menu)/i,name:"identity widget element"},{pattern:/netlify-identity-widget/i,name:"identity widget import"},{pattern:/new\s+GoTrue\s*\(/i,name:"GoTrue client"},{pattern:/(import\s+.*GoTrue|require\s*\(\s*['"]gotrue-js['"]\s*\))/i,name:"GoTrue import"},{pattern:/netlifyIdentity\s*\.\s*(init|on|off|open|close|login|signup|logout|refresh|currentUser)/i,name:"identity widget API"},{pattern:/['"`]\/?\.netlify\/identity/i,name:"identity endpoint"}];for(let{pattern:s,name:o}of i){let a=n.match(s);if(a){let c=a.index||0,d=Math.max(0,c-20),p=Math.min(n.length,c+a[0].length+20),u=n.slice(d,p).trim();return u=u.replace(/\s+/g," "),u.length>100&&(u=u.slice(0,97)+"..."),{file:r,snippet:`[${o}] ${u}`}}}return null}};var A=E("cleanup_stage"),ct=async e=>await C(Ue(),"cleanup-stage",async()=>vn(e)),lt=1024*1024*10,vn=async({config:e,diff:t,result:r,duration:n,resultDiff:i,diffBinary:s,resultDiffBinary:o,previewInfo:a})=>{let c={result:r||"Done",duration:n};a&&a.deployId&&(c.deploy_id=a.deployId),a&&a.sourceZipFilename&&(c.result_zip_file_name=a.sourceZipFilename);let d=t||s||i||o;if(d&&(c.diff_produced=!0),d){let p=new Fe,u=t||s||"",m=p.scanDiffForForms(u);m.detected?(A.log("Detected Netlify form(s) in diff:"),m.matches.forEach(({file:w,snippet:_})=>{A.log(` - ${w}: ${_}`)}),c.has_netlify_form=!0):A.log("Did not detect Netlify form(s) in diff");let y=new Le().scanDiffForIdentity(u);y.detected?(A.log("Detected Netlify Identity usage in diff:"),y.matches.forEach(({file:w,snippet:_})=>{A.log(` - ${w}: ${_}`)}),c.has_netlify_identity=!0):A.log("Did not detect Netlify Identity usage in diff")}if(d)try{A.log("Getting pre-signed URLs for diff upload");let p=await wt(e.id,e.sessionId),u=[];(t||s)&&u.push(Ye(p.result.upload_url,s||t).then(()=>{c.result_diff_s3_key=p.result.s3_key,A.log("Successfully uploaded result_diff to S3")})),(i||o)&&u.push(Ye(p.cumulative.upload_url,o||i).then(()=>{c.cumulative_diff_s3_key=p.cumulative.s3_key,A.log("Successfully uploaded cumulative_diff to S3")})),A.log(`Uploading ${u.length} diff(s) to S3 in parallel`),await Promise.all(u),(i||o)&&(A.log("Updating agent runner with cumulative diff S3 key"),await C(Ue(),"update-runner",async()=>{await Ee(e.id,{result_diff_s3_key:p.cumulative.s3_key})}))}catch(p){A.error("S3 upload failed, falling back to inline diffs:",p);let u=Buffer.byteLength(t||s||""),m=Buffer.byteLength(o||i||"");if(u>lt||m>lt){let g=`Diffs exceed maximum inline size of ${lt} bytes.`;throw A.error(g),new Error(g)}c.result_diff=t,c.result_diff_binary=s,(i||o)&&(c.cumulative_diff=i,c.cumulative_diff_binary=o,A.log("Updating agent runner with inline diffs (fallback)"),await C(Ue(),"update-runner",async()=>{await Ee(e.id,{result_diff:i,result_diff_binary:o})}))}else A.log("No diffs to upload");return A.log("Updated agent runner with result"),await nr(async()=>await C(Ue(),"update-runner-session",()=>G(e.id,e.sessionId,c)),{maxRetries:3,baseDelay:1e3,onRetry:(p,u)=>{A.error(`Error updating agent runner session (attempt ${p}):`,u),A.log("Retrying...")}}),A.log("Finished updating agent runner with result"),{sessionUpdate:c}};import{getTracer as ir,shutdownTracers as An,withActiveSpan as or}from"@netlify/otel";var bn=Sn(import.meta.url),sr=bn("../package.json"),he=E("pipeline_index"),Me=3,Ns=async({config:e,apiToken:t,cliPath:r="netlify",cwd:n,filter:i,tracing:s={}})=>{let o,{withStageTimer:a}=Rt(J.timeUnits.hours(4)),c=await ft(sr.version,e.id,s);try{await or(ir(),"run-pipeline",{},c,async()=>{let{aiGateway:d,context:p,persistSteps:u,runner:m,sha:g}=await a("init",()=>Xt({config:e,apiToken:t,cliPath:r,cwd:n,filter:i,runnerVersion:sr.version}),J.timeUnits.minutes(10));if(o=m.clean,e.sha=g,e.mode==="redeploy"){await G(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let x=await a("deploy",()=>De({cliPath:r,config:e,context:p,result:"Redeploy completed",filter:i,isRetry:!1}));x.deployError&&he.warn(`Redeploy deploy failed: ${x.deployError}`);let{diff:R,resultDiff:F,previewInfo:h,diffBinary:f,resultDiffBinary:l}=x;await a("cleanup",()=>ct({config:e,diff:R,result:"Redeploy completed",duration:0,resultDiff:F,diffBinary:f,resultDiffBinary:l,previewInfo:h}),J.timeUnits.minutes(10)),process.env.NETLIFY_LOCAL_MODE||(await o?.(),await Ze());return}let{runnerResult:y}=await a("inference",()=>$e({cliPath:r,config:e,context:p,runner:m.runner,persistSteps:u,aiGateway:d}));await G(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let w=await a("deploy",()=>De({cliPath:r,config:e,context:p,result:y.result,filter:i,isRetry:!1})),_=y,I=[];if(w.hasChanges&&w.deployError){I.push(mt(w.deployError));let x=1,R=!1;for(;x<=Me&&!w.previewInfo&&!R;)he.log(`Deploy attempt had errors. Retrying. ${x}/${Me}`),await or(ir(),"deploy-stage",async F=>{F?.setAttributes({"stage.attempt":x});let h;try{h=(await a(`inference-retry-${x}`,()=>$e({cliPath:r,config:e,context:p,runner:m.runner,persistSteps:u,aiGateway:d,buildErrors:I,priorAgentSessionId:y.agentSessionId}))).runnerResult}catch(f){he.warn(`Inference retry ${x} failed, stopping deploy retries:`,f),R=!0;return}_={...h,steps:[..._.steps||[],...h.steps||[]],duration:(_.duration||0)+(h.duration||0)},w=await a(`deploy-retry-${x}`,()=>De({cliPath:r,config:e,context:p,result:h.result,filter:i,isRetry:!0})),w.deployError&&I.push(w.deployError),x++});x>Me&&!w.previewInfo&&console.warn(`Deploy validation failed after ${Me} attempts`)}let{diff:b,resultDiff:S,previewInfo:k,diffBinary:P,resultDiffBinary:$}=w;await a("cleanup",()=>ct({config:e,diff:b,result:_.result,duration:_.duration,resultDiff:S,diffBinary:P,resultDiffBinary:$,previewInfo:k}),J.timeUnits.minutes(10)),process.env.NETLIFY_LOCAL_MODE||(await o?.(),await Ze())})}catch(d){if(gt(d)){he.info("Agent run terminated gracefully",{statusCode:d.statusCode,reason:d.message}),await o?.();try{await G(e.id,e.sessionId,{result:d.userMessage,state:"error"})}catch{he.info("Could not update session (site may have been deleted)")}return}he.error("Got error while running pipeline",d),await o?.();let p=d instanceof Error&&d.message;throw await G(e.id,e.sessionId,{result:p||"Encountered error when running agent",state:"error"}),d}finally{await An()}};export{Ns as runPipeline};
|
|
175
174
|
//# sourceMappingURL=index.js.map
|