@netlify/agent-runner-cli 1.32.0 → 1.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +25 -31
- package/dist/index.js +24 -30
- package/package.json +1 -1
package/dist/bin.js
CHANGED
|
@@ -1,29 +1,23 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`),r=[],n=-1,o=0;for(;o<t.length;){let l=t[o].slice(0,500).toLowerCase();if(
|
|
2
|
+
import De from"process";import Pr from"minimist";import{createRequire as xr}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]-[${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)=>It({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 Ct({url:r}))],instrumentations:[new wt({skipHeaders:!0})]});function ae(e,t,r){return Ne.log(`\u23F3 TRACE: ${t} starting...`),At(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 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 l=t[o].slice(0,500).toLowerCase();if(St.some(f=>l.includes(f))){let f=Math.max(0,o-10,n+1),c=Math.min(t.length-1,o+20),p=[];for(let h=f;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
|
|
9
|
-
`).filter(o=>!Yt.some(s=>s instanceof RegExp?s.test(o):o===s))).length!==0,status:t.stdout}};var
|
|
10
|
-
`).forEach(a=>{let l=a.match(/\?\? (.+?)\.log$/)?.[1];l&&n.push(`:!${l}.log`)}),n};import
|
|
11
|
-
`))return;let g=w.split(`
|
|
12
|
-
`).filter(Boolean).map(f=>{try{return JSON.parse(f)}catch{B.log("Could not parse line",f)}return null}).filter(Boolean);w="",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(`
|
|
8
|
+
`);return s.length>e.length*.8?e:s}import ge from"process";import{getTracer as ur}from"@netlify/otel";import le from"process";var Re=le.env.NETLIFY_API_URL,Ie=le.env.NETLIFY_API_TOKEN,oe=_("api"),ue=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}`}};le.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(le.env.AGENT_RUNNERS_DEBUG==="true")oe.log(`Response headers for ${r}:`),o.headers.forEach((l,i)=>{oe.log(` ${i}: ${l}`)});else{let l=o.headers.get("x-request-id")||o.headers.get("x-nf-request-id");oe.log(`Request ID for ${r}: ${l||"N/A"}`)}if(s||oe.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},Ye=e=>{oe.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)},ce=(e,t)=>ue(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),X=(e,t,r)=>ue(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var Me=(e,t)=>ue(`/api/v1/agent_runners/${e}/sessions/${t}`),je=(e,t,r)=>ue(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}});var Be=_("ai_gateway"),He=async({netlify:e,config:t})=>{let r,n,o,s,a=e.constants?.SITE_ID;if(!a)throw new Error("No site id");let l=async()=>{clearTimeout(o),Be.log("Requesting AI gateway information");let i=await je(a,t.id,t.sessionId);if({token:r,url:s}=i,n=i.expires_at?i.expires_at*1e3:void 0,Be.log("Got AI gateway information",{token:!!r,expiresAt:n,url:s}),n){let f=n-Date.now()-6e4;f>0&&(o=setTimeout(()=>{l()},f))}};return await l(),{get url(){return s},get token(){return r}}};import z from"process";import{execa as Ft,execaCommand as Jr}from"execa";import{Transform as Pt}from"stream";var Ot=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"]),vt=new Set(["true","false","undefined","null","deploy","project","claude","gemini","codex",""]);function Lt(){return Object.entries(process.env).filter(([e,t])=>!(!t||Ot.has(e)||vt.has(t)||!isNaN(Number(t))||t.length<5)).map(([,e])=>e).filter(Boolean)}function we(e){if(typeof e!="string")return e;let t=Lt();if(t.length===0)return e;let r=e;return t.forEach(n=>{let o=new RegExp(kt(n),"g");r=r.replace(o,"******")}),r}function kt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var J=class extends Pt{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 Qr=_("shell"),bt={preferLocal:!0},Ve=(e,t,r)=>{let[n,o]=Dt(t,r),s={...bt,...o},a=Ft(e,n,s);return $t(a,s),a};var Dt=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(z.env.NETLIFY_MASK_LOGS!=="false"){e.all?.pipe(new J).pipe(z.stdout),e.stdout?.pipe(new J).pipe(z.stdout),e.stderr?.pipe(new J).pipe(z.stderr);return}e.stdout?.pipe(z.stdout),e.stderr?.pipe(z.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 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,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 Ut(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)})}})(),f};return a.flush=async()=>{if((r||n)&&s)return await s,a.flush()},a},pe=(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},de=(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 f=Math.min(i-s.length,e.length);return`${s}${e.slice(0,f)}`}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 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 Mt(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 g=(await t.utils.run("git",["diff",e.sha,"HEAD","--binary"],a)).stdout;p!==g&&(h=Qe.from(g).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/],Mt=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 Ht from"fs/promises";import qt from"os";import fe from"path";import B from"process";import Vt from"readline";import Pe from"path";import Bt from"fs/promises";var Oe=_("agent-output-utils");async function Z({initialResult:e,agentName:t,hasError:r}){let n="",o=Pe.join(process.cwd(),F,se);try{let s=await Bt.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 Q({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 ee(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("499")||r?.includes("connection closed prematurely while waiting for the model"))}var D=_("runner_claude"),nt="Claude Code",Kt=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(D.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?(D.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}):(D.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:x,url:d}=n;if(!x||!d)throw new Error("No token or url provided from AI Gateway");let u=Wt[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(l?.claude){let m=l?.claude?.[s];m&&(i=m)}B.env.ANTHROPIC_API_KEY=x,B.env.ANTHROPIC_BASE_URL=d}else if(!B.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let f=[],c=[],p={},h=0,E=0,R,y,g=fe.join(B.cwd(),"node_modules"),w=[fe.join(B.env.NODE_PATH||g,".bin/claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...i?["--model",i]:[],"-p",a],A=`${B.env.NVM_BIN}/node`;D.log(`Running ${A} ${w.join(" ")}`);let S=t.utils.run(A,w,{all:!0,env:B.env});S.stdin?.end();let I=pe(()=>{r?.({steps:f,duration:E})},250),N=(x,d)=>{let u={...x,id:h};h+=1,c.push(u),f.push(u),d||I.flush(),I(),d&&I.flush()},T=Vt.createInterface({input:S.all});return T.on("error",x=>{D.error("Readline interface error",{error:x.message,stack:x.stack})}),T.on("line",x=>{let d=null;try{d=JSON.parse(x)}catch{D.log("Could not parse line",x)}Array.isArray(d?.message?.content)?d.message.content.forEach(u=>{switch(u.type){case"text":{u.text&&N({message:u.text});break}case"image":{typeof u.source=="object"&&u.source&&u.source.type==="base64"&&u.source.media_type?N({message:``}):D.log(`Unsupported image type ${u.source?.type}`,u.source);break}case"tool_use":{if(u.name==="Task"){let m=u.input?.description&&`\`${u.input.description}\``;N({title:[u.name,m].filter(Boolean).join(" ")})}else u.id&&(p[u.id]=u);I.flush();break}case"tool_result":{let m=u.tool_use_id?p[u.tool_use_id]:void 0,P;if(m){let $=m.input?.file_path&&fe.relative(B.cwd(),m.input.file_path),C=$&&`\`${$}\``;P=[m.name,C].filter(Boolean).join(" ")}let j=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(m?.name||""),k;if(typeof u.content=="string")k=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(``):D.log(`Unsupported image type ${C.source.type}`,C.source):D.log(`Unsupported block type ${C?.type}`)}),k=$.join(`
|
|
13
11
|
|
|
14
12
|
`)}j&&k&&(k=`\`\`\`
|
|
15
13
|
${k.trim()}
|
|
16
|
-
\`\`\``),
|
|
17
|
-
`)
|
|
18
|
-
`)
|
|
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=>{let w=zt({catchError:x,runCmd:P,error:y,result:N,runnerName:"Codex"});y=w.error,N=w.result}),{steps:c,duration:E,result:await J({initialResult:N,agentName:it,hasError:!!y}),error:z({error:y,agentName:it}),isRetryableError:Z(y)}}var at=async()=>{let e=ke.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=`\`\`\`
|
|
14
|
+
\`\`\``),N({title:P,message:k},!0);break}case"thinking":{u.thinking&&N({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?y=d.result:R=d.result,[c,f].forEach(u=>{u[u.length-1]?.message===R&&u.pop()}))}),await S.catch(x=>{({error:y,result:R}=Kt({catchError:x,runCmd:S,error:y,result:R,runnerName:"Claude"}))}),T.close(),I.flush(),{steps:c,duration:E,result:await Z({initialResult:R,agentName:nt,hasError:!!y}),error:Q({error:y,agentName:nt}),isRetryableError:ee(y)}}var ot=async()=>{let e=fe.join(qt.homedir(),".claude");await Ht.rm(e,{recursive:!0,force:!0})},Wt={[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 Xt from"fs/promises";import Jt from"os";import Le from"path";import K from"process";import zt from"readline";var W=_("runner_codex"),st="Codex CLI",Zt=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(W.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?(W.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}):(W.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:N,url:T}=o;if(!N||!T)throw new Error("No token or url provided from AI Gateway");let x=Qt[s];if(!x)throw new Error(`Codex is not supported for the account type ${s}`);if(i&&!x?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(l?.codex){let d=l?.codex?.[s];d&&(i=d)}K.env.OPENAI_API_KEY=N,K.env.OPENAI_BASE_URL=T}else if(!K.env.OPENAI_API_KEY)throw new Error("OPENAI_API_KEY is not provided");let f=[],c=[],p={},h=0,E=0,R,y,g=Le.join(K.cwd(),"node_modules"),w=[Le.join(K.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),A=`${K.env.NVM_BIN}/node`;W.log(`Running ${A} ${w.join(" ")}`);let S=t.utils.run(A,w,{all:!0,env:{...K.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),I=zt.createInterface({input:S.all});return I.on("error",N=>{W.error("Readline interface error",{error:N.message,stack:N.stack})}),I.on("line",N=>{let T=null;try{T=JSON.parse(N)}catch{W.log("Could not parse line",N);return}let x=[],d=!1;if(T?.duration_ms&&(E=T.duration_ms,d=!0),T?.type==="local_shell_call")p[T.call_id]=T;else if(T?.type==="local_shell_call_output"){let u=tr(p[T.call_id],T);u&&(u.id=h,h+=1,c.push(u),f.push(u),x.push(u),d=!0)}else T?.type==="message"&&T.role==="assistant"?R=T.content.map(u=>u.text).join(`
|
|
15
|
+
`):T?.type==="message"&&T.role==="system"&&(y=T.content.map(u=>u.text).join(`
|
|
16
|
+
`));d&&(r?.({steps:f,duration:E}),n?.({steps:x,duration:E}))}),await S.catch(N=>{let T=Zt({catchError:N,runCmd:S,error:y,result:R,runnerName:"Codex"});y=T.error,R=T.result}),I.close(),{steps:c,duration:E,result:await Z({initialResult:R,agentName:st,hasError:!!y}),error:Q({error:y,agentName:st}),isRetryableError:ee(y)}}var it=async()=>{let e=Le.join(Jt.homedir(),".codex");await Xt.rm(e,{recursive:!0,force:!0})},Qt={[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}}}},er=new Set(["bash","-lc"]),tr=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!er.has(s)),n=r?`Running \`${r.join(" ")}\``:void 0,o;try{o=JSON.parse(t.output).output?.trim(),o&&(o=`\`\`\`
|
|
21
17
|
${o.trim()}
|
|
22
|
-
\`\`\``)}catch(s){
|
|
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;w({title:T?.subject??"Thinking...",message:T?.description},!0);break}case"content":{u.value&&w({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=`\`\`\`
|
|
18
|
+
\`\`\``)}catch(s){W.error("Could not decode outputMsg",s,t.output)}return{title:n,message:o}};import rr from"fs/promises";import nr from"os";import me from"path";import H from"process";import or from"readline";var te=_("runner_gemini"),at="Gemini CLI",sr=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(te.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(te.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(te.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0})),ir={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:d,url:u}=o;if(!d||!u)throw new Error("No token or url provided from AI Gateway");let m=ar[s];if(!m)throw new Error(`Gemini is not supported for the account type ${s}`);if(i&&!m?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(l?.gemini){let P=l?.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 f=[],c=[],p=[],h={},E=0,R=0,y,g,w=me.join(H.cwd(),"node_modules"),A=[me.join(H.env.NODE_PATH||w,".bin/gemini"),...i?["--model",i]:[],"--yolo","-p",a],S=`${H.env.NVM_BIN}/node`;te.log(`Running ${S} ${A.join(" ")}`);let I=t.utils.run(S,A,{all:!0,env:H.env});I.stdin?.end();let N=pe(()=>{r?.({steps:f,duration:R}),n?.({steps:c,duration:R}),c=[]},250),T=(d,u)=>{d.id=E,E+=1,p.push(d),f.push(d),c.push(d),u||N.flush(),N(),u&&N.flush()},x=or.createInterface({input:I.all});return x.on("error",d=>{te.error("Readline interface error",{error:d.message,stack:d.stack})}),x.on("line",d=>{let u=null;try{if(d.startsWith("[API Error")){let m=d.match(/\[api error: (.+?)]$/i)?.[1];u={type:"error",value:de(m,!1)?.error?.message||m||"Gemini encountered error"}}else u=JSON.parse(d)}catch{return}if(u)switch(u.type){case"thought":{let m=u.value;T({title:m?.subject??"Thinking...",message:m?.description},!0);break}case"content":{u.value&&T({message:u.value});break}case"tool_call_request":{let m=u.value,P=ir[m.name]??m.name,j=m.args?.path||m.args?.absolute_path,k=j&&me.relative(H.cwd(),j),$=m.args?.command,Rt={title:[P,k&&`\`${k}\``,$&&`\`${$}\``].filter(Boolean).join(" ")};h[m.callId]=Rt,N.flush();break}case"tool_result":{let m=u.value,P=h[m.callId];if(P){let j=[m.resultDisplay,m.responseParts?.functionResponse?.response?.output].find(k=>typeof k=="string"&&k);j&&(P.message=`\`\`\`
|
|
25
19
|
${j.trim()}
|
|
26
|
-
\`\`\``),
|
|
20
|
+
\`\`\``),T(P,!0)}break}case"result":{R=u.duration_ms,y=u.value,[p,f,c].forEach(m=>{m[m.length-1]?.message===y&&m.pop()});break}case"error":{g=u.value;break}case"finished":break;default:{te.warn("Unhandled message type:",u.type);break}}}),await I.catch(d=>{({error:g,result:y}=sr({catchError:d,runCmd:I,error:g,result:y,runnerName:"Gemini"}))}),x.close(),N.flush(),{steps:p,duration:R,result:await Z({initialResult:y,agentName:at,hasError:!!g}),error:Q({error:g,agentName:at}),isRetryableError:ee(g)}}var lt=async()=>{let e=me.join(nr.homedir(),".gemini");await rr.rm(e,{recursive:!0,force:!0})},ar={[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 lr={codex:{runner:ke,clean:it},claude:{runner:ve,clean:ot},gemini:{runner:Fe,clean:lt}},ut=lr;var ct=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:n})=>{let o=ur();return ae(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=cr({apiToken:r});Ye(i);let f=e.useGateway?await He({netlify:i,config:e}):void 0;s?.setAttributes({"init.aiGateway.created":!!f}),e.validateAgent&&e.errorLogsPath&&s?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let c=Je(({steps:E=[],duration:R})=>{let y=[...E];return E.length=0,X(e.id,e.sessionId,{steps:y,duration:R})},t),p;e.hasRepo?e.sha?(p=e.sha,s?.setAttributes({"init.sha.source":"provided"})):(p=await tt(i),await ce(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:f,context:i,persistSteps:c,runner:l,sha:p}})},cr=({apiToken:e})=>({constants:{NETLIFY_API_HOST:ge.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||ge.env.NETLIFY_API_TOKEN,SITE_ID:ge.env.SITE_ID,FUNCTIONS_DIST:ge.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:Ve}});import pr from"crypto";import q from"fs/promises";import L from"path";import b from"process";var O=_("context"),dr=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}},fr=10,mr=async e=>{let{name:t,ext:r}=L.parse(e),n=e,o=L.join(b.cwd(),F,n),s=0;for(;await gr(o);){if(s>=fr)throw new Error("Failed to generate context file");n=`${t}-${pr.randomUUID().slice(0,5)}${r}`,o=L.join(b.cwd(),F,n),s+=1}return n},gr=async e=>{try{return await q.access(e),!0}catch{return!1}},hr=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}},Er=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"?O.warn(`Download timeout for ${e}`):O.warn(`Failed to download context file ${e}:`,r.message),!1}},he=null,_r=async()=>{if(he)return he;let e=await hr();if(!e)return[];let t=L.join(b.cwd(),F,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 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 Er(s.endpoint,l)?(O.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:o}):null});return he=(await Promise.all(r)).filter(o=>o!==null),he},pt=async({cliPath:e,netlify:t,config:r,buildErrorContext:n})=>{let o=dr(t),s=await mr(Ke),a=L.join(b.cwd(),F);await q.mkdir(a,{recursive:!0});let l=L.join(F,s),i=L.join(b.cwd(),l),f=L.join(b.cwd(),F,se);try{await q.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.
|
|
27
21
|
Your task is to analyze and fix the build errors.
|
|
28
22
|
Don't apply techniques of reverting changes. Apply fixes related to errors.
|
|
29
23
|
Don't try to run build by yourself. Just fix the errors.
|
|
@@ -32,35 +26,35 @@ Don't try to run build by yourself. Just fix the errors.
|
|
|
32
26
|
${n}
|
|
33
27
|
</build_error_context>`:"",p="";r.siteContext&&r.siteContext.length!==0&&(p=`
|
|
34
28
|
<project_rules>
|
|
35
|
-
${r.siteContext.filter(
|
|
29
|
+
${r.siteContext.filter(g=>g.site_context).map(g=>typeof g.site_context=="string"?g.site_context:typeof g.site_context=="object"?JSON.stringify(g.site_context):"").join(`
|
|
36
30
|
|
|
37
31
|
`)}
|
|
38
32
|
</project_rules>
|
|
39
|
-
`);let h="";if(r.sessionHistoryContext?.length){let
|
|
33
|
+
`);let h="";if(r.sessionHistoryContext?.length){let g=L.join(b.cwd(),F,Ae);await q.mkdir(g,{recursive:!0});let w=await Promise.all(r.sessionHistoryContext.map(async(A,S)=>{let I=S+1,N=`attempt-${I}.md`,T=L.join(g,N),x=L.join(F,Ae,N),d=`# Task History - Attempt ${I}
|
|
40
34
|
|
|
41
35
|
## Request - what the user asked for
|
|
42
|
-
${
|
|
36
|
+
${A.request}
|
|
43
37
|
|
|
44
38
|
---
|
|
45
39
|
|
|
46
40
|
## Response - what the agent replied with after its work
|
|
47
41
|
|
|
48
|
-
${
|
|
49
|
-
`;return await
|
|
42
|
+
${A.response}
|
|
43
|
+
`;return await q.writeFile(T,d,"utf-8"),O.log(`Created history file: ${x}`),x}));h+=`
|
|
50
44
|
<session_history_context>
|
|
51
45
|
History of prior work on this task.
|
|
52
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.
|
|
53
47
|
|
|
54
|
-
${
|
|
48
|
+
${w.slice(-5).map(A=>`- ${A}`).join(`
|
|
55
49
|
`)}
|
|
56
50
|
|
|
57
51
|
</session_history_context>
|
|
58
|
-
`}let E=await
|
|
52
|
+
`}let E=await _r(),R="";E.length>0&&(R=`
|
|
59
53
|
<netlify_features_context>
|
|
60
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.
|
|
61
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.
|
|
62
56
|
|
|
63
|
-
${E.map(
|
|
57
|
+
${E.map(g=>`- **${g.scope}**: ${g.path}`).join(`
|
|
64
58
|
`)}
|
|
65
59
|
|
|
66
60
|
Refer to these files when working with specific Netlify features.
|
|
@@ -82,8 +76,8 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
82
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.
|
|
83
77
|
</responses>
|
|
84
78
|
<attachements>
|
|
85
|
-
- for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${a}/${
|
|
86
|
-
- move assets from ${a}/${
|
|
79
|
+
- for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${a}/${Se} folder
|
|
80
|
+
- move assets from ${a}/${Se} folder to the project assets folder if they are referenced in a code or applied changes
|
|
87
81
|
</attachements>
|
|
88
82
|
${p}
|
|
89
83
|
</requirements>
|
|
@@ -102,7 +96,7 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
102
96
|
- 'netlify-cli' npm package is already available as a global package. Don't try to install it again
|
|
103
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.
|
|
104
98
|
</environment>
|
|
105
|
-
${
|
|
99
|
+
${R}
|
|
106
100
|
<docs>
|
|
107
101
|
- Netlify Docs: https://docs.netlify.com
|
|
108
102
|
- LLM Resources Index: https://docs.netlify.com/llms.txt
|
|
@@ -110,7 +104,7 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
110
104
|
</extra_context>
|
|
111
105
|
|
|
112
106
|
${h}
|
|
113
|
-
`;return await
|
|
107
|
+
`;return await q.writeFile(i,y,"utf-8"),O.log(`Generated agent context document at: ${i}`),y.length>5e5&&(y=`
|
|
114
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.
|
|
115
109
|
|
|
116
110
|
<request>
|
|
@@ -121,12 +115,12 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
121
115
|
</request>
|
|
122
116
|
|
|
123
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.
|
|
124
|
-
`),y};var
|
|
118
|
+
`),y};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 Ee=_("inference_stage"),ft=2,_e=async e=>{let{cliPath:t,config:r,context:n,buildErrors:o,runner:s,persistSteps:a,aiGateway:l,attempt:i}=e;Ee.log(`Retrying inference stage, attempt ${i} of ${ft}`),qe();let{prompt:f}=await dt({cliPath:t,config:r,buildErrorContext:yr(o),netlify:n}),c={...r,prompt:f},p=await s({aiGateway:l,config:c,netlify:n,persistSteps:a});if(await a.flush(),p.error){if(Ee.error("Runner failed",{stepsCount:p.steps.length,duration:p.duration,error:p.error,isRetryableError:p.isRetryableError,attempt:i||1}),p.error&&p.isRetryableError&&(!i||i<ft))return Ee.log("Retrying inference stage"),await new Promise(E=>setTimeout(E,5e3)),{runnerResult:(await _e({...e,attempt:(i||1)+1})).runnerResult};throw Ee.log("Do not retry inference stage"),new Error(p.error)}return{runnerResult:p}},yr=e=>!e||e.length===0?"":`
|
|
125
119
|
Deploy failed failed. Here are the errors to review on the latest build:
|
|
126
120
|
|
|
127
121
|
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
122
|
|
|
129
123
|
${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
|
|
124
|
+
`;import Nr from"process";var ie=_("deploy"),mt=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||(ie.log("Deploy: Uploading source zip"),l.push("--upload-source-zip")),o&&l.push("--alias",o),a&&l.push("--filter",a),r?(ie.log("Deploy: Skipping build"),l.push("--no-build")):l.push("--context","deploy-preview");let i=s||"netlify";ie.log(`Running: ${i} ${l.join(" ")}`);let f=await e.utils.run(i,l,{stdio:["ignore","pipe","pipe"]}),c=JSON.parse(f.stdout.trim());ie.log(`
|
|
125
|
+
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 ie.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:f}=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 Me(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 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:a,resultDiff:l,hasChanges:c,previewInfo:null,diffBinary:i,resultDiffBinary:f,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:f}};async function gt(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 re=_("cleanup_stage"),ht=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?(re.log("Updating total agent result diff"),await ce(e.id,{result_diff:o,result_diff_binary:a})):re.log("No total result diff, not updating"),re.log("Updated agent runner with result"),await gt(()=>X(e.id,e.sessionId,i),{maxRetries:3,baseDelay:1e3,onRetry:(f,c)=>{re.error(`Error updating agent runner session (attempt ${f}):`,c),re.log("Retrying...")}}),re.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as Rr}from"@netlify/otel";var Ir=xr(import.meta.url),Et=Ir("../package.json"),_t=_("pipeline_index"),ye=3,Tt=async({config:e,apiToken:t,cliPath:r="netlify",cwd:n,errorLogsPath:o,filter:s,traceExporterUrl:a})=>{let l;try{await Ue(Et.version,e.id,a);let i=Rr(),f,{aiGateway:c,context:p,persistSteps:h,runner:E,sha:R}=await ct({config:e,apiToken:t,cliPath:r,cwd:n,errorLogsPath:o,filter:s,runnerVersion:Et.version});l=E.clean,e.sha=R;let{runnerResult:y}=await _e({cliPath:r,config:e,context:p,runner:E.runner,persistSteps:h,aiGateway:c}),g=await be({cliPath:r,config:e,context:p,result:y.result,filter:s}),w=y,A=[];if(g.hasChanges&&g.deployError){A.push(Ge(g.deployError));let d=1;for(;d<=ye&&!g.previewInfo;)_t.log(`Deploy attempt had errors. Retrying. ${d}/${ye}`),await ae(i,"stage-deploy",async u=>{u?.setAttributes({"stage.attempt":d});let{runnerResult:m}=await _e({cliPath:r,config:e,context:p,runner:E.runner,persistSteps:h,aiGateway:c,buildErrors:A});w={...m,steps:[...w.steps||[],...m.steps||[]],duration:(w.duration||0)+(m.duration||0)},g=await be({cliPath:r,config:e,context:p,result:m.result,filter:s}),g.deployError&&A.push(g.deployError),d++});d>ye&&!g.previewInfo&&(f=new Error(`Deploy validation failed after ${ye} attempts`))}let{diff:S,resultDiff:I,previewInfo:N,diffBinary:T,resultDiffBinary:x}=g;if(await ht({config:e,diff:S,result:w.result,duration:w.duration,resultDiff:I,diffBinary:T,resultDiffBinary:x,previewInfo:N}),f)throw f;await E.clean?.()}catch(i){_t.error("Got error while running pipeline",i),await l?.();let f=i instanceof Error&&i.message;throw await X(e.id,e.sessionId,{result:f||"Encountered error when running agent",state:"error"}),i}};import v from"process";var wr="codex",Ar=e=>(e??[]).filter(t=>t.request&&t.response),Cr=e=>(e??[]).filter(t=>t.site_context),yt=_("config"),Nt=()=>{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||wr,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,f=de(v.env.NETLIFY_AGENT_RUNNER_CONTEXT,!0,yt),c=Ar(f),p=Cr(f),h=v.env.NETLIFY_AGENT_RUNNER_HAS_REPO!=="0",E=!v.env.NETLIFY_FF_AGENT_RUNNER_BYOK_ENABLED,R=v.env.NETLIFY_AGENT_RUNNER_SHA,y=Sr(),g=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:R,accountType:y,validateAgentWithBuild:l,modelVersionOverrides:g};return yt.log({fullConfig:w}),w},Sr=()=>{let e=v.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 xt=_("bin_cmd"),ne=Pr(De.argv.slice(2),{string:["auth","cwd","cli-path","error-logs-path","filter","trace-exporter-url"]});try{let e=Nt();await Tt({config:e,apiToken:ne.auth,cwd:ne.cwd,cliPath:ne["cli-path"],errorLogsPath:ne["error-logs-path"],filter:ne.filter,traceExporterUrl:ne["trace-exporter-url"]}),xt.info("Finished agent"),De.exit(0)}catch(e){xt.error("Error running agent pipeline:",e),De.exit(1)}
|
|
132
126
|
//# sourceMappingURL=bin.js.map
|
package/dist/index.js
CHANGED
|
@@ -1,28 +1,22 @@
|
|
|
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 pr}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 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)=>mt({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 Et({url:r}))],instrumentations:[new gt({skipHeaders:!0})]});function se(e,t,r){return _e.log(`\u23F3 TRACE: ${t} starting...`),ht(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 _t=["error","failed","exception","fatal","panic","abort","crash"];function De(e){let t=e.split(`
|
|
2
|
+
`),r=[],n=-1,o=0;for(;o<t.length;){let l=t[o].slice(0,500).toLowerCase();if(_t.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
|
|
8
|
-
`).filter(o=>!
|
|
9
|
-
`).forEach(a=>{let l=a.match(/\?\? (.+?)\.log$/)?.[1];l&&n.push(`:!${l}.log`)}),n};import
|
|
10
|
-
`))return;let m=N.split(`
|
|
11
|
-
`).filter(Boolean).map(p=>{try{return JSON.parse(p)}catch{F.log("Could not parse line",p)}return null}).filter(Boolean);N="",m.forEach(p=>{Array.isArray(p?.message?.content)?p.message.content.forEach(u=>{switch(u.type){case"text":{u.text&&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,D;if(_){let $=_.input?.file_path&&de.relative(M.cwd(),_.input.file_path),C=$&&`\`${$}\``;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 $=[];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}`)}),k=$.join(`
|
|
7
|
+
`);return s.length>e.length*.8?e:s}import pe from"process";import{getTracer as Qt}from"@netlify/otel";import ie from"process";var Te=ie.env.NETLIFY_API_URL,xe=ie.env.NETLIFY_API_TOKEN,te=y("api"),ae=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}`}};ie.env.AGENT_RUNNERS_DEBUG==="true"&&(n.headers["x-nf-debug-logging"]="true"),t.json&&(n.headers||={},n.headers["Content-Type"]="application/json",n.body=JSON.stringify(t.json));let o=await fetch(r,n),s=o.ok&&o.status<=299;if(ie.env.AGENT_RUNNERS_DEBUG==="true")te.log(`Response headers for ${r}:`),o.headers.forEach((l,i)=>{te.log(` ${i}: ${l}`)});else{let l=o.headers.get("x-request-id")||o.headers.get("x-nf-request-id");te.log(`Request ID for ${r}: ${l||"N/A"}`)}if(s||te.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},$e=e=>{te.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)},le=(e,t)=>ae(`/api/v1/agent_runners/${e}`,{method:"PUT",json:t}),B=(e,t,r)=>ae(`/api/v1/agent_runners/${e}/sessions/${t}`,{method:"PUT",json:r});var Fe=(e,t)=>ae(`/api/v1/agent_runners/${e}/sessions/${t}`),Ue=(e,t,r)=>ae(`/api/v1/sites/${e}/ai-gateway/token`,{headers:{"X-Nf-Agent-Runner-Id":t,"X-Nf-Agent-Runner-Session-Id":r}});var 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 q from"process";import{execa as wt,execaCommand as Dr}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 Re(e){if(typeof e!="string")return e;let t=Rt();if(t.length===0)return e;let r=e;return t.forEach(n=>{let o=new RegExp(It(n),"g");r=r.replace(o,"******")}),r}function It(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var H=class extends yt{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 Ur=y("shell"),Nt={preferLocal:!0},Ye=(e,t,r)=>{let[n,o]=At(t,r),s={...Nt,...o},a=wt(e,n,s);return Ct(a,s),a};var At=function(e,t){return Array.isArray(e)?[e,t]:typeof e=="object"&&e!==null?[[],e]:[[],void 0]},Ct=(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 H).pipe(q.stdout),e.stdout?.pipe(new H).pipe(q.stdout),e.stderr?.pipe(new H).pipe(q.stderr);return}e.stdout?.pipe(q.stdout),e.stderr?.pipe(q.stderr)};var Be="netlify-agent-runner-context.md",Ie="task-history",we="netlify-context",b=".netlify",re="results.md",Ne="assets",K="other",V="personal";var W="enterprise",X="free";var St=y("utils"),Pt=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 Pt(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},ue=(e,t,r=!1)=>{let n=null,o=null,s=null,a=function(...l){o=l,s=this;let i=r&&!n;clearTimeout(n),n=setTimeout(()=>{n=null,r||(e.apply(s,o),o=null,s=null)},t),i&&(e.apply(s,o),o=null,s=null)};return a.cancel=()=>{clearTimeout(n),n=null,o=null,s=null},a.flush=()=>{if(n){clearTimeout(n);let l=o,i=s;n=null,o=null,s=null,e.apply(i,l)}},a},qe=(e,t=!0,r)=>{if(e)try{return JSON.parse(e)}catch(n){t&&(r?.error?r.error("Could not parse JSON",n):St.error("Could not parse JSON",n))}},Ke=(e,t)=>{let o=".netlify.app",s="agent-";if(!t)return`${s}${e.slice(0,6)}`;let l=`--${t}${o}`;if(l.length>55)return"";let i=60-l.length;if(i<=0)return"";if(i>=s.length+6){let f=Math.min(i-s.length,e.length);return`${s}${e.slice(0,f)}`}return e.slice(0,i)};import{Buffer as Ve}from"buffer";var We=async({config:e,netlify:t})=>{let r=await vt(t),{hasChanges:n}=r,{status:o}=r;if(!n)return{hasChanges:!1};let s=await kt(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},Ot=["?? mise.toml","?? deno.lock",/\?\? .+?\.log/],vt=async e=>{let t=await e.utils.run("git",["status","-s"]);return{hasChanges:(t.stdout.trim().length===0?[]:t.stdout.split(`
|
|
8
|
+
`).filter(o=>!Ot.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()},kt=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 Lt from"fs/promises";import Dt from"os";import ce from"path";import U from"process";import $t from"readline";import Ae from"path";import bt from"fs/promises";var Ce=y("agent-output-utils");async function J({initialResult:e,agentName:t,hasError:r}){let n="",o=Ae.join(process.cwd(),b,re);try{let s=await bt.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 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&&Ce.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("499")||r?.includes("connection closed prematurely while waiting for the model"))}var D=y("runner_claude"),ze="Claude Code",Ft=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(D.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?(D.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}):(D.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:p}=n;if(!R||!p)throw new Error("No token or url provided from AI Gateway");let u=Ut[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(l?.claude){let m=l?.claude?.[s];m&&(i=m)}U.env.ANTHROPIC_API_KEY=R,U.env.ANTHROPIC_BASE_URL=p}else if(!U.env.ANTHROPIC_API_KEY)throw new Error("ANTHROPIC_API_KEY is not provided");let f=[],c=[],d={},h=0,E=0,I,T,g=ce.join(U.cwd(),"node_modules"),C=[ce.join(U.env.NODE_PATH||g,".bin/claude"),"--permission-mode","bypassPermissions","--dangerously-skip-permissions","--output-format","stream-json","--verbose",...i?["--model",i]:[],"-p",a],N=`${U.env.NVM_BIN}/node`;D.log(`Running ${N} ${C.join(" ")}`);let S=t.utils.run(N,C,{all:!0,env:U.env});S.stdin?.end();let w=ue(()=>{r?.({steps:f,duration:E})},250),x=(R,p)=>{let u={...R,id:h};h+=1,c.push(u),f.push(u),p||w.flush(),w(),p&&w.flush()},_=$t.createInterface({input:S.all});return _.on("error",R=>{D.error("Readline interface error",{error:R.message,stack:R.stack})}),_.on("line",R=>{let p=null;try{p=JSON.parse(R)}catch{D.log("Could not parse line",R)}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:``}):D.log(`Unsupported image type ${u.source?.type}`,u.source);break}case"tool_use":{if(u.name==="Task"){let m=u.input?.description&&`\`${u.input.description}\``;x({title:[u.name,m].filter(Boolean).join(" ")})}else u.id&&(d[u.id]=u);w.flush();break}case"tool_result":{let m=u.tool_use_id?d[u.tool_use_id]:void 0,P;if(m){let $=m.input?.file_path&&ce.relative(U.cwd(),m.input.file_path),A=$&&`\`${$}\``;P=[m.name,A].filter(Boolean).join(" ")}let F=["Bash","Glob","Grep","LS","Read","Edit","Write"].includes(m?.name||""),k;if(typeof u.content=="string")k=u.content;else if(Array.isArray(u.content)){let $=[];u.content.forEach(A=>{A?.type==="text"&&typeof A.text=="string"?$.push(A.text):A?.type==="image"&&typeof A.source=="object"&&A.source?A.source.type==="base64"&&A.source.media_type?$.push(``):D.log(`Unsupported image type ${A.source.type}`,A.source):D.log(`Unsupported block type ${A?.type}`)}),k=$.join(`
|
|
12
10
|
|
|
13
|
-
`)}
|
|
11
|
+
`)}F&&k&&(k=`\`\`\`
|
|
14
12
|
${k.trim()}
|
|
15
|
-
\`\`\``),x({title:
|
|
16
|
-
`)
|
|
17
|
-
`)
|
|
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=>{let N=jt({catchError:x,runCmd:P,error:T,result:I,runnerName:"Codex"});T=N.error,I=N.result}),{steps:c,duration:E,result:await W({initialResult:I,agentName:et,hasError:!!T}),error:X({error:T,agentName:et}),isRetryableError:J(T)}}var tt=async()=>{let e=Oe.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=`\`\`\`
|
|
13
|
+
\`\`\``),x({title:P,message:k},!0);break}case"thinking":{u.thinking&&x({title:"Thinking",message:u.thinking},!0);break}default:D.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 S.catch(R=>{({error:T,result:I}=Ft({catchError:R,runCmd:S,error:T,result:I,runnerName:"Claude"}))}),_.close(),w.flush(),{steps:c,duration:E,result:await J({initialResult:I,agentName:ze,hasError:!!T}),error:z({error:T,agentName:ze}),isRetryableError:Z(T)}}var Ze=async()=>{let e=ce.join(Dt.homedir(),".claude");await Lt.rm(e,{recursive:!0,force:!0})},Ut={[W]:{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}}},[V]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-haiku-20240307":{maxTokens:4096}}},[X]:{models:{"claude-3-5-haiku-20241022":{maxTokens:8192},"claude-3-7-sonnet-20250219":{maxTokens:16e3}}},[K]:{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 j from"process";import jt from"readline";var Y=y("runner_codex"),Qe="Codex CLI",Yt=({catchError:e,runCmd:t,error:r,result:n,runnerName:o})=>(Y.log(`${o} command completed with catch handler triggered`,{hadExistingError:!!r,hadExistingResult:!!n,resultLength:n?n.length:0,catchError:e?.message||"No error object",processExitCode:t.exitCode,processKilled:t.killed}),n?(Y.log("Preserving existing result despite catch handler being triggered"),r?{error:r,result:n}:{error:"Process completed with errors but result was captured",result:n}):(Y.log("Setting result to undefined because no valid result was captured"),{error:r||`${o} failed`,result:void 0}));async function Oe({config:e,netlify:t,persistSteps:r,sendSteps:n,aiGateway:o}){let{accountType:s,prompt:a,modelVersionOverrides:l}=e,{model:i}=e;if(o){let{token:x,url:_}=o;if(!x||!_)throw new Error("No token or url provided from AI Gateway");let R=Bt[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 p=l?.codex?.[s];p&&(i=p)}j.env.OPENAI_API_KEY=x,j.env.OPENAI_BASE_URL=_}else if(!j.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(j.cwd(),"node_modules"),C=[Pe.join(j.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=`${j.env.NVM_BIN}/node`;Y.log(`Running ${N} ${C.join(" ")}`);let S=t.utils.run(N,C,{all:!0,env:{...j.env,CODEX_UNSAFE_ALLOW_NO_SANDBOX:"1"}}),w=jt.createInterface({input:S.all});return w.on("error",x=>{Y.error("Readline interface error",{error:x.message,stack:x.stack})}),w.on("line",x=>{let _=null;try{_=JSON.parse(x)}catch{Y.log("Could not parse line",x);return}let R=[],p=!1;if(_?.duration_ms&&(E=_.duration_ms,p=!0),_?.type==="local_shell_call")d[_.call_id]=_;else if(_?.type==="local_shell_call_output"){let u=qt(d[_.call_id],_);u&&(u.id=h,h+=1,c.push(u),f.push(u),R.push(u),p=!0)}else _?.type==="message"&&_.role==="assistant"?I=_.content.map(u=>u.text).join(`
|
|
14
|
+
`):_?.type==="message"&&_.role==="system"&&(T=_.content.map(u=>u.text).join(`
|
|
15
|
+
`));p&&(r?.({steps:f,duration:E}),n?.({steps:R,duration:E}))}),await S.catch(x=>{let _=Yt({catchError:x,runCmd:S,error:T,result:I,runnerName:"Codex"});T=_.error,I=_.result}),w.close(),{steps:c,duration:E,result:await J({initialResult:I,agentName:Qe,hasError:!!T}),error:z({error:T,agentName:Qe}),isRetryableError:Z(T)}}var et=async()=>{let e=Pe.join(Gt.homedir(),".codex");await Mt.rm(e,{recursive:!0,force:!0})},Bt={[W]:{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":{}}},[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}}},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}}},[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}}},[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},"o3-mini":{maxTokens:16e3}}}},Ht=new Set(["bash","-lc"]),qt=(e,t)=>{if(!e||!t||e.call_id!==t.call_id)return null;let r=e.action?.command?.filter(s=>!Ht.has(s)),n=r?`Running \`${r.join(" ")}\``:void 0,o;try{o=JSON.parse(t.output).output?.trim(),o&&(o=`\`\`\`
|
|
20
16
|
${o.trim()}
|
|
21
|
-
\`\`\``)}catch(s){
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
${U.trim()}
|
|
25
|
-
\`\`\``),N(D,!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:rt,hasError:!!g}),error:X({error:g,agentName:rt}),isRetryableError:J(g)}}var nt=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:ve,clean:tt},claude:{runner:Pe,clean:Qe},gemini:{runner:ke,clean:nt}},ot=Jt;var st=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=ot[e.runner];if(!l)throw s?.setAttributes({"init.error":"unsupported_runner"}),new Error(`${e.runner} is not supported`);let i=Zt({apiToken:r});Fe(i);let f=e.useGateway?await je({netlify:i,config:e}):void 0;s?.setAttributes({"init.aiGateway.created":!!f}),e.validateAgent&&e.errorLogsPath&&s?.setAttributes({"init.errorLogsPath":e.errorLogsPath});let c=qe(({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 Je(i),await ue(e.id,{sha:d}),s?.setAttributes({"init.sha.source":"current_commit"})):(d=await ze(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:Be}});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,Ne);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,Ne,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},it=async({cliPath:e,netlify:t,config:r,buildErrorContext:n})=>{let o=er(t),s=await rr(He),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.
|
|
17
|
+
\`\`\``)}catch(s){Y.error("Could not decode outputMsg",s,t.output)}return{title:n,message:o}};import Kt from"fs/promises";import Vt from"os";import de from"path";import M from"process";import Wt from"readline";var Q=y("runner_gemini"),tt="Gemini CLI",Xt=({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})),Jt={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:p,url:u}=o;if(!p||!u)throw new Error("No token or url provided from AI Gateway");let m=zt[s];if(!m)throw new Error(`Gemini is not supported for the account type ${s}`);if(i&&!m?.models?.[i])throw new Error(`${i} is not supported for account type ${s}`);if(l?.gemini){let P=l?.gemini?.[s];P&&(i=P)}M.env.GEMINI_API_KEY=p,M.env.GOOGLE_GEMINI_BASE_URL=u}else if(!M.env.GEMINI_API_KEY)throw new Error("GEMINI_API_KEY is not provided");let f=[],c=[],d=[],h={},E=0,I=0,T,g,C=de.join(M.cwd(),"node_modules"),N=[de.join(M.env.NODE_PATH||C,".bin/gemini"),...i?["--model",i]:[],"--yolo","-p",a],S=`${M.env.NVM_BIN}/node`;Q.log(`Running ${S} ${N.join(" ")}`);let w=t.utils.run(S,N,{all:!0,env:M.env});w.stdin?.end();let x=ue(()=>{r?.({steps:f,duration:I}),n?.({steps:c,duration:I}),c=[]},250),_=(p,u)=>{p.id=E,E+=1,d.push(p),f.push(p),c.push(p),u||x.flush(),x(),u&&x.flush()},R=Wt.createInterface({input:w.all});return R.on("error",p=>{Q.error("Readline interface error",{error:p.message,stack:p.stack})}),R.on("line",p=>{let u=null;try{if(p.startsWith("[API Error")){let m=p.match(/\[api error: (.+?)]$/i)?.[1];u={type:"error",value:qe(m,!1)?.error?.message||m||"Gemini encountered error"}}else u=JSON.parse(p)}catch{return}if(u)switch(u.type){case"thought":{let m=u.value;_({title:m?.subject??"Thinking...",message:m?.description},!0);break}case"content":{u.value&&_({message:u.value});break}case"tool_call_request":{let m=u.value,P=Jt[m.name]??m.name,F=m.args?.path||m.args?.absolute_path,k=F&&de.relative(M.cwd(),F),$=m.args?.command,ft={title:[P,k&&`\`${k}\``,$&&`\`${$}\``].filter(Boolean).join(" ")};h[m.callId]=ft,x.flush();break}case"tool_result":{let m=u.value,P=h[m.callId];if(P){let F=[m.resultDisplay,m.responseParts?.functionResponse?.response?.output].find(k=>typeof k=="string"&&k);F&&(P.message=`\`\`\`
|
|
18
|
+
${F.trim()}
|
|
19
|
+
\`\`\``),_(P,!0)}break}case"result":{I=u.duration_ms,T=u.value,[d,f,c].forEach(m=>{m[m.length-1]?.message===T&&m.pop()});break}case"error":{g=u.value;break}case"finished":break;default:{Q.warn("Unhandled message type:",u.type);break}}}),await w.catch(p=>{({error:g,result:T}=Xt({catchError:p,runCmd:w,error:g,result:T,runnerName:"Gemini"}))}),R.close(),x.flush(),{steps:d,duration:I,result:await J({initialResult:T,agentName:tt,hasError:!!g}),error:z({error:g,agentName:tt}),isRetryableError:Z(g)}}var rt=async()=>{let e=de.join(Vt.homedir(),".gemini");await Kt.rm(e,{recursive:!0,force:!0})},zt={[W]:{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}}},[V]:{models:{"gemini-1.5-flash-8b":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192}}},[X]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}},[K]:{models:{"gemini-2.0-flash":{maxTokens:8192},"gemini-2.0-flash-lite":{maxTokens:8192},"gemini-2.5-flash":{maxTokens:16e3}}}};var Zt={codex:{runner:Oe,clean:et},claude:{runner:Se,clean:Ze},gemini:{runner:ve,clean:rt}},nt=Zt;var ot=async({config:e,apiThrottle:t,apiToken:r,runnerVersion:n})=>{let o=Qt();return se(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=er({apiToken:r});$e(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 le(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}})},er=({apiToken:e})=>({constants:{NETLIFY_API_HOST:pe.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||pe.env.NETLIFY_API_TOKEN,SITE_ID:pe.env.SITE_ID,FUNCTIONS_DIST:pe.env.FUNCTIONS_DIST||"netlify/functions"},utils:{run:Ye}});import tr from"crypto";import G from"fs/promises";import v from"path";import L from"process";var O=y("context"),rr=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}},nr=10,or=async e=>{let{name:t,ext:r}=v.parse(e),n=e,o=v.join(L.cwd(),b,n),s=0;for(;await sr(o);){if(s>=nr)throw new Error("Failed to generate context file");n=`${t}-${tr.randomUUID().slice(0,5)}${r}`,o=v.join(L.cwd(),b,n),s+=1}return n},sr=async e=>{try{return await G.access(e),!0}catch{return!1}},ir=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}},ar=async(e,t)=>{try{let r=await fetch(e,{signal:AbortSignal.timeout(1e4)});if(!r.ok)throw new Error(`Failed to fetch ${e}: ${r.status} ${r.statusText}`);let n=await r.text();return await G.writeFile(t,n,"utf-8"),!0}catch(r){return r.name==="AbortError"?O.warn(`Download timeout for ${e}`):O.warn(`Failed to download context file ${e}:`,r.message),!1}},fe=null,lr=async()=>{if(fe)return fe;let e=await ir();if(!e)return[];let t=v.join(L.cwd(),b,we);await G.mkdir(t,{recursive:!0});let r=Object.entries(e.contextScopes).map(async([o,s])=>{if(!s||typeof s!="object"||!s.endpoint||!s.scope)return 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 ar(s.endpoint,l)?(O.log(`Downloaded: ${i}`),{scope:s.scope,path:i,key:o}):null});return fe=(await Promise.all(r)).filter(o=>o!==null),fe},st=async({cliPath:e,netlify:t,config:r,buildErrorContext:n})=>{let o=rr(t),s=await or(Be),a=v.join(L.cwd(),b);await G.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 G.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
20
|
Your task is to analyze and fix the build errors.
|
|
27
21
|
Don't apply techniques of reverting changes. Apply fixes related to errors.
|
|
28
22
|
Don't try to run build by yourself. Just fix the errors.
|
|
@@ -35,26 +29,26 @@ ${r.siteContext.filter(g=>g.site_context).map(g=>typeof g.site_context=="string"
|
|
|
35
29
|
|
|
36
30
|
`)}
|
|
37
31
|
</project_rules>
|
|
38
|
-
`);let h="";if(r.sessionHistoryContext?.length){let g=v.join(L.cwd(),b,
|
|
32
|
+
`);let h="";if(r.sessionHistoryContext?.length){let g=v.join(L.cwd(),b,Ie);await G.mkdir(g,{recursive:!0});let C=await Promise.all(r.sessionHistoryContext.map(async(N,S)=>{let w=S+1,x=`attempt-${w}.md`,_=v.join(g,x),R=v.join(b,Ie,x),p=`# Task History - Attempt ${w}
|
|
39
33
|
|
|
40
34
|
## Request - what the user asked for
|
|
41
|
-
${
|
|
35
|
+
${N.request}
|
|
42
36
|
|
|
43
37
|
---
|
|
44
38
|
|
|
45
39
|
## Response - what the agent replied with after its work
|
|
46
40
|
|
|
47
|
-
${
|
|
48
|
-
`;return await
|
|
41
|
+
${N.response}
|
|
42
|
+
`;return await G.writeFile(_,p,"utf-8"),O.log(`Created history file: ${R}`),R}));h+=`
|
|
49
43
|
<session_history_context>
|
|
50
44
|
History of prior work on this task.
|
|
51
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.
|
|
52
46
|
|
|
53
|
-
${
|
|
47
|
+
${C.slice(-5).map(N=>`- ${N}`).join(`
|
|
54
48
|
`)}
|
|
55
49
|
|
|
56
50
|
</session_history_context>
|
|
57
|
-
`}let E=await
|
|
51
|
+
`}let E=await lr(),I="";E.length>0&&(I=`
|
|
58
52
|
<netlify_features_context>
|
|
59
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.
|
|
60
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.
|
|
@@ -81,8 +75,8 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
81
75
|
- 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
76
|
</responses>
|
|
83
77
|
<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}/${
|
|
78
|
+
- for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${a}/${Ne} folder
|
|
79
|
+
- move assets from ${a}/${Ne} folder to the project assets folder if they are referenced in a code or applied changes
|
|
86
80
|
</attachements>
|
|
87
81
|
${d}
|
|
88
82
|
</requirements>
|
|
@@ -109,7 +103,7 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
109
103
|
</extra_context>
|
|
110
104
|
|
|
111
105
|
${h}
|
|
112
|
-
`;return await
|
|
106
|
+
`;return await G.writeFile(i,T,"utf-8"),O.log(`Generated agent context document at: ${i}`),T.length>5e5&&(T=`
|
|
113
107
|
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
108
|
|
|
115
109
|
<request>
|
|
@@ -120,12 +114,12 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
120
114
|
</request>
|
|
121
115
|
|
|
122
116
|
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
|
-
`),T};var
|
|
117
|
+
`),T};var ur=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&&ur.log("Contextful Prompt:",o),{prompt:o}};var me=y("inference_stage"),at=2,ge=async e=>{let{cliPath:t,config:r,context:n,buildErrors:o,runner:s,persistSteps:a,aiGateway:l,attempt:i}=e;me.log(`Retrying inference stage, attempt ${i} of ${at}`),je();let{prompt:f}=await it({cliPath:t,config:r,buildErrorContext:cr(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(me.error("Runner failed",{stepsCount:d.steps.length,duration:d.duration,error:d.error,isRetryableError:d.isRetryableError,attempt:i||1}),d.error&&d.isRetryableError&&(!i||i<at))return me.log("Retrying inference stage"),await new Promise(E=>setTimeout(E,5e3)),{runnerResult:(await ge({...e,attempt:(i||1)+1})).runnerResult};throw me.log("Do not retry inference stage"),new Error(d.error)}return{runnerResult:d}},cr=e=>!e||e.length===0?"":`
|
|
124
118
|
Deploy failed failed. Here are the errors to review on the latest build:
|
|
125
119
|
|
|
126
120
|
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
121
|
|
|
128
122
|
${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
|
|
123
|
+
`;import dr from"process";var oe=y("deploy"),lt=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||(oe.log("Deploy: Uploading source zip"),l.push("--upload-source-zip")),o&&l.push("--alias",o),a&&l.push("--filter",a),r?(oe.log("Deploy: Skipping build"),l.push("--no-build")):l.push("--context","deploy-preview");let i=s||"netlify";oe.log(`Running: ${i} ${l.join(" ")}`);let f=await e.utils.run(i,l,{stdio:["ignore","pipe","pipe"]}),c=JSON.parse(f.stdout.trim());oe.log(`
|
|
124
|
+
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 oe.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 lt({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:h,skipBuild:!1,deploySubdomain:Ke(t.id,dr.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 ut(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=y("cleanup_stage"),ct=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 le(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 ut(()=>B(e.id,e.sessionId,i),{maxRetries:3,baseDelay:1e3,onRetry:(f,c)=>{ee.error(`Error updating agent runner session (attempt ${f}):`,c),ee.log("Retrying...")}}),ee.log("Finished updating agent runner with result"),{sessionUpdate:i}};import{getTracer as fr}from"@netlify/otel";var mr=pr(import.meta.url),dt=mr("../package.json"),pt=y("pipeline_index"),Ee=3,Co=async({config:e,apiToken:t,cliPath:r="netlify",cwd:n,errorLogsPath:o,filter:s,traceExporterUrl:a})=>{let l;try{await Le(dt.version,e.id,a);let i=fr(),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:dt.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}),C=T,N=[];if(g.hasChanges&&g.deployError){N.push(De(g.deployError));let p=1;for(;p<=Ee&&!g.previewInfo;)pt.log(`Deploy attempt had errors. Retrying. ${p}/${Ee}`),await se(i,"stage-deploy",async u=>{u?.setAttributes({"stage.attempt":p});let{runnerResult:m}=await ge({cliPath:r,config:e,context:d,runner:E.runner,persistSteps:h,aiGateway:c,buildErrors:N});C={...m,steps:[...C.steps||[],...m.steps||[]],duration:(C.duration||0)+(m.duration||0)},g=await ke({cliPath:r,config:e,context:d,result:m.result,filter:s}),g.deployError&&N.push(g.deployError),p++});p>Ee&&!g.previewInfo&&(f=new Error(`Deploy validation failed after ${Ee} attempts`))}let{diff:S,resultDiff:w,previewInfo:x,diffBinary:_,resultDiffBinary:R}=g;if(await ct({config:e,diff:S,result:C.result,duration:C.duration,resultDiff:w,diffBinary:_,resultDiffBinary:R,previewInfo:x}),f)throw f;await E.clean?.()}catch(i){pt.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{Co as runPipeline};
|
|
131
125
|
//# sourceMappingURL=index.js.map
|