@netlify/agent-runner-cli 1.33.0 → 1.33.1
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 +1 -1
- package/dist/index.js +15 -15
- package/package.json +1 -1
package/dist/bin.js
CHANGED
|
@@ -7,7 +7,7 @@ ${a}
|
|
|
7
7
|
|
|
8
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
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
|
|
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().toLowerCase()||"",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")||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().toLowerCase()||"";return!!(r?.includes("error when talking to gemini api")||r?.includes("499")||r?.includes("connection closed prematurely"))}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(`
|
|
11
11
|
|
|
12
12
|
`)}j&&k&&(k=`\`\`\`
|
|
13
13
|
${k.trim()}
|
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(f=>l.includes(f))){let f=Math.max(0,o-10,n+1),c=Math.min(t.length-1,o+20),
|
|
1
|
+
import{createRequire as dr}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),p=[];for(let h=f;h<=c;h++)p.push(t[h]);r.push(p.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 de 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 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},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,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=Ve.from(g).toString("base64"))}let E={hasChanges:!0,diff:i,resultDiff:p};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
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
|
|
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().toLowerCase()||"",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")||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().toLowerCase()||"";return!!(r?.includes("error when talking to gemini api")||r?.includes("499")||r?.includes("connection closed prematurely"))}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: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 m=l?.claude?.[s];m&&(i=m)}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 f=[],c=[],p={},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,d)=>{let u={...R,id:h};h+=1,c.push(u),f.push(u),d||w.flush(),w(),d&&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 d=null;try{d=JSON.parse(R)}catch{D.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:``}):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&&(p[u.id]=u);w.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&&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(`
|
|
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:D.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:D.log(`Message content type is not supported ${u.type}`,u)}}):d?.type==="result"&&(E=d.duration_ms||0,d.is_error?T=d.result:I=d.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 d=l?.codex?.[s];d&&(i=d)}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=[],p={},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=[],d=!1;if(_?.duration_ms&&(E=_.duration_ms,d=!0),_?.type==="local_shell_call")p[_.call_id]=_;else if(_?.type==="local_shell_call_output"){let u=qt(p[_.call_id],_);u&&(u.id=h,h+=1,c.push(u),f.push(u),R.push(u),d=!0)}else _?.type==="message"&&_.role==="assistant"?I=_.content.map(u=>u.text).join(`
|
|
14
14
|
`):_?.type==="message"&&_.role==="system"&&(T=_.content.map(u=>u.text).join(`
|
|
15
|
-
`));
|
|
15
|
+
`));d&&(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=`\`\`\`
|
|
16
16
|
${o.trim()}
|
|
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
|
|
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 pe 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:d,url:u}=o;if(!d||!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=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 f=[],c=[],p=[],h={},E=0,I=0,T,g,C=pe.join(M.cwd(),"node_modules"),N=[pe.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),_=(d,u)=>{d.id=E,E+=1,p.push(d),f.push(d),c.push(d),u||x.flush(),x(),u&&x.flush()},R=Wt.createInterface({input:w.all});return R.on("error",d=>{Q.error("Readline interface error",{error:d.message,stack:d.stack})}),R.on("line",d=>{let u=null;try{if(d.startsWith("[API Error")){let m=d.match(/\[api error: (.+?)]$/i)?.[1];u={type:"error",value:qe(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;_({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&&pe.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
18
|
${F.trim()}
|
|
19
|
-
\`\`\``),_(P,!0)}break}case"result":{I=u.duration_ms,T=u.value,[
|
|
19
|
+
\`\`\``),_(P,!0)}break}case"result":{I=u.duration_ms,T=u.value,[p,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(d=>{({error:g,result:T}=Xt({catchError:d,runCmd:w,error:g,result:T,runnerName:"Gemini"}))}),R.close(),x.flush(),{steps:p,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=pe.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),p;e.hasRepo?e.sha?(p=e.sha,s?.setAttributes({"init.sha.source":"provided"})):(p=await Xe(i),await le(e.id,{sha:p}),s?.setAttributes({"init.sha.source":"current_commit"})):(p=await Je(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}})},er=({apiToken:e})=>({constants:{NETLIFY_API_HOST:de.env.NETLIFY_API_HOST||"api.netlify.com",NETLIFY_API_TOKEN:e||de.env.NETLIFY_API_TOKEN,SITE_ID:de.env.SITE_ID,FUNCTIONS_DIST:de.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.
|
|
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>`:"",p="";r.siteContext&&r.siteContext.length!==0&&(p=`
|
|
27
27
|
<project_rules>
|
|
28
28
|
${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(`
|
|
29
29
|
|
|
30
30
|
`)}
|
|
31
31
|
</project_rules>
|
|
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),
|
|
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),d=`# Task History - Attempt ${w}
|
|
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"),O.log(`Created history file: ${R}`),R}));h+=`
|
|
43
43
|
<session_history_context>
|
|
44
44
|
History of prior work on this task.
|
|
45
45
|
You MUST review ALL of the files below as context to understand the context of previous attempts. Use this information to continue the discussion appropriately.
|
|
@@ -78,7 +78,7 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
78
78
|
- for requests that require work with attachments or assets, take into account that uploaded attachments are stored in ${a}/${Ne} folder
|
|
79
79
|
- move assets from ${a}/${Ne} folder to the project assets folder if they are referenced in a code or applied changes
|
|
80
80
|
</attachements>
|
|
81
|
-
${
|
|
81
|
+
${p}
|
|
82
82
|
</requirements>
|
|
83
83
|
|
|
84
84
|
<extra_context>
|
|
@@ -114,12 +114,12 @@ You're an AI agent designed to assist with tasks related to a Netlify project. P
|
|
|
114
114
|
</request>
|
|
115
115
|
|
|
116
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.
|
|
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},
|
|
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},p=await s({aiGateway:l,config:c,netlify:n,persistSteps:a});if(await a.flush(),p.error){if(me.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<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(p.error)}return{runnerResult:p}},cr=e=>!e||e.length===0?"":`
|
|
118
118
|
Deploy failed failed. Here are the errors to review on the latest build:
|
|
119
119
|
|
|
120
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.
|
|
121
121
|
|
|
122
122
|
${e.pop()}
|
|
123
|
-
`;import
|
|
124
|
-
Preview deploy created successfully:`,{deployId:c.deploy_id,deployUrl:c.deploy_url,siteId:c.site_id});let
|
|
123
|
+
`;import pr 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 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 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 p=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)}p=await lt({cliPath:e,netlify:r,hasRepo:t.hasRepo,message:h,skipBuild:!1,deploySubdomain:Ke(t.id,pr.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:p,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=dr(import.meta.url),pt=mr("../package.json"),dt=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(pt.version,e.id,a);let i=fr(),f,{aiGateway:c,context:p,persistSteps:h,runner:E,sha:I}=await ot({config:e,apiToken:t,cliPath:r,cwd:n,errorLogsPath:o,filter:s,runnerVersion:pt.version});l=E.clean,e.sha=I;let{runnerResult:T}=await ge({cliPath:r,config:e,context:p,runner:E.runner,persistSteps:h,aiGateway:c}),g=await ke({cliPath:r,config:e,context:p,result:T.result,filter:s}),C=T,N=[];if(g.hasChanges&&g.deployError){N.push(De(g.deployError));let d=1;for(;d<=Ee&&!g.previewInfo;)dt.log(`Deploy attempt had errors. Retrying. ${d}/${Ee}`),await se(i,"stage-deploy",async u=>{u?.setAttributes({"stage.attempt":d});let{runnerResult:m}=await ge({cliPath:r,config:e,context:p,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:p,result:m.result,filter:s}),g.deployError&&N.push(g.deployError),d++});d>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){dt.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};
|
|
125
125
|
//# sourceMappingURL=index.js.map
|