@netlify/agent-runner-cli 1.31.0-alpha.0 → 1.31.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 +32 -32
- package/dist/index.js +32 -32
- package/package.json +1 -1
package/dist/bin.js
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import De from"process";import Cr from"minimist";import{createRequire as yr}from"module";import{createTracerProvider as
|
|
2
|
+
import De from"process";import Cr from"minimist";import{createRequire as yr}from"module";import{createTracerProvider as wt}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as $e}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as At}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as Ct}from"@netlify/otel";import{OTLPTraceExporter as St}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 Ne=_("tracing"),Ue=(e,t,r)=>wt({serviceName:"@netlify/agent-runner-cli",serviceVersion:e,deploymentEnvironment:"production",siteUrl:"",siteId:process.env.SITE_ID??"",siteName:t,spanProcessors:[new $e(new xe),new $e(new St({url:r}))],instrumentations:[new At({skipHeaders:!0})]});function le(e,t,r){return Ne.log(`\u23F3 TRACE: ${t} starting...`),Ct(e,t,r)}var xe=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(", ")}]`:"";Ne.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${a}`),t.status?.code===2&&t.status.message&&Ne.log(` \u274C Error: ${t.status.message}`)}};var Pt=["error","failed","exception","fatal","panic","abort","crash"];function Ge(e){let t=e.split(`
|
|
3
3
|
`),r=[],n=-1,o=0;for(;o<t.length;){let l=t[o].slice(0,500).toLowerCase();if(Pt.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
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(o=>!
|
|
10
|
-
`).forEach(a=>{let l=a.match(/\?\? (.+?)\.log$/)?.[1];l&&n.push(`:!${l}.log`)}),n};import
|
|
11
|
-
`))return;let g=
|
|
12
|
-
`).filter(Boolean).map(f=>{try{return JSON.parse(f)}catch{
|
|
13
|
-
|
|
14
|
-
`)}
|
|
15
|
-
${
|
|
16
|
-
\`\`\``),
|
|
17
|
-
`))return;let
|
|
18
|
-
`).filter(Boolean).map(f=>{try{return JSON.parse(f)}catch{Q.log("Could not parse line",f)}return null}).filter(Boolean);I="";let
|
|
19
|
-
`):f?.type==="message"&&f.role==="system"&&(
|
|
20
|
-
`))}),g&&(r?.({steps:d,duration:E}),n?.({steps:
|
|
8
|
+
`);return s.length>e.length*.8?e:s}import he from"process";import{getTracer as ar}from"@netlify/otel";import ue from"process";var Re=ue.env.NETLIFY_API_URL,Ie=ue.env.NETLIFY_API_TOKEN,re=_("api"),ce=async(e,t={})=>{if(!Re||!Ie)throw new Error("No API URL or token");let r=new URL(e,Re),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},Me=e=>{re.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Re=`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}),X=(e,t,r)=>ce(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var Ye=(e,t)=>ce(`/api/v1/agent_runners/${e}/sessions/${t}`),Be=(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 je=_("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),je.log("Requesting AI gateway information");let i=await Be(a,t.id,t.sessionId);if({token:r,url:s}=i,n=i.expires_at?i.expires_at*1e3:void 0,je.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 Wr}from"execa";import{Transform as Ot}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","NETLIFY_AGENT_RUNNER_ID","NETLIFY_AGENT_RUNNER_SESSION_ID","NETLIFY_AGENT_RUNNER_PROMPT","NETLIFY_AGENT_RUNNER_AGENT","NETLIFY_AGENT_RUNNER_MODEL","NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED","NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED","ERROR_LOGS_PATH","NETLIFY_AGENT_RUNNER_CONTEXT","NETLIFY_AGENT_RUNNER_HAS_REPO","NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED","NETLIFY_AGENT_RUNNER_SHA","NETLIFY_TEAM_TYPE","AGENT_RUNNERS_DEBUG","NETLIFY_TEAM_ID","NETLIFY_AGENT_RUNNER_USER_ID","SITE_NAME"],Lt=["true","false","undefined","null","claude","gemini","codex",""];function kt(){return Object.entries(process.env).filter(([e,t])=>!(!t||vt.includes(e)||Lt.includes(t)||parseInt(t)||t.length<5)).map(([,e])=>e).filter(Boolean)}function we(e){if(typeof e!="string")return e;let t=kt();if(t.length===0)return e;let r=e;return t.forEach(n=>{let o=new RegExp(Ft(n),"g");r=r.replace(o,"******")}),r}function Ft(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ne=class extends Ot{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,n){let o=t.toString(),s=we(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"?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 zr=_("shell"),Dt={preferLocal:!0},Ve=(e,t,r)=>{let[n,o]=$t(t,r),s={...Dt,...o},a=bt(e,n,s);return Ut(a,s),a};var $t=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Ut=(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",Ae="task-history",Ce="netlify-context",F=".netlify",se="results.md",Se="assets",U="other",G="personal";var M="enterprise",Y="free",We=[G,"pro",M,Y];var Xe=_("utils"),Gt=e=>new Promise(t=>{setTimeout(t,e)}),Je=(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 Gt(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):Xe.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)},Mt=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);Mt(s)&&(e[r]=s)}catch(s){let l=s instanceof SyntaxError?"Invalid JSON":s.message;Xe.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 Bt(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},Yt=["?? mise.toml","?? deno.lock",/\?\? .+?\.log/],Bt=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
|
|
9
|
+
`).filter(o=>!Yt.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 qt from"fs/promises";import Vt from"os";import me from"path";import H from"process";import Pe from"path";import Ht from"fs/promises";var Oe=_("agent-output-utils");async function J({initialResult:e,agentName:t,hasError:r}){let n="",o=Pe.join(process.cwd(),F,se);try{let s=await Ht.readFile(o,"utf-8");s&&(n=s,Oe.log(`Pulled result from ${Pe.relative(process.cwd(),o)}`))}catch{Oe.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&&Oe.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 B=_("runner_claude"),nt="Claude Code",Kt=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(B.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?(B.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}):(B.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,aiGateway:n}){let o=e,{accountType:s,prompt:a,modelVersionOverrides:l}=o,{model:i}=o;if(n){let{token:R,url:g}=n;if(!R||!g)throw new Error("No token or url provided from AI Gateway");let f=Wt[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=R,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,N,y,m=me.join(H.cwd(),"node_modules"),w=[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],A=`${H.env.NVM_BIN}/node`;B.log(`Running ${A} ${w.join(" ")}`);let P=t.utils.run(A,w,{all:!0,env:H.env});P.stdin?.end();let I=de(()=>{r?.({steps:d,duration:E})},250),x=(R,g)=>{let f={...R,id:h};h+=1,c.push(f),d.push(f),g||I.flush(),I(),g&&I.flush()},C="";return P.all?.on("data",R=>{if(C+=R.toString(),!R.includes(`
|
|
11
|
+
`))return;let g=C.split(`
|
|
12
|
+
`).filter(Boolean).map(f=>{try{return JSON.parse(f)}catch{B.log("Could not parse line",f)}return null}).filter(Boolean);C="",g.forEach(f=>{Array.isArray(f?.message?.content)?f.message.content.forEach(u=>{switch(u.type){case"text":{u.text&&x({message:u.text});break}case"image":{typeof u.source=="object"&&u.source&&u.source.type==="base64"&&u.source.media_type?x({message:``}):B.log(`Unsupported image type ${u.source?.type}`,u.source);break}case"tool_use":{if(u.name==="Task"){let T=u.input?.description&&`\`${u.input.description}\``;x({title:[u.name,T].filter(Boolean).join(" ")})}else u.id&&(p[u.id]=u);I.flush();break}case"tool_result":{let T=u.tool_use_id?p[u.tool_use_id]:void 0,D;if(T){let $=T.input?.file_path&&me.relative(H.cwd(),T.input.file_path),S=$&&`\`${$}\``;D=[T.name,S].filter(Boolean).join(" ")}let j=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(T?.name||""),k;if(typeof u.content=="string")k=u.content;else if(Array.isArray(u.content)){let $=[];u.content.forEach(S=>{S?.type==="text"&&typeof S.text=="string"?$.push(S.text):S?.type==="image"&&typeof S.source=="object"&&S.source?S.source.type==="base64"&&S.source.media_type?$.push(``):B.log(`Unsupported image type ${S.source.type}`,S.source):B.log(`Unsupported block type ${S?.type}`)}),k=$.join(`
|
|
13
|
+
|
|
14
|
+
`)}j&&k&&(k=`\`\`\`
|
|
15
|
+
${k.trim()}
|
|
16
|
+
\`\`\``),x({title:D,message:k},!0);break}case"thinking":{u.thinking&&x({title:"Thinking",message:u.thinking},!0);break}default:B.log(`Message content type is not supported ${u.type}`,u)}}):f?.type==="result"&&(E=f.duration_ms||0,f.is_error?y=f.result:N=f.result,[c,d].forEach(u=>{u[u.length-1]?.message===N&&u.pop()}))})}),await P.catch(R=>{({error:y,result:N}=Kt({catchError:R,runCmd:P,error:y,result:N,runnerName:"Claude"}))}),I.flush(),{steps:c,duration:E,result:await J({initialResult:N,agentName:nt,hasError:!!y}),error:z({error:y,agentName:nt}),isRetryableError:Z(y)}}var ot=async()=>{let e=me.join(Vt.homedir(),".claude");await qt.rm(e,{recursive:!0,force:!0})},Wt={[M]:{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}}},[G]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[Y]:{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 Xt from"fs/promises";import Jt from"os";import Le from"path";import W from"process";var Q=_("runner_codex"),st="Codex CLI",zt=({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 ke({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:x,url:C}=o;if(!x||!C)throw new Error("No token or url provided from AI Gateway");let R=Zt[s];if(!R)throw new Error(`Codex is not supported for the account type ${s}`);if(i&&!R?.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=x,W.env.OPENAI_BASE_URL=C}else if(!W.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let d=[],c=[],p={},h=0,E=0,N,y,m=Le.join(W.cwd(),"node_modules"),w=[Le.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),A=`${W.env.NVM_BIN}/node`;Q.log(`Running ${A} ${w.join(" ")}`);let P=t.utils.run(A,w,{all:!0,env:{...W.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),I="";return P.all.on("data",x=>{if(I+=x.toString(),!x.includes(`
|
|
17
|
+
`))return;let C=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 R=[],g=!1;C.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=er(p[f.call_id],f);u.id=h,h+=1,u&&(c.push(u),d.push(u),R.push(u),g=!0)}else f?.type==="message"&&f.role==="assistant"?N=f.content.map(u=>u.text).join(`
|
|
19
|
+
`):f?.type==="message"&&f.role==="system"&&(y=f.content.map(u=>u.text).join(`
|
|
20
|
+
`))}),g&&(r?.({steps:d,duration:E}),n?.({steps:R,duration:E}))}),await P.catch(x=>{({error:y,result:N}=zt({catchError:x,runCmd:P,error:y,result:N,runnerName:"Codex"}))}),{steps:c,duration:E,result:await J({initialResult:N,agentName:st,hasError:!!y}),error:z({error:y,agentName:st}),isRetryableError:Z(y)}}var it=async()=>{let e=Le.join(Jt.homedir(),".codex");await Xt.rm(e,{recursive:!0,force:!0})},Zt={[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},o1:{maxTokens:1e5},"o1-mini":{maxTokens:65536},"o3-mini":{maxTokens:1e5},"gpt-image-1":{},"dall-e-2":{},"dall-e-3":{}}},[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}}},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}}},[Y]:{models:{"codex-mini-latest":{maxTokens:75e3},"gpt-3.5-turbo":{maxTokens:4096},"gpt-4-turbo":{maxTokens:4096},"gpt-4o":{maxTokens:16384},"gpt-4o-mini":{maxTokens:32768},"o3-mini":{maxTokens:16e3}}},[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}}}},Qt=new Set(["bash","-lc"]),er=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!Qt.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){Q.error("Could not decode outputMsg",s,t.output)}return{title:n,message:o}};import
|
|
23
|
-
`))return;let f=
|
|
24
|
-
`).filter(Boolean).map(u=>{try{if(u.startsWith("[API Error")){let
|
|
25
|
-
${
|
|
26
|
-
\`\`\``),
|
|
22
|
+
\`\`\``)}catch(s){Q.error("Could not decode outputMsg",s,t.output)}return{title:n,message:o}};import tr from"fs/promises";import rr from"os";import ge from"path";import q from"process";var ie=_("runner_gemini"),at="Gemini CLI",nr=({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})),or={list_directory:"List",read_file:"Read",write_file:"Write",glob:"Find",search_file_content:"Find",replace:"Edit",run_shell_command:"Run",web_fetch:"Web Fetch",web_search:"Web Search",read_many_files:"Read Many",save_memory:"Memorize"};async function Fe({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=sr[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 T=l?.gemini?.[s];T&&(i=T)}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,N=0,y,m,w=ge.join(q.cwd(),"node_modules"),A=[ge.join(q.env.NODE_PATH||w,".bin/gemini"),...i?["--model",i]:[],"--yolo","-p",a],P=`${q.env.NVM_BIN}/node`;ie.log(`Running ${P} ${A.join(" ")}`);let I=t.utils.run(P,A,{all:!0,env:q.env});I.stdin?.end();let x=de(()=>{r?.({steps:d,duration:N}),n?.({steps:c,duration:N}),c=[]},250),C=(g,f)=>{g.id=E,E+=1,p.push(g),d.push(g),c.push(g),f||x.flush(),x(),f&&x.flush()},R="";return I.all.on("data",g=>{if(R+=g.toString(),!g.includes(`
|
|
23
|
+
`))return;let f=R.toString().split(`
|
|
24
|
+
`).filter(Boolean).map(u=>{try{if(u.startsWith("[API Error")){let T=u.match(/\[api error: (.+?)]$/i)?.[1];return{type:"error",value:fe(T,!1)?.error?.message||T||"Gemini encountered error"}}return JSON.parse(u)}catch{}return null}).filter(Boolean);R="",f.forEach(u=>{switch(u.type){case"thought":{let T=u.value;C({title:T?.subject??"Thinking...",message:T?.description},!0);break}case"content":{u.value&&C({message:u.value});break}case"tool_call_request":{let T=u.value,D=or[T.name]??T.name,j=T.args?.path||T.args?.absolute_path,k=j&&ge.relative(q.cwd(),j),$=T.args?.command,It={title:[D,k&&`\`${k}\``,$&&`\`${$}\``].filter(Boolean).join(" ")};h[T.callId]=It,x.flush();break}case"tool_result":{let T=u.value,D=h[T.callId];if(D){let j=[T.resultDisplay,T.responseParts?.functionResponse?.response?.output].find(k=>typeof k=="string"&&k);j&&(D.message=`\`\`\`
|
|
25
|
+
${j.trim()}
|
|
26
|
+
\`\`\``),C(D,!0)}break}case"result":{N=u.duration_ms,y=u.value,[p,d,c].forEach(T=>{T[T.length-1]?.message===y&&T.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:y}=nr({catchError:g,runCmd:I,error:m,result:y,runnerName:"Gemini"}))}),x.flush(),{steps:p,duration:N,result:await J({initialResult:y,agentName:at,hasError:!!m}),error:z({error:m,agentName:at}),isRetryableError:Z(m)}}var lt=async()=>{let e=ge.join(rr.homedir(),".gemini");await tr.rm(e,{recursive:!0,force:!0})},sr={[M]:{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}}},[G]:{models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[Y]:{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 ir={codex:{runner:ke,clean:it},claude:{runner:ve,clean:ot},gemini:{runner:Fe,clean:lt}},ut=ir;var ct=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:n})=>{let o=ar();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=lr({apiToken:r});Me(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=Je(({steps:E=[],duration:N})=>{let y=[...E];return E.length=0,X(e.id,e.sessionId,{steps:y,duration:N})},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}})},lr=({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 ur from"crypto";import V from"fs/promises";import L from"path";import b from"process";var O=_("context"),cr=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:b.env.NETLIFY_TEAM_ID,userId:b.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:b.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},pr=10,dr=async e=>{let{name:t,ext:r}=L.parse(e),n=e,o=L.join(b.cwd(),F,n),s=0;for(;await fr(o);){if(s>=pr)throw new Error("Failed to generate context file");n=`${t}-${ur.randomUUID().slice(0,5)}${r}`,o=L.join(b.cwd(),F,n),s+=1}return n},fr=async e=>{try{return await V.access(e),!0}catch{return!1}},mr=async()=>{try{O.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 O.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"?(O.warn("Catchall consumer missing or invalid contextScopes"),null):r:(O.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?O.warn("Netlify features context request timed out"):O.warn("Failed to fetch Netlify features context:",e.message),null}},gr=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"?O.warn(`Download timeout for ${e}`):O.warn(`Failed to download context file ${e}:`,r.message),!1}},Ee=null,hr=async()=>{if(Ee)return Ee;let e=await mr();if(!e)return[];let t=L.join(b.cwd(),F,Ce);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 O.warn(`Invalid scope data for ${o}, skipping...`),null;let a=`${o}.md`,l=L.join(t,a),i=L.join(F,Ce,a);return O.log(`Downloading ${s.scope} context...`),await gr(s.endpoint,l)?(O.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=cr(t),s=await dr(Ke),a=L.join(b.cwd(),F);await V.mkdir(a,{recursive:!0});let l=L.join(F,s),i=L.join(b.cwd(),l),d=L.join(b.cwd(),F,se);try{await V.unlink(d),O.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.
|
|
@@ -36,26 +36,26 @@ ${r.siteContext.filter(m=>m.site_context).map(m=>typeof m.site_context=="string"
|
|
|
36
36
|
|
|
37
37
|
`)}
|
|
38
38
|
</project_rules>
|
|
39
|
-
`);let h="";if(r.sessionHistoryContext?.length){let m=
|
|
39
|
+
`);let h="";if(r.sessionHistoryContext?.length){let m=L.join(b.cwd(),F,Ae);await V.mkdir(m,{recursive:!0});let w=await Promise.all(r.sessionHistoryContext.map(async(A,P)=>{let I=P+1,x=`attempt-${I}.md`,C=L.join(m,x),R=L.join(F,Ae,x),g=`# Task History - Attempt ${I}
|
|
40
40
|
|
|
41
41
|
## Request - what the user asked for
|
|
42
|
-
${
|
|
42
|
+
${A.request}
|
|
43
43
|
|
|
44
44
|
---
|
|
45
45
|
|
|
46
46
|
## Response - what the agent replied with after its work
|
|
47
47
|
|
|
48
|
-
${
|
|
49
|
-
`;return await V.writeFile(
|
|
48
|
+
${A.response}
|
|
49
|
+
`;return await V.writeFile(C,g,"utf-8"),O.log(`Created history file: ${R}`),R}));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.
|
|
53
53
|
|
|
54
|
-
${
|
|
54
|
+
${w.slice(-5).map(A=>`- ${A}`).join(`
|
|
55
55
|
`)}
|
|
56
56
|
|
|
57
57
|
</session_history_context>
|
|
58
|
-
`}let E=await
|
|
58
|
+
`}let E=await hr(),N="";E.length>0&&(N=`
|
|
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.
|
|
@@ -65,7 +65,7 @@ ${C.response}
|
|
|
65
65
|
|
|
66
66
|
Refer to these files when working with specific Netlify features.
|
|
67
67
|
</netlify_features_context>
|
|
68
|
-
`);let
|
|
68
|
+
`);let y=`
|
|
69
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
70
|
|
|
71
71
|
<request>
|
|
@@ -97,12 +97,12 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
97
97
|
- Netlify Functions directory: ${o.functionsDir}
|
|
98
98
|
</metadata>
|
|
99
99
|
<environment>
|
|
100
|
-
- Node Version: ${
|
|
100
|
+
- Node Version: ${b.version||"unknown"}
|
|
101
101
|
- Environment variables are set globally (e.g. \`echo $VARIABLE_NAME\` can be used to check if a var is set).
|
|
102
102
|
- 'netlify-cli' npm package is already available as a global package. Don't try to install it again
|
|
103
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
104
|
</environment>
|
|
105
|
-
${
|
|
105
|
+
${N}
|
|
106
106
|
<docs>
|
|
107
107
|
- Netlify Docs: https://docs.netlify.com
|
|
108
108
|
- LLM Resources Index: https://docs.netlify.com/llms.txt
|
|
@@ -110,7 +110,7 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
110
110
|
</extra_context>
|
|
111
111
|
|
|
112
112
|
${h}
|
|
113
|
-
`;return await V.writeFile(i,
|
|
113
|
+
`;return await V.writeFile(i,y,"utf-8"),O.log(`Generated agent context document at: ${i}`),y.length>5e5&&(y=`
|
|
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
|
-
`),
|
|
124
|
+
`),y};var Er=_("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&&Er.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:_r(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}},_r=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 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
|
|
130
|
+
`;import Tr 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 Te=_("deploy_stage"),be=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;Te.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 Ye(t.id,t.sessionId);E?.title&&(h=E.title)}catch(E){Te.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,Tr.env.SITE_NAME),filter:o})}catch(h){return Te.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 Te.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(()=>X(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 Nr}from"@netlify/otel";var xr=yr(import.meta.url),_t=xr("../package.json"),Tt=_("pipeline_index"),ye=3,yt=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=Nr(),d,{aiGateway:c,context:p,persistSteps:h,runner:E,sha:N}=await ct({config:e,apiToken:t,cliPath:r,cwd:n,errorLogsPath:o,filter:s,runnerVersion:_t.version});l=E.clean,e.sha=N;let{runnerResult:y}=await _e({cliPath:r,config:e,context:p,runner:E.runner,persistSteps:h,aiGateway:c}),m=await be({cliPath:r,config:e,context:p,result:y.result,filter:s}),w=y,A=[];if(m.hasChanges&&m.deployError){A.push(Ge(m.deployError));let g=1;for(;g<=ye&&!m.previewInfo;)Tt.log(`Deploy attempt had errors. Retrying. ${g}/${ye}`),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:A});w={...u,steps:[...w.steps||[],...u.steps||[]],duration:(w.duration||0)+(u.duration||0)},m=await be({cliPath:r,config:e,context:p,result:u.result,filter:s}),m.deployError&&A.push(m.deployError),g++});g>ye&&!m.previewInfo&&(d=new Error(`Deploy validation failed after ${ye} attempts`))}let{diff:P,resultDiff:I,previewInfo:x,diffBinary:C,resultDiffBinary:R}=m;if(await Et({config:e,diff:P,result:w.result,duration:w.duration,resultDiff:I,diffBinary:C,resultDiffBinary:R,previewInfo:x}),d)throw d;await E.clean?.()}catch(i){Tt.error("Got error while running pipeline",i),await l?.();let d=i instanceof Error&&i.message;throw await X(e.id,e.sessionId,{result:d||"Encountered error when running agent",state:"error"}),i}};import v from"process";var Rr="codex",Ir=e=>(e??[]).filter(t=>t.request&&t.response),wr=e=>(e??[]).filter(t=>t.site_context),Nt=_("config"),xt=()=>{let e=v.env.NETLIFY_AGENT_RUNNER_ID,t=v.env.NETLIFY_AGENT_RUNNER_SESSION_ID;if(!e||!t)throw new Error("ID of agent runner is not provided");let r=v.env.NETLIFY_AGENT_RUNNER_RESULT_BRANCH,n=v.env.NETLIFY_AGENT_RUNNER_PROMPT;if(!n)throw new Error("Prompt is not provided");let o=v.env.NETLIFY_AGENT_RUNNER_AGENT||Rr,s=v.env.NETLIFY_AGENT_RUNNER_MODEL,a=v.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED==="1",l=v.env.NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED==="1",i=v.env.ERROR_LOGS_PATH,d=fe(v.env.NETLIFY_AGENT_RUNNER_CONTEXT,!0,Nt),c=Ir(d),p=wr(d),h=v.env.NETLIFY_AGENT_RUNNER_HAS_REPO!=="0",E=!v.env.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED,N=v.env.NETLIFY_AGENT_RUNNER_SHA,y=Ar(),m=Ze(),w={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:N,accountType:y,validateAgentWithBuild:l,modelVersionOverrides:m};return Nt.log({fullConfig:w}),w},Ar=()=>{let e=v.env.NETLIFY_TEAM_TYPE;return e?e.includes("personal")?G:e.includes("pro")?"pro":e.startsWith("enterprise")?M:e.startsWith("free")?Y:U:U};var Rt=_("bin_cmd"),te=Cr(De.argv.slice(2),{string:["auth","cwd","cli-path","error-logs-path","filter","trace-exporter-url"]});try{let e=xt();await yt({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"]}),Rt.info("Finished agent"),De.exit(0)}catch(e){Rt.error("Error running agent pipeline:",e),De.exit(1)}
|
|
132
132
|
//# sourceMappingURL=bin.js.map
|
package/dist/index.js
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
|
-
import{createRequire as
|
|
2
|
-
`),r=[],n=-1,o=0;for(;o<t.length;){let l=t[o].slice(0,500).toLowerCase();if(
|
|
1
|
+
import{createRequire as cr}from"module";import{createTracerProvider as gt}from"@netlify/otel/bootstrap";import{SimpleSpanProcessor as be}from"@netlify/otel/opentelemetry";import{FetchInstrumentation as ht}from"@netlify/otel/instrumentation-fetch";import{withActiveSpan as Et}from"@netlify/otel";import{OTLPTraceExporter as _t}from"@opentelemetry/exporter-trace-otlp-grpc";function y(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=y("tracing"),Le=(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 ye),new be(new _t({url:r}))],instrumentations:[new ht({skipHeaders:!0})]});function ie(e,t,r){return _e.log(`\u23F3 TRACE: ${t} starting...`),Et(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[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(", ")}]`:"";_e.log(`${s} TRACE: ${t.name} completed in ${r.toFixed(2)}ms${a}`),t.status?.code===2&&t.status.message&&_e.log(` \u274C Error: ${t.status.message}`)}};var yt=["error","failed","exception","fatal","panic","abort","crash"];function $e(e){let t=e.split(`
|
|
2
|
+
`),r=[],n=-1,o=0;for(;o<t.length;){let l=t[o].slice(0,500).toLowerCase();if(yt.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
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(o=>!vt.some(s=>s instanceof RegExp?s.test(o):o===s))).length!==0,status:t.stdout}};var
|
|
9
|
-
`).forEach(a=>{let l=a.match(/\?\? (.+?)\.log$/)?.[1];l&&n.push(`:!${l}.log`)}),n};import $t from"fs/promises";import Dt from"os";import de from"path";import M from"process";import
|
|
10
|
-
`))return;let m=
|
|
11
|
-
`).filter(Boolean).map(p=>{try{return JSON.parse(p)}catch{F.log("Could not parse line",p)}return null}).filter(Boolean);
|
|
7
|
+
`);return s.length>e.length*.8?e:s}import fe from"process";import{getTracer as zt}from"@netlify/otel";import ae from"process";var Te=ae.env.NETLIFY_API_URL,xe=ae.env.NETLIFY_API_TOKEN,Q=y("api"),le=async(e,t={})=>{if(!Te||!xe)throw new Error("No API URL or token");let r=new URL(e,Te),n={...t,headers:{...t.headers,Authorization:`Bearer ${xe}`}};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},De=e=>{Q.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Te=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(xe=e.constants.NETLIFY_API_TOKEN)},ue=(e,t)=>le(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),B=(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=y("ai_gateway"),Ge=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 Nt,execaCommand as br}from"execa";import{Transform as Tt}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","NETLIFY_AGENT_RUNNER_ID","NETLIFY_AGENT_RUNNER_SESSION_ID","NETLIFY_AGENT_RUNNER_PROMPT","NETLIFY_AGENT_RUNNER_AGENT","NETLIFY_AGENT_RUNNER_MODEL","NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_ENABLED","NETLIFY_FF_AGENT_RUNNER_POST_EXECUTION_VALIDATION_WITH_BUILD_ENABLED","ERROR_LOGS_PATH","NETLIFY_AGENT_RUNNER_CONTEXT","NETLIFY_AGENT_RUNNER_HAS_REPO","NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED","NETLIFY_AGENT_RUNNER_SHA","NETLIFY_TEAM_TYPE","AGENT_RUNNERS_DEBUG","NETLIFY_TEAM_ID","NETLIFY_AGENT_RUNNER_USER_ID","SITE_NAME"],Rt=["true","false","undefined","null","claude","gemini","codex",""];function It(){return Object.entries(process.env).filter(([e,t])=>!(!t||xt.includes(e)||Rt.includes(t)||parseInt(t)||t.length<5)).map(([,e])=>e).filter(Boolean)}function Re(e){if(typeof e!="string")return e;let t=It();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 Tt{constructor(t={}){super({...t,objectMode:!1})}_transform(t,r,n){let o=t.toString(),s=Re(o);n(null,s)}};function je(){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"?Re(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"?Re(n):n;return typeof o=="function"?r(a,o):r(a,o,s)}}var Dr=y("shell"),At={preferLocal:!0},Ye=(e,t,r)=>{let[n,o]=Ct(t,r),s={...At,...o},a=Nt(e,n,s);return St(a,s),a};var Ct=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},St=(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 Be="netlify-agent-runner-context.md",Ie="task-history",we="netlify-context",b=".netlify",re="results.md",Ne="assets",H="other",q="personal";var K="enterprise",V="free";var Pt=y("utils"),Ot=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 Ot(t),!n)return r=!1,s=null,c;let d=n,h=o;n=null,o=[],c=await e(...d),h.forEach(E=>{E(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):Pt.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 kt(t),{hasChanges:n}=r,{status:o}=r;if(!n)return{hasChanges:!1};let s=await bt(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 E={hasChanges:!0,diff:i,resultDiff:d};return i!==c&&(E.diffBinary=Ve.from(c).toString("base64")),h&&(E.resultDiffBinary=h),E},vt=["?? mise.toml","?? deno.lock",/\?\? .+?\.log/],kt=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
|
|
8
|
+
`).filter(o=>!vt.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()},Je=async e=>{let{stdout:t}=await e.utils.run("git",["rev-list","--max-parents=0","HEAD"]);return t.trim()},bt=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 $t from"fs/promises";import Dt from"os";import de from"path";import M from"process";import Ae from"path";import Lt from"fs/promises";var Ce=y("agent-output-utils");async function W({initialResult:e,agentName:t,hasError:r}){let n="",o=Ae.join(process.cwd(),b,re);try{let s=await Lt.readFile(o,"utf-8");s&&(n=s,Ce.log(`Pulled result from ${Ae.relative(process.cwd(),o)}`))}catch{Ce.log(`No results file found at ${Ae.relative(process.cwd(),o)}`)}return n||(!e&&!r?`${t} has finished working on task.`:e||void 0)}function X({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&&Ce.log(`Providing updated error messsage: ${o}, replacing original error: ${r}`),o||r||void 0}function J(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=y("runner_claude"),ze="Claude Code",Ft=({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 Se({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:R,url:m}=n;if(!R||!m)throw new Error("No token or url provided from AI Gateway");let p=Ut[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=R,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,E=0,I,T,g=de.join(M.cwd(),"node_modules"),S=[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],N=`${M.env.NVM_BIN}/node`;F.log(`Running ${N} ${S.join(" ")}`);let P=t.utils.run(N,S,{all:!0,env:M.env});P.stdin?.end();let w=ce(()=>{r?.({steps:f,duration:E})},250),x=(R,m)=>{let p={...R,id:h};h+=1,c.push(p),f.push(p),m||w.flush(),w(),m&&w.flush()},A="";return P.all?.on("data",R=>{if(A+=R.toString(),!R.includes(`
|
|
10
|
+
`))return;let m=A.split(`
|
|
11
|
+
`).filter(Boolean).map(p=>{try{return JSON.parse(p)}catch{F.log("Could not parse line",p)}return null}).filter(Boolean);A="",m.forEach(p=>{Array.isArray(p?.message?.content)?p.message.content.forEach(u=>{switch(u.type){case"text":{u.text&&x({message:u.text});break}case"image":{typeof u.source=="object"&&u.source&&u.source.type==="base64"&&u.source.media_type?x({message:``}):F.log(`Unsupported image type ${u.source?.type}`,u.source);break}case"tool_use":{if(u.name==="Task"){let _=u.input?.description&&`\`${u.input.description}\``;x({title:[u.name,_].filter(Boolean).join(" ")})}else u.id&&(d[u.id]=u);w.flush();break}case"tool_result":{let _=u.tool_use_id?d[u.tool_use_id]:void 0,$;if(_){let D=_.input?.file_path&&de.relative(M.cwd(),_.input.file_path),C=D&&`\`${D}\``;$=[_.name,C].filter(Boolean).join(" ")}let U=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(_?.name||""),k;if(typeof u.content=="string")k=u.content;else if(Array.isArray(u.content)){let D=[];u.content.forEach(C=>{C?.type==="text"&&typeof C.text=="string"?D.push(C.text):C?.type==="image"&&typeof C.source=="object"&&C.source?C.source.type==="base64"&&C.source.media_type?D.push(``):F.log(`Unsupported image type ${C.source.type}`,C.source):F.log(`Unsupported block type ${C?.type}`)}),k=D.join(`
|
|
12
12
|
|
|
13
13
|
`)}U&&k&&(k=`\`\`\`
|
|
14
14
|
${k.trim()}
|
|
15
|
-
\`\`\``),
|
|
16
|
-
`))return;let
|
|
17
|
-
`).filter(Boolean).map(p=>{try{return JSON.parse(p)}catch{z.log("Could not parse line",p)}return null}).filter(Boolean);
|
|
18
|
-
`):p?.type==="message"&&p.role==="system"&&(
|
|
19
|
-
`))}),m&&(r?.({steps:f,duration:
|
|
15
|
+
\`\`\``),x({title:$,message:k},!0);break}case"thinking":{u.thinking&&x({title:"Thinking",message:u.thinking},!0);break}default:F.log(`Message content type is not supported ${u.type}`,u)}}):p?.type==="result"&&(E=p.duration_ms||0,p.is_error?T=p.result:I=p.result,[c,f].forEach(u=>{u[u.length-1]?.message===I&&u.pop()}))})}),await P.catch(R=>{({error:T,result:I}=Ft({catchError:R,runCmd:P,error:T,result:I,runnerName:"Claude"}))}),w.flush(),{steps:c,duration:E,result:await W({initialResult:I,agentName:ze,hasError:!!T}),error:X({error:T,agentName:ze}),isRetryableError:J(T)}}var Ze=async()=>{let e=de.join(Dt.homedir(),".claude");await $t.rm(e,{recursive:!0,force:!0})},Ut={[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 Mt from"fs/promises";import Gt from"os";import Pe from"path";import Y from"process";var z=y("runner_codex"),Qe="Codex CLI",jt=({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 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:x,url:A}=o;if(!x||!A)throw new Error("No token or url provided from AI Gateway");let R=Yt[s];if(!R)throw new Error(`Codex is not supported for the account type ${s}`);if(i&&!R?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(l?.codex){let m=l?.codex?.[s];m&&(i=m)}Y.env.OPENAI_API_KEY=x,Y.env.OPENAI_BASE_URL=A}else if(!Y.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let f=[],c=[],d={},h=0,E=0,I,T,g=Pe.join(Y.cwd(),"node_modules"),S=[Pe.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",a].filter(Boolean),N=`${Y.env.NVM_BIN}/node`;z.log(`Running ${N} ${S.join(" ")}`);let P=t.utils.run(N,S,{all:!0,env:{...Y.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),w="";return P.all.on("data",x=>{if(w+=x.toString(),!x.includes(`
|
|
16
|
+
`))return;let A=w.toString().split(`
|
|
17
|
+
`).filter(Boolean).map(p=>{try{return JSON.parse(p)}catch{z.log("Could not parse line",p)}return null}).filter(Boolean);w="";let R=[],m=!1;A.forEach(p=>{if(p?.duration_ms&&(E=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=Ht(d[p.call_id],p);u.id=h,h+=1,u&&(c.push(u),f.push(u),R.push(u),m=!0)}else p?.type==="message"&&p.role==="assistant"?I=p.content.map(u=>u.text).join(`
|
|
18
|
+
`):p?.type==="message"&&p.role==="system"&&(T=p.content.map(u=>u.text).join(`
|
|
19
|
+
`))}),m&&(r?.({steps:f,duration:E}),n?.({steps:R,duration:E}))}),await P.catch(x=>{({error:T,result:I}=jt({catchError:x,runCmd:P,error:T,result:I,runnerName:"Codex"}))}),{steps:c,duration:E,result:await W({initialResult:I,agentName:Qe,hasError:!!T}),error:X({error:T,agentName:Qe}),isRetryableError:J(T)}}var et=async()=>{let e=Pe.join(Gt.homedir(),".codex");await Mt.rm(e,{recursive:!0,force:!0})},Yt={[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}}}},Bt=new Set(["bash","-lc"]),Ht=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!Bt.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){z.error("Could not decode outputMsg",s,t.output)}return{title:n,message:o}};import
|
|
22
|
-
`))return;let p=
|
|
23
|
-
`).filter(Boolean).map(u=>{try{if(u.startsWith("[API Error")){let
|
|
21
|
+
\`\`\``)}catch(s){z.error("Could not decode outputMsg",s,t.output)}return{title:n,message:o}};import qt from"fs/promises";import Kt from"os";import pe from"path";import G from"process";var oe=y("runner_gemini"),tt="Gemini CLI",Vt=({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})),Wt={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 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:m,url:p}=o;if(!m||!p)throw new Error("No token or url provided from AI Gateway");let u=Xt[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 _=l?.gemini?.[s];_&&(i=_)}G.env.GEMINI_API_KEY=m,G.env.GOOGLE_GEMINI_BASE_URL=p}else if(!G.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let f=[],c=[],d=[],h={},E=0,I=0,T,g,S=pe.join(G.cwd(),"node_modules"),N=[pe.join(G.env.NODE_PATH||S,".bin/gemini"),...i?["--model",i]:[],"--yolo","-p",a],P=`${G.env.NVM_BIN}/node`;oe.log(`Running ${P} ${N.join(" ")}`);let w=t.utils.run(P,N,{all:!0,env:G.env});w.stdin?.end();let x=ce(()=>{r?.({steps:f,duration:I}),n?.({steps:c,duration:I}),c=[]},250),A=(m,p)=>{m.id=E,E+=1,d.push(m),f.push(m),c.push(m),p||x.flush(),x(),p&&x.flush()},R="";return w.all.on("data",m=>{if(R+=m.toString(),!m.includes(`
|
|
22
|
+
`))return;let p=R.toString().split(`
|
|
23
|
+
`).filter(Boolean).map(u=>{try{if(u.startsWith("[API Error")){let _=u.match(/\[api error: (.+?)]$/i)?.[1];return{type:"error",value:qe(_,!1)?.error?.message||_||"Gemini encountered error"}}return JSON.parse(u)}catch{}return null}).filter(Boolean);R="",p.forEach(u=>{switch(u.type){case"thought":{let _=u.value;A({title:_?.subject??"Thinking...",message:_?.description},!0);break}case"content":{u.value&&A({message:u.value});break}case"tool_call_request":{let _=u.value,$=Wt[_.name]??_.name,U=_.args?.path||_.args?.absolute_path,k=U&&pe.relative(G.cwd(),U),D=_.args?.command,mt={title:[$,k&&`\`${k}\``,D&&`\`${D}\``].filter(Boolean).join(" ")};h[_.callId]=mt,x.flush();break}case"tool_result":{let _=u.value,$=h[_.callId];if($){let U=[_.resultDisplay,_.responseParts?.functionResponse?.response?.output].find(k=>typeof k=="string"&&k);U&&($.message=`\`\`\`
|
|
24
24
|
${U.trim()}
|
|
25
|
-
\`\`\``),
|
|
25
|
+
\`\`\``),A($,!0)}break}case"result":{I=u.duration_ms,T=u.value,[d,f,c].forEach(_=>{_[_.length-1]?.message===T&&_.pop()});break}case"error":{g=u.value;break}case"finished":break;default:{oe.warn("Unhandled message type:",u.type);break}}})}),await w.catch(m=>{({error:g,result:T}=Vt({catchError:m,runCmd:w,error:g,result:T,runnerName:"Gemini"}))}),x.flush(),{steps:d,duration:I,result:await W({initialResult:T,agentName:tt,hasError:!!g}),error:X({error:g,agentName:tt}),isRetryableError:J(g)}}var rt=async()=>{let e=pe.join(Kt.homedir(),".gemini");await qt.rm(e,{recursive:!0,force:!0})},Xt={[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 Jt={codex:{runner:Oe,clean:et},claude:{runner:Se,clean:Ze},gemini:{runner:ve,clean:rt}},nt=Jt;var ot=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:n})=>{let o=zt();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=Zt({apiToken:r});De(i);let f=e.useGateway?await Ge({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:E=[],duration:I})=>{let T=[...E];return E.length=0,B(e.id,e.sessionId,{steps:T,duration:I})},t),d;e.hasRepo?e.sha?(d=e.sha,s?.setAttributes({"init.sha.source":"provided"})):(d=await Xe(i),await ue(e.id,{sha:d}),s?.setAttributes({"init.sha.source":"current_commit"})):(d=await Je(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}})},Zt=({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:Ye}});import Qt from"crypto";import j from"fs/promises";import v from"path";import L from"process";var O=y("context"),er=e=>{let t=e?.constants||{};return{siteId:t.SITE_ID,accountId:L.env.NETLIFY_TEAM_ID,userId:L.env.NETLIFY_AGENT_RUNNER_USER_ID,siteSlug:L.env.SITE_NAME,apiHost:t.NETLIFY_API_HOST,functionsDir:t.FUNCTIONS_DIST}},tr=10,rr=async e=>{let{name:t,ext:r}=v.parse(e),n=e,o=v.join(L.cwd(),b,n),s=0;for(;await nr(o);){if(s>=tr)throw new Error("Failed to generate context file");n=`${t}-${Qt.randomUUID().slice(0,5)}${r}`,o=v.join(L.cwd(),b,n),s+=1}return n},nr=async e=>{try{return await j.access(e),!0}catch{return!1}},or=async()=>{try{O.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 O.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"?(O.warn("Catchall consumer missing or invalid contextScopes"),null):r:(O.warn("Catchall consumer not found in context consumers"),null)}catch(e){return e.name==="AbortError"?O.warn("Netlify features context request timed out"):O.warn("Failed to fetch Netlify features context:",e.message),null}},sr=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 j.writeFile(t,n,"utf-8"),!0}catch(r){return r.name==="AbortError"?O.warn(`Download timeout for ${e}`):O.warn(`Failed to download context file ${e}:`,r.message),!1}},me=null,ir=async()=>{if(me)return me;let e=await or();if(!e)return[];let t=v.join(L.cwd(),b,we);await j.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([o,s])=>{if(!s||typeof s!="object"||!s.endpoint||!s.scope)return O.warn(`Invalid scope data for ${o}, skipping...`),null;let a=`${o}.md`,l=v.join(t,a),i=v.join(b,we,a);return O.log(`Downloading ${s.scope} context...`),await sr(s.endpoint,l)?(O.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=er(t),s=await rr(Be),a=v.join(L.cwd(),b);await j.mkdir(a,{recursive:!0});let l=v.join(b,s),i=v.join(L.cwd(),l),f=v.join(L.cwd(),b,re);try{await j.unlink(f),O.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.
|
|
@@ -35,36 +35,36 @@ ${r.siteContext.filter(g=>g.site_context).map(g=>typeof g.site_context=="string"
|
|
|
35
35
|
|
|
36
36
|
`)}
|
|
37
37
|
</project_rules>
|
|
38
|
-
`);let h="";if(r.sessionHistoryContext?.length){let g=
|
|
38
|
+
`);let h="";if(r.sessionHistoryContext?.length){let g=v.join(L.cwd(),b,Ie);await j.mkdir(g,{recursive:!0});let S=await Promise.all(r.sessionHistoryContext.map(async(N,P)=>{let w=P+1,x=`attempt-${w}.md`,A=v.join(g,x),R=v.join(b,Ie,x),m=`# Task History - Attempt ${w}
|
|
39
39
|
|
|
40
40
|
## Request - what the user asked for
|
|
41
|
-
${
|
|
41
|
+
${N.request}
|
|
42
42
|
|
|
43
43
|
---
|
|
44
44
|
|
|
45
45
|
## Response - what the agent replied with after its work
|
|
46
46
|
|
|
47
|
-
${
|
|
48
|
-
`;return await
|
|
47
|
+
${N.response}
|
|
48
|
+
`;return await j.writeFile(A,m,"utf-8"),O.log(`Created history file: ${R}`),R}));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.
|
|
52
52
|
|
|
53
|
-
${
|
|
53
|
+
${S.slice(-5).map(N=>`- ${N}`).join(`
|
|
54
54
|
`)}
|
|
55
55
|
|
|
56
56
|
</session_history_context>
|
|
57
|
-
`}let
|
|
57
|
+
`}let E=await ir(),I="";E.length>0&&(I=`
|
|
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
|
-
${
|
|
62
|
+
${E.map(g=>`- **${g.scope}**: ${g.path}`).join(`
|
|
63
63
|
`)}
|
|
64
64
|
|
|
65
65
|
Refer to these files when working with specific Netlify features.
|
|
66
66
|
</netlify_features_context>
|
|
67
|
-
`);let
|
|
67
|
+
`);let T=`
|
|
68
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
69
|
|
|
70
70
|
<request>
|
|
@@ -81,8 +81,8 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
81
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
82
|
</responses>
|
|
83
83
|
<attachements>
|
|
84
|
-
- for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${a}/${
|
|
85
|
-
- move assets from ${a}/${
|
|
84
|
+
- for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${a}/${Ne} folder
|
|
85
|
+
- move assets from ${a}/${Ne} 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>
|
|
@@ -96,12 +96,12 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
96
96
|
- Netlify Functions directory: ${o.functionsDir}
|
|
97
97
|
</metadata>
|
|
98
98
|
<environment>
|
|
99
|
-
- Node Version: ${
|
|
99
|
+
- Node Version: ${L.version||"unknown"}
|
|
100
100
|
- Environment variables are set globally (e.g. \`echo $VARIABLE_NAME\` can be used to check if a var is set).
|
|
101
101
|
- 'netlify-cli' npm package is already available as a global package. Don't try to install it again
|
|
102
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
103
|
</environment>
|
|
104
|
-
${
|
|
104
|
+
${I}
|
|
105
105
|
<docs>
|
|
106
106
|
- Netlify Docs: https://docs.netlify.com
|
|
107
107
|
- LLM Resources Index: https://docs.netlify.com/llms.txt
|
|
@@ -109,7 +109,7 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
109
109
|
</extra_context>
|
|
110
110
|
|
|
111
111
|
${h}
|
|
112
|
-
`;return await
|
|
112
|
+
`;return await j.writeFile(i,T,"utf-8"),O.log(`Generated agent context document at: ${i}`),T.length>5e5&&(T=`
|
|
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
|
|
|
115
115
|
<request>
|
|
@@ -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
|
-
`),
|
|
123
|
+
`),T};var ar=y("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&&ar.log("Contextful Prompt:",o),{prompt:o}};var at=y("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;je();let{prompt:f}=await it({cliPath:t,config:r,buildErrorContext:lr(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(E=>setTimeout(E,5e3)),{runnerResult:(await ge({...e,attempt:(i||1)+1})).runnerResult};throw new Error(d.error)}return{runnerResult:d}},lr=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 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=
|
|
129
|
+
`;import ur from"process";var se=y("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=y("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 E=await Fe(t.id,t.sessionId);E?.title&&(h=E.title)}catch(E){he.warn("Failed to fetch session title, using fallback message:",E.message)}d=await ut({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:h,skipBuild:!1,deploySubdomain:Ke(t.id,ur.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=y("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(()=>B(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 dr}from"@netlify/otel";var pr=cr(import.meta.url),pt=pr("../package.json"),ft=y("pipeline_index"),Ee=3,Ro=async({config:e,apiToken:t,cliPath:r="netlify",cwd:n,errorLogsPath:o,filter:s,traceExporterUrl:a})=>{let l;try{await Le(pt.version,e.id,a);let i=dr(),f,{aiGateway:c,context:d,persistSteps:h,runner:E,sha:I}=await ot({config:e,apiToken:t,cliPath:r,cwd:n,errorLogsPath:o,filter:s,runnerVersion:pt.version});l=E.clean,e.sha=I;let{runnerResult:T}=await ge({cliPath:r,config:e,context:d,runner:E.runner,persistSteps:h,aiGateway:c}),g=await ke({cliPath:r,config:e,context:d,result:T.result,filter:s}),S=T,N=[];if(g.hasChanges&&g.deployError){N.push($e(g.deployError));let m=1;for(;m<=Ee&&!g.previewInfo;)ft.log(`Deploy attempt had errors. Retrying. ${m}/${Ee}`),await ie(i,"stage-deploy",async p=>{p?.setAttributes({"stage.attempt":m});let{runnerResult:u}=await ge({cliPath:r,config:e,context:d,runner:E.runner,persistSteps:h,aiGateway:c,buildErrors:N});S={...u,steps:[...S.steps||[],...u.steps||[]],duration:(S.duration||0)+(u.duration||0)},g=await ke({cliPath:r,config:e,context:d,result:u.result,filter:s}),g.deployError&&N.push(g.deployError),m++});m>Ee&&!g.previewInfo&&(f=new Error(`Deploy validation failed after ${Ee} attempts`))}let{diff:P,resultDiff:w,previewInfo:x,diffBinary:A,resultDiffBinary:R}=g;if(await dt({config:e,diff:P,result:S.result,duration:S.duration,resultDiff:w,diffBinary:A,resultDiffBinary:R,previewInfo:x}),f)throw f;await E.clean?.()}catch(i){ft.error("Got error while running pipeline",i),await l?.();let f=i instanceof Error&&i.message;throw await B(e.id,e.sessionId,{result:f||"Encountered error when running agent",state:"error"}),i}};export{Ro as runPipeline};
|
|
131
131
|
//# sourceMappingURL=index.js.map
|