@netlify/agent-runner-cli 1.49.5-alpha → 1.49.7-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 +43 -44
- package/dist/bin.js +43 -44
- package/dist/index.js +42 -43
- package/package.json +6 -6
- package/patches/@google+gemini-cli+0.1.17.patch +0 -87
package/dist/bin-local.js
CHANGED
|
@@ -1,64 +1,61 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`),r=[],o=-1,n=0;for(;n<t.length;){let
|
|
4
|
-
`)),o=
|
|
2
|
+
import O from"process";import Xt from"path";import zt from"fs";import pn from"minimist";import{createRequire as un}from"module";import{createTracerProvider as Zt}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as et}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as Qt}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as er}from"@netlify/otel";import{propagation as tt,context as rt,W3CTraceContextPropagator as tr}from"@netlify/otel/opentelemetry";import{OTLPTraceExporter as rr}from"@opentelemetry/exporter-trace-otlp-grpc";function E(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 Pe=E("tracing"),nt=async(e,t,r)=>(await Zt({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new et(new Oe),new et(new rr({url:r.exporterUrl}))],instrumentations:[new Qt({skipHeaders:!0})]}),r.traceparent?(tt.setGlobalPropagator(new tr),tt.extract(rt.active(),{traceparent:r.traceparent,isRemote:!0})):rt.active());function b(e,t,r){return Pe.log(`\u23F3 TRACE: ${t} starting...`),er(e,t,r)}var Oe=class{export(t,r){for(let o of t)this.logSpan(o);r({code:1})}async shutdown(){}forceFlush(){return Promise.resolve()}logSpan(t){let r=(t.endTime[0]-t.startTime[0])*1e3+(t.endTime[1]-t.startTime[1])/1e6,o=t.attributes,n=[];for(let[l,s]of Object.entries(o))l.includes("duration")&&typeof s=="number"?n.push(`${l}=${s.toFixed(2)}ms`):n.push(`${l}=${s}`);let i=t.status?.code===2?"\u274C":"\u2705",a=n.length>0?` [${n.join(", ")}]`:"";Pe.log(`${i} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${a}`),t.status?.code===2&&t.status.message&&Pe.log(` \u274C Error: ${t.status.message}`)}};var nr=["error","failed","exception","fatal","panic","abort","crash"];function ot(e){let t=e.split(`
|
|
3
|
+
`),r=[],o=-1,n=0;for(;n<t.length;){let l=t[n].slice(0,500).toLowerCase();if(nr.some(m=>l.includes(m))){let m=Math.max(0,n-10,o+1),c=Math.min(t.length-1,n+20),u=[];for(let f=m;f<=c;f++)u.push(t[f]);r.push(u.join(`
|
|
4
|
+
`)),o=c,n=c+1}else n++}if(r.length===0)return e;let i=r.map((a,l)=>`<extracted_error_chunk order="${l+1}">
|
|
5
5
|
${a}
|
|
6
6
|
</extracted_error_chunk>`).join(`
|
|
7
7
|
|
|
8
|
-
`);return i.length>e.length*.8?e:i}import Re from"process";import{getTracer as Lr}from"@netlify/otel";import le from"process";var me=le.env.NETLIFY_API_URL,he=le.env.NETLIFY_API_TOKEN,j=w("api"),ye=()=>le.env.NETLIFY_LOCAL_MODE==="true",ue=async(e,t={})=>{if(!me||!he)throw new Error("No API URL or token");let r=new URL(e,me),o={...t,headers:{...t.headers,Authorization:`Bearer ${he}`}};le.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(le.env.AGENT_RUNNERS_DEBUG==="true")j.log(`Response headers for ${r}:`),n.headers.forEach((u,s)=>{j.log(` ${s}: ${u}`)});else{let u=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");j.log(`Request ID for ${r}: ${u||"N/A"}`)}if(i||j.error(`Got status ${n.status} for request ${r}`),t.raw){if(!i)throw n;return n}let a=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!i)throw a;return a},nt=e=>{j.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(me=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(he=e.constants.NETLIFY_API_TOKEN)},ot=()=>({apiUrl:me,token:he}),ce=async(e,t)=>ye()?(j.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):ue(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),B=async(e,t,r)=>ye()?(j.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):ue(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var it=async(e,t)=>ye()?(j.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):ue(`/api/v1/agent_runners/${e}/sessions/${t}`),st=(e,t,r)=>ue(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}}),at=async(e,t)=>ye()?(j.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"}}):ue(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),$e=async(e,t)=>{j.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 ee=w("ai_gateway"),De=null;var lt=async()=>{if(De)return De;ee.log("Fetching available AI gateway providers");let e=await fetch(`${ot().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 De=t,ee.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},er=async(e,t)=>{let o=(await lt()).providers[e];if(!o)return ee.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return ee.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},ut=async({netlify:e,config:t})=>{let r,o,n,i,a=e.constants?.SITE_ID;if(!a)throw new Error("No site id");let u=async()=>{clearTimeout(n),ee.log("Requesting AI gateway information");let s=await st(a,t.id,t.sessionId);if({token:r,url:i}=s,o=s.expires_at?s.expires_at*1e3:void 0,ee.log("Got AI gateway information",{token:!!r,expiresAt:o,url:i}),o){let y=o-Date.now()-6e4;y>0&&(n=setTimeout(()=>{u()},y))}};return await Promise.all([u(),lt()]),{get url(){return i},get token(){return r},isModelAvailableForProvider:er}};import K from"process";import Ee from"path";import ke from"fs";import{fileURLToPath as sr}from"url";import{execa as ar,execaCommand as Cn}from"execa";import{Transform as tr}from"stream";var rr=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"]),nr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function or(){return Object.entries(process.env).filter(([e,t])=>!(!t||rr.has(e)||nr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function H(e){if(typeof e!="string")return e;let t=or();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(ir(o),"g");r=r.replace(n,"******")}),r}function ir(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var te=class extends tr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),i=H(n);o(null,i)}};function ct(){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 a=typeof o=="string"?H(o):o;return typeof n=="function"?t(a,n):t(a,n,i)},process.stderr.write=function(o,n,i){let a=typeof o=="string"?H(o):o;return typeof n=="function"?r(a,n):r(a,n,i)}}var de=null,dt=e=>(de&&de.destroy(),de=new V({totalAllowedTime:e}),de),pt=()=>de;var V=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,a=null;o!==void 0&&(a=new Promise((u,s)=>{i=setTimeout(()=>{s(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return a?await Promise.race([r(),a]):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 lr=sr(import.meta.url),ur=Ee.dirname(lr),_e=w("shell"),Le=new Set,cr={preferLocal:!0},we=(e,t,r)=>{let[o,n]=dr(t,r),i={...cr,...n},a=ar(e,o,i);return pr(a,i),gr(a),a};var dr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},pr=(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 te).pipe(K.stdout),e.stdout?.pipe(new te).pipe(K.stdout),e.stderr?.pipe(new te).pipe(K.stderr);return}e.stdout?.pipe(K.stdout),e.stderr?.pipe(K.stderr)},ft=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(K.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=>ft(e,"SIGKILL"),gr=e=>{Le.add(e);let t=pt();if(t){let r=t.onTimesUp(()=>{_e.log(`Global timer expired, killing process ${e.pid}`),ft(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(_e.log(`Force killing process ${e.pid} after timeout`),fr(e))},5e3)});e.on("exit",()=>{Le.delete(e),r()}),e.on("error",()=>{Le.delete(e),r()})}};function Ie(e,t){return!!J(e,t)}function J(e,t){if(K.env.NODE_PATH){let n=Ee.join(K.env.NODE_PATH,".bin",t);if(ke.existsSync(n))return n}let r=Ee.join(e,"node_modules",".bin",t);if(ke.existsSync(r))return r;let o=Ee.join(ur,"..","node_modules",".bin",t);if(ke.existsSync(o))return o}var gt="netlify-agent-runner-context.md",Fe="task-history",Ue="netlify-context",U=".netlify",re="results.md",Me="assets";var mr=w("utils"),hr=e=>new Promise(t=>{setTimeout(t,e)}),mt=(e,t=3e3)=>{let r=!1,o=null,n=[],i=null,a=(...u)=>{if(r)return o=u,new Promise(l=>{n.push(l)});r=!0;let s,y=new Promise(l=>{s=l});return i=(async()=>{await Promise.resolve();let l=await e(...u);for(s(l);;){if(await hr(t),!o)return r=!1,i=null,l;let c=o,m=n;o=null,n=[],l=await e(...c),m.forEach(E=>{E(l)})}})(),y};return a.flush=async()=>{if((r||o)&&i)return await i,a.flush()},a},Te=(e,t,r=!1)=>{let o=null,n=null,i=null,a=function(...u){n=u,i=this;let s=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(i,n),n=null,i=null)},t),s&&(e.apply(i,n),n=null,i=null)};return a.cancel=()=>{clearTimeout(o),o=null,n=null,i=null},a.flush=()=>{if(o){clearTimeout(o);let u=n,s=i;o=null,n=null,i=null,e.apply(s,u)}},a},ht=(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))}},yt=(e,t)=>{let n=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let u=`--${t}${n}`;if(u.length>55)return"";let s=60-u.length;if(s<=0)return"";if(s>=i.length+6){let y=Math.min(s-i.length,e.length);return`${i}${e.slice(0,y)}`}return e.slice(0,s)};import{Buffer as Et}from"buffer";import yr from"path";var _t=async({config:e,netlify:t})=>{let r=await _r(t),{hasChanges:o}=r,{status:n}=r;if(!o)return{hasChanges:!1};let i=await wr(n);await t.utils.run("git",["add",".",...i]);let a={stdio:["ignore","pipe","pipe"]},s=(await t.utils.run("git",["diff","--staged"],a)).stdout;if(o=!!s,!o)return{hasChanges:!1,ignored:i};let l=(await t.utils.run("git",["diff","--staged","--binary"],a)).stdout,c,m;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await t.utils.run("git",["commit","-m","Agent runner"]),c=(await t.utils.run("git",["diff",e.sha,"HEAD"],a)).stdout;let h=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;c!==h&&(m=Et.from(h).toString("base64"))}let E={hasChanges:!0,diff:s,resultDiff:c,ignored:i};return s!==l&&(E.diffBinary=Et.from(l).toString("base64")),m&&(E.resultDiffBinary=m),E},Er=["?? mise.toml","?? deno.lock","?? .npmrc",/\?\? .+?\.log/],_r=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
|
|
9
|
-
`).filter(
|
|
10
|
-
`).forEach(o=>{t.forEach(i=>{[`?? ${i}`,`?? ${i}${
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
`,await pe.writeFile(v,p,"utf-8"),$.log("Updated Codex config with web_search enabled"))}catch(g){throw $.warn("Failed to setup Codex config and credentials",{error:g.message}),new Error(`Codex setup failed: ${g.message}`)}let N=[J(z.cwd(),"codex"),"exec","--yolo","--json","--config","web_search=true",...s?["--model",s]:[],a].filter(Boolean);$.log(`Running ${h} ${N.join(" ")}`);let R=t.utils.run(h,N,{all:!0,env:z.env});R.stdin?.end(),R.stdout?.on("data",g=>{$.log("[STDOUT]",g.toString())}),R.stderr?.on("data",g=>{$.log("[STDERR]",g.toString())}),R.all?.on("data",g=>{$.log("[ALL]",g.toString())});let S=Sr.createInterface({input:R.all});return S.on("error",g=>{$.error("Readline interface error",{error:g.message,stack:g.stack})}),S.on("line",g=>{$.log("Received line from Codex:",g);let p=null;try{p=JSON.parse(g)}catch{$.log("Could not parse line",g);return}let f=[],_=!1;if(p?.duration_ms&&(E=p.duration_ms,_=!0),p?.type==="local_shell_call")c[p.call_id]=p;else if(p?.type==="local_shell_call_output"){let d=br(c[p.call_id],p);d&&(d.id=m,m+=1,l.push(d),y.push(d),f.push(d),_=!0)}else p?.type==="message"&&p.role==="assistant"?T=p.content.map(d=>d.text).join(`
|
|
19
|
-
`):p?.type==="message"&&p.role==="system"&&(I=p.content.map(d=>d.text).join(`
|
|
20
|
-
`));_&&(r?.({steps:y,duration:E}),o?.({steps:f,duration:E}))}),await R.catch(g=>{let p=Ar({catchError:g,runCmd:R,error:I,result:T,runnerName:"Codex"});I=p.error,T=p.result}),S.close(),!T&&!I&&R.exitCode===0&&(I="Codex process completed successfully but produced no output",$.error("Codex process exited with code 0 but no result or error was captured")),{steps:l,duration:E,result:await ne({initialResult:T,agentName:St,hasError:!!I}),error:oe({error:I,agentName:St}),isRetryableError:ie(I)}}var Nt=async()=>{let e=ve.join(At.homedir(),".codex");await pe.rm(e,{recursive:!0,force:!0})},Nr=new Set(["bash","-lc"]),br=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(i=>!Nr.has(i)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
|
|
8
|
+
`);return i.length>e.length*.8?e:i}import ve from"process";import{getTracer as Hr}from"@netlify/otel";import ue from"process";var he=ue.env.NETLIFY_API_URL,ye=ue.env.NETLIFY_API_TOKEN,j=E("api"),Ee=()=>ue.env.NETLIFY_LOCAL_MODE==="true",ce=async(e,t={})=>{if(!he||!ye)throw new Error("No API URL or token");let r=new URL(e,he),o={...t,headers:{...t.headers,Authorization:`Bearer ${ye}`}};ue.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(ue.env.AGENT_RUNNERS_DEBUG==="true")j.log(`Response headers for ${r}:`),n.headers.forEach((l,s)=>{j.log(` ${s}: ${l}`)});else{let l=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");j.log(`Request ID for ${r}: ${l||"N/A"}`)}if(i||j.error(`Got status ${n.status} for request ${r}`),t.raw){if(!i)throw n;return n}let a=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!i)throw a;return a},it=e=>{j.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(he=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(ye=e.constants.NETLIFY_API_TOKEN)},st=()=>({apiUrl:he,token:ye}),de=async(e,t)=>Ee()?(j.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):ce(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),B=async(e,t,r)=>Ee()?(j.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):ce(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var at=async(e,t)=>Ee()?(j.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):ce(`/api/v1/agent_runners/${e}/sessions/${t}`),lt=(e,t,r)=>ce(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}}),ut=async(e,t)=>Ee()?(j.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"}}):ce(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Fe=async(e,t)=>{j.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 te=E("ai_gateway"),$e=null;var ct=async()=>{if($e)return $e;te.log("Fetching available AI gateway providers");let e=await fetch(`${st().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 $e=t,te.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},or=async(e,t)=>{let o=(await ct()).providers[e];if(!o)return te.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return te.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},dt=async({netlify:e,config:t})=>{let r,o,n,i,a=e.constants?.SITE_ID;if(!a)throw new Error("No site id");let l=async()=>{clearTimeout(n),te.log("Requesting AI gateway information");let s=await lt(a,t.id,t.sessionId);if({token:r,url:i}=s,o=s.expires_at?s.expires_at*1e3:void 0,te.log("Got AI gateway information",{token:!!r,expiresAt:o,url:i}),o){let m=o-Date.now()-6e4;m>0&&(n=setTimeout(()=>{l()},m))}};return await Promise.all([l(),ct()]),{get url(){return i},get token(){return r},isModelAvailableForProvider:or}};import q from"process";import _e from"path";import De from"fs";import{fileURLToPath as cr}from"url";import{execa as dr,execaCommand as Mn}from"execa";import{Transform as ir}from"stream";var sr=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"]),ar=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function lr(){return Object.entries(process.env).filter(([e,t])=>!(!t||sr.has(e)||ar.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function H(e){if(typeof e!="string")return e;let t=lr();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(ur(o),"g");r=r.replace(n,"******")}),r}function ur(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var re=class extends ir{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),i=H(n);o(null,i)}};function pt(){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 a=typeof o=="string"?H(o):o;return typeof n=="function"?t(a,n):t(a,n,i)},process.stderr.write=function(o,n,i){let a=typeof o=="string"?H(o):o;return typeof n=="function"?r(a,n):r(a,n,i)}}var pe=null,ft=e=>(pe&&pe.destroy(),pe=new J({totalAllowedTime:e}),pe),gt=()=>pe;var J=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,a=null;o!==void 0&&(a=new Promise((l,s)=>{i=setTimeout(()=>{s(new Error(`${t} stage exceeded its maximum duration of ${o}ms`))},o)}));try{return a?await Promise.race([r(),a]):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 pr=cr(import.meta.url),fr=_e.dirname(pr),we=E("shell"),Le=new Set,gr={preferLocal:!0},P=(e,t,r)=>{let[o,n]=mr(t,r),i={...gr,...n},a=dr(e,o,i);return hr(a,i),Er(a),a};var mr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},hr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(q.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new re).pipe(q.stdout),e.stdout?.pipe(new re).pipe(q.stdout),e.stderr?.pipe(new re).pipe(q.stderr);return}e.stdout?.pipe(q.stdout),e.stderr?.pipe(q.stderr)},mt=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(q.kill(-e.pid,t),we.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return we.error("Error killing process:",r),!1}},yr=e=>mt(e,"SIGKILL"),Er=e=>{Le.add(e);let t=gt();if(t){let r=t.onTimesUp(()=>{we.log(`Global timer expired, killing process ${e.pid}`),mt(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(we.log(`Force killing process ${e.pid} after timeout`),yr(e))},5e3)});e.on("exit",()=>{Le.delete(e),r()}),e.on("error",()=>{Le.delete(e),r()})}};function Ie(e,t){return!!X(e,t)}function X(e,t){if(q.env.NODE_PATH){let n=_e.join(q.env.NODE_PATH,".bin",t);if(De.existsSync(n))return n}let r=_e.join(e,"node_modules",".bin",t);if(De.existsSync(r))return r;let o=_e.join(fr,"..","node_modules",".bin",t);if(De.existsSync(o))return o}var ht="netlify-agent-runner-context.md",ke="task-history",Ue="netlify-context",U=".netlify",ne="results.md",Me="assets";var _r=E("utils"),wr=e=>new Promise(t=>{setTimeout(t,e)}),yt=(e,t=3e3)=>{let r=!1,o=null,n=[],i=null,a=(...l)=>{if(r)return o=l,new Promise(c=>{n.push(c)});r=!0;let s,m=new Promise(c=>{s=c});return i=(async()=>{await Promise.resolve();let c=await e(...l);for(s(c);;){if(await wr(t),!o)return r=!1,i=null,c;let u=o,f=n;o=null,n=[],c=await e(...u),f.forEach(h=>{h(c)})}})(),m};return a.flush=async()=>{if((r||o)&&i)return await i,a.flush()},a},Te=(e,t,r=!1)=>{let o=null,n=null,i=null,a=function(...l){n=l,i=this;let s=r&&!o;clearTimeout(o),o=setTimeout(()=>{o=null,r||(e.apply(i,n),n=null,i=null)},t),s&&(e.apply(i,n),n=null,i=null)};return a.cancel=()=>{clearTimeout(o),o=null,n=null,i=null},a.flush=()=>{if(o){clearTimeout(o);let l=n,s=i;o=null,n=null,i=null,e.apply(s,l)}},a},Et=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):_r.error("Could not parse JSON",o))}},_t=(e,t)=>{let n=".netlify.app",i="agent-";if(!t)return`${i}${e.slice(0,6)}`;let l=`--${t}${n}`;if(l.length>55)return"";let s=60-l.length;if(s<=0)return"";if(s>=i.length+6){let m=Math.min(s-i.length,e.length);return`${i}${e.slice(0,m)}`}return e.slice(0,s)};import{Buffer as wt}from"buffer";import Ir from"path";var It=E("repo"),Tt=async({config:e})=>{It.info("Getting runner diffs");let t=await xr(),{hasChanges:r}=t,{status:o}=t;if(!r)return{hasChanges:!1};let n=vr(o);await Rr(n),It.info("Changes after processing"),await je();let i=await Ye(o);await Ge(i);let a={stdio:["ignore","pipe","pipe"]},s=(await P("git",["diff","--staged"],a)).stdout;if(r=!!s,!r)return{hasChanges:!1,ignored:i};let c=(await P("git",["diff","--staged","--binary"],a)).stdout,u,f;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await P("git",["commit","-m","Agent runner"]),u=(await P("git",["diff",e.sha,"HEAD"],a)).stdout;let g=(await P("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;u!==g&&(f=wt.from(g).toString("base64"))}let h={hasChanges:!0,diff:s,resultDiff:u,ignored:i};return s!==c&&(h.diffBinary=wt.from(c).toString("base64")),f&&(h.resultDiffBinary=f),h},Ge=async(e=[])=>{await P("git",["add",".",...e])},je=async()=>(await P("git",["status","-s"])).stdout,xt=/.. (.+)?\.log$/,Tr=[xt],xr=async()=>{let e=await je();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
9
|
+
`).filter(o=>Tr.some(i=>i instanceof RegExp?i.test(o):o===i)?!1:o[1]?.trim()!=="")).length!==0,status:e}},vt=async()=>{let{stdout:e}=await P("git",["rev-parse","HEAD"]);return e.trim()},Rt=async()=>{let{stdout:e}=await P("git",["rev-list","--max-parents=0","HEAD"]);return e.trim()},Ye=async e=>{e||=await je();let t=[".netlify","node_modules"],r=[];return e.split(`
|
|
10
|
+
`).forEach(o=>{t.forEach(i=>{[`?? ${i}`,`?? ${i}${Ir.sep}`].some(l=>o.startsWith(l))&&r.push(`:!${i}`)});let n=o.match(xt)?.[1];n&&r.push(`:!${n}.log`)}),r},St=async()=>{await P("git",["reset","--hard","HEAD"])},vr=e=>{let t=e.split(`
|
|
11
|
+
`).reduce((r,o)=>{if(!o)return r;let[n,i,,...a]=o,l=a.join(""),s=n.trim(),m=i.trim();return r[l]?r[l].change=m:r[l]={filePath:l,stage:s,change:m},r},{});return Object.values(t)},Rr=async e=>{let t=[];for(let r of e)r.stage&&!r.change&&t.push(P("git",["restore","--staged","--worktree",r.filePath]));await Promise.allSettled(t)};import Ar from"fs/promises";import Nr from"os";import bt from"path";import z from"process";import br from"readline";import Be from"path";import Sr from"fs/promises";var He=E("agent-output-utils");async function oe({initialResult:e,agentName:t,hasError:r}){let o="",n=Be.join(process.cwd(),U,ne);try{let i=await Sr.readFile(n,"utf-8");i&&(o=i,He.log(`Pulled result from ${Be.relative(process.cwd(),n)}`))}catch{He.log(`No results file found at ${Be.relative(process.cwd(),n)}`)}return o||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function ie({error:e,agentName:t}){let r=e&&typeof e=="object"?JSON.stringify(e):e,o=r?.replace(/\s+/g," ").trim().toLowerCase()||"",n="";return o?.includes("ai gateway is not available for your account")||o?.includes("ai gateway is not enabled for your account")?n="AI Gateway is currently not available on your account. Please confirm your account meets the criteria for using Agent Runners and AI Gateway and that your account has remaining AI Gateway inference credits available. Reach out to Netlify support if this is unexpected.":o?.includes("error when talking to gemini api")?n="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":(o?.includes("connection closed prematurely")||o?.includes("499")&&t.toLowerCase().includes("gemini"))&&(n=`The ${t} models were currently overloaded. Please try again or use a different available agent.`),o?.includes("request timed out")&&(n=`The ${t} API request's have timed out. Please try again or use a different available agent.`),o?.includes("network error")&&(n=`The ${t} agent is having network issues. Please try again or use a different available agent.`),n&&He.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function se(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 M=E("runner_claude"),At="Claude Code",xe="claude-sonnet-4-5-20250929",Nt=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,Cr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(M.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(M.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(M.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function qe({config:e,netlify:t,persistSteps:r,aiGateway:o,continueSession:n,priorAgentSessionId:i}){let a=e,{accountType:l,prompt:s,modelVersionOverrides:m}=a,{model:c}=a,u="";if(o){let{token:y,url:p}=o;if(!y||!p)throw new Error("No token or url provided from AI Gateway");if(m?.claude){let d=m?.claude?.[l];if(d){if(!await o.isModelAvailableForProvider("anthropic",d))throw new Error(`Model override '${d}' is not available for anthropic provider`);c=d}}else if(c){if(!await o.isModelAvailableForProvider("anthropic",c))throw new Error(`Model '${c}' is not available for anthropic provider`)}else await o.isModelAvailableForProvider("anthropic",xe)?(c=xe,M.log(`Using default model: ${xe}`)):M.log(`Default model ${xe} is not available, proceeding without model specification`);z.env.ANTHROPIC_API_KEY=y,z.env.ANTHROPIC_BASE_URL=p}else if(!z.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let f=[],h=[],w={},I=0,g=0,v,x,N=[X(z.cwd(),"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...c?["--model",c]:[],...n?["--continue"]:[],...n&&i?["--resume",i]:[],"-p",s],T=`${z.env.NVM_BIN}/node`;M.log(`Running ${T} ${N.join(" ")}`);let _=t.utils.run(T,N,{all:!0,env:z.env});_.stdin?.end();let R=Te(()=>{r?.({steps:f,duration:g})},250),S=(y,p)=>{let d={...y,id:I};I+=1,h.push(d),f.push(d),p||R.flush(),R(),p&&R.flush()},A=br.createInterface({input:_.all});return A.on("error",y=>{M.error("Readline interface error",{error:y.message,stack:y.stack})}),A.on("line",y=>{let p=null;try{p=JSON.parse(y)}catch{M.log("Could not parse line",y)}p?.session_id&&p.session_id!==u&&(u=p.session_id),Array.isArray(p?.message?.content)?p.message.content.forEach(d=>{switch(d.type){case"text":{d.text&&S({message:d.text});break}case"image":{typeof d.source=="object"&&d.source&&d.source.type==="base64"&&d.source.media_type?S({message:``}):M.log(`Unsupported image type ${d.source?.type}`,d.source);break}case"tool_use":{if(d.name==="Task"){let D=d.input?.description&&`\`${d.input.description}\``;S({title:[Nt(d.name),D].filter(Boolean).join(" ")})}else d.id&&(w[d.id]=d);R.flush();break}case"tool_result":{let D=d.tool_use_id?w[d.tool_use_id]:void 0,ee;if(D){let K=D.input?.file_path&&bt.relative(z.cwd(),D.input.file_path),F=K&&`\`${K}\``;ee=[Nt(D.name||""),F].filter(Boolean).join(" ")}let me=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(D?.name||""),V;if(typeof d.content=="string")V=d.content;else if(Array.isArray(d.content)){let K=[];d.content.forEach(F=>{F?.type==="text"&&typeof F.text=="string"?K.push(F.text):F?.type==="image"&&typeof F.source=="object"&&F.source?F.source.type==="base64"&&F.source.media_type?K.push(``):M.log(`Unsupported image type ${F.source.type}`,F.source):M.log(`Unsupported block type ${F?.type}`)}),V=K.join(`
|
|
12
|
+
|
|
13
|
+
`)}me&&V&&(V=`\`\`\`
|
|
14
|
+
${V.trim()}
|
|
15
|
+
\`\`\``),S({title:ee,message:V},!0);break}case"thinking":{d.thinking&&S({title:"Thinking",message:d.thinking},!0);break}default:M.log(`Message content type is not supported ${d.type}`,d)}}):p?.type==="result"&&(g=p.duration_ms||0,p.is_error?x=p.result:v=p.result,[h,f].forEach(d=>{d[d.length-1]?.message===v&&d.pop()}))}),await _.catch(y=>{({error:x,result:v}=Cr({catchError:y,runCmd:_,error:x,result:v,runnerName:"Claude"}))}),A.close(),R.flush(),{steps:h,duration:g,result:await oe({initialResult:v,agentName:At,hasError:!!x}),error:ie({error:x,agentName:At}),isRetryableError:se(x),agentSessionId:u}}var Ct=async()=>{let e=bt.join(Nr.homedir(),".claude");await Ar.rm(e,{recursive:!0,force:!0})};import Pr from"fs/promises";import Or from"os";import Fr from"path";import ae from"process";import $r from"readline";var Z=E("runner_codex"),Pt="Codex CLI",Dr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(Z.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(Z.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(Z.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function Ke({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:i,prompt:a,modelVersionOverrides:l}=e,{model:s}=e;if(n){let{token:T,url:_}=n;if(!T||!_)throw new Error("No token or url provided from AI Gateway");if(l?.codex){let R=l?.codex?.[i];if(R){if(!await n.isModelAvailableForProvider("openai",R))throw new Error(`Model override '${R}' is not available for openai provider`);s=R}}else if(s&&!await n.isModelAvailableForProvider("openai",s))throw new Error(`Model '${s}' is not available for openai provider`);ae.env.OPENAI_API_KEY=T,ae.env.OPENAI_BASE_URL=_}else if(!ae.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let m=[],c=[],u={},f=0,h=0,w,I,g=[X(ae.cwd(),"codex"),"--approval-mode","full-auto",n?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...s?["--model",s]:[],"-q",a].filter(Boolean),v=`${ae.env.NVM_BIN}/node`;Z.log(`Running ${v} ${g.join(" ")}`);let x=t.utils.run(v,g,{all:!0,env:{...ae.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),N=$r.createInterface({input:x.all});return N.on("error",T=>{Z.error("Readline interface error",{error:T.message,stack:T.stack})}),N.on("line",T=>{let _=null;try{_=JSON.parse(T)}catch{Z.log("Could not parse line",T);return}let R=[],S=!1;if(_?.duration_ms&&(h=_.duration_ms,S=!0),_?.type==="local_shell_call")u[_.call_id]=_;else if(_?.type==="local_shell_call_output"){let A=kr(u[_.call_id],_);A&&(A.id=f,f+=1,c.push(A),m.push(A),R.push(A),S=!0)}else _?.type==="message"&&_.role==="assistant"?w=_.content.map(A=>A.text).join(`
|
|
16
|
+
`):_?.type==="message"&&_.role==="system"&&(I=_.content.map(A=>A.text).join(`
|
|
17
|
+
`));S&&(r?.({steps:m,duration:h}),o?.({steps:R,duration:h}))}),await x.catch(T=>{let _=Dr({catchError:T,runCmd:x,error:I,result:w,runnerName:"Codex"});I=_.error,w=_.result}),N.close(),{steps:c,duration:h,result:await oe({initialResult:w,agentName:Pt,hasError:!!I}),error:ie({error:I,agentName:Pt}),isRetryableError:se(I)}}var Ot=async()=>{let e=Fr.join(Or.homedir(),".codex");await Pr.rm(e,{recursive:!0,force:!0})},Lr=new Set(["bash","-lc"]),kr=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(i=>!Lr.has(i)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
|
|
21
18
|
${n.trim()}
|
|
22
|
-
\`\`\``)}catch(i){
|
|
23
|
-
${
|
|
24
|
-
\`\`\``),
|
|
19
|
+
\`\`\``)}catch(i){Z.error("Could not decode outputMsg",i,t.output)}return{title:o,message:n}};import Ur from"fs/promises";import Mr from"os";import $t from"path";import Q from"process";import Gr from"readline";var le=E("runner_gemini"),Ft="Gemini CLI",jr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(le.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!o,resultLength:o?o.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),o?(le.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:o}:{error:"Process completed with errors but result was captured",result:o}):(le.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),Yr={list_directory:"List",read_file:"Read",write_file:"Write",glob:"Find",search_file_content:"Find",replace:"Edit",run_shell_command:"Run",web_fetch:"Web Fetch",web_search:"Web Search",read_many_files:"Read Many",save_memory:"Memorize"};async function We({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:i,prompt:a,modelVersionOverrides:l}=e,{model:s}=e;if(n){let{token:y,url:p}=n;if(!y||!p)throw new Error("No token or url provided from AI Gateway");if(l?.gemini){let d=l?.gemini?.[i];if(d){if(!await n.isModelAvailableForProvider("gemini",d))throw new Error(`Model override '${d}' is not available for gemini provider`);s=d}}else if(s&&!await n.isModelAvailableForProvider("gemini",s))throw new Error(`Model '${s}' is not available for gemini provider`);Q.env.GEMINI_API_KEY=y,Q.env.GOOGLE_GEMINI_BASE_URL=p}else if(!Q.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let m=[],c=[],u=[],f={},h=0,w=0,I,g,v=[X(Q.cwd(),"gemini"),...s?["--model",s]:[],"--yolo","--output-format","stream-json","-p",a],x=`${Q.env.NVM_BIN}/node`;le.log(`Running ${x} ${v.join(" ")}`);let N=t.utils.run(x,v,{all:!0,env:Q.env});N.stdin?.end();let T=Te(()=>{r?.({steps:m,duration:w}),o?.({steps:c,duration:w}),c=[]},250),_=(y,p)=>{y.id=h,h+=1,u.push(y),m.push(y),c.push(y),p||T.flush(),T(),p&&T.flush()},R=Gr.createInterface({input:N.all});R.on("error",y=>{le.error("Readline interface error",{error:y.message,stack:y.stack})});let S="",A=()=>{S&&_({message:S.trim()}),S=""};return R.on("line",y=>{let p=null;try{if(y.startsWith("[API Error")){let d=y.match(/\[api error: (.+?)]$/i)?.[1];p={type:"error",value:Et(d,!1)?.error?.message||d||"Gemini encountered error"}}else p=JSON.parse(y)}catch{return}if(p)switch(["message","result"].includes(p.type)||A(),p.type){case"message":{p.role!=="user"&&p.content&&(S+=p.content);break}case"tool_use":{let d=Yr[p.tool_name]??p.tool_name,D=p.parameters?.file_path,ee=D&&$t.relative(Q.cwd(),D),me=p.parameters?.command,K={title:[d,ee&&`\`${ee}\``,me&&`\`${me}\``].filter(Boolean).join(" ")};f[p.tool_id]=K,T.flush();break}case"tool_result":{let d=f[p.tool_id];d&&(p.output&&(d.message=`\`\`\`
|
|
20
|
+
${p.output.trim()}
|
|
21
|
+
\`\`\``),_(d,!0));break}case"result":{w=p.stats?.duration_ms,p.status==="error"?g=p.error?.message:I=S.trim();break}case"error":{g=p.error;break}case"finished":break;default:{le.warn("Unhandled message type:",p.type);break}}}),await N.catch(y=>{({error:g,result:I}=jr({catchError:y,runCmd:N,error:g,result:I,runnerName:"Gemini"}))}),R.close(),T.flush(),{steps:u,duration:w,result:await oe({initialResult:I,agentName:Ft,hasError:!!g}),error:ie({error:g,agentName:Ft}),isRetryableError:se(g)}}var Dt=async()=>{let e=$t.join(Mr.homedir(),".gemini");await Ur.rm(e,{recursive:!0,force:!0})};var Br={codex:{runner:Ke,clean:Ot},claude:{runner:qe,clean:Ct},gemini:{runner:We,clean:Dt}},Lt=Br;var qr=E("init_stage"),kt=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>await b(Hr(),"init-stage",async n=>{let i=performance.now();n?.setAttributes({"init.runner":e.runner,"init.id":e.id,"init.sessionId":e.sessionId,"init.hasRepo":e.hasRepo,"init.useGateway":e.useGateway,"init.validateAgent":e.validateAgent,"init.runnerVersion":o||"unknown"});let a=Lt[e.runner];if(!a)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let l=Kr({apiToken:r});it(l);let s=e.useGateway?await dt({netlify:l,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!s}),e.validateAgent&&e.errorLogsPath&&n?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let m=yt(({steps:h=[],duration:w})=>{let I=h.map(g=>({...g,title:g.title?H(g.title):void 0,message:g.message?H(g.message):void 0}));return h.length=0,B(e.id,e.sessionId,{steps:I,duration:w})},t);qr.info("Adding build files to stage");let c=await Ye();await Ge(c);let u;e.hasRepo?e.sha?(u=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(u=await vt(),await de(e.id,{sha:u}),n?.setAttributes({"init.sha.source":"current_commit"})):(u=await Rt(),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let f=performance.now()-i;return n?.setAttributes({"init.sha":u||"unknown","init.duration.ms":f,"init.status":"success"}),{aiGateway:s,context:l,persistSteps:m,runner:a,sha:u}}),Kr=({apiToken:e})=>({constants:{NETLIFY_API_HOST:ve.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||ve.env.NETLIFY_API_TOKEN,SITE_ID:ve.env.SITE_ID,FUNCTIONS_DIST:ve.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:P}});import{getTracer as Ve}from"@netlify/otel";import Wr from"crypto";import W from"fs/promises";import k from"path";import G from"process";var L=E("context"),Vr=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:G.env.NETLIFY_TEAM_ID,userId:G.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:G.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},Jr=10,Xr=async e=>{let{name:t,ext:r}=k.parse(e),o=e,n=k.join(G.cwd(),U,o),i=0;for(;await zr(n);){if(i>=Jr)throw new Error("Failed to generate context file");o=`${t}-${Wr.randomUUID().slice(0,5)}${r}`,n=k.join(G.cwd(),U,o),i+=1}return o},zr=async e=>{try{return await W.access(e),!0}catch{return!1}},Zr=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(o=>o&&typeof o=="object"&&o.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}},Qr=async(e,t)=>{try{let r=await fetch(e,{signal:AbortSignal.timeout(1e4)});if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let o=await r.text();return await W.writeFile(t,o,"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}},Re=null,en=async()=>{if(Re)return Re;let e=await Zr();if(!e)return[];let t=k.join(G.cwd(),U,Ue);await W.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([n,i])=>{if(!i||typeof i!="object"||!i.endpoint||!i.scope)return L.warn(`Invalid scope data for ${n}, skipping...`),null;let a=`${n}.md`,l=k.join(t,a),s=k.join(U,Ue,a);return L.log(`Downloading ${i.scope} context...`),await Qr(i.endpoint,l)?(L.log(`Downloaded: ${s}`),{scope:i.scope,path:s,key:n}):null});return Re=(await Promise.all(r)).filter(n=>n!==null),Re},Ut=async({cliPath:e,netlify:t,config:r,buildErrorContext:o})=>{let n=Vr(t),i=await Xr(ht),a=k.join(G.cwd(),U);await W.mkdir(a,{recursive:!0});let l=k.join(U,i),s=k.join(G.cwd(),l),m=k.join(G.cwd(),U,ne);try{await W.unlink(m),L.log(`Deleted old results file: ${m}`)}catch{}let c=o?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
|
|
25
22
|
Your task is to analyze and fix the build errors.
|
|
26
23
|
Don't apply techniques of reverting changes. Apply fixes related to errors.
|
|
27
24
|
Don't try to run build by yourself. Just fix the errors.
|
|
28
25
|
|
|
29
26
|
<build_error_context>
|
|
30
27
|
${o}
|
|
31
|
-
</build_error_context>`:"",
|
|
28
|
+
</build_error_context>`:"",u="";r.siteContext&&r.siteContext.length!==0&&(u=`
|
|
32
29
|
<project_rules>
|
|
33
|
-
${r.siteContext.filter(
|
|
30
|
+
${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(`
|
|
34
31
|
|
|
35
32
|
`)}
|
|
36
33
|
</project_rules>
|
|
37
|
-
`);let
|
|
34
|
+
`);let f="";if(r.sessionHistoryContext?.length){let g=k.join(G.cwd(),U,ke);await W.mkdir(g,{recursive:!0});let v=await Promise.all(r.sessionHistoryContext.map(async(x,N)=>{let T=N+1,_=`attempt-${T}.md`,R=k.join(g,_),S=k.join(U,ke,_),A=`# Task History - Attempt ${T}
|
|
38
35
|
|
|
39
36
|
## Request - what the user asked for
|
|
40
|
-
${
|
|
37
|
+
${x.request}
|
|
41
38
|
|
|
42
39
|
---
|
|
43
40
|
|
|
44
41
|
## Response - what the agent replied with after its work
|
|
45
42
|
|
|
46
|
-
${
|
|
47
|
-
`;return await W.writeFile(
|
|
43
|
+
${x.response}
|
|
44
|
+
`;return await W.writeFile(R,A,"utf-8"),L.log(`Created history file: ${S}`),S}));f+=`
|
|
48
45
|
<session_history_context>
|
|
49
46
|
History of prior work on this task.
|
|
50
47
|
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.
|
|
51
48
|
|
|
52
|
-
${
|
|
49
|
+
${v.slice(-5).map(x=>`- ${x}`).join(`
|
|
53
50
|
`)}
|
|
54
51
|
|
|
55
52
|
</session_history_context>
|
|
56
|
-
`}let
|
|
53
|
+
`}let h=await en(),w="";h.length>0&&(w=`
|
|
57
54
|
<netlify_features_context>
|
|
58
55
|
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.
|
|
59
56
|
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.
|
|
60
57
|
|
|
61
|
-
${
|
|
58
|
+
${h.map(g=>`- **${g.scope}**: ${g.path}`).join(`
|
|
62
59
|
`)}
|
|
63
60
|
|
|
64
61
|
Refer to these files when working with specific Netlify features.
|
|
@@ -70,14 +67,14 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
70
67
|
<user_request>
|
|
71
68
|
${r.prompt}
|
|
72
69
|
</user_request>
|
|
73
|
-
${
|
|
70
|
+
${c}
|
|
74
71
|
</request>
|
|
75
72
|
|
|
76
73
|
<requirements>
|
|
77
74
|
<responses>
|
|
78
75
|
- Do not speak in first person. You may speak as "the agent".
|
|
79
|
-
- When work is complete, write a changes summary in ${a}/${
|
|
80
|
-
- If the user's request is informational in nature (asking for output, status, information, or analysis rather than asking you to make changes), write the requested information directly to the ${a}/${
|
|
76
|
+
- When work is complete, write a changes summary in ${a}/${ne} 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.
|
|
77
|
+
- 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}/${ne} file.
|
|
81
78
|
- 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.
|
|
82
79
|
- NEVER look into the \`.git\` folder
|
|
83
80
|
- NEVER print potentially sensitive values (like secrets) in the planning output or results
|
|
@@ -86,7 +83,7 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
86
83
|
- for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${a}/${Me} folder
|
|
87
84
|
- move assets from ${a}/${Me} folder to the project assets folder if they are referenced in a code or applied changes
|
|
88
85
|
</attachements>
|
|
89
|
-
${
|
|
86
|
+
${u}
|
|
90
87
|
</requirements>
|
|
91
88
|
|
|
92
89
|
<extra_context>
|
|
@@ -103,36 +100,38 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
103
100
|
- 'netlify-cli' npm package is already available as a global package. Don't try to install it again
|
|
104
101
|
- If you need to start a local development server in order to fulfill the request, try using the Netlify CLI over by running the shell command '${e} dev'. This will start a local HTTP server on port 8888, including live-reloading of any changes and, most critically, it offers local emulation for all Netlify features.
|
|
105
102
|
</environment>
|
|
106
|
-
${
|
|
103
|
+
${w}
|
|
107
104
|
<docs>
|
|
108
105
|
- Netlify Docs: https://docs.netlify.com
|
|
109
106
|
- LLM Resources Index: https://docs.netlify.com/llms.txt
|
|
110
107
|
</docs>
|
|
111
108
|
</extra_context>
|
|
112
109
|
|
|
113
|
-
${
|
|
114
|
-
`;return await W.writeFile(s,I,"utf-8"),
|
|
110
|
+
${f}
|
|
111
|
+
`;return await W.writeFile(s,I,"utf-8"),L.log(`Generated agent context document at: ${s}`),I.length>5e5&&(I=`
|
|
115
112
|
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.
|
|
116
113
|
|
|
117
114
|
<request>
|
|
118
115
|
<user_request>
|
|
119
116
|
${r.prompt}
|
|
120
117
|
</user_request>
|
|
121
|
-
${
|
|
118
|
+
${c}
|
|
122
119
|
</request>
|
|
123
120
|
|
|
124
121
|
Use the following file for the complete context of the ask, the environment, and what's available. ${s} You MUST READ ALL OF IT. Make sure to read it first. Never cite or paraphrase private context.
|
|
125
|
-
`),I};var
|
|
126
|
-
${
|
|
127
|
-
${
|
|
128
|
-
`.trim(),I={...r,prompt:
|
|
122
|
+
`),I};var tn=E("prompt"),Mt=async({cliPath:e,config:t,netlify:r,buildErrorContext:o})=>{let n=await Ut({cliPath:e,config:t,netlify:r,buildErrorContext:o});return process.env.AGENT_RUNNER_DEBUG&&tn.log("Contextful Prompt:",n),{prompt:n}};var Se=E("inference_stage"),Gt=5,Ae=async e=>{let{cliPath:t,config:r,context:o,buildErrors:n,runner:i,persistSteps:a,aiGateway:l,attempt:s,contextPrefix:m,priorAgentSessionId:c}=e;Se.log(`Running inference stage, attempt ${s} of ${Gt}`);let u=await b(Ve(),"inference-stage",async f=>{f?.setAttributes({"inference.attempt":s||1}),pt();let{prompt:h}=await b(Ve(),"compose-prompt",async()=>await Mt({cliPath:t,config:r,buildErrorContext:rn(n),netlify:o})),w=`
|
|
123
|
+
${m||""}
|
|
124
|
+
${h}
|
|
125
|
+
`.trim(),I={...r,prompt:w},g=await b(Ve(),`run-${r.runner}`,async()=>await i({aiGateway:l,config:I,netlify:o,persistSteps:a,continueSession:!!(s&&s>1),priorAgentSessionId:c}));return g.result&&(g.result=H(g.result)),g.error&&(g.error=H(g.error)),await a.flush(),g});if(u.error){if(Se.error("Runner failed",{stepsCount:u.steps.length,duration:u.duration,error:u.error,isRetryableError:u.isRetryableError,attempt:s||1,agentSessionId:u.agentSessionId}),u.isRetryableError&&(!s||s<Gt))return Se.log("Retrying inference stage"),await new Promise(h=>setTimeout(h,5e3)),{runnerResult:(await Ae({...e,attempt:(s||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 Se.log("Do not retry inference stage"),new Error(u.error)}return{runnerResult:u}},rn=e=>!e||e.length===0?"":`
|
|
129
126
|
Deploy failed failed. Here are the errors to review on the latest build:
|
|
130
127
|
|
|
131
128
|
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.
|
|
132
129
|
|
|
133
130
|
${e.pop()}
|
|
134
|
-
`;import
|
|
135
|
-
Preview deploy created successfully:`,{deployId:
|
|
131
|
+
`;import sn from"process";import{getTracer as Je}from"@netlify/otel";import{getTracer as nn}from"@netlify/otel";var fe=E("deploy"),jt=async e=>await b(nn(),"create-preview-deploy",async t=>on(e,t)),on=async({netlify:e,hasRepo:t,skipBuild:r,message:o="Agent Preview",deploySubdomain:n,cliPath:i,filter:a},l)=>{try{let s=["deploy","--message",`"${o}"`,"--json","--draft","--verbose"];t||(fe.log("Deploy: Uploading source zip"),s.push("--upload-source-zip")),n&&s.push("--alias",n),a&&s.push("--filter",a),r?(fe.log("Deploy: Skipping build"),s.push("--no-build")):s.push("--context","deploy-preview");let m=i||"netlify";fe.log(`Running: ${m} ${s.join(" ")}`),l?.setAttributes({cmd:m,args:s});let c=await e.utils.run(m,s,{stdio:["ignore","pipe","pipe"]}),u=JSON.parse(c.stdout.trim());l?.setAttributes({success:!0,deployId:u.deploy_id,deployUrl:u.deploy_url,siteId:u.site_id}),fe.log(`
|
|
132
|
+
Preview deploy created successfully:`,{deployId:u.deploy_id,deployUrl:u.deploy_url,siteId:u.site_id});let f={deployId:u.deploy_id,previewUrl:u.deploy_url,logsUrl:u.logs,siteId:u.site_id};return t||(f.sourceZipFilename=u.source_zip_filename),f}catch(s){throw fe.error("Failed to create preview deploy via CLI:",s),l?.setAttributes({success:!1,error:s.message}),s}};var ge=E("deploy_stage"),Xe=async e=>await b(Je(),"run-deploy-stage",async()=>an(e)),an=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let i=await b(Je(),"get-runner-diffs",async()=>await Tt({config:t,netlify:r}));if(ge.info("Resolved git",{hasChanges:i.hasChanges,ignored:i.ignored??[]}),!i.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:l,diffBinary:s,resultDiffBinary:m}=i,c=!0;ge.log("Preview deploy condition check:",{resultUndefined:o===void 0,resultType:typeof o,hasChanges:c,wouldCreatePreview:o!==void 0&&c});let u=null;if(o!==void 0&&c)try{let f;try{let h=await b(Je(),"get-runner-session",async()=>await at(t.id,t.sessionId));h?.title&&(f=h.title)}catch(h){ge.warn("Failed to fetch session title, using fallback message:",h.message)}await B(t.id,t.sessionId,{steps:[{title:"Deploying the run preview"}]}),u=await jt({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:f,skipBuild:!1,deploySubdomain:_t(t.id,sn.env.SITE_NAME),filter:n})}catch(f){return ge.warn("Failed to create preview deploy (continuing with agent run):",f),{diff:a,resultDiff:l,hasChanges:c,previewInfo:null,diffBinary:s,resultDiffBinary:m,deployError:f instanceof Error?f.message:String(f)}}return ge.log("Git status",{hasDiff:!!a,hasChanges:c}),{diff:a,resultDiff:l,hasChanges:c,previewInfo:u,diffBinary:s,resultDiffBinary:m}};import{getTracer as be}from"@netlify/otel";async function Yt(e,t){let{maxRetries:r,baseDelay:o,onRetry:n}=t,i;for(let a=1;a<=r;a++)try{return await e()}catch(l){if(i=l,a===r)throw i;n&&n(a,i),await new Promise(s=>setTimeout(s,o*a))}throw i}var Ne=class{scanDiffForForms(t){let r=[],o=null,n=[],i=t.split(`
|
|
133
|
+
`);for(let a of i)if(a.startsWith("diff --git")){if(o&&n.length>0){let s=this.containsNetlifyForm(n,o);s&&r.push(s)}let l=a.split(" ");o=l[l.length-1].replace(/^b\//,""),n=[]}else a.startsWith("+")&&!a.startsWith("+++")&&n.push(a.slice(1));if(o&&n.length>0){let a=this.containsNetlifyForm(n,o);a&&r.push(a)}return{detected:r.length>0,matches:r}}containsNetlifyForm(t,r){let o=t.join(`
|
|
134
|
+
`),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:i,name:a}of n){let l=o.match(i);if(l){let s=l.index||0,m=Math.max(0,s-20),c=Math.min(o.length,s+l[0].length+20),u=o.slice(m,c).trim();return u=u.replace(/\s+/g," "),u.length>100&&(u=u.slice(0,97)+"..."),{file:r,snippet:`[${a}] ${u}`}}}return null}};var C=E("cleanup_stage"),Bt=async e=>await b(be(),"cleanup-stage",async()=>ln(e)),ze=1024*1024*10,ln=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:i,resultDiffBinary:a,previewInfo:l})=>{let s={result:r||"Done",duration:o};l&&l.deployId&&(s.deploy_id=l.deployId),l&&l.sourceZipFilename&&(s.result_zip_file_name=l.sourceZipFilename);let m=t||i||n||a;if(m){let c=new Ne,u=t||i||"",f=c.scanDiffForForms(u);f.detected?(C.log("Detected Netlify form(s) in diff:"),f.matches.forEach(({file:h,snippet:w})=>{C.log(` - ${h}: ${w}`)}),s.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 c=await ut(e.id,e.sessionId),u=[];(t||i)&&u.push(Fe(c.result.upload_url,i||t).then(()=>{s.result_diff_s3_key=c.result.s3_key,C.log("Successfully uploaded result_diff to S3")})),(n||a)&&u.push(Fe(c.cumulative.upload_url,a||n).then(()=>{s.cumulative_diff_s3_key=c.cumulative.s3_key,C.log("Successfully uploaded cumulative_diff to S3")})),C.log(`Uploading ${u.length} diff(s) to S3 in parallel`),await Promise.all(u),(n||a)&&(C.log("Updating agent runner with cumulative diff S3 key"),await b(be(),"update-runner",async()=>{await de(e.id,{result_diff_s3_key:c.cumulative.s3_key})}))}catch(c){C.error("S3 upload failed, falling back to inline diffs:",c);let u=Buffer.byteLength(t||i||""),f=Buffer.byteLength(a||n||"");if(u>ze||f>ze){let h=`Diffs exceed maximum inline size of ${ze} bytes.`;throw C.error(h),new Error(h)}s.result_diff=t,s.result_diff_binary=i,(n||a)&&(s.cumulative_diff=n,s.cumulative_diff_binary=a,C.log("Updating agent runner with inline diffs (fallback)"),await b(be(),"update-runner",async()=>{await de(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 Yt(async()=>await b(be(),"update-runner-session",()=>B(e.id,e.sessionId,s)),{maxRetries:3,baseDelay:1e3,onRetry:(c,u)=>{C.error(`Error updating agent runner session (attempt ${c}):`,u),C.log("Retrying...")}}),C.log("Finished updating agent runner with result"),{sessionUpdate:s}};import{getTracer as Ht,shutdownTracers as cn,withActiveSpan as qt}from"@netlify/otel";var dn=un(import.meta.url),Kt=dn("../package.json"),Wt=E("pipeline_index"),Ce=3,Vt=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:i,tracing:a={}})=>{let l,{withStageTimer:s}=ft(J.timeUnits.hours(4)),m=await nt(Kt.version,e.id,a);try{await qt(Ht(),"run-pipeline",{},m,async()=>{let c,{aiGateway:u,context:f,persistSteps:h,runner:w,sha:I}=await s("init",()=>kt({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:i,runnerVersion:Kt.version}),J.timeUnits.minutes(10));l=w.clean,e.sha=I;let{runnerResult:g}=await s("inference",()=>Ae({cliPath:r,config:e,context:f,runner:w.runner,persistSteps:h,aiGateway:u}));await B(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let v=await s("deploy",()=>Xe({cliPath:r,config:e,context:f,result:g.result,filter:i})),x=g,N=[];if(v.hasChanges&&v.deployError){N.push(ot(v.deployError));let y=1;for(;y<=Ce&&!v.previewInfo;)Wt.log(`Deploy attempt had errors. Retrying. ${y}/${Ce}`),await qt(Ht(),"deploy-stage",async p=>{p?.setAttributes({"stage.attempt":y});let{runnerResult:d}=await s(`inference-retry-${y}`,()=>Ae({cliPath:r,config:e,context:f,runner:w.runner,persistSteps:h,aiGateway:u,buildErrors:N,priorAgentSessionId:g.agentSessionId}));x={...d,steps:[...x.steps||[],...d.steps||[]],duration:(x.duration||0)+(d.duration||0)},v=await s(`deploy-retry-${y}`,()=>Xe({cliPath:r,config:e,context:f,result:d.result,filter:i})),v.deployError&&N.push(v.deployError),y++});y>Ce&&!v.previewInfo&&(c=new Error(`Deploy validation failed after ${Ce} attempts`))}let{diff:T,resultDiff:_,previewInfo:R,diffBinary:S,resultDiffBinary:A}=v;if(await s("cleanup",()=>Bt({config:e,diff:T,result:x.result,duration:x.duration,resultDiff:_,diffBinary:S,resultDiffBinary:A,previewInfo:R}),J.timeUnits.minutes(10)),c)throw c;process.env.NETLIFY_LOCAL_MODE||(await l?.(),await St())})}catch(c){Wt.error("Got error while running pipeline",c),await l?.();let u=c instanceof Error&&c.message;throw await B(e.id,e.sessionId,{result:u||"Encountered error when running agent",state:"error"}),c}finally{await cn()}};import Jt from"crypto";var $=E("bin_local"),Y=pn(O.argv.slice(2),{string:["cwd","cli-path","filter","prompt","runner","model","netlify-api-token"],boolean:["verbose","help"],alias:{h:"help",v:"verbose"}}),Qe=()=>{console.log(`
|
|
136
135
|
agent-runner-cli-local - Run Netlify agent runner locally without API connections
|
|
137
136
|
|
|
138
137
|
USAGE:
|
|
@@ -164,6 +163,6 @@ NOTE:
|
|
|
164
163
|
This local mode mocks all Netlify API calls. The agent will run through
|
|
165
164
|
the full pipeline including inference and deployment, but API calls will
|
|
166
165
|
be logged instead of executed.
|
|
167
|
-
`)};Y.help&&(
|
|
168
|
-
To link this directory to a Netlify site, run:`)
|
|
166
|
+
`)};Y.help&&(Qe(),O.exit(0));Y.prompt||($.error("Error: --prompt is required"),Qe(),O.exit(1));Y["netlify-api-token"]||($.error("Error: --netlify-api-token is required - generate a PAT from your Netlify user settings"),Qe(),O.exit(1));try{let e=Y.cwd||O.cwd(),t=Xt.join(e,".netlify","netlify-agent-runner-context*");zt.rmSync(t,{recursive:!0,force:!0});let r;try{r=await fn(e)}catch(l){$.error(l.message),$.error(`
|
|
167
|
+
To link this directory to a Netlify site, run:`),$.error(" netlify link"),O.exit(1)}let o=`local-${Jt.randomBytes(8).toString("hex")}`,n=`session-${Jt.randomBytes(8).toString("hex")}`,i=Y.runner||"claude";$.log("Starting agent runner in local mode",{runnerId:o,sessionId:n,siteId:r,cwd:e,runner:i});let a={id:o,sessionId:n,prompt:Y.prompt,runner:i,model:Y.model,accountType:"local",validateAgent:!1,validateAgentWithBuild:!1,sessionHistoryContext:[],siteContext:[],hasRepo:!0,useGateway:!0,sha:void 0,modelVersionOverrides:{}};O.env.NETLIFY_LOCAL_MODE="true",O.env.NETLIFY_API_HOST="api.netlify.com",O.env.NETLIFY_API_TOKEN=Y["netlify-api-token"],O.env.SITE_ID=r,O.env.NETLIFY_TEAM_ID="local-team-id",O.env.NETLIFY_AGENT_RUNNER_USER_ID="local-user-id",O.env.SITE_NAME="local-site",i==="claude"?Ie(e,"claude")||($.log("Claude CLI not found, installing..."),await Ze(e,"@anthropic-ai/claude-code")):i==="gemini"?Ie(e,"gemini")||($.log("Gemini CLI not found, installing..."),await Ze(e,"@google/gemini-cli@0.1.17")):i==="codex"?Ie(e,"codex")||($.log("Codex CLI not found, installing..."),await Ze(e,"my-codex-no-sandbox")):($.error(`Unknown runner: ${i}`),O.exit(1)),await Vt({config:a,cwd:e,cliPath:Y["cli-path"],filter:Y.filter,tracing:{exporterUrl:void 0,traceparent:void 0}}),$.info("Finished agent (local mode)"),O.exit(0)}catch(e){$.error("Error running agent pipeline (local mode):",e),O.exit(1)}function Ze(e,t){return new Promise((r,o)=>{P("npm",["install",t,"--no-save"],{cwd:e}).then(({stdout:n})=>{$.log(`${t} installed: ${n}`),r()}).catch(n=>{$.error(`Error installing ${t}: ${n.stderr||n.message}`),o(n)})})}async function fn(e){let t=Xt.join(e,".netlify","state.json");try{let r=await zt.readFileSync(t,"utf-8"),o=JSON.parse(r);if(!o.siteId)throw new Error(`No siteId found in ${t}. Please link this directory to a Netlify site using 'netlify link'.`);return $.log(`Found site ID from state file: ${o.siteId}`),o.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}}
|
|
169
168
|
//# sourceMappingURL=bin-local.js.map
|