@netlify/agent-runner-cli 1.61.2-alpha → 1.62.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 +49 -46
- package/dist/bin.js +40 -37
- package/dist/index.d.ts +32 -5
- package/dist/index.js +49 -46
- package/package.json +4 -4
package/dist/bin-local.js
CHANGED
|
@@ -1,38 +1,38 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import C from"process";import
|
|
3
|
-
`),r=[],
|
|
4
|
-
`)),
|
|
2
|
+
import C from"process";import fr from"path";import mr from"fs";import Fn from"minimist";import{createRequire as Cn}from"module";import{createTracerProvider as hr}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as mt}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as yr}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as _r}from"@netlify/otel";import{propagation as gt,context as ht,W3CTraceContextPropagator as Er}from"@netlify/otel/opentelemetry";import{OTLPTraceExporter as wr}from"@opentelemetry/exporter-trace-otlp-grpc";import gr from"process";function _(e){let t=gr.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 He=_("tracing"),yt=async(e,t,r)=>(await hr({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new mt(new qe),new mt(new wr({url:r.exporterUrl}))],instrumentations:[new yr({skipHeaders:!0})]}),r.traceparent?(gt.setGlobalPropagator(new Er),gt.extract(ht.active(),{traceparent:r.traceparent,isRemote:!0})):ht.active());function A(e,t,r){return He.log(`\u23F3 TRACE: ${t} starting...`),_r(e,t,r)}var qe=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[l,a]of Object.entries(i))l.includes("duration")&&typeof a=="number"?n.push(`${l}=${a.toFixed(2)}ms`):n.push(`${l}=${a}`);let o=t.status?.code===2?"\u274C":"\u2705",s=n.length>0?` [${n.join(", ")}]`:"";He.log(`${o} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${s}`),t.status?.code===2&&t.status.message&&He.log(` \u274C Error: ${t.status.message}`)}};var Tr=["error","failed","exception","fatal","panic","abort","crash"];function _t(e){let t=e.split(`
|
|
3
|
+
`),r=[],i=-1,n=0;for(;n<t.length;){let l=t[n].slice(0,500).toLowerCase();if(Tr.some(p=>l.includes(p))){let p=Math.max(0,n-10,i+1),f=Math.min(t.length-1,n+20),u=[];for(let g=p;g<=f;g++)u.push(t[g]);r.push(u.join(`
|
|
4
|
+
`)),i=f,n=f+1}else n++}if(r.length===0)return e;let o=r.map((s,l)=>`<extracted_error_chunk order="${l+1}">
|
|
5
5
|
${s}
|
|
6
6
|
</extracted_error_chunk>`).join(`
|
|
7
7
|
|
|
8
|
-
`);return i.length>e.length*.8?e:i}import Qt from"fs/promises";import cn from"path";import oe from"process";import{getTracer as un}from"@netlify/otel";import Ee from"process";var ie=class extends Error{constructor(r,o,n){super(r);this.statusCode=o;this.userMessage=n;this.name="GracefulShutdownError"}},_t=e=>e instanceof ie;var Ae=Ee.env.NETLIFY_API_URL,Ne=Ee.env.NETLIFY_API_TOKEN,H=_("api"),Ce=()=>Ee.env.NETLIFY_LOCAL_MODE==="true",we=async(e,t={})=>{if(!Ae||!Ne)throw new Error("No API URL or token");let r=new URL(e,Ae),o={...t,headers:{...t.headers,Authorization:`Bearer ${Ne}`}};Ee.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let n=await fetch(r,o),i=n.ok&&n.status<=299;if(Ee.env.AGENT_RUNNERS_DEBUG==="true")H.log(`Response headers for ${r}:`),n.headers.forEach((c,l)=>{H.log(` ${l}: ${c}`)});else{let c=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");H.log(`Request ID for ${r}: ${c||"N/A"}`)}if(i||H.error(`Got status ${n.status} for request ${r}`),t.raw){if(!i)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(!i){let c=typeof s=="string"?s:JSON.stringify(s);throw n.status===404?new ie(`API request failed: 404 - ${c}`,404,"The site associated with this agent run no longer exists."):n.status===403&&t.gracefulOn403?new ie(`API request failed: 403 - ${c}`,403,"Credit limit reached. Please add more credits to continue using Agent Runners."):new Error(`API request failed: ${n.status} - ${c}`)}return s},Et=e=>{H.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Ae=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Ne=e.constants.NETLIFY_API_TOKEN)},wt=()=>({apiUrl:Ae,token:Ne}),Te=async(e,t)=>Ce()?(H.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):we(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),q=async(e,t,r)=>Ce()?(H.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):we(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var Tt=async(e,t)=>Ce()?(H.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):we(`/api/v1/agent_runners/${e}/sessions/${t}`),It=(e,t,r)=>we(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn403:!0}),xt=async(e,t)=>Ce()?(H.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"}}):we(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),qe=async(e,t)=>{H.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 se=_("ai_gateway"),Ke=null;var vt=async()=>{if(Ke)return Ke;se.log("Fetching available AI gateway providers");let e=await fetch(`${wt().apiUrl}/api/v1/ai-gateway/providers`);if(!e.ok)throw new Error(`Failed to fetch AI gateway providers: ${e.statusText}`);let t=await e.json();return Ke=t,se.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},Tr=async(e,t)=>{let o=(await vt()).providers[e];if(!o)return se.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return se.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},Rt=async({netlify:e,config:t})=>{let r,o,n,i,s=e.constants?.SITE_ID;if(!s)throw new Error("No site id");let c=async()=>{clearTimeout(n),se.log("Requesting AI gateway information");let l=await It(s,t.id,t.sessionId);if({token:r,url:i}=l,o=l.expires_at?l.expires_at*1e3:void 0,se.log("Got AI gateway information",{token:!!r,expiresAt:o,url:i}),o){let p=o-Date.now()-6e4;p>0&&(n=setTimeout(()=>{c()},p))}};return await Promise.all([c(),vt()]),{get url(){return i},get token(){return r},isModelAvailableForProvider:Tr}};import K from"process";import V from"path";import Pe from"fs";import{fileURLToPath as Ar}from"url";import{createRequire as Nr}from"module";import{execa as Cr,execaCommand as uo}from"execa";import{Transform as Ir}from"stream";var xr=new Set(["NODE_ENV","PATH","HOME","USER","USERNAME","SHELL","PWD","OLDPWD","TMPDIR","TMP","TEMP","LANG","TERM","EDITOR","PAGER","OS","PROCESSOR_ARCHITECTURE","PROCESSOR_IDENTIFIER","SYSTEMROOT","WINDIR","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","APPDATA","LOCALAPPDATA","NODE_OPTIONS","NODE_PATH","NODE_DEBUG","NODE_NO_WARNINGS","npm_config_registry","npm_config_cache","npm_execpath","npm_node_execpath","CI","GITHUB_ACTIONS","GITHUB_WORKSPACE","GITHUB_REPOSITORY","GITHUB_REF","BUILDKITE","BUILDKITE_BRANCH","BUILDKITE_COMMIT","BUILDKITE_BUILD_NUMBER","JENKINS_URL","TRAVIS","CIRCLECI","DISPLAY","COLORTERM","TERM_PROGRAM","TERM_PROGRAM_VERSION","COLUMNS","LINES","HISTSIZE","HISTFILE","NETLIFY_AGENT_RUNNER_ID","NETLIFY_AGENT_RUNNER_SESSION_ID","NETLIFY_AGENT_RUNNER_PROMPT","NETLIFY_AGENT_RUNNER_AGENT","NETLIFY_AGENT_RUNNER_MODEL","NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED","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"]),vr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function Rr(){return Object.entries(process.env).filter(([e,t])=>!(!t||xr.has(e)||vr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function J(e){if(typeof e!="string")return e;let t=Rr();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(Sr(o),"g");r=r.replace(n,"******")}),r}function Sr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ae=class extends Ir{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),i=J(n);o(null,i)}};function St(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(o,n,i){let s=typeof o=="string"?J(o):o;return typeof n=="function"?t(s,n):t(s,n,i)},process.stderr.write=function(o,n,i){let s=typeof o=="string"?J(o):o;return typeof n=="function"?r(s,n):r(s,n,i)}}var Ie=null,bt=e=>(Ie&&Ie.destroy(),Ie=new ee({totalAllowedTime:e}),Ie),At=()=>Ie;var ee=class{constructor({totalAllowedTime:t}){this.withStageTimer=async(t,r,o)=>{if(this.isTimeExpired())throw new Error(`${t} stage did not complete in the allowed time. Time has already expired.`);let n=this.onTimesUp(()=>{throw new Error(`${t} stage did not complete in the allowed time.`)}),i=null,s=null;o!==void 0&&(s=new Promise((c,l)=>{i=setTimeout(()=>{l(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return s?await Promise.race([r(),s]):await r()}finally{n(),i&&clearTimeout(i)}};this.startTime=Date.now(),this.totalAllowedTime=t,this.globalTimeoutId=null,this.subscribers=[],this.hasTimedOut=!1,this.setupGlobalTimeout()}getElapsedTime(){return Date.now()-this.startTime}getRemainingTime(){let t=this.getElapsedTime(),r=this.totalAllowedTime-t;return Math.max(0,r)}isTimeExpired(){return this.getRemainingTime()===0||this.hasTimedOut}setupGlobalTimeout(){this.globalTimeoutId&&clearTimeout(this.globalTimeoutId),this.globalTimeoutId=setTimeout(()=>{this.notifyTimeUp()},this.totalAllowedTime)}notifyTimeUp(){this.hasTimedOut=!0;for(let t=this.subscribers.length-1;t>=0;t--)try{this.subscribers[t]()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}}onTimesUp(t){if(this.subscribers.push(t),this.hasTimedOut)try{t()}catch(r){console.error("TimeKeeper: Error in time up callback:",r)}return()=>{let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}}off(t){let r=this.subscribers.indexOf(t);r>-1&&this.subscribers.splice(r,1)}clearSubscribers(){this.subscribers.length=0}getSubscriberCount(){return this.subscribers.length}destroy(){this.globalTimeoutId&&(clearTimeout(this.globalTimeoutId),this.globalTimeoutId=null),this.clearSubscribers()}static{this.timeUnits={seconds:t=>t*1e3,minutes:t=>t*60*1e3,hours:t=>t*60*60*1e3}}};var Nt="netlify-agent-runner-context.md",We="task-history",Je="netlify-context",U=".netlify",le="results.md",Ve="assets";var te=1800*1e3;var Ct={name:"@netlify/agent-runner-cli",type:"module",version:"1.61.2-alpha",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.0.76","@google/gemini-cli":"0.23.0","@netlify/otel":"^5.1.1","@openai/codex":"0.81.0","@opentelemetry/exporter-trace-otlp-grpc":"^0.208.0",execa:"^9.6.1",minimist:"^1.2.8"}};var Pr=Ar(import.meta.url),Fr=V.dirname(Pr),$r=Nr(import.meta.url),ce=_("shell"),Xe=new Set,Or={preferLocal:!0},N=(e,t,r)=>{let[o,n]=Lr(t,r),i={...Or,...n},s=Cr(e,o,i);kr(s,i),Ur(s);let c=r?.idleTimeout;return c&&c>0&&Dr(s,c),s};var Lr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},kr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(K.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new ae).pipe(K.stdout),e.stdout?.pipe(new ae).pipe(K.stdout),e.stderr?.pipe(new ae).pipe(K.stderr);return}e.stdout?.pipe(K.stdout),e.stderr?.pipe(K.stderr)},ze=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(K.kill(-e.pid,t),ce.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return ce.error("Error killing process:",r),!1}},Pt=e=>ze(e,"SIGKILL"),Dr=(e,t)=>{let r=null,o=()=>{ce.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),ze(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ce.log(`Force killing idle process ${e.pid}`),Pt(e))},5e3)},n=()=>{r&&clearTimeout(r),r=setTimeout(o,t)};n(),e.stdout?.on("data",n),e.stderr?.on("data",n);let i=()=>{r&&(clearTimeout(r),r=null)};e.on("exit",i),e.on("error",i)},Ur=e=>{Xe.add(e);let t=At();if(t){let r=t.onTimesUp(()=>{ce.log(`Global timer expired, killing process ${e.pid}`),ze(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ce.log(`Force killing process ${e.pid} after timeout`),Pt(e))},5e3)});e.on("exit",()=>{Xe.delete(e),r()}),e.on("error",()=>{Xe.delete(e),r()})}};function Fe(e,t){return!!re(e,t)}function re(e,t){if(!K.env.NETLIFY_LOCAL_MODE)try{let n=$r.resolve(Ct.name),i=V.dirname(n);for(;i!==V.dirname(i);){let s=V.dirname(i);if(V.basename(s)==="node_modules"){let c=V.join(s,".bin",t);if(Pe.existsSync(c))return c;break}i=s}}catch(n){console.error("Could not resolve package.json",n)}if(K.env.NODE_PATH){let n=V.join(K.env.NODE_PATH,".bin",t);if(Pe.existsSync(n))return n}let r=V.join(e,"node_modules",".bin",t);if(Pe.existsSync(r))return r;let o=V.join(Fr,"..","node_modules",".bin",t);if(Pe.existsSync(o))return o}var Mr=_("utils"),Gr=e=>new Promise(t=>{setTimeout(t,e)}),Ft=(e,t=3e3)=>{let r=!1,o=null,n=[],i=null,s=(...c)=>{if(r)return o=c,new Promise(f=>{n.push(f)});r=!0;let l,p=new Promise(f=>{l=f});return i=(async()=>{await Promise.resolve();let f=await e(...c);for(l(f);;){if(await Gr(t),!o)return r=!1,i=null,f;let u=o,m=n;o=null,n=[],f=await e(...u),m.forEach(y=>{y(f)})}})(),p};return s.flush=async()=>{if((r||o)&&i)return await i,s.flush()},s},ue=(e,t,r=!1)=>{let o=null,n=null,i=null,s=function(...c){n=c,i=this;let l=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(i,n),n=null,i=null)},t),l&&(e.apply(i,n),n=null,i=null)};return s.cancel=()=>{clearTimeout(o),o=null,n=null,i=null},s.flush=()=>{if(o){clearTimeout(o);let c=n,l=i;o=null,n=null,i=null,e.apply(l,c)}},s},$t=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):Mr.error("Could not parse JSON",o))}},Ot=(e,t)=>{let n=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let c=`--${t}${n}`;if(c.length>55)return"";let l=60-c.length;if(l<=0)return"";if(l>=i.length+6){let p=Math.min(l-i.length,e.length);return`${i}${e.slice(0,p)}`}return e.slice(0,l)};var jr=50*1024,Ze=(e,t=jr)=>{if(!e||typeof e!="string"||e.length<=t)return e;let o=e.startsWith("```")?"\n... [truncated]\n```":"... [truncated]";return e.slice(0,t)+o};import{Buffer as Lt}from"buffer";import Yr from"path";var kt=_("repo"),Dt=async({config:e,isRetry:t})=>{kt.info("Getting runner diffs");let r=await Hr(),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};if(!t){let I=qr(n);await Kr(I)}kt.info("Changes after processing"),await et();let i=await tt(n);await Qe(i);let s={stdio:["ignore","pipe","pipe"]},c=await N("git",["diff","--staged"],s),l=String(c.stdout??"");if(o=!!l,!o)return{hasChanges:!1,ignored:i};let p=await N("git",["diff","--staged","--binary"],s),f=String(p.stdout??""),u,m;if(e.sha){if(!process.env.NETLIFY_LOCAL_MODE){process.env.NETLIFY_INTERNAL_GIT="1";try{await N("git",["commit","-m","Agent runner"])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}}let I=await N("git",["diff",e.sha,"HEAD"],s);u=String(I.stdout??"");let w=await N("git",["diff",e.sha,"HEAD","--binary"],s),g=String(w.stdout??"");u!==g&&(m=Lt.from(g).toString("base64"))}let y={hasChanges:!0,diff:l,resultDiff:u,ignored:i};return l!==f&&(y.diffBinary=Lt.from(f).toString("base64")),m&&(y.resultDiffBinary=m),y},Qe=async(e=[])=>{process.env.NETLIFY_INTERNAL_GIT="1";try{await N("git",["add",".",...e])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}},et=async()=>{let e=await N("git",["status","-s"]);return String(e.stdout??"")},Ut=/.. (.+)?\.log$/,Br=[Ut],Hr=async()=>{let e=await et();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
9
|
-
`).filter(
|
|
10
|
-
`).forEach(
|
|
11
|
-
`).reduce((r,
|
|
8
|
+
`);return o.length>e.length*.8?e:o}import{execSync as un}from"child_process";import er from"fs/promises";import dn from"path";import z from"process";import{getTracer as pn}from"@netlify/otel";import Ee from"process";var se=class extends Error{constructor(r,i,n){super(r);this.statusCode=i;this.userMessage=n;this.name="GracefulShutdownError"}},Et=e=>e instanceof se;var Ae=Ee.env.NETLIFY_API_URL,Ne=Ee.env.NETLIFY_API_TOKEN,H=_("api"),Ce=()=>Ee.env.NETLIFY_LOCAL_MODE==="true",we=async(e,t={})=>{if(!Ae||!Ne)throw new Error("No API URL or token");let r=new URL(e,Ae),i={...t,headers:{...t.headers,Authorization:`Bearer ${Ne}`}};Ee.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(Ee.env.AGENT_RUNNERS_DEBUG==="true")H.log(`Response headers for ${r}:`),n.headers.forEach((l,a)=>{H.log(` ${a}: ${l}`)});else{let l=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");H.log(`Request ID for ${r}: ${l||"N/A"}`)}if(o||H.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 se(`API request failed: 404 - ${l}`,404,"The site associated with this agent run no longer exists."):n.status===403&&t.gracefulOn403?new se(`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},wt=e=>{H.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Ae=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Ne=e.constants.NETLIFY_API_TOKEN)},Tt=()=>({apiUrl:Ae,token:Ne}),Te=async(e,t)=>Ce()?(H.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):we(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),q=async(e,t,r)=>Ce()?(H.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):we(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var It=async(e,t)=>Ce()?(H.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):we(`/api/v1/agent_runners/${e}/sessions/${t}`),xt=(e,t,r)=>we(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r},gracefulOn403:!0}),vt=async(e,t)=>Ce()?(H.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"}}):we(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),We=async(e,t)=>{H.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 ae=_("ai_gateway"),Ke=null;var Rt=async()=>{if(Ke)return Ke;ae.log("Fetching available AI gateway providers");let e=await fetch(`${Tt().apiUrl}/api/v1/ai-gateway/providers`);if(!e.ok)throw new Error(`Failed to fetch AI gateway providers: ${e.statusText}`);let t=await e.json();return Ke=t,ae.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},Ir=async(e,t)=>{let i=(await Rt()).providers[e];if(!i)return ae.log(`Provider '${e}' not found`),!1;let n=i.models.includes(t);return ae.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},St=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),ae.log("Requesting AI gateway information");let a=await xt(s,t.id,t.sessionId);if({token:r,url:o}=a,i=a.expires_at?a.expires_at*1e3:void 0,ae.log("Got AI gateway information",{token:!!r,expiresAt:i,url:o}),i){let p=i-Date.now()-6e4;p>0&&(n=setTimeout(()=>{l()},p))}};return await Promise.all([l(),Rt()]),{get url(){return o},get token(){return r},isModelAvailableForProvider:Ir}};import W from"process";import V from"path";import Pe from"fs";import{fileURLToPath as Nr}from"url";import{createRequire as Cr}from"module";import{execa as Pr,execaCommand as pi}from"execa";import{Transform as xr}from"stream";var vr=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"]),Rr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function Sr(){return Object.entries(process.env).filter(([e,t])=>!(!t||vr.has(e)||Rr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function J(e){if(typeof e!="string")return e;let t=Sr();if(t.length===0)return e;let r=e;return t.forEach(i=>{let n=new RegExp(br(i),"g");r=r.replace(n,"******")}),r}function br(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var le=class extends xr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,i){let n=t.toString(),o=J(n);i(null,o)}};function bt(){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"?J(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"?J(i):i;return typeof n=="function"?r(s,n):r(s,n,o)}}var Ie=null,At=e=>(Ie&&Ie.destroy(),Ie=new te({totalAllowedTime:e}),Ie),Nt=()=>Ie;var te=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,a)=>{o=setTimeout(()=>{a(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 Ct="netlify-agent-runner-context.md",Je="task-history",Ve="netlify-context",U=".netlify",re="results.md",Xe="assets";var ne=1800*1e3;var Pt={name:"@netlify/agent-runner-cli",type:"module",version:"1.62.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.20","@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 $r=Nr(import.meta.url),Fr=V.dirname($r),Or=Cr(import.meta.url),ce=_("shell"),ze=new Set,kr={preferLocal:!0},N=(e,t,r)=>{let[i,n]=Lr(t,r),o={...kr,...n},s=Pr(e,i,o);Dr(s,o),Mr(s);let l=r?.idleTimeout;return l&&l>0&&Ur(s,l),s};var Lr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Dr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(W.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new le).pipe(W.stdout),e.stdout?.pipe(new le).pipe(W.stdout),e.stderr?.pipe(new le).pipe(W.stderr);return}e.stdout?.pipe(W.stdout),e.stderr?.pipe(W.stderr)},Ze=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(W.kill(-e.pid,t),ce.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return ce.error("Error killing process:",r),!1}},$t=e=>Ze(e,"SIGKILL"),Ur=(e,t)=>{let r=null,i=()=>{ce.log(`Process ${e.pid} killed due to idle timeout (no output for ${t}ms)`),Ze(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ce.log(`Force killing idle process ${e.pid}`),$t(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)},Mr=e=>{ze.add(e);let t=Nt();if(t){let r=t.onTimesUp(()=>{ce.log(`Global timer expired, killing process ${e.pid}`),Ze(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ce.log(`Force killing process ${e.pid} after timeout`),$t(e))},5e3)});e.on("exit",()=>{ze.delete(e),r()}),e.on("error",()=>{ze.delete(e),r()})}};function $e(e,t){return!!ie(e,t)}function ie(e,t){if(!W.env.NETLIFY_LOCAL_MODE)try{let n=Or.resolve(Pt.name),o=V.dirname(n);for(;o!==V.dirname(o);){let s=V.dirname(o);if(V.basename(s)==="node_modules"){let l=V.join(s,".bin",t);if(Pe.existsSync(l))return l;break}o=s}}catch(n){console.error("Could not resolve package.json",n)}if(W.env.NODE_PATH){let n=V.join(W.env.NODE_PATH,".bin",t);if(Pe.existsSync(n))return n}let r=V.join(e,"node_modules",".bin",t);if(Pe.existsSync(r))return r;let i=V.join(Fr,"..","node_modules",".bin",t);if(Pe.existsSync(i))return i}var Gr=_("utils"),jr=e=>new Promise(t=>{setTimeout(t,e)}),Ft=(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 a,p=new Promise(f=>{a=f});return o=(async()=>{await Promise.resolve();let f=await e(...l);for(a(f);;){if(await jr(t),!i)return r=!1,o=null,f;let u=i,g=n;i=null,n=[],f=await e(...u),g.forEach(y=>{y(f)})}})(),p};return s.flush=async()=>{if((r||i)&&o)return await o,s.flush()},s},ue=(e,t,r=!1)=>{let i=null,n=null,o=null,s=function(...l){n=l,o=this;let a=r&&!i;clearTimeout(i),i=setTimeout(()=>{i=null,r||(e.apply(o,n),n=null,o=null)},t),a&&(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,a=o;i=null,n=null,o=null,e.apply(a,l)}},s},Ot=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(i){t&&(r?.error?r.error("Could not parse JSON",i):Gr.error("Could not parse JSON",i))}},kt=(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 a=60-l.length;if(a<=0)return"";if(a>=o.length+6){let p=Math.min(a-o.length,e.length);return`${o}${e.slice(0,p)}`}return e.slice(0,a)};var Yr=50*1024,Qe=(e,t=Yr)=>{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 Lt}from"buffer";import Br from"path";var Dt=_("repo"),Ut=async({config:e,isRetry:t})=>{Dt.info("Getting runner diffs");let r=await qr(),{hasChanges:i}=r,{status:n}=r;if(!i)return{hasChanges:!1};if(!t){let T=Wr(n);await Kr(T)}Dt.info("Changes after processing"),await tt();let o=await rt(n);await et(o);let s={stdio:["ignore","pipe","pipe"]},l=await N("git",["diff","--staged"],s),a=String(l.stdout??"");if(i=!!a,!i)return{hasChanges:!1,ignored:o};let p=await N("git",["diff","--staged","--binary"],s),f=String(p.stdout??""),u,g;if(e.sha){if(!process.env.NETLIFY_LOCAL_MODE){process.env.NETLIFY_INTERNAL_GIT="1";try{await N("git",["commit","-m","Agent runner"])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}}let T=await N("git",["diff",e.sha,"HEAD"],s);u=String(T.stdout??"");let E=await N("git",["diff",e.sha,"HEAD","--binary"],s),m=String(E.stdout??"");u!==m&&(g=Lt.from(m).toString("base64"))}let y={hasChanges:!0,diff:a,resultDiff:u,ignored:o};return a!==f&&(y.diffBinary=Lt.from(f).toString("base64")),g&&(y.resultDiffBinary=g),y},et=async(e=[])=>{process.env.NETLIFY_INTERNAL_GIT="1";try{await N("git",["add",".",...e])}finally{process.env.NETLIFY_INTERNAL_GIT="0"}},tt=async()=>{let e=await N("git",["status","-s"]);return String(e.stdout??"")},Mt=/.. (.+)?\.log$/,Hr=[Mt],qr=async()=>{let e=await tt();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
9
|
+
`).filter(i=>Hr.some(o=>o instanceof RegExp?o.test(i):i===o)?!1:i[1]?.trim()!=="")).length!==0,status:e}},Gt=async()=>{let{stdout:e}=await N("git",["rev-parse","HEAD"]);return String(e??"").trim()},jt=async()=>{let{stdout:e}=await N("git",["rev-list","--max-parents=0","HEAD"]);return String(e??"").trim()},rt=async e=>{e||=await tt();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(`
|
|
10
|
+
`).forEach(i=>{t.forEach(o=>{let s=i===`?? ${o}`,l=i.startsWith(`?? ${o}/`)||i.startsWith(`?? ${o}${Br.sep}`);(s||l)&&r.push(`:!${o}`)});let n=i.match(Mt)?.[1];n&&r.push(`:!${n}.log`)}),r},Yt=async()=>{await N("git",["reset","--hard","HEAD"])},Wr=e=>{let t=e.split(`
|
|
11
|
+
`).reduce((r,i)=>{if(!i)return r;let[n,o,,...s]=i,l=s.join(""),a=n.trim(),p=o.trim();return r[l]?r[l].change=p:r[l]={filePath:l,stage:a,change:p},r},{});return Object.values(t)},Kr=async e=>{let t=[];for(let r of e)r.stage&&!r.change&&t.push(N("git",["restore","--staged","--worktree",r.filePath]));await Promise.allSettled(t)};import Vr from"fs/promises";import Xr from"os";import qt from"path";import me from"process";import zr from"readline";import nt from"path";import Jr from"fs/promises";var it=_("agent-output-utils");async function de({initialResult:e,agentName:t,hasError:r}){let i="",n=nt.join(process.cwd(),U,re);try{let o=await Jr.readFile(n,"utf-8");o&&(i=o,it.log(`Pulled result from ${nt.relative(process.cwd(),n)}`))}catch{it.log(`No results file found at ${nt.relative(process.cwd(),n)}`)}return i||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function pe({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&&it.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function fe(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 M=_("runner_claude"),Bt="Claude Code",ge="claude-opus-4-5-20251101",Ht=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,Zr=({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,aiGateway:i,continueSession:n,priorAgentSessionId:o,cwd:s=me.cwd()}){let l=e,{accountType:a,prompt:p,modelVersionOverrides:f}=l,{model:u}=l,g="";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 c=f?.claude?.[a];if(c){if(!await i.isModelAvailableForProvider("anthropic",c))throw new Error(`Model override '${c}' is not available for anthropic provider`);u=c}}else if(u){if(!await i.isModelAvailableForProvider("anthropic",u))throw new Error(`Model '${u}' is not available for anthropic provider`)}else!!ge&&await i.isModelAvailableForProvider("anthropic",ge)?(u=ge,M.log(`Using default model: ${ge}`)):ge&&M.log(`Default model ${ge} is not available, proceeding without model specification`);me.env.ANTHROPIC_API_KEY=h,me.env.ANTHROPIC_BASE_URL=d}else if(!me.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let y=[],T=[],E={},m=0,I=0,R,S,P=[ie(s,"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose","--disallowed-tools","ExitPlanMode,AskUserQuestion",...u?["--model",u]:[],...n?["--continue"]:[],...n&&o?["--resume",o]:[],"-p",p],$=`${me.env.NVM_BIN}/node`;M.log(`Running ${$} ${P.join(" ")}`);let k=t.utils.run($,P,{all:!0,env:me.env,cwd:s,idleTimeout:ne});k.stdin?.end();let x=ue(()=>{r?.({steps:y,duration:I})},250),v=(h,d)=>{let c={...h,id:m};m+=1,T.push(c),y.push(c),d||x.flush(),x(),d&&x.flush()},j=zr.createInterface({input:k.all});return j.on("error",h=>{M.error("Readline interface error",{error:h.message,stack:h.stack})}),j.on("line",h=>{let d=null;try{d=JSON.parse(h)}catch{M.log("Could not parse line",h)}d?.session_id&&d.session_id!==g&&(g=d.session_id),Array.isArray(d?.message?.content)?d.message.content.forEach(c=>{switch(c.type){case"text":{c.text&&v({message:c.text});break}case"image":{typeof c.source=="object"&&c.source&&c.source.type==="base64"&&c.source.media_type?v({message:``}):M.log(`Unsupported image type ${c.source?.type}`,c.source);break}case"tool_use":{if(c.name==="Task"){let w=c.input?.description&&`\`${c.input.description}\``;v({title:[Ht(c.name),w].filter(Boolean).join(" ")})}else c.id&&(E[c.id]=c);x.flush();break}case"tool_result":{let w=c.tool_use_id?E[c.tool_use_id]:void 0,Q;if(w){let X=w.input?.file_path&&qt.relative(s,w.input.file_path),F=X&&`\`${X}\``;Q=[Ht(w.name||""),F].filter(Boolean).join(" ")}let be=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(w?.name||""),ee;if(typeof c.content=="string")ee=c.content;else if(Array.isArray(c.content)){let X=[];c.content.forEach(F=>{F?.type==="text"&&typeof F.text=="string"?X.push(F.text):F?.type==="image"&&typeof F.source=="object"&&F.source?F.source.type==="base64"&&F.source.media_type?X.push(``):M.log(`Unsupported image type ${F.source.type}`,F.source):M.log(`Unsupported block type ${F?.type}`)}),ee=X.join(`
|
|
12
12
|
|
|
13
|
-
`)}be&&
|
|
14
|
-
${
|
|
15
|
-
\`\`\``),v({title:
|
|
16
|
-
web_search_request = true`):
|
|
13
|
+
`)}be&&ee&&(ee=`\`\`\`
|
|
14
|
+
${ee.trim()}
|
|
15
|
+
\`\`\``),v({title:Q,message:ee},!0);break}case"thinking":{c.thinking&&v({title:"Thinking",message:c.thinking},!0);break}default:M.log(`Message content type is not supported ${c.type}`,c)}}):d?.type==="result"&&(I=d.duration_ms||0,d.is_error?S=d.result:R=d.result,[T,y].forEach(c=>{c[c.length-1]?.message===R&&c.pop()}))}),await k.catch(h=>{({error:S,result:R}=Zr({catchError:h,runCmd:k,error:S,result:R,runnerName:"Claude"}))}),j.close(),x.flush(),{steps:T,duration:I,result:await de({initialResult:R,agentName:Bt,hasError:!!S}),error:pe({error:S,agentName:Bt}),isRetryableError:fe(S),agentSessionId:g}}var Wt=async()=>{let e=qt.join(Xr.homedir(),".claude");await Vr.rm(e,{recursive:!0,force:!0})};import xe from"fs/promises";import Jt from"os";import Fe from"path";import oe from"process";import Qr from"readline";var G=_("runner_codex"),Kt="Codex CLI",he="",en=({catchError:e,runCmd:t,error:r,result:i,runnerName:n})=>(G.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?(G.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}):(G.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function st({config:e,netlify:t,persistSteps:r=void 0,sendSteps:i=void 0,aiGateway:n,cwd:o=oe.cwd()}){let{accountType:s,prompt:l,modelVersionOverrides:a}=e,{model:p}=e;if(n){let{token:d,url:c}=n;if(!d||!c)throw new Error("No token or url provided from AI Gateway");if(a?.codex){let w=a?.codex?.[s];if(w){if(!await n.isModelAvailableForProvider("openai",w))throw new Error(`Model override '${w}' is not available for openai provider`);p=w}}else if(p){if(!await n.isModelAvailableForProvider("openai",p))throw new Error(`Model '${p}' is not available for openai provider`)}else!!he&&await n.isModelAvailableForProvider("openai",he)?(p=he,G.log(`Using default model: ${he}`)):he&&G.log(`Default model ${he} is not available, proceeding without model specification`);oe.env.OPENAI_API_KEY=d,oe.env.OPENAI_BASE_URL=c}else if(!oe.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let f=[],u=[],g=[],y={},T=0,E=0,m,I,R=`${oe.env.NVM_BIN}/node`,S=Fe.join(Jt.homedir(),".codex"),P=Fe.join(S,"config.toml"),$=Fe.join(S,"auth.json");try{await xe.mkdir(S,{recursive:!0});let d={OPENAI_API_KEY:oe.env.OPENAI_API_KEY};await xe.writeFile($,JSON.stringify(d,null,2),"utf-8"),G.log("Created Codex auth.json file");let c="";try{c=await xe.readFile(P,"utf-8")}catch{}c.includes("web_search_request")||(c.includes("[features]")?c=c.replace(/\[features\]/,`[features]
|
|
16
|
+
web_search_request = true`):c+=`
|
|
17
17
|
[features]
|
|
18
18
|
web_search_request = true
|
|
19
|
-
`,await xe.writeFile(P,
|
|
20
|
-
`):
|
|
21
|
-
`))}),await x.catch(d=>{let
|
|
22
|
-
${
|
|
23
|
-
\`\`\``),e.status==="failed"&&e.exit_code!==0&&(
|
|
19
|
+
`,await xe.writeFile(P,c,"utf-8"),G.log("Updated Codex config with web_search_request enabled"))}catch(d){throw G.warn("Failed to setup Codex config and credentials",{error:d.message}),new Error(`Codex setup failed: ${d.message}`)}let k=[ie(o,"codex"),"exec","--yolo","--json","--enable","web_search_request",...p?["--model",p]:[],l].filter(Boolean);G.log(`Running ${R} ${k.join(" ")}`);let x=t.utils.run(R,k,{all:!0,cwd:o,env:{...oe.env},idleTimeout:ne}),v=ue(()=>{r?.({steps:f,duration:E}),i?.({steps:u,duration:E}),u=[]},250),j=(d,c)=>{d.id=T,T+=1,g.push(d),f.push(d),u.push(d),c||v.flush(),v(),c&&v.flush()},h=Qr.createInterface({input:x.all});return h.on("error",d=>{G.error("Readline interface error",{error:d.message,stack:d.stack})}),h.on("line",d=>{let c=null;try{c=JSON.parse(d)}catch{G.log("Could not parse line",d);return}if(c?.duration_ms&&(E=c.duration_ms),c?.type==="item.started"&&c?.item?.type==="command_execution")y[c.item.id]=c.item;else if(c?.type==="item.completed"&&c?.item?.type==="command_execution"){let w=rn(c.item);w&&j(w,!0)}else if(c?.type==="item.completed"&&c?.item?.type==="reasoning"){let w={title:"Reasoning",message:c.item.text};j(w,!0)}else if(c?.type==="local_shell_call")y[c.call_id]=c;else if(c?.type==="local_shell_call_output"){let w=nn(y[c.call_id],c);w&&j(w,!0)}else c?.type==="message"&&c.role==="assistant"?m=c.content.map(w=>w.text).join(`
|
|
20
|
+
`):c?.type==="message"&&c.role==="system"&&(I=c.content.map(w=>w.text).join(`
|
|
21
|
+
`))}),await x.catch(d=>{let c=en({catchError:d,runCmd:x,error:I,result:m,runnerName:"Codex"});I=c.error,m=c.result}),h.close(),v.flush(),{steps:g,duration:E,result:await de({initialResult:m,agentName:Kt,hasError:!!I}),error:pe({error:I,agentName:Kt}),isRetryableError:fe(I)}}var Vt=async()=>{let e=Fe.join(Jt.homedir(),".codex");await xe.rm(e,{recursive:!0,force:!0})},tn=new Set(["bash","-lc"]),rn=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
24
|
|
|
25
|
-
*Exit code: ${e.exit_code}*`:`*Command failed with exit code: ${e.exit_code}*`),{title:r,message:
|
|
25
|
+
*Exit code: ${e.exit_code}*`:`*Command failed with exit code: ${e.exit_code}*`),{title:r,message:i}},nn=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(o=>!tn.has(o)),i=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
|
|
26
26
|
${n.trim()}
|
|
27
|
-
\`\`\``)}catch(
|
|
27
|
+
\`\`\``)}catch(o){G.error("Could not decode outputMsg",o,t.output)}return{title:i,message:n}};import Oe from"fs/promises";import zt from"os";import ke from"path";import ye from"process";import on from"readline";var Y=_("runner_gemini"),Xt="Gemini CLI",_e="",sn=({catchError:e,runCmd:t,error:r,result:i,runnerName:n})=>(Y.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?(Y.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}):(Y.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),an={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"},ln=async()=>{let e=ke.join(zt.homedir(),".gemini"),t=ke.join(e,"settings.json");try{await Oe.mkdir(e,{recursive:!0});let r={};try{let i=await Oe.readFile(t,"utf-8");r=JSON.parse(i)}catch{Y.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 Oe.writeFile(t,JSON.stringify(r,null,2),"utf-8"),Y.log("Configured Gemini CLI settings (preview features and compression threshold)")}catch(r){Y.error("Failed to ensure Gemini CLI settings",{error:r.message})}};async function at({config:e,netlify:t,persistSteps:r=void 0,sendSteps:i=void 0,aiGateway:n,cwd:o=ye.cwd()}){let{accountType:s,prompt:l,modelVersionOverrides:a}=e,{model:p}=e;if(await ln(),n){let{token:h,url:d}=n;if(!h||!d)throw new Error("No token or url provided from AI Gateway");if(a?.gemini){let c=a?.gemini?.[s];if(c){if(!await n.isModelAvailableForProvider("gemini",c))throw new Error(`Model override '${c}' is not available for gemini provider`);p=c}}if(!p)!!_e&&await n.isModelAvailableForProvider("gemini",_e)?(p=_e,Y.log(`Using default model: ${_e}`)):_e&&Y.log(`Default model ${_e} is not available, proceeding without model specification`);else if(p&&!a?.gemini?.[s]&&!await n.isModelAvailableForProvider("gemini",p))throw new Error(`Model '${p}' is not available for gemini provider`);ye.env.GEMINI_API_KEY=h,ye.env.GOOGLE_GEMINI_BASE_URL=d}else if(!ye.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let f=[],u=[],g=[],y={},T=0,E=0,m,I,R=[ie(o,"gemini"),...p?["--model",p]:[],"--yolo","--output-format","stream-json","-p",l],S=`${ye.env.NVM_BIN}/node`;Y.log(`Running ${S} ${R.join(" ")}`);let P=t.utils.run(S,R,{all:!0,env:ye.env,cwd:o,idleTimeout:ne});P.stdin?.end();let $=ue(()=>{r?.({steps:f,duration:E}),i?.({steps:u,duration:E}),u=[]},250),k=(h,d)=>{h.id=T,T+=1,g.push(h),f.push(h),u.push(h),d||$.flush(),$(),d&&$.flush()},x=on.createInterface({input:P.all});x.on("error",h=>{Y.error("Readline interface error",{error:h.message,stack:h.stack})});let v="",j=()=>{v&&k({message:v.trim()}),v=""};return x.on("line",h=>{let d=null;try{if(h.startsWith("[API Error")){let c=h.match(/\[api error: (.+?)]$/i)?.[1];d={type:"error",value:Ot(c,!1)?.error?.message||c||"Gemini encountered error"}}else d=JSON.parse(h)}catch{return}if(d)switch(["message","result"].includes(d.type)||j(),d.type){case"message":{d.role!=="user"&&d.content&&(v+=d.content);break}case"tool_use":{let c=an[d.tool_name]??d.tool_name,w=d.parameters?.file_path,Q=w&&ke.relative(o,w),be=d.parameters?.command,X={title:[c,Q&&`\`${Q}\``,be&&`\`${be}\``].filter(Boolean).join(" ")};y[d.tool_id]=X,$.flush();break}case"tool_result":{let c=y[d.tool_id];c&&(d.output&&(c.message=`\`\`\`
|
|
28
28
|
${d.output.trim()}
|
|
29
|
-
\`\`\``),
|
|
29
|
+
\`\`\``),k(c,!0));break}case"result":{E=d.stats?.duration_ms,d.status==="error"?I=d.error?.message:m=v.trim();break}case"error":{I=d.error;break}case"finished":break;default:{Y.warn("Unhandled message type:",d.type);break}}}),await P.catch(h=>{({error:I,result:m}=sn({catchError:h,runCmd:P,error:I,result:m,runnerName:"Gemini"}))}),x.close(),$.flush(),{steps:g,duration:E,result:await de({initialResult:m,agentName:Xt,hasError:!!I}),error:pe({error:I,agentName:Xt}),isRetryableError:fe(I)}}var Zt=async()=>{let e=ke.join(zt.homedir(),".gemini");await Oe.rm(e,{recursive:!0,force:!0})};var cn={codex:{runner:st,clean:Vt},claude:{runner:ot,clean:Wt},gemini:{runner:at,clean:Zt}},Qt=cn;var Le=_("init_stage"),tr=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:i})=>await A(pn(),"init-stage",async n=>{let o=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 s=Qt[e.runner];if(!s)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let l=mn({apiToken:r});wt(l);let a=e.useGateway?await St({netlify:l,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!a});let p=5*1024,f=Ft(async({steps:T=[],duration:E})=>{let m=T.map(I=>{let R=I.title?Qe(J(I.title),p):void 0,S=I.message?Qe(J(I.message)):void 0;return{...I,title:R,message:S}});T.length=0;try{return await q(e.id,e.sessionId,{steps:m,duration:E})}catch(I){Le.error("persistSteps failed",{error:I?.message||I})}},t);Le.info("Adding build files to stage");let u=await rt();await et(u),z.env.NETLIFY_LOCAL_MODE||await fn();let g;e.hasRepo?e.sha?(g=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(g=await Gt(),await Te(e.id,{sha:g}),n?.setAttributes({"init.sha.source":"current_commit"})):(g=await jt(),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let y=performance.now()-o;return n?.setAttributes({"init.sha":g||"unknown","init.duration.ms":y,"init.status":"success"}),{aiGateway:a,context:l,persistSteps:f,runner:s,sha:g}}),fn=async()=>{let e="/usr/bin/git";try{e=un("which git").toString().trim()||e}catch{}let t="/tmp/netlify-git-wrapper",r=dn.join(t,"git"),i=`#!/bin/bash
|
|
30
30
|
# Git wrapper that blocks add and commit commands
|
|
31
31
|
# The deployment system handles staging and commits automatically
|
|
32
32
|
|
|
33
33
|
# Allow internal system calls to bypass the wrapper
|
|
34
34
|
if [ "$NETLIFY_INTERNAL_GIT" = "1" ]; then
|
|
35
|
-
exec
|
|
35
|
+
exec ${e} "$@"
|
|
36
36
|
fi
|
|
37
37
|
|
|
38
38
|
case "$1" in
|
|
@@ -53,23 +53,23 @@ case "$1" in
|
|
|
53
53
|
exit 1
|
|
54
54
|
;;
|
|
55
55
|
*)
|
|
56
|
-
exec
|
|
56
|
+
exec ${e} "$@"
|
|
57
57
|
;;
|
|
58
58
|
esac
|
|
59
|
-
`;try{await
|
|
59
|
+
`;try{await er.mkdir(t,{recursive:!0}),await er.writeFile(r,i,{mode:493}),z.env.PATH=`${t}:${z.env.PATH}`,z.env.NETLIFY_INTERNAL_GIT="0",Le.info("Installed git wrapper to block add/commit commands")}catch(n){Le.warn("Failed to install git wrapper",{error:n?.message||n})}},mn=({apiToken:e})=>({constants:{NETLIFY_API_HOST:z.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||z.env.NETLIFY_API_TOKEN,SITE_ID:z.env.SITE_ID,FUNCTIONS_DIST:z.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:N}});import{getTracer as lt}from"@netlify/otel";import gn from"crypto";import Z from"fs/promises";import D from"path";import B from"process";var L=_("context"),hn=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:B.env.NETLIFY_TEAM_ID,userId:B.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:B.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},yn=10,_n=async e=>{let{name:t,ext:r}=D.parse(e),i=e,n=D.join(B.cwd(),U,i),o=0;for(;await En(n);){if(o>=yn)throw new Error("Failed to generate context file");i=`${t}-${gn.randomUUID().slice(0,5)}${r}`,n=D.join(B.cwd(),U,i),o+=1}return i},En=async e=>{try{return await Z.access(e),!0}catch{return!1}},wn=async()=>{try{L.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 L.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"?(L.warn("Catchall consumer missing or invalid contextScopes"),null):r:(L.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?L.warn("Netlify features context request timed out"):L.warn("Failed to fetch Netlify features context:",e.message),null}},Tn=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 Z.writeFile(t,i,"utf-8"),!0}catch(r){return r.name==="AbortError"?L.warn(`Download timeout for ${e}`):L.warn(`Failed to download context file ${e}:`,r.message),!1}},De=null,In=async()=>{if(De)return De;let e=await wn();if(!e)return[];let t=D.join(B.cwd(),U,Ve);await Z.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([n,o])=>{if(!o||typeof o!="object"||!o.endpoint||!o.scope)return L.warn(`Invalid scope data for ${n}, skipping...`),null;let s=`${n}.md`,l=D.join(t,s),a=D.join(U,Ve,s);return L.log(`Downloading ${o.scope} context...`),await Tn(o.endpoint,l)?(L.log(`Downloaded: ${a}`),{scope:o.scope,path:a,key:n}):null});return De=(await Promise.all(r)).filter(n=>n!==null),De},rr=async({cliPath:e,netlify:t,config:r,buildErrorContext:i})=>{let n=hn(t),o=await _n(Ct),s=D.join(B.cwd(),U);await Z.mkdir(s,{recursive:!0});let l=D.join(U,o),a=D.join(B.cwd(),l),p=D.join(B.cwd(),U,re);try{await Z.unlink(p),L.log(`Deleted old results file: ${p}`)}catch{}let f=i?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
|
|
60
60
|
Your task is to analyze and fix the build errors.
|
|
61
61
|
Don't apply techniques of reverting changes. Apply fixes related to errors.
|
|
62
62
|
Don't try to run build by yourself. Just fix the errors.
|
|
63
63
|
|
|
64
64
|
<build_error_context>
|
|
65
|
-
${
|
|
65
|
+
${i}
|
|
66
66
|
</build_error_context>`:"",u="";r.siteContext&&r.siteContext.length!==0&&(u=`
|
|
67
67
|
<project_rules>
|
|
68
|
-
${r.siteContext.filter(
|
|
68
|
+
${r.siteContext.filter(m=>m.site_context).map(m=>typeof m.site_context=="string"?m.site_context:typeof m.site_context=="object"?JSON.stringify(m.site_context):"").join(`
|
|
69
69
|
|
|
70
70
|
`)}
|
|
71
71
|
</project_rules>
|
|
72
|
-
`);let
|
|
72
|
+
`);let g="";if(r.sessionHistoryContext?.length){let m=D.join(B.cwd(),U,Je);await Z.mkdir(m,{recursive:!0});let I=await Promise.all(r.sessionHistoryContext.map(async(R,S)=>{let P=S+1,$=`attempt-${P}.md`,k=D.join(m,$),x=D.join(U,Je,$),v=`# Task History - Attempt ${P}
|
|
73
73
|
|
|
74
74
|
## Request - what the user asked for
|
|
75
75
|
${R.request}
|
|
@@ -79,26 +79,26 @@ ${R.request}
|
|
|
79
79
|
## Response - what the agent replied with after its work
|
|
80
80
|
|
|
81
81
|
${R.response}
|
|
82
|
-
`;return await
|
|
82
|
+
`;return await Z.writeFile(k,v,"utf-8"),L.log(`Created history file: ${x}`),x}));g+=`
|
|
83
83
|
<session_history_context>
|
|
84
84
|
History of prior work on this task.
|
|
85
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.
|
|
86
86
|
|
|
87
|
-
${
|
|
87
|
+
${I.slice(-5).map(R=>`- ${R}`).join(`
|
|
88
88
|
`)}
|
|
89
89
|
|
|
90
90
|
</session_history_context>
|
|
91
|
-
`}let y=await
|
|
91
|
+
`}let y=await In(),T="";y.length>0&&(T=`
|
|
92
92
|
<netlify_features_context>
|
|
93
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
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
95
|
|
|
96
|
-
${y.map(
|
|
96
|
+
${y.map(m=>`- **${m.scope}**: ${m.path}`).join(`
|
|
97
97
|
`)}
|
|
98
98
|
|
|
99
99
|
Refer to these files when working with specific Netlify features.
|
|
100
100
|
</netlify_features_context>
|
|
101
|
-
`);let
|
|
101
|
+
`);let E=`
|
|
102
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.
|
|
103
103
|
|
|
104
104
|
<request>
|
|
@@ -111,15 +111,16 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
111
111
|
<requirements>
|
|
112
112
|
<responses>
|
|
113
113
|
- Do not speak in first person. You may speak as "the agent".
|
|
114
|
-
- When work is complete, write a changes summary in ${s}/${
|
|
115
|
-
- 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 ${s}/${
|
|
114
|
+
- When work is complete, write a changes summary in ${s}/${re} 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.
|
|
115
|
+
- 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 ${s}/${re} file.
|
|
116
116
|
- 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.
|
|
117
117
|
- NEVER look into the \`.git\` folder
|
|
118
118
|
- NEVER print potentially sensitive values (like secrets) in the planning output or results
|
|
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 ${s}/${re}. 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 ${s}/${
|
|
122
|
-
- move assets from ${s}/${
|
|
122
|
+
- for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${s}/${Xe} folder
|
|
123
|
+
- move assets from ${s}/${Xe} folder to the project assets folder if they are referenced in a code or applied changes
|
|
123
124
|
</attachements>
|
|
124
125
|
${u}
|
|
125
126
|
</requirements>
|
|
@@ -138,15 +139,15 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
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>
|
|
141
|
-
${
|
|
142
|
+
${T}
|
|
142
143
|
<docs>
|
|
143
144
|
- Netlify Docs: https://docs.netlify.com
|
|
144
145
|
- LLM Resources Index: https://docs.netlify.com/llms.txt
|
|
145
146
|
</docs>
|
|
146
147
|
</extra_context>
|
|
147
148
|
|
|
148
|
-
${
|
|
149
|
-
`;return await
|
|
149
|
+
${g}
|
|
150
|
+
`;return await Z.writeFile(a,E,"utf-8"),L.log(`Generated agent context document at: ${a}`),E.length>5e5&&(E=`
|
|
150
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.
|
|
151
152
|
|
|
152
153
|
<request>
|
|
@@ -156,20 +157,22 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
156
157
|
${f}
|
|
157
158
|
</request>
|
|
158
159
|
|
|
159
|
-
Use the following file for the complete context of the ask, the environment, and what's available. ${
|
|
160
|
-
`),
|
|
160
|
+
Use the following file for the complete context of the ask, the environment, and what's available. ${a} You MUST READ ALL OF IT. Make sure to read it first. Never cite or paraphrase private context.
|
|
161
|
+
`),E};var xn=_("prompt"),nr=async({cliPath:e,config:t,netlify:r,buildErrorContext:i})=>{let n=await rr({cliPath:e,config:t,netlify:r,buildErrorContext:i});return process.env.AGENT_RUNNER_DEBUG&&xn.log("Contextful Prompt:",n),{prompt:n}};var Ue=_("inference_stage"),ir=5,Me=async e=>{let{cliPath:t,config:r,context:i,buildErrors:n,runner:o,persistSteps:s,aiGateway:l,attempt:a,contextPrefix:p,priorAgentSessionId:f}=e;Ue.log(`Running inference stage, attempt ${a} of ${ir}`);let u=await A(lt(),"inference-stage",async g=>{g?.setAttributes({"inference.attempt":a||1}),bt();let{prompt:y}=await A(lt(),"compose-prompt",async()=>await nr({cliPath:t,config:r,buildErrorContext:vn(n),netlify:i})),T=`
|
|
161
162
|
${p||""}
|
|
162
163
|
${y}
|
|
163
|
-
`.trim(),
|
|
164
|
+
`.trim(),E={...r,prompt:T},m=await A(lt(),`run-${r.runner}`,async()=>await o({aiGateway:l,config:E,netlify:i,persistSteps:s,continueSession:!!(a&&a>1),priorAgentSessionId:f}));return m.result&&(m.result=J(m.result)),m.error&&(m.error=J(m.error)),await s.flush(),m});if(u.error){if(Ue.error("Runner failed",{stepsCount:u.steps.length,duration:u.duration,error:u.error,isRetryableError:u.isRetryableError,attempt:a||1,agentSessionId:u.agentSessionId}),u.isRetryableError&&(!a||a<ir))return Ue.log("Retrying inference stage"),await new Promise(y=>setTimeout(y,5e3)),{runnerResult:(await Me({...e,attempt:(a||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 Ue.log("Do not retry inference stage"),new Error(u.error)}return{runnerResult:u}},vn=e=>!e||e.length===0?"":`
|
|
164
165
|
Deploy failed failed. Here are the errors to review on the latest build:
|
|
165
166
|
|
|
166
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.
|
|
167
168
|
|
|
168
169
|
${e.pop()}
|
|
169
|
-
`;import
|
|
170
|
-
Preview deploy created successfully:`,{deployId:u.deploy_id,deployUrl:u.deploy_url,siteId:u.site_id});let
|
|
171
|
-
`);for(let s of
|
|
172
|
-
`),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:
|
|
170
|
+
`;import bn from"process";import{getTracer as ct}from"@netlify/otel";import{getTracer as Rn}from"@netlify/otel";var ve=_("deploy"),or=async e=>await A(Rn(),"create-preview-deploy",async t=>Sn(e,t)),Sn=async({netlify:e,hasRepo:t,skipBuild:r,message:i="Agent Preview",deploySubdomain:n,cliPath:o,filter:s},l)=>{try{let a=["deploy","--message",`"${i}"`,"--json","--draft","--verbose"];t||(ve.log("Deploy: Uploading source zip"),a.push("--upload-source-zip")),n&&a.push("--alias",n),s&&a.push("--filter",s),r?(ve.log("Deploy: Skipping build"),a.push("--no-build")):a.push("--context","deploy-preview");let p=o||"netlify";ve.log(`Running: ${p} ${a.join(" ")}`),l?.setAttributes({cmd:p,args:a});let f=await e.utils.run(p,a,{stdio:["ignore","pipe","pipe"]}),u=JSON.parse(String(f.stdout??"").trim());l?.setAttributes({success:!0,deployId:u.deploy_id,deployUrl:u.deploy_url,siteId:u.site_id}),ve.log(`
|
|
171
|
+
Preview deploy created successfully:`,{deployId:u.deploy_id,deployUrl:u.deploy_url,siteId:u.site_id});let g={deployId:u.deploy_id,previewUrl:u.deploy_url,logsUrl:u.logs,siteId:u.site_id};return t||(g.sourceZipFilename=u.source_zip_filename),g}catch(a){throw ve.error("Failed to create preview deploy via CLI:",a),l?.setAttributes({success:!1,error:a.message}),a}};var Re=_("deploy_stage"),ut=async e=>await A(ct(),"run-deploy-stage",async()=>An(e)),An=async({cliPath:e,config:t,context:r,result:i,filter:n,isRetry:o})=>{let s=await A(ct(),"get-runner-diffs",async()=>await Ut({config:t,isRetry:o}));if(Re.info("Resolved git",{hasChanges:s.hasChanges,ignored:s.ignored??[]}),!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:l,resultDiff:a,diffBinary:p,resultDiffBinary:f}=s,u=!0;Re.log("Preview deploy condition check:",{resultUndefined:i===void 0,resultType:typeof i,hasChanges:u,wouldCreatePreview:i!==void 0&&u});let g=null;if(i!==void 0&&u)try{let y;try{let T=await A(ct(),"get-runner-session",async()=>await It(t.id,t.sessionId));T?.title&&(y=T.title)}catch(T){Re.warn("Failed to fetch session title, using fallback message:",T.message)}await q(t.id,t.sessionId,{steps:[{title:"Deploying the run preview"}]}),g=await or({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:y,skipBuild:!1,deploySubdomain:kt(t.id,bn.env.SITE_NAME),filter:n})}catch(y){return Re.warn("Failed to create preview deploy (continuing with agent run):",y),{diff:l,resultDiff:a,hasChanges:u,previewInfo:null,diffBinary:p,resultDiffBinary:f,deployError:y instanceof Error?y.message:String(y)}}return Re.log("Git status",{hasDiff:!!l,hasChanges:u}),{diff:l,resultDiff:a,hasChanges:u,previewInfo:g,diffBinary:p,resultDiffBinary:f}};import{getTracer as Ye}from"@netlify/otel";async function sr(e,t){let{maxRetries:r,baseDelay:i,onRetry:n}=t,o;for(let s=1;s<=r;s++)try{return await e()}catch(l){if(o=l,s===r)throw o;n&&n(s,o),await new Promise(a=>setTimeout(a,i*s))}throw o}var Ge=class{scanDiffForForms(t){let r=[],i=null,n=[],o=t.split(`
|
|
172
|
+
`);for(let s of o)if(s.startsWith("diff --git")){if(i&&n.length>0){let a=this.containsNetlifyForm(n,i);a&&r.push(a)}let l=s.split(" ");i=l[l.length-1].replace(/^b\//,""),n=[]}else s.startsWith("+")&&!s.startsWith("+++")&&n.push(s.slice(1));if(i&&n.length>0){let s=this.containsNetlifyForm(n,i);s&&r.push(s)}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:o,name:s}of n){let l=i.match(o);if(l){let a=l.index||0,p=Math.max(0,a-20),f=Math.min(i.length,a+l[0].length+20),u=i.slice(p,f).trim();return u=u.replace(/\s+/g," "),u.length>100&&(u=u.slice(0,97)+"..."),{file:r,snippet:`[${s}] ${u}`}}}return null}};var je=class{scanDiffForIdentity(t){let r=[],i=null,n=[],o=t.split(`
|
|
174
|
+
`);for(let s of o)if(s.startsWith("diff --git")){if(i&&n.length>0){let a=this.containsNetlifyIdentity(n,i);a&&r.push(a)}let l=s.split(" ");i=l[l.length-1].replace(/^b\//,""),n=[]}else s.startsWith("+")&&!s.startsWith("+++")&&n.push(s.slice(1));if(i&&n.length>0){let s=this.containsNetlifyIdentity(n,i);s&&r.push(s)}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:o,name:s}of n){let l=i.match(o);if(l){let a=l.index||0,p=Math.max(0,a-20),f=Math.min(i.length,a+l[0].length+20),u=i.slice(p,f).trim();return u=u.replace(/\s+/g," "),u.length>100&&(u=u.slice(0,97)+"..."),{file:r,snippet:`[${s}] ${u}`}}}return null}};var b=_("cleanup_stage"),ar=async e=>await A(Ye(),"cleanup-stage",async()=>Nn(e)),dt=1024*1024*10,Nn=async({config:e,diff:t,result:r,duration:i,resultDiff:n,diffBinary:o,resultDiffBinary:s,previewInfo:l})=>{let a={result:r||"Done",duration:i};l&&l.deployId&&(a.deploy_id=l.deployId),l&&l.sourceZipFilename&&(a.result_zip_file_name=l.sourceZipFilename);let p=t||o||n||s;if(p&&(a.diff_produced=!0),p){let f=new Ge,u=t||o||"",g=f.scanDiffForForms(u);g.detected?(b.log("Detected Netlify form(s) in diff:"),g.matches.forEach(({file:E,snippet:m})=>{b.log(` - ${E}: ${m}`)}),a.has_netlify_form=!0):b.log("Did not detect Netlify form(s) in diff");let T=new je().scanDiffForIdentity(u);T.detected?(b.log("Detected Netlify Identity usage in diff:"),T.matches.forEach(({file:E,snippet:m})=>{b.log(` - ${E}: ${m}`)}),a.has_netlify_identity=!0):b.log("Did not detect Netlify Identity usage in diff")}if(p)try{b.log("Getting pre-signed URLs for diff upload");let f=await vt(e.id,e.sessionId),u=[];(t||o)&&u.push(We(f.result.upload_url,o||t).then(()=>{a.result_diff_s3_key=f.result.s3_key,b.log("Successfully uploaded result_diff to S3")})),(n||s)&&u.push(We(f.cumulative.upload_url,s||n).then(()=>{a.cumulative_diff_s3_key=f.cumulative.s3_key,b.log("Successfully uploaded cumulative_diff to S3")})),b.log(`Uploading ${u.length} diff(s) to S3 in parallel`),await Promise.all(u),(n||s)&&(b.log("Updating agent runner with cumulative diff S3 key"),await A(Ye(),"update-runner",async()=>{await Te(e.id,{result_diff_s3_key:f.cumulative.s3_key})}))}catch(f){b.error("S3 upload failed, falling back to inline diffs:",f);let u=Buffer.byteLength(t||o||""),g=Buffer.byteLength(s||n||"");if(u>dt||g>dt){let y=`Diffs exceed maximum inline size of ${dt} bytes.`;throw b.error(y),new Error(y)}a.result_diff=t,a.result_diff_binary=o,(n||s)&&(a.cumulative_diff=n,a.cumulative_diff_binary=s,b.log("Updating agent runner with inline diffs (fallback)"),await A(Ye(),"update-runner",async()=>{await Te(e.id,{result_diff:n,result_diff_binary:s})}))}else b.log("No diffs to upload");return b.log("Updated agent runner with result"),await sr(async()=>await A(Ye(),"update-runner-session",()=>q(e.id,e.sessionId,a)),{maxRetries:3,baseDelay:1e3,onRetry:(f,u)=>{b.error(`Error updating agent runner session (attempt ${f}):`,u),b.log("Retrying...")}}),b.log("Finished updating agent runner with result"),{sessionUpdate:a}};import{getTracer as lr,shutdownTracers as Pn,withActiveSpan as cr}from"@netlify/otel";var $n=Cn(import.meta.url),ur=$n("../package.json"),Se=_("pipeline_index"),Be=3,dr=async({config:e,apiToken:t,cliPath:r="netlify",cwd:i,filter:n,tracing:o={}})=>{let s,{withStageTimer:l}=At(te.timeUnits.hours(4)),a=await yt(ur.version,e.id,o);try{await cr(lr(),"run-pipeline",{},a,async()=>{let{aiGateway:p,context:f,persistSteps:u,runner:g,sha:y}=await l("init",()=>tr({config:e,apiToken:t,cliPath:r,cwd:i,filter:n,runnerVersion:ur.version}),te.timeUnits.minutes(10));s=g.clean,e.sha=y;let{runnerResult:T}=await l("inference",()=>Me({cliPath:r,config:e,context:f,runner:g.runner,persistSteps:u,aiGateway:p}));await q(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let E=await l("deploy",()=>ut({cliPath:r,config:e,context:f,result:T.result,filter:n,isRetry:!1})),m=T,I=[];if(E.hasChanges&&E.deployError){I.push(_t(E.deployError));let x=1,v=!1;for(;x<=Be&&!E.previewInfo&&!v;)Se.log(`Deploy attempt had errors. Retrying. ${x}/${Be}`),await cr(lr(),"deploy-stage",async j=>{j?.setAttributes({"stage.attempt":x});let h;try{h=(await l(`inference-retry-${x}`,()=>Me({cliPath:r,config:e,context:f,runner:g.runner,persistSteps:u,aiGateway:p,buildErrors:I,priorAgentSessionId:T.agentSessionId}))).runnerResult}catch(d){Se.warn(`Inference retry ${x} failed, stopping deploy retries:`,d),v=!0;return}m={...h,steps:[...m.steps||[],...h.steps||[]],duration:(m.duration||0)+(h.duration||0)},E=await l(`deploy-retry-${x}`,()=>ut({cliPath:r,config:e,context:f,result:h.result,filter:n,isRetry:!0})),E.deployError&&I.push(E.deployError),x++});x>Be&&!E.previewInfo&&console.warn(`Deploy validation failed after ${Be} attempts`)}let{diff:R,resultDiff:S,previewInfo:P,diffBinary:$,resultDiffBinary:k}=E;await l("cleanup",()=>ar({config:e,diff:R,result:m.result,duration:m.duration,resultDiff:S,diffBinary:$,resultDiffBinary:k,previewInfo:P}),te.timeUnits.minutes(10)),process.env.NETLIFY_LOCAL_MODE||(await s?.(),await Yt())})}catch(p){if(Et(p)){Se.info("Agent run terminated gracefully",{statusCode:p.statusCode,reason:p.message}),await s?.();try{await q(e.id,e.sessionId,{result:p.userMessage,state:"error"})}catch{Se.info("Could not update session (site may have been deleted)")}return}Se.error("Got error while running pipeline",p),await s?.();let f=p instanceof Error&&p.message;throw await q(e.id,e.sessionId,{result:f||"Encountered error when running agent",state:"error"}),p}finally{await Pn()}};import pr from"crypto";var O=_("bin_local"),K=Fn(C.argv.slice(2),{string:["cwd","cli-path","filter","prompt","runner","model","netlify-api-token"],boolean:["verbose","help"],alias:{h:"help",v:"verbose"}}),ft=()=>{console.log(`
|
|
173
176
|
agent-runner-cli-local - Run Netlify agent runner locally without API connections
|
|
174
177
|
|
|
175
178
|
USAGE:
|
|
@@ -201,6 +204,6 @@ NOTE:
|
|
|
201
204
|
This local mode mocks all Netlify API calls. The agent will run through
|
|
202
205
|
the full pipeline including inference and deployment, but API calls will
|
|
203
206
|
be logged instead of executed.
|
|
204
|
-
`)};
|
|
205
|
-
To link this directory to a Netlify site, run:`),O.error(" netlify link"),C.exit(1)}let
|
|
207
|
+
`)};K.help&&(ft(),C.exit(0));K.prompt||(O.error("Error: --prompt is required"),ft(),C.exit(1));K["netlify-api-token"]||(O.error("Error: --netlify-api-token is required - generate a PAT from your Netlify user settings"),ft(),C.exit(1));try{let e=K.cwd||C.cwd(),t=fr.join(e,".netlify","netlify-agent-runner-context*");mr.rmSync(t,{recursive:!0,force:!0});let r;try{r=await On(e)}catch(l){O.error(l.message),O.error(`
|
|
208
|
+
To link this directory to a Netlify site, run:`),O.error(" netlify link"),C.exit(1)}let i=`local-${pr.randomBytes(8).toString("hex")}`,n=`session-${pr.randomBytes(8).toString("hex")}`,o=K.runner||"claude";O.log("Starting agent runner in local mode",{runnerId:i,sessionId:n,siteId:r,cwd:e,runner:o});let s={id:i,sessionId:n,prompt:K.prompt,runner:o,model:K.model,accountType:"free",mode:"normal",sessionHistoryContext:[],siteContext:[],hasRepo:!0,useGateway:!0,sha:void 0,modelVersionOverrides:{}};C.env.NETLIFY_LOCAL_MODE="true",C.env.NETLIFY_API_HOST="api.netlify.com",C.env.NETLIFY_API_TOKEN=K["netlify-api-token"],C.env.SITE_ID=r,C.env.NETLIFY_TEAM_ID="local-team-id",C.env.NETLIFY_AGENT_RUNNER_USER_ID="local-user-id",C.env.SITE_NAME="local-site",o==="claude"?$e(e,"claude")||(O.log("Claude CLI not found, installing..."),await pt(e,"@anthropic-ai/claude-code")):o==="gemini"?$e(e,"gemini")||(O.log("Gemini CLI not found, installing..."),await pt(e,"@google/gemini-cli")):o==="codex"?$e(e,"codex")||(O.log("Codex CLI not found, installing..."),await pt(e,"@openai/codex")):(O.error(`Unknown runner: ${o}`),C.exit(1)),await dr({config:s,cwd:e,cliPath:K["cli-path"],filter:K.filter,tracing:{exporterUrl:void 0,traceparent:void 0}}),O.info("Finished agent (local mode)"),C.exit(0)}catch(e){O.error("Error running agent pipeline (local mode):",e),C.exit(1)}function pt(e,t){return new Promise((r,i)=>{N("npm",["install",t,"--no-save"],{cwd:e}).then(({stdout:n})=>{O.log(`${t} installed: ${n}`),r()}).catch(n=>{O.error(`Error installing ${t}: ${n.stderr||n.message}`),i(n)})})}async function On(e){let t=fr.join(e,".netlify","state.json");try{let r=await mr.readFileSync(t,"utf-8"),i=JSON.parse(r);if(!i.siteId)throw new Error(`No siteId found in ${t}. Please link this directory to a Netlify site using 'netlify link'.`);return O.log(`Found site ID from state file: ${i.siteId}`),i.siteId}catch(r){throw r.code==="ENOENT"?new Error(`No .netlify/state.json found in ${e}. Please link this directory to a Netlify site using 'netlify link'.`):r}}
|
|
206
209
|
//# sourceMappingURL=bin-local.js.map
|