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