@netlify/agent-runner-cli 1.29.0 → 1.30.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 +33 -33
- package/dist/index.js +33 -33
- package/package.json +1 -1
package/dist/bin.js
CHANGED
|
@@ -1,42 +1,42 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`),r=[],
|
|
4
|
-
`)),
|
|
2
|
+
import De from"process";import Nr from"minimist";import{createRequire as _r}from"module";import{createTracerProvider as Nt}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as Fe}from"@netlify/otel/opentelemetry";import{withActiveSpan as Ct}from"@netlify/otel";import{OTLPTraceExporter as At}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 xe=_("tracing"),Ue=(e,t,r)=>Nt({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new Fe(new Re),new Fe(new At({url:r}))]});function le(e,t,r){return xe.log(`\u23F3 TRACE: ${t} starting...`),Ct(e,t,r)}var Re=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[l,i]of Object.entries(n))l.includes("duration")&&typeof i=="number"?o.push(`${l}=${i.toFixed(2)}ms`):o.push(`${l}=${i}`);let s=t.status?.code===2?"\u274C":"\u2705",a=o.length>0?` [${o.join(", ")}]`:"";xe.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${a}`),t.status?.code===2&&t.status.message&&xe.log(` \u274C Error: ${t.status.message}`)}};var St=["error","failed","exception","fatal","panic","abort","crash"];function Me(e){let t=e.split(`
|
|
3
|
+
`),r=[],n=-1,o=0;for(;o<t.length;){let l=t[o].slice(0,500).toLowerCase();if(St.some(d=>l.includes(d))){let d=Math.max(0,o-10,n+1),c=Math.min(t.length-1,o+20),p=[];for(let h=d;h<=c;h++)p.push(t[h]);r.push(p.join(`
|
|
4
|
+
`)),n=c,o=c+1}else o++}if(r.length===0)return e;let s=r.map((a,l)=>`<extracted_error_chunk order="${l+1}">
|
|
5
5
|
${a}
|
|
6
6
|
</extracted_error_chunk>`).join(`
|
|
7
7
|
|
|
8
|
-
`);return s.length>e.length*.8?e:s}import he from"process";import{getTracer as
|
|
9
|
-
`).filter(
|
|
10
|
-
`).forEach(a=>{let l=a.match(/\?\? (.+?)\.log$/)?.[1];l&&
|
|
11
|
-
`))return;let
|
|
12
|
-
`).filter(Boolean).map(f=>{try{return JSON.parse(f)}catch{
|
|
8
|
+
`);return s.length>e.length*.8?e:s}import he from"process";import{getTracer as sr}from"@netlify/otel";import ue from"process";var we=ue.env.NETLIFY_API_URL,Ie=ue.env.NETLIFY_API_TOKEN,re=_("api"),ce=async(e,t={})=>{if(!we||!Ie)throw new Error("No API URL or token");let r=new URL(e,we),n={...t,headers:{...t.headers,Authorization:`Bearer ${Ie}`}};ue.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(ue.env.AGENT_RUNNERS_DEBUG==="true")re.log(`Response headers for ${r}:`),o.headers.forEach((l,i)=>{re.log(` ${i}: ${l}`)});else{let l=o.headers.get("x-request-id")||o.headers.get("x-nf-request-id");re.log(`Request ID for ${r}: ${l||"N/A"}`)}if(s||re.error(`Got status ${o.status} for request ${r}`),t.raw){if(!s)throw o;return o}let a=await(o.headers.get("content-type")?.includes("application/json")?o.json():o.text());if(!s)throw a;return a},Ge=e=>{re.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(we=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Ie=e.constants.NETLIFY_API_TOKEN)},pe=(e,t)=>ce(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),J=(e,t,r)=>ce(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var je=(e,t)=>ce(`/api/v1/agent_runners/${e}/sessions/${t}`),Ye=(e,t,r)=>ce(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}});var Be=_("ai_gateway"),He=async({netlify:e,config:t})=>{let r,n,o,s,a=e.constants?.SITE_ID;if(!a)throw new Error("No site id");let l=async()=>{clearTimeout(o),Be.log("Requesting AI gateway information");let i=await Ye(a,t.id,t.sessionId);if({token:r,url:s}=i,n=i.expires_at?i.expires_at*1e3:void 0,Be.log("Got AI gateway information",{token:!!r,expiresAt:n,url:s}),n){let d=n-Date.now()-6e4;d>0&&(o=setTimeout(()=>{l()},d))}};return await l(),{get url(){return s},get token(){return r}}};import oe from"process";import{execa as bt,execaCommand as qr}from"execa";import{Transform as Pt}from"stream";var vt=["NODE_ENV","PATH","HOME","USER","USERNAME","SHELL","PWD","OLDPWD","TMPDIR","TMP","TEMP","LANG","TERM","EDITOR","PAGER","OS","PROCESSOR_ARCHITECTURE","PROCESSOR_IDENTIFIER","SYSTEMROOT","WINDIR","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","APPDATA","LOCALAPPDATA","NODE_OPTIONS","NODE_PATH","NODE_DEBUG","NODE_NO_WARNINGS","npm_config_registry","npm_config_cache","npm_execpath","npm_node_execpath","CI","GITHUB_ACTIONS","GITHUB_WORKSPACE","GITHUB_REPOSITORY","GITHUB_REF","BUILDKITE","BUILDKITE_BRANCH","BUILDKITE_COMMIT","BUILDKITE_BUILD_NUMBER","JENKINS_URL","TRAVIS","CIRCLECI","DISPLAY","COLORTERM","TERM_PROGRAM","TERM_PROGRAM_VERSION","COLUMNS","LINES","HISTSIZE","HISTFILE"];function Ot(){return Object.entries(process.env).filter(([e,t])=>!(!t||vt.includes(e)||t.length<5)).map(([,e])=>e).filter(Boolean)}function Ne(e){if(typeof e!="string")return e;let t=Ot();if(t.length===0)return e;let r=e;return t.forEach(n=>{let o=new RegExp(kt(n),"g");r=r.replace(o,"******")}),r}function kt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ne=class extends Pt{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,n){let o=t.toString(),s=Ne(o);n(null,s)}};function qe(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(n,o,s){let a=typeof n=="string"?Ne(n):n;return typeof o=="function"?t(a,o):t(a,o,s)},process.stderr.write=function(n,o,s){let a=typeof n=="string"?Ne(n):n;return typeof o=="function"?r(a,o):r(a,o,s)}}var Wr=_("shell"),Lt={preferLocal:!0},Ve=(e,t,r)=>{let[n,o]=$t(t,r),s={...Lt,...o},a=bt(e,n,s);return Dt(a,s),a};var $t=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Dt=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(oe.env.NETLIFY_MASK_LOGS!=="false"){e.stdout?.pipe(new ne).pipe(oe.stdout),e.stderr?.pipe(new ne).pipe(oe.stderr);return}e.stdout?.pipe(oe.stdout),e.stderr?.pipe(oe.stderr)};var Ke="netlify-agent-runner-context.md",Ce="task-history",Ae="netlify-context",L=".netlify",se="results.md",Se="assets",U="other",M="personal";var G="enterprise",j="free",We=[M,"pro",G,j];var Je=_("utils"),Ft=e=>new Promise(t=>{setTimeout(t,e)}),Xe=(e,t=3e3)=>{let r=!1,n=null,o=[],s=null,a=(...l)=>{if(r)return n=l,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(...l);for(i(c);;){if(await Ft(t),!n)return r=!1,s=null,c;let p=n,h=o;n=null,o=[],c=await e(...p),h.forEach(E=>{E(c)})}})(),d};return a.flush=async()=>{if((r||n)&&s)return await s,a.flush()},a},de=(e,t,r=!1)=>{let n=null,o=null,s=null,a=function(...l){o=l,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 a.cancel=()=>{clearTimeout(n),n=null,o=null,s=null},a.flush=()=>{if(n){clearTimeout(n);let l=o,i=s;n=null,o=null,s=null,e.apply(i,l)}},a},fe=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(n){t&&(r?.error?r.error("Could not parse JSON",n):Je.error("Could not parse JSON",n))}},ze=(e,t)=>{let o=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let l=`--${t}${o}`;if(l.length>55)return"";let i=60-l.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)},Ut=e=>!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0?!1:!!We.some(t=>t in e),Ze=()=>{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);Ut(s)&&(e[r]=s)}catch(s){let l=s instanceof SyntaxError?"Invalid JSON":s.message;Je.error(`Could not parse ${r} model version override from ${o}: ${l}`)}}}),e};import{Buffer as Qe}from"buffer";var et=async({config:e,netlify:t})=>{let r=await Gt(t),{hasChanges:n}=r,{status:o}=r;if(!n)return{hasChanges:!1};let s=await jt(t,o);await t.utils.run("git",["add",".",...s]);let a={stdio:["ignore","pipe","pipe"]},i=(await t.utils.run("git",["diff","--staged"],a)).stdout;if(n=!!i,!n)return{hasChanges:!1};let c=(await t.utils.run("git",["diff","--staged","--binary"],a)).stdout,p,h;if(e.sha){await t.utils.run("git",["commit","-m","Agent runner"]),p=(await t.utils.run("git",["diff",e.sha,"HEAD"],a)).stdout;let m=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;p!==m&&(h=Qe.from(m).toString("base64"))}let E={hasChanges:!0,diff:i,resultDiff:p};return i!==c&&(E.diffBinary=Qe.from(c).toString("base64")),h&&(E.resultDiffBinary=h),E},Mt=["?? mise.toml","?? deno.lock",/\?\? .+?\.log/],Gt=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
|
|
9
|
+
`).filter(o=>!Mt.some(s=>s instanceof RegExp?s.test(o):o===s))).length!==0,status:t.stdout}};var tt=async e=>{let{stdout:t}=await e.utils.run("git",["rev-parse","HEAD"]);return t.trim()},rt=async e=>{let{stdout:t}=await e.utils.run("git",["rev-list","--max-parents=0","HEAD"]);return t.trim()},jt=async(e,t="")=>{let r=[".netlify","mise.toml","deno.lock","node_modules"],n=[],o=r.map(async a=>{try{return await e.utils.run("git",["check-ignore","-v",a]),null}catch{return`:!${a}`}});return(await Promise.all(o)).forEach(a=>{a&&n.push(a)}),t.split(`
|
|
10
|
+
`).forEach(a=>{let l=a.match(/\?\? (.+?)\.log$/)?.[1];l&&n.push(`:!${l}.log`)}),n};import Bt from"fs/promises";import Ht from"os";import me from"path";import H from"process";import Pe from"path";import Yt from"fs/promises";var ve=_("agent-output-utils");async function X({initialResult:e,agentName:t,hasError:r}){let n="",o=Pe.join(process.cwd(),L,se);try{let s=await Yt.readFile(o,"utf-8");s&&(n=s,ve.log(`Pulled result from ${Pe.relative(process.cwd(),o)}`))}catch{ve.log(`No results file found at ${Pe.relative(process.cwd(),o)}`)}return n||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function z({error:e,agentName:t}){let r=e&&typeof e=="object"?JSON.stringify(e):e,n=r?.replace(/\s+/g," ").trim()||"",o="";return n?.includes("ai gateway is not available for your account")?o="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.":n?.includes("error when talking to gemini api")?o="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":(n?.includes("connection closed prematurely while waiting for the model")||n?.includes("499")&&t.toLowerCase().includes("gemini"))&&(o="The agent's models were currently overloaded. Please try again or use a different available agent."),o&&ve.log(`Providing updated error messsage: ${o}, replacing original error: ${r}`),o||r||void 0}function Z(e){if(!e)return!1;let r=(e&&typeof e=="object"?JSON.stringify(e):e)?.replace(/\s+/g," ").trim()||"";return!!(r?.includes("error when talking to gemini api")||r?.includes("connection closed prematurely while waiting for the model"))}var Y=_("runner_claude"),nt="Claude Code",qt=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(Y.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?(Y.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}):(Y.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0}));async function Oe({config:e,netlify:t,persistSteps:r,aiGateway:n}){let o=e,{accountType:s,prompt:a,modelVersionOverrides:l}=o,{model:i}=o;if(n){let{token:w,url:g}=n;if(!w||!g)throw new Error("No token or url provided from AI Gateway");let f=Vt[s];if(!f)throw new Error(`Claude is not supported for the account type ${s}`);if(i&&!f?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(l?.claude){let u=l?.claude?.[s];u&&(i=u)}H.env.ANTHROPIC_API_KEY=w,H.env.ANTHROPIC_BASE_URL=g}else if(!H.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let d=[],c=[],p={},h=0,E=0,x,T,m=me.join(H.cwd(),"node_modules"),N=[me.join(H.env.NODE_PATH||m,".bin/claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...i?["--model",i]:[],"-p",a],C=`${H.env.NVM_BIN}/node`;Y.log(`Running ${C} ${N.join(" ")}`);let P=t.utils.run(C,N,{all:!0,env:H.env});P.stdin?.end();let I=de(()=>{r?.({steps:d,duration:E})},250),R=(w,g)=>{let f={...w,id:h};h+=1,c.push(f),d.push(f),g||I.flush(),I(),g&&I.flush()},A="";return P.all?.on("data",w=>{if(A+=w.toString(),!w.includes(`
|
|
11
|
+
`))return;let g=A.split(`
|
|
12
|
+
`).filter(Boolean).map(f=>{try{return JSON.parse(f)}catch{Y.log("Could not parse line",f)}return null}).filter(Boolean);A="",g.forEach(f=>{Array.isArray(f?.message?.content)?f.message.content.forEach(u=>{switch(u.type){case"text":{u.text&&R({message:u.text});break}case"image":{typeof u.source=="object"&&u.source&&u.source.type==="base64"&&u.source.media_type?R({message:``}):Y.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}\``;R({title:[u.name,y].filter(Boolean).join(" ")})}else u.id&&(p[u.id]=u);I.flush();break}case"tool_result":{let y=u.tool_use_id?p[u.tool_use_id]:void 0,D;if(y){let F=y.input?.file_path&&me.relative(H.cwd(),y.input.file_path),S=F&&`\`${F}\``;D=[y.name,S].filter(Boolean).join(" ")}let B=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(y?.name||""),b;if(typeof u.content=="string")b=u.content;else if(Array.isArray(u.content)){let F=[];u.content.forEach(S=>{S?.type==="text"&&typeof S.text=="string"?F.push(S.text):S?.type==="image"&&typeof S.source=="object"&&S.source?S.source.type==="base64"&&S.source.media_type?F.push(``):Y.log(`Unsupported image type ${S.source.type}`,S.source):Y.log(`Unsupported block type ${S?.type}`)}),b=F.join(`
|
|
13
13
|
|
|
14
14
|
`)}B&&b&&(b=`\`\`\`
|
|
15
15
|
${b.trim()}
|
|
16
|
-
\`\`\``),R({title:D,message:b},!0);break}case"thinking":{u.thinking&&R({title:"Thinking",message:u.thinking},!0);break}default:
|
|
16
|
+
\`\`\``),R({title:D,message:b},!0);break}case"thinking":{u.thinking&&R({title:"Thinking",message:u.thinking},!0);break}default:Y.log(`Message content type is not supported ${u.type}`,u)}}):f?.type==="result"&&(E=f.duration_ms||0,f.is_error?T=f.result:x=f.result,[c,d].forEach(u=>{u[u.length-1]?.message===x&&u.pop()}))})}),await P.catch(w=>{({error:T,result:x}=qt({catchError:w,runCmd:P,error:T,result:x,runnerName:"Claude"}))}),I.flush(),{steps:c,duration:E,result:await X({initialResult:x,agentName:nt,hasError:!!T}),error:z({error:T,agentName:nt}),isRetryableError:Z(T)}}var ot=async()=>{let e=me.join(Ht.homedir(),".claude");await Bt.rm(e,{recursive:!0,force:!0})},Vt={[G]:{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}}},[M]:{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}}},[U]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}}};import Kt from"fs/promises";import Wt from"os";import ke from"path";import W from"process";var Q=_("runner_codex"),st="Codex CLI",Jt=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(Q.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?(Q.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}):(Q.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0}));async function be({config:e,netlify:t,persistSteps:r,sendSteps:n,aiGateway:o}){let{accountType:s,prompt:a,modelVersionOverrides:l}=e,{model:i}=e;if(o){let{token:R,url:A}=o;if(!R||!A)throw new Error("No token or url provided from AI Gateway");let w=Xt[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(l?.codex){let g=l?.codex?.[s];g&&(i=g)}W.env.OPENAI_API_KEY=R,W.env.OPENAI_BASE_URL=A}else if(!W.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let d=[],c=[],p={},h=0,E=0,x,T,m=ke.join(W.cwd(),"node_modules"),N=[ke.join(W.env.NODE_PATH||m,".bin/codex"),"--approval-mode","full-auto",o?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...i?["--model",i]:[],"-q",a].filter(Boolean),C=`${W.env.NVM_BIN}/node`;Q.log(`Running ${C} ${N.join(" ")}`);let P=t.utils.run(C,N,{all:!0,env:{...W.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),I="";return P.all.on("data",R=>{if(I+=R.toString(),!R.includes(`
|
|
17
17
|
`))return;let A=I.toString().split(`
|
|
18
|
-
`).filter(Boolean).map(f=>{try{return JSON.parse(f)}catch{Q.log("Could not parse line",f)}return null}).filter(Boolean);I="";let w=[],
|
|
18
|
+
`).filter(Boolean).map(f=>{try{return JSON.parse(f)}catch{Q.log("Could not parse line",f)}return null}).filter(Boolean);I="";let w=[],g=!1;A.forEach(f=>{if(f?.duration_ms&&(E=f.duration_ms,g=!0),f?.type==="local_shell_call")p[f.call_id]=f;else if(f?.type==="local_shell_call_output"){let u=Zt(p[f.call_id],f);u.id=h,h+=1,u&&(c.push(u),d.push(u),w.push(u),g=!0)}else f?.type==="message"&&f.role==="assistant"?x=f.content.map(u=>u.text).join(`
|
|
19
19
|
`):f?.type==="message"&&f.role==="system"&&(T=f.content.map(u=>u.text).join(`
|
|
20
|
-
`))}),
|
|
21
|
-
${
|
|
22
|
-
\`\`\``)}catch(s){Q.error("Could not decode outputMsg",s,t.output)}return{title:
|
|
20
|
+
`))}),g&&(r?.({steps:d,duration:E}),n?.({steps:w,duration:E}))}),await P.catch(R=>{({error:T,result:x}=Jt({catchError:R,runCmd:P,error:T,result:x,runnerName:"Codex"}))}),{steps:c,duration:E,result:await X({initialResult:x,agentName:st,hasError:!!T}),error:z({error:T,agentName:st}),isRetryableError:Z(T)}}var it=async()=>{let e=ke.join(Wt.homedir(),".codex");await Kt.rm(e,{recursive:!0,force:!0})},Xt={[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},o1:{maxTokens:1e5},"o1-mini":{maxTokens:65536},"o3-mini":{maxTokens:1e5},"gpt-image-1":{},"dall-e-2":{},"dall-e-3":{}}},[M]:{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}}},[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}}}},zt=new Set(["bash","-lc"]),Zt=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!zt.has(s)),n=r?`Running \`${r.join(" ")}\``:void 0,o;try{o=JSON.parse(t.output).output?.trim(),o&&(o=`\`\`\`
|
|
21
|
+
${o.trim()}
|
|
22
|
+
\`\`\``)}catch(s){Q.error("Could not decode outputMsg",s,t.output)}return{title:n,message:o}};import Qt from"fs/promises";import er from"os";import ge from"path";import q from"process";var ie=_("runner_gemini"),at="Gemini CLI",tr=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(ie.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?(ie.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}):(ie.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0})),rr={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 Le({config:e,netlify:t,persistSteps:r,sendSteps:n,aiGateway:o}){let{accountType:s,prompt:a,modelVersionOverrides:l}=e,{model:i}=e;if(o){let{token:g,url:f}=o;if(!g||!f)throw new Error("No token or url provided from AI Gateway");let u=nr[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(l?.gemini){let y=l?.gemini?.[s];y&&(i=y)}q.env.GEMINI_API_KEY=g,q.env.GOOGLE_GEMINI_BASE_URL=f}else if(!q.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let d=[],c=[],p=[],h={},E=0,x=0,T,m,N=ge.join(q.cwd(),"node_modules"),C=[ge.join(q.env.NODE_PATH||N,".bin/gemini"),...i?["--model",i]:[],"--yolo","-p",a],P=`${q.env.NVM_BIN}/node`;ie.log(`Running ${P} ${C.join(" ")}`);let I=t.utils.run(P,C,{all:!0,env:q.env});I.stdin?.end();let R=de(()=>{r?.({steps:d,duration:x}),n?.({steps:c,duration:x}),c=[]},250),A=(g,f)=>{g.id=E,E+=1,p.push(g),d.push(g),c.push(g),f||R.flush(),R(),f&&R.flush()},w="";return I.all.on("data",g=>{if(w+=g.toString(),!g.includes(`
|
|
23
23
|
`))return;let f=w.toString().split(`
|
|
24
|
-
`).filter(Boolean).map(u=>{try{if(u.startsWith("[API Error")){let y=u.match(/\[api error: (.+?)]$/i)?.[1];return{type:"error",value:fe(y,!1)?.error?.message||y||"Gemini encountered error"}}return JSON.parse(u)}catch{}return null}).filter(Boolean);w="",f.forEach(u=>{switch(u.type){case"thought":{let y=u.value;A({title:y?.subject??"Thinking...",message:y?.description},!0);break}case"content":{u.value&&A({message:u.value});break}case"tool_call_request":{let y=u.value,D=
|
|
24
|
+
`).filter(Boolean).map(u=>{try{if(u.startsWith("[API Error")){let y=u.match(/\[api error: (.+?)]$/i)?.[1];return{type:"error",value:fe(y,!1)?.error?.message||y||"Gemini encountered error"}}return JSON.parse(u)}catch{}return null}).filter(Boolean);w="",f.forEach(u=>{switch(u.type){case"thought":{let y=u.value;A({title:y?.subject??"Thinking...",message:y?.description},!0);break}case"content":{u.value&&A({message:u.value});break}case"tool_call_request":{let y=u.value,D=rr[y.name]??y.name,B=y.args?.path||y.args?.absolute_path,b=B&&ge.relative(q.cwd(),B),F=y.args?.command,It={title:[D,b&&`\`${b}\``,F&&`\`${F}\``].filter(Boolean).join(" ")};h[y.callId]=It,R.flush();break}case"tool_result":{let y=u.value,D=h[y.callId];if(D){let B=[y.resultDisplay,y.responseParts?.functionResponse?.response?.output].find(b=>typeof b=="string"&&b);B&&(D.message=`\`\`\`
|
|
25
25
|
${B.trim()}
|
|
26
|
-
\`\`\``),A(D,!0)}break}case"result":{x=u.duration_ms,T=u.value,[d,
|
|
26
|
+
\`\`\``),A(D,!0)}break}case"result":{x=u.duration_ms,T=u.value,[p,d,c].forEach(y=>{y[y.length-1]?.message===T&&y.pop()});break}case"error":{m=u.value;break}case"finished":break;default:{ie.warn("Unhandled message type:",u.type);break}}})}),await I.catch(g=>{({error:m,result:T}=tr({catchError:g,runCmd:I,error:m,result:T,runnerName:"Gemini"}))}),R.flush(),{steps:p,duration:x,result:await X({initialResult:T,agentName:at,hasError:!!m}),error:z({error:m,agentName:at}),isRetryableError:Z(m)}}var lt=async()=>{let e=ge.join(er.homedir(),".gemini");await Qt.rm(e,{recursive:!0,force:!0})},nr={[G]:{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}}},[M]:{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}}},[U]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}}};var or={codex:{runner:be,clean:it},claude:{runner:Oe,clean:ot},gemini:{runner:Le,clean:lt}},ut=or;var ct=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:n})=>{let o=sr();return le(o,"init-stage",async s=>{let a=performance.now();s?.setAttributes({"init.runner":e.runner,"init.id":e.id,"init.sessionId":e.sessionId,"init.hasRepo":e.hasRepo,"init.useGateway":e.useGateway,"init.validateAgent":e.validateAgent,"init.runnerVersion":n||"unknown"});let l=ut[e.runner];if(!l)throw s?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let i=ir({apiToken:r});Ge(i);let d=e.useGateway?await He({netlify:i,config:e}):void 0;s?.setAttributes({"init.aiGateway.created":!!d}),e.validateAgent&&e.errorLogsPath&&s?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let c=Xe(({steps:E=[],duration:x})=>{let T=[...E];return E.length=0,J(e.id,e.sessionId,{steps:T,duration:x})},t),p;e.hasRepo?e.sha?(p=e.sha,s?.setAttributes({"init.sha.source":"provided"})):(p=await tt(i),await pe(e.id,{sha:p}),s?.setAttributes({"init.sha.source":"current_commit"})):(p=await rt(i),s?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let h=performance.now()-a;return s?.setAttributes({"init.sha":p||"unknown","init.duration.ms":h,"init.status":"success"}),{aiGateway:d,context:i,persistSteps:c,runner:l,sha:p}})},ir=({apiToken:e})=>({constants:{NETLIFY_API_HOST:he.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||he.env.NETLIFY_API_TOKEN,SITE_ID:he.env.SITE_ID,FUNCTIONS_DIST:he.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:Ve}});import ar from"crypto";import V from"fs/promises";import k from"path";import $ from"process";var v=_("context"),lr=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}},ur=10,cr=async e=>{let{name:t,ext:r}=k.parse(e),n=e,o=k.join($.cwd(),L,n),s=0;for(;await pr(o);){if(s>=ur)throw new Error("Failed to generate context file");n=`${t}-${ar.randomUUID().slice(0,5)}${r}`,o=k.join($.cwd(),L,n),s+=1}return n},pr=async e=>{try{return await V.access(e),!0}catch{return!1}},dr=async()=>{try{v.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 v.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"?(v.warn("Catchall consumer missing or invalid contextScopes"),null):r:(v.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?v.warn("Netlify features context request timed out"):v.warn("Failed to fetch Netlify features context:",e.message),null}},fr=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"?v.warn(`Download timeout for ${e}`):v.warn(`Failed to download context file ${e}:`,r.message),!1}},Ee=null,mr=async()=>{if(Ee)return Ee;let e=await dr();if(!e)return[];let t=k.join($.cwd(),L,Ae);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 v.warn(`Invalid scope data for ${o}, skipping...`),null;let a=`${o}.md`,l=k.join(t,a),i=k.join(L,Ae,a);return v.log(`Downloading ${s.scope} context...`),await fr(s.endpoint,l)?(v.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:o}):null});return Ee=(await Promise.all(r)).filter(o=>o!==null),Ee},pt=async({cliPath:e,netlify:t,config:r,buildErrorContext:n})=>{let o=lr(t),s=await cr(Ke),a=k.join($.cwd(),L);await V.mkdir(a,{recursive:!0});let l=k.join(L,s),i=k.join($.cwd(),l),d=k.join($.cwd(),L,se);try{await V.unlink(d),v.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.
|
|
27
27
|
Your task is to analyze and fix the build errors.
|
|
28
28
|
Don't apply techniques of reverting changes. Apply fixes related to errors.
|
|
29
29
|
Don't try to run build by yourself. Just fix the errors.
|
|
30
30
|
|
|
31
31
|
<build_error_context>
|
|
32
|
-
${
|
|
33
|
-
</build_error_context>`:"",
|
|
32
|
+
${n}
|
|
33
|
+
</build_error_context>`:"",p="";r.siteContext&&r.siteContext.length!==0&&(p=`
|
|
34
34
|
<project_rules>
|
|
35
|
-
${r.siteContext.filter(
|
|
35
|
+
${r.siteContext.filter(m=>m.site_context).map(m=>typeof m.site_context=="string"?m.site_context:typeof m.site_context=="object"?JSON.stringify(m.site_context):"").join(`
|
|
36
36
|
|
|
37
37
|
`)}
|
|
38
38
|
</project_rules>
|
|
39
|
-
`);let
|
|
39
|
+
`);let h="";if(r.sessionHistoryContext?.length){let m=k.join($.cwd(),L,Ce);await V.mkdir(m,{recursive:!0});let N=await Promise.all(r.sessionHistoryContext.map(async(C,P)=>{let I=P+1,R=`attempt-${I}.md`,A=k.join(m,R),w=k.join(L,Ce,R),g=`# Task History - Attempt ${I}
|
|
40
40
|
|
|
41
41
|
## Request - what the user asked for
|
|
42
42
|
${C.request}
|
|
@@ -46,7 +46,7 @@ ${C.request}
|
|
|
46
46
|
## Response - what the agent replied with after its work
|
|
47
47
|
|
|
48
48
|
${C.response}
|
|
49
|
-
`;return await
|
|
49
|
+
`;return await V.writeFile(A,g,"utf-8"),v.log(`Created history file: ${w}`),w}));h+=`
|
|
50
50
|
<session_history_context>
|
|
51
51
|
History of prior work on this task.
|
|
52
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.
|
|
@@ -55,12 +55,12 @@ ${C.response}
|
|
|
55
55
|
`)}
|
|
56
56
|
|
|
57
57
|
</session_history_context>
|
|
58
|
-
`}let E=await
|
|
58
|
+
`}let E=await mr(),x="";E.length>0&&(x=`
|
|
59
59
|
<netlify_features_context>
|
|
60
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
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.
|
|
62
62
|
|
|
63
|
-
${E.map(
|
|
63
|
+
${E.map(m=>`- **${m.scope}**: ${m.path}`).join(`
|
|
64
64
|
`)}
|
|
65
65
|
|
|
66
66
|
Refer to these files when working with specific Netlify features.
|
|
@@ -85,16 +85,16 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
85
85
|
- for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${a}/${Se} folder
|
|
86
86
|
- move assets from ${a}/${Se} folder to the project assets folder if they are referenced in a code or applied changes
|
|
87
87
|
</attachements>
|
|
88
|
-
${
|
|
88
|
+
${p}
|
|
89
89
|
</requirements>
|
|
90
90
|
|
|
91
91
|
<extra_context>
|
|
92
92
|
<metadata>
|
|
93
|
-
- Site/Project ID: ${
|
|
94
|
-
- Account/Team ID: ${
|
|
95
|
-
- User ID: ${
|
|
96
|
-
- Site/Project Slug: ${
|
|
97
|
-
- Netlify Functions directory: ${
|
|
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
98
|
</metadata>
|
|
99
99
|
<environment>
|
|
100
100
|
- Node Version: ${$.version||"unknown"}
|
|
@@ -109,8 +109,8 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
109
109
|
</docs>
|
|
110
110
|
</extra_context>
|
|
111
111
|
|
|
112
|
-
${
|
|
113
|
-
`;return await
|
|
112
|
+
${h}
|
|
113
|
+
`;return await V.writeFile(i,T,"utf-8"),v.log(`Generated agent context document at: ${i}`),T.length>5e5&&(T=`
|
|
114
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
115
|
|
|
116
116
|
<request>
|
|
@@ -121,12 +121,12 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
121
121
|
</request>
|
|
122
122
|
|
|
123
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
|
|
124
|
+
`),T};var gr=_("prompt"),dt=async({cliPath:e,config:t,netlify:r,buildErrorContext:n})=>{let o=await pt({cliPath:e,config:t,netlify:r,buildErrorContext:n});return process.env.AGENT_RUNNER_DEBUG&&gr.log("Contextful Prompt:",o),{prompt:o}};var ft=_("inference_stage"),mt=2,_e=async e=>{let{cliPath:t,config:r,context:n,buildErrors:o,runner:s,persistSteps:a,aiGateway:l,attempt:i}=e;qe();let{prompt:d}=await dt({cliPath:t,config:r,buildErrorContext:hr(o),netlify:n}),c={...r,prompt:d},p=await s({aiGateway:l,config:c,netlify:n,persistSteps:a});if(await a.flush(),p.error){if(ft.error("Runner failed",{stepsCount:p.steps.length,duration:p.duration,error:p.error,isRetryableError:p.isRetryableError}),p.error&&p.isRetryableError&&(!i||i<mt))return ft.log(`Retrying inference stage, attempt ${i} of ${mt}...`),await new Promise(E=>setTimeout(E,5e3)),{runnerResult:(await _e({...e,attempt:(i||1)+1})).runnerResult};throw new Error(p.error)}return{runnerResult:p}},hr=e=>!e||e.length===0?"":`
|
|
125
125
|
Deploy failed failed. Here are the errors to review on the latest build:
|
|
126
126
|
|
|
127
127
|
Below are all of the logs with potential issues that we extracted. Some of them may be false positives, discern them carefully and ensure fixes are relevant.
|
|
128
128
|
|
|
129
129
|
${e.pop()}
|
|
130
|
-
`;import
|
|
131
|
-
Preview deploy created successfully:`,{deployId:c.deploy_id,deployUrl:c.deploy_url,siteId:c.site_id});let
|
|
130
|
+
`;import Er from"process";var ae=_("deploy"),gt=async({netlify:e,hasRepo:t,skipBuild:r,message:n="Agent Preview",deploySubdomain:o,cliPath:s,filter:a})=>{try{let l=["deploy","--message",`"${n}"`,"--json","--draft","--verbose"];t||(ae.log("Deploy: Uploading source zip"),l.push("--upload-source-zip")),o&&l.push("--alias",o),a&&l.push("--filter",a),r?(ae.log("Deploy: Skipping build"),l.push("--no-build")):l.push("--context","deploy-preview");let i=s||"netlify";ae.log(`Running: ${i} ${l.join(" ")}`);let d=await e.utils.run(i,l,{stdio:["ignore","pipe","pipe"]}),c=JSON.parse(d.stdout.trim());ae.log(`
|
|
131
|
+
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(l){throw ae.error("Failed to create preview deploy via CLI:",l),l}};var ye=_("deploy_stage"),$e=async({cliPath:e,config:t,context:r,result:n,filter:o})=>{let s=await et({config:t,netlify:r});if(!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:l,diffBinary:i,resultDiffBinary:d}=s,c=!0;ye.log("Preview deploy condition check:",{resultUndefined:n===void 0,resultType:typeof n,hasChanges:c,wouldCreatePreview:n!==void 0&&c});let p=null;if(n!==void 0&&c)try{let h;try{let E=await je(t.id,t.sessionId);E?.title&&(h=E.title)}catch(E){ye.warn("Failed to fetch session title, using fallback message:",E.message)}p=await gt({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:h,skipBuild:!1,deploySubdomain:ze(t.id,Er.env.SITE_NAME),filter:o})}catch(h){return ye.warn("Failed to create preview deploy (continuing with agent run):",h),{diff:a,resultDiff:l,hasChanges:c,previewInfo:null,diffBinary:i,resultDiffBinary:d,deployError:h instanceof Error?h.message:String(h)}}return ye.log("Git status",{hasDiff:!!a,hasChanges:c}),{diff:a,resultDiff:l,hasChanges:c,previewInfo:p,diffBinary:i,resultDiffBinary:d}};async function ht(e,t){let{maxRetries:r,baseDelay:n,onRetry:o}=t,s;for(let a=1;a<=r;a++)try{return await e()}catch(l){if(s=l,a===r)throw s;o&&o(a,s),await new Promise(i=>setTimeout(i,n*a))}throw s}var ee=_("cleanup_stage"),Et=async({config:e,diff:t,result:r,duration:n,resultDiff:o,diffBinary:s,resultDiffBinary:a,previewInfo:l})=>{let i={result_diff:t,result:r||"Done",duration:n,result_diff_binary:s};return l&&l.deployId&&(i.deploy_id=l.deployId),l&&l.sourceZipFilename&&(i.result_zip_file_name=l.sourceZipFilename),o||a?(ee.log("Updating total agent result diff"),await pe(e.id,{result_diff:o,result_diff_binary:a})):ee.log("No total result diff, not updating"),ee.log("Updated agent runner with result"),await ht(()=>J(e.id,e.sessionId,i),{maxRetries:3,baseDelay:1e3,onRetry:(d,c)=>{ee.error(`Error updating agent runner session (attempt ${d}):`,c),ee.log("Retrying...")}}),ee.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as yr}from"@netlify/otel";var Tr=_r(import.meta.url),_t=Tr("../package.json"),yt=_("pipeline_index"),Te=3,Tt=async({config:e,apiToken:t,cliPath:r="netlify",cwd:n,errorLogsPath:o,filter:s,traceExporterUrl:a})=>{let l;try{await Ue(_t.version,e.id,a);let i=yr(),d,{aiGateway:c,context:p,persistSteps:h,runner:E,sha:x}=await ct({config:e,apiToken:t,cliPath:r,cwd:n,errorLogsPath:o,filter:s,runnerVersion:_t.version});l=E.clean,e.sha=x;let{runnerResult:T}=await _e({cliPath:r,config:e,context:p,runner:E.runner,persistSteps:h,aiGateway:c}),m=await $e({cliPath:r,config:e,context:p,result:T.result,filter:s}),N=T,C=[];if(m.hasChanges&&m.deployError){C.push(Me(m.deployError));let g=1;for(;g<=Te&&!m.previewInfo;)yt.log(`Deploy attempt had errors. Retrying. ${g}/${Te}`),await le(i,"stage-deploy",async f=>{f?.setAttributes({"stage.attempt":g});let{runnerResult:u}=await _e({cliPath:r,config:e,context:p,runner:E.runner,persistSteps:h,aiGateway:c,buildErrors:C});N={...u,steps:[...N.steps||[],...u.steps||[]],duration:(N.duration||0)+(u.duration||0)},m=await $e({cliPath:r,config:e,context:p,result:u.result,filter:s}),m.deployError&&C.push(m.deployError),g++});g>Te&&!m.previewInfo&&(d=new Error(`Deploy validation failed after ${Te} attempts`))}let{diff:P,resultDiff:I,previewInfo:R,diffBinary:A,resultDiffBinary:w}=m;if(await Et({config:e,diff:P,result:N.result,duration:N.duration,resultDiff:I,diffBinary:A,resultDiffBinary:w,previewInfo:R}),d)throw d;await E.clean?.()}catch(i){yt.error("Got error while running pipeline",i),await l?.();let d=i instanceof Error&&i.message;throw await J(e.id,e.sessionId,{result:d||"Encountered error when running agent",state:"error"}),i}};import O from"process";var xr="codex",Rr=e=>(e??[]).filter(t=>t.request&&t.response),wr=e=>(e??[]).filter(t=>t.site_context),xt=_("config"),Rt=()=>{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||xr,s=O.env.NETLIFY_AGENT_RUNNER_MODEL,a=O.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED==="1",l=O.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED==="1",i=O.env.ERROR_LOGS_PATH,d=fe(O.env.NETLIFY_AGENT_RUNNER_CONTEXT,!0,xt),c=Rr(d),p=wr(d),h=O.env.NETLIFY_AGENT_RUNNER_HAS_REPO!=="0",E=!O.env.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED,x=O.env.NETLIFY_AGENT_RUNNER_SHA,T=Ir(),m=Ze(),N={id:e,sessionId:t,resultBranch:r,prompt:n,runner:o,model:s,validateAgent:a,errorLogsPath:i,sessionHistoryContext:c,siteContext:p,hasRepo:h,useGateway:E,sha:x,accountType:T,validateAgentWithBuild:l,modelVersionOverrides:m};return xt.log({fullConfig:N}),N},Ir=()=>{let e=O.env.NETLIFY_TEAM_TYPE;return e?e.includes("personal")?M:e.includes("pro")?"pro":e.startsWith("enterprise")?G:e.startsWith("free")?j:U:U};var wt=_("bin_cmd"),te=Nr(De.argv.slice(2),{string:["auth","cwd","cli-path","error-logs-path","filter","trace-exporter-url"]});try{let e=Rt();await Tt({config:e,apiToken:te.auth,cwd:te.cwd,cliPath:te["cli-path"],errorLogsPath:te["error-logs-path"],filter:te.filter,traceExporterUrl:te["trace-exporter-url"]}),wt.info("Finished agent"),De.exit(0)}catch(e){wt.error("Error running agent pipeline:",e),De.exit(1)}
|
|
132
132
|
//# sourceMappingURL=bin.js.map
|
package/dist/index.js
CHANGED
|
@@ -1,41 +1,41 @@
|
|
|
1
|
-
import{createRequire as
|
|
2
|
-
`),r=[],
|
|
3
|
-
`)),
|
|
1
|
+
import{createRequire as lr}from"module";import{createTracerProvider as gt}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as be}from"@netlify/otel/opentelemetry";import{withActiveSpan as ht}from"@netlify/otel";import{OTLPTraceExporter as yt}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 Ee=_("tracing"),$e=(e,t,r)=>gt({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new be(new _e),new be(new yt({url:r}))]});function ie(e,t,r){return Ee.log(`\u23F3 TRACE: ${t} starting...`),ht(e,t,r)}var _e=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[l,i]of Object.entries(n))l.includes("duration")&&typeof i=="number"?o.push(`${l}=${i.toFixed(2)}ms`):o.push(`${l}=${i}`);let s=t.status?.code===2?"\u274C":"\u2705",a=o.length>0?` [${o.join(", ")}]`:"";Ee.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${a}`),t.status?.code===2&&t.status.message&&Ee.log(` \u274C Error: ${t.status.message}`)}};var Et=["error","failed","exception","fatal","panic","abort","crash"];function De(e){let t=e.split(`
|
|
2
|
+
`),r=[],n=-1,o=0;for(;o<t.length;){let l=t[o].slice(0,500).toLowerCase();if(Et.some(f=>l.includes(f))){let f=Math.max(0,o-10,n+1),c=Math.min(t.length-1,o+20),d=[];for(let h=f;h<=c;h++)d.push(t[h]);r.push(d.join(`
|
|
3
|
+
`)),n=c,o=c+1}else o++}if(r.length===0)return e;let s=r.map((a,l)=>`<extracted_error_chunk order="${l+1}">
|
|
4
4
|
${a}
|
|
5
5
|
</extracted_error_chunk>`).join(`
|
|
6
6
|
|
|
7
|
-
`);return s.length>e.length*.8?e:s}import fe from"process";import{getTracer as
|
|
8
|
-
`).filter(
|
|
9
|
-
`).forEach(a=>{let l=a.match(/\?\? (.+?)\.log$/)?.[1];l&&
|
|
7
|
+
`);return s.length>e.length*.8?e:s}import fe from"process";import{getTracer as Jt}from"@netlify/otel";import ae from"process";var xe=ae.env.NETLIFY_API_URL,Te=ae.env.NETLIFY_API_TOKEN,Q=_("api"),le=async(e,t={})=>{if(!xe||!Te)throw new Error("No API URL or token");let r=new URL(e,xe),n={...t,headers:{...t.headers,Authorization:`Bearer ${Te}`}};ae.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(ae.env.AGENT_RUNNERS_DEBUG==="true")Q.log(`Response headers for ${r}:`),o.headers.forEach((l,i)=>{Q.log(` ${i}: ${l}`)});else{let l=o.headers.get("x-request-id")||o.headers.get("x-nf-request-id");Q.log(`Request ID for ${r}: ${l||"N/A"}`)}if(s||Q.error(`Got status ${o.status} for request ${r}`),t.raw){if(!s)throw o;return o}let a=await(o.headers.get("content-type")?.includes("application/json")?o.json():o.text());if(!s)throw a;return a},Le=e=>{Q.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(xe=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Te=e.constants.NETLIFY_API_TOKEN)},ue=(e,t)=>le(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),Y=(e,t,r)=>le(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var Fe=(e,t)=>le(`/api/v1/agent_runners/${e}/sessions/${t}`),Ue=(e,t,r)=>le(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}});var Me=_("ai_gateway"),je=async({netlify:e,config:t})=>{let r,n,o,s,a=e.constants?.SITE_ID;if(!a)throw new Error("No site id");let l=async()=>{clearTimeout(o),Me.log("Requesting AI gateway information");let i=await Ue(a,t.id,t.sessionId);if({token:r,url:s}=i,n=i.expires_at?i.expires_at*1e3:void 0,Me.log("Got AI gateway information",{token:!!r,expiresAt:n,url:s}),n){let f=n-Date.now()-6e4;f>0&&(o=setTimeout(()=>{l()},f))}};return await l(),{get url(){return s},get token(){return r}}};import te from"process";import{execa as Rt,execaCommand as vr}from"execa";import{Transform as _t}from"stream";var xt=["NODE_ENV","PATH","HOME","USER","USERNAME","SHELL","PWD","OLDPWD","TMPDIR","TMP","TEMP","LANG","TERM","EDITOR","PAGER","OS","PROCESSOR_ARCHITECTURE","PROCESSOR_IDENTIFIER","SYSTEMROOT","WINDIR","PROGRAMFILES","PROGRAMFILES(X86)","PROGRAMDATA","APPDATA","LOCALAPPDATA","NODE_OPTIONS","NODE_PATH","NODE_DEBUG","NODE_NO_WARNINGS","npm_config_registry","npm_config_cache","npm_execpath","npm_node_execpath","CI","GITHUB_ACTIONS","GITHUB_WORKSPACE","GITHUB_REPOSITORY","GITHUB_REF","BUILDKITE","BUILDKITE_BRANCH","BUILDKITE_COMMIT","BUILDKITE_BUILD_NUMBER","JENKINS_URL","TRAVIS","CIRCLECI","DISPLAY","COLORTERM","TERM_PROGRAM","TERM_PROGRAM_VERSION","COLUMNS","LINES","HISTSIZE","HISTFILE"];function Tt(){return Object.entries(process.env).filter(([e,t])=>!(!t||xt.includes(e)||t.length<5)).map(([,e])=>e).filter(Boolean)}function we(e){if(typeof e!="string")return e;let t=Tt();if(t.length===0)return e;let r=e;return t.forEach(n=>{let o=new RegExp(wt(n),"g");r=r.replace(o,"******")}),r}function wt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ee=class extends _t{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,n){let o=t.toString(),s=we(o);n(null,s)}};function Ge(){if(!(process.env.NETLIFY_MASK_LOGS!=="false"))return;let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr);process.stdout.write=function(n,o,s){let a=typeof n=="string"?we(n):n;return typeof o=="function"?t(a,o):t(a,o,s)},process.stderr.write=function(n,o,s){let a=typeof n=="string"?we(n):n;return typeof o=="function"?r(a,o):r(a,o,s)}}var br=_("shell"),It={preferLocal:!0},Be=(e,t,r)=>{let[n,o]=Ct(t,r),s={...It,...o},a=Rt(e,n,s);return Nt(a,s),a};var Ct=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Nt=(e,t)=>{if(t.stdio!==void 0||t.stdout!==void 0||t.stderr!==void 0)return;if(te.env.NETLIFY_MASK_LOGS!=="false"){e.stdout?.pipe(new ee).pipe(te.stdout),e.stderr?.pipe(new ee).pipe(te.stderr);return}e.stdout?.pipe(te.stdout),e.stderr?.pipe(te.stderr)};var Ye="netlify-agent-runner-context.md",Re="task-history",Ie="netlify-context",b=".netlify",re="results.md",Ce="assets",H="other",q="personal";var K="enterprise",V="free";var St=_("utils"),At=e=>new Promise(t=>{setTimeout(t,e)}),He=(e,t=3e3)=>{let r=!1,n=null,o=[],s=null,a=(...l)=>{if(r)return n=l,new Promise(c=>{o.push(c)});r=!0;let i,f=new Promise(c=>{i=c});return s=(async()=>{await Promise.resolve();let c=await e(...l);for(i(c);;){if(await At(t),!n)return r=!1,s=null,c;let d=n,h=o;n=null,o=[],c=await e(...d),h.forEach(y=>{y(c)})}})(),f};return a.flush=async()=>{if((r||n)&&s)return await s,a.flush()},a},ce=(e,t,r=!1)=>{let n=null,o=null,s=null,a=function(...l){o=l,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 a.cancel=()=>{clearTimeout(n),n=null,o=null,s=null},a.flush=()=>{if(n){clearTimeout(n);let l=o,i=s;n=null,o=null,s=null,e.apply(i,l)}},a},qe=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(n){t&&(r?.error?r.error("Could not parse JSON",n):St.error("Could not parse JSON",n))}},Ke=(e,t)=>{let o=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let l=`--${t}${o}`;if(l.length>55)return"";let i=60-l.length;if(i<=0)return"";if(i>=s.length+6){let f=Math.min(i-s.length,e.length);return`${s}${e.slice(0,f)}`}return e.slice(0,i)};import{Buffer as Ve}from"buffer";var We=async({config:e,netlify:t})=>{let r=await vt(t),{hasChanges:n}=r,{status:o}=r;if(!n)return{hasChanges:!1};let s=await Ot(t,o);await t.utils.run("git",["add",".",...s]);let a={stdio:["ignore","pipe","pipe"]},i=(await t.utils.run("git",["diff","--staged"],a)).stdout;if(n=!!i,!n)return{hasChanges:!1};let c=(await t.utils.run("git",["diff","--staged","--binary"],a)).stdout,d,h;if(e.sha){await t.utils.run("git",["commit","-m","Agent runner"]),d=(await t.utils.run("git",["diff",e.sha,"HEAD"],a)).stdout;let g=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;d!==g&&(h=Ve.from(g).toString("base64"))}let y={hasChanges:!0,diff:i,resultDiff:d};return i!==c&&(y.diffBinary=Ve.from(c).toString("base64")),h&&(y.resultDiffBinary=h),y},Pt=["?? mise.toml","?? deno.lock",/\?\? .+?\.log/],vt=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
|
|
8
|
+
`).filter(o=>!Pt.some(s=>s instanceof RegExp?s.test(o):o===s))).length!==0,status:t.stdout}};var Je=async e=>{let{stdout:t}=await e.utils.run("git",["rev-parse","HEAD"]);return t.trim()},Xe=async e=>{let{stdout:t}=await e.utils.run("git",["rev-list","--max-parents=0","HEAD"]);return t.trim()},Ot=async(e,t="")=>{let r=[".netlify","mise.toml","deno.lock","node_modules"],n=[],o=r.map(async a=>{try{return await e.utils.run("git",["check-ignore","-v",a]),null}catch{return`:!${a}`}});return(await Promise.all(o)).forEach(a=>{a&&n.push(a)}),t.split(`
|
|
9
|
+
`).forEach(a=>{let l=a.match(/\?\? (.+?)\.log$/)?.[1];l&&n.push(`:!${l}.log`)}),n};import bt from"fs/promises";import $t from"os";import de from"path";import M from"process";import Ne from"path";import kt from"fs/promises";var Se=_("agent-output-utils");async function W({initialResult:e,agentName:t,hasError:r}){let n="",o=Ne.join(process.cwd(),b,re);try{let s=await kt.readFile(o,"utf-8");s&&(n=s,Se.log(`Pulled result from ${Ne.relative(process.cwd(),o)}`))}catch{Se.log(`No results file found at ${Ne.relative(process.cwd(),o)}`)}return n||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function J({error:e,agentName:t}){let r=e&&typeof e=="object"?JSON.stringify(e):e,n=r?.replace(/\s+/g," ").trim()||"",o="";return n?.includes("ai gateway is not available for your account")?o="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.":n?.includes("error when talking to gemini api")?o="Gemini's API is currently having issues. Please try again or use a different available agent while Google resolves the issue.":(n?.includes("connection closed prematurely while waiting for the model")||n?.includes("499")&&t.toLowerCase().includes("gemini"))&&(o="The agent's models were currently overloaded. Please try again or use a different available agent."),o&&Se.log(`Providing updated error messsage: ${o}, replacing original error: ${r}`),o||r||void 0}function X(e){if(!e)return!1;let r=(e&&typeof e=="object"?JSON.stringify(e):e)?.replace(/\s+/g," ").trim()||"";return!!(r?.includes("error when talking to gemini api")||r?.includes("connection closed prematurely while waiting for the model"))}var F=_("runner_claude"),ze="Claude Code",Dt=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(F.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?(F.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}):(F.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0}));async function Ae({config:e,netlify:t,persistSteps:r,aiGateway:n}){let o=e,{accountType:s,prompt:a,modelVersionOverrides:l}=o,{model:i}=o;if(n){let{token:w,url:m}=n;if(!w||!m)throw new Error("No token or url provided from AI Gateway");let p=Lt[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(l?.claude){let u=l?.claude?.[s];u&&(i=u)}M.env.ANTHROPIC_API_KEY=w,M.env.ANTHROPIC_BASE_URL=m}else if(!M.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let f=[],c=[],d={},h=0,y=0,R,x,g=de.join(M.cwd(),"node_modules"),A=[de.join(M.env.NODE_PATH||g,".bin/claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...i?["--model",i]:[],"-p",a],C=`${M.env.NVM_BIN}/node`;F.log(`Running ${C} ${A.join(" ")}`);let P=t.utils.run(C,A,{all:!0,env:M.env});P.stdin?.end();let I=ce(()=>{r?.({steps:f,duration:y})},250),T=(w,m)=>{let p={...w,id:h};h+=1,c.push(p),f.push(p),m||I.flush(),I(),m&&I.flush()},N="";return P.all?.on("data",w=>{if(N+=w.toString(),!w.includes(`
|
|
10
10
|
`))return;let m=N.split(`
|
|
11
|
-
`).filter(Boolean).map(
|
|
11
|
+
`).filter(Boolean).map(p=>{try{return JSON.parse(p)}catch{F.log("Could not parse line",p)}return null}).filter(Boolean);N="",m.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:``}):F.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}\``;T({title:[u.name,E].filter(Boolean).join(" ")})}else u.id&&(d[u.id]=u);I.flush();break}case"tool_result":{let E=u.tool_use_id?d[u.tool_use_id]:void 0,D;if(E){let L=E.input?.file_path&&de.relative(M.cwd(),E.input.file_path),S=L&&`\`${L}\``;D=[E.name,S].filter(Boolean).join(" ")}let U=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(E?.name||""),k;if(typeof u.content=="string")k=u.content;else if(Array.isArray(u.content)){let L=[];u.content.forEach(S=>{S?.type==="text"&&typeof S.text=="string"?L.push(S.text):S?.type==="image"&&typeof S.source=="object"&&S.source?S.source.type==="base64"&&S.source.media_type?L.push(``):F.log(`Unsupported image type ${S.source.type}`,S.source):F.log(`Unsupported block type ${S?.type}`)}),k=L.join(`
|
|
12
12
|
|
|
13
13
|
`)}U&&k&&(k=`\`\`\`
|
|
14
14
|
${k.trim()}
|
|
15
|
-
\`\`\``),T({title:D,message:k},!0);break}case"thinking":{u.thinking&&T({title:"Thinking",message:u.thinking},!0);break}default:F.log(`Message content type is not supported ${u.type}`,u)}}):
|
|
15
|
+
\`\`\``),T({title:D,message:k},!0);break}case"thinking":{u.thinking&&T({title:"Thinking",message:u.thinking},!0);break}default:F.log(`Message content type is not supported ${u.type}`,u)}}):p?.type==="result"&&(y=p.duration_ms||0,p.is_error?x=p.result:R=p.result,[c,f].forEach(u=>{u[u.length-1]?.message===R&&u.pop()}))})}),await P.catch(w=>{({error:x,result:R}=Dt({catchError:w,runCmd:P,error:x,result:R,runnerName:"Claude"}))}),I.flush(),{steps:c,duration:y,result:await W({initialResult:R,agentName:ze,hasError:!!x}),error:J({error:x,agentName:ze}),isRetryableError:X(x)}}var Ze=async()=>{let e=de.join($t.homedir(),".claude");await bt.rm(e,{recursive:!0,force:!0})},Lt={[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 Ft from"fs/promises";import Ut from"os";import Pe from"path";import B from"process";var z=_("runner_codex"),Qe="Codex CLI",Mt=({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:a,modelVersionOverrides:l}=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=jt[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(l?.codex){let m=l?.codex?.[s];m&&(i=m)}B.env.OPENAI_API_KEY=T,B.env.OPENAI_BASE_URL=N}else if(!B.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let f=[],c=[],d={},h=0,y=0,R,x,g=Pe.join(B.cwd(),"node_modules"),A=[Pe.join(B.env.NODE_PATH||g,".bin/codex"),"--approval-mode","full-auto",o?"--disable-response-storage":void 0,"--dangerously-auto-approve-everything",...i?["--model",i]:[],"-q",a].filter(Boolean),C=`${B.env.NVM_BIN}/node`;z.log(`Running ${C} ${A.join(" ")}`);let P=t.utils.run(C,A,{all:!0,env:{...B.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),I="";return P.all.on("data",T=>{if(I+=T.toString(),!T.includes(`
|
|
16
16
|
`))return;let N=I.toString().split(`
|
|
17
|
-
`).filter(Boolean).map(
|
|
18
|
-
`):
|
|
19
|
-
`))}),m&&(r?.({steps:f,duration:y}),
|
|
20
|
-
${
|
|
21
|
-
\`\`\``)}catch(s){z.error("Could not decode outputMsg",s,t.output)}return{title:
|
|
22
|
-
`))return;let
|
|
23
|
-
`).filter(Boolean).map(u=>{try{if(u.startsWith("[API Error")){let E=u.match(/\[api error: (.+?)]$/i)?.[1];return{type:"error",value:qe(E,!1)?.error?.message||E||"Gemini encountered error"}}return JSON.parse(u)}catch{}return null}).filter(Boolean);w="",
|
|
17
|
+
`).filter(Boolean).map(p=>{try{return JSON.parse(p)}catch{z.log("Could not parse line",p)}return null}).filter(Boolean);I="";let w=[],m=!1;N.forEach(p=>{if(p?.duration_ms&&(y=p.duration_ms,m=!0),p?.type==="local_shell_call")d[p.call_id]=p;else if(p?.type==="local_shell_call_output"){let u=Bt(d[p.call_id],p);u.id=h,h+=1,u&&(c.push(u),f.push(u),w.push(u),m=!0)}else p?.type==="message"&&p.role==="assistant"?R=p.content.map(u=>u.text).join(`
|
|
18
|
+
`):p?.type==="message"&&p.role==="system"&&(x=p.content.map(u=>u.text).join(`
|
|
19
|
+
`))}),m&&(r?.({steps:f,duration:y}),n?.({steps:w,duration:y}))}),await P.catch(T=>{({error:x,result:R}=Mt({catchError:T,runCmd:P,error:x,result:R,runnerName:"Codex"}))}),{steps:c,duration:y,result:await W({initialResult:R,agentName:Qe,hasError:!!x}),error:J({error:x,agentName:Qe}),isRetryableError:X(x)}}var et=async()=>{let e=Pe.join(Ut.homedir(),".codex");await Ft.rm(e,{recursive:!0,force:!0})},jt={[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}}}},Gt=new Set(["bash","-lc"]),Bt=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!Gt.has(s)),n=r?`Running \`${r.join(" ")}\``:void 0,o;try{o=JSON.parse(t.output).output?.trim(),o&&(o=`\`\`\`
|
|
20
|
+
${o.trim()}
|
|
21
|
+
\`\`\``)}catch(s){z.error("Could not decode outputMsg",s,t.output)}return{title:n,message:o}};import Yt from"fs/promises";import Ht from"os";import pe from"path";import j from"process";var oe=_("runner_gemini"),tt="Gemini CLI",qt=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(oe.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?(oe.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}):(oe.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0})),Kt={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 Oe({config:e,netlify:t,persistSteps:r,sendSteps:n,aiGateway:o}){let{accountType:s,prompt:a,modelVersionOverrides:l}=e,{model:i}=e;if(o){let{token:m,url:p}=o;if(!m||!p)throw new Error("No token or url provided from AI Gateway");let u=Vt[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(l?.gemini){let E=l?.gemini?.[s];E&&(i=E)}j.env.GEMINI_API_KEY=m,j.env.GOOGLE_GEMINI_BASE_URL=p}else if(!j.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let f=[],c=[],d=[],h={},y=0,R=0,x,g,A=pe.join(j.cwd(),"node_modules"),C=[pe.join(j.env.NODE_PATH||A,".bin/gemini"),...i?["--model",i]:[],"--yolo","-p",a],P=`${j.env.NVM_BIN}/node`;oe.log(`Running ${P} ${C.join(" ")}`);let I=t.utils.run(P,C,{all:!0,env:j.env});I.stdin?.end();let T=ce(()=>{r?.({steps:f,duration:R}),n?.({steps:c,duration:R}),c=[]},250),N=(m,p)=>{m.id=y,y+=1,d.push(m),f.push(m),c.push(m),p||T.flush(),T(),p&&T.flush()},w="";return I.all.on("data",m=>{if(w+=m.toString(),!m.includes(`
|
|
22
|
+
`))return;let p=w.toString().split(`
|
|
23
|
+
`).filter(Boolean).map(u=>{try{if(u.startsWith("[API Error")){let E=u.match(/\[api error: (.+?)]$/i)?.[1];return{type:"error",value:qe(E,!1)?.error?.message||E||"Gemini encountered error"}}return JSON.parse(u)}catch{}return null}).filter(Boolean);w="",p.forEach(u=>{switch(u.type){case"thought":{let E=u.value;N({title:E?.subject??"Thinking...",message:E?.description},!0);break}case"content":{u.value&&N({message:u.value});break}case"tool_call_request":{let E=u.value,D=Kt[E.name]??E.name,U=E.args?.path||E.args?.absolute_path,k=U&&pe.relative(j.cwd(),U),L=E.args?.command,mt={title:[D,k&&`\`${k}\``,L&&`\`${L}\``].filter(Boolean).join(" ")};h[E.callId]=mt,T.flush();break}case"tool_result":{let E=u.value,D=h[E.callId];if(D){let U=[E.resultDisplay,E.responseParts?.functionResponse?.response?.output].find(k=>typeof k=="string"&&k);U&&(D.message=`\`\`\`
|
|
24
24
|
${U.trim()}
|
|
25
|
-
\`\`\``),N(D,!0)}break}case"result":{R=u.duration_ms,x=u.value,[
|
|
25
|
+
\`\`\``),N(D,!0)}break}case"result":{R=u.duration_ms,x=u.value,[d,f,c].forEach(E=>{E[E.length-1]?.message===x&&E.pop()});break}case"error":{g=u.value;break}case"finished":break;default:{oe.warn("Unhandled message type:",u.type);break}}})}),await I.catch(m=>{({error:g,result:x}=qt({catchError:m,runCmd:I,error:g,result:x,runnerName:"Gemini"}))}),T.flush(),{steps:d,duration:R,result:await W({initialResult:x,agentName:tt,hasError:!!g}),error:J({error:g,agentName:tt}),isRetryableError:X(g)}}var rt=async()=>{let e=pe.join(Ht.homedir(),".gemini");await Yt.rm(e,{recursive:!0,force:!0})},Vt={[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 Wt={codex:{runner:ve,clean:et},claude:{runner:Ae,clean:Ze},gemini:{runner:Oe,clean:rt}},nt=Wt;var ot=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:n})=>{let o=Jt();return ie(o,"init-stage",async s=>{let a=performance.now();s?.setAttributes({"init.runner":e.runner,"init.id":e.id,"init.sessionId":e.sessionId,"init.hasRepo":e.hasRepo,"init.useGateway":e.useGateway,"init.validateAgent":e.validateAgent,"init.runnerVersion":n||"unknown"});let l=nt[e.runner];if(!l)throw s?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let i=Xt({apiToken:r});Le(i);let f=e.useGateway?await je({netlify:i,config:e}):void 0;s?.setAttributes({"init.aiGateway.created":!!f}),e.validateAgent&&e.errorLogsPath&&s?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let c=He(({steps:y=[],duration:R})=>{let x=[...y];return y.length=0,Y(e.id,e.sessionId,{steps:x,duration:R})},t),d;e.hasRepo?e.sha?(d=e.sha,s?.setAttributes({"init.sha.source":"provided"})):(d=await Je(i),await ue(e.id,{sha:d}),s?.setAttributes({"init.sha.source":"current_commit"})):(d=await Xe(i),s?.setAttributes({"init.sha.source":"first_commit","init.source":"zip"}));let h=performance.now()-a;return s?.setAttributes({"init.sha":d||"unknown","init.duration.ms":h,"init.status":"success"}),{aiGateway:f,context:i,persistSteps:c,runner:l,sha:d}})},Xt=({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:Be}});import zt from"crypto";import G from"fs/promises";import O from"path";import $ from"process";var v=_("context"),Zt=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}},Qt=10,er=async e=>{let{name:t,ext:r}=O.parse(e),n=e,o=O.join($.cwd(),b,n),s=0;for(;await tr(o);){if(s>=Qt)throw new Error("Failed to generate context file");n=`${t}-${zt.randomUUID().slice(0,5)}${r}`,o=O.join($.cwd(),b,n),s+=1}return n},tr=async e=>{try{return await G.access(e),!0}catch{return!1}},rr=async()=>{try{v.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 v.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"?(v.warn("Catchall consumer missing or invalid contextScopes"),null):r:(v.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?v.warn("Netlify features context request timed out"):v.warn("Failed to fetch Netlify features context:",e.message),null}},nr=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"?v.warn(`Download timeout for ${e}`):v.warn(`Failed to download context file ${e}:`,r.message),!1}},me=null,or=async()=>{if(me)return me;let e=await rr();if(!e)return[];let t=O.join($.cwd(),b,Ie);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 v.warn(`Invalid scope data for ${o}, skipping...`),null;let a=`${o}.md`,l=O.join(t,a),i=O.join(b,Ie,a);return v.log(`Downloading ${s.scope} context...`),await nr(s.endpoint,l)?(v.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:o}):null});return me=(await Promise.all(r)).filter(o=>o!==null),me},st=async({cliPath:e,netlify:t,config:r,buildErrorContext:n})=>{let o=Zt(t),s=await er(Ye),a=O.join($.cwd(),b);await G.mkdir(a,{recursive:!0});let l=O.join(b,s),i=O.join($.cwd(),l),f=O.join($.cwd(),b,re);try{await G.unlink(f),v.log(`Deleted old results file: ${f}`)}catch{}let c=n?`You've already made changes to complete the above request. However, the build is currently failing after your changes.
|
|
26
26
|
Your task is to analyze and fix the build errors.
|
|
27
27
|
Don't apply techniques of reverting changes. Apply fixes related to errors.
|
|
28
28
|
Don't try to run build by yourself. Just fix the errors.
|
|
29
29
|
|
|
30
30
|
<build_error_context>
|
|
31
|
-
${
|
|
32
|
-
</build_error_context>`:"",
|
|
31
|
+
${n}
|
|
32
|
+
</build_error_context>`:"",d="";r.siteContext&&r.siteContext.length!==0&&(d=`
|
|
33
33
|
<project_rules>
|
|
34
|
-
${r.siteContext.filter(
|
|
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(`
|
|
35
35
|
|
|
36
36
|
`)}
|
|
37
37
|
</project_rules>
|
|
38
|
-
`);let
|
|
38
|
+
`);let h="";if(r.sessionHistoryContext?.length){let g=O.join($.cwd(),b,Re);await G.mkdir(g,{recursive:!0});let A=await Promise.all(r.sessionHistoryContext.map(async(C,P)=>{let I=P+1,T=`attempt-${I}.md`,N=O.join(g,T),w=O.join(b,Re,T),m=`# Task History - Attempt ${I}
|
|
39
39
|
|
|
40
40
|
## Request - what the user asked for
|
|
41
41
|
${C.request}
|
|
@@ -45,7 +45,7 @@ ${C.request}
|
|
|
45
45
|
## Response - what the agent replied with after its work
|
|
46
46
|
|
|
47
47
|
${C.response}
|
|
48
|
-
`;return await G.writeFile(N,m,"utf-8"),v.log(`Created history file: ${w}`),w}));
|
|
48
|
+
`;return await G.writeFile(N,m,"utf-8"),v.log(`Created history file: ${w}`),w}));h+=`
|
|
49
49
|
<session_history_context>
|
|
50
50
|
History of prior work on this task.
|
|
51
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.
|
|
@@ -54,12 +54,12 @@ ${C.response}
|
|
|
54
54
|
`)}
|
|
55
55
|
|
|
56
56
|
</session_history_context>
|
|
57
|
-
`}let y=await
|
|
57
|
+
`}let y=await or(),R="";y.length>0&&(R=`
|
|
58
58
|
<netlify_features_context>
|
|
59
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
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.
|
|
61
61
|
|
|
62
|
-
${y.map(
|
|
62
|
+
${y.map(g=>`- **${g.scope}**: ${g.path}`).join(`
|
|
63
63
|
`)}
|
|
64
64
|
|
|
65
65
|
Refer to these files when working with specific Netlify features.
|
|
@@ -84,16 +84,16 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
84
84
|
- for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${a}/${Ce} folder
|
|
85
85
|
- move assets from ${a}/${Ce} folder to the project assets folder if they are referenced in a code or applied changes
|
|
86
86
|
</attachements>
|
|
87
|
-
${
|
|
87
|
+
${d}
|
|
88
88
|
</requirements>
|
|
89
89
|
|
|
90
90
|
<extra_context>
|
|
91
91
|
<metadata>
|
|
92
|
-
- Site/Project ID: ${
|
|
93
|
-
- Account/Team ID: ${
|
|
94
|
-
- User ID: ${
|
|
95
|
-
- Site/Project Slug: ${
|
|
96
|
-
- Netlify Functions directory: ${
|
|
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
97
|
</metadata>
|
|
98
98
|
<environment>
|
|
99
99
|
- Node Version: ${$.version||"unknown"}
|
|
@@ -108,7 +108,7 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
108
108
|
</docs>
|
|
109
109
|
</extra_context>
|
|
110
110
|
|
|
111
|
-
${
|
|
111
|
+
${h}
|
|
112
112
|
`;return await G.writeFile(i,x,"utf-8"),v.log(`Generated agent context document at: ${i}`),x.length>5e5&&(x=`
|
|
113
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
114
|
|
|
@@ -120,12 +120,12 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
120
120
|
</request>
|
|
121
121
|
|
|
122
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
|
-
`),x};var
|
|
123
|
+
`),x};var sr=_("prompt"),it=async({cliPath:e,config:t,netlify:r,buildErrorContext:n})=>{let o=await st({cliPath:e,config:t,netlify:r,buildErrorContext:n});return process.env.AGENT_RUNNER_DEBUG&&sr.log("Contextful Prompt:",o),{prompt:o}};var at=_("inference_stage"),lt=2,ge=async e=>{let{cliPath:t,config:r,context:n,buildErrors:o,runner:s,persistSteps:a,aiGateway:l,attempt:i}=e;Ge();let{prompt:f}=await it({cliPath:t,config:r,buildErrorContext:ir(o),netlify:n}),c={...r,prompt:f},d=await s({aiGateway:l,config:c,netlify:n,persistSteps:a});if(await a.flush(),d.error){if(at.error("Runner failed",{stepsCount:d.steps.length,duration:d.duration,error:d.error,isRetryableError:d.isRetryableError}),d.error&&d.isRetryableError&&(!i||i<lt))return at.log(`Retrying inference stage, attempt ${i} of ${lt}...`),await new Promise(y=>setTimeout(y,5e3)),{runnerResult:(await ge({...e,attempt:(i||1)+1})).runnerResult};throw new Error(d.error)}return{runnerResult:d}},ir=e=>!e||e.length===0?"":`
|
|
124
124
|
Deploy failed failed. Here are the errors to review on the latest build:
|
|
125
125
|
|
|
126
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.
|
|
127
127
|
|
|
128
128
|
${e.pop()}
|
|
129
|
-
`;import
|
|
130
|
-
Preview deploy created successfully:`,{deployId:c.deploy_id,deployUrl:c.deploy_url,siteId:c.site_id});let
|
|
129
|
+
`;import ar from"process";var se=_("deploy"),ut=async({netlify:e,hasRepo:t,skipBuild:r,message:n="Agent Preview",deploySubdomain:o,cliPath:s,filter:a})=>{try{let l=["deploy","--message",`"${n}"`,"--json","--draft","--verbose"];t||(se.log("Deploy: Uploading source zip"),l.push("--upload-source-zip")),o&&l.push("--alias",o),a&&l.push("--filter",a),r?(se.log("Deploy: Skipping build"),l.push("--no-build")):l.push("--context","deploy-preview");let i=s||"netlify";se.log(`Running: ${i} ${l.join(" ")}`);let f=await e.utils.run(i,l,{stdio:["ignore","pipe","pipe"]}),c=JSON.parse(f.stdout.trim());se.log(`
|
|
130
|
+
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(l){throw se.error("Failed to create preview deploy via CLI:",l),l}};var he=_("deploy_stage"),ke=async({cliPath:e,config:t,context:r,result:n,filter:o})=>{let s=await We({config:t,netlify:r});if(!s.hasChanges)return{diff:"",hasChanges:!1,previewInfo:null};let{diff:a,resultDiff:l,diffBinary:i,resultDiffBinary:f}=s,c=!0;he.log("Preview deploy condition check:",{resultUndefined:n===void 0,resultType:typeof n,hasChanges:c,wouldCreatePreview:n!==void 0&&c});let d=null;if(n!==void 0&&c)try{let h;try{let y=await Fe(t.id,t.sessionId);y?.title&&(h=y.title)}catch(y){he.warn("Failed to fetch session title, using fallback message:",y.message)}d=await ut({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:h,skipBuild:!1,deploySubdomain:Ke(t.id,ar.env.SITE_NAME),filter:o})}catch(h){return he.warn("Failed to create preview deploy (continuing with agent run):",h),{diff:a,resultDiff:l,hasChanges:c,previewInfo:null,diffBinary:i,resultDiffBinary:f,deployError:h instanceof Error?h.message:String(h)}}return he.log("Git status",{hasDiff:!!a,hasChanges:c}),{diff:a,resultDiff:l,hasChanges:c,previewInfo:d,diffBinary:i,resultDiffBinary:f}};async function ct(e,t){let{maxRetries:r,baseDelay:n,onRetry:o}=t,s;for(let a=1;a<=r;a++)try{return await e()}catch(l){if(s=l,a===r)throw s;o&&o(a,s),await new Promise(i=>setTimeout(i,n*a))}throw s}var Z=_("cleanup_stage"),dt=async({config:e,diff:t,result:r,duration:n,resultDiff:o,diffBinary:s,resultDiffBinary:a,previewInfo:l})=>{let i={result_diff:t,result:r||"Done",duration:n,result_diff_binary:s};return l&&l.deployId&&(i.deploy_id=l.deployId),l&&l.sourceZipFilename&&(i.result_zip_file_name=l.sourceZipFilename),o||a?(Z.log("Updating total agent result diff"),await ue(e.id,{result_diff:o,result_diff_binary:a})):Z.log("No total result diff, not updating"),Z.log("Updated agent runner with result"),await ct(()=>Y(e.id,e.sessionId,i),{maxRetries:3,baseDelay:1e3,onRetry:(f,c)=>{Z.error(`Error updating agent runner session (attempt ${f}):`,c),Z.log("Retrying...")}}),Z.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as ur}from"@netlify/otel";var cr=lr(import.meta.url),pt=cr("../package.json"),ft=_("pipeline_index"),ye=3,_o=async({config:e,apiToken:t,cliPath:r="netlify",cwd:n,errorLogsPath:o,filter:s,traceExporterUrl:a})=>{let l;try{await $e(pt.version,e.id,a);let i=ur(),f,{aiGateway:c,context:d,persistSteps:h,runner:y,sha:R}=await ot({config:e,apiToken:t,cliPath:r,cwd:n,errorLogsPath:o,filter:s,runnerVersion:pt.version});l=y.clean,e.sha=R;let{runnerResult:x}=await ge({cliPath:r,config:e,context:d,runner:y.runner,persistSteps:h,aiGateway:c}),g=await ke({cliPath:r,config:e,context:d,result:x.result,filter:s}),A=x,C=[];if(g.hasChanges&&g.deployError){C.push(De(g.deployError));let m=1;for(;m<=ye&&!g.previewInfo;)ft.log(`Deploy attempt had errors. Retrying. ${m}/${ye}`),await ie(i,"stage-deploy",async p=>{p?.setAttributes({"stage.attempt":m});let{runnerResult:u}=await ge({cliPath:r,config:e,context:d,runner:y.runner,persistSteps:h,aiGateway:c,buildErrors:C});A={...u,steps:[...A.steps||[],...u.steps||[]],duration:(A.duration||0)+(u.duration||0)},g=await ke({cliPath:r,config:e,context:d,result:u.result,filter:s}),g.deployError&&C.push(g.deployError),m++});m>ye&&!g.previewInfo&&(f=new Error(`Deploy validation failed after ${ye} attempts`))}let{diff:P,resultDiff:I,previewInfo:T,diffBinary:N,resultDiffBinary:w}=g;if(await dt({config:e,diff:P,result:A.result,duration:A.duration,resultDiff:I,diffBinary:N,resultDiffBinary:w,previewInfo:T}),f)throw f;await y.clean?.()}catch(i){ft.error("Got error while running pipeline",i),await l?.();let f=i instanceof Error&&i.message;throw await Y(e.id,e.sessionId,{result:f||"Encountered error when running agent",state:"error"}),i}};export{_o as runPipeline};
|
|
131
131
|
//# sourceMappingURL=index.js.map
|