@netlify/agent-runner-cli 1.48.0 → 1.48.1
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 +6 -6
- package/dist/bin.js +3 -3
- package/dist/index.js +3 -3
- package/package.json +3 -3
package/dist/bin-local.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
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 Ce=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 Pe),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 Ce.log(`\u23F3 TRACE: ${t} starting...`),er(e,t,r)}var Pe=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,i]of Object.entries(o))l.includes("duration")&&typeof i=="number"?n.push(`${l}=${i.toFixed(2)}ms`):n.push(`${l}=${i}`);let s=t.status?.code===2?"\u274C":"\u2705",a=n.length>0?` [${n.join(", ")}]`:"";Ce.log(`${s} 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 nr=["error","failed","exception","fatal","panic","abort","crash"];function ot(e){let t=e.split(`
|
|
3
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 p=m;p<=c;p++)u.push(t[p]);r.push(u.join(`
|
|
4
4
|
`)),o=c,n=c+1}else n++}if(r.length===0)return e;let s=r.map((a,l)=>`<extracted_error_chunk order="${l+1}">
|
|
5
5
|
${a}
|
|
@@ -8,7 +8,7 @@ ${a}
|
|
|
8
8
|
`);return s.length>e.length*.8?e:s}import xe from"process";import{getTracer as Hr}from"@netlify/otel";import ue from"process";var me=ue.env.NETLIFY_API_URL,he=ue.env.NETLIFY_API_TOKEN,j=E("api"),ye=()=>ue.env.NETLIFY_LOCAL_MODE==="true",ce=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}`}};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),s=n.ok&&n.status<=299;if(ue.env.AGENT_RUNNERS_DEBUG==="true")j.log(`Response headers for ${r}:`),n.headers.forEach((l,i)=>{j.log(` ${i}: ${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(s||j.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},st=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)},it=()=>({apiUrl:me,token:he}),de=async(e,t)=>ye()?(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)=>ye()?(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)=>ye()?(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)=>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"}}):ce(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Oe=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=E("ai_gateway"),Fe=null;var ct=async()=>{if(Fe)return Fe;ee.log("Fetching available AI gateway providers");let e=await fetch(`${it().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,ee.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 ee.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return ee.log(`Model validation for ${e}/${t}`,{isAvailable:n}),n},dt=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),ee.log("Requesting AI gateway information");let i=await lt(a,t.id,t.sessionId);if({token:r,url:s}=i,o=i.expires_at?i.expires_at*1e3:void 0,ee.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(),ct()]),{get url(){return s},get token(){return r},isModelAvailableForProvider:or}};import q from"process";import Ee from"path";import $e from"fs";import{fileURLToPath as cr}from"url";import{execa as dr,execaCommand as Mn}from"execa";import{Transform as sr}from"stream";var ir=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||ir.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 te=class extends sr{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),s=H(n);o(null,s)}};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,s){let a=typeof o=="string"?H(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"?H(o):o;return typeof n=="function"?r(a,n):r(a,n,s)}}var pe=null,ft=e=>(pe&&pe.destroy(),pe=new V({totalAllowedTime:e}),pe),gt=()=>pe;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.`)}),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 pr=cr(import.meta.url),fr=Ee.dirname(pr),_e=E("shell"),De=new Set,gr={preferLocal:!0},C=(e,t,r)=>{let[o,n]=mr(t,r),s={...gr,...n},a=dr(e,o,s);return hr(a,s),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 te).pipe(q.stdout),e.stdout?.pipe(new te).pipe(q.stdout),e.stderr?.pipe(new te).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),_e.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return _e.error("Error killing process:",r),!1}},yr=e=>mt(e,"SIGKILL"),Er=e=>{De.add(e);let t=gt();if(t){let r=t.onTimesUp(()=>{_e.log(`Global timer expired, killing process ${e.pid}`),mt(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(_e.log(`Force killing process ${e.pid} after timeout`),yr(e))},5e3)});e.on("exit",()=>{De.delete(e),r()}),e.on("error",()=>{De.delete(e),r()})}};function we(e,t){return!!J(e,t)}function J(e,t){if(q.env.NODE_PATH){let n=Ee.join(q.env.NODE_PATH,".bin",t);if($e.existsSync(n))return n}let r=Ee.join(e,"node_modules",".bin",t);if($e.existsSync(r))return r;let o=Ee.join(fr,"..","node_modules",".bin",t);if($e.existsSync(o))return o}var ht="netlify-agent-runner-context.md",Le="task-history",ke="netlify-context",U=".netlify",re="results.md",Ue="assets";var _r=E("utils"),wr=e=>new Promise(t=>{setTimeout(t,e)}),yt=(e,t=3e3)=>{let r=!1,o=null,n=[],s=null,a=(...l)=>{if(r)return o=l,new Promise(c=>{n.push(c)});r=!0;let i,m=new Promise(c=>{i=c});return s=(async()=>{await Promise.resolve();let c=await e(...l);for(i(c);;){if(await wr(t),!o)return r=!1,s=null,c;let u=o,p=n;o=null,n=[],c=await e(...u),p.forEach(h=>{h(c)})}})(),m};return a.flush=async()=>{if((r||o)&&s)return await s,a.flush()},a},Ie=(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},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",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 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 Ge();let s=await je(o);await Me(s);let a={stdio:["ignore","pipe","pipe"]},i=(await C("git",["diff","--staged"],a)).stdout;if(r=!!i,!r)return{hasChanges:!1,ignored:s};let c=(await C("git",["diff","--staged","--binary"],a)).stdout,u,p;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await C("git",["commit","-m","Agent runner"]),u=(await C("git",["diff",e.sha,"HEAD"],a)).stdout;let g=(await C("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;u!==g&&(p=wt.from(g).toString("base64"))}let h={hasChanges:!0,diff:i,resultDiff:u,ignored:s};return i!==c&&(h.diffBinary=wt.from(c).toString("base64")),p&&(h.resultDiffBinary=p),h},Me=async(e=[])=>{await C("git",["add",".",...e])},Ge=async()=>(await C("git",["status","-s"])).stdout,xt=/.. (.+)?\.log$/,Tr=[xt],xr=async()=>{let e=await Ge();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
9
9
|
`).filter(o=>Tr.some(s=>s instanceof RegExp?s.test(o):o===s)?!1:o[1]?.trim()!=="")).length!==0,status:e}},vt=async()=>{let{stdout:e}=await C("git",["rev-parse","HEAD"]);return e.trim()},Rt=async()=>{let{stdout:e}=await C("git",["rev-list","--max-parents=0","HEAD"]);return e.trim()},je=async e=>{e||=await Ge();let t=[".netlify","node_modules"],r=[];return e.split(`
|
|
10
10
|
`).forEach(o=>{t.forEach(s=>{[`?? ${s}`,`?? ${s}${Ir.sep}`].some(l=>o.startsWith(l))&&r.push(`:!${s}`)});let n=o.match(xt)?.[1];n&&r.push(`:!${n}.log`)}),r},St=async()=>{await C("git",["reset","--hard","HEAD"])},vr=e=>{let t=e.split(`
|
|
11
|
-
`).reduce((r,o)=>{if(!o)return r;let[n,s,,...a]=o,l=a.join(""),i=n.trim(),m=s.trim();return r[l]?r[l].change=m:r[l]={filePath:l,stage:i,change:m},r},{});return Object.values(t)},Rr=async e=>{let t=[];for(let r of e)r.stage&&!r.change&&t.push(C("git",["restore","--staged","--worktree",r.filePath]));await Promise.allSettled(t)};import Ar from"fs/promises";import Nr from"os";import bt from"path";import X from"process";import br from"readline";import Ye from"path";import Sr from"fs/promises";var Be=E("agent-output-utils");async function ne({initialResult:e,agentName:t,hasError:r}){let o="",n=Ye.join(process.cwd(),U,re);try{let s=await Sr.readFile(n,"utf-8");s&&(o=s,Be.log(`Pulled result from ${Ye.relative(process.cwd(),n)}`))}catch{Be.log(`No results file found at ${Ye.relative(process.cwd(),n)}`)}return o||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function oe({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&&Be.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",Te="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 He({config:e,netlify:t,persistSteps:r,aiGateway:o,continueSession:n,priorAgentSessionId:s}){let a=e,{accountType:l,prompt:i,modelVersionOverrides:m}=a,{model:c}=a,u="";if(o){let{token:f,url:I}=o;if(!f||!I)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",Te)?(c=Te,M.log(`Using default model: ${Te}`)):M.log(`Default model ${Te} is not available, proceeding without model specification`);X.env.ANTHROPIC_API_KEY=f,X.env.ANTHROPIC_BASE_URL=I}else if(!X.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let p=[],h=[],x={},T=0,g=0,S,R,N=[J(X.cwd(),"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...c?["--model",c]:[],...n?["--continue"]:[],...n&&s?["--resume",s]:[],"-p",i],v=`${X.env.NVM_BIN}/node`;M.log(`Running ${v} ${N.join(" ")}`);let _=t.utils.run(v,N,{all:!0,env:X.env});_.stdin?.end();let A=Ie(()=>{r?.({steps:p,duration:g})},250),w=(f,I)=>{let d={...f,id:T};T+=1,h.push(d),p.push(d),I||A.flush(),A(),I&&A.flush()},y=br.createInterface({input:_.all});return y.on("error",f=>{M.error("Readline interface error",{error:f.message,stack:f.stack})}),y.on("line",f=>{let I=null;try{I=JSON.parse(f)}catch{M.log("Could not parse line",f)}I?.session_id&&I.session_id!==u&&(u=I.session_id),Array.isArray(I?.message?.content)?I.message.content.forEach(d=>{switch(d.type){case"text":{d.text&&w({message:d.text});break}case"image":{typeof d.source=="object"&&d.source&&d.source.type==="base64"&&d.source.media_type?w({message:``}):M.log(`Unsupported image type ${d.source?.type}`,d.source);break}case"tool_use":{if(d.name==="Task"){let
|
|
11
|
+
`).reduce((r,o)=>{if(!o)return r;let[n,s,,...a]=o,l=a.join(""),i=n.trim(),m=s.trim();return r[l]?r[l].change=m:r[l]={filePath:l,stage:i,change:m},r},{});return Object.values(t)},Rr=async e=>{let t=[];for(let r of e)r.stage&&!r.change&&t.push(C("git",["restore","--staged","--worktree",r.filePath]));await Promise.allSettled(t)};import Ar from"fs/promises";import Nr from"os";import bt from"path";import X from"process";import br from"readline";import Ye from"path";import Sr from"fs/promises";var Be=E("agent-output-utils");async function ne({initialResult:e,agentName:t,hasError:r}){let o="",n=Ye.join(process.cwd(),U,re);try{let s=await Sr.readFile(n,"utf-8");s&&(o=s,Be.log(`Pulled result from ${Ye.relative(process.cwd(),n)}`))}catch{Be.log(`No results file found at ${Ye.relative(process.cwd(),n)}`)}return o||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function oe({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&&Be.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",Te="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 He({config:e,netlify:t,persistSteps:r,aiGateway:o,continueSession:n,priorAgentSessionId:s}){let a=e,{accountType:l,prompt:i,modelVersionOverrides:m}=a,{model:c}=a,u="";if(o){let{token:f,url:I}=o;if(!f||!I)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",Te)?(c=Te,M.log(`Using default model: ${Te}`)):M.log(`Default model ${Te} is not available, proceeding without model specification`);X.env.ANTHROPIC_API_KEY=f,X.env.ANTHROPIC_BASE_URL=I}else if(!X.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let p=[],h=[],x={},T=0,g=0,S,R,N=[J(X.cwd(),"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...c?["--model",c]:[],...n?["--continue"]:[],...n&&s?["--resume",s]:[],"-p",i],v=`${X.env.NVM_BIN}/node`;M.log(`Running ${v} ${N.join(" ")}`);let _=t.utils.run(v,N,{all:!0,env:X.env});_.stdin?.end();let A=Ie(()=>{r?.({steps:p,duration:g})},250),w=(f,I)=>{let d={...f,id:T};T+=1,h.push(d),p.push(d),I||A.flush(),A(),I&&A.flush()},y=br.createInterface({input:_.all});return y.on("error",f=>{M.error("Readline interface error",{error:f.message,stack:f.stack})}),y.on("line",f=>{let I=null;try{I=JSON.parse(f)}catch{M.log("Could not parse line",f)}I?.session_id&&I.session_id!==u&&(u=I.session_id),Array.isArray(I?.message?.content)?I.message.content.forEach(d=>{switch(d.type){case"text":{d.text&&w({message:d.text});break}case"image":{typeof d.source=="object"&&d.source&&d.source.type==="base64"&&d.source.media_type?w({message:``}):M.log(`Unsupported image type ${d.source?.type}`,d.source);break}case"tool_use":{if(d.name==="Task"){let F=d.input?.description&&`\`${d.input.description}\``;w({title:[Nt(d.name),F].filter(Boolean).join(" ")})}else d.id&&(x[d.id]=d);A.flush();break}case"tool_result":{let F=d.tool_use_id?x[d.tool_use_id]:void 0,le;if(F){let Q=F.input?.file_path&&bt.relative(X.cwd(),F.input.file_path),$=Q&&`\`${Q}\``;le=[Nt(F.name||""),$].filter(Boolean).join(" ")}let Qe=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(F?.name||""),K;if(typeof d.content=="string")K=d.content;else if(Array.isArray(d.content)){let Q=[];d.content.forEach($=>{$?.type==="text"&&typeof $.text=="string"?Q.push($.text):$?.type==="image"&&typeof $.source=="object"&&$.source?$.source.type==="base64"&&$.source.media_type?Q.push(``):M.log(`Unsupported image type ${$.source.type}`,$.source):M.log(`Unsupported block type ${$?.type}`)}),K=Q.join(`
|
|
12
12
|
|
|
13
13
|
`)}Qe&&K&&(K=`\`\`\`
|
|
14
14
|
${K.trim()}
|
|
@@ -16,7 +16,7 @@ ${K.trim()}
|
|
|
16
16
|
`):_?.type==="message"&&_.role==="system"&&(T=_.content.map(y=>y.text).join(`
|
|
17
17
|
`));w&&(r?.({steps:m,duration:h}),o?.({steps:A,duration:h}))}),await R.catch(v=>{let _=Dr({catchError:v,runCmd:R,error:T,result:x,runnerName:"Codex"});T=_.error,x=_.result}),N.close(),{steps:c,duration:h,result:await ne({initialResult:x,agentName:Pt,hasError:!!T}),error:oe({error:T,agentName:Pt}),isRetryableError:se(T)}}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(s=>!Lr.has(s)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
|
|
18
18
|
${n.trim()}
|
|
19
|
-
\`\`\``)}catch(s){z.error("Could not decode outputMsg",s,t.output)}return{title:o,message:n}};import Ur from"fs/promises";import Mr from"os";import $t from"path";import Z from"process";import Gr from"readline";var ae=E("runner_gemini"),Ft="Gemini CLI",jr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(ae.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?(ae.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}):(ae.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 Ke({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:a,modelVersionOverrides:l}=e,{model:i}=e;if(n){let{token:w,url:y}=n;if(!w||!y)throw new Error("No token or url provided from AI Gateway");if(l?.gemini){let f=l?.gemini?.[s];if(f){if(!await n.isModelAvailableForProvider("gemini",f))throw new Error(`Model override '${f}' is not available for gemini provider`);i=f}}else if(i&&!await n.isModelAvailableForProvider("gemini",i))throw new Error(`Model '${i}' is not available for gemini provider`);Z.env.GEMINI_API_KEY=w,Z.env.GOOGLE_GEMINI_BASE_URL=y}else if(!Z.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let m=[],c=[],u=[],p={},h=0,x=0,T,g,S=[J(Z.cwd(),"gemini"),...i?["--model",i]:[],"--yolo","-p",a],R=`${Z.env.NVM_BIN}/node`;ae.log(`Running ${R} ${S.join(" ")}`);let N=t.utils.run(R,S,{all:!0,env:Z.env});N.stdin?.end();let v=Ie(()=>{r?.({steps:m,duration:x}),o?.({steps:c,duration:x}),c=[]},250),_=(w,y)=>{w.id=h,h+=1,u.push(w),m.push(w),c.push(w),y||v.flush(),v(),y&&v.flush()},A=Gr.createInterface({input:N.all});return A.on("error",w=>{ae.error("Readline interface error",{error:w.message,stack:w.stack})}),A.on("line",w=>{let y=null;try{if(w.startsWith("[API Error")){let f=w.match(/\[api error: (.+?)]$/i)?.[1];y={type:"error",value:Et(f,!1)?.error?.message||f||"Gemini encountered error"}}else y=JSON.parse(w)}catch{return}if(y)switch(y.type){case"thought":{let f=y.value;_({title:f?.subject??"Thinking...",message:f?.description},!0);break}case"content":{y.value&&_({message:y.value});break}case"tool_call_request":{let f=y.value,I=Yr[f.name]??f.name,d=f.args?.path||f.args?.absolute_path,
|
|
19
|
+
\`\`\``)}catch(s){z.error("Could not decode outputMsg",s,t.output)}return{title:o,message:n}};import Ur from"fs/promises";import Mr from"os";import $t from"path";import Z from"process";import Gr from"readline";var ae=E("runner_gemini"),Ft="Gemini CLI",jr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(ae.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?(ae.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}):(ae.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 Ke({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:a,modelVersionOverrides:l}=e,{model:i}=e;if(n){let{token:w,url:y}=n;if(!w||!y)throw new Error("No token or url provided from AI Gateway");if(l?.gemini){let f=l?.gemini?.[s];if(f){if(!await n.isModelAvailableForProvider("gemini",f))throw new Error(`Model override '${f}' is not available for gemini provider`);i=f}}else if(i&&!await n.isModelAvailableForProvider("gemini",i))throw new Error(`Model '${i}' is not available for gemini provider`);Z.env.GEMINI_API_KEY=w,Z.env.GOOGLE_GEMINI_BASE_URL=y}else if(!Z.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let m=[],c=[],u=[],p={},h=0,x=0,T,g,S=[J(Z.cwd(),"gemini"),...i?["--model",i]:[],"--yolo","-p",a],R=`${Z.env.NVM_BIN}/node`;ae.log(`Running ${R} ${S.join(" ")}`);let N=t.utils.run(R,S,{all:!0,env:Z.env});N.stdin?.end();let v=Ie(()=>{r?.({steps:m,duration:x}),o?.({steps:c,duration:x}),c=[]},250),_=(w,y)=>{w.id=h,h+=1,u.push(w),m.push(w),c.push(w),y||v.flush(),v(),y&&v.flush()},A=Gr.createInterface({input:N.all});return A.on("error",w=>{ae.error("Readline interface error",{error:w.message,stack:w.stack})}),A.on("line",w=>{let y=null;try{if(w.startsWith("[API Error")){let f=w.match(/\[api error: (.+?)]$/i)?.[1];y={type:"error",value:Et(f,!1)?.error?.message||f||"Gemini encountered error"}}else y=JSON.parse(w)}catch{return}if(y)switch(y.type){case"thought":{let f=y.value;_({title:f?.subject??"Thinking...",message:f?.description},!0);break}case"content":{y.value&&_({message:y.value});break}case"tool_call_request":{let f=y.value,I=Yr[f.name]??f.name,d=f.args?.path||f.args?.absolute_path,F=d&&$t.relative(Z.cwd(),d),le=f.args?.command,K={title:[I,F&&`\`${F}\``,le&&`\`${le}\``].filter(Boolean).join(" ")};p[f.callId]=K,v.flush();break}case"tool_result":{let f=y.value,I=p[f.callId];if(I){let d=[f.resultDisplay,f.responseParts?.functionResponse?.response?.output].find(F=>typeof F=="string"&&F);d&&(I.message=`\`\`\`
|
|
20
20
|
${d.trim()}
|
|
21
21
|
\`\`\``),_(I,!0)}break}case"result":{x=y.duration_ms,T=y.value,[u,m,c].forEach(f=>{f[f.length-1]?.message===T&&f.pop()});break}case"error":{g=y.value;break}case"finished":break;default:{ae.warn("Unhandled message type:",y.type);break}}}),await N.catch(w=>{({error:g,result:T}=jr({catchError:w,runCmd:N,error:g,result:T,runnerName:"Gemini"}))}),A.close(),v.flush(),{steps:u,duration:x,result:await ne({initialResult:T,agentName:Ft,hasError:!!g}),error:oe({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:qe,clean:Ot},claude:{runner:He,clean:Ct},gemini:{runner:Ke,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 s=performance.now();n?.setAttributes({"init.runner":e.runner,"init.id":e.id,"init.sessionId":e.sessionId,"init.hasRepo":e.hasRepo,"init.useGateway":e.useGateway,"init.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});st(l);let i=e.useGateway?await dt({netlify:l,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!i}),e.validateAgent&&e.errorLogsPath&&n?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let m=yt(({steps:h=[],duration:x})=>{let T=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:T,duration:x})},t);qr.info("Adding build files to stage");let c=await je();await Me(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 p=performance.now()-s;return n?.setAttributes({"init.sha":u||"unknown","init.duration.ms":p,"init.status":"success"}),{aiGateway:i,context:l,persistSteps:m,runner:a,sha:u}}),Kr=({apiToken:e})=>({constants:{NETLIFY_API_HOST:xe.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||xe.env.NETLIFY_API_TOKEN,SITE_ID:xe.env.SITE_ID,FUNCTIONS_DIST:xe.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:C}});import{getTracer as We}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),s=0;for(;await zr(n);){if(s>=Jr)throw new Error("Failed to generate context file");o=`${t}-${Wr.randomUUID().slice(0,5)}${r}`,n=k.join(G.cwd(),U,o),s+=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}},ve=null,en=async()=>{if(ve)return ve;let e=await Zr();if(!e)return[];let t=k.join(G.cwd(),U,ke);await W.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([n,s])=>{if(!s||typeof s!="object"||!s.endpoint||!s.scope)return L.warn(`Invalid scope data for ${n}, skipping...`),null;let a=`${n}.md`,l=k.join(t,a),i=k.join(U,ke,a);return L.log(`Downloading ${s.scope} context...`),await Qr(s.endpoint,l)?(L.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:n}):null});return ve=(await Promise.all(r)).filter(n=>n!==null),ve},Ut=async({cliPath:e,netlify:t,config:r,buildErrorContext:o})=>{let n=Vr(t),s=await Xr(ht),a=k.join(G.cwd(),U);await W.mkdir(a,{recursive:!0});let l=k.join(U,s),i=k.join(G.cwd(),l),m=k.join(G.cwd(),U,re);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.
|
|
22
22
|
Your task is to analyze and fix the build errors.
|
|
@@ -131,7 +131,7 @@ ${e.pop()}
|
|
|
131
131
|
`;import sn from"process";import{getTracer as Ve}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:s,filter:a},l)=>{try{let i=["deploy","--message",`"${o}"`,"--json","--draft","--verbose"];t||(fe.log("Deploy: Uploading source zip"),i.push("--upload-source-zip")),n&&i.push("--alias",n),a&&i.push("--filter",a),r?(fe.log("Deploy: Skipping build"),i.push("--no-build")):i.push("--context","deploy-preview");let m=s||"netlify";fe.log(`Running: ${m} ${i.join(" ")}`),l?.setAttributes({cmd:m,args:i});let c=await e.utils.run(m,i,{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
132
|
Preview deploy created successfully:`,{deployId:u.deploy_id,deployUrl:u.deploy_url,siteId:u.site_id});let p={deployId:u.deploy_id,previewUrl:u.deploy_url,logsUrl:u.logs,siteId:u.site_id};return t||(p.sourceZipFilename=u.source_zip_filename),p}catch(i){throw fe.error("Failed to create preview deploy via CLI:",i),l?.setAttributes({success:!1,error:i.message}),i}};var ge=E("deploy_stage"),Je=async e=>await b(Ve(),"run-deploy-stage",async()=>an(e)),an=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let s=await b(Ve(),"get-runner-diffs",async()=>await Tt({config:t,netlify:r}));if(ge.info("Resolved git",{hasChanges:s.hasChanges,ignored:s.ignored??[]}),!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:l,diffBinary:i,resultDiffBinary:m}=s,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 p;try{let h=await b(Ve(),"get-runner-session",async()=>await at(t.id,t.sessionId));h?.title&&(p=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:p,skipBuild:!1,deploySubdomain:_t(t.id,sn.env.SITE_NAME),filter:n})}catch(p){return ge.warn("Failed to create preview deploy (continuing with agent run):",p),{diff:a,resultDiff:l,hasChanges:c,previewInfo:null,diffBinary:i,resultDiffBinary:m,deployError:p instanceof Error?p.message:String(p)}}return ge.log("Git status",{hasDiff:!!a,hasChanges:c}),{diff:a,resultDiff:l,hasChanges:c,previewInfo:u,diffBinary:i,resultDiffBinary:m}};import{getTracer as Ne}from"@netlify/otel";async function Yt(e,t){let{maxRetries:r,baseDelay:o,onRetry:n}=t,s;for(let a=1;a<=r;a++)try{return await e()}catch(l){if(s=l,a===r)throw s;n&&n(a,s),await new Promise(i=>setTimeout(i,o*a))}throw s}var Ae=class{scanDiffForForms(t){let r=[],o=null,n=[],s=t.split(`
|
|
133
133
|
`);for(let a of s)if(a.startsWith("diff --git")){if(o&&n.length>0){let i=this.containsNetlifyForm(n,o);i&&r.push(i)}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:s,name:a}of n){let l=o.match(s);if(l){let i=l.index||0,m=Math.max(0,i-20),c=Math.min(o.length,i+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
|
|
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:s,name:a}of n){let l=o.match(s);if(l){let i=l.index||0,m=Math.max(0,i-20),c=Math.min(o.length,i+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 P=E("cleanup_stage"),Bt=async e=>await b(Ne(),"cleanup-stage",async()=>ln(e)),Xe=1024*1024*10,ln=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:s,resultDiffBinary:a,previewInfo:l})=>{let i={result:r||"Done",duration:o};l&&l.deployId&&(i.deploy_id=l.deployId),l&&l.sourceZipFilename&&(i.result_zip_file_name=l.sourceZipFilename);let m=t||s||n||a;if(m){let c=new Ae,u=t||s||"",p=c.scanDiffForForms(u);p.detected&&(P.log("Detected Netlify form(s) in diff:"),p.matches.forEach(({file:h,snippet:x})=>{P.log(` - ${h}: ${x}`)}),i.has_netlify_form=!0),P.log("Did not detect Netlify form(s) in diff")}if(m)try{P.log("Getting pre-signed URLs for diff upload");let c=await ut(e.id,e.sessionId),u=[];(t||s)&&u.push(Oe(c.result.upload_url,s||t).then(()=>{i.result_diff_s3_key=c.result.s3_key,P.log("Successfully uploaded result_diff to S3")})),(n||a)&&u.push(Oe(c.cumulative.upload_url,a||n).then(()=>{i.cumulative_diff_s3_key=c.cumulative.s3_key,P.log("Successfully uploaded cumulative_diff to S3")})),P.log(`Uploading ${u.length} diff(s) to S3 in parallel`),await Promise.all(u),(n||a)&&(P.log("Updating agent runner with cumulative diff S3 key"),await b(Ne(),"update-runner",async()=>{await de(e.id,{result_diff_s3_key:c.cumulative.s3_key})}))}catch(c){P.error("S3 upload failed, falling back to inline diffs:",c);let u=Buffer.byteLength(t||s||""),p=Buffer.byteLength(a||n||"");if(u>Xe||p>Xe){let h=`Diffs exceed maximum inline size of ${Xe} bytes.`;throw P.error(h),new Error(h)}i.result_diff=t,i.result_diff_binary=s,(n||a)&&(i.cumulative_diff=n,i.cumulative_diff_binary=a,P.log("Updating agent runner with inline diffs (fallback)"),await b(Ne(),"update-runner",async()=>{await de(e.id,{result_diff:n,result_diff_binary:a})}))}else P.log("No diffs to upload");return P.log("Updated agent runner with result"),await Yt(async()=>await b(Ne(),"update-runner-session",()=>B(e.id,e.sessionId,i)),{maxRetries:3,baseDelay:1e3,onRetry:(c,u)=>{P.error(`Error updating agent runner session (attempt ${c}):`,u),P.log("Retrying...")}}),P.log("Finished updating agent runner with result"),{sessionUpdate:i}};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"),be=3,Vt=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:s,tracing:a={}})=>{let l,{withStageTimer:i}=ft(V.timeUnits.hours(4)),m=await nt(Kt.version,e.id,a);try{await qt(Ht(),"run-pipeline",{},m,async()=>{let c,{aiGateway:u,context:p,persistSteps:h,runner:x,sha:T}=await i("init",()=>kt({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:s,runnerVersion:Kt.version}),V.timeUnits.minutes(10));l=x.clean,e.sha=T;let{runnerResult:g}=await i("inference",()=>Se({cliPath:r,config:e,context:p,runner:x.runner,persistSteps:h,aiGateway:u}));await B(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let S=await i("deploy",()=>Je({cliPath:r,config:e,context:p,result:g.result,filter:s})),R=g,N=[];if(S.hasChanges&&S.deployError){N.push(ot(S.deployError));let f=1;for(;f<=be&&!S.previewInfo;)Wt.log(`Deploy attempt had errors. Retrying. ${f}/${be}`),await qt(Ht(),"deploy-stage",async I=>{I?.setAttributes({"stage.attempt":f});let{runnerResult:d}=await i(`inference-retry-${f}`,()=>Se({cliPath:r,config:e,context:p,runner:x.runner,persistSteps:h,aiGateway:u,buildErrors:N,priorAgentSessionId:g.agentSessionId}));R={...d,steps:[...R.steps||[],...d.steps||[]],duration:(R.duration||0)+(d.duration||0)},S=await i(`deploy-retry-${f}`,()=>Je({cliPath:r,config:e,context:p,result:d.result,filter:s})),S.deployError&&N.push(S.deployError),f++});f>be&&!S.previewInfo&&(c=new Error(`Deploy validation failed after ${be} attempts`))}let{diff:v,resultDiff:_,previewInfo:A,diffBinary:w,resultDiffBinary:y}=S;if(await i("cleanup",()=>Bt({config:e,diff:v,result:R.result,duration:R.duration,resultDiff:_,diffBinary:w,resultDiffBinary:y,previewInfo:A}),V.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 D=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"}}),Ze=()=>{console.log(`
|
|
135
135
|
agent-runner-cli-local - Run Netlify agent runner locally without API connections
|
|
136
136
|
|
|
137
137
|
USAGE:
|
|
@@ -163,6 +163,6 @@ NOTE:
|
|
|
163
163
|
This local mode mocks all Netlify API calls. The agent will run through
|
|
164
164
|
the full pipeline including inference and deployment, but API calls will
|
|
165
165
|
be logged instead of executed.
|
|
166
|
-
`)};Y.help&&(Ze(),
|
|
167
|
-
To link this directory to a Netlify site, run:`),D.error(" netlify link"),
|
|
166
|
+
`)};Y.help&&(Ze(),O.exit(0));Y.prompt||(D.error("Error: --prompt is required"),Ze(),O.exit(1));Y["netlify-api-token"]||(D.error("Error: --netlify-api-token is required - generate a PAT from your Netlify user settings"),Ze(),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){D.error(l.message),D.error(`
|
|
167
|
+
To link this directory to a Netlify site, run:`),D.error(" netlify link"),O.exit(1)}let o=`local-${Jt.randomBytes(8).toString("hex")}`,n=`session-${Jt.randomBytes(8).toString("hex")}`,s=Y.runner||"claude";D.log("Starting agent runner in local mode",{runnerId:o,sessionId:n,siteId:r,cwd:e,runner:s});let a={id:o,sessionId:n,prompt:Y.prompt,runner:s,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",s==="claude"?we(e,"claude")||(D.log("Claude CLI not found, installing..."),await ze(e,"@anthropic-ai/claude-code")):s==="gemini"?we(e,"gemini")||(D.log("Gemini CLI not found, installing..."),await ze(e,"@google/gemini-cli@0.1.17")):s==="codex"?we(e,"codex")||(D.log("Codex CLI not found, installing..."),await ze(e,"my-codex-no-sandbox")):(D.error(`Unknown runner: ${s}`),O.exit(1)),await Vt({config:a,cwd:e,cliPath:Y["cli-path"],filter:Y.filter,tracing:{exporterUrl:void 0,traceparent:void 0}}),D.info("Finished agent (local mode)"),O.exit(0)}catch(e){D.error("Error running agent pipeline (local mode):",e),O.exit(1)}function ze(e,t){return new Promise((r,o)=>{C("npm",["install",t,"--no-save"],{cwd:e}).then(({stdout:n})=>{D.log(`${t} installed: ${n}`),r()}).catch(n=>{D.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 D.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}}
|
|
168
168
|
//# sourceMappingURL=bin-local.js.map
|
package/dist/bin.js
CHANGED
|
@@ -8,7 +8,7 @@ ${a}
|
|
|
8
8
|
`);return s.length>e.length*.8?e:s}import Ie from"process";import{getTracer as Vr}from"@netlify/otel";import le from"process";var ge=le.env.NETLIFY_API_URL,me=le.env.NETLIFY_API_TOKEN,G=E("api"),he=()=>le.env.NETLIFY_LOCAL_MODE==="true",ue=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}`}};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),s=n.ok&&n.status<=299;if(le.env.AGENT_RUNNERS_DEBUG==="true")G.log(`Response headers for ${r}:`),n.headers.forEach((l,i)=>{G.log(` ${i}: ${l}`)});else{let l=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");G.log(`Request ID for ${r}: ${l||"N/A"}`)}if(s||G.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},at=e=>{G.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)},lt=()=>({apiUrl:ge,token:me}),ce=async(e,t)=>he()?(G.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):ue(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),j=async(e,t,r)=>he()?(G.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 ut=async(e,t)=>he()?(G.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):ue(`/api/v1/agent_runners/${e}/sessions/${t}`),ct=(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}}),pt=async(e,t)=>he()?(G.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"}),Pe=async(e,t)=>{G.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=E("ai_gateway"),Oe=null;var dt=async()=>{if(Oe)return Oe;Z.log("Fetching available AI gateway providers");let e=await fetch(`${lt().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 Oe=t,Z.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},lr=async(e,t)=>{let o=(await dt()).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},ft=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 ct(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 f=o-Date.now()-6e4;f>0&&(n=setTimeout(()=>{l()},f))}};return await Promise.all([l(),dt()]),{get url(){return s},get token(){return r},isModelAvailableForProvider:lr}};import B from"process";import Ee from"path";import Fe from"fs";import{fileURLToPath as gr}from"url";import{execa as mr,execaCommand as Kn}from"execa";import{Transform as ur}from"stream";var cr=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"]),pr=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function dr(){return Object.entries(process.env).filter(([e,t])=>!(!t||cr.has(e)||pr.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function Y(e){if(typeof e!="string")return e;let t=dr();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(fr(o),"g");r=r.replace(n,"******")}),r}function fr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Q=class extends ur{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),s=Y(n);o(null,s)}};function gt(){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 pe=null,mt=e=>(pe&&pe.destroy(),pe=new q({totalAllowedTime:e}),pe),ht=()=>pe;var q=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 hr=gr(import.meta.url),Er=Ee.dirname(hr),ye=E("shell"),Le=new Set,yr={preferLocal:!0},F=(e,t,r)=>{let[o,n]=_r(t,r),s={...yr,...n},a=mr(e,o,s);return Tr(a,s),Ir(a),a};var _r=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Tr=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(B.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new Q).pipe(B.stdout),e.stdout?.pipe(new Q).pipe(B.stdout),e.stderr?.pipe(new Q).pipe(B.stderr);return}e.stdout?.pipe(B.stdout),e.stderr?.pipe(B.stderr)},Et=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(B.kill(-e.pid,t),ye.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return ye.error("Error killing process:",r),!1}},wr=e=>Et(e,"SIGKILL"),Ir=e=>{Le.add(e);let t=ht();if(t){let r=t.onTimesUp(()=>{ye.log(`Global timer expired, killing process ${e.pid}`),Et(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(ye.log(`Force killing process ${e.pid} after timeout`),wr(e))},5e3)});e.on("exit",()=>{Le.delete(e),r()}),e.on("error",()=>{Le.delete(e),r()})}};function ee(e,t){if(B.env.NODE_PATH){let n=Ee.join(B.env.NODE_PATH,".bin",t);if(Fe.existsSync(n))return n}let r=Ee.join(e,"node_modules",".bin",t);if(Fe.existsSync(r))return r;let o=Ee.join(Er,"..","node_modules",".bin",t);if(Fe.existsSync(o))return o}var yt="netlify-agent-runner-context.md",De="task-history",$e="netlify-context",k=".netlify",te="results.md",ke="assets",Ue="other",Me="personal";var Ge="enterprise",je="free",_t=[Me,"pro",Ge,je];var Tt=E("utils"),Rr=e=>new Promise(t=>{setTimeout(t,e)}),wt=(e,t=3e3)=>{let r=!1,o=null,n=[],s=null,a=(...l)=>{if(r)return o=l,new Promise(c=>{n.push(c)});r=!0;let i,f=new Promise(c=>{i=c});return s=(async()=>{await Promise.resolve();let c=await e(...l);for(i(c);;){if(await Rr(t),!o)return r=!1,s=null,c;let u=o,d=n;o=null,n=[],c=await e(...u),d.forEach(h=>{h(c)})}})(),f};return a.flush=async()=>{if((r||o)&&s)return await s,a.flush()},a},_e=(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},Te=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):Tt.error("Could not parse JSON",o))}},It=(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 f=Math.min(i-s.length,e.length);return`${s}${e.slice(0,f)}`}return e.slice(0,i)},Nr=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!_t.some(t=>t in e),Rt=()=>{let e={},t={codex:process.env.NETLIFY_FF_AGENT_RUNNER_CODEX_VERSION,claude:process.env.NETLIFY_FF_AGENT_RUNNER_CLAUDE_VERSION,gemini:process.env.NETLIFY_FF_AGENT_RUNNER_GEMINI_VERSION};return Object.entries(t).forEach(([r,o])=>{if(o){let n=`NETLIFY_FF_AGENT_RUNNER_${r.toUpperCase()}_VERSION`;try{let s=JSON.parse(o);Nr(s)&&(e[r]=s)}catch(s){let l=s instanceof SyntaxError?"Invalid JSON":s.message;Tt.error(`Could not parse ${r} model version override from ${n}: ${l}`)}}}),e};import{Buffer as Nt}from"buffer";import xr from"path";var xt=E("repo"),vt=async({config:e})=>{xt.info("Getting runner diffs");let t=await Ar(),{hasChanges:r}=t,{status:o}=t;if(!r)return{hasChanges:!1};let n=Sr(o);await Cr(n),xt.info("Changes after processing"),await Be();let s=await He(o);await Ye(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 c=(await F("git",["diff","--staged","--binary"],a)).stdout,u,d;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await F("git",["commit","-m","Agent runner"]),u=(await F("git",["diff",e.sha,"HEAD"],a)).stdout;let g=(await F("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;u!==g&&(d=Nt.from(g).toString("base64"))}let h={hasChanges:!0,diff:i,resultDiff:u,ignored:s};return i!==c&&(h.diffBinary=Nt.from(c).toString("base64")),d&&(h.resultDiffBinary=d),h},Ye=async(e=[])=>{await F("git",["add",".",...e])},Be=async()=>(await F("git",["status","-s"])).stdout,At=/.. (.+)?\.log$/,vr=[At],Ar=async()=>{let e=await Be();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
9
9
|
`).filter(o=>vr.some(s=>s instanceof RegExp?s.test(o):o===s)?!1:o[1]?.trim()!=="")).length!==0,status:e}},St=async()=>{let{stdout:e}=await F("git",["rev-parse","HEAD"]);return e.trim()},Ct=async()=>{let{stdout:e}=await F("git",["rev-list","--max-parents=0","HEAD"]);return e.trim()},He=async e=>{e||=await Be();let t=[".netlify","node_modules"],r=[];return e.split(`
|
|
10
10
|
`).forEach(o=>{t.forEach(s=>{[`?? ${s}`,`?? ${s}${xr.sep}`].some(l=>o.startsWith(l))&&r.push(`:!${s}`)});let n=o.match(At)?.[1];n&&r.push(`:!${n}.log`)}),r},bt=async()=>{await F("git",["reset","--hard","HEAD"])},Sr=e=>{let t=e.split(`
|
|
11
|
-
`).reduce((r,o)=>{if(!o)return r;let[n,s,,...a]=o,l=a.join(""),i=n.trim(),f=s.trim();return r[l]?r[l].change=f:r[l]={filePath:l,stage:i,change:f},r},{});return Object.values(t)},Cr=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 Pr from"fs/promises";import Or from"os";import Ft from"path";import K from"process";import Fr from"readline";import We from"path";import br from"fs/promises";var qe=E("agent-output-utils");async function re({initialResult:e,agentName:t,hasError:r}){let o="",n=We.join(process.cwd(),k,te);try{let s=await br.readFile(n,"utf-8");s&&(o=s,qe.log(`Pulled result from ${We.relative(process.cwd(),n)}`))}catch{qe.log(`No results file found at ${We.relative(process.cwd(),n)}`)}return o||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function ne({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&&qe.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 U=E("runner_claude"),Pt="Claude Code",we="claude-sonnet-4-5-20250929",Ot=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,Lr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(U.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?(U.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}):(U.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,aiGateway:o,continueSession:n,priorAgentSessionId:s}){let a=e,{accountType:l,prompt:i,modelVersionOverrides:f}=a,{model:c}=a,u="";if(o){let{token:m,url:I}=o;if(!m||!I)throw new Error("No token or url provided from AI Gateway");if(f?.claude){let p=f?.claude?.[l];if(p){if(!await o.isModelAvailableForProvider("anthropic",p))throw new Error(`Model override '${p}' is not available for anthropic provider`);c=p}}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",we)?(c=we,U.log(`Using default model: ${we}`)):U.log(`Default model ${we} is not available, proceeding without model specification`);K.env.ANTHROPIC_API_KEY=m,K.env.ANTHROPIC_BASE_URL=I}else if(!K.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let d=[],h=[],R={},w=0,g=0,N,v,S=[ee(K.cwd(),"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...c?["--model",c]:[],...n?["--continue"]:[],...n&&s?["--resume",s]:[],"-p",i],x=`${K.env.NVM_BIN}/node`;U.log(`Running ${x} ${S.join(" ")}`);let _=t.utils.run(x,S,{all:!0,env:K.env});_.stdin?.end();let A=_e(()=>{r?.({steps:d,duration:g})},250),T=(m,I)=>{let p={...m,id:w};w+=1,h.push(p),d.push(p),I||A.flush(),A(),I&&A.flush()},y=Fr.createInterface({input:_.all});return y.on("error",m=>{U.error("Readline interface error",{error:m.message,stack:m.stack})}),y.on("line",m=>{let I=null;try{I=JSON.parse(m)}catch{U.log("Could not parse line",m)}I?.session_id&&I.session_id!==u&&(u=I.session_id),Array.isArray(I?.message?.content)?I.message.content.forEach(p=>{switch(p.type){case"text":{p.text&&T({message:p.text});break}case"image":{typeof p.source=="object"&&p.source&&p.source.type==="base64"&&p.source.media_type?T({message:``}):U.log(`Unsupported image type ${p.source?.type}`,p.source);break}case"tool_use":{if(p.name==="Task"){let
|
|
11
|
+
`).reduce((r,o)=>{if(!o)return r;let[n,s,,...a]=o,l=a.join(""),i=n.trim(),f=s.trim();return r[l]?r[l].change=f:r[l]={filePath:l,stage:i,change:f},r},{});return Object.values(t)},Cr=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 Pr from"fs/promises";import Or from"os";import Ft from"path";import K from"process";import Fr from"readline";import We from"path";import br from"fs/promises";var qe=E("agent-output-utils");async function re({initialResult:e,agentName:t,hasError:r}){let o="",n=We.join(process.cwd(),k,te);try{let s=await br.readFile(n,"utf-8");s&&(o=s,qe.log(`Pulled result from ${We.relative(process.cwd(),n)}`))}catch{qe.log(`No results file found at ${We.relative(process.cwd(),n)}`)}return o||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function ne({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&&qe.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 U=E("runner_claude"),Pt="Claude Code",we="claude-sonnet-4-5-20250929",Ot=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,Lr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(U.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?(U.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}):(U.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,aiGateway:o,continueSession:n,priorAgentSessionId:s}){let a=e,{accountType:l,prompt:i,modelVersionOverrides:f}=a,{model:c}=a,u="";if(o){let{token:m,url:I}=o;if(!m||!I)throw new Error("No token or url provided from AI Gateway");if(f?.claude){let p=f?.claude?.[l];if(p){if(!await o.isModelAvailableForProvider("anthropic",p))throw new Error(`Model override '${p}' is not available for anthropic provider`);c=p}}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",we)?(c=we,U.log(`Using default model: ${we}`)):U.log(`Default model ${we} is not available, proceeding without model specification`);K.env.ANTHROPIC_API_KEY=m,K.env.ANTHROPIC_BASE_URL=I}else if(!K.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let d=[],h=[],R={},w=0,g=0,N,v,S=[ee(K.cwd(),"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...c?["--model",c]:[],...n?["--continue"]:[],...n&&s?["--resume",s]:[],"-p",i],x=`${K.env.NVM_BIN}/node`;U.log(`Running ${x} ${S.join(" ")}`);let _=t.utils.run(x,S,{all:!0,env:K.env});_.stdin?.end();let A=_e(()=>{r?.({steps:d,duration:g})},250),T=(m,I)=>{let p={...m,id:w};w+=1,h.push(p),d.push(p),I||A.flush(),A(),I&&A.flush()},y=Fr.createInterface({input:_.all});return y.on("error",m=>{U.error("Readline interface error",{error:m.message,stack:m.stack})}),y.on("line",m=>{let I=null;try{I=JSON.parse(m)}catch{U.log("Could not parse line",m)}I?.session_id&&I.session_id!==u&&(u=I.session_id),Array.isArray(I?.message?.content)?I.message.content.forEach(p=>{switch(p.type){case"text":{p.text&&T({message:p.text});break}case"image":{typeof p.source=="object"&&p.source&&p.source.type==="base64"&&p.source.media_type?T({message:``}):U.log(`Unsupported image type ${p.source?.type}`,p.source);break}case"tool_use":{if(p.name==="Task"){let P=p.input?.description&&`\`${p.input.description}\``;T({title:[Ot(p.name),P].filter(Boolean).join(" ")})}else p.id&&(R[p.id]=p);A.flush();break}case"tool_result":{let P=p.tool_use_id?R[p.tool_use_id]:void 0,ae;if(P){let z=P.input?.file_path&&Ft.relative(K.cwd(),P.input.file_path),O=z&&`\`${z}\``;ae=[Ot(P.name||""),O].filter(Boolean).join(" ")}let tt=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(P?.name||""),H;if(typeof p.content=="string")H=p.content;else if(Array.isArray(p.content)){let z=[];p.content.forEach(O=>{O?.type==="text"&&typeof O.text=="string"?z.push(O.text):O?.type==="image"&&typeof O.source=="object"&&O.source?O.source.type==="base64"&&O.source.media_type?z.push(``):U.log(`Unsupported image type ${O.source.type}`,O.source):U.log(`Unsupported block type ${O?.type}`)}),H=z.join(`
|
|
12
12
|
|
|
13
13
|
`)}tt&&H&&(H=`\`\`\`
|
|
14
14
|
${H.trim()}
|
|
@@ -16,7 +16,7 @@ ${H.trim()}
|
|
|
16
16
|
`):_?.type==="message"&&_.role==="system"&&(w=_.content.map(y=>y.text).join(`
|
|
17
17
|
`));T&&(r?.({steps:f,duration:h}),o?.({steps:A,duration:h}))}),await v.catch(x=>{let _=Mr({catchError:x,runCmd:v,error:w,result:R,runnerName:"Codex"});w=_.error,R=_.result}),S.close(),{steps:c,duration:h,result:await re({initialResult:R,agentName:Dt,hasError:!!w}),error:ne({error:w,agentName:Dt}),isRetryableError:oe(w)}}var $t=async()=>{let e=kr.join($r.homedir(),".codex");await Dr.rm(e,{recursive:!0,force:!0})},Gr=new Set(["bash","-lc"]),jr=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!Gr.has(s)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
|
|
18
18
|
${n.trim()}
|
|
19
|
-
\`\`\``)}catch(s){V.error("Could not decode outputMsg",s,t.output)}return{title:o,message:n}};import Yr from"fs/promises";import Br from"os";import Ut from"path";import J from"process";import Hr from"readline";var ie=E("runner_gemini"),kt="Gemini CLI",Wr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(ie.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?(ie.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}):(ie.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),qr={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 Je({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:a,modelVersionOverrides:l}=e,{model:i}=e;if(n){let{token:T,url:y}=n;if(!T||!y)throw new Error("No token or url provided from AI Gateway");if(l?.gemini){let m=l?.gemini?.[s];if(m){if(!await n.isModelAvailableForProvider("gemini",m))throw new Error(`Model override '${m}' is not available for gemini provider`);i=m}}else if(i&&!await n.isModelAvailableForProvider("gemini",i))throw new Error(`Model '${i}' is not available for gemini provider`);J.env.GEMINI_API_KEY=T,J.env.GOOGLE_GEMINI_BASE_URL=y}else if(!J.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let f=[],c=[],u=[],d={},h=0,R=0,w,g,N=[ee(J.cwd(),"gemini"),...i?["--model",i]:[],"--yolo","-p",a],v=`${J.env.NVM_BIN}/node`;ie.log(`Running ${v} ${N.join(" ")}`);let S=t.utils.run(v,N,{all:!0,env:J.env});S.stdin?.end();let x=_e(()=>{r?.({steps:f,duration:R}),o?.({steps:c,duration:R}),c=[]},250),_=(T,y)=>{T.id=h,h+=1,u.push(T),f.push(T),c.push(T),y||x.flush(),x(),y&&x.flush()},A=Hr.createInterface({input:S.all});return A.on("error",T=>{ie.error("Readline interface error",{error:T.message,stack:T.stack})}),A.on("line",T=>{let y=null;try{if(T.startsWith("[API Error")){let m=T.match(/\[api error: (.+?)]$/i)?.[1];y={type:"error",value:Te(m,!1)?.error?.message||m||"Gemini encountered error"}}else y=JSON.parse(T)}catch{return}if(y)switch(y.type){case"thought":{let m=y.value;_({title:m?.subject??"Thinking...",message:m?.description},!0);break}case"content":{y.value&&_({message:y.value});break}case"tool_call_request":{let m=y.value,I=qr[m.name]??m.name,p=m.args?.path||m.args?.absolute_path,
|
|
19
|
+
\`\`\``)}catch(s){V.error("Could not decode outputMsg",s,t.output)}return{title:o,message:n}};import Yr from"fs/promises";import Br from"os";import Ut from"path";import J from"process";import Hr from"readline";var ie=E("runner_gemini"),kt="Gemini CLI",Wr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(ie.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?(ie.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}):(ie.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),qr={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 Je({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:a,modelVersionOverrides:l}=e,{model:i}=e;if(n){let{token:T,url:y}=n;if(!T||!y)throw new Error("No token or url provided from AI Gateway");if(l?.gemini){let m=l?.gemini?.[s];if(m){if(!await n.isModelAvailableForProvider("gemini",m))throw new Error(`Model override '${m}' is not available for gemini provider`);i=m}}else if(i&&!await n.isModelAvailableForProvider("gemini",i))throw new Error(`Model '${i}' is not available for gemini provider`);J.env.GEMINI_API_KEY=T,J.env.GOOGLE_GEMINI_BASE_URL=y}else if(!J.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let f=[],c=[],u=[],d={},h=0,R=0,w,g,N=[ee(J.cwd(),"gemini"),...i?["--model",i]:[],"--yolo","-p",a],v=`${J.env.NVM_BIN}/node`;ie.log(`Running ${v} ${N.join(" ")}`);let S=t.utils.run(v,N,{all:!0,env:J.env});S.stdin?.end();let x=_e(()=>{r?.({steps:f,duration:R}),o?.({steps:c,duration:R}),c=[]},250),_=(T,y)=>{T.id=h,h+=1,u.push(T),f.push(T),c.push(T),y||x.flush(),x(),y&&x.flush()},A=Hr.createInterface({input:S.all});return A.on("error",T=>{ie.error("Readline interface error",{error:T.message,stack:T.stack})}),A.on("line",T=>{let y=null;try{if(T.startsWith("[API Error")){let m=T.match(/\[api error: (.+?)]$/i)?.[1];y={type:"error",value:Te(m,!1)?.error?.message||m||"Gemini encountered error"}}else y=JSON.parse(T)}catch{return}if(y)switch(y.type){case"thought":{let m=y.value;_({title:m?.subject??"Thinking...",message:m?.description},!0);break}case"content":{y.value&&_({message:y.value});break}case"tool_call_request":{let m=y.value,I=qr[m.name]??m.name,p=m.args?.path||m.args?.absolute_path,P=p&&Ut.relative(J.cwd(),p),ae=m.args?.command,H={title:[I,P&&`\`${P}\``,ae&&`\`${ae}\``].filter(Boolean).join(" ")};d[m.callId]=H,x.flush();break}case"tool_result":{let m=y.value,I=d[m.callId];if(I){let p=[m.resultDisplay,m.responseParts?.functionResponse?.response?.output].find(P=>typeof P=="string"&&P);p&&(I.message=`\`\`\`
|
|
20
20
|
${p.trim()}
|
|
21
21
|
\`\`\``),_(I,!0)}break}case"result":{R=y.duration_ms,w=y.value,[u,f,c].forEach(m=>{m[m.length-1]?.message===w&&m.pop()});break}case"error":{g=y.value;break}case"finished":break;default:{ie.warn("Unhandled message type:",y.type);break}}}),await S.catch(T=>{({error:g,result:w}=Wr({catchError:T,runCmd:S,error:g,result:w,runnerName:"Gemini"}))}),A.close(),x.flush(),{steps:u,duration:R,result:await re({initialResult:w,agentName:kt,hasError:!!g}),error:ne({error:g,agentName:kt}),isRetryableError:oe(g)}}var Mt=async()=>{let e=Ut.join(Br.homedir(),".gemini");await Yr.rm(e,{recursive:!0,force:!0})};var Kr={codex:{runner:Ve,clean:$t},claude:{runner:Ke,clean:Lt},gemini:{runner:Je,clean:Mt}},Gt=Kr;var Jr=E("init_stage"),jt=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>await C(Vr(),"init-stage",async n=>{let s=performance.now();n?.setAttributes({"init.runner":e.runner,"init.id":e.id,"init.sessionId":e.sessionId,"init.hasRepo":e.hasRepo,"init.useGateway":e.useGateway,"init.validateAgent":e.validateAgent,"init.runnerVersion":o||"unknown"});let a=Gt[e.runner];if(!a)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let l=Xr({apiToken:r});at(l);let i=e.useGateway?await ft({netlify:l,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!i}),e.validateAgent&&e.errorLogsPath&&n?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let f=wt(({steps:h=[],duration:R})=>{let w=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:w,duration:R})},t);Jr.info("Adding build files to stage");let c=await He();await Ye(c);let u;e.hasRepo?e.sha?(u=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(u=await St(),await ce(e.id,{sha:u}),n?.setAttributes({"init.sha.source":"current_commit"})):(u=await Ct(),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let d=performance.now()-s;return n?.setAttributes({"init.sha":u||"unknown","init.duration.ms":d,"init.status":"success"}),{aiGateway:i,context:l,persistSteps:f,runner:a,sha:u}}),Xr=({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 Xe}from"@netlify/otel";import zr from"crypto";import W from"fs/promises";import $ from"path";import M from"process";var L=E("context"),Zr=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:M.env.NETLIFY_TEAM_ID,userId:M.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:M.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},Qr=10,en=async e=>{let{name:t,ext:r}=$.parse(e),o=e,n=$.join(M.cwd(),k,o),s=0;for(;await tn(n);){if(s>=Qr)throw new Error("Failed to generate context file");o=`${t}-${zr.randomUUID().slice(0,5)}${r}`,n=$.join(M.cwd(),k,o),s+=1}return o},tn=async e=>{try{return await W.access(e),!0}catch{return!1}},rn=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}},nn=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,on=async()=>{if(Re)return Re;let e=await rn();if(!e)return[];let t=$.join(M.cwd(),k,$e);await W.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([n,s])=>{if(!s||typeof s!="object"||!s.endpoint||!s.scope)return L.warn(`Invalid scope data for ${n}, skipping...`),null;let a=`${n}.md`,l=$.join(t,a),i=$.join(k,$e,a);return L.log(`Downloading ${s.scope} context...`),await nn(s.endpoint,l)?(L.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:n}):null});return Re=(await Promise.all(r)).filter(n=>n!==null),Re},Yt=async({cliPath:e,netlify:t,config:r,buildErrorContext:o})=>{let n=Zr(t),s=await en(yt),a=$.join(M.cwd(),k);await W.mkdir(a,{recursive:!0});let l=$.join(k,s),i=$.join(M.cwd(),l),f=$.join(M.cwd(),k,te);try{await W.unlink(f),L.log(`Deleted old results file: ${f}`)}catch{}let c=o?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
|
|
22
22
|
Your task is to analyze and fix the build errors.
|
|
@@ -131,5 +131,5 @@ ${e.pop()}
|
|
|
131
131
|
`;import cn from"process";import{getTracer as ze}from"@netlify/otel";import{getTracer as ln}from"@netlify/otel";var de=E("deploy"),Wt=async e=>await C(ln(),"create-preview-deploy",async t=>un(e,t)),un=async({netlify:e,hasRepo:t,skipBuild:r,message:o="Agent Preview",deploySubdomain:n,cliPath:s,filter:a},l)=>{try{let i=["deploy","--message",`"${o}"`,"--json","--draft","--verbose"];t||(de.log("Deploy: Uploading source zip"),i.push("--upload-source-zip")),n&&i.push("--alias",n),a&&i.push("--filter",a),r?(de.log("Deploy: Skipping build"),i.push("--no-build")):i.push("--context","deploy-preview");let f=s||"netlify";de.log(`Running: ${f} ${i.join(" ")}`),l?.setAttributes({cmd:f,args:i});let c=await e.utils.run(f,i,{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}),de.log(`
|
|
132
132
|
Preview deploy created successfully:`,{deployId:u.deploy_id,deployUrl:u.deploy_url,siteId:u.site_id});let d={deployId:u.deploy_id,previewUrl:u.deploy_url,logsUrl:u.logs,siteId:u.site_id};return t||(d.sourceZipFilename=u.source_zip_filename),d}catch(i){throw de.error("Failed to create preview deploy via CLI:",i),l?.setAttributes({success:!1,error:i.message}),i}};var fe=E("deploy_stage"),Ze=async e=>await C(ze(),"run-deploy-stage",async()=>pn(e)),pn=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let s=await C(ze(),"get-runner-diffs",async()=>await vt({config:t,netlify:r}));if(fe.info("Resolved git",{hasChanges:s.hasChanges,ignored:s.ignored??[]}),!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:l,diffBinary:i,resultDiffBinary:f}=s,c=!0;fe.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 d;try{let h=await C(ze(),"get-runner-session",async()=>await ut(t.id,t.sessionId));h?.title&&(d=h.title)}catch(h){fe.warn("Failed to fetch session title, using fallback message:",h.message)}await j(t.id,t.sessionId,{steps:[{title:"Deploying the run preview"}]}),u=await Wt({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:d,skipBuild:!1,deploySubdomain:It(t.id,cn.env.SITE_NAME),filter:n})}catch(d){return fe.warn("Failed to create preview deploy (continuing with agent run):",d),{diff:a,resultDiff:l,hasChanges:c,previewInfo:null,diffBinary:i,resultDiffBinary:f,deployError:d instanceof Error?d.message:String(d)}}return fe.log("Git status",{hasDiff:!!a,hasChanges:c}),{diff:a,resultDiff:l,hasChanges:c,previewInfo:u,diffBinary:i,resultDiffBinary:f}};import{getTracer as Ae}from"@netlify/otel";async function qt(e,t){let{maxRetries:r,baseDelay:o,onRetry:n}=t,s;for(let a=1;a<=r;a++)try{return await e()}catch(l){if(s=l,a===r)throw s;n&&n(a,s),await new Promise(i=>setTimeout(i,o*a))}throw s}var ve=class{scanDiffForForms(t){let r=[],o=null,n=[],s=t.split(`
|
|
133
133
|
`);for(let a of s)if(a.startsWith("diff --git")){if(o&&n.length>0){let i=this.containsNetlifyForm(n,o);i&&r.push(i)}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:s,name:a}of n){let l=o.match(s);if(l){let i=l.index||0,f=Math.max(0,i-20),c=Math.min(o.length,i+l[0].length+20),u=o.slice(f,c).trim();return u=u.replace(/\s+/g," "),u.length>100&&(u=u.slice(0,97)+"..."),{file:r,snippet:`[${a}] ${u}`}}}return null}};var
|
|
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:s,name:a}of n){let l=o.match(s);if(l){let i=l.index||0,f=Math.max(0,i-20),c=Math.min(o.length,i+l[0].length+20),u=o.slice(f,c).trim();return u=u.replace(/\s+/g," "),u.length>100&&(u=u.slice(0,97)+"..."),{file:r,snippet:`[${a}] ${u}`}}}return null}};var b=E("cleanup_stage"),Kt=async e=>await C(Ae(),"cleanup-stage",async()=>dn(e)),Qe=1024*1024*10,dn=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:s,resultDiffBinary:a,previewInfo:l})=>{let i={result:r||"Done",duration:o};l&&l.deployId&&(i.deploy_id=l.deployId),l&&l.sourceZipFilename&&(i.result_zip_file_name=l.sourceZipFilename);let f=t||s||n||a;if(f){let c=new ve,u=t||s||"",d=c.scanDiffForForms(u);d.detected&&(b.log("Detected Netlify form(s) in diff:"),d.matches.forEach(({file:h,snippet:R})=>{b.log(` - ${h}: ${R}`)}),i.has_netlify_form=!0),b.log("Did not detect Netlify form(s) in diff")}if(f)try{b.log("Getting pre-signed URLs for diff upload");let c=await pt(e.id,e.sessionId),u=[];(t||s)&&u.push(Pe(c.result.upload_url,s||t).then(()=>{i.result_diff_s3_key=c.result.s3_key,b.log("Successfully uploaded result_diff to S3")})),(n||a)&&u.push(Pe(c.cumulative.upload_url,a||n).then(()=>{i.cumulative_diff_s3_key=c.cumulative.s3_key,b.log("Successfully uploaded cumulative_diff to S3")})),b.log(`Uploading ${u.length} diff(s) to S3 in parallel`),await Promise.all(u),(n||a)&&(b.log("Updating agent runner with cumulative diff S3 key"),await C(Ae(),"update-runner",async()=>{await ce(e.id,{result_diff_s3_key:c.cumulative.s3_key})}))}catch(c){b.error("S3 upload failed, falling back to inline diffs:",c);let u=Buffer.byteLength(t||s||""),d=Buffer.byteLength(a||n||"");if(u>Qe||d>Qe){let h=`Diffs exceed maximum inline size of ${Qe} bytes.`;throw b.error(h),new Error(h)}i.result_diff=t,i.result_diff_binary=s,(n||a)&&(i.cumulative_diff=n,i.cumulative_diff_binary=a,b.log("Updating agent runner with inline diffs (fallback)"),await C(Ae(),"update-runner",async()=>{await ce(e.id,{result_diff:n,result_diff_binary:a})}))}else b.log("No diffs to upload");return b.log("Updated agent runner with result"),await qt(async()=>await C(Ae(),"update-runner-session",()=>j(e.id,e.sessionId,i)),{maxRetries:3,baseDelay:1e3,onRetry:(c,u)=>{b.error(`Error updating agent runner session (attempt ${c}):`,u),b.log("Retrying...")}}),b.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as Vt,shutdownTracers as gn,withActiveSpan as Jt}from"@netlify/otel";var mn=fn(import.meta.url),Xt=mn("../package.json"),zt=E("pipeline_index"),Se=3,Zt=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:s,tracing:a={}})=>{let l,{withStageTimer:i}=mt(q.timeUnits.hours(4)),f=await st(Xt.version,e.id,a);try{await Jt(Vt(),"run-pipeline",{},f,async()=>{let c,{aiGateway:u,context:d,persistSteps:h,runner:R,sha:w}=await i("init",()=>jt({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:s,runnerVersion:Xt.version}),q.timeUnits.minutes(10));l=R.clean,e.sha=w;let{runnerResult:g}=await i("inference",()=>xe({cliPath:r,config:e,context:d,runner:R.runner,persistSteps:h,aiGateway:u}));await j(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let N=await i("deploy",()=>Ze({cliPath:r,config:e,context:d,result:g.result,filter:s})),v=g,S=[];if(N.hasChanges&&N.deployError){S.push(it(N.deployError));let m=1;for(;m<=Se&&!N.previewInfo;)zt.log(`Deploy attempt had errors. Retrying. ${m}/${Se}`),await Jt(Vt(),"deploy-stage",async I=>{I?.setAttributes({"stage.attempt":m});let{runnerResult:p}=await i(`inference-retry-${m}`,()=>xe({cliPath:r,config:e,context:d,runner:R.runner,persistSteps:h,aiGateway:u,buildErrors:S,priorAgentSessionId:g.agentSessionId}));v={...p,steps:[...v.steps||[],...p.steps||[]],duration:(v.duration||0)+(p.duration||0)},N=await i(`deploy-retry-${m}`,()=>Ze({cliPath:r,config:e,context:d,result:p.result,filter:s})),N.deployError&&S.push(N.deployError),m++});m>Se&&!N.previewInfo&&(c=new Error(`Deploy validation failed after ${Se} attempts`))}let{diff:x,resultDiff:_,previewInfo:A,diffBinary:T,resultDiffBinary:y}=N;if(await i("cleanup",()=>Kt({config:e,diff:x,result:v.result,duration:v.duration,resultDiff:_,diffBinary:T,resultDiffBinary:y,previewInfo:A}),q.timeUnits.minutes(10)),c)throw c;process.env.NETLIFY_LOCAL_MODE||(await l?.(),await bt())})}catch(c){zt.error("Got error while running pipeline",c),await l?.();let u=c instanceof Error&&c.message;throw await j(e.id,e.sessionId,{result:u||"Encountered error when running agent",state:"error"}),c}finally{await gn()}};import D from"process";var En="claude",yn=e=>(e??[]).filter(t=>t.request&&t.response),_n=e=>(e??[]).filter(t=>t.site_context),Qt=E("config"),er=()=>{let e=D.env.NETLIFY_AGENT_RUNNER_ID,t=D.env.NETLIFY_AGENT_RUNNER_SESSION_ID;if(!e||!t)throw new Error("ID of agent runner is not provided");let r=D.env.NETLIFY_AGENT_RUNNER_RESULT_BRANCH,o=D.env.NETLIFY_AGENT_RUNNER_PROMPT;if(!o)throw new Error("Prompt is not provided");let n=D.env.NETLIFY_AGENT_RUNNER_AGENT||En,s=D.env.NETLIFY_AGENT_RUNNER_MODEL,a=D.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED==="1",l=D.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED==="1",i=D.env.ERROR_LOGS_PATH,f=Te(D.env.NETLIFY_AGENT_RUNNER_CONTEXT,!0,Qt),c=yn(f),u=_n(f),d=D.env.NETLIFY_AGENT_RUNNER_HAS_REPO!=="0",h=!D.env.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED,R=D.env.NETLIFY_AGENT_RUNNER_SHA,w=Tn(),g=Rt(),N={id:e,sessionId:t,resultBranch:r,prompt:o,runner:n,model:s,validateAgent:a,errorLogsPath:i,sessionHistoryContext:c,siteContext:u,hasRepo:d,useGateway:h,sha:R,accountType:w,validateAgentWithBuild:l,modelVersionOverrides:g};return Qt.log({fullConfig:N}),N},Tn=()=>{let e=D.env.NETLIFY_TEAM_TYPE;return e?e.includes("personal")?Me:e.includes("pro")?"pro":e.startsWith("enterprise")?Ge:e.startsWith("free")?je:Ue:Ue};var tr=E("bin_cmd"),X=wn(et.argv.slice(2),{string:["auth","cwd","cli-path","error-logs-path","filter","trace-exporter-url","traceparent"]});try{let e=er();await Zt({config:e,apiToken:X.auth,cwd:X.cwd,cliPath:X["cli-path"],errorLogsPath:X["error-logs-path"],filter:X.filter,tracing:{exporterUrl:X["trace-exporter-url"],traceparent:X.traceparent}}),tr.info("Finished agent"),et.exit(0)}catch(e){tr.error("Error running agent pipeline:",e),et.exit(1)}
|
|
135
135
|
//# sourceMappingURL=bin.js.map
|
package/dist/index.js
CHANGED
|
@@ -7,7 +7,7 @@ ${a}
|
|
|
7
7
|
`);return s.length>e.length*.8?e:s}import _e from"process";import{getTracer as $r}from"@netlify/otel";import ie from"process";var de=ie.env.NETLIFY_API_URL,fe=ie.env.NETLIFY_API_TOKEN,M=E("api"),ge=()=>ie.env.NETLIFY_LOCAL_MODE==="true",ae=async(e,t={})=>{if(!de||!fe)throw new Error("No API URL or token");let r=new URL(e,de),o={...t,headers:{...t.headers,Authorization:`Bearer ${fe}`}};ie.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(ie.env.AGENT_RUNNERS_DEBUG==="true")M.log(`Response headers for ${r}:`),n.headers.forEach((u,i)=>{M.log(` ${i}: ${u}`)});else{let u=n.headers.get("x-request-id")||n.headers.get("x-nf-request-id");M.log(`Request ID for ${r}: ${u||"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&&(de=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(fe=e.constants.NETLIFY_API_TOKEN)},et=()=>({apiUrl:de,token:fe}),le=async(e,t)=>ge()?(M.log("Mock API: updateRunner called",{runnerId:e,data:t}),{id:e,...t}):ae(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),G=async(e,t,r)=>ge()?(M.log("Mock API: updateRunnerSession called",JSON.stringify({runnerId:e,sessionId:t,data:r},null,2)),{id:e,sessionId:t,...r}):ae(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var tt=async(e,t)=>ge()?(M.log("Mock API: getRunnerSession called",{runnerId:e,sessionId:t}),{id:t,runnerId:e,state:"running"}):ae(`/api/v1/agent_runners/${e}/sessions/${t}`),rt=(e,t,r)=>ae(`/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)=>ge()?(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"}}):ae(`/api/v1/agent_runners/${e}/sessions/${t}/diff/upload_urls`,{method:"POST"}),Ne=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 X=E("ai_gateway"),be=null;var ot=async()=>{if(be)return be;X.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 be=t,X.log("Cached AI gateway providers",{providerCount:Object.keys(t.providers).length}),t},Vt=async(e,t)=>{let o=(await ot()).providers[e];if(!o)return X.log(`Provider '${e}' not found`),!1;let n=o.models.includes(t);return X.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 u=async()=>{clearTimeout(n),X.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,X.log("Got AI gateway information",{token:!!r,expiresAt:o,url:s}),o){let m=o-Date.now()-6e4;m>0&&(n=setTimeout(()=>{u()},m))}};return await Promise.all([u(),ot()]),{get url(){return s},get token(){return r},isModelAvailableForProvider:Vt}};import Y from"process";import me from"path";import Ce from"fs";import{fileURLToPath as er}from"url";import{execa as tr,execaCommand as An}from"execa";import{Transform as Jt}from"stream";var Xt=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 Zt(){return Object.entries(process.env).filter(([e,t])=>!(!t||Xt.has(e)||zt.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function j(e){if(typeof e!="string")return e;let t=Zt();if(t.length===0)return e;let r=e;return t.forEach(o=>{let n=new RegExp(Qt(o),"g");r=r.replace(n,"******")}),r}function Qt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var z=class extends Jt{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,o){let n=t.toString(),s=j(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"?j(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"?j(o):o;return typeof n=="function"?r(a,n):r(a,n,s)}}var ue=null,at=e=>(ue&&ue.destroy(),ue=new q({totalAllowedTime:e}),ue),lt=()=>ue;var q=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((u,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 rr=er(import.meta.url),nr=me.dirname(rr),he=E("shell"),Pe=new Set,or={preferLocal:!0},F=(e,t,r)=>{let[o,n]=sr(t,r),s={...or,...n},a=tr(e,o,s);return ir(a,s),lr(a),a};var sr=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},ir=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(Y.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new z).pipe(Y.stdout),e.stdout?.pipe(new z).pipe(Y.stdout),e.stderr?.pipe(new z).pipe(Y.stderr);return}e.stdout?.pipe(Y.stdout),e.stderr?.pipe(Y.stderr)},ut=(e,t="SIGTERM")=>{try{return e.pid&&!e.killed?(Y.kill(-e.pid,t),he.log(`Killed process ${e.pid} with signal ${t}`),!0):!1}catch(r){return he.error("Error killing process:",r),!1}},ar=e=>ut(e,"SIGKILL"),lr=e=>{Pe.add(e);let t=lt();if(t){let r=t.onTimesUp(()=>{he.log(`Global timer expired, killing process ${e.pid}`),ut(e,"SIGTERM"),setTimeout(()=>{e.pid&&!e.killed&&(he.log(`Force killing process ${e.pid} after timeout`),ar(e))},5e3)});e.on("exit",()=>{Pe.delete(e),r()}),e.on("error",()=>{Pe.delete(e),r()})}};function Z(e,t){if(Y.env.NODE_PATH){let n=me.join(Y.env.NODE_PATH,".bin",t);if(Ce.existsSync(n))return n}let r=me.join(e,"node_modules",".bin",t);if(Ce.existsSync(r))return r;let o=me.join(nr,"..","node_modules",".bin",t);if(Ce.existsSync(o))return o}var ct="netlify-agent-runner-context.md",Oe="task-history",Fe="netlify-context",L=".netlify",Q="results.md",$e="assets";var ur=E("utils"),cr=e=>new Promise(t=>{setTimeout(t,e)}),pt=(e,t=3e3)=>{let r=!1,o=null,n=[],s=null,a=(...u)=>{if(r)return o=u,new Promise(c=>{n.push(c)});r=!0;let i,m=new Promise(c=>{i=c});return s=(async()=>{await Promise.resolve();let c=await e(...u);for(i(c);;){if(await cr(t),!o)return r=!1,s=null,c;let l=o,d=n;o=null,n=[],c=await e(...l),d.forEach(h=>{h(c)})}})(),m};return a.flush=async()=>{if((r||o)&&s)return await s,a.flush()},a},ye=(e,t,r=!1)=>{let o=null,n=null,s=null,a=function(...u){n=u,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 u=n,i=s;o=null,n=null,s=null,e.apply(i,u)}},a},dt=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(o){t&&(r?.error?r.error("Could not parse JSON",o):ur.error("Could not parse JSON",o))}},ft=(e,t)=>{let n=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let u=`--${t}${n}`;if(u.length>55)return"";let i=60-u.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 gt}from"buffer";import pr from"path";var mt=E("repo"),ht=async({config:e})=>{mt.info("Getting runner diffs");let t=await fr(),{hasChanges:r}=t,{status:o}=t;if(!r)return{hasChanges:!1};let n=gr(o);await mr(n),mt.info("Changes after processing"),await Le();let s=await ke(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 c=(await F("git",["diff","--staged","--binary"],a)).stdout,l,d;if(e.sha){process.env.NETLIFY_LOCAL_MODE||await F("git",["commit","-m","Agent runner"]),l=(await F("git",["diff",e.sha,"HEAD"],a)).stdout;let g=(await F("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;l!==g&&(d=gt.from(g).toString("base64"))}let h={hasChanges:!0,diff:i,resultDiff:l,ignored:s};return i!==c&&(h.diffBinary=gt.from(c).toString("base64")),d&&(h.resultDiffBinary=d),h},De=async(e=[])=>{await F("git",["add",".",...e])},Le=async()=>(await F("git",["status","-s"])).stdout,yt=/.. (.+)?\.log$/,dr=[yt],fr=async()=>{let e=await Le();return{hasChanges:(e.trim().length===0?[]:e.split(`
|
|
8
8
|
`).filter(o=>dr.some(s=>s instanceof RegExp?s.test(o):o===s)?!1:o[1]?.trim()!=="")).length!==0,status:e}},Et=async()=>{let{stdout:e}=await F("git",["rev-parse","HEAD"]);return e.trim()},_t=async()=>{let{stdout:e}=await F("git",["rev-list","--max-parents=0","HEAD"]);return e.trim()},ke=async e=>{e||=await Le();let t=[".netlify","node_modules"],r=[];return e.split(`
|
|
9
9
|
`).forEach(o=>{t.forEach(s=>{[`?? ${s}`,`?? ${s}${pr.sep}`].some(u=>o.startsWith(u))&&r.push(`:!${s}`)});let n=o.match(yt)?.[1];n&&r.push(`:!${n}.log`)}),r},wt=async()=>{await F("git",["reset","--hard","HEAD"])},gr=e=>{let t=e.split(`
|
|
10
|
-
`).reduce((r,o)=>{if(!o)return r;let[n,s,,...a]=o,u=a.join(""),i=n.trim(),m=s.trim();return r[u]?r[u].change=m:r[u]={filePath:u,stage:i,change:m},r},{});return Object.values(t)},mr=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 yr from"fs/promises";import Er from"os";import xt from"path";import K from"process";import _r from"readline";import Ue from"path";import hr from"fs/promises";var Me=E("agent-output-utils");async function ee({initialResult:e,agentName:t,hasError:r}){let o="",n=Ue.join(process.cwd(),L,Q);try{let s=await hr.readFile(n,"utf-8");s&&(o=s,Me.log(`Pulled result from ${Ue.relative(process.cwd(),n)}`))}catch{Me.log(`No results file found at ${Ue.relative(process.cwd(),n)}`)}return o||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function te({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&&Me.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function re(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 k=E("runner_claude"),Tt="Claude Code",Ee="claude-sonnet-4-5-20250929",It=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,wr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(k.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?(k.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}):(k.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function Ge({config:e,netlify:t,persistSteps:r,aiGateway:o,continueSession:n,priorAgentSessionId:s}){let a=e,{accountType:u,prompt:i,modelVersionOverrides:m}=a,{model:c}=a,l="";if(o){let{token:f,url:T}=o;if(!f||!T)throw new Error("No token or url provided from AI Gateway");if(m?.claude){let p=m?.claude?.[u];if(p){if(!await o.isModelAvailableForProvider("anthropic",p))throw new Error(`Model override '${p}' is not available for anthropic provider`);c=p}}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",Ee)?(c=Ee,k.log(`Using default model: ${Ee}`)):k.log(`Default model ${Ee} is not available, proceeding without model specification`);K.env.ANTHROPIC_API_KEY=f,K.env.ANTHROPIC_BASE_URL=T}else if(!K.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let d=[],h=[],x={},I=0,g=0,S,v,N=[Z(K.cwd(),"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...c?["--model",c]:[],...n?["--continue"]:[],...n&&s?["--resume",s]:[],"-p",i],R=`${K.env.NVM_BIN}/node`;k.log(`Running ${R} ${N.join(" ")}`);let _=t.utils.run(R,N,{all:!0,env:K.env});_.stdin?.end();let A=ye(()=>{r?.({steps:d,duration:g})},250),w=(f,T)=>{let p={...f,id:I};I+=1,h.push(p),d.push(p),T||A.flush(),A(),T&&A.flush()},y=_r.createInterface({input:_.all});return y.on("error",f=>{k.error("Readline interface error",{error:f.message,stack:f.stack})}),y.on("line",f=>{let T=null;try{T=JSON.parse(f)}catch{k.log("Could not parse line",f)}T?.session_id&&T.session_id!==l&&(l=T.session_id),Array.isArray(T?.message?.content)?T.message.content.forEach(p=>{switch(p.type){case"text":{p.text&&w({message:p.text});break}case"image":{typeof p.source=="object"&&p.source&&p.source.type==="base64"&&p.source.media_type?w({message:``}):k.log(`Unsupported image type ${p.source?.type}`,p.source);break}case"tool_use":{if(p.name==="Task"){let
|
|
10
|
+
`).reduce((r,o)=>{if(!o)return r;let[n,s,,...a]=o,u=a.join(""),i=n.trim(),m=s.trim();return r[u]?r[u].change=m:r[u]={filePath:u,stage:i,change:m},r},{});return Object.values(t)},mr=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 yr from"fs/promises";import Er from"os";import xt from"path";import K from"process";import _r from"readline";import Ue from"path";import hr from"fs/promises";var Me=E("agent-output-utils");async function ee({initialResult:e,agentName:t,hasError:r}){let o="",n=Ue.join(process.cwd(),L,Q);try{let s=await hr.readFile(n,"utf-8");s&&(o=s,Me.log(`Pulled result from ${Ue.relative(process.cwd(),n)}`))}catch{Me.log(`No results file found at ${Ue.relative(process.cwd(),n)}`)}return o||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function te({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&&Me.log(`Providing updated error messsage: ${n}, replacing original error: ${r}`),n||r||void 0}function re(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 k=E("runner_claude"),Tt="Claude Code",Ee="claude-sonnet-4-5-20250929",It=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,wr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(k.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?(k.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}):(k.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0}));async function Ge({config:e,netlify:t,persistSteps:r,aiGateway:o,continueSession:n,priorAgentSessionId:s}){let a=e,{accountType:u,prompt:i,modelVersionOverrides:m}=a,{model:c}=a,l="";if(o){let{token:f,url:T}=o;if(!f||!T)throw new Error("No token or url provided from AI Gateway");if(m?.claude){let p=m?.claude?.[u];if(p){if(!await o.isModelAvailableForProvider("anthropic",p))throw new Error(`Model override '${p}' is not available for anthropic provider`);c=p}}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",Ee)?(c=Ee,k.log(`Using default model: ${Ee}`)):k.log(`Default model ${Ee} is not available, proceeding without model specification`);K.env.ANTHROPIC_API_KEY=f,K.env.ANTHROPIC_BASE_URL=T}else if(!K.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let d=[],h=[],x={},I=0,g=0,S,v,N=[Z(K.cwd(),"claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...c?["--model",c]:[],...n?["--continue"]:[],...n&&s?["--resume",s]:[],"-p",i],R=`${K.env.NVM_BIN}/node`;k.log(`Running ${R} ${N.join(" ")}`);let _=t.utils.run(R,N,{all:!0,env:K.env});_.stdin?.end();let A=ye(()=>{r?.({steps:d,duration:g})},250),w=(f,T)=>{let p={...f,id:I};I+=1,h.push(p),d.push(p),T||A.flush(),A(),T&&A.flush()},y=_r.createInterface({input:_.all});return y.on("error",f=>{k.error("Readline interface error",{error:f.message,stack:f.stack})}),y.on("line",f=>{let T=null;try{T=JSON.parse(f)}catch{k.log("Could not parse line",f)}T?.session_id&&T.session_id!==l&&(l=T.session_id),Array.isArray(T?.message?.content)?T.message.content.forEach(p=>{switch(p.type){case"text":{p.text&&w({message:p.text});break}case"image":{typeof p.source=="object"&&p.source&&p.source.type==="base64"&&p.source.media_type?w({message:``}):k.log(`Unsupported image type ${p.source?.type}`,p.source);break}case"tool_use":{if(p.name==="Task"){let P=p.input?.description&&`\`${p.input.description}\``;w({title:[It(p.name),P].filter(Boolean).join(" ")})}else p.id&&(x[p.id]=p);A.flush();break}case"tool_result":{let P=p.tool_use_id?x[p.tool_use_id]:void 0,se;if(P){let J=P.input?.file_path&&xt.relative(K.cwd(),P.input.file_path),O=J&&`\`${J}\``;se=[It(P.name||""),O].filter(Boolean).join(" ")}let We=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(P?.name||""),B;if(typeof p.content=="string")B=p.content;else if(Array.isArray(p.content)){let J=[];p.content.forEach(O=>{O?.type==="text"&&typeof O.text=="string"?J.push(O.text):O?.type==="image"&&typeof O.source=="object"&&O.source?O.source.type==="base64"&&O.source.media_type?J.push(``):k.log(`Unsupported image type ${O.source.type}`,O.source):k.log(`Unsupported block type ${O?.type}`)}),B=J.join(`
|
|
11
11
|
|
|
12
12
|
`)}We&&B&&(B=`\`\`\`
|
|
13
13
|
${B.trim()}
|
|
@@ -15,7 +15,7 @@ ${B.trim()}
|
|
|
15
15
|
`):_?.type==="message"&&_.role==="system"&&(I=_.content.map(y=>y.text).join(`
|
|
16
16
|
`));w&&(r?.({steps:m,duration:h}),o?.({steps:A,duration:h}))}),await v.catch(R=>{let _=vr({catchError:R,runCmd:v,error:I,result:x,runnerName:"Codex"});I=_.error,x=_.result}),N.close(),{steps:c,duration:h,result:await ee({initialResult:x,agentName:vt,hasError:!!I}),error:te({error:I,agentName:vt}),isRetryableError:re(I)}}var St=async()=>{let e=xr.join(Ir.homedir(),".codex");await Tr.rm(e,{recursive:!0,force:!0})},Sr=new Set(["bash","-lc"]),Ar=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!Sr.has(s)),o=r?`Running \`${r.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
|
|
17
17
|
${n.trim()}
|
|
18
|
-
\`\`\``)}catch(s){W.error("Could not decode outputMsg",s,t.output)}return{title:o,message:n}};import Nr from"fs/promises";import br from"os";import Nt from"path";import V from"process";import Cr from"readline";var oe=E("runner_gemini"),At="Gemini CLI",Pr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(oe.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?(oe.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}):(oe.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),Or={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 Ye({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:a,modelVersionOverrides:u}=e,{model:i}=e;if(n){let{token:w,url:y}=n;if(!w||!y)throw new Error("No token or url provided from AI Gateway");if(u?.gemini){let f=u?.gemini?.[s];if(f){if(!await n.isModelAvailableForProvider("gemini",f))throw new Error(`Model override '${f}' is not available for gemini provider`);i=f}}else if(i&&!await n.isModelAvailableForProvider("gemini",i))throw new Error(`Model '${i}' is not available for gemini provider`);V.env.GEMINI_API_KEY=w,V.env.GOOGLE_GEMINI_BASE_URL=y}else if(!V.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let m=[],c=[],l=[],d={},h=0,x=0,I,g,S=[Z(V.cwd(),"gemini"),...i?["--model",i]:[],"--yolo","-p",a],v=`${V.env.NVM_BIN}/node`;oe.log(`Running ${v} ${S.join(" ")}`);let N=t.utils.run(v,S,{all:!0,env:V.env});N.stdin?.end();let R=ye(()=>{r?.({steps:m,duration:x}),o?.({steps:c,duration:x}),c=[]},250),_=(w,y)=>{w.id=h,h+=1,l.push(w),m.push(w),c.push(w),y||R.flush(),R(),y&&R.flush()},A=Cr.createInterface({input:N.all});return A.on("error",w=>{oe.error("Readline interface error",{error:w.message,stack:w.stack})}),A.on("line",w=>{let y=null;try{if(w.startsWith("[API Error")){let f=w.match(/\[api error: (.+?)]$/i)?.[1];y={type:"error",value:dt(f,!1)?.error?.message||f||"Gemini encountered error"}}else y=JSON.parse(w)}catch{return}if(y)switch(y.type){case"thought":{let f=y.value;_({title:f?.subject??"Thinking...",message:f?.description},!0);break}case"content":{y.value&&_({message:y.value});break}case"tool_call_request":{let f=y.value,T=Or[f.name]??f.name,p=f.args?.path||f.args?.absolute_path,
|
|
18
|
+
\`\`\``)}catch(s){W.error("Could not decode outputMsg",s,t.output)}return{title:o,message:n}};import Nr from"fs/promises";import br from"os";import Nt from"path";import V from"process";import Cr from"readline";var oe=E("runner_gemini"),At="Gemini CLI",Pr=({catchError:e,runCmd:t,error:r,result:o,runnerName:n})=>(oe.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?(oe.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}):(oe.log("Setting result to undefined because no valid result was captured"),{error:r||`${n} failed`,result:void 0})),Or={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 Ye({config:e,netlify:t,persistSteps:r,sendSteps:o,aiGateway:n}){let{accountType:s,prompt:a,modelVersionOverrides:u}=e,{model:i}=e;if(n){let{token:w,url:y}=n;if(!w||!y)throw new Error("No token or url provided from AI Gateway");if(u?.gemini){let f=u?.gemini?.[s];if(f){if(!await n.isModelAvailableForProvider("gemini",f))throw new Error(`Model override '${f}' is not available for gemini provider`);i=f}}else if(i&&!await n.isModelAvailableForProvider("gemini",i))throw new Error(`Model '${i}' is not available for gemini provider`);V.env.GEMINI_API_KEY=w,V.env.GOOGLE_GEMINI_BASE_URL=y}else if(!V.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let m=[],c=[],l=[],d={},h=0,x=0,I,g,S=[Z(V.cwd(),"gemini"),...i?["--model",i]:[],"--yolo","-p",a],v=`${V.env.NVM_BIN}/node`;oe.log(`Running ${v} ${S.join(" ")}`);let N=t.utils.run(v,S,{all:!0,env:V.env});N.stdin?.end();let R=ye(()=>{r?.({steps:m,duration:x}),o?.({steps:c,duration:x}),c=[]},250),_=(w,y)=>{w.id=h,h+=1,l.push(w),m.push(w),c.push(w),y||R.flush(),R(),y&&R.flush()},A=Cr.createInterface({input:N.all});return A.on("error",w=>{oe.error("Readline interface error",{error:w.message,stack:w.stack})}),A.on("line",w=>{let y=null;try{if(w.startsWith("[API Error")){let f=w.match(/\[api error: (.+?)]$/i)?.[1];y={type:"error",value:dt(f,!1)?.error?.message||f||"Gemini encountered error"}}else y=JSON.parse(w)}catch{return}if(y)switch(y.type){case"thought":{let f=y.value;_({title:f?.subject??"Thinking...",message:f?.description},!0);break}case"content":{y.value&&_({message:y.value});break}case"tool_call_request":{let f=y.value,T=Or[f.name]??f.name,p=f.args?.path||f.args?.absolute_path,P=p&&Nt.relative(V.cwd(),p),se=f.args?.command,B={title:[T,P&&`\`${P}\``,se&&`\`${se}\``].filter(Boolean).join(" ")};d[f.callId]=B,R.flush();break}case"tool_result":{let f=y.value,T=d[f.callId];if(T){let p=[f.resultDisplay,f.responseParts?.functionResponse?.response?.output].find(P=>typeof P=="string"&&P);p&&(T.message=`\`\`\`
|
|
19
19
|
${p.trim()}
|
|
20
20
|
\`\`\``),_(T,!0)}break}case"result":{x=y.duration_ms,I=y.value,[l,m,c].forEach(f=>{f[f.length-1]?.message===I&&f.pop()});break}case"error":{g=y.value;break}case"finished":break;default:{oe.warn("Unhandled message type:",y.type);break}}}),await N.catch(w=>{({error:g,result:I}=Pr({catchError:w,runCmd:N,error:g,result:I,runnerName:"Gemini"}))}),A.close(),R.flush(),{steps:l,duration:x,result:await ee({initialResult:I,agentName:At,hasError:!!g}),error:te({error:g,agentName:At}),isRetryableError:re(g)}}var bt=async()=>{let e=Nt.join(br.homedir(),".gemini");await Nr.rm(e,{recursive:!0,force:!0})};var Fr={codex:{runner:je,clean:St},claude:{runner:Ge,clean:Rt},gemini:{runner:Ye,clean:bt}},Ct=Fr;var Dr=E("init_stage"),Pt=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:o})=>await b($r(),"init-stage",async n=>{let s=performance.now();n?.setAttributes({"init.runner":e.runner,"init.id":e.id,"init.sessionId":e.sessionId,"init.hasRepo":e.hasRepo,"init.useGateway":e.useGateway,"init.validateAgent":e.validateAgent,"init.runnerVersion":o||"unknown"});let a=Ct[e.runner];if(!a)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let u=Lr({apiToken:r});Qe(u);let i=e.useGateway?await st({netlify:u,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!i}),e.validateAgent&&e.errorLogsPath&&n?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let m=pt(({steps:h=[],duration:x})=>{let I=h.map(g=>({...g,title:g.title?j(g.title):void 0,message:g.message?j(g.message):void 0}));return h.length=0,G(e.id,e.sessionId,{steps:I,duration:x})},t);Dr.info("Adding build files to stage");let c=await ke();await De(c);let l;e.hasRepo?e.sha?(l=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(l=await Et(),await le(e.id,{sha:l}),n?.setAttributes({"init.sha.source":"current_commit"})):(l=await _t(),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let d=performance.now()-s;return n?.setAttributes({"init.sha":l||"unknown","init.duration.ms":d,"init.status":"success"}),{aiGateway:i,context:u,persistSteps:m,runner:a,sha:l}}),Lr=({apiToken:e})=>({constants:{NETLIFY_API_HOST:_e.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||_e.env.NETLIFY_API_TOKEN,SITE_ID:_e.env.SITE_ID,FUNCTIONS_DIST:_e.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:F}});import{getTracer as Be}from"@netlify/otel";import kr from"crypto";import H from"fs/promises";import D from"path";import U from"process";var $=E("context"),Ur=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}},Mr=10,Gr=async e=>{let{name:t,ext:r}=D.parse(e),o=e,n=D.join(U.cwd(),L,o),s=0;for(;await jr(n);){if(s>=Mr)throw new Error("Failed to generate context file");o=`${t}-${kr.randomUUID().slice(0,5)}${r}`,n=D.join(U.cwd(),L,o),s+=1}return o},jr=async e=>{try{return await H.access(e),!0}catch{return!1}},Yr=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(o=>o&&typeof o=="object"&&o.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}},Br=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 H.writeFile(t,o,"utf-8"),!0}catch(r){return r.name==="AbortError"?$.warn(`Download timeout for ${e}`):$.warn(`Failed to download context file ${e}:`,r.message),!1}},we=null,Hr=async()=>{if(we)return we;let e=await Yr();if(!e)return[];let t=D.join(U.cwd(),L,Fe);await H.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([n,s])=>{if(!s||typeof s!="object"||!s.endpoint||!s.scope)return $.warn(`Invalid scope data for ${n}, skipping...`),null;let a=`${n}.md`,u=D.join(t,a),i=D.join(L,Fe,a);return $.log(`Downloading ${s.scope} context...`),await Br(s.endpoint,u)?($.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:n}):null});return we=(await Promise.all(r)).filter(n=>n!==null),we},Ot=async({cliPath:e,netlify:t,config:r,buildErrorContext:o})=>{let n=Ur(t),s=await Gr(ct),a=D.join(U.cwd(),L);await H.mkdir(a,{recursive:!0});let u=D.join(L,s),i=D.join(U.cwd(),u),m=D.join(U.cwd(),L,Q);try{await H.unlink(m),$.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.
|
|
21
21
|
Your task is to analyze and fix the build errors.
|
|
@@ -130,5 +130,5 @@ ${e.pop()}
|
|
|
130
130
|
`;import Jr from"process";import{getTracer as He}from"@netlify/otel";import{getTracer as Wr}from"@netlify/otel";var ce=E("deploy"),Dt=async e=>await b(Wr(),"create-preview-deploy",async t=>Vr(e,t)),Vr=async({netlify:e,hasRepo:t,skipBuild:r,message:o="Agent Preview",deploySubdomain:n,cliPath:s,filter:a},u)=>{try{let i=["deploy","--message",`"${o}"`,"--json","--draft","--verbose"];t||(ce.log("Deploy: Uploading source zip"),i.push("--upload-source-zip")),n&&i.push("--alias",n),a&&i.push("--filter",a),r?(ce.log("Deploy: Skipping build"),i.push("--no-build")):i.push("--context","deploy-preview");let m=s||"netlify";ce.log(`Running: ${m} ${i.join(" ")}`),u?.setAttributes({cmd:m,args:i});let c=await e.utils.run(m,i,{stdio:["ignore","pipe","pipe"]}),l=JSON.parse(c.stdout.trim());u?.setAttributes({success:!0,deployId:l.deploy_id,deployUrl:l.deploy_url,siteId:l.site_id}),ce.log(`
|
|
131
131
|
Preview deploy created successfully:`,{deployId:l.deploy_id,deployUrl:l.deploy_url,siteId:l.site_id});let d={deployId:l.deploy_id,previewUrl:l.deploy_url,logsUrl:l.logs,siteId:l.site_id};return t||(d.sourceZipFilename=l.source_zip_filename),d}catch(i){throw ce.error("Failed to create preview deploy via CLI:",i),u?.setAttributes({success:!1,error:i.message}),i}};var pe=E("deploy_stage"),qe=async e=>await b(He(),"run-deploy-stage",async()=>Xr(e)),Xr=async({cliPath:e,config:t,context:r,result:o,filter:n})=>{let s=await b(He(),"get-runner-diffs",async()=>await ht({config:t,netlify:r}));if(pe.info("Resolved git",{hasChanges:s.hasChanges,ignored:s.ignored??[]}),!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:u,diffBinary:i,resultDiffBinary:m}=s,c=!0;pe.log("Preview deploy condition check:",{resultUndefined:o===void 0,resultType:typeof o,hasChanges:c,wouldCreatePreview:o!==void 0&&c});let l=null;if(o!==void 0&&c)try{let d;try{let h=await b(He(),"get-runner-session",async()=>await tt(t.id,t.sessionId));h?.title&&(d=h.title)}catch(h){pe.warn("Failed to fetch session title, using fallback message:",h.message)}await G(t.id,t.sessionId,{steps:[{title:"Deploying the run preview"}]}),l=await Dt({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:d,skipBuild:!1,deploySubdomain:ft(t.id,Jr.env.SITE_NAME),filter:n})}catch(d){return pe.warn("Failed to create preview deploy (continuing with agent run):",d),{diff:a,resultDiff:u,hasChanges:c,previewInfo:null,diffBinary:i,resultDiffBinary:m,deployError:d instanceof Error?d.message:String(d)}}return pe.log("Git status",{hasDiff:!!a,hasChanges:c}),{diff:a,resultDiff:u,hasChanges:c,previewInfo:l,diffBinary:i,resultDiffBinary:m}};import{getTracer as Re}from"@netlify/otel";async function Lt(e,t){let{maxRetries:r,baseDelay:o,onRetry:n}=t,s;for(let a=1;a<=r;a++)try{return await e()}catch(u){if(s=u,a===r)throw s;n&&n(a,s),await new Promise(i=>setTimeout(i,o*a))}throw s}var xe=class{scanDiffForForms(t){let r=[],o=null,n=[],s=t.split(`
|
|
132
132
|
`);for(let a of s)if(a.startsWith("diff --git")){if(o&&n.length>0){let i=this.containsNetlifyForm(n,o);i&&r.push(i)}let u=a.split(" ");o=u[u.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(`
|
|
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:s,name:a}of n){let u=o.match(s);if(u){let i=u.index||0,m=Math.max(0,i-20),c=Math.min(o.length,i+u[0].length+20),l=o.slice(m,c).trim();return l=l.replace(/\s+/g," "),l.length>100&&(l=l.slice(0,97)+"..."),{file:r,snippet:`[${a}] ${l}`}}}return null}};var
|
|
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:s,name:a}of n){let u=o.match(s);if(u){let i=u.index||0,m=Math.max(0,i-20),c=Math.min(o.length,i+u[0].length+20),l=o.slice(m,c).trim();return l=l.replace(/\s+/g," "),l.length>100&&(l=l.slice(0,97)+"..."),{file:r,snippet:`[${a}] ${l}`}}}return null}};var C=E("cleanup_stage"),kt=async e=>await b(Re(),"cleanup-stage",async()=>zr(e)),Ke=1024*1024*10,zr=async({config:e,diff:t,result:r,duration:o,resultDiff:n,diffBinary:s,resultDiffBinary:a,previewInfo:u})=>{let i={result:r||"Done",duration:o};u&&u.deployId&&(i.deploy_id=u.deployId),u&&u.sourceZipFilename&&(i.result_zip_file_name=u.sourceZipFilename);let m=t||s||n||a;if(m){let c=new xe,l=t||s||"",d=c.scanDiffForForms(l);d.detected&&(C.log("Detected Netlify form(s) in diff:"),d.matches.forEach(({file:h,snippet:x})=>{C.log(` - ${h}: ${x}`)}),i.has_netlify_form=!0),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 nt(e.id,e.sessionId),l=[];(t||s)&&l.push(Ne(c.result.upload_url,s||t).then(()=>{i.result_diff_s3_key=c.result.s3_key,C.log("Successfully uploaded result_diff to S3")})),(n||a)&&l.push(Ne(c.cumulative.upload_url,a||n).then(()=>{i.cumulative_diff_s3_key=c.cumulative.s3_key,C.log("Successfully uploaded cumulative_diff to S3")})),C.log(`Uploading ${l.length} diff(s) to S3 in parallel`),await Promise.all(l),(n||a)&&(C.log("Updating agent runner with cumulative diff S3 key"),await b(Re(),"update-runner",async()=>{await le(e.id,{result_diff_s3_key:c.cumulative.s3_key})}))}catch(c){C.error("S3 upload failed, falling back to inline diffs:",c);let l=Buffer.byteLength(t||s||""),d=Buffer.byteLength(a||n||"");if(l>Ke||d>Ke){let h=`Diffs exceed maximum inline size of ${Ke} bytes.`;throw C.error(h),new Error(h)}i.result_diff=t,i.result_diff_binary=s,(n||a)&&(i.cumulative_diff=n,i.cumulative_diff_binary=a,C.log("Updating agent runner with inline diffs (fallback)"),await b(Re(),"update-runner",async()=>{await le(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 Lt(async()=>await b(Re(),"update-runner-session",()=>G(e.id,e.sessionId,i)),{maxRetries:3,baseDelay:1e3,onRetry:(c,l)=>{C.error(`Error updating agent runner session (attempt ${c}):`,l),C.log("Retrying...")}}),C.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as Ut,shutdownTracers as Qr,withActiveSpan as Mt}from"@netlify/otel";var en=Zr(import.meta.url),Gt=en("../package.json"),jt=E("pipeline_index"),ve=3,Ds=async({config:e,apiToken:t,cliPath:r="netlify",cwd:o,errorLogsPath:n,filter:s,tracing:a={}})=>{let u,{withStageTimer:i}=at(q.timeUnits.hours(4)),m=await ze(Gt.version,e.id,a);try{await Mt(Ut(),"run-pipeline",{},m,async()=>{let c,{aiGateway:l,context:d,persistSteps:h,runner:x,sha:I}=await i("init",()=>Pt({config:e,apiToken:t,cliPath:r,cwd:o,errorLogsPath:n,filter:s,runnerVersion:Gt.version}),q.timeUnits.minutes(10));u=x.clean,e.sha=I;let{runnerResult:g}=await i("inference",()=>Ie({cliPath:r,config:e,context:d,runner:x.runner,persistSteps:h,aiGateway:l}));await G(e.id,e.sessionId,{steps:[{title:"Building and deploying the preview"}]});let S=await i("deploy",()=>qe({cliPath:r,config:e,context:d,result:g.result,filter:s})),v=g,N=[];if(S.hasChanges&&S.deployError){N.push(Ze(S.deployError));let f=1;for(;f<=ve&&!S.previewInfo;)jt.log(`Deploy attempt had errors. Retrying. ${f}/${ve}`),await Mt(Ut(),"deploy-stage",async T=>{T?.setAttributes({"stage.attempt":f});let{runnerResult:p}=await i(`inference-retry-${f}`,()=>Ie({cliPath:r,config:e,context:d,runner:x.runner,persistSteps:h,aiGateway:l,buildErrors:N,priorAgentSessionId:g.agentSessionId}));v={...p,steps:[...v.steps||[],...p.steps||[]],duration:(v.duration||0)+(p.duration||0)},S=await i(`deploy-retry-${f}`,()=>qe({cliPath:r,config:e,context:d,result:p.result,filter:s})),S.deployError&&N.push(S.deployError),f++});f>ve&&!S.previewInfo&&(c=new Error(`Deploy validation failed after ${ve} attempts`))}let{diff:R,resultDiff:_,previewInfo:A,diffBinary:w,resultDiffBinary:y}=S;if(await i("cleanup",()=>kt({config:e,diff:R,result:v.result,duration:v.duration,resultDiff:_,diffBinary:w,resultDiffBinary:y,previewInfo:A}),q.timeUnits.minutes(10)),c)throw c;process.env.NETLIFY_LOCAL_MODE||(await u?.(),await wt())})}catch(c){jt.error("Got error while running pipeline",c),await u?.();let l=c instanceof Error&&c.message;throw await G(e.id,e.sessionId,{result:l||"Encountered error when running agent",state:"error"}),c}finally{await Qr()}};export{Ds as runPipeline};
|
|
134
134
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@netlify/agent-runner-cli",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "1.48.
|
|
4
|
+
"version": "1.48.1",
|
|
5
5
|
"description": "CLI tool for running Netlify agents",
|
|
6
6
|
"main": "./dist/index.js",
|
|
7
7
|
"types": "./dist/index.d.ts",
|
|
@@ -73,8 +73,8 @@
|
|
|
73
73
|
},
|
|
74
74
|
"dependencies": {
|
|
75
75
|
"@anthropic-ai/claude-code": "2.0.42",
|
|
76
|
-
"@google/gemini-cli": "0.
|
|
77
|
-
"@netlify/otel": "^
|
|
76
|
+
"@google/gemini-cli": "0.15.4",
|
|
77
|
+
"@netlify/otel": "^5.0.0",
|
|
78
78
|
"@opentelemetry/exporter-trace-otlp-grpc": "^0.57.0",
|
|
79
79
|
"execa": "^8.0.0",
|
|
80
80
|
"get-port": "^5.1.1",
|