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