@netlify/agent-runner-cli 1.27.0 → 1.28.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 +105 -78
- package/dist/index.js +105 -78
- package/package.json +1 -1
package/dist/bin.js
CHANGED
|
@@ -1,105 +1,132 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`),r=[],n=-1,o=0;for(;o<t.length;){let
|
|
4
|
-
`)),n=c,o=c+1}else o++}if(r.length===0)return e;let s=r.map((l,
|
|
2
|
+
import dt from"process";import gr from"minimist";import{createRequire as ar}from"module";import{createTracerProvider as mt}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as ke}from"@netlify/otel/opentelemetry";import{withActiveSpan as gt}from"@netlify/otel";import{OTLPTraceExporter as ht}from"@opentelemetry/exporter-trace-otlp-grpc";function _(e){let t=!process.env.VITEST;return{log:(...r)=>{t&&console.log(`[AR]-[${e}]`,...r)},error:(...r)=>{t&&console.error(`[AR]-[${e}]`,...r)},warn:(...r)=>{t&&console.warn(`[AR]-[${e}]`,...r)},info:(...r)=>{t&&console.info(`[AR]-[${e}]`,...r)},debug:(...r)=>{t&&console.debug(`[AR]-[${e}]`,...r)}}}var _e=_("tracing"),be=(e,t,r)=>mt({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new ke(new ye),new ke(new ht({url:r}))]});function se(e,t,r){return _e.log(`\u23F3 TRACE: ${t} starting...`),gt(e,t,r)}var ye=class{export(t,r){for(let n of t)this.logSpan(n);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,n=t.attributes,o=[];for(let[a,i]of Object.entries(n))a.includes("duration")&&typeof i=="number"?o.push(`${a}=${i.toFixed(2)}ms`):o.push(`${a}=${i}`);let s=t.status?.code===2?"\u274C":"\u2705",l=o.length>0?` [${o.join(", ")}]`:"";_e.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${l}`),t.status?.code===2&&t.status.message&&_e.log(` \u274C Error: ${t.status.message}`)}};var _t=["error","failed","exception","fatal","panic","abort","crash"];function $e(e){let t=e.split(`
|
|
3
|
+
`),r=[],n=-1,o=0;for(;o<t.length;){let a=t[o].slice(0,500).toLowerCase();if(_t.some(p=>a.includes(p))){let p=Math.max(0,o-10,n+1),c=Math.min(t.length-1,o+20),h=[];for(let m=p;m<=c;m++)h.push(t[m]);r.push(h.join(`
|
|
4
|
+
`)),n=c,o=c+1}else o++}if(r.length===0)return e;let s=r.map((l,a)=>`<extracted_error_chunk order="${a+1}">
|
|
5
5
|
${l}
|
|
6
6
|
</extracted_error_chunk>`).join(`
|
|
7
7
|
|
|
8
|
-
`);return s.length>e.length*.8?e:s}import
|
|
9
|
-
`).filter(o=>!
|
|
10
|
-
`).forEach(l=>{let
|
|
11
|
-
`))return;let
|
|
12
|
-
`).filter(Boolean).map(
|
|
13
|
-
|
|
14
|
-
`)}B&&
|
|
15
|
-
${
|
|
16
|
-
\`\`\``),w({title
|
|
17
|
-
`))return;let
|
|
18
|
-
`).filter(Boolean).map(
|
|
19
|
-
`):
|
|
20
|
-
`))}),
|
|
8
|
+
`);return s.length>e.length*.8?e:s}import fe from"process";import{getTracer as Kt}from"@netlify/otel";import ie from"process";var Ee=ie.env.NETLIFY_API_URL,Te=ie.env.NETLIFY_API_TOKEN,te=_("api"),ae=async(e,t={})=>{if(!Ee||!Te)throw new Error("No API URL or token");let r=new URL(e,Ee),n={...t,headers:{...t.headers,Authorization:`Bearer ${Te}`}};ie.env.AGENT_RUNNERS_DEBUG==="true"&&(n.headers["x-nf-debug-logging"]="true"),t.json&&(n.headers||={},n.headers["Content-Type"]="application/json",n.body=JSON.stringify(t.json));let o=await fetch(r,n),s=o.ok&&o.status<=299;if(ie.env.AGENT_RUNNERS_DEBUG==="true")te.log(`Response headers for ${r}:`),o.headers.forEach((a,i)=>{te.log(` ${i}: ${a}`)});else{let a=o.headers.get("x-nf-request-id");te.log(`Request ID for ${r}: ${a||"N/A"}`)}if(s||te.error(`Got status ${o.status} for request ${r}`),t.raw){if(!s)throw o;return o}let l=await(o.headers.get("content-type")?.includes("application/json")?o.json():o.text());if(!s)throw l;return l},Fe=e=>{te.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Ee=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Te=e.constants.NETLIFY_API_TOKEN)},le=(e,t)=>ae(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),J=(e,t,r)=>ae(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var Le=(e,t)=>ae(`/api/v1/agent_runners/${e}/sessions/${t}`),De=(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}});var Ue=_("ai_gateway"),je=async({netlify:e,config:t})=>{let r,n,o,s,l=e.constants?.SITE_ID;if(!l)throw new Error("No site id");let a=async()=>{clearTimeout(o),Ue.log("Requesting AI gateway information");let i=await De(l,t.id,t.sessionId);if({token:r,url:s}=i,n=i.expires_at?i.expires_at*1e3:void 0,Ue.log("Got AI gateway information",{token:!!r,expiresAt:n,url:s}),n){let p=n-Date.now()-6e4;p>0&&(o=setTimeout(()=>{a()},p))}};return await a(),{get url(){return s},get token(){return r}}};import Ye from"process";import{execa as yt,execaCommand as $r}from"execa";var Lr=_("shell"),Et={preferLocal:!0},Ge=(e,t,r)=>{let[n,o]=Tt(t,r),s={...Et,...o},l=yt(e,n,s);return xt(l,s),l};var Tt=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},xt=(e,t)=>{t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0||(e.stdout?.pipe(Ye.stdout),e.stderr?.pipe(Ye.stderr))};var Me="netlify-agent-runner-context.md",xe="task-history",we="netlify-context",$=".netlify",re="results.md",Ne="assets",U="other",j="personal";var Y="enterprise",G="free",Be=[j,"pro",Y,G];var He=_("utils"),wt=e=>new Promise(t=>{setTimeout(t,e)}),qe=(e,t=3e3)=>{let r=!1,n=null,o=[],s=null,l=(...a)=>{if(r)return n=a,new Promise(c=>{o.push(c)});r=!0;let i,p=new Promise(c=>{i=c});return s=(async()=>{await Promise.resolve();let c=await e(...a);for(i(c);;){if(await wt(t),!n)return r=!1,s=null,c;let h=n,m=o;n=null,o=[],c=await e(...h),m.forEach(y=>{y(c)})}})(),p};return l.flush=async()=>{if((r||n)&&s)return await s,l.flush()},l},ue=(e,t,r=!1)=>{let n=null,o=null,s=null,l=function(...a){o=a,s=this;let i=r&&!n;clearTimeout(n),n=setTimeout(()=>{n=null,r||(e.apply(s,o),o=null,s=null)},t),i&&(e.apply(s,o),o=null,s=null)};return l.cancel=()=>{clearTimeout(n),n=null,o=null,s=null},l.flush=()=>{if(n){clearTimeout(n);let a=o,i=s;n=null,o=null,s=null,e.apply(i,a)}},l},ce=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(n){t&&(r?.error?r.error("Could not parse JSON",n):He.error("Could not parse JSON",n))}},Ve=(e,t)=>{let o=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let a=`--${t}${o}`;if(a.length>55)return"";let i=60-a.length;if(i<=0)return"";if(i>=s.length+6){let p=Math.min(i-s.length,e.length);return`${s}${e.slice(0,p)}`}return e.slice(0,i)},Nt=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!Be.some(t=>t in e),Ke=()=>{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,n])=>{if(n){let o=`NETLIFY_FF_AGENT_RUNNER_${r.toUpperCase()}_VERSION`;try{let s=JSON.parse(n);Nt(s)&&(e[r]=s)}catch(s){let a=s instanceof SyntaxError?"Invalid JSON":s.message;He.error(`Could not parse ${r} model version override from ${o}: ${a}`)}}}),e};import{Buffer as We}from"buffer";var Je=async({config:e,netlify:t})=>{let r=await It(t),{hasChanges:n}=r,{status:o}=r;if(!n)return{hasChanges:!1};let s=await Ct(t,o);await t.utils.run("git",["add",".",...s]);let l={stdio:["ignore","pipe","pipe"]},i=(await t.utils.run("git",["diff","--staged"],l)).stdout;if(n=!!i,!n)return{hasChanges:!1};let c=(await t.utils.run("git",["diff","--staged","--binary"],l)).stdout,h,m;if(e.sha){await t.utils.run("git",["commit","-m","Agent runner"]),h=(await t.utils.run("git",["diff",e.sha,"HEAD"],l)).stdout;let g=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"],l)).stdout;h!==g&&(m=We.from(g).toString("base64"))}let y={hasChanges:!0,diff:i,resultDiff:h};return i!==c&&(y.diffBinary=We.from(c).toString("base64")),m&&(y.resultDiffBinary=m),y},Rt=["?? mise.toml",/\?\? .+?\.log/],It=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
|
|
9
|
+
`).filter(o=>!Rt.some(s=>s instanceof RegExp?s.test(o):o===s))).length!==0,status:t.stdout}};var Xe=async e=>{let{stdout:t}=await e.utils.run("git",["rev-parse","HEAD"]);return t.trim()},ze=async e=>{let{stdout:t}=await e.utils.run("git",["rev-list","--max-parents=0","HEAD"]);return t.trim()},Ct=async(e,t="")=>{let r=[".netlify","mise.toml","node_modules"],n=[],o=r.map(async l=>{try{return await e.utils.run("git",["check-ignore","-v",l]),null}catch{return`:!${l}`}});return(await Promise.all(o)).forEach(l=>{l&&n.push(l)}),t.split(`
|
|
10
|
+
`).forEach(l=>{let a=l.match(/\?\? (.+?)\.log$/)?.[1];a&&n.push(`:!${a}.log`)}),n};import vt from"fs/promises";import St from"os";import pe from"path";import H from"process";import Re from"path";import At from"fs/promises";var Ie=_("agent-output-utils");async function X({initialResult:e,agentName:t,hasError:r}){let n="",o=Re.join(process.cwd(),$,re);try{let s=await At.readFile(o,"utf-8");s&&(n=s,Ie.log(`Pulled result from ${Re.relative(process.cwd(),o)}`))}catch{Ie.log(`No results file found at ${Re.relative(process.cwd(),o)}`)}return n||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function z({error:e}){let t=e&&typeof e=="object"?JSON.stringify(e):e,r=t?.replace(/\s+/g," ").trim()||"",n="";return r?.includes("ai gateway is not available 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.":r?.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.":r?.includes("connection closed prematurely while waiting for the model")&&(n="The agent's models were currently overloaded. Please try again or use a different available agent."),n&&Ie.log(`Providing updated error messsage: ${n}, replacing original error: ${t}`),r||void 0}var M=_("runner_claude"),Pt="Claude Code",Ot=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(M.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(M.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(M.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0}));async function Ce({config:e,netlify:t,persistSteps:r,aiGateway:n}){let o=e,{accountType:s,prompt:l,modelVersionOverrides:a}=o,{model:i}=o;if(n){let{token:N,url:f}=n;if(!N||!f)throw new Error("No token or url provided from AI Gateway");let d=kt[s];if(!d)throw new Error(`Claude is not supported for the account type ${s}`);if(i&&!d?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(a?.claude){let u=a?.claude?.[s];u&&(i=u)}H.env.ANTHROPIC_API_KEY=N,H.env.ANTHROPIC_BASE_URL=f}else if(!H.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let p=[],c=[],h={},m=0,y=0,x,T,g=pe.join(H.cwd(),"node_modules"),I=[pe.join(H.env.NODE_PATH||g,".bin/claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...i?["--model",i]:[],"-p",l],C=`${H.env.NVM_BIN}/node`;M.log(`Running ${C} ${I.join(" ")}`);let S=t.utils.run(C,I,{all:!0,env:H.env});S.stdin?.end();let R=ue(()=>{r?.({steps:p,duration:y})},250),w=(N,f)=>{let d={...N,id:m};m+=1,c.push(d),p.push(d),f||R.flush(),R(),f&&R.flush()},A="";return S.all?.on("data",N=>{if(A+=N.toString(),!N.includes(`
|
|
11
|
+
`))return;let f=A.split(`
|
|
12
|
+
`).filter(Boolean).map(d=>{try{return JSON.parse(d)}catch{M.log("Could not parse line",d)}return null}).filter(Boolean);A="",f.forEach(d=>{Array.isArray(d?.message?.content)?d.message.content.forEach(u=>{switch(u.type){case"text":{u.text&&w({message:u.text});break}case"image":{typeof u.source=="object"&&u.source&&u.source.type==="base64"&&u.source.media_type?w({message:``}):M.log(`Unsupported image type ${u.source?.type}`,u.source);break}case"tool_use":{if(u.name==="Task"){let E=u.input?.description&&`\`${u.input.description}\``;w({title:[u.name,E].filter(Boolean).join(" ")})}else u.id&&(h[u.id]=u);R.flush();break}case"tool_result":{let E=u.tool_use_id?h[u.tool_use_id]:void 0,L;if(E){let D=E.input?.file_path&&pe.relative(H.cwd(),E.input.file_path),v=D&&`\`${D}\``;L=[E.name,v].filter(Boolean).join(" ")}let B=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(E?.name||""),b;if(typeof u.content=="string")b=u.content;else if(Array.isArray(u.content)){let D=[];u.content.forEach(v=>{v?.type==="text"&&typeof v.text=="string"?D.push(v.text):v?.type==="image"&&typeof v.source=="object"&&v.source?v.source.type==="base64"&&v.source.media_type?D.push(``):M.log(`Unsupported image type ${v.source.type}`,v.source):M.log(`Unsupported block type ${v?.type}`)}),b=D.join(`
|
|
13
|
+
|
|
14
|
+
`)}B&&b&&(b=`\`\`\`
|
|
15
|
+
${b.trim()}
|
|
16
|
+
\`\`\``),w({title:L,message:b},!0);break}case"thinking":{u.thinking&&w({title:"Thinking",message:u.thinking},!0);break}default:M.log(`Message content type is not supported ${u.type}`,u)}}):d?.type==="result"&&(y=d.duration_ms||0,d.is_error?T=d.result:x=d.result,[c,p].forEach(u=>{u[u.length-1]?.message===x&&u.pop()}))})}),await S.catch(N=>{({error:T,result:x}=Ot({catchError:N,runCmd:S,error:T,result:x,runnerName:"Claude"}))}),R.flush(),{steps:c,duration:y,result:await X({initialResult:x,agentName:Pt,hasError:!!T}),error:z({error:T})}}var Ze=async()=>{let e=pe.join(St.homedir(),".claude");await vt.rm(e,{recursive:!0,force:!0})},kt={[Y]:{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}}},[j]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[G]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}},[U]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}}};import bt from"fs/promises";import $t from"os";import Ae from"path";import W from"process";var Z=_("runner_codex"),Ft="Codex CLI",Lt=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(Z.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(Z.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(Z.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0}));async function ve({config:e,netlify:t,persistSteps:r,sendSteps:n,aiGateway:o}){let{accountType:s,prompt:l,modelVersionOverrides:a}=e,{model:i}=e;if(o){let{token:w,url:A}=o;if(!w||!A)throw new Error("No token or url provided from AI Gateway");let N=Dt[s];if(!N)throw new Error(`Codex is not supported for the account type ${s}`);if(i&&!N?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(a?.codex){let f=a?.codex?.[s];f&&(i=f)}W.env.OPENAI_API_KEY=w,W.env.OPENAI_BASE_URL=A}else if(!W.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let p=[],c=[],h={},m=0,y=0,x,T,g=Ae.join(W.cwd(),"node_modules"),I=[Ae.join(W.env.NODE_PATH||g,".bin/codex"),"--approval-mode","full-auto",o?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...i?["--model",i]:[],"-q",l].filter(Boolean),C=`${W.env.NVM_BIN}/node`;Z.log(`Running ${C} ${I.join(" ")}`);let S=t.utils.run(C,I,{all:!0,env:{...W.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),R="";return S.all.on("data",w=>{if(R+=w.toString(),!w.includes(`
|
|
17
|
+
`))return;let A=R.toString().split(`
|
|
18
|
+
`).filter(Boolean).map(d=>{try{return JSON.parse(d)}catch{Z.log("Could not parse line",d)}return null}).filter(Boolean);R="";let N=[],f=!1;A.forEach(d=>{if(d?.duration_ms&&(y=d.duration_ms,f=!0),d?.type==="local_shell_call")h[d.call_id]=d;else if(d?.type==="local_shell_call_output"){let u=jt(h[d.call_id],d);u.id=m,m+=1,u&&(c.push(u),p.push(u),N.push(u),f=!0)}else d?.type==="message"&&d.role==="assistant"?x=d.content.map(u=>u.text).join(`
|
|
19
|
+
`):d?.type==="message"&&d.role==="system"&&(T=d.content.map(u=>u.text).join(`
|
|
20
|
+
`))}),f&&(r?.({steps:p,duration:y}),n?.({steps:N,duration:y}))}),await S.catch(w=>{({error:T,result:x}=Lt({catchError:w,runCmd:S,error:T,result:x,runnerName:"Codex"}))}),{steps:c,duration:y,result:await X({initialResult:x,agentName:Ft,hasError:!!T}),error:z({error:T})}}var Qe=async()=>{let e=Ae.join($t.homedir(),".codex");await bt.rm(e,{recursive:!0,force:!0})},Dt={[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},o1:{maxTokens:1e5},"o1-mini":{maxTokens:65536},"o3-mini":{maxTokens:1e5},"gpt-image-1":{},"dall-e-2":{},"dall-e-3":{}}},[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}}},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}}},[G]:{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}}},[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},"o3-mini":{maxTokens:16e3}}}},Ut=new Set(["bash","-lc"]),jt=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!Ut.has(s)),n=r?`Running \`${r.join(" ")}\``:void 0,o;try{o=JSON.parse(t.output).output?.trim(),o&&(o=`\`\`\`
|
|
21
21
|
${o.trim()}
|
|
22
|
-
\`\`\``)}catch(s){
|
|
23
|
-
`))return;let
|
|
24
|
-
`).filter(Boolean).map(u=>{try{if(u.startsWith("[API Error")){let
|
|
22
|
+
\`\`\``)}catch(s){Z.error("Could not decode outputMsg",s,t.output)}return{title:n,message:o}};import Yt from"fs/promises";import Gt from"os";import de from"path";import q from"process";var ne=_("runner_gemini"),Mt="Gemini CLI",Bt=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(ne.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(ne.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(ne.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0})),Ht={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 Se({config:e,netlify:t,persistSteps:r,sendSteps:n,aiGateway:o}){let{accountType:s,prompt:l,modelVersionOverrides:a}=e,{model:i}=e;if(o){let{token:f,url:d}=o;if(!f||!d)throw new Error("No token or url provided from AI Gateway");let u=qt[s];if(!u)throw new Error(`Gemini is not supported for the account type ${s}`);if(i&&!u?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(a?.gemini){let E=a?.gemini?.[s];E&&(i=E)}q.env.GEMINI_API_KEY=f,q.env.GOOGLE_GEMINI_BASE_URL=d}else if(!q.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let p=[],c=[],h=[],m={},y=0,x=0,T,g,I=de.join(q.cwd(),"node_modules"),C=[de.join(q.env.NODE_PATH||I,".bin/gemini"),...i?["--model",i]:[],"--yolo","-p",l],S=`${q.env.NVM_BIN}/node`;ne.log(`Running ${S} ${C.join(" ")}`);let R=t.utils.run(S,C,{all:!0,env:q.env});R.stdin?.end();let w=ue(()=>{r?.({steps:p,duration:x}),n?.({steps:c,duration:x}),c=[]},250),A=(f,d)=>{f.id=y,y+=1,h.push(f),p.push(f),c.push(f),d||w.flush(),w(),d&&w.flush()},N="";return R.all.on("data",f=>{if(N+=f.toString(),!f.includes(`
|
|
23
|
+
`))return;let d=N.toString().split(`
|
|
24
|
+
`).filter(Boolean).map(u=>{try{if(u.startsWith("[API Error")){let E=u.match(/\[api error: (.+?)]$/i)?.[1];return{type:"error",value:ce(E,!1)?.error?.message||E||"Gemini encountered error"}}return JSON.parse(u)}catch{}return null}).filter(Boolean);N="",d.forEach(u=>{switch(u.type){case"thought":{let E=u.value;A({title:E?.subject??"Thinking...",message:E?.description},!0);break}case"content":{u.value&&A({message:u.value});break}case"tool_call_request":{let E=u.value,L=Ht[E.name]??E.name,B=E.args?.path||E.args?.absolute_path,b=B&&de.relative(q.cwd(),B),D=E.args?.command,ft={title:[L,b&&`\`${b}\``,D&&`\`${D}\``].filter(Boolean).join(" ")};m[E.callId]=ft,w.flush();break}case"tool_result":{let E=u.value,L=m[E.callId];if(L){let B=[E.resultDisplay,E.responseParts?.functionResponse?.response?.output].find(b=>typeof b=="string"&&b);B&&(L.message=`\`\`\`
|
|
25
25
|
${B.trim()}
|
|
26
|
-
\`\`\``),
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
If you need to start a local development server in order to fulfill the request, try using the Netlify CLI over by running the shell command '${e} dev'. This will start a local HTTP server on port 8888, including live-reloading of any changes and, most critically, it offers local emulation for all Netlify features.
|
|
31
|
-
|
|
32
|
-
## Netlify Site
|
|
33
|
-
- Site ID: ${n.siteId}
|
|
34
|
-
- Account ID: ${n.accountId}
|
|
35
|
-
- User ID: ${n.userId}
|
|
36
|
-
- Site Slug: ${n.siteSlug}
|
|
37
|
-
- Netlify Functions directory: ${n.functionsDir}
|
|
38
|
-
- Running Node Version: ${o.nodeVersion}
|
|
39
|
-
|
|
40
|
-
The available environment variables are set globally (e.g. \`echo $VARIABLE_NAME\` can be used to check if a var is set).:
|
|
41
|
-
|
|
42
|
-
## Attachments
|
|
43
|
-
|
|
44
|
-
- for requests that require work with attachments or assets, take into account that uploaded attachments are stored in .netlify/assets folder
|
|
45
|
-
- move assets from .netlify/assets folder to the project assets folder if they are referenced in a code or applied changes
|
|
46
|
-
|
|
47
|
-
## Netlify CLI
|
|
48
|
-
'netlify-cli' npm package is already available as a global package.
|
|
49
|
-
Don't try to install it, in case you want to use it, use the global package.
|
|
50
|
-
|
|
51
|
-
`;r.siteContext&&r.siteContext.length!==0&&(p+=`
|
|
52
|
-
# Project Guidelines
|
|
53
|
-
<project_guidelines>
|
|
54
|
-
${r.siteContext.filter(d=>d.site_context).map(d=>typeof d.site_context=="string"?d.site_context:typeof d.site_context=="object"?JSON.stringify(d.site_context):"").join(`
|
|
55
|
-
|
|
56
|
-
`)}
|
|
57
|
-
</project_guidelines>
|
|
58
|
-
`);let c=await Xt();if(c.length>0&&(p+=`
|
|
59
|
-
# Netlify Features Context
|
|
26
|
+
\`\`\``),A(L,!0)}break}case"result":{x=u.duration_ms,T=u.value,[h,p,c].forEach(E=>{E[E.length-1]?.message===T&&E.pop()});break}case"error":{g=u.value;break}case"finished":break;default:{ne.warn("Unhandled message type:",u.type);break}}})}),await R.catch(f=>{({error:g,result:T}=Bt({catchError:f,runCmd:R,error:g,result:T,runnerName:"Gemini"}))}),w.flush(),{steps:h,duration:x,result:await X({initialResult:T,agentName:Mt,hasError:!!g}),error:z({error:g})}}var et=async()=>{let e=de.join(Gt.homedir(),".gemini");await Yt.rm(e,{recursive:!0,force:!0})},qt={[Y]:{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}}},[j]:{models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[G]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}},[U]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}}};var Vt={codex:{runner:ve,clean:Qe},claude:{runner:Ce,clean:Ze},gemini:{runner:Se,clean:et}},tt=Vt;var rt=async({config:e,apiThrottle:t,apiToken:r})=>{let n=Kt();return se(n,"init-stage",async o=>{let s=performance.now();o?.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=tt[e.runner];if(!l)throw o?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let a=Wt({apiToken:r});Fe(a);let i=e.useGateway?await je({netlify:a,config:e}):void 0;o?.setAttributes({"init.aiGateway.created":!!i}),e.validateAgent&&e.errorLogsPath&&o?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let p=qe(({steps:m=[],duration:y})=>{let x=[...m];return m.length=0,J(e.id,e.sessionId,{steps:x,duration:y})},t),c;e.hasRepo?e.sha?(c=e.sha,o?.setAttributes({"init.sha.source":"provided"})):(c=await Xe(a),await le(e.id,{sha:c}),o?.setAttributes({"init.sha.source":"current_commit"})):(c=await ze(a),o?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let h=performance.now()-s;return o?.setAttributes({"init.sha":c||"unknown","init.duration.ms":h,"init.status":"success"}),{aiGateway:i,context:a,persistSteps:p,runner:l,sha:c}})},Wt=({apiToken:e})=>({constants:{NETLIFY_API_HOST:fe.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||fe.env.NETLIFY_API_TOKEN,SITE_ID:fe.env.SITE_ID,FUNCTIONS_DIST:fe.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:Ge}});import Jt from"crypto";import V from"fs/promises";import k from"path";import F from"process";var P=_("context"),Xt=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:F.env.NETLIFY_TEAM_ID,userId:F.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:F.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},zt=10,Zt=async e=>{let{name:t,ext:r}=k.parse(e),n=e,o=k.join(F.cwd(),$,n),s=0;for(;await Qt(o);){if(s>=zt)throw new Error("Failed to generate context file");n=`${t}-${Jt.randomUUID().slice(0,5)}${r}`,o=k.join(F.cwd(),$,n),s+=1}return n},Qt=async e=>{try{return await V.access(e),!0}catch{return!1}},er=async()=>{try{P.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 P.warn("Invalid response structure: missing or invalid consumers array"),null;let r=t.consumers.find(n=>n&&typeof n=="object"&&n.key==="catchall-consumer");return r?!r.contextScopes||typeof r.contextScopes!="object"?(P.warn("Catchall consumer missing or invalid contextScopes"),null):r:(P.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?P.warn("Netlify features context request timed out"):P.warn("Failed to fetch Netlify features context:",e.message),null}},tr=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 n=await r.text();return await V.writeFile(t,n,"utf-8"),!0}catch(r){return r.name==="AbortError"?P.warn(`Download timeout for ${e}`):P.warn(`Failed to download context file ${e}:`,r.message),!1}},me=null,rr=async()=>{if(me)return me;let e=await er();if(!e)return[];let t=k.join(F.cwd(),$,we);await V.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([o,s])=>{if(!s||typeof s!="object"||!s.endpoint||!s.scope)return P.warn(`Invalid scope data for ${o}, skipping...`),null;let l=`${o}.md`,a=k.join(t,l),i=k.join($,we,l);return P.log(`Downloading ${s.scope} context...`),await tr(s.endpoint,a)?(P.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:o}):null});return me=(await Promise.all(r)).filter(o=>o!==null),me},nt=async({cliPath:e,netlify:t,config:r,buildErrorContext:n})=>{let o=Xt(t),s=await Zt(Me),l=k.join(F.cwd(),$);await V.mkdir(l,{recursive:!0});let a=k.join($,s),i=k.join(F.cwd(),a),p=k.join(F.cwd(),$,re);try{await V.unlink(p),P.log(`Deleted old results file: ${p}`)}catch{}let c=n?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
|
|
27
|
+
Your task is to analyze and fix the build errors.
|
|
28
|
+
Don't apply techniques of reverting changes. Apply fixes related to errors.
|
|
29
|
+
Don't try to run build by yourself. Just fix the errors.
|
|
60
30
|
|
|
61
|
-
|
|
62
|
-
|
|
31
|
+
<build_error_context>
|
|
32
|
+
${c}
|
|
33
|
+
</build_error_context>`:"",h="";r.siteContext&&r.siteContext.length!==0&&(h=`
|
|
34
|
+
<project_rules>
|
|
35
|
+
${r.siteContext.filter(g=>g.site_context).map(g=>typeof g.site_context=="string"?g.site_context:typeof g.site_context=="object"?JSON.stringify(g.site_context):"").join(`
|
|
63
36
|
|
|
64
|
-
${c.map(d=>`- **${d.scope}**: ${d.path}`).join(`
|
|
65
37
|
`)}
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
`),p+=`
|
|
69
|
-
Additional Documentation Resources
|
|
70
|
-
- Netlify Docs: https://docs.netlify.com
|
|
71
|
-
- LLM Resources Index: https://docs.netlify.com/llms.txt
|
|
72
|
-
`,r.sessionHistoryContext?.length){let d=b.join(F.cwd(),L,Ee);await X.mkdir(d,{recursive:!0});let m=await Promise.all(r.sessionHistoryContext.map(async(h,T)=>{let E=T+1,x=`attempt-${E}.md`,I=b.join(d,x),A=b.join(L,Ee,x),v=`# Task History - Attempt ${E}
|
|
38
|
+
</project_rules>
|
|
39
|
+
`);let m="";if(r.sessionHistoryContext?.length){let g=k.join(F.cwd(),$,xe);await V.mkdir(g,{recursive:!0});let I=await Promise.all(r.sessionHistoryContext.map(async(C,S)=>{let R=S+1,w=`attempt-${R}.md`,A=k.join(g,w),N=k.join($,xe,w),f=`# Task History - Attempt ${R}
|
|
73
40
|
|
|
74
41
|
## Request - what the user asked for
|
|
75
|
-
${
|
|
42
|
+
${C.request}
|
|
76
43
|
|
|
77
44
|
---
|
|
78
45
|
|
|
79
46
|
## Response - what the agent replied with after its work
|
|
80
47
|
|
|
81
|
-
${
|
|
82
|
-
`;return await
|
|
83
|
-
|
|
84
|
-
|
|
48
|
+
${C.response}
|
|
49
|
+
`;return await V.writeFile(A,f,"utf-8"),P.log(`Created history file: ${N}`),N}));m+=`
|
|
50
|
+
<session_history_context>
|
|
51
|
+
History of prior work on this task.
|
|
52
|
+
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
53
|
|
|
86
|
-
${
|
|
54
|
+
${I.slice(-5).map(C=>`- ${C}`).join(`
|
|
87
55
|
`)}
|
|
88
|
-
`}return await X.writeFile(a,p,"utf-8"),O.log(`Generated agent context document at: ${a}`),i},Ze=e=>`The build is currently failing after your changes.
|
|
89
|
-
Your task is to analyze and fix the build errors.
|
|
90
|
-
Don't apply techniques of reverting changes. Apply fixes related to errors.
|
|
91
|
-
Don't try to run build by yourself. Just fix the errors.
|
|
92
56
|
|
|
93
|
-
|
|
57
|
+
</session_history_context>
|
|
58
|
+
`}let y=await rr(),x="";y.length>0&&(x=`
|
|
59
|
+
<netlify_features_context>
|
|
60
|
+
If the user request is explicitly related to a specific Netlify feature (e.g., Netlify Forms, Netlify Functions, etc.), you MUST review the relevant documentation below in addition to reviewing the project files.
|
|
61
|
+
DO NOT force the use of any Netlify feature if the user request does not explicitly require it or if the project has alternative implementations in place already.
|
|
94
62
|
|
|
95
|
-
`)
|
|
63
|
+
${y.map(g=>`- **${g.scope}**: ${g.path}`).join(`
|
|
64
|
+
`)}
|
|
96
65
|
|
|
97
|
-
|
|
66
|
+
Refer to these files when working with specific Netlify features.
|
|
67
|
+
</netlify_features_context>
|
|
68
|
+
`);let T=`
|
|
69
|
+
You're an AI agent designed to assist with tasks related to a Netlify project. Please review, understand, and use the context provided to complete the user's request as needed.
|
|
70
|
+
|
|
71
|
+
<request>
|
|
72
|
+
<user_request>
|
|
73
|
+
${r.prompt}
|
|
74
|
+
</user_request>
|
|
75
|
+
${c}
|
|
76
|
+
</request>
|
|
77
|
+
|
|
78
|
+
<requirements>
|
|
79
|
+
<responses>
|
|
80
|
+
- Do not speak in first person. You may speak as "the agent".
|
|
81
|
+
- When your work is complete, create a changelog summary in ${l}/${re} that is pull request or changelog blog appropriate for the primary work that was completed.
|
|
82
|
+
- Do not attempt to create git commits, PRs, etc. directly. You can use git to review information if required but the system that runs this agent will handle creating PRs or commits of the changes it performs.
|
|
83
|
+
</responses>
|
|
84
|
+
<attachements>
|
|
85
|
+
- for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${l}/${Ne} folder
|
|
86
|
+
- move assets from ${l}/${Ne} folder to the project assets folder if they are referenced in a code or applied changes
|
|
87
|
+
</attachements>
|
|
88
|
+
${h}
|
|
89
|
+
</requirements>
|
|
90
|
+
|
|
91
|
+
<extra_context>
|
|
92
|
+
<metadata>
|
|
93
|
+
- Site/Project ID: ${o.siteId}
|
|
94
|
+
- Account/Team ID: ${o.accountId}
|
|
95
|
+
- User ID: ${o.userId}
|
|
96
|
+
- Site/Project Slug: ${o.siteSlug}
|
|
97
|
+
- Netlify Functions directory: ${o.functionsDir}
|
|
98
|
+
</metadata>
|
|
99
|
+
<environment>
|
|
100
|
+
- Node Version: ${F.version||"unknown"}
|
|
101
|
+
- Environment variables are set globally (e.g. \`echo $VARIABLE_NAME\` can be used to check if a var is set).
|
|
102
|
+
- 'netlify-cli' npm package is already available as a global package. Don't try to install it again
|
|
103
|
+
- If you need to start a local development server in order to fulfill the request, try using the Netlify CLI over by running the shell command '${e} dev'. This will start a local HTTP server on port 8888, including live-reloading of any changes and, most critically, it offers local emulation for all Netlify features.
|
|
104
|
+
</environment>
|
|
105
|
+
${x}
|
|
106
|
+
<docs>
|
|
107
|
+
- Netlify Docs: https://docs.netlify.com
|
|
108
|
+
- LLM Resources Index: https://docs.netlify.com/llms.txt
|
|
109
|
+
</docs>
|
|
110
|
+
</extra_context>
|
|
111
|
+
|
|
112
|
+
${m}
|
|
113
|
+
`;return await V.writeFile(i,T,"utf-8"),P.log(`Generated agent context document at: ${i}`),T.length>5e5&&(T=`
|
|
114
|
+
You're an AI agent designed to assist with tasks related to a Netlify project. Please review, understand, and use the context provided to complete the user's request as needed.
|
|
115
|
+
|
|
116
|
+
<request>
|
|
117
|
+
<user_request>
|
|
118
|
+
${r.prompt}
|
|
119
|
+
</user_request>
|
|
120
|
+
${c}
|
|
121
|
+
</request>
|
|
122
|
+
|
|
123
|
+
Use the following file for the complete context of the ask, the environment, and what's available. ${i} You MUST READ ALL OF IT. Make sure to read it first. Never cite or paraphrase private context.
|
|
124
|
+
`),T};var nr=_("prompt"),ot=async({cliPath:e,config:t,netlify:r,buildErrorContext:n})=>{let o=await nt({cliPath:e,config:t,netlify:r,buildErrorContext:n});return process.env.AGENT_RUNNER_DEBUG&&nr.log("Contextful Prompt:",o),{prompt:o}};var or=_("inference_stage"),Pe=async({cliPath:e,config:t,context:r,buildErrors:n,runner:o,persistSteps:s,aiGateway:l})=>{let{prompt:a}=await ot({cliPath:e,config:t,buildErrorContext:sr(n),netlify:r}),i={...t,prompt:a},p=await o({aiGateway:l,config:i,netlify:r,persistSteps:s});if(await s.flush(),p.error)throw or.error("Runner failed",{stepsCount:p.steps.length,duration:p.duration,error:p.error}),new Error(p.error);return{runnerResult:p}},sr=e=>!e||e.length===0?"":`
|
|
98
125
|
Deploy failed failed. Here are the errors to review on the latest build:
|
|
99
126
|
|
|
100
127
|
Below are all of the logs with potential issues that we extracted. Some of them may be false positives, discern them carefully and ensure fixes are relevant.
|
|
101
128
|
|
|
102
129
|
${e.pop()}
|
|
103
|
-
`;import
|
|
104
|
-
Preview deploy created successfully:`,{deployId:c.deploy_id,deployUrl:c.deploy_url,siteId:c.site_id});let
|
|
130
|
+
`;import ir from"process";var oe=_("deploy"),st=async({netlify:e,hasRepo:t,skipBuild:r,message:n="Agent Preview",deploySubdomain:o,cliPath:s,filter:l})=>{try{let a=["deploy","--message",`"${n}"`,"--json","--draft","--verbose"];t||(oe.log("Deploy: Uploading source zip"),a.push("--upload-source-zip")),o&&a.push("--alias",o),l&&a.push("--filter",l),r?(oe.log("Deploy: Skipping build"),a.push("--no-build")):a.push("--context","deploy-preview");let i=s||"netlify";oe.log(`Running: ${i} ${a.join(" ")}`);let p=await e.utils.run(i,a,{stdio:["ignore","pipe","pipe"]}),c=JSON.parse(p.stdout.trim());oe.log(`
|
|
131
|
+
Preview deploy created successfully:`,{deployId:c.deploy_id,deployUrl:c.deploy_url,siteId:c.site_id});let h={deployId:c.deploy_id,previewUrl:c.deploy_url,logsUrl:c.logs,siteId:c.site_id};return t||(h.sourceZipFilename=c.source_zip_filename),h}catch(a){throw oe.error("Failed to create preview deploy via CLI:",a),a}};var ge=_("deploy_stage"),Oe=async({cliPath:e,config:t,context:r,result:n,filter:o})=>{let s=await Je({config:t,netlify:r});if(!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:l,resultDiff:a,diffBinary:i,resultDiffBinary:p}=s,c=!0;ge.log("Preview deploy condition check:",{resultUndefined:n===void 0,resultType:typeof n,hasChanges:c,wouldCreatePreview:n!==void 0&&c});let h=null;if(n!==void 0&&c)try{let m;try{let y=await Le(t.id,t.sessionId);y?.title&&(m=y.title)}catch(y){ge.warn("Failed to fetch session title, using fallback message:",y.message)}h=await st({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:m,skipBuild:!1,deploySubdomain:Ve(t.id,ir.env.SITE_NAME),filter:o})}catch(m){return ge.warn("Failed to create preview deploy (continuing with agent run):",m),{diff:l,resultDiff:a,hasChanges:c,previewInfo:null,diffBinary:i,resultDiffBinary:p,deployError:m instanceof Error?m.message:String(m)}}return ge.log("Git status",{hasDiff:!!l,hasChanges:c}),{diff:l,resultDiff:a,hasChanges:c,previewInfo:h,diffBinary:i,resultDiffBinary:p}};async function it(e,t){let{maxRetries:r,baseDelay:n,onRetry:o}=t,s;for(let l=1;l<=r;l++)try{return await e()}catch(a){if(s=a,l===r)throw s;o&&o(l,s),await new Promise(i=>setTimeout(i,n*l))}throw s}var Q=_("cleanup_stage"),at=async({config:e,diff:t,result:r,duration:n,resultDiff:o,diffBinary:s,resultDiffBinary:l,previewInfo:a})=>{let i={result_diff:t,result:r||"Done",duration:n,result_diff_binary:s};return a&&a.deployId&&(i.deploy_id=a.deployId),a&&a.sourceZipFilename&&(i.result_zip_file_name=a.sourceZipFilename),o||l?(Q.log("Updating total agent result diff"),await le(e.id,{result_diff:o,result_diff_binary:l})):Q.log("No total result diff, not updating"),Q.log("Updated agent runner with result"),await it(()=>J(e.id,e.sessionId,i),{maxRetries:3,baseDelay:1e3,onRetry:(p,c)=>{Q.error(`Error updating agent runner session (attempt ${p}):`,c),Q.log("Retrying...")}}),Q.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as lr}from"@netlify/otel";var ur=ar(import.meta.url),cr=ur("../package.json"),lt=_("pipeline_index"),he=3,ut=async({config:e,apiToken:t,cliPath:r="netlify",cwd:n,errorLogsPath:o,filter:s,traceExporterUrl:l})=>{let a;try{await be(cr.version,e.id,l);let i=lr(),p,{aiGateway:c,context:h,persistSteps:m,runner:y,sha:x}=await rt({config:e,apiToken:t,cliPath:r,cwd:n,errorLogsPath:o,filter:s});a=y.clean,e.sha=x;let{runnerResult:T}=await Pe({cliPath:r,config:e,context:h,runner:y.runner,persistSteps:m,aiGateway:c}),g=await Oe({cliPath:r,config:e,context:h,result:T.result,filter:s}),I=T,C=[];if(g.hasChanges&&g.deployError){C.push($e(g.deployError));let f=1;for(;f<=he&&!g.previewInfo;)lt.log(`Deploy attempt had errors. Retrying. ${f}/${he}`),await se(i,"stage-deploy",async d=>{d?.setAttributes({"stage.attempt":f});let{runnerResult:u}=await Pe({cliPath:r,config:e,context:h,runner:y.runner,persistSteps:m,aiGateway:c,buildErrors:C});I={...u,steps:[...I.steps||[],...u.steps||[]],duration:(I.duration||0)+(u.duration||0)},g=await Oe({cliPath:r,config:e,context:h,result:u.result,filter:s}),g.deployError&&C.push(g.deployError),f++});f>he&&!g.previewInfo&&(p=new Error(`Deploy validation failed after ${he} attempts`))}let{diff:S,resultDiff:R,previewInfo:w,diffBinary:A,resultDiffBinary:N}=g;if(await at({config:e,diff:S,result:I.result,duration:I.duration,resultDiff:R,diffBinary:A,resultDiffBinary:N,previewInfo:w}),p)throw p;await y.clean?.()}catch(i){lt.error("Got error while running pipeline",i),await a?.();let p=i instanceof Error&&i.message;throw await J(e.id,e.sessionId,{result:p||"Encountered error when running agent",state:"error"}),i}};import O from"process";var pr="codex",dr=e=>(e??[]).filter(t=>t.request&&t.response),fr=e=>(e??[]).filter(t=>t.site_context),ct=_("config"),pt=()=>{let e=O.env.NETLIFY_AGENT_RUNNER_ID,t=O.env.NETLIFY_AGENT_RUNNER_SESSION_ID;if(!e||!t)throw new Error("ID of agent runner is not provided");let r=O.env.NETLIFY_AGENT_RUNNER_RESULT_BRANCH,n=O.env.NETLIFY_AGENT_RUNNER_PROMPT;if(!n)throw new Error("Prompt is not provided");let o=O.env.NETLIFY_AGENT_RUNNER_AGENT||pr,s=O.env.NETLIFY_AGENT_RUNNER_MODEL,l=O.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED==="1",a=O.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED==="1",i=O.env.ERROR_LOGS_PATH,p=ce(O.env.NETLIFY_AGENT_RUNNER_CONTEXT,!0,ct),c=dr(p),h=fr(p),m=O.env.NETLIFY_AGENT_RUNNER_HAS_REPO!=="0",y=!O.env.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED,x=O.env.NETLIFY_AGENT_RUNNER_SHA,T=mr(),g=Ke(),I={id:e,sessionId:t,resultBranch:r,prompt:n,runner:o,model:s,validateAgent:l,errorLogsPath:i,sessionHistoryContext:c,siteContext:h,hasRepo:m,useGateway:y,sha:x,accountType:T,validateAgentWithBuild:a,modelVersionOverrides:g};return ct.log({fullConfig:I}),I},mr=()=>{let e=O.env.NETLIFY_TEAM_TYPE;return e?e.includes("personal")?j:e.includes("pro")?"pro":e.startsWith("enterprise")?Y:e.startsWith("free")?G:U:U};var hr=_("bin_cmd"),ee=gr(dt.argv.slice(2),{string:["auth","cwd","cli-path","error-logs-path","filter","trace-exporter-url"]});try{let e=pt();await ut({config:e,apiToken:ee.auth,cwd:ee.cwd,cliPath:ee["cli-path"],errorLogsPath:ee["error-logs-path"],filter:ee.filter,traceExporterUrl:ee["trace-exporter-url"]})}catch(e){hr.error("Error running agent pipeline:",e),dt.exit(1)}
|
|
105
132
|
//# sourceMappingURL=bin.js.map
|
package/dist/index.js
CHANGED
|
@@ -1,104 +1,131 @@
|
|
|
1
|
-
import{createRequire as
|
|
2
|
-
`),r=[],n=-1,o=0;for(;o<t.length;){let
|
|
3
|
-
`)),n=c,o=c+1}else o++}if(r.length===0)return e;let s=r.map((l,
|
|
1
|
+
import{createRequire as Zt}from"module";import{createTracerProvider as st}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as ve}from"@netlify/otel/opentelemetry";import{withActiveSpan as it}from"@netlify/otel";import{OTLPTraceExporter as at}from"@opentelemetry/exporter-trace-otlp-grpc";function x(e){let t=!process.env.VITEST;return{log:(...r)=>{t&&console.log(`[AR]-[${e}]`,...r)},error:(...r)=>{t&&console.error(`[AR]-[${e}]`,...r)},warn:(...r)=>{t&&console.warn(`[AR]-[${e}]`,...r)},info:(...r)=>{t&&console.info(`[AR]-[${e}]`,...r)},debug:(...r)=>{t&&console.debug(`[AR]-[${e}]`,...r)}}}var me=x("tracing"),Pe=(e,t,r)=>st({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new ve(new ge),new ve(new at({url:r}))]});function ne(e,t,r){return me.log(`\u23F3 TRACE: ${t} starting...`),it(e,t,r)}var ge=class{export(t,r){for(let n of t)this.logSpan(n);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,n=t.attributes,o=[];for(let[a,i]of Object.entries(n))a.includes("duration")&&typeof i=="number"?o.push(`${a}=${i.toFixed(2)}ms`):o.push(`${a}=${i}`);let s=t.status?.code===2?"\u274C":"\u2705",l=o.length>0?` [${o.join(", ")}]`:"";me.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${l}`),t.status?.code===2&&t.status.message&&me.log(` \u274C Error: ${t.status.message}`)}};var lt=["error","failed","exception","fatal","panic","abort","crash"];function ke(e){let t=e.split(`
|
|
2
|
+
`),r=[],n=-1,o=0;for(;o<t.length;){let a=t[o].slice(0,500).toLowerCase();if(lt.some(d=>a.includes(d))){let d=Math.max(0,o-10,n+1),c=Math.min(t.length-1,o+20),h=[];for(let m=d;m<=c;m++)h.push(t[m]);r.push(h.join(`
|
|
3
|
+
`)),n=c,o=c+1}else o++}if(r.length===0)return e;let s=r.map((l,a)=>`<extracted_error_chunk order="${a+1}">
|
|
4
4
|
${l}
|
|
5
5
|
</extracted_error_chunk>`).join(`
|
|
6
6
|
|
|
7
|
-
`);return s.length>e.length*.8?e:s}import
|
|
8
|
-
`).filter(o=>!
|
|
9
|
-
`).forEach(l=>{let
|
|
10
|
-
`))return;let
|
|
11
|
-
`).filter(Boolean).map(
|
|
12
|
-
|
|
13
|
-
`)}j&&
|
|
14
|
-
${
|
|
15
|
-
\`\`\``),T({title
|
|
16
|
-
`))return;let
|
|
17
|
-
`).filter(Boolean).map(
|
|
18
|
-
`):
|
|
19
|
-
`))}),
|
|
7
|
+
`);return s.length>e.length*.8?e:s}import ce from"process";import{getTracer as jt}from"@netlify/otel";import oe from"process";var he=oe.env.NETLIFY_API_URL,ye=oe.env.NETLIFY_API_TOKEN,Z=x("api"),se=async(e,t={})=>{if(!he||!ye)throw new Error("No API URL or token");let r=new URL(e,he),n={...t,headers:{...t.headers,Authorization:`Bearer ${ye}`}};oe.env.AGENT_RUNNERS_DEBUG==="true"&&(n.headers["x-nf-debug-logging"]="true"),t.json&&(n.headers||={},n.headers["Content-Type"]="application/json",n.body=JSON.stringify(t.json));let o=await fetch(r,n),s=o.ok&&o.status<=299;if(oe.env.AGENT_RUNNERS_DEBUG==="true")Z.log(`Response headers for ${r}:`),o.headers.forEach((a,i)=>{Z.log(` ${i}: ${a}`)});else{let a=o.headers.get("x-nf-request-id");Z.log(`Request ID for ${r}: ${a||"N/A"}`)}if(s||Z.error(`Got status ${o.status} for request ${r}`),t.raw){if(!s)throw o;return o}let l=await(o.headers.get("content-type")?.includes("application/json")?o.json():o.text());if(!s)throw l;return l},Oe=e=>{Z.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(he=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(ye=e.constants.NETLIFY_API_TOKEN)},ie=(e,t)=>se(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),B=(e,t,r)=>se(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var be=(e,t)=>se(`/api/v1/agent_runners/${e}/sessions/${t}`),$e=(e,t,r)=>se(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}});var De=x("ai_gateway"),Fe=async({netlify:e,config:t})=>{let r,n,o,s,l=e.constants?.SITE_ID;if(!l)throw new Error("No site id");let a=async()=>{clearTimeout(o),De.log("Requesting AI gateway information");let i=await $e(l,t.id,t.sessionId);if({token:r,url:s}=i,n=i.expires_at?i.expires_at*1e3:void 0,De.log("Got AI gateway information",{token:!!r,expiresAt:n,url:s}),n){let d=n-Date.now()-6e4;d>0&&(o=setTimeout(()=>{a()},d))}};return await a(),{get url(){return s},get token(){return r}}};import Le from"process";import{execa as ut,execaCommand as xr}from"execa";var Tr=x("shell"),ct={preferLocal:!0},je=(e,t,r)=>{let[n,o]=dt(t,r),s={...ct,...o},l=ut(e,n,s);return pt(l,s),l};var dt=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},pt=(e,t)=>{t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0||(e.stdout?.pipe(Le.stdout),e.stderr?.pipe(Le.stderr))};var Ue="netlify-agent-runner-context.md",_e="task-history",xe="netlify-context",b=".netlify",Q="results.md",Ee="assets",H="other",q="personal";var K="enterprise",V="free";var ft=x("utils"),mt=e=>new Promise(t=>{setTimeout(t,e)}),Me=(e,t=3e3)=>{let r=!1,n=null,o=[],s=null,l=(...a)=>{if(r)return n=a,new Promise(c=>{o.push(c)});r=!0;let i,d=new Promise(c=>{i=c});return s=(async()=>{await Promise.resolve();let c=await e(...a);for(i(c);;){if(await mt(t),!n)return r=!1,s=null,c;let h=n,m=o;n=null,o=[],c=await e(...h),m.forEach(_=>{_(c)})}})(),d};return l.flush=async()=>{if((r||n)&&s)return await s,l.flush()},l},ae=(e,t,r=!1)=>{let n=null,o=null,s=null,l=function(...a){o=a,s=this;let i=r&&!n;clearTimeout(n),n=setTimeout(()=>{n=null,r||(e.apply(s,o),o=null,s=null)},t),i&&(e.apply(s,o),o=null,s=null)};return l.cancel=()=>{clearTimeout(n),n=null,o=null,s=null},l.flush=()=>{if(n){clearTimeout(n);let a=o,i=s;n=null,o=null,s=null,e.apply(i,a)}},l},Ge=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(n){t&&(r?.error?r.error("Could not parse JSON",n):ft.error("Could not parse JSON",n))}},Ye=(e,t)=>{let o=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let a=`--${t}${o}`;if(a.length>55)return"";let i=60-a.length;if(i<=0)return"";if(i>=s.length+6){let d=Math.min(i-s.length,e.length);return`${s}${e.slice(0,d)}`}return e.slice(0,i)};import{Buffer as Be}from"buffer";var He=async({config:e,netlify:t})=>{let r=await ht(t),{hasChanges:n}=r,{status:o}=r;if(!n)return{hasChanges:!1};let s=await yt(t,o);await t.utils.run("git",["add",".",...s]);let l={stdio:["ignore","pipe","pipe"]},i=(await t.utils.run("git",["diff","--staged"],l)).stdout;if(n=!!i,!n)return{hasChanges:!1};let c=(await t.utils.run("git",["diff","--staged","--binary"],l)).stdout,h,m;if(e.sha){await t.utils.run("git",["commit","-m","Agent runner"]),h=(await t.utils.run("git",["diff",e.sha,"HEAD"],l)).stdout;let g=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"],l)).stdout;h!==g&&(m=Be.from(g).toString("base64"))}let _={hasChanges:!0,diff:i,resultDiff:h};return i!==c&&(_.diffBinary=Be.from(c).toString("base64")),m&&(_.resultDiffBinary=m),_},gt=["?? mise.toml",/\?\? .+?\.log/],ht=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
|
|
8
|
+
`).filter(o=>!gt.some(s=>s instanceof RegExp?s.test(o):o===s))).length!==0,status:t.stdout}};var qe=async e=>{let{stdout:t}=await e.utils.run("git",["rev-parse","HEAD"]);return t.trim()},Ke=async e=>{let{stdout:t}=await e.utils.run("git",["rev-list","--max-parents=0","HEAD"]);return t.trim()},yt=async(e,t="")=>{let r=[".netlify","mise.toml","node_modules"],n=[],o=r.map(async l=>{try{return await e.utils.run("git",["check-ignore","-v",l]),null}catch{return`:!${l}`}});return(await Promise.all(o)).forEach(l=>{l&&n.push(l)}),t.split(`
|
|
9
|
+
`).forEach(l=>{let a=l.match(/\?\? (.+?)\.log$/)?.[1];a&&n.push(`:!${a}.log`)}),n};import xt from"fs/promises";import Et from"os";import le from"path";import U from"process";import Te from"path";import _t from"fs/promises";var we=x("agent-output-utils");async function J({initialResult:e,agentName:t,hasError:r}){let n="",o=Te.join(process.cwd(),b,Q);try{let s=await _t.readFile(o,"utf-8");s&&(n=s,we.log(`Pulled result from ${Te.relative(process.cwd(),o)}`))}catch{we.log(`No results file found at ${Te.relative(process.cwd(),o)}`)}return n||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function W({error:e}){let t=e&&typeof e=="object"?JSON.stringify(e):e,r=t?.replace(/\s+/g," ").trim()||"",n="";return r?.includes("ai gateway is not available 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.":r?.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.":r?.includes("connection closed prematurely while waiting for the model")&&(n="The agent's models were currently overloaded. Please try again or use a different available agent."),n&&we.log(`Providing updated error messsage: ${n}, replacing original error: ${t}`),r||void 0}var L=x("runner_claude"),Tt="Claude Code",wt=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(L.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(L.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(L.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0}));async function Ie({config:e,netlify:t,persistSteps:r,aiGateway:n}){let o=e,{accountType:s,prompt:l,modelVersionOverrides:a}=o,{model:i}=o;if(n){let{token:w,url:f}=n;if(!w||!f)throw new Error("No token or url provided from AI Gateway");let p=It[s];if(!p)throw new Error(`Claude is not supported for the account type ${s}`);if(i&&!p?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(a?.claude){let u=a?.claude?.[s];u&&(i=u)}U.env.ANTHROPIC_API_KEY=w,U.env.ANTHROPIC_BASE_URL=f}else if(!U.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let d=[],c=[],h={},m=0,_=0,I,E,g=le.join(U.cwd(),"node_modules"),S=[le.join(U.env.NODE_PATH||g,".bin/claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...i?["--model",i]:[],"-p",l],R=`${U.env.NVM_BIN}/node`;L.log(`Running ${R} ${S.join(" ")}`);let v=t.utils.run(R,S,{all:!0,env:U.env});v.stdin?.end();let C=ae(()=>{r?.({steps:d,duration:_})},250),T=(w,f)=>{let p={...w,id:m};m+=1,c.push(p),d.push(p),f||C.flush(),C(),f&&C.flush()},N="";return v.all?.on("data",w=>{if(N+=w.toString(),!w.includes(`
|
|
10
|
+
`))return;let f=N.split(`
|
|
11
|
+
`).filter(Boolean).map(p=>{try{return JSON.parse(p)}catch{L.log("Could not parse line",p)}return null}).filter(Boolean);N="",f.forEach(p=>{Array.isArray(p?.message?.content)?p.message.content.forEach(u=>{switch(u.type){case"text":{u.text&&T({message:u.text});break}case"image":{typeof u.source=="object"&&u.source&&u.source.type==="base64"&&u.source.media_type?T({message:``}):L.log(`Unsupported image type ${u.source?.type}`,u.source);break}case"tool_use":{if(u.name==="Task"){let y=u.input?.description&&`\`${u.input.description}\``;T({title:[u.name,y].filter(Boolean).join(" ")})}else u.id&&(h[u.id]=u);C.flush();break}case"tool_result":{let y=u.tool_use_id?h[u.tool_use_id]:void 0,D;if(y){let F=y.input?.file_path&&le.relative(U.cwd(),y.input.file_path),A=F&&`\`${F}\``;D=[y.name,A].filter(Boolean).join(" ")}let j=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(y?.name||""),O;if(typeof u.content=="string")O=u.content;else if(Array.isArray(u.content)){let F=[];u.content.forEach(A=>{A?.type==="text"&&typeof A.text=="string"?F.push(A.text):A?.type==="image"&&typeof A.source=="object"&&A.source?A.source.type==="base64"&&A.source.media_type?F.push(``):L.log(`Unsupported image type ${A.source.type}`,A.source):L.log(`Unsupported block type ${A?.type}`)}),O=F.join(`
|
|
12
|
+
|
|
13
|
+
`)}j&&O&&(O=`\`\`\`
|
|
14
|
+
${O.trim()}
|
|
15
|
+
\`\`\``),T({title:D,message:O},!0);break}case"thinking":{u.thinking&&T({title:"Thinking",message:u.thinking},!0);break}default:L.log(`Message content type is not supported ${u.type}`,u)}}):p?.type==="result"&&(_=p.duration_ms||0,p.is_error?E=p.result:I=p.result,[c,d].forEach(u=>{u[u.length-1]?.message===I&&u.pop()}))})}),await v.catch(w=>{({error:E,result:I}=wt({catchError:w,runCmd:v,error:E,result:I,runnerName:"Claude"}))}),C.flush(),{steps:c,duration:_,result:await J({initialResult:I,agentName:Tt,hasError:!!E}),error:W({error:E})}}var Ve=async()=>{let e=le.join(Et.homedir(),".claude");await xt.rm(e,{recursive:!0,force:!0})},It={[K]:{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}}},[q]:{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}}},[H]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}}};import Ct from"fs/promises";import Rt from"os";import Ce from"path";import Y from"process";var X=x("runner_codex"),Nt="Codex CLI",At=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(X.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(X.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(X.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0}));async function Re({config:e,netlify:t,persistSteps:r,sendSteps:n,aiGateway:o}){let{accountType:s,prompt:l,modelVersionOverrides:a}=e,{model:i}=e;if(o){let{token:T,url:N}=o;if(!T||!N)throw new Error("No token or url provided from AI Gateway");let w=St[s];if(!w)throw new Error(`Codex is not supported for the account type ${s}`);if(i&&!w?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(a?.codex){let f=a?.codex?.[s];f&&(i=f)}Y.env.OPENAI_API_KEY=T,Y.env.OPENAI_BASE_URL=N}else if(!Y.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let d=[],c=[],h={},m=0,_=0,I,E,g=Ce.join(Y.cwd(),"node_modules"),S=[Ce.join(Y.env.NODE_PATH||g,".bin/codex"),"--approval-mode","full-auto",o?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...i?["--model",i]:[],"-q",l].filter(Boolean),R=`${Y.env.NVM_BIN}/node`;X.log(`Running ${R} ${S.join(" ")}`);let v=t.utils.run(R,S,{all:!0,env:{...Y.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),C="";return v.all.on("data",T=>{if(C+=T.toString(),!T.includes(`
|
|
16
|
+
`))return;let N=C.toString().split(`
|
|
17
|
+
`).filter(Boolean).map(p=>{try{return JSON.parse(p)}catch{X.log("Could not parse line",p)}return null}).filter(Boolean);C="";let w=[],f=!1;N.forEach(p=>{if(p?.duration_ms&&(_=p.duration_ms,f=!0),p?.type==="local_shell_call")h[p.call_id]=p;else if(p?.type==="local_shell_call_output"){let u=Pt(h[p.call_id],p);u.id=m,m+=1,u&&(c.push(u),d.push(u),w.push(u),f=!0)}else p?.type==="message"&&p.role==="assistant"?I=p.content.map(u=>u.text).join(`
|
|
18
|
+
`):p?.type==="message"&&p.role==="system"&&(E=p.content.map(u=>u.text).join(`
|
|
19
|
+
`))}),f&&(r?.({steps:d,duration:_}),n?.({steps:w,duration:_}))}),await v.catch(T=>{({error:E,result:I}=At({catchError:T,runCmd:v,error:E,result:I,runnerName:"Codex"}))}),{steps:c,duration:_,result:await J({initialResult:I,agentName:Nt,hasError:!!E}),error:W({error:E})}}var Je=async()=>{let e=Ce.join(Rt.homedir(),".codex");await Ct.rm(e,{recursive:!0,force:!0})},St={[K]:{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":{}}},[q]:{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}}},[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},"o3-mini":{maxTokens:16e3}}}},vt=new Set(["bash","-lc"]),Pt=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!vt.has(s)),n=r?`Running \`${r.join(" ")}\``:void 0,o;try{o=JSON.parse(t.output).output?.trim(),o&&(o=`\`\`\`
|
|
20
20
|
${o.trim()}
|
|
21
|
-
\`\`\``)}catch(s){
|
|
22
|
-
`))return;let
|
|
23
|
-
`).filter(Boolean).map(u=>{try{if(u.startsWith("[API Error")){let
|
|
21
|
+
\`\`\``)}catch(s){X.error("Could not decode outputMsg",s,t.output)}return{title:n,message:o}};import kt from"fs/promises";import Ot from"os";import ue from"path";import M from"process";var te=x("runner_gemini"),bt="Gemini CLI",$t=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(te.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(te.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(te.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0})),Dt={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 Ne({config:e,netlify:t,persistSteps:r,sendSteps:n,aiGateway:o}){let{accountType:s,prompt:l,modelVersionOverrides:a}=e,{model:i}=e;if(o){let{token:f,url:p}=o;if(!f||!p)throw new Error("No token or url provided from AI Gateway");let u=Ft[s];if(!u)throw new Error(`Gemini is not supported for the account type ${s}`);if(i&&!u?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(a?.gemini){let y=a?.gemini?.[s];y&&(i=y)}M.env.GEMINI_API_KEY=f,M.env.GOOGLE_GEMINI_BASE_URL=p}else if(!M.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let d=[],c=[],h=[],m={},_=0,I=0,E,g,S=ue.join(M.cwd(),"node_modules"),R=[ue.join(M.env.NODE_PATH||S,".bin/gemini"),...i?["--model",i]:[],"--yolo","-p",l],v=`${M.env.NVM_BIN}/node`;te.log(`Running ${v} ${R.join(" ")}`);let C=t.utils.run(v,R,{all:!0,env:M.env});C.stdin?.end();let T=ae(()=>{r?.({steps:d,duration:I}),n?.({steps:c,duration:I}),c=[]},250),N=(f,p)=>{f.id=_,_+=1,h.push(f),d.push(f),c.push(f),p||T.flush(),T(),p&&T.flush()},w="";return C.all.on("data",f=>{if(w+=f.toString(),!f.includes(`
|
|
22
|
+
`))return;let p=w.toString().split(`
|
|
23
|
+
`).filter(Boolean).map(u=>{try{if(u.startsWith("[API Error")){let y=u.match(/\[api error: (.+?)]$/i)?.[1];return{type:"error",value:Ge(y,!1)?.error?.message||y||"Gemini encountered error"}}return JSON.parse(u)}catch{}return null}).filter(Boolean);w="",p.forEach(u=>{switch(u.type){case"thought":{let y=u.value;N({title:y?.subject??"Thinking...",message:y?.description},!0);break}case"content":{u.value&&N({message:u.value});break}case"tool_call_request":{let y=u.value,D=Dt[y.name]??y.name,j=y.args?.path||y.args?.absolute_path,O=j&&ue.relative(M.cwd(),j),F=y.args?.command,ot={title:[D,O&&`\`${O}\``,F&&`\`${F}\``].filter(Boolean).join(" ")};m[y.callId]=ot,T.flush();break}case"tool_result":{let y=u.value,D=m[y.callId];if(D){let j=[y.resultDisplay,y.responseParts?.functionResponse?.response?.output].find(O=>typeof O=="string"&&O);j&&(D.message=`\`\`\`
|
|
24
24
|
${j.trim()}
|
|
25
|
-
\`\`\``),
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
If you need to start a local development server in order to fulfill the request, try using the Netlify CLI over by running the shell command '${e} dev'. This will start a local HTTP server on port 8888, including live-reloading of any changes and, most critically, it offers local emulation for all Netlify features.
|
|
30
|
-
|
|
31
|
-
## Netlify Site
|
|
32
|
-
- Site ID: ${n.siteId}
|
|
33
|
-
- Account ID: ${n.accountId}
|
|
34
|
-
- User ID: ${n.userId}
|
|
35
|
-
- Site Slug: ${n.siteSlug}
|
|
36
|
-
- Netlify Functions directory: ${n.functionsDir}
|
|
37
|
-
- Running Node Version: ${o.nodeVersion}
|
|
38
|
-
|
|
39
|
-
The available environment variables are set globally (e.g. \`echo $VARIABLE_NAME\` can be used to check if a var is set).:
|
|
40
|
-
|
|
41
|
-
## Attachments
|
|
42
|
-
|
|
43
|
-
- for requests that require work with attachments or assets, take into account that uploaded attachments are stored in .netlify/assets folder
|
|
44
|
-
- move assets from .netlify/assets folder to the project assets folder if they are referenced in a code or applied changes
|
|
45
|
-
|
|
46
|
-
## Netlify CLI
|
|
47
|
-
'netlify-cli' npm package is already available as a global package.
|
|
48
|
-
Don't try to install it, in case you want to use it, use the global package.
|
|
49
|
-
|
|
50
|
-
`;r.siteContext&&r.siteContext.length!==0&&(p+=`
|
|
51
|
-
# Project Guidelines
|
|
52
|
-
<project_guidelines>
|
|
53
|
-
${r.siteContext.filter(f=>f.site_context).map(f=>typeof f.site_context=="string"?f.site_context:typeof f.site_context=="object"?JSON.stringify(f.site_context):"").join(`
|
|
54
|
-
|
|
55
|
-
`)}
|
|
56
|
-
</project_guidelines>
|
|
57
|
-
`);let c=await Ut();if(c.length>0&&(p+=`
|
|
58
|
-
# Netlify Features Context
|
|
25
|
+
\`\`\``),N(D,!0)}break}case"result":{I=u.duration_ms,E=u.value,[h,d,c].forEach(y=>{y[y.length-1]?.message===E&&y.pop()});break}case"error":{g=u.value;break}case"finished":break;default:{te.warn("Unhandled message type:",u.type);break}}})}),await C.catch(f=>{({error:g,result:E}=$t({catchError:f,runCmd:C,error:g,result:E,runnerName:"Gemini"}))}),T.flush(),{steps:h,duration:I,result:await J({initialResult:E,agentName:bt,hasError:!!g}),error:W({error:g})}}var We=async()=>{let e=ue.join(Ot.homedir(),".gemini");await kt.rm(e,{recursive:!0,force:!0})},Ft={[K]:{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}}},[q]:{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}}},[H]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}}};var Lt={codex:{runner:Re,clean:Je},claude:{runner:Ie,clean:Ve},gemini:{runner:Ne,clean:We}},Xe=Lt;var ze=async({config:e,apiThrottle:t,apiToken:r})=>{let n=jt();return ne(n,"init-stage",async o=>{let s=performance.now();o?.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=Xe[e.runner];if(!l)throw o?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let a=Ut({apiToken:r});Oe(a);let i=e.useGateway?await Fe({netlify:a,config:e}):void 0;o?.setAttributes({"init.aiGateway.created":!!i}),e.validateAgent&&e.errorLogsPath&&o?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let d=Me(({steps:m=[],duration:_})=>{let I=[...m];return m.length=0,B(e.id,e.sessionId,{steps:I,duration:_})},t),c;e.hasRepo?e.sha?(c=e.sha,o?.setAttributes({"init.sha.source":"provided"})):(c=await qe(a),await ie(e.id,{sha:c}),o?.setAttributes({"init.sha.source":"current_commit"})):(c=await Ke(a),o?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let h=performance.now()-s;return o?.setAttributes({"init.sha":c||"unknown","init.duration.ms":h,"init.status":"success"}),{aiGateway:i,context:a,persistSteps:d,runner:l,sha:c}})},Ut=({apiToken:e})=>({constants:{NETLIFY_API_HOST:ce.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||ce.env.NETLIFY_API_TOKEN,SITE_ID:ce.env.SITE_ID,FUNCTIONS_DIST:ce.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:je}});import Mt from"crypto";import G from"fs/promises";import k from"path";import $ from"process";var P=x("context"),Gt=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:$.env.NETLIFY_TEAM_ID,userId:$.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:$.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},Yt=10,Bt=async e=>{let{name:t,ext:r}=k.parse(e),n=e,o=k.join($.cwd(),b,n),s=0;for(;await Ht(o);){if(s>=Yt)throw new Error("Failed to generate context file");n=`${t}-${Mt.randomUUID().slice(0,5)}${r}`,o=k.join($.cwd(),b,n),s+=1}return n},Ht=async e=>{try{return await G.access(e),!0}catch{return!1}},qt=async()=>{try{P.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 P.warn("Invalid response structure: missing or invalid consumers array"),null;let r=t.consumers.find(n=>n&&typeof n=="object"&&n.key==="catchall-consumer");return r?!r.contextScopes||typeof r.contextScopes!="object"?(P.warn("Catchall consumer missing or invalid contextScopes"),null):r:(P.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?P.warn("Netlify features context request timed out"):P.warn("Failed to fetch Netlify features context:",e.message),null}},Kt=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 n=await r.text();return await G.writeFile(t,n,"utf-8"),!0}catch(r){return r.name==="AbortError"?P.warn(`Download timeout for ${e}`):P.warn(`Failed to download context file ${e}:`,r.message),!1}},de=null,Vt=async()=>{if(de)return de;let e=await qt();if(!e)return[];let t=k.join($.cwd(),b,xe);await G.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([o,s])=>{if(!s||typeof s!="object"||!s.endpoint||!s.scope)return P.warn(`Invalid scope data for ${o}, skipping...`),null;let l=`${o}.md`,a=k.join(t,l),i=k.join(b,xe,l);return P.log(`Downloading ${s.scope} context...`),await Kt(s.endpoint,a)?(P.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:o}):null});return de=(await Promise.all(r)).filter(o=>o!==null),de},Ze=async({cliPath:e,netlify:t,config:r,buildErrorContext:n})=>{let o=Gt(t),s=await Bt(Ue),l=k.join($.cwd(),b);await G.mkdir(l,{recursive:!0});let a=k.join(b,s),i=k.join($.cwd(),a),d=k.join($.cwd(),b,Q);try{await G.unlink(d),P.log(`Deleted old results file: ${d}`)}catch{}let c=n?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
|
|
26
|
+
Your task is to analyze and fix the build errors.
|
|
27
|
+
Don't apply techniques of reverting changes. Apply fixes related to errors.
|
|
28
|
+
Don't try to run build by yourself. Just fix the errors.
|
|
59
29
|
|
|
60
|
-
|
|
61
|
-
|
|
30
|
+
<build_error_context>
|
|
31
|
+
${c}
|
|
32
|
+
</build_error_context>`:"",h="";r.siteContext&&r.siteContext.length!==0&&(h=`
|
|
33
|
+
<project_rules>
|
|
34
|
+
${r.siteContext.filter(g=>g.site_context).map(g=>typeof g.site_context=="string"?g.site_context:typeof g.site_context=="object"?JSON.stringify(g.site_context):"").join(`
|
|
62
35
|
|
|
63
|
-
${c.map(f=>`- **${f.scope}**: ${f.path}`).join(`
|
|
64
36
|
`)}
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
`),p+=`
|
|
68
|
-
Additional Documentation Resources
|
|
69
|
-
- Netlify Docs: https://docs.netlify.com
|
|
70
|
-
- LLM Resources Index: https://docs.netlify.com/llms.txt
|
|
71
|
-
`,r.sessionHistoryContext?.length){let f=O.join(b.cwd(),F,he);await G.mkdir(f,{recursive:!0});let g=await Promise.all(r.sessionHistoryContext.map(async(y,E)=>{let x=E+1,C=`attempt-${x}.md`,N=O.join(f,C),A=O.join(F,he,C),S=`# Task History - Attempt ${x}
|
|
37
|
+
</project_rules>
|
|
38
|
+
`);let m="";if(r.sessionHistoryContext?.length){let g=k.join($.cwd(),b,_e);await G.mkdir(g,{recursive:!0});let S=await Promise.all(r.sessionHistoryContext.map(async(R,v)=>{let C=v+1,T=`attempt-${C}.md`,N=k.join(g,T),w=k.join(b,_e,T),f=`# Task History - Attempt ${C}
|
|
72
39
|
|
|
73
40
|
## Request - what the user asked for
|
|
74
|
-
${
|
|
41
|
+
${R.request}
|
|
75
42
|
|
|
76
43
|
---
|
|
77
44
|
|
|
78
45
|
## Response - what the agent replied with after its work
|
|
79
46
|
|
|
80
|
-
${
|
|
81
|
-
`;return await G.writeFile(N,
|
|
82
|
-
|
|
83
|
-
|
|
47
|
+
${R.response}
|
|
48
|
+
`;return await G.writeFile(N,f,"utf-8"),P.log(`Created history file: ${w}`),w}));m+=`
|
|
49
|
+
<session_history_context>
|
|
50
|
+
History of prior work on this task.
|
|
51
|
+
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
52
|
|
|
85
|
-
${
|
|
53
|
+
${S.slice(-5).map(R=>`- ${R}`).join(`
|
|
86
54
|
`)}
|
|
87
|
-
`}return await G.writeFile(a,p,"utf-8"),P.log(`Generated agent context document at: ${a}`),i},Ke=e=>`The build is currently failing after your changes.
|
|
88
|
-
Your task is to analyze and fix the build errors.
|
|
89
|
-
Don't apply techniques of reverting changes. Apply fixes related to errors.
|
|
90
|
-
Don't try to run build by yourself. Just fix the errors.
|
|
91
55
|
|
|
92
|
-
|
|
56
|
+
</session_history_context>
|
|
57
|
+
`}let _=await Vt(),I="";_.length>0&&(I=`
|
|
58
|
+
<netlify_features_context>
|
|
59
|
+
If the user request is explicitly related to a specific Netlify feature (e.g., Netlify Forms, Netlify Functions, etc.), you MUST review the relevant documentation below in addition to reviewing the project files.
|
|
60
|
+
DO NOT force the use of any Netlify feature if the user request does not explicitly require it or if the project has alternative implementations in place already.
|
|
93
61
|
|
|
94
|
-
`)
|
|
62
|
+
${_.map(g=>`- **${g.scope}**: ${g.path}`).join(`
|
|
63
|
+
`)}
|
|
95
64
|
|
|
96
|
-
|
|
65
|
+
Refer to these files when working with specific Netlify features.
|
|
66
|
+
</netlify_features_context>
|
|
67
|
+
`);let E=`
|
|
68
|
+
You're an AI agent designed to assist with tasks related to a Netlify project. Please review, understand, and use the context provided to complete the user's request as needed.
|
|
69
|
+
|
|
70
|
+
<request>
|
|
71
|
+
<user_request>
|
|
72
|
+
${r.prompt}
|
|
73
|
+
</user_request>
|
|
74
|
+
${c}
|
|
75
|
+
</request>
|
|
76
|
+
|
|
77
|
+
<requirements>
|
|
78
|
+
<responses>
|
|
79
|
+
- Do not speak in first person. You may speak as "the agent".
|
|
80
|
+
- When your work is complete, create a changelog summary in ${l}/${Q} that is pull request or changelog blog appropriate for the primary work that was completed.
|
|
81
|
+
- Do not attempt to create git commits, PRs, etc. directly. You can use git to review information if required but the system that runs this agent will handle creating PRs or commits of the changes it performs.
|
|
82
|
+
</responses>
|
|
83
|
+
<attachements>
|
|
84
|
+
- for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${l}/${Ee} folder
|
|
85
|
+
- move assets from ${l}/${Ee} folder to the project assets folder if they are referenced in a code or applied changes
|
|
86
|
+
</attachements>
|
|
87
|
+
${h}
|
|
88
|
+
</requirements>
|
|
89
|
+
|
|
90
|
+
<extra_context>
|
|
91
|
+
<metadata>
|
|
92
|
+
- Site/Project ID: ${o.siteId}
|
|
93
|
+
- Account/Team ID: ${o.accountId}
|
|
94
|
+
- User ID: ${o.userId}
|
|
95
|
+
- Site/Project Slug: ${o.siteSlug}
|
|
96
|
+
- Netlify Functions directory: ${o.functionsDir}
|
|
97
|
+
</metadata>
|
|
98
|
+
<environment>
|
|
99
|
+
- Node Version: ${$.version||"unknown"}
|
|
100
|
+
- Environment variables are set globally (e.g. \`echo $VARIABLE_NAME\` can be used to check if a var is set).
|
|
101
|
+
- 'netlify-cli' npm package is already available as a global package. Don't try to install it again
|
|
102
|
+
- If you need to start a local development server in order to fulfill the request, try using the Netlify CLI over by running the shell command '${e} dev'. This will start a local HTTP server on port 8888, including live-reloading of any changes and, most critically, it offers local emulation for all Netlify features.
|
|
103
|
+
</environment>
|
|
104
|
+
${I}
|
|
105
|
+
<docs>
|
|
106
|
+
- Netlify Docs: https://docs.netlify.com
|
|
107
|
+
- LLM Resources Index: https://docs.netlify.com/llms.txt
|
|
108
|
+
</docs>
|
|
109
|
+
</extra_context>
|
|
110
|
+
|
|
111
|
+
${m}
|
|
112
|
+
`;return await G.writeFile(i,E,"utf-8"),P.log(`Generated agent context document at: ${i}`),E.length>5e5&&(E=`
|
|
113
|
+
You're an AI agent designed to assist with tasks related to a Netlify project. Please review, understand, and use the context provided to complete the user's request as needed.
|
|
114
|
+
|
|
115
|
+
<request>
|
|
116
|
+
<user_request>
|
|
117
|
+
${r.prompt}
|
|
118
|
+
</user_request>
|
|
119
|
+
${c}
|
|
120
|
+
</request>
|
|
121
|
+
|
|
122
|
+
Use the following file for the complete context of the ask, the environment, and what's available. ${i} You MUST READ ALL OF IT. Make sure to read it first. Never cite or paraphrase private context.
|
|
123
|
+
`),E};var Jt=x("prompt"),Qe=async({cliPath:e,config:t,netlify:r,buildErrorContext:n})=>{let o=await Ze({cliPath:e,config:t,netlify:r,buildErrorContext:n});return process.env.AGENT_RUNNER_DEBUG&&Jt.log("Contextful Prompt:",o),{prompt:o}};var Wt=x("inference_stage"),Ae=async({cliPath:e,config:t,context:r,buildErrors:n,runner:o,persistSteps:s,aiGateway:l})=>{let{prompt:a}=await Qe({cliPath:e,config:t,buildErrorContext:Xt(n),netlify:r}),i={...t,prompt:a},d=await o({aiGateway:l,config:i,netlify:r,persistSteps:s});if(await s.flush(),d.error)throw Wt.error("Runner failed",{stepsCount:d.steps.length,duration:d.duration,error:d.error}),new Error(d.error);return{runnerResult:d}},Xt=e=>!e||e.length===0?"":`
|
|
97
124
|
Deploy failed failed. Here are the errors to review on the latest build:
|
|
98
125
|
|
|
99
126
|
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.
|
|
100
127
|
|
|
101
128
|
${e.pop()}
|
|
102
|
-
`;import
|
|
103
|
-
Preview deploy created successfully:`,{deployId:c.deploy_id,deployUrl:c.deploy_url,siteId:c.site_id});let
|
|
129
|
+
`;import zt from"process";var re=x("deploy"),et=async({netlify:e,hasRepo:t,skipBuild:r,message:n="Agent Preview",deploySubdomain:o,cliPath:s,filter:l})=>{try{let a=["deploy","--message",`"${n}"`,"--json","--draft","--verbose"];t||(re.log("Deploy: Uploading source zip"),a.push("--upload-source-zip")),o&&a.push("--alias",o),l&&a.push("--filter",l),r?(re.log("Deploy: Skipping build"),a.push("--no-build")):a.push("--context","deploy-preview");let i=s||"netlify";re.log(`Running: ${i} ${a.join(" ")}`);let d=await e.utils.run(i,a,{stdio:["ignore","pipe","pipe"]}),c=JSON.parse(d.stdout.trim());re.log(`
|
|
130
|
+
Preview deploy created successfully:`,{deployId:c.deploy_id,deployUrl:c.deploy_url,siteId:c.site_id});let h={deployId:c.deploy_id,previewUrl:c.deploy_url,logsUrl:c.logs,siteId:c.site_id};return t||(h.sourceZipFilename=c.source_zip_filename),h}catch(a){throw re.error("Failed to create preview deploy via CLI:",a),a}};var pe=x("deploy_stage"),Se=async({cliPath:e,config:t,context:r,result:n,filter:o})=>{let s=await He({config:t,netlify:r});if(!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:l,resultDiff:a,diffBinary:i,resultDiffBinary:d}=s,c=!0;pe.log("Preview deploy condition check:",{resultUndefined:n===void 0,resultType:typeof n,hasChanges:c,wouldCreatePreview:n!==void 0&&c});let h=null;if(n!==void 0&&c)try{let m;try{let _=await be(t.id,t.sessionId);_?.title&&(m=_.title)}catch(_){pe.warn("Failed to fetch session title, using fallback message:",_.message)}h=await et({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:m,skipBuild:!1,deploySubdomain:Ye(t.id,zt.env.SITE_NAME),filter:o})}catch(m){return pe.warn("Failed to create preview deploy (continuing with agent run):",m),{diff:l,resultDiff:a,hasChanges:c,previewInfo:null,diffBinary:i,resultDiffBinary:d,deployError:m instanceof Error?m.message:String(m)}}return pe.log("Git status",{hasDiff:!!l,hasChanges:c}),{diff:l,resultDiff:a,hasChanges:c,previewInfo:h,diffBinary:i,resultDiffBinary:d}};async function tt(e,t){let{maxRetries:r,baseDelay:n,onRetry:o}=t,s;for(let l=1;l<=r;l++)try{return await e()}catch(a){if(s=a,l===r)throw s;o&&o(l,s),await new Promise(i=>setTimeout(i,n*l))}throw s}var z=x("cleanup_stage"),rt=async({config:e,diff:t,result:r,duration:n,resultDiff:o,diffBinary:s,resultDiffBinary:l,previewInfo:a})=>{let i={result_diff:t,result:r||"Done",duration:n,result_diff_binary:s};return a&&a.deployId&&(i.deploy_id=a.deployId),a&&a.sourceZipFilename&&(i.result_zip_file_name=a.sourceZipFilename),o||l?(z.log("Updating total agent result diff"),await ie(e.id,{result_diff:o,result_diff_binary:l})):z.log("No total result diff, not updating"),z.log("Updated agent runner with result"),await tt(()=>B(e.id,e.sessionId,i),{maxRetries:3,baseDelay:1e3,onRetry:(d,c)=>{z.error(`Error updating agent runner session (attempt ${d}):`,c),z.log("Retrying...")}}),z.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as Qt}from"@netlify/otel";var er=Zt(import.meta.url),tr=er("../package.json"),nt=x("pipeline_index"),fe=3,so=async({config:e,apiToken:t,cliPath:r="netlify",cwd:n,errorLogsPath:o,filter:s,traceExporterUrl:l})=>{let a;try{await Pe(tr.version,e.id,l);let i=Qt(),d,{aiGateway:c,context:h,persistSteps:m,runner:_,sha:I}=await ze({config:e,apiToken:t,cliPath:r,cwd:n,errorLogsPath:o,filter:s});a=_.clean,e.sha=I;let{runnerResult:E}=await Ae({cliPath:r,config:e,context:h,runner:_.runner,persistSteps:m,aiGateway:c}),g=await Se({cliPath:r,config:e,context:h,result:E.result,filter:s}),S=E,R=[];if(g.hasChanges&&g.deployError){R.push(ke(g.deployError));let f=1;for(;f<=fe&&!g.previewInfo;)nt.log(`Deploy attempt had errors. Retrying. ${f}/${fe}`),await ne(i,"stage-deploy",async p=>{p?.setAttributes({"stage.attempt":f});let{runnerResult:u}=await Ae({cliPath:r,config:e,context:h,runner:_.runner,persistSteps:m,aiGateway:c,buildErrors:R});S={...u,steps:[...S.steps||[],...u.steps||[]],duration:(S.duration||0)+(u.duration||0)},g=await Se({cliPath:r,config:e,context:h,result:u.result,filter:s}),g.deployError&&R.push(g.deployError),f++});f>fe&&!g.previewInfo&&(d=new Error(`Deploy validation failed after ${fe} attempts`))}let{diff:v,resultDiff:C,previewInfo:T,diffBinary:N,resultDiffBinary:w}=g;if(await rt({config:e,diff:v,result:S.result,duration:S.duration,resultDiff:C,diffBinary:N,resultDiffBinary:w,previewInfo:T}),d)throw d;await _.clean?.()}catch(i){nt.error("Got error while running pipeline",i),await a?.();let d=i instanceof Error&&i.message;throw await B(e.id,e.sessionId,{result:d||"Encountered error when running agent",state:"error"}),i}};export{so as runPipeline};
|
|
104
131
|
//# sourceMappingURL=index.js.map
|