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