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