@netlify/agent-runner-cli 1.24.0 → 1.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +25 -25
- package/dist/index.js +28 -28
- package/package.json +2 -1
package/dist/bin.js
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`),o=[],r=-1,n=0;for(;n<t.length;){let i=t[n].slice(0,500).toLowerCase();if(
|
|
2
|
+
import Ke from"process";import Kt from"minimist";import{createRequire as jt}from"module";import{createTracerProvider as Je}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as _e}from"@netlify/otel/opentelemetry";import{withActiveSpan as Xe}from"@netlify/otel";import{OTLPTraceExporter as We}from"@opentelemetry/exporter-trace-otlp-grpc";var Ee=(e,t)=>Je({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new _e(new se),new _e(new We)]});function X(e,t,o){return console.log(`\u23F3 TRACE: ${t} starting...`),Xe(e,t,o)}var se=class{export(t,o){for(let r of t)this.logSpan(r);o({code:1})}async shutdown(){}forceFlush(){return Promise.resolve()}logSpan(t){let o=(t.endTime[0]-t.startTime[0])*1e3+(t.endTime[1]-t.startTime[1])/1e6,r=t.attributes,n=[];for(let[i,l]of Object.entries(r))i.includes("duration")&&typeof l=="number"?n.push(`${i}=${l.toFixed(2)}ms`):n.push(`${i}=${l}`);let s=t.status?.code===2?"\u274C":"\u2705",a=n.length>0?` [${n.join(", ")}]`:"";console.log(`${s} TRACE: ${t.name} completed in ${o.toFixed(2)}ms${a}`),t.status?.code===2&&t.status.message&&console.log(` \u274C Error: ${t.status.message}`)}};var ze=["error","failed","exception","fatal","panic","abort","crash"];function ye(e){let t=e.split(`
|
|
3
|
+
`),o=[],r=-1,n=0;for(;n<t.length;){let i=t[n].slice(0,500).toLowerCase();if(ze.some(p=>i.includes(p))){let p=Math.max(0,n-10,r+1),c=Math.min(t.length-1,n+20),d=[];for(let h=p;h<=c;h++)d.push(t[h]);o.push(d.join(`
|
|
4
4
|
`)),r=c,n=c+1}else n++}if(o.length===0)return e;let s=o.map((a,i)=>`<extracted_error_chunk order="${i+1}">
|
|
5
5
|
${a}
|
|
6
6
|
</extracted_error_chunk>`).join(`
|
|
7
7
|
|
|
8
|
-
`);return s.length>e.length*.8?e:s}import ne from"process";import{getTracer as
|
|
9
|
-
`).filter(n=>!
|
|
10
|
-
`).forEach(a=>{let i=a.match(/\?\? (.+?)\.log$/)?.[1];i&&r.push(`:!${i}.log`)}),r};import
|
|
11
|
-
`))return;let
|
|
12
|
-
`).filter(Boolean).map(f=>{try{return JSON.parse(f)}catch{console.log("Could not parse line",f)}return null}).filter(Boolean);
|
|
8
|
+
`);return s.length>e.length*.8?e:s}import ne from"process";import{getTracer as wt}from"@netlify/otel";import W from"process";var ie=W.env.NETLIFY_API_URL,ae=W.env.NETLIFY_API_TOKEN,z=async(e,t={})=>{if(!ie||!ae)throw new Error("No API URL or token");let o=new URL(e,ie),r={...t,headers:{...t.headers,Authorization:`Bearer ${ae}`}};W.env.AGENT_RUNNERS_DEBUG==="true"&&(r.headers["x-nf-debug-logging"]="true"),t.json&&(r.headers||={},r.headers["Content-Type"]="application/json",r.body=JSON.stringify(t.json));let n=await fetch(o,r),s=n.ok&&n.status<=299;if(W.env.AGENT_RUNNERS_DEBUG==="true"&&(console.log(`[DEBUG] Response headers for ${o}:`),n.headers.forEach((i,l)=>{console.log(` ${l}: ${i}`)})),s||console.error(`Got status ${n.status} for request ${o}`),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},Te=e=>{console.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(ie=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(ae=e.constants.NETLIFY_API_TOKEN)},Z=(e,t)=>z(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),K=(e,t,o)=>z(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:o});var xe=(e,t)=>z(`/api/v1/agent_runners/${e}/sessions/${t}`),Ne=(e,t,o)=>z(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":o}});var we=async({netlify:e,config:t})=>{let o,r,n,s,a=e.constants?.SITE_ID;if(!a)throw new Error("No site id");let i=async()=>{clearTimeout(n),console.log("Requesting AI gateway information");let l=await Ne(a,t.id,t.sessionId);if({token:o,url:s}=l,r=l.expires_at?l.expires_at*1e3:void 0,console.log("Got AI gateway information",{token:!!o,expiresAt:r,url:s}),r){let p=r-Date.now()-6e4;p>0&&(n=setTimeout(()=>{i()},p))}};return await i(),{get url(){return s},get token(){return o}}};import Ie from"process";import{execa as Ze,execaCommand as ar}from"execa";var Qe={preferLocal:!0},Ae=(e,t,o)=>{let[r,n]=et(t,o),s={...Qe,...n},a=Ze(e,r,s);return tt(a,s),a};var et=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},tt=(e,t)=>{t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0||(e.stdout?.pipe(Ie.stdout),e.stderr?.pipe(Ie.stderr))};var Q="netlify-agent-runner-context.md",le="task-history",ce="netlify-context",D=".netlify",$="other",L="personal";var U="enterprise",j="free",Ce=[L,"pro",U,j];var rt=e=>new Promise(t=>{setTimeout(t,e)}),Re=(e,t=3e3)=>{let o=!1,r=null,n=[],s=null,a=(...i)=>{if(o)return r=i,new Promise(c=>{n.push(c)});o=!0;let l,p=new Promise(c=>{l=c});return s=(async()=>{await Promise.resolve();let c=await e(...i);for(l(c);;){if(await rt(t),!r)return o=!1,s=null,c;let d=r,h=n;r=null,n=[],c=await e(...d),h.forEach(E=>{E(c)})}})(),p};return a.flush=async()=>{if((o||r)&&s)return await s,a.flush()},a},ee=(e,t,o=!1)=>{let r=null,n=null,s=null,a=function(...i){n=i,s=this;let l=o&&!r;clearTimeout(r),r=setTimeout(()=>{r=null,o||(e.apply(s,n),n=null,s=null)},t),l&&(e.apply(s,n),n=null,s=null)};return a.cancel=()=>{clearTimeout(r),r=null,n=null,s=null},a.flush=()=>{if(r){clearTimeout(r);let i=n,l=s;r=null,n=null,s=null,e.apply(l,i)}},a},te=(e,t=!0)=>{if(e)try{return JSON.parse(e)}catch(o){t&&console.error("Could not parse JSON",o)}},ve=(e,t)=>{let n=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let i=`--${t}${n}`;if(i.length>55)return"";let l=60-i.length;if(l<=0)return"";if(l>=s.length+6){let p=Math.min(l-s.length,e.length);return`${s}${e.slice(0,p)}`}return e.slice(0,l)},ot=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!Ce.some(t=>t in e),Se=()=>{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(([o,r])=>{if(r){let n=`NETLIFY_FF_AGENT_RUNNER_${o.toUpperCase()}_VERSION`;try{let s=JSON.parse(r);ot(s)&&(e[o]=s)}catch(s){let i=s instanceof SyntaxError?"Invalid JSON":s.message;console.error(`Could not parse ${o} model version override from ${n}: ${i}`)}}}),e};import{Buffer as Pe}from"buffer";var Oe=async({config:e,netlify:t})=>{let o=await st(t),{hasChanges:r}=o,{status:n}=o;if(!r)return{hasChanges:!1};let s=await it(t,n);await t.utils.run("git",["add",".",...s]);let i=(await t.utils.run("git",["diff","--staged"])).stdout;if(r=!!i,!r)return{hasChanges:!1};let p=(await t.utils.run("git",["diff","--staged","--binary"])).stdout,c,d;if(e.sha){await t.utils.run("git",["commit","-m","Agent runner"]),c=(await t.utils.run("git",["diff",e.sha,"HEAD"])).stdout;let _=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"])).stdout;c!==_&&(d=Pe.from(_).toString("base64"))}let h={hasChanges:!0,diff:i,resultDiff:c};return i!==p&&(h.diffBinary=Pe.from(p).toString("base64")),d&&(h.resultDiffBinary=d),h},nt=["?? mise.toml",/\?\? .+?\.log/],st=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
|
|
9
|
+
`).filter(n=>!nt.some(s=>s instanceof RegExp?s.test(n):n===s))).length!==0,status:t.stdout}};var ke=async e=>{let{stdout:t}=await e.utils.run("git",["rev-parse","HEAD"]);return t.trim()},Fe=async e=>{let{stdout:t}=await e.utils.run("git",["rev-list","--max-parents=0","HEAD"]);return t.trim()},it=async(e,t="")=>{let o=[".netlify","mise.toml","node_modules"],r=[],n=o.map(async a=>{try{return await e.utils.run("git",["check-ignore","-v",a]),null}catch{return`:!${a}`}});return(await Promise.all(n)).forEach(a=>{a&&r.push(a)}),t.split(`
|
|
10
|
+
`).forEach(a=>{let i=a.match(/\?\? (.+?)\.log$/)?.[1];i&&r.push(`:!${i}.log`)}),r};import at from"fs/promises";import lt from"os";import re from"path";import Y from"process";var ct=({catchError:e,runCmd:t,error:o,result:r,runnerName:n})=>(console.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!o,hadExistingResult:!!r,resultLength:r?r.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),r?(console.log("Preserving existing result despite catch handler being triggered"),o?{error:o,result:r}:{error:"Process completed with errors but result was captured",result:r}):(console.log("Setting result to undefined because no valid result was captured"),{error:o||`${n} failed`,result:void 0}));async function ue({config:e,netlify:t,persistSteps:o,sendSteps:r,aiGateway:n}){let{accountType:s,prompt:a,modelVersionOverrides:i}=e,{model:l}=e;if(n){let{token:g,url:m}=n;if(!g||!m)throw new Error("No token or url provided from AI Gateway");let f=ut[s];if(!f)throw new Error(`Claude is not supported for the account type ${s}`);if(l&&!f?.models?.[l])throw new Error(`${l} is not supported for account type ${s}`);if(i?.claude){let u=i?.claude?.[s];u&&(l=u)}Y.env.ANTHROPIC_API_KEY=g,Y.env.ANTHROPIC_BASE_URL=m}else if(!Y.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let p=[],c=[],d=[],h={},E=0,y=0,_,T,P=re.join(Y.cwd(),"node_modules"),v=[re.join(Y.env.NODE_PATH||P,".bin/claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...l?["--model",l]:[],"-p",a],S=`${Y.env.NVM_BIN}/node`;console.log(`Running ${S} ${v.join(" ")}`);let C=t.utils.run(S,v,{all:!0,env:Y.env});C.stdin?.end();let x=ee(()=>{o?.({steps:p,duration:y}),r?.({steps:c,duration:y}),c=[]},250),w=(g,m)=>{g.id=E,E+=1,d.push(g),p.push(g),c.push(g),m||x.flush(),x(),m&&x.flush()},N="";return C.all.on("data",g=>{if(N+=g.toString(),!g.includes(`
|
|
11
|
+
`))return;let m=N.split(`
|
|
12
|
+
`).filter(Boolean).map(f=>{try{return JSON.parse(f)}catch{console.log("Could not parse line",f)}return null}).filter(Boolean);N="",m.forEach(f=>{Array.isArray(f?.message?.content)?f.message.content.forEach(u=>{switch(u.type){case"text":{u.text&&w({message:u.text});break}case"image":{typeof u.source=="object"&&u.source.type==="base64"&&u.source.media_type?w({message:``}):console.log(`Unsupported image type ${u.source?.type}`,u.source);break}case"tool_use":{if(u.name==="Task"){let I=u.input?.description&&`\`${u.input.description}\``;w({title:[u.name,I].filter(Boolean).join(" ")})}else h[u.id]=u;x.flush();break}case"tool_result":{let I=h[u.tool_use_id],F;if(I){let B=I.input?.file_path&&re.relative(Y.cwd(),I.input.file_path),A=B&&`\`${B}\``;F=[I.name,A].filter(Boolean).join(" ")}let M=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(I?.name),b;if(typeof u.content=="string")b=u.content;else if(Array.isArray(u.content)){let B=[];u.content.forEach(A=>{A?.type==="text"&&typeof A.text=="string"?B.push(A.text):A?.type==="image"&&typeof A.source=="object"?A.source.type==="base64"&&A.source.media_type?B.push(``):console.log(`Unsupported image type ${A.source.type}`,A.source):console.log(`Unsupported block type ${A?.type}`)}),b=B.join(`
|
|
13
13
|
|
|
14
14
|
`)}M&&b&&(b=`\`\`\`
|
|
15
15
|
${b.trim()}
|
|
16
|
-
\`\`\``),
|
|
17
|
-
`))return;let
|
|
18
|
-
`).filter(Boolean).map(
|
|
19
|
-
`):
|
|
20
|
-
`))}),
|
|
16
|
+
\`\`\``),w({title:F,message:b},!0);break}case"thinking":{u.thinking&&w({title:"Thinking",message:u.thinking},!0);break}default:console.log(`Message content type is not supported ${u.type}`,u)}}):f?.type==="result"&&(y=f.duration_ms,f.is_error?T=f.result:_=f.result,[d,p,c].forEach(u=>{u[u.length-1]?.message===_&&u.pop()}))})}),await C.catch(g=>{({error:T,result:_}=ct({catchError:g,runCmd:C,error:T,result:_,runnerName:"Claude"}))}),x.flush(),{steps:d,duration:y,result:_,error:T}}var be=async()=>{let e=re.join(lt.homedir(),".claude");await at.rm(e,{recursive:!0,force:!0})},ut={[U]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:64e3},"claude-3-haiku-20240307":{maxTokens:4096},"claude-opus-4-20250514":{maxTokens:32e3},"claude-sonnet-4-20250514":{maxTokens:64e3}}},pro:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[L]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[j]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}},[$]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}}};import pt from"fs/promises";import dt from"os";import pe from"path";import V from"process";var ft=({catchError:e,runCmd:t,error:o,result:r,runnerName:n})=>(console.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!o,hadExistingResult:!!r,resultLength:r?r.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),r?(console.log("Preserving existing result despite catch handler being triggered"),o?{error:o,result:r}:{error:"Process completed with errors but result was captured",result:r}):(console.log("Setting result to undefined because no valid result was captured"),{error:o||`${n} failed`,result:void 0}));async function de({config:e,netlify:t,persistSteps:o,sendSteps:r,aiGateway:n}){let{accountType:s,prompt:a,modelVersionOverrides:i}=e,{model:l}=e;if(n){let{token:x,url:w}=n;if(!x||!w)throw new Error("No token or url provided from AI Gateway");let N=mt[s];if(!N)throw new Error(`Codex is not supported for the account type ${s}`);if(l&&!N?.models?.[l])throw new Error(`${l} is not supported for account type ${s}`);if(i?.codex){let g=i?.codex?.[s];g&&(l=g)}V.env.OPENAI_API_KEY=x,V.env.OPENAI_BASE_URL=w}else if(!V.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let p=[],c=[],d={},h=0,E=0,y,_,T=pe.join(V.cwd(),"node_modules"),P=[pe.join(V.env.NODE_PATH||T,".bin/codex"),"--approval-mode","full-auto",n?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...l?["--model",l]:[],"-q",a].filter(Boolean),v=`${V.env.NVM_BIN}/node`;console.log(`Running ${v} ${P.join(" ")}`);let S=t.utils.run(v,P,{all:!0,env:{...V.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),C="";return S.all.on("data",x=>{if(C+=x.toString(),!x.includes(`
|
|
17
|
+
`))return;let w=C.toString().split(`
|
|
18
|
+
`).filter(Boolean).map(m=>{try{return JSON.parse(m)}catch{console.log("Could not parse line",m)}return null}).filter(Boolean);C="";let N=[],g=!1;w.forEach(m=>{if(m?.duration_ms&&(E=m.duration_ms,g=!0),m?.type==="local_shell_call")d[m.call_id]=m;else if(m?.type==="local_shell_call_output"){let f=gt(d[m.call_id],m);f.id=h,h+=1,f&&(c.push(f),p.push(f),N.push(f),g=!0)}else m?.type==="message"&&m.role==="assistant"?y=m.content.map(f=>f.text).join(`
|
|
19
|
+
`):m?.type==="message"&&m.role==="system"&&(_=m.content.map(f=>f.text).join(`
|
|
20
|
+
`))}),g&&(o?.({steps:p,duration:E}),r?.({steps:N,duration:E}))}),await S.catch(x=>{({error:_,result:y}=ft({catchError:x,runCmd:S,error:_,result:y,runnerName:"Codex"}))}),{steps:c,duration:E,result:y,error:_}}var De=async()=>{let e=pe.join(dt.homedir(),".codex");await pt.rm(e,{recursive:!0,force:!0})},mt={[U]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},o1:{maxTokens:1e5},"o1-mini":{maxTokens:65536},"o3-mini":{maxTokens:1e5},"gpt-image-1":{},"dall-e-2":{},"dall-e-3":{}}},[L]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768}}},pro:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768}}},[j]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},"o3-mini":{maxTokens:16e3}}},[$]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},"o3-mini":{maxTokens:16e3}}}},ht=new Set(["bash","-lc"]),gt=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let o=e.action?.command?.filter(s=>!ht.has(s)),r=o?`Running \`${o.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
|
|
21
21
|
${n.trim()}
|
|
22
|
-
\`\`\``)}catch(s){console.error("Could not decode outputMsg",s,t.output)}return{title:r,message:n}};import
|
|
23
|
-
`))return;let
|
|
24
|
-
`).filter(Boolean).map(f=>{try{if(f.startsWith("[API Error")){let u=f.match(/\[api error: (.+?)]$/i)?.[1];return{type:"error",value:te(u,!1)?.error?.message||u||"Gemini encountered error"}}return JSON.parse(f)}catch{}return null}).filter(Boolean);
|
|
22
|
+
\`\`\``)}catch(s){console.error("Could not decode outputMsg",s,t.output)}return{title:r,message:n}};import _t from"fs/promises";import Et from"os";import oe from"path";import G from"process";var yt=({catchError:e,runCmd:t,error:o,result:r,runnerName:n})=>(console.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!o,hadExistingResult:!!r,resultLength:r?r.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),r?(console.log("Preserving existing result despite catch handler being triggered"),o?{error:o,result:r}:{error:"Process completed with errors but result was captured",result:r}):(console.log("Setting result to undefined because no valid result was captured"),{error:o||`${n} failed`,result:void 0})),Tt={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 fe({config:e,netlify:t,persistSteps:o,sendSteps:r,aiGateway:n}){let{accountType:s,prompt:a,modelVersionOverrides:i}=e,{model:l}=e;if(n){let{token:g,url:m}=n;if(!g||!m)throw new Error("No token or url provided from AI Gateway");let f=xt[s];if(!f)throw new Error(`Gemini is not supported for the account type ${s}`);if(l&&!f?.models?.[l])throw new Error(`${l} is not supported for account type ${s}`);if(i?.gemini){let u=i?.gemini?.[s];u&&(l=u)}G.env.GEMINI_API_KEY=g,G.env.GOOGLE_GEMINI_BASE_URL=m}else if(!G.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let p=[],c=[],d=[],h={},E=0,y=0,_,T,P=oe.join(G.cwd(),"node_modules"),v=[oe.join(G.env.NODE_PATH||P,".bin/gemini"),...l?["--model",l]:[],"--yolo","-p",a],S=`${G.env.NVM_BIN}/node`;console.log(`Running ${S} ${v.join(" ")}`);let C=t.utils.run(S,v,{all:!0,env:G.env});C.stdin?.end();let x=ee(()=>{o?.({steps:p,duration:y}),r?.({steps:c,duration:y}),c=[]},250),w=(g,m)=>{g.id=E,E+=1,d.push(g),p.push(g),c.push(g),m||x.flush(),x(),m&&x.flush()},N="";return C.all.on("data",g=>{if(N+=g.toString(),!g.includes(`
|
|
23
|
+
`))return;let m=N.toString().split(`
|
|
24
|
+
`).filter(Boolean).map(f=>{try{if(f.startsWith("[API Error")){let u=f.match(/\[api error: (.+?)]$/i)?.[1];return{type:"error",value:te(u,!1)?.error?.message||u||"Gemini encountered error"}}return JSON.parse(f)}catch{}return null}).filter(Boolean);N="",m.forEach(f=>{switch(f.type){case"thought":{let u=f.value;w({title:u?.subject??"Thinking...",message:u?.description},!0);break}case"content":{f.value&&w({message:f.value});break}case"tool_call_request":{let u=f.value,I=Tt[u.name]??u.name,F=u.args?.path||u.args?.absolute_path,M=F&&oe.relative(G.cwd(),F),b=u.args?.command,A={title:[I,M&&`\`${M}\``,b&&`\`${b}\``].filter(Boolean).join(" ")};h[u.callId]=A,x.flush();break}case"tool_result":{let u=f.value,I=h[u.callId];if(I){let F=[u.resultDisplay,u.responseParts?.functionResponse?.response?.output].find(M=>typeof M=="string"&&M);F&&(I.message=`\`\`\`
|
|
25
25
|
${F.trim()}
|
|
26
|
-
\`\`\``),
|
|
26
|
+
\`\`\``),w(I,!0)}break}case"result":{y=f.duration_ms,_=f.value,[d,p,c].forEach(u=>{u[u.length-1]?.message===_&&u.pop()});break}case"error":{T=f.value;break}case"finished":break;default:{console.warn("Unhandled message type:",f.type);break}}})}),await C.catch(g=>{({error:T,result:_}=yt({catchError:g,runCmd:C,error:T,result:_,runnerName:"Gemini"}))}),x.flush(),{steps:d,duration:y,result:_,error:T}}var $e=async()=>{let e=oe.join(Et.homedir(),".gemini");await _t.rm(e,{recursive:!0,force:!0})},xt={[U]:{models:{"gemini-1.5-flash":{maxTokens:8192},"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-1.5-pro":{maxTokens:8192},"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:65536},"gemini-2.5-flash-lite":{maxTokens:65536},"gemini-2.5-pro":{maxTokens:65536},"imagen-4.0-generate-001":{},"veo-3.0-generate-preview":{}}},pro:{models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[L]:{models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[j]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}},[$]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}}};var Nt={codex:{runner:de,clean:De},claude:{runner:ue,clean:be},gemini:{runner:fe,clean:$e}},Le=Nt;var Ue=async({config:e,apiThrottle:t,apiToken:o})=>{let r=wt();return X(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});let a=Le[e.runner];if(!a)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let i=It({apiToken:o});Te(i);let l=e.useGateway?await we({netlify:i,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!l}),e.validateAgent&&e.errorLogsPath&&n?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let p=Re(({steps:h=[],duration:E})=>{let y=[...h];return h.length=0,K(e.id,e.sessionId,{steps:y,duration:E})},t),c;e.hasRepo?e.sha?(c=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(c=await ke(i),await Z(e.id,{sha:c}),n?.setAttributes({"init.sha.source":"current_commit"})):(c=await Fe(i),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let d=performance.now()-s;return n?.setAttributes({"init.sha":c||"unknown","init.duration.ms":d,"init.status":"success"}),{aiGateway:l,context:i,persistSteps:p,runner:a,sha:c}})},It=({apiToken:e})=>({constants:{NETLIFY_API_HOST:ne.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||ne.env.NETLIFY_API_TOKEN,SITE_ID:ne.env.SITE_ID,FUNCTIONS_DIST:ne.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:Ae}});import At from"crypto";import q from"fs/promises";import O from"path";import k from"process";var Ct=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:k.env.NETLIFY_TEAM_ID,userId:k.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:k.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},Rt=()=>{let e=Object.keys(k.env).sort();return{nodeVersion:k.version,envVars:e}},vt=10,St=async e=>{let{name:t,ext:o}=O.parse(e),r=e,n=O.join(k.cwd(),D,r),s=0;for(;await Pt(n);){if(s>=vt)throw new Error("Failed to generate context file");r=`${t}-${At.randomUUID().slice(0,5)}${o}`,n=O.join(k.cwd(),D,r),s+=1}return r},Pt=async e=>{try{return await q.access(e),!0}catch{return!1}},Ot=async()=>{try{console.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 console.warn("Invalid response structure: missing or invalid consumers array"),null;let o=t.consumers.find(r=>r&&typeof r=="object"&&r.key==="catchall-consumer");return o?!o.contextScopes||typeof o.contextScopes!="object"?(console.warn("Catchall consumer missing or invalid contextScopes"),null):o:(console.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?console.warn("Netlify features context request timed out"):console.warn("Failed to fetch Netlify features context:",e.message),null}},kt=async(e,t)=>{try{let o=await fetch(e,{signal:AbortSignal.timeout(1e4)});if(!o.ok)throw new Error(`Failed to fetch ${e}: ${o.status} ${o.statusText}`);let r=await o.text();return await q.writeFile(t,r,"utf-8"),!0}catch(o){return o.name==="AbortError"?console.warn(`Download timeout for ${e}`):console.warn(`Failed to download context file ${e}:`,o.message),!1}},Ft=async()=>{let e=await Ot();if(!e)return[];let t=O.join(k.cwd(),D,ce);await q.mkdir(t,{recursive:!0});let o=Object.entries(e.contextScopes).map(async([s,a])=>{if(!a||typeof a!="object"||!a.endpoint||!a.scope)return console.warn(`Invalid scope data for ${s}, skipping...`),null;let i=`${s}.md`,l=O.join(t,i),p=O.join(D,ce,i);return console.log(`Downloading ${a.scope} context...`),await kt(a.endpoint,l)?(console.log(`Downloaded: ${p}`),{scope:a.scope,path:p,key:s}):null});return(await Promise.all(o)).filter(s=>s!==null)},je=async({cliPath:e,netlify:t,config:o})=>{let r=Ct(t),n=Rt(),s=await St(Q),a=O.join(k.cwd(),D);await q.mkdir(a,{recursive:!0});let i=O.join(D,s),l=O.join(k.cwd(),i),p=`# Agent Context
|
|
27
27
|
|
|
28
28
|
In Netlify documentation and interfaces, the terms "site" and "project" refer to the same thing.
|
|
29
29
|
|
|
@@ -55,7 +55,7 @@ ${o.siteContext.filter(d=>d.site_context).map(d=>typeof d.site_context=="string"
|
|
|
55
55
|
|
|
56
56
|
`)}
|
|
57
57
|
</project_guidelines>
|
|
58
|
-
`);let c=await
|
|
58
|
+
`);let c=await Ft();if(c.length>0&&(p+=`
|
|
59
59
|
# Netlify Features Context
|
|
60
60
|
|
|
61
61
|
If the user request is explicitly related to a specific Netlify feature (e.g., Forms, Identity, Functions, etc.), you MUST review the relevant documentation below in addition to reviewing the project files.
|
|
@@ -69,7 +69,7 @@ Refer to these files when working with specific Netlify features.
|
|
|
69
69
|
Additional Documentation Resources
|
|
70
70
|
- Netlify Docs: https://docs.netlify.com
|
|
71
71
|
- LLM Resources Index: https://docs.netlify.com/llms.txt
|
|
72
|
-
`,o.sessionHistoryContext?.length){let d=
|
|
72
|
+
`,o.sessionHistoryContext?.length){let d=O.join(k.cwd(),D,le);await q.mkdir(d,{recursive:!0});let h=await Promise.all(o.sessionHistoryContext.map(async(E,y)=>{let _=y+1,T=`attempt-${_}.md`,P=O.join(d,T),v=O.join(D,le,T),S=`# Task History - Attempt ${_}
|
|
73
73
|
|
|
74
74
|
## Request - what the user asked for
|
|
75
75
|
${E.request}
|
|
@@ -79,18 +79,18 @@ ${E.request}
|
|
|
79
79
|
## Response - what the agent replied with after its work
|
|
80
80
|
|
|
81
81
|
${E.response}
|
|
82
|
-
`;return await q.writeFile(
|
|
82
|
+
`;return await q.writeFile(P,S,"utf-8"),console.log(`Created history file: ${v}`),v}));p+=`# History of prior work on this task
|
|
83
83
|
|
|
84
84
|
You MUST review ALL of the files below as context to understand the context of previous attempts. Use this information to continue the discussion appropriately.
|
|
85
85
|
|
|
86
86
|
${h.map(E=>`- ${E}`).join(`
|
|
87
87
|
`)}
|
|
88
|
-
`}return await q.writeFile(l,p,"utf-8"),console.log(`Generated agent context document at: ${l}`),i},
|
|
88
|
+
`}return await q.writeFile(l,p,"utf-8"),console.log(`Generated agent context document at: ${l}`),i},Ye=e=>`The build is currently failing after your changes.
|
|
89
89
|
Your task is to analyze and fix the build errors.
|
|
90
90
|
Don't apply techniques of reverting changes. Apply fixes related to errors.
|
|
91
91
|
Don't try to run build by yourself. Just fix the errors.
|
|
92
92
|
|
|
93
|
-
${e}`;var
|
|
93
|
+
${e}`;var Ge=(e={})=>`
|
|
94
94
|
Check for errors and validate the fix
|
|
95
95
|
|
|
96
96
|
${e.errorLogsPath?`Error Check Process:
|
|
@@ -114,16 +114,16 @@ ${e}`;var Ye=(e={})=>`
|
|
|
114
114
|
VALIDATION_RESULT: PASS {"checks": ["error_logs"]}
|
|
115
115
|
or
|
|
116
116
|
VALIDATION_RESULT: FAIL {"checks": ["error_logs"], "errors": ["<errors>"]}
|
|
117
|
-
`;var
|
|
117
|
+
`;var bt=(e=Q)=>`Use ${e} to understand the Netlify project context and resources. It also contains history of previous conversations. READ ALL OF IT. Make sure to read it first. Never reveal, cite, or paraphrase private context.`,Dt=async({cliPath:e,config:t,netlify:o})=>{let r=await je({cliPath:e,netlify:o,config:t});return{context:bt(r)}},$t=({config:e})=>{let t=[];return e?.validateAgent&&t.push(Ge(e)),t},Me=async({cliPath:e,config:t,netlify:o,buildErrorContext:r}={})=>{let{context:n}=await Dt({cliPath:e,config:t,netlify:o}),s;s=[...$t({config:t})],r&&(s=[...s,Ye(r)]);let a=[];return n&&a.push(n),t.prompt&&a.push("New user request comes in the <new_request> tag.",`<new_request>${t.prompt}</new_request>`),s?.length&&a.push(s.join(`
|
|
118
118
|
|
|
119
119
|
`)),{prompt:a.join(`
|
|
120
120
|
|
|
121
|
-
`)}};var me=async({cliPath:e,config:t,context:o,buildErrors:r,runner:n,persistSteps:s,aiGateway:a})=>{let{prompt:i}=await
|
|
121
|
+
`)}};var me=async({cliPath:e,config:t,context:o,buildErrors:r,runner:n,persistSteps:s,aiGateway:a})=>{let{prompt:i}=await Me({cliPath:e,config:t,buildErrorContext:Lt(r),netlify:o}),l={...t,prompt:i},p=await n({aiGateway:a,config:l,netlify:o,persistSteps:s});if(p.error)throw console.error("Runner failed",{stepsCount:p.steps.length,duration:p.duration,error:p.error}),new Error(p.error);return{runnerResult:p}},Lt=e=>!e||e.length===0?"":`
|
|
122
122
|
Deploy failed failed. Here are the errors to review on the latest build:
|
|
123
123
|
|
|
124
124
|
Below are all of the logs with potential issues that we extracted. Some of them may be false positives, discern them carefully and ensure fixes are relevant.
|
|
125
125
|
|
|
126
126
|
${e.pop()}
|
|
127
|
-
`;import
|
|
128
|
-
Preview deploy created successfully:`,{deployId:c.deploy_id,deployUrl:c.deploy_url,siteId:c.site_id});let d={deployId:c.deploy_id,previewUrl:c.deploy_url,logsUrl:c.logs,siteId:c.site_id};return t||(d.sourceZipFilename=c.source_zip_filename),d}catch(i){throw console.error("Failed to create preview deploy via CLI:",i),i}};var he=async({cliPath:e,config:t,context:o,result:r,filter:n})=>{let s=await
|
|
127
|
+
`;import Ut from"process";var Be=async({netlify:e,hasRepo:t,skipBuild:o,message:r="Agent Preview",deploySubdomain:n,cliPath:s,filter:a})=>{try{let i=["deploy","--message",`"${r}"`,"--json","--draft","--verbose"];t||(console.log("Deploy: Uploading source zip"),i.push("--upload-source-zip")),n&&i.push("--alias",n),a&&i.push("--filter",a),o?(console.log("Deploy: Skipping build"),i.push("--no-build")):i.push("--context","deploy-preview");let l=s||"netlify";console.log(`Running: ${l} ${i.join(" ")}`);let p=await e.utils.run(l,i,{stdio:["ignore","pipe","pipe"]}),c=JSON.parse(p.stdout.trim());console.log(`
|
|
128
|
+
Preview deploy created successfully:`,{deployId:c.deploy_id,deployUrl:c.deploy_url,siteId:c.site_id});let d={deployId:c.deploy_id,previewUrl:c.deploy_url,logsUrl:c.logs,siteId:c.site_id};return t||(d.sourceZipFilename=c.source_zip_filename),d}catch(i){throw console.error("Failed to create preview deploy via CLI:",i),i}};var he=async({cliPath:e,config:t,context:o,result:r,filter:n})=>{let s=await Oe({config:t,netlify:o});if(!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:i,diffBinary:l,resultDiffBinary:p}=s,c=!0;console.log("Preview deploy condition check:",{resultUndefined:r===void 0,resultType:typeof r,hasChanges:c,wouldCreatePreview:r!==void 0&&c});let d=null;if(r!==void 0&&c)try{let h;try{let E=await xe(t.id,t.sessionId);E?.title&&(h=E.title)}catch(E){console.warn("Failed to fetch session title, using fallback message:",E.message)}d=await Be({cliPath:e,netlify:o,hasRepo:t.hasRepo,message:h,skipBuild:!1,deploySubdomain:ve(t.id,Ut.env.SITE_NAME),filter:n})}catch(h){return console.warn("Failed to create preview deploy (continuing with agent run):",h),{diff:a,resultDiff:i,hasChanges:c,previewInfo:null,diffBinary:l,resultDiffBinary:p,deployError:h instanceof Error?h.message:String(h)}}return console.log("Git status",{hasDiff:!!a,hasChanges:c}),{diff:a,resultDiff:i,hasChanges:c,previewInfo:d,diffBinary:l,resultDiffBinary:p}};var He=async({config:e,diff:t,result:o,duration:r,resultDiff:n,diffBinary:s,resultDiffBinary:a,previewInfo:i})=>{let l={result_diff:t,result:o||"Done",duration:r,result_diff_binary:s};return i&&i.deployId&&(l.deploy_id=i.deployId),i&&i.sourceZipFilename&&(l.result_zip_file_name=i.sourceZipFilename),n||a?(console.log("Updating total agent result diff"),await Z(e.id,{result_diff:n,result_diff_binary:a})):console.log("No total result diff, not updating"),console.log("Updated agent runner with result"),await K(e.id,e.sessionId,l),{sessionUpdate:l}};import{getTracer as Yt}from"@netlify/otel";var Gt=jt(import.meta.url),Mt=Gt("../package.json"),ge=3,Ve=async({config:e,apiToken:t,cliPath:o="netlify",cwd:r,errorLogsPath:n,filter:s})=>{let a;try{await Ee(Mt.version,e.id);let i=Yt(),l,{aiGateway:p,context:c,persistSteps:d,runner:h,sha:E}=await Ue({config:e,apiToken:t,cliPath:o,cwd:r,errorLogsPath:n,filter:s});a=h.clean,e.sha=E;let{runnerResult:y}=await me({cliPath:o,config:e,context:c,runner:h.runner,persistSteps:d,aiGateway:p}),_=await he({cliPath:o,config:e,context:c,result:y.result,filter:s}),T=y,P=[];if(_.hasChanges&&_.deployError){console.log("Deploy validation enabled, starting deploy-fix iteration process"),P.push(ye(_.deployError));let N=1;for(;N<=ge&&!_.previewInfo;)await X(i,"stage-deploy",async g=>{g?.setAttributes({"stage.attempt":N});let{runnerResult:m}=await me({cliPath:o,config:e,context:c,runner:h.runner,persistSteps:d,aiGateway:p,buildErrors:P});T={...m,steps:[...T.steps||[],...m.steps||[]],duration:(T.duration||0)+(m.duration||0)},_=await he({cliPath:o,config:e,context:c,result:m.result,filter:s}),_.deployError&&P.push(_.deployError),N++});N>ge&&!_.previewInfo&&(l=new Error(`Deploy validation failed after ${ge} attempts`))}let{diff:v,resultDiff:S,previewInfo:C,diffBinary:x,resultDiffBinary:w}=_;if(await He({config:e,diff:v,result:T.result,duration:T.duration,resultDiff:S,diffBinary:x,resultDiffBinary:w,previewInfo:C}),l)throw l;await h.clean?.()}catch(i){console.error("Got error while running pipeline",i),await a?.();let l=i instanceof Error&&i.message;throw await K(e.id,e.sessionId,{result:l||"Encountered error when running agent",state:"error"}),i}};import R from"process";var Bt="codex",Ht=e=>(e??[]).filter(t=>t.request&&t.response),Vt=e=>(e??[]).filter(t=>t.site_context),qe=()=>{let e=R.env.NETLIFY_AGENT_RUNNER_ID,t=R.env.NETLIFY_AGENT_RUNNER_SESSION_ID;if(!e||!t)throw new Error("ID of agent runner is not provided");let o=R.env.NETLIFY_AGENT_RUNNER_RESULT_BRANCH,r=R.env.NETLIFY_AGENT_RUNNER_PROMPT;if(!r)throw new Error("Prompt is not provided");let n=R.env.NETLIFY_AGENT_RUNNER_AGENT||Bt,s=R.env.NETLIFY_AGENT_RUNNER_MODEL,a=R.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED==="1",i=R.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED==="1",l=R.env.ERROR_LOGS_PATH,p=te(R.env.NETLIFY_AGENT_RUNNER_CONTEXT),c=Ht(p),d=Vt(p),h=R.env.NETLIFY_AGENT_RUNNER_HAS_REPO!=="0",E=!R.env.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED,y=R.env.NETLIFY_AGENT_RUNNER_SHA,_=qt(),T=Se();return{id:e,sessionId:t,resultBranch:o,prompt:r,runner:n,model:s,validateAgent:a,errorLogsPath:l,sessionHistoryContext:c,siteContext:d,hasRepo:h,useGateway:E,sha:y,accountType:_,validateAgentWithBuild:i,modelVersionOverrides:T}},qt=()=>{let e=R.env.NETLIFY_TEAM_TYPE;return e?e.includes("personal")?L:e.includes("pro")?"pro":e.startsWith("enterprise")?U:e.startsWith("free")?j:$:$};var J=Kt(Ke.argv.slice(2),{string:["auth","cwd","cli-path","error-logs-path","filter"]});try{let e=qe();await Ve({config:e,apiToken:J.auth,cwd:J.cwd,cliPath:J["cli-path"],errorLogsPath:J["error-logs-path"],filter:J.filter})}catch(e){console.error("Error running agent pipeline:",e),Ke.exit(1)}
|
|
129
129
|
//# sourceMappingURL=bin.js.map
|
package/dist/index.js
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
|
-
import{createRequire as
|
|
2
|
-
`),o=[],r=-1,n=0;for(;n<t.length;){let i=t[n].slice(0,500).toLowerCase();if(
|
|
3
|
-
`)),r=c,n=c+1}else n++}if(o.length===0)return e;let s=o.map((
|
|
4
|
-
${
|
|
1
|
+
import{createRequire as kt}from"module";import{createTracerProvider as Me}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as me}from"@netlify/otel/opentelemetry";import{withActiveSpan as Ye}from"@netlify/otel";import{OTLPTraceExporter as Be}from"@opentelemetry/exporter-trace-otlp-grpc";var he=(e,t)=>Me({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new me(new re),new me(new Be)]});function K(e,t,o){return console.log(`\u23F3 TRACE: ${t} starting...`),Ye(e,t,o)}var re=class{export(t,o){for(let r of t)this.logSpan(r);o({code:1})}async shutdown(){}forceFlush(){return Promise.resolve()}logSpan(t){let o=(t.endTime[0]-t.startTime[0])*1e3+(t.endTime[1]-t.startTime[1])/1e6,r=t.attributes,n=[];for(let[i,a]of Object.entries(r))i.includes("duration")&&typeof a=="number"?n.push(`${i}=${a.toFixed(2)}ms`):n.push(`${i}=${a}`);let s=t.status?.code===2?"\u274C":"\u2705",l=n.length>0?` [${n.join(", ")}]`:"";console.log(`${s} TRACE: ${t.name} completed in ${o.toFixed(2)}ms${l}`),t.status?.code===2&&t.status.message&&console.log(` \u274C Error: ${t.status.message}`)}};var He=["error","failed","exception","fatal","panic","abort","crash"];function ge(e){let t=e.split(`
|
|
2
|
+
`),o=[],r=-1,n=0;for(;n<t.length;){let i=t[n].slice(0,500).toLowerCase();if(He.some(d=>i.includes(d))){let d=Math.max(0,n-10,r+1),c=Math.min(t.length-1,n+20),p=[];for(let g=d;g<=c;g++)p.push(t[g]);o.push(p.join(`
|
|
3
|
+
`)),r=c,n=c+1}else n++}if(o.length===0)return e;let s=o.map((l,i)=>`<extracted_error_chunk order="${i+1}">
|
|
4
|
+
${l}
|
|
5
5
|
</extracted_error_chunk>`).join(`
|
|
6
6
|
|
|
7
|
-
`);return s.length>e.length*.8?e:s}import te from"process";import{getTracer as
|
|
8
|
-
`).filter(n=>!
|
|
9
|
-
`).forEach(
|
|
10
|
-
`))return;let
|
|
11
|
-
`).filter(Boolean).map(f=>{try{return JSON.parse(f)}catch{console.log("Could not parse line",f)}return null}).filter(Boolean);
|
|
7
|
+
`);return s.length>e.length*.8?e:s}import te from"process";import{getTracer as ht}from"@netlify/otel";import J from"process";var oe=J.env.NETLIFY_API_URL,ne=J.env.NETLIFY_API_TOKEN,X=async(e,t={})=>{if(!oe||!ne)throw new Error("No API URL or token");let o=new URL(e,oe),r={...t,headers:{...t.headers,Authorization:`Bearer ${ne}`}};J.env.AGENT_RUNNERS_DEBUG==="true"&&(r.headers["x-nf-debug-logging"]="true"),t.json&&(r.headers||={},r.headers["Content-Type"]="application/json",r.body=JSON.stringify(t.json));let n=await fetch(o,r),s=n.ok&&n.status<=299;if(J.env.AGENT_RUNNERS_DEBUG==="true"&&(console.log(`[DEBUG] Response headers for ${o}:`),n.headers.forEach((i,a)=>{console.log(` ${a}: ${i}`)})),s||console.error(`Got status ${n.status} for request ${o}`),t.raw){if(!s)throw n;return n}let l=await(n.headers.get("content-type")?.includes("application/json")?n.json():n.text());if(!s)throw l;return l},ye=e=>{console.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(oe=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(ne=e.constants.NETLIFY_API_TOKEN)},W=(e,t)=>X(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),M=(e,t,o)=>X(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:o});var _e=(e,t)=>X(`/api/v1/agent_runners/${e}/sessions/${t}`),xe=(e,t,o)=>X(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":o}});var Ee=async({netlify:e,config:t})=>{let o,r,n,s,l=e.constants?.SITE_ID;if(!l)throw new Error("No site id");let i=async()=>{clearTimeout(n),console.log("Requesting AI gateway information");let a=await xe(l,t.id,t.sessionId);if({token:o,url:s}=a,r=a.expires_at?a.expires_at*1e3:void 0,console.log("Got AI gateway information",{token:!!o,expiresAt:r,url:s}),r){let d=r-Date.now()-6e4;d>0&&(n=setTimeout(()=>{i()},d))}};return await i(),{get url(){return s},get token(){return o}}};import Te from"process";import{execa as Ve,execaCommand as Jt}from"execa";var qe={preferLocal:!0},we=(e,t,o)=>{let[r,n]=Ke(t,o),s={...qe,...n},l=Ve(e,r,s);return Je(l,s),l};var Ke=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Je=(e,t)=>{t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0||(e.stdout?.pipe(Te.stdout),e.stderr?.pipe(Te.stderr))};var z="netlify-agent-runner-context.md",se="task-history",ie="netlify-context",$=".netlify",Y="other",B="personal";var H="enterprise",V="free";var Xe=e=>new Promise(t=>{setTimeout(t,e)}),Ie=(e,t=3e3)=>{let o=!1,r=null,n=[],s=null,l=(...i)=>{if(o)return r=i,new Promise(c=>{n.push(c)});o=!0;let a,d=new Promise(c=>{a=c});return s=(async()=>{await Promise.resolve();let c=await e(...i);for(a(c);;){if(await Xe(t),!r)return o=!1,s=null,c;let p=r,g=n;r=null,n=[],c=await e(...p),g.forEach(_=>{_(c)})}})(),d};return l.flush=async()=>{if((o||r)&&s)return await s,l.flush()},l},Z=(e,t,o=!1)=>{let r=null,n=null,s=null,l=function(...i){n=i,s=this;let a=o&&!r;clearTimeout(r),r=setTimeout(()=>{r=null,o||(e.apply(s,n),n=null,s=null)},t),a&&(e.apply(s,n),n=null,s=null)};return l.cancel=()=>{clearTimeout(r),r=null,n=null,s=null},l.flush=()=>{if(r){clearTimeout(r);let i=n,a=s;r=null,n=null,s=null,e.apply(a,i)}},l},Ce=(e,t=!0)=>{if(e)try{return JSON.parse(e)}catch(o){t&&console.error("Could not parse JSON",o)}},Ne=(e,t)=>{let n=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let i=`--${t}${n}`;if(i.length>55)return"";let a=60-i.length;if(a<=0)return"";if(a>=s.length+6){let d=Math.min(a-s.length,e.length);return`${s}${e.slice(0,d)}`}return e.slice(0,a)};import{Buffer as Ae}from"buffer";var Se=async({config:e,netlify:t})=>{let o=await ze(t),{hasChanges:r}=o,{status:n}=o;if(!r)return{hasChanges:!1};let s=await Ze(t,n);await t.utils.run("git",["add",".",...s]);let i=(await t.utils.run("git",["diff","--staged"])).stdout;if(r=!!i,!r)return{hasChanges:!1};let d=(await t.utils.run("git",["diff","--staged","--binary"])).stdout,c,p;if(e.sha){await t.utils.run("git",["commit","-m","Agent runner"]),c=(await t.utils.run("git",["diff",e.sha,"HEAD"])).stdout;let y=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"])).stdout;c!==y&&(p=Ae.from(y).toString("base64"))}let g={hasChanges:!0,diff:i,resultDiff:c};return i!==d&&(g.diffBinary=Ae.from(d).toString("base64")),p&&(g.resultDiffBinary=p),g},We=["?? mise.toml",/\?\? .+?\.log/],ze=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
|
|
8
|
+
`).filter(n=>!We.some(s=>s instanceof RegExp?s.test(n):n===s))).length!==0,status:t.stdout}};var ve=async e=>{let{stdout:t}=await e.utils.run("git",["rev-parse","HEAD"]);return t.trim()},Re=async e=>{let{stdout:t}=await e.utils.run("git",["rev-list","--max-parents=0","HEAD"]);return t.trim()},Ze=async(e,t="")=>{let o=[".netlify","mise.toml","node_modules"],r=[],n=o.map(async l=>{try{return await e.utils.run("git",["check-ignore","-v",l]),null}catch{return`:!${l}`}});return(await Promise.all(n)).forEach(l=>{l&&r.push(l)}),t.split(`
|
|
9
|
+
`).forEach(l=>{let i=l.match(/\?\? (.+?)\.log$/)?.[1];i&&r.push(`:!${i}.log`)}),r};import Qe from"fs/promises";import et from"os";import Q from"path";import D from"process";var tt=({catchError:e,runCmd:t,error:o,result:r,runnerName:n})=>(console.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!o,hadExistingResult:!!r,resultLength:r?r.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),r?(console.log("Preserving existing result despite catch handler being triggered"),o?{error:o,result:r}:{error:"Process completed with errors but result was captured",result:r}):(console.log("Setting result to undefined because no valid result was captured"),{error:o||`${n} failed`,result:void 0}));async function ae({config:e,netlify:t,persistSteps:o,sendSteps:r,aiGateway:n}){let{accountType:s,prompt:l,modelVersionOverrides:i}=e,{model:a}=e;if(n){let{token:h,url:m}=n;if(!h||!m)throw new Error("No token or url provided from AI Gateway");let f=rt[s];if(!f)throw new Error(`Claude is not supported for the account type ${s}`);if(a&&!f?.models?.[a])throw new Error(`${a} is not supported for account type ${s}`);if(i?.claude){let u=i?.claude?.[s];u&&(a=u)}D.env.ANTHROPIC_API_KEY=h,D.env.ANTHROPIC_BASE_URL=m}else if(!D.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let d=[],c=[],p=[],g={},_=0,x=0,y,T,R=Q.join(D.cwd(),"node_modules"),S=[Q.join(D.env.NODE_PATH||R,".bin/claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...a?["--model",a]:[],"-p",l],v=`${D.env.NVM_BIN}/node`;console.log(`Running ${v} ${S.join(" ")}`);let A=t.utils.run(v,S,{all:!0,env:D.env});A.stdin?.end();let E=Z(()=>{o?.({steps:d,duration:x}),r?.({steps:c,duration:x}),c=[]},250),I=(h,m)=>{h.id=_,_+=1,p.push(h),d.push(h),c.push(h),m||E.flush(),E(),m&&E.flush()},w="";return A.all.on("data",h=>{if(w+=h.toString(),!h.includes(`
|
|
10
|
+
`))return;let m=w.split(`
|
|
11
|
+
`).filter(Boolean).map(f=>{try{return JSON.parse(f)}catch{console.log("Could not parse line",f)}return null}).filter(Boolean);w="",m.forEach(f=>{Array.isArray(f?.message?.content)?f.message.content.forEach(u=>{switch(u.type){case"text":{u.text&&I({message:u.text});break}case"image":{typeof u.source=="object"&&u.source.type==="base64"&&u.source.media_type?I({message:``}):console.log(`Unsupported image type ${u.source?.type}`,u.source);break}case"tool_use":{if(u.name==="Task"){let C=u.input?.description&&`\`${u.input.description}\``;I({title:[u.name,C].filter(Boolean).join(" ")})}else g[u.id]=u;E.flush();break}case"tool_result":{let C=g[u.tool_use_id],O;if(C){let j=C.input?.file_path&&Q.relative(D.cwd(),C.input.file_path),N=j&&`\`${j}\``;O=[C.name,N].filter(Boolean).join(" ")}let L=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(C?.name),b;if(typeof u.content=="string")b=u.content;else if(Array.isArray(u.content)){let j=[];u.content.forEach(N=>{N?.type==="text"&&typeof N.text=="string"?j.push(N.text):N?.type==="image"&&typeof N.source=="object"?N.source.type==="base64"&&N.source.media_type?j.push(``):console.log(`Unsupported image type ${N.source.type}`,N.source):console.log(`Unsupported block type ${N?.type}`)}),b=j.join(`
|
|
12
12
|
|
|
13
13
|
`)}L&&b&&(b=`\`\`\`
|
|
14
14
|
${b.trim()}
|
|
15
|
-
\`\`\``),
|
|
16
|
-
`))return;let
|
|
17
|
-
`).filter(Boolean).map(
|
|
18
|
-
`):
|
|
19
|
-
`))}),
|
|
15
|
+
\`\`\``),I({title:O,message:b},!0);break}case"thinking":{u.thinking&&I({title:"Thinking",message:u.thinking},!0);break}default:console.log(`Message content type is not supported ${u.type}`,u)}}):f?.type==="result"&&(x=f.duration_ms,f.is_error?T=f.result:y=f.result,[p,d,c].forEach(u=>{u[u.length-1]?.message===y&&u.pop()}))})}),await A.catch(h=>{({error:T,result:y}=tt({catchError:h,runCmd:A,error:T,result:y,runnerName:"Claude"}))}),E.flush(),{steps:p,duration:x,result:y,error:T}}var Pe=async()=>{let e=Q.join(et.homedir(),".claude");await Qe.rm(e,{recursive:!0,force:!0})},rt={[H]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:64e3},"claude-3-haiku-20240307":{maxTokens:4096},"claude-opus-4-20250514":{maxTokens:32e3},"claude-sonnet-4-20250514":{maxTokens:64e3}}},pro:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[B]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[V]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}},[Y]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}}};import ot from"fs/promises";import nt from"os";import le from"path";import U from"process";var st=({catchError:e,runCmd:t,error:o,result:r,runnerName:n})=>(console.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!o,hadExistingResult:!!r,resultLength:r?r.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),r?(console.log("Preserving existing result despite catch handler being triggered"),o?{error:o,result:r}:{error:"Process completed with errors but result was captured",result:r}):(console.log("Setting result to undefined because no valid result was captured"),{error:o||`${n} failed`,result:void 0}));async function ce({config:e,netlify:t,persistSteps:o,sendSteps:r,aiGateway:n}){let{accountType:s,prompt:l,modelVersionOverrides:i}=e,{model:a}=e;if(n){let{token:E,url:I}=n;if(!E||!I)throw new Error("No token or url provided from AI Gateway");let w=it[s];if(!w)throw new Error(`Codex is not supported for the account type ${s}`);if(a&&!w?.models?.[a])throw new Error(`${a} is not supported for account type ${s}`);if(i?.codex){let h=i?.codex?.[s];h&&(a=h)}U.env.OPENAI_API_KEY=E,U.env.OPENAI_BASE_URL=I}else if(!U.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let d=[],c=[],p={},g=0,_=0,x,y,T=le.join(U.cwd(),"node_modules"),R=[le.join(U.env.NODE_PATH||T,".bin/codex"),"--approval-mode","full-auto",n?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...a?["--model",a]:[],"-q",l].filter(Boolean),S=`${U.env.NVM_BIN}/node`;console.log(`Running ${S} ${R.join(" ")}`);let v=t.utils.run(S,R,{all:!0,env:{...U.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),A="";return v.all.on("data",E=>{if(A+=E.toString(),!E.includes(`
|
|
16
|
+
`))return;let I=A.toString().split(`
|
|
17
|
+
`).filter(Boolean).map(m=>{try{return JSON.parse(m)}catch{console.log("Could not parse line",m)}return null}).filter(Boolean);A="";let w=[],h=!1;I.forEach(m=>{if(m?.duration_ms&&(_=m.duration_ms,h=!0),m?.type==="local_shell_call")p[m.call_id]=m;else if(m?.type==="local_shell_call_output"){let f=lt(p[m.call_id],m);f.id=g,g+=1,f&&(c.push(f),d.push(f),w.push(f),h=!0)}else m?.type==="message"&&m.role==="assistant"?x=m.content.map(f=>f.text).join(`
|
|
18
|
+
`):m?.type==="message"&&m.role==="system"&&(y=m.content.map(f=>f.text).join(`
|
|
19
|
+
`))}),h&&(o?.({steps:d,duration:_}),r?.({steps:w,duration:_}))}),await v.catch(E=>{({error:y,result:x}=st({catchError:E,runCmd:v,error:y,result:x,runnerName:"Codex"}))}),{steps:c,duration:_,result:x,error:y}}var ke=async()=>{let e=le.join(nt.homedir(),".codex");await ot.rm(e,{recursive:!0,force:!0})},it={[H]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},o1:{maxTokens:1e5},"o1-mini":{maxTokens:65536},"o3-mini":{maxTokens:1e5},"gpt-image-1":{},"dall-e-2":{},"dall-e-3":{}}},[B]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768}}},pro:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768}}},[V]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},"o3-mini":{maxTokens:16e3}}},[Y]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},"o3-mini":{maxTokens:16e3}}}},at=new Set(["bash","-lc"]),lt=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let o=e.action?.command?.filter(s=>!at.has(s)),r=o?`Running \`${o.join(" ")}\``:void 0,n;try{n=JSON.parse(t.output).output?.trim(),n&&(n=`\`\`\`
|
|
20
20
|
${n.trim()}
|
|
21
|
-
\`\`\``)}catch(s){console.error("Could not decode outputMsg",s,t.output)}return{title:r,message:n}};import
|
|
22
|
-
`))return;let
|
|
23
|
-
`).filter(Boolean).map(f=>{try{if(f.startsWith("[API Error")){let u=f.match(/\[api error: (.+?)]$/i)?.[1];return{type:"error",value:
|
|
21
|
+
\`\`\``)}catch(s){console.error("Could not decode outputMsg",s,t.output)}return{title:r,message:n}};import ct from"fs/promises";import ut from"os";import ee from"path";import F from"process";var dt=({catchError:e,runCmd:t,error:o,result:r,runnerName:n})=>(console.log(`${n} command completed with catch handler triggered`,{hadExistingError:!!o,hadExistingResult:!!r,resultLength:r?r.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),r?(console.log("Preserving existing result despite catch handler being triggered"),o?{error:o,result:r}:{error:"Process completed with errors but result was captured",result:r}):(console.log("Setting result to undefined because no valid result was captured"),{error:o||`${n} failed`,result:void 0})),pt={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 ue({config:e,netlify:t,persistSteps:o,sendSteps:r,aiGateway:n}){let{accountType:s,prompt:l,modelVersionOverrides:i}=e,{model:a}=e;if(n){let{token:h,url:m}=n;if(!h||!m)throw new Error("No token or url provided from AI Gateway");let f=ft[s];if(!f)throw new Error(`Gemini is not supported for the account type ${s}`);if(a&&!f?.models?.[a])throw new Error(`${a} is not supported for account type ${s}`);if(i?.gemini){let u=i?.gemini?.[s];u&&(a=u)}F.env.GEMINI_API_KEY=h,F.env.GOOGLE_GEMINI_BASE_URL=m}else if(!F.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let d=[],c=[],p=[],g={},_=0,x=0,y,T,R=ee.join(F.cwd(),"node_modules"),S=[ee.join(F.env.NODE_PATH||R,".bin/gemini"),...a?["--model",a]:[],"--yolo","-p",l],v=`${F.env.NVM_BIN}/node`;console.log(`Running ${v} ${S.join(" ")}`);let A=t.utils.run(v,S,{all:!0,env:F.env});A.stdin?.end();let E=Z(()=>{o?.({steps:d,duration:x}),r?.({steps:c,duration:x}),c=[]},250),I=(h,m)=>{h.id=_,_+=1,p.push(h),d.push(h),c.push(h),m||E.flush(),E(),m&&E.flush()},w="";return A.all.on("data",h=>{if(w+=h.toString(),!h.includes(`
|
|
22
|
+
`))return;let m=w.toString().split(`
|
|
23
|
+
`).filter(Boolean).map(f=>{try{if(f.startsWith("[API Error")){let u=f.match(/\[api error: (.+?)]$/i)?.[1];return{type:"error",value:Ce(u,!1)?.error?.message||u||"Gemini encountered error"}}return JSON.parse(f)}catch{}return null}).filter(Boolean);w="",m.forEach(f=>{switch(f.type){case"thought":{let u=f.value;I({title:u?.subject??"Thinking...",message:u?.description},!0);break}case"content":{f.value&&I({message:f.value});break}case"tool_call_request":{let u=f.value,C=pt[u.name]??u.name,O=u.args?.path||u.args?.absolute_path,L=O&&ee.relative(F.cwd(),O),b=u.args?.command,N={title:[C,L&&`\`${L}\``,b&&`\`${b}\``].filter(Boolean).join(" ")};g[u.callId]=N,E.flush();break}case"tool_result":{let u=f.value,C=g[u.callId];if(C){let O=[u.resultDisplay,u.responseParts?.functionResponse?.response?.output].find(L=>typeof L=="string"&&L);O&&(C.message=`\`\`\`
|
|
24
24
|
${O.trim()}
|
|
25
|
-
\`\`\``),
|
|
25
|
+
\`\`\``),I(C,!0)}break}case"result":{x=f.duration_ms,y=f.value,[p,d,c].forEach(u=>{u[u.length-1]?.message===y&&u.pop()});break}case"error":{T=f.value;break}case"finished":break;default:{console.warn("Unhandled message type:",f.type);break}}})}),await A.catch(h=>{({error:T,result:y}=dt({catchError:h,runCmd:A,error:T,result:y,runnerName:"Gemini"}))}),E.flush(),{steps:p,duration:x,result:y,error:T}}var Oe=async()=>{let e=ee.join(ut.homedir(),".gemini");await ct.rm(e,{recursive:!0,force:!0})},ft={[H]:{models:{"gemini-1.5-flash":{maxTokens:8192},"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-1.5-pro":{maxTokens:8192},"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:65536},"gemini-2.5-flash-lite":{maxTokens:65536},"gemini-2.5-pro":{maxTokens:65536},"imagen-4.0-generate-001":{},"veo-3.0-generate-preview":{}}},pro:{models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[B]:{models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[V]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}},[Y]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}}};var mt={codex:{runner:ce,clean:ke},claude:{runner:ae,clean:Pe},gemini:{runner:ue,clean:Oe}},be=mt;var $e=async({config:e,apiThrottle:t,apiToken:o})=>{let r=ht();return K(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});let l=be[e.runner];if(!l)throw n?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let i=gt({apiToken:o});ye(i);let a=e.useGateway?await Ee({netlify:i,config:e}):void 0;n?.setAttributes({"init.aiGateway.created":!!a}),e.validateAgent&&e.errorLogsPath&&n?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let d=Ie(({steps:g=[],duration:_})=>{let x=[...g];return g.length=0,M(e.id,e.sessionId,{steps:x,duration:_})},t),c;e.hasRepo?e.sha?(c=e.sha,n?.setAttributes({"init.sha.source":"provided"})):(c=await ve(i),await W(e.id,{sha:c}),n?.setAttributes({"init.sha.source":"current_commit"})):(c=await Re(i),n?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let p=performance.now()-s;return n?.setAttributes({"init.sha":c||"unknown","init.duration.ms":p,"init.status":"success"}),{aiGateway:a,context:i,persistSteps:d,runner:l,sha:c}})},gt=({apiToken:e})=>({constants:{NETLIFY_API_HOST:te.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||te.env.NETLIFY_API_TOKEN,SITE_ID:te.env.SITE_ID,FUNCTIONS_DIST:te.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:we}});import yt from"crypto";import G from"fs/promises";import P from"path";import k from"process";var _t=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:k.env.NETLIFY_TEAM_ID,userId:k.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:k.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},xt=()=>{let e=Object.keys(k.env).sort();return{nodeVersion:k.version,envVars:e}},Et=10,Tt=async e=>{let{name:t,ext:o}=P.parse(e),r=e,n=P.join(k.cwd(),$,r),s=0;for(;await wt(n);){if(s>=Et)throw new Error("Failed to generate context file");r=`${t}-${yt.randomUUID().slice(0,5)}${o}`,n=P.join(k.cwd(),$,r),s+=1}return r},wt=async e=>{try{return await G.access(e),!0}catch{return!1}},It=async()=>{try{console.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 console.warn("Invalid response structure: missing or invalid consumers array"),null;let o=t.consumers.find(r=>r&&typeof r=="object"&&r.key==="catchall-consumer");return o?!o.contextScopes||typeof o.contextScopes!="object"?(console.warn("Catchall consumer missing or invalid contextScopes"),null):o:(console.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?console.warn("Netlify features context request timed out"):console.warn("Failed to fetch Netlify features context:",e.message),null}},Ct=async(e,t)=>{try{let o=await fetch(e,{signal:AbortSignal.timeout(1e4)});if(!o.ok)throw new Error(`Failed to fetch ${e}: ${o.status} ${o.statusText}`);let r=await o.text();return await G.writeFile(t,r,"utf-8"),!0}catch(o){return o.name==="AbortError"?console.warn(`Download timeout for ${e}`):console.warn(`Failed to download context file ${e}:`,o.message),!1}},Nt=async()=>{let e=await It();if(!e)return[];let t=P.join(k.cwd(),$,ie);await G.mkdir(t,{recursive:!0});let o=Object.entries(e.contextScopes).map(async([s,l])=>{if(!l||typeof l!="object"||!l.endpoint||!l.scope)return console.warn(`Invalid scope data for ${s}, skipping...`),null;let i=`${s}.md`,a=P.join(t,i),d=P.join($,ie,i);return console.log(`Downloading ${l.scope} context...`),await Ct(l.endpoint,a)?(console.log(`Downloaded: ${d}`),{scope:l.scope,path:d,key:s}):null});return(await Promise.all(o)).filter(s=>s!==null)},De=async({cliPath:e,netlify:t,config:o})=>{let r=_t(t),n=xt(),s=await Tt(z),l=P.join(k.cwd(),$);await G.mkdir(l,{recursive:!0});let i=P.join($,s),a=P.join(k.cwd(),i),d=`# Agent Context
|
|
26
26
|
|
|
27
27
|
In Netlify documentation and interfaces, the terms "site" and "project" refer to the same thing.
|
|
28
28
|
|
|
@@ -54,7 +54,7 @@ ${o.siteContext.filter(p=>p.site_context).map(p=>typeof p.site_context=="string"
|
|
|
54
54
|
|
|
55
55
|
`)}
|
|
56
56
|
</project_guidelines>
|
|
57
|
-
`);let c=await
|
|
57
|
+
`);let c=await Nt();if(c.length>0&&(d+=`
|
|
58
58
|
# Netlify Features Context
|
|
59
59
|
|
|
60
60
|
If the user request is explicitly related to a specific Netlify feature (e.g., Forms, Identity, Functions, etc.), you MUST review the relevant documentation below in addition to reviewing the project files.
|
|
@@ -68,7 +68,7 @@ Refer to these files when working with specific Netlify features.
|
|
|
68
68
|
Additional Documentation Resources
|
|
69
69
|
- Netlify Docs: https://docs.netlify.com
|
|
70
70
|
- LLM Resources Index: https://docs.netlify.com/llms.txt
|
|
71
|
-
`,o.sessionHistoryContext?.length){let p=
|
|
71
|
+
`,o.sessionHistoryContext?.length){let p=P.join(k.cwd(),$,se);await G.mkdir(p,{recursive:!0});let g=await Promise.all(o.sessionHistoryContext.map(async(_,x)=>{let y=x+1,T=`attempt-${y}.md`,R=P.join(p,T),S=P.join($,se,T),v=`# Task History - Attempt ${y}
|
|
72
72
|
|
|
73
73
|
## Request - what the user asked for
|
|
74
74
|
${_.request}
|
|
@@ -78,18 +78,18 @@ ${_.request}
|
|
|
78
78
|
## Response - what the agent replied with after its work
|
|
79
79
|
|
|
80
80
|
${_.response}
|
|
81
|
-
`;return await G.writeFile(
|
|
81
|
+
`;return await G.writeFile(R,v,"utf-8"),console.log(`Created history file: ${S}`),S}));d+=`# History of prior work on this task
|
|
82
82
|
|
|
83
83
|
You MUST review ALL of the files below as context to understand the context of previous attempts. Use this information to continue the discussion appropriately.
|
|
84
84
|
|
|
85
85
|
${g.map(_=>`- ${_}`).join(`
|
|
86
86
|
`)}
|
|
87
|
-
`}return await G.writeFile(
|
|
87
|
+
`}return await G.writeFile(a,d,"utf-8"),console.log(`Generated agent context document at: ${a}`),i},Fe=e=>`The build is currently failing after your changes.
|
|
88
88
|
Your task is to analyze and fix the build errors.
|
|
89
89
|
Don't apply techniques of reverting changes. Apply fixes related to errors.
|
|
90
90
|
Don't try to run build by yourself. Just fix the errors.
|
|
91
91
|
|
|
92
|
-
${e}`;var
|
|
92
|
+
${e}`;var Le=(e={})=>`
|
|
93
93
|
Check for errors and validate the fix
|
|
94
94
|
|
|
95
95
|
${e.errorLogsPath?`Error Check Process:
|
|
@@ -113,16 +113,16 @@ ${e}`;var Fe=(e={})=>`
|
|
|
113
113
|
VALIDATION_RESULT: PASS {"checks": ["error_logs"]}
|
|
114
114
|
or
|
|
115
115
|
VALIDATION_RESULT: FAIL {"checks": ["error_logs"], "errors": ["<errors>"]}
|
|
116
|
-
`;var
|
|
116
|
+
`;var At=(e=z)=>`Use ${e} to understand the Netlify project context and resources. It also contains history of previous conversations. READ ALL OF IT. Make sure to read it first. Never reveal, cite, or paraphrase private context.`,St=async({cliPath:e,config:t,netlify:o})=>{let r=await De({cliPath:e,netlify:o,config:t});return{context:At(r)}},vt=({config:e})=>{let t=[];return e?.validateAgent&&t.push(Le(e)),t},je=async({cliPath:e,config:t,netlify:o,buildErrorContext:r}={})=>{let{context:n}=await St({cliPath:e,config:t,netlify:o}),s;s=[...vt({config:t})],r&&(s=[...s,Fe(r)]);let l=[];return n&&l.push(n),t.prompt&&l.push("New user request comes in the <new_request> tag.",`<new_request>${t.prompt}</new_request>`),s?.length&&l.push(s.join(`
|
|
117
117
|
|
|
118
|
-
`)),{prompt:
|
|
118
|
+
`)),{prompt:l.join(`
|
|
119
119
|
|
|
120
|
-
`)}};var de=async({cliPath:e,config:t,context:o,buildErrors:r,runner:n,persistSteps:s,aiGateway:
|
|
120
|
+
`)}};var de=async({cliPath:e,config:t,context:o,buildErrors:r,runner:n,persistSteps:s,aiGateway:l})=>{let{prompt:i}=await je({cliPath:e,config:t,buildErrorContext:Rt(r),netlify:o}),a={...t,prompt:i},d=await n({aiGateway:l,config:a,netlify:o,persistSteps:s});if(d.error)throw console.error("Runner failed",{stepsCount:d.steps.length,duration:d.duration,error:d.error}),new Error(d.error);return{runnerResult:d}},Rt=e=>!e||e.length===0?"":`
|
|
121
121
|
Deploy failed failed. Here are the errors to review on the latest build:
|
|
122
122
|
|
|
123
123
|
Below are all of the logs with potential issues that we extracted. Some of them may be false positives, discern them carefully and ensure fixes are relevant.
|
|
124
124
|
|
|
125
125
|
${e.pop()}
|
|
126
|
-
`;import
|
|
127
|
-
Preview deploy created successfully:`,{deployId:c.deploy_id,deployUrl:c.deploy_url,siteId:c.site_id});let p={deployId:c.deploy_id,previewUrl:c.deploy_url,logsUrl:c.logs,siteId:c.site_id};return t||(p.sourceZipFilename=c.source_zip_filename),p}catch(i){throw console.error("Failed to create preview deploy via CLI:",i),i}};var pe=async({cliPath:e,config:t,context:o,result:r,filter:n})=>{let s=await
|
|
126
|
+
`;import Pt from"process";var Ue=async({netlify:e,hasRepo:t,skipBuild:o,message:r="Agent Preview",deploySubdomain:n,cliPath:s,filter:l})=>{try{let i=["deploy","--message",`"${r}"`,"--json","--draft","--verbose"];t||(console.log("Deploy: Uploading source zip"),i.push("--upload-source-zip")),n&&i.push("--alias",n),l&&i.push("--filter",l),o?(console.log("Deploy: Skipping build"),i.push("--no-build")):i.push("--context","deploy-preview");let a=s||"netlify";console.log(`Running: ${a} ${i.join(" ")}`);let d=await e.utils.run(a,i,{stdio:["ignore","pipe","pipe"]}),c=JSON.parse(d.stdout.trim());console.log(`
|
|
127
|
+
Preview deploy created successfully:`,{deployId:c.deploy_id,deployUrl:c.deploy_url,siteId:c.site_id});let p={deployId:c.deploy_id,previewUrl:c.deploy_url,logsUrl:c.logs,siteId:c.site_id};return t||(p.sourceZipFilename=c.source_zip_filename),p}catch(i){throw console.error("Failed to create preview deploy via CLI:",i),i}};var pe=async({cliPath:e,config:t,context:o,result:r,filter:n})=>{let s=await Se({config:t,netlify:o});if(!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:l,resultDiff:i,diffBinary:a,resultDiffBinary:d}=s,c=!0;console.log("Preview deploy condition check:",{resultUndefined:r===void 0,resultType:typeof r,hasChanges:c,wouldCreatePreview:r!==void 0&&c});let p=null;if(r!==void 0&&c)try{let g;try{let _=await _e(t.id,t.sessionId);_?.title&&(g=_.title)}catch(_){console.warn("Failed to fetch session title, using fallback message:",_.message)}p=await Ue({cliPath:e,netlify:o,hasRepo:t.hasRepo,message:g,skipBuild:!1,deploySubdomain:Ne(t.id,Pt.env.SITE_NAME),filter:n})}catch(g){return console.warn("Failed to create preview deploy (continuing with agent run):",g),{diff:l,resultDiff:i,hasChanges:c,previewInfo:null,diffBinary:a,resultDiffBinary:d,deployError:g instanceof Error?g.message:String(g)}}return console.log("Git status",{hasDiff:!!l,hasChanges:c}),{diff:l,resultDiff:i,hasChanges:c,previewInfo:p,diffBinary:a,resultDiffBinary:d}};var Ge=async({config:e,diff:t,result:o,duration:r,resultDiff:n,diffBinary:s,resultDiffBinary:l,previewInfo:i})=>{let a={result_diff:t,result:o||"Done",duration:r,result_diff_binary:s};return i&&i.deployId&&(a.deploy_id=i.deployId),i&&i.sourceZipFilename&&(a.result_zip_file_name=i.sourceZipFilename),n||l?(console.log("Updating total agent result diff"),await W(e.id,{result_diff:n,result_diff_binary:l})):console.log("No total result diff, not updating"),console.log("Updated agent runner with result"),await M(e.id,e.sessionId,a),{sessionUpdate:a}};import{getTracer as Ot}from"@netlify/otel";var bt=kt(import.meta.url),$t=bt("../package.json"),fe=3,mo=async({config:e,apiToken:t,cliPath:o="netlify",cwd:r,errorLogsPath:n,filter:s})=>{let l;try{await he($t.version,e.id);let i=Ot(),a,{aiGateway:d,context:c,persistSteps:p,runner:g,sha:_}=await $e({config:e,apiToken:t,cliPath:o,cwd:r,errorLogsPath:n,filter:s});l=g.clean,e.sha=_;let{runnerResult:x}=await de({cliPath:o,config:e,context:c,runner:g.runner,persistSteps:p,aiGateway:d}),y=await pe({cliPath:o,config:e,context:c,result:x.result,filter:s}),T=x,R=[];if(y.hasChanges&&y.deployError){console.log("Deploy validation enabled, starting deploy-fix iteration process"),R.push(ge(y.deployError));let w=1;for(;w<=fe&&!y.previewInfo;)await K(i,"stage-deploy",async h=>{h?.setAttributes({"stage.attempt":w});let{runnerResult:m}=await de({cliPath:o,config:e,context:c,runner:g.runner,persistSteps:p,aiGateway:d,buildErrors:R});T={...m,steps:[...T.steps||[],...m.steps||[]],duration:(T.duration||0)+(m.duration||0)},y=await pe({cliPath:o,config:e,context:c,result:m.result,filter:s}),y.deployError&&R.push(y.deployError),w++});w>fe&&!y.previewInfo&&(a=new Error(`Deploy validation failed after ${fe} attempts`))}let{diff:S,resultDiff:v,previewInfo:A,diffBinary:E,resultDiffBinary:I}=y;if(await Ge({config:e,diff:S,result:T.result,duration:T.duration,resultDiff:v,diffBinary:E,resultDiffBinary:I,previewInfo:A}),a)throw a;await g.clean?.()}catch(i){console.error("Got error while running pipeline",i),await l?.();let a=i instanceof Error&&i.message;throw await M(e.id,e.sessionId,{result:a||"Encountered error when running agent",state:"error"}),i}};export{mo as runPipeline};
|
|
128
128
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@netlify/agent-runner-cli",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "1.
|
|
4
|
+
"version": "1.25.0",
|
|
5
5
|
"description": "CLI tool for running Netlify agents",
|
|
6
6
|
"main": "./dist/index.js",
|
|
7
7
|
"types": "./dist/index.d.ts",
|
|
@@ -75,6 +75,7 @@
|
|
|
75
75
|
"@anthropic-ai/claude-code": "^1.0.51",
|
|
76
76
|
"@google/gemini-cli": "0.1.17",
|
|
77
77
|
"@netlify/otel": "^4.0.0",
|
|
78
|
+
"@opentelemetry/exporter-trace-otlp-grpc": "^0.57.0",
|
|
78
79
|
"execa": "^8.0.0",
|
|
79
80
|
"get-port": "^5.1.1",
|
|
80
81
|
"minimist": "^1.2.8",
|